@raulaguila/maat-ui 0.6.1 → 0.8.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 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.6.1
10
+ pnpm add --save-exact @raulaguila/maat-ui@0.8.0
11
11
  ```
12
12
 
13
13
  Inclua o `package.json` e o `pnpm-lock.yaml` no mesmo commit.
@@ -63,11 +63,12 @@ Os textos vêm de `FamilyUIProvider`; as props de rótulo, quando existem, têm
63
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
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
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 />`
66
+ - `ThemeToggle` (`/theme-toggle`, requer next-themes, fora da entrada raiz): alterna claro e escuro; aplica o tema na hora e depois chama `onToggle`, para salvar na conta. `<ThemeToggle />`
67
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
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
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
70
  - `Button` com `loading`: spinner antes do rótulo, desabilitado e `aria-busy`. `<Button loading={salvando}>Salvar</Button>`
71
+ - `FormField floating` posiciona o rótulo de um `Input` ou `PasswordInput` na borda ao focar ou preencher, inclusive com autofill. Use um único controle com o `autoComplete` apropriado.
71
72
  - `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
73
  - `PasswordStrength` e `passwordScore` (`/password-strength`): medidor de quatro barras (0 a 4). `<PasswordStrength password={senha} />`
73
74
  - `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} />`
@@ -98,33 +99,35 @@ O [`tools/golangci.yml`](tools/golangci.yml) é a base de lint dos backends (gol
98
99
 
99
100
  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
 
101
- ### Estrutura e operação (v3)
102
+ ### Estrutura e operação (v4)
102
103
 
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
+ O Thoth é a implementação de referência das imagens (modelo bin/code); Seshat e Khnum seguem o mesmo modelo. 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
 
105
106
  ```
106
107
  Makefile alvos da família; inclui deploy/*.mk
107
- .env.example todas as variáveis, comentadas; segredos como <hex>, <base64> ou <ed25519>
108
+ config/env.sh make init: gera o .env da raiz com todas as variáveis comentadas e segredos novos; completa um .env existente sem alterar valores
108
109
  .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
110
  deploy/help.mk make help a partir dos comentários "## descrição"
111
111
  deploy/compose.mk variável COMPOSE e perfis
112
- deploy/migrations.mk migrate-* com golang-migrate v4.19.1
112
+ deploy/migrations.mk migrate-* com a CLI golang-migrate v4.19.1 no host (sem serviço migrate no compose); a URL vem do .env
113
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
114
+ deploy/docker/compose.yml serviços da aplicação; inclui services.compose.yml
115
+ deploy/docker/services.compose.yml infraestrutura (banco e extras), rede e volumes; make compose-services
116
+ deploy/docker/<serviço>/bin.Dockerfile copia o binário compilado no host (make build)
117
+ deploy/docker/<serviço>/code.Dockerfile compila dentro do Docker
118
+ deploy/docker/compose.<extra>.yml sobreposições opcionais (gpu, seshat-local...)
119
+ deploy/docker/backup/ imagem e script do serviço backup
120
+ backend/ frontend/ worker/ cada componente com Makefile próprio
118
121
  backend/deploy/db/migrations/ migrações SQL
119
122
  ```
120
123
 
121
124
  | Área | Padrão |
122
125
  | --- | --- |
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`. |
126
+ | Configuração | Um único `.env` na raiz para a stack inteira, fora do git, modo 0600. `make init` roda `config/env.sh`, que traz o modelo completo (variáveis, comentários e valores padrão) e gera os segredos com `openssl`; num `.env` existente só acrescenta as variáveis que faltam, sem alterar valores. 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. |
127
+ | 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 `deploy/docker/compose.yml` a partir dessas variáveis. |
128
+ | Compose | Projeto `name:` igual ao produto (`seshat`, `thoth`, `khnum`). Serviços `db`, `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. |
129
+ | Imagens | Dois Dockerfiles por serviço em `deploy/docker/<serviço>/`. `bin.Dockerfile` (padrão) copia o binário Go ou o `.next/standalone` gerados por `make build` no host: rápido, reaproveita o cache local. `code.Dockerfile` compila dentro do Docker, para CI ou máquina sem Go/Node: `make compose-build base=code`. Imagens sem binário (backup, worker Python) têm um único `Dockerfile`. Todo `apk add`, em todo estágio, vem precedido de `sed -i 's\|https://dl-cdn.alpinelinux.org\|http://dl-cdn.alpinelinux.org\|g' /etc/apk/repositories` (rede corporativa); o runtime instala `bash tzdata dumb-init` e roda como usuário não root. |
130
+ | Make | A raiz tem `init`, `check`, `test`, `build`, `lint`, `compose-up`, `compose-build`, `compose-down`, `compose-log`, `compose-exec`, `compose-ps`, `compose-services` (só a infraestrutura), `build` (binários Go e `pnpm build`), `base=bin\|code` em `compose-build`, `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
131
  | Versão | `SYS_VERSION` vem do `.env`; `BUILD_REVISION` é calculado por `scripts/revision.py` e entra nas imagens. |
129
132
 
130
133
  ### Contrato operacional v2
@@ -3,7 +3,7 @@ import { type ComponentProps, type ReactNode } from "react";
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, error, children, className, labelClassName }: {
6
+ export declare function FormField({ id, label, description, error, children, className, labelClassName, floating }: {
7
7
  id: string;
8
8
  label: ReactNode;
9
9
  description?: ReactNode;
@@ -12,4 +12,6 @@ export declare function FormField({ id, label, description, error, children, cla
12
12
  children: ReactNode;
13
13
  className?: string;
14
14
  labelClassName?: string;
15
+ /** Float the label on the border of a single text or password input. */
16
+ floating?: boolean;
15
17
  }): import("react").JSX.Element;
