svelte-rtf-editor 1.8.3 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/utils.js CHANGED
@@ -1,102 +1,704 @@
1
- export function htmlToMarkdown(el) {
2
- let md = '';
3
- el.childNodes.forEach((node) => {
1
+ import { linkTarget } from './rtf-writer.js';
2
+ import { tableModel } from './table-model.js';
3
+ /** Elements whose text is never shown. */
4
+ const UNSHOWN_TAGS = new Set(['style', 'script', 'template', 'noscript', 'title', 'head']);
5
+ /** Elements that are a line of their own and nothing more, as a <div> is. */
6
+ const LINE_TAGS = [
7
+ 'p', 'div', 'dl', 'dt', 'dd', 'section', 'article', 'address', 'details', 'summary', 'center', 'header', 'footer',
8
+ 'main', 'aside', 'nav', 'figcaption', 'li', 'fieldset', 'form', 'legend', 'hgroup'
9
+ ];
10
+ /** Every element that starts a line of its own; anything else is part of the line it stands in. */
11
+ const BLOCK_TAGS = new Set([
12
+ ...LINE_TAGS, 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'menu', 'dir', 'blockquote', 'pre', 'hr', 'table', 'figure'
13
+ ]);
14
+ const BLOCK_SELECTOR = Array.from(BLOCK_TAGS).join(',');
15
+ /**
16
+ * Text as Markdown shows it: the characters Markdown reads as markup are escaped, so "2*3*4" is
17
+ * not emphasis, "#1" not a heading, "[x]" not a link, "<b>" not HTML and "&copy;" not a ©.
18
+ * An "&" is escaped only where a name and a ";" follow it, so "H&E" stays as it is typed.
19
+ * ("&#35;" needs nothing more: its "#" is escaped already.)
20
+ * A "|" is escaped everywhere, not only in a table cell: two lines typed as "Stain | Result" and
21
+ * "--- | ---" are a table to a viewer that knows tables, which then drops what does not fit its
22
+ * columns and cuts a code span in the lines below at its "|", letting the code out.
23
+ */
24
+ function escapeMarkdown(text) {
25
+ return text.replace(/[\\`*_[\]#<~|]/g, '\\$&').replace(/&(?=[a-z][a-z0-9]*;)/gi, '\\&');
26
+ }
27
+ /**
28
+ * Code as a Markdown code span: fenced with more backticks than it holds, and in a table cell its
29
+ * pipes escaped. A line break in it is a space, which is how Markdown shows one in a code span:
30
+ * left as it is, an empty line would end the paragraph and the span with it, and the rest of the
31
+ * code would be read as Markdown and as HTML.
32
+ */
33
+ function codeSpan(code, ctx) {
34
+ const line = code.replace(/[\r\n]+/g, ' ');
35
+ const longest = Math.max(0, ...Array.from(line.matchAll(/`+/g), (m) => m[0].length));
36
+ const fence = '`'.repeat(longest + 1);
37
+ const pad = /^`|`$/.test(line) ? ' ' : '';
38
+ const body = ctx.inCell ? line.replace(/\|/g, '\\|') : line;
39
+ return `${fence}${pad}${body}${pad}${fence}`;
40
+ }
41
+ /**
42
+ * An address as a Markdown link or image target: what would end it, or a table cell, is encoded.
43
+ * Markdown reads "&copy;" in an address as it does in text, so there the "&" is written out.
44
+ */
45
+ function markdownUrl(url) {
46
+ return url
47
+ .replace(/[()|\s<>]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`)
48
+ .replace(/&(?=#?[a-z0-9]+;)/gi, '&amp;');
49
+ }
50
+ /**
51
+ * A picture's address, if it is one a Markdown viewer may load: a web address, a relative path,
52
+ * or PNG/JPEG/GIF/WebP data. Any other scheme (javascript:, file:) is not. Nor is an address with
53
+ * a control character in it: a browser drops some of those before it reads the scheme, so
54
+ * "\x01javascript:…" would pass for a relative path here and be a script there.
55
+ */
56
+ function imageTarget(src) {
57
+ const value = src.trim();
58
+ if (!value)
59
+ return null;
60
+ if (/^data:image\/(png|jpe?g|gif|webp);base64,[A-Za-z0-9+/=\s]+$/i.test(value))
61
+ return value.replace(/\s+/g, '');
62
+ if (/[\u0000-\u001f\u007f]/.test(value))
63
+ return null;
64
+ if (/^https?:\/\//i.test(value) || !/^[a-z][a-z0-9+.-]*:/i.test(value))
65
+ return markdownUrl(value);
66
+ return null;
67
+ }
68
+ /** A picture as Markdown, or its description alone where its address is not one to load. */
69
+ function imageToMarkdown(alt, src, ctx) {
70
+ const target = imageTarget(src);
71
+ const text = escapeMarkdown(alt);
72
+ return target ? `![${text}](${target})` : text;
73
+ }
74
+ /**
75
+ * A list item's Markdown under its marker: later lines are indented to the item's text, so a
76
+ * table, a code block or a list inside the item stays in it.
77
+ */
78
+ function listItem(marker, body) {
79
+ // (Spaces and line breaks only are taken off its ends: other white space is the document's.)
80
+ return `${marker}${body.replace(/^[ \n]+|[ \n]+$/g, '').replace(/\n(?=[^\n])/g, `\n${' '.repeat(marker.length)}`)}`;
81
+ }
82
+ /**
83
+ * A block's text with the marks escaped that mean something only where a line starts: "-", "+"
84
+ * and "1." open a list, ">" a quotation (with or without a space after it). A report line typed
85
+ * as "- Benign." stays that line. A line made only of "=" or of "-" is escaped too: under a line
86
+ * of text it would turn that line into a heading, and on its own "---" would be a rule.
87
+ */
88
+ function escapeLineStarts(markdown) {
89
+ // A line starts at the start of the text and after "\n", and nowhere else: with the "m" flag
90
+ // a pattern also takes U+2028 for a line break, and put backslashes into a code span.
91
+ return markdown.replace(/(^|\n)([ \t]*)(?:(>|[-+](?=\s|$)|-(?=[- \t]*(?:\n|$))|=(?=[= \t]*(?:\n|$)))|(\d+)([.)])(?=\s|$))/g, (_m, start, lead, mark, digits, dot) => (mark ? `${start}${lead}\\${mark}` : `${start}${lead}${digits}\\${dot}`));
92
+ }
93
+ /**
94
+ * Two pieces of one line put together.
95
+ * - A space on each side of the join is one space, as it is on screen ("is <i> benign</i>").
96
+ * - "!" right before a link would make the link a picture, so that "!" is escaped.
97
+ * - "&" in one piece and "copy;" in the next would be read as ©, so that "&" is escaped.
98
+ */
99
+ function joinLine(line, piece) {
100
+ if (!piece)
101
+ return line;
102
+ if (line.endsWith(' ') && piece.startsWith(' '))
103
+ piece = piece.slice(1);
104
+ if (line.endsWith('!') && piece.startsWith('['))
105
+ return `${line.slice(0, -1)}\\!${piece}`;
106
+ const open = line.match(/&[a-z0-9]*$/i);
107
+ if (open && /^[a-z0-9]*;/i.test(piece) && /^&[a-z][a-z0-9]*;/i.test(open[0] + piece)) {
108
+ return `${line.slice(0, open.index)}\\${open[0]}${piece}`;
109
+ }
110
+ return line + piece;
111
+ }
112
+ /**
113
+ * Text between a pair of emphasis marks. Markdown reads "**word **" as plain asterisks, so white
114
+ * space at either end is written outside the marks; with nothing left between them, no marks.
115
+ */
116
+ function emphasis(inner, mark) {
117
+ return around(inner, mark, mark);
118
+ }
119
+ /**
120
+ * Text with something written around it: around the text itself, with the white space and line
121
+ * breaks at either end left outside. (Found with trim, not with one pattern for all three parts:
122
+ * on a long run of spaces inside the text such a pattern took a second.)
123
+ */
124
+ function around(text, open, close) {
125
+ const core = text.trim();
126
+ if (!core)
127
+ return text;
128
+ const start = text.length - text.trimStart().length;
129
+ return `${text.slice(0, start)}${open}${core}${close}${text.slice(start + core.length)}`;
130
+ }
131
+ /**
132
+ * Add a part to a line. Formatted text right after text formatted the same way goes on from it:
133
+ * "<b>Diag</b><b>nosis</b>", which is what a paste from a word processor often holds, is one bold
134
+ * word, where two pairs of marks back to back ("**Diag****nosis**") would show as asterisks.
135
+ */
136
+ function addPart(parts, part) {
137
+ const last = parts[parts.length - 1];
138
+ if (typeof part === 'string') {
139
+ if (!part)
140
+ return;
141
+ if (typeof last === 'string')
142
+ parts[parts.length - 1] = joinLine(last, part);
143
+ else
144
+ parts.push(part);
145
+ }
146
+ else if (part.code !== undefined) {
147
+ // Code right after code is one code span. Two spans back to back run their backticks
148
+ // together ("`a``b`"), which Markdown reads as other fences than the ones written: the
149
+ // two show as one, and with a backtick at the end of the first the code is out of its span.
150
+ if (last !== undefined && typeof last !== 'string' && last.code !== undefined)
151
+ last.code += part.code;
152
+ else
153
+ parts.push({ ...part });
154
+ }
155
+ else if (part.parts.length) {
156
+ if (last !== undefined && typeof last !== 'string' && last.code === undefined && last.key === part.key)
157
+ part.parts.forEach((inner) => addPart(last.parts, inner));
158
+ else
159
+ parts.push({ ...part, parts: [...part.parts] });
160
+ }
161
+ }
162
+ /** The parts of a line as Markdown, each span inside its formatting. */
163
+ function lineOf(parts) {
164
+ return parts.reduce((line, part) => joinLine(line, typeof part === 'string' ? part : part.wrap(part.code ?? lineOf(part.parts))), '');
165
+ }
166
+ /** Parts of a line, inside the formatting of the elements around their block (see MarkdownContext.open). */
167
+ function inOpenFormats(parts, ctx) {
168
+ return ctx.open.reduceRight((inner, format) => (inner.length ? [{ ...format, parts: inner }] : inner), parts);
169
+ }
170
+ /** The formatting of a pair of emphasis marks; none where the same marks are open already, so bold in bold is marked once. */
171
+ function emphasisFormat(mark, ctx) {
172
+ if (ctx.marks.includes(mark))
173
+ return { key: '', inner: ctx, wrap: (text) => text };
174
+ return { key: mark, inner: { ...ctx, marks: [...ctx.marks, mark] }, wrap: (text) => emphasis(text, mark) };
175
+ }
176
+ /**
177
+ * A finished line of text. White space at its ends shows as nothing and is dropped, and so is a
178
+ * line break at its end. A line break inside it is one Markdown keeps: two spaces before the new
179
+ * line. A second break in a row is an empty line, which Markdown would read as the end of the
180
+ * paragraph (and of any bold running through it), so it is written as a <br> at the end of the
181
+ * line before it. Never on a line of its own: a line that holds one tag and nothing else opens a
182
+ * block of HTML, in which "\<" is no escape and the text after it is read as HTML.
183
+ * Where the text must stay on one line (a table cell, a heading), every break is a <br>.
184
+ */
185
+ function finishLine(line, ctx) {
186
+ const text = line.replace(/ *\n */g, '\n').replace(/^[ \n]+|[ \n]+$/g, '');
187
+ if (ctx.oneLine)
188
+ return text.replace(/\n/g, '<br>');
189
+ // Split into what each line holds and the breaks after it, by turns.
190
+ return text
191
+ .split(/(\n+)/)
192
+ .map((piece, i) => (i % 2 ? `${'<br>'.repeat(piece.length - 1)} \n` : startOfLine(piece)))
193
+ .join('');
194
+ }
195
+ /**
196
+ * What a line of a paragraph holds, made safe at its start. White space there is not text to
197
+ * Markdown: a tab makes the line a code block, and a line of white space alone (a tab, a no-break
198
+ * space) is no line at all, so the <br> after it would stand first, as a tag alone on a line does.
199
+ * Such a line is written as "&nbsp;", and a tab at the start as "&#9;", which are text.
200
+ */
201
+ function startOfLine(held) {
202
+ if (held && !/\S/.test(held))
203
+ return '&nbsp;';
204
+ return held.replace(/^[ \t]+/, (lead) => lead.replace(/\t/g, '&#9;'));
205
+ }
206
+ /** End the line of text being written: loose text before a block is a paragraph of its own. */
207
+ function endLine(out, ctx) {
208
+ const text = finishLine(lineOf(out.line), ctx);
209
+ out.line = [];
210
+ if (text)
211
+ out.blocks.push(escapeLineStarts(text));
212
+ }
213
+ /**
214
+ * The context for what an element holds, or null if the screen shows none of it: a <style> or a
215
+ * <script>, the hidden attribute, display:none, or visibility:hidden. Text inside a
216
+ * visibility:hidden element can be shown again by visibility:visible, and then it is written.
217
+ */
218
+ function shown(el, ctx) {
219
+ if (UNSHOWN_TAGS.has(el.tagName.toLowerCase()) || el.hasAttribute('hidden'))
220
+ return null;
221
+ // Word's hidden text, which a paste from Word carries as a style no browser knows.
222
+ if (/mso-hide\s*:\s*all/i.test(el.getAttribute('style') ?? ''))
223
+ return null;
224
+ const style = el.style;
225
+ if (!style)
226
+ return ctx;
227
+ if (style.display === 'none')
228
+ return null;
229
+ if (style.visibility === 'visible')
230
+ return ctx.unseen ? { ...ctx, unseen: false } : ctx;
231
+ if (style.visibility === 'hidden' || style.visibility === 'collapse') {
232
+ const shownAgain = Array.from(el.querySelectorAll('[style]')).some((d) => d.style?.visibility === 'visible');
233
+ return shownAgain ? { ...ctx, unseen: true } : null;
234
+ }
235
+ return ctx;
236
+ }
237
+ /** The same for an element some levels down, as a table's cell is: null if it or anything around it is hidden. */
238
+ function shownIn(el, root, ctx) {
239
+ const path = [];
240
+ for (let at = el; at && at !== root; at = at.parentElement)
241
+ path.unshift(at);
242
+ let inside = ctx;
243
+ for (const step of path)
244
+ inside = inside && shown(step, inside);
245
+ return inside;
246
+ }
247
+ /**
248
+ * The text of a code block or a code span, as the screen shows it: a <br> is a new line and a
249
+ * <div> (which is what Enter leaves in a code block) is a line of its own.
250
+ */
251
+ function codeText(el, ctx) {
252
+ let code = '';
253
+ // A block has started or ended: what comes next starts a new line.
254
+ let lineDue = false;
255
+ const newLineIfDue = () => {
256
+ if (lineDue && code && !code.endsWith('\n'))
257
+ code += '\n';
258
+ lineDue = false;
259
+ };
260
+ const visit = (node, at) => {
4
261
  if (node.nodeType === Node.TEXT_NODE) {
5
- md += node.textContent;
262
+ if (at.unseen || !node.textContent)
263
+ return;
264
+ newLineIfDue();
265
+ code += node.textContent;
6
266
  return;
7
267
  }
8
268
  if (node.nodeType !== Node.ELEMENT_NODE)
9
269
  return;
270
+ const inside = shown(node, at);
271
+ if (!inside)
272
+ return;
10
273
  const tag = node.tagName.toLowerCase();
11
- const inner = htmlToMarkdown(node);
12
- switch (tag) {
13
- case 'h1':
14
- md += `# ${inner}\n\n`;
15
- break;
16
- case 'h2':
17
- md += `## ${inner}\n\n`;
18
- break;
19
- case 'h3':
20
- md += `### ${inner}\n\n`;
21
- break;
22
- case 'p':
23
- md += `${inner}\n\n`;
24
- break;
25
- case 'strong':
26
- case 'b':
27
- md += `**${inner}**`;
28
- break;
29
- case 'em':
30
- case 'i':
31
- md += `*${inner}*`;
32
- break;
33
- case 'u':
34
- md += `<u>${inner}</u>`;
35
- break;
36
- case 's':
37
- case 'strike':
38
- md += `~~${inner}~~`;
39
- break;
40
- case 'a':
41
- md += `[${inner}](${node.href || ''})`;
42
- break;
43
- case 'img':
44
- md += `![${node.alt || ''}](${node.src || ''})`;
45
- break;
46
- case 'figure': {
47
- const img = node.querySelector('img');
48
- const caption = (node.querySelector('figcaption')?.textContent || '').trim();
49
- if (img) {
50
- md += `![${img.getAttribute('alt') || caption}](${img.getAttribute('src') || ''})\n\n`;
51
- if (caption)
52
- md += `*${caption}*\n\n`;
53
- }
54
- break;
274
+ if (tag === 'br') {
275
+ if (inside.unseen)
276
+ return;
277
+ newLineIfDue();
278
+ code += '\n';
279
+ return;
280
+ }
281
+ const block = BLOCK_TAGS.has(tag);
282
+ if (block)
283
+ lineDue = true;
284
+ if (codeDepth >= MAX_ELEMENT_DEPTH) {
285
+ newLineIfDue();
286
+ code += (node.textContent || '');
287
+ }
288
+ else {
289
+ codeDepth++;
290
+ node.childNodes.forEach((child) => visit(child, inside));
291
+ codeDepth--;
292
+ }
293
+ if (block)
294
+ lineDue = true;
295
+ };
296
+ let codeDepth = depth;
297
+ el.childNodes.forEach((child) => visit(child, ctx));
298
+ return code;
299
+ }
300
+ /**
301
+ * How an element formats the text it holds: the context for that text, and what is written
302
+ * around it. Used the same way for a word in a line and for an element around whole paragraphs.
303
+ */
304
+ function formatOf(el, tag, ctx) {
305
+ const plain = { key: '', inner: ctx, wrap: (text) => text };
306
+ const marked = (mark) => emphasisFormat(mark, ctx);
307
+ // What is written around the text goes around the text itself, and white space and line
308
+ // breaks at either end stay outside it. For an HTML tag this is what keeps the text text: a
309
+ // tag alone on a line opens a block of HTML, in which "\<" is no escape.
310
+ const within = (open, close) => ({
311
+ key: open + close,
312
+ inner: ctx,
313
+ wrap: (text) => around(text, open, close)
314
+ });
315
+ switch (tag) {
316
+ case 'strong':
317
+ case 'b':
318
+ // A paste from Google Docs is wrapped in <b style="font-weight:normal">, which is not bold.
319
+ return /^(normal|[1-4]00)$/.test(el.style?.fontWeight ?? '') ? plain : marked('**');
320
+ case 'em':
321
+ case 'i':
322
+ return el.style?.fontStyle === 'normal' ? plain : marked('*');
323
+ case 's':
324
+ case 'strike':
325
+ case 'del':
326
+ return marked('~~');
327
+ case 'u':
328
+ case 'ins':
329
+ case 'sup':
330
+ case 'sub':
331
+ // Markdown has no mark for these; it allows the HTML itself.
332
+ return within(`<${tag}>`, `</${tag}>`);
333
+ case 'a': {
334
+ // As in the RTF: only a web, mail or phone address is a link; a javascript:
335
+ // address, which a Markdown viewer would run, is written as its text alone.
336
+ const target = linkTarget(el.getAttribute('href') || '');
337
+ return target ? within('[', `](${markdownUrl(target)})`) : plain;
338
+ }
339
+ default:
340
+ return plain;
341
+ }
342
+ }
343
+ /**
344
+ * The deepest nesting of elements written element by element. A browser's HTML parser stops at
345
+ * 512, so only a DOM built by script goes deeper; a few thousand deep, one call per element ran
346
+ * out of stack. Past this depth an element is written as its text.
347
+ */
348
+ const MAX_ELEMENT_DEPTH = 600;
349
+ /** How many elements deep the converter is. */
350
+ let depth = 0;
351
+ /** The text an element shows, escaped, read without a call per level of nesting. */
352
+ function flatText(root, ctx) {
353
+ let text = '';
354
+ const pending = [{ node: root, at: ctx }];
355
+ while (pending.length > 0) {
356
+ const { node, at } = pending.pop();
357
+ if (node.nodeType === Node.TEXT_NODE) {
358
+ if (!at.unseen)
359
+ text += node.textContent || '';
360
+ }
361
+ else if (node.nodeType === Node.ELEMENT_NODE) {
362
+ const inside = shown(node, at);
363
+ if (!inside)
364
+ continue;
365
+ for (let i = node.childNodes.length - 1; i >= 0; i--)
366
+ pending.push({ node: node.childNodes[i], at: inside });
367
+ }
368
+ }
369
+ return escapeMarkdown(text.replace(/[ \t\r\n]+/g, ' '));
370
+ }
371
+ /** A piece of a line, as its parts: text, or an element that holds no block. */
372
+ function inlineParts(node, ctx) {
373
+ if (node.nodeType !== Node.ELEMENT_NODE)
374
+ return inlinePartsAt(node, ctx);
375
+ if (depth >= MAX_ELEMENT_DEPTH)
376
+ return [flatText(node, ctx)];
377
+ depth++;
378
+ try {
379
+ return inlinePartsAt(node, ctx);
380
+ }
381
+ finally {
382
+ depth--;
383
+ }
384
+ }
385
+ function inlinePartsAt(node, ctx) {
386
+ if (node.nodeType === Node.TEXT_NODE) {
387
+ if (ctx.unseen)
388
+ return [];
389
+ // A line break in the HTML source shows as a space, as it does on screen; where white
390
+ // space is kept (the editor's tab, <span style="white-space:pre">), it stays.
391
+ const text = node.textContent || '';
392
+ const kept = node.parentElement?.closest('[style*="white-space"]');
393
+ const keeps = kept !== null && /^pre/.test(kept.style.whiteSpace);
394
+ return [escapeMarkdown(keeps ? text.replace(/\r\n?/g, '\n') : text.replace(/[ \t\r\n]+/g, ' '))];
395
+ }
396
+ if (node.nodeType !== Node.ELEMENT_NODE)
397
+ return [];
398
+ const el = node;
399
+ const inside = shown(el, ctx);
400
+ if (!inside)
401
+ return [];
402
+ const tag = el.tagName.toLowerCase();
403
+ switch (tag) {
404
+ case 'br':
405
+ return inside.unseen ? [] : ['\n'];
406
+ case 'img':
407
+ return inside.unseen ? [] : [imageToMarkdown(el.getAttribute('alt') || inside.figure?.alt || '', el.getAttribute('src') || '', inside)];
408
+ case 'code': {
409
+ // Code is written as it is. With no code in it there is nothing to show: an empty
410
+ // code span is not Markdown, it would be read as two backticks.
411
+ const code = codeText(el, inside);
412
+ return code ? [{ key: 'code', code, parts: [], wrap: (text) => codeSpan(text, inside) }] : [];
413
+ }
414
+ }
415
+ const format = formatOf(el, tag, inside);
416
+ const parts = [];
417
+ el.childNodes.forEach((child) => inlineParts(child, format.inner).forEach((part) => addPart(parts, part)));
418
+ return format.key ? [{ key: format.key, wrap: format.wrap, parts }] : parts;
419
+ }
420
+ /**
421
+ * Write what a run of nodes holds. Text and the elements that are part of a line are added to the
422
+ * line being written; a block ends that line first, so text typed before a block (which is what a
423
+ * browser leaves when a line is typed and Enter pressed) is a paragraph of its own. An element
424
+ * that is not a block but holds one (<b><p>…</p></b>, a <span> around a list) is opened up: its
425
+ * blocks are written as blocks, each with the element's formatting on its text.
426
+ */
427
+ function nodesToMarkdown(nodes, ctx, out) {
428
+ let run = [];
429
+ const endRun = () => {
430
+ inOpenFormats(run, ctx).forEach((part) => addPart(out.line, part));
431
+ run = [];
432
+ };
433
+ for (const node of nodes) {
434
+ if (node.nodeType !== Node.ELEMENT_NODE) {
435
+ inlineParts(node, ctx).forEach((part) => addPart(run, part));
436
+ continue;
437
+ }
438
+ const el = node;
439
+ if (ctx.captions.has(el))
440
+ continue;
441
+ const inside = shown(el, ctx);
442
+ if (!inside)
443
+ continue;
444
+ if (depth >= MAX_ELEMENT_DEPTH) {
445
+ addPart(run, flatText(el, ctx));
446
+ continue;
447
+ }
448
+ const tag = el.tagName.toLowerCase();
449
+ // In a figure a picture is a block of its own, so text typed beside it is not run into it.
450
+ const isBlock = BLOCK_TAGS.has(tag) || (tag === 'img' && ctx.figure !== null);
451
+ if (!isBlock && (tag === 'code' || !el.querySelector(BLOCK_SELECTOR))) {
452
+ inlineParts(el, ctx).forEach((part) => addPart(run, part));
453
+ continue;
454
+ }
455
+ endRun();
456
+ depth++;
457
+ try {
458
+ if (!isBlock) {
459
+ const format = formatOf(el, tag, inside);
460
+ nodesToMarkdown(el.childNodes, { ...format.inner, open: format.key ? [...inside.open, format] : inside.open }, out);
461
+ continue;
55
462
  }
56
- case 'figcaption':
57
- // Rendered by the enclosing <figure>.
58
- break;
59
- case 'blockquote':
60
- md += `> ${inner.trim()}\n\n`;
61
- break;
62
- case 'pre':
63
- md += `\`\`\`\n${node.textContent}\n\`\`\`\n\n`;
64
- break;
65
- case 'code':
66
- md += `\`${inner}\``;
67
- break;
68
- case 'ul':
69
- node.querySelectorAll(':scope > li').forEach((li) => {
70
- md += `- ${htmlToMarkdown(li).trim()}\n`;
71
- });
72
- md += '\n';
73
- break;
74
- case 'ol': {
75
- let i = 1;
76
- node.querySelectorAll(':scope > li').forEach((li) => {
77
- md += `${i++}. ${htmlToMarkdown(li).trim()}\n`;
78
- });
79
- md += '\n';
463
+ endLine(out, ctx);
464
+ blockToMarkdown(el, tag, inside, out);
465
+ }
466
+ finally {
467
+ depth--;
468
+ }
469
+ }
470
+ endRun();
471
+ }
472
+ /** The blocks a run of nodes holds, with any loose text among them as paragraphs. */
473
+ function blocksOf(nodes, ctx) {
474
+ const out = { blocks: [], line: [] };
475
+ nodesToMarkdown(nodes, ctx, out);
476
+ endLine(out, ctx);
477
+ return out.blocks;
478
+ }
479
+ /**
480
+ * What an element holds, as Markdown: each block followed by a blank line. Text at the very end
481
+ * that is in no block ends with no line break, so a caller can go on from it.
482
+ */
483
+ function childrenToMarkdown(el, ctx) {
484
+ const out = { blocks: [], line: [] };
485
+ nodesToMarkdown(el.childNodes, ctx, out);
486
+ return out.blocks.map((block) => `${block}\n\n`).join('') + escapeLineStarts(finishLine(lineOf(out.line), ctx));
487
+ }
488
+ /** What a table cell holds, on the one line a cell has; nothing for a cell, or a row, that is hidden. */
489
+ function cellToMarkdown(cell, table, ctx, lineBreak) {
490
+ const inside = shownIn(cell, table, ctx);
491
+ return inside ? childrenToMarkdown(cell, inside).trim().replace(/\s*\n\s*/g, lineBreak) : '';
492
+ }
493
+ /** Whether a row of the table is one the screen shows: a hidden row is not written as an empty one. */
494
+ function rowShown(row, r, table, ctx) {
495
+ const own = row.find((cell) => cell?.row === r);
496
+ return !own?.el.parentElement || shownIn(own.el.parentElement, table, ctx) !== null;
497
+ }
498
+ /** A table's caption, which stands above it: a line of its own, so its text is not lost. */
499
+ function captionBlocks(table, ctx) {
500
+ return Array.from(table.children)
501
+ .filter((child) => child.tagName.toLowerCase() === 'caption')
502
+ .flatMap((caption) => blocksOf([caption], ctx));
503
+ }
504
+ /** A table as a Markdown (GFM) table. */
505
+ function tableToMarkdown(table, ctx) {
506
+ const model = tableModel(table);
507
+ if (model.columns === 0)
508
+ return '';
509
+ const inCell = { ...ctx, inCell: true, oneLine: true, figure: null };
510
+ // The first row is always written: it is the header Markdown requires.
511
+ const lines = model.rows.filter((row, r) => r === 0 || rowShown(row, r, table, ctx)).map((row) => {
512
+ // Markdown has no merged cells: a cell that spans is written where it starts, and the
513
+ // other columns and rows it covers are left empty so the columns still line up.
514
+ const cells = row.map((cell, c) => {
515
+ if (!cell || cell.col !== c || model.rows[cell.row] !== row)
516
+ return '';
517
+ return cellToMarkdown(cell.el, table, inCell, '<br>');
518
+ });
519
+ return `| ${cells.join(' | ')} |`;
520
+ });
521
+ // The first row is the header if it holds a header cell; a table with none gets an empty
522
+ // one, which Markdown requires.
523
+ const hasHeader = model.rows[0].some((cell) => cell?.row === 0 && cell.el.tagName.toLowerCase() === 'th');
524
+ if (!hasHeader)
525
+ lines.unshift(`| ${model.rows[0].map(() => ' ').join(' | ')} |`);
526
+ lines.splice(1, 0, `| ${model.rows[0].map(() => '---').join(' | ')} |`);
527
+ return lines.join('\n');
528
+ }
529
+ /** A table inside a table cell, as text: its caption, then each row a line, its cells a slash apart. */
530
+ function nestedTableToText(table, ctx) {
531
+ const model = tableModel(table);
532
+ const rows = model.rows
533
+ .filter((row, r) => rowShown(row, r, table, ctx))
534
+ .map((row) => row
535
+ .filter((cell, c) => cell && cell.col === c && model.rows[cell.row] === row)
536
+ .map((cell) => cellToMarkdown(cell.el, table, ctx, ' '))
537
+ .join(' / '));
538
+ return [...captionBlocks(table, ctx), ...rows].filter(Boolean).join('\n');
539
+ }
540
+ /**
541
+ * A list. An item is its marker and what it holds. A list written straight inside a list, which
542
+ * is not valid HTML but is what some editors and pastes produce, is nested under the item before
543
+ * it, as the screen shows it. Anything else that is not an item (loose text, a paragraph) is kept
544
+ * as a line of its own between the items; a numbered list goes on counting after it.
545
+ */
546
+ function listToMarkdown(list, ordered, ctx, out) {
547
+ const start = parseInt(list.getAttribute('start') ?? '', 10);
548
+ // Markdown writes a list number in up to nine digits and none below zero. A number it cannot
549
+ // write ("-3.", or ten digits) is text, not a marker, and a code block in that item no code
550
+ // block: the list starts as near to its own number as Markdown can count from.
551
+ const itemCount = Array.from(list.children).filter((child) => child.tagName === 'LI').length;
552
+ let number = Number.isFinite(start) ? Math.max(0, Math.min(start, 1_000_000_000 - Math.max(itemCount, 1))) : 1;
553
+ let items = [];
554
+ let loose = [];
555
+ const endItems = () => {
556
+ if (items.length)
557
+ out.blocks.push(items.map((item) => listItem(item.marker, item.blocks.join('\n\n'))).join('\n'));
558
+ items = [];
559
+ };
560
+ const endLoose = () => {
561
+ const blocks = blocksOf(loose, ctx);
562
+ loose = [];
563
+ if (!blocks.length)
564
+ return;
565
+ endItems();
566
+ out.blocks.push(...blocks);
567
+ };
568
+ list.childNodes.forEach((node) => {
569
+ const tag = node.nodeType === Node.ELEMENT_NODE ? node.tagName.toLowerCase() : '';
570
+ if (tag === 'li') {
571
+ endLoose();
572
+ const inside = shown(node, ctx);
573
+ if (!inside)
574
+ return;
575
+ const blocks = blocksOf(node.childNodes, inside);
576
+ // An item whose text is hidden shows no marker either.
577
+ if (blocks.length || !inside.unseen)
578
+ items.push({ marker: ordered ? `${number++}. ` : '- ', blocks });
579
+ }
580
+ else if (['ul', 'ol', 'menu', 'dir'].includes(tag)) {
581
+ endLoose();
582
+ if (items.length)
583
+ items[items.length - 1].blocks.push(...blocksOf([node], ctx));
584
+ else
585
+ loose.push(node);
586
+ }
587
+ else {
588
+ loose.push(node);
589
+ }
590
+ });
591
+ endLoose();
592
+ endItems();
593
+ }
594
+ /** Write one block element. The line before it has been ended. */
595
+ function blockToMarkdown(el, tag, ctx, out) {
596
+ switch (tag) {
597
+ case 'h1':
598
+ case 'h2':
599
+ case 'h3':
600
+ case 'h4':
601
+ case 'h5':
602
+ case 'h6': {
603
+ // A heading is one line: a line break in it, written as a new line, would put the
604
+ // rest of its text outside the heading.
605
+ const text = blocksOf(el.childNodes, { ...ctx, oneLine: true }).join('<br>').replace(/\s*\n\s*/g, '<br>');
606
+ if (text)
607
+ out.blocks.push(`${'#'.repeat(Number(tag[1]))} ${text}`);
608
+ break;
609
+ }
610
+ case 'ul':
611
+ case 'menu':
612
+ case 'dir':
613
+ case 'ol':
614
+ listToMarkdown(el, tag === 'ol', ctx, out);
615
+ break;
616
+ case 'blockquote': {
617
+ // Every line of the quotation carries the mark, the blank ones too: a line without it
618
+ // would end the quotation, and a code block opened in it would close outside it.
619
+ const held = blocksOf(el.childNodes, ctx).join('\n\n');
620
+ if (held)
621
+ out.blocks.push(held.split('\n').map((line) => (line.trim() ? `> ${line}` : '>')).join('\n'));
622
+ break;
623
+ }
624
+ case 'pre': {
625
+ // A lone carriage return ends a line in Markdown too, and the lines of a code block
626
+ // are indented and quoted one by one: left in, it would start a line without the
627
+ // ">" or the indent, outside the block.
628
+ const code = codeText(el, ctx).replace(/\r\n?/g, '\n');
629
+ if (ctx.oneLine) {
630
+ // A table cell holds one line: each line of the block is a code span of its own.
631
+ const spans = code.split('\n').map((line) => (line ? codeSpan(line, ctx) : '')).join('<br>');
632
+ if (spans)
633
+ out.blocks.push(spans);
80
634
  break;
81
635
  }
82
- case 'li':
83
- md += inner;
84
- break;
85
- case 'br':
86
- md += '\n';
87
- break;
88
- case 'hr':
89
- md += '\n---\n\n';
90
- break;
91
- case 'div':
92
- md += `${inner}\n`;
93
- break;
94
- default:
95
- md += inner;
636
+ const longest = Math.max(2, ...Array.from(code.matchAll(/`+/g), (m) => m[0].length));
637
+ const fence = '`'.repeat(longest + 1);
638
+ out.blocks.push(`${fence}\n${code}\n${fence}`);
639
+ break;
640
+ }
641
+ case 'hr':
642
+ if (!ctx.unseen)
643
+ out.blocks.push('\n---');
644
+ break;
645
+ case 'table': {
646
+ // Markdown cannot put a table in a table cell: the inner one is its rows as lines,
647
+ // its cells a slash apart, as the RTF writes them a tab apart.
648
+ if (ctx.oneLine) {
649
+ const text = nestedTableToText(el, ctx);
650
+ if (text)
651
+ out.blocks.push(text);
96
652
  break;
653
+ }
654
+ out.blocks.push(...captionBlocks(el, ctx));
655
+ const table = tableToMarkdown(el, ctx);
656
+ if (table)
657
+ out.blocks.push(table);
658
+ break;
659
+ }
660
+ case 'figure': {
661
+ // A figure writes everything it holds: each picture as a block of its own, text typed
662
+ // beside a picture as paragraphs, and last its own caption (not the caption of a
663
+ // figure inside it, which that figure writes). The caption and a picture's description
664
+ // are text like any other, so a "[x](javascript:…)" in either stays text.
665
+ const captions = Array.from(el.querySelectorAll('figcaption')).filter((c) => c.parentElement?.closest('figure') === el);
666
+ const seen = captions.filter((c) => shownIn(c, el, ctx) !== null);
667
+ const alt = seen.map((c) => (c.textContent || '').replace(/\s+/g, ' ').trim()).find(Boolean) ?? '';
668
+ nodesToMarkdown(el.childNodes, { ...ctx, figure: { alt }, captions: new Set([...ctx.captions, ...captions]) }, out);
669
+ endLine(out, ctx);
670
+ // A caption is written in italics, as it always was.
671
+ const italic = emphasisFormat('*', { ...ctx, figure: null });
672
+ const inCaption = { ...italic.inner, open: italic.key ? [...ctx.open, italic] : ctx.open };
673
+ for (const caption of seen)
674
+ out.blocks.push(...blocksOf(caption.childNodes, inCaption));
675
+ break;
676
+ }
677
+ case 'img': {
678
+ // Reached only inside a figure (see nodesToMarkdown).
679
+ const image = ctx.unseen ? '' : imageToMarkdown(el.getAttribute('alt') || ctx.figure?.alt || '', el.getAttribute('src') || '', ctx);
680
+ if (image)
681
+ out.blocks.push(lineOf(inOpenFormats([image], ctx)));
682
+ break;
97
683
  }
684
+ default:
685
+ // A paragraph, a <div>, or a block Markdown has no word for (<section>, <dd>, …): what
686
+ // it holds, as a paragraph of its own.
687
+ nodesToMarkdown(el.childNodes, ctx, out);
688
+ endLine(out, ctx);
689
+ break;
690
+ }
691
+ }
692
+ export function htmlToMarkdown(el) {
693
+ return childrenToMarkdown(el, {
694
+ inCell: false,
695
+ oneLine: false,
696
+ open: [],
697
+ marks: [],
698
+ figure: null,
699
+ unseen: false,
700
+ captions: new Set()
98
701
  });
99
- return md;
100
702
  }
101
703
  export function downloadFile(filename, content, mimeType) {
102
704
  const blob = new Blob([content], { type: mimeType });