@alexsun-top/opencode-chat-room 0.8.2 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +18 -62
  3. package/README.zh-CN.md +25 -69
  4. package/dist/cli.js +466 -188
  5. package/package.json +11 -5
  6. package/packages/chat-room-channeld/README.md +25 -3
  7. package/packages/chat-room-channeld/dist/mock-adapter.js +5 -5
  8. package/packages/chat-room-channeld/src/adapter.ts +5 -0
  9. package/packages/chat-room-channeld/src/cli.ts +72 -5
  10. package/packages/chat-room-channeld/src/host.ts +17 -2
  11. package/packages/chat-room-channeld/src/pg/database.ts +187 -0
  12. package/packages/chat-room-channeld/src/pg/migrate.ts +150 -0
  13. package/packages/chat-room-channeld/src/pg/schema.ts +60 -0
  14. package/packages/chat-room-channeld/src/pg/sql.mjs +175 -0
  15. package/packages/chat-room-channeld/src/pg/sqlite.ts +100 -0
  16. package/packages/chat-room-channeld/src/pg/worker.mjs +133 -0
  17. package/packages/chat-room-channeld/src/protocol.ts +1 -0
  18. package/packages/chat-room-channeld/src/state.ts +73 -97
  19. package/packages/chat-room-channeld/src/stats.ts +140 -109
  20. package/server/assets/base.css +3 -1
  21. package/server/assets/chat/admin-badge.js +32 -30
  22. package/server/assets/chat/admin.js +201 -161
  23. package/server/assets/chat/announcements.js +302 -208
  24. package/server/assets/chat/attachment-store.js +116 -76
  25. package/server/assets/chat/attachments.js +701 -441
  26. package/server/assets/chat/chat-background.js +179 -156
  27. package/server/assets/chat/clipboard.js +45 -25
  28. package/server/assets/chat/confirm-dialog.js +38 -35
  29. package/server/assets/chat/copy-action.js +40 -41
  30. package/server/assets/chat/create-room-dialog.js +50 -47
  31. package/server/assets/chat/diagram-viewer.js +293 -236
  32. package/server/assets/chat/doc-preview.js +516 -443
  33. package/server/assets/chat/editor.js +446 -336
  34. package/server/assets/chat/events.js +650 -510
  35. package/server/assets/chat/files.js +505 -431
  36. package/server/assets/chat/history-loader.js +81 -73
  37. package/server/assets/chat/icons.js +9 -11
  38. package/server/assets/chat/image-zoom.js +246 -179
  39. package/server/assets/chat/index.js +2 -3
  40. package/server/assets/chat/install-prompt.js +90 -69
  41. package/server/assets/chat/integration-account-schema.js +91 -87
  42. package/server/assets/chat/integration-editor.js +162 -155
  43. package/server/assets/chat/integration-values.js +116 -101
  44. package/server/assets/chat/integrations.js +750 -626
  45. package/server/assets/chat/join-requests.js +415 -358
  46. package/server/assets/chat/locales/de.js +193 -194
  47. package/server/assets/chat/locales/es.js +193 -194
  48. package/server/assets/chat/locales/fr.js +193 -194
  49. package/server/assets/chat/locales/index.js +1 -2
  50. package/server/assets/chat/locales/it.js +193 -194
  51. package/server/assets/chat/locales/ja.js +193 -193
  52. package/server/assets/chat/locales/ko.js +193 -193
  53. package/server/assets/chat/markdown-footnotes.js +134 -103
  54. package/server/assets/chat/markdown.js +557 -404
  55. package/server/assets/chat/members.js +259 -197
  56. package/server/assets/chat/mentions.js +181 -133
  57. package/server/assets/chat/message-cache.js +40 -33
  58. package/server/assets/chat/message-polling.js +299 -227
  59. package/server/assets/chat/message-window.js +78 -55
  60. package/server/assets/chat/messages.js +562 -480
  61. package/server/assets/chat/office-preview.js +46 -45
  62. package/server/assets/chat/palette.js +464 -417
  63. package/server/assets/chat/panels.js +94 -79
  64. package/server/assets/chat/pwa.js +147 -75
  65. package/server/assets/chat/questions.js +374 -302
  66. package/server/assets/chat/recall.js +338 -273
  67. package/server/assets/chat/receipts.js +151 -121
  68. package/server/assets/chat/reminders.js +345 -214
  69. package/server/assets/chat/replies.js +181 -130
  70. package/server/assets/chat/resource-format.js +59 -62
  71. package/server/assets/chat/room-list.js +58 -55
  72. package/server/assets/chat/room-watcher.js +76 -50
  73. package/server/assets/chat/rooms.js +631 -500
  74. package/server/assets/chat/search.js +138 -114
  75. package/server/assets/chat/settings.js +225 -201
  76. package/server/assets/chat/shiki.js +62 -63
  77. package/server/assets/chat/shortcuts.js +212 -189
  78. package/server/assets/chat/side-pane.js +161 -150
  79. package/server/assets/chat/state.js +860 -737
  80. package/server/assets/chat/system-events.js +46 -44
  81. package/server/assets/chat/system-messages.js +57 -56
  82. package/server/assets/chat/task-form.js +179 -183
  83. package/server/assets/chat/task-row.js +158 -155
  84. package/server/assets/chat/tasks.js +665 -587
  85. package/server/assets/chat/viewport.js +32 -29
  86. package/server/assets/chat/window-controls.js +32 -32
  87. package/server/assets/conversation.css +10 -4
  88. package/server/chat-server.ts +9 -1
  89. package/server/chat.html +3 -1
  90. package/server/routes/pages.ts +7 -5
  91. package/server/sw.js +346 -268
  92. package/src/web/integration-rules-editor.ts +2 -0
@@ -1,389 +1,499 @@
1
1
  import { createRandomId } from "./state.js";
2
-
3
2
  const trustedChipNames = new Map();
4
3
  const autoSeparator = "\uE000\uE001";
5
4
  function mentionName(node) {
6
- const name = trustedChipNames.get(node.dataset?.chatChip);
7
- return name !== undefined && node.dataset.mention === name ? name : null;
5
+ const chip = node.dataset.chatChip;
6
+ const name = chip === undefined ? undefined : trustedChipNames.get(chip);
7
+ return name !== undefined && node.dataset.mention === name ? name : null;
8
8
  }
9
9
  function chipLabel(editor, name) {
10
- return editor.mentionLabel ? editor.mentionLabel(name) : name;
10
+ return editor.mentionLabel ? editor.mentionLabel(name) : name;
11
11
  }
