@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
@@ -4,11 +4,38 @@
4
4
  // template, liga os eventos do DOM aos métodos daqui e relê `getState()` a cada `changed()`.
5
5
  import { formatMessage, pluralMessage } from './i18n';
6
6
  import { RICH_TEXT_DELETE_INPUTS, RICH_TEXT_FORMAT_INPUTS, isRichTextButtonTool, isRichTextPlainPasteKey, isRichTextToolAllowed, matchRichTextShortcut, richTextToolLabel, richTextToolStates, runRichTextCommand, } from './rich-text-commands';
7
- import { RichTextSurface } from './rich-text-dom';
7
+ import { isRtl } from './direction';
8
+ import { isRichTextVariableKnown, isRichTextVariableName, richTextGroupVariableOptions, richTextVariableLabel, richTextVariableText, richTextVariableOptions, richTextVariableSyntaxOr, rtAtomizeState, rtCodeHasVariables, rtDocVariables, rtReplaceAtom, rtSingleLine, } from './rich-text-atoms';
9
+ import { renderIconSvg } from '@trismegisto/icons';
10
+ import { RICH_TEXT_ATOM_ATTR, RichTextSurface, rtAtomElement, rtWithoutCaretSupport } from './rich-text-dom';
8
11
  import { historyBreak, historyRecord, historyRedo, historyUndo, richTextHistory } from './rich-text-history';
9
- import { rtBlock, rtBlockText, rtClampPos, rtCollapsed, rtDeleteBackward, rtDeleteForward, rtDeleteRange, rtDeleteSelection, rtDocEnd, rtEmptyDoc, rtExitAtEnd, rtInsertFragment, rtInsertLineBreak, rtInsertText, rtIsBlank, rtIsCollapsed, rtMapThroughDelete, rtPlainText, rtRemoveLink, rtRun, rtSameSelection, rtSelectionFrom, rtSelectionInfo, rtSelectionTo, rtSerialize, rtSetLink, rtSliceDoc, rtSplitBlock, rtTextToDoc, rtTranspose, } from './rich-text-model';
10
- import { normalizeRichTextUrl, richTextFromDom, richTextParseHtml } from './rich-text-sanitize';
12
+ import { richTextSerialize, richTextToPlainText, rtAtomAt, rtAtomText, rtBlock, rtBlockText, rtClampPos, rtCollapsed, rtDeleteBackward, rtDeleteForward, rtDeleteRange, rtDeleteSelection, rtDocEnd, rtEmptyDoc, rtExitAtEnd, rtInsertAtom, rtInsertFragment, rtInsertLineBreak, rtInsertText, rtIsBlank, rtIsCollapsed, rtMapThroughDelete, rtPlainText, rtRemoveLink, rtRun, rtSameSelection, rtSelectionFrom, rtSelectionInfo, rtSelectionTo, rtSelectedAtom, rtSerialize, rtSetLink, rtSliceDoc, rtSplitBlock, rtTextToDoc, rtTranspose, RT_TABLE_MAX_COLS, RT_TABLE_MAX_ROWS, } from './rich-text-model';
13
+ import { normalizeRichTextUrl, normalizeRichTextVariableUrl, richTextFromDom, richTextParseHtml } from './rich-text-sanitize';
14
+ import { richTextFromMarkdown, richTextLooksLikeMarkdown, richTextToMarkdown } from './rich-text-markdown';
15
+ import { rtMarkdownBlockShortcut, rtMarkdownInlineShortcut } from './rich-text-markdown-shortcuts';
16
+ import { richTextCleanPaste } from './rich-text-paste';
17
+ import { historyResolvePendingImage, normalizeRichTextImageUrl, richTextImageFileProblem, richTextImageId, richTextImageSize, rtImageOf, rtInsertImage, rtPendingImages, rtResolvePendingImage, RICH_TEXT_IMAGE_ACCEPT, RICH_TEXT_IMAGE_MAX_BYTES, } from './rich-text-image';
18
+ import { richTextCommandSuggestions, richTextMentionSuggestions, richTextSameSuggestion, richTextSuggestMove, richTextSuggestQuery, rtRemoveSuggestQuery, } from './rich-text-suggest';
19
+ import { RT_BOLD, RT_CODE, RT_ITALIC, RT_STRIKE, RT_UNDERLINE } from './rich-text-schema';
11
20
  import { detectShortcutPlatform } from './shortcuts';
21
+ import { rtCellAt, rtCellIndex, rtCellSelectionBlocks, rtCellSelectionFromText, rtCellHorizontal, rtCellVertical, rtCellsFragment, rtCellsToTsv, rtClearCells, rtExitTable, rtFragmentGrid, rtInsertTable, rtLooksLikeTsv, rtMoveToCell, rtParseTsv, rtPasteCells, rtTableCommand, rtTableCommandDeletesTable, rtTableCommandEnabled, rtTableFromValues, rtTextCells, rtToggleMarkCells, RICH_TEXT_TABLE_COMMANDS, RT_TABLE_DEFAULT_COLS, RT_TABLE_DEFAULT_ROWS, } from './rich-text-table';
22
+ const CLOSED_ALT = { open: false, alt: '', decorative: false };
23
+ const CLOSED_FLOATING = { open: false, anchor: null };
24
+ /** Tamanho máximo de texto puro colado (1 MB): acima disso a colagem é recusada. */
25
+ export const RICH_TEXT_PASTE_MAX_TEXT = 1024 * 1024;
26
+ const CLOSED_SUGGEST = { open: false, kind: null, query: '', items: [], active: -1, loading: false, error: false, anchor: null, status: '' };
27
+ /** Estado do botão de tabela: fora de tabela ele insere; dentro, vira o menu da tabela. */
28
+ export function richTextEditorTableMenu(state) {
29
+ const base = { doc: state.doc, selection: state.selection, stored: state.stored };
30
+ const inTable = !!rtCellAt(state.doc, state.selection.focus);
31
+ return {
32
+ inTable,
33
+ items: inTable
34
+ ? RICH_TEXT_TABLE_COMMANDS.map((command) => ({ command, enabled: rtTableCommandEnabled(base, command), deletesTable: rtTableCommandDeletesTable(base, command) }))
35
+ : [],
36
+ };
37
+ }
38
+ const CLOSED_PICKER = { open: false, query: '', options: [], active: -1, replacing: null };
12
39
  const CLOSED_LINK = { open: false, url: '', text: '', error: '', editing: false, withText: false, href: null };
13
40
  /** Informação de seleção e estado dos botões da barra, a partir do estado do controlador. */
