overtype 1.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,2576 @@
1
+ /**
2
+ * OverType v1.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
+ * Escape HTML special characters
19
+ * @param {string} text - Raw text to escape
20
+ * @returns {string} Escaped HTML-safe text
21
+ */
22
+ static escapeHtml(text) {
23
+ const map = {
24
+ "&": "&",
25
+ "<": "&lt;",
26
+ ">": "&gt;",
27
+ '"': "&quot;",
28
+ "'": "&#39;"
29
+ };
30
+ return text.replace(/[&<>"']/g, (m) => map[m]);
31
+ }
32
+ /**
33
+ * Preserve leading spaces as non-breaking spaces
34
+ * @param {string} html - HTML string
35
+ * @param {string} originalLine - Original line with spaces
36
+ * @returns {string} HTML with preserved indentation
37
+ */
38
+ static preserveIndentation(html, originalLine) {
39
+ const leadingSpaces = originalLine.match(/^(\s*)/)[1];
40
+ const indentation = leadingSpaces.replace(/ /g, "&nbsp;");
41
+ return html.replace(/^\s*/, indentation);
42
+ }
43
+ /**
44
+ * Parse headers (h1-h3 only)
45
+ * @param {string} html - HTML line to parse
46
+ * @returns {string} Parsed HTML with header styling
47
+ */
48
+ static parseHeader(html) {
49
+ return html.replace(/^(#{1,3})\s(.+)$/, (match, hashes, content) => {
50
+ const level = hashes.length;
51
+ const levelClasses = ["h1", "h2", "h3"];
52
+ return `<span class="header ${levelClasses[level - 1]}"><span class="syntax-marker">${hashes}</span> ${content}</span>`;
53
+ });
54
+ }
55
+ /**
56
+ * Parse horizontal rules
57
+ * @param {string} html - HTML line to parse
58
+ * @returns {string|null} Parsed horizontal rule or null
59
+ */
60
+ static parseHorizontalRule(html) {
61
+ if (html.match(/^(-{3,}|\*{3,}|_{3,})$/)) {
62
+ return `<div><span class="hr-marker">${html}</span></div>`;
63
+ }
64
+ return null;
65
+ }
66
+ /**
67
+ * Parse blockquotes
68
+ * @param {string} html - HTML line to parse
69
+ * @returns {string} Parsed blockquote
70
+ */
71
+ static parseBlockquote(html) {
72
+ return html.replace(/^&gt; (.+)$/, (match, content) => {
73
+ return `<span class="blockquote"><span class="syntax-marker">&gt;</span> ${content}</span>`;
74
+ });
75
+ }
76
+ /**
77
+ * Parse bullet lists
78
+ * @param {string} html - HTML line to parse
79
+ * @returns {string} Parsed bullet list item
80
+ */
81
+ static parseBulletList(html) {
82
+ return html.replace(/^((?:&nbsp;)*)([-*])\s(.+)$/, (match, indent, marker, content) => {
83
+ return `${indent}<span class="syntax-marker">${marker}</span> ${content}`;
84
+ });
85
+ }
86
+ /**
87
+ * Parse numbered lists
88
+ * @param {string} html - HTML line to parse
89
+ * @returns {string} Parsed numbered list item
90
+ */
91
+ static parseNumberedList(html) {
92
+ return html.replace(/^((?:&nbsp;)*)(\d+\.)\s(.+)$/, (match, indent, marker, content) => {
93
+ return `${indent}<span class="syntax-marker">${marker}</span> ${content}`;
94
+ });
95
+ }
96
+ /**
97
+ * Parse code blocks (markers only)
98
+ * @param {string} html - HTML line to parse
99
+ * @returns {string|null} Parsed code fence or null
100
+ */
101
+ static parseCodeBlock(html) {
102
+ if (html.startsWith("```")) {
103
+ return `<div><span class="code-fence">${html}</span></div>`;
104
+ }
105
+ return null;
106
+ }
107
+ /**
108
+ * Parse bold text
109
+ * @param {string} html - HTML with potential bold markdown
110
+ * @returns {string} HTML with bold styling
111
+ */
112
+ static parseBold(html) {
113
+ html = html.replace(/\*\*(.+?)\*\*/g, '<strong><span class="syntax-marker">**</span>$1<span class="syntax-marker">**</span></strong>');
114
+ html = html.replace(/__(.+?)__/g, '<strong><span class="syntax-marker">__</span>$1<span class="syntax-marker">__</span></strong>');
115
+ return html;
116
+ }
117
+ /**
118
+ * Parse italic text
119
+ * Note: Uses lookbehind assertions - requires modern browsers
120
+ * @param {string} html - HTML with potential italic markdown
121
+ * @returns {string} HTML with italic styling
122
+ */
123
+ static parseItalic(html) {
124
+ html = html.replace(new RegExp("(?<!\\*)\\*(?!\\*)(.+?)(?<!\\*)\\*(?!\\*)", "g"), '<em><span class="syntax-marker">*</span>$1<span class="syntax-marker">*</span></em>');
125
+ html = html.replace(new RegExp("(?<!_)_(?!_)(.+?)(?<!_)_(?!_)", "g"), '<em><span class="syntax-marker">_</span>$1<span class="syntax-marker">_</span></em>');
126
+ return html;
127
+ }
128
+ /**
129
+ * Parse inline code
130
+ * @param {string} html - HTML with potential code markdown
131
+ * @returns {string} HTML with code styling
132
+ */
133
+ static parseInlineCode(html) {
134
+ return html.replace(/`(.+?)`/g, '<code><span class="syntax-marker">`</span>$1<span class="syntax-marker">`</span></code>');
135
+ }
136
+ /**
137
+ * Parse links
138
+ * @param {string} html - HTML with potential link markdown
139
+ * @returns {string} HTML with link styling
140
+ */
141
+ static parseLinks(html) {
142
+ return html.replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2"><span class="syntax-marker">[</span>$1<span class="syntax-marker">](</span><span class="syntax-marker">$2</span><span class="syntax-marker">)</span></a>');
143
+ }
144
+ /**
145
+ * Parse all inline elements in correct order
146
+ * @param {string} text - Text with potential inline markdown
147
+ * @returns {string} HTML with all inline styling
148
+ */
149
+ static parseInlineElements(text) {
150
+ let html = text;
151
+ html = this.parseInlineCode(html);
152
+ html = this.parseLinks(html);
153
+ html = this.parseBold(html);
154
+ html = this.parseItalic(html);
155
+ return html;
156
+ }
157
+ /**
158
+ * Parse a single line of markdown
159
+ * @param {string} line - Raw markdown line
160
+ * @returns {string} Parsed HTML line
161
+ */
162
+ static parseLine(line) {
163
+ let html = this.escapeHtml(line);
164
+ html = this.preserveIndentation(html, line);
165
+ const horizontalRule = this.parseHorizontalRule(html);
166
+ if (horizontalRule)
167
+ return horizontalRule;
168
+ const codeBlock = this.parseCodeBlock(html);
169
+ if (codeBlock)
170
+ return codeBlock;
171
+ html = this.parseHeader(html);
172
+ html = this.parseBlockquote(html);
173
+ html = this.parseBulletList(html);
174
+ html = this.parseNumberedList(html);
175
+ html = this.parseInlineElements(html);
176
+ if (html.trim() === "") {
177
+ return "<div>&nbsp;</div>";
178
+ }
179
+ return `<div>${html}</div>`;
180
+ }
181
+ /**
182
+ * Parse full markdown text
183
+ * @param {string} text - Full markdown text
184
+ * @param {number} activeLine - Currently active line index (optional)
185
+ * @param {boolean} showActiveLineRaw - Show raw markdown on active line
186
+ * @returns {string} Parsed HTML
187
+ */
188
+ static parse(text, activeLine = -1, showActiveLineRaw = false) {
189
+ const lines = text.split("\n");
190
+ const parsedLines = lines.map((line, index) => {
191
+ if (showActiveLineRaw && index === activeLine) {
192
+ const content = this.escapeHtml(line) || "&nbsp;";
193
+ return `<div class="raw-line">${content}</div>`;
194
+ }
195
+ return this.parseLine(line);
196
+ });
197
+ return parsedLines.join("");
198
+ }
199
+ };
200
+
201
+ // node_modules/markdown-actions/dist/markdown-actions.esm.js
202
+ var __defProp2 = Object.defineProperty;
203
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
204
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
205
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
206
+ var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
207
+ var __spreadValues = (a, b) => {
208
+ for (var prop in b || (b = {}))
209
+ if (__hasOwnProp.call(b, prop))
210
+ __defNormalProp2(a, prop, b[prop]);
211
+ if (__getOwnPropSymbols)
212
+ for (var prop of __getOwnPropSymbols(b)) {
213
+ if (__propIsEnum.call(b, prop))
214
+ __defNormalProp2(a, prop, b[prop]);
215
+ }
216
+ return a;
217
+ };
218
+ var FORMATS = {
219
+ bold: {
220
+ prefix: "**",
221
+ suffix: "**",
222
+ trimFirst: true
223
+ },
224
+ italic: {
225
+ prefix: "_",
226
+ suffix: "_",
227
+ trimFirst: true
228
+ },
229
+ code: {
230
+ prefix: "`",
231
+ suffix: "`",
232
+ blockPrefix: "```",
233
+ blockSuffix: "```"
234
+ },
235
+ link: {
236
+ prefix: "[",
237
+ suffix: "](url)",
238
+ replaceNext: "url",
239
+ scanFor: "https?://"
240
+ },
241
+ bulletList: {
242
+ prefix: "- ",
243
+ multiline: true,
244
+ unorderedList: true
245
+ },
246
+ numberedList: {
247
+ prefix: "1. ",
248
+ multiline: true,
249
+ orderedList: true
250
+ },
251
+ quote: {
252
+ prefix: "> ",
253
+ multiline: true,
254
+ surroundWithNewlines: true
255
+ },
256
+ taskList: {
257
+ prefix: "- [ ] ",
258
+ multiline: true,
259
+ surroundWithNewlines: true
260
+ },
261
+ header1: { prefix: "# " },
262
+ header2: { prefix: "## " },
263
+ header3: { prefix: "### " },
264
+ header4: { prefix: "#### " },
265
+ header5: { prefix: "##### " },
266
+ header6: { prefix: "###### " }
267
+ };
268
+ function getDefaultStyle() {
269
+ return {
270
+ prefix: "",
271
+ suffix: "",
272
+ blockPrefix: "",
273
+ blockSuffix: "",
274
+ multiline: false,
275
+ replaceNext: "",
276
+ prefixSpace: false,
277
+ scanFor: "",
278
+ surroundWithNewlines: false,
279
+ orderedList: false,
280
+ unorderedList: false,
281
+ trimFirst: false
282
+ };
283
+ }
284
+ function mergeWithDefaults(format) {
285
+ return __spreadValues(__spreadValues({}, getDefaultStyle()), format);
286
+ }
287
+ var debugMode = false;
288
+ function getDebugMode() {
289
+ return debugMode;
290
+ }
291
+ function debugLog(funcName, message, data) {
292
+ if (!debugMode)
293
+ return;
294
+ console.group(`\u{1F50D} ${funcName}`);
295
+ console.log(message);
296
+ if (data) {
297
+ console.log("Data:", data);
298
+ }
299
+ console.groupEnd();
300
+ }
301
+ function debugSelection(textarea, label) {
302
+ if (!debugMode)
303
+ return;
304
+ const selected = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
305
+ console.group(`\u{1F4CD} Selection: ${label}`);
306
+ console.log("Position:", `${textarea.selectionStart}-${textarea.selectionEnd}`);
307
+ console.log("Selected text:", JSON.stringify(selected));
308
+ console.log("Length:", selected.length);
309
+ const before = textarea.value.slice(Math.max(0, textarea.selectionStart - 10), textarea.selectionStart);
310
+ const after = textarea.value.slice(textarea.selectionEnd, Math.min(textarea.value.length, textarea.selectionEnd + 10));
311
+ console.log("Context:", JSON.stringify(before) + "[SELECTION]" + JSON.stringify(after));
312
+ console.groupEnd();
313
+ }
314
+ function debugResult(result) {
315
+ if (!debugMode)
316
+ return;
317
+ console.group("\u{1F4DD} Result");
318
+ console.log("Text to insert:", JSON.stringify(result.text));
319
+ console.log("New selection:", `${result.selectionStart}-${result.selectionEnd}`);
320
+ console.groupEnd();
321
+ }
322
+ var canInsertText = null;
323
+ function insertText(textarea, { text, selectionStart, selectionEnd }) {
324
+ const debugMode2 = getDebugMode();
325
+ if (debugMode2) {
326
+ console.group("\u{1F527} insertText");
327
+ console.log("Current selection:", `${textarea.selectionStart}-${textarea.selectionEnd}`);
328
+ console.log("Text to insert:", JSON.stringify(text));
329
+ console.log("New selection to set:", selectionStart, "-", selectionEnd);
330
+ }
331
+ textarea.focus();
332
+ const originalSelectionStart = textarea.selectionStart;
333
+ const originalSelectionEnd = textarea.selectionEnd;
334
+ const before = textarea.value.slice(0, originalSelectionStart);
335
+ const after = textarea.value.slice(originalSelectionEnd);
336
+ if (debugMode2) {
337
+ console.log("Before text (last 20):", JSON.stringify(before.slice(-20)));
338
+ console.log("After text (first 20):", JSON.stringify(after.slice(0, 20)));
339
+ console.log("Selected text being replaced:", JSON.stringify(textarea.value.slice(originalSelectionStart, originalSelectionEnd)));
340
+ }
341
+ const originalValue = textarea.value;
342
+ const hasSelection = originalSelectionStart !== originalSelectionEnd;
343
+ if (!hasSelection && (canInsertText === null || canInsertText === true)) {
344
+ textarea.contentEditable = "true";
345
+ try {
346
+ canInsertText = document.execCommand("insertText", false, text);
347
+ } catch (error) {
348
+ canInsertText = false;
349
+ }
350
+ textarea.contentEditable = "false";
351
+ } else if (hasSelection) {
352
+ if (debugMode2)
353
+ console.log("Has selection, skipping execCommand and using manual mode");
354
+ canInsertText = false;
355
+ }
356
+ if (debugMode2) {
357
+ console.log("canInsertText before:", canInsertText);
358
+ console.log("execCommand result:", canInsertText);
359
+ }
360
+ if (canInsertText) {
361
+ const expectedValue = before + text + after;
362
+ const actualValue = textarea.value;
363
+ if (debugMode2) {
364
+ console.log("Expected length:", expectedValue.length);
365
+ console.log("Actual length:", actualValue.length);
366
+ }
367
+ if (actualValue !== expectedValue) {
368
+ if (debugMode2) {
369
+ console.log("execCommand changed the value but not as expected");
370
+ console.log("Expected:", JSON.stringify(expectedValue.slice(0, 100)));
371
+ console.log("Actual:", JSON.stringify(actualValue.slice(0, 100)));
372
+ }
373
+ }
374
+ }
375
+ if (!canInsertText) {
376
+ if (debugMode2)
377
+ console.log("Using manual insertion");
378
+ if (textarea.value === originalValue) {
379
+ if (debugMode2)
380
+ console.log("Value unchanged, doing manual replacement");
381
+ try {
382
+ document.execCommand("ms-beginUndoUnit");
383
+ } catch (e) {
384
+ }
385
+ textarea.value = before + text + after;
386
+ try {
387
+ document.execCommand("ms-endUndoUnit");
388
+ } catch (e) {
389
+ }
390
+ textarea.dispatchEvent(new CustomEvent("input", { bubbles: true, cancelable: true }));
391
+ } else {
392
+ if (debugMode2)
393
+ console.log("Value was changed by execCommand, skipping manual insertion");
394
+ }
395
+ }
396
+ if (debugMode2)
397
+ console.log("Setting selection range:", selectionStart, selectionEnd);
398
+ if (selectionStart != null && selectionEnd != null) {
399
+ textarea.setSelectionRange(selectionStart, selectionEnd);
400
+ } else {
401
+ textarea.setSelectionRange(originalSelectionStart, textarea.selectionEnd);
402
+ }
403
+ if (debugMode2) {
404
+ console.log("Final value length:", textarea.value.length);
405
+ console.groupEnd();
406
+ }
407
+ }
408
+ function isMultipleLines(string) {
409
+ return string.trim().split("\n").length > 1;
410
+ }
411
+ function wordSelectionStart(text, i) {
412
+ let index = i;
413
+ while (text[index] && text[index - 1] != null && !text[index - 1].match(/\s/)) {
414
+ index--;
415
+ }
416
+ return index;
417
+ }
418
+ function wordSelectionEnd(text, i, multiline) {
419
+ let index = i;
420
+ const breakpoint = multiline ? /\n/ : /\s/;
421
+ while (text[index] && !text[index].match(breakpoint)) {
422
+ index++;
423
+ }
424
+ return index;
425
+ }
426
+ function expandSelectionToLine(textarea) {
427
+ const lines = textarea.value.split("\n");
428
+ let counter = 0;
429
+ for (let index = 0; index < lines.length; index++) {
430
+ const lineLength = lines[index].length + 1;
431
+ if (textarea.selectionStart >= counter && textarea.selectionStart < counter + lineLength) {
432
+ textarea.selectionStart = counter;
433
+ }
434
+ if (textarea.selectionEnd >= counter && textarea.selectionEnd < counter + lineLength) {
435
+ if (index === lines.length - 1) {
436
+ textarea.selectionEnd = Math.min(counter + lines[index].length, textarea.value.length);
437
+ } else {
438
+ textarea.selectionEnd = counter + lineLength - 1;
439
+ }
440
+ }
441
+ counter += lineLength;
442
+ }
443
+ }
444
+ function expandSelectedText(textarea, prefixToUse, suffixToUse, multiline = false) {
445
+ if (textarea.selectionStart === textarea.selectionEnd) {
446
+ textarea.selectionStart = wordSelectionStart(textarea.value, textarea.selectionStart);
447
+ textarea.selectionEnd = wordSelectionEnd(textarea.value, textarea.selectionEnd, multiline);
448
+ } else {
449
+ const expandedSelectionStart = textarea.selectionStart - prefixToUse.length;
450
+ const expandedSelectionEnd = textarea.selectionEnd + suffixToUse.length;
451
+ const beginsWithPrefix = textarea.value.slice(expandedSelectionStart, textarea.selectionStart) === prefixToUse;
452
+ const endsWithSuffix = textarea.value.slice(textarea.selectionEnd, expandedSelectionEnd) === suffixToUse;
453
+ if (beginsWithPrefix && endsWithSuffix) {
454
+ textarea.selectionStart = expandedSelectionStart;
455
+ textarea.selectionEnd = expandedSelectionEnd;
456
+ }
457
+ }
458
+ return textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
459
+ }
460
+ function newlinesToSurroundSelectedText(textarea) {
461
+ const beforeSelection = textarea.value.slice(0, textarea.selectionStart);
462
+ const afterSelection = textarea.value.slice(textarea.selectionEnd);
463
+ const breaksBefore = beforeSelection.match(/\n*$/);
464
+ const breaksAfter = afterSelection.match(/^\n*/);
465
+ const newlinesBeforeSelection = breaksBefore ? breaksBefore[0].length : 0;
466
+ const newlinesAfterSelection = breaksAfter ? breaksAfter[0].length : 0;
467
+ let newlinesToAppend = "";
468
+ let newlinesToPrepend = "";
469
+ if (beforeSelection.match(/\S/) && newlinesBeforeSelection < 2) {
470
+ newlinesToAppend = "\n".repeat(2 - newlinesBeforeSelection);
471
+ }
472
+ if (afterSelection.match(/\S/) && newlinesAfterSelection < 2) {
473
+ newlinesToPrepend = "\n".repeat(2 - newlinesAfterSelection);
474
+ }
475
+ return { newlinesToAppend, newlinesToPrepend };
476
+ }
477
+ function applyLineOperation(textarea, operation, options = {}) {
478
+ const originalStart = textarea.selectionStart;
479
+ const originalEnd = textarea.selectionEnd;
480
+ const noInitialSelection = originalStart === originalEnd;
481
+ const value = textarea.value;
482
+ let lineStart = originalStart;
483
+ while (lineStart > 0 && value[lineStart - 1] !== "\n") {
484
+ lineStart--;
485
+ }
486
+ if (noInitialSelection) {
487
+ let lineEnd = originalStart;
488
+ while (lineEnd < value.length && value[lineEnd] !== "\n") {
489
+ lineEnd++;
490
+ }
491
+ textarea.selectionStart = lineStart;
492
+ textarea.selectionEnd = lineEnd;
493
+ } else {
494
+ expandSelectionToLine(textarea);
495
+ }
496
+ const result = operation(textarea);
497
+ if (options.adjustSelection) {
498
+ const selectedText = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
499
+ const isRemoving = selectedText.startsWith(options.prefix);
500
+ const adjusted = options.adjustSelection(isRemoving, originalStart, originalEnd, lineStart);
501
+ result.selectionStart = adjusted.start;
502
+ result.selectionEnd = adjusted.end;
503
+ } else if (options.prefix) {
504
+ const selectedText = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
505
+ const isRemoving = selectedText.startsWith(options.prefix);
506
+ if (noInitialSelection) {
507
+ if (isRemoving) {
508
+ result.selectionStart = Math.max(originalStart - options.prefix.length, lineStart);
509
+ result.selectionEnd = result.selectionStart;
510
+ } else {
511
+ result.selectionStart = originalStart + options.prefix.length;
512
+ result.selectionEnd = result.selectionStart;
513
+ }
514
+ } else {
515
+ if (isRemoving) {
516
+ result.selectionStart = Math.max(originalStart - options.prefix.length, lineStart);
517
+ result.selectionEnd = Math.max(originalEnd - options.prefix.length, lineStart);
518
+ } else {
519
+ result.selectionStart = originalStart + options.prefix.length;
520
+ result.selectionEnd = originalEnd + options.prefix.length;
521
+ }
522
+ }
523
+ }
524
+ return result;
525
+ }
526
+ function blockStyle(textarea, style) {
527
+ let newlinesToAppend;
528
+ let newlinesToPrepend;
529
+ const { prefix, suffix, blockPrefix, blockSuffix, replaceNext, prefixSpace, scanFor, surroundWithNewlines, trimFirst } = style;
530
+ const originalSelectionStart = textarea.selectionStart;
531
+ const originalSelectionEnd = textarea.selectionEnd;
532
+ let selectedText = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
533
+ let prefixToUse = isMultipleLines(selectedText) && blockPrefix && blockPrefix.length > 0 ? `${blockPrefix}
534
+ ` : prefix;
535
+ let suffixToUse = isMultipleLines(selectedText) && blockSuffix && blockSuffix.length > 0 ? `
536
+ ${blockSuffix}` : suffix;
537
+ if (prefixSpace) {
538
+ const beforeSelection = textarea.value[textarea.selectionStart - 1];
539
+ if (textarea.selectionStart !== 0 && beforeSelection != null && !beforeSelection.match(/\s/)) {
540
+ prefixToUse = ` ${prefixToUse}`;
541
+ }
542
+ }
543
+ selectedText = expandSelectedText(textarea, prefixToUse, suffixToUse, style.multiline);
544
+ let selectionStart = textarea.selectionStart;
545
+ let selectionEnd = textarea.selectionEnd;
546
+ const hasReplaceNext = replaceNext && replaceNext.length > 0 && suffixToUse.indexOf(replaceNext) > -1 && selectedText.length > 0;
547
+ if (surroundWithNewlines) {
548
+ const ref = newlinesToSurroundSelectedText(textarea);
549
+ newlinesToAppend = ref.newlinesToAppend;
550
+ newlinesToPrepend = ref.newlinesToPrepend;
551
+ prefixToUse = newlinesToAppend + prefix;
552
+ suffixToUse += newlinesToPrepend;
553
+ }
554
+ if (selectedText.startsWith(prefixToUse) && selectedText.endsWith(suffixToUse)) {
555
+ const replacementText = selectedText.slice(prefixToUse.length, selectedText.length - suffixToUse.length);
556
+ if (originalSelectionStart === originalSelectionEnd) {
557
+ let position = originalSelectionStart - prefixToUse.length;
558
+ position = Math.max(position, selectionStart);
559
+ position = Math.min(position, selectionStart + replacementText.length);
560
+ selectionStart = selectionEnd = position;
561
+ } else {
562
+ selectionEnd = selectionStart + replacementText.length;
563
+ }
564
+ return { text: replacementText, selectionStart, selectionEnd };
565
+ } else if (!hasReplaceNext) {
566
+ let replacementText = prefixToUse + selectedText + suffixToUse;
567
+ selectionStart = originalSelectionStart + prefixToUse.length;
568
+ selectionEnd = originalSelectionEnd + prefixToUse.length;
569
+ const whitespaceEdges = selectedText.match(/^\s*|\s*$/g);
570
+ if (trimFirst && whitespaceEdges) {
571
+ const leadingWhitespace = whitespaceEdges[0] || "";
572
+ const trailingWhitespace = whitespaceEdges[1] || "";
573
+ replacementText = leadingWhitespace + prefixToUse + selectedText.trim() + suffixToUse + trailingWhitespace;
574
+ selectionStart += leadingWhitespace.length;
575
+ selectionEnd -= trailingWhitespace.length;
576
+ }
577
+ return { text: replacementText, selectionStart, selectionEnd };
578
+ } else if (scanFor && scanFor.length > 0 && selectedText.match(scanFor)) {
579
+ suffixToUse = suffixToUse.replace(replaceNext, selectedText);
580
+ const replacementText = prefixToUse + suffixToUse;
581
+ selectionStart = selectionEnd = selectionStart + prefixToUse.length;
582
+ return { text: replacementText, selectionStart, selectionEnd };
583
+ } else {
584
+ const replacementText = prefixToUse + selectedText + suffixToUse;
585
+ selectionStart = selectionStart + prefixToUse.length + selectedText.length + suffixToUse.indexOf(replaceNext);
586
+ selectionEnd = selectionStart + replaceNext.length;
587
+ return { text: replacementText, selectionStart, selectionEnd };
588
+ }
589
+ }
590
+ function multilineStyle(textarea, style) {
591
+ const { prefix, suffix, surroundWithNewlines } = style;
592
+ let text = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
593
+ let selectionStart = textarea.selectionStart;
594
+ let selectionEnd = textarea.selectionEnd;
595
+ const lines = text.split("\n");
596
+ const undoStyle = lines.every((line) => line.startsWith(prefix) && (!suffix || line.endsWith(suffix)));
597
+ if (undoStyle) {
598
+ text = lines.map((line) => {
599
+ let result = line.slice(prefix.length);
600
+ if (suffix) {
601
+ result = result.slice(0, result.length - suffix.length);
602
+ }
603
+ return result;
604
+ }).join("\n");
605
+ selectionEnd = selectionStart + text.length;
606
+ } else {
607
+ text = lines.map((line) => prefix + line + (suffix || "")).join("\n");
608
+ if (surroundWithNewlines) {
609
+ const { newlinesToAppend, newlinesToPrepend } = newlinesToSurroundSelectedText(textarea);
610
+ selectionStart += newlinesToAppend.length;
611
+ selectionEnd = selectionStart + text.length;
612
+ text = newlinesToAppend + text + newlinesToPrepend;
613
+ }
614
+ }
615
+ return { text, selectionStart, selectionEnd };
616
+ }
617
+ function undoOrderedListStyle(text) {
618
+ const lines = text.split("\n");
619
+ const orderedListRegex = /^\d+\.\s+/;
620
+ const shouldUndoOrderedList = lines.every((line) => orderedListRegex.test(line));
621
+ let result = lines;
622
+ if (shouldUndoOrderedList) {
623
+ result = lines.map((line) => line.replace(orderedListRegex, ""));
624
+ }
625
+ return {
626
+ text: result.join("\n"),
627
+ processed: shouldUndoOrderedList
628
+ };
629
+ }
630
+ function undoUnorderedListStyle(text) {
631
+ const lines = text.split("\n");
632
+ const unorderedListPrefix = "- ";
633
+ const shouldUndoUnorderedList = lines.every((line) => line.startsWith(unorderedListPrefix));
634
+ let result = lines;
635
+ if (shouldUndoUnorderedList) {
636
+ result = lines.map((line) => line.slice(unorderedListPrefix.length));
637
+ }
638
+ return {
639
+ text: result.join("\n"),
640
+ processed: shouldUndoUnorderedList
641
+ };
642
+ }
643
+ function makePrefix(index, unorderedList) {
644
+ if (unorderedList) {
645
+ return "- ";
646
+ } else {
647
+ return `${index + 1}. `;
648
+ }
649
+ }
650
+ function clearExistingListStyle(style, selectedText) {
651
+ let undoResult;
652
+ let undoResultOppositeList;
653
+ let pristineText;
654
+ if (style.orderedList) {
655
+ undoResult = undoOrderedListStyle(selectedText);
656
+ undoResultOppositeList = undoUnorderedListStyle(undoResult.text);
657
+ pristineText = undoResultOppositeList.text;
658
+ } else {
659
+ undoResult = undoUnorderedListStyle(selectedText);
660
+ undoResultOppositeList = undoOrderedListStyle(undoResult.text);
661
+ pristineText = undoResultOppositeList.text;
662
+ }
663
+ return [undoResult, undoResultOppositeList, pristineText];
664
+ }
665
+ function listStyle(textarea, style) {
666
+ const noInitialSelection = textarea.selectionStart === textarea.selectionEnd;
667
+ let selectionStart = textarea.selectionStart;
668
+ let selectionEnd = textarea.selectionEnd;
669
+ expandSelectionToLine(textarea);
670
+ const selectedText = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
671
+ const [undoResult, undoResultOppositeList, pristineText] = clearExistingListStyle(style, selectedText);
672
+ const prefixedLines = pristineText.split("\n").map((value, index) => {
673
+ return `${makePrefix(index, style.unorderedList)}${value}`;
674
+ });
675
+ const totalPrefixLength = prefixedLines.reduce((previousValue, _currentValue, currentIndex) => {
676
+ return previousValue + makePrefix(currentIndex, style.unorderedList).length;
677
+ }, 0);
678
+ const totalPrefixLengthOppositeList = prefixedLines.reduce((previousValue, _currentValue, currentIndex) => {
679
+ return previousValue + makePrefix(currentIndex, !style.unorderedList).length;
680
+ }, 0);
681
+ if (undoResult.processed) {
682
+ if (noInitialSelection) {
683
+ selectionStart = Math.max(selectionStart - makePrefix(0, style.unorderedList).length, 0);
684
+ selectionEnd = selectionStart;
685
+ } else {
686
+ selectionStart = textarea.selectionStart;
687
+ selectionEnd = textarea.selectionEnd - totalPrefixLength;
688
+ }
689
+ return { text: pristineText, selectionStart, selectionEnd };
690
+ }
691
+ const { newlinesToAppend, newlinesToPrepend } = newlinesToSurroundSelectedText(textarea);
692
+ const text = newlinesToAppend + prefixedLines.join("\n") + newlinesToPrepend;
693
+ if (noInitialSelection) {
694
+ selectionStart = Math.max(selectionStart + makePrefix(0, style.unorderedList).length + newlinesToAppend.length, 0);
695
+ selectionEnd = selectionStart;
696
+ } else {
697
+ if (undoResultOppositeList.processed) {
698
+ selectionStart = Math.max(textarea.selectionStart + newlinesToAppend.length, 0);
699
+ selectionEnd = textarea.selectionEnd + newlinesToAppend.length + totalPrefixLength - totalPrefixLengthOppositeList;
700
+ } else {
701
+ selectionStart = Math.max(textarea.selectionStart + newlinesToAppend.length, 0);
702
+ selectionEnd = textarea.selectionEnd + newlinesToAppend.length + totalPrefixLength;
703
+ }
704
+ }
705
+ return { text, selectionStart, selectionEnd };
706
+ }
707
+ function applyListStyle(textarea, style) {
708
+ const result = applyLineOperation(
709
+ textarea,
710
+ (ta) => listStyle(ta, style),
711
+ {
712
+ // Custom selection adjustment for lists
713
+ adjustSelection: (isRemoving, selStart, selEnd, lineStart) => {
714
+ const currentLine = textarea.value.slice(lineStart, textarea.selectionEnd);
715
+ const orderedListRegex = /^\d+\.\s+/;
716
+ const unorderedListRegex = /^- /;
717
+ const hasOrderedList = orderedListRegex.test(currentLine);
718
+ const hasUnorderedList = unorderedListRegex.test(currentLine);
719
+ const isRemovingCurrent = style.orderedList && hasOrderedList || style.unorderedList && hasUnorderedList;
720
+ if (selStart === selEnd) {
721
+ if (isRemovingCurrent) {
722
+ const prefixMatch = currentLine.match(style.orderedList ? orderedListRegex : unorderedListRegex);
723
+ const prefixLength = prefixMatch ? prefixMatch[0].length : 0;
724
+ return {
725
+ start: Math.max(selStart - prefixLength, lineStart),
726
+ end: Math.max(selStart - prefixLength, lineStart)
727
+ };
728
+ } else if (hasOrderedList || hasUnorderedList) {
729
+ const oldPrefixMatch = currentLine.match(hasOrderedList ? orderedListRegex : unorderedListRegex);
730
+ const oldPrefixLength = oldPrefixMatch ? oldPrefixMatch[0].length : 0;
731
+ const newPrefixLength = style.unorderedList ? 2 : 3;
732
+ const adjustment = newPrefixLength - oldPrefixLength;
733
+ return {
734
+ start: selStart + adjustment,
735
+ end: selStart + adjustment
736
+ };
737
+ } else {
738
+ const prefixLength = style.unorderedList ? 2 : 3;
739
+ return {
740
+ start: selStart + prefixLength,
741
+ end: selStart + prefixLength
742
+ };
743
+ }
744
+ } else {
745
+ if (isRemovingCurrent) {
746
+ const prefixMatch = currentLine.match(style.orderedList ? orderedListRegex : unorderedListRegex);
747
+ const prefixLength = prefixMatch ? prefixMatch[0].length : 0;
748
+ return {
749
+ start: Math.max(selStart - prefixLength, lineStart),
750
+ end: Math.max(selEnd - prefixLength, lineStart)
751
+ };
752
+ } else if (hasOrderedList || hasUnorderedList) {
753
+ const oldPrefixMatch = currentLine.match(hasOrderedList ? orderedListRegex : unorderedListRegex);
754
+ const oldPrefixLength = oldPrefixMatch ? oldPrefixMatch[0].length : 0;
755
+ const newPrefixLength = style.unorderedList ? 2 : 3;
756
+ const adjustment = newPrefixLength - oldPrefixLength;
757
+ return {
758
+ start: selStart + adjustment,
759
+ end: selEnd + adjustment
760
+ };
761
+ } else {
762
+ const prefixLength = style.unorderedList ? 2 : 3;
763
+ return {
764
+ start: selStart + prefixLength,
765
+ end: selEnd + prefixLength
766
+ };
767
+ }
768
+ }
769
+ }
770
+ }
771
+ );
772
+ insertText(textarea, result);
773
+ }
774
+ function getActiveFormats(textarea) {
775
+ if (!textarea)
776
+ return [];
777
+ const formats = [];
778
+ const { selectionStart, selectionEnd, value } = textarea;
779
+ const lines = value.split("\n");
780
+ let lineStart = 0;
781
+ let currentLine = "";
782
+ for (const line of lines) {
783
+ if (selectionStart >= lineStart && selectionStart <= lineStart + line.length) {
784
+ currentLine = line;
785
+ break;
786
+ }
787
+ lineStart += line.length + 1;
788
+ }
789
+ if (currentLine.startsWith("- ")) {
790
+ if (currentLine.startsWith("- [ ] ") || currentLine.startsWith("- [x] ")) {
791
+ formats.push("task-list");
792
+ } else {
793
+ formats.push("bullet-list");
794
+ }
795
+ }
796
+ if (/^\d+\.\s/.test(currentLine)) {
797
+ formats.push("numbered-list");
798
+ }
799
+ if (currentLine.startsWith("> ")) {
800
+ formats.push("quote");
801
+ }
802
+ if (currentLine.startsWith("# "))
803
+ formats.push("header");
804
+ if (currentLine.startsWith("## "))
805
+ formats.push("header-2");
806
+ if (currentLine.startsWith("### "))
807
+ formats.push("header-3");
808
+ const lookBehind = Math.max(0, selectionStart - 10);
809
+ const lookAhead = Math.min(value.length, selectionEnd + 10);
810
+ const surrounding = value.slice(lookBehind, lookAhead);
811
+ if (surrounding.includes("**")) {
812
+ const beforeCursor = value.slice(Math.max(0, selectionStart - 100), selectionStart);
813
+ const afterCursor = value.slice(selectionEnd, Math.min(value.length, selectionEnd + 100));
814
+ const lastOpenBold = beforeCursor.lastIndexOf("**");
815
+ const nextCloseBold = afterCursor.indexOf("**");
816
+ if (lastOpenBold !== -1 && nextCloseBold !== -1) {
817
+ formats.push("bold");
818
+ }
819
+ }
820
+ if (surrounding.includes("_")) {
821
+ const beforeCursor = value.slice(Math.max(0, selectionStart - 100), selectionStart);
822
+ const afterCursor = value.slice(selectionEnd, Math.min(value.length, selectionEnd + 100));
823
+ const lastOpenItalic = beforeCursor.lastIndexOf("_");
824
+ const nextCloseItalic = afterCursor.indexOf("_");
825
+ if (lastOpenItalic !== -1 && nextCloseItalic !== -1) {
826
+ formats.push("italic");
827
+ }
828
+ }
829
+ if (surrounding.includes("`")) {
830
+ const beforeCursor = value.slice(Math.max(0, selectionStart - 100), selectionStart);
831
+ const afterCursor = value.slice(selectionEnd, Math.min(value.length, selectionEnd + 100));
832
+ if (beforeCursor.includes("`") && afterCursor.includes("`")) {
833
+ formats.push("code");
834
+ }
835
+ }
836
+ if (surrounding.includes("[") && surrounding.includes("]")) {
837
+ const beforeCursor = value.slice(Math.max(0, selectionStart - 100), selectionStart);
838
+ const afterCursor = value.slice(selectionEnd, Math.min(value.length, selectionEnd + 100));
839
+ const lastOpenBracket = beforeCursor.lastIndexOf("[");
840
+ const nextCloseBracket = afterCursor.indexOf("]");
841
+ if (lastOpenBracket !== -1 && nextCloseBracket !== -1) {
842
+ const afterBracket = value.slice(selectionEnd + nextCloseBracket + 1, selectionEnd + nextCloseBracket + 10);
843
+ if (afterBracket.startsWith("(")) {
844
+ formats.push("link");
845
+ }
846
+ }
847
+ }
848
+ return formats;
849
+ }
850
+ function toggleBold(textarea) {
851
+ if (!textarea || textarea.disabled || textarea.readOnly)
852
+ return;
853
+ debugLog("toggleBold", "Starting");
854
+ debugSelection(textarea, "Before");
855
+ const style = mergeWithDefaults(FORMATS.bold);
856
+ const result = blockStyle(textarea, style);
857
+ debugResult(result);
858
+ insertText(textarea, result);
859
+ debugSelection(textarea, "After");
860
+ }
861
+ function toggleItalic(textarea) {
862
+ if (!textarea || textarea.disabled || textarea.readOnly)
863
+ return;
864
+ const style = mergeWithDefaults(FORMATS.italic);
865
+ const result = blockStyle(textarea, style);
866
+ insertText(textarea, result);
867
+ }
868
+ function toggleCode(textarea) {
869
+ if (!textarea || textarea.disabled || textarea.readOnly)
870
+ return;
871
+ const style = mergeWithDefaults(FORMATS.code);
872
+ const result = blockStyle(textarea, style);
873
+ insertText(textarea, result);
874
+ }
875
+ function insertLink(textarea, options = {}) {
876
+ if (!textarea || textarea.disabled || textarea.readOnly)
877
+ return;
878
+ const selectedText = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
879
+ let style = mergeWithDefaults(FORMATS.link);
880
+ const isURL = selectedText && selectedText.match(/^https?:\/\//);
881
+ if (isURL && !options.url) {
882
+ style.suffix = `](${selectedText})`;
883
+ style.replaceNext = "";
884
+ } else if (options.url) {
885
+ style.suffix = `](${options.url})`;
886
+ style.replaceNext = "";
887
+ }
888
+ if (options.text && !selectedText) {
889
+ const pos = textarea.selectionStart;
890
+ textarea.value = textarea.value.slice(0, pos) + options.text + textarea.value.slice(pos);
891
+ textarea.selectionStart = pos;
892
+ textarea.selectionEnd = pos + options.text.length;
893
+ }
894
+ const result = blockStyle(textarea, style);
895
+ insertText(textarea, result);
896
+ }
897
+ function toggleBulletList(textarea) {
898
+ if (!textarea || textarea.disabled || textarea.readOnly)
899
+ return;
900
+ const style = mergeWithDefaults(FORMATS.bulletList);
901
+ applyListStyle(textarea, style);
902
+ }
903
+ function toggleNumberedList(textarea) {
904
+ if (!textarea || textarea.disabled || textarea.readOnly)
905
+ return;
906
+ const style = mergeWithDefaults(FORMATS.numberedList);
907
+ applyListStyle(textarea, style);
908
+ }
909
+ function toggleQuote(textarea) {
910
+ if (!textarea || textarea.disabled || textarea.readOnly)
911
+ return;
912
+ debugLog("toggleQuote", "Starting");
913
+ debugSelection(textarea, "Initial");
914
+ const style = mergeWithDefaults(FORMATS.quote);
915
+ const result = applyLineOperation(
916
+ textarea,
917
+ (ta) => multilineStyle(ta, style),
918
+ { prefix: style.prefix }
919
+ );
920
+ debugResult(result);
921
+ insertText(textarea, result);
922
+ debugSelection(textarea, "Final");
923
+ }
924
+ function toggleTaskList(textarea) {
925
+ if (!textarea || textarea.disabled || textarea.readOnly)
926
+ return;
927
+ const style = mergeWithDefaults(FORMATS.taskList);
928
+ const result = applyLineOperation(
929
+ textarea,
930
+ (ta) => multilineStyle(ta, style),
931
+ { prefix: style.prefix }
932
+ );
933
+ insertText(textarea, result);
934
+ }
935
+ function insertHeader(textarea, level = 1, toggle = false) {
936
+ if (!textarea || textarea.disabled || textarea.readOnly)
937
+ return;
938
+ if (level < 1 || level > 6)
939
+ level = 1;
940
+ debugLog("insertHeader", `============ START ============`);
941
+ debugLog("insertHeader", `Level: ${level}, Toggle: ${toggle}`);
942
+ debugLog("insertHeader", `Initial cursor: ${textarea.selectionStart}-${textarea.selectionEnd}`);
943
+ const headerKey = `header${level === 1 ? "1" : level}`;
944
+ const style = mergeWithDefaults(FORMATS[headerKey] || FORMATS.header1);
945
+ debugLog("insertHeader", `Style prefix: "${style.prefix}"`);
946
+ const value = textarea.value;
947
+ const originalStart = textarea.selectionStart;
948
+ const originalEnd = textarea.selectionEnd;
949
+ let lineStart = originalStart;
950
+ while (lineStart > 0 && value[lineStart - 1] !== "\n") {
951
+ lineStart--;
952
+ }
953
+ let lineEnd = originalEnd;
954
+ while (lineEnd < value.length && value[lineEnd] !== "\n") {
955
+ lineEnd++;
956
+ }
957
+ const currentLineContent = value.slice(lineStart, lineEnd);
958
+ debugLog("insertHeader", `Current line (before): "${currentLineContent}"`);
959
+ const existingHeaderMatch = currentLineContent.match(/^(#{1,6})\s*/);
960
+ const existingLevel = existingHeaderMatch ? existingHeaderMatch[1].length : 0;
961
+ const existingPrefixLength = existingHeaderMatch ? existingHeaderMatch[0].length : 0;
962
+ debugLog("insertHeader", `Existing header check:`);
963
+ debugLog("insertHeader", ` - Match: ${existingHeaderMatch ? `"${existingHeaderMatch[0]}"` : "none"}`);
964
+ debugLog("insertHeader", ` - Existing level: ${existingLevel}`);
965
+ debugLog("insertHeader", ` - Existing prefix length: ${existingPrefixLength}`);
966
+ debugLog("insertHeader", ` - Target level: ${level}`);
967
+ const shouldToggleOff = toggle && existingLevel === level;
968
+ debugLog("insertHeader", `Should toggle OFF: ${shouldToggleOff} (toggle=${toggle}, existingLevel=${existingLevel}, level=${level})`);
969
+ const result = applyLineOperation(
970
+ textarea,
971
+ (ta) => {
972
+ const currentLine = ta.value.slice(ta.selectionStart, ta.selectionEnd);
973
+ debugLog("insertHeader", `Line in operation: "${currentLine}"`);
974
+ const cleanedLine = currentLine.replace(/^#{1,6}\s*/, "");
975
+ debugLog("insertHeader", `Cleaned line: "${cleanedLine}"`);
976
+ let newLine;
977
+ if (shouldToggleOff) {
978
+ debugLog("insertHeader", "ACTION: Toggling OFF - removing header");
979
+ newLine = cleanedLine;
980
+ } else if (existingLevel > 0) {
981
+ debugLog("insertHeader", `ACTION: Replacing H${existingLevel} with H${level}`);
982
+ newLine = style.prefix + cleanedLine;
983
+ } else {
984
+ debugLog("insertHeader", "ACTION: Adding new header");
985
+ newLine = style.prefix + cleanedLine;
986
+ }
987
+ debugLog("insertHeader", `New line: "${newLine}"`);
988
+ return {
989
+ text: newLine,
990
+ selectionStart: ta.selectionStart,
991
+ selectionEnd: ta.selectionEnd
992
+ };
993
+ },
994
+ {
995
+ prefix: style.prefix,
996
+ // Custom selection adjustment for headers
997
+ adjustSelection: (isRemoving, selStart, selEnd, lineStartPos) => {
998
+ debugLog("insertHeader", `Adjusting selection:`);
999
+ debugLog("insertHeader", ` - isRemoving param: ${isRemoving}`);
1000
+ debugLog("insertHeader", ` - shouldToggleOff: ${shouldToggleOff}`);
1001
+ debugLog("insertHeader", ` - selStart: ${selStart}, selEnd: ${selEnd}`);
1002
+ debugLog("insertHeader", ` - lineStartPos: ${lineStartPos}`);
1003
+ if (shouldToggleOff) {
1004
+ const adjustment = Math.max(selStart - existingPrefixLength, lineStartPos);
1005
+ debugLog("insertHeader", ` - Removing header, adjusting by -${existingPrefixLength}`);
1006
+ return {
1007
+ start: adjustment,
1008
+ end: selStart === selEnd ? adjustment : Math.max(selEnd - existingPrefixLength, lineStartPos)
1009
+ };
1010
+ } else if (existingPrefixLength > 0) {
1011
+ const prefixDiff = style.prefix.length - existingPrefixLength;
1012
+ debugLog("insertHeader", ` - Replacing header, adjusting by ${prefixDiff}`);
1013
+ return {
1014
+ start: selStart + prefixDiff,
1015
+ end: selEnd + prefixDiff
1016
+ };
1017
+ } else {
1018
+ debugLog("insertHeader", ` - Adding header, adjusting by +${style.prefix.length}`);
1019
+ return {
1020
+ start: selStart + style.prefix.length,
1021
+ end: selEnd + style.prefix.length
1022
+ };
1023
+ }
1024
+ }
1025
+ }
1026
+ );
1027
+ debugLog("insertHeader", `Final result: text="${result.text}", cursor=${result.selectionStart}-${result.selectionEnd}`);
1028
+ debugLog("insertHeader", `============ END ============`);
1029
+ insertText(textarea, result);
1030
+ }
1031
+ function toggleH1(textarea) {
1032
+ insertHeader(textarea, 1, true);
1033
+ }
1034
+ function toggleH2(textarea) {
1035
+ insertHeader(textarea, 2, true);
1036
+ }
1037
+ function toggleH3(textarea) {
1038
+ insertHeader(textarea, 3, true);
1039
+ }
1040
+ function getActiveFormats2(textarea) {
1041
+ return getActiveFormats(textarea);
1042
+ }
1043
+
1044
+ // src/shortcuts.js
1045
+ var ShortcutsManager = class {
1046
+ constructor(editor) {
1047
+ this.editor = editor;
1048
+ this.textarea = editor.textarea;
1049
+ }
1050
+ /**
1051
+ * Handle keydown events - called by OverType
1052
+ * @param {KeyboardEvent} event - The keyboard event
1053
+ * @returns {boolean} Whether the event was handled
1054
+ */
1055
+ handleKeydown(event) {
1056
+ const isMac = navigator.platform.toLowerCase().includes("mac");
1057
+ const modKey = isMac ? event.metaKey : event.ctrlKey;
1058
+ if (!modKey)
1059
+ return false;
1060
+ let action = null;
1061
+ switch (event.key.toLowerCase()) {
1062
+ case "b":
1063
+ if (!event.shiftKey) {
1064
+ action = "toggleBold";
1065
+ }
1066
+ break;
1067
+ case "i":
1068
+ if (!event.shiftKey) {
1069
+ action = "toggleItalic";
1070
+ }
1071
+ break;
1072
+ case "k":
1073
+ if (!event.shiftKey) {
1074
+ action = "insertLink";
1075
+ }
1076
+ break;
1077
+ case "7":
1078
+ if (event.shiftKey) {
1079
+ action = "toggleNumberedList";
1080
+ }
1081
+ break;
1082
+ case "8":
1083
+ if (event.shiftKey) {
1084
+ action = "toggleBulletList";
1085
+ }
1086
+ break;
1087
+ }
1088
+ if (action) {
1089
+ event.preventDefault();
1090
+ if (this.editor.toolbar) {
1091
+ this.editor.toolbar.handleAction(action);
1092
+ } else {
1093
+ this.handleAction(action);
1094
+ }
1095
+ return true;
1096
+ }
1097
+ return false;
1098
+ }
1099
+ /**
1100
+ * Handle action - fallback when no toolbar exists
1101
+ * This duplicates toolbar.handleAction for consistency
1102
+ */
1103
+ async handleAction(action) {
1104
+ const textarea = this.textarea;
1105
+ if (!textarea)
1106
+ return;
1107
+ textarea.focus();
1108
+ try {
1109
+ switch (action) {
1110
+ case "toggleBold":
1111
+ toggleBold(textarea);
1112
+ break;
1113
+ case "toggleItalic":
1114
+ toggleItalic(textarea);
1115
+ break;
1116
+ case "insertLink":
1117
+ insertLink(textarea);
1118
+ break;
1119
+ case "toggleBulletList":
1120
+ toggleBulletList(textarea);
1121
+ break;
1122
+ case "toggleNumberedList":
1123
+ toggleNumberedList(textarea);
1124
+ break;
1125
+ }
1126
+ textarea.dispatchEvent(new Event("input", { bubbles: true }));
1127
+ } catch (error) {
1128
+ console.error("Error in markdown action:", error);
1129
+ }
1130
+ }
1131
+ /**
1132
+ * Cleanup
1133
+ */
1134
+ destroy() {
1135
+ }
1136
+ };
1137
+
1138
+ // src/themes.js
1139
+ var solar = {
1140
+ name: "solar",
1141
+ colors: {
1142
+ bgPrimary: "#faf0ca",
1143
+ // Lemon Chiffon - main background
1144
+ bgSecondary: "#ffffff",
1145
+ // White - editor background
1146
+ text: "#0d3b66",
1147
+ // Yale Blue - main text
1148
+ h1: "#f95738",
1149
+ // Tomato - h1 headers
1150
+ h2: "#ee964b",
1151
+ // Sandy Brown - h2 headers
1152
+ h3: "#3d8a51",
1153
+ // Forest green - h3 headers
1154
+ strong: "#ee964b",
1155
+ // Sandy Brown - bold text
1156
+ em: "#f95738",
1157
+ // Tomato - italic text
1158
+ link: "#0d3b66",
1159
+ // Yale Blue - links
1160
+ code: "#0d3b66",
1161
+ // Yale Blue - inline code
1162
+ codeBg: "rgba(244, 211, 94, 0.4)",
1163
+ // Naples Yellow with transparency
1164
+ blockquote: "#5a7a9b",
1165
+ // Muted blue - blockquotes
1166
+ hr: "#5a7a9b",
1167
+ // Muted blue - horizontal rules
1168
+ syntaxMarker: "rgba(13, 59, 102, 0.52)",
1169
+ // Yale Blue with transparency
1170
+ cursor: "#f95738",
1171
+ // Tomato - cursor
1172
+ selection: "rgba(244, 211, 94, 0.4)",
1173
+ // Naples Yellow with transparency
1174
+ listMarker: "#ee964b",
1175
+ // Sandy Brown - list markers
1176
+ // Toolbar colors
1177
+ toolbarBg: "#ffffff",
1178
+ // White - toolbar background
1179
+ toolbarBorder: "rgba(13, 59, 102, 0.15)",
1180
+ // Yale Blue border
1181
+ toolbarIcon: "#0d3b66",
1182
+ // Yale Blue - icon color
1183
+ toolbarHover: "#f5f5f5",
1184
+ // Light gray - hover background
1185
+ toolbarActive: "#faf0ca"
1186
+ // Lemon Chiffon - active button background
1187
+ }
1188
+ };
1189
+ var cave = {
1190
+ name: "cave",
1191
+ colors: {
1192
+ bgPrimary: "#141E26",
1193
+ // Deep ocean - main background
1194
+ bgSecondary: "#1D2D3E",
1195
+ // Darker charcoal - editor background
1196
+ text: "#c5dde8",
1197
+ // Light blue-gray - main text
1198
+ h1: "#d4a5ff",
1199
+ // Rich lavender - h1 headers
1200
+ h2: "#f6ae2d",
1201
+ // Hunyadi Yellow - h2 headers
1202
+ h3: "#9fcfec",
1203
+ // Brighter blue - h3 headers
1204
+ strong: "#f6ae2d",
1205
+ // Hunyadi Yellow - bold text
1206
+ em: "#9fcfec",
1207
+ // Brighter blue - italic text
1208
+ link: "#9fcfec",
1209
+ // Brighter blue - links
1210
+ code: "#c5dde8",
1211
+ // Light blue-gray - inline code
1212
+ codeBg: "#1a232b",
1213
+ // Very dark blue - code background
1214
+ blockquote: "#9fcfec",
1215
+ // Brighter blue - same as italic
1216
+ hr: "#c5dde8",
1217
+ // Light blue-gray - horizontal rules
1218
+ syntaxMarker: "rgba(159, 207, 236, 0.73)",
1219
+ // Brighter blue semi-transparent
1220
+ cursor: "#f26419",
1221
+ // Orange Pantone - cursor
1222
+ selection: "rgba(51, 101, 138, 0.4)",
1223
+ // Lapis Lazuli with transparency
1224
+ listMarker: "#f6ae2d",
1225
+ // Hunyadi Yellow - list markers
1226
+ // Toolbar colors for dark theme
1227
+ toolbarBg: "#1D2D3E",
1228
+ // Darker charcoal - toolbar background
1229
+ toolbarBorder: "rgba(197, 221, 232, 0.1)",
1230
+ // Light blue-gray border
1231
+ toolbarIcon: "#c5dde8",
1232
+ // Light blue-gray - icon color
1233
+ toolbarHover: "#243546",
1234
+ // Slightly lighter charcoal - hover background
1235
+ toolbarActive: "#2a3f52"
1236
+ // Even lighter - active button background
1237
+ }
1238
+ };
1239
+ var themes = {
1240
+ solar,
1241
+ cave,
1242
+ // Aliases for backward compatibility
1243
+ light: solar,
1244
+ dark: cave
1245
+ };
1246
+ function getTheme(theme) {
1247
+ if (typeof theme === "string") {
1248
+ const themeObj = themes[theme] || themes.solar;
1249
+ return { ...themeObj, name: theme };
1250
+ }
1251
+ return theme;
1252
+ }
1253
+ function themeToCSSVars(colors) {
1254
+ const vars = [];
1255
+ for (const [key, value] of Object.entries(colors)) {
1256
+ const varName = key.replace(/([A-Z])/g, "-$1").toLowerCase();
1257
+ vars.push(`--${varName}: ${value};`);
1258
+ }
1259
+ return vars.join("\n");
1260
+ }
1261
+ function mergeTheme(baseTheme, customColors = {}) {
1262
+ return {
1263
+ ...baseTheme,
1264
+ colors: {
1265
+ ...baseTheme.colors,
1266
+ ...customColors
1267
+ }
1268
+ };
1269
+ }
1270
+
1271
+ // src/styles.js
1272
+ function generateStyles(options = {}) {
1273
+ const {
1274
+ fontSize = "14px",
1275
+ lineHeight = 1.6,
1276
+ fontFamily = "'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace",
1277
+ padding = "20px",
1278
+ theme = null,
1279
+ mobile = {}
1280
+ } = options;
1281
+ const mobileStyles = Object.keys(mobile).length > 0 ? `
1282
+ @media (max-width: 640px) {
1283
+ .overtype-wrapper .overtype-input,
1284
+ .overtype-wrapper .overtype-preview {
1285
+ ${Object.entries(mobile).map(([prop, val]) => {
1286
+ const cssProp = prop.replace(/([A-Z])/g, "-$1").toLowerCase();
1287
+ return `${cssProp}: ${val} !important;`;
1288
+ }).join("\n ")}
1289
+ }
1290
+ }
1291
+ ` : "";
1292
+ const themeVars = theme && theme.colors ? themeToCSSVars(theme.colors) : "";
1293
+ return `
1294
+ /* OverType Editor Styles */
1295
+ .overtype-container {
1296
+ position: relative !important;
1297
+ width: 100% !important;
1298
+ height: 100% !important;
1299
+ ${themeVars ? `
1300
+ /* Theme Variables */
1301
+ ${themeVars}` : ""}
1302
+ }
1303
+
1304
+ .overtype-wrapper {
1305
+ position: relative !important;
1306
+ width: 100% !important;
1307
+ height: 100% !important;
1308
+ overflow: hidden !important;
1309
+ background: var(--bg-secondary, #ffffff) !important;
1310
+ }
1311
+
1312
+ /* Critical alignment styles - must be identical for both layers */
1313
+ .overtype-wrapper .overtype-input,
1314
+ .overtype-wrapper .overtype-preview {
1315
+ /* Positioning - must be identical */
1316
+ position: absolute !important;
1317
+ top: 0 !important;
1318
+ left: 0 !important;
1319
+ width: 100% !important;
1320
+ height: 100% !important;
1321
+
1322
+ /* Font properties - any difference breaks alignment */
1323
+ font-family: ${fontFamily} !important;
1324
+ font-size: var(--instance-font-size, ${fontSize}) !important;
1325
+ line-height: var(--instance-line-height, ${lineHeight}) !important;
1326
+ font-weight: normal !important;
1327
+ font-style: normal !important;
1328
+ font-variant: normal !important;
1329
+ font-stretch: normal !important;
1330
+ font-kerning: none !important;
1331
+ font-feature-settings: normal !important;
1332
+
1333
+ /* Box model - must match exactly */
1334
+ padding: var(--instance-padding, ${padding}) !important;
1335
+ margin: 0 !important;
1336
+ border: none !important;
1337
+ outline: none !important;
1338
+ box-sizing: border-box !important;
1339
+
1340
+ /* Text layout - critical for character positioning */
1341
+ white-space: pre-wrap !important;
1342
+ word-wrap: break-word !important;
1343
+ word-break: normal !important;
1344
+ overflow-wrap: break-word !important;
1345
+ tab-size: 2 !important;
1346
+ -moz-tab-size: 2 !important;
1347
+ text-align: left !important;
1348
+ text-indent: 0 !important;
1349
+ letter-spacing: normal !important;
1350
+ word-spacing: normal !important;
1351
+
1352
+ /* Text rendering */
1353
+ text-transform: none !important;
1354
+ text-rendering: auto !important;
1355
+ -webkit-font-smoothing: auto !important;
1356
+ -webkit-text-size-adjust: 100% !important;
1357
+
1358
+ /* Direction and writing */
1359
+ direction: ltr !important;
1360
+ writing-mode: horizontal-tb !important;
1361
+ unicode-bidi: normal !important;
1362
+ text-orientation: mixed !important;
1363
+
1364
+ /* Visual effects that could shift perception */
1365
+ text-shadow: none !important;
1366
+ filter: none !important;
1367
+ transform: none !important;
1368
+ zoom: 1 !important;
1369
+
1370
+ /* Vertical alignment */
1371
+ vertical-align: baseline !important;
1372
+
1373
+ /* Size constraints */
1374
+ min-width: 0 !important;
1375
+ min-height: 0 !important;
1376
+ max-width: none !important;
1377
+ max-height: none !important;
1378
+
1379
+ /* Overflow */
1380
+ overflow-y: auto !important;
1381
+ overflow-x: auto !important;
1382
+ scrollbar-width: auto !important;
1383
+ scrollbar-gutter: auto !important;
1384
+
1385
+ /* Animation/transition - disabled to prevent movement */
1386
+ animation: none !important;
1387
+ transition: none !important;
1388
+ }
1389
+
1390
+ /* Input layer styles */
1391
+ .overtype-wrapper .overtype-input {
1392
+ /* Layer positioning */
1393
+ z-index: 1 !important;
1394
+
1395
+ /* Text visibility */
1396
+ color: transparent !important;
1397
+ caret-color: var(--cursor, #f95738) !important;
1398
+ background-color: transparent !important;
1399
+
1400
+ /* Textarea-specific */
1401
+ resize: none !important;
1402
+ appearance: none !important;
1403
+ -webkit-appearance: none !important;
1404
+ -moz-appearance: none !important;
1405
+
1406
+ /* Prevent mobile zoom on focus */
1407
+ touch-action: manipulation !important;
1408
+
1409
+ /* Disable autofill and spellcheck */
1410
+ autocomplete: off !important;
1411
+ autocorrect: off !important;
1412
+ autocapitalize: off !important;
1413
+ spellcheck: false !important;
1414
+ }
1415
+
1416
+ .overtype-wrapper .overtype-input::selection {
1417
+ background-color: var(--selection, rgba(244, 211, 94, 0.4));
1418
+ }
1419
+
1420
+ /* Preview layer styles */
1421
+ .overtype-wrapper .overtype-preview {
1422
+ /* Layer positioning */
1423
+ z-index: 0 !important;
1424
+ pointer-events: none !important;
1425
+ color: var(--text, #0d3b66) !important;
1426
+ background-color: transparent !important;
1427
+
1428
+ /* Prevent text selection */
1429
+ user-select: none !important;
1430
+ -webkit-user-select: none !important;
1431
+ -moz-user-select: none !important;
1432
+ -ms-user-select: none !important;
1433
+ }
1434
+
1435
+ /* Defensive styles for preview child divs */
1436
+ .overtype-wrapper .overtype-preview div {
1437
+ /* Reset any inherited styles */
1438
+ margin: 0 !important;
1439
+ padding: 0 !important;
1440
+ border: none !important;
1441
+ text-align: left !important;
1442
+ text-indent: 0 !important;
1443
+ display: block !important;
1444
+ position: static !important;
1445
+ transform: none !important;
1446
+ min-height: 0 !important;
1447
+ max-height: none !important;
1448
+ line-height: inherit !important;
1449
+ font-size: inherit !important;
1450
+ font-family: inherit !important;
1451
+ }
1452
+
1453
+ /* Markdown element styling - NO SIZE CHANGES */
1454
+ .overtype-wrapper .overtype-preview .header {
1455
+ font-weight: bold !important;
1456
+ }
1457
+
1458
+ /* Header colors */
1459
+ .overtype-wrapper .overtype-preview .h1 {
1460
+ color: var(--h1, #f95738) !important;
1461
+ }
1462
+ .overtype-wrapper .overtype-preview .h2 {
1463
+ color: var(--h2, #ee964b) !important;
1464
+ }
1465
+ .overtype-wrapper .overtype-preview .h3 {
1466
+ color: var(--h3, #3d8a51) !important;
1467
+ }
1468
+
1469
+ /* Bold text */
1470
+ .overtype-wrapper .overtype-preview strong {
1471
+ color: var(--strong, #ee964b) !important;
1472
+ font-weight: bold !important;
1473
+ }
1474
+
1475
+ /* Italic text */
1476
+ .overtype-wrapper .overtype-preview em {
1477
+ color: var(--em, #f95738) !important;
1478
+ text-decoration-color: var(--em, #f95738) !important;
1479
+ text-decoration-thickness: 1px !important;
1480
+ font-style: italic !important;
1481
+ }
1482
+
1483
+ /* Inline code */
1484
+ .overtype-wrapper .overtype-preview code {
1485
+ background: var(--code-bg, rgba(244, 211, 94, 0.4)) !important;
1486
+ color: var(--code, #0d3b66) !important;
1487
+ padding: 0 !important;
1488
+ border-radius: 2px !important;
1489
+ font-family: inherit !important;
1490
+ font-weight: normal !important;
1491
+ }
1492
+
1493
+ /* Code blocks */
1494
+ .overtype-wrapper .overtype-preview pre {
1495
+ background: #1e1e1e !important;
1496
+ padding: 0 !important;
1497
+ margin: 0 !important;
1498
+ border-radius: 4px !important;
1499
+ overflow-x: auto !important;
1500
+ }
1501
+
1502
+ .overtype-wrapper .overtype-preview pre code {
1503
+ background: none !important;
1504
+ }
1505
+
1506
+ /* Blockquotes */
1507
+ .overtype-wrapper .overtype-preview .blockquote {
1508
+ color: var(--blockquote, #5a7a9b) !important;
1509
+ padding: 0 !important;
1510
+ margin: 0 !important;
1511
+ border: none !important;
1512
+ }
1513
+
1514
+ /* Links */
1515
+ .overtype-wrapper .overtype-preview a {
1516
+ color: var(--link, #0d3b66) !important;
1517
+ text-decoration: underline !important;
1518
+ font-weight: normal !important;
1519
+ }
1520
+
1521
+ .overtype-wrapper .overtype-preview a:hover {
1522
+ text-decoration: underline !important;
1523
+ color: var(--link, #0d3b66) !important;
1524
+ }
1525
+
1526
+ /* Lists - no list styling */
1527
+ .overtype-wrapper .overtype-preview ul,
1528
+ .overtype-wrapper .overtype-preview ol {
1529
+ list-style: none !important;
1530
+ margin: 0 !important;
1531
+ padding: 0 !important;
1532
+ }
1533
+
1534
+ .overtype-wrapper .overtype-preview li {
1535
+ margin: 0 !important;
1536
+ padding: 0 !important;
1537
+ list-style: none !important;
1538
+ }
1539
+
1540
+ /* Horizontal rules */
1541
+ .overtype-wrapper .overtype-preview hr {
1542
+ border: none !important;
1543
+ color: var(--hr, #5a7a9b) !important;
1544
+ margin: 0 !important;
1545
+ padding: 0 !important;
1546
+ }
1547
+
1548
+ .overtype-wrapper .overtype-preview .hr-marker {
1549
+ color: var(--hr, #5a7a9b) !important;
1550
+ opacity: 0.6 !important;
1551
+ }
1552
+
1553
+ /* Code fence markers - with background when not in code block */
1554
+ .overtype-wrapper .overtype-preview .code-fence {
1555
+ color: var(--code, #0d3b66) !important;
1556
+ background: var(--code-bg, rgba(244, 211, 94, 0.4)) !important;
1557
+ }
1558
+
1559
+ /* Code block lines - background for entire code block */
1560
+ .overtype-wrapper .overtype-preview .code-block-line {
1561
+ background: var(--code-bg, rgba(244, 211, 94, 0.4)) !important;
1562
+ }
1563
+
1564
+ /* Remove background from code fence when inside code block line */
1565
+ .overtype-wrapper .overtype-preview .code-block-line .code-fence {
1566
+ background: transparent !important;
1567
+ }
1568
+
1569
+ /* Raw markdown line */
1570
+ .overtype-wrapper .overtype-preview .raw-line {
1571
+ color: var(--raw-line, #5a7a9b) !important;
1572
+ font-style: normal !important;
1573
+ font-weight: normal !important;
1574
+ }
1575
+
1576
+ /* Syntax markers */
1577
+ .overtype-wrapper .overtype-preview .syntax-marker {
1578
+ color: var(--syntax-marker, rgba(13, 59, 102, 0.52)) !important;
1579
+ opacity: 0.7 !important;
1580
+ }
1581
+
1582
+ /* List markers */
1583
+ .overtype-wrapper .overtype-preview .list-marker {
1584
+ color: var(--list-marker, #ee964b) !important;
1585
+ }
1586
+
1587
+ /* Stats bar */
1588
+ .overtype-wrapper.with-stats {
1589
+ padding-bottom: 40px !important;
1590
+ }
1591
+
1592
+ .overtype-wrapper .overtype-stats {
1593
+ position: absolute !important;
1594
+ bottom: 0 !important;
1595
+ left: 0 !important;
1596
+ right: 0 !important;
1597
+ height: 40px !important;
1598
+ padding: 0 20px !important;
1599
+ background: #f8f9fa !important;
1600
+ border-top: 1px solid #e0e0e0 !important;
1601
+ display: flex !important;
1602
+ justify-content: space-between !important;
1603
+ align-items: center !important;
1604
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
1605
+ font-size: 0.85rem !important;
1606
+ color: #666 !important;
1607
+ z-index: 2 !important;
1608
+ }
1609
+
1610
+ /* Dark theme stats bar */
1611
+ .overtype-wrapper[data-theme="cave"] .overtype-stats {
1612
+ background: var(--bg-secondary, #1D2D3E) !important;
1613
+ border-top: 1px solid rgba(197, 221, 232, 0.1) !important;
1614
+ color: var(--text, #c5dde8) !important;
1615
+ }
1616
+
1617
+ .overtype-wrapper .overtype-stats .overtype-stat {
1618
+ display: flex !important;
1619
+ align-items: center !important;
1620
+ gap: 5px !important;
1621
+ white-space: nowrap !important;
1622
+ }
1623
+
1624
+ .overtype-wrapper .overtype-stats .live-dot {
1625
+ width: 8px !important;
1626
+ height: 8px !important;
1627
+ background: #4caf50 !important;
1628
+ border-radius: 50% !important;
1629
+ animation: pulse 2s infinite !important;
1630
+ }
1631
+
1632
+ @keyframes pulse {
1633
+ 0%, 100% { opacity: 1; transform: scale(1); }
1634
+ 50% { opacity: 0.6; transform: scale(1.2); }
1635
+ }
1636
+
1637
+ /* Adjust textarea and preview for stats bar */
1638
+ .overtype-wrapper.with-stats .overtype-input,
1639
+ .overtype-wrapper.with-stats .overtype-preview {
1640
+ height: calc(100% - 40px) !important;
1641
+ }
1642
+
1643
+ /* Toolbar Styles */
1644
+ .overtype-toolbar {
1645
+ display: flex;
1646
+ align-items: center;
1647
+ gap: 4px;
1648
+ padding: 8px;
1649
+ background: var(--toolbar-bg, var(--bg-primary, #f8f9fa));
1650
+ border: 1px solid var(--toolbar-border, var(--border, #e0e0e0));
1651
+ border-bottom: none;
1652
+ border-radius: 8px 8px 0 0;
1653
+ overflow-x: auto;
1654
+ -webkit-overflow-scrolling: touch;
1655
+ }
1656
+
1657
+ .overtype-toolbar-button {
1658
+ display: flex;
1659
+ align-items: center;
1660
+ justify-content: center;
1661
+ width: 32px;
1662
+ height: 32px;
1663
+ padding: 0;
1664
+ border: none;
1665
+ border-radius: 6px;
1666
+ background: transparent;
1667
+ color: var(--toolbar-icon, var(--text-secondary, #666));
1668
+ cursor: pointer;
1669
+ transition: all 0.2s ease;
1670
+ flex-shrink: 0;
1671
+ }
1672
+
1673
+ .overtype-toolbar-button svg {
1674
+ width: 20px;
1675
+ height: 20px;
1676
+ fill: currentColor;
1677
+ }
1678
+
1679
+ /* Special sizing for code block icon */
1680
+ .overtype-toolbar-button[data-action="insertCodeBlock"] svg {
1681
+ width: 22px;
1682
+ height: 18px;
1683
+ fill: transparent !important;
1684
+ }
1685
+
1686
+ .overtype-toolbar-button:hover {
1687
+ background: var(--toolbar-hover, var(--bg-secondary, #e9ecef));
1688
+ color: var(--toolbar-icon, var(--text-primary, #333));
1689
+ }
1690
+
1691
+ .overtype-toolbar-button:active {
1692
+ transform: scale(0.95);
1693
+ }
1694
+
1695
+ .overtype-toolbar-button.active {
1696
+ background: var(--toolbar-active, var(--primary, #007bff));
1697
+ color: var(--toolbar-icon, var(--text-primary, #333));
1698
+ }
1699
+
1700
+ .overtype-toolbar-button:disabled {
1701
+ opacity: 0.5;
1702
+ cursor: not-allowed;
1703
+ }
1704
+
1705
+ .overtype-toolbar-separator {
1706
+ width: 1px;
1707
+ height: 24px;
1708
+ background: var(--border, #e0e0e0);
1709
+ margin: 0 4px;
1710
+ flex-shrink: 0;
1711
+ }
1712
+
1713
+ /* Adjust wrapper when toolbar is present */
1714
+ .overtype-container .overtype-toolbar + .overtype-wrapper {
1715
+ border-radius: 0 0 8px 8px;
1716
+ border-top: none;
1717
+ }
1718
+
1719
+ /* Mobile toolbar adjustments */
1720
+ @media (max-width: 640px) {
1721
+ .overtype-toolbar {
1722
+ padding: 6px;
1723
+ gap: 2px;
1724
+ }
1725
+
1726
+ .overtype-toolbar-button {
1727
+ width: 36px;
1728
+ height: 36px;
1729
+ }
1730
+
1731
+ .overtype-toolbar-separator {
1732
+ margin: 0 2px;
1733
+ }
1734
+ }
1735
+
1736
+ ${mobileStyles}
1737
+ `;
1738
+ }
1739
+
1740
+ // src/icons.js
1741
+ var boldIcon = `<svg viewBox="0 0 18 18">
1742
+ <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>
1743
+ <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>
1744
+ </svg>`;
1745
+ var italicIcon = `<svg viewBox="0 0 18 18">
1746
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="7" x2="13" y1="4" y2="4"></line>
1747
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="5" x2="11" y1="14" y2="14"></line>
1748
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="8" x2="10" y1="14" y2="4"></line>
1749
+ </svg>`;
1750
+ var h1Icon = `<svg viewBox="0 0 18 18">
1751
+ <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>
1752
+ </svg>`;
1753
+ var h2Icon = `<svg viewBox="0 0 18 18">
1754
+ <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>
1755
+ </svg>`;
1756
+ var h3Icon = `<svg viewBox="0 0 18 18">
1757
+ <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>
1758
+ </svg>`;
1759
+ var linkIcon = `<svg viewBox="0 0 18 18">
1760
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="7" x2="11" y1="7" y2="11"></line>
1761
+ <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>
1762
+ <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>
1763
+ </svg>`;
1764
+ var codeIcon = `<svg viewBox="0 0 18 18">
1765
+ <polyline stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" points="5 7 3 9 5 11"></polyline>
1766
+ <polyline stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" points="13 7 15 9 13 11"></polyline>
1767
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="10" x2="8" y1="5" y2="13"></line>
1768
+ </svg>`;
1769
+ var codeBlockIcon = `<svg viewBox="0 0 46 33" fill="transparent" xmlns="http://www.w3.org/2000/svg">
1770
+ <path d="M35 8h3a5 5 0 0 1 5 5v12a5 5 0 0 1-5 5H18a5 5 0 0 1-5-5v-2" stroke="currentColor" stroke-width="4" stroke-linecap="round"></path>
1771
+ <path d="m9 2.5-6 6L9 14M20 2.5l6 6-6 5.5" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"></path>
1772
+ </svg>`;
1773
+ var bulletListIcon = `<svg viewBox="0 0 18 18">
1774
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="6" x2="15" y1="4" y2="4"></line>
1775
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="6" x2="15" y1="9" y2="9"></line>
1776
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="6" x2="15" y1="14" y2="14"></line>
1777
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="3" x2="3" y1="4" y2="4"></line>
1778
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="3" x2="3" y1="9" y2="9"></line>
1779
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="3" x2="3" y1="14" y2="14"></line>
1780
+ </svg>`;
1781
+ var orderedListIcon = `<svg viewBox="0 0 18 18">
1782
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="7" x2="15" y1="4" y2="4"></line>
1783
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="7" x2="15" y1="9" y2="9"></line>
1784
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="7" x2="15" y1="14" y2="14"></line>
1785
+ <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>
1786
+ <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>
1787
+ <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>
1788
+ <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>
1789
+ </svg>`;
1790
+ var quoteIcon = `<svg viewBox="2 2 20 20">
1791
+ <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>
1792
+ <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>
1793
+ </svg>`;
1794
+ var taskListIcon = `<svg viewBox="0 0 18 18">
1795
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="8" x2="16" y1="4" y2="4"></line>
1796
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="8" x2="16" y1="9" y2="9"></line>
1797
+ <line stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="8" x2="16" y1="14" y2="14"></line>
1798
+ <rect stroke="currentColor" fill="none" stroke-width="1.5" x="2" y="3" width="3" height="3" rx="0.5"></rect>
1799
+ <rect stroke="currentColor" fill="none" stroke-width="1.5" x="2" y="13" width="3" height="3" rx="0.5"></rect>
1800
+ <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>
1801
+ </svg>`;
1802
+
1803
+ // src/toolbar.js
1804
+ var Toolbar = class {
1805
+ constructor(editor) {
1806
+ this.editor = editor;
1807
+ this.container = null;
1808
+ this.buttons = {};
1809
+ }
1810
+ /**
1811
+ * Create and attach toolbar to editor
1812
+ */
1813
+ create() {
1814
+ this.container = document.createElement("div");
1815
+ this.container.className = "overtype-toolbar";
1816
+ this.container.setAttribute("role", "toolbar");
1817
+ this.container.setAttribute("aria-label", "Text formatting");
1818
+ const buttonConfig = [
1819
+ { name: "bold", icon: boldIcon, title: "Bold (Ctrl+B)", action: "toggleBold" },
1820
+ { name: "italic", icon: italicIcon, title: "Italic (Ctrl+I)", action: "toggleItalic" },
1821
+ { separator: true },
1822
+ { name: "h1", icon: h1Icon, title: "Heading 1", action: "insertH1" },
1823
+ { name: "h2", icon: h2Icon, title: "Heading 2", action: "insertH2" },
1824
+ { name: "h3", icon: h3Icon, title: "Heading 3", action: "insertH3" },
1825
+ { separator: true },
1826
+ { name: "link", icon: linkIcon, title: "Insert Link (Ctrl+K)", action: "insertLink" },
1827
+ { name: "code", icon: codeIcon, title: "Inline Code", action: "toggleCode" },
1828
+ { name: "codeBlock", icon: codeBlockIcon, title: "Code Block", action: "insertCodeBlock" },
1829
+ { separator: true },
1830
+ { name: "quote", icon: quoteIcon, title: "Quote", action: "toggleQuote" },
1831
+ { separator: true },
1832
+ { name: "bulletList", icon: bulletListIcon, title: "Bullet List", action: "toggleBulletList" },
1833
+ { name: "orderedList", icon: orderedListIcon, title: "Numbered List", action: "toggleNumberedList" },
1834
+ { name: "taskList", icon: taskListIcon, title: "Task List", action: "toggleTaskList" }
1835
+ ];
1836
+ buttonConfig.forEach((config) => {
1837
+ if (config.separator) {
1838
+ const separator = document.createElement("div");
1839
+ separator.className = "overtype-toolbar-separator";
1840
+ separator.setAttribute("role", "separator");
1841
+ this.container.appendChild(separator);
1842
+ } else {
1843
+ const button = this.createButton(config);
1844
+ this.buttons[config.name] = button;
1845
+ this.container.appendChild(button);
1846
+ }
1847
+ });
1848
+ const container = this.editor.element.querySelector(".overtype-container");
1849
+ const wrapper = this.editor.element.querySelector(".overtype-wrapper");
1850
+ if (container && wrapper) {
1851
+ container.insertBefore(this.container, wrapper);
1852
+ }
1853
+ return this.container;
1854
+ }
1855
+ /**
1856
+ * Create individual toolbar button
1857
+ */
1858
+ createButton(config) {
1859
+ const button = document.createElement("button");
1860
+ button.className = "overtype-toolbar-button";
1861
+ button.type = "button";
1862
+ button.title = config.title;
1863
+ button.setAttribute("aria-label", config.title);
1864
+ button.setAttribute("data-action", config.action);
1865
+ button.innerHTML = config.icon;
1866
+ button.addEventListener("click", (e) => {
1867
+ e.preventDefault();
1868
+ this.handleAction(config.action);
1869
+ });
1870
+ return button;
1871
+ }
1872
+ /**
1873
+ * Handle toolbar button actions
1874
+ */
1875
+ async handleAction(action) {
1876
+ const textarea = this.editor.textarea;
1877
+ if (!textarea)
1878
+ return;
1879
+ textarea.focus();
1880
+ try {
1881
+ switch (action) {
1882
+ case "toggleBold":
1883
+ toggleBold(textarea);
1884
+ break;
1885
+ case "toggleItalic":
1886
+ toggleItalic(textarea);
1887
+ break;
1888
+ case "insertH1":
1889
+ toggleH1(textarea);
1890
+ break;
1891
+ case "insertH2":
1892
+ toggleH2(textarea);
1893
+ break;
1894
+ case "insertH3":
1895
+ toggleH3(textarea);
1896
+ break;
1897
+ case "insertLink":
1898
+ insertLink(textarea);
1899
+ break;
1900
+ case "toggleCode":
1901
+ toggleCode(textarea);
1902
+ break;
1903
+ case "insertCodeBlock":
1904
+ const start = textarea.selectionStart;
1905
+ const end = textarea.selectionEnd;
1906
+ const selectedText = textarea.value.slice(start, end);
1907
+ const codeBlock = "```\n" + selectedText + "\n```";
1908
+ textarea.setRangeText(codeBlock, start, end, "end");
1909
+ break;
1910
+ case "toggleBulletList":
1911
+ toggleBulletList(textarea);
1912
+ break;
1913
+ case "toggleNumberedList":
1914
+ toggleNumberedList(textarea);
1915
+ break;
1916
+ case "toggleQuote":
1917
+ toggleQuote(textarea);
1918
+ break;
1919
+ case "toggleTaskList":
1920
+ toggleTaskList(textarea);
1921
+ break;
1922
+ }
1923
+ textarea.dispatchEvent(new Event("input", { bubbles: true }));
1924
+ } catch (error) {
1925
+ console.error("Error loading markdown-actions:", error);
1926
+ }
1927
+ }
1928
+ /**
1929
+ * Update toolbar button states based on current selection
1930
+ */
1931
+ async updateButtonStates() {
1932
+ const textarea = this.editor.textarea;
1933
+ if (!textarea)
1934
+ return;
1935
+ try {
1936
+ const activeFormats = getActiveFormats2(textarea);
1937
+ Object.entries(this.buttons).forEach(([name, button]) => {
1938
+ let isActive = false;
1939
+ switch (name) {
1940
+ case "bold":
1941
+ isActive = activeFormats.includes("bold");
1942
+ break;
1943
+ case "italic":
1944
+ isActive = activeFormats.includes("italic");
1945
+ break;
1946
+ case "code":
1947
+ isActive = false;
1948
+ break;
1949
+ case "bulletList":
1950
+ isActive = activeFormats.includes("bullet-list");
1951
+ break;
1952
+ case "orderedList":
1953
+ isActive = activeFormats.includes("numbered-list");
1954
+ break;
1955
+ case "quote":
1956
+ isActive = activeFormats.includes("quote");
1957
+ break;
1958
+ case "taskList":
1959
+ isActive = activeFormats.includes("task-list");
1960
+ break;
1961
+ case "h1":
1962
+ isActive = activeFormats.includes("header");
1963
+ break;
1964
+ case "h2":
1965
+ isActive = activeFormats.includes("header-2");
1966
+ break;
1967
+ case "h3":
1968
+ isActive = activeFormats.includes("header-3");
1969
+ break;
1970
+ }
1971
+ button.classList.toggle("active", isActive);
1972
+ button.setAttribute("aria-pressed", isActive.toString());
1973
+ });
1974
+ } catch (error) {
1975
+ }
1976
+ }
1977
+ /**
1978
+ * Destroy toolbar
1979
+ */
1980
+ destroy() {
1981
+ if (this.container) {
1982
+ this.container.remove();
1983
+ this.container = null;
1984
+ this.buttons = {};
1985
+ }
1986
+ }
1987
+ };
1988
+
1989
+ // src/overtype.js
1990
+ var _OverType = class _OverType {
1991
+ /**
1992
+ * Constructor - Always returns an array of instances
1993
+ * @param {string|Element|NodeList|Array} target - Target element(s)
1994
+ * @param {Object} options - Configuration options
1995
+ * @returns {Array} Array of OverType instances
1996
+ */
1997
+ constructor(target, options = {}) {
1998
+ let elements;
1999
+ if (typeof target === "string") {
2000
+ elements = document.querySelectorAll(target);
2001
+ if (elements.length === 0) {
2002
+ throw new Error(`No elements found for selector: ${target}`);
2003
+ }
2004
+ elements = Array.from(elements);
2005
+ } else if (target instanceof Element) {
2006
+ elements = [target];
2007
+ } else if (target instanceof NodeList) {
2008
+ elements = Array.from(target);
2009
+ } else if (Array.isArray(target)) {
2010
+ elements = target;
2011
+ } else {
2012
+ throw new Error("Invalid target: must be selector string, Element, NodeList, or Array");
2013
+ }
2014
+ const instances = elements.map((element) => {
2015
+ if (element.overTypeInstance) {
2016
+ element.overTypeInstance.reinit(options);
2017
+ return element.overTypeInstance;
2018
+ }
2019
+ const instance = Object.create(_OverType.prototype);
2020
+ instance._init(element, options);
2021
+ element.overTypeInstance = instance;
2022
+ _OverType.instances.set(element, instance);
2023
+ return instance;
2024
+ });
2025
+ return instances;
2026
+ }
2027
+ /**
2028
+ * Internal initialization
2029
+ * @private
2030
+ */
2031
+ _init(element, options = {}) {
2032
+ this.element = element;
2033
+ this.options = this._mergeOptions(options);
2034
+ this.instanceId = ++_OverType.instanceCount;
2035
+ this.initialized = false;
2036
+ _OverType.injectStyles();
2037
+ _OverType.initGlobalListeners();
2038
+ const container = element.querySelector(".overtype-container");
2039
+ const wrapper = element.querySelector(".overtype-wrapper");
2040
+ if (container || wrapper) {
2041
+ this._recoverFromDOM(container, wrapper);
2042
+ } else {
2043
+ this._buildFromScratch();
2044
+ }
2045
+ this.shortcuts = new ShortcutsManager(this);
2046
+ if (this.options.toolbar) {
2047
+ this.toolbar = new Toolbar(this);
2048
+ this.toolbar.create();
2049
+ this.textarea.addEventListener("selectionchange", () => {
2050
+ this.toolbar.updateButtonStates();
2051
+ });
2052
+ this.textarea.addEventListener("input", () => {
2053
+ this.toolbar.updateButtonStates();
2054
+ });
2055
+ }
2056
+ this.initialized = true;
2057
+ if (this.options.onChange) {
2058
+ this.options.onChange(this.getValue(), this);
2059
+ }
2060
+ }
2061
+ /**
2062
+ * Merge user options with defaults
2063
+ * @private
2064
+ */
2065
+ _mergeOptions(options) {
2066
+ const defaults = {
2067
+ // Typography
2068
+ fontSize: "14px",
2069
+ lineHeight: 1.6,
2070
+ fontFamily: "'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace",
2071
+ padding: "16px",
2072
+ // Mobile styles
2073
+ mobile: {
2074
+ fontSize: "16px",
2075
+ // Prevent zoom on iOS
2076
+ padding: "12px",
2077
+ lineHeight: 1.5
2078
+ },
2079
+ // Behavior
2080
+ autofocus: false,
2081
+ placeholder: "Start typing...",
2082
+ value: "",
2083
+ // Callbacks
2084
+ onChange: null,
2085
+ onKeydown: null,
2086
+ // Features
2087
+ showActiveLineRaw: false,
2088
+ showStats: false,
2089
+ toolbar: false,
2090
+ statsFormatter: null
2091
+ };
2092
+ const { theme, colors, ...cleanOptions } = options;
2093
+ return {
2094
+ ...defaults,
2095
+ ...cleanOptions
2096
+ };
2097
+ }
2098
+ /**
2099
+ * Recover from existing DOM structure
2100
+ * @private
2101
+ */
2102
+ _recoverFromDOM(container, wrapper) {
2103
+ if (container && container.classList.contains("overtype-container")) {
2104
+ this.container = container;
2105
+ this.wrapper = container.querySelector(".overtype-wrapper");
2106
+ } else if (wrapper) {
2107
+ this.wrapper = wrapper;
2108
+ this.container = document.createElement("div");
2109
+ this.container.className = "overtype-container";
2110
+ const currentTheme = _OverType.currentTheme || solar;
2111
+ const themeName = typeof currentTheme === "string" ? currentTheme : currentTheme.name;
2112
+ if (themeName) {
2113
+ this.container.setAttribute("data-theme", themeName);
2114
+ }
2115
+ wrapper.parentNode.insertBefore(this.container, wrapper);
2116
+ this.container.appendChild(wrapper);
2117
+ }
2118
+ if (!this.wrapper) {
2119
+ if (container)
2120
+ container.remove();
2121
+ if (wrapper)
2122
+ wrapper.remove();
2123
+ this._buildFromScratch();
2124
+ return;
2125
+ }
2126
+ this.textarea = this.wrapper.querySelector(".overtype-input");
2127
+ this.preview = this.wrapper.querySelector(".overtype-preview");
2128
+ if (!this.textarea || !this.preview) {
2129
+ this.container.remove();
2130
+ this._buildFromScratch();
2131
+ return;
2132
+ }
2133
+ this.wrapper._instance = this;
2134
+ if (this.options.fontSize) {
2135
+ this.wrapper.style.setProperty("--instance-font-size", this.options.fontSize);
2136
+ }
2137
+ if (this.options.lineHeight) {
2138
+ this.wrapper.style.setProperty("--instance-line-height", String(this.options.lineHeight));
2139
+ }
2140
+ if (this.options.padding) {
2141
+ this.wrapper.style.setProperty("--instance-padding", this.options.padding);
2142
+ }
2143
+ this._configureTextarea();
2144
+ this._applyOptions();
2145
+ }
2146
+ /**
2147
+ * Build editor from scratch
2148
+ * @private
2149
+ */
2150
+ _buildFromScratch() {
2151
+ const content = this._extractContent();
2152
+ this.element.innerHTML = "";
2153
+ this._createDOM();
2154
+ if (content || this.options.value) {
2155
+ this.setValue(content || this.options.value);
2156
+ }
2157
+ this._applyOptions();
2158
+ }
2159
+ /**
2160
+ * Extract content from element
2161
+ * @private
2162
+ */
2163
+ _extractContent() {
2164
+ const textarea = this.element.querySelector(".overtype-input");
2165
+ if (textarea)
2166
+ return textarea.value;
2167
+ return this.element.textContent || "";
2168
+ }
2169
+ /**
2170
+ * Create DOM structure
2171
+ * @private
2172
+ */
2173
+ _createDOM() {
2174
+ this.container = document.createElement("div");
2175
+ this.container.className = "overtype-container";
2176
+ const currentTheme = _OverType.currentTheme || solar;
2177
+ const themeName = typeof currentTheme === "string" ? currentTheme : currentTheme.name;
2178
+ if (themeName) {
2179
+ this.container.setAttribute("data-theme", themeName);
2180
+ }
2181
+ this.wrapper = document.createElement("div");
2182
+ this.wrapper.className = "overtype-wrapper";
2183
+ if (this.options.showStats) {
2184
+ this.wrapper.classList.add("with-stats");
2185
+ }
2186
+ if (this.options.fontSize) {
2187
+ this.wrapper.style.setProperty("--instance-font-size", this.options.fontSize);
2188
+ }
2189
+ if (this.options.lineHeight) {
2190
+ this.wrapper.style.setProperty("--instance-line-height", String(this.options.lineHeight));
2191
+ }
2192
+ if (this.options.padding) {
2193
+ this.wrapper.style.setProperty("--instance-padding", this.options.padding);
2194
+ }
2195
+ this.wrapper._instance = this;
2196
+ this.textarea = document.createElement("textarea");
2197
+ this.textarea.className = "overtype-input";
2198
+ this.textarea.placeholder = this.options.placeholder;
2199
+ this._configureTextarea();
2200
+ this.preview = document.createElement("div");
2201
+ this.preview.className = "overtype-preview";
2202
+ this.preview.setAttribute("aria-hidden", "true");
2203
+ this.wrapper.appendChild(this.textarea);
2204
+ this.wrapper.appendChild(this.preview);
2205
+ if (this.options.showStats) {
2206
+ this.statsBar = document.createElement("div");
2207
+ this.statsBar.className = "overtype-stats";
2208
+ this.wrapper.appendChild(this.statsBar);
2209
+ this._updateStats();
2210
+ }
2211
+ this.container.appendChild(this.wrapper);
2212
+ this.element.appendChild(this.container);
2213
+ }
2214
+ /**
2215
+ * Configure textarea attributes
2216
+ * @private
2217
+ */
2218
+ _configureTextarea() {
2219
+ this.textarea.setAttribute("autocomplete", "off");
2220
+ this.textarea.setAttribute("autocorrect", "off");
2221
+ this.textarea.setAttribute("autocapitalize", "off");
2222
+ this.textarea.setAttribute("spellcheck", "false");
2223
+ this.textarea.setAttribute("data-gramm", "false");
2224
+ this.textarea.setAttribute("data-gramm_editor", "false");
2225
+ this.textarea.setAttribute("data-enable-grammarly", "false");
2226
+ }
2227
+ /**
2228
+ * Apply options to the editor
2229
+ * @private
2230
+ */
2231
+ _applyOptions() {
2232
+ if (this.options.autofocus) {
2233
+ this.textarea.focus();
2234
+ }
2235
+ this.updatePreview();
2236
+ }
2237
+ /**
2238
+ * Update preview with parsed markdown
2239
+ */
2240
+ updatePreview() {
2241
+ const text = this.textarea.value;
2242
+ const cursorPos = this.textarea.selectionStart;
2243
+ const activeLine = this._getCurrentLine(text, cursorPos);
2244
+ const html = MarkdownParser.parse(text, activeLine, this.options.showActiveLineRaw);
2245
+ this.preview.innerHTML = html || '<span style="color: #808080;">Start typing...</span>';
2246
+ this._applyCodeBlockBackgrounds();
2247
+ if (this.options.showStats && this.statsBar) {
2248
+ this._updateStats();
2249
+ }
2250
+ if (this.options.onChange && this.initialized) {
2251
+ this.options.onChange(text, this);
2252
+ }
2253
+ }
2254
+ /**
2255
+ * Apply background styling to code blocks
2256
+ * @private
2257
+ */
2258
+ _applyCodeBlockBackgrounds() {
2259
+ const codeFences = this.preview.querySelectorAll(".code-fence");
2260
+ for (let i = 0; i < codeFences.length - 1; i += 2) {
2261
+ const openFence = codeFences[i];
2262
+ const closeFence = codeFences[i + 1];
2263
+ const openParent = openFence.parentElement;
2264
+ const closeParent = closeFence.parentElement;
2265
+ if (!openParent || !closeParent)
2266
+ continue;
2267
+ openFence.style.display = "block";
2268
+ closeFence.style.display = "block";
2269
+ openParent.classList.add("code-block-line");
2270
+ closeParent.classList.add("code-block-line");
2271
+ let currentDiv = openParent.nextElementSibling;
2272
+ while (currentDiv && currentDiv !== closeParent) {
2273
+ if (currentDiv.tagName === "DIV") {
2274
+ currentDiv.classList.add("code-block-line");
2275
+ }
2276
+ currentDiv = currentDiv.nextElementSibling;
2277
+ if (!currentDiv)
2278
+ break;
2279
+ }
2280
+ }
2281
+ }
2282
+ /**
2283
+ * Get current line number from cursor position
2284
+ * @private
2285
+ */
2286
+ _getCurrentLine(text, cursorPos) {
2287
+ const lines = text.substring(0, cursorPos).split("\n");
2288
+ return lines.length - 1;
2289
+ }
2290
+ /**
2291
+ * Handle input events
2292
+ * @private
2293
+ */
2294
+ handleInput(event) {
2295
+ this.updatePreview();
2296
+ }
2297
+ /**
2298
+ * Handle keydown events
2299
+ * @private
2300
+ */
2301
+ handleKeydown(event) {
2302
+ const handled = this.shortcuts.handleKeydown(event);
2303
+ if (!handled && this.options.onKeydown) {
2304
+ this.options.onKeydown(event, this);
2305
+ }
2306
+ }
2307
+ /**
2308
+ * Handle scroll events
2309
+ * @private
2310
+ */
2311
+ handleScroll(event) {
2312
+ this.preview.scrollTop = this.textarea.scrollTop;
2313
+ this.preview.scrollLeft = this.textarea.scrollLeft;
2314
+ }
2315
+ /**
2316
+ * Get editor content
2317
+ * @returns {string} Current markdown content
2318
+ */
2319
+ getValue() {
2320
+ return this.textarea.value;
2321
+ }
2322
+ /**
2323
+ * Set editor content
2324
+ * @param {string} value - Markdown content to set
2325
+ */
2326
+ setValue(value) {
2327
+ this.textarea.value = value;
2328
+ this.updatePreview();
2329
+ }
2330
+ /**
2331
+ * Focus the editor
2332
+ */
2333
+ focus() {
2334
+ this.textarea.focus();
2335
+ }
2336
+ /**
2337
+ * Blur the editor
2338
+ */
2339
+ blur() {
2340
+ this.textarea.blur();
2341
+ }
2342
+ /**
2343
+ * Check if editor is initialized
2344
+ * @returns {boolean}
2345
+ */
2346
+ isInitialized() {
2347
+ return this.initialized;
2348
+ }
2349
+ /**
2350
+ * Re-initialize with new options
2351
+ * @param {Object} options - New options to apply
2352
+ */
2353
+ reinit(options = {}) {
2354
+ this.options = this._mergeOptions({ ...this.options, ...options });
2355
+ this._applyOptions();
2356
+ this.updatePreview();
2357
+ }
2358
+ /**
2359
+ * Update stats bar
2360
+ * @private
2361
+ */
2362
+ _updateStats() {
2363
+ if (!this.statsBar)
2364
+ return;
2365
+ const value = this.textarea.value;
2366
+ const lines = value.split("\n");
2367
+ const chars = value.length;
2368
+ const words = value.split(/\s+/).filter((w) => w.length > 0).length;
2369
+ const selectionStart = this.textarea.selectionStart;
2370
+ const beforeCursor = value.substring(0, selectionStart);
2371
+ const linesBeforeCursor = beforeCursor.split("\n");
2372
+ const currentLine = linesBeforeCursor.length;
2373
+ const currentColumn = linesBeforeCursor[linesBeforeCursor.length - 1].length + 1;
2374
+ if (this.options.statsFormatter) {
2375
+ this.statsBar.innerHTML = this.options.statsFormatter({
2376
+ chars,
2377
+ words,
2378
+ lines: lines.length,
2379
+ line: currentLine,
2380
+ column: currentColumn
2381
+ });
2382
+ } else {
2383
+ this.statsBar.innerHTML = `
2384
+ <div class="overtype-stat">
2385
+ <span class="live-dot"></span>
2386
+ <span>${chars} chars, ${words} words, ${lines.length} lines</span>
2387
+ </div>
2388
+ <div class="overtype-stat">Line ${currentLine}, Col ${currentColumn}</div>
2389
+ `;
2390
+ }
2391
+ }
2392
+ /**
2393
+ * Show or hide stats bar
2394
+ * @param {boolean} show - Whether to show stats
2395
+ */
2396
+ showStats(show) {
2397
+ this.options.showStats = show;
2398
+ if (show && !this.statsBar) {
2399
+ this.statsBar = document.createElement("div");
2400
+ this.statsBar.className = "overtype-stats";
2401
+ this.wrapper.appendChild(this.statsBar);
2402
+ this.wrapper.classList.add("with-stats");
2403
+ this._updateStats();
2404
+ } else if (!show && this.statsBar) {
2405
+ this.statsBar.remove();
2406
+ this.statsBar = null;
2407
+ this.wrapper.classList.remove("with-stats");
2408
+ }
2409
+ }
2410
+ /**
2411
+ * Destroy the editor instance
2412
+ */
2413
+ destroy() {
2414
+ this.element.overTypeInstance = null;
2415
+ _OverType.instances.delete(this.element);
2416
+ if (this.shortcuts) {
2417
+ this.shortcuts.destroy();
2418
+ }
2419
+ if (this.wrapper) {
2420
+ const content = this.getValue();
2421
+ this.wrapper.remove();
2422
+ this.element.textContent = content;
2423
+ }
2424
+ this.initialized = false;
2425
+ }
2426
+ // ===== Static Methods =====
2427
+ /**
2428
+ * Initialize multiple editors (static convenience method)
2429
+ * @param {string|Element|NodeList|Array} target - Target element(s)
2430
+ * @param {Object} options - Configuration options
2431
+ * @returns {Array} Array of OverType instances
2432
+ */
2433
+ static init(target, options = {}) {
2434
+ return new _OverType(target, options);
2435
+ }
2436
+ /**
2437
+ * Get instance from element
2438
+ * @param {Element} element - DOM element
2439
+ * @returns {OverType|null} OverType instance or null
2440
+ */
2441
+ static getInstance(element) {
2442
+ return element.overTypeInstance || _OverType.instances.get(element) || null;
2443
+ }
2444
+ /**
2445
+ * Destroy all instances
2446
+ */
2447
+ static destroyAll() {
2448
+ const elements = document.querySelectorAll("[data-overtype-instance]");
2449
+ elements.forEach((element) => {
2450
+ const instance = _OverType.getInstance(element);
2451
+ if (instance) {
2452
+ instance.destroy();
2453
+ }
2454
+ });
2455
+ }
2456
+ /**
2457
+ * Inject styles into the document
2458
+ * @param {boolean} force - Force re-injection
2459
+ */
2460
+ static injectStyles(force = false) {
2461
+ if (_OverType.stylesInjected && !force)
2462
+ return;
2463
+ const existing = document.querySelector("style.overtype-styles");
2464
+ if (existing) {
2465
+ existing.remove();
2466
+ }
2467
+ const theme = _OverType.currentTheme || solar;
2468
+ const styles = generateStyles({ theme });
2469
+ const styleEl = document.createElement("style");
2470
+ styleEl.className = "overtype-styles";
2471
+ styleEl.textContent = styles;
2472
+ document.head.appendChild(styleEl);
2473
+ _OverType.stylesInjected = true;
2474
+ }
2475
+ /**
2476
+ * Set global theme for all OverType instances
2477
+ * @param {string|Object} theme - Theme name or custom theme object
2478
+ * @param {Object} customColors - Optional color overrides
2479
+ */
2480
+ static setTheme(theme, customColors = null) {
2481
+ let themeObj = typeof theme === "string" ? getTheme(theme) : theme;
2482
+ if (customColors) {
2483
+ themeObj = mergeTheme(themeObj, customColors);
2484
+ }
2485
+ _OverType.currentTheme = themeObj;
2486
+ _OverType.injectStyles(true);
2487
+ document.querySelectorAll(".overtype-container").forEach((container) => {
2488
+ const themeName = typeof themeObj === "string" ? themeObj : themeObj.name;
2489
+ if (themeName) {
2490
+ container.setAttribute("data-theme", themeName);
2491
+ }
2492
+ });
2493
+ document.querySelectorAll(".overtype-wrapper").forEach((wrapper) => {
2494
+ if (!wrapper.closest(".overtype-container")) {
2495
+ const themeName = typeof themeObj === "string" ? themeObj : themeObj.name;
2496
+ if (themeName) {
2497
+ wrapper.setAttribute("data-theme", themeName);
2498
+ }
2499
+ }
2500
+ const instance = wrapper._instance;
2501
+ if (instance) {
2502
+ instance.updatePreview();
2503
+ }
2504
+ });
2505
+ }
2506
+ /**
2507
+ * Initialize global event listeners
2508
+ */
2509
+ static initGlobalListeners() {
2510
+ if (_OverType.globalListenersInitialized)
2511
+ return;
2512
+ document.addEventListener("input", (e) => {
2513
+ if (e.target && e.target.classList && e.target.classList.contains("overtype-input")) {
2514
+ const wrapper = e.target.closest(".overtype-wrapper");
2515
+ const instance = wrapper == null ? void 0 : wrapper._instance;
2516
+ if (instance)
2517
+ instance.handleInput(e);
2518
+ }
2519
+ });
2520
+ document.addEventListener("keydown", (e) => {
2521
+ if (e.target && e.target.classList && e.target.classList.contains("overtype-input")) {
2522
+ const wrapper = e.target.closest(".overtype-wrapper");
2523
+ const instance = wrapper == null ? void 0 : wrapper._instance;
2524
+ if (instance)
2525
+ instance.handleKeydown(e);
2526
+ }
2527
+ });
2528
+ document.addEventListener("scroll", (e) => {
2529
+ if (e.target && e.target.classList && e.target.classList.contains("overtype-input")) {
2530
+ const wrapper = e.target.closest(".overtype-wrapper");
2531
+ const instance = wrapper == null ? void 0 : wrapper._instance;
2532
+ if (instance)
2533
+ instance.handleScroll(e);
2534
+ }
2535
+ }, true);
2536
+ document.addEventListener("selectionchange", (e) => {
2537
+ const activeElement = document.activeElement;
2538
+ if (activeElement && activeElement.classList.contains("overtype-input")) {
2539
+ const wrapper = activeElement.closest(".overtype-wrapper");
2540
+ const instance = wrapper == null ? void 0 : wrapper._instance;
2541
+ if (instance) {
2542
+ if (instance.options.showStats && instance.statsBar) {
2543
+ instance._updateStats();
2544
+ }
2545
+ clearTimeout(instance._selectionTimeout);
2546
+ instance._selectionTimeout = setTimeout(() => {
2547
+ instance.updatePreview();
2548
+ }, 50);
2549
+ }
2550
+ }
2551
+ });
2552
+ _OverType.globalListenersInitialized = true;
2553
+ }
2554
+ };
2555
+ // Static properties
2556
+ __publicField(_OverType, "instances", /* @__PURE__ */ new WeakMap());
2557
+ __publicField(_OverType, "stylesInjected", false);
2558
+ __publicField(_OverType, "globalListenersInitialized", false);
2559
+ __publicField(_OverType, "instanceCount", 0);
2560
+ var OverType = _OverType;
2561
+ OverType.MarkdownParser = MarkdownParser;
2562
+ OverType.ShortcutsManager = ShortcutsManager;
2563
+ OverType.themes = { solar, cave: getTheme("cave") };
2564
+ OverType.getTheme = getTheme;
2565
+ OverType.currentTheme = solar;
2566
+ var overtype_default = OverType;
2567
+ export {
2568
+ OverType,
2569
+ overtype_default as default
2570
+ };
2571
+ /**
2572
+ * OverType - A lightweight markdown editor library with perfect WYSIWYG alignment
2573
+ * @version 1.0.0
2574
+ * @license MIT
2575
+ */
2576
+ //# sourceMappingURL=overtype.esm.js.map