@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,903 @@
1
+ 'use client';
2
+
3
+ import {
4
+ BotIcon,
5
+ CheckCheckIcon,
6
+ CheckIcon,
7
+ ChevronDownIcon,
8
+ CircleAlertIcon,
9
+ ClockIcon,
10
+ CopyIcon,
11
+ EllipsisIcon,
12
+ LockIcon,
13
+ MessageSquareTextIcon,
14
+ ReplyIcon,
15
+ RotateCwIcon,
16
+ SmartphoneIcon,
17
+ SmilePlusIcon,
18
+ ThumbsDownIcon,
19
+ ThumbsUpIcon,
20
+ WorkflowIcon,
21
+ } from 'lucide-react';
22
+ import {
23
+ Children,
24
+ isValidElement,
25
+ type PointerEvent,
26
+ type ReactNode,
27
+ useEffect,
28
+ useRef,
29
+ useState,
30
+ } from 'react';
31
+ import { AiSparkleIcon } from './badge';
32
+ import { Avatar } from './avatar';
33
+ import { Button } from './button';
34
+ import {
35
+ DropdownMenu,
36
+ DropdownMenuContent,
37
+ DropdownMenuGroup,
38
+ DropdownMenuItem,
39
+ DropdownMenuSeparator,
40
+ DropdownMenuTrigger,
41
+ } from './dropdown-menu';
42
+ import { Popover, PopoverContent, PopoverTrigger } from './popover';
43
+ import { Textarea } from './textarea';
44
+ import { Tooltip, TooltipContent, TooltipTrigger } from './tooltip';
45
+ import { cn } from '../lib/utils';
46
+
47
+ // Texto corrido com peças em linha, como um negrito ou o número de uma fonte: o corpo da mensagem
48
+ // é uma grade, e cada pedaço solto viraria uma linha. Junta o texto e as peças vizinhas num bloco
49
+ // só, para a frase seguir inteira. Anexos, com `kind`, e blocos como lista ficam fora.
50
+ const INLINE_TAGS = new Set([
51
+ 'a',
52
+ 'abbr',
53
+ 'b',
54
+ 'br',
55
+ 'code',
56
+ 'em',
57
+ 'i',
58
+ 'kbd',
59
+ 'mark',
60
+ 's',
61
+ 'small',
62
+ 'span',
63
+ 'strong',
64
+ 'sub',
65
+ 'sup',
66
+ 'u',
67
+ ]);
68
+ type FlowGroup = { inline: boolean; nodes: ReactNode[] };
69
+ const isText = (p: ReactNode) => typeof p === 'string' || typeof p === 'number';
70
+ function groupFlow(parts: ReactNode[]): FlowGroup[] {
71
+ const inline = (p: ReactNode, i: number) =>
72
+ isText(p) ||
73
+ (isValidElement<Record<string, unknown>>(p) &&
74
+ (typeof p.type === 'string'
75
+ ? INLINE_TAGS.has(p.type)
76
+ : !('kind' in p.props) && (isText(parts[i - 1]) || isText(parts[i + 1]))));
77
+ const groups: FlowGroup[] = [];
78
+ parts.forEach((p, i) => {
79
+ const last = groups[groups.length - 1];
80
+ if (inline(p, i) && last?.inline) last.nodes.push(p);
81
+ else groups.push({ inline: inline(p, i), nodes: [p] });
82
+ });
83
+ return groups;
84
+ }
85
+
86
+ // Mensagem de conversa (D-157), a mesma para o chat com a IA e para o atendimento por WhatsApp.
87
+ // Quem manda decide o lado e a cara:
88
+ // - `user`: a pessoa que usa o sistema falando com a IA; balão cinza à direita.
89
+ // - `assistant`: a IA; sem balão, à esquerda, com o brilho em degradê.
90
+ // - `contact`: o cliente no atendimento; balão branco à esquerda, com o avatar.
91
+ // - `agent`: a empresa respondendo; balão à direita, com a situação do envio. `via` diz quando não
92
+ // foi um atendente pelo sistema: o robô, o agente de IA ou o celular (D-330). D-844: todas as
93
+ // nossas mensagens, da equipe, do robô e do agente de IA, no mesmo azul claro, `chat-ours`; quem
94
+ // mandou fica na foto, com `byline`, ou no ícone junto da hora.
95
+ // - `note`: nota interna; faixa âmbar centralizada, que só a equipe vê.
96
+
97
+ export type ChatRole = 'user' | 'assistant' | 'contact' | 'agent' | 'note';
98
+ export type ChatStatus = 'sending' | 'sent' | 'delivered' | 'read' | 'failed';
99
+ export type ChatVia = 'bot' | 'ai' | 'phone';
100
+ /** Mensagem citada na resposta. `onClick` leva até a original. */
101
+ export type ChatQuote = { name: string; text: string; onClick?: () => void };
102
+ /**
103
+ * Item do app no menu da mensagem, como Editar ou Apagar para todos. Entra no fim do mesmo menu,
104
+ * depois de Responder e Copiar. `destructive` fica em vermelho, no fim, com o separador antes.
105
+ */
106
+ export type ChatMenuItem = {
107
+ label: string;
108
+ /** Ícone do item, obrigatório pela regra de menu. Na ação que apaga, a lixeira. */
109
+ icon: ReactNode;
110
+ onSelect: () => void;
111
+ destructive?: boolean;
112
+ disabled?: boolean;
113
+ };
114
+
115
+ const STATUS: Record<ChatStatus, { icon: typeof CheckIcon; label: string; className?: string }> = {
116
+ sending: { icon: ClockIcon, label: 'Enviando' },
117
+ sent: { icon: CheckIcon, label: 'Enviada' },
118
+ delivered: { icon: CheckCheckIcon, label: 'Entregue' },
119
+ read: { icon: CheckCheckIcon, label: 'Lida', className: 'text-text-action' },
120
+ failed: { icon: CircleAlertIcon, label: 'Não enviada', className: 'text-text-error' },
121
+ };
122
+
123
+ /** Reações rápidas do menu da mensagem, as mesmas do WhatsApp. */
124
+ const QUICK_REACTIONS = ['👍', '❤️', '😂', '😮', '😢', '🙏'];
125
+
126
+ function ChatMessage({
127
+ id,
128
+ role,
129
+ grouped,
130
+ name,
131
+ avatar,
132
+ time,
133
+ status,
134
+ via,
135
+ template,
136
+ quote,
137
+ reactions,
138
+ error,
139
+ onRetry,
140
+ onReply,
141
+ copyText,
142
+ onReact,
143
+ menuItems,
144
+ edited,
145
+ showName = false,
146
+ byline = false,
147
+ showVia = true,
148
+ reactButton = true,
149
+ actions,
150
+ children,
151
+ className,
152
+ sentAt: _sentAt,
153
+ ...rest
154
+ }: {
155
+ id?: string;
156
+ role: ChatRole;
157
+ /**
158
+ * Continua a sequência de quem mandou: sem nome, avatar nem a ponta do balão, mais perto da
159
+ * anterior. O app passa quando a mensagem segue a anterior da mesma pessoa.
160
+ */
161
+ grouped?: boolean;
162
+ /**
163
+ * Momento do envio, para o app agrupar as seguidas. Sem ele, o agrupamento usa `time`.
164
+ */
165
+ sentAt?: Date | number | string;
166
+ /** Nome de quem mandou; no `contact`, monta o avatar pelas iniciais. No robô, o nome dele. */
167
+ name?: string;
168
+ /** Foto de quem mandou. */
169
+ avatar?: string;
170
+ /** Hora, como "14:32". */
171
+ time?: string;
172
+ /** Situação do envio, no `agent` e no `user`. */
173
+ status?: ChatStatus;
174
+ /** No `agent`, quando não foi um atendente pelo sistema: robô, agente de IA ou o celular. */
175
+ via?: ChatVia;
176
+ /** Mensagem modelo do WhatsApp; ganha o selo Modelo. */
177
+ template?: boolean;
178
+ /** Mensagem respondida, mostrada no alto do balão. */
179
+ quote?: ChatQuote;
180
+ /** Emojis das reações, mostrados pequenos sobre o balão. */
181
+ reactions?: string[];
182
+ /** Motivo técnico da falha, guardado em Ver detalhe. */
183
+ error?: string;
184
+ /** Com `status="failed"`, mostra Tentar novamente. */
185
+ onRetry?: () => void;
186
+ /** Menu da mensagem: Responder. */
187
+ onReply?: () => void;
188
+ /** Menu da mensagem: Copiar, com este texto. */
189
+ copyText?: string;
190
+ /** Menu da mensagem: as reações rápidas. */
191
+ onReact?: (emoji: string) => void;
192
+ /** Menu da mensagem: itens do app no fim, como Editar e Apagar para todos. */
193
+ menuItems?: ChatMenuItem[];
194
+ /** Mensagem editada: mostra Editada ao lado da hora, como no WhatsApp. */
195
+ edited?: boolean;
196
+ /**
197
+ * Mostra o nome de quem mandou em cima do balão, como na conversa em grupo. Sem ele, o nome
198
+ * fica só no avatar do cliente e na dica do robô e do agente de IA (D-775).
199
+ */
200
+ showName?: boolean;
201
+ /**
202
+ * Foto ao lado e "nome • hora" em cima, uma vez por sequência, dos dois lados, D-844. Equipe com a
203
+ * foto de quem mandou, agente de IA com o ícone dele e cliente com a foto ou as iniciais. Nas
204
+ * seguidas, `grouped`, o lugar da foto fica reservado e a hora volta para dentro do balão.
205
+ */
206
+ byline?: boolean;
207
+ /** Ícone de "via" junto da hora: celular, robô e agente de IA. `false` esconde, D-844. */
208
+ showVia?: boolean;
209
+ /**
210
+ * Botão do rosto ao lado do balão, que abre a barra de reações. `false` deixa reagir só pelo menu
211
+ * da setinha, junto com Responder, D-844.
212
+ */
213
+ reactButton?: boolean;
214
+ /** Ações embaixo da mensagem, como as do ChatMessageActions. */
215
+ actions?: ReactNode;
216
+ children: ReactNode;
217
+ className?: string;
218
+ /** Atributos `data-*` vão para o elemento de fora, para o app achar a mensagem. */
219
+ [data: `data-${string}`]: string | number | boolean | undefined;
220
+ }) {
221
+ const mine = role === 'user' || role === 'agent';
222
+ const failed = status === 'failed';
223
+ const appItems = (menuItems ?? []).filter((item) => !item.destructive);
224
+ const dangerItems = (menuItems ?? []).filter((item) => item.destructive);
225
+ const hasBase = Boolean(onReact || onReply || copyText !== undefined);
226
+ const hasMenu = hasBase || appItems.length > 0 || dangerItems.length > 0;
227
+ const menuItem = (item: ChatMenuItem) => (
228
+ <DropdownMenuItem
229
+ key={item.label}
230
+ variant={item.destructive ? 'destructive' : 'default'}
231
+ disabled={item.disabled}
232
+ onClick={item.onSelect}
233
+ >
234
+ {item.icon}
235
+ {item.label}
236
+ </DropdownMenuItem>
237
+ );
238
+ const [menuOpen, setMenuOpen] = useState(false);
239
+ const [reactOpen, setReactOpen] = useState(false);
240
+ // No celular, segurar o dedo no balão abre o menu.
241
+ const press = useRef<ReturnType<typeof setTimeout>>(undefined);
242
+ // Ao sair da tela com o dedo ainda no balão, o menu não abre depois.
243
+ useEffect(() => () => clearTimeout(press.current), []);
244
+ const touch = hasMenu
245
+ ? {
246
+ onPointerDown: (e: PointerEvent) => {
247
+ if (e.pointerType !== 'touch') return;
248
+ press.current = setTimeout(() => setMenuOpen(true), 500);
249
+ },
250
+ onPointerUp: () => clearTimeout(press.current),
251
+ onPointerLeave: () => clearTimeout(press.current),
252
+ onPointerCancel: () => clearTimeout(press.current),
253
+ }
254
+ : {};
255
+
256
+ const noteMeta = (time || edited) && (
257
+ <span className="inline-flex gap-1 text-body-11 whitespace-nowrap tabular-nums opacity-80">
258
+ {edited && <span>Editada</span>}
259
+ {time}
260
+ </span>
261
+ );
262
+
263
+ if (role === 'note') {
264
+ return (
265
+ <div
266
+ {...rest}
267
+ id={id}
268
+ data-slot="chat-message"
269
+ data-role="note"
270
+ className={cn(
271
+ // D-775: centralizada, sem ir de ponta a ponta; até metade da conversa, D-781.
272
+ 'relative mx-auto grid w-full max-w-4/5 gap-0.5 rounded-card bg-warning-subtle px-2.5 py-2 text-warning-subtle-foreground md:max-w-1/2',
273
+ className,
274
+ )}
275
+ >
276
+ <span className="flex flex-wrap items-center gap-x-1.5 text-body-12-medium">
277
+ <LockIcon className="size-icon-sm" />
278
+ Nota interna{name && ` · ${name}`}
279
+ <span className="text-body-12 opacity-80">· Só a equipe vê</span>
280
+ </span>
281
+ {/* D-775: a hora no canto de baixo, na linha do fim do texto, como nos balões. */}
282
+ <div className="text-body-14 break-words whitespace-pre-line">
283
+ {children}
284
+ {noteMeta && (
285
+ <span aria-hidden className="invisible ml-2">
286
+ {noteMeta}
287
+ </span>
288
+ )}
289
+ </div>
290
+ {noteMeta && <span className="absolute right-2.5 bottom-1">{noteMeta}</span>}
291
+ </div>
292
+ );
293
+ }
294
+
295
+ // D-775: no atendimento, sem o nome em cima, como no WhatsApp; `showName` traz de volta, para a
296
+ // conversa em grupo. Celular, robô, agente de IA e modelo viram um ícone junto da hora, com o
297
+ // nome na dica e no leitor de tela.
298
+ // D-844: com `byline`, "nome • hora" em cima na primeira da sequência, no lugar do nome solto.
299
+ const bylineHead = byline && !grouped && role !== 'assistant' && (!!name || !!time);
300
+ const nameAbove = !bylineHead && !!name && !grouped && (role === 'assistant' || showName);
301
+ const viaLabel =
302
+ via === 'phone'
303
+ ? 'Enviada pelo celular'
304
+ : via === 'ai'
305
+ ? name
306
+ ? `Agente de IA ${name}`
307
+ : 'Agente de IA'
308
+ : via === 'bot'
309
+ ? name
310
+ ? `Robô ${name}`
311
+ : 'Robô'
312
+ : undefined;
313
+ const ViaIcon =
314
+ via === 'phone'
315
+ ? SmartphoneIcon
316
+ : via === 'ai'
317
+ ? BotIcon
318
+ : via === 'bot'
319
+ ? WorkflowIcon
320
+ : undefined;
321
+ const marks = [
322
+ showVia && ViaIcon && viaLabel && { icon: ViaIcon, label: viaLabel },
323
+ template && { icon: MessageSquareTextIcon, label: 'Mensagem modelo' },
324
+ ].filter(Boolean) as { icon: typeof BotIcon; label: string }[];
325
+
326
+ // Horário e tiques dentro do balão, D-650; no assistente, que não tem balão, embaixo.
327
+ const inside = role !== 'assistant' && !failed;
328
+ const parts = Children.toArray(children);
329
+ const isMedia = (p: ReactNode) =>
330
+ isValidElement<{ kind?: string }>(p) && (p.props.kind === 'image' || p.props.kind === 'video');
331
+ const mediaOnly = inside && !quote && parts.length === 1 && isMedia(parts[0]);
332
+ // D-788, como no WhatsApp: foto ou vídeo no começo, com legenda embaixo, fica com a moldura fina,
333
+ // e só a legenda leva o respiro do texto.
334
+ const leadMedia = inside && !quote && parts.length > 1 && isMedia(parts[0]);
335
+ const allGroups = groupFlow(parts);
336
+ const lead = leadMedia ? allGroups[0] : undefined;
337
+ const groups = leadMedia ? allGroups.slice(1) : allGroups;
338
+ const lastGroup = groups[groups.length - 1];
339
+ const textLast = inside && !!lastGroup?.inline && lastGroup.nodes.some(isText);
340
+ const flow = (list: FlowGroup[]) =>
341
+ list.map((g, i) => (g.inline ? <div key={`flow-${i}`}>{g.nodes}</div> : g.nodes));
342
+ // Moldura fina de 3px em volta da citação ou da mídia, D-784 e D-788.
343
+ const framed = role !== 'assistant' && (!!quote || mediaOnly || leadMedia);
344
+ const meta = ((!bylineHead && time) || status || edited || marks.length > 0) && (
345
+ // D-794: o horário em 11, peso normal, como no WhatsApp, no lugar de 10 em seminegrito.
346
+ <span className="inline-flex items-center gap-1 text-body-11 whitespace-nowrap text-muted-foreground tabular-nums [&_svg]:size-icon-xs">
347
+ {marks.map((m) => (
348
+ <Tooltip key={m.label}>
349
+ <TooltipTrigger
350
+ render={<span role="img" aria-label={m.label} className="inline-flex outline-none" />}
351
+ >
352
+ <m.icon className="size-3.5 shrink-0" />
353
+ </TooltipTrigger>
354
+ <TooltipContent>{m.label}</TooltipContent>
355
+ </Tooltip>
356
+ ))}
357
+ {edited && <span>Editada</span>}
358
+ {!bylineHead && time}
359
+ {status && <ChatStatusIcon status={status} />}
360
+ </span>
361
+ );
362
+ // O conteúdo do balão: o texto com o horário no fim, a mídia ou os blocos.
363
+ const bubbleBody = textLast ? (
364
+ // D-650, como no WhatsApp: o horário fica preso no canto de baixo do balão, e um
365
+ // espaço invisível do tamanho dele no fim do texto. Se a última linha tem lugar, o
366
+ // horário fica ao lado do texto; se não tem, o espaço desce e leva o horário junto.
367
+ <>
368
+ {flow(groups.slice(0, -1))}
369
+ <div>
370
+ {lastGroup!.nodes}
371
+ <span aria-hidden className="invisible ml-2">
372
+ {meta}
373
+ </span>
374
+ </div>
375
+ <span className="absolute right-1.75 bottom-1">{meta}</span>
376
+ </>
377
+ ) : mediaOnly ? (
378
+ // Foto ou vídeo sozinho: o horário por cima da imagem, D-651, sobre um degradê escuro no pé
379
+ // da foto, como no WhatsApp, D-788.
380
+ <>
381
+ {children}
382
+ <span className="pointer-events-none absolute inset-x-0.75 bottom-0.75 flex h-10 items-end justify-end rounded-b-inner bg-linear-to-t from-surface-scrim to-transparent px-2 pb-1 [&_*]:text-text-on-scrim!">
383
+ {meta}
384
+ </span>
385
+ </>
386
+ ) : (
387
+ <>
388
+ {flow(groups)}
389
+ {inside && <span className="-mt-1 justify-self-end">{meta}</span>}
390
+ </>
391
+ );
392
+
393
+ return (
394
+ <div
395
+ {...rest}
396
+ id={id}
397
+ data-slot="chat-message"
398
+ data-role={role}
399
+ data-via={via}
400
+ className={cn(
401
+ 'group/message flex gap-2',
402
+ mine && 'flex-row-reverse',
403
+ // Na conversa com gap-3, a seguinte da mesma pessoa fica a 2px da anterior, como no WhatsApp, D-775.
404
+ grouped && '-mt-2.5',
405
+ className,
406
+ )}
407
+ >
408
+ {role === 'assistant' &&
409
+ (name ? (
410
+ <Avatar name={name} ai aria-hidden className="mt-0.5" />
411
+ ) : (
412
+ <span className="grid size-8 shrink-0 place-items-center rounded-full bg-muted">
413
+ <AiSparkleIcon className="size-icon-lg" />
414
+ </span>
415
+ ))}
416
+ {role === 'contact' &&
417
+ (grouped ? (
418
+ <span data-slot="chat-message-avatar" aria-hidden className="size-8 shrink-0" />
419
+ ) : (
420
+ <Avatar
421
+ data-slot="chat-message-avatar"
422
+ name={name ?? '?'}
423
+ src={avatar}
424
+ className={byline ? undefined : 'mt-0.5'}
425
+ />
426
+ ))}
427
+ {/* D-844: com `byline`, a nossa foto também, do lado direito: o agente de IA com o ícone
428
+ dele, o resto com a foto de quem mandou. */}
429
+ {byline &&
430
+ role === 'agent' &&
431
+ (grouped ? (
432
+ <span data-slot="chat-message-author" aria-hidden className="size-8 shrink-0" />
433
+ ) : (
434
+ <Avatar
435
+ data-slot="chat-message-author"
436
+ name={name ?? (via === 'ai' ? 'Agente de IA' : via === 'bot' ? 'Robô' : 'Equipe')}
437
+ src={avatar}
438
+ ai={via === 'ai'}
439
+ aria-hidden
440
+ />
441
+ ))}
442
+ <div
443
+ className={cn(
444
+ 'grid min-w-0 gap-0.5',
445
+ // D-775: no atendimento, o balão vai até 65% da conversa, como no WhatsApp.
446
+ role === 'user' && 'max-w-4/5 justify-items-end md:max-w-1/2',
447
+ role === 'agent' && 'max-w-4/5 justify-items-end md:max-w-13/20',
448
+ role === 'contact' && 'max-w-4/5 justify-items-start md:max-w-13/20',
449
+ role === 'assistant' && 'max-w-[min(100%,48rem)]',
450
+ )}
451
+ >
452
+ {nameAbove && <span className="text-body-12 text-muted-foreground">{name}</span>}
453
+ {bylineHead && (
454
+ <span
455
+ data-slot="chat-message-byline"
456
+ className="flex min-w-0 gap-1 text-body-12 text-muted-foreground"
457
+ >
458
+ {name && <span className="truncate text-body-12-medium text-foreground">{name}</span>}
459
+ {name && time && <span aria-hidden>•</span>}
460
+ {time && <span className="shrink-0 tabular-nums">{time}</span>}
461
+ </span>
462
+ )}
463
+ <div
464
+ className={cn('flex max-w-full min-w-0 items-start gap-1', mine && 'flex-row-reverse')}
465
+ >
466
+ <div
467
+ {...touch}
468
+ data-slot="chat-bubble"
469
+ className={cn(
470
+ 'relative grid min-w-0 grid-cols-1 gap-1.5 text-body-13 break-words whitespace-pre-line [&_p_a]:font-medium [&_p_a]:underline [&_p_a]:underline-offset-2',
471
+ role === 'assistant' && 'pt-1',
472
+ // D-784, como no WhatsApp: com citação, o respiro em volta dela é pequeno, de 4px, e
473
+ // o texto de baixo mantém o respiro de sempre, pelo bloco de dentro.
474
+ role !== 'assistant' && 'rounded-inner',
475
+ // D-788, como no WhatsApp: 6px em cima, 8px embaixo e dos lados, e a sombra leve
476
+ // embaixo; com citação ou mídia, a moldura fina de 3px.
477
+ role !== 'assistant' && 'shadow-bubble',
478
+ // D-794: o texto em 14 e o respiro do WhatsApp, 6px em cima, 7 na direita, 8 embaixo e
479
+ // 9 na esquerda. A resposta da IA, sem balão, fica em 13.
480
+ role !== 'assistant' && 'text-body-14',
481
+ role !== 'assistant' && (framed ? 'gap-1 p-0.75' : 'pt-1.5 pr-1.75 pb-2 pl-2.25'),
482
+ // tokens-ok: a ponta do balão, o canto de cima cortado, só na primeira da sequência
483
+ role !== 'assistant' && !grouped && (mine ? 'rounded-tr-inner' : 'rounded-tl-inner'),
484
+ role === 'user' && 'bg-muted',
485
+ // D-781: o cliente em branco, como no WhatsApp; os avisos do sistema ficam em cinza.
486
+ role === 'contact' && 'border bg-card',
487
+ // D-844: as nossas mensagens, da equipe, do robô e do agente de IA, no mesmo azul
488
+ // claro, pelo token chat-ours. Troca o verde oliva e o violeta da D-795 e da D-807.
489
+ role === 'agent' && 'bg-chat-ours',
490
+ failed && 'ring-1 ring-destructive/40',
491
+ )}
492
+ >
493
+ {/* D-783, como no WhatsApp: a setinha no canto de cima do balão abre o menu. */}
494
+ {hasMenu && inside && (
495
+ <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
496
+ <DropdownMenuTrigger
497
+ render={
498
+ <button
499
+ type="button"
500
+ aria-label="Ações da mensagem"
501
+ className="absolute top-1 right-1 z-10 grid size-5 place-items-center rounded-full bg-inherit text-muted-foreground opacity-0 outline-none group-hover/message:opacity-100 hover:text-foreground focus-visible:opacity-100 focus-visible:focus-ring aria-expanded:opacity-100"
502
+ />
503
+ }
504
+ >
505
+ <ChevronDownIcon className="size-icon-lg" />
506
+ </DropdownMenuTrigger>
507
+ <DropdownMenuContent align={mine ? 'end' : 'start'} className="min-w-48">
508
+ {onReact && (
509
+ <>
510
+ <DropdownMenuGroup aria-label="Reagir" className="flex gap-0.5">
511
+ {QUICK_REACTIONS.map((emoji) => (
512
+ <DropdownMenuItem
513
+ key={emoji}
514
+ // menu-sem-icone: o próprio emoji é o desenho do item
515
+ aria-label={`Reagir com ${emoji}`}
516
+ className="min-h-9 justify-center px-2 text-heading-18"
517
+ onClick={() => onReact(emoji)}
518
+ >
519
+ {emoji}
520
+ </DropdownMenuItem>
521
+ ))}
522
+ </DropdownMenuGroup>
523
+ {(onReply || copyText !== undefined) && <DropdownMenuSeparator />}
524
+ </>
525
+ )}
526
+ {onReply && (
527
+ <DropdownMenuItem onClick={onReply}>
528
+ <ReplyIcon />
529
+ Responder
530
+ </DropdownMenuItem>
531
+ )}
532
+ {copyText !== undefined && (
533
+ <DropdownMenuItem onClick={() => void navigator.clipboard?.writeText(copyText)}>
534
+ <CopyIcon />
535
+ Copiar
536
+ </DropdownMenuItem>
537
+ )}
538
+ {appItems.length > 0 && (
539
+ <>
540
+ {hasBase && <DropdownMenuSeparator />}
541
+ {appItems.map(menuItem)}
542
+ </>
543
+ )}
544
+ {dangerItems.length > 0 && (
545
+ <>
546
+ {(hasBase || appItems.length > 0) && <DropdownMenuSeparator />}
547
+ {dangerItems.map(menuItem)}
548
+ </>
549
+ )}
550
+ </DropdownMenuContent>
551
+ </DropdownMenu>
552
+ )}
553
+ {quote && <ChatQuoteBox quote={quote} />}
554
+ {lead?.nodes}
555
+ {framed && !mediaOnly ? (
556
+ <div className="grid min-w-0 grid-cols-1 gap-1.5 pr-1 pb-1.25 pl-1.5">
557
+ {bubbleBody}
558
+ </div>
559
+ ) : (
560
+ bubbleBody
561
+ )}
562
+ </div>
563
+ {/* D-783, como no WhatsApp: ao lado do balão, o rosto para reagir; na resposta da IA,
564
+ que não tem balão, os três pontinhos. */}
565
+ {inside && onReact && reactButton && (
566
+ <Popover open={reactOpen} onOpenChange={setReactOpen}>
567
+ <PopoverTrigger
568
+ render={
569
+ <Button
570
+ variant="ghost"
571
+ size="icon-xs"
572
+ aria-label="Reagir"
573
+ className="mt-0.5 shrink-0 rounded-full text-muted-foreground opacity-0 group-hover/message:opacity-100 focus-visible:opacity-100 aria-expanded:opacity-100 pointer-coarse:hidden"
574
+ />
575
+ }
576
+ >
577
+ <SmilePlusIcon />
578
+ </PopoverTrigger>
579
+ <PopoverContent
580
+ side="top"
581
+ align="center"
582
+ className="flex w-auto gap-0.5 rounded-full p-1"
583
+ >
584
+ {QUICK_REACTIONS.map((emoji) => (
585
+ <button
586
+ key={emoji}
587
+ type="button"
588
+ aria-label={`Reagir com ${emoji}`}
589
+ className="grid size-9 place-items-center rounded-full text-heading-18 outline-none hover:bg-hover focus-visible:focus-ring"
590
+ onClick={() => {
591
+ onReact(emoji);
592
+ setReactOpen(false);
593
+ }}
594
+ >
595
+ {emoji}
596
+ </button>
597
+ ))}
598
+ </PopoverContent>
599
+ </Popover>
600
+ )}
601
+ {hasMenu && !inside && (
602
+ <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
603
+ <DropdownMenuTrigger
604
+ render={
605
+ <Button
606
+ variant="ghost"
607
+ size="icon-sm"
608
+ aria-label="Ações da mensagem"
609
+ className="shrink-0 text-muted-foreground opacity-0 group-hover/message:opacity-100 focus-visible:opacity-100 aria-expanded:opacity-100"
610
+ />
611
+ }
612
+ >
613
+ <EllipsisIcon />
614
+ </DropdownMenuTrigger>
615
+ <DropdownMenuContent align={mine ? 'end' : 'start'} className="min-w-48">
616
+ {onReact && (
617
+ <>
618
+ <DropdownMenuGroup aria-label="Reagir" className="flex gap-0.5">
619
+ {QUICK_REACTIONS.map((emoji) => (
620
+ <DropdownMenuItem
621
+ key={emoji}
622
+ // menu-sem-icone: o próprio emoji é o desenho do item
623
+ aria-label={`Reagir com ${emoji}`}
624
+ className="min-h-9 justify-center px-2 text-heading-18"
625
+ onClick={() => onReact(emoji)}
626
+ >
627
+ {emoji}
628
+ </DropdownMenuItem>
629
+ ))}
630
+ </DropdownMenuGroup>
631
+ {(onReply || copyText !== undefined) && <DropdownMenuSeparator />}
632
+ </>
633
+ )}
634
+ {onReply && (
635
+ <DropdownMenuItem onClick={onReply}>
636
+ <ReplyIcon />
637
+ Responder
638
+ </DropdownMenuItem>
639
+ )}
640
+ {copyText !== undefined && (
641
+ <DropdownMenuItem onClick={() => void navigator.clipboard?.writeText(copyText)}>
642
+ <CopyIcon />
643
+ Copiar
644
+ </DropdownMenuItem>
645
+ )}
646
+ {appItems.length > 0 && (
647
+ <>
648
+ {hasBase && <DropdownMenuSeparator />}
649
+ {appItems.map(menuItem)}
650
+ </>
651
+ )}
652
+ {dangerItems.length > 0 && (
653
+ <>
654
+ {(hasBase || appItems.length > 0) && <DropdownMenuSeparator />}
655
+ {dangerItems.map(menuItem)}
656
+ </>
657
+ )}
658
+ </DropdownMenuContent>
659
+ </DropdownMenu>
660
+ )}
661
+ </div>
662
+ {reactions && reactions.length > 0 && (
663
+ <span
664
+ aria-label={`Reações: ${reactions.join(' ')}`}
665
+ className={cn(
666
+ // D-787: por cima da borda de baixo do balão, como no WhatsApp.
667
+ 'relative z-10 -mt-2 rounded-full border bg-card px-1.5 text-body-12 shadow-raised',
668
+ mine ? 'mr-2' : 'ml-2',
669
+ )}
670
+ >
671
+ {reactions.join(' ')}
672
+ </span>
673
+ )}
674
+ {failed ? (
675
+ // D-798: só o alerta e Não enviada, com 4px entre os dois, e Tentar novamente em texto. O
676
+ // detalhe técnico do erro aparece ao passar o mouse em Não enviada, sem ícone a mais.
677
+ <span className="flex flex-wrap items-center gap-x-3 text-body-12 text-text-error">
678
+ {error ? (
679
+ <Tooltip>
680
+ <TooltipTrigger
681
+ render={
682
+ <span
683
+ tabIndex={0}
684
+ className="flex items-center gap-1 rounded-small outline-none focus-visible:focus-ring"
685
+ />
686
+ }
687
+ >
688
+ <CircleAlertIcon className="size-icon-sm" />
689
+ Não enviada
690
+ </TooltipTrigger>
691
+ <TooltipContent className="max-w-72 whitespace-normal">{error}</TooltipContent>
692
+ </Tooltip>
693
+ ) : (
694
+ <span className="flex items-center gap-1">
695
+ <CircleAlertIcon className="size-icon-sm" />
696
+ Não enviada
697
+ </span>
698
+ )}
699
+ {onRetry && (
700
+ <Button variant="link" size="xs" className="h-auto p-0" onClick={onRetry}>
701
+ Tentar novamente
702
+ </Button>
703
+ )}
704
+ </span>
705
+ ) : (
706
+ !inside && meta
707
+ )}
708
+ {actions}
709
+ </div>
710
+ </div>
711
+ );
712
+ }
713
+
714
+ /** Mensagem citada no alto do balão; com `onClick`, leva até a original. */
715
+ function ChatQuoteBox({ quote }: { quote: ChatQuote }) {
716
+ const body = (
717
+ <>
718
+ <span className="text-body-12-medium text-text-action">{quote.name}</span>
719
+ <span className="line-clamp-2 text-body-12 text-muted-foreground">{quote.text}</span>
720
+ </>
721
+ );
722
+ const cls =
723
+ 'grid gap-0.5 rounded-control border-l-2 border-text-action bg-foreground/5 px-2 py-1.5 text-left';
724
+ return quote.onClick ? (
725
+ <button
726
+ type="button"
727
+ onClick={quote.onClick}
728
+ aria-label={`Ir para a mensagem de ${quote.name}`}
729
+ className={cn(cls, 'outline-none hover:bg-foreground/10 focus-visible:focus-ring')}
730
+ >
731
+ {body}
732
+ </button>
733
+ ) : (
734
+ <div className={cls}>{body}</div>
735
+ );
736
+ }
737
+
738
+ /** Tique da situação do envio, como no WhatsApp; o nome aparece ao passar o mouse. */
739
+ function ChatStatusIcon({ status, className }: { status: ChatStatus; className?: string }) {
740
+ const st = STATUS[status];
741
+ return (
742
+ <Tooltip>
743
+ <TooltipTrigger
744
+ render={<span role="img" aria-label={st.label} className="inline-flex outline-none" />}
745
+ >
746
+ <st.icon
747
+ data-weight={status === 'read' ? 'bold' : undefined}
748
+ className={cn('size-3.5 shrink-0', st.className, className)}
749
+ />
750
+ </TooltipTrigger>
751
+ <TooltipContent>{st.label}</TooltipContent>
752
+ </Tooltip>
753
+ );
754
+ }
755
+
756
+ /**
757
+ * Ações da resposta da IA: copiar, gostei, não gostei e gerar de novo. Com `askReason`, o não
758
+ * gostei pergunta o que estava errado, sem obrigar a escrever (D-332).
759
+ */
760
+ function ChatMessageActions({
761
+ text,
762
+ onFeedback,
763
+ askReason = false,
764
+ onRetry,
765
+ className,
766
+ }: {
767
+ /** Texto copiado pelo botão de copiar. */
768
+ text?: string;
769
+ /** Gostei ou não gostei; no não gostei com `askReason`, vem o motivo escrito, se houver. */
770
+ onFeedback?: (good: boolean, reason?: string) => void;
771
+ askReason?: boolean;
772
+ onRetry?: () => void;
773
+ className?: string;
774
+ }) {
775
+ const [copied, setCopied] = useState(false);
776
+ const copiedTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
777
+ useEffect(() => () => clearTimeout(copiedTimer.current), []);
778
+ const [vote, setVote] = useState<boolean | null>(null);
779
+ const [asking, setAsking] = useState(false);
780
+ const [reason, setReason] = useState('');
781
+ const action = (label: string, icon: ReactNode, onClick: () => void, on = false) => (
782
+ <Tooltip>
783
+ <TooltipTrigger
784
+ render={
785
+ <Button
786
+ variant="ghost"
787
+ size="icon-sm"
788
+ aria-label={label}
789
+ aria-pressed={on}
790
+ onClick={onClick}
791
+ className="text-muted-foreground aria-pressed:text-foreground"
792
+ />
793
+ }
794
+ >
795
+ {icon}
796
+ </TooltipTrigger>
797
+ <TooltipContent>{label}</TooltipContent>
798
+ </Tooltip>
799
+ );
800
+ return (
801
+ <div data-slot="chat-message-actions" className={cn('-ml-1.5 flex items-center', className)}>
802
+ {text !== undefined &&
803
+ action(copied ? 'Copiado' : 'Copiar', copied ? <CheckIcon /> : <CopyIcon />, () => {
804
+ void navigator.clipboard?.writeText(text);
805
+ setCopied(true);
806
+ clearTimeout(copiedTimer.current);
807
+ copiedTimer.current = setTimeout(() => setCopied(false), 1500);
808
+ })}
809
+ {onFeedback && (
810
+ <>
811
+ {action(
812
+ 'Boa resposta',
813
+ <ThumbsUpIcon fill={vote === true ? 'currentColor' : 'none'} />,
814
+ () => {
815
+ setVote(true);
816
+ onFeedback(true);
817
+ },
818
+ vote === true,
819
+ )}
820
+ {askReason ? (
821
+ <Popover open={asking} onOpenChange={setAsking}>
822
+ <PopoverTrigger
823
+ render={
824
+ <Button
825
+ variant="ghost"
826
+ size="icon-sm"
827
+ aria-label="Resposta ruim"
828
+ aria-pressed={vote === false}
829
+ className="text-muted-foreground aria-pressed:text-foreground"
830
+ />
831
+ }
832
+ >
833
+ <ThumbsDownIcon fill={vote === false ? 'currentColor' : 'none'} />
834
+ </PopoverTrigger>
835
+ <PopoverContent side="top" align="start" className="w-72 gap-3">
836
+ <label className="grid gap-1.5 text-body-13-medium">
837
+ O que estava errado?
838
+ <Textarea
839
+ value={reason}
840
+ maxLength={500}
841
+ rows={3}
842
+ placeholder="Opcional. Ex.: o prazo de troca é de 30 dias, não 7."
843
+ onChange={(e) => setReason(e.target.value)}
844
+ />
845
+ </label>
846
+ <Button
847
+ size="sm"
848
+ className="justify-self-end"
849
+ onClick={() => {
850
+ setVote(false);
851
+ setAsking(false);
852
+ onFeedback(false, reason.trim() || undefined);
853
+ }}
854
+ >
855
+ Enviar
856
+ </Button>
857
+ </PopoverContent>
858
+ </Popover>
859
+ ) : (
860
+ action(
861
+ 'Resposta ruim',
862
+ <ThumbsDownIcon fill={vote === false ? 'currentColor' : 'none'} />,
863
+ () => {
864
+ setVote(false);
865
+ onFeedback(false);
866
+ },
867
+ vote === false,
868
+ )
869
+ )}
870
+ </>
871
+ )}
872
+ {onRetry && action('Gerar novamente', <RotateCwIcon />, onRetry)}
873
+ </div>
874
+ );
875
+ }
876
+
877
+ /** Três pontos de "digitando", da IA ou do cliente. */
878
+ function TypingIndicator({
879
+ label = 'Digitando',
880
+ className,
881
+ }: {
882
+ label?: string;
883
+ className?: string;
884
+ }) {
885
+ return (
886
+ <span
887
+ data-slot="typing-indicator"
888
+ role="status"
889
+ aria-label={label}
890
+ className={cn('inline-flex items-center gap-1 py-2', className)}
891
+ >
892
+ {[0, 1, 2].map((i) => (
893
+ <span
894
+ key={i}
895
+ className="size-1.5 animate-bounce rounded-full bg-muted-foreground"
896
+ style={{ animationDelay: `${i * 150}ms`, animationDuration: '1s' }}
897
+ />
898
+ ))}
899
+ </span>
900
+ );
901
+ }
902
+
903
+ export { ChatMessage, ChatMessageActions, ChatQuoteBox, ChatStatusIcon, TypingIndicator };