-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathstudent_notes_controller.js
More file actions
66 lines (58 loc) · 2.25 KB
/
student_notes_controller.js
File metadata and controls
66 lines (58 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
static targets = ["display", "form", "textarea", "content"];
static values = { url: String };
edit() {
this.displayTarget.classList.add("d-none");
this.formTarget.classList.remove("d-none");
this.textareaTarget.focus();
}
cancel() {
this.formTarget.classList.add("d-none");
this.displayTarget.classList.remove("d-none");
}
async save() {
const notes = this.textareaTarget.value;
const token = document.querySelector('meta[name="csrf-token"]').content;
try {
const response = await fetch(this.urlValue, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": token,
},
body: JSON.stringify({ notes }),
});
const data = await response.json();
if (response.ok && data.success) {
if (notes.trim()) {
// Convert newlines to <br> tags and set as HTML
const escaped = notes
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
const html = `<p>${escaped.replace(/\n\n+/g, "</p>\n\n<p>").replace(/\n/g, "<br>")}</p>`;
this.contentTarget.innerHTML = html;
} else {
this.contentTarget.innerHTML =
'<span class="text-muted">No notes yet.</span>';
}
this.formTarget.classList.add("d-none");
this.displayTarget.classList.remove("d-none");
this._dispatchFlash("notice", "Notes saved successfully.");
} else {
this._dispatchFlash(
"alert",
data.error || "Failed to save notes."
);
}
} catch {
this._dispatchFlash("alert", "Network error. Please try again.");
}
}
_dispatchFlash(type, message) {
window.dispatchEvent(
new CustomEvent("flash", { detail: { type, message } })
);
}
}