svelte-multistyle-ui 0.0.9-alpha → 0.0.11-alpha

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.
@@ -0,0 +1,800 @@
1
+ /**
2
+ * TextEditorCore — a lightweight, framework-agnostic WYSIWYG editor.
3
+ * Uses contenteditable and document.execCommand under the hood.
4
+ */
5
+
6
+ import { createHistory } from "./history.js";
7
+ import { getSelectionState } from "./selection-engine.js";
8
+ import { sanitizeHTML, sanitizeURL, plainTextFromHTML } from "./sanitizer.js";
9
+ import {
10
+ createElement,
11
+ ensureParagraph,
12
+ getWordCount,
13
+ getTextLength,
14
+ htmlToText,
15
+ isInsideEditor,
16
+ closest,
17
+ } from "./dom-utils.js";
18
+ import { DEFAULT_TOOLBAR } from "./toolbar-config.js";
19
+ import { formatHTML } from "./html-formatter.js";
20
+
21
+ const BLOCK_TAG_MAP = {
22
+ p: "p",
23
+ h1: "h1",
24
+ h2: "h2",
25
+ h3: "h3",
26
+ h4: "h4",
27
+ h5: "h5",
28
+ h6: "h6",
29
+ blockquote: "blockquote",
30
+ pre: "pre",
31
+ };
32
+
33
+ export class TextEditorCore {
34
+ constructor(options = {}) {
35
+ this.container = options.element;
36
+ if (!this.container) {
37
+ throw new Error("TextEditorCore requires a container element");
38
+ }
39
+
40
+ this.onChange = options.onChange || (() => {});
41
+ this.onSelectionChange = options.onSelectionChange || (() => {});
42
+ this.onAction = options.onAction || (() => {});
43
+ this.placeholder = options.placeholder || "";
44
+ this.readOnly = options.readOnly || false;
45
+ this.historyLimit = options.historyLimit || 100;
46
+
47
+ this.toolbarConfig = options.toolbar || DEFAULT_TOOLBAR;
48
+ this.value = "";
49
+ this.history = createHistory(this.historyLimit);
50
+ this.isComposing = false;
51
+ this.lastHtml = "";
52
+ this.focused = false;
53
+
54
+ this._handlers = [];
55
+ this._dialogState = { type: null, data: null };
56
+ this._codeView = false;
57
+ this._codeEl = null;
58
+ this._lastCodeValue = "";
59
+ this._savedSelection = null;
60
+
61
+ this._buildDOM();
62
+ this._attachEvents();
63
+ this._renderToolbar();
64
+ this._updatePlaceholder();
65
+ this._updateStatus();
66
+ }
67
+
68
+ // ============ DOM construction ============
69
+ _buildDOM() {
70
+ this.container.classList.add("s-texteditor");
71
+ if (this.readOnly) this.container.classList.add("readonly");
72
+
73
+ this.toolbarEl = createElement("div", { className: "s-texteditor-toolbar" });
74
+ this.bodyEl = createElement("div", { className: "s-texteditor-body" });
75
+ this.editorEl = createElement("div", {
76
+ className: "s-texteditor-content",
77
+ contenteditable: this.readOnly ? "false" : "true",
78
+ role: "textbox",
79
+ "aria-multiline": "true",
80
+ });
81
+ this.statusEl = createElement("div", { className: "s-texteditor-statusbar" });
82
+
83
+ this.bodyEl.appendChild(this.editorEl);
84
+ this.container.appendChild(this.toolbarEl);
85
+ this.container.appendChild(this.bodyEl);
86
+ this.container.appendChild(this.statusEl);
87
+
88
+ if (this.placeholder) {
89
+ this.container.setAttribute("data-placeholder", this.placeholder);
90
+ }
91
+ }
92
+
93
+ // ============ Event wiring ============
94
+ _attachEvents() {
95
+ this._listen(this.editorEl, "input", this._onInput.bind(this));
96
+ this._listen(this.editorEl, "keydown", this._onKeyDown.bind(this));
97
+ this._listen(this.editorEl, "focus", this._onFocus.bind(this));
98
+ this._listen(this.editorEl, "blur", this._onBlur.bind(this));
99
+ this._listen(this.editorEl, "compositionstart", this._onCompositionStart.bind(this));
100
+ this._listen(this.editorEl, "compositionend", this._onCompositionEnd.bind(this));
101
+ this._listen(this.editorEl, "paste", this._onPaste.bind(this));
102
+ this._listen(this.editorEl, "drop", this._onDrop.bind(this));
103
+ this._listen(document, "selectionchange", this._onSelectionChange.bind(this));
104
+ }
105
+
106
+ _listen(target, event, handler) {
107
+ target.addEventListener(event, handler);
108
+ this._handlers.push({ target, event, handler });
109
+ }
110
+
111
+ destroy() {
112
+ for (const { target, event, handler } of this._handlers) {
113
+ target.removeEventListener(event, handler);
114
+ }
115
+ this._handlers = [];
116
+ if (this.toolbarEl) this.toolbarEl.innerHTML = "";
117
+ if (this.container) {
118
+ this.container.classList.remove("s-texteditor", "readonly");
119
+ }
120
+ }
121
+
122
+ // ============ Input handling ============
123
+ _onInput() {
124
+ if (this.isComposing) return;
125
+ this._emitChange();
126
+ }
127
+
128
+ _onCompositionStart() {
129
+ this.isComposing = true;
130
+ }
131
+
132
+ _onCompositionEnd() {
133
+ this.isComposing = false;
134
+ this._emitChange();
135
+ }
136
+
137
+ _emitChange() {
138
+ if (this._codeView) return; // Code view manages value directly.
139
+ const html = this.getHTML();
140
+ if (html === this.lastHtml) return;
141
+ this.lastHtml = html;
142
+ this.value = html;
143
+ this.history.record(html);
144
+ this._updatePlaceholder();
145
+ this._updateStatus();
146
+ this.onChange(html);
147
+ }
148
+
149
+ _onFocus() {
150
+ this.focused = true;
151
+ this.container.classList.add("focused");
152
+ }
153
+
154
+ _onBlur() {
155
+ this.focused = false;
156
+ this.container.classList.remove("focused");
157
+ }
158
+
159
+ _onSelectionChange() {
160
+ const sel = document.getSelection();
161
+ if (!sel || sel.rangeCount === 0) return;
162
+ if (!isInsideEditor(sel.anchorNode, this.editorEl)) return;
163
+
164
+ const state = getSelectionState(this.editorEl);
165
+ this._updateToolbarState(state);
166
+ this._updateStatus(state);
167
+ this.onSelectionChange(state);
168
+ }
169
+
170
+ // ============ Keyboard shortcuts ============
171
+ _onKeyDown(e) {
172
+ const key = e.key;
173
+ const ctrl = e.ctrlKey || e.metaKey;
174
+ const shift = e.shiftKey;
175
+
176
+ if (ctrl) {
177
+ switch (key.toLowerCase()) {
178
+ case "b":
179
+ e.preventDefault();
180
+ this._applyFormat("bold");
181
+ return;
182
+ case "i":
183
+ e.preventDefault();
184
+ this._applyFormat("italic");
185
+ return;
186
+ case "u":
187
+ e.preventDefault();
188
+ this._applyFormat("underline");
189
+ return;
190
+ case "z":
191
+ e.preventDefault();
192
+ if (shift) this.redo();
193
+ else this.undo();
194
+ return;
195
+ case "y":
196
+ e.preventDefault();
197
+ this.redo();
198
+ return;
199
+ case "k":
200
+ e.preventDefault();
201
+ this._openLinkDialog();
202
+ return;
203
+ case "a":
204
+ setTimeout(() => this._onSelectionChange(), 0);
205
+ return;
206
+ }
207
+
208
+ if (shift) {
209
+ switch (key.toLowerCase()) {
210
+ case "s":
211
+ e.preventDefault();
212
+ this._applyFormat("strikeThrough");
213
+ return;
214
+ case "l":
215
+ e.preventDefault();
216
+ this.exec("justifyLeft");
217
+ this._emitChange();
218
+ return;
219
+ case "e":
220
+ e.preventDefault();
221
+ this.exec("justifyCenter");
222
+ this._emitChange();
223
+ return;
224
+ case "r":
225
+ e.preventDefault();
226
+ this.exec("justifyRight");
227
+ this._emitChange();
228
+ return;
229
+ case "j":
230
+ e.preventDefault();
231
+ this.exec("justifyFull");
232
+ this._emitChange();
233
+ return;
234
+ }
235
+ }
236
+ }
237
+
238
+ if (key === "Tab") {
239
+ e.preventDefault();
240
+ if (shift) this.exec("outdent");
241
+ else this.exec("indent");
242
+ this._emitChange();
243
+ return;
244
+ }
245
+ }
246
+
247
+ _applyFormat(command) {
248
+ this.focus();
249
+ this._recordBeforeMutation();
250
+ this.exec(command);
251
+ this._emitChange();
252
+ }
253
+
254
+ // ============ Paste / Drop ============
255
+ _onPaste(e) {
256
+ e.preventDefault();
257
+ const html = e.clipboardData.getData("text/html");
258
+ const text = e.clipboardData.getData("text/plain");
259
+ const toInsert = html ? sanitizeHTML(html) : (text ? text.replace(/\n/g, "<br>") : "");
260
+ if (toInsert) {
261
+ this._recordBeforeMutation();
262
+ this.exec("insertHTML", toInsert);
263
+ this._emitChange();
264
+ }
265
+ }
266
+
267
+ _onDrop(e) {
268
+ e.preventDefault();
269
+ const files = Array.from(e.dataTransfer.files);
270
+ for (const file of files) {
271
+ if (file.type.startsWith("image/")) {
272
+ this._insertImageFromFile(file);
273
+ }
274
+ }
275
+ }
276
+
277
+ _insertImageFromFile(file) {
278
+ const reader = new FileReader();
279
+ reader.onload = (ev) => {
280
+ this._recordBeforeMutation();
281
+ this.exec("insertHTML", `<img src="${ev.target.result}" alt="" style="max-width:100%;" />`);
282
+ this._emitChange();
283
+ };
284
+ reader.readAsDataURL(file);
285
+ }
286
+
287
+ // ============ Toolbar rendering ============
288
+ _renderToolbar() {
289
+ this.toolbarEl.innerHTML = "";
290
+ for (const group of this.toolbarConfig) {
291
+ const groupEl = createElement("div", { className: "s-texteditor-toolbar-group" });
292
+ for (const action of group) {
293
+ if (action.type === "separator") {
294
+ groupEl.appendChild(createElement("span", { className: "s-texteditor-toolbar-separator" }));
295
+ continue;
296
+ }
297
+ const control = this._createControl(action);
298
+ if (control) groupEl.appendChild(control);
299
+ }
300
+ this.toolbarEl.appendChild(groupEl);
301
+ }
302
+ }
303
+
304
+ _createControl(action) {
305
+ if (action.type === "button") {
306
+ const btn = createElement("button", {
307
+ className: `s-texteditor-btn s-texteditor-btn-${action.id}`,
308
+ type: "button",
309
+ title: action.title || action.label,
310
+ "data-command": action.command,
311
+ "data-active": action.active || "",
312
+ innerHTML: action.icon ? `<span class="${action.icon}">${action.label}</span>` : action.label,
313
+ onclick: (e) => {
314
+ e.preventDefault();
315
+ this._handleCommand(action);
316
+ },
317
+ });
318
+ return btn;
319
+ }
320
+
321
+ if (action.type === "select") {
322
+ const select = createElement("select", {
323
+ className: "s-texteditor-select",
324
+ title: action.title,
325
+ "data-command": action.command,
326
+ onchange: (e) => {
327
+ this._handleCommand(action, e.target.value);
328
+ e.target.selectedIndex = 0;
329
+ },
330
+ });
331
+ select.appendChild(createElement("option", { textContent: action.title, value: "" }));
332
+ for (const opt of action.options) {
333
+ select.appendChild(createElement("option", { textContent: opt.label, value: opt.value }));
334
+ }
335
+ return createElement("div", { className: "s-texteditor-select-wrap" }, [select]);
336
+ }
337
+
338
+ if (action.type === "color") {
339
+ const label = createElement("label", {
340
+ className: `s-texteditor-color-btn s-texteditor-color-${action.id}`,
341
+ title: action.title,
342
+ });
343
+ const input = createElement("input", {
344
+ type: "color",
345
+ "data-command": action.command,
346
+ onchange: (e) => {
347
+ this._handleCommand(action, e.target.value);
348
+ },
349
+ });
350
+ label.appendChild(input);
351
+ return label;
352
+ }
353
+
354
+ return null;
355
+ }
356
+
357
+ _handleCommand(action, value) {
358
+ if (action.id === "toggleCodeView") {
359
+ this.toggleCodeView();
360
+ return;
361
+ }
362
+
363
+ this.focus();
364
+
365
+ if (action.id === "undo") {
366
+ this.undo();
367
+ return;
368
+ }
369
+ if (action.id === "redo") {
370
+ this.redo();
371
+ return;
372
+ }
373
+ if (action.id === "removeFormat") {
374
+ this._recordBeforeMutation();
375
+ this.exec("removeFormat");
376
+ this._emitChange();
377
+ return;
378
+ }
379
+ if (action.id === "lineHeight") {
380
+ this._recordBeforeMutation();
381
+ this._applyLineHeight(value);
382
+ this._emitChange();
383
+ return;
384
+ }
385
+ if (action.id === "formatBlock") {
386
+ this._recordBeforeMutation();
387
+ this._applyBlockFormat(value);
388
+ this._emitChange();
389
+ return;
390
+ }
391
+ if (action.id === "insertLink" || action.id === "createLink") {
392
+ this._openLinkDialog();
393
+ return;
394
+ }
395
+ if (action.id === "insertImage") {
396
+ this._openImageDialog();
397
+ return;
398
+ }
399
+ if (action.id === "insertVideo") {
400
+ this._openVideoDialog();
401
+ return;
402
+ }
403
+ if (action.id === "insertTable") {
404
+ this._openTableDialog();
405
+ return;
406
+ }
407
+
408
+ // Default execCommand path.
409
+ this._recordBeforeMutation();
410
+ this.exec(action.command, value || null);
411
+ this._emitChange();
412
+ }
413
+
414
+ // ============ Command helpers ============
415
+ exec(command, value = null) {
416
+ document.execCommand(command, false, value);
417
+ }
418
+
419
+ _applyBlockFormat(tag) {
420
+ if (!tag) return;
421
+ const mapped = BLOCK_TAG_MAP[tag.toLowerCase()] || tag;
422
+ this.exec("formatBlock", `<${mapped}>`);
423
+ }
424
+
425
+ _applyLineHeight(value) {
426
+ const sel = document.getSelection();
427
+ if (!sel.rangeCount) return;
428
+ const range = sel.getRangeAt(0);
429
+ const blocks = [];
430
+ let node = range.startContainer;
431
+ while (node) {
432
+ if (node === this.editorEl) break;
433
+ if (node.nodeType === Node.ELEMENT_NODE) blocks.push(node);
434
+ node = node.parentNode;
435
+ }
436
+ if (blocks.length === 0) {
437
+ this.editorEl.style.lineHeight = value;
438
+ return;
439
+ }
440
+ for (const block of blocks) {
441
+ block.style.lineHeight = value;
442
+ }
443
+ }
444
+
445
+ // ============ Dialog-driven actions ============
446
+ _openLinkDialog() {
447
+ const existing = this._getSelectedLink();
448
+ this._dialogState = {
449
+ type: "link",
450
+ data: existing
451
+ ? { text: existing.textContent, href: existing.getAttribute("href") || "", title: existing.getAttribute("title") || "", target: existing.getAttribute("target") || "_self" }
452
+ : { text: document.getSelection().toString(), href: "https://", title: "", target: "_self" },
453
+ };
454
+ this.onAction({ type: "dialog", dialog: "link", data: this._dialogState.data });
455
+ }
456
+
457
+ _openImageDialog() {
458
+ this._dialogState = { type: "image", data: { src: "", alt: "", width: "", caption: "" } };
459
+ this.onAction({ type: "dialog", dialog: "image", data: this._dialogState.data });
460
+ }
461
+
462
+ _openVideoDialog() {
463
+ this._dialogState = { type: "video", data: { src: "", width: "560", height: "315" } };
464
+ this.onAction({ type: "dialog", dialog: "video", data: this._dialogState.data });
465
+ }
466
+
467
+ _openTableDialog() {
468
+ this._dialogState = { type: "table", data: { rows: 3, cols: 3 } };
469
+ this.onAction({ type: "dialog", dialog: "table", data: this._dialogState.data });
470
+ }
471
+
472
+ _getSelectedLink() {
473
+ const sel = document.getSelection();
474
+ if (!sel.rangeCount) return null;
475
+ let node = sel.anchorNode;
476
+ while (node && node !== this.editorEl) {
477
+ if (node.nodeType === Node.ELEMENT_NODE && node.tagName === "A") {
478
+ return node;
479
+ }
480
+ node = node.parentNode;
481
+ }
482
+ return null;
483
+ }
484
+
485
+ // Public APIs used by the Svelte wrapper to apply dialog results.
486
+ insertLink({ text, href, title, target }) {
487
+ const url = sanitizeURL(href);
488
+ if (!url) return;
489
+ this.focus();
490
+ this._recordBeforeMutation();
491
+
492
+ const existing = this._getSelectedLink();
493
+ if (existing) {
494
+ existing.setAttribute("href", url);
495
+ if (title) existing.setAttribute("title", title);
496
+ else existing.removeAttribute("title");
497
+ existing.setAttribute("target", target || "_self");
498
+ if (text) existing.textContent = text;
499
+ } else {
500
+ const anchor = `<a href="${url}"${title ? ` title="${title}"` : ""} target="${target || "_self"}" rel="noopener noreferrer">${text || url}</a>`;
501
+ this.exec("insertHTML", anchor);
502
+ }
503
+ this._emitChange();
504
+ }
505
+
506
+ removeLink() {
507
+ this.focus();
508
+ this._recordBeforeMutation();
509
+ this.exec("unlink");
510
+ this._emitChange();
511
+ }
512
+
513
+ insertImage({ src, alt, width, align, caption }) {
514
+ if (!src) return;
515
+ this.focus();
516
+ this._recordBeforeMutation();
517
+
518
+ let figure = "";
519
+ const style = [];
520
+ if (width) style.push(`width:${width}`);
521
+ if (align) {
522
+ style.push(`float:${align}`);
523
+ if (align === "left" || align === "right") {
524
+ style.push("margin:0 12px 12px 0");
525
+ }
526
+ }
527
+ const styleAttr = style.length ? ` style="${style.join(";")}"` : "";
528
+
529
+ if (caption) {
530
+ figure = `<figure${styleAttr}><img src="${src}" alt="${alt || ""}" style="max-width:100%;display:block;" /><figcaption>${caption}</figcaption></figure>`;
531
+ } else {
532
+ figure = `<img src="${src}" alt="${alt || ""}"${styleAttr} style="max-width:100%;" />`;
533
+ }
534
+ this.exec("insertHTML", figure);
535
+ this._emitChange();
536
+ }
537
+
538
+ insertVideo({ src, width = "560", height = "315" }) {
539
+ if (!src) return;
540
+ this.focus();
541
+ this._recordBeforeMutation();
542
+
543
+ let embedUrl = src;
544
+ const youtubeMatch = src.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);
545
+ if (youtubeMatch) {
546
+ embedUrl = `https://www.youtube.com/embed/${youtubeMatch[1]}`;
547
+ }
548
+ const vimeoMatch = src.match(/vimeo\.com\/(\d+)/);
549
+ if (vimeoMatch) {
550
+ embedUrl = `https://player.vimeo.com/video/${vimeoMatch[1]}`;
551
+ }
552
+
553
+ const iframe = `<iframe src="${embedUrl}" width="${width}" height="${height}" frameborder="0" allowfullscreen></iframe>`;
554
+ this.exec("insertHTML", iframe);
555
+ this._emitChange();
556
+ }
557
+
558
+ insertTable({ rows, cols }) {
559
+ rows = Math.max(1, Math.min(20, Number(rows) || 1));
560
+ cols = Math.max(1, Math.min(20, Number(cols) || 1));
561
+ this.focus();
562
+ this._recordBeforeMutation();
563
+
564
+ let html = `<table style="width:100%;border-collapse:collapse;"><tbody>`;
565
+ for (let r = 0; r < rows; r++) {
566
+ html += `<tr>`;
567
+ for (let c = 0; c < cols; c++) {
568
+ html += `<td style="border:1px solid currentColor;padding:6px 8px;"></td>`;
569
+ }
570
+ html += `</tr>`;
571
+ }
572
+ html += `</tbody></table><p><br></p>`;
573
+ this.exec("insertHTML", html);
574
+ this._emitChange();
575
+ }
576
+
577
+ // ============ Image helpers ============
578
+ getSelectedImage() {
579
+ const sel = document.getSelection();
580
+ if (!sel.rangeCount) return null;
581
+ let node = sel.anchorNode;
582
+ if (node.nodeType === Node.TEXT_NODE) node = node.parentElement;
583
+ return closest(node, "img");
584
+ }
585
+
586
+ alignImage(align) {
587
+ const img = this.getSelectedImage();
588
+ if (!img) return;
589
+ this._recordBeforeMutation();
590
+ img.style.float = "";
591
+ img.style.margin = "";
592
+ img.style.display = "";
593
+ if (["left", "right"].includes(align)) {
594
+ img.style.float = align;
595
+ img.style.margin = align === "left" ? "0 12px 12px 0" : "0 0 12px 12px";
596
+ } else if (align === "center") {
597
+ img.style.display = "block";
598
+ img.style.margin = "0 auto";
599
+ } else {
600
+ img.style.display = "inline";
601
+ }
602
+ this._emitChange();
603
+ }
604
+
605
+ removeImage() {
606
+ const img = this.getSelectedImage();
607
+ if (!img) return;
608
+ this._recordBeforeMutation();
609
+ const figure = closest(img, "figure");
610
+ if (figure) figure.remove();
611
+ else img.remove();
612
+ this._emitChange();
613
+ }
614
+
615
+ replaceImage(src) {
616
+ const img = this.getSelectedImage();
617
+ if (!img || !src) return;
618
+ this._recordBeforeMutation();
619
+ img.setAttribute("src", src);
620
+ this._emitChange();
621
+ }
622
+
623
+ setImageAlt(alt) {
624
+ const img = this.getSelectedImage();
625
+ if (!img) return;
626
+ img.setAttribute("alt", alt || "");
627
+ this._emitChange();
628
+ }
629
+
630
+ _recordBeforeMutation() {
631
+ this.history.record(this.getHTML());
632
+ }
633
+
634
+ // ============ History ============
635
+ undo() {
636
+ const html = this.history.undo(this.getHTML());
637
+ if (html !== null) {
638
+ this._setHTMLInternal(html, false);
639
+ }
640
+ }
641
+
642
+ redo() {
643
+ const html = this.history.redo();
644
+ if (html !== null) {
645
+ this._setHTMLInternal(html, false);
646
+ }
647
+ }
648
+
649
+ // ============ Code view ============
650
+ toggleCodeView() {
651
+ if (this._codeView) {
652
+ this._exitCodeView();
653
+ } else {
654
+ this._enterCodeView();
655
+ }
656
+ }
657
+
658
+ _enterCodeView() {
659
+ this._codeView = true;
660
+ this.container.classList.add("code-view");
661
+ const html = this.getHTML();
662
+
663
+ this._savedSelection = this._saveSelection();
664
+
665
+ this._lastCodeValue = html;
666
+ const formatted = formatHTML(html);
667
+ this._codeEl = createElement("textarea", {
668
+ className: "s-texteditor-code",
669
+ spellcheck: "false",
670
+ oninput: () => {
671
+ const raw = this._codeEl.value;
672
+ this._lastCodeValue = raw;
673
+ const clean = sanitizeHTML(raw);
674
+ this.value = clean;
675
+ this.lastHtml = clean;
676
+ this.onChange(clean);
677
+ this._updateStatus();
678
+ },
679
+ });
680
+ this._codeEl.value = formatted;
681
+
682
+ this.bodyEl.innerHTML = "";
683
+ this.bodyEl.appendChild(this._codeEl);
684
+ this._codeEl.focus();
685
+
686
+ // Disable toolbar formatting buttons while in code view.
687
+ this.toolbarEl.classList.add("readonly");
688
+ this._updateStatus();
689
+ }
690
+
691
+ _exitCodeView() {
692
+ const raw = this._codeEl ? this._codeEl.value : this._lastCodeValue;
693
+ this._codeView = false;
694
+ this.container.classList.remove("code-view");
695
+
696
+ this._codeEl = null;
697
+ this._lastCodeValue = "";
698
+ this.bodyEl.innerHTML = "";
699
+ this.bodyEl.appendChild(this.editorEl);
700
+ this.toolbarEl.classList.remove("readonly");
701
+
702
+ this._setHTMLInternal(raw, true);
703
+ this.focus();
704
+ this._restoreSelection(this._savedSelection);
705
+ this._savedSelection = null;
706
+ }
707
+
708
+ _saveSelection() {
709
+ const sel = document.getSelection();
710
+ if (!sel || sel.rangeCount === 0 || !this.editorEl.contains(sel.anchorNode)) return null;
711
+ return sel.getRangeAt(0).cloneRange();
712
+ }
713
+
714
+ _restoreSelection(range) {
715
+ if (!range) return;
716
+ try {
717
+ const sel = document.getSelection();
718
+ sel.removeAllRanges();
719
+ sel.addRange(range);
720
+ } catch {
721
+ // Range may no longer be valid after HTML replacement.
722
+ }
723
+ }
724
+
725
+ isCodeView() {
726
+ return this._codeView;
727
+ }
728
+
729
+ // ============ HTML API ============
730
+ getHTML() {
731
+ let html = this.editorEl.innerHTML;
732
+ if (html === "<p><br></p>" || html === "<br>") html = "";
733
+ return sanitizeHTML(html);
734
+ }
735
+
736
+ setHTML(html) {
737
+ this._setHTMLInternal(html, true);
738
+ }
739
+
740
+ _setHTMLInternal(html, record) {
741
+ const clean = sanitizeHTML(html || "");
742
+ this.editorEl.innerHTML = clean || "<p><br></p>";
743
+ ensureParagraph(this.editorEl);
744
+ this.value = clean;
745
+ this.lastHtml = clean;
746
+ this._updatePlaceholder();
747
+ this._updateStatus();
748
+ if (record) this.history.record(clean);
749
+ this.onChange(clean);
750
+ }
751
+
752
+ getText() {
753
+ return htmlToText(this.getHTML());
754
+ }
755
+
756
+ clear() {
757
+ this.setHTML("");
758
+ }
759
+
760
+ focus() {
761
+ this.editorEl.focus();
762
+ }
763
+
764
+ setReadOnly(readOnly) {
765
+ this.readOnly = readOnly;
766
+ this.editorEl.contentEditable = readOnly ? "false" : "true";
767
+ this.container.classList.toggle("readonly", readOnly);
768
+ }
769
+
770
+ // ============ UI updates ============
771
+ _updateToolbarState(state) {
772
+ const buttons = this.toolbarEl.querySelectorAll(".s-texteditor-btn");
773
+ for (const btn of buttons) {
774
+ const activeKey = btn.dataset.active;
775
+ if (!activeKey) continue;
776
+ const active = state.activeFormats.has(activeKey);
777
+ btn.classList.toggle("active", active);
778
+ btn.setAttribute("aria-pressed", String(active));
779
+ }
780
+ }
781
+
782
+ _updatePlaceholder() {
783
+ const empty = !this.editorEl.textContent.trim();
784
+ this.container.classList.toggle("empty", empty);
785
+ }
786
+
787
+ _updateStatus(state = null) {
788
+ const html = this.getHTML();
789
+ const words = getWordCount(html);
790
+ const chars = getTextLength(html);
791
+ const selected = state?.selectedText?.length || 0;
792
+ const tag = state?.currentTag || "";
793
+ this.statusEl.innerHTML = `
794
+ <span>Words: ${words}</span>
795
+ <span>Chars: ${chars}</span>
796
+ ${selected > 0 ? `<span>Selected: ${selected}</span>` : ""}
797
+ ${tag ? `<span>Tag: ${tag.toUpperCase()}</span>` : ""}
798
+ `;
799
+ }
800
+ }