@vowt-tech/ui 0.0.0-stage → 0.177.1

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 (116) hide show
  1. package/README.md +13 -2
  2. package/bin/vowt-ux-ui-design.mjs +483 -0
  3. package/guia/LEIA-PRIMEIRO.md +106 -0
  4. package/guia/VERSAO +1 -0
  5. package/guia/componentes.md +104 -0
  6. package/guia/regras/atualizar.md +136 -0
  7. package/guia/regras/componentes.md +374 -0
  8. package/guia/regras/fundamentos.md +257 -0
  9. package/guia/regras/marca.md +200 -0
  10. package/guia/regras/medidas.md +114 -0
  11. package/guia/regras/regras-de-base.md +85 -0
  12. package/guia/regras/telas/acoes.md +56 -0
  13. package/guia/regras/telas/direcao-ux.md +327 -0
  14. package/guia/regras/telas/padroes.md +58 -0
  15. package/guia/regras/telas/regras.md +171 -0
  16. package/guia/regras/telas/voz.md +134 -0
  17. package/package.json +72 -4
  18. package/src/brand/icons.ts +215 -0
  19. package/src/brand/logo.tsx +288 -0
  20. package/src/components/accordion.tsx +58 -0
  21. package/src/components/ai-orb.tsx +67 -0
  22. package/src/components/alert-dialog.tsx +227 -0
  23. package/src/components/alert.tsx +128 -0
  24. package/src/components/area-chart.tsx +180 -0
  25. package/src/components/attachment.tsx +339 -0
  26. package/src/components/avatar.tsx +197 -0
  27. package/src/components/badge.tsx +242 -0
  28. package/src/components/bar-chart.tsx +138 -0
  29. package/src/components/bar-list.tsx +85 -0
  30. package/src/components/brand-icon.tsx +52 -0
  31. package/src/components/breadcrumb.tsx +96 -0
  32. package/src/components/button-group.tsx +29 -0
  33. package/src/components/button.tsx +208 -0
  34. package/src/components/calendar.tsx +238 -0
  35. package/src/components/card.tsx +136 -0
  36. package/src/components/chart.tsx +289 -0
  37. package/src/components/checkbox.tsx +42 -0
  38. package/src/components/code-block.tsx +31 -0
  39. package/src/components/collapsible.tsx +114 -0
  40. package/src/components/color-picker.tsx +93 -0
  41. package/src/components/combo-chart.tsx +139 -0
  42. package/src/components/combobox.tsx +200 -0
  43. package/src/components/command.tsx +191 -0
  44. package/src/components/date-picker.tsx +435 -0
  45. package/src/components/description-list.tsx +280 -0
  46. package/src/components/dialog.tsx +192 -0
  47. package/src/components/diff-view.tsx +109 -0
  48. package/src/components/dropdown-menu.tsx +248 -0
  49. package/src/components/emoji-picker.tsx +299 -0
  50. package/src/components/empty.tsx +197 -0
  51. package/src/components/field.tsx +226 -0
  52. package/src/components/file-upload.tsx +186 -0
  53. package/src/components/funnel-chart.tsx +224 -0
  54. package/src/components/gauge-chart.tsx +109 -0
  55. package/src/components/heatmap.tsx +105 -0
  56. package/src/components/hover-card.tsx +47 -0
  57. package/src/components/image-viewer.tsx +174 -0
  58. package/src/components/input-otp.tsx +86 -0
  59. package/src/components/input.tsx +470 -0
  60. package/src/components/item.tsx +94 -0
  61. package/src/components/kbd.tsx +28 -0
  62. package/src/components/label.tsx +21 -0
  63. package/src/components/line-chart.tsx +92 -0
  64. package/src/components/link.tsx +34 -0
  65. package/src/components/message.tsx +903 -0
  66. package/src/components/number-field.tsx +79 -0
  67. package/src/components/pagination.tsx +208 -0
  68. package/src/components/phone-input.tsx +147 -0
  69. package/src/components/pie-chart.tsx +117 -0
  70. package/src/components/popover.tsx +102 -0
  71. package/src/components/powered-by.tsx +39 -0
  72. package/src/components/progress.tsx +278 -0
  73. package/src/components/prose.tsx +42 -0
  74. package/src/components/radar-chart.tsx +66 -0
  75. package/src/components/radial-chart.tsx +73 -0
  76. package/src/components/radio-group.tsx +135 -0
  77. package/src/components/rating.tsx +192 -0
  78. package/src/components/rich-text.tsx +1651 -0
  79. package/src/components/scatter-chart.tsx +115 -0
  80. package/src/components/scroll-area.tsx +50 -0
  81. package/src/components/select.tsx +193 -0
  82. package/src/components/separator.tsx +20 -0
  83. package/src/components/sheet.tsx +142 -0
  84. package/src/components/sidebar.tsx +570 -0
  85. package/src/components/skeleton.tsx +18 -0
  86. package/src/components/slider.tsx +47 -0
  87. package/src/components/sonner.tsx +178 -0
  88. package/src/components/sparkline.tsx +68 -0
  89. package/src/components/spinner.tsx +35 -0
  90. package/src/components/status-dot.tsx +45 -0
  91. package/src/components/stepper.tsx +228 -0
  92. package/src/components/switch.tsx +35 -0
  93. package/src/components/table.tsx +267 -0
  94. package/src/components/tabs.tsx +184 -0
  95. package/src/components/tag-input.tsx +238 -0
  96. package/src/components/textarea.tsx +47 -0
  97. package/src/components/time-picker.tsx +183 -0
  98. package/src/components/timeline.tsx +75 -0
  99. package/src/components/toggle-group.tsx +93 -0
  100. package/src/components/toggle.tsx +51 -0
  101. package/src/components/tooltip.tsx +160 -0
  102. package/src/components/tree.tsx +136 -0
  103. package/src/components/voice-message.tsx +193 -0
  104. package/src/css.d.ts +2 -0
  105. package/src/hooks/use-appearance.ts +57 -0
  106. package/src/hooks/use-mobile.ts +20 -0
  107. package/src/lib/appearance.ts +16 -0
  108. package/src/lib/button-render.ts +32 -0
  109. package/src/lib/char-count.tsx +67 -0
  110. package/src/lib/date.ts +45 -0
  111. package/src/lib/file-accept.ts +59 -0
  112. package/src/lib/markdown.ts +187 -0
  113. package/src/lib/utils.ts +29 -0
  114. package/src/lib/voice.ts +68 -0
  115. package/src/styles/shadcn.css +642 -0
  116. package/src/styles/theme.css +1825 -0
