1import type { SpellRange } from "#src/cspell.ts";
2import QuestionRender from "#src/q+a/tags/question.marko";
3import type { ScriptPayload } from "#src/q+a/views/editor.marko";
4
5declare const payload: ScriptPayload;
6const date = new Date(payload.date);
7
8const main = document.getElementById("edit-grid")! as HTMLDivElement;
9const preview = document.getElementById("preview")! as HTMLDivElement;
10const editor = document.getElementById("editor") as HTMLTextAreaElement;
11const overlay = document.getElementById("editor-overlay")!;
12const menu = document.getElementById("spell-menu")!;
13
14async function updatePreview(text: string) {
15 preview.innerHTML = await QuestionRender.render({
16 question: {
17 id: payload.id,
18 qmid: payload.qmid,
19 text: text,
20 type: payload.type,
21 date,
22 },
23 editor: true,
24 });
25}
26updatePreview(payload.text);
27
28const flagged = new Map<HTMLSpanElement, SpellRange>();
29
30function paintSpelling(text: string, issues: SpellRange[]) {
31 const parts: (string | Node)[] = [];
32 flagged.clear();
33 let at = 0;
34 for (const issue of issues) {
35 const { offset, length } = issue;
36 if (offset < at) continue;
37 const word = document.createElement("span");
38 word.textContent = text.slice(offset, offset + length);
39 flagged.set(word, issue);
40 parts.push(text.slice(at, offset), word);
41 at = offset + length;
42 }
43 parts.push(text.slice(at));
44 overlay.replaceChildren(...parts);
45}
46
47/** The overlay spans sit exactly where the textarea draws the same words. */
48function issueAt(x: number, y: number) {
49 for (const [word, issue] of flagged) {
50 for (const rect of word.getClientRects()) {
51 if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) return issue;
52 }
53 }
54 return null;
55}
56
57function closeMenu() {
58 menu.hidden = true;
59}
60
61function openMenu(issue: SpellRange, x: number, y: number) {
62 const wrap = menu.parentElement!.getBoundingClientRect();
63 menu.replaceChildren(...issue.suggestions.map((word) => {
64 const option = document.createElement("button");
65 option.textContent = word;
66 option.addEventListener("click", () => {
67 closeMenu();
68 editor.focus();
69 editor.setSelectionRange(issue.offset, issue.offset + issue.length);
70 // Going through the editing command keeps the textarea's own undo history.
71 document.execCommand("insertText", false, word);
72 });
73 return option;
74 }));
75 menu.style.left = `${x - wrap.left}px`;
76 menu.style.top = `${y - wrap.top}px`;
77 menu.hidden = false;
78}
79
80editor.addEventListener("contextmenu", (event) => {
81 const issue = issueAt(event.clientX, event.clientY);
82 if (!issue?.suggestions.length) return;
83 event.preventDefault();
84 openMenu(issue, event.clientX, event.clientY);
85});
86document.addEventListener("pointerdown", (event) => {
87 if (!menu.contains(event.target as Node)) closeMenu();
88});
89document.addEventListener("keydown", (event) => {
90 if (event.key === "Escape") closeMenu();
91});
92
93let spellTimer: ReturnType<typeof setTimeout> | undefined;
94let spellRequest = 0;
95async function checkSpelling(text: string) {
96 const request = ++spellRequest;
97 const res = await fetch("/admin/q+a/spell", {
98 method: "POST",
99 headers: {
100 Accept: "application/json",
101 "Content-Type": "application/json",
102 },
103 body: JSON.stringify({ text }),
104 });
105 if (!res.ok) return;
106 const { issues } = await res.json() as { issues: SpellRange[] };
107 if (request === spellRequest) paintSpelling(text, issues);
108}
109
110editor.value = payload.text;
111paintSpelling(payload.text, []);
112checkSpelling(payload.text);
113editor.addEventListener("input", () => {
114 updatePreview(editor.value);
115 closeMenu();
116 // Offsets from a request in flight no longer line up with what is on screen.
117 spellRequest++;
118 paintSpelling(editor.value, []);
119 clearTimeout(spellTimer);
120 spellTimer = setTimeout(() => checkSpelling(editor.value), 300);
121});
122editor.addEventListener("scroll", () => {
123 overlay.scrollTop = editor.scrollTop;
124 closeMenu();
125});
126editor.focus();
127
128(globalThis as any).onCommitQuestion = wrapAction(async () => {
129 const text = editor.value;
130 const res = await fetch(`/admin/q+a/${payload.id}`, {
131 method: "PATCH",
132 headers: {
133 Accept: "application/json",
134 "Content-Type": "application/json",
135 },
136 body: JSON.stringify({
137 text,
138 type: payload.type,
139 }),
140 });
141 if (!res.ok) {
142 throw new Error("Failed to update question, status: " + res.status);
143 }
144 if (location.search.includes("return=inbox")) {
145 location.href = "/admin/q+a/inbox";
146 } else {
147 location.href = "/q+a#q" + payload.id;
148 }
149});
150(globalThis as any).onDelete = wrapAction(async () => {
151 if (confirm("Are you sure you want to delete this question?")) {
152 const res = await fetch(`/admin/q+a/${payload.id}`, {
153 method: "DELETE",
154 headers: {
155 Accept: "application/json",
156 },
157 });
158 if (!res.ok) {
159 throw new Error("Failed to delete question, status: " + res.status);
160 }
161 location.href = document.referrer || "/admin/q+a";
162 }
163});
164(globalThis as any).onTypeChange = () => {
165 payload.type = (document.getElementById("type") as HTMLSelectElement).value as ScriptPayload["type"];
166 updatePreview(editor.value);
167};
168
169function wrapAction(cb: () => Promise<void>) {
170 return async () => {
171 main.style.opacity = "0.5";
172 main.style.pointerEvents = "none";
173 const inputs = main.querySelectorAll(
174 "button,select,input",
175 ) as NodeListOf<HTMLButtonElement>;
176 inputs.forEach((b) => {
177 b.disabled = true;
178 });
179 try {
180 await cb();
181 } catch (e: any) {
182 main.style.opacity = "1";
183 main.style.pointerEvents = "auto";
184 inputs.forEach((b) => {
185 b.disabled = false;
186 });
187 alert(e.message);
188 }
189 };
190}