@alexsun-top/opencode-chat-room 0.8.1 → 0.8.3

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