@@ -0,0 +1,1651 @@
1
+ 'use client';
2
+
3
+ import {
4
+ BaselineIcon,
5
+ BetweenHorizontalEndIcon,
6
+ BetweenHorizontalStartIcon,
7
+ BetweenVerticalEndIcon,
8
+ BetweenVerticalStartIcon,
9
+ BoldIcon,
10
+ ChevronDownIcon,
11
+ Heading1Icon,
12
+ Heading2Icon,
13
+ Heading3Icon,
14
+ HighlighterIcon,
15
+ ImageIcon,
16
+ ItalicIcon,
17
+ LinkIcon,
18
+ ListIcon,
19
+ ListOrderedIcon,
20
+ MinusIcon,
21
+ PilcrowIcon,
22
+ RemoveFormattingIcon,
23
+ TableIcon,
24
+ TextAlignCenterIcon,
25
+ TextAlignEndIcon,
26
+ TextAlignJustifyIcon,
27
+ TextAlignStartIcon,
28
+ Trash2Icon,
29
+ UnderlineIcon,
30
+ UploadIcon,
31
+ } from 'lucide-react';
32
+ import { Extension, Mark, Node, mergeAttributes } from '@tiptap/core';
33
+ import { Table, TableCell, TableHeader, TableRow } from '@tiptap/extension-table';
34
+ import { TextAlign } from '@tiptap/extension-text-align';
35
+ import { Placeholder } from '@tiptap/extensions';
36
+ import { Fragment, type Node as PMNode, type Schema, Slice } from '@tiptap/pm/model';
37
+ import type { EditorView } from '@tiptap/pm/view';
38
+ import { type Editor, EditorContent, useEditor, useEditorState } from '@tiptap/react';
39
+ import StarterKit from '@tiptap/starter-kit';
40
+ import {
41
+ type FormEvent,
42
+ type ReactElement,
43
+ type ReactNode,
44
+ type Ref,
45
+ useImperativeHandle,
46
+ useRef,
47
+ useState,
48
+ } from 'react';
49
+ import { htmlHasFormatting, markdownToRich } from '../lib/markdown';
50
+ import { cn } from '../lib/utils';
51
+ import { Button } from './button';
52
+ import { ColorSwatchPicker } from './color-picker';
53
+ import {
54
+ DropdownMenu,
55
+ DropdownMenuContent,
56
+ DropdownMenuItem,
57
+ DropdownMenuRadioGroup,
58
+ DropdownMenuRadioItem,
59
+ DropdownMenuSeparator,
60
+ DropdownMenuTrigger,
61
+ } from './dropdown-menu';
62
+ import { Input } from './input';
63
+ import { Popover, PopoverContent, PopoverTrigger } from './popover';
64
+ import { Toggle } from './toggle';
65
+ import { Tooltip, TooltipContent, TooltipTrigger } from './tooltip';
66
+
67
+ // Editor de texto com formatação (D-339): estilo do texto em três títulos, negrito, itálico,
68
+ // sublinhado, cor do texto e de fundo, alinhamento, listas, link, imagem, tabela, linha divisória
69
+ // e limpar formatação, numa barra que acompanha a rolagem, D-755. Ao colar do Word ou do Google
70
+ // Docs, só fica o que a barra faz. Guarda o conteúdo estruturado, que o produto confere outra vez
71
+ // ao salvar. `RichTextView` mostra o mesmo texto só para ler, sem HTML solto, também na impressão.
72
+ //
73
+ // Campos para completar: com `fields`, trechos marcados de um modelo, como "Horário de
74
+ // atendimento", aparecem destacados até serem preenchidos (`fillRichField`).
75
+ //
76
+ // Imagem: o editor nunca envia arquivo. O produto passa `onUploadImage`, que guarda o arquivo e
77
+ // devolve o endereço, e `isAllowedImageSrc`, que diz quais endereços são dele. Colar ou arrastar
78
+ // imagem passa pela mesma função; endereço de fora ou `data:` não entra.
79
+
80
+ /** As cores da paleta de documento: a cor e o tom, de 1, o mais claro, a 5, o mais forte. */
81
+ export type RichHue =
82
+ 'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'purple' | 'pink';
83
+ export type RichColor = `${RichHue}-${1 | 2 | 3 | 4 | 5}`;
84
+
85
+ // Cada cor é um token do tema, `doc-<cor>-<tom>`, que inverte os tons no escuro, D-755. As classes
86
+ // ficam escritas por inteiro para o Tailwind achar.
87
+ const COLOR_TEXT: Record<RichColor, string> = {
88
+ 'gray-1': 'text-doc-gray-1',
89
+ 'gray-2': 'text-doc-gray-2',
90
+ 'gray-3': 'text-doc-gray-3',
91
+ 'gray-4': 'text-doc-gray-4',
92
+ 'gray-5': 'text-doc-gray-5',
93
+ 'red-1': 'text-doc-red-1',
94
+ 'red-2': 'text-doc-red-2',
95
+ 'red-3': 'text-doc-red-3',
96
+ 'red-4': 'text-doc-red-4',
97
+ 'red-5': 'text-doc-red-5',
98
+ 'orange-1': 'text-doc-orange-1',
99
+ 'orange-2': 'text-doc-orange-2',
100
+ 'orange-3': 'text-doc-orange-3',
101
+ 'orange-4': 'text-doc-orange-4',
102
+ 'orange-5': 'text-doc-orange-5',
103
+ 'yellow-1': 'text-doc-yellow-1',
104
+ 'yellow-2': 'text-doc-yellow-2',
105
+ 'yellow-3': 'text-doc-yellow-3',
106
+ 'yellow-4': 'text-doc-yellow-4',
107
+ 'yellow-5': 'text-doc-yellow-5',
108
+ 'green-1': 'text-doc-green-1',
109
+ 'green-2': 'text-doc-green-2',
110
+ 'green-3': 'text-doc-green-3',
111
+ 'green-4': 'text-doc-green-4',
112
+ 'green-5': 'text-doc-green-5',
113
+ 'teal-1': 'text-doc-teal-1',
114
+ 'teal-2': 'text-doc-teal-2',
115
+ 'teal-3': 'text-doc-teal-3',
116
+ 'teal-4': 'text-doc-teal-4',
117
+ 'teal-5': 'text-doc-teal-5',
118
+ 'blue-1': 'text-doc-blue-1',
119
+ 'blue-2': 'text-doc-blue-2',
120
+ 'blue-3': 'text-doc-blue-3',
121
+ 'blue-4': 'text-doc-blue-4',
122
+ 'blue-5': 'text-doc-blue-5',
123
+ 'purple-1': 'text-doc-purple-1',
124
+ 'purple-2': 'text-doc-purple-2',
125
+ 'purple-3': 'text-doc-purple-3',
126
+ 'purple-4': 'text-doc-purple-4',
127
+ 'purple-5': 'text-doc-purple-5',
128
+ 'pink-1': 'text-doc-pink-1',
129
+ 'pink-2': 'text-doc-pink-2',
130
+ 'pink-3': 'text-doc-pink-3',
131
+ 'pink-4': 'text-doc-pink-4',
132
+ 'pink-5': 'text-doc-pink-5',
133
+ };
134
+ const COLOR_BG: Record<RichColor, string> = {
135
+ 'gray-1': 'bg-doc-gray-1',
136
+ 'gray-2': 'bg-doc-gray-2',
137
+ 'gray-3': 'bg-doc-gray-3',
138
+ 'gray-4': 'bg-doc-gray-4',
139
+ 'gray-5': 'bg-doc-gray-5',
140
+ 'red-1': 'bg-doc-red-1',
141
+ 'red-2': 'bg-doc-red-2',
142
+ 'red-3': 'bg-doc-red-3',
143
+ 'red-4': 'bg-doc-red-4',
144
+ 'red-5': 'bg-doc-red-5',
145
+ 'orange-1': 'bg-doc-orange-1',
146
+ 'orange-2': 'bg-doc-orange-2',
147
+ 'orange-3': 'bg-doc-orange-3',
148
+ 'orange-4': 'bg-doc-orange-4',
149
+ 'orange-5': 'bg-doc-orange-5',
150
+ 'yellow-1': 'bg-doc-yellow-1',
151
+ 'yellow-2': 'bg-doc-yellow-2',
152
+ 'yellow-3': 'bg-doc-yellow-3',
153
+ 'yellow-4': 'bg-doc-yellow-4',
154
+ 'yellow-5': 'bg-doc-yellow-5',
155
+ 'green-1': 'bg-doc-green-1',
156
+ 'green-2': 'bg-doc-green-2',
157
+ 'green-3': 'bg-doc-green-3',
158
+ 'green-4': 'bg-doc-green-4',
159
+ 'green-5': 'bg-doc-green-5',
160
+ 'teal-1': 'bg-doc-teal-1',
161
+ 'teal-2': 'bg-doc-teal-2',
162
+ 'teal-3': 'bg-doc-teal-3',
163
+ 'teal-4': 'bg-doc-teal-4',
164
+ 'teal-5': 'bg-doc-teal-5',
165
+ 'blue-1': 'bg-doc-blue-1',
166
+ 'blue-2': 'bg-doc-blue-2',
167
+ 'blue-3': 'bg-doc-blue-3',
168
+ 'blue-4': 'bg-doc-blue-4',
169
+ 'blue-5': 'bg-doc-blue-5',
170
+ 'purple-1': 'bg-doc-purple-1',
171
+ 'purple-2': 'bg-doc-purple-2',
172
+ 'purple-3': 'bg-doc-purple-3',
173
+ 'purple-4': 'bg-doc-purple-4',
174
+ 'purple-5': 'bg-doc-purple-5',
175
+ 'pink-1': 'bg-doc-pink-1',
176
+ 'pink-2': 'bg-doc-pink-2',
177
+ 'pink-3': 'bg-doc-pink-3',
178
+ 'pink-4': 'bg-doc-pink-4',
179
+ 'pink-5': 'bg-doc-pink-5',
180
+ };
181
+ const HUE_NAMES: Record<RichHue, string> = {
182
+ gray: 'Cinza',
183
+ red: 'Vermelho',
184
+ orange: 'Laranja',
185
+ yellow: 'Amarelo',
186
+ green: 'Verde',
187
+ teal: 'Turquesa',
188
+ blue: 'Azul',
189
+ purple: 'Roxo',
190
+ pink: 'Rosa',
191
+ };
192
+ /** As cores aceitas, tom por tom, na ordem do quadro. */
193
+ export const RICH_COLORS = ([1, 2, 3, 4, 5] as const).flatMap((t) =>
194
+ (Object.keys(HUE_NAMES) as RichHue[]).map((h) => `${h}-${t}` as RichColor),
195
+ );
196
+ const isColor = (v: unknown): v is RichColor =>
197
+ typeof v === 'string' && Object.hasOwn(COLOR_TEXT, v);
198
+ // O quadro de cores: o sinal de escolhida fica escuro nos tons claros e claro nos fortes.
199
+ const SWATCHES = RICH_COLORS.map((c) => {
200
+ const [hue, tone] = c.split('-') as [RichHue, string];
201
+ return {
202
+ value: c,
203
+ label: `${HUE_NAMES[hue]}, tom ${tone}`,
204
+ className: cn(COLOR_BG[c], Number(tone) > 3 ? 'text-background' : 'text-foreground'),
205
+ };
206
+ });
207
+
208
+ type RichAlign = 'left' | 'center' | 'right' | 'justify';
209
+ const ALIGN_CLASS: Record<RichAlign, string> = {
210
+ left: 'text-left',
211
+ center: 'text-center',
212
+ right: 'text-right',
213
+ justify: 'text-justify',
214
+ };
215
+ const isAlign = (v: unknown): v is RichAlign =>
216
+ typeof v === 'string' && Object.hasOwn(ALIGN_CLASS, v);
217
+
218
+ /** Ferramentas da barra. `tools` escolhe quais valem; o que fica de fora também sai ao colar. */
219
+ export type RichTextTool =
220
+ | 'heading'
221
+ | 'bold'
222
+ | 'italic'
223
+ | 'underline'
224
+ | 'color'
225
+ | 'highlight'
226
+ | 'align'
227
+ | 'list'
228
+ | 'link'
229
+ | 'image'
230
+ | 'table'
231
+ | 'divider'
232
+ | 'clear';
233
+ /** Todas as ferramentas, o padrão. */
234
+ export const RICH_TEXT_TOOLS: RichTextTool[] = [
235
+ 'heading',
236
+ 'bold',
237
+ 'italic',
238
+ 'underline',
239
+ 'color',
240
+ 'highlight',
241
+ 'align',
242
+ 'list',
243
+ 'link',
244
+ 'image',
245
+ 'table',
246
+ 'divider',
247
+ 'clear',
248
+ ];
249
+
250
+ /** Tipos de imagem aceitos. SVG não entra: pode carregar código escondido. */
251
+ export const RICH_IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/webp'];
252
+
253
+ /** Guarda a imagem no produto e devolve o endereço dela. Erro com mensagem aparece na caixa. */
254
+ export type RichImageUpload = (file: File) => Promise<{ src: string; alt?: string }>;
255
+
256
+ type RichMark = {
257
+ type: string;
258
+ attrs?: { href?: string; key?: string; label?: string; filled?: boolean; color?: string };
259
+ };
260
+ type RichNode = {
261
+ type: string;
262
+ attrs?: {
263
+ level?: number;
264
+ start?: number;
265
+ textAlign?: string | null;
266
+ src?: string;
267
+ alt?: string | null;
268
+ colspan?: number;
269
+ rowspan?: number;
270
+ };
271
+ content?: RichNode[];
272
+ text?: string;
273
+ marks?: RichMark[];
274
+ };
275
+ /** O conteúdo guardado: o JSON do editor. */
276
+ export type RichDoc = { type: 'doc'; content?: RichNode[] };
277
+
278
+ /** Link só para página ou e-mail. */
279
+ const SAFE_HREF = /^(https?:\/\/|mailto:)/i;
280
+
281
+ /** Endereço de imagem: nunca `data:`, `blob:` ou código, e só o que o produto aprova. */
282
+ function imageOk(src: unknown, check?: (src: string) => boolean): src is string {
283
+ if (typeof src !== 'string' || !src.trim() || !check) return false;
284
+ if (/^\s*(data|blob|javascript|vbscript|file):/i.test(src)) return false;
285
+ return check(src);
286
+ }
287
+
288
+ /** Aparência do texto, igual no editor e na leitura, também na impressão. */
289
+ const PROSE =
290
+ 'text-body-13 break-words [print-color-adjust:exact] [&_h1]:mt-4 [&_h1]:text-heading-20 [&_h2]:mt-3 [&_h2]:text-heading-16 [&_h3]:mt-2 [&_h3]:text-heading-14 [&_ol]:list-decimal [&_ol]:pl-5 [&_ul]:list-disc [&_ul]:pl-5 [&_li>p]:my-0 [&_p]:my-1.5 [&_a]:text-link [&_a]:underline [&_a]:underline-offset-2 [&>*:first-child]:mt-0 [&_mark]:rounded-small [&_mark]:px-0.5 [&_mark[data-filled=false]]:bg-warning-subtle [&_mark[data-filled=false]]:text-warning-subtle-foreground [&_mark[data-filled=true]]:bg-transparent [&_mark[data-filled=true]]:text-inherit [&_[data-highlight]]:rounded-small [&_hr]:my-3 [&_hr]:border-border [&_img]:my-2 [&_img]:h-auto [&_img]:max-w-full [&_img]:rounded-control [&_img]:break-inside-avoid [&_table]:my-2 [&_table]:w-full [&_table]:table-fixed [&_table]:border-collapse [&_td]:border [&_td]:border-border [&_td]:px-2 [&_td]:py-1 [&_td]:align-top [&_th]:border [&_th]:border-border [&_th]:bg-muted [&_th]:px-2 [&_th]:py-1 [&_th]:text-left [&_th]:align-top [&_th]:text-body-13-medium [&_td>p]:my-0 [&_th>p]:my-0 [&_tr]:break-inside-avoid';
291
+
292
+ /** Endereço digitado vira link seguro: sem protocolo, ganha `https://`; o resto não passa. */
293
+ export function safeHref(raw: string): string | null {
294
+ const value = raw.trim();
295
+ if (!value) return null;
296
+ if (SAFE_HREF.test(value)) return value;
297
+ if (/^[a-z][a-z0-9+.-]*:/i.test(value)) return null;
298
+ return `https://${value}`;
299
+ }
300
+
301
+ const textOf = (nodes: RichNode[] = []): string =>
302
+ nodes.map((n) => (n.text ?? '') + textOf(n.content)).join('');
303
+ const hasMedia = (nodes: RichNode[] = []): boolean =>
304
+ nodes.some((n) => n.type === 'image' || n.type === 'horizontalRule' || hasMedia(n.content));
305
+
306
+ /** Sem nada escrito, só parágrafos vazios, conta como vazio. Imagem e linha contam como conteúdo. */
307
+ export function richIsEmpty(doc: RichDoc | null | undefined): boolean {
308
+ return !doc || (!textOf(doc.content).trim() && !hasMedia(doc.content));
309
+ }
310
+
311
+ /** O texto puro, para busca, IA e histórico. Cada linha de tabela vira uma linha, com tabs. */
312
+ export function richText(doc: RichDoc | null | undefined): string {
313
+ const lines = (nodes: RichNode[] = []): string[] =>
314
+ nodes.flatMap((n) => {
315
+ if (['paragraph', 'heading'].includes(n.type)) return [textOf(n.content)];
316
+ if (n.type === 'tableRow')
317
+ return [(n.content ?? []).map((c) => lines(c.content).join(' ')).join('\t')];
318
+ return lines(n.content);
319
+ });
320
+ return doc ? lines(doc.content).join('\n') : '';
321
+ }
322
+
323
+ /** Trecho de modelo para completar, como "Horário de atendimento". */
324
+ const FieldMark = Mark.create({
325
+ name: 'field',
326
+ inclusive: false,
327
+ addAttributes() {
328
+ return {
329
+ key: { default: null, parseHTML: (el) => el.getAttribute('data-field') },
330
+ label: { default: null, parseHTML: (el) => el.getAttribute('data-label') },
331
+ filled: {
332
+ default: false,
333
+ parseHTML: (el) => el.getAttribute('data-filled') === 'true',
334
+ renderHTML: (a) => ({ 'data-filled': a.filled ? 'true' : 'false' }),
335
+ },
336
+ };
337
+ },
338
+ parseHTML: () => [{ tag: 'mark[data-field]' }],
339
+ renderHTML: ({ HTMLAttributes }) => [
340
+ 'mark',
341
+ mergeAttributes(
342
+ { 'data-filled': HTMLAttributes['data-filled'] },
343
+ { 'data-field': HTMLAttributes.key, 'data-label': HTMLAttributes.label },
344
+ ),
345
+ 0,
346
+ ],
347
+ });
348
+
349
+ /** Cor do texto ou do fundo, sempre pelo nome da paleta, nunca por código de cor. */
350
+ function colorMark(
351
+ name: 'textColor' | 'highlight',
352
+ attr: string,
353
+ classes: Record<RichColor, string>,
354
+ ) {
355
+ return Mark.create({
356
+ name,
357
+ addAttributes() {
358
+ return {
359
+ color: {
360
+ default: null,
361
+ parseHTML: (el) => {
362
+ const c = el.getAttribute(attr);
363
+ return isColor(c) ? c : null;
364
+ },
365
+ renderHTML: (a) => (isColor(a.color) ? { [attr]: a.color, class: classes[a.color] } : {}),
366
+ },
367
+ };
368
+ },
369
+ parseHTML: () => [
370
+ { tag: `span[${attr}]`, getAttrs: (el) => (isColor(el.getAttribute(attr)) ? null : false) },
371
+ ],
372
+ renderHTML: ({ HTMLAttributes }) => ['span', HTMLAttributes, 0],
373
+ });
374
+ }
375
+ const TextColorMark = colorMark('textColor', 'data-text-color', COLOR_TEXT);
376
+ const HighlightMark = colorMark('highlight', 'data-highlight', COLOR_BG);
377
+
378
+ /** Imagem só com endereço aprovado pelo produto; a que não passa fica num aviso, sem carregar. */
379
+ function imageNode(check: () => ((src: string) => boolean) | undefined) {
380
+ return Node.create({
381
+ name: 'image',
382
+ group: 'block',
383
+ atom: true,
384
+ draggable: true,
385
+ selectable: true,
386
+ addAttributes() {
387
+ return {
388
+ src: { default: null },
389
+ alt: { default: null },
390
+ };
391
+ },
392
+ parseHTML() {
393
+ return [
394
+ {
395
+ tag: 'img[src]',
396
+ getAttrs: (el) => (imageOk(el.getAttribute('src'), check()) ? null : false),
397
+ },
398
+ ];
399
+ },
400
+ renderHTML({ node }) {
401
+ const { src, alt } = node.attrs as { src: unknown; alt: string | null };
402
+ if (imageOk(src, check())) return ['img', { src, alt: alt ?? '' }];
403
+ return [
404
+ 'span',
405
+ {
406
+ 'data-image-blocked': '',
407
+ class: 'my-2 block rounded-inner border border-dashed px-3 py-2 text-muted-foreground',
408
+ },
409
+ alt || 'Imagem fora do endereço aceito',
410
+ ];
411
+ },
412
+ });
413
+ }
414
+
415
+ /** Célula com parágrafos, sem lista, imagem ou tabela dentro. */
416
+ const Cell = TableCell.extend({ content: 'paragraph+' });
417
+ const HeaderCell = TableHeader.extend({ content: 'paragraph+' });
418
+
419
+ // Atalhos de cada ferramenta, que param quando ela está fora de `tools`.
420
+ const TOOL_KEYS: Partial<Record<RichTextTool, string[]>> = {
421
+ bold: ['Mod-b', 'Mod-B'],
422
+ italic: ['Mod-i', 'Mod-I'],
423
+ underline: ['Mod-u', 'Mod-U'],
424
+ heading: ['Mod-Alt-1', 'Mod-Alt-2', 'Mod-Alt-3'],
425
+ list: ['Mod-Shift-7', 'Mod-Shift-8'],
426
+ align: ['Mod-Shift-l', 'Mod-Shift-e', 'Mod-Shift-r', 'Mod-Shift-j'],
427
+ };
428
+ // Regras de digitação, como "# " para título, de cada ferramenta.
429
+ const TOOL_INPUT_RULES: Partial<Record<RichTextTool, string[]>> = {
430
+ bold: ['bold'],
431
+ italic: ['italic'],
432
+ underline: ['underline'],
433
+ heading: ['heading'],
434
+ list: ['bulletList', 'orderedList'],
435
+ divider: ['horizontalRule'],
436
+ link: ['link'],
437
+ };
438
+ const MARK_TOOL: Record<string, RichTextTool> = {
439
+ bold: 'bold',
440
+ italic: 'italic',
441
+ underline: 'underline',
442
+ link: 'link',
443
+ textColor: 'color',
444
+ highlight: 'highlight',
445
+ };
446
+ const NODE_TOOL: Record<string, RichTextTool> = {
447
+ heading: 'heading',
448
+ bulletList: 'list',
449
+ orderedList: 'list',
450
+ table: 'table',
451
+ horizontalRule: 'divider',
452
+ image: 'image',
453
+ };
454
+
455
+ /** O que se cola perde o que está fora de `tools`; numa linha, vira um trecho só. */
456
+ function cleanSlice(slice: Slice, allow: Set<RichTextTool>, schema: Schema, single: boolean) {
457
+ let changed = false;
458
+ const paragraph = schema.nodes.paragraph!;
459
+ const mapAll = (frag: Fragment): PMNode[] => {
460
+ const out: PMNode[] = [];
461
+ frag.forEach((n) => out.push(...mapNode(n)));
462
+ return out;
463
+ };
464
+ const inner = (n: PMNode): PMNode[] => {
465
+ const out: PMNode[] = [];
466
+ n.descendants((d) => {
467
+ if (!d.isTextblock) return true;
468
+ out.push(...mapNode(d));
469
+ return false;
470
+ });
471
+ return out;
472
+ };
473
+ const mapNode = (n: PMNode): PMNode[] => {
474
+ if (n.isText) {
475
+ const marks = n.marks.filter((m) => {
476
+ const tool = MARK_TOOL[m.type.name];
477
+ return !tool || allow.has(tool);
478
+ });
479
+ if (marks.length === n.marks.length) return [n];
480
+ changed = true;
481
+ return [n.mark(marks)];
482
+ }
483
+ let attrs = n.attrs;
484
+ if (attrs.textAlign && !allow.has('align')) {
485
+ changed = true;
486
+ attrs = { ...attrs, textAlign: null };
487
+ }
488
+ const tool = NODE_TOOL[n.type.name];
489
+ if (tool && !allow.has(tool)) {
490
+ changed = true;
491
+ if (n.type.name === 'heading')
492
+ return [paragraph.create({ textAlign: attrs.textAlign ?? null }, mapAll(n.content))];
493
+ if (n.isAtom) return [];
494
+ return inner(n);
495
+ }
496
+ return [n.type.create(attrs, mapAll(n.content), n.marks)];
497
+ };
498
+ const nodes = mapAll(slice.content);
499
+ if (single) {
500
+ const run: PMNode[] = [];
501
+ const take = (n: PMNode) => {
502
+ if (n.isText) run.push(n);
503
+ else if (n.isTextblock) {
504
+ if (run.length) run.push(schema.text(' '));
505
+ n.forEach(take);
506
+ } else n.forEach(take);
507
+ };
508
+ nodes.forEach(take);
509
+ return new Slice(Fragment.from(paragraph.create(null, run)), 1, 1);
510
+ }
511
+ return changed ? Slice.maxOpen(Fragment.from(nodes)) : slice;
512
+ }
513
+
514
+ /**
515
+ * Texto puro com cara de Markdown entra já formatado: `#`, `##` e `###` viram Título 1, 2 e 3.
516
+ * HTML de verdade, como o do Word ou de um site, segue o caminho de sempre. Numa célula de
517
+ * tabela, só negrito e itálico, porque ali não cabe título nem lista.
518
+ */
519
+ function pasteMarkdown(view: EditorView, event: ClipboardEvent, allow: Set<RichTextTool>) {
520
+ const data = event.clipboardData;
521
+ const text = data?.getData('text/plain');
522
+ if (!text) return false;
523
+ const html = data?.getData('text/html');
524
+ if (html && htmlHasFormatting(html)) return false;
525
+ const { $from } = view.state.selection;
526
+ let inCell = false;
527
+ for (let d = $from.depth; d > 0; d--) if ($from.node(d).type.spec.tableRole) inCell = true;
528
+ const tools = inCell
529
+ ? new Set<RichTextTool>((['bold', 'italic'] as const).filter((t) => allow.has(t)))
530
+ : allow;
531
+ const nodes = markdownToRich(text, { has: (t) => tools.has(t) });
532
+ if (!nodes) return false;
533
+ const { schema } = view.state;
534
+ const pasted = Slice.maxOpen(Fragment.fromArray(nodes.map((n) => schema.nodeFromJSON(n))));
535
+ const slice = cleanSlice(pasted, allow, schema, false);
536
+ view.dispatch(
537
+ view.state.tr
538
+ .replaceSelection(slice)
539
+ .scrollIntoView()
540
+ .setMeta('paste', true)
541
+ .setMeta('uiEvent', 'paste'),
542
+ );
543
+ return true;
544
+ }
545
+
546
+ /** Campos para completar do texto, pela ordem em que aparecem. */
547
+ export function richFields(doc: RichDoc | null | undefined) {
548
+ const out = new Map<string, { key: string; label: string; value: string; filled: boolean }>();
549
+ const walk = (nodes: RichNode[] = []) =>
550
+ nodes.forEach((n) => {
551
+ const m = n.marks?.find((x) => x.type === 'field');
552
+ if (m?.attrs?.key && !out.has(m.attrs.key))
553
+ out.set(m.attrs.key, {
554
+ key: m.attrs.key,
555
+ label: m.attrs.label ?? n.text ?? '',
556
+ value: m.attrs.filled ? (n.text ?? '') : '',
557
+ filled: !!m.attrs.filled,
558
+ });
559
+ walk(n.content);
560
+ });
561
+ walk(doc?.content);
562
+ return [...out.values()];
563
+ }
564
+
565
+ /** Preenche um campo: o texto troca, e o destaque some. Vazio volta ao nome do campo. */
566
+ export function fillRichField(doc: RichDoc, key: string, value: string): RichDoc {
567
+ const map = (nodes: RichNode[] = []): RichNode[] =>
568
+ nodes.map((n) => {
569
+ const m = n.marks?.find((x) => x.type === 'field' && x.attrs?.key === key);
570
+ if (m)
571
+ return {
572
+ ...n,
573
+ text: value.trim() || m.attrs?.label || n.text,
574
+ marks: n.marks?.map((x) =>
575
+ x === m ? { ...x, attrs: { ...x.attrs, filled: !!value.trim() } } : x,
576
+ ),
577
+ };
578
+ return n.content ? { ...n, content: map(n.content) } : n;
579
+ });
580
+ return { ...doc, content: map(doc.content) };
581
+ }
582
+
583
+ const TOOL_CLASS = 'size-control-xs min-w-control-xs px-0';
584
+ const MENU_CLASS = 'h-control-xs min-w-control-xs gap-0.5 px-1';
585
+
586
+ /** Dica com o nome por cima de um gatilho, como o de um menu ou de um balão. */
587
+ function Tip({
588
+ label,
589
+ trigger,
590
+ children,
591
+ }: {
592
+ label: string;
593
+ trigger: ReactElement;
594
+ children: ReactNode;
595
+ }) {
596
+ return (
597
+ <Tooltip>
598
+ <TooltipTrigger render={trigger}>{children}</TooltipTrigger>
599
+ <TooltipContent>{label}</TooltipContent>
600
+ </Tooltip>
601
+ );
602
+ }
603
+
604
+ function ToolButton({
605
+ label,
606
+ shortcut,
607
+ pressed,
608
+ onClick,
609
+ children,
610
+ }: {
611
+ label: string;
612
+ shortcut?: string;
613
+ pressed: boolean;
614
+ onClick: () => void;
615
+ children: ReactNode;
616
+ }) {
617
+ return (
618
+ <Tip
619
+ label={shortcut ? `${label} (${shortcut})` : label}
620
+ trigger={
621
+ <Toggle
622
+ size="sm"
623
+ aria-label={label}
624
+ pressed={pressed}
625
+ onPressedChange={onClick}
626
+ className={TOOL_CLASS}
627
+ />
628
+ }
629
+ >
630
+ {children}
631
+ </Tip>
632
+ );
633
+ }
634
+
635
+ /**
636
+ * Ação de um menu da barra, que só roda depois que o menu fecha: assim o cursor não volta para
637
+ * onde estava antes, como ao inserir uma tabela. Sem ação, como no Esc, o foco volta ao botão.
638
+ */
639
+ function useMenuAction(editor: Editor) {
640
+ const pending = useRef<(() => void) | null>(null);
641
+ return {
642
+ later: (fn: () => void) => {
643
+ pending.current = fn;
644
+ },
645
+ onOpenChangeComplete: (open: boolean) => {
646
+ const fn = pending.current;
647
+ pending.current = null;
648
+ if (open || !fn) return;
649
+ // A caixa recebe o foco antes e a ação vem depois, quando o navegador já devolveu a
650
+ // seleção antiga; senão, ela passa por cima da nova.
651
+ editor.view.focus();
652
+ setTimeout(() => {
653
+ if (!editor.isDestroyed) fn();
654
+ }, 30);
655
+ },
656
+ finalFocus: () => !pending.current,
657
+ };
658
+ }
659
+
660
+ const HEADINGS = [
661
+ { level: 0, label: 'Texto normal', icon: PilcrowIcon },
662
+ { level: 1, label: 'Título 1', icon: Heading1Icon },
663
+ { level: 2, label: 'Título 2', icon: Heading2Icon },
664
+ { level: 3, label: 'Título 3', icon: Heading3Icon },
665
+ ] as const;
666
+
667
+ function HeadingMenu({ editor, level }: { editor: Editor; level: number }) {
668
+ const menu = useMenuAction(editor);
669
+ const Current = HEADINGS.find((h) => h.level === level)?.icon ?? PilcrowIcon;
670
+ return (
671
+ <DropdownMenu onOpenChangeComplete={menu.onOpenChangeComplete}>
672
+ <Tip
673
+ label="Estilo do texto"
674
+ trigger={
675
+ <DropdownMenuTrigger
676
+ render={
677
+ <Toggle
678
+ size="sm"
679
+ aria-label="Estilo do texto"
680
+ pressed={level > 0}
681
+ className={MENU_CLASS}
682
+ />
683
+ }
684
+ />
685
+ }
686
+ >
687
+ <Current />
688
+ <ChevronDownIcon className="size-icon-xs text-muted-foreground" />
689
+ </Tip>
690
+ <DropdownMenuContent finalFocus={menu.finalFocus}>
691
+ <DropdownMenuRadioGroup
692
+ value={String(level)}
693
+ onValueChange={(v) => {
694
+ const n = Number(v) as 0 | 1 | 2 | 3;
695
+ menu.later(() => {
696
+ const chain = editor.chain().focus();
697
+ (n ? chain.setHeading({ level: n }) : chain.setParagraph()).run();
698
+ });
699
+ }}
700
+ >
701
+ {HEADINGS.map(({ level: l, label, icon: Icon }) => (
702
+ <DropdownMenuRadioItem key={l} value={String(l)}>
703
+ <Icon />
704
+ {label}
705
+ </DropdownMenuRadioItem>
706
+ ))}
707
+ </DropdownMenuRadioGroup>
708
+ </DropdownMenuContent>
709
+ </DropdownMenu>
710
+ );
711
+ }
712
+
713
+ const ALIGNS = [
714
+ { value: 'left', label: 'À esquerda', icon: TextAlignStartIcon },
715
+ { value: 'center', label: 'Ao centro', icon: TextAlignCenterIcon },
716
+ { value: 'right', label: 'À direita', icon: TextAlignEndIcon },
717
+ { value: 'justify', label: 'Justificado', icon: TextAlignJustifyIcon },
718
+ ] as const;
719
+
720
+ function AlignMenu({ editor, align }: { editor: Editor; align: RichAlign }) {
721
+ const menu = useMenuAction(editor);
722
+ const Current = ALIGNS.find((a) => a.value === align)?.icon ?? TextAlignStartIcon;
723
+ return (
724
+ <DropdownMenu onOpenChangeComplete={menu.onOpenChangeComplete}>
725
+ <Tip
726
+ label="Alinhamento"
727
+ trigger={
728
+ <DropdownMenuTrigger
729
+ render={
730
+ <Toggle
731
+ size="sm"
732
+ aria-label="Alinhamento"
733
+ pressed={align !== 'left'}
734
+ className={MENU_CLASS}
735
+ />
736
+ }
737
+ />
738
+ }
739
+ >
740
+ <Current />
741
+ <ChevronDownIcon className="size-icon-xs text-muted-foreground" />
742
+ </Tip>
743
+ <DropdownMenuContent finalFocus={menu.finalFocus}>
744
+ <DropdownMenuRadioGroup
745
+ value={align}
746
+ onValueChange={(v) => {
747
+ menu.later(() => {
748
+ const chain = editor.chain().focus();
749
+ (v === 'left' ? chain.unsetTextAlign() : chain.setTextAlign(v as string)).run();
750
+ });
751
+ }}
752
+ >
753
+ {ALIGNS.map(({ value, label, icon: Icon }) => (
754
+ <DropdownMenuRadioItem key={value} value={value}>
755
+ <Icon />
756
+ {label}
757
+ </DropdownMenuRadioItem>
758
+ ))}
759
+ </DropdownMenuRadioGroup>
760
+ </DropdownMenuContent>
761
+ </DropdownMenu>
762
+ );
763
+ }
764
+
765
+ function ColorButton({
766
+ editor,
767
+ kind,
768
+ value,
769
+ }: {
770
+ editor: Editor;
771
+ kind: 'textColor' | 'highlight';
772
+ value: RichColor | null;
773
+ }) {
774
+ const [open, setOpen] = useState(false);
775
+ const label = kind === 'textColor' ? 'Cor do texto' : 'Cor de fundo';
776
+ function pick(color: RichColor | null) {
777
+ const chain = editor.chain().focus();
778
+ (color ? chain.setMark(kind, { color }) : chain.unsetMark(kind)).run();
779
+ setOpen(false);
780
+ }
781
+ return (
782
+ <Popover open={open} onOpenChange={setOpen}>
783
+ <Tip
784
+ label={label}
785
+ trigger={
786
+ <PopoverTrigger
787
+ render={
788
+ <Toggle size="sm" aria-label={label} pressed={!!value} className={TOOL_CLASS} />
789
+ }
790
+ />
791
+ }
792
+ >
793
+ {kind === 'textColor' ? <BaselineIcon /> : <HighlighterIcon />}
794
+ </Tip>
795
+ <PopoverContent align="start" className="w-auto" finalFocus={false}>
796
+ <div className="flex flex-col gap-3">
797
+ <p className="text-body-12-medium text-muted-foreground">{label}</p>
798
+ <Button
799
+ type="button"
800
+ size="sm"
801
+ variant="ghost"
802
+ className="justify-start"
803
+ disabled={!value}
804
+ onClick={() => pick(null)}
805
+ >
806
+ <RemoveFormattingIcon />
807
+ Nenhuma
808
+ </Button>
809
+ <ColorSwatchPicker
810
+ aria-label={label}
811
+ size="sm"
812
+ colors={SWATCHES}
813
+ value={value ?? ''}
814
+ onValueChange={(v) => pick(isColor(v) ? v : null)}
815
+ className="grid grid-cols-9"
816
+ />
817
+ </div>
818
+ </PopoverContent>
819
+ </Popover>
820
+ );
821
+ }
822
+
823
+ function TableMenu({ editor, inTable }: { editor: Editor; inTable: boolean }) {
824
+ const menu = useMenuAction(editor);
825
+ const run = (fn: (c: ReturnType<Editor['chain']>) => ReturnType<Editor['chain']>) =>
826
+ menu.later(() => fn(editor.chain().focus()).run());
827
+ return (
828
+ <DropdownMenu onOpenChangeComplete={menu.onOpenChangeComplete}>
829
+ <Tip
830
+ label="Tabela"
831
+ trigger={
832
+ <DropdownMenuTrigger
833
+ render={
834
+ <Toggle size="sm" aria-label="Tabela" pressed={inTable} className={MENU_CLASS} />
835
+ }
836
+ />
837
+ }
838
+ >
839
+ <TableIcon />
840
+ <ChevronDownIcon className="size-icon-xs text-muted-foreground" />
841
+ </Tip>
842
+ <DropdownMenuContent finalFocus={menu.finalFocus}>
843
+ <DropdownMenuItem
844
+ disabled={inTable}
845
+ onClick={() => run((c) => c.insertTable({ rows: 3, cols: 3, withHeaderRow: true }))}
846
+ >
847
+ <TableIcon />
848
+ Inserir tabela
849
+ </DropdownMenuItem>
850
+ <DropdownMenuSeparator />
851
+ <DropdownMenuItem disabled={!inTable} onClick={() => run((c) => c.addRowBefore())}>
852
+ <BetweenHorizontalStartIcon />
853
+ Linha acima
854
+ </DropdownMenuItem>
855
+ <DropdownMenuItem disabled={!inTable} onClick={() => run((c) => c.addRowAfter())}>
856
+ <BetweenHorizontalEndIcon />
857
+ Linha abaixo
858
+ </DropdownMenuItem>
859
+ <DropdownMenuItem disabled={!inTable} onClick={() => run((c) => c.addColumnBefore())}>
860
+ <BetweenVerticalStartIcon />
861
+ Coluna à esquerda
862
+ </DropdownMenuItem>
863
+ <DropdownMenuItem disabled={!inTable} onClick={() => run((c) => c.addColumnAfter())}>
864
+ <BetweenVerticalEndIcon />
865
+ Coluna à direita
866
+ </DropdownMenuItem>
867
+ <DropdownMenuSeparator />
868
+ <DropdownMenuItem
869
+ variant="destructive"
870
+ disabled={!inTable}
871
+ onClick={() => run((c) => c.deleteRow())}
872
+ >
873
+ <Trash2Icon data-danger />
874
+ Remover linha
875
+ </DropdownMenuItem>
876
+ <DropdownMenuItem
877
+ variant="destructive"
878
+ disabled={!inTable}
879
+ onClick={() => run((c) => c.deleteColumn())}
880
+ >
881
+ <Trash2Icon data-danger />
882
+ Remover coluna
883
+ </DropdownMenuItem>
884
+ <DropdownMenuItem
885
+ variant="destructive"
886
+ disabled={!inTable}
887
+ onClick={() => run((c) => c.deleteTable())}
888
+ >
889
+ <Trash2Icon data-danger />
890
+ Apagar tabela
891
+ </DropdownMenuItem>
892
+ </DropdownMenuContent>
893
+ </DropdownMenu>
894
+ );
895
+ }
896
+
897
+ function ImageButton({
898
+ editor,
899
+ selected,
900
+ alt,
901
+ busy,
902
+ onPick,
903
+ }: {
904
+ editor: Editor;
905
+ selected: boolean;
906
+ alt: string;
907
+ busy: boolean;
908
+ onPick: (file: File, alt: string) => void;
909
+ }) {
910
+ const [open, setOpen] = useState(false);
911
+ const [text, setText] = useState('');
912
+ const file = useRef<HTMLInputElement>(null);
913
+
914
+ function openChange(next: boolean) {
915
+ if (next) setText(selected ? alt : '');
916
+ setOpen(next);
917
+ }
918
+
919
+ function apply(e: FormEvent) {
920
+ e.preventDefault();
921
+ e.stopPropagation();
922
+ editor
923
+ .chain()
924
+ .focus()
925
+ .updateAttributes('image', { alt: text.trim() || null })
926
+ .run();
927
+ setOpen(false);
928
+ }
929
+
930
+ return (
931
+ <Popover open={open} onOpenChange={openChange}>
932
+ <Tip
933
+ label="Imagem"
934
+ trigger={
935
+ <PopoverTrigger
936
+ render={
937
+ <Toggle
938
+ size="sm"
939
+ aria-label="Imagem"
940
+ pressed={selected}
941
+ disabled={busy}
942
+ className={TOOL_CLASS}
943
+ />
944
+ }
945
+ />
946
+ }
947
+ >
948
+ <ImageIcon />
949
+ </Tip>
950
+ <PopoverContent align="start" className="w-80" finalFocus={false}>
951
+ <form onSubmit={apply} className="flex flex-col gap-2">
952
+ <Input
953
+ aria-label="Texto alternativo"
954
+ placeholder="Descreva a imagem, para quem não consegue ver"
955
+ value={text}
956
+ onChange={(e) => setText(e.target.value)}
957
+ autoFocus
958
+ />
959
+ {!selected && <p className="text-body-12 text-muted-foreground">PNG, JPG ou WebP.</p>}
960
+ <input
961
+ ref={file}
962
+ type="file"
963
+ accept={RICH_IMAGE_TYPES.join(',')}
964
+ className="hidden"
965
+ onChange={(e) => {
966
+ const f = e.target.files?.[0];
967
+ e.target.value = '';
968
+ if (!f) return;
969
+ setOpen(false);
970
+ onPick(f, text.trim());
971
+ }}
972
+ />
973
+ <div className="flex justify-end gap-2">
974
+ {selected ? (
975
+ <>
976
+ <Button
977
+ type="button"
978
+ size="sm"
979
+ variant="destructive"
980
+ onClick={() => {
981
+ editor.chain().focus().deleteSelection().run();
982
+ setOpen(false);
983
+ }}
984
+ >
985
+ <Trash2Icon data-danger />
986
+ Remover imagem
987
+ </Button>
988
+ <Button type="submit" size="sm">
989
+ Aplicar
990
+ </Button>
991
+ </>
992
+ ) : (
993
+ <Button type="button" size="sm" onClick={() => file.current?.click()}>
994
+ <UploadIcon />
995
+ Escolher imagem
996
+ </Button>
997
+ )}
998
+ </div>
999
+ </form>
1000
+ </PopoverContent>
1001
+ </Popover>
1002
+ );
1003
+ }
1004
+
1005
+ function LinkButton({ editor, active }: { editor: Editor; active: boolean }) {
1006
+ const [open, setOpen] = useState(false);
1007
+ const [value, setValue] = useState('');
1008
+ const [invalid, setInvalid] = useState(false);
1009
+
1010
+ function openChange(next: boolean) {
1011
+ if (next) {
1012
+ setValue((editor.getAttributes('link').href as string | undefined) ?? '');
1013
+ setInvalid(false);
1014
+ }
1015
+ setOpen(next);
1016
+ }
1017
+
1018
+ function apply(e: FormEvent) {
1019
+ e.preventDefault();
1020
+ e.stopPropagation();
1021
+ const href = safeHref(value);
1022
+ if (!href) return setInvalid(true);
1023
+ const chain = editor.chain().focus().extendMarkRange('link');
1024
+ if (editor.state.selection.empty && !active) {
1025
+ chain
1026
+ .insertContent({
1027
+ type: 'text',
1028
+ text: value.trim(),
1029
+ marks: [{ type: 'link', attrs: { href } }],
1030
+ })
1031
+ .run();
1032
+ } else {
1033
+ chain.setLink({ href }).run();
1034
+ }
1035
+ setOpen(false);
1036
+ }
1037
+
1038
+ return (
1039
+ <Popover open={open} onOpenChange={openChange}>
1040
+ <Tip
1041
+ label="Link"
1042
+ trigger={
1043
+ <PopoverTrigger
1044
+ render={<Toggle size="sm" aria-label="Link" pressed={active} className={TOOL_CLASS} />}
1045
+ />
1046
+ }
1047
+ >
1048
+ <LinkIcon />
1049
+ </Tip>
1050
+ <PopoverContent align="start" className="w-80" finalFocus={false}>
1051
+ <form onSubmit={apply} className="flex flex-col gap-2">
1052
+ <Input
1053
+ aria-label="Endereço do link"
1054
+ aria-invalid={invalid || undefined}
1055
+ placeholder="https://site.com.br ou mailto:email@site.com.br"
1056
+ value={value}
1057
+ onChange={(e) => {
1058
+ setValue(e.target.value);
1059
+ setInvalid(false);
1060
+ }}
1061
+ autoFocus
1062
+ />
1063
+ {invalid && (
1064
+ <p className="text-body-12 text-destructive">
1065
+ Use um endereço de site, com https://, ou de e-mail, com mailto:.
1066
+ </p>
1067
+ )}
1068
+ <div className="flex justify-end gap-2">
1069
+ {active && (
1070
+ <Button
1071
+ type="button"
1072
+ size="sm"
1073
+ variant="ghost"
1074
+ onClick={() => {
1075
+ editor.chain().focus().extendMarkRange('link').unsetLink().run();
1076
+ setOpen(false);
1077
+ }}
1078
+ >
1079
+ Tirar link
1080
+ </Button>
1081
+ )}
1082
+ <Button type="submit" size="sm">
1083
+ Aplicar
1084
+ </Button>
1085
+ </div>
1086
+ </form>
1087
+ </PopoverContent>
1088
+ </Popover>
1089
+ );
1090
+ }
1091
+
1092
+ function Toolbar({
1093
+ editor,
1094
+ tools,
1095
+ bare,
1096
+ busy,
1097
+ onPickImage,
1098
+ }: {
1099
+ editor: Editor;
1100
+ tools: Set<RichTextTool>;
1101
+ bare?: boolean;
1102
+ busy: boolean;
1103
+ onPickImage: (file: File, alt: string) => void;
1104
+ }) {
1105
+ const state = useEditorState({
1106
+ editor,
1107
+ selector: ({ editor: e }) => ({
1108
+ bold: e.isActive('bold'),
1109
+ italic: e.isActive('italic'),
1110
+ underline: e.isActive('underline'),
1111
+ level: [1, 2, 3].find((level) => e.isActive('heading', { level })) ?? 0,
1112
+ align: ((['center', 'right', 'justify'] as const).find((a) => e.isActive({ textAlign: a })) ??
1113
+ 'left') as RichAlign,
1114
+ color: (e.getAttributes('textColor').color as RichColor | undefined) ?? null,
1115
+ highlight: (e.getAttributes('highlight').color as RichColor | undefined) ?? null,
1116
+ bullet: e.isActive('bulletList'),
1117
+ ordered: e.isActive('orderedList'),
1118
+ link: e.isActive('link'),
1119
+ table: e.isActive('table'),
1120
+ image: e.isActive('image'),
1121
+ alt: e.isActive('image') ? ((e.getAttributes('image').alt as string | null) ?? '') : '',
1122
+ }),
1123
+ });
1124
+ const run = () => editor.chain().focus();
1125
+ const on = (t: RichTextTool) => tools.has(t);
1126
+
1127
+ function clear() {
1128
+ const chain = run()
1129
+ .unsetMark('bold')
1130
+ .unsetMark('italic')
1131
+ .unsetMark('underline')
1132
+ .unsetMark('textColor')
1133
+ .unsetMark('highlight')
1134
+ .unsetTextAlign();
1135
+ (state.level ? chain.setParagraph() : chain).run();
1136
+ }
1137
+
1138
+ const groups: ReactNode[][] = [
1139
+ [on('heading') && <HeadingMenu key="h" editor={editor} level={state.level} />],
1140
+ [
1141
+ on('bold') && (
1142
+ <ToolButton
1143
+ key="b"
1144
+ label="Negrito"
1145
+ shortcut="Ctrl+B"
1146
+ pressed={state.bold}
1147
+ onClick={() => run().toggleBold().run()}
1148
+ >
1149
+ <BoldIcon />
1150
+ </ToolButton>
1151
+ ),
1152
+ on('italic') && (
1153
+ <ToolButton
1154
+ key="i"
1155
+ label="Itálico"
1156
+ shortcut="Ctrl+I"
1157
+ pressed={state.italic}
1158
+ onClick={() => run().toggleItalic().run()}
1159
+ >
1160
+ <ItalicIcon />
1161
+ </ToolButton>
1162
+ ),
1163
+ on('underline') && (
1164
+ <ToolButton
1165
+ key="u"
1166
+ label="Sublinhado"
1167
+ shortcut="Ctrl+U"
1168
+ pressed={state.underline}
1169
+ onClick={() => run().toggleUnderline().run()}
1170
+ >
1171
+ <UnderlineIcon />
1172
+ </ToolButton>
1173
+ ),
1174
+ on('color') && <ColorButton key="c" editor={editor} kind="textColor" value={state.color} />,
1175
+ on('highlight') && (
1176
+ <ColorButton key="hl" editor={editor} kind="highlight" value={state.highlight} />
1177
+ ),
1178
+ ],
1179
+ [
1180
+ on('align') && <AlignMenu key="a" editor={editor} align={state.align} />,
1181
+ on('list') && (
1182
+ <ToolButton
1183
+ key="ul"
1184
+ label="Lista com marcadores"
1185
+ pressed={state.bullet}
1186
+ onClick={() => run().toggleBulletList().run()}
1187
+ >
1188
+ <ListIcon />
1189
+ </ToolButton>
1190
+ ),
1191
+ on('list') && (
1192
+ <ToolButton
1193
+ key="ol"
1194
+ label="Lista numerada"
1195
+ pressed={state.ordered}
1196
+ onClick={() => run().toggleOrderedList().run()}
1197
+ >
1198
+ <ListOrderedIcon />
1199
+ </ToolButton>
1200
+ ),
1201
+ ],
1202
+ [
1203
+ on('link') && <LinkButton key="l" editor={editor} active={state.link} />,
1204
+ on('image') && (
1205
+ <ImageButton
1206
+ key="img"
1207
+ editor={editor}
1208
+ selected={state.image}
1209
+ alt={state.alt}
1210
+ busy={busy}
1211
+ onPick={onPickImage}
1212
+ />
1213
+ ),
1214
+ on('table') && <TableMenu key="t" editor={editor} inTable={state.table} />,
1215
+ on('divider') && (
1216
+ <ToolButton
1217
+ key="hr"
1218
+ label="Linha divisória"
1219
+ pressed={false}
1220
+ onClick={() => run().setHorizontalRule().run()}
1221
+ >
1222
+ <MinusIcon />
1223
+ </ToolButton>
1224
+ ),
1225
+ ],
1226
+ [
1227
+ on('clear') && (
1228
+ <ToolButton key="x" label="Limpar formatação" pressed={false} onClick={clear}>
1229
+ <RemoveFormattingIcon />
1230
+ </ToolButton>
1231
+ ),
1232
+ ],
1233
+ ]
1234
+ .map((g) => g.filter(Boolean))
1235
+ .filter((g) => g.length);
1236
+
1237
+ if (!groups.length) return null;
1238
+ return (
1239
+ // A barra acompanha a rolagem e fica no alto da caixa enquanto se escreve, D-755.
1240
+ <div className={cn('sticky top-0 z-10 bg-background', !bare && 'rounded-t-control')}>
1241
+ <div
1242
+ role="toolbar"
1243
+ aria-label="Formatação"
1244
+ className={cn(
1245
+ 'flex flex-wrap items-center gap-0.5 border-b px-1.5 py-1',
1246
+ !bare && 'rounded-t-control dark:bg-input/30',
1247
+ )}
1248
+ >
1249
+ {groups.map((g, i) => (
1250
+ <span key={i} className="contents">
1251
+ {i > 0 && <span aria-hidden className="mx-1 h-4 w-px bg-border" />}
1252
+ {g}
1253
+ </span>
1254
+ ))}
1255
+ </div>
1256
+ </div>
1257
+ );
1258
+ }
1259
+
1260
+ /** Para o produto agir na caixa, como pôr uma variável onde está o cursor. */
1261
+ export type RichTextHandle = {
1262
+ /** Põe um campo para completar, como uma variável, onde está o cursor. */
1263
+ insertField: (field: { key: string; label: string }) => void;
1264
+ focus: () => void;
1265
+ };
1266
+
1267
+ /**
1268
+ * Caixa de texto com formatação. Não é controlada: começa com `value` e avisa cada mudança em
1269
+ * `onChange`, com `null` quando vazia. Para trocar o conteúdo, as ferramentas ou o modo de fora,
1270
+ * troque a `key`.
1271
+ */
1272
+ export function RichTextEditor({
1273
+ value,
1274
+ onChange,
1275
+ label,
1276
+ placeholder,
1277
+ autoFocus,
1278
+ editable = true,
1279
+ bare,
1280
+ className,
1281
+ contentClassName,
1282
+ footer,
1283
+ tools = RICH_TEXT_TOOLS,
1284
+ singleLine,
1285
+ onUploadImage,
1286
+ isAllowedImageSrc,
1287
+ ref,
1288
+ }: {
1289
+ value?: RichDoc | null;
1290
+ onChange: (doc: RichDoc | null) => void;
1291
+ /** Nome da caixa para leitores de tela. */
1292
+ label: string;
1293
+ placeholder?: string;
1294
+ autoFocus?: boolean;
1295
+ /** Falso: só leitura, sem a barra, como numa proposta já aceita. */
1296
+ editable?: boolean;
1297
+ /** Sem borda própria, dentro de um cartão que já tem. */
1298
+ bare?: boolean;
1299
+ className?: string;
1300
+ /** Classes da área de texto, como a altura mínima. */
1301
+ contentClassName?: string;
1302
+ /** Embaixo da caixa, dentro da borda, como um botão Salvar. */
1303
+ footer?: ReactNode;
1304
+ /** Ferramentas da barra; o que fica de fora também sai ao colar. Padrão: todas. */
1305
+ tools?: RichTextTool[];
1306
+ /**
1307
+ * Uma linha só, sem barra e sem Enter, para título ou célula. Campos para completar, como as
1308
+ * variáveis, seguem como etiqueta.
1309
+ */
1310
+ singleLine?: boolean;
1311
+ /** Guarda a imagem e devolve o endereço. Sem ela, ou sem `isAllowedImageSrc`, não há imagem. */
1312
+ onUploadImage?: RichImageUpload;
1313
+ /** Diz se o endereço da imagem é do produto. Só o que passa aparece ou entra ao colar. */
1314
+ isAllowedImageSrc?: (src: string) => boolean;
1315
+ ref?: Ref<RichTextHandle>;
1316
+ }) {
1317
+ const latest = useRef({ onUploadImage, isAllowedImageSrc });
1318
+ latest.current = { onUploadImage, isAllowedImageSrc };
1319
+ const [notice, setNotice] = useState<string | null>(null);
1320
+ const [busy, setBusy] = useState(0);
1321
+
1322
+ const imagesOn = !singleLine && !!onUploadImage && !!isAllowedImageSrc;
1323
+ const allow = new Set(singleLine ? [] : tools.filter((t) => t !== 'image' || imagesOn));
1324
+ const allowRef = useRef(allow);
1325
+ const editorRef = useRef<Editor | null>(null);
1326
+
1327
+ async function insertImages(files: File[], pos?: number, alt?: string) {
1328
+ const upload = latest.current.onUploadImage;
1329
+ const ed = editorRef.current;
1330
+ if (!upload || !ed) return;
1331
+ setNotice(null);
1332
+ for (const file of files) {
1333
+ if (!RICH_IMAGE_TYPES.includes(file.type)) {
1334
+ setNotice('A imagem precisa ser PNG, JPG ou WebP.');
1335
+ continue;
1336
+ }
1337
+ setBusy((n) => n + 1);
1338
+ try {
1339
+ const res = await upload(file);
1340
+ if (!imageOk(res.src, latest.current.isAllowedImageSrc))
1341
+ throw new Error('A imagem voltou com um endereço que não é aceito.');
1342
+ const node = { type: 'image', attrs: { src: res.src, alt: alt || res.alt || null } };
1343
+ if (pos != null) ed.chain().insertContentAt(pos, node).run();
1344
+ else ed.chain().focus().insertContent(node).run();
1345
+ } catch (error) {
1346
+ setNotice(
1347
+ error instanceof Error && error.message
1348
+ ? error.message
1349
+ : 'Não foi possível enviar a imagem.',
1350
+ );
1351
+ } finally {
1352
+ setBusy((n) => n - 1);
1353
+ }
1354
+ }
1355
+ }
1356
+ const insertRef = useRef(insertImages);
1357
+ insertRef.current = insertImages;
1358
+
1359
+ const imageFiles = (list?: FileList | null) =>
1360
+ Array.from(list ?? []).filter((f) => f.type.startsWith('image/'));
1361
+
1362
+ const editor = useEditor({
1363
+ immediatelyRender: false,
1364
+ editable,
1365
+ autofocus: autoFocus ? 'end' : false,
1366
+ content: value ?? undefined,
1367
+ // Regras de digitação, como "# " para título, só das ferramentas que valem.
1368
+ enableInputRules: [...allow].flatMap((t) => TOOL_INPUT_RULES[t] ?? []),
1369
+ enablePasteRules: allow.has('link') ? ['link'] : false,
1370
+ extensions: [
1371
+ // O esquema tem sempre tudo, para nenhum texto guardado se perder; `tools` só limita a barra,
1372
+ // os atalhos e o que se cola.
1373
+ StarterKit.configure({
1374
+ blockquote: false,
1375
+ code: false,
1376
+ codeBlock: false,
1377
+ strike: false,
1378
+ trailingNode: false,
1379
+ heading: { levels: [1, 2, 3] },
1380
+ link: {
1381
+ openOnClick: false,
1382
+ autolink: allow.has('link'),
1383
+ defaultProtocol: 'https',
1384
+ isAllowedUri: (url, ctx) => SAFE_HREF.test(url) && ctx.defaultValidate(url),
1385
+ HTMLAttributes: { target: '_blank', rel: 'noopener noreferrer nofollow' },
1386
+ },
1387
+ }),
1388
+ TextAlign.configure({
1389
+ types: ['heading', 'paragraph'],
1390
+ alignments: ['left', 'center', 'right', 'justify'],
1391
+ }),
1392
+ TextColorMark,
1393
+ HighlightMark,
1394
+ imageNode(() => latest.current.isAllowedImageSrc),
1395
+ Table.configure({ resizable: false }),
1396
+ TableRow,
1397
+ HeaderCell,
1398
+ Cell,
1399
+ FieldMark,
1400
+ Placeholder.configure({ placeholder: placeholder ?? '' }),
1401
+ Extension.create({
1402
+ name: 'richTextGuard',
1403
+ priority: 1000,
1404
+ addKeyboardShortcuts() {
1405
+ const keys: Record<string, () => boolean> = {};
1406
+ for (const [tool, list] of Object.entries(TOOL_KEYS))
1407
+ if (!allowRef.current.has(tool as RichTextTool))
1408
+ for (const k of list) keys[k] = () => true;
1409
+ if (singleLine)
1410
+ for (const k of ['Enter', 'Shift-Enter', 'Mod-Enter']) keys[k] = () => true;
1411
+ return keys;
1412
+ },
1413
+ }),
1414
+ ],
1415
+ editorProps: {
1416
+ attributes: {
1417
+ role: 'textbox',
1418
+ 'aria-multiline': singleLine ? 'false' : 'true',
1419
+ 'aria-label': label,
1420
+ class: cn(
1421
+ PROSE,
1422
+ 'outline-none [&_p.is-editor-empty:first-child]:before:pointer-events-none [&_p.is-editor-empty:first-child]:before:float-left [&_p.is-editor-empty:first-child]:before:h-0 [&_p.is-editor-empty:first-child]:before:text-muted-foreground [&_p.is-editor-empty:first-child]:before:content-[attr(data-placeholder)] [&_.selectedCell]:bg-selected [&_img.ProseMirror-selectednode]:ring-2 [&_img.ProseMirror-selectednode]:ring-ring [&_.tableWrapper]:overflow-x-auto',
1423
+ singleLine ? 'px-2.5 py-1.5 [&_p]:my-0' : 'min-h-20 px-2.5 py-2.5',
1424
+ contentClassName,
1425
+ ),
1426
+ },
1427
+ transformPasted: (slice, view) =>
1428
+ cleanSlice(slice, allowRef.current, view.state.schema, !!singleLine),
1429
+ handlePaste: (view, event) => {
1430
+ const files = imageFiles(event.clipboardData?.files);
1431
+ if (files.length) {
1432
+ if (allowRef.current.has('image')) void insertRef.current(files);
1433
+ return true;
1434
+ }
1435
+ return !singleLine && pasteMarkdown(view, event, allowRef.current);
1436
+ },
1437
+ handleDrop: (view, event, _slice, moved) => {
1438
+ if (moved) return false;
1439
+ const files = imageFiles(event.dataTransfer?.files);
1440
+ if (!files.length) return false;
1441
+ event.preventDefault();
1442
+ if (allowRef.current.has('image')) {
1443
+ const pos = view.posAtCoords({ left: event.clientX, top: event.clientY })?.pos;
1444
+ void insertRef.current(files, pos);
1445
+ }
1446
+ return true;
1447
+ },
1448
+ },
1449
+ onCreate: ({ editor: e }) => {
1450
+ editorRef.current = e;
1451
+ },
1452
+ onUpdate: ({ editor: e }) => {
1453
+ const doc = e.getJSON() as RichDoc;
1454
+ onChange(richIsEmpty(doc) ? null : doc);
1455
+ },
1456
+ });
1457
+ editorRef.current = editor;
1458
+
1459
+ useImperativeHandle(
1460
+ ref,
1461
+ () => ({
1462
+ insertField: ({ key, label: name }) =>
1463
+ editor
1464
+ ?.chain()
1465
+ .focus()
1466
+ .insertContent([
1467
+ { type: 'text', text: name, marks: [{ type: 'field', attrs: { key, label: name } }] },
1468
+ { type: 'text', text: ' ' },
1469
+ ])
1470
+ .run(),
1471
+ focus: () => editor?.commands.focus(),
1472
+ }),
1473
+ [editor],
1474
+ );
1475
+
1476
+ return (
1477
+ <div
1478
+ data-slot="rich-text-editor"
1479
+ data-single-line={singleLine || undefined}
1480
+ className={cn(
1481
+ 'flex flex-col',
1482
+ !bare &&
1483
+ (singleLine
1484
+ ? 'min-h-control rounded-control border border-input bg-surface-control transition-colors focus-within:border-ring-strong focus-within:focus-ring-field'
1485
+ : 'rounded-control border border-input bg-transparent transition-colors focus-within:border-ring-strong focus-within:focus-ring dark:bg-input/30'),
1486
+ className,
1487
+ )}
1488
+ >
1489
+ {editor && editable && !singleLine && (
1490
+ <Toolbar
1491
+ editor={editor}
1492
+ tools={allow}
1493
+ bare={bare}
1494
+ busy={busy > 0}
1495
+ onPickImage={(file, alt) => void insertRef.current([file], undefined, alt)}
1496
+ />
1497
+ )}
1498
+ {(notice || busy > 0) && (
1499
+ <p
1500
+ role="status"
1501
+ className={cn(
1502
+ 'px-2.5 pt-2 text-body-12',
1503
+ notice ? 'text-destructive' : 'text-muted-foreground',
1504
+ )}
1505
+ >
1506
+ {notice ?? 'Enviando a imagem…'}
1507
+ </p>
1508
+ )}
1509
+ <EditorContent editor={editor} className="flex-1" />
1510
+ {footer}
1511
+ </div>
1512
+ );
1513
+ }
1514
+
1515
+ function Inline({ nodes }: { nodes?: RichNode[] }) {
1516
+ return (
1517
+ <>
1518
+ {nodes?.map((n, i) => {
1519
+ if (n.type === 'hardBreak') return <br key={i} />;
1520
+ if (n.type !== 'text' || !n.text) return null;
1521
+ let el: ReactNode = n.text;
1522
+ for (const m of n.marks ?? []) {
1523
+ const color = m.attrs?.color;
1524
+ if (m.type === 'bold') el = <strong>{el}</strong>;
1525
+ else if (m.type === 'italic') el = <em>{el}</em>;
1526
+ else if (m.type === 'underline') el = <u>{el}</u>;
1527
+ else if (m.type === 'textColor' && isColor(color))
1528
+ el = (
1529
+ <span data-text-color={color} className={COLOR_TEXT[color]}>
1530
+ {el}
1531
+ </span>
1532
+ );
1533
+ else if (m.type === 'highlight' && isColor(color))
1534
+ el = (
1535
+ <span data-highlight={color} className={COLOR_BG[color]}>
1536
+ {el}
1537
+ </span>
1538
+ );
1539
+ else if (m.type === 'field')
1540
+ el = <mark data-filled={m.attrs?.filled ? 'true' : 'false'}>{el}</mark>;
1541
+ else if (m.type === 'link' && m.attrs?.href && SAFE_HREF.test(m.attrs.href)) {
1542
+ el = (
1543
+ <a href={m.attrs.href} target="_blank" rel="noopener noreferrer nofollow">
1544
+ {el}
1545
+ </a>
1546
+ );
1547
+ }
1548
+ }
1549
+ return <span key={i}>{el}</span>;
1550
+ })}
1551
+ </>
1552
+ );
1553
+ }
1554
+
1555
+ const alignOf = (n: RichNode) => {
1556
+ const a = n.attrs?.textAlign;
1557
+ return isAlign(a) ? ALIGN_CLASS[a] : undefined;
1558
+ };
1559
+ const span = (v: unknown) => (typeof v === 'number' && v > 1 && v < 100 ? v : undefined);
1560
+
1561
+ function Blocks({ nodes, check }: { nodes?: RichNode[]; check?: (src: string) => boolean }) {
1562
+ return (
1563
+ <>
1564
+ {nodes?.map((n, i) => {
1565
+ switch (n.type) {
1566
+ case 'paragraph':
1567
+ return (
1568
+ <p key={i} className={alignOf(n)}>
1569
+ <Inline nodes={n.content} />
1570
+ </p>
1571
+ );
1572
+ case 'heading': {
1573
+ const H = n.attrs?.level === 1 ? 'h1' : n.attrs?.level === 3 ? 'h3' : 'h2';
1574
+ return (
1575
+ <H key={i} className={alignOf(n)}>
1576
+ <Inline nodes={n.content} />
1577
+ </H>
1578
+ );
1579
+ }
1580
+ case 'bulletList':
1581
+ case 'orderedList': {
1582
+ const items = n.content?.map((item, j) => (
1583
+ <li key={j}>
1584
+ <Blocks nodes={item.content} check={check} />
1585
+ </li>
1586
+ ));
1587
+ return n.type === 'bulletList' ? (
1588
+ <ul key={i}>{items}</ul>
1589
+ ) : (
1590
+ <ol key={i} start={n.attrs?.start}>
1591
+ {items}
1592
+ </ol>
1593
+ );
1594
+ }
1595
+ case 'horizontalRule':
1596
+ return <hr key={i} />;
1597
+ case 'image': {
1598
+ const src = n.attrs?.src;
1599
+ return imageOk(src, check) ? <img key={i} src={src} alt={n.attrs?.alt ?? ''} /> : null;
1600
+ }
1601
+ case 'table':
1602
+ return (
1603
+ <table key={i}>
1604
+ <tbody>
1605
+ {n.content?.map((row, r) => (
1606
+ <tr key={r}>
1607
+ {row.content?.map((cell, c) => {
1608
+ const C = cell.type === 'tableHeader' ? 'th' : 'td';
1609
+ return (
1610
+ <C
1611
+ key={c}
1612
+ colSpan={span(cell.attrs?.colspan)}
1613
+ rowSpan={span(cell.attrs?.rowspan)}
1614
+ >
1615
+ <Blocks nodes={cell.content} check={check} />
1616
+ </C>
1617
+ );
1618
+ })}
1619
+ </tr>
1620
+ ))}
1621
+ </tbody>
1622
+ </table>
1623
+ );
1624
+ default:
1625
+ return null;
1626
+ }
1627
+ })}
1628
+ </>
1629
+ );
1630
+ }
1631
+
1632
+ /**
1633
+ * O texto formatado só para ler. Monta os elementos, sem HTML solto. Imagem só aparece quando o
1634
+ * endereço passa em `isAllowedImageSrc`.
1635
+ */
1636
+ export function RichTextView({
1637
+ doc,
1638
+ className,
1639
+ isAllowedImageSrc,
1640
+ }: {
1641
+ doc: RichDoc;
1642
+ className?: string;
1643
+ /** Diz se o endereço da imagem é do produto. Sem ela, nenhuma imagem aparece. */
1644
+ isAllowedImageSrc?: (src: string) => boolean;
1645
+ }) {
1646
+ return (
1647
+ <div data-slot="rich-text" className={cn(PROSE, className)}>
1648
+ <Blocks nodes={doc.content} check={isAllowedImageSrc} />
1649
+ </div>
1650
+ );
1651
+ }