@raulaguila/maat-ui 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +137 -2
- package/dist/account-menu.d.ts +10 -0
- package/dist/account-menu.js +17 -0
- package/dist/auth-card.d.ts +22 -0
- package/dist/auth-card.js +14 -0
- package/dist/badge.d.ts +1 -1
- package/dist/breadcrumb.d.ts +15 -0
- package/dist/breadcrumb.js +24 -0
- package/dist/button.d.ts +5 -2
- package/dist/button.js +4 -3
- package/dist/device.d.ts +5 -0
- package/dist/device.js +23 -0
- package/dist/error-screens.d.ts +14 -0
- package/dist/error-screens.js +18 -0
- package/dist/form-error.d.ts +6 -0
- package/dist/form-error.js +8 -0
- package/dist/form-field.d.ts +4 -2
- package/dist/form-field.js +10 -2
- package/dist/format.d.ts +12 -0
- package/dist/format.js +46 -0
- package/dist/hooks.d.ts +26 -0
- package/dist/hooks.js +87 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +15 -0
- package/dist/labels.d.ts +66 -3
- package/dist/labels.js +55 -5
- package/dist/notification-bell.d.ts +5 -0
- package/dist/notification-bell.js +11 -0
- package/dist/password-strength.d.ts +7 -0
- package/dist/password-strength.js +27 -0
- package/dist/pre-paint.d.ts +9 -0
- package/dist/pre-paint.js +12 -0
- package/dist/save-bar.d.ts +20 -0
- package/dist/save-bar.js +19 -0
- package/dist/selection-bar.d.ts +8 -0
- package/dist/selection-bar.js +11 -0
- package/dist/sessions-table.d.ts +20 -0
- package/dist/sessions-table.js +48 -0
- package/dist/skeleton.d.ts +6 -1
- package/dist/skeleton.js +6 -1
- package/dist/sonner.d.ts +13 -1
- package/dist/sonner.js +29 -2
- package/dist/sort-head.d.ts +12 -0
- package/dist/sort-head.js +10 -0
- package/dist/status-badge.d.ts +8 -0
- package/dist/status-badge.js +13 -0
- package/dist/theme-toggle.d.ts +4 -0
- package/dist/theme-toggle.js +20 -0
- package/package.json +78 -4
- package/styles.css +55 -0
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@ O pacote **@raulaguila/maat-ui** é a biblioteca de componentes da família Maat
|
|
|
7
7
|
O pacote público requer React 19, React DOM 19 e Tailwind CSS 4. Escolha a versão em cada frontend:
|
|
8
8
|
|
|
9
9
|
```sh
|
|
10
|
-
pnpm add --save-exact @raulaguila/maat-ui@0.
|
|
10
|
+
pnpm add --save-exact @raulaguila/maat-ui@0.6.0
|
|
11
11
|
```
|
|
12
12
|
|
|
13
13
|
Inclua o `package.json` e o `pnpm-lock.yaml` no mesmo commit.
|
|
@@ -34,7 +34,7 @@ export function Profile() {
|
|
|
34
34
|
}
|
|
35
35
|
```
|
|
36
36
|
|
|
37
|
-
Para localizar controles, envolva a aplicação em `FamilyUIProvider` com `labels={{ close, rows, of, previous, next }}`. O idioma inicial da biblioteca é português. Para importar um único módulo, use, por exemplo, `@raulaguila/maat-ui/button` ou `@raulaguila/maat-ui/layout`.
|
|
37
|
+
Para localizar controles, envolva a aplicação em `FamilyUIProvider` com `labels={{ close, rows, of, previous, next }}`. `familyLabelsPtBR` e `familyLabelsEn` trazem todos os textos da biblioteca, inclusive o glossário de conta ("Login em duas etapas", "Encerrar", "Este dispositivo", "e-mail"…); uma chave omitida cai no português. `locale` define o idioma de datas e números, e `link` recebe o componente de link do produto (o `Link` do Next, por exemplo; `<a>` por padrão). O idioma inicial da biblioteca é português. Para importar um único módulo, use, por exemplo, `@raulaguila/maat-ui/button` ou `@raulaguila/maat-ui/layout`.
|
|
38
38
|
|
|
39
39
|
## Componentes
|
|
40
40
|
|
|
@@ -44,10 +44,35 @@ O Seshat é a referência de apresentação. Quando o Thoth precisa de um contro
|
|
|
44
44
|
|
|
45
45
|
Os módulos opcionais `@raulaguila/maat-ui/chart` (Recharts) e `@raulaguila/maat-ui/sonner` (Sonner e next-themes) têm entradas próprias. Instale os respectivos peers no produto que os utiliza.
|
|
46
46
|
|
|
47
|
+
`AuthLayout` e `AuthCard` (`@raulaguila/maat-ui/auth-card`) formam as telas de entrada, cadastro e recuperação. O produto passa o `wordmark` por altura (36 na faixa do celular, 44 acima do formulário), os `controls` de tema e idioma e o `panel` com marca, chamada e texto da coluna do desktop. `describeDevice` (`@raulaguila/maat-ui/device`) dá um nome curto ao User-Agent das sessões. `deleteWithUndo` (`@raulaguila/maat-ui/sonner`) apaga depois de um aviso com Desfazer; a tabela some na hora e `onSettled` roda ao fim. A paginação usa `[10, 25, 50, 100]` por padrão.
|
|
48
|
+
|
|
47
49
|
`ApplicationShell`, disponível em `@raulaguila/maat-ui/layout`, organiza a navegação lateral, o cabeçalho e a região principal rolável. Passe `sidebar` (incluindo o drawer), `header`, `skipLabel` traduzido e o conteúdo como filho. A biblioteca define margens, alturas e link de salto para o conteúdo nas três plataformas. O produto continua responsável por rotas, permissões e estado da navegação.
|
|
48
50
|
|
|
49
51
|
Botões, campos, seleção, checkbox, switch, badges, avatares, abas, cartões, tabelas, paginação, menus, diálogos, painéis, tooltips e skeletons compartilham tamanhos e estados. `Sidebar`, `SidebarBody` e `SidebarFooter` mantêm um centro rolável e o rodapé na base. A aplicação fornece a marca e os itens do menu. `ManagementGroup` e `ManagementRow` agrupam itens com um título acessível. Use o contêiner `family-management` e as áreas `family-open`, `family-roles`, `family-stats` e `family-actions` para reorganizar as linhas pela largura disponível.
|
|
50
52
|
|
|
53
|
+
### Peças compartilhadas (0.6.0)
|
|
54
|
+
|
|
55
|
+
Os textos vêm de `FamilyUIProvider`; as props de rótulo, quando existem, têm precedência. Componentes com dados recebem tudo por props e callbacks.
|
|
56
|
+
|
|
57
|
+
- `StatusBadge` (`/status-badge`): pílula com ponto e tom `success`, `warn`, `danger`, `muted` ou `info`. `<StatusBadge tone="success">Ativo</StatusBadge>`
|
|
58
|
+
- `ListSkeleton` (`/skeleton`): linhas de espera de uma lista. `<ListSkeleton rows={3} />`
|
|
59
|
+
- `FormError` (`/form-error`): caixa vermelha com `role="alert"` no topo do formulário; vazio não desenha nada. `<FormError>{erro}</FormError>`
|
|
60
|
+
- `SaveBar` (`/save-bar`): barra fixa de Salvar/Descartar enquanto `dirty`; `submit`, `footer`, `error` e `canSave` opcionais. `<SaveBar dirty={sujo} saving={salvando} onSave={salvar} onDiscard={descartar} />`
|
|
61
|
+
- `SelectionBar` (`/selection-bar`): contagem e ações em lote enquanto há linhas marcadas. `<SelectionBar count={n} onClear={limpar}><Button variant="destructive">Excluir</Button></SelectionBar>`
|
|
62
|
+
- `SortHead` (`/sort-head`): cabeçalho ordenável com `aria-sort`; coluna nova começa crescente, datas (`*_at`) da mais nova. `<SortHead field="name" label="Nome" sort={sort} order={order} onSort={ordenar} />`
|
|
63
|
+
- `NotFoundScreen` e `ErrorScreen` (`/error-screens`): telas de 404 e de erro com "Tentar de novo" e "Ir para o início". `export default (p) => <ErrorScreen {...p} />`
|
|
64
|
+
- `AccountMenu` (`/account-menu`): nome e e-mail, Perfil, Atalhos (com `onShortcuts`), separador e Sair. `<AccountMenu name={u.name} email={u.email} avatar={url} profileHref="/profile" onLogout={sair} />`
|
|
65
|
+
- `NotificationBell` (`/notification-bell`): link com o número de não lidas no nome acessível; o selo é decorativo. `<NotificationBell count={n} href="/notifications" />`
|
|
66
|
+
- `ThemeToggle` (`/theme-toggle`, requer next-themes, fora da entrada raiz): alterna claro e escuro; `onToggle` substitui o `setTheme` para salvar na conta. `<ThemeToggle />`
|
|
67
|
+
- `Breadcrumb` (`/breadcrumb`): trilha "Caminho da página"; `scope` em negrito, a página atual e os ancestrais distantes somem no celular. `<Breadcrumb items={[{ label: "Workspaces", href: "/workspaces" }, { label: ws, href: base, scope: true }, { label: "Arquivos" }]} />`
|
|
68
|
+
- `useDebounced`, `useDiscardChanges` e `useHashToken` (`/hooks`): valor depois de parar de mudar; proteção de alterações não salvas (fechar aba sempre; com `onOpenChange` devolve `requestClose` e `discardDialog` para diálogos, sem ele confirma cliques em links); token de `#token=` (ou `?token=` antigo) retirado da barra de endereço. `const { token, setToken, read } = useHashToken()`
|
|
69
|
+
- `formatDateTime`, `relativeTime`, `formatBytes` e `formatDuration` (`/format`): funções puras com Intl; `relativeTime` usa semanas e diz "agora" abaixo de um minuto, `formatDateTime(d, locale, { long: true })` mostra segundos e fuso (auditoria). `relativeTime(iso, locale)`
|
|
70
|
+
- `Button` com `loading`: spinner antes do rótulo, desabilitado e `aria-busy`. `<Button loading={salvando}>Salvar</Button>`
|
|
71
|
+
- `FormField` com `error`: substitui a descrição, `role="alert"`, e marca o controle com `aria-invalid` e `aria-describedby`. `<FormField id="email" label="E-mail" error={erro}><Input id="email" /></FormField>`
|
|
72
|
+
- `PasswordStrength` e `passwordScore` (`/password-strength`): medidor de quatro barras (0 a 4). `<PasswordStrength password={senha} />`
|
|
73
|
+
- `SessionsTable` (`/sessions-table`, requer sonner, fora da entrada raiz): dispositivo, IP, último acesso relativo (absoluto no `title`), "Este dispositivo", "Encerrar" por linha (toast em falha) e "Encerrar as outras" com confirmação. `<SessionsTable items={s} onRevoke={encerrar} onRevokeOthers={encerrarOutras} />`
|
|
74
|
+
- `prePaintScript` (`/pre-paint`): script do `<head>` que aplica a sidebar recolhida e a densidade salvas antes da pintura. `<script dangerouslySetInnerHTML={{ __html: prePaintScript({ uiKey: "ui", densityKey: "density" }) }} />`
|
|
75
|
+
|
|
51
76
|
## Desenvolver e distribuir
|
|
52
77
|
|
|
53
78
|
1. Execute `pnpm install --frozen-lockfile`, `pnpm test` e `pnpm catalog`. O catálogo permite alternar os três produtos, tema e densidade e testar os componentes. `pnpm catalog:build` gera a versão estática.
|
|
@@ -56,3 +81,113 @@ Botões, campos, seleção, checkbox, switch, badges, avatares, abas, cartões,
|
|
|
56
81
|
4. Faça commit da versão e envie a tag correspondente, por exemplo `v0.2.2`. O workflow de publicação verifica a versão da tag, executa os testes, compila o catálogo e publica o pacote no npm público e testa a instalação anônima.
|
|
57
82
|
|
|
58
83
|
As referências de validação são Perfil, Workspaces/Datasets e a sidebar, com mouse e teclado no desktop e alvos de 44 px no toque.
|
|
84
|
+
|
|
85
|
+
As integrações entre os produtos estão em [INTEGRATIONS.md](INTEGRATIONS.md).
|
|
86
|
+
|
|
87
|
+
## Contrato de comandos Make
|
|
88
|
+
|
|
89
|
+
O [contrato da família](tools/check_make_contract.py) define os alvos comuns e os perfis `backend`, `frontend` e `worker` (treino de IA). Cada plataforma mantém uma cópia deste arquivo em `.github/scripts/`. Ao mudar a lista, copie o arquivo para os repositórios do backend e do frontend do Thoth, do Seshat e do Khnum no mesmo conjunto de alterações. A CI de cada repositório verifica seu próprio checkout com Python 3 e GNU Make, sem acessar os outros repositórios.
|
|
90
|
+
|
|
91
|
+
Para verificar um componente localmente, execute, por exemplo, `python3 tools/check_make_contract.py frontend ../dataset/frontend` a partir deste repositório. O verificador lê as regras resolvidas pelo Make e aceita aliases que levem a uma receita. A execução das suítes e dos builds continua nos jobs de cada componente.
|
|
92
|
+
|
|
93
|
+
### Lint Go
|
|
94
|
+
|
|
95
|
+
O [`tools/golangci.yml`](tools/golangci.yml) é a base de lint dos backends (golangci-lint v2.15.0). Cada backend mantém uma cópia como `.golangci.yml` e acrescenta regras próprias só nos pontos marcados com `product`. Um limite acima da base leva um comentário `shortcut:` com o plano para baixá-lo.
|
|
96
|
+
|
|
97
|
+
### Testes de integração
|
|
98
|
+
|
|
99
|
+
Os testes que usam PostgreSQL sobem o próprio banco com testcontainers, igual na máquina e na CI (o runner do GitHub tem Docker). No Seshat e no Khnum, `internal/testpg` sobe um contêiner por binário de teste, migra um banco template com golang-migrate v4.19.1 (a mesma versão do CLI) e entrega a cada teste um banco novo copiado dele. Nenhuma variável de ambiente é necessária.
|
|
100
|
+
|
|
101
|
+
### Estrutura e operação (v3)
|
|
102
|
+
|
|
103
|
+
O Khnum é a implementação de referência. O Thoth segue o mesmo modelo em dois repositórios até virar monorepo: o repositório do backend faz o papel da raiz, e o do frontend tem só o serviço `web`, ligado à rede do backend.
|
|
104
|
+
|
|
105
|
+
```
|
|
106
|
+
Makefile alvos da família; inclui deploy/*.mk
|
|
107
|
+
.env.example todas as variáveis, comentadas; segredos como <hex>, <base64> ou <ed25519>
|
|
108
|
+
.env gerado por make init, fora do git, modo 0600
|
|
109
|
+
compose.yaml stack completa; compose.<extra>.yaml para sobreposições opcionais (gpu, docling...)
|
|
110
|
+
deploy/help.mk make help a partir dos comentários "## descrição"
|
|
111
|
+
deploy/compose.mk variável COMPOSE e perfis
|
|
112
|
+
deploy/migrations.mk migrate-* com golang-migrate v4.19.1
|
|
113
|
+
deploy/component.mk alvos de operação de um componente delegados à raiz
|
|
114
|
+
deploy/backup/ imagem e script do serviço backup
|
|
115
|
+
scripts/init_env.py cópia de tools/init_env.py (make init)
|
|
116
|
+
scripts/env-upgrade renomeações e .env antigos importados pelo init
|
|
117
|
+
backend/ frontend/ worker/ cada componente com Makefile e Dockerfile próprios
|
|
118
|
+
backend/deploy/db/migrations/ migrações SQL
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
| Área | Padrão |
|
|
122
|
+
| --- | --- |
|
|
123
|
+
| Configuração | Um único `.env` na raiz para a stack inteira. `make init` cria a partir do `.env.example` ou importa um `.env` antigo; em execuções seguintes renomeia chaves antigas e acrescenta as novas, sem alterar valores existentes. Compose e Make leem esse arquivo. Os programas leem variáveis de ambiente; em desenvolvimento local podem carregar o `.env` da raiz, sem sobrescrever o que já está no ambiente. |
|
|
124
|
+
| Nomes de variáveis | `SYS_VERSION`, `SYS_ENVIRONMENT` (`development` ou `production`), `TZ`, `LOG_LEVEL`, `LOG_FORMAT`; `POSTGRES_HOST`, `POSTGRES_PORT`, `POSTGRES_DB`, `POSTGRES_USER`, `POSTGRES_PASSWORD` e `POSTGRES_<PAPEL>_PASSWORD` para logins dedicados; `API_PORT`, `WEB_PORT`, `PUBLIC_URL` (origem do produto vista pelo navegador); `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASSWORD`, `SMTP_FROM`. Um programa que recebe uma URL de conexão a monta no `compose.yaml` a partir dessas variáveis. |
|
|
125
|
+
| Compose | Projeto `name:` igual ao produto (`seshat`, `thoth`, `khnum`). Serviços `db`, `migrate` (uma execução), `api`, `mailer`, `worker`, `web`, `backup` e os extras do produto. `container_name` e imagem `<produto>_<serviço>`; rede `<produto>_network` com nome fixo para integrações locais. Volumes com `name:` fixo; volumes de dados existentes mantêm o nome que já têm. |
|
|
126
|
+
| Imagens | Um Dockerfile multi-stage por imagem, na raiz do componente, compilando do código. Um segundo binário do mesmo componente (por exemplo o mailer) é um `target` do mesmo Dockerfile. |
|
|
127
|
+
| Make | A raiz tem `init`, `check`, `test`, `build`, `lint`, `compose-up`, `compose-build`, `compose-down`, `compose-log`, `compose-exec`, `compose-ps`, `compose-services` (só o banco), `deploy` (backup verificado, migrações, reconstrução), `migrate-*`, `backup-now`, `backup-verify`, `verify-restore`, `db-restore`. Os componentes têm `install`, `dev`, `format`, `lint`, `test`, `check`, `build` e delegam os alvos de operação à raiz com `service=` do componente. Descrições em português, no formato `alvo: ## descrição`. |
|
|
128
|
+
| Versão | `SYS_VERSION` vem do `.env`; `BUILD_REVISION` é calculado por `scripts/revision.py` e entra nas imagens. |
|
|
129
|
+
|
|
130
|
+
### Contrato operacional v2
|
|
131
|
+
|
|
132
|
+
| Área | Critério verificável |
|
|
133
|
+
| --- | --- |
|
|
134
|
+
| Recuperação | `make db-restore` restaura em destino novo e recusa destino existente. `make verify-restore` verifica uma restauração isolada. O ensaio de cada produto deve comprovar que os dados de origem permanecem íntegros; no Khnum, deve incluir os adaptadores. Uma eventual substituição do banco ativo tem comando próprio e exige escolha explícita. |
|
|
135
|
+
| Saúde | `GET /livez` indica que o processo atende. `GET /readyz` retorna 200 quando a aplicação pode atender e 503 quando perde a dependência obrigatória. Os healthchecks de prontidão usam essa segunda rota. Probes legados preservam seu significado. |
|
|
136
|
+
| CI do backend | O pipeline verifica compilação, testes de integração com o banco, lint e análise de vulnerabilidades Go com versões de ferramentas fixadas. |
|
|
137
|
+
| Regressão visual | A CI de cada frontend compara imagens de referência do perfil, sidebar e lista principal, no desktop e no celular. Também verifica largura e centralização do card de login. |
|
|
138
|
+
| Erros HTTP | O status vem no HTTP. O corpo público tem `code` textual estável, `message` legível e, quando disponíveis, `field` e `details`. Clientes do Thoth podem solicitar esse formato com `X-Maat-Error-Format: 1`; a resposta padrão da v1 preserva o tipo numérico de `code`. Os códigos seguem a lista abaixo. |
|
|
139
|
+
| Autenticação | As APIs publicam operações de conta em `/v1/auth/*`, incluindo login e refresh. Endereços públicos e contratos anteriores continuam funcionando. A sessão de cada plataforma permanece independente. |
|
|
140
|
+
| OpenAPI | `GET /openapi.yaml` fornece OpenAPI 3 sem credenciais; os formatos e endereços de documentação já utilizados continuam disponíveis. A CI do produto valida a geração do documento. |
|
|
141
|
+
|
|
142
|
+
### Códigos de erro
|
|
143
|
+
|
|
144
|
+
O `code` usa `UPPER_SNAKE`. Para cada status, o código base é:
|
|
145
|
+
|
|
146
|
+
| Status | `code` |
|
|
147
|
+
| --- | --- |
|
|
148
|
+
| 400 | `INVALID_INPUT` |
|
|
149
|
+
| 401 | `UNAUTHORIZED` |
|
|
150
|
+
| 403 | `FORBIDDEN` |
|
|
151
|
+
| 404 | `NOT_FOUND` |
|
|
152
|
+
| 409 | `CONFLICT` |
|
|
153
|
+
| 413 | `PAYLOAD_TOO_LARGE` |
|
|
154
|
+
| 422 | `UNPROCESSABLE_ENTITY` |
|
|
155
|
+
| 429 | `RATE_LIMITED` (com `Retry-After`) |
|
|
156
|
+
| 500 | `INTERNAL_ERROR` |
|
|
157
|
+
| 502 | `DEPENDENCY_UNAVAILABLE` |
|
|
158
|
+
| 503 | `UNAVAILABLE` |
|
|
159
|
+
| 504 | `TIMEOUT` |
|
|
160
|
+
|
|
161
|
+
Um produto pode usar um código mais específico com o mesmo status, também em `UPPER_SNAKE` (por exemplo `MFA_REQUIRED`, `SLUG_TAKEN`). Os clientes tratam um código desconhecido pelo status.
|
|
162
|
+
|
|
163
|
+
O verificador Make confirma os alvos disponíveis. Cada plataforma mantém uma cópia do [smoke HTTP somente leitura](tools/check_http_contract.py) em `.github/scripts/` e a CI o executa contra a API iniciada, com o banco disponível e depois parado (`--expect-ready 503`). Ao mudar o script, copie-o para os três produtos no mesmo conjunto de alterações. Localmente, informe o endereço da API e o produto (`thoth`, `seshat` ou `khnum`).
|
|
164
|
+
|
|
165
|
+
```sh
|
|
166
|
+
python3 tools/check_http_contract.py khnum http://127.0.0.1:8090
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Para o cenário de banco indisponível, use uma instalação de teste isolada. Com a falha já simulada, acrescente `--expect-ready 503`. O smoke verifica o processo, a prontidão, o erro de uma consulta de perfil sem autenticação e a versão publicada do OpenAPI. A simulação de falha e os testes autenticados ficam com a suíte do produto.
|
|
170
|
+
|
|
171
|
+
### Convenções de backend para código novo
|
|
172
|
+
|
|
173
|
+
Valem para endpoints, tabelas e jobs novos. Os contratos v1 existentes continuam como estão.
|
|
174
|
+
|
|
175
|
+
| Área | Padrão |
|
|
176
|
+
| --- | --- |
|
|
177
|
+
| Listas | Lista por cursor responde `{items, next_cursor}`; `next_cursor` é `null` na última página. Lista paginada responde `{items, pagination: {page, limit, total_items, total_pages}}`. |
|
|
178
|
+
| Correlação | Toda resposta traz `X-Request-ID`. Um id recebido só é reaproveitado quando vem de proxy confiável; o id vai para os logs da requisição. |
|
|
179
|
+
| Logs | `log/slog` em JSON, com `request_id` quando houver requisição. Nunca registra query string, token ou senha. |
|
|
180
|
+
| Acesso a dados | `pgx/v5` com SQL escrito à mão; cada consulta lê só as colunas e linhas que o chamador usa. Migrações com golang-migrate v4.19.1 em `deploy/db/migrations`. |
|
|
181
|
+
| Esquemas | Tabelas novas ficam em `auth` (identidade e sessão), `app` (domínio) ou `sys` (jobs, outbox, auditoria). |
|
|
182
|
+
| Tempo | Colunas `timestamptz` em UTC; a API envia RFC 3339 e o frontend exibe no fuso do usuário. |
|
|
183
|
+
| Idempotência | POST caro ou assíncrono aceita `Idempotency-Key`; a mesma chave com o mesmo corpo devolve a primeira resposta. |
|
|
184
|
+
|
|
185
|
+
### Convenções de frontend
|
|
186
|
+
|
|
187
|
+
| Área | Padrão |
|
|
188
|
+
| --- | --- |
|
|
189
|
+
| Dados | `@tanstack/react-query`; falhas de carga usam o estado de erro e o skeleton da família, e ações mostram o resultado com `sonner`. |
|
|
190
|
+
| Tipos da API | `pnpm gen:api` gera `src/lib/api/schema.d.ts` com `openapi-typescript` a partir do OpenAPI do backend. Tipos novos vêm do schema; os escritos à mão migram quando forem alterados. Nos monorepos, a CI falha quando o arquivo gerado diverge. |
|
|
191
|
+
| Idiomas | Catálogo em `src/lib/i18n/messages.ts` (`pt-BR` é a fonte, `en-US` tem as mesmas chaves). `make check-i18n` roda o teste vitest de paridade de chaves. |
|
|
192
|
+
| Rotas | Recursos de um usuário ficam em `[username]/[slug]`. Abas de página usam `PageTabs`. |
|
|
193
|
+
| Código | Alias `@/` para `src/`; ESLint com `core-web-vitals` e `typescript` do `eslint-config-next`; `app/error.tsx` em cada aplicação. |
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** The header's account menu: name and e-mail, Perfil, Atalhos (with `onShortcuts`), Sair. */
|
|
2
|
+
export declare function AccountMenu({ name, email, avatar, profileHref, onShortcuts, onLogout }: {
|
|
3
|
+
name: string;
|
|
4
|
+
email?: string;
|
|
5
|
+
/** Image URL; initials otherwise. */
|
|
6
|
+
avatar?: string | null;
|
|
7
|
+
profileHref: string;
|
|
8
|
+
onShortcuts?: () => void;
|
|
9
|
+
onLogout: () => void;
|
|
10
|
+
}): import("react").JSX.Element;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { Avatar, AvatarFallback, AvatarImage } from "./avatar.js";
|
|
4
|
+
import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "./dropdown-menu.js";
|
|
5
|
+
import { useFamilyLabels, useFamilyUI } from "./labels.js";
|
|
6
|
+
/** First and last word's first letters ("Ana Maria Souza" → "AS"). */
|
|
7
|
+
function initials(name) {
|
|
8
|
+
const parts = name.trim().split(/\s+/).filter((w) => /[\p{L}\p{N}]/u.test(w));
|
|
9
|
+
const last = parts.length > 1 ? parts[parts.length - 1] : undefined;
|
|
10
|
+
return ((parts[0]?.[0] ?? "") + (last?.[0] ?? parts[0]?.[1] ?? "")).toUpperCase();
|
|
11
|
+
}
|
|
12
|
+
/** The header's account menu: name and e-mail, Perfil, Atalhos (with `onShortcuts`), Sair. */
|
|
13
|
+
export function AccountMenu({ name, email, avatar, profileHref, onShortcuts, onLogout }) {
|
|
14
|
+
const labels = useFamilyLabels();
|
|
15
|
+
const { link: Link } = useFamilyUI();
|
|
16
|
+
return (_jsxs(DropdownMenu, { children: [_jsx(DropdownMenuTrigger, { "aria-label": labels.accountMenu, className: "ml-1 flex size-11 items-center justify-center rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring md:size-8", children: _jsxs(Avatar, { className: "size-8", children: [avatar && _jsx(AvatarImage, { src: avatar, alt: "" }), _jsx(AvatarFallback, { className: "text-xs", children: initials(name) || "?" })] }) }), _jsxs(DropdownMenuContent, { align: "end", className: "w-auto min-w-56 max-w-80", children: [_jsx(DropdownMenuGroup, { children: _jsxs(DropdownMenuLabel, { children: [_jsx("div", { className: "truncate text-sm text-foreground", children: name }), email && _jsx("div", { className: "truncate text-xs font-normal text-muted-foreground", children: email })] }) }), _jsx(DropdownMenuSeparator, {}), _jsx(DropdownMenuItem, { render: _jsx(Link, { href: profileHref }), children: labels.profile }), onShortcuts && _jsx(DropdownMenuItem, { onClick: onShortcuts, children: labels.shortcuts }), _jsx(DropdownMenuSeparator, {}), _jsx(DropdownMenuItem, { onClick: onLogout, children: labels.logout })] })] }));
|
|
17
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ReactNode } from "react";
|
|
2
|
+
/** The sign-in, sign-up and recovery screens: one card with the form and, on
|
|
3
|
+
* desktop, the product's brand column. The product supplies its wordmark (by
|
|
4
|
+
* height: 36 on the mobile strip, 44 above the form), its theme and language
|
|
5
|
+
* controls and the brand column's texts. Wrap it in AuthLayout. */
|
|
6
|
+
export declare function AuthCard({ title, subtitle, children, footer, wordmark, controls, panel, }: {
|
|
7
|
+
title: string;
|
|
8
|
+
subtitle?: string;
|
|
9
|
+
children?: ReactNode;
|
|
10
|
+
footer?: ReactNode;
|
|
11
|
+
wordmark: (height: number) => ReactNode;
|
|
12
|
+
controls?: ReactNode;
|
|
13
|
+
panel?: {
|
|
14
|
+
mark?: ReactNode;
|
|
15
|
+
tagline: string;
|
|
16
|
+
body: string;
|
|
17
|
+
};
|
|
18
|
+
}): import("react").JSX.Element;
|
|
19
|
+
/** Centers an AuthCard on the screen. */
|
|
20
|
+
export declare function AuthLayout({ children }: {
|
|
21
|
+
children: ReactNode;
|
|
22
|
+
}): import("react").JSX.Element;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
/** The sign-in, sign-up and recovery screens: one card with the form and, on
|
|
3
|
+
* desktop, the product's brand column. The product supplies its wordmark (by
|
|
4
|
+
* height: 36 on the mobile strip, 44 above the form), its theme and language
|
|
5
|
+
* controls and the brand column's texts. Wrap it in AuthLayout. */
|
|
6
|
+
export function AuthCard({ title, subtitle, children, footer, wordmark, controls, panel, }) {
|
|
7
|
+
return (_jsxs("div", { "data-ui-auth-card": true, className: "relative bg-card dark:bg-background", children: [_jsx("div", { "aria-hidden": true, "data-ui-auth-brand-strip": true, children: wordmark(36) }), _jsxs("div", { "data-ui-auth-form": true, className: "relative flex flex-col justify-center", children: [controls && _jsx("div", { className: "mb-4 flex items-center justify-end gap-1 text-foreground lg:hidden", children: controls }), _jsxs("div", { className: "mx-auto w-full max-w-sm space-y-8", children: [_jsx("div", { className: "hidden w-full justify-center lg:flex", children: wordmark(44) }), _jsxs("div", { children: [_jsx("h1", { className: "font-heading text-xl font-semibold tracking-tight", children: title }), subtitle && _jsx("p", { className: "mt-1.5 text-sm text-muted-foreground", children: subtitle }), _jsx("div", { className: "mt-6 space-y-5 [&_[data-slot=button]]:h-11 [&_[data-slot=button]]:rounded-md [&_[data-slot=input]]:h-11 [&_[data-slot=input]]:rounded-md [&_[data-slot=input]]:px-3 [&_[data-slot=input]]:text-base [&_[data-slot=input]]:shadow-none [&_[data-slot=input]]:focus-visible:ring-1 [&_[data-slot=input]]:focus-visible:ring-ring/40 md:[&_[data-slot=input]]:text-sm", children: children })] }), footer && _jsx("div", { className: "text-center text-sm text-muted-foreground", children: footer })] })] }), panel && (_jsxs("div", { className: "relative hidden flex-col overflow-hidden bg-(--brand-panel) text-(--brand-foreground) lg:flex", children: [controls && (_jsx("div", { className: "relative z-20 flex items-center justify-end gap-1 p-6 text-(--brand-foreground) [&_button]:text-(--brand-foreground) [&_button:hover]:bg-white/10", children: controls })), panel.mark && (
|
|
8
|
+
// Upper half only: behind the headline it fought the text.
|
|
9
|
+
_jsx("div", { "aria-hidden": true, className: "pointer-events-none absolute inset-x-0 top-0 bottom-1/2 flex items-center justify-center overflow-hidden opacity-[0.14]", children: panel.mark })), _jsxs("div", { className: "relative z-10 mt-auto max-w-md space-y-3 p-10 pr-12 pb-12", children: [_jsx("h2", { className: "font-heading text-3xl leading-tight font-semibold text-(--brand-foreground)", children: panel.tagline }), _jsx("p", { className: "text-sm leading-relaxed text-pretty text-(--brand-foreground)", children: panel.body })] })] }))] }));
|
|
10
|
+
}
|
|
11
|
+
/** Centers an AuthCard on the screen. */
|
|
12
|
+
export function AuthLayout({ children }) {
|
|
13
|
+
return _jsx("main", { "data-ui-auth-layout": true, children: children });
|
|
14
|
+
}
|
package/dist/badge.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { useRender } from "@base-ui/react/use-render";
|
|
2
2
|
import { type VariantProps } from "class-variance-authority";
|
|
3
3
|
declare const badgeVariants: (props?: ({
|
|
4
|
-
variant?: "default" | "link" | "
|
|
4
|
+
variant?: "default" | "link" | "destructive" | "secondary" | "outline" | "ghost" | null | undefined;
|
|
5
5
|
} & import("class-variance-authority/types").ClassProp) | undefined) => string;
|
|
6
6
|
declare function Badge({ className, variant, render, ...props }: useRender.ComponentProps<"span"> & VariantProps<typeof badgeVariants>): import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
|
|
7
7
|
export { Badge, badgeVariants };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface BreadcrumbItem {
|
|
2
|
+
label: string;
|
|
3
|
+
/** Left out on the last item, the current page. */
|
|
4
|
+
href?: string;
|
|
5
|
+
/** The scope the page lives in (a workspace, a collection), drawn in font-medium. */
|
|
6
|
+
scope?: boolean;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The header's trail. On a phone the h1 names the page, so only the nearest link stays: the way back.
|
|
10
|
+
* The last item without `href` is the current page.
|
|
11
|
+
*/
|
|
12
|
+
export declare function Breadcrumb({ items, label }: {
|
|
13
|
+
items: BreadcrumbItem[];
|
|
14
|
+
label?: string;
|
|
15
|
+
}): import("react").JSX.Element | null;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { Fragment } from "react";
|
|
4
|
+
import { ChevronRight } from "lucide-react";
|
|
5
|
+
import { cn } from "./cn.js";
|
|
6
|
+
import { useFamilyLabels, useFamilyUI } from "./labels.js";
|
|
7
|
+
/**
|
|
8
|
+
* The header's trail. On a phone the h1 names the page, so only the nearest link stays: the way back.
|
|
9
|
+
* The last item without `href` is the current page.
|
|
10
|
+
*/
|
|
11
|
+
export function Breadcrumb({ items, label }) {
|
|
12
|
+
const labels = useFamilyLabels();
|
|
13
|
+
const { link: Link } = useFamilyUI();
|
|
14
|
+
if (!items.length)
|
|
15
|
+
return null;
|
|
16
|
+
const lastLink = items.map((x) => !!x.href).lastIndexOf(true);
|
|
17
|
+
const sep = _jsx(ChevronRight, { "aria-hidden": true, className: "size-3.5 shrink-0 text-muted-foreground max-sm:hidden" });
|
|
18
|
+
return (_jsx("nav", { "data-ui-breadcrumb": true, "aria-label": label ?? labels.breadcrumb, className: "flex min-w-0 items-center gap-1.5 text-sm", children: items.map((x, i) => {
|
|
19
|
+
const cls = cn("min-w-0 truncate", x.scope ? "font-medium text-foreground" : "text-muted-foreground", i !== lastLink && "max-sm:hidden");
|
|
20
|
+
return _jsxs(Fragment, { children: [i > 0 && sep, x.href
|
|
21
|
+
? _jsx(Link, { href: x.href, className: cn(cls, "hover:text-foreground hover:underline"), children: x.label })
|
|
22
|
+
: _jsx("span", { "aria-current": "page", className: cls, children: x.label })] }, i);
|
|
23
|
+
}) }));
|
|
24
|
+
}
|
package/dist/button.d.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { Button as ButtonPrimitive } from "@base-ui/react/button";
|
|
2
2
|
import { type VariantProps } from "class-variance-authority";
|
|
3
3
|
declare const buttonVariants: (props?: ({
|
|
4
|
-
variant?: "default" | "link" | "
|
|
4
|
+
variant?: "default" | "link" | "destructive" | "secondary" | "outline" | "ghost" | null | undefined;
|
|
5
5
|
size?: "default" | "sm" | "lg" | "xs" | "icon" | "icon-xs" | "icon-sm" | "icon-lg" | null | undefined;
|
|
6
6
|
} & import("class-variance-authority/types").ClassProp) | undefined) => string;
|
|
7
|
-
declare function Button({ className, variant, size, ...props }: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>
|
|
7
|
+
declare function Button({ className, variant, size, loading, disabled, children, ...props }: ButtonPrimitive.Props & VariantProps<typeof buttonVariants> & {
|
|
8
|
+
/** Spinner before the label, disabled and aria-busy while true; the label stays. */
|
|
9
|
+
loading?: boolean;
|
|
10
|
+
}): import("react").JSX.Element;
|
|
8
11
|
export { Button, buttonVariants };
|
package/dist/button.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { jsx as _jsx } from "react/jsx-runtime";
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
2
|
import { Button as ButtonPrimitive } from "@base-ui/react/button";
|
|
3
3
|
import { cva } from "class-variance-authority";
|
|
4
|
+
import { Loader2 } from "lucide-react";
|
|
4
5
|
import { cn } from "./cn.js";
|
|
5
6
|
const buttonVariants = cva("group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px active:not-aria-[haspopup]:scale-[0.99] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", {
|
|
6
7
|
variants: {
|
|
@@ -28,7 +29,7 @@ const buttonVariants = cva("group/button inline-flex shrink-0 items-center justi
|
|
|
28
29
|
size: "default",
|
|
29
30
|
},
|
|
30
31
|
});
|
|
31
|
-
function Button({ className, variant = "default", size = "default", ...props }) {
|
|
32
|
-
return (
|
|
32
|
+
function Button({ className, variant = "default", size = "default", loading = false, disabled, children, ...props }) {
|
|
33
|
+
return (_jsxs(ButtonPrimitive, { "data-slot": "button", className: cn(buttonVariants({ variant, size, className })), disabled: disabled || loading, "aria-busy": loading || undefined, ...props, children: [loading && _jsx(Loader2, { "aria-hidden": true, className: "animate-spin" }), children] }));
|
|
33
34
|
}
|
|
34
35
|
export { Button, buttonVariants };
|
package/dist/device.d.ts
ADDED
package/dist/device.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
const BROWSER_NAMES = { Edg: "Edge", OPR: "Opera", CriOS: "Chrome", SamsungBrowser: "Samsung Internet" };
|
|
2
|
+
/** A short name for a User-Agent, such as "Chrome 152 · Linux" or "curl 8.18". */
|
|
3
|
+
export function describeDevice(ua) {
|
|
4
|
+
if (!ua)
|
|
5
|
+
return { label: null, mobile: false };
|
|
6
|
+
const mobile = /Mobile|Android|iPhone|iPad/.test(ua);
|
|
7
|
+
const tool = /^(curl|Wget|PostmanRuntime|python-requests|Go-http-client|okhttp)\/([\d.]+)/i.exec(ua);
|
|
8
|
+
if (tool)
|
|
9
|
+
return { label: `${tool[1]} ${tool[2]}`, mobile };
|
|
10
|
+
// Order matters: Edge and Opera also say Chrome, and Chrome also says Safari.
|
|
11
|
+
const m = /(Edg|OPR|Firefox|SamsungBrowser)\/(\d+)/.exec(ua) ??
|
|
12
|
+
/(Chrome|CriOS)\/(\d+)/.exec(ua) ??
|
|
13
|
+
/(Version)\/(\d+).*Safari\//.exec(ua);
|
|
14
|
+
const browser = m && `${m[1] === "Version" ? "Safari" : (BROWSER_NAMES[m[1]] ?? m[1])} ${m[2]}`;
|
|
15
|
+
const os = /iPhone|iPad/.test(ua) ? "iOS" :
|
|
16
|
+
/Android/.test(ua) ? "Android" :
|
|
17
|
+
/Windows/.test(ua) ? "Windows" :
|
|
18
|
+
/CrOS/.test(ua) ? "ChromeOS" :
|
|
19
|
+
/Mac OS X|Macintosh/.test(ua) ? "macOS" :
|
|
20
|
+
/Linux/.test(ua) ? "Linux" : null;
|
|
21
|
+
const label = [browser, os].filter(Boolean).join(" · ");
|
|
22
|
+
return { label: label || ua.slice(0, 60), mobile };
|
|
23
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Any address no route matches (Next's not-found). */
|
|
2
|
+
export declare function NotFoundScreen({ homeHref, title, description }: {
|
|
3
|
+
homeHref?: string;
|
|
4
|
+
title?: string;
|
|
5
|
+
description?: string;
|
|
6
|
+
}): import("react").JSX.Element;
|
|
7
|
+
/** A screen that crashed while rendering (Next's error boundary): say so and offer a way out. `error` is accepted, never shown. */
|
|
8
|
+
export declare function ErrorScreen({ reset, homeHref, title, description }: {
|
|
9
|
+
error?: unknown;
|
|
10
|
+
reset: () => void;
|
|
11
|
+
homeHref?: string;
|
|
12
|
+
title?: string;
|
|
13
|
+
description?: string;
|
|
14
|
+
}): import("react").JSX.Element;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { AlertTriangle, Compass } from "lucide-react";
|
|
4
|
+
import { Button } from "./button.js";
|
|
5
|
+
import { EmptyState } from "./empty-state.js";
|
|
6
|
+
import { useFamilyLabels, useFamilyUI } from "./labels.js";
|
|
7
|
+
/** Any address no route matches (Next's not-found). */
|
|
8
|
+
export function NotFoundScreen({ homeHref = "/", title, description }) {
|
|
9
|
+
const labels = useFamilyLabels();
|
|
10
|
+
const { link: Link } = useFamilyUI();
|
|
11
|
+
return (_jsx("div", { className: "flex flex-1 items-center justify-center p-6", children: _jsx(EmptyState, { icon: Compass, title: title ?? labels.pageNotFound, description: description ?? labels.pageNotFoundDescription, className: "w-full max-w-md", action: _jsx(Button, { nativeButton: false, render: _jsx(Link, { href: homeHref }), children: labels.goHome }) }) }));
|
|
12
|
+
}
|
|
13
|
+
/** A screen that crashed while rendering (Next's error boundary): say so and offer a way out. `error` is accepted, never shown. */
|
|
14
|
+
export function ErrorScreen({ reset, homeHref = "/", title, description }) {
|
|
15
|
+
const labels = useFamilyLabels();
|
|
16
|
+
const { link: Link } = useFamilyUI();
|
|
17
|
+
return (_jsx("div", { className: "flex flex-1 items-center justify-center p-6", children: _jsx(EmptyState, { icon: AlertTriangle, title: title ?? labels.errorTitle, description: description ?? labels.errorDescription, className: "w-full max-w-md", action: _jsxs("div", { className: "flex flex-wrap justify-center gap-2", children: [_jsx(Button, { variant: "outline", onClick: reset, children: labels.retry }), _jsx(Button, { nativeButton: false, render: _jsx(Link, { href: homeHref }), children: labels.goHome })] }) }) }));
|
|
18
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { ReactNode } from "react";
|
|
2
|
+
/** The red box a form shows above its fields when the server refuses it; nothing when empty. */
|
|
3
|
+
export declare function FormError({ children, className }: {
|
|
4
|
+
children?: ReactNode;
|
|
5
|
+
className?: string;
|
|
6
|
+
}): import("react").JSX.Element | null;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { cn } from "./cn.js";
|
|
3
|
+
/** The red box a form shows above its fields when the server refuses it; nothing when empty. */
|
|
4
|
+
export function FormError({ children, className }) {
|
|
5
|
+
if (!children)
|
|
6
|
+
return null;
|
|
7
|
+
return (_jsx("div", { role: "alert", className: cn("rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive", className), children: children }));
|
|
8
|
+
}
|
package/dist/form-field.d.ts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type ComponentProps, type ReactNode } from "react";
|
|
2
2
|
/** Share label, control and help rows so wrapped labels never offset controls. */
|
|
3
3
|
export declare function FormFieldGrid({ className, columns, ...props }: ComponentProps<"div"> & {
|
|
4
4
|
columns?: 2 | 3;
|
|
5
5
|
}): import("react").JSX.Element;
|
|
6
|
-
export declare function FormField({ id, label, description, children, className, labelClassName }: {
|
|
6
|
+
export declare function FormField({ id, label, description, error, children, className, labelClassName }: {
|
|
7
7
|
id: string;
|
|
8
8
|
label: ReactNode;
|
|
9
9
|
description?: ReactNode;
|
|
10
|
+
/** Shown in place of the description, in red and announced; marks the control aria-invalid. */
|
|
11
|
+
error?: ReactNode;
|
|
10
12
|
children: ReactNode;
|
|
11
13
|
className?: string;
|
|
12
14
|
labelClassName?: string;
|
package/dist/form-field.js
CHANGED
|
@@ -1,10 +1,18 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { cloneElement, isValidElement } from "react";
|
|
2
3
|
import { Label } from "./label.js";
|
|
3
4
|
import { cn } from "./cn.js";
|
|
4
5
|
/** Share label, control and help rows so wrapped labels never offset controls. */
|
|
5
6
|
export function FormFieldGrid({ className, columns = 2, ...props }) {
|
|
6
7
|
return _jsx("div", { "data-slot": "form-field-grid", className: cn("grid min-w-0 grid-cols-1 gap-x-4 gap-y-4 sm:gap-y-0 sm:*:data-[slot=form-field]:row-span-3 sm:*:data-[slot=form-field]:grid-rows-subgrid", columns === 3 ? "sm:grid-cols-3" : "sm:grid-cols-2", className), ...props });
|
|
7
8
|
}
|
|
8
|
-
export function FormField({ id, label, description, children, className, labelClassName }) {
|
|
9
|
-
|
|
9
|
+
export function FormField({ id, label, description, error, children, className, labelClassName }) {
|
|
10
|
+
const note = error || description;
|
|
11
|
+
const noteId = `${id}-note`;
|
|
12
|
+
// The single control gets the state and the note's id; a group of controls sets its own.
|
|
13
|
+
const control = isValidElement(children) ? cloneElement(children, {
|
|
14
|
+
"aria-invalid": error ? true : children.props["aria-invalid"],
|
|
15
|
+
"aria-describedby": note ? [children.props["aria-describedby"], noteId].filter(Boolean).join(" ") : children.props["aria-describedby"],
|
|
16
|
+
}) : children;
|
|
17
|
+
return _jsxs("div", { "data-slot": "form-field", className: cn("grid min-w-0 grid-rows-[auto_auto_1fr] content-start gap-0", className), children: [_jsx(Label, { htmlFor: id, className: cn("self-end pb-2", labelClassName), children: label }), _jsx("div", { "data-slot": "form-control", className: "min-w-0 self-start *:data-[slot=select-trigger]:w-full *:data-[slot=dropdown-select-trigger]:w-full", children: control }), _jsx("div", { id: noteId, "data-slot": "form-description", role: error ? "alert" : undefined, className: cn("min-w-0 space-y-2 text-xs", error ? "text-destructive" : "text-muted-foreground", note && "pt-2"), "aria-hidden": note ? undefined : true, children: note })] });
|
|
10
18
|
}
|
package/dist/format.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
type DateInput = string | number | Date;
|
|
2
|
+
/** Date and time in the user's language ("2 de dez. de 2026, 14:05"); `long` adds seconds and time zone (audit). "" for an invalid date. */
|
|
3
|
+
export declare function formatDateTime(date: DateInput, locale: string, opts?: {
|
|
4
|
+
long?: boolean;
|
|
5
|
+
}): string;
|
|
6
|
+
/** "há 3 horas", "em 2 semanas"; under a minute it is "agora". Pure: pass `now` to pin the clock. "" for an invalid date. */
|
|
7
|
+
export declare function relativeTime(date: DateInput, locale: string, now?: number): string;
|
|
8
|
+
/** 1536 → "1,5 kB" (binary steps, at most one decimal). */
|
|
9
|
+
export declare function formatBytes(n: number, locale: string): string;
|
|
10
|
+
/** 3725 → "1 h 2 min": the two largest non-zero units, rounded to whole seconds. */
|
|
11
|
+
export declare function formatDuration(seconds: number, locale: string): string;
|
|
12
|
+
export {};
|
package/dist/format.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
const toDate = (d) => (d instanceof Date ? d : new Date(d));
|
|
2
|
+
/** Date and time in the user's language ("2 de dez. de 2026, 14:05"); `long` adds seconds and time zone (audit). "" for an invalid date. */
|
|
3
|
+
export function formatDateTime(date, locale, opts = {}) {
|
|
4
|
+
const d = toDate(date);
|
|
5
|
+
if (Number.isNaN(d.getTime()))
|
|
6
|
+
return "";
|
|
7
|
+
return d.toLocaleString(locale, { dateStyle: "medium", timeStyle: opts.long ? "long" : "short" });
|
|
8
|
+
}
|
|
9
|
+
const STEPS = [
|
|
10
|
+
["year", 31536000], ["month", 2592000], ["week", 604800], ["day", 86400], ["hour", 3600], ["minute", 60],
|
|
11
|
+
];
|
|
12
|
+
/** "há 3 horas", "em 2 semanas"; under a minute it is "agora". Pure: pass `now` to pin the clock. "" for an invalid date. */
|
|
13
|
+
export function relativeTime(date, locale, now = Date.now()) {
|
|
14
|
+
const t = toDate(date).getTime();
|
|
15
|
+
if (Number.isNaN(t))
|
|
16
|
+
return "";
|
|
17
|
+
const secs = (t - now) / 1000;
|
|
18
|
+
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
|
|
19
|
+
const step = STEPS.find(([, s]) => Math.abs(secs) >= s);
|
|
20
|
+
return step ? rtf.format(Math.round(secs / step[1]), step[0]) : rtf.format(0, "second");
|
|
21
|
+
}
|
|
22
|
+
const BYTE_UNITS = ["byte", "kilobyte", "megabyte", "gigabyte", "terabyte"];
|
|
23
|
+
/** 1536 → "1,5 kB" (binary steps, at most one decimal). */
|
|
24
|
+
export function formatBytes(n, locale) {
|
|
25
|
+
let i = 0;
|
|
26
|
+
while (Math.abs(n) >= 1024 && i < BYTE_UNITS.length - 1) {
|
|
27
|
+
n /= 1024;
|
|
28
|
+
i++;
|
|
29
|
+
}
|
|
30
|
+
return new Intl.NumberFormat(locale, { style: "unit", unit: BYTE_UNITS[i], unitDisplay: "short", maximumFractionDigits: i ? 1 : 0 }).format(n);
|
|
31
|
+
}
|
|
32
|
+
const DURATION_UNITS = [["day", 86400], ["hour", 3600], ["minute", 60], ["second", 1]];
|
|
33
|
+
/** 3725 → "1 h 2 min": the two largest non-zero units, rounded to whole seconds. */
|
|
34
|
+
export function formatDuration(seconds, locale) {
|
|
35
|
+
let rest = Math.max(0, Math.round(seconds));
|
|
36
|
+
const parts = [];
|
|
37
|
+
for (const [unit, size] of DURATION_UNITS) {
|
|
38
|
+
const n = Math.floor(rest / size);
|
|
39
|
+
rest -= n * size;
|
|
40
|
+
if (n && parts.length < 2)
|
|
41
|
+
parts.push(new Intl.NumberFormat(locale, { style: "unit", unit, unitDisplay: "short" }).format(n));
|
|
42
|
+
else if (parts.length)
|
|
43
|
+
break; // keep the units adjacent: "1 h 2 min", never "1 h 5 s"
|
|
44
|
+
}
|
|
45
|
+
return parts.join(" ") || new Intl.NumberFormat(locale, { style: "unit", unit: "second", unitDisplay: "short" }).format(0);
|
|
46
|
+
}
|
package/dist/hooks.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** The value once it has stopped changing for `ms`; keeps typing from firing a request per key. */
|
|
2
|
+
export declare function useDebounced<T>(value: T, ms?: number): T;
|
|
3
|
+
/**
|
|
4
|
+
* Guards unsaved work while `dirty`: tab close and reload always ask. With `onOpenChange` (a dialog),
|
|
5
|
+
* `requestClose` replaces it and asks before closing through `discardDialog`, which the caller renders.
|
|
6
|
+
* Without it (a page), clicks on in-app links ask first.
|
|
7
|
+
* shortcut: browser back/forward inside the app is not caught, the App Router has no blocking API.
|
|
8
|
+
*/
|
|
9
|
+
export declare function useDiscardChanges(dirty: boolean, onOpenChange?: (open: boolean) => void): {
|
|
10
|
+
requestClose: (next: boolean) => void;
|
|
11
|
+
discardDialog: import("react").JSX.Element;
|
|
12
|
+
};
|
|
13
|
+
/** The token an e-mail link carries (`#token=`, or `?token=` from links sent before the fragment), and the address without it. */
|
|
14
|
+
export declare function takeToken(href: string): {
|
|
15
|
+
token: string | null;
|
|
16
|
+
clean: string;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Reads the link's token once mounted and clears it from the address bar, so it stays out of history and
|
|
20
|
+
* of any server log. `read` turns true after the first look; `setToken` takes a pasted one.
|
|
21
|
+
*/
|
|
22
|
+
export declare function useHashToken(): {
|
|
23
|
+
token: string;
|
|
24
|
+
setToken: import("react").Dispatch<import("react").SetStateAction<string>>;
|
|
25
|
+
read: boolean;
|
|
26
|
+
};
|