12
-
13
12
  export function editorText(editor, draft = false) {
14
- if (editor.childNodes.length === 1 && editor.firstChild?.nodeName === "BR") return "";
15
- if (editor.childNodes.length === 1 && editor.firstChild?.nodeName === "DIV" && editor.firstElementChild?.nodeName === "BR") return "";
16
- let value = "";
17
- const block = (node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV";
18
- const walk = (node) => {
19
- if (node.nodeType === Node.TEXT_NODE) value += draft ? encodeDraftText(node.nodeValue) : node.nodeValue;
20
- else if (node.nodeType === Node.ELEMENT_NODE) {
21
- const mention = mentionName(node);
22
- if (node.dataset?.chatAutoSeparator) value += draft && node.textContent.startsWith(" ")
23
- ? autoSeparator + encodeDraftText(node.textContent.slice(1)) : draft ? encodeDraftText(node.textContent) : node.textContent;
24
- else if (mention !== null) value += `<at>@${mention}</at>`;
25
- else if (node.tagName === "BR") { if (!node.dataset?.chatTail) value += "\n"; }
26
- else node.childNodes.forEach((child, index, all) => {
27
- if (index && (block(child) || block(all[index - 1]))) value += "\n";
28
- if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR")) walk(child);
29
- });
30
- }
31
- };
32
- editor.childNodes.forEach((node, index, all) => {
33
- if (index && (block(node) || block(all[index - 1]))) value += "\n";
34
- if (!(block(node) && node.childNodes.length === 1 && node.firstChild.nodeName === "BR")) walk(node);
35
- });
36
- return value;
13
+ if (editor.childNodes.length === 1 && editor.firstChild?.nodeName === "BR")
14
+ return "";
15
+ if (editor.childNodes.length === 1 && editor.firstChild?.nodeName === "DIV" && editor.firstElementChild?.nodeName === "BR")
16
+ return "";
17
+ let value = "";
18
+ const block = (node) => node.nodeName === "DIV";
19
+ const walk = (node) => {
20
+ if (node.nodeType === Node.TEXT_NODE)
21
+ value += draft ? encodeDraftText(node.nodeValue ?? "") : node.nodeValue ?? "";
22
+ else if (node instanceof HTMLElement) {
23
+ const mention = mentionName(node), text = node.textContent ?? "";
24
+ if (node.dataset.chatAutoSeparator)
25
+ value += draft && text.startsWith(" ")
26
+ ? autoSeparator + encodeDraftText(text.slice(1)) : draft ? encodeDraftText(text) : text;
27
+ else if (mention !== null)
28
+ value += `<at>@${mention}</at>`;
29
+ else if (node.tagName === "BR") {
30
+ if (!node.dataset.chatTail)
31
+ value += "\n";
32
+ }
33
+ else
34
+ node.childNodes.forEach((child, index, all) => {
35
+ if (index && (block(child) || block(all[index - 1])))
36
+ value += "\n";
37
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild?.nodeName === "BR"))
38
+ walk(child);
39
+ });
40
+ }
41
+ };
42
+ editor.childNodes.forEach((node, index, all) => {
43
+ if (index && (block(node) || block(all[index - 1])))
44
+ value += "\n";
45
+ if (!(block(node) && node.childNodes.length === 1 && node.firstChild?.nodeName === "BR"))
46
+ walk(node);
47
+ });
48
+ return value;
37
49
  }
38
-
39
50
  export const editorDraftText = (editor) => editorText(editor, true);
40
51
  export const autoMentionDraft = (name) => `<at>@${name}</at>${autoSeparator}`;
41
52
  const literalMention = /<at>@([^<]+)<\/at>/g;
42
53
  function encodeDraftText(text) { return String(text).replace(/\uE000/g, "\uE000\uE000").replace(literalMention, "\uE000$&"); }
43
54
  function appendText(editor, text) {
44
- String(text).split("\n").forEach((line, index) => {
45
- if (index) editor.append(document.createElement("br"));
46
- if (line) editor.append(document.createTextNode(line));
47
- });
55
+ String(text).split("\n").forEach((line, index) => {
56
+ if (index)
57
+ editor.append(document.createElement("br"));
58
+ if (line)
59
+ editor.append(document.createTextNode(line));
60
+ });
48
61
  }
49
-
50
62
  export function setEditorText(editor, value, draft = false) {
51
- editor.replaceChildren();
52
- const pattern = draft ? /\uE000\uE001|\uE000\uE000|\uE000<at>@([^<]+)<\/at>|<at>@([^<]+)<\/at>/g : /<at>@([^<]+)<\/at>/g;
53
- let offset = 0, match;
54
- while ((match = pattern.exec(String(value))) !== null) {
55
- appendText(editor, String(value).slice(offset, match.index));
56
- if (draft && match[0] === autoSeparator) { editor.append(createAutoSeparator()); offset = pattern.lastIndex; continue; }
57
- if (draft && match[0] === "\uE000\uE000") { appendText(editor, "\uE000"); offset = pattern.lastIndex; continue; }
58
- if (draft && match[0].startsWith("\uE000")) { appendText(editor, match[0].slice(1)); offset = pattern.lastIndex; continue; }
59
- editor.append(createMention(editor, draft ? match[2] : match[1])); offset = pattern.lastIndex;
60
- }
61
- appendText(editor, String(value).slice(offset));
62
- editor.dataset.empty = value ? "false" : "true";
63
- pruneTrustedChipNames();
63
+ editor.replaceChildren();
64
+ const pattern = draft ? /\uE000\uE001|\uE000\uE000|\uE000<at>@([^<]+)<\/at>|<at>@([^<]+)<\/at>/g : /<at>@([^<]+)<\/at>/g;
65
+ let offset = 0, match;
66
+ while ((match = pattern.exec(String(value))) !== null) {
67
+ appendText(editor, String(value).slice(offset, match.index));
68
+ if (draft && match[0] === autoSeparator) {
69
+ editor.append(createAutoSeparator());
70
+ offset = pattern.lastIndex;
71
+ continue;
72
+ }
73
+ if (draft && match[0] === "\uE000\uE000") {
74
+ appendText(editor, "\uE000");
75
+ offset = pattern.lastIndex;
76
+ continue;
77
+ }
78
+ if (draft && match[0].startsWith("\uE000")) {
79
+ appendText(editor, match[0].slice(1));
80
+ offset = pattern.lastIndex;
81
+ continue;
82
+ }
83
+ editor.append(createMention(editor, draft ? match[2] : match[1]));
84
+ offset = pattern.lastIndex;
85
+ }
86
+ appendText(editor, String(value).slice(offset));
87
+ editor.dataset.empty = value ? "false" : "true";
88
+ pruneTrustedChipNames();
64
89
  }
