-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathrich_text_editor.js
697 lines (621 loc) · 18.9 KB
/
rich_text_editor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
/**
* @typedef {Object} QuillAttributes
* @property {boolean} [bold] - Whether the text is bold.
* @property {boolean} [italic] - Whether the text is italic.
* @property {string} [link] - URL if the text is a link.
* @property {number} [header] - Header level (1-3).
* @property {string} [list] - List type ('ordered' or 'bullet').
* @property {boolean} [blockquote] - Whether the text is in a blockquote.
* @property {string} [code-block] - Code language if in a code block.
* @property {string} [alt] - Alt text for images.
*/
/**
* @typedef {Object} QuillOperation
* @property {string|Object} [insert] - Content to insert (string or object with image URL).
* @property {number} [delete] - Number of characters to delete.
* @property {number} [retain] - Number of characters to retain.
* @property {QuillAttributes} [attributes] - Formatting attributes.
*/
/**
* @typedef {Object} QuillDelta
* @property {Array<QuillOperation>} ops - Array of operations in the delta.
*/
/**
* Converts Quill Delta object to a Markdown string using mdast.
* @param {QuillDelta} delta - Quill Delta object (https://quilljs.com/docs/delta/).
* @returns {string} - Markdown representation.
*/
function deltaToMarkdown(delta) {
const mdastTree = deltaToMdast(delta);
const options = {
bullet: "*",
listItemIndent: "one",
handlers: {},
unknownHandler: (node) => {
console.warn(`Unknown node type encountered: ${node.type}`, node);
return false;
},
};
return mdastUtilToMarkdown(mdastTree, options);
}
/**
* Creates a div to replace the textarea and prepares it for Quill.
* @param {HTMLTextAreaElement} textarea - The original textarea.
* @returns {HTMLDivElement} - The div element created for the Quill editor.
*/
function createAndReplaceTextarea(textarea) {
const editorDiv = document.createElement("div");
editorDiv.className = "mb-3";
editorDiv.style.height = "250px";
const label = textarea.closest("label");
if (!label) {
textarea.parentNode.insertBefore(editorDiv, textarea);
} else {
label.parentNode.insertBefore(editorDiv, label.nextSibling);
}
textarea.style.display = "none";
return editorDiv;
}
/**
* Returns the toolbar options array configured for Markdown compatibility.
* @returns {Array<Array<any>>} - Quill toolbar options.
*/
function getMarkdownToolbarOptions() {
return [
[{ header: 1 }, { header: 2 }, { header: 3 }],
["bold", "italic", "code"],
["link", "image", "blockquote", "code-block"],
[{ list: "ordered" }, { list: "bullet" }],
["clean"],
];
}
/**
* Initializes a Quill editor instance on a given div.
* @param {HTMLDivElement} editorDiv - The div element for the editor.
* @param {Array<Array<any>>} toolbarOptions - The toolbar configuration.
* @param {string} initialValue - The initial content for the editor.
* @returns {Quill} - The initialized Quill instance.
*/
function initializeQuillEditor(editorDiv, toolbarOptions, initialValue) {
const quill = new Quill(editorDiv, {
theme: "snow",
modules: {
toolbar: toolbarOptions,
},
formats: [
"bold",
"italic",
"link",
"header",
"list",
"blockquote",
"code",
"code-block",
"image",
],
});
if (initialValue) {
quill.setText(initialValue);
}
return quill;
}
/**
* Attaches a submit event listener to the form to update the hidden textarea.
* @param {HTMLFormElement|null} form - The form containing the editor.
* @param {HTMLTextAreaElement} textarea - The original (hidden) textarea.
* @param {Quill} quill - The Quill editor instance.
* @returns {void}
*/
function updateTextareaOnSubmit(form, textarea, quill) {
if (!form) {
console.warn(
"Textarea not inside a form, submission handling skipped for:",
textarea.name || textarea.id,
);
return;
}
form.addEventListener("submit", () => {
const delta = quill.getContents();
const markdownContent = deltaToMarkdown(delta);
textarea.value = markdownContent;
});
}
/**
* Loads the Quill CSS stylesheet.
* @returns {void}
*/
function loadQuillStylesheet() {
const link = document.createElement("link");
link.rel = "stylesheet";
document.head.appendChild(link);
}
/**
* Handles errors during editor initialization.
* @param {HTMLTextAreaElement} textarea - The textarea that failed initialization.
* @param {Error} error - The error that occurred.
* @returns {void}
*/
function handleEditorInitError(textarea, error) {
console.error("Failed to initialize Quill for textarea:", textarea, error);
textarea.style.display = "";
const errorMsg = document.createElement("p");
errorMsg.textContent = "Failed to load rich text editor.";
errorMsg.style.color = "red";
textarea.parentNode.insertBefore(errorMsg, textarea.nextSibling);
}
/**
* Sets up a single editor for a textarea.
* @param {HTMLTextAreaElement} textarea - The textarea to replace with an editor.
* @param {Array<Array<any>>} toolbarOptions - The toolbar configuration.
* @returns {boolean} - Whether the setup was successful.
*/
function setupSingleEditor(textarea, toolbarOptions) {
if (textarea.dataset.quillInitialized === "true") {
return false;
}
try {
const initialValue = textarea.value;
const form = textarea.closest("form");
const editorDiv = createAndReplaceTextarea(textarea);
const quill = initializeQuillEditor(
editorDiv,
toolbarOptions,
initialValue,
);
updateTextareaOnSubmit(form, textarea, quill);
textarea.dataset.quillInitialized = "true";
return true;
} catch (error) {
handleEditorInitError(textarea, error);
return false;
}
}
/**
* Initializes Quill editors for all textareas in the document.
* @returns {void}
*/
function initializeEditors() {
loadQuillStylesheet();
const textareas = document.getElementsByTagName("textarea");
if (textareas.length === 0) {
return;
}
const toolbarOptions = getMarkdownToolbarOptions();
let initializedCount = 0;
for (const textarea of textareas) {
if (setupSingleEditor(textarea, toolbarOptions)) {
initializedCount++;
}
}
if (initializedCount > 0) {
console.log(
`Successfully initialized Quill for ${initializedCount} textareas.`,
);
}
}
// MDAST conversion functions
/**
* @typedef {Object} MdastNode
* @property {string} type - The type of the node.
* @property {Array<MdastNode>} [children] - Child nodes.
* @property {string} [value] - Text value for text nodes.
* @property {string} [url] - URL for link and image nodes.
* @property {string} [title] - Title for image nodes.
* @property {string} [alt] - Alt text for image nodes.
* @property {number} [depth] - Depth for heading nodes.
* @property {boolean} [ordered] - Whether the list is ordered.
* @property {boolean} [spread] - Whether the list is spread.
* @property {string} [lang] - Language for code blocks.
*/
/**
* Converts a Quill Delta to a MDAST (Markdown Abstract Syntax Tree).
* @param {QuillDelta} delta - The Quill Delta to convert.
* @returns {MdastNode} - The root MDAST node.
*/
function deltaToMdast(delta) {
const mdast = createRootNode();
/** @type {MdastNode|null} */
let currentParagraph = null;
/** @type {MdastNode|null} */
let currentList = null;
let textBuffer = "";
for (const op of delta.ops) {
if (isImageInsert(op)) {
if (!currentParagraph) {
currentParagraph = createParagraphNode();
}
currentParagraph.children.push(createImageNode(op));
}
if (typeof op.insert !== "string") continue;
const text = op.insert;
const attributes = op.attributes || {};
// Handle newlines within text content
if (text.includes("\n") && text !== "\n") {
const lines = text.split("\n");
// Process all lines except the last one as complete lines
for (let i = 0; i < lines.length - 1; i++) {
const line = lines[i];
if (line.length > 0) {
// Add text to current paragraph
if (!currentParagraph) {
currentParagraph = createParagraphNode();
}
const nodes = createTextNodes(line, attributes);
currentParagraph.children.push(...nodes);
textBuffer = line;
}
// Process line break with empty attributes (regular paragraph break)
processLineBreak(mdast, currentParagraph, {}, textBuffer, currentList);
currentParagraph = null;
textBuffer = "";
}
// Add the last line to the buffer without processing the line break yet
const lastLine = lines[lines.length - 1];
if (lastLine.length > 0) {
if (!currentParagraph) {
currentParagraph = createParagraphNode();
}
const nodes = createTextNodes(lastLine, attributes);
currentParagraph.children.push(...nodes);
textBuffer = lastLine;
}
continue;
}
if (text === "\n") {
currentList = processLineBreak(
mdast,
currentParagraph,
attributes,
textBuffer,
currentList,
);
// Reset paragraph and buffer after processing line break
currentParagraph = null;
textBuffer = "";
continue;
}
// Process regular text
const nodes = createTextNodes(text, attributes);
if (!currentParagraph) {
currentParagraph = createParagraphNode();
}
textBuffer += text;
currentParagraph.children.push(...nodes);
}
if (currentParagraph) {
mdast.children.push(currentParagraph);
}
return mdast;
}
/**
* Creates a root MDAST node.
* @returns {MdastNode} - The root node.
*/
function createRootNode() {
return {
type: "root",
children: [],
};
}
/**
* Creates a paragraph MDAST node.
* @returns {MdastNode} - The paragraph node.
*/
function createParagraphNode() {
return {
type: "paragraph",
children: [],
};
}
/**
* Checks if an operation is an image insertion.
* @param {Object} op - The operation to check.
* @returns {boolean} - Whether the operation is an image insertion.
*/
function isImageInsert(op) {
return typeof op.insert === "object" && op.insert.image;
}
/**
* Creates an image MDAST node.
* @param {Object} op - The operation containing the image.
* @returns {MdastNode} - The image node.
*/
function createImageNode(op) {
return {
type: "image",
url: op.insert.image,
title: op.attributes?.alt || "",
alt: op.attributes?.alt || "",
};
}
/**
* Creates a text MDAST node with optional formatting.
* @param {string} text - The text content.
* @param {Object} attributes - The formatting attributes.
* @returns {MdastNode[]} - The formatted text nodes.
*/
function createTextNodes(text, attributes) {
let nodes = text.split("\n").flatMap((value, i) => [
...(i > 0 ? [{ type: "break" }] : []),
{
type: "text",
value,
},
]);
if (attributes.bold) {
nodes = [wrapNodesWith(nodes, "strong")];
}
if (attributes.italic) {
nodes = [wrapNodesWith(nodes, "emphasis")];
}
if (attributes.link) {
nodes = [{ ...wrapNodesWith(nodes, "link"), url: attributes.link }];
}
return nodes;
}
/**
* Wraps a node with a formatting container.
* @param {MdastNode[]} children - The node to wrap.
* @param {string} type - The type of container.
* @returns {MdastNode} - The wrapped node.
*/
function wrapNodesWith(children, type) {
return {
type: type,
children,
};
}
/**
* Processes a line break in the Delta.
* @param {MdastNode} mdast - The root MDAST node.
* @param {MdastNode|null} currentParagraph - The current paragraph being built.
* @param {Object} attributes - The attributes for the line.
* @param {string} textBuffer - The text buffer for the current line.
* @param {MdastNode|null} currentList - The current list being built.
* @returns {MdastNode|null} - The updated current list.
*/
function processLineBreak(
mdast,
currentParagraph,
attributes,
textBuffer,
currentList,
) {
if (!currentParagraph) {
return handleEmptyLineWithAttributes(mdast, attributes, currentList);
}
if (attributes.header) {
processHeaderLineBreak(mdast, textBuffer, attributes);
return null;
}
if (attributes["code-block"]) {
processCodeBlockLineBreak(mdast, textBuffer, attributes);
return currentList;
}
if (attributes.list) {
return processListLineBreak(
mdast,
currentParagraph,
attributes,
currentList,
);
}
if (attributes.blockquote) {
processBlockquoteLineBreak(mdast, currentParagraph);
return currentList;
}
// Default case: regular paragraph
mdast.children.push(currentParagraph);
return null;
}
/**
* Handles an empty line with special attributes.
* @param {MdastNode} mdast - The root MDAST node.
* @param {Object} attributes - The attributes for the line.
* @param {MdastNode|null} currentList - The current list being built.
* @returns {MdastNode|null} - The updated current list.
*/
function handleEmptyLineWithAttributes(mdast, attributes, currentList) {
if (attributes["code-block"]) {
mdast.children.push(createEmptyCodeBlock(attributes));
return currentList;
}
if (attributes.list) {
const list = ensureList(mdast, attributes, currentList);
list.children.push(createEmptyListItem());
return list;
}
if (attributes.blockquote) {
mdast.children.push(createEmptyBlockquote());
return currentList;
}
return null;
}
/**
* Creates an empty code block MDAST node.
* @param {Object} attributes - The attributes for the code block.
* @returns {MdastNode} - The code block node.
*/
function createEmptyCodeBlock(attributes) {
return {
type: "code",
value: "",
lang:
attributes["code-block"] === "plain" ? null : attributes["code-block"],
};
}
/**
* Creates an empty list item MDAST node.
* @returns {MdastNode} - The list item node.
*/
function createEmptyListItem() {
return {
type: "listItem",
spread: false,
children: [{ type: "paragraph", children: [] }],
};
}
/**
* Creates an empty blockquote MDAST node.
* @returns {MdastNode} - The blockquote node.
*/
function createEmptyBlockquote() {
return {
type: "blockquote",
children: [{ type: "paragraph", children: [] }],
};
}
/**
* Processes a header line break.
* @param {MdastNode} mdast - The root MDAST node.
* @param {string} textBuffer - The text buffer for the current line.
* @param {Object} attributes - The attributes for the line.
* @returns {void}
*/
function processHeaderLineBreak(mdast, textBuffer, attributes) {
const lines = textBuffer.split("\n");
if (lines.length > 1) {
const lastLine = lines.pop();
const previousLines = lines.join("\n");
if (previousLines) {
mdast.children.push({
type: "paragraph",
children: [{ type: "text", value: previousLines }],
});
}
mdast.children.push({
type: "heading",
depth: attributes.header,
children: [{ type: "text", value: lastLine }],
});
} else {
mdast.children.push({
type: "heading",
depth: attributes.header,
children: [{ type: "text", value: textBuffer }],
});
}
}
/**
* Processes a code block line break.
* @param {MdastNode} mdast - The root MDAST node.
* @param {string} textBuffer - The text buffer for the current line.
* @param {Object} attributes - The attributes for the line.
* @returns {void}
*/
function processCodeBlockLineBreak(mdast, textBuffer, attributes) {
const lang =
attributes["code-block"] === "plain" ? null : attributes["code-block"];
// Find the last code block with the same language
let lastCodeBlock = null;
for (let i = mdast.children.length - 1; i >= 0; i--) {
const child = mdast.children[i];
if (child.type === "code" && child.lang === lang) {
lastCodeBlock = child;
break;
}
}
if (lastCodeBlock) {
// Append to existing code block with same language
lastCodeBlock.value += `\n${textBuffer}`;
} else {
// Create new code block
mdast.children.push({
type: "code",
value: textBuffer,
lang,
});
}
}
/**
* Ensures a list exists in the MDAST.
* @param {MdastNode} mdast - The root MDAST node.
* @param {Object} attributes - The attributes for the line.
* @param {MdastNode|null} currentList - The current list being built.
* @returns {MdastNode} - The list node.
*/
function ensureList(mdast, attributes, currentList) {
const isOrderedList = attributes.list === "ordered";
// If there's no current list or the list type doesn't match
if (!currentList || currentList.ordered !== isOrderedList) {
// Check if the last child is a list of the correct type
const lastChild = mdast.children[mdast.children.length - 1];
if (
lastChild &&
lastChild.type === "list" &&
lastChild.ordered === isOrderedList
) {
// Use the last list if it matches the type
return lastChild;
}
// Create a new list
const newList = {
type: "list",
ordered: isOrderedList,
spread: false,
children: [],
};
mdast.children.push(newList);
return newList;
}
return currentList;
}
/**
* Processes a list line break.
* @param {MdastNode} mdast - The root MDAST node.
* @param {MdastNode} currentParagraph - The current paragraph being built.
* @param {Object} attributes - The attributes for the line.
* @param {MdastNode|null} currentList - The current list being built.
* @returns {MdastNode} - The updated list node.
*/
function processListLineBreak(
mdast,
currentParagraph,
attributes,
currentList,
) {
const list = ensureList(mdast, attributes, currentList);
// Check if this list item already exists to avoid duplication
const paragraphContent = JSON.stringify(currentParagraph.children);
const isDuplicate = list.children.some(
(item) =>
item.children?.length === 1 &&
JSON.stringify(item.children[0].children) === paragraphContent,
);
if (!isDuplicate) {
const listItem = {
type: "listItem",
spread: false,
children: [currentParagraph],
};
list.children.push(listItem);
}
return list;
}
/**
* Processes a blockquote line break.
* @param {MdastNode} mdast - The root MDAST node.
* @param {MdastNode} currentParagraph - The current paragraph being built.
* @returns {void}
*/
function processBlockquoteLineBreak(mdast, currentParagraph) {
// Look for an existing blockquote with identical content to avoid duplication
const paragraphContent = JSON.stringify(currentParagraph.children);
const existingBlockquote = mdast.children.find(
(child) =>
child.type === "blockquote" &&
child.children?.length === 1 &&
JSON.stringify(child.children[0].children) === paragraphContent,
);
if (!existingBlockquote) {
mdast.children.push({
type: "blockquote",
children: [currentParagraph],
});
}
}
// Main execution
document.addEventListener("DOMContentLoaded", initializeEditors);