@@ -1,4 +1,4 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { cloneElement, isValidElement } from "react";
3
3
  import { Label } from "./label.js";
4
4
  import { cn } from "./cn.js";
@@ -6,13 +6,15 @@ import { cn } from "./cn.js";
6
6
  export function FormFieldGrid({ className, columns = 2, ...props }) {
7
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 });
8
8
  }
9
- export function FormField({ id, label, description, error, children, className, labelClassName }) {
9
+ export function FormField({ id, label, description, error, children, className, labelClassName, floating = false }) {
10
10
  const note = error || description;
11
11
  const noteId = `${id}-note`;
12
12
  // The single control gets the state and the note's id; a group of controls sets its own.
13
13
  const control = isValidElement(children) ? cloneElement(children, {
14
+ ...(floating ? { id, placeholder: " " } : {}),
14
15
  "aria-invalid": error ? true : children.props["aria-invalid"],
15
16
  "aria-describedby": note ? [children.props["aria-describedby"], noteId].filter(Boolean).join(" ") : children.props["aria-describedby"],
16
17
  }) : 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 })] });
18
+ const fieldLabel = _jsx(Label, { htmlFor: id, className: cn(!floating && "self-end pb-2", labelClassName), children: label });
19
+ return _jsxs("div", { "data-slot": "form-field", className: cn("grid min-w-0 grid-rows-[auto_auto_1fr] content-start gap-0", className), children: [floating ? _jsxs("div", { "data-ui-floating-control": true, children: [fieldLabel, control] }) : _jsxs(_Fragment, { children: [fieldLabel, _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 })] });
18
20
  }
@@ -1,4 +1,4 @@
1
- /** Light/dark switch (next-themes). `onToggle` replaces setTheme, to save the choice to the account. */
1
+ /** Light/dark switch (next-themes). The theme applies at once; `onToggle` then runs, to save the choice to the account. */
2
2
  export declare function ThemeToggle({ onToggle }: {
3
3
  onToggle?: (theme: "light" | "dark") => void;
4
4
  }): import("react").JSX.Element;
@@ -4,7 +4,7 @@ import { useEffect, useState } from "react";
4
4
  import { useTheme } from "next-themes";
5
5
  import { Moon, Sun } from "lucide-react";
6
6
  import { useFamilyLabels } from "./labels.js";
7
- /** Light/dark switch (next-themes). `onToggle` replaces setTheme, to save the choice to the account. */
7
+ /** Light/dark switch (next-themes). The theme applies at once; `onToggle` then runs, to save the choice to the account. */
8
8
  export function ThemeToggle({ onToggle }) {
9
9
  const labels = useFamilyLabels();
10
10
  const { resolvedTheme, setTheme } = useTheme();
@@ -13,8 +13,5 @@ export function ThemeToggle({ onToggle }) {
13
13
  useEffect(() => setMounted(true), []);
14
14
  const isDark = mounted && resolvedTheme === "dark";
15
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 }) }));
16
+ return (_jsx("button", { type: "button", "aria-label": label, title: label, onClick: () => { const next = isDark ? "light" : "dark"; setTheme(next); onToggle?.(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
17
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raulaguila/maat-ui",
3
- "version": "0.6.1",
3
+ "version": "0.8.0",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org",
6
6
  "access": "public"
package/styles.css CHANGED
@@ -431,6 +431,33 @@ html[data-density="compact"] {
431
431
  [data-ui-app-header] { height: 56px; padding-inline: 0; margin-bottom: 8px; }
432
432
  }
433
433
 
434
+ /* The native input state also covers values restored before hydration. */
435
+ [data-ui-floating-control] { position: relative; min-width: 0 }
436
+ [data-ui-floating-control] > label {
437
+ position: absolute;
438
+ z-index: 1;
439
+ inset-inline-start: .5rem;
440
+ top: 0;
441
+ transform: translateY(-50%);
442
+ padding-inline: .25rem;
443
+ max-width: calc(100% - 3.5rem);
444
+ background: var(--floating-label-surface, var(--card));
445
+ color: var(--muted-foreground);
446
+ font-size: .75rem;
447
+ line-height: 1rem;
448
+ }
449
+ [data-ui-floating-control]:not(:focus-within):has(input:placeholder-shown):not(:has(input:is(:autofill, :-webkit-autofill))) > label {
450
+ top: 50%;
451
+ background: transparent;
452
+ font-size: 1rem;
453
+ cursor: text;
454
+ }
455
+ [data-ui-floating-control]:focus-within > label { color: var(--primary) }
456
+ [data-ui-floating-control]:has(input[aria-invalid=true]) > label { color: var(--destructive) }
457
+ .dark [data-ui-auth-card] { --floating-label-surface: var(--background) }
458
+ @media (prefers-reduced-motion: no-preference) {
459
+ [data-ui-floating-control] > label { transition: top 140ms ease-out, font-size 140ms ease-out }
460
+ }
434
461
  /* Sign-in, sign-up and recovery screens (AuthLayout, AuthCard). */
435
462
  [data-ui-auth-layout] {
436
463
  display: flex;