@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.
Files changed (254) hide show
  1. package/LICENSE +56 -56
  2. package/MIGRATION.md +831 -0
  3. package/README.md +8 -0
  4. package/dist/assignee.js +1 -1
  5. package/dist/assignee.js.map +1 -1
  6. package/dist/attachment.js +31 -2
  7. package/dist/attachment.js.map +1 -1
  8. package/dist/back-stack.d.ts +32 -0
  9. package/dist/back-stack.js +166 -0
  10. package/dist/back-stack.js.map +1 -0
  11. package/dist/bottom-sheet-gesture.d.ts +22 -0
  12. package/dist/bottom-sheet-gesture.js +58 -0
  13. package/dist/bottom-sheet-gesture.js.map +1 -0
  14. package/dist/calendar-display.d.ts +60 -0
  15. package/dist/calendar-display.js +132 -0
  16. package/dist/calendar-display.js.map +1 -0
  17. package/dist/calendar-external.d.ts +30 -0
  18. package/dist/calendar-external.js +129 -0
  19. package/dist/calendar-external.js.map +1 -0
  20. package/dist/calendar-grid-nav.d.ts +52 -0
  21. package/dist/calendar-grid-nav.js +91 -0
  22. package/dist/calendar-grid-nav.js.map +1 -0
  23. package/dist/calendar-hit.d.ts +33 -0
  24. package/dist/calendar-hit.js +57 -0
  25. package/dist/calendar-hit.js.map +1 -0
  26. package/dist/calendar-index.d.ts +20 -0
  27. package/dist/calendar-index.js +98 -0
  28. package/dist/calendar-index.js.map +1 -0
  29. package/dist/calendar-interaction.d.ts +83 -0
  30. package/dist/calendar-interaction.js +136 -0
  31. package/dist/calendar-interaction.js.map +1 -0
  32. package/dist/calendar-layout.d.ts +275 -0
  33. package/dist/calendar-layout.js +546 -0
  34. package/dist/calendar-layout.js.map +1 -0
  35. package/dist/calendar-now.d.ts +64 -0
  36. package/dist/calendar-now.js +122 -0
  37. package/dist/calendar-now.js.map +1 -0
  38. package/dist/calendar-pointer.d.ts +90 -0
  39. package/dist/calendar-pointer.js +357 -0
  40. package/dist/calendar-pointer.js.map +1 -0
  41. package/dist/calendar-rules.d.ts +139 -0
  42. package/dist/calendar-rules.js +265 -0
  43. package/dist/calendar-rules.js.map +1 -0
  44. package/dist/calendar-series.d.ts +27 -0
  45. package/dist/calendar-series.js +150 -0
  46. package/dist/calendar-series.js.map +1 -0
  47. package/dist/calendar-timeline.d.ts +75 -0
  48. package/dist/calendar-timeline.js +141 -0
  49. package/dist/calendar-timeline.js.map +1 -0
  50. package/dist/calendar-zone.d.ts +101 -0
  51. package/dist/calendar-zone.js +319 -0
  52. package/dist/calendar-zone.js.map +1 -0
  53. package/dist/camera-capture.d.ts +101 -0
  54. package/dist/camera-capture.js +206 -0
  55. package/dist/camera-capture.js.map +1 -0
  56. package/dist/data-grid-clipboard.d.ts +85 -0
  57. package/dist/data-grid-clipboard.js +223 -0
  58. package/dist/data-grid-clipboard.js.map +1 -0
  59. package/dist/data-grid-cursor.d.ts +165 -0
  60. package/dist/data-grid-cursor.js +219 -0
  61. package/dist/data-grid-cursor.js.map +1 -0
  62. package/dist/data-grid-export.d.ts +6 -1
  63. package/dist/data-grid-export.js +10 -18
  64. package/dist/data-grid-export.js.map +1 -1
  65. package/dist/data-grid-measure.d.ts +1 -1
  66. package/dist/data-grid-measure.js +2 -1
  67. package/dist/data-grid-measure.js.map +1 -1
  68. package/dist/data-grid.d.ts +7 -0
  69. package/dist/data-grid.js.map +1 -1
  70. package/dist/download.d.ts +15 -0
  71. package/dist/download.js +39 -0
  72. package/dist/download.js.map +1 -0
  73. package/dist/drag-drop.js +5 -3
  74. package/dist/drag-drop.js.map +1 -1
  75. package/dist/event-calendar-edit.d.ts +37 -5
  76. package/dist/event-calendar-edit.js +144 -13
  77. package/dist/event-calendar-edit.js.map +1 -1
  78. package/dist/event-calendar.d.ts +130 -11
  79. package/dist/event-calendar.js +195 -29
  80. package/dist/event-calendar.js.map +1 -1
  81. package/dist/file-upload-edit.d.ts +43 -0
  82. package/dist/file-upload-edit.js +64 -0
  83. package/dist/file-upload-edit.js.map +1 -0
  84. package/dist/file-upload-entries.d.ts +84 -0
  85. package/dist/file-upload-entries.js +214 -0
  86. package/dist/file-upload-entries.js.map +1 -0
  87. package/dist/file-upload.d.ts +74 -5
  88. package/dist/file-upload.js +165 -41
  89. package/dist/file-upload.js.map +1 -1
  90. package/dist/focus.d.ts +11 -0
  91. package/dist/focus.js +80 -4
  92. package/dist/focus.js.map +1 -1
  93. package/dist/gallery.d.ts +15 -4
  94. package/dist/gallery.js +28 -7
  95. package/dist/gallery.js.map +1 -1
  96. package/dist/gesture.d.ts +90 -0
  97. package/dist/gesture.js +165 -0
  98. package/dist/gesture.js.map +1 -0
  99. package/dist/graph-centrality.d.ts +36 -0
  100. package/dist/graph-centrality.js +160 -0
  101. package/dist/graph-centrality.js.map +1 -0
  102. package/dist/graph-components.d.ts +49 -0
  103. package/dist/graph-components.js +344 -0
  104. package/dist/graph-components.js.map +1 -0
  105. package/dist/graph-core.d.ts +124 -0
  106. package/dist/graph-core.js +275 -0
  107. package/dist/graph-core.js.map +1 -0
  108. package/dist/graph-order.d.ts +27 -0
  109. package/dist/graph-order.js +105 -0
  110. package/dist/graph-order.js.map +1 -0
  111. package/dist/graph-paths.d.ts +39 -0
  112. package/dist/graph-paths.js +105 -0
  113. package/dist/graph-paths.js.map +1 -0
  114. package/dist/graph-traverse.d.ts +89 -0
  115. package/dist/graph-traverse.js +164 -0
  116. package/dist/graph-traverse.js.map +1 -0
  117. package/dist/graph.d.ts +30 -0
  118. package/dist/graph.js +31 -0
  119. package/dist/graph.js.map +1 -0
  120. package/dist/icalendar.d.ts +33 -5
  121. package/dist/icalendar.js +269 -9
  122. package/dist/icalendar.js.map +1 -1
  123. package/dist/image-crop-io.d.ts +5 -1
  124. package/dist/image-crop-io.js +18 -5
  125. package/dist/image-crop-io.js.map +1 -1
  126. package/dist/image-crop.d.ts +84 -0
  127. package/dist/image-crop.js +131 -0
  128. package/dist/image-crop.js.map +1 -1
  129. package/dist/incident.js +2 -2
  130. package/dist/index.d.ts +32 -0
  131. package/dist/index.js +32 -0
  132. package/dist/index.js.map +1 -1
  133. package/dist/messages-data-grid.d.ts +42 -7
  134. package/dist/messages-data-grid.js +51 -0
  135. package/dist/messages-data-grid.js.map +1 -1
  136. package/dist/messages-en.js +11 -0
  137. package/dist/messages-en.js.map +1 -1
  138. package/dist/messages-es.js +11 -0
  139. package/dist/messages-es.js.map +1 -1
  140. package/dist/messages-event-calendar-pro.d.ts +105 -0
  141. package/dist/messages-event-calendar-pro.js +273 -0
  142. package/dist/messages-event-calendar-pro.js.map +1 -0
  143. package/dist/messages-resumable-upload.d.ts +106 -0
  144. package/dist/messages-resumable-upload.js +256 -0
  145. package/dist/messages-resumable-upload.js.map +1 -0
  146. package/dist/messages-rich-text.d.ts +120 -0
  147. package/dist/messages-rich-text.js +235 -0
  148. package/dist/messages-rich-text.js.map +1 -0
  149. package/dist/messages-secret.d.ts +32 -0
  150. package/dist/messages-secret.js +62 -0
  151. package/dist/messages-secret.js.map +1 -0
  152. package/dist/messages.d.ts +14 -0
  153. package/dist/messages.js +11 -0
  154. package/dist/messages.js.map +1 -1
  155. package/dist/mobile.d.ts +25 -0
  156. package/dist/mobile.js +45 -0
  157. package/dist/mobile.js.map +1 -0
  158. package/dist/native.d.ts +71 -0
  159. package/dist/native.js +147 -0
  160. package/dist/native.js.map +1 -0
  161. package/dist/payments.js +1 -1
  162. package/dist/payments.js.map +1 -1
  163. package/dist/popover-overlay.d.ts +4 -1
  164. package/dist/popover-overlay.js +10 -3
  165. package/dist/popover-overlay.js.map +1 -1
  166. package/dist/recurrence-editor.d.ts +3 -1
  167. package/dist/recurrence-editor.js +6 -0
  168. package/dist/recurrence-editor.js.map +1 -1
  169. package/dist/recurrence.d.ts +70 -10
  170. package/dist/recurrence.js +363 -24
  171. package/dist/recurrence.js.map +1 -1
  172. package/dist/resource-usage.js +1 -1
  173. package/dist/resource-usage.js.map +1 -1
  174. package/dist/resumable-upload-field.d.ts +57 -0
  175. package/dist/resumable-upload-field.js +196 -0
  176. package/dist/resumable-upload-field.js.map +1 -0
  177. package/dist/resumable-upload-store.d.ts +40 -0
  178. package/dist/resumable-upload-store.js +209 -0
  179. package/dist/resumable-upload-store.js.map +1 -0
  180. package/dist/resumable-upload-xhr.d.ts +37 -0
  181. package/dist/resumable-upload-xhr.js +180 -0
  182. package/dist/resumable-upload-xhr.js.map +1 -0
  183. package/dist/resumable-upload.d.ts +268 -0
  184. package/dist/resumable-upload.js +1221 -0
  185. package/dist/resumable-upload.js.map +1 -0
  186. package/dist/rich-text-atoms.d.ts +114 -0
  187. package/dist/rich-text-atoms.js +328 -0
  188. package/dist/rich-text-atoms.js.map +1 -0
  189. package/dist/rich-text-commands.d.ts +2 -2
  190. package/dist/rich-text-commands.js +1 -1
  191. package/dist/rich-text-commands.js.map +1 -1
  192. package/dist/rich-text-dom.d.ts +48 -4
  193. package/dist/rich-text-dom.js +337 -15
  194. package/dist/rich-text-dom.js.map +1 -1
  195. package/dist/rich-text-editor.d.ts +238 -3
  196. package/dist/rich-text-editor.js +1670 -26
  197. package/dist/rich-text-editor.js.map +1 -1
  198. package/dist/rich-text-image.d.ts +62 -0
  199. package/dist/rich-text-image.js +152 -0
  200. package/dist/rich-text-image.js.map +1 -0
  201. package/dist/rich-text-markdown-shortcuts.d.ts +21 -0
  202. package/dist/rich-text-markdown-shortcuts.js +89 -0
  203. package/dist/rich-text-markdown-shortcuts.js.map +1 -0
  204. package/dist/rich-text-markdown.d.ts +57 -0
  205. package/dist/rich-text-markdown.js +1245 -0
  206. package/dist/rich-text-markdown.js.map +1 -0
  207. package/dist/rich-text-model.d.ts +129 -4
  208. package/dist/rich-text-model.js +554 -33
  209. package/dist/rich-text-model.js.map +1 -1
  210. package/dist/rich-text-paste.d.ts +35 -0
  211. package/dist/rich-text-paste.js +254 -0
  212. package/dist/rich-text-paste.js.map +1 -0
  213. package/dist/rich-text-sanitize.d.ts +18 -16
  214. package/dist/rich-text-sanitize.js +203 -10
  215. package/dist/rich-text-sanitize.js.map +1 -1
  216. package/dist/rich-text-schema.d.ts +51 -2
  217. package/dist/rich-text-schema.js +52 -10
  218. package/dist/rich-text-schema.js.map +1 -1
  219. package/dist/rich-text-suggest.d.ts +109 -0
  220. package/dist/rich-text-suggest.js +181 -0
  221. package/dist/rich-text-suggest.js.map +1 -0
  222. package/dist/rich-text-table.d.ts +125 -0
  223. package/dist/rich-text-table.js +478 -0
  224. package/dist/rich-text-table.js.map +1 -0
  225. package/dist/rich-text-validation.d.ts +29 -0
  226. package/dist/rich-text-validation.js +46 -0
  227. package/dist/rich-text-validation.js.map +1 -0
  228. package/dist/rich-text.d.ts +8 -0
  229. package/dist/rich-text.js +8 -0
  230. package/dist/rich-text.js.map +1 -1
  231. package/dist/scheduling.d.ts +6 -0
  232. package/dist/scheduling.js.map +1 -1
  233. package/dist/secret.d.ts +120 -0
  234. package/dist/secret.js +310 -0
  235. package/dist/secret.js.map +1 -0
  236. package/dist/service-graph.js +62 -42
  237. package/dist/service-graph.js.map +1 -1
  238. package/dist/tabs-overflow.d.ts +27 -0
  239. package/dist/tabs-overflow.js +36 -0
  240. package/dist/tabs-overflow.js.map +1 -1
  241. package/dist/theme-builder.js +16 -16
  242. package/dist/viewport-gestures.d.ts +144 -0
  243. package/dist/viewport-gestures.js +352 -0
  244. package/dist/viewport-gestures.js.map +1 -0
  245. package/dist/viewport.d.ts +98 -0
  246. package/dist/viewport.js +241 -0
  247. package/dist/viewport.js.map +1 -0
  248. package/dist/workflow.d.ts +0 -7
  249. package/dist/workflow.js +22 -30
  250. package/dist/workflow.js.map +1 -1
  251. package/dist/workspace.d.ts +3 -4
  252. package/dist/workspace.js +2 -2
  253. package/dist/workspace.js.map +1 -1
  254. package/package.json +51 -50