14
41
  export function richTextEditorToolStates(state, disabled, text) {
@@ -29,6 +56,33 @@ export function richTextEditorInfo(state) {
29
56
  export function richTextEditorBlank(state, value) {
30
57
  return state.ready ? rtIsBlank(state.doc) : !value;
31
58
  }
59
+ /** O texto tem alguma variável pela sintaxe (para dizer por que um endereço foi recusado). */
60
+ function rtDocVariablesInText(text, syntax) {
61
+ const open = text.indexOf(syntax.open);
62
+ return open >= 0 && text.indexOf(syntax.close, open) > open;
63
+ }
64
+ let alertSvg;
65
+ /** Ícone de alerta da pílula inválida, do catálogo de ícones (desenho próprio), num documento inerte. */
66
+ function alertIcon(document) {
67
+ if (alertSvg === undefined) {
68
+ try {
69
+ alertSvg = renderIconSvg('exclamation-triangle');
70
+ }
71
+ catch {
72
+ alertSvg = null;
73
+ }
74
+ }
75
+ if (!alertSvg || typeof DOMParser === 'undefined')
76
+ return null;
77
+ const parsed = new DOMParser().parseFromString(alertSvg, 'image/svg+xml').documentElement;
78
+ if (!parsed || parsed.localName !== 'svg')
79
+ return null;
80
+ const icon = document.importNode(parsed, true);
81
+ icon.setAttribute('aria-hidden', 'true');
82
+ icon.setAttribute('focusable', 'false');
83
+ icon.setAttribute('class', 'hm-rich-text__atom-alert');
84
+ return icon;
85
+ }
32
86
  function pickKeys(event) {
33
87
  return { key: event.key, code: event.code, ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey };
34
88
  }
@@ -48,7 +102,31 @@ export class RichTextEditor {
48
102
  #ready = false;
49
103
  #announcement = '';
50
104
  #link = CLOSED_LINK;
105
+ #picker = CLOSED_PICKER;
106
+ #pickerTarget = null;
107
+ #pickerSelection = null;
108
+ #suggest = CLOSED_SUGGEST;
109
+ #floating = CLOSED_FLOATING;
110
+ #imageAlt = CLOSED_ALT;
111
+ #altTarget = null;
112
+ /** Envios pendentes que o editor conhece (id → prévia local `blob:` e progresso). */
113
+ #pending = new Map();
114
+ #altAsked = new Set();
115
+ #pendingVersion = 0;
116
+ #floatingTimer = null;
117
+ #pointerSelecting = false;
118
+ #lastKeyAt = 0;
119
+ #suggestQuery = null;
120
+ #dismissed = null;
121
+ #remoteId = 0;
122
+ #remoteTimer = null;
123
+ #remoteTimeout = null;
124
+ #statusTimer = null;
125
+ #remoteItems = null;
51
126
  #state = null;
127
+ #atomKey = [];
128
+ #lastVariables = null;
129
+ #lastPlain = null;
52
130
  #surface = null;
53
131
  #observer = null;
54
132
  #document = null;
@@ -81,6 +159,13 @@ export class RichTextEditor {
81
159
  ready: this.#ready,
82
160
  announcement: this.#announcement,
83
161
  link: this.#link,
162
+ variablePicker: this.#picker,
163
+ suggest: this.#suggest,
164
+ floating: this.#floating,
165
+ imageAlt: this.#imageAlt,
166
+ pendingImages: this.#pending.size,
167
+ // Antes da montagem não há opções lidas (a casca ainda está construindo os campos dela).
168
+ cells: this.#surface ? this.#cellsOf() : null,
84
169
  };
85
170
  return this.#state;
86
171
  }
@@ -89,9 +174,370 @@ export class RichTextEditor {
89
174
  return this.#surface?.root ?? null;
90
175
  }
91
176
  #changed() {
177
+ this.#evaluateSuggest();
178
+ this.#evaluateFloating();
92
179
  this.#state = null;
180
+ this.#surface?.markSelectedAtom(rtSelectedAtom({ doc: this.#doc, selection: this.#selection }));
181
+ if (this.#surface) {
182
+ const cells = this.#cellsOf();
183
+ this.#surface.markSelectedCells(cells ? rtCellSelectionBlocks(this.#doc, cells) : []);
184
+ this.#trackCell();
185
+ }
93
186
  this.host.changed();
94
187
  }
188
+ // ── tabela ───────────────────────────────────────────────────────────────────────────────────
189
+ /** Célula do último anúncio de posição (`tabela:linha:coluna`) e a tabela em que o cursor entrou. */
190
+ #lastCell = null;
191
+ #lastTable = null;
192
+ #cellTimer = null;
193
+ /** Seleção de células: a seleção atual cruza células da mesma tabela (só com a ferramenta `table`). */
194
+ #cellsOf() {
195
+ if (!this.#opts().schema.table)
196
+ return null;
197
+ return rtCellSelectionFromText(this.#doc, this.#selection.anchor, this.#selection.focus);
198
+ }
199
+ /**
200
+ * Ao mudar de célula, anuncia a posição ("Tabela, linha 2 de 4, coluna 1 de 3") 300 ms depois; ao entrar numa tabela,
201
+ * junta a dica de teclado (uma vez por entrada).
202
+ */
203
+ #trackCell() {
204
+ const t = this.#opts().extraText;
205
+ const at = this.#surface ? rtCellAt(this.#doc, this.#selection.focus) : null;
206
+ const key = at ? `${at.table.start}:${at.row}:${at.col}` : null;
207
+ if (key === this.#lastCell)
208
+ return;
209
+ this.#lastCell = key;
210
+ if (this.#cellTimer)
211
+ clearTimeout(this.#cellTimer);
212
+ this.#cellTimer = null;
213
+ if (!at) {
214
+ this.#lastTable = null;
215
+ return;
216
+ }
217
+ const entering = this.#lastTable !== at.table.start;
218
+ this.#lastTable = at.table.start;
219
+ if (!t || !this.#areaFocused())
220
+ return;
221
+ const message = formatMessage(t.tablePosition, { row: at.row + 1, rows: at.table.rows, col: at.col + 1, cols: at.table.cols });
222
+ const hint = formatMessage(t.tableHint, { mod: this.#platform === 'mac' ? '⌘' : 'Ctrl' });
223
+ this.#cellTimer = setTimeout(() => {
224
+ this.#cellTimer = null;
225
+ this.#announce(entering ? `${message}. ${hint}` : message);
226
+ }, 300);
227
+ }
228
+ #setSelection(selection) {
229
+ this.#selection = selection;
230
+ this.#stored = null;
231
+ this.#history = historyBreak(this.#history);
232
+ this.#writeSelection(selection);
233
+ this.#changed();
234
+ }
235
+ /**
236
+ * Insere uma tabela `rows` × `cols` (padrão 3 × 3, com cabeçalho) no cursor: no lugar do parágrafo vazio, ou depois do
237
+ * bloco atual; o cursor vai para a primeira célula. Recusa (com anúncio) dentro de outra tabela ou além dos limites.
238
+ */
239
+ insertTable(rows = RT_TABLE_DEFAULT_ROWS, cols = RT_TABLE_DEFAULT_COLS, header = true) {
240
+ if (!this.#editable() || !this.#opts().schema.table)
241
+ return false;
242
+ const t = this.#opts().extraText;
243
+ const next = rtInsertTable(this.#current(), rows, cols, header);
244
+ if (!next) {
245
+ if (t)
246
+ this.#announce(formatMessage(t.tableLimit, { rows: RT_TABLE_MAX_ROWS, cols: RT_TABLE_MAX_COLS }));
247
+ return false;
248
+ }
249
+ this.#history = historyBreak(this.#history);
250
+ this.#apply(next);
251
+ this.#history = historyBreak(this.#history);
252
+ this.#focusArea();
253
+ if (t)
254
+ this.#announce(formatMessage(t.tableInserted, { rows, cols }));
255
+ return true;
256
+ }
257
+ /** Comando do menu da tabela na célula do cursor (cada um é um passo de desfazer), com o anúncio do efeito. */
258
+ tableCommand(command) {
259
+ if (!this.#editable())
260
+ return false;
261
+ const state = this.#current();
262
+ const deletes = rtTableCommandDeletesTable(state, command);
263
+ const header = rtCellAt(state.doc, state.selection.focus)?.table.header;
264
+ const next = rtTableCommand(state, command);
265
+ if (!next)
266
+ return false;
267
+ this.#history = historyBreak(this.#history);
268
+ this.#apply(next);
269
+ this.#history = historyBreak(this.#history);
270
+ this.#focusArea();
271
+ const t = this.#opts().extraText;
272
+ if (!t)
273
+ return true;
274
+ const messages = {
275
+ rowAbove: t.rowInsertedAbove,
276
+ rowBelow: t.rowInsertedBelow,
277
+ colLeft: t.colInsertedLeft,
278
+ colRight: t.colInsertedRight,
279
+ deleteRow: t.rowDeleted,
280
+ deleteCol: t.colDeleted,
281
+ toggleHeader: header ? t.headerOff : t.headerOn,
282
+ deleteTable: t.tableDeleted,
283
+ };
284
+ this.#announce(deletes ? t.tableDeleted : messages[command]);
285
+ return true;
286
+ }
287
+ /** O cursor está na primeira (↑) ou na última (↓) linha visual da célula. */
288
+ #caretOnEdgeLine(direction, state) {
289
+ const pos = state.selection.focus;
290
+ const text = rtBlockText(state.doc[pos.block]);
291
+ if (direction === 'up' ? text.slice(0, pos.offset).includes('\n') : text.slice(pos.offset).includes('\n'))
292
+ return false;
293
+ // Linha quebrada pela largura da célula: confere a geometria do cursor quando o navegador a dá.
294
+ const leaf = this.#surface?.leaves[pos.block];
295
+ const selection = this.#domSelection();
296
+ if (!leaf || !selection?.rangeCount)
297
+ return true;
298
+ const rect = selection.getRangeAt(0).getClientRects?.()[0];
299
+ if (!rect || !rect.height)
300
+ return true;
301
+ const box = leaf.getBoundingClientRect();
302
+ return direction === 'up' ? rect.top - box.top < rect.height : box.bottom - rect.bottom < rect.height;
303
+ }
304
+ /**
305
+ * Teclas na tabela: Tab/Shift+Tab entre células (Tab na última cria linha), setas atravessando a borda da célula e
306
+ * saindo da tabela, Shift+setas passando para a seleção de células, Mod+Enter saindo, Esc recolhendo a seleção de
307
+ * células.
308
+ */
309
+ #tableKeydown(event) {
310
+ if (!this.#opts().schema.table)
311
+ return false;
312
+ const key = event.key;
313
+ const mod = event.ctrlKey || event.metaKey;
314
+ if (key !== 'Tab' && key !== 'Enter' && key !== 'Escape' && !key.startsWith('Arrow'))
315
+ return false;
316
+ const state = this.#current();
317
+ const at = rtCellAt(state.doc, state.selection.focus);
318
+ if (!at)
319
+ return false;
320
+ const cells = this.#cellsOf();
321
+ const t = this.#opts().extraText;
322
+ if (key === 'Tab') {
323
+ if (mod || event.altKey)
324
+ return false;
325
+ event.preventDefault();
326
+ const next = rtMoveToCell(state, event.shiftKey ? 'prev' : 'next');
327
+ if (!next || next === state)
328
+ return true;
329
+ const grew = next.doc !== state.doc;
330
+ if (grew)
331
+ this.#history = historyBreak(this.#history);
332
+ this.#apply(next);
333
+ if (grew) {
334
+ this.#history = historyBreak(this.#history);
335
+ if (t)
336
+ this.#announce(t.rowInsertedBelow);
337
+ }
338
+ return true;
339
+ }
340
+ if (key === 'Enter') {
341
+ if (!mod || event.altKey || event.shiftKey)
342
+ return false;
343
+ event.preventDefault();
344
+ const next = rtExitTable(state, 'after', true);
345
+ if (next)
346
+ this.#apply(next);
347
+ return true;
348
+ }
349
+ if (key === 'Escape') {
350
+ if (!cells)
351
+ return false;
352
+ event.preventDefault();
353
+ this.#setSelection(rtCollapsed({ block: state.selection.focus.block, offset: 0 }));
354
+ return true;
355
+ }
356
+ if (mod || event.altKey)
357
+ return false;
358
+ const forward = (key === 'ArrowRight') !== isRtl(this.root);
359
+ const vertical = key === 'ArrowUp' || key === 'ArrowDown';
360
+ if (event.shiftKey) {
361
+ // Shift+setas cruzando a borda da célula: seleção de células (o retângulo entre a célula da âncora e a do foco).
362
+ const focus = state.selection.focus;
363
+ const text = rtBlockText(state.doc[focus.block]);
364
+ const crossing = !!cells ||
365
+ (key === 'ArrowUp'
366
+ ? !text.slice(0, focus.offset).includes('\n')
367
+ : key === 'ArrowDown'
368
+ ? !text.slice(focus.offset).includes('\n')
369
+ : forward
370
+ ? focus.offset >= text.length
371
+ : focus.offset <= 0);
372
+ if (!crossing)
373
+ return false;
374
+ const row = at.row + (key === 'ArrowUp' ? -1 : key === 'ArrowDown' ? 1 : 0);
375
+ const col = at.col + (vertical ? 0 : forward ? 1 : -1);
376
+ if (row < 0 || row >= at.table.rows || col < 0 || col >= at.table.cols) {
377
+ if (!cells)
378
+ return false;
379
+ event.preventDefault();
380
+ return true;
381
+ }
382
+ event.preventDefault();
383
+ const index = rtCellIndex(at.table, row, col);
384
+ const anchor = cells ? state.selection.anchor : { block: focus.block, offset: 0 };
385
+ this.#setSelection({ anchor, focus: { block: index, offset: 0 } });
386
+ const selected = this.#cellsOf();
387
+ if (t && selected)
388
+ this.#announce(pluralMessage(t.cellsSelected, rtCellSelectionBlocks(this.#doc, selected).length, this.#opts().locale ?? 'pt-BR'));
389
+ return true;
390
+ }
391
+ if (!rtIsCollapsed(state.selection))
392
+ return false;
393
+ let next;
394
+ if (vertical) {
395
+ const direction = key === 'ArrowUp' ? 'up' : 'down';
396
+ if (!this.#caretOnEdgeLine(direction, state))
397
+ return false;
398
+ next = rtCellVertical(state, direction);
399
+ }
400
+ else
401
+ next = rtCellHorizontal(state, forward ? 'forward' : 'backward');
402
+ if (!next)
403
+ return false;
404
+ event.preventDefault();
405
+ if (next.doc === state.doc)
406
+ this.#setSelection(next.selection);
407
+ else
408
+ this.#apply(next);
409
+ return true;
410
+ }
411
+ // ── variáveis e átomos ───────────────────────────────────────────────────────────────────────
412
+ #variablesOn() {
413
+ return !!this.#opts().schema.variables;
414
+ }
415
+ #syntax() {
416
+ const o = this.#opts();
417
+ return richTextVariableSyntaxOr(o.variableSyntax ?? o.schema.variableSyntax);
418
+ }
419
+ /** Desenho da pílula pelas entradas atuais (rótulo, texto falado, estado inválido). */
420
+ #atomRenderer() {
421
+ const o = this.#opts();
422
+ const variables = o.variables ?? null;
423
+ const mode = o.variableMode ?? 'closed';
424
+ const display = o.variableDisplay ?? 'label';
425
+ const syntax = this.#syntax();
426
+ const t = o.extraText;
427
+ return (document, atom) => {
428
+ const element = rtAtomElement(document, atom);
429
+ let visible;
430
+ let spoken;
431
+ let invalid = false;
432
+ if (atom.kind === 'image')
433
+ return this.#renderImage(document, element, atom);
434
+ if (atom.kind === 'variable') {
435
+ const label = richTextVariableLabel(atom.name, variables);
436
+ // Descrição da lista como dica nativa: apoio, nunca o essencial (o rótulo já está na pílula).
437
+ const description = variables?.find((v) => v.name === atom.name)?.description;
438
+ if (description)
439
+ element.title = description;
440
+ visible = display === 'name' ? atom.name : display === 'syntax' ? rtAtomText(atom, syntax) : label;
441
+ invalid = !isRichTextVariableKnown(atom.name, variables, mode);
442
+ spoken = t ? formatMessage(invalid ? t.variableUnknownSpoken : t.variableSpoken, { label, name: atom.name }) : visible;
443
+ }
444
+ else {
445
+ visible = `@${atom.label}`;
446
+ spoken = visible;
447
+ }
448
+ if (invalid) {
449
+ element.classList.add('hm-rich-text__atom--invalid');
450
+ const icon = alertIcon(document);
451
+ if (icon)
452
+ element.appendChild(icon);
453
+ }
454
+ const hidden = document.createElement('span');
455
+ hidden.className = 'hm-visually-hidden';
456
+ hidden.textContent = spoken;
457
+ const shown = document.createElement('span');
458
+ shown.className = 'hm-rich-text__atom-label';
459
+ shown.setAttribute('aria-hidden', 'true');
460
+ shown.textContent = visible;
461
+ element.append(hidden, shown);
462
+ return element;
463
+ };
464
+ }
465
+ /** O desenho dos átomos depende de entradas que mudam (lista, modo, exibição, idioma): troca quando mudam. */
466
+ #syncAtomRenderer() {
467
+ const surface = this.#surface;
468
+ if (!surface)
469
+ return false;
470
+ const o = this.#opts();
471
+ const key = [o.variables ?? null, o.variableMode, o.variableDisplay, o.variableSyntax, o.extraText, this.#pendingVersion];
472
+ if (key.length === this.#atomKey.length && key.every((value, i) => value === this.#atomKey[i]))
473
+ return false;
474
+ this.#atomKey = key;
475
+ surface.setAtomRenderer(this.#atomRenderer());
476
+ return true;
477
+ }
478
+ /** As entradas das variáveis mudaram (lista, modo, exibição, textos): redesenha as pílulas, sem mexer no histórico. */
479
+ refresh() {
480
+ if (!this.#surface || !this.#syncAtomRenderer())
481
+ return;
482
+ this.#render();
483
+ if (this.#areaFocused())
484
+ this.#writeSelection(this.#selection);
485
+ this.#changed();
486
+ }
487
+ /** Faixa de aviso nos blocos de código com sintaxe de variável (atributo lido pelo CSS; fora do texto do bloco). */
488
+ #syncCodeNotes() {
489
+ const surface = this.#surface;
490
+ if (!surface)
491
+ return;
492
+ const on = this.#variablesOn();
493
+ const syntax = this.#syntax();
494
+ const note = this.#opts().extraText?.variableInCode ?? '';
495
+ this.#doc.forEach((block, i) => {
496
+ const leaf = surface.leaves[i];
497
+ if (!leaf || block.type !== 'code')
498
+ return;
499
+ if (on && note && rtCodeHasVariables(block, syntax))
500
+ leaf.setAttribute('data-hm-note', note);
501
+ else
502
+ leaf.removeAttribute('data-hm-note');
503
+ });
504
+ }
505
+ /**
506
+ * Conversão automática depois de uma mudança: o texto que casa com a sintaxe vira variável. É um passo de histórico
507
+ * próprio, logo depois do passo da digitação (desfazer devolve o literal digitado).
508
+ */
509
+ #autoConvert() {
510
+ if (!this.#variablesOn())
511
+ return false;
512
+ const state = this.#current0();
513
+ const next = rtAtomizeState(state, this.#syntax());
514
+ if (next === state)
515
+ return false;
516
+ this.#history = historyRecord(this.#history, this.#snapshot(), 'other', Date.now());
517
+ this.#history = historyBreak(this.#history);
518
+ this.#doc = next.doc;
519
+ this.#selection = next.selection;
520
+ this.#render();
521
+ if (this.#areaFocused())
522
+ this.#writeSelection(next.selection);
523
+ return true;
524
+ }
525
+ /** Insere a variável no cursor (troca a seleção, se houver) e devolve o foco à área com o cursor depois dela. */
526
+ insertVariable(name) {
527
+ if (!isRichTextVariableName(name)) {
528
+ if (this.host.devMode?.())
529
+ console.warn('[hermes-rich-text] Nome de variável fora da regra; nada foi inserido:', name);
530
+ return;
531
+ }
532
+ if (!this.#editable() || !this.#surface || !this.#variablesOn())
533
+ return;
534
+ const state = this.#areaFocused() ? this.#current() : this.#current0();
535
+ this.#apply(rtInsertAtom(state, { kind: 'variable', name }, this.#syntax()));
536
+ const t = this.#opts().extraText;
537
+ if (t)
538
+ this.#announce(formatMessage(t.variableInserted, { label: richTextVariableLabel(name, this.#opts().variables) }));
539
+ this.#focusArea();
540
+ }
95
541
  #opts() {
96
542
  return this.host.options();
97
543
  }
@@ -121,15 +567,19 @@ export class RichTextEditor {
121
567
  }
122
568
  this.#platform = detectShortcutPlatform();
123
569
  this.#docSchema = this.#opts().schema;
570
+ this.#syncAtomRenderer();
124
571
  const pending = this.#pendingValue;
125
572
  this.#pendingValue = null;
126
573
  const value = pending ? pending.value : initial;
127
574
  this.#doc = this.#parse(value);
128
575
  this.#lastValue = typeof value === 'string' ? value : '';
129
576
  this.#surface.render(this.#doc);
577
+ this.#syncCodeNotes();
130
578
  this.#selection = rtCollapsed(rtDocEnd(this.#doc));
131
579
  this.#ready = true;
132
580
  this.syncLinks();
581
+ this.#emitVariables();
582
+ this.#emitPlain();
133
583
  this.#observer?.takeRecords();
134
584
  this.#document.addEventListener('selectionchange', this.#onSelectionChange);
135
585
  // Captura no documento: a dica (tooltip) do botão focado também escuta o Esc ali e o consome.
@@ -138,6 +588,10 @@ export class RichTextEditor {
138
588
  }
139
589
  /** Solta os listeners do documento (o componente saiu da tela). */
140
590
  destroy() {
591
+ this.#clearSuggestTimers();
592
+ if (this.#floatingTimer)
593
+ clearTimeout(this.#floatingTimer);
594
+ this.#document?.removeEventListener('mouseup', this.#onPointerUp, true);
141
595
  this.#observer?.disconnect();
142
596
  this.#document?.removeEventListener('selectionchange', this.#onSelectionChange);
143
597
  this.#document?.removeEventListener('keydown', this.#onDocumentKeydown, true);
@@ -152,7 +606,41 @@ export class RichTextEditor {
152
606
  this.#warnedType = true;
153
607
  return rtEmptyDoc();
154
608
  }
155
- return richTextParseHtml(value, this.#opts().schema);
609
+ const schema = this.#opts().schema;
610
+ if (this.#opts().singleLine) {
611
+ // Linha única: o valor é texto puro com a forma textual das variáveis.
612
+ const doc = rtSingleLine(rtTextToDoc(value));
613
+ return schema.variables ? rtAtomizeState({ doc, selection: rtCollapsed({ block: 0, offset: 0 }), stored: null }, this.#syntax()).doc : doc;
614
+ }
615
+ if (this.#opts().valueFormat === 'markdown')
616
+ return richTextFromMarkdown(value, schema, this.#markdownOptions());
617
+ return richTextParseHtml(value, schema);
618
+ }
619
+ #markdownOptions() {
620
+ return { underline: this.#opts().markdownUnderline ?? 'drop', variableSyntax: this.#syntax() };
621
+ }
622
+ /** Valor do campo a partir do documento, pelo modo (linha única = texto) e perfil. */
623
+ #serializeValue(doc) {
624
+ const o = this.#opts();
625
+ if (o.singleLine)
626
+ return rtPlainText(doc, this.#syntax()).replace(/\n/g, ' ');
627
+ if (o.valueFormat === 'markdown')
628
+ return richTextToMarkdown(doc, this.#markdownOptions()).replace(/\n$/, '');
629
+ const variables = this.#variablesOn();
630
+ const profile = o.outputProfile ?? o.schema.profile ?? 'web';
631
+ if (profile === 'web' && !variables && !o.schema.mentions)
632
+ return rtSerialize(doc);
633
+ return richTextSerialize(doc, { profile, variableSyntax: this.#syntax(), markVariableHrefs: variables });
634
+ }
635
+ #emitVariables() {
636
+ if (!this.host.variablesChange || !this.#variablesOn())
637
+ return;
638
+ const names = rtDocVariables(this.#doc, this.#syntax());
639
+ const last = this.#lastVariables;
640
+ if (last && last.length === names.length && last.every((n, i) => n === names[i]))
641
+ return;
642
+ this.#lastVariables = names;
643
+ this.host.variablesChange(names);
156
644
  }
157
645
  /** Valor do app (formulário ou prop): sanitiza, troca o documento e zera o histórico, sem emitir. */
158
646
  receive(value) {
@@ -178,11 +666,15 @@ export class RichTextEditor {
178
666
  if (this.#areaFocused())
179
667
  this.#writeSelection(end);
180
668
  this.#changed();
669
+ this.#emitVariables();
670
+ this.#emitPlain();
181
671
  }
182
672
  #render() {
183
673
  if (!this.#surface)
184
674
  return;
675
+ this.#syncAtomRenderer();
185
676
  this.#surface.render(this.#doc);
677
+ this.#syncCodeNotes();
186
678
  this.#observer?.takeRecords();
187
679
  this.syncLinks();
188
680
  }
@@ -201,11 +693,24 @@ export class RichTextEditor {
201
693
  this.#observer?.takeRecords();
202
694
  }
203
695
  #emit() {
204
- const html = rtSerialize(this.#doc);
696
+ const html = this.#serializeValue(this.#doc);
697
+ this.#emitVariables();
205
698
  if (html === this.#lastValue)
206
699
  return;
207
700
  this.#lastValue = html;
208
701
  this.host.commit(html);
702
+ this.#emitPlain();
703
+ }
704
+ /** Texto puro do documento, quando mudou (também na montagem e no valor do app, para o app já ter o texto). */
705
+ #emitPlain() {
706
+ if (!this.host.plainTextChange)
707
+ return;
708
+ const o = this.#opts();
709
+ const plain = richTextToPlainText(this.#doc, { layout: o.plainTextLayout ?? 'readable', variableSyntax: this.#syntax() });
710
+ if (plain === this.#lastPlain)
711
+ return;
712
+ this.#lastPlain = plain;
713
+ this.host.plainTextChange(plain);
209
714
  }
210
715
  #snapshot() {
211
716
  return { doc: this.#doc, selection: this.#selection };
@@ -215,6 +720,7 @@ export class RichTextEditor {
215
720
  }
216
721
  /** Aplica um estado novo vindo de um comando: histórico, redesenho, seleção (se a área tem o foco) e valor. */
217
722
  #apply(next, kind = 'other') {
723
+ this.#afterDocChange(next.doc);
218
724
  const before = this.#snapshot();
219
725
  const changed = next.doc !== before.doc;
220
726
  if (changed)
@@ -226,11 +732,14 @@ export class RichTextEditor {
226
732
  this.#render();
227
733
  if (this.#areaFocused())
228
734
  this.#writeSelection(next.selection);
735
+ if (changed)
736
+ this.#autoConvert();
229
737
  this.#changed();
230
738
  if (changed)
231
739
  this.#emit();
232
740
  }
233
741
  #restore(snapshot) {
742
+ this.#afterDocChange(snapshot.doc);
234
743
  this.#doc = snapshot.doc;
235
744
  this.#selection = snapshot.selection;
236
745
  this.#stored = null;
@@ -253,7 +762,7 @@ export class RichTextEditor {
253
762
  if (!this.#surface || this.#docSchema === schema)
254
763
  return;
255
764
  this.#docSchema = schema;
256
- const doc = richTextParseHtml(rtSerialize(this.#doc), schema);
765
+ const doc = this.#opts().singleLine || this.#opts().valueFormat === 'markdown' ? this.#parse(this.#serializeValue(this.#doc)) : richTextParseHtml(rtSerialize(this.#doc), schema);
257
766
  this.#doc = doc;
258
767
  this.#selection = { anchor: rtClampPos(doc, this.#selection.anchor), focus: rtClampPos(doc, this.#selection.focus) };
259
768
  this.#render();
@@ -366,6 +875,14 @@ export class RichTextEditor {
366
875
  this.redo();
367
876
  return null;
368
877
  default: {
878
+ // Células selecionadas: a marca vale para todo o texto delas.
879
+ const cells = this.#cellsOf();
880
+ if (cells && (tool === 'bold' || tool === 'italic' || tool === 'underline' || tool === 'strike' || tool === 'code')) {
881
+ const next = rtToggleMarkCells(state, cells, tool);
882
+ this.#apply(next);
883
+ const bit = { bold: RT_BOLD, italic: RT_ITALIC, underline: RT_UNDERLINE, strike: RT_STRIKE, code: RT_CODE }[tool];
884
+ return rtCellSelectionBlocks(next.doc, cells).some((index) => next.doc[index].runs.some((run) => !run.atom && run.marks & bit));
885
+ }
369
886
  const result = runRichTextCommand(state, tool);
370
887
  this.#apply(result.state);
371
888
  return result.on;
@@ -392,8 +909,16 @@ export class RichTextEditor {
392
909
  #onDocumentKeydown = (event) => {
393
910
  if (event.key !== 'Escape')
394
911
  return;
395
- const bar = this.host.elements().bar;
396
912
  const active = this.#document?.activeElement;
913
+ // Barra flutuante: Esc volta à área com a mesma seleção (antes da dica do botão, que também escuta o Esc).
914
+ const floating = this.host.elements().floatingBar;
915
+ if (floating && active && floating.contains(active)) {
916
+ event.preventDefault();
917
+ event.stopPropagation();
918
+ this.#focusArea();
919
+ return;
920
+ }
921
+ const bar = this.host.elements().bar;
397
922
  if (!bar || !active || !bar.contains(active))
398
923
  return;
399
924
  if (bar.querySelector('[aria-expanded="true"]'))
@@ -442,6 +967,10 @@ export class RichTextEditor {
442
967
  }
443
968
  /** `focusout` no host (e no painel do link). */
444
969
  onFocusOut(event) {
970
+ if (!this.#isInside(event.relatedTarget)) {
971
+ this.#closeSuggest();
972
+ this.#hideFloating(true);
973
+ }
445
974
  if (this.#isInside(event.relatedTarget))
446
975
  return;
447
976
  this.#inside = false;
@@ -461,6 +990,11 @@ export class RichTextEditor {
461
990
  return menuOpen && !!node.closest?.('[role="menu"]');
462
991
  }
463
992
  onAreaPointerDown() {
993
+ if (this.#opts().floatingToolbar && this.#document) {
994
+ this.#pointerSelecting = true;
995
+ this.#hideFloating();
996
+ this.#document.addEventListener('mouseup', this.#onPointerUp, true);
997
+ }
464
998
  this.#pointerFocus = !this.#areaFocused();
465
999
  }
466
1000
  onAreaFocus() {
@@ -487,12 +1021,24 @@ export class RichTextEditor {
487
1021
  return;
488
1022
  const o = this.#opts();
489
1023
  if (event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey && event.key === 'F10') {
1024
+ if (!o.disabled && this.#focusFloating()) {
1025
+ event.preventDefault();
1026
+ return;
1027
+ }
490
1028
  if (o.showToolbar && !o.disabled && this.#focusToolbar())
491
1029
  event.preventDefault();
492
1030
  return;
493
1031
  }
1032
+ this.#lastKeyAt = Date.now();
1033
+ if (event.key === 'Escape' && this.#floating.open && !this.#suggest.open) {
1034
+ event.preventDefault();
1035
+ this.#hideFloating(true);
1036
+ return;
1037
+ }
494
1038
  if (!this.#editable())
495
1039
  return;
1040
+ if (this.#suggestKeydown(event))
1041
+ return;
496
1042
  const platform = this.#platform;
497
1043
  if (isRichTextPlainPasteKey(event, platform)) {
498
1044
  // O navegador cola em seguida (evento `paste`); sem colagem, o pedido expira.
@@ -513,7 +1059,11 @@ export class RichTextEditor {
513
1059
  }
514
1060
  return;
515
1061
  }
516
- if (event.key === 'ArrowDown' && !event.shiftKey && !event.altKey && !event.ctrlKey && !event.metaKey) {
1062
+ if (this.#atomKeydown(event))
1063
+ return;
1064
+ if (this.#tableKeydown(event))
1065
+ return;
1066
+ if (event.key === 'ArrowDown' && !event.shiftKey && !event.altKey && !event.ctrlKey && !event.metaKey && !o.singleLine) {
517
1067
  const next = rtExitAtEnd(this.#current());
518
1068
  if (next) {
519
1069
  event.preventDefault();
@@ -521,6 +1071,51 @@ export class RichTextEditor {
521
1071
  }
522
1072
  }
523
1073
  }
1074
+ /** Teclas junto de um átomo: setas pulam a pílula em um passo; Enter/F2 abre a troca; Esc recolhe a seleção. */
1075
+ #atomKeydown(event) {
1076
+ if (event.ctrlKey || event.metaKey || event.altKey)
1077
+ return false;
1078
+ const key = event.key;
1079
+ if (key !== 'ArrowLeft' && key !== 'ArrowRight' && key !== 'Enter' && key !== 'F2' && key !== 'Escape')
1080
+ return false;
1081
+ const state = this.#current();
1082
+ const selected = rtSelectedAtom(state);
1083
+ if ((key === 'Enter' || key === 'F2') && !event.shiftKey && selected?.atom.kind === 'image' && !selected.atom.pending) {
1084
+ event.preventDefault();
1085
+ this.openImageAlt(selected.block, selected.index);
1086
+ return true;
1087
+ }
1088
+ if ((key === 'Enter' || key === 'F2') && !event.shiftKey) {
1089
+ if (!selected || selected.atom.kind !== 'variable' || !this.#variablesOn() || !this.host.showVariablePopover)
1090
+ return false;
1091
+ event.preventDefault();
1092
+ this.openVariablePicker(selected.atom.name);
1093
+ return true;
1094
+ }
1095
+ if (key === 'Escape') {
1096
+ if (!selected)
1097
+ return false;
1098
+ event.preventDefault();
1099
+ this.#selection = rtCollapsed({ block: selected.block, offset: selected.index + 1 });
1100
+ this.#writeSelection(this.#selection);
1101
+ this.#changed();
1102
+ return true;
1103
+ }
1104
+ const forward = (key === 'ArrowRight') !== isRtl(this.root);
1105
+ const focus = state.selection.focus;
1106
+ if (!event.shiftKey && !rtIsCollapsed(state.selection))
1107
+ return false;
1108
+ const index = forward ? focus.offset : focus.offset - 1;
1109
+ if (!rtAtomAt(state.doc, focus.block, index))
1110
+ return false;
1111
+ event.preventDefault();
1112
+ const moved = { block: focus.block, offset: focus.offset + (forward ? 1 : -1) };
1113
+ this.#selection = event.shiftKey ? { anchor: state.selection.anchor, focus: moved } : rtCollapsed(moved);
1114
+ this.#history = historyBreak(this.#history);
1115
+ this.#writeSelection(this.#selection);
1116
+ this.#changed();
1117
+ return true;
1118
+ }
524
1119
  // ── área: beforeinput / input ────────────────────────────────────────────────────────────────
525
1120
  onBeforeInput(event) {
526
1121
  if (!this.#surface)
@@ -534,14 +1129,32 @@ export class RichTextEditor {
534
1129
  return;
535
1130
  if (!event.cancelable)
536
1131
  return;
1132
+ if (this.#opts().singleLine && (type === 'insertParagraph' || type === 'insertLineBreak')) {
1133
+ event.preventDefault();
1134
+ this.host.submitted?.();
1135
+ return;
1136
+ }
1137
+ if (this.#floating.open && (type.startsWith('insert') || type.startsWith('delete')))
1138
+ this.#hideFloating(true);
1139
+ if ((type === 'insertText' || type === 'insertParagraph') && this.#typeAfterImage(event))
1140
+ return;
1141
+ if (type === 'insertText' && this.#markdownShortcut(event))
1142
+ return;
537
1143
  if (type === 'insertText') {
538
1144
  const state = this.#current();
1145
+ // Digitar com células selecionadas: esvazia as células e escreve na primeira.
1146
+ const cells = this.#cellsOf();
1147
+ if (cells) {
1148
+ event.preventDefault();
1149
+ this.#apply(rtInsertText(rtClearCells(state, cells), this.#lineText(event.data ?? '')), 'typing');
1150
+ return;
1151
+ }
539
1152
  const anchorInLeaf = this.#surface.leafIndexOf(this.#domSelection()?.anchorNode ?? null) >= 0;
540
1153
  // Texto simples com o cursor num bloco fica com o navegador (IME, corretor, teclado virtual).
541
1154
  if (rtIsCollapsed(state.selection) && state.stored === null && anchorInLeaf)
542
1155
  return;
543
1156
  event.preventDefault();
544
- this.#apply(rtInsertText(state, event.data ?? ''), 'typing');
1157
+ this.#apply(rtInsertText(state, this.#lineText(event.data ?? '')), 'typing');
545
1158
  return;
546
1159
  }
547
1160
  const format = RICH_TEXT_FORMAT_INPUTS[type];
@@ -562,10 +1175,18 @@ export class RichTextEditor {
562
1175
  return;
563
1176
  }
564
1177
  switch (type) {
565
- case 'insertParagraph':
1178
+ case 'insertParagraph': {
566
1179
  event.preventDefault();
567
- this.#apply(rtSplitBlock(this.#current()));
1180
+ const state = this.#current();
1181
+ // Três crases + Enter: bloco de código (atalho de Markdown).
1182
+ const fence = this.#opts().markdownShortcuts && !this.#composing ? rtMarkdownBlockShortcut(state, '\n', this.#opts().schema) : null;
1183
+ if (fence) {
1184
+ this.#convertShortcut(state, fence.state, fence.label);
1185
+ return;
1186
+ }
1187
+ this.#apply(rtSplitBlock(state));
568
1188
  return;
1189
+ }
569
1190
  case 'insertLineBreak':
570
1191
  event.preventDefault();
571
1192
  this.#apply(rtInsertLineBreak(this.#current()));
@@ -585,10 +1206,13 @@ export class RichTextEditor {
585
1206
  event.preventDefault();
586
1207
  return;
587
1208
  case 'deleteByCut':
588
- case 'deleteContent':
1209
+ case 'deleteContent': {
589
1210
  event.preventDefault();
590
- this.#apply(rtDeleteSelection(this.#current()));
1211
+ const state = this.#current();
1212
+ const cells = this.#cellsOf();
1213
+ this.#apply(cells ? rtClearCells(state, cells) : rtDeleteSelection(state));
591
1214
  return;
1215
+ }
592
1216
  case 'insertTranspose':
593
1217
  event.preventDefault();
594
1218
  this.#apply(rtTranspose(this.#current()));
@@ -609,10 +1233,73 @@ export class RichTextEditor {
609
1233
  event.preventDefault();
610
1234
  }
611
1235
  }
1236
+ /**
1237
+ * Atalhos de Markdown ao digitar: o caractere que dispara entra no passo da digitação e a conversão abre um passo
1238
+ * próprio (desfazer logo depois devolve o literal). Nunca dentro de código nem durante composição.
1239
+ */
1240
+ #markdownShortcut(event) {
1241
+ const o = this.#opts();
1242
+ if (!o.markdownShortcuts || o.singleLine || this.#composing || event.isComposing)
1243
+ return false;
1244
+ const data = event.data ?? '';
1245
+ if (data !== ' ' && data !== '*' && data !== '_' && data !== '`' && data !== '~')
1246
+ return false;
1247
+ const state = this.#current();
1248
+ if (!rtIsCollapsed(state.selection))
1249
+ return false;
1250
+ const typed = rtInsertText(state, data);
1251
+ const converted = data === ' ' ? rtMarkdownBlockShortcut(typed, ' ', o.schema) : rtMarkdownInlineShortcut(typed, o.schema);
1252
+ if (!converted)
1253
+ return false;
1254
+ event.preventDefault();
1255
+ this.#apply(typed, 'typing');
1256
+ this.#convertShortcut(this.#current0(), converted.state, converted.label);
1257
+ return true;
1258
+ }
1259
+ #convertShortcut(before, next, label) {
1260
+ this.#history = historyBreak(this.#history);
1261
+ this.#doc = before.doc;
1262
+ this.#selection = before.selection;
1263
+ this.#apply(next);
1264
+ this.#history = historyBreak(this.#history);
1265
+ const t = this.#opts().extraText;
1266
+ if (t)
1267
+ this.#announce(formatMessage(t.markdownApplied, { format: this.#shortcutLabel(label) }));
1268
+ }
1269
+ /** Nome do formato aplicado pelo atalho, nos textos do campo. */
1270
+ #shortcutLabel(label) {
1271
+ const t = this.#opts().text;
1272
+ if (label.startsWith('heading'))
1273
+ return formatMessage(t.heading, { level: label.slice(7) });
1274
+ return t[label] ?? label;
1275
+ }
612
1276
  #delete(event, unit, direction) {
613
1277
  const state = this.#current();
614
1278
  const surface = this.#surface;
1279
+ // Backspace/Delete com células selecionadas: esvazia as células (a estrutura fica).
1280
+ const cells = this.#cellsOf();
1281
+ if (cells) {
1282
+ this.#apply(rtClearCells(state, cells));
1283
+ const t = this.#opts().extraText;
1284
+ if (t)
1285
+ this.#announce(t.cellsCleared);
1286
+ return;
1287
+ }
615
1288
  const sel = state.selection;
1289
+ if (rtIsCollapsed(sel) && unit === 'char' && (this.#opts().variableDeleteMode ?? 'select') === 'select') {
1290
+ // Primeiro toque seleciona a pílula (realce e anúncio); o segundo apaga.
1291
+ const pos = sel.focus;
1292
+ const index = direction === 'backward' ? pos.offset - 1 : pos.offset;
1293
+ const atom = rtAtomAt(state.doc, pos.block, index);
1294
+ if (atom) {
1295
+ this.#selection = { anchor: { block: pos.block, offset: index }, focus: { block: pos.block, offset: index + 1 } };
1296
+ this.#history = historyBreak(this.#history);
1297
+ this.#writeSelection(this.#selection);
1298
+ this.#changed();
1299
+ this.#announceAtom(atom, 'selected');
1300
+ return;
1301
+ }
1302
+ }
616
1303
  if (rtIsCollapsed(sel)) {
617
1304
  const pos = sel.focus;
618
1305
  const block = state.doc[pos.block];
@@ -631,6 +1318,21 @@ export class RichTextEditor {
631
1318
  }
632
1319
  this.#apply(direction === 'backward' ? rtDeleteBackward(state, unit) : rtDeleteForward(state, unit));
633
1320
  }
1321
+ #announceAtom(atom, what) {
1322
+ const t = this.#opts().extraText;
1323
+ if (!t || what !== 'selected')
1324
+ return;
1325
+ if (atom.kind === 'image') {
1326
+ this.#announce(atom.alt || (atom.decorative ? '' : t.imageNoAlt));
1327
+ return;
1328
+ }
1329
+ const label = atom.kind === 'variable' ? richTextVariableLabel(atom.name, this.#opts().variables) : `@${atom.label}`;
1330
+ this.#announce(formatMessage(t.variableSelected, { label }));
1331
+ }
1332
+ /** Linha única: quebras e tabulações viram espaço. */
1333
+ #lineText(text) {
1334
+ return this.#opts().singleLine ? text.replace(/[\r\n\t]+/g, ' ') : text;
1335
+ }
634
1336
  onInput(event) {
635
1337
  if (this.#composing || event.isComposing)
636
1338
  return;
@@ -664,13 +1366,14 @@ export class RichTextEditor {
664
1366
  const records = this.#observer?.takeRecords() ?? [];
665
1367
  if (!surface.isIntact(doc)) {
666
1368
  const rough = surface.roughPos(selection?.focusNode ?? null, selection?.focusOffset ?? 0);
667
- const next = richTextFromDom(surface.root, schema, 'readback');
1369
+ const next = richTextFromDom(rtWithoutCaretSupport(surface.root), schema, 'readback');
668
1370
  const pos = rtClampPos(next, rough ?? rtDocEnd(next));
669
1371
  this.#history = historyRecord(this.#history, before, 'other', Date.now());
670
1372
  this.#doc = next;
671
1373
  this.#selection = rtCollapsed(pos);
672
1374
  this.#render();
673
1375
  this.#writeSelection(rtCollapsed(pos));
1376
+ this.#autoConvert();
674
1377
  this.#changed();
675
1378
  this.#emit();
676
1379
  return;
@@ -715,6 +1418,10 @@ export class RichTextEditor {
715
1418
  this.syncLinks();
716
1419
  this.#writeSelection(read);
717
1420
  }
1421
+ if (changed) {
1422
+ this.#syncCodeNotes();
1423
+ this.#autoConvert();
1424
+ }
718
1425
  this.#changed();
719
1426
  if (changed)
720
1427
  this.#emit();
@@ -732,12 +1439,36 @@ export class RichTextEditor {
732
1439
  const schema = this.#opts().schema;
733
1440
  const html = plain ? '' : data.getData('text/html');
734
1441
  const text = data.getData('text/plain');
1442
+ if (this.#opts().singleLine) {
1443
+ const source = html.trim() ? richTextParseHtml(html, schema) : text ? rtTextToDoc(text) : null;
1444
+ return source ? rtSingleLine(source) : null;
1445
+ }
735
1446
  if (intoCode) {
736
- const literal = text || (html ? rtPlainText(richTextParseHtml(html, schema)) : '');
1447
+ const literal = text || (html ? rtPlainText(richTextParseHtml(html, schema), this.#syntax()) : '');
737
1448
  return literal ? [rtBlock('code', [rtRun(literal.replace(/\r\n?/g, '\n'))])] : null;
738
1449
  }
739
- if (html.trim())
740
- return richTextParseHtml(html, schema);
1450
+ if (html.trim()) {
1451
+ const cleaned = richTextCleanPaste(html, text, schema);
1452
+ const t = this.#opts().extraText;
1453
+ if (cleaned.tooLarge) {
1454
+ if (t)
1455
+ this.#announce(t.pasteTooLarge);
1456
+ }
1457
+ else if (cleaned.removed.length) {
1458
+ this.host.pasteCleaned?.({ removed: cleaned.removed });
1459
+ if (t)
1460
+ this.#announce(t.pastedSimplified);
1461
+ }
1462
+ return cleaned.doc;
1463
+ }
1464
+ if (text.length > RICH_TEXT_PASTE_MAX_TEXT) {
1465
+ const t = this.#opts().extraText;
1466
+ if (t)
1467
+ this.#announce(t.pasteRefused);
1468
+ return null;
1469
+ }
1470
+ if (text && !plain && this.#opts().pasteMarkdown === 'plain' && richTextLooksLikeMarkdown(text))
1471
+ return richTextFromMarkdown(text, schema, this.#markdownOptions());
741
1472
  if (text)
742
1473
  return rtTextToDoc(text);
743
1474
  // Só arquivos (imagem etc.): ignorados.
@@ -746,6 +1477,8 @@ export class RichTextEditor {
746
1477
  #paste(data, plain) {
747
1478
  if (!data)
748
1479
  return;
1480
+ if (this.#imageFiles(data, 'paste'))
1481
+ return;
749
1482
  const state = this.#current();
750
1483
  const text = data.getData('text/plain').trim();
751
1484
  if (!rtIsCollapsed(state.selection) && text && !/\s/.test(text) && this.#opts().tools.includes('link') && !this.#toolDisabled('link')) {
@@ -757,8 +1490,35 @@ export class RichTextEditor {
757
1490
  }
758
1491
  const intoCode = state.doc[rtSelectionFrom(state.selection).block].type === 'code';
759
1492
  const fragment = this.#fragment(data, plain, intoCode);
1493
+ const o = this.#opts();
1494
+ let target = state;
1495
+ if (o.schema.table && !o.singleLine) {
1496
+ const raw = data.getData('text/plain');
1497
+ const html = plain ? '' : data.getData('text/html');
1498
+ const cells = this.#cellsOf();
1499
+ const first = cells ? rtCellSelectionBlocks(state.doc, cells)[0] : null;
1500
+ const at = first !== null && first !== undefined ? { ...state, selection: rtCollapsed({ block: first, offset: 0 }) } : state;
1501
+ if (state.doc[rtSelectionFrom(at.selection).block]?.cell) {
1502
+ // Na célula: tabela colada (HTML) ou valores com tabulação preenchem a partir dela, criando o que faltar.
1503
+ const grid = fragment?.some((block) => block.cell) ? rtFragmentGrid(fragment) : !plain && !html.trim() ? rtTextCells(raw) : null;
1504
+ const pasted = grid ? rtPasteCells(at, grid) : null;
1505
+ if (pasted) {
1506
+ this.#apply(pasted);
1507
+ return;
1508
+ }
1509
+ if (cells)
1510
+ target = rtClearCells(state, cells);
1511
+ }
1512
+ else if (!plain && !intoCode && !html.trim() && rtLooksLikeTsv(raw)) {
1513
+ // Fora de tabela: duas ou mais linhas com as mesmas duas ou mais colunas viram tabela.
1514
+ this.#apply(rtInsertFragment(state, rtTableFromValues(rtParseTsv(raw) ?? [])));
1515
+ return;
1516
+ }
1517
+ }
760
1518
  if (fragment)
761
- this.#apply(rtInsertFragment(state, fragment));
1519
+ this.#apply(rtInsertFragment(target, fragment));
1520
+ if (!plain && this.#opts().pasteImages === 'request')
1521
+ this.#requestPastedImages(data.getData('text/html'));
762
1522
  }
763
1523
  onCopy(event) {
764
1524
  this.#copy(event);
@@ -766,7 +1526,8 @@ export class RichTextEditor {
766
1526
  onCut(event) {
767
1527
  if (!this.#copy(event) || !this.#editable())
768
1528
  return;
769
- this.#apply(rtDeleteSelection(this.#current0()));
1529
+ const cells = this.#cellsOf();
1530
+ this.#apply(cells ? rtClearCells(this.#current0(), cells) : rtDeleteSelection(this.#current0()));
770
1531
  }
771
1532
  /** Põe na área de transferência o HTML canônico da seleção e o texto puro. */
772
1533
  #copy(event) {
@@ -777,12 +1538,27 @@ export class RichTextEditor {
777
1538
  return false;
778
1539
  this.#selection = selection;
779
1540
  this.#changed();
1541
+ // Células selecionadas: só elas (uma tabela), e o texto em valores separados por tabulação.
1542
+ const cells = this.#cellsOf();
1543
+ if (cells) {
1544
+ event.preventDefault();
1545
+ event.clipboardData.setData('text/html', this.#clipboardHtml(rtCellsFragment(this.#doc, cells)));
1546
+ event.clipboardData.setData('text/plain', rtCellsToTsv(this.#doc, cells, this.#syntax()));
1547
+ return true;
1548
+ }
780
1549
  const slice = rtSliceDoc(this.#doc, rtSelectionFrom(selection), rtSelectionTo(selection));
781
1550
  event.preventDefault();
782
- event.clipboardData.setData('text/html', rtSerialize(slice));
783
- event.clipboardData.setData('text/plain', rtPlainText(slice));
1551
+ event.clipboardData.setData('text/html', this.#clipboardHtml(slice));
1552
+ event.clipboardData.setData('text/plain', rtPlainText(slice, this.#syntax()));
784
1553
  return true;
785
1554
  }
1555
+ /** HTML da área de transferência: o perfil web, com o marcador de fragmento do editor quando há recursos novos. */
1556
+ #clipboardHtml(slice) {
1557
+ const schema = this.#opts().schema;
1558
+ if (!schema.variables && !schema.mentions)
1559
+ return rtSerialize(slice);
1560
+ return `<meta data-hm-fragment="1">${richTextSerialize(slice, { variableSyntax: this.#syntax() })}`;
1561
+ }
786
1562
  onDragStart(event) {
787
1563
  if (!this.#surface)
788
1564
  return;
@@ -791,8 +1567,8 @@ export class RichTextEditor {
791
1567
  return;
792
1568
  this.#dragSource = this.#editable() ? selection : null;
793
1569
  const slice = rtSliceDoc(this.#doc, rtSelectionFrom(selection), rtSelectionTo(selection));
794
- event.dataTransfer.setData('text/html', rtSerialize(slice));
795
- event.dataTransfer.setData('text/plain', rtPlainText(slice));
1570
+ event.dataTransfer.setData('text/html', this.#clipboardHtml(slice));
1571
+ event.dataTransfer.setData('text/plain', rtPlainText(slice, this.#syntax()));
796
1572
  }
797
1573
  onDragEnd() {
798
1574
  this.#dragSource = null;
@@ -804,6 +1580,8 @@ export class RichTextEditor {
804
1580
  event.preventDefault();
805
1581
  }
806
1582
  #drop(event) {
1583
+ if (event.dataTransfer && this.#imageFiles(event.dataTransfer, 'drop'))
1584
+ return;
807
1585
  const surface = this.#surface;
808
1586
  const doc = this.#doc;
809
1587
  const range = event.getTargetRanges?.()[0];
@@ -830,13 +1608,38 @@ export class RichTextEditor {
830
1608
  if (fragment)
831
1609
  this.#apply(rtInsertFragment({ doc, selection: rtCollapsed(target), stored: null }, fragment));
832
1610
  }
833
- /** No modo de edição (e desabilitado), clicar num link só posiciona o cursor. */
1611
+ /**
1612
+ * No modo de edição (e desabilitado), clicar num link só posiciona o cursor. Clicar (ou tocar) numa pílula a seleciona;
1613
+ * clicar de novo na pílula já selecionada abre a troca de variável.
1614
+ */
834
1615
  onAreaClick(event) {
835
1616
  const o = this.#opts();
836
1617
  if (o.readonly && !o.disabled)
837
1618
  return;
838
- if (event.target?.closest?.('a'))
1619
+ const target = event.target;
1620
+ if (target?.closest?.('a'))
839
1621
  event.preventDefault();
1622
+ const atomElement = target?.closest?.(`[${RICH_TEXT_ATOM_ATTR}]`);
1623
+ if (!atomElement || !this.#editable() || !this.#surface || !this.root?.contains(atomElement))
1624
+ return;
1625
+ const at = this.#surface.atomPosition(atomElement);
1626
+ if (!at)
1627
+ return;
1628
+ const atom = rtAtomAt(this.#doc, at.block, at.index);
1629
+ if (!atom)
1630
+ return;
1631
+ const already = rtSelectedAtom({ doc: this.#doc, selection: this.#selection });
1632
+ if (already && already.block === at.block && already.index === at.index) {
1633
+ if (atom.kind === 'variable' && this.#variablesOn() && this.host.showVariablePopover)
1634
+ this.openVariablePicker(atom.name);
1635
+ return;
1636
+ }
1637
+ this.#selection = { anchor: { block: at.block, offset: at.index }, focus: { block: at.block, offset: at.index + 1 } };
1638
+ this.#history = historyBreak(this.#history);
1639
+ if (this.#areaFocused())
1640
+ this.#writeSelection(this.#selection);
1641
+ this.#changed();
1642
+ this.#announceAtom(atom, 'selected');
840
1643
  }
841
1644
  // ── link ─────────────────────────────────────────────────────────────────────────────────────
842
1645
  #setLink(patch) {
@@ -911,7 +1714,16 @@ export class RichTextEditor {
911
1714
  this.#setLink({ error: t.linkRequired });
912
1715
  return;
913
1716
  }
914
- const href = normalizeRichTextUrl(raw, schema);
1717
+ let href = normalizeRichTextUrl(raw, schema);
1718
+ if (schema.variables && (!href || href.includes(this.#syntax().open))) {
1719
+ const withVariable = normalizeRichTextVariableUrl(raw, schema, this.#syntax());
1720
+ if (withVariable)
1721
+ href = withVariable;
1722
+ else if (rtDocVariablesInText(raw, this.#syntax())) {
1723
+ this.#setLink({ error: this.#opts().extraText?.linkVariablePosition ?? formatMessage(t.linkInvalid, { protocols: schema.protocols.join(', ') }) });
1724
+ return;
1725
+ }
1726
+ }
915
1727
  if (!href) {
916
1728
  this.#setLink({ error: formatMessage(t.linkInvalid, { protocols: schema.protocols.join(', ') }) });
917
1729
  return;
@@ -947,6 +1759,838 @@ export class RichTextEditor {
947
1759
  this.#linkSelection = null;
948
1760
  this.#setLink({ open: false });
949
1761
  }
1762
+ // ── imagem ───────────────────────────────────────────────────────────────────────────────────
1763
+ /** Desenho da imagem na superfície: `<img>` (prévia local enquanto envia), progresso e o aviso sem descrição. */
1764
+ #renderImage(document, element, atom) {
1765
+ const t = this.#opts().extraText;
1766
+ element.classList.add('hm-rich-text__image');
1767
+ let img = element.querySelector('img');
1768
+ if (!img) {
1769
+ img = document.createElement('img');
1770
+ if (atom.src)
1771
+ img.setAttribute('src', atom.src);
1772
+ img.setAttribute('alt', atom.alt);
1773
+ element.appendChild(img);
1774
+ }
1775
+ if (img) {
1776
+ if (atom.width)
1777
+ img.setAttribute('width', String(atom.width));
1778
+ if (atom.height)
1779
+ img.setAttribute('height', String(atom.height));
1780
+ }
1781
+ if (atom.pending) {
1782
+ const info = this.#pending.get(atom.pending);
1783
+ element.classList.add('hm-rich-text__image--pending');
1784
+ if (img && info?.preview)
1785
+ img.setAttribute('src', info.preview);
1786
+ const bar = document.createElement('span');
1787
+ bar.className = 'hm-rich-text__image-progress';
1788
+ bar.setAttribute('role', 'progressbar');
1789
+ bar.setAttribute('aria-valuemin', '0');
1790
+ bar.setAttribute('aria-valuemax', '100');
1791
+ if (info?.progress !== null && info?.progress !== undefined)
1792
+ bar.setAttribute('aria-valuenow', String(Math.round(info.progress * 100)));
1793
+ bar.setAttribute('aria-label', t ? formatMessage(t.uploadingImage, { name: info?.name ?? '' }) : '');
1794
+ const fill = document.createElement('span');
1795
+ fill.className = 'hm-rich-text__image-progress-fill';
1796
+ fill.style.setProperty('--hm-rich-text-image-progress', String(info?.progress ?? 0));
1797
+ bar.appendChild(fill);
1798
+ element.appendChild(bar);
1799
+ }
1800
+ else if (!atom.alt && !atom.decorative) {
1801
+ element.classList.add('hm-rich-text__image--no-alt');
1802
+ const hidden = document.createElement('span');
1803
+ hidden.className = 'hm-visually-hidden';
1804
+ hidden.textContent = t?.imageNoAlt ?? '';
1805
+ element.appendChild(hidden);
1806
+ }
1807
+ return element;
1808
+ }
1809
+ #redrawImages() {
1810
+ this.#pendingVersion++;
1811
+ if (!this.#surface)
1812
+ return;
1813
+ this.#syncAtomRenderer();
1814
+ this.#render();
1815
+ if (this.#areaFocused())
1816
+ this.#writeSelection(this.#selection);
1817
+ }
1818
+ /** Marcadores que saíram do documento (apagados, desfeitos): avisa o app e esquece (a resposta tardia é ignorada). */
1819
+ #afterDocChange(doc) {
1820
+ if (!this.#pending.size)
1821
+ return;
1822
+ const present = new Set(rtPendingImages(doc));
1823
+ for (const [id, info] of [...this.#pending]) {
1824
+ if (present.has(id))
1825
+ continue;
1826
+ this.#pending.delete(id);
1827
+ if (info.preview)
1828
+ URL.revokeObjectURL?.(info.preview);
1829
+ this.host.imageCancel?.(id);
1830
+ }
1831
+ }
1832
+ /** Arquivos de imagem colados ou soltos: valida e pede o envio ao app. `true` se havia arquivo de imagem. */
1833
+ #imageFiles(data, source) {
1834
+ if (!this.#opts().schema.image)
1835
+ return false;
1836
+ const files = Array.from(data.files ?? []).filter((file) => file.type.startsWith('image/'));
1837
+ if (!files.length)
1838
+ return false;
1839
+ this.insertImageFiles(files, source);
1840
+ return true;
1841
+ }
1842
+ /** Insere marcadores para os arquivos (um por arquivo, na ordem) e emite um pedido para cada. */
1843
+ insertImageFiles(files, source) {
1844
+ const o = this.#opts();
1845
+ if (!this.#editable() || !o.schema.image)
1846
+ return;
1847
+ const t = o.extraText;
1848
+ let state = this.#areaFocused() ? this.#current() : this.#current0();
1849
+ const requests = [];
1850
+ for (const file of files) {
1851
+ const problem = richTextImageFileProblem(file, o.imageAccept ?? RICH_TEXT_IMAGE_ACCEPT, o.imageMaxBytes ?? RICH_TEXT_IMAGE_MAX_BYTES);
1852
+ if (problem) {
1853
+ if (t) {
1854
+ const max = `${Math.round((o.imageMaxBytes ?? RICH_TEXT_IMAGE_MAX_BYTES) / (1024 * 1024))} MB`;
1855
+ this.#announce(problem === 'size' ? formatMessage(t.imageTooLarge, { max }) : t.imageTypeRefused);
1856
+ }
1857
+ continue;
1858
+ }
1859
+ const id = richTextImageId();
1860
+ const preview = typeof URL !== 'undefined' && URL.createObjectURL ? URL.createObjectURL(file) : null;
1861
+ this.#pending.set(id, { preview, progress: null, name: file.name ?? '' });
1862
+ state = rtInsertImage(state, { src: '', alt: '', decorative: false, pending: id });
1863
+ requests.push({ id, file, source });
1864
+ }
1865
+ if (!requests.length)
1866
+ return;
1867
+ this.#pendingVersion++;
1868
+ this.#syncAtomRenderer();
1869
+ this.#history = historyBreak(this.#history);
1870
+ this.#apply(state);
1871
+ this.#history = historyBreak(this.#history);
1872
+ for (const request of requests)
1873
+ this.host.imageRequest?.(request);
1874
+ }
1875
+ /** `<img>` com `src` https no HTML colado (`pasteImages: 'request'`): marcador e pedido com o endereço. */
1876
+ #requestPastedImages(html) {
1877
+ if (!html || !html.includes('<img') || !this.#opts().schema.image || typeof DOMParser === 'undefined')
1878
+ return;
1879
+ const doc = new DOMParser().parseFromString(html, 'text/html');
1880
+ const urls = Array.from(doc.querySelectorAll('img'))
1881
+ .map((img) => normalizeRichTextImageUrl(img.getAttribute('src'), this.#opts().schema))
1882
+ .filter((url) => !!url);
1883
+ if (!urls.length)
1884
+ return;
1885
+ let state = this.#current0();
1886
+ const requests = [];
1887
+ for (const url of urls) {
1888
+ const id = richTextImageId();
1889
+ this.#pending.set(id, { preview: null, progress: null, name: url });
1890
+ state = rtInsertImage(state, { src: '', alt: '', decorative: false, pending: id });
1891
+ requests.push({ id, url, source: 'paste-html' });
1892
+ }
1893
+ this.#pendingVersion++;
1894
+ this.#syncAtomRenderer();
1895
+ this.#apply(state);
1896
+ for (const request of requests)
1897
+ this.host.imageRequest?.(request);
1898
+ }
1899
+ /** Botão da barra: o seletor de arquivo do navegador (na casca). */
1900
+ openImagePicker() {
1901
+ if (!this.#editable() || !this.#opts().schema.image)
1902
+ return;
1903
+ if (this.#areaFocused())
1904
+ this.#readSelection();
1905
+ this.host.pickImage?.();
1906
+ }
1907
+ /**
1908
+ * Resposta do app: troca o marcador pela imagem no documento e em todos os instantâneos do histórico (não cria
1909
+ * passo). Endereço fora da regra conta como recusa. Id desconhecido (cancelado) é ignorado.
1910
+ */
1911
+ resolveImage(id, resolution) {
1912
+ const info = this.#pending.get(id);
1913
+ if (!info)
1914
+ return;
1915
+ const o = this.#opts();
1916
+ const src = normalizeRichTextImageUrl(resolution?.src, o.schema, !!o.allowRelativeImages && o.outputProfile !== 'email');
1917
+ if (!src) {
1918
+ this.rejectImage(id);
1919
+ return;
1920
+ }
1921
+ const alt = typeof resolution.alt === 'string' ? resolution.alt.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 512) : '';
1922
+ const image = { src, alt, decorative: !!resolution.decorative && !alt, width: richTextImageSize(resolution.width), height: richTextImageSize(resolution.height) };
1923
+ this.#pending.delete(id);
1924
+ if (info.preview)
1925
+ URL.revokeObjectURL?.(info.preview);
1926
+ this.#history = historyResolvePendingImage(this.#history, id, image);
1927
+ const before = this.#doc;
1928
+ this.#doc = rtResolvePendingImage(this.#doc, id, image);
1929
+ this.#redrawImages();
1930
+ this.#changed();
1931
+ this.#emit();
1932
+ // Sem descrição: o popover de texto alternativo abre uma vez, ancorado na imagem.
1933
+ if (!image.alt && !image.decorative && !this.#altAsked.has(id) && before !== this.#doc) {
1934
+ this.#altAsked.add(id);
1935
+ const at = this.#doc.findIndex((block) => rtImageOf(block)?.src === src && !rtImageOf(block)?.alt);
1936
+ if (at >= 0)
1937
+ this.openImageAlt(at, 0);
1938
+ }
1939
+ }
1940
+ /** Progresso do envio (0 a 1). */
1941
+ progressImage(id, fraction) {
1942
+ const info = this.#pending.get(id);
1943
+ if (!info || typeof fraction !== 'number' || Number.isNaN(fraction))
1944
+ return;
1945
+ info.progress = Math.max(0, Math.min(1, fraction));
1946
+ this.#redrawImages();
1947
+ }
1948
+ /** Recusa do app: tira o marcador (do documento e do histórico) e anuncia a mensagem (do app ou do catálogo). */
1949
+ rejectImage(id, message) {
1950
+ const info = this.#pending.get(id);
1951
+ if (!info)
1952
+ return;
1953
+ this.#pending.delete(id);
1954
+ if (info.preview)
1955
+ URL.revokeObjectURL?.(info.preview);
1956
+ this.#history = historyResolvePendingImage(this.#history, id, null);
1957
+ this.#doc = rtResolvePendingImage(this.#doc, id, null);
1958
+ this.#selection = { anchor: rtClampPos(this.#doc, this.#selection.anchor), focus: rtClampPos(this.#doc, this.#selection.focus) };
1959
+ this.#redrawImages();
1960
+ this.#changed();
1961
+ this.#emit();
1962
+ const t = this.#opts().extraText;
1963
+ this.#announce(typeof message === 'string' && message ? message : (t?.imageFailed ?? ''));
1964
+ }
1965
+ /** Digitar (ou Enter) com a imagem selecionada não a troca: escreve num parágrafo depois dela. */
1966
+ #typeAfterImage(event) {
1967
+ const state = this.#current();
1968
+ const selected = rtSelectedAtom(state);
1969
+ if (!selected || selected.atom.kind !== 'image')
1970
+ return false;
1971
+ event.preventDefault();
1972
+ const doc = state.doc.slice();
1973
+ const at = selected.block + 1;
1974
+ if (!doc[at] || rtBlockText(doc[at]).length || doc[at].type !== 'paragraph')
1975
+ doc.splice(at, 0, rtBlock('paragraph', []));
1976
+ let next = { doc, selection: rtCollapsed({ block: at, offset: 0 }), stored: null };
1977
+ if (event.inputType === 'insertText' && event.data)
1978
+ next = rtInsertText(next, event.data);
1979
+ this.#apply(next, 'other');
1980
+ return true;
1981
+ }
1982
+ /** Abre o popover de texto alternativo da imagem do bloco. */
1983
+ openImageAlt(block, index) {
1984
+ const atom = rtAtomAt(this.#doc, block, index);
1985
+ if (!atom || atom.kind !== 'image' || !this.#editable() || !this.host.showImageAltPopover)
1986
+ return;
1987
+ this.#altTarget = { block, index };
1988
+ this.#imageAlt = { open: true, alt: atom.alt, decorative: atom.decorative };
1989
+ this.#changed();
1990
+ const element = this.#surface?.atomElementAt(block, index) ?? null;
1991
+ this.host.showImageAltPopover(element);
1992
+ }
1993
+ setImageAlt(alt) {
1994
+ this.#imageAlt = { ...this.#imageAlt, alt: String(alt ?? '') };
1995
+ this.#changed();
1996
+ }
1997
+ setImageDecorative(decorative) {
1998
+ this.#imageAlt = { ...this.#imageAlt, decorative: !!decorative };
1999
+ this.#changed();
2000
+ }
2001
+ /** Aplica o texto alternativo (passo de histórico próprio) e devolve o foco com a imagem selecionada. */
2002
+ applyImageAlt() {
2003
+ const target = this.#altTarget;
2004
+ const atom = target ? rtAtomAt(this.#doc, target.block, target.index) : null;
2005
+ const state = this.#imageAlt;
2006
+ this.#closeImageAlt();
2007
+ if (!target || !atom || atom.kind !== 'image')
2008
+ return;
2009
+ const alt = state.decorative ? '' : state.alt.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 512);
2010
+ const doc = rtReplaceAtom(this.#doc, target.block, target.index, { ...atom, alt, decorative: state.decorative && !alt });
2011
+ this.#apply({ doc, selection: { anchor: { block: target.block, offset: target.index }, focus: { block: target.block, offset: target.index + 1 } }, stored: null });
2012
+ this.#focusArea();
2013
+ }
2014
+ cancelImageAlt() {
2015
+ const target = this.#altTarget;
2016
+ this.#closeImageAlt();
2017
+ if (target)
2018
+ this.#selection = { anchor: { block: target.block, offset: target.index }, focus: { block: target.block, offset: target.index + 1 } };
2019
+ this.#focusArea();
2020
+ }
2021
+ onImageAltOpenChange(open) {
2022
+ if (!open && this.#imageAlt.open) {
2023
+ this.#altTarget = null;
2024
+ this.#imageAlt = CLOSED_ALT;
2025
+ this.#changed();
2026
+ }
2027
+ }
2028
+ /** Teclado no popover: Esc cancela; Enter no campo aplica. */
2029
+ onImageAltKeydown(event) {
2030
+ if (event.key === 'Escape') {
2031
+ event.preventDefault();
2032
+ event.stopPropagation();
2033
+ this.cancelImageAlt();
2034
+ }
2035
+ else if (event.key === 'Enter' && event.target?.localName === 'input' && event.target.type !== 'checkbox') {
2036
+ event.preventDefault();
2037
+ this.applyImageAlt();
2038
+ }
2039
+ }
2040
+ #closeImageAlt() {
2041
+ this.host.hideImageAltPopover?.();
2042
+ this.#altTarget = null;
2043
+ this.#imageAlt = CLOSED_ALT;
2044
+ this.#changed();
2045
+ }
2046
+ // ── barra flutuante ──────────────────────────────────────────────────────────────────────────
2047
+ #onPointerUp = () => {
2048
+ this.#document?.removeEventListener('mouseup', this.#onPointerUp, true);
2049
+ this.#pointerSelecting = false;
2050
+ // Depois de o navegador fechar a seleção do arraste.
2051
+ setTimeout(() => {
2052
+ this.#readSelection();
2053
+ this.#evaluateFloating(true);
2054
+ this.#state = null;
2055
+ this.host.changed();
2056
+ }, 0);
2057
+ };
2058
+ /**
2059
+ * Mostra a barra com a seleção não recolhida dentro da área: com o ponteiro, ao soltar; com o teclado, depois de
2060
+ * 400 ms sem tecla nova (não pisca a cada passo). Some com a seleção recolhida, sem foco, digitando ou com Esc.
2061
+ */
2062
+ #evaluateFloating(immediate = false) {
2063
+ const o = this.#opts();
2064
+ if (!o.floatingToolbar || !this.#surface || !this.#ready) {
2065
+ if (this.#floating.open)
2066
+ this.#floating = CLOSED_FLOATING;
2067
+ return;
2068
+ }
2069
+ const focusInBar = !!o.floatingToolbar && this.#floatingHasFocus();
2070
+ if (focusInBar) {
2071
+ this.#floating = { open: true, anchor: this.#floating.anchor ?? this.#selectionBox() };
2072
+ return;
2073
+ }
2074
+ if (!this.#editable() || !this.#areaFocused() || rtIsCollapsed(this.#selection) || this.#suggest.open) {
2075
+ if (this.#floatingTimer)
2076
+ clearTimeout(this.#floatingTimer);
2077
+ this.#floatingTimer = null;
2078
+ if (this.#floating.open)
2079
+ this.#floating = CLOSED_FLOATING;
2080
+ return;
2081
+ }
2082
+ if (this.#pointerSelecting)
2083
+ return;
2084
+ if (this.#floating.open) {
2085
+ this.#floating = { open: true, anchor: this.#selectionBox() };
2086
+ return;
2087
+ }
2088
+ const typing = Date.now() - this.#lastKeyAt < 400;
2089
+ if (immediate || !typing) {
2090
+ this.#floating = { open: true, anchor: this.#selectionBox() };
2091
+ return;
2092
+ }
2093
+ if (this.#floatingTimer)
2094
+ clearTimeout(this.#floatingTimer);
2095
+ this.#floatingTimer = setTimeout(() => {
2096
+ this.#floatingTimer = null;
2097
+ this.#lastKeyAt = 0;
2098
+ this.#evaluateFloating(true);
2099
+ this.#state = null;
2100
+ this.host.changed();
2101
+ }, 400);
2102
+ }
2103
+ #hideFloating(notify = false) {
2104
+ if (this.#floatingTimer)
2105
+ clearTimeout(this.#floatingTimer);
2106
+ this.#floatingTimer = null;
2107
+ if (!this.#floating.open)
2108
+ return;
2109
+ this.#floating = CLOSED_FLOATING;
2110
+ if (notify) {
2111
+ this.#state = null;
2112
+ this.host.changed();
2113
+ }
2114
+ }
2115
+ #floatingHasFocus() {
2116
+ const bar = this.host.elements().floatingBar;
2117
+ const active = this.#document?.activeElement ?? null;
2118
+ return !!bar && !!active && bar.contains(active);
2119
+ }
2120
+ /** Retângulo da primeira linha da seleção, para a barra (embaixo sem espaço em cima, ou no toque). */
2121
+ #selectionBox() {
2122
+ const selection = this.#domSelection();
2123
+ if (!selection || !selection.rangeCount)
2124
+ return null;
2125
+ const range = selection.getRangeAt(0);
2126
+ // Sem retângulo da seleção (ambiente sem leiaute): a borda de cima da área.
2127
+ const first = range.getClientRects?.()[0] ?? range.getBoundingClientRect?.() ?? this.root?.getBoundingClientRect();
2128
+ if (!first)
2129
+ return null;
2130
+ const view = this.#document?.defaultView;
2131
+ const coarse = !!view?.matchMedia?.('(pointer: coarse)').matches;
2132
+ const all = range.getBoundingClientRect?.() ?? first;
2133
+ return { x: first.left + first.width / 2, top: first.top, bottom: coarse ? all.bottom : first.bottom, below: coarse || first.top < 56 };
2134
+ }
2135
+ /** Alt+F10 com a barra flutuante à vista: foco no primeiro botão dela. */
2136
+ #focusFloating() {
2137
+ if (!this.#floating.open)
2138
+ return false;
2139
+ const bar = this.host.elements().floatingBar;
2140
+ const button = bar?.querySelector('button:not([disabled]), [tabindex="0"]');
2141
+ if (!button)
2142
+ return false;
2143
+ this.#readSelection();
2144
+ button.focus();
2145
+ return true;
2146
+ }
2147
+ /** Teclado na barra flutuante: Esc devolve o foco à área com a mesma seleção. */
2148
+ onFloatingKeydown(event) {
2149
+ if (event.key !== 'Escape')
2150
+ return;
2151
+ event.preventDefault();
2152
+ event.stopPropagation();
2153
+ this.#focusArea();
2154
+ }
2155
+ // ── sugestões por gatilho ──────────────────────────────────────────────────────────────────────
2156
+ /** Gatilhos ligados pelas entradas atuais. */
2157
+ #triggers() {
2158
+ const o = this.#opts();
2159
+ const list = [];
2160
+ if (o.singleLine) {
2161
+ if (this.#variablesOn())
2162
+ list.push({ char: this.#syntax().open, kind: 'variable' });
2163
+ if (o.mentionCandidates)
2164
+ list.push({ char: o.mentionTrigger || '@', kind: 'mention' });
2165
+ return list;
2166
+ }
2167
+ if (this.#variablesOn())
2168
+ list.push({ char: this.#syntax().open, kind: 'variable' });
2169
+ if (o.mentionCandidates)
2170
+ list.push({ char: o.mentionTrigger || '@', kind: 'mention' });
2171
+ if (o.slashCommands)
2172
+ list.push({ char: '/', kind: 'command', lineStart: true });
2173
+ return list;
2174
+ }
2175
+ /** Reavalia a consulta depois de cada mudança de documento ou de seleção (abre, filtra ou fecha a lista). */
2176
+ #evaluateSuggest() {
2177
+ if (!this.#surface || !this.#ready)
2178
+ return;
2179
+ if (this.#composing || !this.#areaFocused() || !this.#editable()) {
2180
+ if (this.#suggest.open)
2181
+ this.#closeSuggest(false);
2182
+ return;
2183
+ }
2184
+ const query = richTextSuggestQuery(this.#current0(), this.#triggers());
2185
+ if (!query) {
2186
+ this.#dismissed = null;
2187
+ if (this.#suggest.open)
2188
+ this.#closeSuggest(false);
2189
+ return;
2190
+ }
2191
+ if (this.#dismissed && richTextSameSuggestion(this.#dismissed, query))
2192
+ return;
2193
+ this.#dismissed = null;
2194
+ const same = this.#suggestQuery && richTextSameSuggestion(this.#suggestQuery, query) && this.#suggestQuery.query === query.query;
2195
+ this.#suggestQuery = query;
2196
+ if (same && this.#suggest.open) {
2197
+ this.#suggest = { ...this.#suggest, anchor: this.#caretBox() };
2198
+ return;
2199
+ }
2200
+ this.#fillSuggest(query);
2201
+ }
2202
+ /** Opções da consulta (locais ou a resposta remota) e a primeira habilitada ativa. */
2203
+ #fillSuggest(query) {
2204
+ const o = this.#opts();
2205
+ const kind = query.trigger.kind;
2206
+ const remote = kind !== 'command' && o.suggestionSource?.[kind] === 'remote';
2207
+ let items;
2208
+ let loading = false;
2209
+ if (remote) {
2210
+ this.#requestRemote(kind, query.query);
2211
+ items = this.#remoteItems?.id === this.#remoteId ? this.#remoteItems.items : [];
2212
+ loading = this.#remoteItems?.id !== this.#remoteId;
2213
+ }
2214
+ else
2215
+ items = this.#localSuggestions(kind, query.query);
2216
+ const active = richTextSuggestMove(items, -1, 1);
2217
+ this.#suggest = { open: true, kind, query: query.query, items, active, loading, error: false, anchor: this.#caretBox(), status: this.#suggest.status };
2218
+ this.#scheduleStatus();
2219
+ }
2220
+ #localSuggestions(kind, query) {
2221
+ const o = this.#opts();
2222
+ const t = o.extraText;
2223
+ if (kind === 'mention')
2224
+ return richTextMentionSuggestions(o.mentionCandidates, query);
2225
+ if (kind === 'command') {
2226
+ const text = o.text;
2227
+ return richTextCommandSuggestions(o.schema, {
2228
+ paragraph: text.paragraph,
2229
+ heading: text.heading,
2230
+ bulletList: text.bulletList,
2231
+ orderedList: text.orderedList,
2232
+ quote: text.quote,
2233
+ codeBlock: text.codeBlock,
2234
+ variable: t?.variableCommand ?? t?.insertVariable ?? 'Variable',
2235
+ table: t?.table,
2236
+ }, query, o.extraCommands ?? [], (template, params) => formatMessage(template, params));
2237
+ }
2238
+ return this.#variableSuggestions(o.variables, query);
2239
+ }
2240
+ #variableSuggestions(variables, query) {
2241
+ const o = this.#opts();
2242
+ const t = o.extraText;
2243
+ const syntax = this.#syntax();
2244
+ return richTextGroupVariableOptions(richTextVariableOptions(variables, query, o.variableMode ?? 'closed')).map((option) => ({
2245
+ key: `var-${option.name}`,
2246
+ label: option.custom ? (t ? formatMessage(t.useVariable, { syntax: richTextVariableText(option.name, syntax) }) : option.name) : option.label,
2247
+ description: option.description,
2248
+ group: option.group,
2249
+ icon: 'braces',
2250
+ code: option.custom ? '' : option.name,
2251
+ disabled: false,
2252
+ value: { kind: 'variable', name: option.name },
2253
+ }));
2254
+ }
2255
+ /** Consulta remota com atraso de 200 ms; sem resposta em 10 s, estado de erro. */
2256
+ #requestRemote(kind, query) {
2257
+ if (this.#remoteTimer)
2258
+ clearTimeout(this.#remoteTimer);
2259
+ if (this.#remoteTimeout)
2260
+ clearTimeout(this.#remoteTimeout);
2261
+ const id = ++this.#remoteId;
2262
+ this.#remoteTimer = setTimeout(() => {
2263
+ this.#remoteTimer = null;
2264
+ if (id !== this.#remoteId)
2265
+ return;
2266
+ this.host.suggestionQuery?.({ kind, query, id });
2267
+ this.#remoteTimeout = setTimeout(() => {
2268
+ if (id !== this.#remoteId || !this.#suggest.open || !this.#suggest.loading)
2269
+ return;
2270
+ this.#suggest = { ...this.#suggest, loading: false, error: true };
2271
+ this.#state = null;
2272
+ this.host.changed();
2273
+ }, 10_000);
2274
+ }, 200);
2275
+ }
2276
+ /** Resposta do app à consulta remota; `id` antigo é descartado (a consulta já mudou). */
2277
+ suggestionResults(results) {
2278
+ if (!results || results.id !== this.#remoteId)
2279
+ return;
2280
+ if (this.#remoteTimeout)
2281
+ clearTimeout(this.#remoteTimeout);
2282
+ const kind = this.#suggest.kind;
2283
+ if (!this.#suggest.open || (kind !== 'variable' && kind !== 'mention'))
2284
+ return;
2285
+ if (results.error) {
2286
+ this.#suggest = { ...this.#suggest, loading: false, error: true, items: [], active: -1 };
2287
+ }
2288
+ else {
2289
+ const items = kind === 'mention'
2290
+ ? richTextMentionSuggestions(results.items, '')
2291
+ : this.#variableSuggestions(results.items, this.#suggest.query);
2292
+ this.#remoteItems = { id: results.id, items };
2293
+ this.#suggest = { ...this.#suggest, loading: false, error: false, items, active: richTextSuggestMove(items, -1, 1) };
2294
+ this.#scheduleStatus();
2295
+ }
2296
+ this.#state = null;
2297
+ this.host.changed();
2298
+ }
2299
+ /** "Tentar de novo" do estado de erro. */
2300
+ retrySuggestions() {
2301
+ const query = this.#suggestQuery;
2302
+ if (!query || !this.#suggest.open)
2303
+ return;
2304
+ this.#remoteItems = null;
2305
+ this.#fillSuggest(query);
2306
+ this.#state = null;
2307
+ this.host.changed();
2308
+ this.#focusArea();
2309
+ }
2310
+ /** Contagem anunciada 300 ms depois da última mudança da lista. */
2311
+ #scheduleStatus() {
2312
+ if (this.#statusTimer)
2313
+ clearTimeout(this.#statusTimer);
2314
+ this.#statusTimer = setTimeout(() => {
2315
+ this.#statusTimer = null;
2316
+ const t = this.#opts().extraText;
2317
+ if (!t || !this.#suggest.open)
2318
+ return;
2319
+ const s = this.#suggest;
2320
+ const status = s.loading ? t.suggestionsLoading : s.error ? t.suggestionsError : pluralMessage(t.suggestionsCount, s.items.length, this.#locale());
2321
+ if (status === s.status)
2322
+ return;
2323
+ this.#suggest = { ...s, status };
2324
+ this.#state = null;
2325
+ this.host.changed();
2326
+ }, 300);
2327
+ }
2328
+ #locale() {
2329
+ return this.#opts().locale ?? 'pt-BR';
2330
+ }
2331
+ #clearSuggestTimers() {
2332
+ for (const timer of [this.#remoteTimer, this.#remoteTimeout, this.#statusTimer])
2333
+ if (timer)
2334
+ clearTimeout(timer);
2335
+ this.#remoteTimer = this.#remoteTimeout = this.#statusTimer = null;
2336
+ }
2337
+ /** Fecha a lista; `dismiss` (Esc) marca a consulta para não reabrir enquanto o cursor continuar nela. */
2338
+ #closeSuggest(notify = true, dismiss = false) {
2339
+ if (!this.#suggest.open && !dismiss)
2340
+ return;
2341
+ if (dismiss)
2342
+ this.#dismissed = this.#suggestQuery;
2343
+ this.#suggestQuery = null;
2344
+ this.#remoteId++;
2345
+ this.#clearSuggestTimers();
2346
+ this.#suggest = CLOSED_SUGGEST;
2347
+ if (notify) {
2348
+ this.#state = null;
2349
+ this.host.changed();
2350
+ }
2351
+ }
2352
+ /** Retângulo da linha do cursor na janela, para a lista (abre para cima sem espaço embaixo). */
2353
+ #caretBox() {
2354
+ const root = this.root;
2355
+ const selection = this.#domSelection();
2356
+ if (!root || !selection || !selection.rangeCount)
2357
+ return null;
2358
+ let rect = selection.getRangeAt(0).getBoundingClientRect?.() ?? null;
2359
+ if (!rect || (!rect.width && !rect.height && !rect.left && !rect.top)) {
2360
+ const node = selection.focusNode;
2361
+ const element = node?.nodeType === 1 ? node : node?.parentElement;
2362
+ rect = element?.getBoundingClientRect?.() ?? root.getBoundingClientRect();
2363
+ }
2364
+ const area = root.getBoundingClientRect();
2365
+ const view = this.#document?.defaultView;
2366
+ const height = view?.visualViewport?.height ?? view?.innerHeight ?? 0;
2367
+ // Estimativa do teto da lista (8 opções); o CSS limita a altura real.
2368
+ const room = height - rect.bottom;
2369
+ return { x: rect.left, top: rect.top, bottom: rect.bottom, above: room < 280 && rect.top > room, width: area.width };
2370
+ }
2371
+ /** Teclado com a lista aberta (o foco fica na área): setas, PageUp/Down, Ctrl+Home/End, Enter/Tab, Esc. */
2372
+ #suggestKeydown(event) {
2373
+ const s = this.#suggest;
2374
+ if (!s.open)
2375
+ return false;
2376
+ const key = event.key;
2377
+ const items = s.items;
2378
+ let next = null;
2379
+ if (key === 'ArrowDown' && !event.altKey)
2380
+ next = richTextSuggestMove(items, s.active, 1);
2381
+ else if (key === 'ArrowUp' && !event.altKey)
2382
+ next = richTextSuggestMove(items, s.active, -1);
2383
+ else if (key === 'PageDown')
2384
+ next = richTextSuggestMove(items, s.active, 8, false);
2385
+ else if (key === 'PageUp')
2386
+ next = richTextSuggestMove(items, s.active, -8, false);
2387
+ else if (key === 'Home' && (event.ctrlKey || event.metaKey))
2388
+ next = richTextSuggestMove(items, -1, 1);
2389
+ else if (key === 'End' && (event.ctrlKey || event.metaKey))
2390
+ next = richTextSuggestMove(items, items.length, -1);
2391
+ else if (key === 'Escape') {
2392
+ event.preventDefault();
2393
+ event.stopPropagation();
2394
+ this.#closeSuggest(true, true);
2395
+ return true;
2396
+ }
2397
+ else if ((key === 'Enter' || (key === 'Tab' && !event.shiftKey)) && !event.altKey && !event.ctrlKey && !event.metaKey) {
2398
+ if (s.active < 0 || !items[s.active] || items[s.active].disabled)
2399
+ return false;
2400
+ event.preventDefault();
2401
+ this.pickSuggestion(s.active);
2402
+ return true;
2403
+ }
2404
+ else if (key === 'Tab' && event.shiftKey) {
2405
+ this.#closeSuggest();
2406
+ return false;
2407
+ }
2408
+ if (next === null)
2409
+ return false;
2410
+ event.preventDefault();
2411
+ if (next >= 0) {
2412
+ this.#suggest = { ...s, active: next };
2413
+ this.#state = null;
2414
+ this.host.changed();
2415
+ }
2416
+ return true;
2417
+ }
2418
+ /** Escolhe a opção `index`: troca a consulta pelo resultado num passo só de histórico. */
2419
+ pickSuggestion(index) {
2420
+ const s = this.#suggest;
2421
+ const item = s.items[index];
2422
+ const query = this.#suggestQuery;
2423
+ if (!item || item.disabled || !query || !this.#editable())
2424
+ return;
2425
+ this.#closeSuggest(false);
2426
+ const current = this.#current0();
2427
+ const base = rtRemoveSuggestQuery(current, query);
2428
+ const value = item.value;
2429
+ const t = this.#opts().extraText;
2430
+ this.#history = historyBreak(this.#history);
2431
+ switch (value.kind) {
2432
+ case 'variable': {
2433
+ this.#apply(rtInsertAtom(base, { kind: 'variable', name: value.name }, this.#syntax()));
2434
+ if (t)
2435
+ this.#announce(formatMessage(t.variableInserted, { label: richTextVariableLabel(value.name, this.#opts().variables) }));
2436
+ break;
2437
+ }
2438
+ case 'mention': {
2439
+ const withAtom = rtInsertAtom(base, { kind: 'mention', id: value.candidate.id, label: value.candidate.handle || value.candidate.name }, this.#syntax());
2440
+ this.#apply(rtInsertText(withAtom, ' '));
2441
+ this.host.mentioned?.(value.candidate);
2442
+ break;
2443
+ }
2444
+ case 'block': {
2445
+ const result = runRichTextCommand(base, value.tool);
2446
+ this.#apply(result.state);
2447
+ break;
2448
+ }
2449
+ case 'insert': {
2450
+ this.#apply(base);
2451
+ if (value.tool === 'variable')
2452
+ this.openVariablePicker();
2453
+ else if (value.tool === 'table')
2454
+ this.insertTable();
2455
+ break;
2456
+ }
2457
+ case 'app': {
2458
+ this.#apply(base);
2459
+ this.host.commandPicked?.(value.id);
2460
+ break;
2461
+ }
2462
+ }
2463
+ this.#history = historyBreak(this.#history);
2464
+ if (value.kind !== 'insert' || value.tool !== 'variable')
2465
+ this.#focusArea();
2466
+ }
2467
+ /** Lista aberta: id da opção ativa para o `aria-activedescendant` (com o prefixo da instância). */
2468
+ suggestOptionId(prefix, index) {
2469
+ return `${prefix}-${index}`;
2470
+ }
2471
+ // ── popover de variáveis ─────────────────────────────────────────────────────────────────────
2472
+ #setPicker(patch) {
2473
+ const next = { ...this.#picker, ...patch };
2474
+ if ('query' in patch || 'open' in patch) {
2475
+ const o = this.#opts();
2476
+ const options = richTextGroupVariableOptions(richTextVariableOptions(o.variables, next.query, o.variableMode ?? 'closed'));
2477
+ next.options = options;
2478
+ next.active = options.length ? Math.max(0, options.findIndex((opt) => opt.name === next.replacing)) : -1;
2479
+ }
2480
+ this.#picker = next;
2481
+ this.#changed();
2482
+ }
2483
+ /**
2484
+ * Abre o popover de variáveis: pela barra (insere no cursor) ou, com `replacing`, para trocar a pílula selecionada. O
2485
+ * gatilho é o botão da barra quando visível; senão, a âncora no cursor.
2486
+ */
2487
+ openVariablePicker(replacing = null) {
2488
+ if (!this.#editable() || !this.#variablesOn() || !this.host.showVariablePopover)
2489
+ return;
2490
+ const state = this.#areaFocused() ? this.#current() : this.#current0();
2491
+ this.#pickerSelection = state.selection;
2492
+ const selected = replacing !== null ? rtSelectedAtom(state) : null;
2493
+ this.#pickerTarget = selected ? { block: selected.block, index: selected.index } : null;
2494
+ this.#setPicker({ open: true, query: '', replacing: selected ? replacing : null });
2495
+ const button = this.host.elements().bar?.querySelector('[data-tool="variable"] button');
2496
+ const trigger = (!selected && this.#opts().showToolbar && button) || this.#placeCaretAnchor();
2497
+ this.host.showVariablePopover(trigger ?? null);
2498
+ }
2499
+ /** Texto do campo de busca do popover. */
2500
+ setVariableQuery(query) {
2501
+ this.#setPicker({ query });
2502
+ }
2503
+ /** Escolhe uma opção do popover: insere ou troca, fecha e devolve o foco à área depois da pílula. */
2504
+ pickVariable(name) {
2505
+ if (!isRichTextVariableName(name))
2506
+ return;
2507
+ const target = this.#pickerTarget;
2508
+ const selection = this.#pickerSelection;
2509
+ this.#closePicker();
2510
+ const t = this.#opts().extraText;
2511
+ const label = richTextVariableLabel(name, this.#opts().variables);
2512
+ if (target && rtAtomAt(this.#doc, target.block, target.index)?.kind === 'variable') {
2513
+ const doc = rtReplaceAtom(this.#doc, target.block, target.index, { kind: 'variable', name });
2514
+ this.#apply({ doc, selection: { anchor: { block: target.block, offset: target.index }, focus: { block: target.block, offset: target.index + 1 } }, stored: null });
2515
+ if (t)
2516
+ this.#announce(formatMessage(t.variableReplaced, { label }));
2517
+ this.#focusArea();
2518
+ return;
2519
+ }
2520
+ if (selection) {
2521
+ this.#selection = { anchor: rtClampPos(this.#doc, selection.anchor), focus: rtClampPos(this.#doc, selection.focus) };
2522
+ }
2523
+ this.insertVariable(name);
2524
+ }
2525
+ /** Fecha o popover sem mudar nada; a seleção (a pílula, na troca) volta à área. */
2526
+ cancelVariablePicker() {
2527
+ const selection = this.#pickerSelection;
2528
+ this.#closePicker();
2529
+ if (selection) {
2530
+ this.#selection = { anchor: rtClampPos(this.#doc, selection.anchor), focus: rtClampPos(this.#doc, selection.focus) };
2531
+ this.#changed();
2532
+ }
2533
+ this.#focusArea();
2534
+ }
2535
+ /** O popover abriu ou fechou por conta própria (clique fora, Esc do overlay). */
2536
+ onVariablePickerOpenChange(open) {
2537
+ if (!open && this.#picker.open) {
2538
+ this.#pickerTarget = null;
2539
+ this.#pickerSelection = null;
2540
+ this.#setPicker({ open: false });
2541
+ }
2542
+ }
2543
+ /**
2544
+ * Teclado no painel de variáveis (padrão listbox com foco nas opções): ↓ do campo de busca vai à lista; ↑/↓, Home/End
2545
+ * entre as opções; Enter ou Espaço escolhe; Esc cancela; letra digitada na lista volta ao campo de busca.
2546
+ */
2547
+ onVariablePanelKeydown(event) {
2548
+ const panel = this.host.elements().variablePanel;
2549
+ const picker = this.#picker;
2550
+ if (event.key === 'Escape') {
2551
+ event.preventDefault();
2552
+ event.stopPropagation();
2553
+ this.cancelVariablePicker();
2554
+ return;
2555
+ }
2556
+ if (!panel || !picker.options.length)
2557
+ return;
2558
+ const target = event.target;
2559
+ const inList = !!target?.closest('[role="option"]');
2560
+ const count = picker.options.length;
2561
+ let next = -1;
2562
+ if (event.key === 'ArrowDown')
2563
+ next = inList ? (picker.active + 1) % count : Math.max(0, picker.active);
2564
+ else if (event.key === 'ArrowUp')
2565
+ next = inList ? (picker.active - 1 + count) % count : count - 1;
2566
+ else if (inList && event.key === 'Home')
2567
+ next = 0;
2568
+ else if (inList && event.key === 'End')
2569
+ next = count - 1;
2570
+ else if (event.key === 'Enter' || (inList && event.key === ' ')) {
2571
+ event.preventDefault();
2572
+ const option = picker.options[Math.max(0, picker.active)];
2573
+ if (option)
2574
+ this.pickVariable(option.name);
2575
+ return;
2576
+ }
2577
+ else if (inList && event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
2578
+ panel.querySelector('input')?.focus();
2579
+ return;
2580
+ }
2581
+ if (next < 0)
2582
+ return;
2583
+ event.preventDefault();
2584
+ this.#picker = { ...picker, active: next };
2585
+ this.#changed();
2586
+ this.host.afterRender(() => panel.querySelectorAll('[role="option"]')[next]?.focus());
2587
+ }
2588
+ #closePicker() {
2589
+ this.host.hideVariablePopover?.();
2590
+ this.#pickerTarget = null;
2591
+ this.#pickerSelection = null;
2592
+ this.#setPicker({ open: false });
2593
+ }
950
2594
  /** Foco de volta na área com a seleção do modelo. */
951
2595
  #focusArea() {
952
2596
  const root = this.root;