@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,136 @@
1
+ 'use client';
2
+
3
+ import { ChevronRightIcon } from 'lucide-react';
4
+ import { type ReactNode, useState } from 'react';
5
+ import { cn } from '../lib/utils';
6
+
7
+ // tokens-ok-ligacao: estrutura e tokens; cada linha da árvore é um botão de linha, como no menu lateral.
8
+
9
+ // Árvore de pastas e itens (D-339), como as coleções e os documentos da Base de conhecimento. A
10
+ // pasta abre e fecha e pode ter uma ação ao lado, como o + de novo documento; o item escolhido
11
+ // fica marcado. Até dois níveis, para não virar um explorador de arquivos. As listas usam uma
12
+ // coluna que não passa da largura da árvore, para nome longo cortar com reticências e a ação da
13
+ // pasta não sair do painel.
14
+
15
+ export type TreeNavItem = {
16
+ id: string;
17
+ label: ReactNode;
18
+ icon?: ReactNode;
19
+ /** À direita do nome, como um selo de Rascunho. */
20
+ badge?: ReactNode;
21
+ /** Linha de baixo, só nas pastas, como "Usada por Lia e Tom". */
22
+ meta?: ReactNode;
23
+ /** Ação ao lado da pasta, como o + de novo documento ou um menu. */
24
+ action?: ReactNode;
25
+ /** Itens dentro da pasta. */
26
+ items?: TreeNavItem[];
27
+ };
28
+
29
+ function TreeNav({
30
+ items,
31
+ selected,
32
+ onSelect,
33
+ expanded: expandedProp,
34
+ defaultExpanded,
35
+ onExpandedChange,
36
+ empty,
37
+ className,
38
+ 'aria-label': ariaLabel,
39
+ }: {
40
+ items: TreeNavItem[];
41
+ /** O item escolhido. */
42
+ selected?: string | null;
43
+ onSelect?: (id: string) => void;
44
+ /** Pastas abertas. Sem isso, a árvore guarda sozinha. */
45
+ expanded?: string[];
46
+ /** Pastas abertas no começo; sem isso, todas abertas. */
47
+ defaultExpanded?: string[];
48
+ onExpandedChange?: (ids: string[]) => void;
49
+ /** Dentro de uma pasta vazia, como "Nenhum documento". */
50
+ empty?: ReactNode;
51
+ className?: string;
52
+ 'aria-label': string;
53
+ }) {
54
+ const [own, setOwn] = useState<string[]>(
55
+ defaultExpanded ?? items.filter((i) => i.items).map((i) => i.id),
56
+ );
57
+ const open = expandedProp ?? own;
58
+ const toggle = (id: string) => {
59
+ const next = open.includes(id) ? open.filter((x) => x !== id) : [...open, id];
60
+ setOwn(next);
61
+ onExpandedChange?.(next);
62
+ };
63
+
64
+ const leaf = (item: TreeNavItem, nested: boolean) => (
65
+ <li key={item.id}>
66
+ <button
67
+ type="button"
68
+ aria-current={selected === item.id ? 'true' : undefined}
69
+ onClick={() => onSelect?.(item.id)}
70
+ className={cn(
71
+ 'flex w-full min-w-0 items-center gap-2 rounded-control py-1.5 pr-2 text-left text-body-13 text-muted-foreground transition-colors outline-none hover:bg-hover hover:text-foreground focus-visible:focus-ring aria-[current=true]:bg-selected aria-[current=true]:text-body-13-medium aria-[current=true]:text-selected-foreground [&_svg]:size-icon-lg [&_svg]:shrink-0',
72
+ nested ? 'pl-8' : 'pl-2',
73
+ )}
74
+ >
75
+ {item.icon}
76
+ <span className="min-w-0 flex-1 truncate">{item.label}</span>
77
+ {item.badge}
78
+ </button>
79
+ </li>
80
+ );
81
+
82
+ return (
83
+ <nav aria-label={ariaLabel} data-slot="tree-nav" className={cn('min-w-0', className)}>
84
+ <ul className="grid grid-cols-1 gap-0.5">
85
+ {items.map((item) => {
86
+ if (!item.items) return leaf(item, false);
87
+ const isOpen = open.includes(item.id);
88
+ return (
89
+ <li key={item.id} className="grid min-w-0 grid-cols-1 gap-0.5">
90
+ <div className="flex min-w-0 items-start gap-1 rounded-control hover:bg-hover">
91
+ <button
92
+ type="button"
93
+ aria-expanded={isOpen}
94
+ onClick={() => toggle(item.id)}
95
+ className="flex min-w-0 flex-1 items-start gap-2 rounded-control px-2 py-1.5 text-left outline-none focus-visible:focus-ring [&_svg]:size-icon-lg [&_svg]:shrink-0"
96
+ >
97
+ <ChevronRightIcon
98
+ aria-hidden
99
+ className={cn(
100
+ 'mt-0.5 text-muted-foreground transition-transform',
101
+ isOpen && 'rotate-90',
102
+ )}
103
+ />
104
+ <span className="grid min-w-0 flex-1 gap-0.5">
105
+ <span className="flex min-w-0 items-center gap-2">
106
+ {item.icon}
107
+ <span className="truncate text-body-13-medium">{item.label}</span>
108
+ {item.badge}
109
+ </span>
110
+ {item.meta && (
111
+ <span className="truncate text-body-12 text-muted-foreground">
112
+ {item.meta}
113
+ </span>
114
+ )}
115
+ </span>
116
+ </button>
117
+ {item.action && <span className="shrink-0 py-0.5 pr-0.5">{item.action}</span>}
118
+ </div>
119
+ {isOpen && (
120
+ <ul className="grid grid-cols-1 gap-0.5">
121
+ {item.items.length > 0
122
+ ? item.items.map((child) => leaf(child, true))
123
+ : empty && (
124
+ <li className="py-1.5 pl-8 text-body-12 text-muted-foreground">{empty}</li>
125
+ )}
126
+ </ul>
127
+ )}
128
+ </li>
129
+ );
130
+ })}
131
+ </ul>
132
+ </nav>
133
+ );
134
+ }
135
+
136
+ export { TreeNav };
@@ -0,0 +1,193 @@
1
+ 'use client';
2
+
3
+ import { PauseIcon, PlayIcon } from 'lucide-react';
4
+ import { type KeyboardEvent, type PointerEvent, type ReactNode, useRef, useState } from 'react';
5
+ import { AiSparkleIcon } from './badge';
6
+ import { Button } from './button';
7
+ import { formatClock, parseClock, seekByKey, waveformBars } from '../lib/voice';
8
+ import { cn } from '../lib/utils';
9
+
10
+ // Mensagem de voz, D-845, pedido do VOWT CRM: como o áudio do WhatsApp. Play e pausa, as ondas que
11
+ // se clicam ou arrastam para ir a um ponto, o tempo corrido e a duração, e a transcrição embaixo.
12
+ // As ondas são um controle deslizante para o teclado e o leitor de tela: setas andam 5 segundos,
13
+ // Page Up e Page Down 10%, Home e End vão às pontas. Usada pelo Chat attachment de áudio e solta
14
+ // em qualquer lugar que toque uma gravação, como a ficha da ligação.
15
+
16
+ const BARS = 40;
17
+
18
+ function VoiceMessage({
19
+ src,
20
+ duration,
21
+ waveform,
22
+ transcript,
23
+ transcriptLabel = 'Transcrição',
24
+ onError,
25
+ className,
26
+ }: {
27
+ /** Endereço do áudio. */
28
+ src?: string;
29
+ /** Duração em segundos ou já escrita, como "0:19". Sem ela, vem do arquivo ao carregar. */
30
+ duration?: number | string;
31
+ /** Alturas das ondas, de 0 a 1, vindas do app. Sem elas, um desenho fixo para o mesmo áudio. */
32
+ waveform?: number[];
33
+ /** Texto do áudio, embaixo. Longo, fica em três linhas com Ver mais. */
34
+ transcript?: ReactNode;
35
+ /** Título da transcrição. */
36
+ transcriptLabel?: ReactNode;
37
+ /** O arquivo não abriu. */
38
+ onError?: () => void;
39
+ className?: string;
40
+ }) {
41
+ const audio = useRef<HTMLAudioElement>(null);
42
+ const [playing, setPlaying] = useState(false);
43
+ const [current, setCurrent] = useState(0);
44
+ const [loaded, setLoaded] = useState<number | undefined>(undefined);
45
+ const [open, setOpen] = useState(false);
46
+ const dragging = useRef(false);
47
+ const total = loaded ?? parseClock(duration) ?? 0;
48
+ const pct = total > 0 ? Math.min(100, (current / total) * 100) : 0;
49
+ const bars = waveformBars(waveform, BARS, src);
50
+ const started = playing || current > 0;
51
+
52
+ const seek = (seconds: number) => {
53
+ const next = Math.min(total, Math.max(0, seconds));
54
+ setCurrent(next);
55
+ const el = audio.current;
56
+ if (el && Number.isFinite(el.duration)) el.currentTime = next;
57
+ };
58
+ const seekAt = (e: PointerEvent<HTMLDivElement>) => {
59
+ const r = e.currentTarget.getBoundingClientRect();
60
+ if (r.width > 0) seek(((e.clientX - r.left) / r.width) * total);
61
+ };
62
+ const toggle = () => {
63
+ const el = audio.current;
64
+ if (!el) return;
65
+ if (el.paused) {
66
+ // Se a pessoa já escolheu um ponto antes de tocar, começa dali.
67
+ if (Number.isFinite(el.duration) && Math.abs(el.currentTime - current) > 0.5)
68
+ el.currentTime = current;
69
+ void el.play().catch(() => onError?.());
70
+ } else el.pause();
71
+ };
72
+ const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
73
+ const next = seekByKey(e.key, current, total);
74
+ if (next === undefined) return;
75
+ e.preventDefault();
76
+ seek(next);
77
+ };
78
+ const long = typeof transcript === 'string' && transcript.length > 160;
79
+
80
+ return (
81
+ <div
82
+ data-slot="voice-message"
83
+ data-kind="audio"
84
+ className={cn('grid w-64 max-w-full gap-1.5', className)}
85
+ >
86
+ <div className="flex items-center gap-2">
87
+ <Button
88
+ variant="ghost"
89
+ size="icon-sm"
90
+ className="shrink-0 rounded-full"
91
+ aria-label={playing ? 'Pausar áudio' : 'Ouvir áudio'}
92
+ onClick={toggle}
93
+ >
94
+ {playing ? <PauseIcon fill="currentColor" /> : <PlayIcon fill="currentColor" />}
95
+ </Button>
96
+ <div className="grid min-w-0 flex-1 gap-0.5">
97
+ <div
98
+ role="slider"
99
+ tabIndex={0}
100
+ aria-label="Posição do áudio"
101
+ aria-valuemin={0}
102
+ aria-valuemax={Math.round(total)}
103
+ aria-valuenow={Math.round(current)}
104
+ aria-valuetext={`${formatClock(current)} de ${formatClock(total)}`}
105
+ aria-disabled={total > 0 ? undefined : true}
106
+ onKeyDown={onKey}
107
+ onPointerDown={(e) => {
108
+ if (!(total > 0)) return;
109
+ dragging.current = true;
110
+ e.currentTarget.setPointerCapture(e.pointerId);
111
+ seekAt(e);
112
+ }}
113
+ onPointerMove={(e) => {
114
+ if (dragging.current) seekAt(e);
115
+ }}
116
+ onPointerUp={() => {
117
+ dragging.current = false;
118
+ }}
119
+ onPointerCancel={() => {
120
+ dragging.current = false;
121
+ }}
122
+ className="relative flex h-7 cursor-pointer touch-none items-center gap-px rounded-small outline-none focus-visible:focus-ring aria-disabled:cursor-default"
123
+ >
124
+ {bars.map((h, i) => (
125
+ <span
126
+ key={i}
127
+ aria-hidden
128
+ style={{ height: `${Math.round(h * 100)}%` }}
129
+ className={cn(
130
+ 'min-w-0.5 flex-1 rounded-full',
131
+ ((i + 0.5) / BARS) * 100 <= pct ? 'bg-surface-action' : 'bg-border-strong',
132
+ )}
133
+ />
134
+ ))}
135
+ {/* O ponto que marca onde o áudio está, como no WhatsApp. */}
136
+ <span
137
+ aria-hidden
138
+ style={{ left: `${pct}%` }}
139
+ className="pointer-events-none absolute top-1/2 size-3 -translate-x-1/2 -translate-y-1/2 rounded-full bg-surface-action shadow-raised"
140
+ />
141
+ </div>
142
+ <div className="flex justify-between text-body-11 text-muted-foreground tabular-nums">
143
+ <span aria-hidden>{started ? formatClock(current) : '0:00'}</span>
144
+ <span aria-hidden>{formatClock(total)}</span>
145
+ </div>
146
+ </div>
147
+ <audio
148
+ ref={audio}
149
+ src={src}
150
+ preload="metadata"
151
+ onLoadedMetadata={(e) => {
152
+ const d = e.currentTarget.duration;
153
+ if (Number.isFinite(d) && d > 0) setLoaded(d);
154
+ }}
155
+ onPlay={() => setPlaying(true)}
156
+ onPause={() => setPlaying(false)}
157
+ onEnded={() => {
158
+ setPlaying(false);
159
+ setCurrent(0);
160
+ }}
161
+ onTimeUpdate={(e) => {
162
+ if (!dragging.current) setCurrent(e.currentTarget.currentTime);
163
+ }}
164
+ onError={src ? () => onError?.() : undefined}
165
+ />
166
+ </div>
167
+ {transcript && (
168
+ <div data-slot="voice-message-transcript" className="grid gap-0.5 border-t pt-1.5">
169
+ <span className="flex items-center gap-1 text-body-12 text-muted-foreground">
170
+ <AiSparkleIcon className="size-icon-sm" />
171
+ {transcriptLabel}
172
+ </span>
173
+ <div className={cn('text-body-13 whitespace-pre-line', long && !open && 'line-clamp-3')}>
174
+ {transcript}
175
+ </div>
176
+ {long && (
177
+ <Button
178
+ variant="link"
179
+ size="xs"
180
+ className="h-auto justify-self-start p-0"
181
+ aria-expanded={open}
182
+ onClick={() => setOpen((v) => !v)}
183
+ >
184
+ {open ? 'Ver menos' : 'Ver mais'}
185
+ </Button>
186
+ )}
187
+ </div>
188
+ )}
189
+ </div>
190
+ );
191
+ }
192
+
193
+ export { VoiceMessage };
package/src/css.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ // Folhas de estilo de bibliotecas importadas pelos componentes, como o desenho do fluxo.
2
+ declare module '*.css';
@@ -0,0 +1,57 @@
1
+ import * as React from 'react';
2
+ import { DEFAULT_THEME, type Theme, THEME_KEY } from '../lib/appearance';
3
+
4
+ // Lê e muda a aparência: o tema, claro, escuro ou do aparelho. Aplica na página na hora e guarda no
5
+ // navegador; todas as telas abertas que usam o gancho se atualizam. Sem escolha, claro, D-750.
6
+ // Toda escolha fica guardada, até a igual ao padrão, para que uma troca futura do padrão não mude
7
+ // a tela de quem já escolheu. A largura saiu daqui na D-817: cada tela declara a sua.
8
+
9
+ const listeners = new Set<() => void>();
10
+ const read = <T extends string>(key: string, fallback: T): T => {
11
+ try {
12
+ return (localStorage.getItem(key) as T | null) ?? fallback;
13
+ } catch {
14
+ return fallback;
15
+ }
16
+ };
17
+
18
+ function apply() {
19
+ const root = document.documentElement;
20
+ const theme = read<Theme>(THEME_KEY, DEFAULT_THEME);
21
+ const dark =
22
+ theme === 'dark' ||
23
+ (theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
24
+ root.classList.toggle('dark', dark);
25
+ listeners.forEach((l) => l());
26
+ }
27
+
28
+ function write(key: string, value: string) {
29
+ try {
30
+ localStorage.setItem(key, value);
31
+ } catch {}
32
+ apply();
33
+ }
34
+
35
+ function subscribe(onChange: () => void) {
36
+ listeners.add(onChange);
37
+ const mql = window.matchMedia('(prefers-color-scheme: dark)');
38
+ mql.addEventListener('change', apply);
39
+ return () => {
40
+ listeners.delete(onChange);
41
+ mql.removeEventListener('change', apply);
42
+ };
43
+ }
44
+
45
+ const snapshot = () =>
46
+ `${read<Theme>(THEME_KEY, DEFAULT_THEME)}|${document.documentElement.classList.contains('dark') ? 'd' : 'l'}`;
47
+
48
+ export function useAppearance() {
49
+ const value = React.useSyncExternalStore(subscribe, snapshot, () => `${DEFAULT_THEME}|l`);
50
+ const [theme, mode] = value.split('|') as [Theme, 'd' | 'l'];
51
+ return {
52
+ theme,
53
+ /** O tema que está valendo agora, já resolvido quando segue o aparelho. */
54
+ dark: mode === 'd',
55
+ setTheme: (t: Theme) => write(THEME_KEY, t),
56
+ };
57
+ }
@@ -0,0 +1,20 @@
1
+ import * as React from 'react';
2
+
3
+ const MOBILE_BREAKPOINT = 768;
4
+ const QUERY = `(max-width: ${MOBILE_BREAKPOINT - 1}px)`;
5
+
6
+ // Gerado pelo shadcn; reescrito com useSyncExternalStore para seguir a regra de lint do React 19
7
+ // (sem setState dentro de efeito). No servidor considera tela grande.
8
+ function subscribe(onChange: () => void) {
9
+ const mql = window.matchMedia(QUERY);
10
+ mql.addEventListener('change', onChange);
11
+ return () => mql.removeEventListener('change', onChange);
12
+ }
13
+
14
+ export function useIsMobile() {
15
+ return React.useSyncExternalStore(
16
+ subscribe,
17
+ () => window.matchMedia(QUERY).matches,
18
+ () => false,
19
+ );
20
+ }
@@ -0,0 +1,16 @@
1
+ // Aparência escolhida pela pessoa: o tema. Fica guardada no navegador e vale para todo app que usa
2
+ // o pacote. Sem escolha, o tema é o claro, D-750. A largura do conteúdo saiu da Aparência na D-817:
3
+ // cada tela declara a sua, pelo `width` do App shell.
4
+
5
+ export type Theme = 'light' | 'dark' | 'system';
6
+
7
+ export const THEME_KEY = 'vowt-theme';
8
+
9
+ /** O que vale para quem nunca escolheu, D-750. */
10
+ export const DEFAULT_THEME: Theme = 'light';
11
+
12
+ /**
13
+ * Script para o <head> do app, que aplica a aparência antes de a página aparecer, sem piscar:
14
+ * `<script dangerouslySetInnerHTML={{ __html: APPEARANCE_SCRIPT }} />`.
15
+ */
16
+ export const APPEARANCE_SCRIPT = `try{var t=localStorage.getItem('${THEME_KEY}'),d=document.documentElement;if(t==='dark'||(t==='system'&&matchMedia('(prefers-color-scheme: dark)').matches))d.classList.add('dark')}catch(e){}`;
@@ -0,0 +1,32 @@
1
+ import { isValidElement, type ReactNode } from 'react';
2
+
3
+ type Render = ReactNode | ((...args: never[]) => ReactNode) | undefined;
4
+
5
+ /**
6
+ * O que o `render` de um botão desenha: um `<button>` de verdade, um link ou outro elemento.
7
+ * Link é `<a>` ou qualquer elemento com `href`, como o `Link` do pacote e o `next/link`.
8
+ * Um `render` em forma de função conta como `<button>`, como o Base UI espera.
9
+ */
10
+ export function renderKind(render: Render): 'button' | 'link' | 'other' {
11
+ if (!render || !isValidElement(render)) return 'button';
12
+ if (render.type === 'button') return 'button';
13
+ const props = render.props as { href?: unknown };
14
+ if (render.type === 'a' || props.href !== undefined) return 'link';
15
+ return 'other';
16
+ }
17
+
18
+ /**
19
+ * As props que dão ao botão a semântica certa para o leitor de tela. Sem elas, o Base UI põe
20
+ * `role="button"` em todo elemento que não é `<button>`, e um link com cara de botão era
21
+ * anunciado como botão. No link, o papel vira `link`; o `role` de quem usa ainda vale por cima.
22
+ */
23
+ export function buttonSemantics(
24
+ render: Render,
25
+ nativeButton: boolean | undefined,
26
+ ): { nativeButton: boolean; role?: 'link' } {
27
+ const kind = renderKind(render);
28
+ return {
29
+ nativeButton: nativeButton ?? kind === 'button',
30
+ ...(kind === 'link' ? { role: 'link' as const } : {}),
31
+ };
32
+ }
@@ -0,0 +1,67 @@
1
+ 'use client';
2
+
3
+ import * as React from 'react';
4
+ import { cn } from './utils';
5
+
6
+ // Contador de letras do Input e do Textarea, pelo `showCount`: "45/120" no canto do campo, só
7
+ // quando o texto passa de 80% do `maxLength`. O espaço do contador fica guardado desde o começo,
8
+ // para o texto não pular quando ele aparece. Funciona com o campo controlado ou não.
9
+
10
+ /** A partir de quanto do limite o contador aparece. */
11
+ const SHOW_FROM = 0.8;
12
+
13
+ type ChangeEvent = React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>;
14
+
15
+ export function useCharCount<E extends ChangeEvent>({
16
+ enabled,
17
+ maxLength,
18
+ value,
19
+ defaultValue,
20
+ onChange,
21
+ }: {
22
+ enabled: boolean;
23
+ maxLength?: number;
24
+ value?: unknown;
25
+ defaultValue?: unknown;
26
+ onChange?: (event: E) => void;
27
+ }) {
28
+ const on = enabled && typeof maxLength === 'number' && maxLength > 0;
29
+ const controlled = value !== undefined;
30
+ const [typed, setTyped] = React.useState(() => String(defaultValue ?? '').length);
31
+ const length = controlled ? String(value ?? '').length : typed;
32
+ return {
33
+ on,
34
+ visible: on && length >= (maxLength as number) * SHOW_FROM,
35
+ length,
36
+ /** Folga à direita para o contador, pelo tamanho do limite. */
37
+ room: on && (maxLength as number) >= 1000 ? 'pr-18' : 'pr-14',
38
+ onChange: on
39
+ ? (event: E) => {
40
+ if (!controlled) setTyped(event.target.value.length);
41
+ onChange?.(event);
42
+ }
43
+ : onChange,
44
+ };
45
+ }
46
+
47
+ export function CharCount({
48
+ length,
49
+ max,
50
+ className,
51
+ }: {
52
+ length: number;
53
+ max: number;
54
+ className?: string;
55
+ }) {
56
+ return (
57
+ <span
58
+ data-slot="char-count"
59
+ className={cn(
60
+ 'pointer-events-none absolute right-2.5 text-body-12 text-muted-foreground tabular-nums',
61
+ className,
62
+ )}
63
+ >
64
+ {length}/{max}
65
+ </span>
66
+ );
67
+ }
@@ -0,0 +1,45 @@
1
+ // Datas no formato do campo de data, "2026-10-31", sem fuso: o dia é o do calendário, e não muda
2
+ // para o dia anterior quando o horário de Brasília é convertido. Usadas pelo DatePicker e pelos
3
+ // blocos de agenda, fatura e avaliações. Import: @vowt-tech/ui/date.
4
+
5
+ /** "2026-10-31" vira a data local. Texto fora do formato devolve undefined. */
6
+ export function parseDate(value: string): Date | undefined {
7
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
8
+ return m ? new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])) : undefined;
9
+ }
10
+
11
+ /** A data local vira "2026-10-31". */
12
+ export function toDateValue(date: Date): string {
13
+ const pad = (n: number) => String(n).padStart(2, '0');
14
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
15
+ }
16
+
17
+ /** Soma dias, negativos para voltar: addDays("2026-10-31", 1) dá "2026-11-01". */
18
+ export function addDays(value: string, days: number): string {
19
+ const date = parseDate(value);
20
+ if (!date) return value;
21
+ date.setDate(date.getDate() + days);
22
+ return toDateValue(date);
23
+ }
24
+
25
+ const formatters = new Map<string, Intl.DateTimeFormat>();
26
+
27
+ /**
28
+ * "2026-10-31" escrito em português. Sem opções, "31/10/2026". Com opções do Intl, como
29
+ * { weekday: 'long', day: 'numeric', month: 'long' }, "sexta-feira, 31 de outubro". Texto fora do
30
+ * formato volta como veio.
31
+ */
32
+ export function formatDate(
33
+ value: string,
34
+ options: Intl.DateTimeFormatOptions = { day: '2-digit', month: '2-digit', year: 'numeric' },
35
+ ): string {
36
+ const date = parseDate(value);
37
+ if (!date) return value;
38
+ const key = JSON.stringify(options);
39
+ let f = formatters.get(key);
40
+ if (!f) {
41
+ f = new Intl.DateTimeFormat('pt-BR', options);
42
+ formatters.set(key, f);
43
+ }
44
+ return f.format(date);
45
+ }
@@ -0,0 +1,59 @@
1
+ // Conferência de anexos antes de entregar ao app: o tipo, pelo `accept` do campo de arquivo, e o
2
+ // tamanho de cada um. Serve ao clipe, ao colar e ao soltar arquivos, que o navegador não confere
3
+ // sozinho: só a janela de escolher arquivo respeita o `accept`.
4
+
5
+ /** "1,8 MB", "245 KB". */
6
+ export function fileSize(bytes: number): string {
7
+ if (bytes < 1024) return `${bytes} B`;
8
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
9
+ return `${(bytes / 1024 / 1024).toLocaleString('pt-BR', { maximumFractionDigits: 1 })} MB`;
10
+ }
11
+
12
+ type FileLike = { name: string; type: string; size: number };
13
+
14
+ /**
15
+ * Se o arquivo passa no `accept`, no formato do campo de arquivo: "image/*,.pdf,application/zip".
16
+ * Sem `accept`, tudo passa.
17
+ */
18
+ export function acceptsFile(file: Pick<FileLike, 'name' | 'type'>, accept?: string): boolean {
19
+ const rules = (accept ?? '')
20
+ .split(',')
21
+ .map((r) => r.trim().toLowerCase())
22
+ .filter(Boolean);
23
+ if (rules.length === 0) return true;
24
+ const name = file.name.toLowerCase();
25
+ const type = file.type.toLowerCase();
26
+ return rules.some((rule) => {
27
+ if (rule.startsWith('.')) return name.endsWith(rule);
28
+ if (rule.endsWith('/*')) return type.startsWith(rule.slice(0, -1));
29
+ return type === rule;
30
+ });
31
+ }
32
+
33
+ /**
34
+ * Separa o que pode ser anexado e diz o motivo do que ficou de fora, numa frase só, como
35
+ * "1 arquivo de tipo não aceito. Cada arquivo pode ter até 10 MB." `folders` conta as pastas
36
+ * soltas, que o navegador entrega como arquivo vazio e não dá para ler.
37
+ */
38
+ export function checkFiles<F extends FileLike>(
39
+ files: readonly F[],
40
+ { accept, maxFileSize, folders = 0 }: { accept?: string; maxFileSize?: number; folders?: number },
41
+ ): { ok: F[]; error: string } {
42
+ const wrongType = files.filter((f) => !acceptsFile(f, accept));
43
+ const tooBig = files.filter(
44
+ (f) => !wrongType.includes(f) && maxFileSize !== undefined && f.size > maxFileSize,
45
+ );
46
+ const ok = files.filter((f) => !wrongType.includes(f) && !tooBig.includes(f));
47
+ const errors: string[] = [];
48
+ if (folders > 0)
49
+ errors.push(folders === 1 ? 'Pasta não é anexada.' : `${folders} pastas não são anexadas.`);
50
+ if (wrongType.length > 0)
51
+ errors.push(
52
+ wrongType.length === 1
53
+ ? `${wrongType[0]!.name} tem um tipo de arquivo não aceito.`
54
+ : `${wrongType.length} arquivos têm um tipo não aceito.`,
55
+ );
56
+ if (tooBig.length > 0 && maxFileSize !== undefined)
57
+ errors.push(`Cada arquivo pode ter até ${fileSize(maxFileSize)}.`);
58
+ return { ok, error: errors.join(' ') };
59
+ }