65
-
66
90
  export function editorSelectionOffsets(editor) {
67
- const selection = getSelection();
68
- if (!selection?.rangeCount || !editor.contains(selection.anchorNode)) return [editorText(editor).length, editorText(editor).length];
69
- const selected = selection.getRangeAt(0), collapsed = selected.collapsed;
70
- const offset = (node, position, isStart) => {
71
- const element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
72
- const chip = element?.closest(".editor-mention");
73
- const raw = lengthBefore(editor, node, position);
74
- if (chip && editor.contains(chip) && mentionName(chip) !== null) {
75
- const start = lengthBefore(editor, chip, 0), end = start + `<at>@${mentionName(chip)}</at>`.length;
76
- // A caret strictly inside a non-editable chip (e.g. left there by an
77
- // ESC-cancelled IME composition) is not a text position; snap to the end.
78
- // A selection edge inside a chip expands to the whole chip so copy and
79
- // cut keep the mention token instead of falling back to plain text.
80
- if (raw > start && raw < end) return collapsed || !isStart ? end : start;
81
- }
82
- return raw;
83
- };
84
- return [offset(selected.startContainer, selected.startOffset, true), offset(selected.endContainer, selected.endOffset, false)];
91
+ const selection = getSelection();
92
+ if (!selection?.rangeCount || !editor.contains(selection.anchorNode))
93
+ return [editorText(editor).length, editorText(editor).length];
94
+ const selected = selection.getRangeAt(0), collapsed = selected.collapsed;
95
+ const offset = (node, position, isStart) => {
96
+ const element = node instanceof HTMLElement ? node : node.parentElement;
97
+ const chip = element?.closest(".editor-mention");
98
+ const raw = lengthBefore(editor, node, position);
99
+ if (chip && editor.contains(chip)) {
100
+ const name = mentionName(chip);
101
+ // A caret strictly inside a non-editable chip (e.g. left there by an
102
+ // ESC-cancelled IME composition) is not a text position; snap to the end.
103
+ // A selection edge inside a chip expands to the whole chip so copy and
104
+ // cut keep the mention token instead of falling back to plain text.
105
+ if (name !== null) {
106
+ const start = lengthBefore(editor, chip, 0), end = start + `<at>@${name}</at>`.length;
107
+ if (raw > start && raw < end)
108
+ return collapsed || !isStart ? end : start;
109
+ }
110
+ }
111
+ return raw;
112
+ };
113
+ return [offset(selected.startContainer, selected.startOffset, true), offset(selected.endContainer, selected.endOffset, false)];
85
114
  }
86
-
87
115
  function lengthBefore(root, target, position) {
88
- const block = (node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV";
89
- const length = (node) => node.nodeType === Node.TEXT_NODE ? node.length
90
- : mentionName(node) !== null ? `<at>@${mentionName(node)}</at>`.length
91
- : node.tagName === "BR" ? (node.dataset?.chatTail ? 0 : 1) : childrenLength(node);
92
- const childrenLength = (parent, until = parent.childNodes.length) => {
93
- let sum = 0;
94
- for (let index = 0; index < until; index++) {
95
- const child = parent.childNodes[index];
96
- if (index && (block(child) || block(parent.childNodes[index - 1]))) sum++;
97
- if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR")) sum += length(child);
98
- }
99
- return sum;
100
- };
101
- const visit = (node) => {
102
- if (node === target) return node.nodeType === Node.TEXT_NODE ? Math.min(position, node.length)
103
- : childrenLength(node, position);
104
- let total = 0;
105
- for (let index = 0; index < node.childNodes.length; index++) {
106
- const child = node.childNodes[index];
107
- if (index && (block(child) || block(node.childNodes[index - 1]))) total++;
108
- if (child === target || child.contains(target)) return total + visit(child);
109
- if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR")) total += length(child);
110
- }
111
- return total;
112
- };
113
- return visit(root);
116
+ const block = (node) => node.nodeName === "DIV";
117
+ const length = (node) => {
118
+ if (node instanceof Text)
119
+ return node.length;
120
+ const mention = node instanceof HTMLElement ? mentionName(node) : null;
121
+ if (mention !== null)
122
+ return `<at>@${mention}</at>`.length;
123
+ if (node instanceof HTMLElement && node.tagName === "BR")
124
+ return node.dataset.chatTail ? 0 : 1;
125
+ return childrenLength(node);
126
+ };
127
+ const childrenLength = (parent, until = parent.childNodes.length) => {
128
+ let sum = 0;
129
+ for (let index = 0; index < until; index++) {
130
+ const child = parent.childNodes[index];
131
+ if (index && (block(child) || block(parent.childNodes[index - 1])))
132
+ sum++;
133
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild?.nodeName === "BR"))
134
+ sum += length(child);
135
+ }
136
+ return sum;
137
+ };
138
+ const visit = (node) => {
139
+ if (node === target)
140
+ return node instanceof Text ? Math.min(position, node.length)
141
+ : childrenLength(node, position);
142
+ let total = 0;
143
+ for (let index = 0; index < node.childNodes.length; index++) {
144
+ const child = node.childNodes[index];
145
+ if (index && (block(child) || block(node.childNodes[index - 1])))
146
+ total++;
147
+ if (child === target || child.contains(target))
148
+ return total + visit(child);
149
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild?.nodeName === "BR"))
150
+ total += length(child);
151
+ }
152
+ return total;
153
+ };
154
+ return visit(root);
114
155
  }
115
-
116
156
  export function setCaret(editor, offset) {
117
- const selection = getSelection(), range = document.createRange();
118
- // Chromium starts IME composition poorly at an element boundary next to a
119
- // non-editable chip; keep the caret inside a real text node instead.
120
- const [container, index] = textPoint(editorPoint(editor, offset));
121
- range.setStart(container, index); range.collapse(true);
122
- selection.removeAllRanges(); selection.addRange(range);
157
+ const selection = getSelection(), range = document.createRange();
158
+ // Chromium starts IME composition poorly at an element boundary next to a
159
+ // non-editable chip; keep the caret inside a real text node instead.
160
+ const [container, index] = textPoint(editorPoint(editor, offset));
161
+ range.setStart(container, index);
162
+ range.collapse(true);
163
+ selection?.removeAllRanges();
164
+ selection?.addRange(range);
123
165
  }
