@raulaguila/maat-ui 0.5.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 +88 -2
- package/dist/account-menu.d.ts +10 -0
- package/dist/account-menu.js +17 -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/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 +13 -0
- package/dist/index.js +13 -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/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 +61 -1
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
|
|
|
@@ -50,6 +50,29 @@ Os módulos opcionais `@raulaguila/maat-ui/chart` (Recharts) e `@raulaguila/maat
|
|
|
50
50
|
|
|
51
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.
|
|
52
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
|
+
|
|
53
76
|
## Desenvolver e distribuir
|
|
54
77
|
|
|
55
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.
|
|
@@ -59,12 +82,51 @@ Botões, campos, seleção, checkbox, switch, badges, avatares, abas, cartões,
|
|
|
59
82
|
|
|
60
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.
|
|
61
84
|
|
|
85
|
+
As integrações entre os produtos estão em [INTEGRATIONS.md](INTEGRATIONS.md).
|
|
86
|
+
|
|
62
87
|
## Contrato de comandos Make
|
|
63
88
|
|
|
64
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.
|
|
65
90
|
|
|
66
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.
|
|
67
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
|
+
|
|
68
130
|
### Contrato operacional v2
|
|
69
131
|
|
|
70
132
|
| Área | Critério verificável |
|
|
@@ -105,3 +167,27 @@ python3 tools/check_http_contract.py khnum http://127.0.0.1:8090
|
|
|
105
167
|
```
|
|
106
168
|
|
|
107
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
|
+
}
|
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?: "
|
|
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?: "
|
|
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 };
|
|
@@ -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
|
+
};
|
package/dist/hooks.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
3
|
+
import { useEffect, useState } from "react";
|
|
4
|
+
import { ConfirmDialog } from "./confirm-dialog.js";
|
|
5
|
+
import { useFamilyLabels } from "./labels.js";
|
|
6
|
+
/** The value once it has stopped changing for `ms`; keeps typing from firing a request per key. */
|
|
7
|
+
export function useDebounced(value, ms = 300) {
|
|
8
|
+
const [debounced, setDebounced] = useState(value);
|
|
9
|
+
useEffect(() => {
|
|
10
|
+
const id = setTimeout(() => setDebounced(value), ms);
|
|
11
|
+
return () => clearTimeout(id);
|
|
12
|
+
}, [value, ms]);
|
|
13
|
+
return debounced;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Guards unsaved work while `dirty`: tab close and reload always ask. With `onOpenChange` (a dialog),
|
|
17
|
+
* `requestClose` replaces it and asks before closing through `discardDialog`, which the caller renders.
|
|
18
|
+
* Without it (a page), clicks on in-app links ask first.
|
|
19
|
+
* shortcut: browser back/forward inside the app is not caught, the App Router has no blocking API.
|
|
20
|
+
*/
|
|
21
|
+
export function useDiscardChanges(dirty, onOpenChange) {
|
|
22
|
+
const labels = useFamilyLabels();
|
|
23
|
+
const [confirmOpen, setConfirmOpen] = useState(false);
|
|
24
|
+
const guardLinks = !onOpenChange;
|
|
25
|
+
const message = labels.discardChanges;
|
|
26
|
+
useEffect(() => {
|
|
27
|
+
if (!dirty)
|
|
28
|
+
return;
|
|
29
|
+
const unload = (e) => { e.preventDefault(); e.returnValue = ""; };
|
|
30
|
+
const click = (e) => {
|
|
31
|
+
const a = e.target?.closest("a[href]");
|
|
32
|
+
if (!a || a.getAttribute("target") === "_blank" || e.metaKey || e.ctrlKey || e.shiftKey)
|
|
33
|
+
return;
|
|
34
|
+
if (!window.confirm(message)) {
|
|
35
|
+
e.preventDefault();
|
|
36
|
+
e.stopPropagation();
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
window.addEventListener("beforeunload", unload);
|
|
40
|
+
if (guardLinks)
|
|
41
|
+
document.addEventListener("click", click, true);
|
|
42
|
+
return () => {
|
|
43
|
+
window.removeEventListener("beforeunload", unload);
|
|
44
|
+
document.removeEventListener("click", click, true);
|
|
45
|
+
};
|
|
46
|
+
}, [dirty, guardLinks, message]);
|
|
47
|
+
const requestClose = (next) => {
|
|
48
|
+
if (!next && dirty)
|
|
49
|
+
setConfirmOpen(true);
|
|
50
|
+
else
|
|
51
|
+
onOpenChange?.(next);
|
|
52
|
+
};
|
|
53
|
+
const discardDialog = _jsx(ConfirmDialog, { open: confirmOpen, onOpenChange: setConfirmOpen, title: labels.discardTitle, description: labels.discardChanges, cancelLabel: labels.keepEditing, confirmLabel: labels.discard, destructive: true, onConfirm: () => onOpenChange?.(false) });
|
|
54
|
+
return { requestClose, discardDialog };
|
|
55
|
+
}
|
|
56
|
+
/** The token an e-mail link carries (`#token=`, or `?token=` from links sent before the fragment), and the address without it. */
|
|
57
|
+
export function takeToken(href) {
|
|
58
|
+
const url = new URL(href);
|
|
59
|
+
const token = new URLSearchParams(url.hash.slice(1)).get("token") ?? url.searchParams.get("token");
|
|
60
|
+
url.searchParams.delete("token");
|
|
61
|
+
if (new URLSearchParams(url.hash.slice(1)).has("token"))
|
|
62
|
+
url.hash = "";
|
|
63
|
+
return { token, clean: url.pathname + url.search + url.hash };
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Reads the link's token once mounted and clears it from the address bar, so it stays out of history and
|
|
67
|
+
* of any server log. `read` turns true after the first look; `setToken` takes a pasted one.
|
|
68
|
+
*/
|
|
69
|
+
export function useHashToken() {
|
|
70
|
+
const [token, setToken] = useState("");
|
|
71
|
+
const [read, setRead] = useState(false);
|
|
72
|
+
useEffect(() => {
|
|
73
|
+
const take = () => {
|
|
74
|
+
const { token: fromLink, clean } = takeToken(window.location.href);
|
|
75
|
+
setRead(true);
|
|
76
|
+
if (!fromLink)
|
|
77
|
+
return;
|
|
78
|
+
setToken(fromLink);
|
|
79
|
+
window.history.replaceState(null, "", clean);
|
|
80
|
+
};
|
|
81
|
+
take();
|
|
82
|
+
// A link pasted into the same tab changes only the fragment, so the page does not reload.
|
|
83
|
+
window.addEventListener("hashchange", take);
|
|
84
|
+
return () => window.removeEventListener("hashchange", take);
|
|
85
|
+
}, []);
|
|
86
|
+
return { token, setToken, read };
|
|
87
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -31,3 +31,16 @@ export * from "./empty-state.js";
|
|
|
31
31
|
export * from "./query-error-state.js";
|
|
32
32
|
export * from "./auth-card.js";
|
|
33
33
|
export * from "./device.js";
|
|
34
|
+
export * from "./status-badge.js";
|
|
35
|
+
export * from "./form-error.js";
|
|
36
|
+
export * from "./save-bar.js";
|
|
37
|
+
export * from "./selection-bar.js";
|
|
38
|
+
export * from "./sort-head.js";
|
|
39
|
+
export * from "./error-screens.js";
|
|
40
|
+
export * from "./account-menu.js";
|
|
41
|
+
export * from "./notification-bell.js";
|
|
42
|
+
export * from "./breadcrumb.js";
|
|
43
|
+
export * from "./format.js";
|
|
44
|
+
export * from "./hooks.js";
|
|
45
|
+
export * from "./password-strength.js";
|
|
46
|
+
export * from "./pre-paint.js";
|
package/dist/index.js
CHANGED
|
@@ -31,3 +31,16 @@ export * from "./empty-state.js";
|
|
|
31
31
|
export * from "./query-error-state.js";
|
|
32
32
|
export * from "./auth-card.js";
|
|
33
33
|
export * from "./device.js";
|
|
34
|
+
export * from "./status-badge.js";
|
|
35
|
+
export * from "./form-error.js";
|
|
36
|
+
export * from "./save-bar.js";
|
|
37
|
+
export * from "./selection-bar.js";
|
|
38
|
+
export * from "./sort-head.js";
|
|
39
|
+
export * from "./error-screens.js";
|
|
40
|
+
export * from "./account-menu.js";
|
|
41
|
+
export * from "./notification-bell.js";
|
|
42
|
+
export * from "./breadcrumb.js";
|
|
43
|
+
export * from "./format.js";
|
|
44
|
+
export * from "./hooks.js";
|
|
45
|
+
export * from "./password-strength.js";
|
|
46
|
+
export * from "./pre-paint.js";
|
package/dist/labels.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type ReactNode } from "react";
|
|
1
|
+
import { type ElementType, type ReactNode } from "react";
|
|
2
2
|
export interface FamilyLabels {
|
|
3
3
|
close: string;
|
|
4
4
|
rows: string;
|
|
@@ -15,9 +15,72 @@ export interface FamilyLabels {
|
|
|
15
15
|
errorTitle?: string;
|
|
16
16
|
errorDescription?: string;
|
|
17
17
|
retry?: string;
|
|
18
|
+
goHome?: string;
|
|
19
|
+
pageNotFound?: string;
|
|
20
|
+
pageNotFoundDescription?: string;
|
|
21
|
+
save?: string;
|
|
22
|
+
discard?: string;
|
|
23
|
+
keepEditing?: string;
|
|
24
|
+
unsaved?: string;
|
|
25
|
+
discardTitle?: string;
|
|
26
|
+
discardChanges?: string;
|
|
27
|
+
selection?: string;
|
|
28
|
+
selectedOne?: string;
|
|
29
|
+
selectedMany?: string;
|
|
30
|
+
clearSelection?: string;
|
|
31
|
+
accountMenu?: string;
|
|
32
|
+
profile?: string;
|
|
33
|
+
shortcuts?: string;
|
|
34
|
+
logout?: string;
|
|
35
|
+
notifications?: string;
|
|
36
|
+
/** "{count}" is replaced by the number. */
|
|
37
|
+
notificationsUnread?: string;
|
|
38
|
+
themeToDark?: string;
|
|
39
|
+
themeToLight?: string;
|
|
40
|
+
breadcrumb?: string;
|
|
41
|
+
passwordStrength?: string;
|
|
42
|
+
passwordWeak?: string;
|
|
43
|
+
passwordFair?: string;
|
|
44
|
+
passwordGood?: string;
|
|
45
|
+
passwordStrong?: string;
|
|
46
|
+
sessions?: string;
|
|
47
|
+
device?: string;
|
|
48
|
+
ip?: string;
|
|
49
|
+
lastSeen?: string;
|
|
50
|
+
thisDevice?: string;
|
|
51
|
+
unknownDevice?: string;
|
|
52
|
+
revoke?: string;
|
|
53
|
+
revokeOthers?: string;
|
|
54
|
+
revokeOthersDescription?: string;
|
|
55
|
+
revokeFailed?: string;
|
|
56
|
+
/** "{n}" is replaced by the number of sessions. */
|
|
57
|
+
sessionsAll?: string;
|
|
58
|
+
sessionsFewer?: string;
|
|
59
|
+
twoStepLogin?: string;
|
|
60
|
+
passwordsMismatch?: string;
|
|
61
|
+
backToLogin?: string;
|
|
62
|
+
email?: string;
|
|
18
63
|
}
|
|
19
|
-
|
|
64
|
+
/** Portuguese, the library's default language. */
|
|
65
|
+
export declare const familyLabelsPtBR: Required<FamilyLabels>;
|
|
66
|
+
export declare const familyLabelsEn: Required<FamilyLabels>;
|
|
67
|
+
/** How the library renders an in-app link (Next's Link, for example); a plain <a> by default. */
|
|
68
|
+
export type FamilyLink = ElementType<{
|
|
69
|
+
href: string;
|
|
70
|
+
className?: string;
|
|
71
|
+
children?: ReactNode;
|
|
72
|
+
}>;
|
|
73
|
+
export declare function FamilyUIProvider({ labels, locale, link, children }: {
|
|
20
74
|
labels: FamilyLabels;
|
|
75
|
+
/** BCP 47 locale for dates and numbers. */
|
|
76
|
+
locale?: string;
|
|
77
|
+
link?: FamilyLink;
|
|
21
78
|
children: ReactNode;
|
|
22
79
|
}): import("react").JSX.Element;
|
|
23
|
-
|
|
80
|
+
/** The host's labels; a key it leaves out falls back to Portuguese. */
|
|
81
|
+
export declare function useFamilyLabels(): Required<FamilyLabels>;
|
|
82
|
+
/** The host's locale and link component. */
|
|
83
|
+
export declare function useFamilyUI(): {
|
|
84
|
+
locale: string;
|
|
85
|
+
link: FamilyLink;
|
|
86
|
+
};
|
package/dist/labels.js
CHANGED
|
@@ -1,10 +1,60 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
3
3
|
import { createContext, useContext } from "react";
|
|
4
|
-
|
|
4
|
+
/** Portuguese, the library's default language. */
|
|
5
|
+
export const familyLabelsPtBR = {
|
|
5
6
|
close: "Fechar", rows: "Linhas", of: "de", previous: "Página anterior", next: "Próxima página",
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
7
|
+
noChoices: "Nenhuma opção encontrada.", hidePassword: "Ocultar senha", showPassword: "Mostrar senha",
|
|
8
|
+
cancel: "Cancelar", confirm: "Confirmar", confirming: "Aguarde…", confirmFailed: "Não foi possível concluir a ação.",
|
|
9
|
+
errorTitle: "Algo deu errado", errorDescription: "Os dados não puderam ser carregados.", retry: "Tentar de novo",
|
|
10
|
+
goHome: "Ir para o início", pageNotFound: "Página não encontrada", pageNotFoundDescription: "O endereço não existe ou mudou.",
|
|
11
|
+
save: "Salvar", discard: "Descartar", keepEditing: "Continuar editando", unsaved: "Alterações não salvas",
|
|
12
|
+
discardTitle: "Descartar alterações?", discardChanges: "Há alterações não salvas. Descartar e fechar?",
|
|
13
|
+
selection: "Seleção", selectedOne: "selecionado", selectedMany: "selecionados", clearSelection: "Limpar seleção",
|
|
14
|
+
accountMenu: "Menu da conta", profile: "Perfil", shortcuts: "Atalhos", logout: "Sair",
|
|
15
|
+
notifications: "Notificações", notificationsUnread: "Notificações, {count} por ler",
|
|
16
|
+
themeToDark: "Mudar para tema escuro", themeToLight: "Mudar para tema claro", breadcrumb: "Caminho da página",
|
|
17
|
+
passwordStrength: "Força da senha", passwordWeak: "Fraca", passwordFair: "Razoável", passwordGood: "Boa", passwordStrong: "Forte",
|
|
18
|
+
sessions: "Sessões", device: "Dispositivo", ip: "IP", lastSeen: "Último acesso", thisDevice: "Este dispositivo",
|
|
19
|
+
unknownDevice: "Dispositivo desconhecido", revoke: "Encerrar", revokeOthers: "Encerrar as outras",
|
|
20
|
+
revokeOthersDescription: "Todas as sessões, exceto esta, serão encerradas.", revokeFailed: "Não foi possível encerrar a sessão.",
|
|
21
|
+
sessionsAll: "Ver todas as {n} sessões", sessionsFewer: "Ver menos",
|
|
22
|
+
twoStepLogin: "Login em duas etapas", passwordsMismatch: "As senhas não coincidem", backToLogin: "Voltar para o login",
|
|
23
|
+
email: "e-mail",
|
|
24
|
+
};
|
|
25
|
+
export const familyLabelsEn = {
|
|
26
|
+
close: "Close", rows: "Rows", of: "of", previous: "Previous page", next: "Next page",
|
|
27
|
+
noChoices: "No options found.", hidePassword: "Hide password", showPassword: "Show password",
|
|
28
|
+
cancel: "Cancel", confirm: "Confirm", confirming: "Please wait…", confirmFailed: "The action could not be completed.",
|
|
29
|
+
errorTitle: "Something went wrong", errorDescription: "The data could not be loaded.", retry: "Try again",
|
|
30
|
+
goHome: "Go to home", pageNotFound: "Page not found", pageNotFoundDescription: "The address does not exist or has moved.",
|
|
31
|
+
save: "Save", discard: "Discard", keepEditing: "Keep editing", unsaved: "Unsaved changes",
|
|
32
|
+
discardTitle: "Discard changes?", discardChanges: "You have unsaved changes. Discard and close?",
|
|
33
|
+
selection: "Selection", selectedOne: "selected", selectedMany: "selected", clearSelection: "Clear selection",
|
|
34
|
+
accountMenu: "Account menu", profile: "Profile", shortcuts: "Shortcuts", logout: "Sign out",
|
|
35
|
+
notifications: "Notifications", notificationsUnread: "Notifications, {count} unread",
|
|
36
|
+
themeToDark: "Switch to dark theme", themeToLight: "Switch to light theme", breadcrumb: "Page path",
|
|
37
|
+
passwordStrength: "Password strength", passwordWeak: "Weak", passwordFair: "Fair", passwordGood: "Good", passwordStrong: "Strong",
|
|
38
|
+
sessions: "Sessions", device: "Device", ip: "IP", lastSeen: "Last seen", thisDevice: "This device",
|
|
39
|
+
unknownDevice: "Unknown device", revoke: "End", revokeOthers: "End the others",
|
|
40
|
+
revokeOthersDescription: "Every session except this one will be ended.", revokeFailed: "The session could not be ended.",
|
|
41
|
+
sessionsAll: "Show all {n} sessions", sessionsFewer: "Show fewer",
|
|
42
|
+
twoStepLogin: "Two-step login", passwordsMismatch: "The passwords do not match", backToLogin: "Back to sign in",
|
|
43
|
+
email: "email",
|
|
44
|
+
};
|
|
45
|
+
const Labels = createContext(familyLabelsPtBR);
|
|
46
|
+
const Env = createContext({ locale: "pt-BR", link: "a" });
|
|
47
|
+
export function FamilyUIProvider({ labels, locale = "pt-BR", link = "a", children }) {
|
|
48
|
+
return _jsx(Env.Provider, { value: { locale, link }, children: _jsx(Labels.Provider, { value: labels, children: children }) });
|
|
9
49
|
}
|
|
10
|
-
|
|
50
|
+
/** The host's labels; a key it leaves out falls back to Portuguese. */
|
|
51
|
+
export function useFamilyLabels() {
|
|
52
|
+
const labels = useContext(Labels);
|
|
53
|
+
const merged = { ...familyLabelsPtBR };
|
|
54
|
+
for (const [k, v] of Object.entries(labels))
|
|
55
|
+
if (v !== undefined)
|
|
56
|
+
merged[k] = v;
|
|
57
|
+
return merged;
|
|
58
|
+
}
|
|
59
|
+
/** The host's locale and link component. */
|
|
60
|
+
export function useFamilyUI() { return useContext(Env); }
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { Bell } from "lucide-react";
|
|
4
|
+
import { useFamilyLabels, useFamilyUI } from "./labels.js";
|
|
5
|
+
/** Header link to the notifications page with the unread count; the badge is decoration, the name says the number. */
|
|
6
|
+
export function NotificationBell({ count, href }) {
|
|
7
|
+
const labels = useFamilyLabels();
|
|
8
|
+
const { link: Link } = useFamilyUI();
|
|
9
|
+
const label = count > 0 ? labels.notificationsUnread.replace("{count}", String(count)) : labels.notifications;
|
|
10
|
+
return (_jsxs(Link, { href: href, "aria-label": label, title: label, className: "relative flex size-11 items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring md:pointer-fine:size-8", children: [_jsx(Bell, { className: "size-4", "aria-hidden": true }), count > 0 && _jsx("span", { "aria-hidden": true, className: "absolute -right-0.5 -top-0.5 min-w-4 rounded-full bg-primary px-1 text-center text-xs font-semibold leading-4 text-primary-foreground", children: count > 99 ? "99+" : count })] }));
|
|
11
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** 0 under 8 characters; then 1, plus one each for 12+ characters, mixed case, and a digit with a symbol. */
|
|
2
|
+
export declare function passwordScore(pw: string): number;
|
|
3
|
+
/** Four bars and a word under a new-password field; nothing while empty. */
|
|
4
|
+
export declare function PasswordStrength({ password, className }: {
|
|
5
|
+
password: string;
|
|
6
|
+
className?: string;
|
|
7
|
+
}): import("react").JSX.Element | null;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { cn } from "./cn.js";
|
|
4
|
+
import { useFamilyLabels } from "./labels.js";
|
|
5
|
+
/** 0 under 8 characters; then 1, plus one each for 12+ characters, mixed case, and a digit with a symbol. */
|
|
6
|
+
export function passwordScore(pw) {
|
|
7
|
+
if (pw.length < 8)
|
|
8
|
+
return 0;
|
|
9
|
+
let score = 1;
|
|
10
|
+
if (pw.length >= 12)
|
|
11
|
+
score++;
|
|
12
|
+
if (/[a-z]/.test(pw) && /[A-Z]/.test(pw))
|
|
13
|
+
score++;
|
|
14
|
+
if (/\d/.test(pw) && /[^A-Za-z0-9]/.test(pw))
|
|
15
|
+
score++;
|
|
16
|
+
return score;
|
|
17
|
+
}
|
|
18
|
+
const BAR = ["bg-destructive", "bg-destructive", "bg-warn", "bg-success/70", "bg-success"];
|
|
19
|
+
/** Four bars and a word under a new-password field; nothing while empty. */
|
|
20
|
+
export function PasswordStrength({ password, className }) {
|
|
21
|
+
const labels = useFamilyLabels();
|
|
22
|
+
if (!password)
|
|
23
|
+
return null;
|
|
24
|
+
const score = passwordScore(password);
|
|
25
|
+
const word = [labels.passwordWeak, labels.passwordWeak, labels.passwordFair, labels.passwordGood, labels.passwordStrong][score];
|
|
26
|
+
return (_jsxs("div", { className: cn("flex items-center gap-2", className), "aria-live": "polite", children: [_jsx("div", { className: "flex flex-1 gap-1", "aria-hidden": true, children: [1, 2, 3, 4].map((i) => _jsx("div", { className: cn("h-1 flex-1 rounded-full bg-muted", i <= Math.max(score, 1) && BAR[score]) }, i)) }), _jsxs("span", { className: "w-16 text-right text-xs text-muted-foreground", children: [_jsxs("span", { className: "sr-only", children: [labels.passwordStrength, ": "] }), word] })] }));
|
|
27
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inline <head> script that applies the saved collapsed sidebar (zustand-persisted `state.sidebarCollapsed`
|
|
3
|
+
* under `uiKey`) and density (under `densityKey`) before the first paint. The shell removes the
|
|
4
|
+
* `sidebar-collapsed` class once its store takes over.
|
|
5
|
+
*/
|
|
6
|
+
export declare function prePaintScript({ uiKey, densityKey }: {
|
|
7
|
+
uiKey: string;
|
|
8
|
+
densityKey?: string;
|
|
9
|
+
}): string;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inline <head> script that applies the saved collapsed sidebar (zustand-persisted `state.sidebarCollapsed`
|
|
3
|
+
* under `uiKey`) and density (under `densityKey`) before the first paint. The shell removes the
|
|
4
|
+
* `sidebar-collapsed` class once its store takes over.
|
|
5
|
+
*/
|
|
6
|
+
export function prePaintScript({ uiKey, densityKey }) {
|
|
7
|
+
const ui = JSON.stringify(uiKey);
|
|
8
|
+
const density = densityKey
|
|
9
|
+
? `try{var d=localStorage.getItem(${JSON.stringify(densityKey)});if(d==='comfortable'||d==='compact')document.documentElement.setAttribute('data-density',d)}catch(e){}`
|
|
10
|
+
: "";
|
|
11
|
+
return `(function(){try{var r=localStorage.getItem(${ui});var p=r&&JSON.parse(r);if(p&&p.state&&p.state.sidebarCollapsed)document.documentElement.classList.add('sidebar-collapsed')}catch(e){}${density}})();`;
|
|
12
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ReactNode } from "react";
|
|
2
|
+
/**
|
|
3
|
+
* Save control, sticky at the bottom while `dirty`. As the last child of FormSections, `footer` makes it
|
|
4
|
+
* the card's footer; otherwise it sits inside its section. `submit` makes Save the form's submit button, so Enter saves.
|
|
5
|
+
*/
|
|
6
|
+
export declare function SaveBar({ dirty, saving, canSave, onSave, onDiscard, label, error, saveLabel, discardLabel, submit, footer }: {
|
|
7
|
+
dirty: boolean;
|
|
8
|
+
saving?: boolean;
|
|
9
|
+
canSave?: boolean;
|
|
10
|
+
onSave?: () => void;
|
|
11
|
+
onDiscard: () => void;
|
|
12
|
+
/** Names the bar; "Alterações não salvas" by default. */
|
|
13
|
+
label?: string;
|
|
14
|
+
/** Takes the label's place, so the buttons keep theirs. */
|
|
15
|
+
error?: ReactNode;
|
|
16
|
+
saveLabel?: string;
|
|
17
|
+
discardLabel?: string;
|
|
18
|
+
submit?: boolean;
|
|
19
|
+
footer?: boolean;
|
|
20
|
+
}): import("react").JSX.Element | null;
|
package/dist/save-bar.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { Button } from "./button.js";
|
|
4
|
+
import { cn } from "./cn.js";
|
|
5
|
+
import { FormError } from "./form-error.js";
|
|
6
|
+
import { useFamilyLabels } from "./labels.js";
|
|
7
|
+
/**
|
|
8
|
+
* Save control, sticky at the bottom while `dirty`. As the last child of FormSections, `footer` makes it
|
|
9
|
+
* the card's footer; otherwise it sits inside its section. `submit` makes Save the form's submit button, so Enter saves.
|
|
10
|
+
*/
|
|
11
|
+
export function SaveBar({ dirty, saving = false, canSave = true, onSave, onDiscard, label, error, saveLabel, discardLabel, submit = false, footer = false }) {
|
|
12
|
+
const labels = useFamilyLabels();
|
|
13
|
+
if (!dirty)
|
|
14
|
+
return null;
|
|
15
|
+
const name = label ?? labels.unsaved;
|
|
16
|
+
return (_jsxs("div", { role: "region", "aria-label": name, className: cn("sticky z-10 flex flex-wrap items-center gap-3",
|
|
17
|
+
// The negative margins undo FormSections' padding so the bar spans the card.
|
|
18
|
+
footer ? "bottom-0 -mx-6 -mb-6 rounded-b-xl border-t bg-card px-6 py-4 sm:-mx-8 sm:-mb-8 sm:px-8" : "bottom-4 rounded-lg border bg-muted px-4 py-3"), children: [_jsx("div", { className: "min-w-0 flex-1 text-sm font-medium", children: error ? _jsx(FormError, { children: error }) : name }), _jsx(Button, { type: "button", variant: "ghost", disabled: saving, onClick: onDiscard, children: discardLabel ?? labels.discard }), _jsx(Button, { type: submit ? "submit" : "button", loading: saving, disabled: !canSave, onClick: submit ? undefined : onSave, children: saveLabel ?? labels.save })] }));
|
|
19
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ReactNode } from "react";
|
|
2
|
+
/** Sticky bar with the count and the bulk actions while rows are ticked; nothing at zero. */
|
|
3
|
+
export declare function SelectionBar({ count, onClear, children, label }: {
|
|
4
|
+
count: number;
|
|
5
|
+
onClear: () => void;
|
|
6
|
+
children?: ReactNode;
|
|
7
|
+
label?: string;
|
|
8
|
+
}): import("react").JSX.Element | null;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
|
|
3
|
+
import { Button } from "./button.js";
|
|
4
|
+
import { useFamilyLabels } from "./labels.js";
|
|
5
|
+
/** Sticky bar with the count and the bulk actions while rows are ticked; nothing at zero. */
|
|
6
|
+
export function SelectionBar({ count, onClear, children, label }) {
|
|
7
|
+
const labels = useFamilyLabels();
|
|
8
|
+
if (count === 0)
|
|
9
|
+
return null;
|
|
10
|
+
return (_jsxs("div", { role: "region", "aria-label": label ?? labels.selection, className: "sticky bottom-4 z-10 flex flex-wrap items-center gap-2 rounded-xl border bg-card px-4 py-3 shadow-lg", children: [_jsxs("span", { "aria-live": "polite", className: "flex-1 text-sm font-medium", children: [count, " ", count === 1 ? labels.selectedOne : labels.selectedMany] }), _jsx(Button, { variant: "ghost", onClick: onClear, children: labels.clearSelection }), children] }));
|
|
11
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export interface SessionItem {
|
|
2
|
+
id: string;
|
|
3
|
+
user_agent: string | null;
|
|
4
|
+
ip_address: string | null;
|
|
5
|
+
/** RFC 3339. */
|
|
6
|
+
last_seen_at: string;
|
|
7
|
+
current?: boolean;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* The account's sessions: this device first, then the newest; a long list shows five until asked.
|
|
11
|
+
* "Encerrar as outras" asks first. A failed revoke toasts `formatError(error)` (or a generic line).
|
|
12
|
+
*/
|
|
13
|
+
export declare function SessionsTable({ items, currentId, onRevoke, onRevokeOthers, formatError }: {
|
|
14
|
+
items: SessionItem[];
|
|
15
|
+
/** The current session, when items do not mark it with `current`. */
|
|
16
|
+
currentId?: string;
|
|
17
|
+
onRevoke: (id: string) => Promise<unknown>;
|
|
18
|
+
onRevokeOthers: () => Promise<unknown>;
|
|
19
|
+
formatError?: (error: unknown) => string;
|
|
20
|
+
}): import("react").JSX.Element;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useState } from "react";
|
|
4
|
+
import { Monitor, Smartphone } from "lucide-react";
|
|
5
|
+
import { toast } from "sonner";
|
|
6
|
+
import { Badge } from "./badge.js";
|
|
7
|
+
import { Button } from "./button.js";
|
|
8
|
+
import { Card } from "./card.js";
|
|
9
|
+
import { ConfirmDialog } from "./confirm-dialog.js";
|
|
10
|
+
import { describeDevice } from "./device.js";
|
|
11
|
+
import { formatDateTime, relativeTime } from "./format.js";
|
|
12
|
+
import { useFamilyLabels, useFamilyUI } from "./labels.js";
|
|
13
|
+
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./table.js";
|
|
14
|
+
const SHOWN = 5;
|
|
15
|
+
/**
|
|
16
|
+
* The account's sessions: this device first, then the newest; a long list shows five until asked.
|
|
17
|
+
* "Encerrar as outras" asks first. A failed revoke toasts `formatError(error)` (or a generic line).
|
|
18
|
+
*/
|
|
19
|
+
export function SessionsTable({ items, currentId, onRevoke, onRevokeOthers, formatError }) {
|
|
20
|
+
const labels = useFamilyLabels();
|
|
21
|
+
const { locale } = useFamilyUI();
|
|
22
|
+
const [all, setAll] = useState(false);
|
|
23
|
+
const [confirmOthers, setConfirmOthers] = useState(false);
|
|
24
|
+
const [pending, setPending] = useState(null);
|
|
25
|
+
const isCurrent = (s) => s.current ?? s.id === currentId;
|
|
26
|
+
const sorted = items.slice().sort((a, b) => Number(isCurrent(b)) - Number(isCurrent(a)) || b.last_seen_at.localeCompare(a.last_seen_at));
|
|
27
|
+
const shown = all ? sorted : sorted.slice(0, SHOWN);
|
|
28
|
+
const others = sorted.filter((s) => !isCurrent(s)).length;
|
|
29
|
+
const revoke = async (id) => {
|
|
30
|
+
setPending(id);
|
|
31
|
+
try {
|
|
32
|
+
await onRevoke(id);
|
|
33
|
+
}
|
|
34
|
+
catch (e) {
|
|
35
|
+
toast.error(formatError?.(e) ?? labels.revokeFailed);
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
setPending(null);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
return (_jsxs("div", { className: "space-y-3", children: [others > 0 && (_jsx("div", { className: "flex justify-end", children: _jsx(Button, { variant: "outline", size: "sm", onClick: () => setConfirmOthers(true), children: labels.revokeOthers }) })), _jsxs(Card, { className: "gap-0 overflow-hidden p-0", children: [_jsxs(Table, { "aria-label": labels.sessions, children: [_jsx(TableHeader, { children: _jsxs(TableRow, { children: [_jsx(TableHead, { children: labels.device }), _jsx(TableHead, { className: "max-sm:hidden", children: labels.ip }), _jsx(TableHead, { children: labels.lastSeen }), _jsx(TableHead, { className: "w-28", children: _jsx("span", { className: "sr-only", children: labels.revoke }) })] }) }), _jsx(TableBody, { children: shown.map((s) => {
|
|
42
|
+
const device = describeDevice(s.user_agent);
|
|
43
|
+
const Icon = device.mobile ? Smartphone : Monitor;
|
|
44
|
+
return (_jsxs(TableRow, { children: [_jsx(TableCell, { className: "w-1/2 max-w-0", children: _jsxs("span", { className: "flex min-w-0 items-center gap-2", children: [_jsx(Icon, { className: "size-4 shrink-0 text-muted-foreground", "aria-hidden": true }), _jsx("span", { className: "truncate font-medium", title: s.user_agent ?? undefined, children: device.label ?? labels.unknownDevice })] }) }), _jsx(TableCell, { className: "font-mono text-xs text-muted-foreground max-sm:hidden", children: s.ip_address ?? "—" }), _jsx(TableCell, { className: "whitespace-normal text-muted-foreground", children: _jsx("time", { dateTime: s.last_seen_at, title: formatDateTime(s.last_seen_at, locale), children: relativeTime(s.last_seen_at, locale) }) }), _jsx(TableCell, { className: "text-right", children: isCurrent(s)
|
|
45
|
+
? _jsx(Badge, { variant: "secondary", children: labels.thisDevice })
|
|
46
|
+
: _jsx(Button, { variant: "ghost", size: "sm", loading: pending === s.id, disabled: pending !== null, onClick: () => void revoke(s.id), children: labels.revoke }) })] }, s.id));
|
|
47
|
+
}) })] }), sorted.length > SHOWN && (_jsx("div", { className: "border-t px-4 py-2", children: _jsx(Button, { variant: "link", size: "sm", className: "h-auto p-0", "aria-expanded": all, onClick: () => setAll(!all), children: all ? labels.sessionsFewer : labels.sessionsAll.replace("{n}", String(sorted.length)) }) }))] }), _jsx(ConfirmDialog, { open: confirmOthers, onOpenChange: setConfirmOthers, title: labels.revokeOthers, description: labels.revokeOthersDescription, destructive: true, formatError: formatError, onConfirm: async () => { await onRevokeOthers(); } })] }));
|
|
48
|
+
}
|
package/dist/skeleton.d.ts
CHANGED
|
@@ -1,2 +1,7 @@
|
|
|
1
1
|
declare function Skeleton({ className, ...props }: React.ComponentProps<"div">): import("react").JSX.Element;
|
|
2
|
-
|
|
2
|
+
/** Stacked rows standing in for a list while it loads. */
|
|
3
|
+
declare function ListSkeleton({ rows, className }: {
|
|
4
|
+
rows?: number;
|
|
5
|
+
className?: string;
|
|
6
|
+
}): import("react").JSX.Element;
|
|
7
|
+
export { Skeleton, ListSkeleton };
|
package/dist/skeleton.js
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { Card } from "./card.js";
|
|
2
3
|
import { cn } from "./cn.js";
|
|
3
4
|
function Skeleton({ className, ...props }) {
|
|
4
5
|
return (_jsx("div", { "data-slot": "skeleton", className: cn("animate-pulse rounded-md bg-muted", className), ...props }));
|
|
5
6
|
}
|
|
6
|
-
|
|
7
|
+
/** Stacked rows standing in for a list while it loads. */
|
|
8
|
+
function ListSkeleton({ rows = 5, className }) {
|
|
9
|
+
return (_jsx(Card, { "aria-hidden": true, className: cn("gap-0 divide-y p-0", className), children: Array.from({ length: rows }, (_, i) => (_jsx("div", { className: "px-4 py-3", children: _jsx(Skeleton, { className: "h-4 w-1/2" }) }, i))) }));
|
|
10
|
+
}
|
|
11
|
+
export { Skeleton, ListSkeleton };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type LucideIcon } from "lucide-react";
|
|
2
|
+
export type SortOrder = "asc" | "desc";
|
|
3
|
+
/** A column header that sorts the list; a new column starts ascending, dates (`*_at`) newest first. */
|
|
4
|
+
export declare function SortHead({ field, label, icon: Icon, sort, order, onSort, className }: {
|
|
5
|
+
field: string;
|
|
6
|
+
label: string;
|
|
7
|
+
icon?: LucideIcon;
|
|
8
|
+
sort: string;
|
|
9
|
+
order: SortOrder;
|
|
10
|
+
onSort: (sort: string, order: SortOrder) => void;
|
|
11
|
+
className?: string;
|
|
12
|
+
}): import("react").JSX.Element;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { ArrowDown, ArrowUp } from "lucide-react";
|
|
4
|
+
import { TableHead } from "./table.js";
|
|
5
|
+
/** A column header that sorts the list; a new column starts ascending, dates (`*_at`) newest first. */
|
|
6
|
+
export function SortHead({ field, label, icon: Icon, sort, order, onSort, className }) {
|
|
7
|
+
const active = sort === field;
|
|
8
|
+
const next = active ? (order === "asc" ? "desc" : "asc") : field.endsWith("_at") ? "desc" : "asc";
|
|
9
|
+
return (_jsx(TableHead, { className: className, "aria-sort": active ? (order === "asc" ? "ascending" : "descending") : undefined, children: _jsxs("button", { type: "button", className: "inline-flex items-center gap-1 rounded-sm outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring", onClick: () => onSort(field, next), children: [Icon && _jsx(Icon, { className: "size-3.5 opacity-60", "aria-hidden": true }), label, active && (order === "asc" ? _jsx(ArrowUp, { "aria-hidden": true, className: "size-3.5" }) : _jsx(ArrowDown, { "aria-hidden": true, className: "size-3.5" }))] }) }));
|
|
10
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ReactNode } from "react";
|
|
2
|
+
export type StatusTone = "success" | "warn" | "danger" | "muted" | "info";
|
|
3
|
+
/** A state as a tinted pill with a dot (active, failed, running…); the product maps its states to tones. */
|
|
4
|
+
export declare function StatusBadge({ tone, children, className }: {
|
|
5
|
+
tone: StatusTone;
|
|
6
|
+
children: ReactNode;
|
|
7
|
+
className?: string;
|
|
8
|
+
}): import("react").JSX.Element;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { cn } from "./cn.js";
|
|
3
|
+
const TONE = {
|
|
4
|
+
success: "bg-success/15 text-success",
|
|
5
|
+
warn: "bg-warn/15 text-warn",
|
|
6
|
+
danger: "bg-destructive/15 text-destructive",
|
|
7
|
+
muted: "bg-muted-foreground/15 text-muted-foreground",
|
|
8
|
+
info: "bg-info/15 text-info",
|
|
9
|
+
};
|
|
10
|
+
/** A state as a tinted pill with a dot (active, failed, running…); the product maps its states to tones. */
|
|
11
|
+
export function StatusBadge({ tone, children, className }) {
|
|
12
|
+
return (_jsxs("span", { "data-slot": "status-badge", "data-tone": tone, className: cn("inline-flex items-center gap-1.5 whitespace-nowrap rounded-full px-2 py-0.5 text-xs font-medium", TONE[tone], className), children: [_jsx("span", { "aria-hidden": true, className: "size-1.5 shrink-0 rounded-full bg-current" }), children] }));
|
|
13
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
3
|
+
import { useEffect, useState } from "react";
|
|
4
|
+
import { useTheme } from "next-themes";
|
|
5
|
+
import { Moon, Sun } from "lucide-react";
|
|
6
|
+
import { useFamilyLabels } from "./labels.js";
|
|
7
|
+
/** Light/dark switch (next-themes). `onToggle` replaces setTheme, to save the choice to the account. */
|
|
8
|
+
export function ThemeToggle({ onToggle }) {
|
|
9
|
+
const labels = useFamilyLabels();
|
|
10
|
+
const { resolvedTheme, setTheme } = useTheme();
|
|
11
|
+
const [mounted, setMounted] = useState(false);
|
|
12
|
+
// Mount flag: the server cannot know the theme, so the first render matches it.
|
|
13
|
+
useEffect(() => setMounted(true), []);
|
|
14
|
+
const isDark = mounted && resolvedTheme === "dark";
|
|
15
|
+
const label = isDark ? labels.themeToLight : labels.themeToDark;
|
|
16
|
+
return (_jsx("button", { type: "button", "aria-label": label, title: label, onClick: () => { const next = isDark ? "light" : "dark"; if (onToggle)
|
|
17
|
+
onToggle(next);
|
|
18
|
+
else
|
|
19
|
+
setTheme(next); }, className: "flex size-11 items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring md:size-8", children: isDark ? _jsx(Sun, { className: "size-4", "aria-hidden": true }) : _jsx(Moon, { className: "size-4", "aria-hidden": true }) }));
|
|
20
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@raulaguila/maat-ui",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"registry": "https://registry.npmjs.org",
|
|
6
6
|
"access": "public"
|
|
@@ -163,6 +163,66 @@
|
|
|
163
163
|
"./sonner": {
|
|
164
164
|
"types": "./dist/sonner.d.ts",
|
|
165
165
|
"import": "./dist/sonner.js"
|
|
166
|
+
},
|
|
167
|
+
"./status-badge": {
|
|
168
|
+
"types": "./dist/status-badge.d.ts",
|
|
169
|
+
"import": "./dist/status-badge.js"
|
|
170
|
+
},
|
|
171
|
+
"./form-error": {
|
|
172
|
+
"types": "./dist/form-error.d.ts",
|
|
173
|
+
"import": "./dist/form-error.js"
|
|
174
|
+
},
|
|
175
|
+
"./save-bar": {
|
|
176
|
+
"types": "./dist/save-bar.d.ts",
|
|
177
|
+
"import": "./dist/save-bar.js"
|
|
178
|
+
},
|
|
179
|
+
"./selection-bar": {
|
|
180
|
+
"types": "./dist/selection-bar.d.ts",
|
|
181
|
+
"import": "./dist/selection-bar.js"
|
|
182
|
+
},
|
|
183
|
+
"./sort-head": {
|
|
184
|
+
"types": "./dist/sort-head.d.ts",
|
|
185
|
+
"import": "./dist/sort-head.js"
|
|
186
|
+
},
|
|
187
|
+
"./error-screens": {
|
|
188
|
+
"types": "./dist/error-screens.d.ts",
|
|
189
|
+
"import": "./dist/error-screens.js"
|
|
190
|
+
},
|
|
191
|
+
"./account-menu": {
|
|
192
|
+
"types": "./dist/account-menu.d.ts",
|
|
193
|
+
"import": "./dist/account-menu.js"
|
|
194
|
+
},
|
|
195
|
+
"./notification-bell": {
|
|
196
|
+
"types": "./dist/notification-bell.d.ts",
|
|
197
|
+
"import": "./dist/notification-bell.js"
|
|
198
|
+
},
|
|
199
|
+
"./theme-toggle": {
|
|
200
|
+
"types": "./dist/theme-toggle.d.ts",
|
|
201
|
+
"import": "./dist/theme-toggle.js"
|
|
202
|
+
},
|
|
203
|
+
"./breadcrumb": {
|
|
204
|
+
"types": "./dist/breadcrumb.d.ts",
|
|
205
|
+
"import": "./dist/breadcrumb.js"
|
|
206
|
+
},
|
|
207
|
+
"./format": {
|
|
208
|
+
"types": "./dist/format.d.ts",
|
|
209
|
+
"import": "./dist/format.js"
|
|
210
|
+
},
|
|
211
|
+
"./hooks": {
|
|
212
|
+
"types": "./dist/hooks.d.ts",
|
|
213
|
+
"import": "./dist/hooks.js"
|
|
214
|
+
},
|
|
215
|
+
"./password-strength": {
|
|
216
|
+
"types": "./dist/password-strength.d.ts",
|
|
217
|
+
"import": "./dist/password-strength.js"
|
|
218
|
+
},
|
|
219
|
+
"./sessions-table": {
|
|
220
|
+
"types": "./dist/sessions-table.d.ts",
|
|
221
|
+
"import": "./dist/sessions-table.js"
|
|
222
|
+
},
|
|
223
|
+
"./pre-paint": {
|
|
224
|
+
"types": "./dist/pre-paint.d.ts",
|
|
225
|
+
"import": "./dist/pre-paint.js"
|
|
166
226
|
}
|
|
167
227
|
},
|
|
168
228
|
"sideEffects": [
|