@mzeahmed/rich-editor 0.0.0-stage → 0.1.0
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.
- package/CHANGELOG.md +65 -0
- package/LICENSE +21 -0
- package/README.md +301 -2
- package/dist/Editor.d.ts +273 -0
- package/dist/Editor.js +959 -0
- package/dist/EmojiPicker.d.ts +33 -0
- package/dist/EmojiPicker.js +268 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +5 -0
- package/dist/messages.d.ts +61 -0
- package/dist/messages.js +111 -0
- package/dist/security.d.ts +20 -0
- package/dist/security.js +124 -0
- package/dist/style.css +486 -0
- package/dist/styles.d.ts +22 -0
- package/dist/styles.js +515 -0
- package/dist/types.d.ts +28 -0
- package/dist/types.js +1 -0
- package/package.json +60 -4
package/dist/Editor.js
ADDED
|
@@ -0,0 +1,959 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standalone rich text editor.
|
|
3
|
+
* Automatically replaces <textarea> elements with an enhanced contenteditable editor.
|
|
4
|
+
*
|
|
5
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6
|
+
* BASIC USAGE
|
|
7
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
8
|
+
*
|
|
9
|
+
* 1) Every <textarea> on the page
|
|
10
|
+
* Editor.init();
|
|
11
|
+
*
|
|
12
|
+
* 2) Targeted CSS selector
|
|
13
|
+
* Editor.init({ selector: '.richtext' });
|
|
14
|
+
*
|
|
15
|
+
* 3) Exclude some textareas
|
|
16
|
+
* Editor.init({ exclude: '.no-editor' });
|
|
17
|
+
*
|
|
18
|
+
* 4) Mount on a specific element (dynamic DOM)
|
|
19
|
+
* Editor.mount('#my-textarea');
|
|
20
|
+
* Editor.mount(textareaElement);
|
|
21
|
+
*
|
|
22
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
23
|
+
* TOOLBAR OPTIONS
|
|
24
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
25
|
+
*
|
|
26
|
+
* toolbar: 'always' → toolbar always visible (default)
|
|
27
|
+
* Editor.init({ toolbar: 'always' });
|
|
28
|
+
*
|
|
29
|
+
* toolbar: 'focus' → toolbar shown only while the field is focused
|
|
30
|
+
* Editor.init({ toolbar: 'focus' });
|
|
31
|
+
*
|
|
32
|
+
* toolbar: 'toggle' → a "Formatting" button shows/hides the toolbar
|
|
33
|
+
* Editor.init({ toolbar: 'toggle' });
|
|
34
|
+
*
|
|
35
|
+
* toolbar: 'never' → no toolbar (plain rich input field)
|
|
36
|
+
* Editor.init({ toolbar: 'never' });
|
|
37
|
+
*
|
|
38
|
+
* Per-textarea override through a data attribute:
|
|
39
|
+
* <textarea data-mzre-toolbar="focus"></textarea>
|
|
40
|
+
*
|
|
41
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
42
|
+
* FOOTER (character counter + HTML / Clear / Copy buttons)
|
|
43
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
44
|
+
*
|
|
45
|
+
* Hide the footer (useful for embedded fields, e.g. messaging):
|
|
46
|
+
* Editor.mount('#msg-textarea', { footer: false });
|
|
47
|
+
*
|
|
48
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
49
|
+
* HEIGHT OF THE WRITING AREA
|
|
50
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
51
|
+
*
|
|
52
|
+
* Through the JS options:
|
|
53
|
+
* Editor.mount('#my-textarea', { minHeight: '80px', maxHeight: '300px' });
|
|
54
|
+
*
|
|
55
|
+
* Through data attributes on the <textarea> (they take precedence over the JS options):
|
|
56
|
+
* <textarea data-mzre-min-height="60px" data-mzre-max-height="200px"></textarea>
|
|
57
|
+
*
|
|
58
|
+
* When maxHeight is set, overflow-y: auto is enabled automatically.
|
|
59
|
+
*
|
|
60
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
61
|
+
* EMOJI
|
|
62
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
63
|
+
*
|
|
64
|
+
* Adds an inline 😊 button to the writing area. The picker is provided by the package
|
|
65
|
+
* (no modal to prepare); its data is loaded on first open.
|
|
66
|
+
*
|
|
67
|
+
* Editor.mount('#editor', { emoji: true });
|
|
68
|
+
*
|
|
69
|
+
* Combined with no toolbar (post/comment field style):
|
|
70
|
+
* Editor.mount('#post-textarea', {
|
|
71
|
+
* toolbar: 'never',
|
|
72
|
+
* footer: false,
|
|
73
|
+
* emoji: true,
|
|
74
|
+
* });
|
|
75
|
+
*
|
|
76
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
77
|
+
* MENTIONS
|
|
78
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
79
|
+
*
|
|
80
|
+
* Enables assisted @user mentions (requires integrations.mentions):
|
|
81
|
+
* · Typing @ → user search bubble (integrations.mentions.searchUsers)
|
|
82
|
+
* · Selection → inserts <a class="mention" href="/profile" data-user-id="…">First Last</a>
|
|
83
|
+
* · Closes on Space / Escape / Enter, with the cross, or by clicking outside
|
|
84
|
+
*
|
|
85
|
+
* Simple activation:
|
|
86
|
+
* Editor.mount('#editor', { mention: true }, { mentions: … });
|
|
87
|
+
*
|
|
88
|
+
* Full combination (publishing form style), with a "publish" button disabled
|
|
89
|
+
* while the field is empty (onChange is also called once at mount):
|
|
90
|
+
* Editor.mount('#post-textarea', {
|
|
91
|
+
* toolbar: 'never',
|
|
92
|
+
* footer: false,
|
|
93
|
+
* emoji: true,
|
|
94
|
+
* mention: true,
|
|
95
|
+
* onChange: ({ isEmpty }) => { publishButton.disabled = isEmpty; },
|
|
96
|
+
* }, { mentions: … });
|
|
97
|
+
*
|
|
98
|
+
* Comment combination:
|
|
99
|
+
* Editor.mount('#comment-textarea', {
|
|
100
|
+
* toolbar: 'never',
|
|
101
|
+
* footer: false,
|
|
102
|
+
* emoji: true,
|
|
103
|
+
* mention: true,
|
|
104
|
+
* });
|
|
105
|
+
*
|
|
106
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
107
|
+
* LANGUAGE
|
|
108
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
109
|
+
*
|
|
110
|
+
* Interface and emojis in English by default; { locale: 'fr' } (or setEditorLocale('fr')) for
|
|
111
|
+
* French. A text can be overridden: integrations.messages = { close: 'Dismiss' }.
|
|
112
|
+
*
|
|
113
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
114
|
+
* COMPLETE USE CASES
|
|
115
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
116
|
+
*
|
|
117
|
+
* A) Rich content editor (article, long description)
|
|
118
|
+
* Editor.init({
|
|
119
|
+
* selector: 'textarea.rich-content',
|
|
120
|
+
* toolbar: 'always',
|
|
121
|
+
* minHeight: '300px',
|
|
122
|
+
* });
|
|
123
|
+
*
|
|
124
|
+
* B) Compact comment editor (toolbar on focus)
|
|
125
|
+
* Editor.init({
|
|
126
|
+
* selector: 'textarea.comment',
|
|
127
|
+
* toolbar: 'focus',
|
|
128
|
+
* minHeight: '80px',
|
|
129
|
+
* maxHeight: '200px',
|
|
130
|
+
* footer: false,
|
|
131
|
+
* });
|
|
132
|
+
*
|
|
133
|
+
* C) Messaging input field (no toolbar, no footer, fixed height)
|
|
134
|
+
* Editor.mount('#messaging-textarea', {
|
|
135
|
+
* toolbar: 'never',
|
|
136
|
+
* footer: false,
|
|
137
|
+
* minHeight: '40px',
|
|
138
|
+
* maxHeight: '120px',
|
|
139
|
+
* });
|
|
140
|
+
*
|
|
141
|
+
* D) Editor with an optional toolbar behind a toggle button
|
|
142
|
+
* Editor.mount('#post-content', { toolbar: 'toggle' });
|
|
143
|
+
*
|
|
144
|
+
* E) Mounting on a dynamically added element (e.g. an opened modal)
|
|
145
|
+
* modal.addEventListener('shown', () => { // your modal's open event
|
|
146
|
+
* Editor.mount('#modal-textarea', { toolbar: 'focus', minHeight: '120px' });
|
|
147
|
+
* });
|
|
148
|
+
*
|
|
149
|
+
* F) Per-textarea override (data attributes, no extra JS)
|
|
150
|
+
* <textarea
|
|
151
|
+
* data-mzre-toolbar="toggle"
|
|
152
|
+
* data-mzre-min-height="100px"
|
|
153
|
+
* data-mzre-max-height="400px"
|
|
154
|
+
* ></textarea>
|
|
155
|
+
* then: Editor.init(); ← the data attributes take precedence
|
|
156
|
+
*
|
|
157
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
158
|
+
* CHAINING
|
|
159
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
160
|
+
*
|
|
161
|
+
* init() and mount() return the class, so calls can be chained:
|
|
162
|
+
* Editor
|
|
163
|
+
* .init({ selector: '.rich', toolbar: 'always' })
|
|
164
|
+
* .mount('#extra-field', { toolbar: 'never', footer: false });
|
|
165
|
+
*/
|
|
166
|
+
import EmojiPicker from './EmojiPicker.js';
|
|
167
|
+
import { escapeHtml, safeHttpUrl, safeSitePath, sanitizeHtml } from './security.js';
|
|
168
|
+
import { EDITOR_CSS, injectStyleSheet, setEditorStyles } from './styles.js';
|
|
169
|
+
import { message as t, setEditorLocale, setEditorMessages } from './messages.js';
|
|
170
|
+
/** Interface text, escaped so it can be inserted into HTML. */
|
|
171
|
+
const te = (key) => escapeHtml(t(key));
|
|
172
|
+
let mentionBubbleCount = 0;
|
|
173
|
+
/**
|
|
174
|
+
* ARIA attributes carried by the writing area (`textbox` role) while the mention bubble is
|
|
175
|
+
* open. Only those this role accepts: `aria-expanded` and `aria-haspopup` are not allowed.
|
|
176
|
+
*/
|
|
177
|
+
const MENTION_ARIA = ['aria-autocomplete', 'aria-controls', 'aria-activedescendant'];
|
|
178
|
+
/* ─────────────────────────────────────────
|
|
179
|
+
CSS injected only once into <head>
|
|
180
|
+
───────────────────────────────────────── */
|
|
181
|
+
/* ─────────────────────────────────────────
|
|
182
|
+
SVG icons inline
|
|
183
|
+
───────────────────────────────────────── */
|
|
184
|
+
const ICONS = {
|
|
185
|
+
ul: `<svg width="14" height="14" viewBox="0 0 14 14" fill="none"><circle cx="2" cy="3.5" r="1.3" fill="currentColor"/><rect x="5" y="2.8" width="8" height="1.4" rx="0.7" fill="currentColor"/><circle cx="2" cy="7" r="1.3" fill="currentColor"/><rect x="5" y="6.3" width="8" height="1.4" rx="0.7" fill="currentColor"/><circle cx="2" cy="10.5" r="1.3" fill="currentColor"/><rect x="5" y="9.8" width="8" height="1.4" rx="0.7" fill="currentColor"/></svg>`,
|
|
186
|
+
ol: `<svg width="14" height="14" viewBox="0 0 14 14" fill="none"><text x="0" y="5" font-size="5" fill="currentColor" font-family="sans-serif">1.</text><rect x="5" y="2.8" width="8" height="1.4" rx="0.7" fill="currentColor"/><text x="0" y="9" font-size="5" fill="currentColor" font-family="sans-serif">2.</text><rect x="5" y="6.3" width="8" height="1.4" rx="0.7" fill="currentColor"/><text x="0" y="13" font-size="5" fill="currentColor" font-family="sans-serif">3.</text><rect x="5" y="9.8" width="8" height="1.4" rx="0.7" fill="currentColor"/></svg>`,
|
|
187
|
+
alignL: `<svg width="14" height="12" viewBox="0 0 14 12"><rect y="0" width="14" height="1.5" rx=".75" fill="currentColor"/><rect y="3.5" width="10" height="1.5" rx=".75" fill="currentColor"/><rect y="7" width="14" height="1.5" rx=".75" fill="currentColor"/><rect y="10.5" width="8" height="1.5" rx=".75" fill="currentColor"/></svg>`,
|
|
188
|
+
alignC: `<svg width="14" height="12" viewBox="0 0 14 12"><rect y="0" width="14" height="1.5" rx=".75" fill="currentColor"/><rect x="2" y="3.5" width="10" height="1.5" rx=".75" fill="currentColor"/><rect y="7" width="14" height="1.5" rx=".75" fill="currentColor"/><rect x="3" y="10.5" width="8" height="1.5" rx=".75" fill="currentColor"/></svg>`,
|
|
189
|
+
alignR: `<svg width="14" height="12" viewBox="0 0 14 12"><rect y="0" width="14" height="1.5" rx=".75" fill="currentColor"/><rect x="4" y="3.5" width="10" height="1.5" rx=".75" fill="currentColor"/><rect y="7" width="14" height="1.5" rx=".75" fill="currentColor"/><rect x="6" y="10.5" width="8" height="1.5" rx=".75" fill="currentColor"/></svg>`,
|
|
190
|
+
link: `<svg width="15" height="14" viewBox="0 0 15 14" fill="none"><path d="M6 8.5a3.5 3.5 0 0 0 5 0l2-2a3.536 3.536 0 0 0-5-5L6.5 3" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/><path d="M9 5.5a3.5 3.5 0 0 0-5 0L2 7.5a3.536 3.536 0 0 0 5 5L8.5 11" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg>`,
|
|
191
|
+
clear: `<svg width="15" height="14" viewBox="0 0 15 14" fill="none"><path d="M3 11h9M5.5 3h5l-2 8" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/><line x1="2" y1="2" x2="13" y2="12" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg>`,
|
|
192
|
+
undo: `<svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2 5h6a4 4 0 0 1 0 8H6" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/><path d="M2 5l3-3M2 5l3 3" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
|
193
|
+
redo: `<svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M12 5H6a4 4 0 0 0 0 8h2" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/><path d="M12 5l-3-3M12 5l-3 3" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
|
194
|
+
};
|
|
195
|
+
export default class Editor {
|
|
196
|
+
/* ─────────────────────────────────────────
|
|
197
|
+
Inject CSS only once
|
|
198
|
+
───────────────────────────────────────── */
|
|
199
|
+
static injectStyles() {
|
|
200
|
+
injectStyleSheet('mzre-editor-styles', EDITOR_CSS);
|
|
201
|
+
}
|
|
202
|
+
/* ─────────────────────────────────────────
|
|
203
|
+
Builds the HTML of an editor
|
|
204
|
+
───────────────────────────────────────── */
|
|
205
|
+
static buildEditorHTML(placeholder, toolbarMode, label) {
|
|
206
|
+
const toggleBar = toolbarMode === 'toggle'
|
|
207
|
+
? `<div class="mzre-toolbar-toggle">
|
|
208
|
+
<button type="button" class="mzre-toggle-btn" title="${te('toggleToolbar')}">
|
|
209
|
+
<svg width="12" height="12" viewBox="0 0 12 12" fill="none"><rect y="0" width="12" height="1.5" rx=".75" fill="currentColor"/><rect y="4" width="12" height="1.5" rx=".75" fill="currentColor"/><rect y="8" width="12" height="1.5" rx=".75" fill="currentColor"/></svg>
|
|
210
|
+
${te('formatting')}
|
|
211
|
+
</button>
|
|
212
|
+
</div>`
|
|
213
|
+
: '';
|
|
214
|
+
// In 'never' mode, the toolbar and the link bar are not rendered in the DOM
|
|
215
|
+
// `type="button"` on every button: without it, a <button> inside a
|
|
216
|
+
// <form> implicitly has type="submit" and submits the host form
|
|
217
|
+
// on click instead of running its editing command.
|
|
218
|
+
const toolbarAndLinkBar = toolbarMode !== 'never' ? `
|
|
219
|
+
<div class="mzre-toolbar">
|
|
220
|
+
<select class="mzre-block-select" aria-label="${te('textStyle')}">
|
|
221
|
+
<option value="p">${te('paragraph')}</option>
|
|
222
|
+
<option value="h2">${te('heading')}</option>
|
|
223
|
+
<option value="h3">${te('subheading')}</option>
|
|
224
|
+
<option value="blockquote">${te('quote')}</option>
|
|
225
|
+
</select>
|
|
226
|
+
<div class="mzre-sep"></div>
|
|
227
|
+
<button type="button" data-cmd="bold" title="${te('bold')}"><b>B</b></button>
|
|
228
|
+
<button type="button" data-cmd="italic" title="${te('italic')}"><i>I</i></button>
|
|
229
|
+
<button type="button" data-cmd="underline" title="${te('underline')}" class="mzre-btn-underline">U</button>
|
|
230
|
+
<button type="button" data-cmd="strikeThrough" title="${te('strikethrough')}" class="mzre-btn-strike">S</button>
|
|
231
|
+
<div class="mzre-sep"></div>
|
|
232
|
+
<button type="button" data-cmd="insertUnorderedList" title="${te('bulletList')}">${ICONS.ul}</button>
|
|
233
|
+
<button type="button" data-cmd="insertOrderedList" title="${te('numberedList')}">${ICONS.ol}</button>
|
|
234
|
+
<div class="mzre-sep"></div>
|
|
235
|
+
<button type="button" data-cmd="justifyLeft" title="${te('alignLeft')}">${ICONS.alignL}</button>
|
|
236
|
+
<button type="button" data-cmd="justifyCenter" title="${te('alignCenter')}">${ICONS.alignC}</button>
|
|
237
|
+
<button type="button" data-cmd="justifyRight" title="${te('alignRight')}">${ICONS.alignR}</button>
|
|
238
|
+
<div class="mzre-sep"></div>
|
|
239
|
+
<button type="button" data-action="link" title="${te('insertLink')}">${ICONS.link}</button>
|
|
240
|
+
<button type="button" data-cmd="removeFormat" title="${te('clearFormatting')}">${ICONS.clear}</button>
|
|
241
|
+
<div class="mzre-sep"></div>
|
|
242
|
+
<button type="button" data-cmd="undo" title="${te('undo')}">${ICONS.undo}</button>
|
|
243
|
+
<button type="button" data-cmd="redo" title="${te('redo')}">${ICONS.redo}</button>
|
|
244
|
+
</div>
|
|
245
|
+
|
|
246
|
+
<div class="mzre-link-bar">
|
|
247
|
+
<input type="text" class="mzre-link-input" placeholder="https://" />
|
|
248
|
+
<button type="button" class="mzre-btn-insert">${te('insert')}</button>
|
|
249
|
+
<button type="button" class="mzre-btn-remove">${te('remove')}</button>
|
|
250
|
+
<button type="button" class="mzre-btn-close">×</button>
|
|
251
|
+
</div>` : '';
|
|
252
|
+
return `
|
|
253
|
+
${toggleBar}
|
|
254
|
+
${toolbarAndLinkBar}
|
|
255
|
+
|
|
256
|
+
<div class="mzre-content-wrap"><div
|
|
257
|
+
class="mzre-content"
|
|
258
|
+
contenteditable="true"
|
|
259
|
+
role="textbox"
|
|
260
|
+
aria-multiline="true"
|
|
261
|
+
aria-label="${escapeHtml(label) || escapeHtml(placeholder) || te('placeholder')}"
|
|
262
|
+
data-placeholder="${escapeHtml(placeholder) || te('placeholder')}"
|
|
263
|
+
></div></div>
|
|
264
|
+
|
|
265
|
+
<div class="mzre-export-box"></div>
|
|
266
|
+
|
|
267
|
+
<div class="mzre-footer">
|
|
268
|
+
<span class="mzre-charcount">0 ${te('character')}</span>
|
|
269
|
+
<div class="mzre-footer-actions">
|
|
270
|
+
<button type="button" class="mzre-btn-action mzre-btn-html">${te('html')}</button>
|
|
271
|
+
<button type="button" class="mzre-btn-action mzre-btn-clear">${te('clear')}</button>
|
|
272
|
+
<button type="button" class="mzre-btn-primary mzre-btn-copy">${te('copyContent')}</button>
|
|
273
|
+
</div>
|
|
274
|
+
</div>
|
|
275
|
+
`;
|
|
276
|
+
}
|
|
277
|
+
/* ─────────────────────────────────────────
|
|
278
|
+
Mounts the editor on a <textarea>
|
|
279
|
+
───────────────────────────────────────── */
|
|
280
|
+
static mountEditor(textarea, opts = {}, integrations = {}) {
|
|
281
|
+
if (textarea.dataset.mzreMounted)
|
|
282
|
+
return;
|
|
283
|
+
if (opts.locale)
|
|
284
|
+
setEditorLocale(opts.locale);
|
|
285
|
+
if (integrations.messages)
|
|
286
|
+
setEditorMessages(integrations.messages);
|
|
287
|
+
textarea.dataset.mzreMounted = 'true';
|
|
288
|
+
const placeholder = textarea.getAttribute('placeholder') ?? '';
|
|
289
|
+
const initialValue = textarea.value ?? '';
|
|
290
|
+
const toolbarMode = (textarea.dataset.mzreToolbar ?? opts.toolbar ?? 'always');
|
|
291
|
+
const showFooter = opts.footer !== false;
|
|
292
|
+
const minHeight = textarea.dataset.mzreMinHeight ?? opts.minHeight ?? null;
|
|
293
|
+
const maxHeight = textarea.dataset.mzreMaxHeight ?? opts.maxHeight ?? null;
|
|
294
|
+
const wrap = document.createElement('div');
|
|
295
|
+
wrap.className = 'mzre-editor-wrap';
|
|
296
|
+
// Accessible name of the writing area: the textarea's aria-label, else its placeholder.
|
|
297
|
+
wrap.innerHTML = Editor.buildEditorHTML(placeholder, toolbarMode, textarea.getAttribute('aria-label') ?? '');
|
|
298
|
+
textarea.parentNode.insertBefore(wrap, textarea);
|
|
299
|
+
textarea.style.display = 'none';
|
|
300
|
+
const content = wrap.querySelector('.mzre-content');
|
|
301
|
+
const toolbar = wrap.querySelector('.mzre-toolbar');
|
|
302
|
+
const linkBar = wrap.querySelector('.mzre-link-bar');
|
|
303
|
+
const linkInput = wrap.querySelector('.mzre-link-input');
|
|
304
|
+
const exportBox = wrap.querySelector('.mzre-export-box');
|
|
305
|
+
const charCount = wrap.querySelector('.mzre-charcount');
|
|
306
|
+
const blockSelect = wrap.querySelector('.mzre-block-select');
|
|
307
|
+
const btnHtml = wrap.querySelector('.mzre-btn-html');
|
|
308
|
+
const btnClear = wrap.querySelector('.mzre-btn-clear');
|
|
309
|
+
const btnCopy = wrap.querySelector('.mzre-btn-copy');
|
|
310
|
+
const toggleBtn = wrap.querySelector('.mzre-toggle-btn');
|
|
311
|
+
// Hide the footer if requested
|
|
312
|
+
if (!showFooter) {
|
|
313
|
+
const footer = wrap.querySelector('.mzre-footer');
|
|
314
|
+
if (footer)
|
|
315
|
+
footer.style.display = 'none';
|
|
316
|
+
exportBox.style.display = 'none';
|
|
317
|
+
}
|
|
318
|
+
// Apply the custom heights
|
|
319
|
+
if (minHeight)
|
|
320
|
+
content.style.minHeight = minHeight;
|
|
321
|
+
if (maxHeight) {
|
|
322
|
+
content.style.maxHeight = maxHeight;
|
|
323
|
+
content.style.overflowY = 'auto';
|
|
324
|
+
}
|
|
325
|
+
let savedRange = null;
|
|
326
|
+
/* ── Toolbar visibility ── */
|
|
327
|
+
const showToolbar = () => {
|
|
328
|
+
if (!toolbar)
|
|
329
|
+
return;
|
|
330
|
+
toolbar.classList.remove('mzre-toolbar-anim-hide');
|
|
331
|
+
toolbar.classList.add('mzre-toolbar-anim-show');
|
|
332
|
+
wrap.classList.remove('mzre-toolbar-hidden');
|
|
333
|
+
wrap.classList.add('mzre-toolbar-visible');
|
|
334
|
+
toggleBtn?.classList.add('mzre-active');
|
|
335
|
+
};
|
|
336
|
+
const hideToolbar = () => {
|
|
337
|
+
if (!toolbar)
|
|
338
|
+
return;
|
|
339
|
+
toolbar.classList.remove('mzre-toolbar-anim-show');
|
|
340
|
+
toolbar.classList.add('mzre-toolbar-anim-hide');
|
|
341
|
+
wrap.classList.remove('mzre-toolbar-visible');
|
|
342
|
+
wrap.classList.add('mzre-toolbar-hidden');
|
|
343
|
+
toggleBtn?.classList.remove('mzre-active');
|
|
344
|
+
};
|
|
345
|
+
// toolbarMode 'never': no toolbar in the DOM, nothing to do
|
|
346
|
+
if (toolbarMode === 'focus') {
|
|
347
|
+
hideToolbar();
|
|
348
|
+
content.addEventListener('focus', showToolbar);
|
|
349
|
+
content.addEventListener('blur', () => {
|
|
350
|
+
// Short delay so the toolbar click can fire before hiding
|
|
351
|
+
setTimeout(() => { if (!wrap.contains(document.activeElement))
|
|
352
|
+
hideToolbar(); }, 150);
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
else if (toolbarMode === 'toggle') {
|
|
356
|
+
hideToolbar();
|
|
357
|
+
toggleBtn.addEventListener('click', () => {
|
|
358
|
+
wrap.classList.contains('mzre-toolbar-visible') ? hideToolbar() : showToolbar();
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
else if (toolbarMode !== 'never') {
|
|
362
|
+
showToolbar();
|
|
363
|
+
}
|
|
364
|
+
// Initial content sanitized: a stored and reloaded value must never run a script.
|
|
365
|
+
if (initialValue)
|
|
366
|
+
content.innerHTML = sanitizeHtml(initialValue);
|
|
367
|
+
/* ── Sync to the hidden textarea ── */
|
|
368
|
+
const emitChange = () => {
|
|
369
|
+
const text = content.innerText ?? '';
|
|
370
|
+
opts.onChange?.({ html: content.innerHTML, text, isEmpty: text.trim() === '' });
|
|
371
|
+
};
|
|
372
|
+
const sync = () => {
|
|
373
|
+
textarea.value = content.innerHTML;
|
|
374
|
+
emitChange();
|
|
375
|
+
};
|
|
376
|
+
/* ── Character counter ── */
|
|
377
|
+
const refreshCount = () => {
|
|
378
|
+
const n = content.innerText.replace(/\n/g, '').length;
|
|
379
|
+
charCount.textContent = n + (n <= 1 ? ` ${t('character')}` : ` ${t('characters')}`);
|
|
380
|
+
};
|
|
381
|
+
/* ── Run a command ── */
|
|
382
|
+
const exec = (cmd, val = null) => {
|
|
383
|
+
content.focus();
|
|
384
|
+
if (savedRange) {
|
|
385
|
+
const sel = window.getSelection();
|
|
386
|
+
sel.removeAllRanges();
|
|
387
|
+
sel.addRange(savedRange);
|
|
388
|
+
savedRange = null;
|
|
389
|
+
}
|
|
390
|
+
document.execCommand(cmd, false, val ?? undefined);
|
|
391
|
+
refreshToolbar();
|
|
392
|
+
sync();
|
|
393
|
+
};
|
|
394
|
+
/* ── Block style ── */
|
|
395
|
+
const setBlock = (tag) => {
|
|
396
|
+
content.focus();
|
|
397
|
+
document.execCommand('formatBlock', false, tag);
|
|
398
|
+
sync();
|
|
399
|
+
};
|
|
400
|
+
/* ── Toolbar button state ── */
|
|
401
|
+
const refreshToolbar = () => {
|
|
402
|
+
if (!toolbar || !blockSelect)
|
|
403
|
+
return;
|
|
404
|
+
const stateCmds = new Set([
|
|
405
|
+
'bold', 'italic', 'underline', 'strikeThrough',
|
|
406
|
+
'insertUnorderedList', 'insertOrderedList',
|
|
407
|
+
]);
|
|
408
|
+
toolbar.querySelectorAll('button[data-cmd]').forEach(btn => {
|
|
409
|
+
if (stateCmds.has(btn.dataset.cmd)) {
|
|
410
|
+
btn.classList.toggle('mzre-active', document.queryCommandState(btn.dataset.cmd));
|
|
411
|
+
}
|
|
412
|
+
});
|
|
413
|
+
const block = document.queryCommandValue('formatBlock').toLowerCase();
|
|
414
|
+
blockSelect.value = ['p', 'h2', 'h3', 'blockquote'].includes(block) ? block : 'p';
|
|
415
|
+
};
|
|
416
|
+
/* ── Link bar ── */
|
|
417
|
+
const openLinkBar = () => {
|
|
418
|
+
if (!linkBar || !linkInput)
|
|
419
|
+
return;
|
|
420
|
+
const sel = window.getSelection();
|
|
421
|
+
if (sel?.rangeCount)
|
|
422
|
+
savedRange = sel.getRangeAt(0).cloneRange();
|
|
423
|
+
linkBar.style.display = 'flex';
|
|
424
|
+
setTimeout(() => linkInput.focus(), 50);
|
|
425
|
+
};
|
|
426
|
+
const closeLinkBar = () => { if (linkBar)
|
|
427
|
+
linkBar.style.display = 'none'; };
|
|
428
|
+
const insertLink = () => {
|
|
429
|
+
if (!linkInput)
|
|
430
|
+
return;
|
|
431
|
+
const url = linkInput.value.trim();
|
|
432
|
+
if (!url)
|
|
433
|
+
return;
|
|
434
|
+
exec('createLink', url);
|
|
435
|
+
content.querySelectorAll('a').forEach(a => a.target = '_blank');
|
|
436
|
+
linkInput.value = '';
|
|
437
|
+
closeLinkBar();
|
|
438
|
+
};
|
|
439
|
+
/* ── HTML export ── */
|
|
440
|
+
const toggleHTML = () => {
|
|
441
|
+
const visible = exportBox.style.display !== 'none' && exportBox.style.display !== '';
|
|
442
|
+
if (visible) {
|
|
443
|
+
exportBox.style.display = 'none';
|
|
444
|
+
btnHtml.classList.remove('mzre-active');
|
|
445
|
+
}
|
|
446
|
+
else {
|
|
447
|
+
exportBox.textContent = content.innerHTML;
|
|
448
|
+
exportBox.style.display = 'block';
|
|
449
|
+
btnHtml.classList.add('mzre-active');
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
/* ── Clear ── */
|
|
453
|
+
const clearContent = () => {
|
|
454
|
+
if (content.innerText.trim() && !confirm(t('clearConfirm')))
|
|
455
|
+
return;
|
|
456
|
+
content.innerHTML = '';
|
|
457
|
+
refreshCount();
|
|
458
|
+
sync();
|
|
459
|
+
if (exportBox.style.display !== 'none')
|
|
460
|
+
exportBox.textContent = '';
|
|
461
|
+
};
|
|
462
|
+
/* ── Copy ── */
|
|
463
|
+
const copyHTML = () => {
|
|
464
|
+
navigator.clipboard.writeText(content.innerHTML).then(() => {
|
|
465
|
+
const orig = btnCopy.textContent;
|
|
466
|
+
btnCopy.textContent = t('copied');
|
|
467
|
+
setTimeout(() => (btnCopy.textContent = orig), 1500);
|
|
468
|
+
});
|
|
469
|
+
};
|
|
470
|
+
/* ── Toolbar events (absent in 'never' mode) ── */
|
|
471
|
+
if (toolbar) {
|
|
472
|
+
toolbar.addEventListener('click', (e) => {
|
|
473
|
+
const btn = e.target.closest('button[data-cmd]');
|
|
474
|
+
if (btn) {
|
|
475
|
+
exec(btn.dataset.cmd);
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
const actionBtn = e.target.closest('button[data-action]');
|
|
479
|
+
if (actionBtn?.dataset.action === 'link')
|
|
480
|
+
openLinkBar();
|
|
481
|
+
});
|
|
482
|
+
blockSelect.addEventListener('change', () => setBlock(blockSelect.value));
|
|
483
|
+
}
|
|
484
|
+
/* ── Link bar events (absent in 'never' mode) ── */
|
|
485
|
+
if (linkBar && linkInput) {
|
|
486
|
+
wrap.querySelector('.mzre-btn-insert').addEventListener('click', insertLink);
|
|
487
|
+
wrap.querySelector('.mzre-btn-remove').addEventListener('click', () => {
|
|
488
|
+
exec('unlink');
|
|
489
|
+
closeLinkBar();
|
|
490
|
+
});
|
|
491
|
+
wrap.querySelector('.mzre-btn-close').addEventListener('click', closeLinkBar);
|
|
492
|
+
linkInput.addEventListener('keydown', (e) => { if (e.key === 'Enter')
|
|
493
|
+
insertLink(); });
|
|
494
|
+
}
|
|
495
|
+
/* ── Footer events ── */
|
|
496
|
+
btnHtml.addEventListener('click', toggleHTML);
|
|
497
|
+
btnClear.addEventListener('click', clearContent);
|
|
498
|
+
btnCopy.addEventListener('click', copyHTML);
|
|
499
|
+
/* ── Writing area events ── */
|
|
500
|
+
content.addEventListener('input', () => {
|
|
501
|
+
sync();
|
|
502
|
+
refreshCount();
|
|
503
|
+
if (exportBox.style.display !== 'none')
|
|
504
|
+
exportBox.textContent = content.innerHTML;
|
|
505
|
+
});
|
|
506
|
+
if (toolbar) {
|
|
507
|
+
content.addEventListener('keyup', refreshToolbar);
|
|
508
|
+
content.addEventListener('mouseup', refreshToolbar);
|
|
509
|
+
}
|
|
510
|
+
content.addEventListener('mousedown', () => {
|
|
511
|
+
const sel = window.getSelection();
|
|
512
|
+
if (sel?.rangeCount)
|
|
513
|
+
savedRange = sel.getRangeAt(0).cloneRange();
|
|
514
|
+
});
|
|
515
|
+
content.addEventListener('keydown', (e) => {
|
|
516
|
+
if (e.key === 'Tab') {
|
|
517
|
+
e.preventDefault();
|
|
518
|
+
document.execCommand('insertHTML', false, ' ');
|
|
519
|
+
}
|
|
520
|
+
});
|
|
521
|
+
refreshCount();
|
|
522
|
+
emitChange();
|
|
523
|
+
if (opts.emoji) {
|
|
524
|
+
Editor._addEmojiInEditor(content, wrap);
|
|
525
|
+
}
|
|
526
|
+
if (opts.mention) {
|
|
527
|
+
if (!integrations.mentions)
|
|
528
|
+
throw new Error('Editor requires a mention integration.');
|
|
529
|
+
Editor._setupMentions(content, integrations.mentions);
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
/* ─────────────────────────────────────────
|
|
533
|
+
Emoji
|
|
534
|
+
───────────────────────────────────────── */
|
|
535
|
+
static _addEmojiInEditor(content, wrap) {
|
|
536
|
+
const button = document.createElement('button');
|
|
537
|
+
button.textContent = '😊';
|
|
538
|
+
button.className = 'mzre-emoji-button';
|
|
539
|
+
button.type = 'button';
|
|
540
|
+
button.title = t('addEmoji');
|
|
541
|
+
button.setAttribute('aria-label', t('addEmoji'));
|
|
542
|
+
// mousedown.preventDefault() keeps the contenteditable focused so the
|
|
543
|
+
// selection is still valid when the click handler calls _saveSelection().
|
|
544
|
+
button.addEventListener('mousedown', (e) => { e.preventDefault(); });
|
|
545
|
+
button.addEventListener('click', (e) => {
|
|
546
|
+
e.preventDefault();
|
|
547
|
+
const savedRange = Editor._saveSelection();
|
|
548
|
+
Editor._showEmojiPicker(content, savedRange);
|
|
549
|
+
});
|
|
550
|
+
const contentWrap = wrap.querySelector('.mzre-content-wrap');
|
|
551
|
+
if (contentWrap) {
|
|
552
|
+
contentWrap.style.position = contentWrap.style.position || 'relative';
|
|
553
|
+
contentWrap.appendChild(button);
|
|
554
|
+
// Prevent text from being hidden under the button
|
|
555
|
+
content.style.paddingRight = '44px';
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
static _saveSelection() {
|
|
559
|
+
const sel = window.getSelection();
|
|
560
|
+
return sel?.rangeCount ? sel.getRangeAt(0).cloneRange() : null;
|
|
561
|
+
}
|
|
562
|
+
static _showEmojiPicker(content, savedRange) {
|
|
563
|
+
EmojiPicker.open({
|
|
564
|
+
title: t('chooseEmoji'),
|
|
565
|
+
closeLabel: t('close'),
|
|
566
|
+
onSelect: (emoji) => {
|
|
567
|
+
const range = savedRange && content.contains(savedRange.commonAncestorContainer)
|
|
568
|
+
? savedRange
|
|
569
|
+
: document.createRange();
|
|
570
|
+
if (!savedRange || !content.contains(range.commonAncestorContainer)) {
|
|
571
|
+
range.selectNodeContents(content);
|
|
572
|
+
range.collapse(false);
|
|
573
|
+
}
|
|
574
|
+
range.deleteContents();
|
|
575
|
+
const emojiNode = document.createTextNode(emoji);
|
|
576
|
+
range.insertNode(emojiNode);
|
|
577
|
+
range.setStartAfter(emojiNode);
|
|
578
|
+
range.collapse(true);
|
|
579
|
+
const selection = window.getSelection();
|
|
580
|
+
selection?.removeAllRanges();
|
|
581
|
+
selection?.addRange(range);
|
|
582
|
+
// Triggers the sync from the contenteditable to the source textarea.
|
|
583
|
+
content.dispatchEvent(new Event('input', { bubbles: true }));
|
|
584
|
+
content.focus();
|
|
585
|
+
},
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
/* ─────────────────────────────────────────
|
|
589
|
+
Mentions
|
|
590
|
+
───────────────────────────────────────── */
|
|
591
|
+
static _setupMentions(content, integration) {
|
|
592
|
+
const state = {
|
|
593
|
+
isSearch: false,
|
|
594
|
+
atNode: null,
|
|
595
|
+
atOffset: 0,
|
|
596
|
+
previousTerm: null,
|
|
597
|
+
dropdown: null,
|
|
598
|
+
content,
|
|
599
|
+
activeIndex: -1,
|
|
600
|
+
listId: null,
|
|
601
|
+
stopOutsideClose: null,
|
|
602
|
+
};
|
|
603
|
+
// In capture phase: before the editor's handler (otherwise Tab inserts spaces).
|
|
604
|
+
content.addEventListener('keydown', (e) => {
|
|
605
|
+
Editor._handleMentionKeydown(e, content, state, integration);
|
|
606
|
+
}, true);
|
|
607
|
+
content.addEventListener('keyup', integration.debounce((e) => {
|
|
608
|
+
Editor._handleMentionSearch(e, content, state, integration);
|
|
609
|
+
}, 300));
|
|
610
|
+
}
|
|
611
|
+
static _handleMentionSearch(e, content, state, integration) {
|
|
612
|
+
const sel = window.getSelection();
|
|
613
|
+
if (!sel?.rangeCount)
|
|
614
|
+
return;
|
|
615
|
+
const range = sel.getRangeAt(0);
|
|
616
|
+
const node = range.endContainer;
|
|
617
|
+
if (node.nodeType !== Node.TEXT_NODE)
|
|
618
|
+
return;
|
|
619
|
+
const textNode = node;
|
|
620
|
+
const textBeforeCursor = (textNode.textContent ?? '').substring(0, range.endOffset);
|
|
621
|
+
const lastChar = textBeforeCursor[textBeforeCursor.length - 1];
|
|
622
|
+
if (lastChar === '@') {
|
|
623
|
+
// A new "@" while a bubble is open: the old one must not stay on screen.
|
|
624
|
+
Editor._closeMentionDropdown(state);
|
|
625
|
+
state.isSearch = true;
|
|
626
|
+
state.atNode = textNode;
|
|
627
|
+
state.atOffset = range.endOffset - 1;
|
|
628
|
+
state.previousTerm = null;
|
|
629
|
+
state.dropdown = Editor._showMentionDropdown(content, state, integration);
|
|
630
|
+
Editor._closeOnOutsidePointer(state);
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
if (!state.isSearch)
|
|
634
|
+
return;
|
|
635
|
+
if (e.code === 'Space' || e.code === 'Escape' || e.code === 'Enter' ||
|
|
636
|
+
content.innerText.trim() === '' || state.atNode !== textNode) {
|
|
637
|
+
Editor._closeMentionDropdown(state);
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
const atIndex = textBeforeCursor.lastIndexOf('@');
|
|
641
|
+
if (atIndex === -1) {
|
|
642
|
+
Editor._closeMentionDropdown(state);
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
const term = textBeforeCursor.substring(atIndex + 1).trim();
|
|
646
|
+
if (term.length >= 2 && term !== state.previousTerm) {
|
|
647
|
+
state.previousTerm = term;
|
|
648
|
+
Editor._performMentionSearch(term, content, state, integration);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* Creates the bubble on document.body with fixed positioning — works around the overflow:hidden of
|
|
653
|
+
* .mzre-editor-wrap, same pattern as the emoji picker. Placed below the writing area,
|
|
654
|
+
* shifted upward if needed.
|
|
655
|
+
*
|
|
656
|
+
* Its structure is built once: a header with the cross, an announcement area for screen
|
|
657
|
+
* readers (present before it changes, otherwise nothing is read) and a results area. It stays
|
|
658
|
+
* hidden while there is nothing to show.
|
|
659
|
+
*/
|
|
660
|
+
static _showMentionDropdown(content, state, integration) {
|
|
661
|
+
const dropdown = document.createElement('div');
|
|
662
|
+
dropdown.className = 'mzre-mentions-dropdown';
|
|
663
|
+
// Named landmark: the bubble's content, appended at the end of the page, would otherwise be in no landmark.
|
|
664
|
+
dropdown.setAttribute('role', 'region');
|
|
665
|
+
dropdown.setAttribute('aria-label', t('mentionSuggestions'));
|
|
666
|
+
dropdown.hidden = true;
|
|
667
|
+
state.listId = `mzre-mentions-list-${++mentionBubbleCount}`;
|
|
668
|
+
dropdown.innerHTML = `
|
|
669
|
+
<div class="mzre-mentions-header">
|
|
670
|
+
<button type="button" class="mzre-mentions-close" aria-label="${te('close')}">×</button>
|
|
671
|
+
</div>
|
|
672
|
+
<div class="mzre-sr-only" role="status" aria-live="polite"></div>
|
|
673
|
+
<div class="mzre-mentions-results"></div>`;
|
|
674
|
+
// Keeps focus in the writing area when the cross is pressed: closing happens on
|
|
675
|
+
// the click, handled below.
|
|
676
|
+
dropdown.querySelector('.mzre-mentions-close').addEventListener('mousedown', (e) => e.preventDefault());
|
|
677
|
+
dropdown.addEventListener('click', (e) => {
|
|
678
|
+
if (e.target.closest('.mzre-mentions-close')) {
|
|
679
|
+
Editor._closeMentionDropdown(state);
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
const option = e.target.closest('.mzre-mention-item');
|
|
683
|
+
if (option)
|
|
684
|
+
Editor._insertMention(option, content, state, integration);
|
|
685
|
+
});
|
|
686
|
+
document.body.appendChild(dropdown);
|
|
687
|
+
Editor._positionDropdown(dropdown, content);
|
|
688
|
+
return dropdown;
|
|
689
|
+
}
|
|
690
|
+
static _positionDropdown(dropdown, content) {
|
|
691
|
+
const rect = content.getBoundingClientRect();
|
|
692
|
+
const width = Math.min(Math.round(rect.width), 420);
|
|
693
|
+
const dropH = 300; // estimated max height of the dropdown
|
|
694
|
+
dropdown.style.left = `${Math.round(rect.left)}px`;
|
|
695
|
+
dropdown.style.width = `${width}px`;
|
|
696
|
+
const spaceBelow = window.innerHeight - rect.bottom;
|
|
697
|
+
if (spaceBelow >= dropH || spaceBelow >= 150) {
|
|
698
|
+
// Below the writing area
|
|
699
|
+
dropdown.style.top = `${Math.round(rect.bottom + 4)}px`;
|
|
700
|
+
dropdown.style.bottom = 'auto';
|
|
701
|
+
}
|
|
702
|
+
else {
|
|
703
|
+
// Above if there is not enough room below
|
|
704
|
+
dropdown.style.bottom = `${Math.round(window.innerHeight - rect.top + 4)}px`;
|
|
705
|
+
dropdown.style.top = 'auto';
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Closes the bubble as soon as the user presses (mouse or finger) anywhere but on it, including in the text
|
|
710
|
+
* of the editor. The listener is added on open and removed by _closeMentionDropdown().
|
|
711
|
+
*/
|
|
712
|
+
static _closeOnOutsidePointer(state) {
|
|
713
|
+
const onPointerDown = (event) => {
|
|
714
|
+
const target = event.target;
|
|
715
|
+
if (target && state.dropdown?.contains(target))
|
|
716
|
+
return;
|
|
717
|
+
Editor._closeMentionDropdown(state);
|
|
718
|
+
};
|
|
719
|
+
document.addEventListener('pointerdown', onPointerDown, true);
|
|
720
|
+
state.stopOutsideClose = () => document.removeEventListener('pointerdown', onPointerDown, true);
|
|
721
|
+
}
|
|
722
|
+
static _closeMentionDropdown(state) {
|
|
723
|
+
state.isSearch = false;
|
|
724
|
+
state.atNode = null;
|
|
725
|
+
state.previousTerm = null;
|
|
726
|
+
state.stopOutsideClose?.();
|
|
727
|
+
state.stopOutsideClose = null;
|
|
728
|
+
state.dropdown?.remove();
|
|
729
|
+
state.dropdown = null;
|
|
730
|
+
state.activeIndex = -1;
|
|
731
|
+
state.listId = null;
|
|
732
|
+
MENTION_ARIA.forEach((attribute) => state.content.removeAttribute(attribute));
|
|
733
|
+
}
|
|
734
|
+
static _performMentionSearch(term, content, state, integration) {
|
|
735
|
+
const dropdown = state.dropdown;
|
|
736
|
+
if (!dropdown)
|
|
737
|
+
return;
|
|
738
|
+
integration.loader.unfreezeElement();
|
|
739
|
+
setTimeout(() => { integration.loader.freezeElement(dropdown); }, 100);
|
|
740
|
+
integration.searchUsers(term)
|
|
741
|
+
.then((users) => {
|
|
742
|
+
if (users) {
|
|
743
|
+
Editor._renderMentionResults(users, dropdown, state);
|
|
744
|
+
}
|
|
745
|
+
})
|
|
746
|
+
.catch((error) => { console.error('[Editor Mentions]', error); })
|
|
747
|
+
.finally(() => integration.loader.unfreezeElement());
|
|
748
|
+
}
|
|
749
|
+
static _renderMentionResults(users, dropdown, state) {
|
|
750
|
+
const listId = state.listId;
|
|
751
|
+
const results = dropdown.querySelector('.mzre-mentions-results');
|
|
752
|
+
const status = dropdown.querySelector('[role="status"]');
|
|
753
|
+
// Bubble closed or replaced during the search: these results no longer concern it.
|
|
754
|
+
if (!listId || !results || !status || state.dropdown !== dropdown)
|
|
755
|
+
return;
|
|
756
|
+
// Texts and URLs come from the host application: escaped here, never inserted raw.
|
|
757
|
+
// A member without a usable profile URL is not offered.
|
|
758
|
+
const items = users
|
|
759
|
+
.filter((user) => user !== null)
|
|
760
|
+
.map((user, index) => Editor._mentionItemHtml(user, `${listId}-option-${index}`))
|
|
761
|
+
.filter((item) => item !== '');
|
|
762
|
+
state.activeIndex = -1;
|
|
763
|
+
state.content.removeAttribute('aria-activedescendant');
|
|
764
|
+
state.content.setAttribute('aria-autocomplete', 'list');
|
|
765
|
+
if (!items.length) {
|
|
766
|
+
results.innerHTML = `
|
|
767
|
+
<div class="mzre-mentions-empty">
|
|
768
|
+
<svg class="mzre-mentions-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true">
|
|
769
|
+
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
|
|
770
|
+
<circle cx="12" cy="7" r="4"></circle>
|
|
771
|
+
</svg>
|
|
772
|
+
<span class="mzre-mentions-empty-text">${te('noUserFound')}</span>
|
|
773
|
+
</div>`;
|
|
774
|
+
state.content.removeAttribute('aria-controls');
|
|
775
|
+
status.textContent = t('noUserFound');
|
|
776
|
+
dropdown.hidden = false;
|
|
777
|
+
return;
|
|
778
|
+
}
|
|
779
|
+
results.innerHTML = `<div class="mzre-mentions-list" role="listbox" id="${listId}" aria-label="${te('mentionSuggestions')}">${items.join('')}</div>`;
|
|
780
|
+
state.content.setAttribute('aria-controls', listId);
|
|
781
|
+
status.textContent = (items.length === 1 ? t('mentionResultsOne') : t('mentionResultsMany'))
|
|
782
|
+
.replace('{count}', String(items.length));
|
|
783
|
+
dropdown.hidden = false;
|
|
784
|
+
}
|
|
785
|
+
/** Options shown in the bubble (empty until it has results). */
|
|
786
|
+
static _mentionOptions(state) {
|
|
787
|
+
return Array.from(state.dropdown?.querySelectorAll('.mzre-mention-item') ?? []);
|
|
788
|
+
}
|
|
789
|
+
/** Chooses an option with the keyboard: `aria-selected` on the option, `aria-activedescendant` on the writing area. */
|
|
790
|
+
static _setActiveMention(state, index) {
|
|
791
|
+
const options = Editor._mentionOptions(state);
|
|
792
|
+
options.forEach((option, position) => option.setAttribute('aria-selected', String(position === index)));
|
|
793
|
+
state.activeIndex = index;
|
|
794
|
+
const active = options[index];
|
|
795
|
+
if (active) {
|
|
796
|
+
state.content.setAttribute('aria-activedescendant', active.id);
|
|
797
|
+
active.scrollIntoView?.({ block: 'nearest' });
|
|
798
|
+
}
|
|
799
|
+
else {
|
|
800
|
+
state.content.removeAttribute('aria-activedescendant');
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
/**
|
|
804
|
+
* Keyboard, while the bubble is open. Focus never leaves the writing area:
|
|
805
|
+
* · Escape → closes the bubble without touching the text (and without closing a host modal)
|
|
806
|
+
* · Up/Down arrows, Home/End → choose a suggestion (Home/End only once
|
|
807
|
+
* a suggestion is chosen; otherwise they move the caret as usual)
|
|
808
|
+
* · Enter or Tab → insert the chosen suggestion; with no choice, they keep their usual role
|
|
809
|
+
*/
|
|
810
|
+
static _handleMentionKeydown(e, content, state, integration) {
|
|
811
|
+
if (!state.isSearch || e.isComposing)
|
|
812
|
+
return;
|
|
813
|
+
const stop = () => {
|
|
814
|
+
e.preventDefault();
|
|
815
|
+
e.stopImmediatePropagation();
|
|
816
|
+
};
|
|
817
|
+
if (e.key === 'Escape') {
|
|
818
|
+
stop();
|
|
819
|
+
e.stopPropagation();
|
|
820
|
+
Editor._closeMentionDropdown(state);
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
const options = Editor._mentionOptions(state);
|
|
824
|
+
if (!options.length)
|
|
825
|
+
return;
|
|
826
|
+
const active = state.activeIndex;
|
|
827
|
+
if (e.key === 'ArrowDown') {
|
|
828
|
+
stop();
|
|
829
|
+
Editor._setActiveMention(state, (active + 1) % options.length);
|
|
830
|
+
}
|
|
831
|
+
else if (e.key === 'ArrowUp') {
|
|
832
|
+
stop();
|
|
833
|
+
Editor._setActiveMention(state, active <= 0 ? options.length - 1 : active - 1);
|
|
834
|
+
}
|
|
835
|
+
else if (e.key === 'Home' && active >= 0) {
|
|
836
|
+
stop();
|
|
837
|
+
Editor._setActiveMention(state, 0);
|
|
838
|
+
}
|
|
839
|
+
else if (e.key === 'End' && active >= 0) {
|
|
840
|
+
stop();
|
|
841
|
+
Editor._setActiveMention(state, options.length - 1);
|
|
842
|
+
}
|
|
843
|
+
else if ((e.key === 'Enter' || e.key === 'Tab') && active >= 0) {
|
|
844
|
+
stop();
|
|
845
|
+
Editor._insertMention(options[active], content, state, integration);
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
/** A member's row in the bubble; empty string if their profile URL is unusable. */
|
|
849
|
+
static _mentionItemHtml(user, id) {
|
|
850
|
+
const profilePath = safeSitePath(user.profileUrl);
|
|
851
|
+
if (profilePath === null)
|
|
852
|
+
return '';
|
|
853
|
+
const firstName = String(user.firstName ?? '');
|
|
854
|
+
const lastName = String(user.lastName ?? '');
|
|
855
|
+
const name = `${firstName} ${lastName}`.trim();
|
|
856
|
+
const avatar = safeHttpUrl(user.avatarUrl);
|
|
857
|
+
const initials = ([...firstName][0] ?? '') + ([...lastName][0] ?? '');
|
|
858
|
+
// Decorative avatar: the name is read right next to it.
|
|
859
|
+
const avatarHtml = avatar
|
|
860
|
+
? `<img src="${escapeHtml(avatar)}" alt="" loading="lazy" />`
|
|
861
|
+
: `<span class="mzre-mention-avatar-fallback" aria-hidden="true">${escapeHtml(initials.toUpperCase())}</span>`;
|
|
862
|
+
return `
|
|
863
|
+
<div class="mzre-mention-item" id="${escapeHtml(id)}" data-user-id="${escapeHtml(user.ID)}" data-profile-url="${escapeHtml(profilePath)}" role="option" aria-selected="false">
|
|
864
|
+
<div class="mzre-mention-avatar">${avatarHtml}</div>
|
|
865
|
+
<div class="mzre-mention-info">
|
|
866
|
+
<span class="mzre-mention-name">${escapeHtml(name)}</span>
|
|
867
|
+
</div>
|
|
868
|
+
</div>`;
|
|
869
|
+
}
|
|
870
|
+
static _insertMention(item, content, state, integration) {
|
|
871
|
+
if (!state.atNode)
|
|
872
|
+
return;
|
|
873
|
+
const username = item.querySelector('.mzre-mention-name')?.textContent?.trim() ?? '';
|
|
874
|
+
const profileUrl = item.dataset.profileUrl ?? '';
|
|
875
|
+
const userId = integration.encodeUserId(item.dataset.userId ?? '');
|
|
876
|
+
// Compute the end of the @term from the saved state — do not use
|
|
877
|
+
// the current selection: focus left the contenteditable on the click
|
|
878
|
+
// on the dropdown, making the offset invalid for state.atNode.
|
|
879
|
+
const nodeLen = state.atNode.textContent?.length ?? 0;
|
|
880
|
+
const termLen = 1 + (state.previousTerm?.length ?? 0); // 1 = the @ itself
|
|
881
|
+
const endOffset = Math.min(state.atOffset + termLen, nodeLen);
|
|
882
|
+
// Remove the "@term" text then insert the mention blot
|
|
883
|
+
const deleteRange = document.createRange();
|
|
884
|
+
deleteRange.setStart(state.atNode, state.atOffset);
|
|
885
|
+
deleteRange.setEnd(state.atNode, endOffset);
|
|
886
|
+
deleteRange.deleteContents();
|
|
887
|
+
const mentionEl = document.createElement('a');
|
|
888
|
+
mentionEl.href = profileUrl;
|
|
889
|
+
mentionEl.dataset.userId = userId;
|
|
890
|
+
mentionEl.target = '_blank';
|
|
891
|
+
mentionEl.className = 'mention';
|
|
892
|
+
mentionEl.textContent = username;
|
|
893
|
+
deleteRange.insertNode(mentionEl);
|
|
894
|
+
// Put focus back on the contenteditable (lost on the dropdown click)
|
|
895
|
+
// then move the caret after the mention and insert a separator space.
|
|
896
|
+
content.focus();
|
|
897
|
+
const sel = window.getSelection();
|
|
898
|
+
const newRange = document.createRange();
|
|
899
|
+
newRange.setStartAfter(mentionEl);
|
|
900
|
+
newRange.collapse(true);
|
|
901
|
+
sel.removeAllRanges();
|
|
902
|
+
sel.addRange(newRange);
|
|
903
|
+
document.execCommand('insertText', false, ' ');
|
|
904
|
+
Editor._closeMentionDropdown(state);
|
|
905
|
+
// Triggers the existing 'input' listener that calls sync() + refreshCount()
|
|
906
|
+
content.dispatchEvent(new Event('input'));
|
|
907
|
+
}
|
|
908
|
+
/* ─────────────────────────────────────────
|
|
909
|
+
Public API
|
|
910
|
+
───────────────────────────────────────── */
|
|
911
|
+
/**
|
|
912
|
+
* Initializes the editor on every textarea matching the selector.
|
|
913
|
+
*
|
|
914
|
+
* @param options.selector CSS selector to target (default: 'textarea')
|
|
915
|
+
* @param options.exclude CSS selector to exclude
|
|
916
|
+
* @param options.toolbar Toolbar mode: 'always' | 'toggle' | 'focus' | 'never'
|
|
917
|
+
* @param options.footer Show the footer — default: true
|
|
918
|
+
* @param options.minHeight Minimum height of the writing area (e.g. '160px')
|
|
919
|
+
* @param options.maxHeight Maximum height before it scrolls (e.g. '400px')
|
|
920
|
+
*
|
|
921
|
+
* The data-mzre-* attributes on each textarea take precedence over the JS options.
|
|
922
|
+
* See the documentation block at the top of the file for detailed use cases.
|
|
923
|
+
*
|
|
924
|
+
* @returns Editor (chainable)
|
|
925
|
+
*/
|
|
926
|
+
static init(options = {}, integrations = {}) {
|
|
927
|
+
if (options.styles)
|
|
928
|
+
setEditorStyles(options.styles);
|
|
929
|
+
Editor.injectStyles();
|
|
930
|
+
const selector = options.selector ?? 'textarea';
|
|
931
|
+
const exclude = options.exclude ?? null;
|
|
932
|
+
Array.from(document.querySelectorAll(selector))
|
|
933
|
+
.filter((el) => el.tagName === 'TEXTAREA')
|
|
934
|
+
.filter(el => !exclude || !el.matches(exclude))
|
|
935
|
+
.forEach(el => Editor.mountEditor(el, options, integrations));
|
|
936
|
+
return Editor;
|
|
937
|
+
}
|
|
938
|
+
/**
|
|
939
|
+
* Mounts the editor on a specific textarea.
|
|
940
|
+
* Ideal for elements added dynamically to the DOM (modals, ajax widgets…).
|
|
941
|
+
*
|
|
942
|
+
* @param target HTMLTextAreaElement element or CSS selector
|
|
943
|
+
* @param options Same options as init()
|
|
944
|
+
*
|
|
945
|
+
* @param integrations
|
|
946
|
+
* @returns Editor (chainable)
|
|
947
|
+
*/
|
|
948
|
+
static mount(target, options = {}, integrations = {}) {
|
|
949
|
+
if (options.styles)
|
|
950
|
+
setEditorStyles(options.styles);
|
|
951
|
+
Editor.injectStyles();
|
|
952
|
+
const el = typeof target === 'string'
|
|
953
|
+
? document.querySelector(target)
|
|
954
|
+
: target;
|
|
955
|
+
if (el?.tagName === 'TEXTAREA')
|
|
956
|
+
Editor.mountEditor(el, options, integrations);
|
|
957
|
+
return Editor;
|
|
958
|
+
}
|
|
959
|
+
}
|