124
-
125
166
  function textPoint([container, offset]) {
126
- if (container.nodeType !== Node.ELEMENT_NODE) return [container, offset];
127
- const child = container.childNodes[offset], previous = container.childNodes[offset - 1];
128
- if (child?.nodeType === Node.TEXT_NODE && child.length === 0) {
129
- const next = child.nextSibling;
130
- if (next?.nodeType === Node.TEXT_NODE) { child.remove(); return [next, 0]; }
131
- }
132
- if (child?.nodeType === Node.TEXT_NODE) return [child, 0];
133
- if (previous?.nodeType === Node.TEXT_NODE) return [previous, previous.length];
134
- const text = document.createTextNode("");
135
- container.insertBefore(text, child || null);
136
- return [text, 0];
167
+ if (container.nodeType !== Node.ELEMENT_NODE)
168
+ return [container, offset];
169
+ const child = container.childNodes[offset], previous = container.childNodes[offset - 1];
170
+ if (child instanceof Text && child.length === 0) {
171
+ const next = child.nextSibling;
172
+ if (next instanceof Text) {
173
+ child.remove();
174
+ return [next, 0];
175
+ }
176
+ }
177
+ if (child instanceof Text)
178
+ return [child, 0];
179
+ if (previous instanceof Text)
180
+ return [previous, previous.length];
181
+ const text = document.createTextNode("");
182
+ container.insertBefore(text, child || null);
183
+ return [text, 0];
137
184
  }
138
-
139
185
  export function setEditorSelection(editor, start, end = start) {
140
- const range = document.createRange(), selection = getSelection();
141
- const first = editorPoint(editor, start), last = editorPoint(editor, end);
142
- range.setStart(first[0], first[1]); range.setEnd(last[0], last[1]);
143
- selection.removeAllRanges(); selection.addRange(range);
186
+ const range = document.createRange(), selection = getSelection();
187
+ const first = editorPoint(editor, start), last = editorPoint(editor, end);
188
+ range.setStart(first[0], first[1]);
189
+ range.setEnd(last[0], last[1]);
190
+ selection?.removeAllRanges();
191
+ selection?.addRange(range);
144
192
  }
145
-
146
193
  function editorPoint(editor, offset) {
147
- const atEnd = offset === editorText(editor).length;
148
- if (atEnd && editor.lastChild?.nodeType === Node.TEXT_NODE && editor.lastChild.nodeValue === "") editor.lastChild.remove();
149
- const last = editor.lastElementChild;
150
- if (atEnd && editor.lastChild === last && last?.tagName === "DIV" && last.firstChild?.nodeName === "BR") {
151
- const text = last.appendChild(document.createTextNode("")); return [text, 0];
152
- }
153
- if (atEnd && editor.lastChild?.nodeName === "BR") {
154
- if (!editor.lastChild.dataset?.chatTail) {
155
- const tail = document.createElement("br");
156
- tail.dataset.chatTail = "true";
157
- editor.append(tail);
194
+ const atEnd = offset === editorText(editor).length;
195
+ if (atEnd && editor.lastChild?.nodeType === Node.TEXT_NODE && editor.lastChild.nodeValue === "")
196
+ editor.lastChild.remove();
197
+ const last = editor.lastElementChild;
198
+ if (atEnd && editor.lastChild === last && last?.tagName === "DIV" && last.firstChild?.nodeName === "BR") {
199
+ const text = last.appendChild(document.createTextNode(""));
200
+ return [text, 0];
158
201
  }
159
- return [editor, editor.childNodes.length - 1];
160
- }
161
- const block = (node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV";
162
- let left = offset, point = null;
163
- const visit = (node) => {
164
- if (point) return;
165
- if (node.nodeType === Node.TEXT_NODE) {
166
- if (left <= node.length) point = [node, left]; else left -= node.length;
167
- } else if (node.nodeType === Node.ELEMENT_NODE && mentionName(node) !== null) {
168
- const index = [...node.parentNode.childNodes].indexOf(node), length = `<at>@${mentionName(node)}</at>`.length;
169
- if (left <= length) point = [node.parentNode, index + (left ? 1 : 0)]; else left -= length;
170
- } else if (node.tagName === "BR") {
171
- const index = [...node.parentNode.childNodes].indexOf(node);
172
- if (left <= 1) point = [node.parentNode, index + (left ? 1 : 0)]; else left--;
173
- } else node.childNodes.forEach((child, index, all) => {
174
- if (index && (block(child) || block(all[index - 1]))) {
175
- if (left === 0) { point = [node, index]; return; }
176
- left--;
177
- }
178
- if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR")) visit(child);
179
- });
180
- };
181
- visit(editor);
182
- if (point) return point;
183
- const node = editor.appendChild(document.createTextNode("")); return [node, 0];
202
+ const tail = editor.lastChild;
203
+ if (atEnd && tail instanceof HTMLElement && tail.nodeName === "BR") {
204
+ if (!tail.dataset.chatTail) {
205
+ const created = document.createElement("br");
206
+ created.dataset.chatTail = "true";
207
+ editor.append(created);
208
+ }
209
+ return [editor, editor.childNodes.length - 1];
210
+ }
211
+ const block = (node) => node.nodeName === "DIV";
212
+ let left = offset, point = null;
213
+ const visit = (node) => {
214
+ if (point)
215
+ return;
216
+ if (node instanceof Text) {
217
+ if (left <= node.length)
218
+ point = [node, left];
219
+ else
220
+ left -= node.length;
221
+ }
222
+ else if (node instanceof HTMLElement && mentionName(node) !== null) {
223
+ const parent = node.parentNode;
224
+ if (!parent)
225
+ return;
226
+ const index = [...parent.childNodes].indexOf(node), length = `<at>@${mentionName(node)}</at>`.length;
227
+ if (left <= length)
228
+ point = [parent, index + (left ? 1 : 0)];
229
+ else
230
+ left -= length;
231
+ }
232
+ else if (node instanceof HTMLElement && node.tagName === "BR") {
233
+ const parent = node.parentNode;
234
+ if (!parent)
235
+ return;
236
+ const index = [...parent.childNodes].indexOf(node);
237
+ if (left <= 1)
238
+ point = [parent, index + (left ? 1 : 0)];
239
+ else
240
+ left--;
241
+ }
242
+ else
243
+ node.childNodes.forEach((child, index, all) => {
244
+ if (index && (block(child) || block(all[index - 1]))) {
245
+ if (left === 0) {
246
+ point = [node, index];
247
+ return;
248
+ }
249
+ left--;
250
+ }
251
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild?.nodeName === "BR"))
252
+ visit(child);
253
+ });
254
+ };
255
+ visit(editor);
256
+ if (point)
257
+ return point;
258
+ const node = editor.appendChild(document.createTextNode(""));
259
+ return [node, 0];
184
260
  }
