@trismegisto/primitives 3.4.0 → 4.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.
- package/LICENSE +56 -56
- package/MIGRATION.md +831 -0
- package/README.md +8 -0
- package/dist/assignee.js +1 -1
- package/dist/assignee.js.map +1 -1
- package/dist/attachment.js +31 -2
- package/dist/attachment.js.map +1 -1
- package/dist/back-stack.d.ts +32 -0
- package/dist/back-stack.js +166 -0
- package/dist/back-stack.js.map +1 -0
- package/dist/bottom-sheet-gesture.d.ts +22 -0
- package/dist/bottom-sheet-gesture.js +58 -0
- package/dist/bottom-sheet-gesture.js.map +1 -0
- package/dist/calendar-display.d.ts +60 -0
- package/dist/calendar-display.js +132 -0
- package/dist/calendar-display.js.map +1 -0
- package/dist/calendar-external.d.ts +30 -0
- package/dist/calendar-external.js +129 -0
- package/dist/calendar-external.js.map +1 -0
- package/dist/calendar-grid-nav.d.ts +52 -0
- package/dist/calendar-grid-nav.js +91 -0
- package/dist/calendar-grid-nav.js.map +1 -0
- package/dist/calendar-hit.d.ts +33 -0
- package/dist/calendar-hit.js +57 -0
- package/dist/calendar-hit.js.map +1 -0
- package/dist/calendar-index.d.ts +20 -0
- package/dist/calendar-index.js +98 -0
- package/dist/calendar-index.js.map +1 -0
- package/dist/calendar-interaction.d.ts +83 -0
- package/dist/calendar-interaction.js +136 -0
- package/dist/calendar-interaction.js.map +1 -0
- package/dist/calendar-layout.d.ts +275 -0
- package/dist/calendar-layout.js +546 -0
- package/dist/calendar-layout.js.map +1 -0
- package/dist/calendar-now.d.ts +64 -0
- package/dist/calendar-now.js +122 -0
- package/dist/calendar-now.js.map +1 -0
- package/dist/calendar-pointer.d.ts +90 -0
- package/dist/calendar-pointer.js +357 -0
- package/dist/calendar-pointer.js.map +1 -0
- package/dist/calendar-rules.d.ts +139 -0
- package/dist/calendar-rules.js +265 -0
- package/dist/calendar-rules.js.map +1 -0
- package/dist/calendar-series.d.ts +27 -0
- package/dist/calendar-series.js +150 -0
- package/dist/calendar-series.js.map +1 -0
- package/dist/calendar-timeline.d.ts +75 -0
- package/dist/calendar-timeline.js +141 -0
- package/dist/calendar-timeline.js.map +1 -0
- package/dist/calendar-zone.d.ts +101 -0
- package/dist/calendar-zone.js +319 -0
- package/dist/calendar-zone.js.map +1 -0
- package/dist/camera-capture.d.ts +101 -0
- package/dist/camera-capture.js +206 -0
- package/dist/camera-capture.js.map +1 -0
- package/dist/data-grid-clipboard.d.ts +85 -0
- package/dist/data-grid-clipboard.js +223 -0
- package/dist/data-grid-clipboard.js.map +1 -0
- package/dist/data-grid-cursor.d.ts +165 -0
- package/dist/data-grid-cursor.js +219 -0
- package/dist/data-grid-cursor.js.map +1 -0
- package/dist/data-grid-export.d.ts +6 -1
- package/dist/data-grid-export.js +10 -18
- package/dist/data-grid-export.js.map +1 -1
- package/dist/data-grid-measure.d.ts +1 -1
- package/dist/data-grid-measure.js +2 -1
- package/dist/data-grid-measure.js.map +1 -1
- package/dist/data-grid.d.ts +7 -0
- package/dist/data-grid.js.map +1 -1
- package/dist/download.d.ts +15 -0
- package/dist/download.js +39 -0
- package/dist/download.js.map +1 -0
- package/dist/drag-drop.js +5 -3
- package/dist/drag-drop.js.map +1 -1
- package/dist/event-calendar-edit.d.ts +37 -5
- package/dist/event-calendar-edit.js +144 -13
- package/dist/event-calendar-edit.js.map +1 -1
- package/dist/event-calendar.d.ts +130 -11
- package/dist/event-calendar.js +195 -29
- package/dist/event-calendar.js.map +1 -1
- package/dist/file-upload-edit.d.ts +43 -0
- package/dist/file-upload-edit.js +64 -0
- package/dist/file-upload-edit.js.map +1 -0
- package/dist/file-upload-entries.d.ts +84 -0
- package/dist/file-upload-entries.js +214 -0
- package/dist/file-upload-entries.js.map +1 -0
- package/dist/file-upload.d.ts +74 -5
- package/dist/file-upload.js +165 -41
- package/dist/file-upload.js.map +1 -1
- package/dist/focus.d.ts +11 -0
- package/dist/focus.js +80 -4
- package/dist/focus.js.map +1 -1
- package/dist/gallery.d.ts +15 -4
- package/dist/gallery.js +28 -7
- package/dist/gallery.js.map +1 -1
- package/dist/gesture.d.ts +90 -0
- package/dist/gesture.js +165 -0
- package/dist/gesture.js.map +1 -0
- package/dist/graph-centrality.d.ts +36 -0
- package/dist/graph-centrality.js +160 -0
- package/dist/graph-centrality.js.map +1 -0
- package/dist/graph-components.d.ts +49 -0
- package/dist/graph-components.js +344 -0
- package/dist/graph-components.js.map +1 -0
- package/dist/graph-core.d.ts +124 -0
- package/dist/graph-core.js +275 -0
- package/dist/graph-core.js.map +1 -0
- package/dist/graph-order.d.ts +27 -0
- package/dist/graph-order.js +105 -0
- package/dist/graph-order.js.map +1 -0
- package/dist/graph-paths.d.ts +39 -0
- package/dist/graph-paths.js +105 -0
- package/dist/graph-paths.js.map +1 -0
- package/dist/graph-traverse.d.ts +89 -0
- package/dist/graph-traverse.js +164 -0
- package/dist/graph-traverse.js.map +1 -0
- package/dist/graph.d.ts +30 -0
- package/dist/graph.js +31 -0
- package/dist/graph.js.map +1 -0
- package/dist/icalendar.d.ts +33 -5
- package/dist/icalendar.js +269 -9
- package/dist/icalendar.js.map +1 -1
- package/dist/image-crop-io.d.ts +5 -1
- package/dist/image-crop-io.js +18 -5
- package/dist/image-crop-io.js.map +1 -1
- package/dist/image-crop.d.ts +84 -0
- package/dist/image-crop.js +131 -0
- package/dist/image-crop.js.map +1 -1
- package/dist/incident.js +2 -2
- package/dist/index.d.ts +32 -0
- package/dist/index.js +32 -0
- package/dist/index.js.map +1 -1
- package/dist/messages-data-grid.d.ts +42 -7
- package/dist/messages-data-grid.js +51 -0
- package/dist/messages-data-grid.js.map +1 -1
- package/dist/messages-en.js +11 -0
- package/dist/messages-en.js.map +1 -1
- package/dist/messages-es.js +11 -0
- package/dist/messages-es.js.map +1 -1
- package/dist/messages-event-calendar-pro.d.ts +105 -0
- package/dist/messages-event-calendar-pro.js +273 -0
- package/dist/messages-event-calendar-pro.js.map +1 -0
- package/dist/messages-resumable-upload.d.ts +106 -0
- package/dist/messages-resumable-upload.js +256 -0
- package/dist/messages-resumable-upload.js.map +1 -0
- package/dist/messages-rich-text.d.ts +120 -0
- package/dist/messages-rich-text.js +235 -0
- package/dist/messages-rich-text.js.map +1 -0
- package/dist/messages-secret.d.ts +32 -0
- package/dist/messages-secret.js +62 -0
- package/dist/messages-secret.js.map +1 -0
- package/dist/messages.d.ts +14 -0
- package/dist/messages.js +11 -0
- package/dist/messages.js.map +1 -1
- package/dist/mobile.d.ts +25 -0
- package/dist/mobile.js +45 -0
- package/dist/mobile.js.map +1 -0
- package/dist/native.d.ts +71 -0
- package/dist/native.js +147 -0
- package/dist/native.js.map +1 -0
- package/dist/payments.js +1 -1
- package/dist/payments.js.map +1 -1
- package/dist/popover-overlay.d.ts +4 -1
- package/dist/popover-overlay.js +10 -3
- package/dist/popover-overlay.js.map +1 -1
- package/dist/recurrence-editor.d.ts +3 -1
- package/dist/recurrence-editor.js +6 -0
- package/dist/recurrence-editor.js.map +1 -1
- package/dist/recurrence.d.ts +70 -10
- package/dist/recurrence.js +363 -24
- package/dist/recurrence.js.map +1 -1
- package/dist/resource-usage.js +1 -1
- package/dist/resource-usage.js.map +1 -1
- package/dist/resumable-upload-field.d.ts +57 -0
- package/dist/resumable-upload-field.js +196 -0
- package/dist/resumable-upload-field.js.map +1 -0
- package/dist/resumable-upload-store.d.ts +40 -0
- package/dist/resumable-upload-store.js +209 -0
- package/dist/resumable-upload-store.js.map +1 -0
- package/dist/resumable-upload-xhr.d.ts +37 -0
- package/dist/resumable-upload-xhr.js +180 -0
- package/dist/resumable-upload-xhr.js.map +1 -0
- package/dist/resumable-upload.d.ts +268 -0
- package/dist/resumable-upload.js +1221 -0
- package/dist/resumable-upload.js.map +1 -0
- package/dist/rich-text-atoms.d.ts +114 -0
- package/dist/rich-text-atoms.js +328 -0
- package/dist/rich-text-atoms.js.map +1 -0
- package/dist/rich-text-commands.d.ts +2 -2
- package/dist/rich-text-commands.js +1 -1
- package/dist/rich-text-commands.js.map +1 -1
- package/dist/rich-text-dom.d.ts +48 -4
- package/dist/rich-text-dom.js +337 -15
- package/dist/rich-text-dom.js.map +1 -1
- package/dist/rich-text-editor.d.ts +238 -3
- package/dist/rich-text-editor.js +1670 -26
- package/dist/rich-text-editor.js.map +1 -1
- package/dist/rich-text-image.d.ts +62 -0
- package/dist/rich-text-image.js +152 -0
- package/dist/rich-text-image.js.map +1 -0
- package/dist/rich-text-markdown-shortcuts.d.ts +21 -0
- package/dist/rich-text-markdown-shortcuts.js +89 -0
- package/dist/rich-text-markdown-shortcuts.js.map +1 -0
- package/dist/rich-text-markdown.d.ts +57 -0
- package/dist/rich-text-markdown.js +1245 -0
- package/dist/rich-text-markdown.js.map +1 -0
- package/dist/rich-text-model.d.ts +129 -4
- package/dist/rich-text-model.js +554 -33
- package/dist/rich-text-model.js.map +1 -1
- package/dist/rich-text-paste.d.ts +35 -0
- package/dist/rich-text-paste.js +254 -0
- package/dist/rich-text-paste.js.map +1 -0
- package/dist/rich-text-sanitize.d.ts +18 -16
- package/dist/rich-text-sanitize.js +203 -10
- package/dist/rich-text-sanitize.js.map +1 -1
- package/dist/rich-text-schema.d.ts +51 -2
- package/dist/rich-text-schema.js +52 -10
- package/dist/rich-text-schema.js.map +1 -1
- package/dist/rich-text-suggest.d.ts +109 -0
- package/dist/rich-text-suggest.js +181 -0
- package/dist/rich-text-suggest.js.map +1 -0
- package/dist/rich-text-table.d.ts +125 -0
- package/dist/rich-text-table.js +478 -0
- package/dist/rich-text-table.js.map +1 -0
- package/dist/rich-text-validation.d.ts +29 -0
- package/dist/rich-text-validation.js +46 -0
- package/dist/rich-text-validation.js.map +1 -0
- package/dist/rich-text.d.ts +8 -0
- package/dist/rich-text.js +8 -0
- package/dist/rich-text.js.map +1 -1
- package/dist/scheduling.d.ts +6 -0
- package/dist/scheduling.js.map +1 -1
- package/dist/secret.d.ts +120 -0
- package/dist/secret.js +310 -0
- package/dist/secret.js.map +1 -0
- package/dist/service-graph.js +62 -42
- package/dist/service-graph.js.map +1 -1
- package/dist/tabs-overflow.d.ts +27 -0
- package/dist/tabs-overflow.js +36 -0
- package/dist/tabs-overflow.js.map +1 -1
- package/dist/theme-builder.js +16 -16
- package/dist/viewport-gestures.d.ts +144 -0
- package/dist/viewport-gestures.js +352 -0
- package/dist/viewport-gestures.js.map +1 -0
- package/dist/viewport.d.ts +98 -0
- package/dist/viewport.js +241 -0
- package/dist/viewport.js.map +1 -0
- package/dist/workflow.d.ts +0 -7
- package/dist/workflow.js +22 -30
- package/dist/workflow.js.map +1 -1
- package/dist/workspace.d.ts +3 -4
- package/dist/workspace.js +2 -2
- package/dist/workspace.js.map +1 -1
- package/package.json +51 -50
|
@@ -0,0 +1,1245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Markdown do `hm-rich-text`, nos dois sentidos, sem DOM e sem dependência: o subconjunto de CommonMark (0.31) que o
|
|
3
|
+
* modelo representa. Entrada (`richTextFromMarkdown`): parágrafo, quebra de linha (barra invertida ou dois espaços no
|
|
4
|
+
* fim), títulos ATX e Setext, ênfase (`*`/`_`, pelas regras de delimitador do CommonMark, com a pilha de delimitadores
|
|
5
|
+
* do apêndice), tachado com `~~`, código em linha e em bloco (cercado ou recuado), links em linha, de referência e
|
|
6
|
+
* automáticos, listas (`-`, `*`, `+`, `N.`, `N)`), citação e tabela de barras verticais (extensão comum, só com a
|
|
7
|
+
* ferramenta `table`; alinhamentos descartados). **HTML bruto é sempre texto** (o único aceito é o `<u>`
|
|
8
|
+
* com `underline: 'html'`), endereços passam pela regra de protocolo do esquema (falha = texto) e o resultado obedece
|
|
9
|
+
* ao esquema da instância. Saída (`richTextToMarkdown`): a forma normalizada, com escape só onde o caractere mudaria o
|
|
10
|
+
* sentido; a variável sai pela sintaxe, sem escape.
|
|
11
|
+
*
|
|
12
|
+
* Limites: entrada acima de 1 MB vira texto puro; aninhamento de citação e lista acima de 64 níveis vira texto corrido;
|
|
13
|
+
* o analisador é linear (sem retrocesso na ênfase nem nos links).
|
|
14
|
+
*/
|
|
15
|
+
import { richTextHeadingFor, RICH_TEXT_DEFAULT_VARIABLE_SYNTAX, RICH_TEXT_EXTENDED_SCHEMA, RT_BOLD, RT_CODE, RT_ITALIC, RT_STRIKE, RT_UNDERLINE } from './rich-text-schema';
|
|
16
|
+
import { RT_ATOM_CHAR, RT_TABLE_MAX_COLS, RT_TABLE_MAX_ROWS, richTextToPlainText, rtAtomText, rtBlock, rtEmptyDoc, rtParagraph, rtTableBlocks, rtTableBounds, rtTextToDoc } from './rich-text-model';
|
|
17
|
+
import { rtAtomizeDoc } from './rich-text-atoms';
|
|
18
|
+
import { normalizeRichTextImageUrl } from './rich-text-image';
|
|
19
|
+
import { normalizeRichTextUrl, normalizeRichTextVariableUrl, richTextParseHtml } from './rich-text-sanitize';
|
|
20
|
+
export const RICH_TEXT_MARKDOWN_MAX_LENGTH = 1024 * 1024;
|
|
21
|
+
export const RICH_TEXT_MARKDOWN_MAX_DEPTH = 64;
|
|
22
|
+
const ATX = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/;
|
|
23
|
+
const SETEXT = /^ {0,3}(=+|-+)[ \t]*$/;
|
|
24
|
+
const FENCE = /^( {0,3})(`{3,}|~{3,})(.*)$/;
|
|
25
|
+
const BREAK = /^ {0,3}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$/;
|
|
26
|
+
const QUOTE = /^ {0,3}> ?/;
|
|
27
|
+
const BULLET = /^( {0,3})([-+*])([ \t]+|$)/;
|
|
28
|
+
const ORDERED = /^( {0,3})(\d{1,9})([.)])([ \t]+|$)/;
|
|
29
|
+
const REF_DEF = /^ {0,3}\[((?:[^\\\]]|\\.){1,999})\]:[ \t]*(<(?:[^<>\n\\]|\\.)*>|\S+)(?:[ \t]+(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\((?:[^()\\]|\\.)*\)))?[ \t]*$/;
|
|
30
|
+
/** Colunas de recuo (tabulação conta até a próxima parada de 4). */
|
|
31
|
+
function indentOf(line) {
|
|
32
|
+
let col = 0;
|
|
33
|
+
for (const ch of line) {
|
|
34
|
+
if (ch === ' ')
|
|
35
|
+
col++;
|
|
36
|
+
else if (ch === '\t')
|
|
37
|
+
col += 4 - (col % 4);
|
|
38
|
+
else
|
|
39
|
+
break;
|
|
40
|
+
}
|
|
41
|
+
return col;
|
|
42
|
+
}
|
|
43
|
+
/** Tira `n` colunas de recuo (tabulação expandida). */
|
|
44
|
+
function stripIndent(line, n) {
|
|
45
|
+
let col = 0;
|
|
46
|
+
let i = 0;
|
|
47
|
+
while (i < line.length && col < n) {
|
|
48
|
+
if (line[i] === ' ')
|
|
49
|
+
col++;
|
|
50
|
+
else if (line[i] === '\t') {
|
|
51
|
+
const next = col + 4 - (col % 4);
|
|
52
|
+
if (next > n)
|
|
53
|
+
return ' '.repeat(next - n) + line.slice(i + 1);
|
|
54
|
+
col = next;
|
|
55
|
+
}
|
|
56
|
+
else
|
|
57
|
+
break;
|
|
58
|
+
i++;
|
|
59
|
+
}
|
|
60
|
+
return line.slice(i);
|
|
61
|
+
}
|
|
62
|
+
const blank = (line) => /^[ \t]*$/.test(line);
|
|
63
|
+
/** Rótulo de referência normalizado (caixa e espaços). */
|
|
64
|
+
function refLabel(label) {
|
|
65
|
+
return label.trim().replace(/[ \t\r\n]+/g, ' ').toLowerCase();
|
|
66
|
+
}
|
|
67
|
+
function listMarker(line) {
|
|
68
|
+
const bullet = BULLET.exec(line);
|
|
69
|
+
const ordered = bullet ? null : ORDERED.exec(line);
|
|
70
|
+
const m = bullet ?? ordered;
|
|
71
|
+
if (!m)
|
|
72
|
+
return null;
|
|
73
|
+
const indent = m[1].length;
|
|
74
|
+
const marker = bullet ? 1 : m[2].length + 1;
|
|
75
|
+
const spaces = (bullet ? m[3] : m[4]) ?? '';
|
|
76
|
+
const after = line.slice(m[0].length);
|
|
77
|
+
const empty = blank(after);
|
|
78
|
+
const width = empty ? 1 : spaces.length >= 5 ? 1 : Math.max(1, indentOf(spaces));
|
|
79
|
+
const content = indent + marker + width;
|
|
80
|
+
const rest = empty ? '' : spaces.length >= 5 ? stripIndent(line.slice(indent + marker), 1) : after;
|
|
81
|
+
return { ordered: !bullet, char: bullet ? m[2] : m[3], start: bullet ? 1 : Number(m[2]), content, empty, rest };
|
|
82
|
+
}
|
|
83
|
+
/** Linha de alinhamento da tabela de barras verticais (`| --- | :-: |`). */
|
|
84
|
+
const TABLE_DELIMITER = /^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;
|
|
85
|
+
/**
|
|
86
|
+
* Células de uma linha de tabela: barras das pontas opcionais, `\|` é barra literal (sai sem a barra invertida, inclusive
|
|
87
|
+
* em código); as outras barras invertidas ficam para o analisador inline.
|
|
88
|
+
*/
|
|
89
|
+
function splitTableRow(line) {
|
|
90
|
+
let text = line.trim();
|
|
91
|
+
if (text.startsWith('|'))
|
|
92
|
+
text = text.slice(1);
|
|
93
|
+
const cells = [];
|
|
94
|
+
let cell = '';
|
|
95
|
+
let closed = false;
|
|
96
|
+
for (let i = 0; i < text.length; i++) {
|
|
97
|
+
const ch = text[i];
|
|
98
|
+
closed = false;
|
|
99
|
+
if (ch === '\\' && text[i + 1] === '|') {
|
|
100
|
+
cell += '|';
|
|
101
|
+
i++;
|
|
102
|
+
}
|
|
103
|
+
else if (ch === '\\') {
|
|
104
|
+
cell += ch + (text[i + 1] ?? '');
|
|
105
|
+
i++;
|
|
106
|
+
}
|
|
107
|
+
else if (ch === '|') {
|
|
108
|
+
cells.push(cell.trim());
|
|
109
|
+
cell = '';
|
|
110
|
+
closed = true;
|
|
111
|
+
}
|
|
112
|
+
else
|
|
113
|
+
cell += ch;
|
|
114
|
+
}
|
|
115
|
+
if (!closed || cell.trim())
|
|
116
|
+
cells.push(cell.trim());
|
|
117
|
+
return cells;
|
|
118
|
+
}
|
|
119
|
+
/** A linha começaria um bloco que interrompe um parágrafo (fim da continuação preguiçosa). */
|
|
120
|
+
function interrupts(line) {
|
|
121
|
+
if (ATX.test(line) || FENCE.test(line) || BREAK.test(line) || QUOTE.test(line))
|
|
122
|
+
return true;
|
|
123
|
+
const marker = listMarker(line);
|
|
124
|
+
return !!marker && !marker.empty && (!marker.ordered || marker.start === 1);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Estrutura de blocos (recursiva para citação e item de lista, com teto de profundidade). Guarda as definições de
|
|
128
|
+
* referência encontradas no começo dos parágrafos.
|
|
129
|
+
*/
|
|
130
|
+
function parseBlocks(lines, refs, depth) {
|
|
131
|
+
const out = [];
|
|
132
|
+
let para = null;
|
|
133
|
+
const flush = () => {
|
|
134
|
+
if (!para)
|
|
135
|
+
return;
|
|
136
|
+
// Definições de referência no começo do parágrafo.
|
|
137
|
+
while (para.length) {
|
|
138
|
+
const def = REF_DEF.exec(para[0]);
|
|
139
|
+
if (!def)
|
|
140
|
+
break;
|
|
141
|
+
const label = refLabel(unescapeBackslashes(def[1]));
|
|
142
|
+
let dest = def[2];
|
|
143
|
+
if (dest.startsWith('<'))
|
|
144
|
+
dest = dest.slice(1, -1);
|
|
145
|
+
if (label && !refs.has(label))
|
|
146
|
+
refs.set(label, { href: decodeEntities(unescapeBackslashes(dest)) });
|
|
147
|
+
para.shift();
|
|
148
|
+
}
|
|
149
|
+
if (para.length)
|
|
150
|
+
out.push({ kind: 'para', text: para.map((l) => l.replace(/^[ \t]+/, '')).join('\n').replace(/[ \t]+$/, '') });
|
|
151
|
+
para = null;
|
|
152
|
+
};
|
|
153
|
+
let i = 0;
|
|
154
|
+
while (i < lines.length) {
|
|
155
|
+
const line = lines[i];
|
|
156
|
+
if (blank(line)) {
|
|
157
|
+
flush();
|
|
158
|
+
i++;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
const indent = indentOf(line);
|
|
162
|
+
// Código recuado (não interrompe parágrafo).
|
|
163
|
+
if (indent >= 4 && !para) {
|
|
164
|
+
const code = [];
|
|
165
|
+
while (i < lines.length && (blank(lines[i]) || indentOf(lines[i]) >= 4))
|
|
166
|
+
code.push(stripIndent(lines[i++], 4));
|
|
167
|
+
while (code.length && blank(code[code.length - 1]))
|
|
168
|
+
code.pop();
|
|
169
|
+
out.push({ kind: 'code', text: code.join('\n') });
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (indent < 4) {
|
|
173
|
+
const fence = FENCE.exec(line);
|
|
174
|
+
if (fence && !(fence[2][0] === '`' && fence[3].includes('`'))) {
|
|
175
|
+
flush();
|
|
176
|
+
const width = fence[1].length;
|
|
177
|
+
const mark = fence[2];
|
|
178
|
+
const code = [];
|
|
179
|
+
i++;
|
|
180
|
+
while (i < lines.length) {
|
|
181
|
+
const close = /^ {0,3}(`{3,}|~{3,})[ \t]*$/.exec(lines[i]);
|
|
182
|
+
if (close && close[1][0] === mark[0] && close[1].length >= mark.length) {
|
|
183
|
+
i++;
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
code.push(stripIndent(lines[i], width));
|
|
187
|
+
i++;
|
|
188
|
+
}
|
|
189
|
+
out.push({ kind: 'code', text: code.join('\n') });
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
// Tabela de barras verticais: cabeçalho + linha de alinhamento com o mesmo número de células (não interrompe
|
|
193
|
+
// parágrafo); as linhas seguintes até a linha em branco ou outro bloco são o corpo.
|
|
194
|
+
if (!para && line.includes('|') && i + 1 < lines.length && TABLE_DELIMITER.test(lines[i + 1])) {
|
|
195
|
+
const head = splitTableRow(line);
|
|
196
|
+
if (head.length === splitTableRow(lines[i + 1]).length) {
|
|
197
|
+
const raw = [line, lines[i + 1]];
|
|
198
|
+
const rows = [];
|
|
199
|
+
i += 2;
|
|
200
|
+
while (i < lines.length && !blank(lines[i]) && indentOf(lines[i]) < 4 && !interrupts(lines[i])) {
|
|
201
|
+
rows.push(splitTableRow(lines[i]));
|
|
202
|
+
raw.push(lines[i++]);
|
|
203
|
+
}
|
|
204
|
+
out.push({ kind: 'table', head, rows, raw });
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const atx = ATX.exec(line);
|
|
209
|
+
if (atx) {
|
|
210
|
+
flush();
|
|
211
|
+
out.push({ kind: 'heading', level: atx[1].length, text: (atx[2] ?? '').trim() });
|
|
212
|
+
i++;
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (para) {
|
|
216
|
+
const setext = SETEXT.exec(line);
|
|
217
|
+
if (setext) {
|
|
218
|
+
const text = para.map((l) => l.replace(/^[ \t]+/, '')).join('\n').trim();
|
|
219
|
+
para = null;
|
|
220
|
+
out.push({ kind: 'heading', level: setext[1][0] === '=' ? 1 : 2, text });
|
|
221
|
+
i++;
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (BREAK.test(line)) {
|
|
226
|
+
// Linha horizontal: o modelo não tem; separa os blocos.
|
|
227
|
+
flush();
|
|
228
|
+
i++;
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
if (QUOTE.test(line)) {
|
|
232
|
+
flush();
|
|
233
|
+
const inner = [];
|
|
234
|
+
let lazy = true;
|
|
235
|
+
while (i < lines.length) {
|
|
236
|
+
const current = lines[i];
|
|
237
|
+
if (QUOTE.test(current)) {
|
|
238
|
+
const content = current.replace(QUOTE, '');
|
|
239
|
+
inner.push(content);
|
|
240
|
+
lazy = !blank(content);
|
|
241
|
+
i++;
|
|
242
|
+
}
|
|
243
|
+
else if (lazy && !blank(current) && !interrupts(current)) {
|
|
244
|
+
inner.push(current);
|
|
245
|
+
i++;
|
|
246
|
+
}
|
|
247
|
+
else
|
|
248
|
+
break;
|
|
249
|
+
}
|
|
250
|
+
out.push(depth >= RICH_TEXT_MARKDOWN_MAX_DEPTH ? flatPara(inner) : { kind: 'quote', children: parseBlocks(inner, refs, depth + 1) });
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
const marker = listMarker(line);
|
|
254
|
+
if (marker && (!para || (!marker.empty && (!marker.ordered || marker.start === 1)))) {
|
|
255
|
+
flush();
|
|
256
|
+
const items = [];
|
|
257
|
+
let current = marker;
|
|
258
|
+
while (current) {
|
|
259
|
+
const content = current.content;
|
|
260
|
+
const item = [current.rest];
|
|
261
|
+
i++;
|
|
262
|
+
let lazy = !current.empty;
|
|
263
|
+
let blankRun = 0;
|
|
264
|
+
while (i < lines.length) {
|
|
265
|
+
const next = lines[i];
|
|
266
|
+
if (blank(next)) {
|
|
267
|
+
item.push('');
|
|
268
|
+
blankRun++;
|
|
269
|
+
lazy = false;
|
|
270
|
+
i++;
|
|
271
|
+
// Item vazio seguido de linha em branco termina o item.
|
|
272
|
+
if (current.empty && item.length === 2)
|
|
273
|
+
break;
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
if (indentOf(next) >= content) {
|
|
277
|
+
item.push(stripIndent(next, content));
|
|
278
|
+
lazy = true;
|
|
279
|
+
blankRun = 0;
|
|
280
|
+
i++;
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
if (lazy && blankRun === 0 && !interrupts(next) && !listMarker(next)) {
|
|
284
|
+
item.push(next);
|
|
285
|
+
i++;
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
break;
|
|
289
|
+
}
|
|
290
|
+
while (item.length && blank(item[item.length - 1]))
|
|
291
|
+
item.pop();
|
|
292
|
+
items.push(item);
|
|
293
|
+
const following = i < lines.length ? listMarker(lines[i]) : null;
|
|
294
|
+
current = following && following.ordered === marker.ordered && following.char === marker.char && indentOf(lines[i]) < 4 ? following : null;
|
|
295
|
+
}
|
|
296
|
+
out.push(depth >= RICH_TEXT_MARKDOWN_MAX_DEPTH
|
|
297
|
+
? flatPara(items.flat())
|
|
298
|
+
: { kind: 'list', ordered: marker.ordered, items: items.map((item) => parseBlocks(item, refs, depth + 1)) });
|
|
299
|
+
continue;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
// Parágrafo (começo ou continuação preguiçosa).
|
|
303
|
+
if (para)
|
|
304
|
+
para.push(line);
|
|
305
|
+
else
|
|
306
|
+
para = [line];
|
|
307
|
+
i++;
|
|
308
|
+
}
|
|
309
|
+
flush();
|
|
310
|
+
return out;
|
|
311
|
+
}
|
|
312
|
+
/** Texto corrido (teto de aninhamento): as linhas viram um parágrafo literal. */
|
|
313
|
+
function flatPara(lines) {
|
|
314
|
+
return { kind: 'code', text: lines.join('\n') };
|
|
315
|
+
}
|
|
316
|
+
// ── inline ───────────────────────────────────────────────────────────────────────────────────────
|
|
317
|
+
const PUNCT = /[!-/:-@[-`{-~\p{P}\p{S}]/u;
|
|
318
|
+
const ASCII_PUNCT = /[!-/:-@[-`{-~]/;
|
|
319
|
+
const SPACE = /[\s ]/u;
|
|
320
|
+
const ENTITIES = {
|
|
321
|
+
amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', copy: '©', reg: '®', trade: '™', hellip: '…',
|
|
322
|
+
mdash: '—', ndash: '–', laquo: '«', raquo: '»', ldquo: '“', rdquo: '”', lsquo: '‘', rsquo: '’', middot: '·',
|
|
323
|
+
bull: '•', deg: '°', euro: '€', times: '×', divide: '÷', sect: '§', para: '¶', iexcl: '¡', iquest: '¿',
|
|
324
|
+
};
|
|
325
|
+
const ENTITY = /&(?:#[xX]([0-9a-fA-F]{1,6})|#([0-9]{1,7})|([A-Za-z][A-Za-z0-9]{1,31}));/y;
|
|
326
|
+
function entityAt(text, at) {
|
|
327
|
+
ENTITY.lastIndex = at;
|
|
328
|
+
const m = ENTITY.exec(text);
|
|
329
|
+
if (!m)
|
|
330
|
+
return null;
|
|
331
|
+
if (m[3]) {
|
|
332
|
+
const value = ENTITIES[m[3]];
|
|
333
|
+
return value === undefined ? null : { value, length: m[0].length };
|
|
334
|
+
}
|
|
335
|
+
const code = parseInt(m[1] ?? m[2], m[1] ? 16 : 10);
|
|
336
|
+
const valid = code > 0 && code <= 0x10ffff && !(code >= 0xd800 && code <= 0xdfff);
|
|
337
|
+
return { value: valid ? String.fromCodePoint(code) : '�', length: m[0].length };
|
|
338
|
+
}
|
|
339
|
+
function decodeEntities(text) {
|
|
340
|
+
if (!text.includes('&'))
|
|
341
|
+
return text;
|
|
342
|
+
let out = '';
|
|
343
|
+
for (let i = 0; i < text.length; i++) {
|
|
344
|
+
const e = text[i] === '&' ? entityAt(text, i) : null;
|
|
345
|
+
if (e) {
|
|
346
|
+
out += e.value;
|
|
347
|
+
i += e.length - 1;
|
|
348
|
+
}
|
|
349
|
+
else
|
|
350
|
+
out += text[i];
|
|
351
|
+
}
|
|
352
|
+
return out;
|
|
353
|
+
}
|
|
354
|
+
function unescapeBackslashes(text) {
|
|
355
|
+
return text.replace(/\\([!-/:-@[-`{-~])/g, '$1');
|
|
356
|
+
}
|
|
357
|
+
function isSpaceAt(text, i) {
|
|
358
|
+
return i < 0 || i >= text.length || SPACE.test(text[i]);
|
|
359
|
+
}
|
|
360
|
+
function isPunctAt(text, i) {
|
|
361
|
+
return i >= 0 && i < text.length && PUNCT.test(text[i]);
|
|
362
|
+
}
|
|
363
|
+
/** Endereço aceito do link (regra de protocolo do esquema; com variáveis, também o endereço com variável). */
|
|
364
|
+
function acceptHref(raw, ctx) {
|
|
365
|
+
const dest = decodeEntities(unescapeBackslashes(raw));
|
|
366
|
+
const plain = normalizeRichTextUrl(dest, ctx.schema);
|
|
367
|
+
if (ctx.schema.variables && (!plain || plain.includes(ctx.syntax.open))) {
|
|
368
|
+
const withVariable = normalizeRichTextVariableUrl(dest, ctx.schema, ctx.syntax);
|
|
369
|
+
if (withVariable)
|
|
370
|
+
return withVariable;
|
|
371
|
+
}
|
|
372
|
+
return plain;
|
|
373
|
+
}
|
|
374
|
+
/** Destino e título de um link em linha a partir de `(`; devolve o destino e onde termina, ou `null`. */
|
|
375
|
+
function inlineLinkTail(text, at) {
|
|
376
|
+
if (text[at] !== '(')
|
|
377
|
+
return null;
|
|
378
|
+
let i = at + 1;
|
|
379
|
+
const skip = () => {
|
|
380
|
+
let newlines = 0;
|
|
381
|
+
while (i < text.length && (text[i] === ' ' || text[i] === '\t' || text[i] === '\n')) {
|
|
382
|
+
if (text[i] === '\n' && ++newlines > 1)
|
|
383
|
+
return false;
|
|
384
|
+
i++;
|
|
385
|
+
}
|
|
386
|
+
return true;
|
|
387
|
+
};
|
|
388
|
+
if (!skip())
|
|
389
|
+
return null;
|
|
390
|
+
let dest = '';
|
|
391
|
+
if (text[i] === '<') {
|
|
392
|
+
i++;
|
|
393
|
+
while (i < text.length && text[i] !== '>') {
|
|
394
|
+
if (text[i] === '\n' || text[i] === '<')
|
|
395
|
+
return null;
|
|
396
|
+
if (text[i] === '\\' && ASCII_PUNCT.test(text[i + 1] ?? '')) {
|
|
397
|
+
dest += text[i] + text[i + 1];
|
|
398
|
+
i += 2;
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
dest += text[i++];
|
|
402
|
+
}
|
|
403
|
+
if (text[i] !== '>')
|
|
404
|
+
return null;
|
|
405
|
+
i++;
|
|
406
|
+
}
|
|
407
|
+
else {
|
|
408
|
+
let depth = 0;
|
|
409
|
+
while (i < text.length) {
|
|
410
|
+
const ch = text[i];
|
|
411
|
+
if (ch === '\\' && ASCII_PUNCT.test(text[i + 1] ?? '')) {
|
|
412
|
+
dest += ch + text[i + 1];
|
|
413
|
+
i += 2;
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
if (/[\s\u0000-\u001f]/.test(ch))
|
|
417
|
+
break;
|
|
418
|
+
if (ch === '(') {
|
|
419
|
+
if (++depth > 32)
|
|
420
|
+
return null;
|
|
421
|
+
}
|
|
422
|
+
else if (ch === ')') {
|
|
423
|
+
if (depth === 0)
|
|
424
|
+
break;
|
|
425
|
+
depth--;
|
|
426
|
+
}
|
|
427
|
+
dest += ch;
|
|
428
|
+
i++;
|
|
429
|
+
}
|
|
430
|
+
if (depth !== 0)
|
|
431
|
+
return null;
|
|
432
|
+
}
|
|
433
|
+
const beforeTitle = i;
|
|
434
|
+
if (!skip())
|
|
435
|
+
return null;
|
|
436
|
+
const quote = text[i];
|
|
437
|
+
if (i > beforeTitle && (quote === '"' || quote === "'" || quote === '(')) {
|
|
438
|
+
const close = quote === '(' ? ')' : quote;
|
|
439
|
+
i++;
|
|
440
|
+
while (i < text.length && text[i] !== close) {
|
|
441
|
+
if (text[i] === '\\')
|
|
442
|
+
i++;
|
|
443
|
+
i++;
|
|
444
|
+
}
|
|
445
|
+
if (text[i] !== close)
|
|
446
|
+
return null;
|
|
447
|
+
i++;
|
|
448
|
+
if (!skip())
|
|
449
|
+
return null;
|
|
450
|
+
}
|
|
451
|
+
if (text[i] !== ')')
|
|
452
|
+
return null;
|
|
453
|
+
return { dest, end: i + 1 };
|
|
454
|
+
}
|
|
455
|
+
/** Rótulo de referência `[...]` a partir de `at`; devolve o rótulo bruto e onde termina. */
|
|
456
|
+
function refTail(text, at) {
|
|
457
|
+
if (text[at] !== '[')
|
|
458
|
+
return null;
|
|
459
|
+
let i = at + 1;
|
|
460
|
+
let label = '';
|
|
461
|
+
while (i < text.length && text[i] !== ']') {
|
|
462
|
+
if (text[i] === '[')
|
|
463
|
+
return null;
|
|
464
|
+
if (text[i] === '\\')
|
|
465
|
+
label += text[i++];
|
|
466
|
+
label += text[i++];
|
|
467
|
+
if (label.length > 999)
|
|
468
|
+
return null;
|
|
469
|
+
}
|
|
470
|
+
if (text[i] !== ']')
|
|
471
|
+
return null;
|
|
472
|
+
return { label, end: i + 1 };
|
|
473
|
+
}
|
|
474
|
+
const AUTOLINK = /^<([A-Za-z][A-Za-z0-9+.-]{1,31}:[^\s<>]*)>/;
|
|
475
|
+
const EMAIL_AUTOLINK = /^<([A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*)>/;
|
|
476
|
+
/**
|
|
477
|
+
* Conteúdo inline → trechos do modelo. Um passo pela entrada; ênfase pela pilha de delimitadores (cada par aplica a
|
|
478
|
+
* marca aos nós entre eles, sem reorganizar a lista); links pela pilha de colchetes, com links dentro de link
|
|
479
|
+
* proibidos.
|
|
480
|
+
*/
|
|
481
|
+
function parseInline(source, ctx) {
|
|
482
|
+
const nodes = [];
|
|
483
|
+
let head = null;
|
|
484
|
+
let tail = null;
|
|
485
|
+
const brackets = [];
|
|
486
|
+
let text = '';
|
|
487
|
+
const flushText = () => {
|
|
488
|
+
if (text)
|
|
489
|
+
nodes.push({ text, marks: 0, href: null });
|
|
490
|
+
text = '';
|
|
491
|
+
};
|
|
492
|
+
const pushDelim = (node) => {
|
|
493
|
+
nodes.push(node);
|
|
494
|
+
const d = { node: nodes.length - 1, prev: tail, next: null };
|
|
495
|
+
if (tail)
|
|
496
|
+
tail.next = d;
|
|
497
|
+
else
|
|
498
|
+
head = d;
|
|
499
|
+
tail = d;
|
|
500
|
+
};
|
|
501
|
+
const removeDelim = (d) => {
|
|
502
|
+
if (d.prev)
|
|
503
|
+
d.prev.next = d.next;
|
|
504
|
+
else
|
|
505
|
+
head = d.next;
|
|
506
|
+
if (d.next)
|
|
507
|
+
d.next.prev = d.prev;
|
|
508
|
+
else
|
|
509
|
+
tail = d.prev;
|
|
510
|
+
};
|
|
511
|
+
// `<u>` com `underline: 'html'`: só abre se houver o fechamento depois.
|
|
512
|
+
let underlineDepth = 0;
|
|
513
|
+
const underlineClose = ctx.underline ? source.toLowerCase().lastIndexOf('</u>') : -1;
|
|
514
|
+
const processEmphasis = (bottom) => {
|
|
515
|
+
const openersBottom = new Map();
|
|
516
|
+
let current = bottom ? bottom.next : head;
|
|
517
|
+
while (current) {
|
|
518
|
+
const closer = nodes[current.node].delim;
|
|
519
|
+
if (!closer.canClose) {
|
|
520
|
+
current = current.next;
|
|
521
|
+
continue;
|
|
522
|
+
}
|
|
523
|
+
const key = `${closer.char}${closer.canOpen ? 1 : 0}${closer.orig % 3}`;
|
|
524
|
+
const floor = openersBottom.has(key) ? openersBottom.get(key) : bottom;
|
|
525
|
+
let opener = current.prev;
|
|
526
|
+
let found = null;
|
|
527
|
+
while (opener && opener !== floor && opener !== bottom) {
|
|
528
|
+
const o = nodes[opener.node].delim;
|
|
529
|
+
if (o.char === closer.char && o.canOpen) {
|
|
530
|
+
const odd = (o.canClose || closer.canOpen) && (o.orig + closer.orig) % 3 === 0 && !(o.orig % 3 === 0 && closer.orig % 3 === 0);
|
|
531
|
+
const tildeOk = closer.char !== '~' || (o.count >= 2 && closer.count >= 2);
|
|
532
|
+
if (!odd && tildeOk) {
|
|
533
|
+
found = opener;
|
|
534
|
+
break;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
opener = opener.prev;
|
|
538
|
+
}
|
|
539
|
+
if (!found) {
|
|
540
|
+
openersBottom.set(key, current.prev);
|
|
541
|
+
const next = current.next;
|
|
542
|
+
if (!closer.canOpen)
|
|
543
|
+
removeDelim(current);
|
|
544
|
+
current = next;
|
|
545
|
+
continue;
|
|
546
|
+
}
|
|
547
|
+
const o = nodes[found.node].delim;
|
|
548
|
+
let use;
|
|
549
|
+
let bit;
|
|
550
|
+
if (closer.char === '~') {
|
|
551
|
+
use = 2;
|
|
552
|
+
bit = RT_STRIKE;
|
|
553
|
+
}
|
|
554
|
+
else if (o.count >= 2 && closer.count >= 2) {
|
|
555
|
+
use = 2;
|
|
556
|
+
bit = RT_BOLD;
|
|
557
|
+
}
|
|
558
|
+
else {
|
|
559
|
+
use = 1;
|
|
560
|
+
bit = RT_ITALIC;
|
|
561
|
+
}
|
|
562
|
+
for (let k = found.node + 1; k < current.node; k++)
|
|
563
|
+
nodes[k].marks |= bit;
|
|
564
|
+
// Delimitadores entre o par saem da pilha.
|
|
565
|
+
let between = found.next;
|
|
566
|
+
while (between && between !== current) {
|
|
567
|
+
const next = between.next;
|
|
568
|
+
removeDelim(between);
|
|
569
|
+
between = next;
|
|
570
|
+
}
|
|
571
|
+
o.count -= use;
|
|
572
|
+
closer.count -= use;
|
|
573
|
+
nodes[found.node].text = o.char.repeat(o.count);
|
|
574
|
+
nodes[current.node].text = closer.char.repeat(closer.count);
|
|
575
|
+
if (o.count === 0)
|
|
576
|
+
removeDelim(found);
|
|
577
|
+
if (closer.count === 0) {
|
|
578
|
+
const next = current.next;
|
|
579
|
+
removeDelim(current);
|
|
580
|
+
current = next;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
// O que sobrou acima do fundo vira texto.
|
|
584
|
+
let rest = bottom ? bottom.next : head;
|
|
585
|
+
while (rest) {
|
|
586
|
+
const next = rest.next;
|
|
587
|
+
removeDelim(rest);
|
|
588
|
+
rest = next;
|
|
589
|
+
}
|
|
590
|
+
};
|
|
591
|
+
let i = 0;
|
|
592
|
+
const n = source.length;
|
|
593
|
+
while (i < n) {
|
|
594
|
+
const ch = source[i];
|
|
595
|
+
if (ch === '\\') {
|
|
596
|
+
const next = source[i + 1];
|
|
597
|
+
if (next === '\n') {
|
|
598
|
+
flushText();
|
|
599
|
+
nodes.push({ text: '\n', marks: 0, href: null });
|
|
600
|
+
i += 2;
|
|
601
|
+
while (i < n && (source[i] === ' ' || source[i] === '\t'))
|
|
602
|
+
i++;
|
|
603
|
+
continue;
|
|
604
|
+
}
|
|
605
|
+
if (next !== undefined && ASCII_PUNCT.test(next)) {
|
|
606
|
+
text += next;
|
|
607
|
+
i += 2;
|
|
608
|
+
continue;
|
|
609
|
+
}
|
|
610
|
+
text += ch;
|
|
611
|
+
i++;
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
if (ch === '\n') {
|
|
615
|
+
// Dois ou mais espaços antes da quebra: quebra de linha; senão, quebra suave (espaço).
|
|
616
|
+
const hard = / +$/.test(text);
|
|
617
|
+
text = text.replace(/[ \t]+$/, '');
|
|
618
|
+
if (hard) {
|
|
619
|
+
flushText();
|
|
620
|
+
nodes.push({ text: '\n', marks: 0, href: null });
|
|
621
|
+
}
|
|
622
|
+
else
|
|
623
|
+
text += ' ';
|
|
624
|
+
i++;
|
|
625
|
+
while (i < n && (source[i] === ' ' || source[i] === '\t'))
|
|
626
|
+
i++;
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
if (ch === '`') {
|
|
630
|
+
let run = 1;
|
|
631
|
+
while (source[i + run] === '`')
|
|
632
|
+
run++;
|
|
633
|
+
// Fechamento: a próxima sequência de crases com o mesmo tamanho.
|
|
634
|
+
let j = i + run;
|
|
635
|
+
let close = -1;
|
|
636
|
+
while (j < n) {
|
|
637
|
+
const at = source.indexOf('`', j);
|
|
638
|
+
if (at < 0)
|
|
639
|
+
break;
|
|
640
|
+
let len = 1;
|
|
641
|
+
while (source[at + len] === '`')
|
|
642
|
+
len++;
|
|
643
|
+
if (len === run) {
|
|
644
|
+
close = at;
|
|
645
|
+
break;
|
|
646
|
+
}
|
|
647
|
+
j = at + len;
|
|
648
|
+
}
|
|
649
|
+
if (close < 0) {
|
|
650
|
+
text += '`'.repeat(run);
|
|
651
|
+
i += run;
|
|
652
|
+
continue;
|
|
653
|
+
}
|
|
654
|
+
let code = source.slice(i + run, close).replace(/\n/g, ' ');
|
|
655
|
+
if (code.length >= 2 && code[0] === ' ' && code[code.length - 1] === ' ' && /[^ ]/.test(code))
|
|
656
|
+
code = code.slice(1, -1);
|
|
657
|
+
flushText();
|
|
658
|
+
nodes.push({ text: code, marks: 0, href: null, code: true });
|
|
659
|
+
i = close + run;
|
|
660
|
+
continue;
|
|
661
|
+
}
|
|
662
|
+
if (ch === '<') {
|
|
663
|
+
const rest = source.slice(i, i + 2100);
|
|
664
|
+
const auto = AUTOLINK.exec(rest) ?? EMAIL_AUTOLINK.exec(rest);
|
|
665
|
+
if (auto) {
|
|
666
|
+
const raw = auto === EMAIL_AUTOLINK.exec(rest) && !auto[1].includes(':') ? `mailto:${auto[1]}` : auto[1];
|
|
667
|
+
const href = acceptHref(raw, ctx);
|
|
668
|
+
if (href) {
|
|
669
|
+
flushText();
|
|
670
|
+
nodes.push({ text: decodeEntities(auto[1]), marks: 0, href });
|
|
671
|
+
i += auto[0].length;
|
|
672
|
+
continue;
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
if (ctx.underline) {
|
|
676
|
+
const lower = source.slice(i, i + 4).toLowerCase();
|
|
677
|
+
if (lower.startsWith('<u>') && i < underlineClose) {
|
|
678
|
+
flushText();
|
|
679
|
+
underlineDepth++;
|
|
680
|
+
nodes.push({ text: '', marks: -1, href: null });
|
|
681
|
+
i += 3;
|
|
682
|
+
continue;
|
|
683
|
+
}
|
|
684
|
+
if (lower === '</u>' && underlineDepth > 0) {
|
|
685
|
+
flushText();
|
|
686
|
+
underlineDepth--;
|
|
687
|
+
nodes.push({ text: '', marks: -2, href: null });
|
|
688
|
+
i += 4;
|
|
689
|
+
continue;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
text += ch;
|
|
693
|
+
i++;
|
|
694
|
+
continue;
|
|
695
|
+
}
|
|
696
|
+
if (ch === '&') {
|
|
697
|
+
const e = entityAt(source, i);
|
|
698
|
+
if (e) {
|
|
699
|
+
text += e.value;
|
|
700
|
+
i += e.length;
|
|
701
|
+
continue;
|
|
702
|
+
}
|
|
703
|
+
text += ch;
|
|
704
|
+
i++;
|
|
705
|
+
continue;
|
|
706
|
+
}
|
|
707
|
+
if (ch === '*' || ch === '_' || ch === '~') {
|
|
708
|
+
let run = 1;
|
|
709
|
+
while (source[i + run] === ch)
|
|
710
|
+
run++;
|
|
711
|
+
if (ch === '~' && run !== 2) {
|
|
712
|
+
text += ch.repeat(run);
|
|
713
|
+
i += run;
|
|
714
|
+
continue;
|
|
715
|
+
}
|
|
716
|
+
const beforeSpace = isSpaceAt(source, i - 1);
|
|
717
|
+
const afterSpace = isSpaceAt(source, i + run);
|
|
718
|
+
const beforePunct = isPunctAt(source, i - 1);
|
|
719
|
+
const afterPunct = isPunctAt(source, i + run);
|
|
720
|
+
const left = !afterSpace && (!afterPunct || beforeSpace || beforePunct);
|
|
721
|
+
const right = !beforeSpace && (!beforePunct || afterSpace || afterPunct);
|
|
722
|
+
const canOpen = ch === '_' ? left && (!right || beforePunct) : left;
|
|
723
|
+
const canClose = ch === '_' ? right && (!left || afterPunct) : right;
|
|
724
|
+
flushText();
|
|
725
|
+
pushDelim({ text: ch.repeat(run), marks: 0, href: null, delim: { char: ch, count: run, orig: run, canOpen, canClose } });
|
|
726
|
+
i += run;
|
|
727
|
+
continue;
|
|
728
|
+
}
|
|
729
|
+
if (ch === '[' || (ch === '!' && source[i + 1] === '[')) {
|
|
730
|
+
const image = ch === '!';
|
|
731
|
+
flushText();
|
|
732
|
+
nodes.push({ text: image ? '![' : '[', marks: 0, href: null, bracket: { image, active: true, source: i + (image ? 2 : 1), delimBottom: tail } });
|
|
733
|
+
brackets.push(nodes.length - 1);
|
|
734
|
+
i += image ? 2 : 1;
|
|
735
|
+
continue;
|
|
736
|
+
}
|
|
737
|
+
if (ch === ']') {
|
|
738
|
+
const openerIndex = brackets.length ? brackets[brackets.length - 1] : -1;
|
|
739
|
+
const opener = openerIndex >= 0 ? nodes[openerIndex].bracket : null;
|
|
740
|
+
if (!opener) {
|
|
741
|
+
text += ch;
|
|
742
|
+
i++;
|
|
743
|
+
continue;
|
|
744
|
+
}
|
|
745
|
+
if (!opener.active) {
|
|
746
|
+
brackets.pop();
|
|
747
|
+
text += ch;
|
|
748
|
+
i++;
|
|
749
|
+
continue;
|
|
750
|
+
}
|
|
751
|
+
// Rótulo de referência tem no máximo 999 caracteres (CommonMark): acima disso nem se recorta.
|
|
752
|
+
const labelText = i - opener.source <= 999 ? source.slice(opener.source, i) : '';
|
|
753
|
+
let dest = null;
|
|
754
|
+
let end = i + 1;
|
|
755
|
+
const inline = inlineLinkTail(source, i + 1);
|
|
756
|
+
if (inline) {
|
|
757
|
+
dest = inline.dest;
|
|
758
|
+
end = inline.end;
|
|
759
|
+
}
|
|
760
|
+
else {
|
|
761
|
+
const ref = refTail(source, i + 1);
|
|
762
|
+
const key = ref ? (ref.label.trim() ? ref.label : labelText) : labelText;
|
|
763
|
+
const found = key && ctx.refs.size ? ctx.refs.get(refLabel(unescapeBackslashes(key))) : undefined;
|
|
764
|
+
if (found) {
|
|
765
|
+
dest = found.href;
|
|
766
|
+
end = ref ? ref.end : i + 1;
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
const href = dest === null ? null : opener.image ? null : acceptHref(dest, ctx);
|
|
770
|
+
if (dest === null || (!opener.image && href === null)) {
|
|
771
|
+
// Não é link (ou endereço recusado): o colchete vira texto.
|
|
772
|
+
brackets.pop();
|
|
773
|
+
text += ch;
|
|
774
|
+
i++;
|
|
775
|
+
continue;
|
|
776
|
+
}
|
|
777
|
+
flushText();
|
|
778
|
+
processEmphasis(opener.delimBottom);
|
|
779
|
+
brackets.pop();
|
|
780
|
+
// Imagem sem a ferramenta (ou com endereço recusado): fica o texto do alt. Link: o endereço vai para os nós entre
|
|
781
|
+
// os colchetes.
|
|
782
|
+
nodes[openerIndex].text = '';
|
|
783
|
+
nodes[openerIndex].bracket = undefined;
|
|
784
|
+
const imageSrc = opener.image && ctx.schema.image && dest !== null ? normalizeRichTextImageUrl(decodeEntities(unescapeBackslashes(dest)), ctx.schema, !!ctx.schema.allowRelativeImages) : null;
|
|
785
|
+
if (imageSrc) {
|
|
786
|
+
const alt = nodes.slice(openerIndex + 1).map((n) => n.text).join('').replace(/\s+/g, ' ').trim().slice(0, 512);
|
|
787
|
+
nodes.length = openerIndex + 1;
|
|
788
|
+
nodes[openerIndex].atom = { kind: 'image', src: imageSrc, alt, decorative: !alt };
|
|
789
|
+
nodes[openerIndex].text = RT_ATOM_CHAR;
|
|
790
|
+
i = end;
|
|
791
|
+
continue;
|
|
792
|
+
}
|
|
793
|
+
if (!opener.image) {
|
|
794
|
+
for (let k = openerIndex + 1; k < nodes.length; k++)
|
|
795
|
+
if (nodes[k].href === null && !nodes[k].bracket)
|
|
796
|
+
nodes[k].href = href;
|
|
797
|
+
// Link dentro de link não existe: os colchetes de antes deixam de abrir link.
|
|
798
|
+
for (const b of brackets)
|
|
799
|
+
if (!nodes[b].bracket.image)
|
|
800
|
+
nodes[b].bracket.active = false;
|
|
801
|
+
}
|
|
802
|
+
i = end;
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
text += ch;
|
|
806
|
+
i++;
|
|
807
|
+
}
|
|
808
|
+
flushText();
|
|
809
|
+
processEmphasis(null);
|
|
810
|
+
// Nós → trechos, com o sublinhado por `<u>` e o esquema da instância.
|
|
811
|
+
const runs = [];
|
|
812
|
+
const allowed = ctx.schema.marks;
|
|
813
|
+
let under = 0;
|
|
814
|
+
for (const node of nodes) {
|
|
815
|
+
if (node.marks === -1) {
|
|
816
|
+
under++;
|
|
817
|
+
continue;
|
|
818
|
+
}
|
|
819
|
+
if (node.marks === -2) {
|
|
820
|
+
under = Math.max(0, under - 1);
|
|
821
|
+
continue;
|
|
822
|
+
}
|
|
823
|
+
if (!node.text)
|
|
824
|
+
continue;
|
|
825
|
+
if (node.atom) {
|
|
826
|
+
runs.push({ text: RT_ATOM_CHAR, marks: 0, href: null, atom: node.atom });
|
|
827
|
+
continue;
|
|
828
|
+
}
|
|
829
|
+
let marks = node.code ? RT_CODE : node.marks;
|
|
830
|
+
if (under)
|
|
831
|
+
marks |= RT_UNDERLINE;
|
|
832
|
+
if (node.code && under)
|
|
833
|
+
marks = RT_CODE;
|
|
834
|
+
marks &= allowed;
|
|
835
|
+
runs.push({ text: node.text, marks, href: ctx.schema.link ? node.href : null });
|
|
836
|
+
}
|
|
837
|
+
// Espaço no começo e no fim do bloco não conta (CommonMark).
|
|
838
|
+
return runs;
|
|
839
|
+
}
|
|
840
|
+
// ── documento ────────────────────────────────────────────────────────────────────────────────────
|
|
841
|
+
function toDoc(blocks, ctx) {
|
|
842
|
+
const out = [];
|
|
843
|
+
const { schema } = ctx;
|
|
844
|
+
const visit = (block, wrap) => {
|
|
845
|
+
switch (block.kind) {
|
|
846
|
+
case 'para':
|
|
847
|
+
out.push(rtBlock('paragraph', trimRuns(parseInline(block.text, ctx)), wrap));
|
|
848
|
+
return;
|
|
849
|
+
case 'heading': {
|
|
850
|
+
const level = richTextHeadingFor(block.level, schema);
|
|
851
|
+
const runs = trimRuns(parseInline(block.text, ctx));
|
|
852
|
+
out.push(level && wrap === 'none' ? rtBlock('heading', runs, 'none', level) : rtBlock('paragraph', runs, wrap));
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
855
|
+
case 'code':
|
|
856
|
+
if (schema.codeBlock)
|
|
857
|
+
out.push(rtBlock('code', [{ text: block.text, marks: 0, href: null }]));
|
|
858
|
+
else
|
|
859
|
+
out.push(rtBlock('paragraph', [{ text: block.text, marks: 0, href: null }], wrap));
|
|
860
|
+
return;
|
|
861
|
+
case 'quote': {
|
|
862
|
+
// Lista dentro da citação vira parágrafos citados (o modelo não aninha contêineres).
|
|
863
|
+
const inner = schema.quote ? 'quote' : wrap;
|
|
864
|
+
for (const child of block.children)
|
|
865
|
+
visit(child, inner);
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
case 'table': {
|
|
869
|
+
// Sem a ferramenta (ou dentro de lista/citação): as linhas ficam como texto.
|
|
870
|
+
if (!schema.table || wrap !== 'none') {
|
|
871
|
+
out.push(rtBlock('paragraph', trimRuns(parseInline(block.raw.map((line) => line.trim()).join('\n'), ctx)), wrap));
|
|
872
|
+
return;
|
|
873
|
+
}
|
|
874
|
+
// Cabeçalho todo vazio = tabela sem cabeçalho (a forma que a saída usa para ela).
|
|
875
|
+
const width = Math.min(RT_TABLE_MAX_COLS, block.head.length);
|
|
876
|
+
const noHeader = block.head.every((cell) => !cell);
|
|
877
|
+
const rows = (noHeader ? block.rows : [block.head, ...block.rows]).slice(0, RT_TABLE_MAX_ROWS);
|
|
878
|
+
if (!rows.length)
|
|
879
|
+
return;
|
|
880
|
+
const grid = rows.map((row) => Array.from({ length: width }, (_, c) => rtParagraph(trimRuns(parseInline(row[c] ?? '', ctx)))));
|
|
881
|
+
out.push(...rtTableBlocks(grid, !noHeader));
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
case 'list': {
|
|
885
|
+
const own = block.ordered ? (schema.orderedList ? 'ordered' : 'none') : schema.bulletList ? 'bullet' : 'none';
|
|
886
|
+
const inner = wrap === 'none' ? own : wrap;
|
|
887
|
+
for (const item of block.items) {
|
|
888
|
+
if (!item.length)
|
|
889
|
+
out.push(rtBlock('paragraph', [], inner));
|
|
890
|
+
for (const child of item)
|
|
891
|
+
visit(child, inner);
|
|
892
|
+
}
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
};
|
|
897
|
+
for (const block of blocks)
|
|
898
|
+
visit(block, 'none');
|
|
899
|
+
return out;
|
|
900
|
+
}
|
|
901
|
+
/** O espaço das bordas do bloco já saiu na estrutura (antes das entidades: o espaço escrito como ` ` fica). */
|
|
902
|
+
function trimRuns(runs) {
|
|
903
|
+
return runs;
|
|
904
|
+
}
|
|
905
|
+
/**
|
|
906
|
+
* Markdown → documento, pelo esquema da instância: o que o esquema não tem é simplificado (marca e link somem e o
|
|
907
|
+
* texto fica; título fora dos níveis cai no nível aceito mais próximo; lista e citação sem a ferramenta viram
|
|
908
|
+
* parágrafos). Com variáveis no esquema, o texto que casa com a sintaxe vira átomo (fora de código).
|
|
909
|
+
*/
|
|
910
|
+
export function richTextFromMarkdown(source, schema, options = {}) {
|
|
911
|
+
if (typeof source !== 'string' || !source)
|
|
912
|
+
return rtEmptyDoc();
|
|
913
|
+
if (source.length > RICH_TEXT_MARKDOWN_MAX_LENGTH)
|
|
914
|
+
return rtTextToDoc(source.slice(0, RICH_TEXT_MARKDOWN_MAX_LENGTH));
|
|
915
|
+
const syntax = options.variableSyntax ?? schema.variableSyntax ?? RICH_TEXT_DEFAULT_VARIABLE_SYNTAX;
|
|
916
|
+
const lines = source.replace(/\r\n?/g, '\n').replace(/\u0000/g, '�').split('\n');
|
|
917
|
+
const refs = new Map();
|
|
918
|
+
const blocks = parseBlocks(lines, refs, 0);
|
|
919
|
+
const ctx = { schema, refs, underline: options.underline === 'html' && !!(schema.marks & RT_UNDERLINE), syntax };
|
|
920
|
+
const doc = toDoc(blocks, ctx);
|
|
921
|
+
if (!doc.length)
|
|
922
|
+
return rtEmptyDoc();
|
|
923
|
+
return schema.variables ? rtAtomizeDoc(doc, syntax) : doc;
|
|
924
|
+
}
|
|
925
|
+
// ── saída ────────────────────────────────────────────────────────────────────────────────────────
|
|
926
|
+
/** Marcas que viram delimitador, de fora para dentro. */
|
|
927
|
+
const MD_MARKS = [
|
|
928
|
+
{ bit: RT_BOLD, open: '**', close: '**' },
|
|
929
|
+
{ bit: RT_ITALIC, open: '_', close: '_' },
|
|
930
|
+
{ bit: RT_STRIKE, open: '~~', close: '~~' },
|
|
931
|
+
{ bit: RT_UNDERLINE, open: '<u>', close: '</u>' },
|
|
932
|
+
];
|
|
933
|
+
/** Escape do texto comum: só o que mudaria o sentido. */
|
|
934
|
+
function escapeInline(text) {
|
|
935
|
+
let out = '';
|
|
936
|
+
for (let i = 0; i < text.length; i++) {
|
|
937
|
+
const ch = text[i];
|
|
938
|
+
if (ch === '\\' || ch === '`' || ch === '*' || ch === '_' || ch === '[' || ch === ']' || ch === '<' || ch === '~')
|
|
939
|
+
out += `\\${ch}`;
|
|
940
|
+
else if (ch === '&' && entityAt(text, i))
|
|
941
|
+
out += '\\&';
|
|
942
|
+
else if (ch === '!' && text[i + 1] === '[')
|
|
943
|
+
out += '\\!';
|
|
944
|
+
else
|
|
945
|
+
out += ch;
|
|
946
|
+
}
|
|
947
|
+
return out;
|
|
948
|
+
}
|
|
949
|
+
/** Escape de começo de linha (título, lista, citação, linha de Setext, código recuado). */
|
|
950
|
+
function escapeLineStart(line) {
|
|
951
|
+
let out = line.replace(/^[ \t]+/, (m) => m.replace(/ /g, ' ').replace(/\t/g, '	'));
|
|
952
|
+
if (/^#{1,6}(?:[ \t]|$)/.test(out))
|
|
953
|
+
out = `\\${out}`;
|
|
954
|
+
else if (/^[-+](?:[ \t]|$)/.test(out))
|
|
955
|
+
out = `\\${out}`;
|
|
956
|
+
else if (/^>/.test(out))
|
|
957
|
+
out = `\\${out}`;
|
|
958
|
+
else if (/^=+[ \t]*$/.test(out) || /^-+[ \t]*$/.test(out))
|
|
959
|
+
out = `\\${out}`;
|
|
960
|
+
else {
|
|
961
|
+
const ordered = /^(\d{1,9})([.)])(?=[ \t]|$)/.exec(out);
|
|
962
|
+
if (ordered)
|
|
963
|
+
out = `${ordered[1]}\\${ordered[2]}${out.slice(ordered[0].length)}`;
|
|
964
|
+
}
|
|
965
|
+
return out.replace(/[ \t]+$/, (m) => m.replace(/ /g, ' ').replace(/\t/g, '	'));
|
|
966
|
+
}
|
|
967
|
+
function codeSpan(text) {
|
|
968
|
+
let longest = 0;
|
|
969
|
+
for (const m of text.matchAll(/`+/g))
|
|
970
|
+
longest = Math.max(longest, m[0].length);
|
|
971
|
+
const fence = '`'.repeat(longest + 1);
|
|
972
|
+
const pad = text.startsWith('`') || text.endsWith('`') || (text.startsWith(' ') && text.endsWith(' ') && /[^ ]/.test(text)) ? ' ' : '';
|
|
973
|
+
return `${fence}${pad}${text}${pad}${fence}`;
|
|
974
|
+
}
|
|
975
|
+
function linkDest(href) {
|
|
976
|
+
if (/[\s<>()]/.test(href) || !href)
|
|
977
|
+
return `<${href.replace(/[<>\\]/g, (c) => `\\${c}`)}>`;
|
|
978
|
+
return href.replace(/\\/g, '\\\\');
|
|
979
|
+
}
|
|
980
|
+
/** Conteúdo inline do bloco em Markdown; quebras de linha separam as linhas devolvidas. */
|
|
981
|
+
function inlineMarkdown(runs, options) {
|
|
982
|
+
const syntax = options.variableSyntax ?? RICH_TEXT_DEFAULT_VARIABLE_SYNTAX;
|
|
983
|
+
const html = options.underline === 'html';
|
|
984
|
+
const pieces = [];
|
|
985
|
+
const stack = [];
|
|
986
|
+
let link = null;
|
|
987
|
+
const closeTo = (keep) => {
|
|
988
|
+
while (stack.length > keep) {
|
|
989
|
+
const bit = stack.pop();
|
|
990
|
+
pieces.push({ kind: 'close', value: MD_MARKS.find((m) => m.bit === bit).close });
|
|
991
|
+
}
|
|
992
|
+
};
|
|
993
|
+
const closeLink = () => {
|
|
994
|
+
if (link === null)
|
|
995
|
+
return;
|
|
996
|
+
closeTo(0);
|
|
997
|
+
pieces.push({ kind: 'close', value: `](${linkDest(link)})` });
|
|
998
|
+
link = null;
|
|
999
|
+
};
|
|
1000
|
+
for (const run of runs) {
|
|
1001
|
+
if (run.href !== link) {
|
|
1002
|
+
closeLink();
|
|
1003
|
+
if (run.href !== null) {
|
|
1004
|
+
pieces.push({ kind: 'open', value: '[' });
|
|
1005
|
+
link = run.href;
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
let marks = run.marks & (RT_BOLD | RT_ITALIC | RT_STRIKE | (html ? RT_UNDERLINE : 0));
|
|
1009
|
+
// Mantém o prefixo comum da pilha; fecha o resto e abre o que falta, na ordem fixa.
|
|
1010
|
+
let keep = 0;
|
|
1011
|
+
while (keep < stack.length && marks & stack[keep])
|
|
1012
|
+
keep++;
|
|
1013
|
+
closeTo(keep);
|
|
1014
|
+
for (const mark of MD_MARKS) {
|
|
1015
|
+
if (marks & mark.bit && !stack.includes(mark.bit)) {
|
|
1016
|
+
stack.push(mark.bit);
|
|
1017
|
+
pieces.push({ kind: 'open', value: mark.open });
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
marks = 0;
|
|
1021
|
+
if (run.atom?.kind === 'image') {
|
|
1022
|
+
if (!run.atom.pending)
|
|
1023
|
+
pieces.push({ kind: 'text', value: `})`, raw: 'x' });
|
|
1024
|
+
continue;
|
|
1025
|
+
}
|
|
1026
|
+
if (run.atom) {
|
|
1027
|
+
const literal = run.atom.kind === 'variable' ? rtAtomText(run.atom, syntax) : escapeInline(rtAtomText(run.atom, syntax));
|
|
1028
|
+
pieces.push({ kind: 'text', value: literal, raw: 'x' });
|
|
1029
|
+
continue;
|
|
1030
|
+
}
|
|
1031
|
+
if (run.marks & RT_CODE) {
|
|
1032
|
+
pieces.push({ kind: 'text', value: codeSpan(run.text), raw: 'x' });
|
|
1033
|
+
continue;
|
|
1034
|
+
}
|
|
1035
|
+
const parts = run.text.split('\n');
|
|
1036
|
+
parts.forEach((part, k) => {
|
|
1037
|
+
if (k > 0)
|
|
1038
|
+
pieces.push({ kind: 'break' });
|
|
1039
|
+
if (part)
|
|
1040
|
+
pieces.push({ kind: 'text', value: escapeInline(part).replace(/ /g, ' '), raw: part });
|
|
1041
|
+
});
|
|
1042
|
+
}
|
|
1043
|
+
closeLink();
|
|
1044
|
+
closeTo(0);
|
|
1045
|
+
// Delimitador encostado em espaço não abre nem fecha: o espaço da borda vai como entidade (continua marcado).
|
|
1046
|
+
for (let k = 0; k < pieces.length; k++) {
|
|
1047
|
+
const piece = pieces[k];
|
|
1048
|
+
if (piece.kind !== 'text')
|
|
1049
|
+
continue;
|
|
1050
|
+
const prev = pieces[k - 1];
|
|
1051
|
+
const next = pieces[k + 1];
|
|
1052
|
+
if (prev?.kind === 'open' && prev.value !== '[' && /^[ \t]/.test(piece.value))
|
|
1053
|
+
piece.value = piece.value.replace(/^[ \t]/, (c) => (c === ' ' ? ' ' : '	'));
|
|
1054
|
+
if (next?.kind === 'close' && !next.value.startsWith(']') && /[ \t]$/.test(piece.value))
|
|
1055
|
+
piece.value = piece.value.replace(/[ \t]$/, (c) => (c === ' ' ? ' ' : '	'));
|
|
1056
|
+
}
|
|
1057
|
+
// Itálico dentro de palavra: `_` não abre entre letras; usa `*`.
|
|
1058
|
+
for (let k = 0; k < pieces.length; k++) {
|
|
1059
|
+
const piece = pieces[k];
|
|
1060
|
+
if ((piece.kind !== 'open' && piece.kind !== 'close') || piece.value !== '_')
|
|
1061
|
+
continue;
|
|
1062
|
+
// Só o lado de fora importa: antes da abertura e depois do fechamento do par.
|
|
1063
|
+
const partnerIndex = findPartner(pieces, k);
|
|
1064
|
+
const outside = piece.kind === 'open' ? textEdge(pieces, k, -1) : textEdge(pieces, k, 1);
|
|
1065
|
+
const other = partnerIndex < 0 ? ' ' : piece.kind === 'open' ? textEdge(pieces, partnerIndex, 1) : textEdge(pieces, partnerIndex, -1);
|
|
1066
|
+
if (/[\p{L}\p{N}]/u.test(outside) || /[\p{L}\p{N}]/u.test(other)) {
|
|
1067
|
+
piece.value = '*';
|
|
1068
|
+
// O par correspondente troca junto.
|
|
1069
|
+
const partner = findPartner(pieces, k);
|
|
1070
|
+
if (partner >= 0)
|
|
1071
|
+
pieces[partner].value = '*';
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
const lines = [''];
|
|
1075
|
+
for (const piece of pieces) {
|
|
1076
|
+
if (piece.kind === 'break')
|
|
1077
|
+
lines.push('');
|
|
1078
|
+
else
|
|
1079
|
+
lines[lines.length - 1] += piece.value;
|
|
1080
|
+
}
|
|
1081
|
+
return lines;
|
|
1082
|
+
}
|
|
1083
|
+
/** Caractere de texto vizinho da peça `k` na direção dada (pula delimitadores). */
|
|
1084
|
+
function textEdge(pieces, k, dir) {
|
|
1085
|
+
for (let j = k + dir; j >= 0 && j < pieces.length; j += dir) {
|
|
1086
|
+
const p = pieces[j];
|
|
1087
|
+
if (p.kind === 'break')
|
|
1088
|
+
return ' ';
|
|
1089
|
+
if (p.kind === 'text')
|
|
1090
|
+
return dir === 1 ? p.value[0] ?? ' ' : p.value[p.value.length - 1] ?? ' ';
|
|
1091
|
+
if (p.value === '[' || p.value.startsWith(']'))
|
|
1092
|
+
return ' ';
|
|
1093
|
+
}
|
|
1094
|
+
return ' ';
|
|
1095
|
+
}
|
|
1096
|
+
/** Índice do delimitador que fecha (ou abre) o da peça `k`. */
|
|
1097
|
+
function findPartner(pieces, k) {
|
|
1098
|
+
const piece = pieces[k];
|
|
1099
|
+
let depth = 0;
|
|
1100
|
+
if (piece.kind === 'open') {
|
|
1101
|
+
for (let j = k + 1; j < pieces.length; j++) {
|
|
1102
|
+
const p = pieces[j];
|
|
1103
|
+
if (p.kind === 'open' && p.value === '_')
|
|
1104
|
+
depth++;
|
|
1105
|
+
else if (p.kind === 'close' && p.value === '_') {
|
|
1106
|
+
if (depth === 0)
|
|
1107
|
+
return j;
|
|
1108
|
+
depth--;
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
else {
|
|
1113
|
+
for (let j = k - 1; j >= 0; j--) {
|
|
1114
|
+
const p = pieces[j];
|
|
1115
|
+
if (p.kind === 'close' && p.value === '_')
|
|
1116
|
+
depth++;
|
|
1117
|
+
else if (p.kind === 'open' && p.value === '_') {
|
|
1118
|
+
if (depth === 0)
|
|
1119
|
+
return j;
|
|
1120
|
+
depth--;
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
return -1;
|
|
1125
|
+
}
|
|
1126
|
+
/** Linhas do conteúdo inline com o escape de começo de linha e a quebra por barra invertida. */
|
|
1127
|
+
function blockLines(runs, options) {
|
|
1128
|
+
const lines = inlineMarkdown(runs, options).map(escapeLineStart);
|
|
1129
|
+
return lines.map((line, k) => (k < lines.length - 1 ? `${line}\\` : line));
|
|
1130
|
+
}
|
|
1131
|
+
function fenceFor(text) {
|
|
1132
|
+
let longest = 0;
|
|
1133
|
+
for (const m of text.matchAll(/`{3,}/g))
|
|
1134
|
+
longest = Math.max(longest, m[0].length);
|
|
1135
|
+
return '`'.repeat(Math.max(3, longest + 1));
|
|
1136
|
+
}
|
|
1137
|
+
/**
|
|
1138
|
+
* Documento → Markdown normalizado: parágrafos separados por linha em branco, `#` nos títulos, `**`/`_`/`~~`, crases
|
|
1139
|
+
* suficientes no código, `- ` e `N. ` com a numeração real, `> ` na citação e cerca de crases no bloco de código. A
|
|
1140
|
+
* variável sai pela sintaxe, sem escape; a menção, como `@rótulo`. Parágrafo vazio não tem forma em Markdown e não sai.
|
|
1141
|
+
*/
|
|
1142
|
+
export function richTextToMarkdown(doc, options = {}) {
|
|
1143
|
+
const out = [];
|
|
1144
|
+
let prevWrap = null;
|
|
1145
|
+
let counter = 0;
|
|
1146
|
+
for (let index = 0; index < doc.length; index++) {
|
|
1147
|
+
const block = doc[index];
|
|
1148
|
+
if (block.cell) {
|
|
1149
|
+
const table = rtTableBounds(doc, index);
|
|
1150
|
+
if (out.length)
|
|
1151
|
+
out.push('');
|
|
1152
|
+
out.push(...tableMarkdown(doc.slice(table.start, table.end), table.cols, table.header, options));
|
|
1153
|
+
index = table.end - 1;
|
|
1154
|
+
prevWrap = null;
|
|
1155
|
+
continue;
|
|
1156
|
+
}
|
|
1157
|
+
const empty = !block.runs.length;
|
|
1158
|
+
if (block.type === 'code') {
|
|
1159
|
+
const text = block.runs.map((r) => r.text).join('');
|
|
1160
|
+
const fence = fenceFor(text);
|
|
1161
|
+
if (out.length)
|
|
1162
|
+
out.push('');
|
|
1163
|
+
out.push(fence, ...(text ? text.split('\n') : []), fence);
|
|
1164
|
+
prevWrap = null;
|
|
1165
|
+
continue;
|
|
1166
|
+
}
|
|
1167
|
+
if (block.type === 'heading') {
|
|
1168
|
+
const line = inlineMarkdown(block.runs, options).join(' ').replace(/^[ \t]+|[ \t]+$/g, '');
|
|
1169
|
+
if (out.length)
|
|
1170
|
+
out.push('');
|
|
1171
|
+
out.push(`${'#'.repeat(block.level)} ${line}`.trimEnd());
|
|
1172
|
+
prevWrap = null;
|
|
1173
|
+
continue;
|
|
1174
|
+
}
|
|
1175
|
+
const wrap = block.wrap;
|
|
1176
|
+
if (empty && wrap !== 'bullet' && wrap !== 'ordered')
|
|
1177
|
+
continue;
|
|
1178
|
+
const lines = empty ? [''] : blockLines(block.runs, options);
|
|
1179
|
+
if (wrap === 'bullet' || wrap === 'ordered') {
|
|
1180
|
+
if (prevWrap !== wrap) {
|
|
1181
|
+
counter = 0;
|
|
1182
|
+
if (out.length)
|
|
1183
|
+
out.push('');
|
|
1184
|
+
}
|
|
1185
|
+
counter++;
|
|
1186
|
+
const marker = wrap === 'bullet' ? '- ' : `${counter}. `;
|
|
1187
|
+
const pad = ' '.repeat(marker.length);
|
|
1188
|
+
lines.forEach((line, k) => out.push(k === 0 ? `${marker}${line}`.trimEnd() : `${pad}${line}`));
|
|
1189
|
+
}
|
|
1190
|
+
else if (wrap === 'quote') {
|
|
1191
|
+
if (out.length)
|
|
1192
|
+
out.push(prevWrap === 'quote' ? '>' : '');
|
|
1193
|
+
for (const line of lines)
|
|
1194
|
+
out.push(line ? `> ${line}` : '>');
|
|
1195
|
+
}
|
|
1196
|
+
else {
|
|
1197
|
+
if (out.length)
|
|
1198
|
+
out.push('');
|
|
1199
|
+
out.push(...lines);
|
|
1200
|
+
}
|
|
1201
|
+
prevWrap = wrap;
|
|
1202
|
+
}
|
|
1203
|
+
return out.length ? `${out.join('\n')}\n` : '';
|
|
1204
|
+
}
|
|
1205
|
+
/**
|
|
1206
|
+
* Tabela em Markdown. `pipe`: cabeçalho (vazio quando a tabela não tem), linha de alinhamento e corpo; `|` do conteúdo
|
|
1207
|
+
* sai como `\|`; a quebra de linha dentro da célula vira espaço (a tabela de barras não tem quebra). `text`: uma linha
|
|
1208
|
+
* por linha da tabela, células separadas por ` | `.
|
|
1209
|
+
*/
|
|
1210
|
+
function tableMarkdown(cells, cols, header, options) {
|
|
1211
|
+
const rows = [];
|
|
1212
|
+
for (let i = 0; i < cells.length; i += cols) {
|
|
1213
|
+
rows.push(cells.slice(i, i + cols).map((cell) => inlineMarkdown(cell.runs, options).join(' ').replace(/^[ \t]+|[ \t]+$/g, '')));
|
|
1214
|
+
}
|
|
1215
|
+
if (options.table === 'text') {
|
|
1216
|
+
const lines = rows.map((row) => escapeLineStart(row.join(' | ')));
|
|
1217
|
+
return lines.map((line, k) => (k < lines.length - 1 ? `${line}\\` : line));
|
|
1218
|
+
}
|
|
1219
|
+
const line = (row) => `| ${row.map((cell) => cell.replace(/\|/g, '\\|')).join(' | ')} |`;
|
|
1220
|
+
const head = header ? rows[0] : rows[0].map(() => '');
|
|
1221
|
+
const body = header ? rows.slice(1) : rows;
|
|
1222
|
+
return [line(head), line(head.map(() => '---')), ...body.map(line)];
|
|
1223
|
+
}
|
|
1224
|
+
/** O texto parece Markdown (colagem): um marcador de bloco no começo de linha, ou um link ou uma ênfase completos. */
|
|
1225
|
+
export function richTextLooksLikeMarkdown(text) {
|
|
1226
|
+
if (typeof text !== 'string' || !text)
|
|
1227
|
+
return false;
|
|
1228
|
+
if (/^ {0,3}(?:#{1,6} |[-*+] |\d{1,9}[.)] |> |```|~~~)/m.test(text))
|
|
1229
|
+
return true;
|
|
1230
|
+
return /\[[^\]\n]+\]\([^)\s]+\)|\*\*[^*\n]+\*\*|__[^_\n]+__|`[^`\n]+`|~~[^~\n]+~~/.test(text);
|
|
1231
|
+
}
|
|
1232
|
+
/**
|
|
1233
|
+
* Texto puro direto do valor guardado (HTML ou Markdown), para o servidor montar o texto alternativo. O Markdown não
|
|
1234
|
+
* usa DOM; o HTML usa o `parse` dado (ou o `DOMParser` do navegador).
|
|
1235
|
+
*/
|
|
1236
|
+
export function richTextPlainTextFrom(value, format, options = {}) {
|
|
1237
|
+
if (typeof value !== 'string' || !value)
|
|
1238
|
+
return '';
|
|
1239
|
+
const schema = options.schema ?? RICH_TEXT_EXTENDED_SCHEMA;
|
|
1240
|
+
const doc = format === 'markdown'
|
|
1241
|
+
? richTextFromMarkdown(value, schema, { underline: options.underline, variableSyntax: options.variableSyntax })
|
|
1242
|
+
: richTextParseHtml(value, schema, options.parse);
|
|
1243
|
+
return richTextToPlainText(doc, options);
|
|
1244
|
+
}
|
|
1245
|
+
//# sourceMappingURL=rich-text-markdown.js.map
|