@@ -10,12 +10,36 @@
10
10
  * é o caractere `\n` dentro do texto; no bloco de código, `\n` é a quebra literal e não há marca.
11
11
  * - **Posição** = (índice do bloco, deslocamento em unidades UTF-16 do texto do bloco), o mesmo que o
12
12
  * `Range` do DOM usa dentro de um nó de texto.
13
+ * - **Tabela** = sequência de blocos-folha de célula (`cell`: linha, coluna e se a tabela tem cabeçalho), linha a
14
+ * linha. A célula é um parágrafo sem contêiner: digitação, marcas, átomos, histórico e leitura de volta valem como
15
+ * em qualquer bloco; a posição dentro da célula é (bloco da célula, deslocamento), e a grade (`rows[][]`) e a célula
16
+ * da posição são visões calculadas (`rtTableBounds`, `rich-text-table`). Uma tabela nova começa na célula (0, 0).
13
17
  * - Todo comando é uma função pura `(estado) → estado` (documento + seleção + marcas armazenadas).
14
18
  *
15
19
  * A serialização canônica (`rtSerialize`) é a única fonte do valor: o mesmo documento produz sempre a
16
20
  * mesma string.
17
21
  */
18
- import { RT_CODE, RICH_TEXT_MARK_BITS, RICH_TEXT_MARK_ORDER, } from './rich-text-schema';
22
+ import { RT_CODE, RICH_TEXT_DEFAULT_VARIABLE_SYNTAX, RICH_TEXT_MARK_BITS, RICH_TEXT_MARK_ORDER, } from './rich-text-schema';
23
+ /** Marcador de objeto do Unicode: o texto de um trecho que é átomo. */
24
+ export const RT_ATOM_CHAR = '';
25
+ /** Forma textual do átomo (a que vai para o HTML, o texto puro e o Markdown). */
26
+ export function rtAtomText(atom, syntax = RICH_TEXT_DEFAULT_VARIABLE_SYNTAX) {
27
+ if (atom.kind === 'mention')
28
+ return `@${atom.label}`;
29
+ if (atom.kind === 'image')
30
+ return atom.decorative || !atom.alt ? '' : `[${atom.alt}]`;
31
+ return syntax.pad ? `${syntax.open} ${atom.name} ${syntax.close}` : `${syntax.open}${atom.name}${syntax.close}`;
32
+ }
33
+ export function rtSameAtom(a, b) {
34
+ if (!a || !b)
35
+ return a === b;
36
+ if (a.kind === 'variable')
37
+ return b.kind === 'variable' && a.name === b.name;
38
+ if (a.kind === 'image') {
39
+ return (b.kind === 'image' && a.src === b.src && a.alt === b.alt && a.decorative === b.decorative && a.width === b.width && a.height === b.height && a.pending === b.pending);
40
+ }
41
+ return b.kind === 'mention' && a.id === b.id && a.label === b.label;
42
+ }
19
43
  export const RT_NBSP = ' ';
