overtype 1.2.7 → 2.0.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.
@@ -0,0 +1,4763 @@
1
+ /**
2
+ * OverType v2.0.0
3
+ * A lightweight markdown editor library with perfect WYSIWYG alignment
4
+ * @license MIT
5
+ * @author Demo User
6
+ * https://github.com/demo/overtype
7
+ */
8
+ var __defProp = Object.defineProperty;
9
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
+ var __publicField = (obj, key, value) => {
11
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
12
+ return value;
13
+ };
14
+
15
+ // src/parser.js
16
+ var MarkdownParser = class {
17
+ /**
18
+ * Reset link index (call before parsing a new document)
19
+ */
20
+ static resetLinkIndex() {
21
+ this.linkIndex = 0;
22
+ }
23
+ /**
24
+ * Set global code highlighter function
25
+ * @param {Function|null} highlighter - Function that takes (code, language) and returns highlighted HTML
26
+ */
27
+ static setCodeHighlighter(highlighter) {
28
+ this.codeHighlighter = highlighter;
29
+ }
30
+ /**
31
+ * Escape HTML special characters
32
+ * @param {string} text - Raw text to escape
33
+ * @returns {string} Escaped HTML-safe text
34
+ */
35
+ static escapeHtml(text) {
36
+ const map = {
37
+ "&": "&",
38
+ "<": "&lt;",
39
+ ">": "&gt;",
40
+ '"': "&quot;",
41
+ "'": "&#39;"
42
+ };
43
+ return text.replace(/[&<>"']/g, (m) => map[m]);
44
+ }
45
+ /**
46
+ * Preserve leading spaces as non-breaking spaces
47
+ * @param {string} html - HTML string
48
+ * @param {string} originalLine - Original line with spaces
49
+ * @returns {string} HTML with preserved indentation
50
+ */
51
+ static preserveIndentation(html, originalLine) {
52
+ const leadingSpaces = originalLine.match(/^(\s*)/)[1];
53
+ const indentation = leadingSpaces.replace(/ /g, "&nbsp;");
54
+ return html.replace(/^\s*/, indentation);
55
+ }
56
+ /**
57
+ * Parse headers (h1-h3 only)
58
+ * @param {string} html - HTML line to parse
59
+ * @returns {string} Parsed HTML with header styling
60
+ */
61
+ static parseHeader(html) {
62
+ return html.replace(/^(#{1,3})\s(.+)$/, (match, hashes, content) => {
63
+ const level = hashes.length;
64
+ return `<h${level}><span class="syntax-marker">${hashes} </span>${content}</h${level}>`;
65
+ });
66
+ }
67
+ /**
68
+ * Parse horizontal rules
69
+ * @param {string} html - HTML line to parse
70
+ * @returns {string|null} Parsed horizontal rule or null
71
+ */
72
+ static parseHorizontalRule(html) {
73
+ if (html.match(/^(-{3,}|\*{3,}|_{3,})$/)) {
74
+ return `<div><span class="hr-marker">${html}</span></div>`;
75
+ }
76
+ return null;
77
+ }
78
+ /**
79
+ * Parse blockquotes
80
+ * @param {string} html - HTML line to parse
81
+ * @returns {string} Parsed blockquote
82
+ */
83
+ static parseBlockquote(html) {
84
+ return html.replace(/^&gt; (.+)$/, (match, content) => {
85
+ return `<span class="blockquote"><span class="syntax-marker">&gt;</span> ${content}</span>`;
86
+ });
87
+ }
88
+ /**
89
+ * Parse bullet lists
90
+ * @param {string} html - HTML line to parse
91
+ * @returns {string} Parsed bullet list item
92
+ */
93
+ static parseBulletList(html) {
94
+ return html.replace(/^((?:&nbsp;)*)([-*])\s(.+)$/, (match, indent, marker, content) => {
95
+ return `${indent}<li class="bullet-list"><span class="syntax-marker">${marker} </span>${content}</li>`;
96
+ });
97
+ }
98
+ /**
99
+ * Parse task lists (GitHub Flavored Markdown checkboxes)
100
+ * @param {string} html - HTML line to parse
101
+ * @param {boolean} isPreviewMode - Whether to render actual checkboxes (preview) or keep syntax visible (normal)
102
+ * @returns {string} Parsed task list item
103
+ */
104
+ static parseTaskList(html, isPreviewMode = false) {
105
+ return html.replace(/^((?:&nbsp;)*)-\s+\[([ xX])\]\s+(.+)$/, (match, indent, checked, content) => {
106
+ if (isPreviewMode) {
107
+ const isChecked = checked.toLowerCase() === "x";
108
+ return `${indent}<li class="task-list"><input type="checkbox" disabled ${isChecked ? "checked" : ""}> ${content}</li>`;
109
+ } else {
110
+ return `${indent}<li class="task-list"><span class="syntax-marker">- [${checked}] </span>${content}</li>`;
111
+ }
112
+ });
113
+ }
114
+ /**
115
+ * Parse numbered lists
116
+ * @param {string} html - HTML line to parse
117
+ * @returns {string} Parsed numbered list item
118
+ */
119
+ static parseNumberedList(html) {
120
+ return html.replace(/^((?:&nbsp;)*)(\d+\.)\s(.+)$/, (match, indent, marker, content) => {
121
+ return `${indent}<li class="ordered-list"><span class="syntax-marker">${marker} </span>${content}</li>`;
122
+ });
123
+ }
124
+ /**
125
+ * Parse code blocks (markers only)
126
+ * @param {string} html - HTML line to parse
127
+ * @returns {string|null} Parsed code fence or null
128
+ */
129
+ static parseCodeBlock(html) {
130
+ const codeFenceRegex = /^`{3}[^`]*$/;
131
+ if (codeFenceRegex.test(html)) {
132
+ return `<div><span class="code-fence">${html}</span></div>`;
133
+ }
134
+ return null;
135
+ }
136
+ /**
137
+ * Parse bold text
138
+ * @param {string} html - HTML with potential bold markdown
139
+ * @returns {string} HTML with bold styling
140
+ */
141
+ static parseBold(html) {
142
+ html = html.replace(/\*\*(.+?)\*\*/g, '<strong><span class="syntax-marker">**</span>$1<span class="syntax-marker">**</span></strong>');
143
+ html = html.replace(/__(.+?)__/g, '<strong><span class="syntax-marker">__</span>$1<span class="syntax-marker">__</span></strong>');
144
+ return html;
145
+ }
146
+ /**
147
+ * Parse italic text
148
+ * Note: Uses lookbehind assertions - requires modern browsers
149
+ * @param {string} html - HTML with potential italic markdown
150
+ * @returns {string} HTML with italic styling
151
+ */
152
+ static parseItalic(html) {
153
+ html = html.replace(new RegExp("(?<!\\*)\\*(?!\\*)(.+?)(?<!\\*)\\*(?!\\*)", "g"), '<em><span class="syntax-marker">*</span>$1<span class="syntax-marker">*</span></em>');
154
+ html = html.replace(new RegExp("(?<=^|\\s)_(?!_)(.+?)(?<!_)_(?!_)(?=\\s|$)", "g"), '<em><span class="syntax-marker">_</span>$1<span class="syntax-marker">_</span></em>');
155
+ return html;
156
+ }
157
+ /**
158
+ * Parse strikethrough text
159
+ * Supports both single (~) and double (~~) tildes, but rejects 3+ tildes
160
+ * @param {string} html - HTML with potential strikethrough markdown
161
+ * @returns {string} HTML with strikethrough styling
162
+ */
163
+ static parseStrikethrough(html) {
164
+ html = html.replace(new RegExp("(?<!~)~~(?!~)(.+?)(?<!~)~~(?!~)", "g"), '<del><span class="syntax-marker">~~</span>$1<span class="syntax-marker">~~</span></del>');
165
+ html = html.replace(new RegExp("(?<!~)~(?!~)(.+?)(?<!~)~(?!~)", "g"), '<del><span class="syntax-marker">~</span>$1<span class="syntax-marker">~</span></del>');
166
+ return html;
167
+ }
168
+ /**
169
+ * Parse inline code
170
+ * @param {string} html - HTML with potential code markdown
171
+ * @returns {string} HTML with code styling
172
+ */
173
+ static parseInlineCode(html) {
174
+ return html.replace(new RegExp("(?<!`)(`+)(?!`)((?:(?!\\1).)+?)(\\1)(?!`)", "g"), '<code><span class="syntax-marker">$1</span>$2<span class="syntax-marker">$3</span></code>');
175
+ }
176
+ /**
177
+ * Sanitize URL to prevent XSS attacks
178
+ * @param {string} url - URL to sanitize
179
+ * @returns {string} Safe URL or '#' if dangerous
180
+ */
181
+ static sanitizeUrl(url) {
182
+ const trimmed = url.trim();
183
+ const lower = trimmed.toLowerCase();
184
+ const safeProtocols = [
185
+ "http://",
186
+ "https://",
187
+ "mailto:",
188
+ "ftp://",
189
+ "ftps://"
190
+ ];
191
+ const hasSafeProtocol = safeProtocols.some((protocol) => lower.startsWith(protocol));
192
+ const isRelative = trimmed.startsWith("/") || trimmed.startsWith("#") || trimmed.startsWith("?") || trimmed.startsWith(".") || !trimmed.includes(":") && !trimmed.includes("//");
193
+ if (hasSafeProtocol || isRelative) {
194
+ return url;
195
+ }
196
+ return "#";
197
+ }
198
+ /**
199
+ * Parse links
200
+ * @param {string} html - HTML with potential link markdown
201
+ * @returns {string} HTML with link styling
202
+ */
203
+ static parseLinks(html) {
204
+ return html.replace(/\[(.+?)\]\((.+?)\)/g, (match, text, url) => {
205
+ const anchorName = `--link-${this.linkIndex++}`;
206
+ const safeUrl = this.sanitizeUrl(url);
207
+ return `<a href="${safeUrl}" style="anchor-name: ${anchorName}"><span class="syntax-marker">[</span>${text}<span class="syntax-marker url-part">](${url})</span></a>`;
208
+ });
209
+ }
210
+ /**
211
+ * Identify and protect sanctuaries (code and links) before parsing
212
+ * @param {string} text - Text with potential markdown
213
+ * @returns {Object} Object with protected text and sanctuary map
214
+ */
215
+ static identifyAndProtectSanctuaries(text) {
216
+ const sanctuaries = /* @__PURE__ */ new Map();
217
+ let sanctuaryCounter = 0;
218
+ let protectedText = text;
219
+ const protectedRegions = [];
220
+ const linkRegex = /\[([^\]]+)\]\(([^)]+)\)/g;
221
+ let linkMatch;
222
+ while ((linkMatch = linkRegex.exec(text)) !== null) {
223
+ const bracketPos = linkMatch.index + linkMatch[0].indexOf("](");
224
+ const urlStart = bracketPos + 2;
225
+ const urlEnd = urlStart + linkMatch[2].length;
226
+ protectedRegions.push({ start: urlStart, end: urlEnd });
227
+ }
228
+ const codeRegex = new RegExp("(?<!`)(`+)(?!`)((?:(?!\\1).)+?)(\\1)(?!`)", "g");
229
+ let codeMatch;
230
+ const codeMatches = [];
231
+ while ((codeMatch = codeRegex.exec(text)) !== null) {
232
+ const codeStart = codeMatch.index;
233
+ const codeEnd = codeMatch.index + codeMatch[0].length;
234
+ const inProtectedRegion = protectedRegions.some(
235
+ (region) => codeStart >= region.start && codeEnd <= region.end
236
+ );
237
+ if (!inProtectedRegion) {
238
+ codeMatches.push({
239
+ match: codeMatch[0],
240
+ index: codeMatch.index,
241
+ openTicks: codeMatch[1],
242
+ content: codeMatch[2],
243
+ closeTicks: codeMatch[3]
244
+ });
245
+ }
246
+ }
247
+ codeMatches.sort((a, b) => b.index - a.index);
248
+ codeMatches.forEach((codeInfo) => {
249
+ const placeholder = `\uE000${sanctuaryCounter++}\uE001`;
250
+ sanctuaries.set(placeholder, {
251
+ type: "code",
252
+ original: codeInfo.match,
253
+ openTicks: codeInfo.openTicks,
254
+ content: codeInfo.content,
255
+ closeTicks: codeInfo.closeTicks
256
+ });
257
+ protectedText = protectedText.substring(0, codeInfo.index) + placeholder + protectedText.substring(codeInfo.index + codeInfo.match.length);
258
+ });
259
+ protectedText = protectedText.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, linkText, url) => {
260
+ const placeholder = `\uE000${sanctuaryCounter++}\uE001`;
261
+ sanctuaries.set(placeholder, {
262
+ type: "link",
263
+ original: match,
264
+ linkText,
265
+ url
266
+ });
267
+ return placeholder;
268
+ });
269
+ return { protectedText, sanctuaries };
270
+ }
271
+ /**
272
+ * Restore and transform sanctuaries back to HTML
273
+ * @param {string} html - HTML with sanctuary placeholders
274
+ * @param {Map} sanctuaries - Map of sanctuaries to restore
275
+ * @returns {string} HTML with sanctuaries restored and transformed
276
+ */
277
+ static restoreAndTransformSanctuaries(html, sanctuaries) {
278
+ const placeholders = Array.from(sanctuaries.keys()).sort((a, b) => {
279
+ const indexA = html.indexOf(a);
280
+ const indexB = html.indexOf(b);
281
+ return indexA - indexB;
282
+ });
283
+ placeholders.forEach((placeholder) => {
284
+ const sanctuary = sanctuaries.get(placeholder);
285
+ let replacement;
286
+ if (sanctuary.type === "code") {
287
+ replacement = `<code><span class="syntax-marker">${sanctuary.openTicks}</span>${sanctuary.content}<span class="syntax-marker">${sanctuary.closeTicks}</span></code>`;
288
+ } else if (sanctuary.type === "link") {
289
+ let processedLinkText = sanctuary.linkText;
290
+ sanctuaries.forEach((innerSanctuary, innerPlaceholder) => {
291
+ if (processedLinkText.includes(innerPlaceholder)) {
292
+ if (innerSanctuary.type === "code") {
293
+ const codeHtml = `<code><span class="syntax-marker">${innerSanctuary.openTicks}</span>${innerSanctuary.content}<span class="syntax-marker">${innerSanctuary.closeTicks}</span></code>`;
294
+ processedLinkText = processedLinkText.replace(innerPlaceholder, codeHtml);
295
+ }
296
+ }
297
+ });
298
+ processedLinkText = this.parseStrikethrough(processedLinkText);
299
+ processedLinkText = this.parseBold(processedLinkText);
300
+ processedLinkText = this.parseItalic(processedLinkText);
301
+ const anchorName = `--link-${this.linkIndex++}`;
302
+ const safeUrl = this.sanitizeUrl(sanctuary.url);
303
+ replacement = `<a href="${safeUrl}" style="anchor-name: ${anchorName}"><span class="syntax-marker">[</span>${processedLinkText}<span class="syntax-marker url-part">](${sanctuary.url})</span></a>`;
304
+ }
305
+ html = html.replace(placeholder, replacement);
306
+ });
307
+ return html;
308
+ }
309
+ /**
310
+ * Parse all inline elements in correct order
311
+ * @param {string} text - Text with potential inline markdown
312
+ * @returns {string} HTML with all inline styling
313
+ */
314
+ static parseInlineElements(text) {
315
+ const { protectedText, sanctuaries } = this.identifyAndProtectSanctuaries(text);
316
+ let html = protectedText;
317
+ html = this.parseStrikethrough(html);
318
+ html = this.parseBold(html);
319
+ html = this.parseItalic(html);
320
+ html = this.restoreAndTransformSanctuaries(html, sanctuaries);
321
+ return html;
322
+ }
323
+ /**
324
+ * Parse a single line of markdown
325
+ * @param {string} line - Raw markdown line
326
+ * @returns {string} Parsed HTML line
327
+ */
328
+ static parseLine(line, isPreviewMode = false) {
329
+ let html = this.escapeHtml(line);
330
+ html = this.preserveIndentation(html, line);
331
+ const horizontalRule = this.parseHorizontalRule(html);
332
+ if (horizontalRule)
333
+ return horizontalRule;
334
+ const codeBlock = this.parseCodeBlock(html);
335
+ if (codeBlock)
336
+ return codeBlock;
337
+ html = this.parseHeader(html);
338
+ html = this.parseBlockquote(html);
339
+ html = this.parseTaskList(html, isPreviewMode);
340
+ html = this.parseBulletList(html);
341
+ html = this.parseNumberedList(html);
342
+ html = this.parseInlineElements(html);
343
+ if (html.trim() === "") {
344
+ return "<div>&nbsp;</div>";
345
+ }
346
+ return `<div>${html}</div>`;
347
+ }
348
+ /**
349
+ * Parse full markdown text
350
+ * @param {string} text - Full markdown text
351
+ * @param {number} activeLine - Currently active line index (optional)
352
+ * @param {boolean} showActiveLineRaw - Show raw markdown on active line
353
+ * @param {Function} instanceHighlighter - Instance-specific code highlighter (optional, overrides global if provided)
354
+ * @returns {string} Parsed HTML
355
+ */
356
+ static parse(text, activeLine = -1, showActiveLineRaw = false, instanceHighlighter, isPreviewMode = false) {
357
+ this.resetLinkIndex();
358
+ const lines = text.split("\n");
359
+ let inCodeBlock = false;
360
+ const parsedLines = lines.map((line, index) => {
361
+ if (showActiveLineRaw && index === activeLine) {
362
+ const content = this.escapeHtml(line) || "&nbsp;";
363
+ return `<div class="raw-line">${content}</div>`;
364
+ }
365
+ const codeFenceRegex = /^```[^`]*$/;
366
+ if (codeFenceRegex.test(line)) {
367
+ inCodeBlock = !inCodeBlock;
368
+ return this.parseLine(line, isPreviewMode);
369
+ }
370
+ if (inCodeBlock) {
371
+ const escaped = this.escapeHtml(line);
372
+ const indented = this.preserveIndentation(escaped, line);
373
+ return `<div>${indented || "&nbsp;"}</div>`;
374
+ }
375
+ return this.parseLine(line, isPreviewMode);
376
+ });
377
+ const html = parsedLines.join("");
378
+ return this.postProcessHTML(html, instanceHighlighter);
379
+ }
380
+ /**
381
+ * Post-process HTML to consolidate lists and code blocks
382
+ * @param {string} html - HTML to post-process
383
+ * @param {Function} instanceHighlighter - Instance-specific code highlighter (optional, overrides global if provided)
384
+ * @returns {string} Post-processed HTML with consolidated lists and code blocks
385
+ */
386
+ static postProcessHTML(html, instanceHighlighter) {
387
+ if (typeof document === "undefined" || !document) {
388
+ return this.postProcessHTMLManual(html, instanceHighlighter);
389
+ }
390
+ const container = document.createElement("div");
391
+ container.innerHTML = html;
392
+ let currentList = null;
393
+ let listType = null;
394
+ let currentCodeBlock = null;
395
+ let inCodeBlock = false;
396
+ const children = Array.from(container.children);
397
+ for (let i = 0; i < children.length; i++) {
398
+ const child = children[i];
399
+ if (!child.parentNode)
400
+ continue;
401
+ const codeFence = child.querySelector(".code-fence");
402
+ if (codeFence) {
403
+ const fenceText = codeFence.textContent;
404
+ if (fenceText.startsWith("```")) {
405
+ if (!inCodeBlock) {
406
+ inCodeBlock = true;
407
+ currentCodeBlock = document.createElement("pre");
408
+ const codeElement = document.createElement("code");
409
+ currentCodeBlock.appendChild(codeElement);
410
+ currentCodeBlock.className = "code-block";
411
+ const lang = fenceText.slice(3).trim();
412
+ if (lang) {
413
+ codeElement.className = `language-${lang}`;
414
+ }
415
+ container.insertBefore(currentCodeBlock, child.nextSibling);
416
+ currentCodeBlock._codeElement = codeElement;
417
+ currentCodeBlock._language = lang;
418
+ currentCodeBlock._codeContent = "";
419
+ continue;
420
+ } else {
421
+ const highlighter = instanceHighlighter || this.codeHighlighter;
422
+ if (currentCodeBlock && highlighter && currentCodeBlock._codeContent) {
423
+ try {
424
+ const result = highlighter(
425
+ currentCodeBlock._codeContent,
426
+ currentCodeBlock._language || ""
427
+ );
428
+ if (result && typeof result.then === "function") {
429
+ console.warn("Async highlighters are not supported in parse() because it returns an HTML string. The caller creates new DOM elements from that string, breaking references to the elements we would update. Use synchronous highlighters only.");
430
+ } else {
431
+ if (result && typeof result === "string" && result.trim()) {
432
+ currentCodeBlock._codeElement.innerHTML = result;
433
+ }
434
+ }
435
+ } catch (error) {
436
+ console.warn("Code highlighting failed:", error);
437
+ }
438
+ }
439
+ inCodeBlock = false;
440
+ currentCodeBlock = null;
441
+ continue;
442
+ }
443
+ }
444
+ }
445
+ if (inCodeBlock && currentCodeBlock && child.tagName === "DIV" && !child.querySelector(".code-fence")) {
446
+ const codeElement = currentCodeBlock._codeElement || currentCodeBlock.querySelector("code");
447
+ if (currentCodeBlock._codeContent.length > 0) {
448
+ currentCodeBlock._codeContent += "\n";
449
+ }
450
+ const lineText = child.textContent.replace(/\u00A0/g, " ");
451
+ currentCodeBlock._codeContent += lineText;
452
+ if (codeElement.textContent.length > 0) {
453
+ codeElement.textContent += "\n";
454
+ }
455
+ codeElement.textContent += lineText;
456
+ child.remove();
457
+ continue;
458
+ }
459
+ let listItem = null;
460
+ if (child.tagName === "DIV") {
461
+ listItem = child.querySelector("li");
462
+ }
463
+ if (listItem) {
464
+ const isBullet = listItem.classList.contains("bullet-list");
465
+ const isOrdered = listItem.classList.contains("ordered-list");
466
+ if (!isBullet && !isOrdered) {
467
+ currentList = null;
468
+ listType = null;
469
+ continue;
470
+ }
471
+ const newType = isBullet ? "ul" : "ol";
472
+ if (!currentList || listType !== newType) {
473
+ currentList = document.createElement(newType);
474
+ container.insertBefore(currentList, child);
475
+ listType = newType;
476
+ }
477
+ const indentationNodes = [];
478
+ for (const node of child.childNodes) {
479
+ if (node.nodeType === 3 && node.textContent.match(/^\u00A0+$/)) {
480
+ indentationNodes.push(node.cloneNode(true));
481
+ } else if (node === listItem) {
482
+ break;
483
+ }
484
+ }
485
+ indentationNodes.forEach((node) => {
486
+ listItem.insertBefore(node, listItem.firstChild);
487
+ });
488
+ currentList.appendChild(listItem);
489
+ child.remove();
490
+ } else {
491
+ currentList = null;
492
+ listType = null;
493
+ }
494
+ }
495
+ return container.innerHTML;
496
+ }
497
+ /**
498
+ * Manual post-processing for Node.js environments (without DOM)
499
+ * @param {string} html - HTML to post-process
500
+ * @param {Function} instanceHighlighter - Instance-specific code highlighter (optional, overrides global if provided)
501
+ * @returns {string} Post-processed HTML
502
+ */
503
+ static postProcessHTMLManual(html, instanceHighlighter) {
504
+ let processed = html;
505
+ processed = processed.replace(/((?:<div>(?:&nbsp;)*<li class="bullet-list">.*?<\/li><\/div>\s*)+)/gs, (match) => {
506
+ const divs = match.match(/<div>(?:&nbsp;)*<li class="bullet-list">.*?<\/li><\/div>/gs) || [];
507
+ if (divs.length > 0) {
508
+ const items = divs.map((div) => {
509
+ const indentMatch = div.match(/<div>((?:&nbsp;)*)<li/);
510
+ const listItemMatch = div.match(/<li class="bullet-list">.*?<\/li>/);
511
+ if (indentMatch && listItemMatch) {
512
+ const indentation = indentMatch[1];
513
+ const listItem = listItemMatch[0];
514
+ return listItem.replace(/<li class="bullet-list">/, `<li class="bullet-list">${indentation}`);
515
+ }
516
+ return listItemMatch ? listItemMatch[0] : "";
517
+ }).filter(Boolean);
518
+ return "<ul>" + items.join("") + "</ul>";
519
+ }
520
+ return match;
521
+ });
522
+ processed = processed.replace(/((?:<div>(?:&nbsp;)*<li class="ordered-list">.*?<\/li><\/div>\s*)+)/gs, (match) => {
523
+ const divs = match.match(/<div>(?:&nbsp;)*<li class="ordered-list">.*?<\/li><\/div>/gs) || [];
524
+ if (divs.length > 0) {
525
+ const items = divs.map((div) => {
526
+ const indentMatch = div.match(/<div>((?:&nbsp;)*)<li/);
527
+ const listItemMatch = div.match(/<li class="ordered-list">.*?<\/li>/);
528
+ if (indentMatch && listItemMatch) {
529
+ const indentation = indentMatch[1];
530
+ const listItem = listItemMatch[0];
531
+ return listItem.replace(/<li class="ordered-list">/, `<li class="ordered-list">${indentation}`);
532
+ }
533
+ return listItemMatch ? listItemMatch[0] : "";
534
+ }).filter(Boolean);
535
+ return "<ol>" + items.join("") + "</ol>";
536
+ }
537
+ return match;
538
+ });
539
+ const codeBlockRegex = /<div><span class="code-fence">(```[^<]*)<\/span><\/div>(.*?)<div><span class="code-fence">(```)<\/span><\/div>/gs;
540
+ processed = processed.replace(codeBlockRegex, (match, openFence, content, closeFence) => {
541
+ const lines = content.match(/<div>(.*?)<\/div>/gs) || [];
542
+ const codeContent = lines.map((line) => {
543
+ const text = line.replace(/<div>(.*?)<\/div>/s, "$1").replace(/&nbsp;/g, " ");
544
+ return text;
545
+ }).join("\n");
546
+ const lang = openFence.slice(3).trim();
547
+ const langClass = lang ? ` class="language-${lang}"` : "";
548
+ let highlightedContent = codeContent;
549
+ const highlighter = instanceHighlighter || this.codeHighlighter;
550
+ if (highlighter) {
551
+ try {
552
+ const decodedCode = codeContent.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
553
+ const result2 = highlighter(decodedCode, lang);
554
+ if (result2 && typeof result2.then === "function") {
555
+ console.warn("Async highlighters are not supported in Node.js (non-DOM) context. Use synchronous highlighters for server-side rendering.");
556
+ } else {
557
+ if (result2 && typeof result2 === "string" && result2.trim()) {
558
+ highlightedContent = result2;
559
+ }
560
+ }
561
+ } catch (error) {
562
+ console.warn("Code highlighting failed:", error);
563
+ }
564
+ }
565
+ let result = `<div><span class="code-fence">${openFence}</span></div>`;
566
+ result += `<pre class="code-block"><code${langClass}>${highlightedContent}</code></pre>`;
567
+ result += `<div><span class="code-fence">${closeFence}</span></div>`;
568
+ return result;
569
+ });
570
+ return processed;
571
+ }
572
+ /**
573
+ * Get list context at cursor position
574
+ * @param {string} text - Full text content
575
+ * @param {number} cursorPosition - Current cursor position
576
+ * @returns {Object} List context information
577
+ */
578
+ static getListContext(text, cursorPosition) {
579
+ const lines = text.split("\n");
580
+ let currentPos = 0;
581
+ let lineIndex = 0;
582
+ let lineStart = 0;
583
+ for (let i = 0; i < lines.length; i++) {
584
+ const lineLength = lines[i].length;
585
+ if (currentPos + lineLength >= cursorPosition) {
586
+ lineIndex = i;
587
+ lineStart = currentPos;
588
+ break;
589
+ }
590
+ currentPos += lineLength + 1;
591
+ }
592
+ const currentLine = lines[lineIndex];
593
+ const lineEnd = lineStart + currentLine.length;
594
+ const checkboxMatch = currentLine.match(this.LIST_PATTERNS.checkbox);
595
+ if (checkboxMatch) {
596
+ return {
597
+ inList: true,
598
+ listType: "checkbox",
599
+ indent: checkboxMatch[1],
600
+ marker: "-",
601
+ checked: checkboxMatch[2] === "x",
602
+ content: checkboxMatch[3],
603
+ lineStart,
604
+ lineEnd,
605
+ markerEndPos: lineStart + checkboxMatch[1].length + checkboxMatch[2].length + 5
606
+ // indent + "- [ ] "
607
+ };
608
+ }
609
+ const bulletMatch = currentLine.match(this.LIST_PATTERNS.bullet);
610
+ if (bulletMatch) {
611
+ return {
612
+ inList: true,
613
+ listType: "bullet",
614
+ indent: bulletMatch[1],
615
+ marker: bulletMatch[2],
616
+ content: bulletMatch[3],
617
+ lineStart,
618
+ lineEnd,
619
+ markerEndPos: lineStart + bulletMatch[1].length + bulletMatch[2].length + 1
620
+ // indent + marker + space
621
+ };
622
+ }
623
+ const numberedMatch = currentLine.match(this.LIST_PATTERNS.numbered);
624
+ if (numberedMatch) {
625
+ return {
626
+ inList: true,
627
+ listType: "numbered",
628
+ indent: numberedMatch[1],
629
+ marker: parseInt(numberedMatch[2]),
630
+ content: numberedMatch[3],
631
+ lineStart,
632
+ lineEnd,
633
+ markerEndPos: lineStart + numberedMatch[1].length + numberedMatch[2].length + 2
634
+ // indent + number + ". "
635
+ };
636
+ }
637
+ return {
638
+ inList: false,
639
+ listType: null,
640
+ indent: "",
641
+ marker: null,
642
+ content: currentLine,
643
+ lineStart,
644
+ lineEnd,
645
+ markerEndPos: lineStart
646
+ };
647
+ }
648
+ /**
649
+ * Create a new list item based on context
650
+ * @param {Object} context - List context from getListContext
651
+ * @returns {string} New list item text
652
+ */
653
+ static createNewListItem(context) {
654
+ switch (context.listType) {
655
+ case "bullet":
656
+ return `${context.indent}${context.marker} `;
657
+ case "numbered":
658
+ return `${context.indent}${context.marker + 1}. `;
659
+ case "checkbox":
660
+ return `${context.indent}- [ ] `;
661
+ default:
662
+ return "";
663
+ }
664
+ }
665
+ /**
666
+ * Renumber all numbered lists in text
667
+ * @param {string} text - Text containing numbered lists
668
+ * @returns {string} Text with renumbered lists
669
+ */
670
+ static renumberLists(text) {
671
+ const lines = text.split("\n");
672
+ const numbersByIndent = /* @__PURE__ */ new Map();
673
+ let inList = false;
674
+ const result = lines.map((line) => {
675
+ const match = line.match(this.LIST_PATTERNS.numbered);
676
+ if (match) {
677
+ const indent = match[1];
678
+ const indentLevel = indent.length;
679
+ const content = match[3];
680
+ if (!inList) {
681
+ numbersByIndent.clear();
682
+ }
683
+ const currentNumber = (numbersByIndent.get(indentLevel) || 0) + 1;
684
+ numbersByIndent.set(indentLevel, currentNumber);
685
+ for (const [level] of numbersByIndent) {
686
+ if (level > indentLevel) {
687
+ numbersByIndent.delete(level);
688
+ }
689
+ }
690
+ inList = true;
691
+ return `${indent}${currentNumber}. ${content}`;
692
+ } else {
693
+ if (line.trim() === "" || !line.match(/^\s/)) {
694
+ inList = false;
695
+ numbersByIndent.clear();
696
+ }
697
+ return line;
698
+ }
699
+ });
700
+ return result.join("\n");
701
+ }
702
+ };
703
+ // Track link index for anchor naming
704
+ __publicField(MarkdownParser, "linkIndex", 0);
705
+ // Global code highlighter function
706
+ __publicField(MarkdownParser, "codeHighlighter", null);
707
+ /**
708
+ * List pattern definitions
709
+ */
710
+ __publicField(MarkdownParser, "LIST_PATTERNS", {
711
+ bullet: /^(\s*)([-*+])\s+(.*)$/,
712
+ numbered: /^(\s*)(\d+)\.\s+(.*)$/,
713
+ checkbox: /^(\s*)-\s+\[([ x])\]\s+(.*)$/
714
+ });
715
+
716
+ // node_modules/markdown-actions/dist/markdown-actions.esm.js
717
+ var __defProp2 = Object.defineProperty;
718
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
719
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
720
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
721
+ var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
722
+ var __spreadValues = (a, b) => {
723
+ for (var prop in b || (b = {}))
724
+ if (__hasOwnProp.call(b, prop))
725
+ __defNormalProp2(a, prop, b[prop]);
726
+ if (__getOwnPropSymbols)
727
+ for (var prop of __getOwnPropSymbols(b)) {
728
+ if (__propIsEnum.call(b, prop))
729
+ __defNormalProp2(a, prop, b[prop]);
730
+ }
731
+ return a;
732
+ };
733
+ var FORMATS = {
734
+ bold: {
735
+ prefix: "**",
736
+ suffix: "**",
737
+ trimFirst: true
738
+ },
739
+ italic: {
740
+ prefix: "_",
741
+ suffix: "_",
742
+ trimFirst: true
743
+ },
744
+ code: {
745
+ prefix: "`",
746
+ suffix: "`",
747
+ blockPrefix: "```",
748
+ blockSuffix: "```"
749
+ },
750
+ link: {
751
+ prefix: "[",
752
+ suffix: "](url)",
753
+ replaceNext: "url",
754
+ scanFor: "https?://"
755
+ },
756
+ bulletList: {
757
+ prefix: "- ",
758
+ multiline: true,
759
+ unorderedList: true
760
+ },
761
+ numberedList: {
762
+ prefix: "1. ",
763
+ multiline: true,
764
+ orderedList: true
765
+ },
766
+ quote: {
767
+ prefix: "> ",
768
+ multiline: true,
769
+ surroundWithNewlines: true
770
+ },
771
+ taskList: {
772
+ prefix: "- [ ] ",
773
+ multiline: true,
774
+ surroundWithNewlines: true
775
+ },
776
+ header1: { prefix: "# " },
777
+ header2: { prefix: "## " },
778
+ header3: { prefix: "### " },
779
+ header4: { prefix: "#### " },
780
+ header5: { prefix: "##### " },
781
+ header6: { prefix: "###### " }
782
+ };
783
+ function getDefaultStyle() {
784
+ return {
785
+ prefix: "",
786
+ suffix: "",
787
+ blockPrefix: "",
788
+ blockSuffix: "",
789
+ multiline: false,
790
+ replaceNext: "",
791
+ prefixSpace: false,
792
+ scanFor: "",
793
+ surroundWithNewlines: false,
794
+ orderedList: false,
795
+ unorderedList: false,
796
+ trimFirst: false
797
+ };
798
+ }
799
+ function mergeWithDefaults(format) {
800
+ return __spreadValues(__spreadValues({}, getDefaultStyle()), format);
801
+ }
802
+ var debugMode = false;
803
+ function getDebugMode() {
804
+ return debugMode;
805
+ }
806
+ function debugLog(funcName, message, data) {
807
+ if (!debugMode)
808
+ return;
809
+ console.group(`\u{1F50D} ${funcName}`);
810
+ console.log(message);
811
+ if (data) {
812
+ console.log("Data:", data);
813
+ }
814
+ console.groupEnd();
815
+ }
816
+ function debugSelection(textarea, label) {
817
+ if (!debugMode)
818
+ return;
819
+ const selected = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
820
+ console.group(`\u{1F4CD} Selection: ${label}`);
821
+ console.log("Position:", `${textarea.selectionStart}-${textarea.selectionEnd}`);
822
+ console.log("Selected text:", JSON.stringify(selected));
823
+ console.log("Length:", selected.length);
824
+ const before = textarea.value.slice(Math.max(0, textarea.selectionStart - 10), textarea.selectionStart);
825
+ const after = textarea.value.slice(textarea.selectionEnd, Math.min(textarea.value.length, textarea.selectionEnd + 10));
826
+ console.log("Context:", JSON.stringify(before) + "[SELECTION]" + JSON.stringify(after));
827
+ console.groupEnd();
828
+ }
829
+ function debugResult(result) {
830
+ if (!debugMode)
831
+ return;
832
+ console.group("\u{1F4DD} Result");
833
+ console.log("Text to insert:", JSON.stringify(result.text));
834
+ console.log("New selection:", `${result.selectionStart}-${result.selectionEnd}`);
835
+ console.groupEnd();
836
+ }
837
+ var canInsertText = null;
838
+ function insertText(textarea, { text, selectionStart, selectionEnd }) {
839
+ const debugMode2 = getDebugMode();
840
+ if (debugMode2) {
841
+ console.group("\u{1F527} insertText");
842
+ console.log("Current selection:", `${textarea.selectionStart}-${textarea.selectionEnd}`);
843
+ console.log("Text to insert:", JSON.stringify(text));
844
+ console.log("New selection to set:", selectionStart, "-", selectionEnd);
845
+ }
846
+ textarea.focus();
847
+ const originalSelectionStart = textarea.selectionStart;
848
+ const originalSelectionEnd = textarea.selectionEnd;
849
+ const before = textarea.value.slice(0, originalSelectionStart);
850
+ const after = textarea.value.slice(originalSelectionEnd);
851
+ if (debugMode2) {
852
+ console.log("Before text (last 20):", JSON.stringify(before.slice(-20)));
853
+ console.log("After text (first 20):", JSON.stringify(after.slice(0, 20)));
854
+ console.log("Selected text being replaced:", JSON.stringify(textarea.value.slice(originalSelectionStart, originalSelectionEnd)));
855
+ }
856
+ const originalValue = textarea.value;
857
+ const hasSelection = originalSelectionStart !== originalSelectionEnd;
858
+ if (canInsertText === null || canInsertText === true) {
859
+ textarea.contentEditable = "true";
860
+ try {
861
+ canInsertText = document.execCommand("insertText", false, text);
862
+ if (debugMode2)
863
+ console.log("execCommand returned:", canInsertText, "for text with", text.split("\n").length, "lines");
864
+ } catch (error) {
865
+ canInsertText = false;
866
+ if (debugMode2)
867
+ console.log("execCommand threw error:", error);
868
+ }
869
+ textarea.contentEditable = "false";
870
+ }
871
+ if (debugMode2) {
872
+ console.log("canInsertText before:", canInsertText);
873
+ console.log("execCommand result:", canInsertText);
874
+ }
875
+ if (canInsertText) {
876
+ const expectedValue = before + text + after;
877
+ const actualValue = textarea.value;
878
+ if (debugMode2) {
879
+ console.log("Expected length:", expectedValue.length);
880
+ console.log("Actual length:", actualValue.length);
881
+ }
882
+ if (actualValue !== expectedValue) {
883
+ if (debugMode2) {
884
+ console.log("execCommand changed the value but not as expected");
885
+ console.log("Expected:", JSON.stringify(expectedValue.slice(0, 100)));
886
+ console.log("Actual:", JSON.stringify(actualValue.slice(0, 100)));
887
+ }
888
+ }
889
+ }
890
+ if (!canInsertText) {
891
+ if (debugMode2)
892
+ console.log("Using manual insertion");
893
+ if (textarea.value === originalValue) {
894
+ if (debugMode2)
895
+ console.log("Value unchanged, doing manual replacement");
896
+ try {
897
+ document.execCommand("ms-beginUndoUnit");
898
+ } catch (e) {
899
+ }
900
+ textarea.value = before + text + after;
901
+ try {
902
+ document.execCommand("ms-endUndoUnit");
903
+ } catch (e) {
904
+ }
905
+ textarea.dispatchEvent(new CustomEvent("input", { bubbles: true, cancelable: true }));
906
+ } else {
907
+ if (debugMode2)
908
+ console.log("Value was changed by execCommand, skipping manual insertion");
909
+ }
910
+ }
911
+ if (debugMode2)
912
+ console.log("Setting selection range:", selectionStart, selectionEnd);
913
+ if (selectionStart != null && selectionEnd != null) {
914
+ textarea.setSelectionRange(selectionStart, selectionEnd);
915
+ } else {
916
+ textarea.setSelectionRange(originalSelectionStart, textarea.selectionEnd);
917
+ }
918
+ if (debugMode2) {
919
+ console.log("Final value length:", textarea.value.length);
920
+ console.groupEnd();
921
+ }
922
+ }
923
+ function isMultipleLines(string) {
924
+ return string.trim().split("\n").length > 1;
925
+ }
926
+ function wordSelectionStart(text, i) {
927
+ let index = i;
928
+ while (text[index] && text[index - 1] != null && !text[index - 1].match(/\s/)) {
929
+ index--;
930
+ }
931
+ return index;
932
+ }
933
+ function wordSelectionEnd(text, i, multiline) {
934
+ let index = i;
935
+ const breakpoint = multiline ? /\n/ : /\s/;
936
+ while (text[index] && !text[index].match(breakpoint)) {
937
+ index++;
938
+ }
939
+ return index;
940
+ }
941
+ function expandSelectionToLine(textarea) {
942
+ const lines = textarea.value.split("\n");
943
+ let counter = 0;
944
+ for (let index = 0; index < lines.length; index++) {
945
+ const lineLength = lines[index].length + 1;
946
+ if (textarea.selectionStart >= counter && textarea.selectionStart < counter + lineLength) {
947
+ textarea.selectionStart = counter;
948
+ }
949
+ if (textarea.selectionEnd >= counter && textarea.selectionEnd < counter + lineLength) {
950
+ if (index === lines.length - 1) {
951
+ textarea.selectionEnd = Math.min(counter + lines[index].length, textarea.value.length);
952
+ } else {
953
+ textarea.selectionEnd = counter + lineLength - 1;
954
+ }
955
+ }
956
+ counter += lineLength;
957
+ }
958
+ }
959
+ function expandSelectedText(textarea, prefixToUse, suffixToUse, multiline = false) {
960
+ if (textarea.selectionStart === textarea.selectionEnd) {
961
+ textarea.selectionStart = wordSelectionStart(textarea.value, textarea.selectionStart);
962
+ textarea.selectionEnd = wordSelectionEnd(textarea.value, textarea.selectionEnd, multiline);
963
+ } else {
964
+ const expandedSelectionStart = textarea.selectionStart - prefixToUse.length;
965
+ const expandedSelectionEnd = textarea.selectionEnd + suffixToUse.length;
966
+ const beginsWithPrefix = textarea.value.slice(expandedSelectionStart, textarea.selectionStart) === prefixToUse;
967
+ const endsWithSuffix = textarea.value.slice(textarea.selectionEnd, expandedSelectionEnd) === suffixToUse;
968
+ if (beginsWithPrefix && endsWithSuffix) {
969
+ textarea.selectionStart = expandedSelectionStart;
970
+ textarea.selectionEnd = expandedSelectionEnd;
971
+ }
972
+ }
973
+ return textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
974
+ }
975
+ function newlinesToSurroundSelectedText(textarea) {
976
+ const beforeSelection = textarea.value.slice(0, textarea.selectionStart);
977
+ const afterSelection = textarea.value.slice(textarea.selectionEnd);
978
+ const breaksBefore = beforeSelection.match(/\n*$/);
979
+ const breaksAfter = afterSelection.match(/^\n*/);
980
+ const newlinesBeforeSelection = breaksBefore ? breaksBefore[0].length : 0;
981
+ const newlinesAfterSelection = breaksAfter ? breaksAfter[0].length : 0;
982
+ let newlinesToAppend = "";
983
+ let newlinesToPrepend = "";
984
+ if (beforeSelection.match(/\S/) && newlinesBeforeSelection < 2) {
985
+ newlinesToAppend = "\n".repeat(2 - newlinesBeforeSelection);
986
+ }
987
+ if (afterSelection.match(/\S/) && newlinesAfterSelection < 2) {
988
+ newlinesToPrepend = "\n".repeat(2 - newlinesAfterSelection);
989
+ }
990
+ return { newlinesToAppend, newlinesToPrepend };
991
+ }
992
+ function applyLineOperation(textarea, operation, options = {}) {
993
+ const originalStart = textarea.selectionStart;
994
+ const originalEnd = textarea.selectionEnd;
995
+ const noInitialSelection = originalStart === originalEnd;
996
+ const value = textarea.value;
997
+ let lineStart = originalStart;
998
+ while (lineStart > 0 && value[lineStart - 1] !== "\n") {
999
+ lineStart--;
1000
+ }
1001
+ if (noInitialSelection) {
1002
+ let lineEnd = originalStart;
1003
+ while (lineEnd < value.length && value[lineEnd] !== "\n") {
1004
+ lineEnd++;
1005
+ }
1006
+ textarea.selectionStart = lineStart;
1007
+ textarea.selectionEnd = lineEnd;
1008
+ } else {
1009
+ expandSelectionToLine(textarea);
1010
+ }
1011
+ const result = operation(textarea);
1012
+ if (options.adjustSelection) {
1013
+ const selectedText = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
1014
+ const isRemoving = selectedText.startsWith(options.prefix);
1015
+ const adjusted = options.adjustSelection(isRemoving, originalStart, originalEnd, lineStart);
1016
+ result.selectionStart = adjusted.start;
1017
+ result.selectionEnd = adjusted.end;
1018
+ } else if (options.prefix) {
1019
+ const selectedText = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
1020
+ const isRemoving = selectedText.startsWith(options.prefix);
1021
+ if (noInitialSelection) {
1022
+ if (isRemoving) {
1023
+ result.selectionStart = Math.max(originalStart - options.prefix.length, lineStart);
1024
+ result.selectionEnd = result.selectionStart;
1025
+ } else {
1026
+ result.selectionStart = originalStart + options.prefix.length;
1027
+ result.selectionEnd = result.selectionStart;
1028
+ }
1029
+ } else {
1030
+ if (isRemoving) {
1031
+ result.selectionStart = Math.max(originalStart - options.prefix.length, lineStart);
1032
+ result.selectionEnd = Math.max(originalEnd - options.prefix.length, lineStart);
1033
+ } else {
1034
+ result.selectionStart = originalStart + options.prefix.length;
1035
+ result.selectionEnd = originalEnd + options.prefix.length;
1036
+ }
1037
+ }
1038
+ }
1039
+ return result;
1040
+ }
1041
+ function blockStyle(textarea, style) {
1042
+ let newlinesToAppend;
1043
+ let newlinesToPrepend;
1044
+ const { prefix, suffix, blockPrefix, blockSuffix, replaceNext, prefixSpace, scanFor, surroundWithNewlines, trimFirst } = style;
1045
+ const originalSelectionStart = textarea.selectionStart;
1046
+ const originalSelectionEnd = textarea.selectionEnd;
1047
+ let selectedText = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
1048
+ let prefixToUse = isMultipleLines(selectedText) && blockPrefix && blockPrefix.length > 0 ? `${blockPrefix}
1049
+ ` : prefix;
1050
+ let suffixToUse = isMultipleLines(selectedText) && blockSuffix && blockSuffix.length > 0 ? `
1051
+ ${blockSuffix}` : suffix;
1052
+ if (prefixSpace) {
1053
+ const beforeSelection = textarea.value[textarea.selectionStart - 1];
1054
+ if (textarea.selectionStart !== 0 && beforeSelection != null && !beforeSelection.match(/\s/)) {
1055
+ prefixToUse = ` ${prefixToUse}`;
1056
+ }
1057
+ }
1058
+ selectedText = expandSelectedText(textarea, prefixToUse, suffixToUse, style.multiline);
1059
+ let selectionStart = textarea.selectionStart;
1060
+ let selectionEnd = textarea.selectionEnd;
1061
+ const hasReplaceNext = replaceNext && replaceNext.length > 0 && suffixToUse.indexOf(replaceNext) > -1 && selectedText.length > 0;
1062
+ if (surroundWithNewlines) {
1063
+ const ref = newlinesToSurroundSelectedText(textarea);
1064
+ newlinesToAppend = ref.newlinesToAppend;
1065
+ newlinesToPrepend = ref.newlinesToPrepend;
1066
+ prefixToUse = newlinesToAppend + prefix;
1067
+ suffixToUse += newlinesToPrepend;
1068
+ }
1069
+ if (selectedText.startsWith(prefixToUse) && selectedText.endsWith(suffixToUse)) {
1070
+ const replacementText = selectedText.slice(prefixToUse.length, selectedText.length - suffixToUse.length);
1071
+ if (originalSelectionStart === originalSelectionEnd) {
1072
+ let position = originalSelectionStart - prefixToUse.length;
1073
+ position = Math.max(position, selectionStart);
1074
+ position = Math.min(position, selectionStart + replacementText.length);
1075
+ selectionStart = selectionEnd = position;
1076
+ } else {
1077
+ selectionEnd = selectionStart + replacementText.length;
1078
+ }
1079
+ return { text: replacementText, selectionStart, selectionEnd };
1080
+ } else if (!hasReplaceNext) {
1081
+ let replacementText = prefixToUse + selectedText + suffixToUse;
1082
+ selectionStart = originalSelectionStart + prefixToUse.length;
1083
+ selectionEnd = originalSelectionEnd + prefixToUse.length;
1084
+ const whitespaceEdges = selectedText.match(/^\s*|\s*$/g);
1085
+ if (trimFirst && whitespaceEdges) {
1086
+ const leadingWhitespace = whitespaceEdges[0] || "";
1087
+ const trailingWhitespace = whitespaceEdges[1] || "";
1088
+ replacementText = leadingWhitespace + prefixToUse + selectedText.trim() + suffixToUse + trailingWhitespace;
1089
+ selectionStart += leadingWhitespace.length;
1090
+ selectionEnd -= trailingWhitespace.length;
1091
+ }
1092
+ return { text: replacementText, selectionStart, selectionEnd };
1093
+ } else if (scanFor && scanFor.length > 0 && selectedText.match(scanFor)) {
1094
+ suffixToUse = suffixToUse.replace(replaceNext, selectedText);
1095
+ const replacementText = prefixToUse + suffixToUse;
1096
+ selectionStart = selectionEnd = selectionStart + prefixToUse.length;
1097
+ return { text: replacementText, selectionStart, selectionEnd };
1098
+ } else {
1099
+ const replacementText = prefixToUse + selectedText + suffixToUse;
1100
+ selectionStart = selectionStart + prefixToUse.length + selectedText.length + suffixToUse.indexOf(replaceNext);
1101
+ selectionEnd = selectionStart + replaceNext.length;
1102
+ return { text: replacementText, selectionStart, selectionEnd };
1103
+ }
1104
+ }
1105
+ function multilineStyle(textarea, style) {
1106
+ const { prefix, suffix, surroundWithNewlines } = style;
1107
+ let text = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
1108
+ let selectionStart = textarea.selectionStart;
1109
+ let selectionEnd = textarea.selectionEnd;
1110
+ const lines = text.split("\n");
1111
+ const undoStyle = lines.every((line) => line.startsWith(prefix) && (!suffix || line.endsWith(suffix)));
1112
+ if (undoStyle) {
1113
+ text = lines.map((line) => {
1114
+ let result = line.slice(prefix.length);
1115
+ if (suffix) {
1116
+ result = result.slice(0, result.length - suffix.length);
1117
+ }
1118
+ return result;
1119
+ }).join("\n");
1120
+ selectionEnd = selectionStart + text.length;
1121
+ } else {
1122
+ text = lines.map((line) => prefix + line + (suffix || "")).join("\n");
1123
+ if (surroundWithNewlines) {
1124
+ const { newlinesToAppend, newlinesToPrepend } = newlinesToSurroundSelectedText(textarea);
1125
+ selectionStart += newlinesToAppend.length;
1126
+ selectionEnd = selectionStart + text.length;
1127
+ text = newlinesToAppend + text + newlinesToPrepend;
1128
+ }
1129
+ }
1130
+ return { text, selectionStart, selectionEnd };
1131
+ }
1132
+ function undoOrderedListStyle(text) {
1133
+ const lines = text.split("\n");
1134
+ const orderedListRegex = /^\d+\.\s+/;
1135
+ const shouldUndoOrderedList = lines.every((line) => orderedListRegex.test(line));
1136
+ let result = lines;
1137
+ if (shouldUndoOrderedList) {
1138
+ result = lines.map((line) => line.replace(orderedListRegex, ""));
1139
+ }
1140
+ return {
1141
+ text: result.join("\n"),
1142
+ processed: shouldUndoOrderedList
1143
+ };
1144
+ }
1145
+ function undoUnorderedListStyle(text) {
1146
+ const lines = text.split("\n");
1147
+ const unorderedListPrefix = "- ";
1148
+ const shouldUndoUnorderedList = lines.every((line) => line.startsWith(unorderedListPrefix));
1149
+ let result = lines;
1150
+ if (shouldUndoUnorderedList) {
1151
+ result = lines.map((line) => line.slice(unorderedListPrefix.length));
1152
+ }
1153
+ return {
1154
+ text: result.join("\n"),
1155
+ processed: shouldUndoUnorderedList
1156
+ };
1157
+ }
1158
+ function makePrefix(index, unorderedList) {
1159
+ if (unorderedList) {
1160
+ return "- ";
1161
+ } else {
1162
+ return `${index + 1}. `;
1163
+ }
1164
+ }
1165
+ function clearExistingListStyle(style, selectedText) {
1166
+ let undoResult;
1167
+ let undoResultOppositeList;
1168
+ let pristineText;
1169
+ if (style.orderedList) {
1170
+ undoResult = undoOrderedListStyle(selectedText);
1171
+ undoResultOppositeList = undoUnorderedListStyle(undoResult.text);
1172
+ pristineText = undoResultOppositeList.text;
1173
+ } else {
1174
+ undoResult = undoUnorderedListStyle(selectedText);
1175
+ undoResultOppositeList = undoOrderedListStyle(undoResult.text);
1176
+ pristineText = undoResultOppositeList.text;
1177
+ }
1178
+ return [undoResult, undoResultOppositeList, pristineText];
1179
+ }
1180
+ function listStyle(textarea, style) {
1181
+ const noInitialSelection = textarea.selectionStart === textarea.selectionEnd;
1182
+ let selectionStart = textarea.selectionStart;
1183
+ let selectionEnd = textarea.selectionEnd;
1184
+ expandSelectionToLine(textarea);
1185
+ const selectedText = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
1186
+ const [undoResult, undoResultOppositeList, pristineText] = clearExistingListStyle(style, selectedText);
1187
+ const prefixedLines = pristineText.split("\n").map((value, index) => {
1188
+ return `${makePrefix(index, style.unorderedList)}${value}`;
1189
+ });
1190
+ const totalPrefixLength = prefixedLines.reduce((previousValue, _currentValue, currentIndex) => {
1191
+ return previousValue + makePrefix(currentIndex, style.unorderedList).length;
1192
+ }, 0);
1193
+ const totalPrefixLengthOppositeList = prefixedLines.reduce((previousValue, _currentValue, currentIndex) => {
1194
+ return previousValue + makePrefix(currentIndex, !style.unorderedList).length;
1195
+ }, 0);
1196
+ if (undoResult.processed) {
1197
+ if (noInitialSelection) {
1198
+ selectionStart = Math.max(selectionStart - makePrefix(0, style.unorderedList).length, 0);
1199
+ selectionEnd = selectionStart;
1200
+ } else {
1201
+ selectionStart = textarea.selectionStart;
1202
+ selectionEnd = textarea.selectionEnd - totalPrefixLength;
1203
+ }
1204
+ return { text: pristineText, selectionStart, selectionEnd };
1205
+ }
1206
+ const { newlinesToAppend, newlinesToPrepend } = newlinesToSurroundSelectedText(textarea);
1207
+ const text = newlinesToAppend + prefixedLines.join("\n") + newlinesToPrepend;
1208
+ if (noInitialSelection) {
1209
+ selectionStart = Math.max(selectionStart + makePrefix(0, style.unorderedList).length + newlinesToAppend.length, 0);
1210
+ selectionEnd = selectionStart;
1211
+ } else {
1212
+ if (undoResultOppositeList.processed) {
1213
+ selectionStart = Math.max(textarea.selectionStart + newlinesToAppend.length, 0);
1214
+ selectionEnd = textarea.selectionEnd + newlinesToAppend.length + totalPrefixLength - totalPrefixLengthOppositeList;
1215
+ } else {
1216
+ selectionStart = Math.max(textarea.selectionStart + newlinesToAppend.length, 0);
1217
+ selectionEnd = textarea.selectionEnd + newlinesToAppend.length + totalPrefixLength;
1218
+ }
1219
+ }
1220
+ return { text, selectionStart, selectionEnd };
1221
+ }
1222
+ function applyListStyle(textarea, style) {
1223
+ const result = applyLineOperation(
1224
+ textarea,
1225
+ (ta) => listStyle(ta, style),
1226
+ {
1227
+ // Custom selection adjustment for lists
1228
+ adjustSelection: (isRemoving, selStart, selEnd, lineStart) => {
1229
+ const currentLine = textarea.value.slice(lineStart, textarea.selectionEnd);
1230
+ const orderedListRegex = /^\d+\.\s+/;
1231
+ const unorderedListRegex = /^- /;
1232
+ const hasOrderedList = orderedListRegex.test(currentLine);
1233
+ const hasUnorderedList = unorderedListRegex.test(currentLine);
1234
+ const isRemovingCurrent = style.orderedList && hasOrderedList || style.unorderedList && hasUnorderedList;
1235
+ if (selStart === selEnd) {
1236
+ if (isRemovingCurrent) {
1237
+ const prefixMatch = currentLine.match(style.orderedList ? orderedListRegex : unorderedListRegex);
1238
+ const prefixLength = prefixMatch ? prefixMatch[0].length : 0;
1239
+ return {
1240
+ start: Math.max(selStart - prefixLength, lineStart),
1241
+ end: Math.max(selStart - prefixLength, lineStart)
1242
+ };
1243
+ } else if (hasOrderedList || hasUnorderedList) {
1244
+ const oldPrefixMatch = currentLine.match(hasOrderedList ? orderedListRegex : unorderedListRegex);
1245
+ const oldPrefixLength = oldPrefixMatch ? oldPrefixMatch[0].length : 0;
1246
+ const newPrefixLength = style.unorderedList ? 2 : 3;
1247
+ const adjustment = newPrefixLength - oldPrefixLength;
1248
+ return {
1249
+ start: selStart + adjustment,
1250
+ end: selStart + adjustment
1251
+ };
1252
+ } else {
1253
+ const prefixLength = style.unorderedList ? 2 : 3;
1254
+ return {
1255
+ start: selStart + prefixLength,
1256
+ end: selStart + prefixLength
1257
+ };
1258
+ }
1259
+ } else {
1260
+ if (isRemovingCurrent) {
1261
+ const prefixMatch = currentLine.match(style.orderedList ? orderedListRegex : unorderedListRegex);
1262
+ const prefixLength = prefixMatch ? prefixMatch[0].length : 0;
1263
+ return {
1264
+ start: Math.max(selStart - prefixLength, lineStart),
1265
+ end: Math.max(selEnd - prefixLength, lineStart)
1266
+ };
1267
+ } else if (hasOrderedList || hasUnorderedList) {
1268
+ const oldPrefixMatch = currentLine.match(hasOrderedList ? orderedListRegex : unorderedListRegex);
1269
+ const oldPrefixLength = oldPrefixMatch ? oldPrefixMatch[0].length : 0;
1270
+ const newPrefixLength = style.unorderedList ? 2 : 3;
1271
+ const adjustment = newPrefixLength - oldPrefixLength;
1272
+ return {
1273
+ start: selStart + adjustment,
1274
+ end: selEnd + adjustment
1275
+ };
1276
+ } else {
1277
+ const prefixLength = style.unorderedList ? 2 : 3;
1278
+ return {
1279
+ start: selStart + prefixLength,
1280
+ end: selEnd + prefixLength
1281
+ };
1282
+ }
1283
+ }
1284
+ }
1285
+ }
1286
+ );
1287
+ insertText(textarea, result);
1288
+ }
1289
+ function getActiveFormats(textarea) {
1290
+ if (!textarea)
1291
+ return [];
1292
+ const formats = [];
1293
+ const { selectionStart, selectionEnd, value } = textarea;
1294
+ const lines = value.split("\n");
1295
+ let lineStart = 0;
1296
+ let currentLine = "";
1297
+ for (const line of lines) {
1298
+ if (selectionStart >= lineStart && selectionStart <= lineStart + line.length) {
1299
+ currentLine = line;
1300
+ break;
1301
+ }
1302
+ lineStart += line.length + 1;
1303
+ }
1304
+ if (currentLine.startsWith("- ")) {
1305
+ if (currentLine.startsWith("- [ ] ") || currentLine.startsWith("- [x] ")) {
1306
+ formats.push("task-list");
1307
+ } else {
1308
+ formats.push("bullet-list");
1309
+ }
1310
+ }
1311
+ if (/^\d+\.\s/.test(currentLine)) {
1312
+ formats.push("numbered-list");
1313
+ }
1314
+ if (currentLine.startsWith("> ")) {
1315
+ formats.push("quote");
1316
+ }
1317
+ if (currentLine.startsWith("# "))
1318
+ formats.push("header");
1319
+ if (currentLine.startsWith("## "))
1320
+ formats.push("header-2");
1321
+ if (currentLine.startsWith("### "))
1322
+ formats.push("header-3");
1323
+ const lookBehind = Math.max(0, selectionStart - 10);
1324
+ const lookAhead = Math.min(value.length, selectionEnd + 10);
1325
+ const surrounding = value.slice(lookBehind, lookAhead);
1326
+ if (surrounding.includes("**")) {
1327
+ const beforeCursor = value.slice(Math.max(0, selectionStart - 100), selectionStart);
1328
+ const afterCursor = value.slice(selectionEnd, Math.min(value.length, selectionEnd + 100));
1329
+ const lastOpenBold = beforeCursor.lastIndexOf("**");
1330
+ const nextCloseBold = afterCursor.indexOf("**");
1331
+ if (lastOpenBold !== -1 && nextCloseBold !== -1) {
1332
+ formats.push("bold");
1333
+ }
1334
+ }
1335
+ if (surrounding.includes("_")) {
1336
+ const beforeCursor = value.slice(Math.max(0, selectionStart - 100), selectionStart);
1337
+ const afterCursor = value.slice(selectionEnd, Math.min(value.length, selectionEnd + 100));
1338
+ const lastOpenItalic = beforeCursor.lastIndexOf("_");
1339
+ const nextCloseItalic = afterCursor.indexOf("_");
1340
+ if (lastOpenItalic !== -1 && nextCloseItalic !== -1) {
1341
+ formats.push("italic");
1342
+ }
1343
+ }
1344
+ if (surrounding.includes("`")) {
1345
+ const beforeCursor = value.slice(Math.max(0, selectionStart - 100), selectionStart);
1346
+ const afterCursor = value.slice(selectionEnd, Math.min(value.length, selectionEnd + 100));
1347
+ if (beforeCursor.includes("`") && afterCursor.includes("`")) {
1348
+ formats.push("code");
1349
+ }
1350
+ }
1351
+ if (surrounding.includes("[") && surrounding.includes("]")) {
1352
+ const beforeCursor = value.slice(Math.max(0, selectionStart - 100), selectionStart);
1353
+ const afterCursor = value.slice(selectionEnd, Math.min(value.length, selectionEnd + 100));
1354
+ const lastOpenBracket = beforeCursor.lastIndexOf("[");
1355
+ const nextCloseBracket = afterCursor.indexOf("]");
1356
+ if (lastOpenBracket !== -1 && nextCloseBracket !== -1) {
1357
+ const afterBracket = value.slice(selectionEnd + nextCloseBracket + 1, selectionEnd + nextCloseBracket + 10);
1358
+ if (afterBracket.startsWith("(")) {
1359
+ formats.push("link");
1360
+ }
1361
+ }
1362
+ }
1363
+ return formats;
1364
+ }
1365
+ function toggleBold(textarea) {
1366
+ if (!textarea || textarea.disabled || textarea.readOnly)
1367
+ return;
1368
+ debugLog("toggleBold", "Starting");
1369
+ debugSelection(textarea, "Before");
1370
+ const style = mergeWithDefaults(FORMATS.bold);
1371
+ const result = blockStyle(textarea, style);
1372
+ debugResult(result);
1373
+ insertText(textarea, result);
1374
+ debugSelection(textarea, "After");
1375
+ }
1376
+ function toggleItalic(textarea) {
1377
+ if (!textarea || textarea.disabled || textarea.readOnly)
1378
+ return;
1379
+ const style = mergeWithDefaults(FORMATS.italic);
1380
+ const result = blockStyle(textarea, style);
1381
+ insertText(textarea, result);
1382
+ }
1383
+ function toggleCode(textarea) {
1384
+ if (!textarea || textarea.disabled || textarea.readOnly)
1385
+ return;
1386
+ const style = mergeWithDefaults(FORMATS.code);
1387
+ const result = blockStyle(textarea, style);
1388
+ insertText(textarea, result);
1389
+ }
1390
+ function insertLink(textarea, options = {}) {
1391
+ if (!textarea || textarea.disabled || textarea.readOnly)
1392
+ return;
1393
+ const selectedText = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
1394
+ let style = mergeWithDefaults(FORMATS.link);
1395
+ const isURL = selectedText && selectedText.match(/^https?:\/\//);
1396
+ if (isURL && !options.url) {
1397
+ style.suffix = `](${selectedText})`;
1398
+ style.replaceNext = "";
1399
+ } else if (options.url) {
1400
+ style.suffix = `](${options.url})`;
1401
+ style.replaceNext = "";
1402
+ }
1403
+ if (options.text && !selectedText) {
1404
+ const pos = textarea.selectionStart;
1405
+ textarea.value = textarea.value.slice(0, pos) + options.text + textarea.value.slice(pos);
1406
+ textarea.selectionStart = pos;
1407
+ textarea.selectionEnd = pos + options.text.length;
1408
+ }
1409
+ const result = blockStyle(textarea, style);
1410
+ insertText(textarea, result);
1411
+ }
1412
+ function toggleBulletList(textarea) {
1413
+ if (!textarea || textarea.disabled || textarea.readOnly)
1414
+ return;
1415
+ const style = mergeWithDefaults(FORMATS.bulletList);
1416
+ applyListStyle(textarea, style);
1417
+ }
1418
+ function toggleNumberedList(textarea) {
1419
+ if (!textarea || textarea.disabled || textarea.readOnly)
1420
+ return;
1421
+ const style = mergeWithDefaults(FORMATS.numberedList);
1422
+ applyListStyle(textarea, style);
1423
+ }
1424
+ function toggleQuote(textarea) {
1425
+ if (!textarea || textarea.disabled || textarea.readOnly)
1426
+ return;
1427
+ debugLog("toggleQuote", "Starting");
1428
+ debugSelection(textarea, "Initial");
1429
+ const style = mergeWithDefaults(FORMATS.quote);
1430
+ const result = applyLineOperation(
1431
+ textarea,
1432
+ (ta) => multilineStyle(ta, style),
1433
+ { prefix: style.prefix }
1434
+ );
1435
+ debugResult(result);
1436
+ insertText(textarea, result);
1437
+ debugSelection(textarea, "Final");
1438
+ }
1439
+ function toggleTaskList(textarea) {
1440
+ if (!textarea || textarea.disabled || textarea.readOnly)
1441
+ return;
1442
+ const style = mergeWithDefaults(FORMATS.taskList);
1443
+ const result = applyLineOperation(
1444
+ textarea,
1445
+ (ta) => multilineStyle(ta, style),
1446
+ { prefix: style.prefix }
1447
+ );
1448
+ insertText(textarea, result);
1449
+ }
1450
+ function insertHeader(textarea, level = 1, toggle = false) {
1451
+ if (!textarea || textarea.disabled || textarea.readOnly)
1452
+ return;
1453
+ if (level < 1 || level > 6)
1454
+ level = 1;
1455
+ debugLog("insertHeader", `============ START ============`);
1456
+ debugLog("insertHeader", `Level: ${level}, Toggle: ${toggle}`);
1457
+ debugLog("insertHeader", `Initial cursor: ${textarea.selectionStart}-${textarea.selectionEnd}`);
1458
+ const headerKey = `header${level === 1 ? "1" : level}`;
1459
+ const style = mergeWithDefaults(FORMATS[headerKey] || FORMATS.header1);
1460
+ debugLog("insertHeader", `Style prefix: "${style.prefix}"`);
1461
+ const value = textarea.value;
1462
+ const originalStart = textarea.selectionStart;
1463
+ const originalEnd = textarea.selectionEnd;
1464
+ let lineStart = originalStart;
1465
+ while (lineStart > 0 && value[lineStart - 1] !== "\n") {
1466
+ lineStart--;
1467
+ }
1468
+ let lineEnd = originalEnd;
1469
+ while (lineEnd < value.length && value[lineEnd] !== "\n") {
1470
+ lineEnd++;
1471
+ }
1472
+ const currentLineContent = value.slice(lineStart, lineEnd);
1473
+ debugLog("insertHeader", `Current line (before): "${currentLineContent}"`);
1474
+ const existingHeaderMatch = currentLineContent.match(/^(#{1,6})\s*/);
1475
+ const existingLevel = existingHeaderMatch ? existingHeaderMatch[1].length : 0;
1476
+ const existingPrefixLength = existingHeaderMatch ? existingHeaderMatch[0].length : 0;
1477
+ debugLog("insertHeader", `Existing header check:`);
1478
+ debugLog("insertHeader", ` - Match: ${existingHeaderMatch ? `"${existingHeaderMatch[0]}"` : "none"}`);
1479
+ debugLog("insertHeader", ` - Existing level: ${existingLevel}`);
1480
+ debugLog("insertHeader", ` - Existing prefix length: ${existingPrefixLength}`);
1481
+ debugLog("insertHeader", ` - Target level: ${level}`);
1482
+ const shouldToggleOff = toggle && existingLevel === level;
1483
+ debugLog("insertHeader", `Should toggle OFF: ${shouldToggleOff} (toggle=${toggle}, existingLevel=${existingLevel}, level=${level})`);
1484
+ const result = applyLineOperation(
1485
+ textarea,
1486
+ (ta) => {
1487
+ const currentLine = ta.value.slice(ta.selectionStart, ta.selectionEnd);
1488
+ debugLog("insertHeader", `Line in operation: "${currentLine}"`);
1489
+ const cleanedLine = currentLine.replace(/^#{1,6}\s*/, "");
1490
+ debugLog("insertHeader", `Cleaned line: "${cleanedLine}"`);
1491
+ let newLine;
1492
+ if (shouldToggleOff) {
1493
+ debugLog("insertHeader", "ACTION: Toggling OFF - removing header");
1494
+ newLine = cleanedLine;
1495
+ } else if (existingLevel > 0) {
1496
+ debugLog("insertHeader", `ACTION: Replacing H${existingLevel} with H${level}`);
1497
+ newLine = style.prefix + cleanedLine;
1498
+ } else {
1499
+ debugLog("insertHeader", "ACTION: Adding new header");
1500
+ newLine = style.prefix + cleanedLine;
1501
+ }
1502
+ debugLog("insertHeader", `New line: "${newLine}"`);
1503
+ return {
1504
+ text: newLine,
1505
+ selectionStart: ta.selectionStart,
1506
+ selectionEnd: ta.selectionEnd
1507
+ };
1508
+ },
1509
+ {
1510
+ prefix: style.prefix,
1511
+ // Custom selection adjustment for headers
1512
+ adjustSelection: (isRemoving, selStart, selEnd, lineStartPos) => {
1513
+ debugLog("insertHeader", `Adjusting selection:`);
1514
+ debugLog("insertHeader", ` - isRemoving param: ${isRemoving}`);
1515
+ debugLog("insertHeader", ` - shouldToggleOff: ${shouldToggleOff}`);
1516
+ debugLog("insertHeader", ` - selStart: ${selStart}, selEnd: ${selEnd}`);
1517
+ debugLog("insertHeader", ` - lineStartPos: ${lineStartPos}`);
1518
+ if (shouldToggleOff) {
1519
+ const adjustment = Math.max(selStart - existingPrefixLength, lineStartPos);
1520
+ debugLog("insertHeader", ` - Removing header, adjusting by -${existingPrefixLength}`);
1521
+ return {
1522
+ start: adjustment,
1523
+ end: selStart === selEnd ? adjustment : Math.max(selEnd - existingPrefixLength, lineStartPos)
1524
+ };
1525
+ } else if (existingPrefixLength > 0) {
1526
+ const prefixDiff = style.prefix.length - existingPrefixLength;
1527
+ debugLog("insertHeader", ` - Replacing header, adjusting by ${prefixDiff}`);
1528
+ return {
1529
+ start: selStart + prefixDiff,
1530
+ end: selEnd + prefixDiff
1531
+ };
1532
+ } else {
1533
+ debugLog("insertHeader", ` - Adding header, adjusting by +${style.prefix.length}`);
1534
+ return {
1535
+ start: selStart + style.prefix.length,
1536
+ end: selEnd + style.prefix.length
1537
+ };
1538
+ }
1539
+ }
1540
+ }
1541
+ );
1542
+ debugLog("insertHeader", `Final result: text="${result.text}", cursor=${result.selectionStart}-${result.selectionEnd}`);
1543
+ debugLog("insertHeader", `============ END ============`);
1544
+ insertText(textarea, result);
1545
+ }
1546
+ function toggleH1(textarea) {
1547
+ insertHeader(textarea, 1, true);
1548
+ }
1549
+ function toggleH2(textarea) {
1550
+ insertHeader(textarea, 2, true);
1551
+ }
1552
+ function toggleH3(textarea) {
1553
+ insertHeader(textarea, 3, true);
1554
+ }
1555
+ function getActiveFormats2(textarea) {
1556
+ return getActiveFormats(textarea);
1557
+ }
1558
+
1559
+ // src/shortcuts.js
1560
+ var ShortcutsManager = class {
1561
+ constructor(editor) {
1562
+ this.editor = editor;
1563
+ this.textarea = editor.textarea;
1564
+ }
1565
+ /**
1566
+ * Handle keydown events - called by OverType
1567
+ * @param {KeyboardEvent} event - The keyboard event
1568
+ * @returns {boolean} Whether the event was handled
1569
+ */
1570
+ handleKeydown(event) {
1571
+ const isMac = navigator.platform.toLowerCase().includes("mac");
1572
+ const modKey = isMac ? event.metaKey : event.ctrlKey;
1573
+ if (!modKey)
1574
+ return false;
1575
+ let action = null;
1576
+ switch (event.key.toLowerCase()) {
1577
+ case "b":
1578
+ if (!event.shiftKey) {
1579
+ action = "toggleBold";
1580
+ }
1581
+ break;
1582
+ case "i":
1583
+ if (!event.shiftKey) {
1584
+ action = "toggleItalic";
1585
+ }
1586
+ break;
1587
+ case "k":
1588
+ if (!event.shiftKey) {
1589
+ action = "insertLink";
1590
+ }
1591
+ break;
1592
+ case "7":
1593
+ if (event.shiftKey) {
1594
+ action = "toggleNumberedList";
1595
+ }
1596
+ break;
1597
+ case "8":
1598
+ if (event.shiftKey) {
1599
+ action = "toggleBulletList";
1600
+ }
1601
+ break;
1602
+ }
1603
+ if (action) {
1604
+ event.preventDefault();
1605
+ if (this.editor.toolbar) {
1606
+ this.editor.toolbar.handleAction(action);
1607
+ } else {
1608
+ this.handleAction(action);
1609
+ }
1610
+ return true;
1611
+ }
1612
+ return false;
1613
+ }
1614
+ /**
1615
+ * Handle action - fallback when no toolbar exists
1616
+ * This duplicates toolbar.handleAction for consistency
1617
+ */
1618
+ async handleAction(action) {
1619
+ const textarea = this.textarea;
1620
+ if (!textarea)
1621
+ return;
1622
+ textarea.focus();
1623
+ try {
1624
+ switch (action) {
1625
+ case "toggleBold":
1626
+ toggleBold(textarea);
1627
+ break;
1628
+ case "toggleItalic":
1629
+ toggleItalic(textarea);
1630
+ break;
1631
+ case "insertLink":
1632
+ insertLink(textarea);
1633
+ break;
1634
+ case "toggleBulletList":
1635
+ toggleBulletList(textarea);
1636
+ break;
1637
+ case "toggleNumberedList":
1638
+ toggleNumberedList(textarea);
1639
+ break;
1640
+ }
1641
+ textarea.dispatchEvent(new Event("input", { bubbles: true }));
1642
+ } catch (error) {
1643
+ console.error("Error in markdown action:", error);
1644
+ }
1645
+ }
1646
+ /**
1647
+ * Cleanup
1648
+ */
1649
+ destroy() {
1650
+ }
1651
+ };
1652
+
1653
+ // src/themes.js
1654
+ var solar = {
1655
+ name: "solar",
1656
+ colors: {
1657
+ bgPrimary: "#faf0ca",
1658
+ // Lemon Chiffon - main background
1659
+ bgSecondary: "#ffffff",
1660
+ // White - editor background
1661
+ text: "#0d3b66",
1662
+ // Yale Blue - main text
1663
+ h1: "#f95738",
1664
+ // Tomato - h1 headers
1665
+ h2: "#ee964b",
1666
+ // Sandy Brown - h2 headers
1667
+ h3: "#3d8a51",
1668
+ // Forest green - h3 headers
1669
+ strong: "#ee964b",
1670
+ // Sandy Brown - bold text
1671
+ em: "#f95738",
1672
+ // Tomato - italic text
1673
+ link: "#0d3b66",
1674
+ // Yale Blue - links
1675
+ code: "#0d3b66",
1676
+ // Yale Blue - inline code
1677
+ codeBg: "rgba(244, 211, 94, 0.4)",
1678
+ // Naples Yellow with transparency
1679
+ blockquote: "#5a7a9b",
1680
+ // Muted blue - blockquotes
1681
+ hr: "#5a7a9b",
1682
+ // Muted blue - horizontal rules
1683
+ syntaxMarker: "rgba(13, 59, 102, 0.52)",
1684
+ // Yale Blue with transparency
1685
+ cursor: "#f95738",
1686
+ // Tomato - cursor
1687
+ selection: "rgba(244, 211, 94, 0.4)",
1688
+ // Naples Yellow with transparency
1689
+ listMarker: "#ee964b",
1690
+ // Sandy Brown - list markers
1691
+ // Toolbar colors
1692
+ toolbarBg: "#ffffff",
1693
+ // White - toolbar background
1694
+ toolbarBorder: "rgba(13, 59, 102, 0.15)",
1695
+ // Yale Blue border
1696
+ toolbarIcon: "#0d3b66",
1697
+ // Yale Blue - icon color
1698
+ toolbarHover: "#f5f5f5",
1699
+ // Light gray - hover background
1700
+ toolbarActive: "#faf0ca"
1701
+ // Lemon Chiffon - active button background
1702
+ }
1703
+ };
1704
+ var cave = {
1705
+ name: "cave",
1706
+ colors: {
1707
+ bgPrimary: "#141E26",
1708
+ // Deep ocean - main background
1709
+ bgSecondary: "#1D2D3E",
1710
+ // Darker charcoal - editor background
1711
+ text: "#c5dde8",
1712
+ // Light blue-gray - main text
1713
+ h1: "#d4a5ff",
1714
+ // Rich lavender - h1 headers
1715
+ h2: "#f6ae2d",
1716
+ // Hunyadi Yellow - h2 headers
1717
+ h3: "#9fcfec",
1718
+ // Brighter blue - h3 headers
1719
+ strong: "#f6ae2d",
1720
+ // Hunyadi Yellow - bold text
1721
+ em: "#9fcfec",
1722
+ // Brighter blue - italic text
1723
+ link: "#9fcfec",
1724
+ // Brighter blue - links
1725
+ code: "#c5dde8",
1726
+ // Light blue-gray - inline code
1727
+ codeBg: "#1a232b",
1728
+ // Very dark blue - code background
1729
+ blockquote: "#9fcfec",
1730
+ // Brighter blue - same as italic
1731
+ hr: "#c5dde8",
1732
+ // Light blue-gray - horizontal rules
1733
+ syntaxMarker: "rgba(159, 207, 236, 0.73)",
1734
+ // Brighter blue semi-transparent
1735
+ cursor: "#f26419",
1736
+ // Orange Pantone - cursor
1737
+ selection: "rgba(51, 101, 138, 0.4)",
1738
+ // Lapis Lazuli with transparency
1739
+ listMarker: "#f6ae2d",
1740
+ // Hunyadi Yellow - list markers
1741
+ // Toolbar colors for dark theme
1742
+ toolbarBg: "#1D2D3E",
1743
+ // Darker charcoal - toolbar background
1744
+ toolbarBorder: "rgba(197, 221, 232, 0.1)",
1745
+ // Light blue-gray border
1746
+ toolbarIcon: "#c5dde8",
1747
+ // Light blue-gray - icon color
1748
+ toolbarHover: "#243546",
1749
+ // Slightly lighter charcoal - hover background
1750
+ toolbarActive: "#2a3f52"
1751
+ // Even lighter - active button background
1752
+ }
1753
+ };
1754
+ var themes = {
1755
+ solar,
1756
+ cave,
1757
+ // Aliases for backward compatibility
1758
+ light: solar,
1759
+ dark: cave
1760
+ };
1761
+ function getTheme(theme) {
1762
+ if (typeof theme === "string") {
1763
+ const themeObj = themes[theme] || themes.solar;
1764
+ return { ...themeObj, name: theme };
1765
+ }
1766
+ return theme;
1767
+ }
1768
+ function themeToCSSVars(colors) {
1769
+ const vars = [];
1770
+ for (const [key, value] of Object.entries(colors)) {
1771
+ const varName = key.replace(/([A-Z])/g, "-$1").toLowerCase();
1772
+ vars.push(`--${varName}: ${value};`);
1773
+ }
1774
+ return vars.join("\n");
1775
+ }
1776
+ function mergeTheme(baseTheme, customColors = {}) {
1777
+ return {
1778
+ ...baseTheme,
1779
+ colors: {
1780
+ ...baseTheme.colors,
1781
+ ...customColors
1782
+ }
1783
+ };
1784
+ }
1785
+
1786
+ // src/styles.js
1787
+ function generateStyles(options = {}) {
1788
+ const {
1789
+ fontSize = "14px",
1790
+ lineHeight = 1.6,
1791
+ /* System-first, guaranteed monospaced; avoids Android 'ui-monospace' pitfalls */
1792
+ fontFamily = '"SF Mono", SFMono-Regular, Menlo, Monaco, "Cascadia Code", Consolas, "Roboto Mono", "Noto Sans Mono", "Droid Sans Mono", "Ubuntu Mono", "DejaVu Sans Mono", "Liberation Mono", "Courier New", Courier, monospace',
1793
+ padding = "20px",
1794
+ theme = null,
1795
+ mobile = {}
1796
+ } = options;
1797
+ const mobileStyles = Object.keys(mobile).length > 0 ? `
1798
+ @media (max-width: 640px) {
1799
+ .overtype-wrapper .overtype-input,
1800
+ .overtype-wrapper .overtype-preview {
1801
+ ${Object.entries(mobile).map(([prop, val]) => {
1802
+ const cssProp = prop.replace(/([A-Z])/g, "-$1").toLowerCase();
1803
+ return `${cssProp}: ${val} !important;`;
1804
+ }).join("\n ")}
1805
+ }
1806
+ }
1807
+ ` : "";
1808
+ const themeVars = theme && theme.colors ? themeToCSSVars(theme.colors) : "";
1809
+ return `
1810
+ /* OverType Editor Styles */
1811
+
1812
+ /* Middle-ground CSS Reset - Prevent parent styles from leaking in */
1813
+ .overtype-container * {
1814
+ /* Box model - these commonly leak */
1815
+ margin: 0 !important;
1816
+ padding: 0 !important;
1817
+ border: 0 !important;
1818
+
1819
+ /* Layout - these can break our layout */
1820
+ /* Don't reset position - it breaks dropdowns */
1821
+ float: none !important;
1822
+ clear: none !important;
1823
+
1824
+ /* Typography - only reset decorative aspects */
1825
+ text-decoration: none !important;
1826
+ text-transform: none !important;
1827
+ letter-spacing: normal !important;
1828
+
1829
+ /* Visual effects that can interfere */
1830
+ box-shadow: none !important;
1831
+ text-shadow: none !important;
1832
+
1833
+ /* Ensure box-sizing is consistent */
1834
+ box-sizing: border-box !important;
1835
+
1836
+ /* Keep inheritance for these */
1837
+ /* font-family, color, line-height, font-size - inherit */
1838
+ }
1839
+
1840
+ /* Container base styles after reset */
1841
+ .overtype-container {
1842
+ display: grid !important;
1843
+ grid-template-rows: auto 1fr auto !important;
1844
+ width: 100% !important;
1845
+ height: 100% !important;
1846
+ position: relative !important; /* Override reset - needed for absolute children */
1847
+ overflow: visible !important; /* Allow dropdown to overflow container */
1848
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
1849
+ text-align: left !important;
1850
+ ${themeVars ? `
1851
+ /* Theme Variables */
1852
+ ${themeVars}` : ""}
1853
+ }
1854
+
1855
+ /* Force left alignment for all elements in the editor */
1856
+ .overtype-container .overtype-wrapper * {
1857
+ text-align: left !important;
1858
+ }
1859
+
1860
+ /* Auto-resize mode styles */
1861
+ .overtype-container.overtype-auto-resize {
1862
+ height: auto !important;
1863
+ grid-template-rows: auto auto auto !important;
1864
+ }
1865
+
1866
+ .overtype-container.overtype-auto-resize .overtype-wrapper {
1867
+ height: auto !important;
1868
+ min-height: 60px !important;
1869
+ overflow: visible !important;
1870
+ }
1871
+
1872
+ .overtype-wrapper {
1873
+ position: relative !important; /* Override reset - needed for absolute children */
1874
+ width: 100% !important;
1875
+ height: 100% !important; /* Take full height of grid cell */
1876
+ min-height: 60px !important; /* Minimum usable height */
1877
+ overflow: hidden !important;
1878
+ background: var(--bg-secondary, #ffffff) !important;
1879
+ grid-row: 2 !important; /* Always second row in grid */
1880
+ z-index: 1; /* Below toolbar and dropdown */
1881
+ }
1882
+
1883
+ /* Critical alignment styles - must be identical for both layers */
1884
+ .overtype-wrapper .overtype-input,
1885
+ .overtype-wrapper .overtype-preview {
1886
+ /* Positioning - must be identical */
1887
+ position: absolute !important; /* Override reset - required for overlay */
1888
+ top: 0 !important;
1889
+ left: 0 !important;
1890
+ width: 100% !important;
1891
+ height: 100% !important;
1892
+
1893
+ /* Font properties - any difference breaks alignment */
1894
+ font-family: ${fontFamily} !important;
1895
+ font-variant-ligatures: none !important; /* keep metrics stable for code */
1896
+ font-size: var(--instance-font-size, ${fontSize}) !important;
1897
+ line-height: var(--instance-line-height, ${lineHeight}) !important;
1898
+ font-weight: normal !important;
1899
+ font-style: normal !important;
1900
+ font-variant: normal !important;
1901
+ font-stretch: normal !important;
1902
+ font-kerning: none !important;
1903
+ font-feature-settings: normal !important;
1904
+
1905
+ /* Box model - must match exactly */
1906
+ padding: var(--instance-padding, ${padding}) !important;
1907
+ margin: 0 !important;
1908
+ border: none !important;
1909
+ outline: none !important;
1910
+ box-sizing: border-box !important;
1911
+
1912
+ /* Text layout - critical for character positioning */
1913
+ white-space: pre-wrap !important;
1914
+ word-wrap: break-word !important;
1915
+ word-break: normal !important;
1916
+ overflow-wrap: break-word !important;
1917
+ tab-size: 2 !important;
1918
+ -moz-tab-size: 2 !important;
1919
+ text-align: left !important;
1920
+ text-indent: 0 !important;
1921
+ letter-spacing: normal !important;
1922
+ word-spacing: normal !important;
1923
+
1924
+ /* Text rendering */
1925
+ text-transform: none !important;
1926
+ text-rendering: auto !important;
1927
+ -webkit-font-smoothing: auto !important;
1928
+ -webkit-text-size-adjust: 100% !important;
1929
+
1930
+ /* Direction and writing */
1931
+ direction: ltr !important;
1932
+ writing-mode: horizontal-tb !important;
1933
+ unicode-bidi: normal !important;
1934
+ text-orientation: mixed !important;
1935
+
1936
+ /* Visual effects that could shift perception */
1937
+ text-shadow: none !important;
1938
+ filter: none !important;
1939
+ transform: none !important;
1940
+ zoom: 1 !important;
1941
+
1942
+ /* Vertical alignment */
1943
+ vertical-align: baseline !important;
1944
+
1945
+ /* Size constraints */
1946
+ min-width: 0 !important;
1947
+ min-height: 0 !important;
1948
+ max-width: none !important;
1949
+ max-height: none !important;
1950
+
1951
+ /* Overflow */
1952
+ overflow-y: auto !important;
1953
+ overflow-x: auto !important;
1954
+ /* overscroll-behavior removed to allow scroll-through to parent */
1955
+ scrollbar-width: auto !important;
1956
+ scrollbar-gutter: auto !important;
1957
+
1958
+ /* Animation/transition - disabled to prevent movement */
1959
+ animation: none !important;
1960
+ transition: none !important;
1961
+ }
1962
+
1963
+ /* Input layer styles */
1964
+ .overtype-wrapper .overtype-input {
1965
+ /* Layer positioning */
1966
+ z-index: 1 !important;
1967
+
1968
+ /* Text visibility */
1969
+ color: transparent !important;
1970
+ caret-color: var(--cursor, #f95738) !important;
1971
+ background-color: transparent !important;
1972
+
1973
+ /* Textarea-specific */
1974
+ resize: none !important;
1975
+ appearance: none !important;
1976
+ -webkit-appearance: none !important;
1977
+ -moz-appearance: none !important;
1978
+
1979
+ /* Prevent mobile zoom on focus */
1980
+ touch-action: manipulation !important;
1981
+
1982
+ /* Disable autofill and spellcheck */
1983
+ autocomplete: off !important;
1984
+ autocorrect: off !important;
1985
+ autocapitalize: off !important;
1986
+ spellcheck: false !important;
1987
+ }
1988
+
1989
+ .overtype-wrapper .overtype-input::selection {
1990
+ background-color: var(--selection, rgba(244, 211, 94, 0.4));
1991
+ }
1992
+
1993
+ /* Preview layer styles */
1994
+ .overtype-wrapper .overtype-preview {
1995
+ /* Layer positioning */
1996
+ z-index: 0 !important;
1997
+ pointer-events: none !important;
1998
+ color: var(--text, #0d3b66) !important;
1999
+ background-color: transparent !important;
2000
+
2001
+ /* Prevent text selection */
2002
+ user-select: none !important;
2003
+ -webkit-user-select: none !important;
2004
+ -moz-user-select: none !important;
2005
+ -ms-user-select: none !important;
2006
+ }
2007
+
2008
+ /* Defensive styles for preview child divs */
2009
+ .overtype-wrapper .overtype-preview div {
2010
+ /* Reset any inherited styles */
2011
+ margin: 0 !important;
2012
+ padding: 0 !important;
2013
+ border: none !important;
2014
+ text-align: left !important;
2015
+ text-indent: 0 !important;
2016
+ display: block !important;
2017
+ position: static !important;
2018
+ transform: none !important;
2019
+ min-height: 0 !important;
2020
+ max-height: none !important;
2021
+ line-height: inherit !important;
2022
+ font-size: inherit !important;
2023
+ font-family: inherit !important;
2024
+ }
2025
+
2026
+ /* Markdown element styling - NO SIZE CHANGES */
2027
+ .overtype-wrapper .overtype-preview .header {
2028
+ font-weight: bold !important;
2029
+ }
2030
+
2031
+ /* Header colors */
2032
+ .overtype-wrapper .overtype-preview .h1 {
2033
+ color: var(--h1, #f95738) !important;
2034
+ }
2035
+ .overtype-wrapper .overtype-preview .h2 {
2036
+ color: var(--h2, #ee964b) !important;
2037
+ }
2038
+ .overtype-wrapper .overtype-preview .h3 {
2039
+ color: var(--h3, #3d8a51) !important;
2040
+ }
2041
+
2042
+ /* Semantic headers - flatten in edit mode */
2043
+ .overtype-wrapper .overtype-preview h1,
2044
+ .overtype-wrapper .overtype-preview h2,
2045
+ .overtype-wrapper .overtype-preview h3 {
2046
+ font-size: inherit !important;
2047
+ font-weight: bold !important;
2048
+ margin: 0 !important;
2049
+ padding: 0 !important;
2050
+ display: inline !important;
2051
+ line-height: inherit !important;
2052
+ }
2053
+
2054
+ /* Header colors for semantic headers */
2055
+ .overtype-wrapper .overtype-preview h1 {
2056
+ color: var(--h1, #f95738) !important;
2057
+ }
2058
+ .overtype-wrapper .overtype-preview h2 {
2059
+ color: var(--h2, #ee964b) !important;
2060
+ }
2061
+ .overtype-wrapper .overtype-preview h3 {
2062
+ color: var(--h3, #3d8a51) !important;
2063
+ }
2064
+
2065
+ /* Lists - remove styling in edit mode */
2066
+ .overtype-wrapper .overtype-preview ul,
2067
+ .overtype-wrapper .overtype-preview ol {
2068
+ list-style: none !important;
2069
+ margin: 0 !important;
2070
+ padding: 0 !important;
2071
+ display: block !important; /* Lists need to be block for line breaks */
2072
+ }
2073
+
2074
+ .overtype-wrapper .overtype-preview li {
2075
+ display: block !important; /* Each item on its own line */
2076
+ margin: 0 !important;
2077
+ padding: 0 !important;
2078
+ /* Don't set list-style here - let ul/ol control it */
2079
+ }
2080
+
2081
+ /* Bold text */
2082
+ .overtype-wrapper .overtype-preview strong {
2083
+ color: var(--strong, #ee964b) !important;
2084
+ font-weight: bold !important;
2085
+ }
2086
+
2087
+ /* Italic text */
2088
+ .overtype-wrapper .overtype-preview em {
2089
+ color: var(--em, #f95738) !important;
2090
+ text-decoration-color: var(--em, #f95738) !important;
2091
+ text-decoration-thickness: 1px !important;
2092
+ font-style: italic !important;
2093
+ }
2094
+
2095
+ /* Strikethrough text */
2096
+ .overtype-wrapper .overtype-preview del {
2097
+ color: var(--del, #ee964b) !important;
2098
+ text-decoration: line-through !important;
2099
+ text-decoration-color: var(--del, #ee964b) !important;
2100
+ text-decoration-thickness: 1px !important;
2101
+ }
2102
+
2103
+ /* Inline code */
2104
+ .overtype-wrapper .overtype-preview code {
2105
+ background: var(--code-bg, rgba(244, 211, 94, 0.4)) !important;
2106
+ color: var(--code, #0d3b66) !important;
2107
+ padding: 0 !important;
2108
+ border-radius: 2px !important;
2109
+ font-family: inherit !important;
2110
+ font-size: inherit !important;
2111
+ line-height: inherit !important;
2112
+ font-weight: normal !important;
2113
+ }
2114
+
2115
+ /* Code blocks - consolidated pre blocks */
2116
+ .overtype-wrapper .overtype-preview pre {
2117
+ padding: 0 !important;
2118
+ margin: 0 !important;
2119
+ border-radius: 4px !important;
2120
+ overflow-x: auto !important;
2121
+ }
2122
+
2123
+ /* Code block styling in normal mode - yellow background */
2124
+ .overtype-wrapper .overtype-preview pre.code-block {
2125
+ background: var(--code-bg, rgba(244, 211, 94, 0.4)) !important;
2126
+ white-space: break-spaces !important; /* Prevent horizontal scrollbar that breaks alignment */
2127
+ }
2128
+
2129
+ /* Code inside pre blocks - remove background */
2130
+ .overtype-wrapper .overtype-preview pre code {
2131
+ background: transparent !important;
2132
+ color: var(--code, #0d3b66) !important;
2133
+ font-family: ${fontFamily} !important; /* Match textarea font exactly for alignment */
2134
+ }
2135
+
2136
+ /* Blockquotes */
2137
+ .overtype-wrapper .overtype-preview .blockquote {
2138
+ color: var(--blockquote, #5a7a9b) !important;
2139
+ padding: 0 !important;
2140
+ margin: 0 !important;
2141
+ border: none !important;
2142
+ }
2143
+
2144
+ /* Links */
2145
+ .overtype-wrapper .overtype-preview a {
2146
+ color: var(--link, #0d3b66) !important;
2147
+ text-decoration: underline !important;
2148
+ font-weight: normal !important;
2149
+ }
2150
+
2151
+ .overtype-wrapper .overtype-preview a:hover {
2152
+ text-decoration: underline !important;
2153
+ color: var(--link, #0d3b66) !important;
2154
+ }
2155
+
2156
+ /* Lists - no list styling */
2157
+ .overtype-wrapper .overtype-preview ul,
2158
+ .overtype-wrapper .overtype-preview ol {
2159
+ list-style: none !important;
2160
+ margin: 0 !important;
2161
+ padding: 0 !important;
2162
+ }
2163
+
2164
+
2165
+ /* Horizontal rules */
2166
+ .overtype-wrapper .overtype-preview hr {
2167
+ border: none !important;
2168
+ color: var(--hr, #5a7a9b) !important;
2169
+ margin: 0 !important;
2170
+ padding: 0 !important;
2171
+ }
2172
+
2173
+ .overtype-wrapper .overtype-preview .hr-marker {
2174
+ color: var(--hr, #5a7a9b) !important;
2175
+ opacity: 0.6 !important;
2176
+ }
2177
+
2178
+ /* Code fence markers - with background when not in code block */
2179
+ .overtype-wrapper .overtype-preview .code-fence {
2180
+ color: var(--code, #0d3b66) !important;
2181
+ background: var(--code-bg, rgba(244, 211, 94, 0.4)) !important;
2182
+ }
2183
+
2184
+ /* Code block lines - background for entire code block */
2185
+ .overtype-wrapper .overtype-preview .code-block-line {
2186
+ background: var(--code-bg, rgba(244, 211, 94, 0.4)) !important;
2187
+ }
2188
+
2189
+ /* Remove background from code fence when inside code block line */
2190
+ .overtype-wrapper .overtype-preview .code-block-line .code-fence {
2191
+ background: transparent !important;
2192
+ }
2193
+
2194
+ /* Raw markdown line */
2195
+ .overtype-wrapper .overtype-preview .raw-line {
2196
+ color: var(--raw-line, #5a7a9b) !important;
2197
+ font-style: normal !important;
2198
+ font-weight: normal !important;
2199
+ }
2200
+
2201
+ /* Syntax markers */
2202
+ .overtype-wrapper .overtype-preview .syntax-marker {
2203
+ color: var(--syntax-marker, rgba(13, 59, 102, 0.52)) !important;
2204
+ opacity: 0.7 !important;
2205
+ }
2206
+
2207
+ /* List markers */
2208
+ .overtype-wrapper .overtype-preview .list-marker {
2209
+ color: var(--list-marker, #ee964b) !important;
2210
+ }
2211
+
2212
+ /* Stats bar */
2213
+
2214
+ /* Stats bar - positioned by grid, not absolute */
2215
+ .overtype-stats {
2216
+ height: 40px !important;
2217
+ padding: 0 20px !important;
2218
+ background: #f8f9fa !important;
2219
+ border-top: 1px solid #e0e0e0 !important;
2220
+ display: flex !important;
2221
+ justify-content: space-between !important;
2222
+ align-items: center !important;
2223
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
2224
+ font-size: 0.85rem !important;
2225
+ color: #666 !important;
2226
+ grid-row: 3 !important; /* Always third row in grid */
2227
+ }
2228
+
2229
+ /* Dark theme stats bar */
2230
+ .overtype-container[data-theme="cave"] .overtype-stats {
2231
+ background: var(--bg-secondary, #1D2D3E) !important;
2232
+ border-top: 1px solid rgba(197, 221, 232, 0.1) !important;
2233
+ color: var(--text, #c5dde8) !important;
2234
+ }
2235
+
2236
+ .overtype-stats .overtype-stat {
2237
+ display: flex !important;
2238
+ align-items: center !important;
2239
+ gap: 5px !important;
2240
+ white-space: nowrap !important;
2241
+ }
2242
+
2243
+ .overtype-stats .live-dot {
2244
+ width: 8px !important;
2245
+ height: 8px !important;
2246
+ background: #4caf50 !important;
2247
+ border-radius: 50% !important;
2248
+ animation: overtype-pulse 2s infinite !important;
2249
+ }
2250
+
2251
+ @keyframes overtype-pulse {
2252
+ 0%, 100% { opacity: 1; transform: scale(1); }
2253
+ 50% { opacity: 0.6; transform: scale(1.2); }
2254
+ }
2255
+
2256
+
2257
+ /* Toolbar Styles */
2258
+ .overtype-toolbar {
2259
+ display: flex !important;
2260
+ align-items: center !important;
2261
+ gap: 4px !important;
2262
+ padding: 8px !important; /* Override reset */
2263
+ background: var(--toolbar-bg, var(--bg-primary, #f8f9fa)) !important; /* Override reset */
2264
+ overflow-x: auto !important; /* Allow horizontal scrolling */
2265
+ overflow-y: hidden !important; /* Hide vertical overflow */
2266
+ -webkit-overflow-scrolling: touch !important;
2267
+ flex-shrink: 0 !important;
2268
+ height: auto !important;
2269
+ grid-row: 1 !important; /* Always first row in grid */
2270
+ position: relative !important; /* Override reset */
2271
+ z-index: 100 !important; /* Ensure toolbar is above wrapper */
2272
+ scrollbar-width: thin; /* Thin scrollbar on Firefox */
2273
+ }
2274
+
2275
+ /* Thin scrollbar styling */
2276
+ .overtype-toolbar::-webkit-scrollbar {
2277
+ height: 4px;
2278
+ }
2279
+
2280
+ .overtype-toolbar::-webkit-scrollbar-track {
2281
+ background: transparent;
2282
+ }
2283
+
2284
+ .overtype-toolbar::-webkit-scrollbar-thumb {
2285
+ background: rgba(0, 0, 0, 0.2);
2286
+ border-radius: 2px;
2287
+ }
2288
+
2289
+ .overtype-toolbar-button {
2290
+ display: flex;
2291
+ align-items: center;
2292
+ justify-content: center;
2293
+ width: 32px;
2294
+ height: 32px;
2295
+ padding: 0;
2296
+ border: none;
2297
+ border-radius: 6px;
2298
+ background: transparent;
2299
+ color: var(--toolbar-icon, var(--text-secondary, #666));
2300
+ cursor: pointer;
2301
+ transition: all 0.2s ease;
2302
+ flex-shrink: 0;
2303
+ }
2304
+
2305
+ .overtype-toolbar-button svg {
2306
+ width: 20px;
2307
+ height: 20px;
2308
+ fill: currentColor;
2309
+ }
2310
+
2311
+ .overtype-toolbar-button:hover {
2312
+ background: var(--toolbar-hover, var(--bg-secondary, #e9ecef));
2313
+ color: var(--toolbar-icon, var(--text-primary, #333));
2314
+ }
2315
+
2316
+ .overtype-toolbar-button:active {
2317
+ transform: scale(0.95);
2318
+ }
2319
+
2320
+ .overtype-toolbar-button.active {
2321
+ background: var(--toolbar-active, var(--primary, #007bff));
2322
+ color: var(--toolbar-icon, var(--text-primary, #333));
2323
+ }
2324
+
2325
+ .overtype-toolbar-button:disabled {
2326
+ opacity: 0.5;
2327
+ cursor: not-allowed;
2328
+ }
2329
+
2330
+ .overtype-toolbar-separator {
2331
+ width: 1px;
2332
+ height: 24px;
2333
+ background: var(--border, #e0e0e0);
2334
+ margin: 0 4px;
2335
+ flex-shrink: 0;
2336
+ }
2337
+
2338
+ /* Adjust wrapper when toolbar is present */
2339
+ .overtype-container .overtype-toolbar + .overtype-wrapper {
2340
+ }
2341
+
2342
+ /* Mobile toolbar adjustments */
2343
+ @media (max-width: 640px) {
2344
+ .overtype-toolbar {
2345
+ padding: 6px;
2346
+ gap: 2px;
2347
+ }
2348
+
2349
+ .overtype-toolbar-button {
2350
+ width: 36px;
2351
+ height: 36px;
2352
+ }
2353
+
2354
+ .overtype-toolbar-separator {
2355
+ margin: 0 2px;
2356
+ }
2357
+ }
2358
+
2359
+ /* Plain mode - hide preview and show textarea text */
2360
+ .overtype-container[data-mode="plain"] .overtype-preview {
2361
+ display: none !important;
2362
+ }
2363
+
2364
+ .overtype-container[data-mode="plain"] .overtype-input {
2365
+ color: var(--text, #0d3b66) !important;
2366
+ /* Use system font stack for better plain text readability */
2367
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
2368
+ "Helvetica Neue", Arial, sans-serif !important;
2369
+ }
2370
+
2371
+ /* Ensure textarea remains transparent in overlay mode */
2372
+ .overtype-container:not([data-mode="plain"]) .overtype-input {
2373
+ color: transparent !important;
2374
+ }
2375
+
2376
+ /* Dropdown menu styles */
2377
+ .overtype-toolbar-button {
2378
+ position: relative !important; /* Override reset - needed for dropdown */
2379
+ }
2380
+
2381
+ .overtype-toolbar-button.dropdown-active {
2382
+ background: var(--toolbar-active, var(--hover-bg, #f0f0f0));
2383
+ }
2384
+
2385
+ .overtype-dropdown-menu {
2386
+ position: fixed !important; /* Fixed positioning relative to viewport */
2387
+ background: var(--bg-secondary, white) !important; /* Override reset */
2388
+ border: 1px solid var(--border, #e0e0e0) !important; /* Override reset */
2389
+ border-radius: 6px;
2390
+ box-shadow: 0 2px 8px rgba(0,0,0,0.1) !important; /* Override reset */
2391
+ z-index: 10000; /* Very high z-index to ensure visibility */
2392
+ min-width: 150px;
2393
+ padding: 4px 0 !important; /* Override reset */
2394
+ /* Position will be set via JavaScript based on button position */
2395
+ }
2396
+
2397
+ .overtype-dropdown-item {
2398
+ display: flex;
2399
+ align-items: center;
2400
+ width: 100%;
2401
+ padding: 8px 12px;
2402
+ border: none;
2403
+ background: none;
2404
+ text-align: left;
2405
+ cursor: pointer;
2406
+ font-size: 14px;
2407
+ color: var(--text, #333);
2408
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
2409
+ }
2410
+
2411
+ .overtype-dropdown-item:hover {
2412
+ background: var(--hover-bg, #f0f0f0);
2413
+ }
2414
+
2415
+ .overtype-dropdown-item.active {
2416
+ font-weight: 600;
2417
+ }
2418
+
2419
+ .overtype-dropdown-check {
2420
+ width: 16px;
2421
+ margin-right: 8px;
2422
+ color: var(--h1, #007bff);
2423
+ }
2424
+
2425
+ .overtype-dropdown-icon {
2426
+ width: 20px;
2427
+ margin-right: 8px;
2428
+ text-align: center;
2429
+ }
2430
+
2431
+ /* Preview mode styles */
2432
+ .overtype-container[data-mode="preview"] .overtype-input {
2433
+ display: none !important;
2434
+ }
2435
+
2436
+ .overtype-container[data-mode="preview"] .overtype-preview {
2437
+ pointer-events: auto !important;
2438
+ user-select: text !important;
2439
+ cursor: text !important;
2440
+ }
2441
+
2442
+ /* Hide syntax markers in preview mode */
2443
+ .overtype-container[data-mode="preview"] .syntax-marker {
2444
+ display: none !important;
2445
+ }
2446
+
2447
+ /* Hide URL part of links in preview mode - extra specificity */
2448
+ .overtype-container[data-mode="preview"] .syntax-marker.url-part,
2449
+ .overtype-container[data-mode="preview"] .url-part {
2450
+ display: none !important;
2451
+ }
2452
+
2453
+ /* Hide all syntax markers inside links too */
2454
+ .overtype-container[data-mode="preview"] a .syntax-marker {
2455
+ display: none !important;
2456
+ }
2457
+
2458
+ /* Headers - restore proper sizing in preview mode */
2459
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview h1,
2460
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview h2,
2461
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview h3 {
2462
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
2463
+ font-weight: 600 !important;
2464
+ margin: 0 !important;
2465
+ display: block !important;
2466
+ color: inherit !important; /* Use parent text color */
2467
+ line-height: 1 !important; /* Tight line height for headings */
2468
+ }
2469
+
2470
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview h1 {
2471
+ font-size: 2em !important;
2472
+ }
2473
+
2474
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview h2 {
2475
+ font-size: 1.5em !important;
2476
+ }
2477
+
2478
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview h3 {
2479
+ font-size: 1.17em !important;
2480
+ }
2481
+
2482
+ /* Lists - restore list styling in preview mode */
2483
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview ul {
2484
+ display: block !important;
2485
+ list-style: disc !important;
2486
+ padding-left: 2em !important;
2487
+ margin: 1em 0 !important;
2488
+ }
2489
+
2490
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview ol {
2491
+ display: block !important;
2492
+ list-style: decimal !important;
2493
+ padding-left: 2em !important;
2494
+ margin: 1em 0 !important;
2495
+ }
2496
+
2497
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview li {
2498
+ display: list-item !important;
2499
+ margin: 0 !important;
2500
+ padding: 0 !important;
2501
+ }
2502
+
2503
+ /* Task list checkboxes - only in preview mode */
2504
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview li.task-list {
2505
+ list-style: none !important;
2506
+ position: relative !important;
2507
+ }
2508
+
2509
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview li.task-list input[type="checkbox"] {
2510
+ margin-right: 0.5em !important;
2511
+ cursor: default !important;
2512
+ vertical-align: middle !important;
2513
+ }
2514
+
2515
+ /* Task list in normal mode - keep syntax visible */
2516
+ .overtype-container:not([data-mode="preview"]) .overtype-wrapper .overtype-preview li.task-list {
2517
+ list-style: none !important;
2518
+ }
2519
+
2520
+ .overtype-container:not([data-mode="preview"]) .overtype-wrapper .overtype-preview li.task-list .syntax-marker {
2521
+ color: var(--syntax, #999999) !important;
2522
+ font-weight: normal !important;
2523
+ }
2524
+
2525
+ /* Links - make clickable in preview mode */
2526
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview a {
2527
+ pointer-events: auto !important;
2528
+ cursor: pointer !important;
2529
+ color: var(--link, #0066cc) !important;
2530
+ text-decoration: underline !important;
2531
+ }
2532
+
2533
+ /* Code blocks - proper pre/code styling in preview mode */
2534
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview pre.code-block {
2535
+ background: #2d2d2d !important;
2536
+ color: #f8f8f2 !important;
2537
+ padding: 1.2em !important;
2538
+ border-radius: 3px !important;
2539
+ overflow-x: auto !important;
2540
+ margin: 0 !important;
2541
+ display: block !important;
2542
+ }
2543
+
2544
+ /* Cave theme code block background in preview mode */
2545
+ .overtype-container[data-theme="cave"][data-mode="preview"] .overtype-wrapper .overtype-preview pre.code-block {
2546
+ background: #11171F !important;
2547
+ }
2548
+
2549
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview pre.code-block code {
2550
+ background: transparent !important;
2551
+ color: inherit !important;
2552
+ padding: 0 !important;
2553
+ font-family: ${fontFamily} !important;
2554
+ font-size: 0.9em !important;
2555
+ line-height: 1.4 !important;
2556
+ }
2557
+
2558
+ /* Hide old code block lines and fences in preview mode */
2559
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview .code-block-line {
2560
+ display: none !important;
2561
+ }
2562
+
2563
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview .code-fence {
2564
+ display: none !important;
2565
+ }
2566
+
2567
+ /* Blockquotes - enhanced styling in preview mode */
2568
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview .blockquote {
2569
+ display: block !important;
2570
+ border-left: 4px solid var(--blockquote, #ddd) !important;
2571
+ padding-left: 1em !important;
2572
+ margin: 1em 0 !important;
2573
+ font-style: italic !important;
2574
+ }
2575
+
2576
+ /* Typography improvements in preview mode */
2577
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview {
2578
+ font-family: Georgia, 'Times New Roman', serif !important;
2579
+ font-size: 16px !important;
2580
+ line-height: 1.8 !important;
2581
+ color: var(--text, #333) !important; /* Consistent text color */
2582
+ }
2583
+
2584
+ /* Inline code in preview mode - keep monospace */
2585
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview code {
2586
+ font-family: ${fontFamily} !important;
2587
+ font-size: 0.9em !important;
2588
+ background: rgba(135, 131, 120, 0.15) !important;
2589
+ padding: 0.2em 0.4em !important;
2590
+ border-radius: 3px !important;
2591
+ }
2592
+
2593
+ /* Strong and em elements in preview mode */
2594
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview strong {
2595
+ font-weight: 700 !important;
2596
+ color: inherit !important; /* Use parent text color */
2597
+ }
2598
+
2599
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview em {
2600
+ font-style: italic !important;
2601
+ color: inherit !important; /* Use parent text color */
2602
+ }
2603
+
2604
+ /* HR in preview mode */
2605
+ .overtype-container[data-mode="preview"] .overtype-wrapper .overtype-preview .hr-marker {
2606
+ display: block !important;
2607
+ border-top: 2px solid var(--hr, #ddd) !important;
2608
+ text-indent: -9999px !important;
2609
+ height: 2px !important;
2610
+ }
2611
+
2612
+ /* Link Tooltip - CSS Anchor Positioning */
2613
+ @supports (position-anchor: --x) and (position-area: center) {
2614
+ .overtype-link-tooltip {
2615
+ position: absolute;
2616
+ position-anchor: var(--target-anchor, --link-0);
2617
+ position-area: block-end center;
2618
+ margin-top: 8px !important;
2619
+
2620
+ background: #333 !important;
2621
+ color: white !important;
2622
+ padding: 6px 10px !important;
2623
+ border-radius: 16px !important;
2624
+ font-size: 12px !important;
2625
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
2626
+ display: none !important;
2627
+ z-index: 10000 !important;
2628
+ cursor: pointer !important;
2629
+ box-shadow: 0 2px 8px rgba(0,0,0,0.3) !important;
2630
+ max-width: 300px !important;
2631
+ white-space: nowrap !important;
2632
+ overflow: hidden !important;
2633
+ text-overflow: ellipsis !important;
2634
+
2635
+ position-try: most-width block-end inline-end, flip-inline, block-start center;
2636
+ position-visibility: anchors-visible;
2637
+ }
2638
+
2639
+ .overtype-link-tooltip.visible {
2640
+ display: flex !important;
2641
+ }
2642
+ }
2643
+
2644
+ ${mobileStyles}
2645
+ `;
2646
+ }
2647
+
2648
+ // src/toolbar.js
2649
+ var Toolbar = class {
2650
+ constructor(editor, options = {}) {
2651
+ this.editor = editor;
2652
+ this.container = null;
2653
+ this.buttons = {};
2654
+ this.toolbarButtons = options.toolbarButtons || [];
2655
+ }
2656
+ /**
2657
+ * Create and render toolbar
2658
+ */
2659
+ create() {
2660
+ this.container = document.createElement("div");
2661
+ this.container.className = "overtype-toolbar";
2662
+ this.container.setAttribute("role", "toolbar");
2663
+ this.container.setAttribute("aria-label", "Formatting toolbar");
2664
+ this.toolbarButtons.forEach((buttonConfig) => {
2665
+ if (buttonConfig.name === "separator") {
2666
+ const separator = this.createSeparator();
2667
+ this.container.appendChild(separator);
2668
+ } else {
2669
+ const button = this.createButton(buttonConfig);
2670
+ this.buttons[buttonConfig.name] = button;
2671
+ this.container.appendChild(button);
2672
+ }
2673
+ });
2674
+ this.editor.wrapper.insertBefore(this.container, this.editor.wrapper.firstChild);
2675
+ }
2676
+ /**
2677
+ * Create a toolbar separator
2678
+ */
2679
+ createSeparator() {
2680
+ const separator = document.createElement("div");
2681
+ separator.className = "overtype-toolbar-separator";
2682
+ separator.setAttribute("role", "separator");
2683
+ return separator;
2684
+ }
2685
+ /**
2686
+ * Create a toolbar button
2687
+ */
2688
+ createButton(buttonConfig) {
2689
+ const button = document.createElement("button");
2690
+ button.className = "overtype-toolbar-button";
2691
+ button.type = "button";
2692
+ button.setAttribute("data-button", buttonConfig.name);
2693
+ button.title = buttonConfig.title || "";
2694
+ button.setAttribute("aria-label", buttonConfig.title || buttonConfig.name);
2695
+ button.innerHTML = this.sanitizeSVG(buttonConfig.icon || "");
2696
+ if (buttonConfig.name === "viewMode") {
2697
+ button.classList.add("has-dropdown");
2698
+ button.dataset.dropdown = "true";
2699
+ button.addEventListener("click", (e) => {
2700
+ e.preventDefault();
2701
+ this.toggleViewModeDropdown(button);
2702
+ });
2703
+ return button;
2704
+ }
2705
+ button._clickHandler = async (e) => {
2706
+ e.preventDefault();
2707
+ this.editor.textarea.focus();
2708
+ try {
2709
+ if (buttonConfig.action) {
2710
+ await buttonConfig.action({
2711
+ editor: this.editor,
2712
+ getValue: () => this.editor.getValue(),
2713
+ setValue: (value) => this.editor.setValue(value),
2714
+ event: e
2715
+ });
2716
+ }
2717
+ } catch (error) {
2718
+ console.error(`Button "${buttonConfig.name}" error:`, error);
2719
+ this.editor.wrapper.dispatchEvent(new CustomEvent("button-error", {
2720
+ detail: { buttonName: buttonConfig.name, error }
2721
+ }));
2722
+ button.classList.add("button-error");
2723
+ button.style.animation = "buttonError 0.3s";
2724
+ setTimeout(() => {
2725
+ button.classList.remove("button-error");
2726
+ button.style.animation = "";
2727
+ }, 300);
2728
+ }
2729
+ };
2730
+ button.addEventListener("click", button._clickHandler);
2731
+ return button;
2732
+ }
2733
+ /**
2734
+ * Sanitize SVG to prevent XSS
2735
+ */
2736
+ sanitizeSVG(svg) {
2737
+ if (typeof svg !== "string")
2738
+ return "";
2739
+ const cleaned = svg.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "").replace(/\son\w+\s*=\s*["'][^"']*["']/gi, "").replace(/\son\w+\s*=\s*[^\s>]*/gi, "");
2740
+ return cleaned;
2741
+ }
2742
+ /**
2743
+ * Toggle view mode dropdown (internal implementation)
2744
+ * Not exposed to users - viewMode button behavior is fixed
2745
+ */
2746
+ toggleViewModeDropdown(button) {
2747
+ const existingDropdown = document.querySelector(".overtype-dropdown-menu");
2748
+ if (existingDropdown) {
2749
+ existingDropdown.remove();
2750
+ button.classList.remove("dropdown-active");
2751
+ return;
2752
+ }
2753
+ button.classList.add("dropdown-active");
2754
+ const dropdown = this.createViewModeDropdown(button);
2755
+ const rect = button.getBoundingClientRect();
2756
+ dropdown.style.position = "absolute";
2757
+ dropdown.style.top = `${rect.bottom + 5}px`;
2758
+ dropdown.style.left = `${rect.left}px`;
2759
+ document.body.appendChild(dropdown);
2760
+ this.handleDocumentClick = (e) => {
2761
+ if (!dropdown.contains(e.target) && !button.contains(e.target)) {
2762
+ dropdown.remove();
2763
+ button.classList.remove("dropdown-active");
2764
+ document.removeEventListener("click", this.handleDocumentClick);
2765
+ }
2766
+ };
2767
+ setTimeout(() => {
2768
+ document.addEventListener("click", this.handleDocumentClick);
2769
+ }, 0);
2770
+ }
2771
+ /**
2772
+ * Create view mode dropdown menu (internal implementation)
2773
+ */
2774
+ createViewModeDropdown(button) {
2775
+ const dropdown = document.createElement("div");
2776
+ dropdown.className = "overtype-dropdown-menu";
2777
+ const items = [
2778
+ { id: "normal", label: "Normal Edit", icon: "\u2713" },
2779
+ { id: "plain", label: "Plain Textarea", icon: "\u2713" },
2780
+ { id: "preview", label: "Preview Mode", icon: "\u2713" }
2781
+ ];
2782
+ const currentMode = this.editor.container.dataset.mode || "normal";
2783
+ items.forEach((item) => {
2784
+ const menuItem = document.createElement("button");
2785
+ menuItem.className = "overtype-dropdown-item";
2786
+ menuItem.type = "button";
2787
+ menuItem.textContent = item.label;
2788
+ if (item.id === currentMode) {
2789
+ menuItem.classList.add("active");
2790
+ menuItem.setAttribute("aria-current", "true");
2791
+ const checkmark = document.createElement("span");
2792
+ checkmark.className = "overtype-dropdown-icon";
2793
+ checkmark.textContent = item.icon;
2794
+ menuItem.prepend(checkmark);
2795
+ }
2796
+ menuItem.addEventListener("click", (e) => {
2797
+ e.preventDefault();
2798
+ switch (item.id) {
2799
+ case "plain":
2800
+ this.editor.showPlainTextarea();
2801
+ break;
2802
+ case "preview":
2803
+ this.editor.showPreviewMode();
2804
+ break;
2805
+ case "normal":
2806
+ default:
2807
+ this.editor.showNormalEditMode();
2808
+ break;
2809
+ }
2810
+ dropdown.remove();
2811
+ button.classList.remove("dropdown-active");
2812
+ document.removeEventListener("click", this.handleDocumentClick);
2813
+ });
2814
+ dropdown.appendChild(menuItem);
2815
+ });
2816
+ return dropdown;
2817
+ }
2818
+ /**
2819
+ * Update active states of toolbar buttons
2820
+ */
2821
+ updateButtonStates() {
2822
+ var _a;
2823
+ try {
2824
+ const activeFormats = ((_a = getActiveFormats2) == null ? void 0 : _a(
2825
+ this.editor.textarea,
2826
+ this.editor.textarea.selectionStart
2827
+ )) || [];
2828
+ Object.entries(this.buttons).forEach(([name, button]) => {
2829
+ if (name === "viewMode")
2830
+ return;
2831
+ let isActive = false;
2832
+ switch (name) {
2833
+ case "bold":
2834
+ isActive = activeFormats.includes("bold");
2835
+ break;
2836
+ case "italic":
2837
+ isActive = activeFormats.includes("italic");
2838
+ break;
2839
+ case "code":
2840
+ isActive = false;
2841
+ break;
2842
+ case "bulletList":
2843
+ isActive = activeFormats.includes("bullet-list");
2844
+ break;
2845
+ case "orderedList":
2846
+ isActive = activeFormats.includes("numbered-list");
2847
+ break;
2848
+ case "taskList":
2849
+ isActive = activeFormats.includes("task-list");
2850
+ break;
2851
+ case "quote":
2852
+ isActive = activeFormats.includes("quote");
2853
+ break;
2854
+ case "h1":
2855
+ isActive = activeFormats.includes("header");
2856
+ break;
2857
+ case "h2":
2858
+ isActive = activeFormats.includes("header-2");
2859
+ break;
2860
+ case "h3":
2861
+ isActive = activeFormats.includes("header-3");
2862
+ break;
2863
+ }
2864
+ button.classList.toggle("active", isActive);
2865
+ button.setAttribute("aria-pressed", isActive.toString());
2866
+ });
2867
+ } catch (error) {
2868
+ }
2869
+ }
2870
+ /**
2871
+ * Destroy toolbar and cleanup
2872
+ */
2873
+ destroy() {
2874
+ if (this.container) {
2875
+ if (this.handleDocumentClick) {
2876
+ document.removeEventListener("click", this.handleDocumentClick);
2877
+ }
2878
+ Object.values(this.buttons).forEach((button) => {
2879
+ if (button._clickHandler) {
2880
+ button.removeEventListener("click", button._clickHandler);
2881
+ delete button._clickHandler;
2882
+ }
2883
+ });
2884
+ this.container.remove();
2885
+ this.container = null;
2886
+ this.buttons = {};
2887
+ }
2888
+ }
2889
+ };
2890
+
2891
+ // src/link-tooltip.js
2892
+ var LinkTooltip = class {
2893
+ constructor(editor) {
2894
+ this.editor = editor;
2895
+ this.tooltip = null;
2896
+ this.currentLink = null;
2897
+ this.hideTimeout = null;
2898
+ this.visibilityChangeHandler = null;
2899
+ this.init();
2900
+ }
2901
+ init() {
2902
+ this.createTooltip();
2903
+ this.editor.textarea.addEventListener("selectionchange", () => this.checkCursorPosition());
2904
+ this.editor.textarea.addEventListener("keyup", (e) => {
2905
+ if (e.key.includes("Arrow") || e.key === "Home" || e.key === "End") {
2906
+ this.checkCursorPosition();
2907
+ }
2908
+ });
2909
+ this.editor.textarea.addEventListener("input", () => this.hide());
2910
+ this.editor.textarea.addEventListener("scroll", () => this.hide());
2911
+ this.editor.textarea.addEventListener("blur", () => this.hide());
2912
+ this.visibilityChangeHandler = () => {
2913
+ if (document.hidden) {
2914
+ this.hide();
2915
+ }
2916
+ };
2917
+ document.addEventListener("visibilitychange", this.visibilityChangeHandler);
2918
+ this.tooltip.addEventListener("mouseenter", () => this.cancelHide());
2919
+ this.tooltip.addEventListener("mouseleave", () => this.scheduleHide());
2920
+ }
2921
+ createTooltip() {
2922
+ this.tooltip = document.createElement("div");
2923
+ this.tooltip.className = "overtype-link-tooltip";
2924
+ this.tooltip.innerHTML = `
2925
+ <span style="display: flex; align-items: center; gap: 6px;">
2926
+ <svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor" style="flex-shrink: 0;">
2927
+ <path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"></path>
2928
+ <path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"></path>
2929
+ </svg>
2930
+ <span class="overtype-link-tooltip-url"></span>
2931
+ </span>
2932
+ `;
2933
+ this.tooltip.addEventListener("click", (e) => {
2934
+ e.preventDefault();
2935
+ e.stopPropagation();
2936
+ if (this.currentLink) {
2937
+ window.open(this.currentLink.url, "_blank");
2938
+ this.hide();
2939
+ }
2940
+ });
2941
+ this.editor.container.appendChild(this.tooltip);
2942
+ }
2943
+ checkCursorPosition() {
2944
+ const cursorPos = this.editor.textarea.selectionStart;
2945
+ const text = this.editor.textarea.value;
2946
+ const linkInfo = this.findLinkAtPosition(text, cursorPos);
2947
+ if (linkInfo) {
2948
+ if (!this.currentLink || this.currentLink.url !== linkInfo.url || this.currentLink.index !== linkInfo.index) {
2949
+ this.show(linkInfo);
2950
+ }
2951
+ } else {
2952
+ this.scheduleHide();
2953
+ }
2954
+ }
2955
+ findLinkAtPosition(text, position) {
2956
+ const linkRegex = /\[([^\]]+)\]\(([^)]+)\)/g;
2957
+ let match;
2958
+ let linkIndex = 0;
2959
+ while ((match = linkRegex.exec(text)) !== null) {
2960
+ const start = match.index;
2961
+ const end = match.index + match[0].length;
2962
+ if (position >= start && position <= end) {
2963
+ return {
2964
+ text: match[1],
2965
+ url: match[2],
2966
+ index: linkIndex,
2967
+ start,
2968
+ end
2969
+ };
2970
+ }
2971
+ linkIndex++;
2972
+ }
2973
+ return null;
2974
+ }
2975
+ show(linkInfo) {
2976
+ this.currentLink = linkInfo;
2977
+ this.cancelHide();
2978
+ const urlSpan = this.tooltip.querySelector(".overtype-link-tooltip-url");
2979
+ urlSpan.textContent = linkInfo.url;
2980
+ this.tooltip.style.setProperty("--target-anchor", `--link-${linkInfo.index}`);
2981
+ this.tooltip.classList.add("visible");
2982
+ }
2983
+ hide() {
2984
+ this.tooltip.classList.remove("visible");
2985
+ this.currentLink = null;
2986
+ }
2987
+ scheduleHide() {
2988
+ this.cancelHide();
2989
+ this.hideTimeout = setTimeout(() => this.hide(), 300);
2990
+ }
2991
+ cancelHide() {
2992
+ if (this.hideTimeout) {
2993
+ clearTimeout(this.hideTimeout);
2994
+ this.hideTimeout = null;
2995
+ }
2996
+ }
2997
+ destroy() {
2998
+ this.cancelHide();
2999
+ if (this.visibilityChangeHandler) {
3000
+ document.removeEventListener("visibilitychange", this.visibilityChangeHandler);
3001
+ this.visibilityChangeHandler = null;
3002
+ }
3003
+ if (this.tooltip && this.tooltip.parentNode) {
3004
+ this.tooltip.parentNode.removeChild(this.tooltip);
3005
+ }
3006
+ this.tooltip = null;
3007
+ this.currentLink = null;
3008
+ }
3009
+ };
3010
+
3011
+ // src/icons.js
3012
+ var boldIcon = `<svg viewBox="0 0 18 18">
3013
+ <path stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5,4H9.5A2.5,2.5,0,0,1,12,6.5v0A2.5,2.5,0,0,1,9.5,9H5A0,0,0,0,1,5,9V4A0,0,0,0,1,5,4Z"></path>
3014
+ <path stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5,9h5.5A2.5,2.5,0,0,1,13,11.5v0A2.5,2.5,0,0,1,10.5,14H5a0,0,0,0,1,0,0V9A0,0,0,0,1,5,9Z"></path>
3015
+ </svg>`;
3016
+ var italicIcon = `<svg viewBox="0 0 18 18">
3017
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="7" x2="13" y1="4" y2="4"></line>
3018
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="5" x2="11" y1="14" y2="14"></line>
3019
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="8" x2="10" y1="14" y2="4"></line>
3020
+ </svg>`;
3021
+ var h1Icon = `<svg viewBox="0 0 18 18">
3022
+ <path fill="currentColor" d="M10,4V14a1,1,0,0,1-2,0V10H3v4a1,1,0,0,1-2,0V4A1,1,0,0,1,3,4V8H8V4a1,1,0,0,1,2,0Zm6.06787,9.209H14.98975V7.59863a.54085.54085,0,0,0-.605-.60547h-.62744a1.01119,1.01119,0,0,0-.748.29688L11.645,8.56641a.5435.5435,0,0,0-.022.8584l.28613.30762a.53861.53861,0,0,0,.84717.0332l.09912-.08789a1.2137,1.2137,0,0,0,.2417-.35254h.02246s-.01123.30859-.01123.60547V13.209H12.041a.54085.54085,0,0,0-.605.60547v.43945a.54085.54085,0,0,0,.605.60547h4.02686a.54085.54085,0,0,0,.605-.60547v-.43945A.54085.54085,0,0,0,16.06787,13.209Z"></path>
3023
+ </svg>`;
3024
+ var h2Icon = `<svg viewBox="0 0 18 18">
3025
+ <path fill="currentColor" d="M16.73975,13.81445v.43945a.54085.54085,0,0,1-.605.60547H11.855a.58392.58392,0,0,1-.64893-.60547V14.0127c0-2.90527,3.39941-3.42187,3.39941-4.55469a.77675.77675,0,0,0-.84717-.78125,1.17684,1.17684,0,0,0-.83594.38477c-.2749.26367-.561.374-.85791.13184l-.4292-.34082c-.30811-.24219-.38525-.51758-.1543-.81445a2.97155,2.97155,0,0,1,2.45361-1.17676,2.45393,2.45393,0,0,1,2.68408,2.40918c0,2.45312-3.1792,2.92676-3.27832,3.93848h2.79443A.54085.54085,0,0,1,16.73975,13.81445ZM9,3A.99974.99974,0,0,0,8,4V8H3V4A1,1,0,0,0,1,4V14a1,1,0,0,0,2,0V10H8v4a1,1,0,0,0,2,0V4A.99974.99974,0,0,0,9,3Z"></path>
3026
+ </svg>`;
3027
+ var h3Icon = `<svg viewBox="0 0 18 18">
3028
+ <path fill="currentColor" d="M16.65186,12.30664a2.6742,2.6742,0,0,1-2.915,2.68457,3.96592,3.96592,0,0,1-2.25537-.6709.56007.56007,0,0,1-.13232-.83594L11.64648,13c.209-.34082.48389-.36328.82471-.1543a2.32654,2.32654,0,0,0,1.12256.33008c.71484,0,1.12207-.35156,1.12207-.78125,0-.61523-.61621-.86816-1.46338-.86816H13.2085a.65159.65159,0,0,1-.68213-.41895l-.05518-.10937a.67114.67114,0,0,1,.14307-.78125l.71533-.86914a8.55289,8.55289,0,0,1,.68213-.7373V8.58887a3.93913,3.93913,0,0,1-.748.05469H11.9873a.54085.54085,0,0,1-.605-.60547V7.59863a.54085.54085,0,0,1,.605-.60547h3.75146a.53773.53773,0,0,1,.60547.59375v.17676a1.03723,1.03723,0,0,1-.27539.748L14.74854,10.0293A2.31132,2.31132,0,0,1,16.65186,12.30664ZM9,3A.99974.99974,0,0,0,8,4V8H3V4A1,1,0,0,0,1,4V14a1,1,0,0,0,2,0V10H8v4a1,1,0,0,0,2,0V4A.99974.99974,0,0,0,9,3Z"></path>
3029
+ </svg>`;
3030
+ var linkIcon = `<svg viewBox="0 0 18 18">
3031
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="7" x2="11" y1="7" y2="11"></line>
3032
+ <path stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.9,4.577a3.476,3.476,0,0,1,.36,4.679A3.476,3.476,0,0,1,4.577,8.9C3.185,7.5,2.035,6.4,4.217,4.217S7.5,3.185,8.9,4.577Z"></path>
3033
+ <path stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.423,9.1a3.476,3.476,0,0,0-4.679-.36,3.476,3.476,0,0,0,.36,4.679c1.392,1.392,2.5,2.542,4.679.36S14.815,10.5,13.423,9.1Z"></path>
3034
+ </svg>`;
3035
+ var codeIcon = `<svg viewBox="0 0 18 18">
3036
+ <polyline stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" points="5 7 3 9 5 11"></polyline>
3037
+ <polyline stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" points="13 7 15 9 13 11"></polyline>
3038
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="10" x2="8" y1="5" y2="13"></line>
3039
+ </svg>`;
3040
+ var bulletListIcon = `<svg viewBox="0 0 18 18">
3041
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="6" x2="15" y1="4" y2="4"></line>
3042
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="6" x2="15" y1="9" y2="9"></line>
3043
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="6" x2="15" y1="14" y2="14"></line>
3044
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="3" x2="3" y1="4" y2="4"></line>
3045
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="3" x2="3" y1="9" y2="9"></line>
3046
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="3" x2="3" y1="14" y2="14"></line>
3047
+ </svg>`;
3048
+ var orderedListIcon = `<svg viewBox="0 0 18 18">
3049
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="7" x2="15" y1="4" y2="4"></line>
3050
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="7" x2="15" y1="9" y2="9"></line>
3051
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="7" x2="15" y1="14" y2="14"></line>
3052
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="1" x1="2.5" x2="4.5" y1="5.5" y2="5.5"></line>
3053
+ <path fill="currentColor" d="M3.5,6A0.5,0.5,0,0,1,3,5.5V3.085l-0.276.138A0.5,0.5,0,0,1,2.053,3c-0.124-.247-0.023-0.324.224-0.447l1-.5A0.5,0.5,0,0,1,4,2.5v3A0.5,0.5,0,0,1,3.5,6Z"></path>
3054
+ <path stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M4.5,10.5h-2c0-.234,1.85-1.076,1.85-2.234A0.959,0.959,0,0,0,2.5,8.156"></path>
3055
+ <path stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M2.5,14.846a0.959,0.959,0,0,0,1.85-.109A0.7,0.7,0,0,0,3.75,14a0.688,0.688,0,0,0,.6-0.736,0.959,0.959,0,0,0-1.85-.109"></path>
3056
+ </svg>`;
3057
+ var quoteIcon = `<svg viewBox="2 2 20 20">
3058
+ <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 10.8182L9 10.8182C8.80222 10.8182 8.60888 10.7649 8.44443 10.665C8.27998 10.5651 8.15181 10.4231 8.07612 10.257C8.00043 10.0909 7.98063 9.90808 8.01922 9.73174C8.0578 9.55539 8.15304 9.39341 8.29289 9.26627C8.43275 9.13913 8.61093 9.05255 8.80491 9.01747C8.99889 8.98239 9.19996 9.00039 9.38268 9.0692C9.56541 9.13801 9.72159 9.25453 9.83147 9.40403C9.94135 9.55353 10 9.72929 10 9.90909L10 12.1818C10 12.664 9.78929 13.1265 9.41421 13.4675C9.03914 13.8084 8.53043 14 8 14"></path>
3059
+ <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 10.8182L15 10.8182C14.8022 10.8182 14.6089 10.7649 14.4444 10.665C14.28 10.5651 14.1518 10.4231 14.0761 10.257C14.0004 10.0909 13.9806 9.90808 14.0192 9.73174C14.0578 9.55539 14.153 9.39341 14.2929 9.26627C14.4327 9.13913 14.6109 9.05255 14.8049 9.01747C14.9989 8.98239 15.2 9.00039 15.3827 9.0692C15.5654 9.13801 15.7216 9.25453 15.8315 9.40403C15.9414 9.55353 16 9.72929 16 9.90909L16 12.1818C16 12.664 15.7893 13.1265 15.4142 13.4675C15.0391 13.8084 14.5304 14 14 14"></path>
3060
+ </svg>`;
3061
+ var taskListIcon = `<svg viewBox="0 0 18 18">
3062
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="8" x2="16" y1="4" y2="4"></line>
3063
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="8" x2="16" y1="9" y2="9"></line>
3064
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="8" x2="16" y1="14" y2="14"></line>
3065
+ <rect stroke="currentColor" fill="none" stroke-width="1.5" x="2" y="3" width="3" height="3" rx="0.5"></rect>
3066
+ <rect stroke="currentColor" fill="none" stroke-width="1.5" x="2" y="13" width="3" height="3" rx="0.5"></rect>
3067
+ <polyline stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" points="2.65 9.5 3.5 10.5 5 8.5"></polyline>
3068
+ </svg>`;
3069
+ var eyeIcon = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
3070
+ <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" fill="none"></path>
3071
+ <circle cx="12" cy="12" r="3" fill="none"></circle>
3072
+ </svg>`;
3073
+
3074
+ // src/toolbar-buttons.js
3075
+ var toolbarButtons = {
3076
+ bold: {
3077
+ name: "bold",
3078
+ icon: boldIcon,
3079
+ title: "Bold (Ctrl+B)",
3080
+ action: ({ editor, event }) => {
3081
+ toggleBold(editor.textarea);
3082
+ editor.textarea.dispatchEvent(new Event("input", { bubbles: true }));
3083
+ }
3084
+ },
3085
+ italic: {
3086
+ name: "italic",
3087
+ icon: italicIcon,
3088
+ title: "Italic (Ctrl+I)",
3089
+ action: ({ editor, event }) => {
3090
+ toggleItalic(editor.textarea);
3091
+ editor.textarea.dispatchEvent(new Event("input", { bubbles: true }));
3092
+ }
3093
+ },
3094
+ code: {
3095
+ name: "code",
3096
+ icon: codeIcon,
3097
+ title: "Inline Code",
3098
+ action: ({ editor, event }) => {
3099
+ toggleCode(editor.textarea);
3100
+ editor.textarea.dispatchEvent(new Event("input", { bubbles: true }));
3101
+ }
3102
+ },
3103
+ separator: {
3104
+ name: "separator"
3105
+ // No icon, title, or action - special separator element
3106
+ },
3107
+ link: {
3108
+ name: "link",
3109
+ icon: linkIcon,
3110
+ title: "Insert Link",
3111
+ action: ({ editor, event }) => {
3112
+ insertLink(editor.textarea);
3113
+ editor.textarea.dispatchEvent(new Event("input", { bubbles: true }));
3114
+ }
3115
+ },
3116
+ h1: {
3117
+ name: "h1",
3118
+ icon: h1Icon,
3119
+ title: "Heading 1",
3120
+ action: ({ editor, event }) => {
3121
+ toggleH1(editor.textarea);
3122
+ editor.textarea.dispatchEvent(new Event("input", { bubbles: true }));
3123
+ }
3124
+ },
3125
+ h2: {
3126
+ name: "h2",
3127
+ icon: h2Icon,
3128
+ title: "Heading 2",
3129
+ action: ({ editor, event }) => {
3130
+ toggleH2(editor.textarea);
3131
+ editor.textarea.dispatchEvent(new Event("input", { bubbles: true }));
3132
+ }
3133
+ },
3134
+ h3: {
3135
+ name: "h3",
3136
+ icon: h3Icon,
3137
+ title: "Heading 3",
3138
+ action: ({ editor, event }) => {
3139
+ toggleH3(editor.textarea);
3140
+ editor.textarea.dispatchEvent(new Event("input", { bubbles: true }));
3141
+ }
3142
+ },
3143
+ bulletList: {
3144
+ name: "bulletList",
3145
+ icon: bulletListIcon,
3146
+ title: "Bullet List",
3147
+ action: ({ editor, event }) => {
3148
+ toggleBulletList(editor.textarea);
3149
+ editor.textarea.dispatchEvent(new Event("input", { bubbles: true }));
3150
+ }
3151
+ },
3152
+ orderedList: {
3153
+ name: "orderedList",
3154
+ icon: orderedListIcon,
3155
+ title: "Numbered List",
3156
+ action: ({ editor, event }) => {
3157
+ toggleNumberedList(editor.textarea);
3158
+ editor.textarea.dispatchEvent(new Event("input", { bubbles: true }));
3159
+ }
3160
+ },
3161
+ taskList: {
3162
+ name: "taskList",
3163
+ icon: taskListIcon,
3164
+ title: "Task List",
3165
+ action: ({ editor, event }) => {
3166
+ if (toggleTaskList) {
3167
+ toggleTaskList(editor.textarea);
3168
+ editor.textarea.dispatchEvent(new Event("input", { bubbles: true }));
3169
+ }
3170
+ }
3171
+ },
3172
+ quote: {
3173
+ name: "quote",
3174
+ icon: quoteIcon,
3175
+ title: "Quote",
3176
+ action: ({ editor, event }) => {
3177
+ toggleQuote(editor.textarea);
3178
+ editor.textarea.dispatchEvent(new Event("input", { bubbles: true }));
3179
+ }
3180
+ },
3181
+ viewMode: {
3182
+ name: "viewMode",
3183
+ icon: eyeIcon,
3184
+ title: "View mode"
3185
+ // Special: handled internally by Toolbar class as dropdown
3186
+ // No action property - dropdown behavior is internal
3187
+ }
3188
+ };
3189
+ var defaultToolbarButtons = [
3190
+ toolbarButtons.bold,
3191
+ toolbarButtons.italic,
3192
+ toolbarButtons.code,
3193
+ toolbarButtons.separator,
3194
+ toolbarButtons.link,
3195
+ toolbarButtons.separator,
3196
+ toolbarButtons.h1,
3197
+ toolbarButtons.h2,
3198
+ toolbarButtons.h3,
3199
+ toolbarButtons.separator,
3200
+ toolbarButtons.bulletList,
3201
+ toolbarButtons.orderedList,
3202
+ toolbarButtons.taskList,
3203
+ toolbarButtons.separator,
3204
+ toolbarButtons.quote,
3205
+ toolbarButtons.separator,
3206
+ toolbarButtons.viewMode
3207
+ ];
3208
+
3209
+ // src/overtype.js
3210
+ var _OverType = class _OverType {
3211
+ /**
3212
+ * Constructor - Always returns an array of instances
3213
+ * @param {string|Element|NodeList|Array} target - Target element(s)
3214
+ * @param {Object} options - Configuration options
3215
+ * @returns {Array} Array of OverType instances
3216
+ */
3217
+ constructor(target, options = {}) {
3218
+ let elements;
3219
+ if (typeof target === "string") {
3220
+ elements = document.querySelectorAll(target);
3221
+ if (elements.length === 0) {
3222
+ throw new Error(`No elements found for selector: ${target}`);
3223
+ }
3224
+ elements = Array.from(elements);
3225
+ } else if (target instanceof Element) {
3226
+ elements = [target];
3227
+ } else if (target instanceof NodeList) {
3228
+ elements = Array.from(target);
3229
+ } else if (Array.isArray(target)) {
3230
+ elements = target;
3231
+ } else {
3232
+ throw new Error("Invalid target: must be selector string, Element, NodeList, or Array");
3233
+ }
3234
+ const instances = elements.map((element) => {
3235
+ if (element.overTypeInstance) {
3236
+ element.overTypeInstance.reinit(options);
3237
+ return element.overTypeInstance;
3238
+ }
3239
+ const instance = Object.create(_OverType.prototype);
3240
+ instance._init(element, options);
3241
+ element.overTypeInstance = instance;
3242
+ _OverType.instances.set(element, instance);
3243
+ return instance;
3244
+ });
3245
+ return instances;
3246
+ }
3247
+ /**
3248
+ * Internal initialization
3249
+ * @private
3250
+ */
3251
+ _init(element, options = {}) {
3252
+ this.element = element;
3253
+ this.instanceTheme = options.theme || null;
3254
+ this.options = this._mergeOptions(options);
3255
+ this.instanceId = ++_OverType.instanceCount;
3256
+ this.initialized = false;
3257
+ _OverType.injectStyles();
3258
+ _OverType.initGlobalListeners();
3259
+ const container = element.querySelector(".overtype-container");
3260
+ const wrapper = element.querySelector(".overtype-wrapper");
3261
+ if (container || wrapper) {
3262
+ this._recoverFromDOM(container, wrapper);
3263
+ } else {
3264
+ this._buildFromScratch();
3265
+ }
3266
+ this.shortcuts = new ShortcutsManager(this);
3267
+ this.linkTooltip = new LinkTooltip(this);
3268
+ this.initialized = true;
3269
+ if (this.options.onChange) {
3270
+ this.options.onChange(this.getValue(), this);
3271
+ }
3272
+ }
3273
+ /**
3274
+ * Merge user options with defaults
3275
+ * @private
3276
+ */
3277
+ _mergeOptions(options) {
3278
+ const defaults = {
3279
+ // Typography
3280
+ fontSize: "14px",
3281
+ lineHeight: 1.6,
3282
+ /* System-first, guaranteed monospaced; avoids Android 'ui-monospace' pitfalls */
3283
+ fontFamily: '"SF Mono", SFMono-Regular, Menlo, Monaco, "Cascadia Code", Consolas, "Roboto Mono", "Noto Sans Mono", "Droid Sans Mono", "Ubuntu Mono", "DejaVu Sans Mono", "Liberation Mono", "Courier New", Courier, monospace',
3284
+ padding: "16px",
3285
+ // Mobile styles
3286
+ mobile: {
3287
+ fontSize: "16px",
3288
+ // Prevent zoom on iOS
3289
+ padding: "12px",
3290
+ lineHeight: 1.5
3291
+ },
3292
+ // Native textarea properties
3293
+ textareaProps: {},
3294
+ // Behavior
3295
+ autofocus: false,
3296
+ autoResize: false,
3297
+ // Auto-expand height with content
3298
+ minHeight: "100px",
3299
+ // Minimum height for autoResize mode
3300
+ maxHeight: null,
3301
+ // Maximum height for autoResize mode (null = unlimited)
3302
+ placeholder: "Start typing...",
3303
+ value: "",
3304
+ // Callbacks
3305
+ onChange: null,
3306
+ onKeydown: null,
3307
+ // Features
3308
+ showActiveLineRaw: false,
3309
+ showStats: false,
3310
+ toolbar: false,
3311
+ toolbarButtons: null,
3312
+ // Defaults to defaultToolbarButtons if toolbar: true
3313
+ statsFormatter: null,
3314
+ smartLists: true,
3315
+ // Enable smart list continuation
3316
+ codeHighlighter: null
3317
+ // Per-instance code highlighter
3318
+ };
3319
+ const { theme, colors, ...cleanOptions } = options;
3320
+ return {
3321
+ ...defaults,
3322
+ ...cleanOptions
3323
+ };
3324
+ }
3325
+ /**
3326
+ * Recover from existing DOM structure
3327
+ * @private
3328
+ */
3329
+ _recoverFromDOM(container, wrapper) {
3330
+ if (container && container.classList.contains("overtype-container")) {
3331
+ this.container = container;
3332
+ this.wrapper = container.querySelector(".overtype-wrapper");
3333
+ } else if (wrapper) {
3334
+ this.wrapper = wrapper;
3335
+ this.container = document.createElement("div");
3336
+ this.container.className = "overtype-container";
3337
+ const themeToUse = this.instanceTheme || _OverType.currentTheme || solar;
3338
+ const themeName = typeof themeToUse === "string" ? themeToUse : themeToUse.name;
3339
+ if (themeName) {
3340
+ this.container.setAttribute("data-theme", themeName);
3341
+ }
3342
+ if (this.instanceTheme) {
3343
+ const themeObj = typeof this.instanceTheme === "string" ? getTheme(this.instanceTheme) : this.instanceTheme;
3344
+ if (themeObj && themeObj.colors) {
3345
+ const cssVars = themeToCSSVars(themeObj.colors);
3346
+ this.container.style.cssText += cssVars;
3347
+ }
3348
+ }
3349
+ wrapper.parentNode.insertBefore(this.container, wrapper);
3350
+ this.container.appendChild(wrapper);
3351
+ }
3352
+ if (!this.wrapper) {
3353
+ if (container)
3354
+ container.remove();
3355
+ if (wrapper)
3356
+ wrapper.remove();
3357
+ this._buildFromScratch();
3358
+ return;
3359
+ }
3360
+ this.textarea = this.wrapper.querySelector(".overtype-input");
3361
+ this.preview = this.wrapper.querySelector(".overtype-preview");
3362
+ if (!this.textarea || !this.preview) {
3363
+ this.container.remove();
3364
+ this._buildFromScratch();
3365
+ return;
3366
+ }
3367
+ this.wrapper._instance = this;
3368
+ if (this.options.fontSize) {
3369
+ this.wrapper.style.setProperty("--instance-font-size", this.options.fontSize);
3370
+ }
3371
+ if (this.options.lineHeight) {
3372
+ this.wrapper.style.setProperty("--instance-line-height", String(this.options.lineHeight));
3373
+ }
3374
+ if (this.options.padding) {
3375
+ this.wrapper.style.setProperty("--instance-padding", this.options.padding);
3376
+ }
3377
+ this._configureTextarea();
3378
+ this._applyOptions();
3379
+ }
3380
+ /**
3381
+ * Build editor from scratch
3382
+ * @private
3383
+ */
3384
+ _buildFromScratch() {
3385
+ const content = this._extractContent();
3386
+ this.element.innerHTML = "";
3387
+ this._createDOM();
3388
+ if (content || this.options.value) {
3389
+ this.setValue(content || this.options.value);
3390
+ }
3391
+ this._applyOptions();
3392
+ }
3393
+ /**
3394
+ * Extract content from element
3395
+ * @private
3396
+ */
3397
+ _extractContent() {
3398
+ const textarea = this.element.querySelector(".overtype-input");
3399
+ if (textarea)
3400
+ return textarea.value;
3401
+ return this.element.textContent || "";
3402
+ }
3403
+ /**
3404
+ * Create DOM structure
3405
+ * @private
3406
+ */
3407
+ _createDOM() {
3408
+ this.container = document.createElement("div");
3409
+ this.container.className = "overtype-container";
3410
+ const themeToUse = this.instanceTheme || _OverType.currentTheme || solar;
3411
+ const themeName = typeof themeToUse === "string" ? themeToUse : themeToUse.name;
3412
+ if (themeName) {
3413
+ this.container.setAttribute("data-theme", themeName);
3414
+ }
3415
+ if (this.instanceTheme) {
3416
+ const themeObj = typeof this.instanceTheme === "string" ? getTheme(this.instanceTheme) : this.instanceTheme;
3417
+ if (themeObj && themeObj.colors) {
3418
+ const cssVars = themeToCSSVars(themeObj.colors);
3419
+ this.container.style.cssText += cssVars;
3420
+ }
3421
+ }
3422
+ this.wrapper = document.createElement("div");
3423
+ this.wrapper.className = "overtype-wrapper";
3424
+ if (this.options.fontSize) {
3425
+ this.wrapper.style.setProperty("--instance-font-size", this.options.fontSize);
3426
+ }
3427
+ if (this.options.lineHeight) {
3428
+ this.wrapper.style.setProperty("--instance-line-height", String(this.options.lineHeight));
3429
+ }
3430
+ if (this.options.padding) {
3431
+ this.wrapper.style.setProperty("--instance-padding", this.options.padding);
3432
+ }
3433
+ this.wrapper._instance = this;
3434
+ this.textarea = document.createElement("textarea");
3435
+ this.textarea.className = "overtype-input";
3436
+ this.textarea.placeholder = this.options.placeholder;
3437
+ this._configureTextarea();
3438
+ if (this.options.textareaProps) {
3439
+ Object.entries(this.options.textareaProps).forEach(([key, value]) => {
3440
+ if (key === "className" || key === "class") {
3441
+ this.textarea.className += " " + value;
3442
+ } else if (key === "style" && typeof value === "object") {
3443
+ Object.assign(this.textarea.style, value);
3444
+ } else {
3445
+ this.textarea.setAttribute(key, value);
3446
+ }
3447
+ });
3448
+ }
3449
+ this.preview = document.createElement("div");
3450
+ this.preview.className = "overtype-preview";
3451
+ this.preview.setAttribute("aria-hidden", "true");
3452
+ this.wrapper.appendChild(this.textarea);
3453
+ this.wrapper.appendChild(this.preview);
3454
+ this.container.appendChild(this.wrapper);
3455
+ if (this.options.showStats) {
3456
+ this.statsBar = document.createElement("div");
3457
+ this.statsBar.className = "overtype-stats";
3458
+ this.container.appendChild(this.statsBar);
3459
+ this._updateStats();
3460
+ }
3461
+ this.element.appendChild(this.container);
3462
+ if (window.location.pathname.includes("demo.html")) {
3463
+ console.log("_createDOM completed:", {
3464
+ elementId: this.element.id,
3465
+ autoResize: this.options.autoResize,
3466
+ containerClasses: this.container.className,
3467
+ hasStats: !!this.statsBar,
3468
+ hasToolbar: this.options.toolbar
3469
+ });
3470
+ }
3471
+ if (this.options.autoResize) {
3472
+ this._setupAutoResize();
3473
+ } else {
3474
+ this.container.classList.remove("overtype-auto-resize");
3475
+ if (window.location.pathname.includes("demo.html")) {
3476
+ console.log("Removed auto-resize class from:", this.element.id);
3477
+ }
3478
+ }
3479
+ }
3480
+ /**
3481
+ * Configure textarea attributes
3482
+ * @private
3483
+ */
3484
+ _configureTextarea() {
3485
+ this.textarea.setAttribute("autocomplete", "off");
3486
+ this.textarea.setAttribute("autocorrect", "off");
3487
+ this.textarea.setAttribute("autocapitalize", "off");
3488
+ this.textarea.setAttribute("spellcheck", "false");
3489
+ this.textarea.setAttribute("data-gramm", "false");
3490
+ this.textarea.setAttribute("data-gramm_editor", "false");
3491
+ this.textarea.setAttribute("data-enable-grammarly", "false");
3492
+ }
3493
+ /**
3494
+ * Create and setup toolbar
3495
+ * @private
3496
+ */
3497
+ _createToolbar() {
3498
+ const toolbarButtons2 = this.options.toolbarButtons || defaultToolbarButtons;
3499
+ this.toolbar = new Toolbar(this, { toolbarButtons: toolbarButtons2 });
3500
+ this.toolbar.create();
3501
+ this._toolbarSelectionListener = () => {
3502
+ if (this.toolbar) {
3503
+ this.toolbar.updateButtonStates();
3504
+ }
3505
+ };
3506
+ this._toolbarInputListener = () => {
3507
+ if (this.toolbar) {
3508
+ this.toolbar.updateButtonStates();
3509
+ }
3510
+ };
3511
+ this.textarea.addEventListener("selectionchange", this._toolbarSelectionListener);
3512
+ this.textarea.addEventListener("input", this._toolbarInputListener);
3513
+ }
3514
+ /**
3515
+ * Cleanup toolbar event listeners
3516
+ * @private
3517
+ */
3518
+ _cleanupToolbarListeners() {
3519
+ if (this._toolbarSelectionListener) {
3520
+ this.textarea.removeEventListener("selectionchange", this._toolbarSelectionListener);
3521
+ this._toolbarSelectionListener = null;
3522
+ }
3523
+ if (this._toolbarInputListener) {
3524
+ this.textarea.removeEventListener("input", this._toolbarInputListener);
3525
+ this._toolbarInputListener = null;
3526
+ }
3527
+ }
3528
+ /**
3529
+ * Apply options to the editor
3530
+ * @private
3531
+ */
3532
+ _applyOptions() {
3533
+ if (this.options.autofocus) {
3534
+ this.textarea.focus();
3535
+ }
3536
+ if (this.options.autoResize) {
3537
+ if (!this.container.classList.contains("overtype-auto-resize")) {
3538
+ this._setupAutoResize();
3539
+ }
3540
+ } else {
3541
+ this.container.classList.remove("overtype-auto-resize");
3542
+ }
3543
+ if (this.options.toolbar && !this.toolbar) {
3544
+ this._createToolbar();
3545
+ } else if (!this.options.toolbar && this.toolbar) {
3546
+ this._cleanupToolbarListeners();
3547
+ this.toolbar.destroy();
3548
+ this.toolbar = null;
3549
+ }
3550
+ this.updatePreview();
3551
+ }
3552
+ /**
3553
+ * Update preview with parsed markdown
3554
+ */
3555
+ updatePreview() {
3556
+ const text = this.textarea.value;
3557
+ const cursorPos = this.textarea.selectionStart;
3558
+ const activeLine = this._getCurrentLine(text, cursorPos);
3559
+ const isPreviewMode = this.container.dataset.mode === "preview";
3560
+ const html = MarkdownParser.parse(text, activeLine, this.options.showActiveLineRaw, this.options.codeHighlighter, isPreviewMode);
3561
+ this.preview.innerHTML = html || '<span style="color: #808080;">Start typing...</span>';
3562
+ this._applyCodeBlockBackgrounds();
3563
+ if (this.options.showStats && this.statsBar) {
3564
+ this._updateStats();
3565
+ }
3566
+ if (this.options.onChange && this.initialized) {
3567
+ this.options.onChange(text, this);
3568
+ }
3569
+ }
3570
+ /**
3571
+ * Apply background styling to code blocks
3572
+ * @private
3573
+ */
3574
+ _applyCodeBlockBackgrounds() {
3575
+ const codeFences = this.preview.querySelectorAll(".code-fence");
3576
+ for (let i = 0; i < codeFences.length - 1; i += 2) {
3577
+ const openFence = codeFences[i];
3578
+ const closeFence = codeFences[i + 1];
3579
+ const openParent = openFence.parentElement;
3580
+ const closeParent = closeFence.parentElement;
3581
+ if (!openParent || !closeParent)
3582
+ continue;
3583
+ openFence.style.display = "block";
3584
+ closeFence.style.display = "block";
3585
+ openParent.classList.add("code-block-line");
3586
+ closeParent.classList.add("code-block-line");
3587
+ }
3588
+ }
3589
+ /**
3590
+ * Get current line number from cursor position
3591
+ * @private
3592
+ */
3593
+ _getCurrentLine(text, cursorPos) {
3594
+ const lines = text.substring(0, cursorPos).split("\n");
3595
+ return lines.length - 1;
3596
+ }
3597
+ /**
3598
+ * Handle input events
3599
+ * @private
3600
+ */
3601
+ handleInput(event) {
3602
+ this.updatePreview();
3603
+ }
3604
+ /**
3605
+ * Handle keydown events
3606
+ * @private
3607
+ */
3608
+ handleKeydown(event) {
3609
+ if (event.key === "Tab") {
3610
+ event.preventDefault();
3611
+ const start = this.textarea.selectionStart;
3612
+ const end = this.textarea.selectionEnd;
3613
+ const value = this.textarea.value;
3614
+ if (start !== end && event.shiftKey) {
3615
+ const before = value.substring(0, start);
3616
+ const selection = value.substring(start, end);
3617
+ const after = value.substring(end);
3618
+ const lines = selection.split("\n");
3619
+ const outdented = lines.map((line) => line.replace(/^ /, "")).join("\n");
3620
+ if (document.execCommand) {
3621
+ this.textarea.setSelectionRange(start, end);
3622
+ document.execCommand("insertText", false, outdented);
3623
+ } else {
3624
+ this.textarea.value = before + outdented + after;
3625
+ this.textarea.selectionStart = start;
3626
+ this.textarea.selectionEnd = start + outdented.length;
3627
+ }
3628
+ } else if (start !== end) {
3629
+ const before = value.substring(0, start);
3630
+ const selection = value.substring(start, end);
3631
+ const after = value.substring(end);
3632
+ const lines = selection.split("\n");
3633
+ const indented = lines.map((line) => " " + line).join("\n");
3634
+ if (document.execCommand) {
3635
+ this.textarea.setSelectionRange(start, end);
3636
+ document.execCommand("insertText", false, indented);
3637
+ } else {
3638
+ this.textarea.value = before + indented + after;
3639
+ this.textarea.selectionStart = start;
3640
+ this.textarea.selectionEnd = start + indented.length;
3641
+ }
3642
+ } else {
3643
+ if (document.execCommand) {
3644
+ document.execCommand("insertText", false, " ");
3645
+ } else {
3646
+ this.textarea.value = value.substring(0, start) + " " + value.substring(end);
3647
+ this.textarea.selectionStart = this.textarea.selectionEnd = start + 2;
3648
+ }
3649
+ }
3650
+ this.textarea.dispatchEvent(new Event("input", { bubbles: true }));
3651
+ return;
3652
+ }
3653
+ if (event.key === "Enter" && !event.shiftKey && !event.metaKey && !event.ctrlKey && this.options.smartLists) {
3654
+ if (this.handleSmartListContinuation()) {
3655
+ event.preventDefault();
3656
+ return;
3657
+ }
3658
+ }
3659
+ const handled = this.shortcuts.handleKeydown(event);
3660
+ if (!handled && this.options.onKeydown) {
3661
+ this.options.onKeydown(event, this);
3662
+ }
3663
+ }
3664
+ /**
3665
+ * Handle smart list continuation
3666
+ * @returns {boolean} Whether the event was handled
3667
+ */
3668
+ handleSmartListContinuation() {
3669
+ const textarea = this.textarea;
3670
+ const cursorPos = textarea.selectionStart;
3671
+ const context = MarkdownParser.getListContext(textarea.value, cursorPos);
3672
+ if (!context || !context.inList)
3673
+ return false;
3674
+ if (context.content.trim() === "" && cursorPos >= context.markerEndPos) {
3675
+ this.deleteListMarker(context);
3676
+ return true;
3677
+ }
3678
+ if (cursorPos > context.markerEndPos && cursorPos < context.lineEnd) {
3679
+ this.splitListItem(context, cursorPos);
3680
+ } else {
3681
+ this.insertNewListItem(context);
3682
+ }
3683
+ if (context.listType === "numbered") {
3684
+ this.scheduleNumberedListUpdate();
3685
+ }
3686
+ return true;
3687
+ }
3688
+ /**
3689
+ * Delete list marker and exit list
3690
+ * @private
3691
+ */
3692
+ deleteListMarker(context) {
3693
+ this.textarea.setSelectionRange(context.lineStart, context.markerEndPos);
3694
+ document.execCommand("delete");
3695
+ this.textarea.dispatchEvent(new Event("input", { bubbles: true }));
3696
+ }
3697
+ /**
3698
+ * Insert new list item
3699
+ * @private
3700
+ */
3701
+ insertNewListItem(context) {
3702
+ const newItem = MarkdownParser.createNewListItem(context);
3703
+ document.execCommand("insertText", false, "\n" + newItem);
3704
+ this.textarea.dispatchEvent(new Event("input", { bubbles: true }));
3705
+ }
3706
+ /**
3707
+ * Split list item at cursor position
3708
+ * @private
3709
+ */
3710
+ splitListItem(context, cursorPos) {
3711
+ const textAfterCursor = context.content.substring(cursorPos - context.markerEndPos);
3712
+ this.textarea.setSelectionRange(cursorPos, context.lineEnd);
3713
+ document.execCommand("delete");
3714
+ const newItem = MarkdownParser.createNewListItem(context);
3715
+ document.execCommand("insertText", false, "\n" + newItem + textAfterCursor);
3716
+ const newCursorPos = this.textarea.selectionStart - textAfterCursor.length;
3717
+ this.textarea.setSelectionRange(newCursorPos, newCursorPos);
3718
+ this.textarea.dispatchEvent(new Event("input", { bubbles: true }));
3719
+ }
3720
+ /**
3721
+ * Schedule numbered list renumbering
3722
+ * @private
3723
+ */
3724
+ scheduleNumberedListUpdate() {
3725
+ if (this.numberUpdateTimeout) {
3726
+ clearTimeout(this.numberUpdateTimeout);
3727
+ }
3728
+ this.numberUpdateTimeout = setTimeout(() => {
3729
+ this.updateNumberedLists();
3730
+ }, 10);
3731
+ }
3732
+ /**
3733
+ * Update/renumber all numbered lists
3734
+ * @private
3735
+ */
3736
+ updateNumberedLists() {
3737
+ const value = this.textarea.value;
3738
+ const cursorPos = this.textarea.selectionStart;
3739
+ const newValue = MarkdownParser.renumberLists(value);
3740
+ if (newValue !== value) {
3741
+ let offset = 0;
3742
+ const oldLines = value.split("\n");
3743
+ const newLines = newValue.split("\n");
3744
+ let charCount = 0;
3745
+ for (let i = 0; i < oldLines.length && charCount < cursorPos; i++) {
3746
+ if (oldLines[i] !== newLines[i]) {
3747
+ const diff = newLines[i].length - oldLines[i].length;
3748
+ if (charCount + oldLines[i].length < cursorPos) {
3749
+ offset += diff;
3750
+ }
3751
+ }
3752
+ charCount += oldLines[i].length + 1;
3753
+ }
3754
+ this.textarea.value = newValue;
3755
+ const newCursorPos = cursorPos + offset;
3756
+ this.textarea.setSelectionRange(newCursorPos, newCursorPos);
3757
+ this.textarea.dispatchEvent(new Event("input", { bubbles: true }));
3758
+ }
3759
+ }
3760
+ /**
3761
+ * Handle scroll events
3762
+ * @private
3763
+ */
3764
+ handleScroll(event) {
3765
+ this.preview.scrollTop = this.textarea.scrollTop;
3766
+ this.preview.scrollLeft = this.textarea.scrollLeft;
3767
+ }
3768
+ /**
3769
+ * Get editor content
3770
+ * @returns {string} Current markdown content
3771
+ */
3772
+ getValue() {
3773
+ return this.textarea.value;
3774
+ }
3775
+ /**
3776
+ * Set editor content
3777
+ * @param {string} value - Markdown content to set
3778
+ */
3779
+ setValue(value) {
3780
+ this.textarea.value = value;
3781
+ this.updatePreview();
3782
+ if (this.options.autoResize) {
3783
+ this._updateAutoHeight();
3784
+ }
3785
+ }
3786
+ /**
3787
+ * Get the rendered HTML of the current content
3788
+ * @param {Object} options - Rendering options
3789
+ * @param {boolean} options.cleanHTML - If true, removes syntax markers and OverType-specific classes
3790
+ * @returns {string} Rendered HTML
3791
+ */
3792
+ getRenderedHTML(options = {}) {
3793
+ const markdown = this.getValue();
3794
+ let html = MarkdownParser.parse(markdown, -1, false, this.options.codeHighlighter);
3795
+ if (options.cleanHTML) {
3796
+ html = html.replace(/<span class="syntax-marker[^"]*">.*?<\/span>/g, "");
3797
+ html = html.replace(/\sclass="(bullet-list|ordered-list|code-fence|hr-marker|blockquote|url-part)"/g, "");
3798
+ html = html.replace(/\sclass=""/g, "");
3799
+ }
3800
+ return html;
3801
+ }
3802
+ /**
3803
+ * Get the current preview element's HTML
3804
+ * This includes all syntax markers and OverType styling
3805
+ * @returns {string} Current preview HTML (as displayed)
3806
+ */
3807
+ getPreviewHTML() {
3808
+ return this.preview.innerHTML;
3809
+ }
3810
+ /**
3811
+ * Get clean HTML without any OverType-specific markup
3812
+ * Useful for exporting to other formats or storage
3813
+ * @returns {string} Clean HTML suitable for export
3814
+ */
3815
+ getCleanHTML() {
3816
+ return this.getRenderedHTML({ cleanHTML: true });
3817
+ }
3818
+ /**
3819
+ * Focus the editor
3820
+ */
3821
+ focus() {
3822
+ this.textarea.focus();
3823
+ }
3824
+ /**
3825
+ * Blur the editor
3826
+ */
3827
+ blur() {
3828
+ this.textarea.blur();
3829
+ }
3830
+ /**
3831
+ * Check if editor is initialized
3832
+ * @returns {boolean}
3833
+ */
3834
+ isInitialized() {
3835
+ return this.initialized;
3836
+ }
3837
+ /**
3838
+ * Re-initialize with new options
3839
+ * @param {Object} options - New options to apply
3840
+ */
3841
+ reinit(options = {}) {
3842
+ this.options = this._mergeOptions({ ...this.options, ...options });
3843
+ this._applyOptions();
3844
+ this.updatePreview();
3845
+ }
3846
+ /**
3847
+ * Set theme for this instance
3848
+ * @param {string|Object} theme - Theme name or custom theme object
3849
+ * @returns {this} Returns this for chaining
3850
+ */
3851
+ setTheme(theme) {
3852
+ this.instanceTheme = theme;
3853
+ const themeObj = typeof theme === "string" ? getTheme(theme) : theme;
3854
+ const themeName = typeof themeObj === "string" ? themeObj : themeObj.name;
3855
+ if (themeName) {
3856
+ this.container.setAttribute("data-theme", themeName);
3857
+ }
3858
+ if (themeObj && themeObj.colors) {
3859
+ const cssVars = themeToCSSVars(themeObj.colors);
3860
+ this.container.style.cssText += cssVars;
3861
+ }
3862
+ this.updatePreview();
3863
+ return this;
3864
+ }
3865
+ /**
3866
+ * Set instance-specific code highlighter
3867
+ * @param {Function|null} highlighter - Function that takes (code, language) and returns highlighted HTML
3868
+ */
3869
+ setCodeHighlighter(highlighter) {
3870
+ this.options.codeHighlighter = highlighter;
3871
+ this.updatePreview();
3872
+ }
3873
+ /**
3874
+ * Update stats bar
3875
+ * @private
3876
+ */
3877
+ _updateStats() {
3878
+ if (!this.statsBar)
3879
+ return;
3880
+ const value = this.textarea.value;
3881
+ const lines = value.split("\n");
3882
+ const chars = value.length;
3883
+ const words = value.split(/\s+/).filter((w) => w.length > 0).length;
3884
+ const selectionStart = this.textarea.selectionStart;
3885
+ const beforeCursor = value.substring(0, selectionStart);
3886
+ const linesBeforeCursor = beforeCursor.split("\n");
3887
+ const currentLine = linesBeforeCursor.length;
3888
+ const currentColumn = linesBeforeCursor[linesBeforeCursor.length - 1].length + 1;
3889
+ if (this.options.statsFormatter) {
3890
+ this.statsBar.innerHTML = this.options.statsFormatter({
3891
+ chars,
3892
+ words,
3893
+ lines: lines.length,
3894
+ line: currentLine,
3895
+ column: currentColumn
3896
+ });
3897
+ } else {
3898
+ this.statsBar.innerHTML = `
3899
+ <div class="overtype-stat">
3900
+ <span class="live-dot"></span>
3901
+ <span>${chars} chars, ${words} words, ${lines.length} lines</span>
3902
+ </div>
3903
+ <div class="overtype-stat">Line ${currentLine}, Col ${currentColumn}</div>
3904
+ `;
3905
+ }
3906
+ }
3907
+ /**
3908
+ * Setup auto-resize functionality
3909
+ * @private
3910
+ */
3911
+ _setupAutoResize() {
3912
+ this.container.classList.add("overtype-auto-resize");
3913
+ this.previousHeight = null;
3914
+ this._updateAutoHeight();
3915
+ this.textarea.addEventListener("input", () => this._updateAutoHeight());
3916
+ window.addEventListener("resize", () => this._updateAutoHeight());
3917
+ }
3918
+ /**
3919
+ * Update height based on scrollHeight
3920
+ * @private
3921
+ */
3922
+ _updateAutoHeight() {
3923
+ if (!this.options.autoResize)
3924
+ return;
3925
+ const textarea = this.textarea;
3926
+ const preview = this.preview;
3927
+ const wrapper = this.wrapper;
3928
+ const computed = window.getComputedStyle(textarea);
3929
+ const paddingTop = parseFloat(computed.paddingTop);
3930
+ const paddingBottom = parseFloat(computed.paddingBottom);
3931
+ const scrollTop = textarea.scrollTop;
3932
+ textarea.style.setProperty("height", "auto", "important");
3933
+ let newHeight = textarea.scrollHeight;
3934
+ if (this.options.minHeight) {
3935
+ const minHeight = parseInt(this.options.minHeight);
3936
+ newHeight = Math.max(newHeight, minHeight);
3937
+ }
3938
+ let overflow = "hidden";
3939
+ if (this.options.maxHeight) {
3940
+ const maxHeight = parseInt(this.options.maxHeight);
3941
+ if (newHeight > maxHeight) {
3942
+ newHeight = maxHeight;
3943
+ overflow = "auto";
3944
+ }
3945
+ }
3946
+ const heightPx = newHeight + "px";
3947
+ textarea.style.setProperty("height", heightPx, "important");
3948
+ textarea.style.setProperty("overflow-y", overflow, "important");
3949
+ preview.style.setProperty("height", heightPx, "important");
3950
+ preview.style.setProperty("overflow-y", overflow, "important");
3951
+ wrapper.style.setProperty("height", heightPx, "important");
3952
+ textarea.scrollTop = scrollTop;
3953
+ preview.scrollTop = scrollTop;
3954
+ if (this.previousHeight !== newHeight) {
3955
+ this.previousHeight = newHeight;
3956
+ }
3957
+ }
3958
+ /**
3959
+ * Show or hide stats bar
3960
+ * @param {boolean} show - Whether to show stats
3961
+ */
3962
+ showStats(show) {
3963
+ this.options.showStats = show;
3964
+ if (show && !this.statsBar) {
3965
+ this.statsBar = document.createElement("div");
3966
+ this.statsBar.className = "overtype-stats";
3967
+ this.container.appendChild(this.statsBar);
3968
+ this._updateStats();
3969
+ } else if (!show && this.statsBar) {
3970
+ this.statsBar.remove();
3971
+ this.statsBar = null;
3972
+ }
3973
+ }
3974
+ /**
3975
+ * Show normal edit mode (overlay with markdown preview)
3976
+ * @returns {this} Returns this for chaining
3977
+ */
3978
+ showNormalEditMode() {
3979
+ this.container.dataset.mode = "normal";
3980
+ requestAnimationFrame(() => {
3981
+ this.textarea.scrollTop = this.preview.scrollTop;
3982
+ this.textarea.scrollLeft = this.preview.scrollLeft;
3983
+ });
3984
+ return this;
3985
+ }
3986
+ /**
3987
+ * Show plain textarea mode (no overlay)
3988
+ * @returns {this} Returns this for chaining
3989
+ */
3990
+ showPlainTextarea() {
3991
+ this.container.dataset.mode = "plain";
3992
+ if (this.toolbar) {
3993
+ const toggleBtn = this.container.querySelector('[data-action="toggle-plain"]');
3994
+ if (toggleBtn) {
3995
+ toggleBtn.classList.remove("active");
3996
+ toggleBtn.title = "Show markdown preview";
3997
+ }
3998
+ }
3999
+ return this;
4000
+ }
4001
+ /**
4002
+ * Show preview mode (read-only view)
4003
+ * @returns {this} Returns this for chaining
4004
+ */
4005
+ showPreviewMode() {
4006
+ this.container.dataset.mode = "preview";
4007
+ return this;
4008
+ }
4009
+ /**
4010
+ * Destroy the editor instance
4011
+ */
4012
+ destroy() {
4013
+ this.element.overTypeInstance = null;
4014
+ _OverType.instances.delete(this.element);
4015
+ if (this.shortcuts) {
4016
+ this.shortcuts.destroy();
4017
+ }
4018
+ if (this.wrapper) {
4019
+ const content = this.getValue();
4020
+ this.wrapper.remove();
4021
+ this.element.textContent = content;
4022
+ }
4023
+ this.initialized = false;
4024
+ }
4025
+ // ===== Static Methods =====
4026
+ /**
4027
+ * Initialize multiple editors (static convenience method)
4028
+ * @param {string|Element|NodeList|Array} target - Target element(s)
4029
+ * @param {Object} options - Configuration options
4030
+ * @returns {Array} Array of OverType instances
4031
+ */
4032
+ static init(target, options = {}) {
4033
+ return new _OverType(target, options);
4034
+ }
4035
+ /**
4036
+ * Get instance from element
4037
+ * @param {Element} element - DOM element
4038
+ * @returns {OverType|null} OverType instance or null
4039
+ */
4040
+ static getInstance(element) {
4041
+ return element.overTypeInstance || _OverType.instances.get(element) || null;
4042
+ }
4043
+ /**
4044
+ * Destroy all instances
4045
+ */
4046
+ static destroyAll() {
4047
+ const elements = document.querySelectorAll("[data-overtype-instance]");
4048
+ elements.forEach((element) => {
4049
+ const instance = _OverType.getInstance(element);
4050
+ if (instance) {
4051
+ instance.destroy();
4052
+ }
4053
+ });
4054
+ }
4055
+ /**
4056
+ * Inject styles into the document
4057
+ * @param {boolean} force - Force re-injection
4058
+ */
4059
+ static injectStyles(force = false) {
4060
+ if (_OverType.stylesInjected && !force)
4061
+ return;
4062
+ const existing = document.querySelector("style.overtype-styles");
4063
+ if (existing) {
4064
+ existing.remove();
4065
+ }
4066
+ const theme = _OverType.currentTheme || solar;
4067
+ const styles = generateStyles({ theme });
4068
+ const styleEl = document.createElement("style");
4069
+ styleEl.className = "overtype-styles";
4070
+ styleEl.textContent = styles;
4071
+ document.head.appendChild(styleEl);
4072
+ _OverType.stylesInjected = true;
4073
+ }
4074
+ /**
4075
+ * Set global theme for all OverType instances
4076
+ * @param {string|Object} theme - Theme name or custom theme object
4077
+ * @param {Object} customColors - Optional color overrides
4078
+ */
4079
+ static setTheme(theme, customColors = null) {
4080
+ let themeObj = typeof theme === "string" ? getTheme(theme) : theme;
4081
+ if (customColors) {
4082
+ themeObj = mergeTheme(themeObj, customColors);
4083
+ }
4084
+ _OverType.currentTheme = themeObj;
4085
+ _OverType.injectStyles(true);
4086
+ document.querySelectorAll(".overtype-container").forEach((container) => {
4087
+ const themeName2 = typeof themeObj === "string" ? themeObj : themeObj.name;
4088
+ if (themeName2) {
4089
+ container.setAttribute("data-theme", themeName2);
4090
+ }
4091
+ });
4092
+ document.querySelectorAll(".overtype-wrapper").forEach((wrapper) => {
4093
+ if (!wrapper.closest(".overtype-container")) {
4094
+ const themeName2 = typeof themeObj === "string" ? themeObj : themeObj.name;
4095
+ if (themeName2) {
4096
+ wrapper.setAttribute("data-theme", themeName2);
4097
+ }
4098
+ }
4099
+ const instance = wrapper._instance;
4100
+ if (instance) {
4101
+ instance.updatePreview();
4102
+ }
4103
+ });
4104
+ const themeName = typeof themeObj === "string" ? themeObj : themeObj.name;
4105
+ document.querySelectorAll("overtype-editor").forEach((webComponent) => {
4106
+ if (themeName && typeof webComponent.setAttribute === "function") {
4107
+ webComponent.setAttribute("theme", themeName);
4108
+ }
4109
+ if (typeof webComponent.refreshTheme === "function") {
4110
+ webComponent.refreshTheme();
4111
+ }
4112
+ });
4113
+ }
4114
+ /**
4115
+ * Set global code highlighter for all OverType instances
4116
+ * @param {Function|null} highlighter - Function that takes (code, language) and returns highlighted HTML
4117
+ */
4118
+ static setCodeHighlighter(highlighter) {
4119
+ MarkdownParser.setCodeHighlighter(highlighter);
4120
+ document.querySelectorAll(".overtype-wrapper").forEach((wrapper) => {
4121
+ const instance = wrapper._instance;
4122
+ if (instance && instance.updatePreview) {
4123
+ instance.updatePreview();
4124
+ }
4125
+ });
4126
+ document.querySelectorAll("overtype-editor").forEach((webComponent) => {
4127
+ if (typeof webComponent.getEditor === "function") {
4128
+ const instance = webComponent.getEditor();
4129
+ if (instance && instance.updatePreview) {
4130
+ instance.updatePreview();
4131
+ }
4132
+ }
4133
+ });
4134
+ }
4135
+ /**
4136
+ * Initialize global event listeners
4137
+ */
4138
+ static initGlobalListeners() {
4139
+ if (_OverType.globalListenersInitialized)
4140
+ return;
4141
+ document.addEventListener("input", (e) => {
4142
+ if (e.target && e.target.classList && e.target.classList.contains("overtype-input")) {
4143
+ const wrapper = e.target.closest(".overtype-wrapper");
4144
+ const instance = wrapper == null ? void 0 : wrapper._instance;
4145
+ if (instance)
4146
+ instance.handleInput(e);
4147
+ }
4148
+ });
4149
+ document.addEventListener("keydown", (e) => {
4150
+ if (e.target && e.target.classList && e.target.classList.contains("overtype-input")) {
4151
+ const wrapper = e.target.closest(".overtype-wrapper");
4152
+ const instance = wrapper == null ? void 0 : wrapper._instance;
4153
+ if (instance)
4154
+ instance.handleKeydown(e);
4155
+ }
4156
+ });
4157
+ document.addEventListener("scroll", (e) => {
4158
+ if (e.target && e.target.classList && e.target.classList.contains("overtype-input")) {
4159
+ const wrapper = e.target.closest(".overtype-wrapper");
4160
+ const instance = wrapper == null ? void 0 : wrapper._instance;
4161
+ if (instance)
4162
+ instance.handleScroll(e);
4163
+ }
4164
+ }, true);
4165
+ document.addEventListener("selectionchange", (e) => {
4166
+ const activeElement = document.activeElement;
4167
+ if (activeElement && activeElement.classList.contains("overtype-input")) {
4168
+ const wrapper = activeElement.closest(".overtype-wrapper");
4169
+ const instance = wrapper == null ? void 0 : wrapper._instance;
4170
+ if (instance) {
4171
+ if (instance.options.showStats && instance.statsBar) {
4172
+ instance._updateStats();
4173
+ }
4174
+ clearTimeout(instance._selectionTimeout);
4175
+ instance._selectionTimeout = setTimeout(() => {
4176
+ instance.updatePreview();
4177
+ }, 50);
4178
+ }
4179
+ }
4180
+ });
4181
+ _OverType.globalListenersInitialized = true;
4182
+ }
4183
+ };
4184
+ // Static properties
4185
+ __publicField(_OverType, "instances", /* @__PURE__ */ new WeakMap());
4186
+ __publicField(_OverType, "stylesInjected", false);
4187
+ __publicField(_OverType, "globalListenersInitialized", false);
4188
+ __publicField(_OverType, "instanceCount", 0);
4189
+ var OverType = _OverType;
4190
+ OverType.MarkdownParser = MarkdownParser;
4191
+ OverType.ShortcutsManager = ShortcutsManager;
4192
+ OverType.themes = { solar, cave: getTheme("cave") };
4193
+ OverType.getTheme = getTheme;
4194
+ OverType.currentTheme = solar;
4195
+ var overtype_default = OverType;
4196
+
4197
+ // src/overtype-webcomponent.js
4198
+ var CONTAINER_CLASS = "overtype-webcomponent-container";
4199
+ var DEFAULT_PLACEHOLDER = "Start typing...";
4200
+ var OBSERVED_ATTRIBUTES = [
4201
+ "value",
4202
+ "theme",
4203
+ "toolbar",
4204
+ "height",
4205
+ "min-height",
4206
+ "max-height",
4207
+ "placeholder",
4208
+ "font-size",
4209
+ "line-height",
4210
+ "padding",
4211
+ "auto-resize",
4212
+ "autofocus",
4213
+ "show-stats",
4214
+ "smart-lists",
4215
+ "readonly"
4216
+ ];
4217
+ var OverTypeEditor = class extends HTMLElement {
4218
+ constructor() {
4219
+ super();
4220
+ this.attachShadow({ mode: "open" });
4221
+ this._editor = null;
4222
+ this._initialized = false;
4223
+ this._pendingOptions = {};
4224
+ this._styleVersion = 0;
4225
+ this._baseStyleElement = null;
4226
+ this._selectionChangeHandler = null;
4227
+ this._isConnected = false;
4228
+ this._handleChange = this._handleChange.bind(this);
4229
+ this._handleKeydown = this._handleKeydown.bind(this);
4230
+ }
4231
+ /**
4232
+ * Decode common escape sequences from attribute string values
4233
+ * @private
4234
+ * @param {string|null|undefined} str
4235
+ * @returns {string}
4236
+ */
4237
+ _decodeValue(str) {
4238
+ if (typeof str !== "string")
4239
+ return "";
4240
+ return str.replace(/\\r/g, "\r").replace(/\\n/g, "\n").replace(/\\t/g, " ");
4241
+ }
4242
+ // Note: _encodeValue removed as it's currently unused
4243
+ // Can be re-added if needed for future attribute encoding
4244
+ /**
4245
+ * Define observed attributes for reactive updates
4246
+ */
4247
+ static get observedAttributes() {
4248
+ return OBSERVED_ATTRIBUTES;
4249
+ }
4250
+ /**
4251
+ * Component connected to DOM - initialize editor
4252
+ */
4253
+ connectedCallback() {
4254
+ this._isConnected = true;
4255
+ this._initializeEditor();
4256
+ }
4257
+ /**
4258
+ * Component disconnected from DOM - cleanup
4259
+ */
4260
+ disconnectedCallback() {
4261
+ this._isConnected = false;
4262
+ this._cleanup();
4263
+ }
4264
+ /**
4265
+ * Attribute changed callback - update editor options
4266
+ */
4267
+ attributeChangedCallback(name, oldValue, newValue) {
4268
+ if (oldValue === newValue)
4269
+ return;
4270
+ if (this._silentUpdate)
4271
+ return;
4272
+ if (!this._initialized) {
4273
+ this._pendingOptions[name] = newValue;
4274
+ return;
4275
+ }
4276
+ this._updateOption(name, newValue);
4277
+ }
4278
+ /**
4279
+ * Initialize the OverType editor inside shadow DOM
4280
+ * @private
4281
+ */
4282
+ _initializeEditor() {
4283
+ if (this._initialized || !this._isConnected)
4284
+ return;
4285
+ try {
4286
+ const container = document.createElement("div");
4287
+ container.className = CONTAINER_CLASS;
4288
+ const height = this.getAttribute("height");
4289
+ const minHeight = this.getAttribute("min-height");
4290
+ const maxHeight = this.getAttribute("max-height");
4291
+ if (height)
4292
+ container.style.height = height;
4293
+ if (minHeight)
4294
+ container.style.minHeight = minHeight;
4295
+ if (maxHeight)
4296
+ container.style.maxHeight = maxHeight;
4297
+ this._injectStyles();
4298
+ this.shadowRoot.appendChild(container);
4299
+ const options = this._getOptionsFromAttributes();
4300
+ const editorInstances = new overtype_default(container, options);
4301
+ this._editor = editorInstances[0];
4302
+ this._initialized = true;
4303
+ if (this._editor && this._editor.textarea) {
4304
+ this._editor.textarea.addEventListener("scroll", () => {
4305
+ if (this._editor && this._editor.preview && this._editor.textarea) {
4306
+ this._editor.preview.scrollTop = this._editor.textarea.scrollTop;
4307
+ this._editor.preview.scrollLeft = this._editor.textarea.scrollLeft;
4308
+ }
4309
+ });
4310
+ this._editor.textarea.addEventListener("input", (e) => {
4311
+ if (this._editor && this._editor.handleInput) {
4312
+ this._editor.handleInput(e);
4313
+ }
4314
+ });
4315
+ this._editor.textarea.addEventListener("keydown", (e) => {
4316
+ if (this._editor && this._editor.handleKeydown) {
4317
+ this._editor.handleKeydown(e);
4318
+ }
4319
+ });
4320
+ this._selectionChangeHandler = () => {
4321
+ if (document.activeElement === this) {
4322
+ const shadowActiveElement = this.shadowRoot.activeElement;
4323
+ if (shadowActiveElement && shadowActiveElement === this._editor.textarea) {
4324
+ if (this._editor.options.showStats && this._editor.statsBar) {
4325
+ this._editor._updateStats();
4326
+ }
4327
+ if (this._editor.linkTooltip && this._editor.linkTooltip.checkCursorPosition) {
4328
+ this._editor.linkTooltip.checkCursorPosition();
4329
+ }
4330
+ }
4331
+ }
4332
+ };
4333
+ document.addEventListener("selectionchange", this._selectionChangeHandler);
4334
+ }
4335
+ this._applyPendingOptions();
4336
+ this._dispatchEvent("ready", { editor: this._editor });
4337
+ } catch (error) {
4338
+ const message = error && error.message ? error.message : String(error);
4339
+ console.warn("OverType Web Component initialization failed:", message);
4340
+ this._dispatchEvent("error", { error: { message } });
4341
+ }
4342
+ }
4343
+ /**
4344
+ * Inject styles into shadow DOM for complete isolation
4345
+ * @private
4346
+ */
4347
+ _injectStyles() {
4348
+ const style = document.createElement("style");
4349
+ const themeAttr = this.getAttribute("theme") || "solar";
4350
+ const theme = getTheme(themeAttr);
4351
+ const options = this._getOptionsFromAttributes();
4352
+ const styles = generateStyles({ ...options, theme });
4353
+ const webComponentStyles = `
4354
+ /* Web Component Host Styles */
4355
+ :host {
4356
+ display: block;
4357
+ position: relative;
4358
+ width: 100%;
4359
+ height: 100%;
4360
+ contain: layout style;
4361
+ }
4362
+
4363
+ .overtype-webcomponent-container {
4364
+ width: 100%;
4365
+ height: 100%;
4366
+ position: relative;
4367
+ }
4368
+
4369
+ /* Override container grid layout for web component */
4370
+ .overtype-container {
4371
+ height: 100% !important;
4372
+ }
4373
+ `;
4374
+ this._styleVersion += 1;
4375
+ const versionBanner = `
4376
+ /* overtype-webcomponent styles v${this._styleVersion} */
4377
+ `;
4378
+ style.textContent = versionBanner + styles + webComponentStyles;
4379
+ this._baseStyleElement = style;
4380
+ this.shadowRoot.appendChild(style);
4381
+ }
4382
+ /**
4383
+ * Extract options from HTML attributes
4384
+ * @private
4385
+ * @returns {Object} OverType options object
4386
+ */
4387
+ _getOptionsFromAttributes() {
4388
+ const options = {
4389
+ // Allow authoring multi-line content via escaped sequences in attributes
4390
+ // and fall back to light DOM text content if attribute is absent
4391
+ value: this.getAttribute("value") !== null ? this._decodeValue(this.getAttribute("value")) : (this.textContent || "").trim(),
4392
+ placeholder: this.getAttribute("placeholder") || DEFAULT_PLACEHOLDER,
4393
+ toolbar: this.hasAttribute("toolbar"),
4394
+ autofocus: this.hasAttribute("autofocus"),
4395
+ autoResize: this.hasAttribute("auto-resize"),
4396
+ showStats: this.hasAttribute("show-stats"),
4397
+ smartLists: !this.hasAttribute("smart-lists") || this.getAttribute("smart-lists") !== "false",
4398
+ onChange: this._handleChange,
4399
+ onKeydown: this._handleKeydown
4400
+ };
4401
+ const fontSize = this.getAttribute("font-size");
4402
+ if (fontSize)
4403
+ options.fontSize = fontSize;
4404
+ const lineHeight = this.getAttribute("line-height");
4405
+ if (lineHeight)
4406
+ options.lineHeight = parseFloat(lineHeight) || 1.6;
4407
+ const padding = this.getAttribute("padding");
4408
+ if (padding)
4409
+ options.padding = padding;
4410
+ const minHeight = this.getAttribute("min-height");
4411
+ if (minHeight)
4412
+ options.minHeight = minHeight;
4413
+ const maxHeight = this.getAttribute("max-height");
4414
+ if (maxHeight)
4415
+ options.maxHeight = maxHeight;
4416
+ return options;
4417
+ }
4418
+ /**
4419
+ * Apply pending option changes after initialization
4420
+ * @private
4421
+ */
4422
+ _applyPendingOptions() {
4423
+ for (const [attr, value] of Object.entries(this._pendingOptions)) {
4424
+ this._updateOption(attr, value);
4425
+ }
4426
+ this._pendingOptions = {};
4427
+ }
4428
+ /**
4429
+ * Update a single editor option
4430
+ * @private
4431
+ * @param {string} attribute - Attribute name
4432
+ * @param {string} value - New value
4433
+ */
4434
+ _updateOption(attribute, value) {
4435
+ if (!this._editor)
4436
+ return;
4437
+ switch (attribute) {
4438
+ case "value":
4439
+ {
4440
+ const decoded = this._decodeValue(value);
4441
+ if (this._editor.getValue() !== decoded) {
4442
+ this._editor.setValue(decoded || "");
4443
+ }
4444
+ }
4445
+ break;
4446
+ case "theme":
4447
+ this._reinjectStyles();
4448
+ break;
4449
+ case "placeholder":
4450
+ if (this._editor.textarea) {
4451
+ this._editor.textarea.placeholder = value || "";
4452
+ }
4453
+ break;
4454
+ case "readonly":
4455
+ if (this._editor.textarea) {
4456
+ this._editor.textarea.readOnly = this.hasAttribute("readonly");
4457
+ }
4458
+ break;
4459
+ case "height":
4460
+ case "min-height":
4461
+ case "max-height":
4462
+ this._updateContainerHeight();
4463
+ break;
4464
+ case "toolbar":
4465
+ if (!!this.hasAttribute("toolbar") === !!this._editor.options.toolbar)
4466
+ return;
4467
+ this._reinitializeEditor();
4468
+ break;
4469
+ case "auto-resize":
4470
+ if (!!this.hasAttribute("auto-resize") === !!this._editor.options.autoResize)
4471
+ return;
4472
+ this._reinitializeEditor();
4473
+ break;
4474
+ case "show-stats":
4475
+ if (!!this.hasAttribute("show-stats") === !!this._editor.options.showStats)
4476
+ return;
4477
+ this._reinitializeEditor();
4478
+ break;
4479
+ case "font-size": {
4480
+ if (this._updateFontSize(value)) {
4481
+ this._reinjectStyles();
4482
+ }
4483
+ break;
4484
+ }
4485
+ case "line-height": {
4486
+ if (this._updateLineHeight(value)) {
4487
+ this._reinjectStyles();
4488
+ }
4489
+ break;
4490
+ }
4491
+ case "padding":
4492
+ this._reinjectStyles();
4493
+ break;
4494
+ case "smart-lists": {
4495
+ const newSmartLists = !this.hasAttribute("smart-lists") || this.getAttribute("smart-lists") !== "false";
4496
+ if (!!this._editor.options.smartLists === !!newSmartLists)
4497
+ return;
4498
+ this._reinitializeEditor();
4499
+ break;
4500
+ }
4501
+ }
4502
+ }
4503
+ /**
4504
+ * Update container height from attributes
4505
+ * @private
4506
+ */
4507
+ _updateContainerHeight() {
4508
+ const container = this.shadowRoot.querySelector(`.${CONTAINER_CLASS}`);
4509
+ if (!container)
4510
+ return;
4511
+ const height = this.getAttribute("height");
4512
+ const minHeight = this.getAttribute("min-height");
4513
+ const maxHeight = this.getAttribute("max-height");
4514
+ container.style.height = height || "";
4515
+ container.style.minHeight = minHeight || "";
4516
+ container.style.maxHeight = maxHeight || "";
4517
+ }
4518
+ /**
4519
+ * Update font size efficiently
4520
+ * @private
4521
+ * @param {string} value - New font size value
4522
+ * @returns {boolean} True if direct update succeeded
4523
+ */
4524
+ _updateFontSize(value) {
4525
+ if (this._editor && this._editor.wrapper) {
4526
+ this._editor.options.fontSize = value || "";
4527
+ this._editor.wrapper.style.setProperty("--instance-font-size", this._editor.options.fontSize);
4528
+ this._editor.updatePreview();
4529
+ return true;
4530
+ }
4531
+ return false;
4532
+ }
4533
+ /**
4534
+ * Update line height efficiently
4535
+ * @private
4536
+ * @param {string} value - New line height value
4537
+ * @returns {boolean} True if direct update succeeded
4538
+ */
4539
+ _updateLineHeight(value) {
4540
+ if (this._editor && this._editor.wrapper) {
4541
+ const numeric = parseFloat(value);
4542
+ const lineHeight = Number.isFinite(numeric) ? numeric : this._editor.options.lineHeight;
4543
+ this._editor.options.lineHeight = lineHeight;
4544
+ this._editor.wrapper.style.setProperty("--instance-line-height", String(lineHeight));
4545
+ this._editor.updatePreview();
4546
+ return true;
4547
+ }
4548
+ return false;
4549
+ }
4550
+ /**
4551
+ * Re-inject styles (useful for theme changes)
4552
+ * @private
4553
+ */
4554
+ _reinjectStyles() {
4555
+ if (this._baseStyleElement && this._baseStyleElement.parentNode) {
4556
+ this._baseStyleElement.remove();
4557
+ }
4558
+ this._injectStyles();
4559
+ }
4560
+ /**
4561
+ * Reinitialize the entire editor (for major option changes)
4562
+ * @private
4563
+ */
4564
+ _reinitializeEditor() {
4565
+ const currentValue = this._editor ? this._editor.getValue() : "";
4566
+ this._cleanup();
4567
+ this._initialized = false;
4568
+ this.shadowRoot.innerHTML = "";
4569
+ if (currentValue && !this.getAttribute("value")) {
4570
+ this.setAttribute("value", currentValue);
4571
+ }
4572
+ this._initializeEditor();
4573
+ }
4574
+ /**
4575
+ * Handle content changes from OverType
4576
+ * @private
4577
+ * @param {string} value - New editor value
4578
+ */
4579
+ _handleChange(value) {
4580
+ this._updateValueAttribute(value);
4581
+ if (!this._initialized || !this._editor) {
4582
+ return;
4583
+ }
4584
+ this._dispatchEvent("change", {
4585
+ value,
4586
+ editor: this._editor
4587
+ });
4588
+ }
4589
+ /**
4590
+ * Handle keydown events from OverType
4591
+ * @private
4592
+ * @param {KeyboardEvent} event - Keyboard event
4593
+ */
4594
+ _handleKeydown(event) {
4595
+ this._dispatchEvent("keydown", {
4596
+ event,
4597
+ editor: this._editor
4598
+ });
4599
+ }
4600
+ /**
4601
+ * Update value attribute without triggering observer
4602
+ * @private
4603
+ * @param {string} value - New value
4604
+ */
4605
+ _updateValueAttribute(value) {
4606
+ const currentAttrValue = this.getAttribute("value");
4607
+ if (currentAttrValue !== value) {
4608
+ this._silentUpdate = true;
4609
+ this.setAttribute("value", value);
4610
+ this._silentUpdate = false;
4611
+ }
4612
+ }
4613
+ /**
4614
+ * Dispatch custom events
4615
+ * @private
4616
+ * @param {string} eventName - Event name
4617
+ * @param {Object} detail - Event detail
4618
+ */
4619
+ _dispatchEvent(eventName, detail = {}) {
4620
+ const event = new CustomEvent(eventName, {
4621
+ detail,
4622
+ bubbles: true,
4623
+ composed: true
4624
+ });
4625
+ this.dispatchEvent(event);
4626
+ }
4627
+ /**
4628
+ * Cleanup editor and remove listeners
4629
+ * @private
4630
+ */
4631
+ _cleanup() {
4632
+ if (this._selectionChangeHandler) {
4633
+ document.removeEventListener("selectionchange", this._selectionChangeHandler);
4634
+ this._selectionChangeHandler = null;
4635
+ }
4636
+ if (this._editor && typeof this._editor.destroy === "function") {
4637
+ this._editor.destroy();
4638
+ }
4639
+ this._editor = null;
4640
+ this._initialized = false;
4641
+ if (this.shadowRoot) {
4642
+ this.shadowRoot.innerHTML = "";
4643
+ }
4644
+ }
4645
+ // ===== PUBLIC API METHODS =====
4646
+ /**
4647
+ * Refresh theme styles (useful when theme object is updated without changing theme name)
4648
+ * @public
4649
+ */
4650
+ refreshTheme() {
4651
+ if (this._initialized) {
4652
+ this._reinjectStyles();
4653
+ }
4654
+ }
4655
+ /**
4656
+ * Get current editor value
4657
+ * @returns {string} Current markdown content
4658
+ */
4659
+ getValue() {
4660
+ return this._editor ? this._editor.getValue() : this.getAttribute("value") || "";
4661
+ }
4662
+ /**
4663
+ * Set editor value
4664
+ * @param {string} value - New markdown content
4665
+ */
4666
+ setValue(value) {
4667
+ if (this._editor) {
4668
+ this._editor.setValue(value);
4669
+ } else {
4670
+ this.setAttribute("value", value);
4671
+ }
4672
+ }
4673
+ /**
4674
+ * Get rendered HTML
4675
+ * @returns {string} Rendered HTML
4676
+ */
4677
+ getHTML() {
4678
+ return this._editor ? this._editor.getRenderedHTML(false) : "";
4679
+ }
4680
+ /**
4681
+ * Insert text at cursor position
4682
+ * @param {string} text - Text to insert
4683
+ */
4684
+ insertText(text) {
4685
+ if (!this._editor || typeof text !== "string") {
4686
+ return;
4687
+ }
4688
+ this._editor.insertText(text);
4689
+ }
4690
+ /**
4691
+ * Focus the editor
4692
+ */
4693
+ focus() {
4694
+ if (this._editor && this._editor.textarea) {
4695
+ this._editor.textarea.focus();
4696
+ }
4697
+ }
4698
+ /**
4699
+ * Blur the editor
4700
+ */
4701
+ blur() {
4702
+ if (this._editor && this._editor.textarea) {
4703
+ this._editor.textarea.blur();
4704
+ }
4705
+ }
4706
+ /**
4707
+ * Get editor statistics
4708
+ * @returns {Object} Statistics object
4709
+ */
4710
+ getStats() {
4711
+ if (!this._editor || !this._editor.textarea)
4712
+ return null;
4713
+ const value = this._editor.textarea.value;
4714
+ const lines = value.split("\n");
4715
+ const chars = value.length;
4716
+ const words = value.split(/\s+/).filter((w) => w.length > 0).length;
4717
+ const selectionStart = this._editor.textarea.selectionStart;
4718
+ const beforeCursor = value.substring(0, selectionStart);
4719
+ const linesBefore = beforeCursor.split("\n");
4720
+ const currentLine = linesBefore.length;
4721
+ const currentColumn = linesBefore[linesBefore.length - 1].length + 1;
4722
+ return {
4723
+ characters: chars,
4724
+ words,
4725
+ lines: lines.length,
4726
+ line: currentLine,
4727
+ column: currentColumn
4728
+ };
4729
+ }
4730
+ /**
4731
+ * Check if editor is ready
4732
+ * @returns {boolean} True if editor is initialized
4733
+ */
4734
+ isReady() {
4735
+ return this._initialized && this._editor !== null;
4736
+ }
4737
+ /**
4738
+ * Get the internal OverType instance
4739
+ * @returns {OverType} The OverType editor instance
4740
+ */
4741
+ getEditor() {
4742
+ return this._editor;
4743
+ }
4744
+ };
4745
+ if (!customElements.get("overtype-editor")) {
4746
+ customElements.define("overtype-editor", OverTypeEditor);
4747
+ }
4748
+ var overtype_webcomponent_default = OverTypeEditor;
4749
+ export {
4750
+ overtype_webcomponent_default as default
4751
+ };
4752
+ /**
4753
+ * OverType - A lightweight markdown editor library with perfect WYSIWYG alignment
4754
+ * @version 1.0.0
4755
+ * @license MIT
4756
+ */
4757
+ /**
4758
+ * OverType Web Component
4759
+ * A custom element wrapper for the OverType markdown editor with Shadow DOM isolation
4760
+ * @version 1.0.0
4761
+ * @license MIT
4762
+ */
4763
+ //# sourceMappingURL=overtype-webcomponent.esm.js.map