185
-
186
261
  export function replaceEditorRange(editor, start, end, value, parseMentions = true) {
187
- const emptyBefore = !editorText(editor);
188
- setEditorSelection(editor, start, end);
189
- if (!parseMentions && document.execCommand("insertText", false, String(value))) {
190
- if (emptyBefore && !String(value).endsWith("\n")) trimTrailingBreak(editor);
262
+ const emptyBefore = !editorText(editor);
263
+ setEditorSelection(editor, start, end);
264
+ if (!parseMentions && document.execCommand("insertText", false, String(value))) {
265
+ if (emptyBefore && !String(value).endsWith("\n"))
266
+ trimTrailingBreak(editor);
267
+ editor.dataset.empty = editorText(editor) ? "false" : "true";
268
+ return;
269
+ }
270
+ const marker = `chat-insert-${createRandomId()}`;
271
+ const source = String(value), generatedSpace = parseMentions && source.endsWith(" "), content = generatedSpace ? source.slice(0, -1) : source;
272
+ const token = parseMentions ? /<at>@([^<]+)<\/at>/g : null;
273
+ let html = "", cursor = 0, match;
274
+ while (token && (match = token.exec(content))) {
275
+ html += textHTML(content.slice(cursor, match.index));
276
+ const name = escapeHTML(match[1]), label = escapeHTML(chipLabel(editor, match[1]));
277
+ const chipID = createRandomId();
278
+ trustedChipNames.set(chipID, match[1]);
279
+ html += `<span class="editor-mention" data-mention="${name}" data-chat-chip="${chipID}" data-insert-marker="${marker}" contenteditable="false" role="img" aria-label="Mention ${label}">@${label}</span>`;
280
+ cursor = token.lastIndex;
281
+ }
282
+ html += textHTML(content.slice(cursor));
283
+ if (generatedSpace)
284
+ html += `<span data-chat-auto-separator="true"> </span>`;
285
+ if (document.execCommand("insertHTML", false, html)) {
286
+ editor.querySelectorAll(`[data-insert-marker="${marker}"]`).forEach((chip) => chip.removeAttribute("data-insert-marker"));
287
+ if (emptyBefore && !String(value).endsWith("\n"))
288
+ trimTrailingBreak(editor);
289
+ setCaret(editor, start + source.length);
290
+ pruneTrustedChipNames();
291
+ }
292
+ else {
293
+ const current = editorText(editor), next = current.slice(0, start) + value + current.slice(end);
294
+ if (parseMentions)
295
+ setEditorText(editor, next);
296
+ else
297
+ editor.replaceChildren(document.createTextNode(next));
298
+ if (generatedSpace)
299
+ wrapAutoSeparator(editor, start + source.length - 1);
300
+ setCaret(editor, start + value.length);
301
+ pruneTrustedChipNames();
302
+ }
191
303
  editor.dataset.empty = editorText(editor) ? "false" : "true";
192
- return;
193
- }
194
- const marker = `chat-insert-${createRandomId()}`;
195
- const source = String(value), generatedSpace = parseMentions && source.endsWith(" "), content = generatedSpace ? source.slice(0, -1) : source;
196
- const token = parseMentions ? /<at>@([^<]+)<\/at>/g : null;
197
- let html = "", cursor = 0, match;
198
- while (token && (match = token.exec(content))) {
199
- html += textHTML(content.slice(cursor, match.index));
200
- const name = escapeHTML(match[1]), label = escapeHTML(chipLabel(editor, match[1]));
201
- const chipID = createRandomId(); trustedChipNames.set(chipID, match[1]);
202
- html += `<span class="editor-mention" data-mention="${name}" data-chat-chip="${chipID}" data-insert-marker="${marker}" contenteditable="false" role="img" aria-label="Mention ${label}">@${label}</span>`;
203
- cursor = token.lastIndex;
204
- }
205
- html += textHTML(content.slice(cursor));
206
- if (generatedSpace) html += `<span data-chat-auto-separator="true"> </span>`;
207
- if (document.execCommand("insertHTML", false, html)) {
208
- editor.querySelectorAll(`[data-insert-marker="${marker}"]`).forEach((chip) => chip.removeAttribute("data-insert-marker"));
209
- if (emptyBefore && !String(value).endsWith("\n")) trimTrailingBreak(editor);
210
- setCaret(editor, start + source.length);
211
- pruneTrustedChipNames();
212
- } else {
213
- const current = editorText(editor), next = current.slice(0, start) + value + current.slice(end);
214
- if (parseMentions) setEditorText(editor, next); else editor.replaceChildren(document.createTextNode(next));
215
- if (generatedSpace) wrapAutoSeparator(editor, start + source.length - 1);
216
- setCaret(editor, start + value.length);
217
- pruneTrustedChipNames();
218
- }
219
- editor.dataset.empty = editorText(editor) ? "false" : "true";
220
304
  }
221
-
222
305
  function trimTrailingBreak(editor) {
223
- let last = editor.lastChild;
224
- if (last?.nodeName === "BR" && last.dataset?.chatTail) last = last.previousSibling;
225
- if (last?.nodeName === "BR") last.remove();
306
+ let last = editor.lastChild;
307
+ if (last instanceof HTMLElement && last.nodeName === "BR" && last.dataset.chatTail)
308
+ last = last.previousSibling;
309
+ if (last?.nodeName === "BR")
310
+ last.remove();
226
311
  }