20
44
  // ── construção ───────────────────────────────────────────────────────────────────────────────────
21
45
  export function rtRun(text, marks = 0, href = null) {
@@ -31,7 +55,7 @@ export function rtNormalizeRuns(runs) {
31
55
  if (!text)
32
56
  return;
33
57
  const last = out[out.length - 1];
34
- if (last && last.marks === marks && last.href === href)
58
+ if (last && !last.atom && last.marks === marks && last.href === href)
35
59
  out[out.length - 1] = { text: last.text + text, marks, href };
36
60
  else
37
61
  out.push({ text, marks, href });
@@ -39,9 +63,18 @@ export function rtNormalizeRuns(runs) {
39
63
  for (const run of runs) {
40
64
  if (!run.text)
41
65
  continue;
66
+ // Átomo: sempre um U+FFFC só, nunca fundido com o vizinho, nunca dentro de código em linha.
67
+ if (run.atom) {
68
+ out.push({ text: RT_ATOM_CHAR, marks: run.marks & ~RT_CODE, href: run.href, atom: run.atom });
69
+ continue;
70
+ }
71
+ // U+FFFC sem átomo (colado de fora) é descartado.
72
+ const text = run.text.includes(RT_ATOM_CHAR) ? run.text.split(RT_ATOM_CHAR).join('') : run.text;
73
+ if (!text)
74
+ continue;
42
75
  const marks = run.marks & RT_CODE ? RT_CODE : run.marks;
43
- if (marks & RT_CODE && run.text.includes('\n')) {
44
- const parts = run.text.split('\n');
76
+ if (marks & RT_CODE && text.includes('\n')) {
77
+ const parts = text.split('\n');
45
78
  parts.forEach((part, i) => {
46
79
  if (i > 0)
47
80
  push('\n', 0, run.href);
@@ -49,14 +82,21 @@ export function rtNormalizeRuns(runs) {
49
82
  });
50
83
  }
51
84
  else {
52
- push(run.text, marks, run.href);
85
+ push(text, marks, run.href);
53
86
  }
54
87
  }
55
88
  return out;
56
89
  }
90
+ /** Texto literal dos trechos: o átomo vira a forma textual (bloco de código, texto puro). */
91
+ export function rtRunsLiteral(runs, syntax) {
92
+ let out = '';
93
+ for (const run of runs)
94
+ out += run.atom ? rtAtomText(run.atom, syntax) : run.text;
95
+ return out;
96
+ }
57
97
  export function rtBlock(type, runs = [], wrap = 'none', level = 0) {
58
98
  if (type === 'code') {
59
- const text = runs.map((r) => r.text).join('');
99
+ const text = rtRunsLiteral(runs);
60
100
  return { type, level: 0, wrap: 'none', runs: text ? [{ text, marks: 0, href: null }] : [] };
61
101
  }
62
102
  return { type, level: type === 'heading' ? level || 2 : 0, wrap: type === 'heading' ? 'none' : wrap, runs: rtNormalizeRuns(runs) };
@@ -67,8 +107,13 @@ export function rtParagraph(runs = [], wrap = 'none') {
67
107
  export function rtEmptyDoc() {
68
108
  return [rtParagraph()];
69
109
  }
110
+ /** O mesmo bloco (tipo, nível, contêiner e célula) com outro conteúdo. */
111
+ export function rtWithRuns(block, runs) {
112
+ const next = rtBlock(block.type, runs, block.wrap, block.level);
113
+ return block.cell ? { ...next, cell: block.cell } : next;
114
+ }
70
115
  function withRuns(block, runs) {
71
- return rtBlock(block.type, runs, block.wrap, block.level);
116
+ return rtWithRuns(block, runs);
72
117
  }
73
118
  // ── consultas básicas ────────────────────────────────────────────────────────────────────────────
74
119
  const textCache = new WeakMap();
@@ -121,7 +166,94 @@ export function rtState(doc, selection = rtCollapsed(rtDocEnd(doc)), stored = nu
121
166
  }
122
167
  /** Documento só com um parágrafo vazio (o que mostra o placeholder). */
123
168
  export function rtIsBlank(doc) {
124
- return doc.length === 1 && doc[0].type === 'paragraph' && doc[0].wrap === 'none' && rtBlockLength(doc[0]) === 0;
169
+ return doc.length === 1 && doc[0].type === 'paragraph' && doc[0].wrap === 'none' && !doc[0].cell && rtBlockLength(doc[0]) === 0;
170
+ }
171
+ // ── tabela (sequência de blocos-célula) ──────────────────────────────────────────────────────────
172
+ /** Limites da tabela: 50 colunas e 500 linhas (acima disso o caso é grade de dados, não documento). */
173
+ export const RT_TABLE_MAX_COLS = 50;
174
+ export const RT_TABLE_MAX_ROWS = 500;
175
+ /** O bloco `index` é a primeira célula de uma tabela (sem célula antes, ou a célula (0, 0)). */
176
+ export function rtStartsTable(doc, index) {
177
+ const cell = doc[index]?.cell;
178
+ return !!cell && (index === 0 || !doc[index - 1].cell || (cell.row === 0 && cell.col === 0));
179
+ }
180
+ /** A tabela que contém o bloco `index` (ou `null` fora de tabela). */
181
+ export function rtTableBounds(doc, index) {
182
+ const first = doc[index]?.cell;
183
+ if (!first)
184
+ return null;
185
+ let start = index;
186
+ while (!rtStartsTable(doc, start))
187
+ start--;
188
+ let end = index + 1;
189
+ while (end < doc.length && doc[end].cell && !rtStartsTable(doc, end))
190
+ end++;
191
+ const row = doc[start].cell.row;
192
+ let cols = 0;
193
+ while (start + cols < end && doc[start + cols].cell.row === row)
194
+ cols++;
195
+ return { start, end, rows: Math.ceil((end - start) / cols), cols, header: doc[start].cell.header };
196
+ }
197
+ /** Algum bloco de [from, to] é célula. */
198
+ function hasCellIn(doc, from, to) {
199
+ for (let i = from; i <= to; i++)
200
+ if (doc[i]?.cell)
201
+ return true;
202
+ return false;
203
+ }
204
+ /** Células numeradas linha a linha a partir de uma grade de blocos (as linhas curtas são completadas com células vazias). */
205
+ export function rtTableBlocks(grid, header) {
206
+ const cols = Math.max(1, ...grid.map((row) => row.length));
207
+ const out = [];
208
+ grid.forEach((row, r) => {
209
+ for (let c = 0; c < cols; c++) {
210
+ const source = row[c];
211
+ const cell = source?.cell;
212
+ if (source && cell && cell.row === r && cell.col === c && cell.header === header && source.type === 'paragraph' && source.wrap === 'none') {
213
+ out.push(source);
214
+ continue;
215
+ }
216
+ const runs = source ? (source.type === 'code' ? plainRuns(source.runs) : source.runs) : [];
217
+ out.push({ ...rtBlock('paragraph', runs), cell: { row: r, col: c, header } });
218
+ }
219
+ });
220
+ return out;
221
+ }
222
+ /**
223
+ * Grade de cada tabela refeita pela invariante: linhas pela mudança do índice de linha, todas com o mesmo número de
224
+ * colunas (completa com células vazias), dentro dos limites, numeradas de novo. O mesmo documento quando já está certo.
225
+ */
226
+ export function rtNormalizeTables(doc) {
227
+ if (!doc.some((block) => block.cell))
228
+ return doc;
229
+ const out = [];
230
+ let changed = false;
231
+ let i = 0;
232
+ while (i < doc.length) {
233
+ if (!doc[i].cell) {
234
+ out.push(doc[i++]);
235
+ continue;
236
+ }
237
+ const header = doc[i].cell.header;
238
+ const grid = [];
239
+ let lastRow = Number.NaN;
240
+ const start = i;
241
+ do {
242
+ const cell = doc[i].cell;
243
+ if (cell.row !== lastRow) {
244
+ grid.push([]);
245
+ lastRow = cell.row;
246
+ }
247
+ grid[grid.length - 1].push(doc[i]);
248
+ i++;
249
+ } while (i < doc.length && doc[i].cell && !(doc[i].cell.row === 0 && doc[i].cell.col === 0));
250
+ const limited = grid.slice(0, RT_TABLE_MAX_ROWS).map((row) => row.slice(0, RT_TABLE_MAX_COLS));
251
+ const blocks = rtTableBlocks(limited, header);
252
+ if (blocks.length !== i - start || blocks.some((block, k) => block !== doc[start + k]))
253
+ changed = true;
254
+ out.push(...blocks);
255
+ }
256
+ return changed ? out : doc;
125
257
  }
126
258
  // ── trechos ──────────────────────────────────────────────────────────────────────────────────────
127
259
  export function rtSliceRuns(runs, from, to) {
@@ -155,7 +287,7 @@ function inlineRuns(block) {
155
287
  return block.type === 'code' ? [{ text: rtBlockText(block), marks: 0, href: null }] : block.runs;
156
288
  }
157
289
  function plainRuns(runs) {
158
- const text = runs.map((r) => r.text).join('');
290
+ const text = rtRunsLiteral(runs);
159
291
  return text ? [{ text, marks: 0, href: null }] : [];
160
292
  }
161
293
  /** Conteúdo de `source` pronto para entrar em `target` (no código, só o texto). */
@@ -221,6 +353,8 @@ export function rtDeleteRange(doc, from, to) {
221
353
  if (from.block === 0 && from.offset === 0 && rtSamePos(to, end) && (doc.length > 1 || doc[0].type !== 'paragraph' || doc[0].wrap !== 'none')) {
222
354
  return { doc: rtEmptyDoc(), pos: rtDocStart() };
223
355
  }
356
+ if (from.block !== to.block && hasCellIn(doc, from.block, to.block))
357
+ return deleteAcrossCells(doc, from, to);
224
358
  const first = doc[from.block];
225
359
  const last = doc[to.block];
226
360
  const head = rtSliceRuns(first.runs, 0, from.offset);
@@ -228,6 +362,42 @@ export function rtDeleteRange(doc, from, to) {
228
362
  const merged = withRuns(first, [...head, ...runsFor(first, tail)]);
229
363
  return { doc: [...doc.slice(0, from.block), merged, ...doc.slice(to.block + 1)], pos: from };
230
364
  }
365
+ /**
366
+ * Apagar um intervalo que passa por células: na mesma tabela, esvazia o que a seleção cobre sem juntar células; cruzando
367
+ * a borda de uma tabela, a tabela tocada sai inteira (a seleção cruzada cobre a tabela toda) e as pontas fora dela se
368
+ * juntam como sempre.
369
+ */
370
+ function deleteAcrossCells(doc, from, to) {
371
+ const a = rtTableBounds(doc, from.block);
372
+ const b = rtTableBounds(doc, to.block);
373
+ if (a && b && a.start === b.start) {
374
+ const out = doc.slice();
375
+ for (let i = from.block; i <= to.block; i++) {
376
+ const block = doc[i];
377
+ const len = rtBlockLength(block);
378
+ const start = i === from.block ? from.offset : 0;
379
+ const end = i === to.block ? to.offset : len;
380
+ out[i] = withRuns(block, [...rtSliceRuns(block.runs, 0, start), ...rtSliceRuns(block.runs, end, len)]);
381
+ }
382
+ return { doc: out, pos: from };
383
+ }
384
+ const start = a ? { block: a.start, offset: 0 } : from;
385
+ const end = b ? { block: b.end - 1, offset: rtBlockLength(doc[b.end - 1]) } : to;
386
+ const first = doc[start.block];
387
+ const last = doc[end.block];
388
+ const head = first.cell ? null : withRuns(first, rtSliceRuns(first.runs, 0, start.offset));
389
+ const tail = last.cell ? null : rtSliceRuns(inlineRuns(last), end.offset, rtBlockLength(last));
390
+ let middle;
391
+ if (head && tail)
392
+ middle = withRuns(head, [...head.runs, ...runsFor(head, tail)]);
393
+ else if (head)
394
+ middle = head;
395
+ else if (tail)
396
+ middle = withRuns(last, tail);
397
+ else
398
+ middle = rtParagraph();
399
+ return { doc: [...doc.slice(0, start.block), middle, ...doc.slice(end.block + 1)], pos: { block: start.block, offset: head ? start.offset : 0 } };
400
+ }
231
401
  function replaceBlock(doc, index, ...blocks) {
232
402
  return [...doc.slice(0, index), ...blocks, ...doc.slice(index + 1)];
233
403
  }
@@ -260,6 +430,39 @@ export function rtInsertText(state, text) {
260
430
  const next = { block: pos.block, offset: pos.offset + text.length };
261
431
  return { doc: replaceBlock(doc, pos.block, block), selection: rtCollapsed(next), stored: null };
262
432
  }
433
+ /**
434
+ * Insere um átomo na seleção (apaga o que estiver selecionado), com as marcas e o link do texto digitado ali; o cursor
435
+ * fica depois dele. No bloco de código entra a forma textual (`syntax`); em código em linha, o código fecha antes e
436
+ * reabre depois.
437
+ */
438
+ export function rtInsertAtom(state, atom, syntax) {
439
+ const { doc, pos } = rtDeleteRange(state.doc, state.selection.anchor, state.selection.focus);
440
+ const target = doc[pos.block];
441
+ if (target.type === 'code') {
442
+ const text = rtAtomText(atom, syntax);
443
+ const block = insertRuns(target, pos.offset, [rtRun(text)]);
444
+ return { doc: replaceBlock(doc, pos.block, block), selection: rtCollapsed({ block: pos.block, offset: pos.offset + text.length }), stored: null };
445
+ }
446
+ const attrs = typingAttrs(state, doc, pos);
447
+ const block = insertRuns(target, pos.offset, [{ text: RT_ATOM_CHAR, marks: attrs.marks & ~RT_CODE, href: attrs.href, atom }]);
448
+ return { doc: replaceBlock(doc, pos.block, block), selection: rtCollapsed({ block: pos.block, offset: pos.offset + 1 }), stored: null };
449
+ }
450
+ /** Átomo no caractere `index` do bloco (ou `null`). */
451
+ export function rtAtomAt(doc, block, index) {
452
+ const target = doc[block];
453
+ if (!target || target.type === 'code')
454
+ return null;
455
+ return runAt(target, index)?.atom ?? null;
456
+ }
457
+ /** A seleção cobre exatamente um átomo: devolve a posição dele (bloco e índice do caractere). */
458
+ export function rtSelectedAtom(state) {
459
+ const from = rtSelectionFrom(state.selection);
460
+ const to = rtSelectionTo(state.selection);
461
+ if (from.block !== to.block || to.offset - from.offset !== 1)
462
+ return null;
463
+ const atom = rtAtomAt(state.doc, from.block, from.offset);
464
+ return atom ? { block: from.block, index: from.offset, atom } : null;
465
+ }
263
466
  /** Shift+Enter: quebra de linha no mesmo bloco (no código, igual a Enter). */
264
467
  export function rtInsertLineBreak(state) {
265
468
  return rtInsertText(state, '\n');
@@ -280,6 +483,11 @@ export function rtSplitBlock(state) {
280
483
  const len = rtBlockLength(block);
281
484
  const text = rtBlockText(block);
282
485
  const done = (next, at) => ({ doc: next, selection: rtCollapsed(at), stored: null });
486
+ // Célula não tem blocos: Enter é quebra de linha dentro dela.
487
+ if (block.cell) {
488
+ const updated = insertRuns(block, pos.offset, [rtRun('\n', rtMarksAt(doc, pos))]);
489
+ return done(replaceBlock(doc, i, updated), { block: i, offset: pos.offset + 1 });
490
+ }
283
491
  if (block.type === 'code') {
284
492
  if (pos.offset === len && text.endsWith('\n')) {
285
493
  const trimmed = rtBlock('code', [rtRun(text.slice(0, -1))]);
@@ -410,11 +618,27 @@ export function rtDeleteBackward(state, unit = 'char') {
410
618
  const doc = state.doc;
411
619
  const block = doc[pos.block];
412
620
  if (pos.offset === 0) {
621
+ // Célula: não junta com a vizinha; na primeira célula de uma tabela toda vazia, apaga a tabela.
622
+ if (block.cell) {
623
+ const table = rtTableBounds(doc, pos.block);
624
+ if (pos.block !== table.start || doc.slice(table.start, table.end).some((cell) => rtBlockLength(cell) > 0))
625
+ return state;
626
+ const next = [...doc.slice(0, table.start), rtParagraph(), ...doc.slice(table.end)];
627
+ return { doc: next, selection: rtCollapsed({ block: table.start, offset: 0 }), stored: null };
628
+ }
413
629
  const unwrapped = unwrapForBackspace(block);
414
630
  if (unwrapped)
415
631
  return { doc: replaceBlock(doc, pos.block, unwrapped), selection: rtCollapsed(pos), stored: null };
416
632
  if (pos.block === 0)
417
633
  return state;
634
+ // Logo depois de uma tabela: o parágrafo vazio sai; com texto, o cursor só vai para o fim da última célula.
635
+ const before = doc[pos.block - 1];
636
+ if (before.cell) {
637
+ const target = rtCollapsed({ block: pos.block - 1, offset: rtBlockLength(before) });
638
+ if (rtBlockLength(block) > 0)
639
+ return { doc, selection: target, stored: state.stored };
640
+ return { doc: [...doc.slice(0, pos.block), ...doc.slice(pos.block + 1)], selection: target, stored: null };
641
+ }
418
642
  const prevLength = rtBlockLength(doc[pos.block - 1]);
419
643
  return { doc: joinWithNext(doc, pos.block - 1), selection: rtCollapsed({ block: pos.block - 1, offset: prevLength }), stored: null };
420
644
  }
@@ -433,6 +657,9 @@ export function rtDeleteForward(state, unit = 'char') {
433
657
  if (pos.offset >= len) {
434
658
  if (pos.block >= doc.length - 1)
435
659
  return state;
660
+ // Célula não junta com a vizinha, e o bloco antes de uma tabela não a engole.
661
+ if (block.cell || doc[pos.block + 1].cell)
662
+ return state;
436
663
  return { doc: joinWithNext(doc, pos.block), selection: rtCollapsed(pos), stored: null };
437
664
  }
438
665
  const end = rtNextBoundary(rtBlockText(block), pos.offset, unit);
@@ -640,11 +867,17 @@ function eachBlock(touched, convert) {
640
867
  }
641
868
  return { blocks, map: (local, offset) => maps[local](offset) };
642
869
  }
870
+ /** A seleção toca alguma célula (os comandos de bloco não se aplicam dentro de tabela). */
871
+ function touchesCell(state) {
872
+ return hasCellIn(state.doc, rtSelectionFrom(state.selection).block, rtSelectionTo(state.selection).block);
873
+ }
643
874
  /**
644
875
  * Parágrafo ou título N em todos os blocos tocados. Item de lista convertido sai da lista; parágrafo
645
876
  * de citação convertido em título sai da citação (parágrafo continua nela).
646
877
  */
647
878
  export function rtSetBlockType(state, kind) {
879
+ if (touchesCell(state))
880
+ return state;
648
881
  return replaceTouched(state, (touched) => eachBlock(touched, (runs, block) => {
649
882
  if (kind === 'paragraph')
650
883
  return rtParagraph(runs, block.wrap === 'quote' && block.type === 'paragraph' ? 'quote' : 'none');
@@ -653,6 +886,8 @@ export function rtSetBlockType(state, kind) {
653
886
  }
654
887
  /** Lista com marcador/numerada: liga, desliga ou troca o tipo dos blocos tocados. */
655
888
  export function rtToggleList(state, kind) {
889
+ if (touchesCell(state))
890
+ return state;
656
891
  return replaceTouched(state, (touched) => {
657
892
  // Todos já itens deste tipo → saem da lista. Senão (itens do outro tipo, ou blocos quaisquer)
658
893
  // → itens deste tipo: o título perde o nível e o código vira um item por linha.
@@ -663,6 +898,8 @@ export function rtToggleList(state, kind) {
663
898
  }
664
899
  /** Citação: tira (todos já citados) ou põe os blocos tocados, como parágrafos, numa citação. */
665
900
  export function rtToggleQuote(state) {
901
+ if (touchesCell(state))
902
+ return state;
666
903
  return replaceTouched(state, (touched) => {
667
904
  if (touched.every((b) => b.wrap === 'quote'))
668
905
  return eachBlock(touched, (runs) => rtParagraph(runs));
@@ -671,6 +908,8 @@ export function rtToggleQuote(state) {
671
908
  }
672
909
  /** Bloco de código: todos já em código → um parágrafo por linha; senão → um bloco só, sem marcas. */
673
910
  export function rtToggleCodeBlock(state) {
911
+ if (touchesCell(state))
912
+ return state;
674
913
  return replaceTouched(state, (touched) => {
675
914
  if (touched.every((b) => b.type === 'code'))
676
915
  return eachBlock(touched, (runs) => rtParagraph(runs));
@@ -678,7 +917,8 @@ export function rtToggleCodeBlock(state) {
678
917
  let at = 0;
679
918
  const texts = touched.map((block) => {
680
919
  starts.push(at);
681
- const text = rtBlockText(block);
920
+ // O átomo entra no código como a forma textual (as posições depois dele no bloco ficam aproximadas).
921
+ const text = rtRunsLiteral(block.runs);
682
922
  at += text.length + 1;
683
923
  return text;
684
924
  });
@@ -694,7 +934,7 @@ export function rtExitAtEnd(state) {
694
934
  const block = doc[pos.block];
695
935
  if (pos.block !== doc.length - 1 || pos.offset !== rtBlockLength(block))
696
936
  return null;
697
- if (block.type !== 'code' && block.wrap !== 'quote')
937
+ if (block.type !== 'code' && block.wrap !== 'quote' && !block.cell)
698
938
  return null;
699
939
  return { doc: [...doc, rtParagraph()], selection: rtCollapsed({ block: doc.length, offset: 0 }), stored: null };
700
940
  }
@@ -719,12 +959,26 @@ export function rtInsertFragment(state, fragment) {
719
959
  const { doc, pos } = rtDeleteRange(state.doc, state.selection.anchor, state.selection.focus);
720
960
  const block = doc[pos.block];
721
961
  if (block.type === 'code') {
722
- const text = fragment.map((b) => rtBlockText(b)).join('\n');
962
+ const text = fragment.map((b) => rtRunsLiteral(b.runs)).join('\n');
723
963
  const updated = insertRuns(block, pos.offset, [rtRun(text)]);
724
964
  return { doc: replaceBlock(doc, pos.block, updated), selection: rtCollapsed({ block: pos.block, offset: pos.offset + text.length }), stored: null };
725
965
  }
966
+ // Na célula, tudo entra em linha: blocos viram quebra de linha e células de uma mesma linha, tabulação.
967
+ if (block.cell) {
968
+ const runs = inlineFragment(fragment);
969
+ const inserted = runs.reduce((n, r) => n + r.text.length, 0);
970
+ return { doc: replaceBlock(doc, pos.block, insertRuns(block, pos.offset, runs)), selection: rtCollapsed({ block: pos.block, offset: pos.offset + inserted }), stored: null };
971
+ }
726
972
  const len = rtBlockLength(block);
727
973
  const blank = len === 0 && block.type === 'paragraph';
974
+ // Tabela no fragmento: entra inteira, partindo o bloco do cursor; o resto da linha vai para depois dela.
975
+ if (fragment.some((b) => b.cell)) {
976
+ const lead = blank && block.wrap === 'none' ? [] : [withRuns(block, rtSliceRuns(block.runs, 0, pos.offset))];
977
+ const trail = withRuns(block, rtSliceRuns(block.runs, pos.offset, len));
978
+ const next = rtNormalizeTables([...doc.slice(0, pos.block), ...lead, ...fragment, trail, ...doc.slice(pos.block + 1)]);
979
+ const at = pos.block + lead.length + fragment.length;
980
+ return { doc: next, selection: rtCollapsed({ block: Math.min(at, next.length - 1), offset: 0 }), stored: null };
981
+ }
728
982
  if (fragment.length === 1) {
729
983
  const only = fragment[0];
730
984
  if (blank && (only.type !== 'paragraph' || only.wrap !== block.wrap)) {
@@ -752,6 +1006,17 @@ export function rtInsertFragment(state, fragment) {
752
1006
  stored: null,
753
1007
  };
754
1008
  }
1009
+ /** Fragmento como conteúdo inline: blocos separados por quebra de linha, células da mesma linha por tabulação. */
1010
+ function inlineFragment(fragment) {
1011
+ const out = [];
1012
+ fragment.forEach((block, i) => {
1013
+ const prev = fragment[i - 1];
1014
+ if (i > 0)
1015
+ out.push(rtRun(block.cell && prev.cell && block.cell.row === prev.cell.row && block.cell.col > 0 ? '\t' : '\n'));
1016
+ out.push(...inlineRuns(block));
1017
+ });
1018
+ return out;
1019
+ }
755
1020
  /** Pedaço do documento entre duas posições (para copiar/recortar/arrastar). */
756
1021
  export function rtSliceDoc(doc, from, to) {
757
1022
  if (rtComparePos(from, to) > 0)
@@ -761,7 +1026,9 @@ export function rtSliceDoc(doc, from, to) {
761
1026
  const block = doc[i];
762
1027
  const start = i === from.block ? from.offset : 0;
763
1028
  const end = i === to.block ? to.offset : rtBlockLength(block);
764
- out.push(withRuns(block, rtSliceRuns(block.runs, start, end)));
1029
+ const runs = rtSliceRuns(block.runs, start, end);
1030
+ // Trecho de uma célula só: o conteúdo, sem a célula (colar em outro lugar não cria tabela de 1 × 1).
1031
+ out.push(from.block === to.block && block.cell ? rtParagraph(runs) : withRuns(block, runs));
765
1032
  }
766
1033
  return out.length ? out : rtEmptyDoc();
767
1034
  }
@@ -794,6 +1061,7 @@ export function rtSelectionInfo(state) {
794
1061
  allBullet: touched.every((b) => b.type === 'paragraph' && b.wrap === 'bullet'),
795
1062
  allOrdered: touched.every((b) => b.type === 'paragraph' && b.wrap === 'ordered'),
796
1063
  allQuote: touched.every((b) => b.wrap === 'quote'),
1064
+ ...(touched.some((b) => b.cell) ? { inTable: true } : {}),
797
1065
  };
798
1066
  if (rtIsCollapsed(state.selection)) {
799
1067
  const marks = base.inCodeBlock ? 0 : rtCursorMarks(state);
@@ -898,12 +1166,17 @@ export function rtInlineTokens(runs, view) {
898
1166
  const to = Math.min(at, end);
899
1167
  if (from >= to)
900
1168
  continue;
901
- const text = view ? view.text.slice(from - start, to - start) : run.text.slice(from - runStart, to - runStart);
902
1169
  const link = run.href !== null ? [`a:${run.href}`] : [];
903
1170
  const wanted = [...link];
904
1171
  for (const { bit, tag } of RICH_TEXT_MARK_ORDER)
905
1172
  if (run.marks & bit)
906
1173
  wanted.push(tag);
1174
+ if (run.atom) {
1175
+ reconcile(wanted);
1176
+ tokens.push({ kind: 'atom', atom: run.atom });
1177
+ continue;
1178
+ }
1179
+ const text = view ? view.text.slice(from - start, to - start) : run.text.slice(from - runStart, to - runStart);
907
1180
  text.split('\n').forEach((piece, index) => {
908
1181
  if (index > 0) {
909
1182
  reconcile(link);
@@ -918,19 +1191,51 @@ export function rtInlineTokens(runs, view) {
918
1191
  reconcile([]);
919
1192
  return tokens;
920
1193
  }
921
- function serializeInline(prepared) {
1194
+ /** Estilo fixo do `pre` no perfil e-mail (os clientes de e-mail ignoram folha de estilo); nunca vem da entrada. */
1195
+ export const RICH_TEXT_EMAIL_PRE_STYLE = 'white-space:pre-wrap';
1196
+ const ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:/i;
1197
+ function hasVariable(text, syntax) {
1198
+ const open = text.indexOf(syntax.open);
1199
+ return open >= 0 && text.indexOf(syntax.close, open + syntax.open.length) > 0;
1200
+ }
1201
+ /** O endereço é exatamente uma variável (`{{ link }}`): o servidor preenche com um endereço absoluto. */
1202
+ function isWholeVariable(href, syntax) {
1203
+ return href.startsWith(syntax.open) && href.endsWith(syntax.close) && href.indexOf(syntax.open, 1) < 0;
1204
+ }
1205
+ function serializeInline(prepared, options = {}) {
922
1206
  if (!prepared.visible)
923
1207
  return '';
1208
+ const email = options.profile === 'email';
1209
+ const syntax = options.variableSyntax ?? RICH_TEXT_DEFAULT_VARIABLE_SYNTAX;
1210
+ // No e-mail não há base para endereço relativo: o link relativo vira texto.
1211
+ const runs = email
1212
+ ? prepared.block.runs.map((run) => (run.href !== null && !ABSOLUTE_URL.test(run.href) && !isWholeVariable(run.href, syntax) ? { ...run, href: null } : run))
1213
+ : prepared.block.runs;
924
1214
  let out = '';
925
- for (const token of rtInlineTokens(prepared.block.runs, prepared)) {
1215
+ for (const token of rtInlineTokens(runs, prepared)) {
926
1216
  if (token.kind === 'text')
927
1217
  out += escapeText(token.text);
928
1218
  else if (token.kind === 'br')
929
1219
  out += '<br>';
1220
+ else if (token.kind === 'atom') {
1221
+ const atom = token.atom;
1222
+ if (atom.kind === 'image')
1223
+ out += atom.pending ? '' : rtImageHtml(atom, email);
1224
+ else if (atom.kind === 'mention' && !email)
1225
+ out += `<span data-hm-mention="${escapeAttribute(atom.id)}">${escapeText(`@${atom.label}`)}</span>`;
1226
+ else
1227
+ out += escapeText(rtAtomText(atom, syntax));
1228
+ }
930
1229
  else {
931
1230
  const href = rtTokenHref(token.key);
932
- if (token.kind === 'open')
933
- out += href !== null ? `<a href="${escapeAttribute(href)}">` : `<${token.key}>`;
1231
+ if (token.kind === 'open') {
1232
+ if (href === null)
1233
+ out += `<${token.key}>`;
1234
+ else {
1235
+ const marked = !email && options.markVariableHrefs && hasVariable(href, syntax) ? ' data-hm-variable-href=""' : '';
1236
+ out += `<a href="${escapeAttribute(href)}"${marked}>`;
1237
+ }
1238
+ }
934
1239
  else
935
1240
  out += href !== null ? '</a>' : `</${token.key}>`;
936
1241
  }
@@ -944,20 +1249,35 @@ function leafTag(block) {
944
1249
  return 'li';
945
1250
  return 'p';
946
1251
  }
947
- /** Blocos visíveis do documento: sem os vazios do começo e do fim. */
1252
+ /** Blocos visíveis do documento: sem os vazios do começo e do fim. A tabela com algum texto fica inteira. */
948
1253
  function trimmedBlocks(doc) {
949
1254
  const prepared = doc.map(prepare);
1255
+ const kept = prepared.map((p) => p.visible);
1256
+ for (let i = 0; i < doc.length; i++) {
1257
+ if (!rtStartsTable(doc, i))
1258
+ continue;
1259
+ const table = rtTableBounds(doc, i);
1260
+ if (kept.slice(table.start, table.end).some(Boolean))
1261
+ kept.fill(true, table.start, table.end);
1262
+ }
950
1263
  let first = 0;
951
- while (first < prepared.length && !prepared[first].visible)
1264
+ while (first < prepared.length && !kept[first])
952
1265
  first++;
953
1266
  let last = prepared.length - 1;
954
- while (last >= first && !prepared[last].visible)
1267
+ while (last >= first && !kept[last])
955
1268
  last--;
956
1269
  return prepared.slice(first, last + 1);
957
1270
  }
958
- /** HTML canônico do documento (`''` quando não há nenhum caractere visível). */
959
- export function rtSerialize(doc) {
1271
+ /** Atributos fixos da tabela no perfil e-mail (clientes de e-mail ignoram folha de estilo); nunca vêm da entrada. */
1272
+ export const RICH_TEXT_EMAIL_TABLE_ATTRS = ' border="1" cellpadding="6" cellspacing="0"';
1273
+ /**
1274
+ * HTML do documento no perfil pedido (`''` quando não há nenhum caractere visível). O perfil web sem átomos é
1275
+ * exatamente o `rtSerialize`; o e-mail só usa `p`, `br`, `h2`–`h4`, marcas, `pre`/`code`, listas, citação e `a`
1276
+ * absoluto, com o único estilo fixo do `pre`. Variável sai como texto da sintaxe; menção, `@rótulo`.
1277
+ */
1278
+ export function richTextSerialize(doc, options = {}) {
960
1279
  const blocks = trimmedBlocks(doc);
1280
+ const pre = options.profile === 'email' ? `<pre style="${RICH_TEXT_EMAIL_PRE_STYLE}">` : '<pre>';
961
1281
  let out = '';
962
1282
  let wrap = 'none';
963
1283
  const close = () => {
@@ -969,8 +1289,35 @@ export function rtSerialize(doc) {
969
1289
  out += '</blockquote>';
970
1290
  wrap = 'none';
971
1291
  };
1292
+ // Tabela aberta: a seção (`thead` só com a linha de cabeçalho) e a linha atual.
1293
+ let table = null;
1294
+ const closeTable = () => {
1295
+ if (table)
1296
+ out += table.section === 'head' ? '</tr></thead></table>' : '</tr></tbody></table>';
1297
+ table = null;
1298
+ };
972
1299
  for (const prepared of blocks) {
973
1300
  const { block } = prepared;
1301
+ const cell = block.cell;
1302
+ if (cell) {
1303
+ close();
1304
+ if (!table || (cell.row === 0 && cell.col === 0)) {
1305
+ closeTable();
1306
+ table = { section: cell.header && cell.row === 0 ? 'head' : 'body', row: cell.row };
1307
+ out += `<table${options.profile === 'email' ? RICH_TEXT_EMAIL_TABLE_ATTRS : ''}>${table.section === 'head' ? '<thead>' : '<tbody>'}<tr>`;
1308
+ }
1309
+ else if (cell.row !== table.row) {
1310
+ out += '</tr>';
1311
+ if (table.section === 'head')
1312
+ out += '</thead><tbody>';
1313
+ table = { section: 'body', row: cell.row };
1314
+ out += '<tr>';
1315
+ }
1316
+ const inline = serializeInline(prepared, options);
1317
+ out += table.section === 'head' ? `<th scope="col">${inline}</th>` : `<td>${inline}</td>`;
1318
+ continue;
1319
+ }
1320
+ closeTable();
974
1321
  if (block.wrap !== wrap) {
975
1322
  close();
976
1323
  wrap = block.wrap;
@@ -982,24 +1329,198 @@ export function rtSerialize(doc) {
982
1329
  out += '<blockquote>';
983
1330
  }
984
1331
  if (block.type === 'code') {
985
- out += `<pre><code>${prepared.visible ? escapeText(prepared.text) : ''}</code></pre>`;
1332
+ out += `${pre}<code>${prepared.visible ? escapeText(prepared.text) : ''}</code></pre>`;
1333
+ continue;
1334
+ }
1335
+ // Imagem sozinha no parágrafo: bloco próprio (`figure` no perfil web; o e-mail não tem `figure`). Pendente não entra.
1336
+ const image = block.type === 'paragraph' && block.wrap === 'none' && block.runs.length === 1 ? block.runs[0].atom : undefined;
1337
+ if (image?.kind === 'image') {
1338
+ if (!image.pending)
1339
+ out += options.profile === 'email' ? `<p>${rtImageHtml(image, true)}</p>` : `<figure>${rtImageHtml(image, false)}</figure>`;
986
1340
  continue;
987
1341
  }
988
1342
  const tag = leafTag(block);
989
- out += `<${tag}>${serializeInline(prepared)}</${tag}>`;
1343
+ out += `<${tag}>${serializeInline(prepared, options)}</${tag}>`;
990
1344
  }
1345
+ closeTable();
991
1346
  close();
992
1347
  return out;
993
1348
  }
994
- /** Texto puro: blocos por `\n`, `br` → `\n`, código literal, nbsp → espaço. */
995
- export function rtPlainText(doc) {
996
- return trimmedBlocks(doc)
997
- .map((p) => (p.visible ? p.text : ''))
998
- .join('\n')
999
- .replace(/ /g, ' ');
1349
+ /** Estilo fixo da imagem no perfil e-mail (clientes de e-mail ignoram folha de estilo). */
1350
+ export const RICH_TEXT_EMAIL_IMG_STYLE = 'max-width:100%;height:auto';
1351
+ /**
1352
+ * `<img>` da imagem: `alt` só quando há texto ou é decorativa (`alt=""`); sem `alt` = sem descrição (o validador
1353
+ * `imageAlt` pega). Medidas como atributos; no e-mail, o estilo fixo.
1354
+ */
1355
+ function rtImageHtml(image, email) {
1356
+ let out = `<img src="${escapeAttribute(image.src)}"`;
1357
+ if (image.decorative)
1358
+ out += ' alt=""';
1359
+ else if (image.alt)
1360
+ out += ` alt="${escapeAttribute(image.alt).replace(/</g, '&lt;').replace(/>/g, '&gt;')}"`;
1361
+ if (image.width)
1362
+ out += ` width="${image.width}"`;
1363
+ if (image.height)
1364
+ out += ` height="${image.height}"`;
1365
+ if (email)
1366
+ out += ` style="${RICH_TEXT_EMAIL_IMG_STYLE}"`;
1367
+ return `${out}>`;
1368
+ }
1369
+ /** HTML canônico do documento (`''` quando não há nenhum caractere visível). */
1370
+ export function rtSerialize(doc) {
1371
+ return richTextSerialize(doc);
1372
+ }
1373
+ /** Texto visível do bloco preparado com cada átomo trocado pela forma textual. */
1374
+ function preparedLiteral(prepared, syntax) {
1375
+ if (!prepared.visible)
1376
+ return '';
1377
+ const { block, text, start } = prepared;
1378
+ if (block.type === 'code' || !text.includes(RT_ATOM_CHAR))
1379
+ return text;
1380
+ let out = '';
1381
+ let at = 0;
1382
+ for (const run of block.runs) {
1383
+ const runStart = at;
1384
+ at += run.text.length;
1385
+ const from = Math.max(runStart, start);
1386
+ const to = Math.min(at, prepared.end);
1387
+ if (from >= to)
1388
+ continue;
1389
+ out += run.atom ? rtAtomText(run.atom, syntax) : text.slice(from - start, to - start);
1390
+ }
1391
+ return out;
1392
+ }
1393
+ /** Texto puro: blocos por `\n`, `br` → `\n`, código literal, nbsp → espaço; átomo pela forma textual. */
1394
+ export function rtPlainText(doc, syntax) {
1395
+ let out = '';
1396
+ let prev = null;
1397
+ for (const prepared of trimmedBlocks(doc)) {
1398
+ // Células da mesma linha de tabela se separam por tabulação; o resto, por quebra de linha.
1399
+ const cell = prepared.block.cell;
1400
+ if (prev)
1401
+ out += cell && prev.cell && cell.col > 0 && cell.row === prev.cell.row ? '\t' : '\n';
1402
+ out += preparedLiteral(prepared, syntax);
1403
+ prev = prepared.block;
1404
+ }
1405
+ return out.replace(/\u00a0/g, ' ');
1000
1406
  }
1001
1407
  /** Contagem do contador e do validador: grafemas do texto puro, sem as quebras de linha. */
1002
- export function rtCharacterCount(doc) {
1003
- return rtGraphemeCount(rtPlainText(doc).replace(/\n/g, ''));
1408
+ export function rtCharacterCount(doc, syntax) {
1409
+ return rtGraphemeCount(rtPlainText(doc, syntax).replace(/\n/g, ''));
1410
+ }
1411
+ /** Texto inline do layout legível: link como `texto (endereço)` quando o texto difere do endereço. */
1412
+ function readableInline(prepared, syntax) {
1413
+ if (!prepared.visible)
1414
+ return '';
1415
+ const { block, text, start, end } = prepared;
1416
+ let out = '';
1417
+ let at = 0;
1418
+ let link = null;
1419
+ const flush = () => {
1420
+ if (!link)
1421
+ return;
1422
+ const bare = link.href.replace(/^mailto:/i, '');
1423
+ out += link.text === link.href || link.text === bare ? link.text : `${link.text} (${bare})`;
1424
+ link = null;
1425
+ };
1426
+ for (const run of block.runs) {
1427
+ const runStart = at;
1428
+ at += run.text.length;
1429
+ const from = Math.max(runStart, start);
1430
+ const to = Math.min(at, end);
1431
+ if (from >= to)
1432
+ continue;
1433
+ const piece = run.atom ? rtAtomText(run.atom, syntax) : text.slice(from - start, to - start);
1434
+ if (link && run.href !== link.href)
1435
+ flush();
1436
+ if (run.href !== null) {
1437
+ link ??= { href: run.href, text: '' };
1438
+ link.text += piece;
1439
+ }
1440
+ else
1441
+ out += piece;
1442
+ }
1443
+ flush();
1444
+ return out.replace(/ /g, ' ');
1445
+ }
1446
+ /**
1447
+ * Texto puro do documento. `compact`: o mesmo que `rtPlainText` (blocos por `\n`). `readable` (padrão): parágrafos
1448
+ * separados por linha em branco, item de lista com `- ` ou `N. ` (numeração real), citação com `> `, código recuado por
1449
+ * quatro espaços, link como `texto (endereço)`, variável pela sintaxe, menção como `@rótulo`; sem espaço no fim de linha.
1450
+ */
1451
+ export function richTextToPlainText(doc, options = {}) {
1452
+ const syntax = options.variableSyntax;
1453
+ if (options.layout === 'compact')
1454
+ return rtPlainText(doc, syntax);
1455
+ const groups = [];
1456
+ let current = [];
1457
+ let kind = null;
1458
+ let counter = 0;
1459
+ const flush = () => {
1460
+ if (current.length)
1461
+ groups.push(current.join('\n'));
1462
+ current = [];
1463
+ };
1464
+ // Tabela: células separadas por ` | `, uma linha por linha da tabela; o cabeçalho, sublinhado por hífens.
1465
+ let rows = [];
1466
+ let header = false;
1467
+ const flushTable = () => {
1468
+ if (!rows.length)
1469
+ return;
1470
+ const lines = rows.map((row) => row.join(' | ').replace(/[ \t]+$/, ''));
1471
+ if (header)
1472
+ lines.splice(1, 0, '-'.repeat(Math.max(3, lines[0].length)));
1473
+ groups.push(lines.join('\n'));
1474
+ rows = [];
1475
+ };
1476
+ for (const prepared of trimmedBlocks(doc)) {
1477
+ const { block } = prepared;
1478
+ if (block.cell) {
1479
+ if (block.cell.row === 0 && block.cell.col === 0)
1480
+ flushTable();
1481
+ if (!rows.length) {
1482
+ flush();
1483
+ kind = 'table';
1484
+ header = block.cell.header;
1485
+ }
1486
+ if (block.cell.col === 0 || !rows.length)
1487
+ rows.push([]);
1488
+ rows[rows.length - 1].push(readableInline(prepared, syntax).replace(/\s*\n\s*/g, ' ').trim());
1489
+ continue;
1490
+ }
1491
+ flushTable();
1492
+ const next = block.type === 'code' ? 'code' : block.type === 'heading' ? 'heading' : block.wrap;
1493
+ // Itens da mesma lista e parágrafos da mesma citação ficam juntos; o resto se separa por linha em branco.
1494
+ const continues = next === kind && (next === 'bullet' || next === 'ordered' || next === 'quote');
1495
+ if (!continues) {
1496
+ flush();
1497
+ counter = 0;
1498
+ }
1499
+ else if (next === 'quote')
1500
+ current.push('>');
1501
+ kind = next;
1502
+ let lines;
1503
+ if (block.type === 'code') {
1504
+ lines = (prepared.visible ? prepared.text : '').split('\n').map((line) => (line ? ` ${line}` : ''));
1505
+ }
1506
+ else {
1507
+ const inline = readableInline(prepared, syntax).split('\n');
1508
+ if (block.wrap === 'bullet')
1509
+ lines = inline.map((line, i) => (i === 0 ? `- ${line}` : ` ${line}`));
1510
+ else if (block.wrap === 'ordered') {
1511
+ counter++;
1512
+ const prefix = `${counter}. `;
1513
+ lines = inline.map((line, i) => (i === 0 ? prefix + line : ' '.repeat(prefix.length) + line));
1514
+ }
1515
+ else if (block.wrap === 'quote')
1516
+ lines = inline.map((line) => (line ? `> ${line}` : '>'));
1517
+ else
1518
+ lines = inline;
1519
+ }
1520
+ current.push(...lines.map((line) => line.replace(/[ \t]+$/, '')));
1521
+ }
1522
+ flushTable();
1523
+ flush();
1524
+ return groups.join('\n\n');
1004
1525
  }
1005
1526
  //# sourceMappingURL=rich-text-model.js.map