227
-
228
312
  function sanitizeEditor(editor) {
229
- for (const node of editor.querySelectorAll("*")) {
230
- if (node.tagName === "BR" || node.classList.contains("editor-mention") || node.hasAttribute("data-chat-auto-separator")) continue;
231
- const selection = getSelection(), range = selection?.rangeCount ? selection.getRangeAt(0) : null;
232
- const [start, end] = editorSelectionOffsets(editor), text = editorText(editor);
233
- let atEnd = false;
234
- if (range?.collapsed && editor.contains(range.endContainer)) {
235
- const tail = document.createRange();
236
- tail.setStart(range.endContainer, range.endOffset);
237
- tail.setEnd(editor, editor.childNodes.length);
238
- atEnd = tail.toString().length === 0;
313
+ for (const node of editor.querySelectorAll("*")) {
314
+ if (node.tagName === "BR" || node.classList.contains("editor-mention") || node.hasAttribute("data-chat-auto-separator"))
315
+ continue;
316
+ const selection = getSelection(), range = selection?.rangeCount ? selection.getRangeAt(0) : null;
317
+ const [start, end] = editorSelectionOffsets(editor), text = editorText(editor);
318
+ let atEnd = false;
319
+ if (range?.collapsed && editor.contains(range.endContainer)) {
320
+ const tail = document.createRange();
321
+ tail.setStart(range.endContainer, range.endOffset);
322
+ tail.setEnd(editor, editor.childNodes.length);
323
+ atEnd = tail.toString().length === 0;
324
+ }
325
+ setEditorText(editor, text);
326
+ setEditorSelection(editor, atEnd ? text.length : start, atEnd ? text.length : end);
327
+ return;
239
328
  }
240
- setEditorText(editor, text);
241
- setEditorSelection(editor, atEnd ? text.length : start, atEnd ? text.length : end);
242
- return;
243
- }
244
329
  }
245
-
246
330
  function knownMentions(editor, text) {
247
- // A copied mention only comes back if that name is still in the room.
248
- return text.replace(/<at>@([^<]+)<\/at>/g, (token, name) => editor.isKnownMention && !editor.isKnownMention(name) ? `@${name}` : token);
331
+ // A copied mention only comes back if that name is still in the room.
332
+ return text.replace(/<at>@([^<]+)<\/at>/g, (token, name) => editor.isKnownMention && !editor.isKnownMention(name) ? `@${name}` : token);
249
333
  }
250
- function escapeHTML(text) { return String(text).replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[char]); }
334
+ const HTML_ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
335
+ function escapeHTML(text) { return String(text).replace(/[&<>"']/g, (char) => HTML_ESCAPES[char]); }
251
336
  function textHTML(text) { return escapeHTML(text).replace(/\r\n|\r|\n/g, "<br>"); }
252
-
253
337
  function createMention(editor, name) {
254
- const chip = document.createElement("span"), label = chipLabel(editor, name);
255
- chip.className = "editor-mention"; chip.dataset.mention = name;
256
- chip.dataset.chatChip = createRandomId(); trustedChipNames.set(chip.dataset.chatChip, name);
257
- chip.contentEditable = "false"; chip.setAttribute("role", "img");
258
- chip.setAttribute("aria-label", `Mention ${label}`); chip.textContent = `@${label}`;
259
- return chip;
338
+ const chip = document.createElement("span"), label = chipLabel(editor, name);
339
+ chip.className = "editor-mention";
340
+ chip.dataset.mention = name;
341
+ chip.dataset.chatChip = createRandomId();
342
+ trustedChipNames.set(chip.dataset.chatChip, name);
343
+ chip.contentEditable = "false";
344
+ chip.setAttribute("role", "img");
345
+ chip.setAttribute("aria-label", `Mention ${label}`);
346
+ chip.textContent = `@${label}`;
347
+ return chip;
260
348
  }
261
349
  function createAutoSeparator() {
262
- const separator = document.createElement("span");
263
- separator.dataset.chatAutoSeparator = "true"; separator.textContent = " ";
264
- return separator;
350
+ const separator = document.createElement("span");
351
+ separator.dataset.chatAutoSeparator = "true";
352
+ separator.textContent = " ";
353
+ return separator;
265
354
  }
266
355
  function wrapAutoSeparator(editor, offset) {
267
- const start = editorPoint(editor, offset), end = editorPoint(editor, offset + 1), range = document.createRange();
268
- range.setStart(start[0], start[1]); range.setEnd(end[0], end[1]); range.deleteContents(); range.insertNode(createAutoSeparator());
356
+ const start = editorPoint(editor, offset), end = editorPoint(editor, offset + 1), range = document.createRange();
357
+ range.setStart(start[0], start[1]);
358
+ range.setEnd(end[0], end[1]);
359
+ range.deleteContents();
360
+ range.insertNode(createAutoSeparator());
269
361
  }
270
-
271
362
  function deleteMentionAtCaret(editor, event) {
272
- if (event.isComposing) return;
273
- const backward = event.inputType === "deleteContentBackward" || (event.key === "Backspace" && event.keyCode !== 229);
274
- if (!backward) return;
275
- const [caret, end] = editorSelectionOffsets(editor);
276
- if (caret !== end) return;
277
- const chips = [...editor.querySelectorAll(".editor-mention")];
278
- const separator = [...editor.querySelectorAll("[data-chat-auto-separator]")].find((node) => {
279
- const start = lengthBefore(editor, node, 0);
280
- return caret === start + 1 && node.previousElementSibling?.classList.contains("editor-mention");
281
- });
282
- const mention = separator?.previousElementSibling || chips.find((node) => {
283
- const start = lengthBefore(editor, node, 0);
284
- return caret > start && caret <= start + `<at>@${mentionName(node)}</at>`.length;
285
- });
286
- if (!mention) return;
287
- const start = lengthBefore(editor, mention, 0);
288
- const autoSeparator = mention.nextElementSibling?.dataset.chatAutoSeparator ? mention.nextElementSibling : null;
289
- event.preventDefault(); mention.remove(); autoSeparator?.remove(); setCaret(editor, start);
290
- editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" }));
363
+ if (event.isComposing)
364
+ return;
365
+ const backward = ("inputType" in event && event.inputType === "deleteContentBackward") || ("key" in event && event.key === "Backspace" && event.keyCode !== 229);
366
+ if (!backward)
367
+ return;
368
+ const [caret, end] = editorSelectionOffsets(editor);
369
+ if (caret !== end)
370
+ return;
371
+ const chips = [...editor.querySelectorAll(".editor-mention")];
372
+ const separator = [...editor.querySelectorAll("[data-chat-auto-separator]")].find((node) => {
373
+ const start = lengthBefore(editor, node, 0);
374
+ return caret === start + 1 && node.previousElementSibling?.classList.contains("editor-mention");
375
+ });
376
+ const previous = separator?.previousElementSibling;
377
+ const mention = previous instanceof HTMLElement ? previous : chips.find((node) => {
378
+ const start = lengthBefore(editor, node, 0);
379
+ return caret > start && caret <= start + `<at>@${mentionName(node)}</at>`.length;
380
+ });
381
+ if (!mention)
382
+ return;
383
+ const start = lengthBefore(editor, mention, 0);
384
+ const next = mention.nextElementSibling;
385
+ const autoSeparator = next?.getAttribute("data-chat-auto-separator") ? next : null;
386
+ event.preventDefault();
387
+ mention.remove();
388
+ autoSeparator?.remove();
389
+ setCaret(editor, start);
390
+ editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" }));
291
391
  }
292
-
293
392
  function pruneTrustedChipNames() {
294
- const live = new Set([...document.querySelectorAll("[data-chat-chip]")].map((node) => node.dataset.chatChip));
295
- const stale = [...trustedChipNames.keys()].filter((id) => !live.has(id));
296
- // shortcut: retain 2,048 detached IDs for undo history; raise if longer histories are required.
297
- stale.slice(0, Math.max(0, stale.length - 2048)).forEach((id) => trustedChipNames.delete(id));
393
+ const live = new Set([...document.querySelectorAll("[data-chat-chip]")].map((node) => node.dataset.chatChip));
394
+ const stale = [...trustedChipNames.keys()].filter((id) => !live.has(id));
395
+ // shortcut: retain 2,048 detached IDs for undo history; raise if longer histories are required.
396
+ stale.slice(0, Math.max(0, stale.length - 2048)).forEach((id) => trustedChipNames.delete(id));
298
397
  }
299
-
300
398
  export function installEditor(editor) {
301
- Object.defineProperty(editor, "value", {
302
- get: () => editorText(editor), set: (value) => setEditorText(editor, value),
303
- });
304
- Object.defineProperty(editor, "draftValue", {
305
- get: () => editorDraftText(editor), set: (value) => setEditorText(editor, value, true),
306
- });
307
- Object.defineProperties(editor, {
308
- selectionStart: { get: () => editorSelectionOffsets(editor)[0] },
309
- selectionEnd: { get: () => editorSelectionOffsets(editor)[1] },
310
- });
311
- editor.getSelectionOffsets = () => editorSelectionOffsets(editor);
312
- editor.setCaret = (offset) => setCaret(editor, offset);
313
- editor.moveCaretToLineEdge = (end) => {
314
- const [start, finish] = editorSelectionOffsets(editor);
315
- const text = editorText(editor);
316
- const caret = end ? finish : start;
317
- const next = text.indexOf("\n", caret);
318
- // A native Home next to a non-editable chip can land inside the chip, where
319
- // the caret is invisible. Re-seat all line-edge moves in a real text node.
320
- const lineStart = end ? caret : text.lastIndexOf("\n", caret - 1) + 1;
321
- const target = end ? (next === -1 ? text.length : next) : lineStart;
322
- // A caret before a leading mention chip can render invisibly in Chromium.
323
- // Home starts at the first editable character after that chip instead.
324
- const leading = !end ? text.slice(lineStart).match(/^(?:<at>@[^<]+<\/at>)+/) : null;
325
- setCaret(editor, leading ? lineStart + leading[0].length : target);
326
- };
327
- editor.setSelectionRange = (start, end = start) => setEditorSelection(editor, start, end);
328
- editor.replaceTextRange = (start, end, value) => replaceEditorRange(editor, start, end, value);
329
- editor.addEventListener("input", pruneTrustedChipNames);
330
- editor.addEventListener("keydown", (event) => deleteMentionAtCaret(editor, event));
331
- editor.addEventListener("beforeinput", (event) => deleteMentionAtCaret(editor, event));
332
- editor.addEventListener("pointerdown", (event) => {
333
- const chip = event.target.closest?.(".editor-mention");
334
- if (!chip || !editor.contains(chip)) return;
335
- event.preventDefault();
336
- editor.focus({ preventScroll: true });
337
- // A tap on a chip is usually followed by Backspace/Delete. Place the caret
338
- // after it so a narrow or rounded chip cannot trap the caret before it.
339
- setCaret(editor, lengthBefore(editor, chip, 0) + `<at>@${mentionName(chip)}</at>`.length);
340
- });
341
- const copySelection = (event) => {
342
- const [start, end] = editorSelectionOffsets(editor);
343
- if (start === end) return "";
344
- const text = editorText(editor).slice(start, end);
345
- if (!text) return "";
346
- // Copy mentions in their token form so a paste rebuilds the same chips.
347
- event.preventDefault();
348
- event.clipboardData?.setData("text/plain", text);
349
- if (/<at>@[^<]+<\/at>/.test(text)) event.clipboardData?.setData("text/html", `<div data-chatroom-mentions>${escapeHTML(text)}</div>`);
350
- return text;
351
- };
352
- editor.addEventListener("copy", (event) => { copySelection(event); });
353
- editor.addEventListener("cut", (event) => {
354
- const [start, end] = editorSelectionOffsets(editor);
355
- if (!copySelection(event)) return;
356
- // The native cut would overwrite the token clipboard; delete the range here.
357
- replaceEditorRange(editor, start, end, "", false);
358
- sanitizeEditor(editor);
359
- editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteByCut" }));
360
- });
361
- editor.addEventListener("paste", (event) => {
362
- if (event.defaultPrevented || event.clipboardData?.files.length) return;
363
- event.preventDefault();
364
- const [start, end] = editorSelectionOffsets(editor);
365
- const text = event.clipboardData?.getData("text/plain") || "";
366
- // Rebuild chips only for copies this app marked; external text stays literal
367
- // and keeps the native insert path, which handles newlines correctly.
368
- const marked = (event.clipboardData?.getData("text/html") || "").includes("data-chatroom-mentions");
369
- const value = marked ? knownMentions(editor, text) : text;
370
- replaceEditorRange(editor, start, end, value, marked && /<at>@[^<]+<\/at>/.test(value));
371
- sanitizeEditor(editor);
372
- editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertFromPaste" }));
373
- });
374
- editor.addEventListener("drop", (event) => {
375
- if (event.defaultPrevented || event.dataTransfer?.files.length) return;
376
- const html = event.dataTransfer?.getData("text/html") || "";
377
- const text = event.dataTransfer?.getData("text/plain") || new DOMParser().parseFromString(html, "text/html").body.textContent || "";
378
- if (!text) return;
379
- event.preventDefault();
380
- const range = document.caretRangeFromPoint?.(event.clientX, event.clientY), selection = getSelection();
381
- if (range && editor.contains(range.startContainer)) { selection.removeAllRanges(); selection.addRange(range); }
382
- const [start, end] = editorSelectionOffsets(editor);
383
- const marked = html.includes("data-chatroom-mentions");
384
- const value = marked ? knownMentions(editor, text) : text;
385
- replaceEditorRange(editor, start, end, value, marked && /<at>@[^<]+<\/at>/.test(value));
386
- sanitizeEditor(editor);
387
- editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertFromDrop" }));
388
- });
399
+ Object.defineProperty(editor, "value", {
400
+ get: () => editorText(editor), set: (value) => setEditorText(editor, value),
401
+ });
402
+ Object.defineProperty(editor, "draftValue", {
403
+ get: () => editorDraftText(editor), set: (value) => setEditorText(editor, value, true),
404
+ });
405
+ Object.defineProperties(editor, {
406
+ selectionStart: { get: () => editorSelectionOffsets(editor)[0] },
407
+ selectionEnd: { get: () => editorSelectionOffsets(editor)[1] },
408
+ });
409
+ const control = editor;
410
+ control.getSelectionOffsets = () => editorSelectionOffsets(editor);
411
+ control.setCaret = (offset) => setCaret(editor, offset);
412
+ control.moveCaretToLineEdge = (end) => {
413
+ const [start, finish] = editorSelectionOffsets(editor);
414
+ const text = editorText(editor);
415
+ const caret = end ? finish : start;
416
+ const next = text.indexOf("\n", caret);
417
+ // A native Home next to a non-editable chip can land inside the chip, where
418
+ // the caret is invisible. Re-seat all line-edge moves in a real text node.
419
+ const lineStart = end ? caret : text.lastIndexOf("\n", caret - 1) + 1;
420
+ const target = end ? (next === -1 ? text.length : next) : lineStart;
421
+ // A caret before a leading mention chip can render invisibly in Chromium.
422
+ // Home starts at the first editable character after that chip instead.
423
+ const leading = !end ? text.slice(lineStart).match(/^(?:<at>@[^<]+<\/at>)+/) : null;
424
+ setCaret(editor, leading ? lineStart + leading[0].length : target);
425
+ };
426
+ control.setSelectionRange = (start, end = start) => setEditorSelection(editor, start, end);
427
+ control.replaceTextRange = (start, end, value) => replaceEditorRange(editor, start, end, value);
428
+ editor.addEventListener("input", pruneTrustedChipNames);
429
+ editor.addEventListener("keydown", (event) => deleteMentionAtCaret(editor, event));
430
+ editor.addEventListener("beforeinput", (event) => deleteMentionAtCaret(editor, event));
431
+ editor.addEventListener("pointerdown", (event) => {
432
+ const chip = event.target instanceof Element ? event.target.closest(".editor-mention") : null;
433
+ if (!chip || !editor.contains(chip))
434
+ return;
435
+ event.preventDefault();
436
+ editor.focus({ preventScroll: true });
437
+ // A tap on a chip is usually followed by Backspace/Delete. Place the caret
438
+ // after it so a narrow or rounded chip cannot trap the caret before it.
439
+ setCaret(editor, lengthBefore(editor, chip, 0) + `<at>@${mentionName(chip)}</at>`.length);
440
+ });
441
+ const copySelection = (event) => {
442
+ const [start, end] = editorSelectionOffsets(editor);
443
+ if (start === end)
444
+ return "";
445
+ const text = editorText(editor).slice(start, end);
446
+ if (!text)
447
+ return "";
448
+ // Copy mentions in their token form so a paste rebuilds the same chips.
449
+ event.preventDefault();
450
+ event.clipboardData?.setData("text/plain", text);
451
+ if (/<at>@[^<]+<\/at>/.test(text))
452
+ event.clipboardData?.setData("text/html", `<div data-chatroom-mentions>${escapeHTML(text)}</div>`);
453
+ return text;
454
+ };
455
+ editor.addEventListener("copy", (event) => { copySelection(event); });
456
+ editor.addEventListener("cut", (event) => {
457
+ const [start, end] = editorSelectionOffsets(editor);
458
+ if (!copySelection(event))
459
+ return;
460
+ // The native cut would overwrite the token clipboard; delete the range here.
461
+ replaceEditorRange(editor, start, end, "", false);
462
+ sanitizeEditor(editor);
463
+ editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteByCut" }));
464
+ });
465
+ editor.addEventListener("paste", (event) => {
466
+ if (event.defaultPrevented || event.clipboardData?.files.length)
467
+ return;
468
+ event.preventDefault();
469
+ const [start, end] = editorSelectionOffsets(editor);
470
+ const text = event.clipboardData?.getData("text/plain") || "";
471
+ // Rebuild chips only for copies this app marked; external text stays literal
472
+ // and keeps the native insert path, which handles newlines correctly.
473
+ const marked = (event.clipboardData?.getData("text/html") || "").includes("data-chatroom-mentions");
474
+ const value = marked ? knownMentions(editor, text) : text;
475
+ replaceEditorRange(editor, start, end, value, marked && /<at>@[^<]+<\/at>/.test(value));
476
+ sanitizeEditor(editor);
477
+ editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertFromPaste" }));
478
+ });
479
+ editor.addEventListener("drop", (event) => {
480
+ if (event.defaultPrevented || event.dataTransfer?.files.length)
481
+ return;
482
+ const html = event.dataTransfer?.getData("text/html") || "";
483
+ const text = event.dataTransfer?.getData("text/plain") || new DOMParser().parseFromString(html, "text/html").body.textContent || "";
484
+ if (!text)
485
+ return;
486
+ event.preventDefault();
487
+ const range = document.caretRangeFromPoint?.(event.clientX, event.clientY), selection = getSelection();
488
+ if (range && editor.contains(range.startContainer)) {
489
+ selection?.removeAllRanges();
490
+ selection?.addRange(range);
491
+ }
492
+ const [start, end] = editorSelectionOffsets(editor);
493
+ const marked = html.includes("data-chatroom-mentions");
494
+ const value = marked ? knownMentions(editor, text) : text;
495
+ replaceEditorRange(editor, start, end, value, marked && /<at>@[^<]+<\/at>/.test(value));
496
+ sanitizeEditor(editor);
497
+ editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertFromDrop" }));
498
+ });
389
499
  }