@majapisoftwares/ui 6.6.0 → 6.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/AGENTS.md +2 -1
- package/docs/STANDARDS.md +17 -6
- package/package.json +6 -2
- package/scripts/check-standards.mjs +2 -2
- package/src/components/ui/code-block.tsx +246 -0
- package/src/components/ui/marker.tsx +72 -0
- package/src/components/ui/message-scroller.tsx +1 -1
- package/src/components/ui/snackbar.tsx +22 -70
- package/src/components/ui/sonner.tsx +36 -3
- package/src/components/ui/toast.tsx +250 -0
- package/src/hooks/use-highlighted-code.ts +77 -0
- package/src/lib/highlighter.tsx +124 -0
- package/src/lib/i18n.tsx +81 -0
- package/src/lib/utils.ts +16 -0
- package/src/patterns/chat-checkpoint.tsx +49 -0
- package/src/patterns/chat-citation.tsx +57 -0
- package/src/patterns/chat-context.tsx +82 -0
- package/src/patterns/chat-trace.tsx +739 -9
- package/src/patterns/chat.tsx +119 -4
- package/src/patterns/file-tree.tsx +122 -0
- package/src/patterns/model-selector.tsx +153 -0
- package/src/patterns/preferences.tsx +2 -2
- package/src/patterns/prompt-input.tsx +18 -0
package/AGENTS.md
CHANGED
|
@@ -23,5 +23,6 @@
|
|
|
23
23
|
- className nos apps é para layout. Mudanças visuais precisam de tokens, variantes ou padrões oficiais. Evite controles HTML crus quando houver um componente da biblioteca.
|
|
24
24
|
- Todos os fluxos devem incluir estados carregando, vazio, erro, parcial e indisponível quando aplicáveis. Não esconda falhas ou altere dados para o exemplo parecer funcionar.
|
|
25
25
|
- Preserve acessibilidade: nome acessível, foco visível, navegação por teclado, título e descrição de overlays, labels em campos, e texto junto aos estados.
|
|
26
|
-
- Antes de
|
|
26
|
+
- Antes de cada push, rode `npm run verify`: tudo o que o CI checa, na mesma ordem e com o ambiente do CI. Corrija as falhas aqui; não use o CI para descobrir falhas. O CI só roda `npm run verify` (depois de instalar e preparar o ambiente) e roda uma vez por mudança: no pull request, e no push só na main. Checagem nova (testes, e2e) entra em `scripts/verify.mjs`, nunca só no workflow.
|
|
27
|
+
- Antes de publicar também: git diff --check e revisão visual em desktop/mobile. Teste comportamentos novos de risco, sem testes que apenas espelhem markup.
|
|
27
28
|
- Publique código e evidências no GitHub e vincule os commits ao PLAN.md central. Registre breaking changes e migração antes de atualizar consumidores.
|
package/docs/STANDARDS.md
CHANGED
|
@@ -8,11 +8,21 @@ Base atual: shadcn base-luma com @base-ui/react. Os componentes interativos exp
|
|
|
8
8
|
|
|
9
9
|
TypeScript em modo strict, React com componentes funcionais e composição. APIs genéricas tipadas; sem any para contornar contratos, estado derivado duplicado ou dependências de domínio na UI. Imports públicos por subpath, internos relativos. Dependências e lockfile versionados. Interface, acesso a dados, autorização e operações de infraestrutura permanecem separados. Entradas externas são validadas no servidor; erros e resultados incompletos são explícitos.
|
|
10
10
|
|
|
11
|
+
## Verificação antes do push
|
|
12
|
+
|
|
13
|
+
Cada repositório tem `npm run verify` (`scripts/verify.mjs`): tudo o que o CI checa, na mesma ordem e com o ambiente do CI, parando na primeira falha. O CI só instala, prepara o ambiente (banco, navegador, preview) e roda `npm run verify`, uma vez por mudança: no pull request, e no push só na `main`. Rode-o antes de cada push e corrija aqui; o CI confirma, não descobre falhas. Checagem nova entra no script, nunca só no workflow, e o ambiente que ela precisa no CI também vale ao rodar localmente. Apps novos já vêm assim do starter.
|
|
14
|
+
|
|
15
|
+
O CI é rápido:
|
|
16
|
+
|
|
17
|
+
- **Jobs em paralelo:** quando um passo demora (e2e), o CI divide `npm run verify` em jobs paralelos, cada um com seus passos (`npm run verify test:e2e`, `npm run verify lint typecheck test build`), em vez de um job em sequência.
|
|
18
|
+
- **Caches de compilação do Next.js:** o Turbopack guarda o que compila. O CI mantém `.next/cache` (build) e `.next/dev/cache` (servidor de desenvolvimento do e2e) entre execuções, com `actions/cache/restore` em todo job e `actions/cache/save` só na `main`. As chaves são `next-build-<hash do package-lock.json>-<sha>` e `next-dev-…`. Assim, pull requests partem do cache da `main` sem gastar tempo enviando um novo.
|
|
19
|
+
- O deploy ([majapisoftwares/ci](https://github.com/majapisoftwares/ci)) restaura o mesmo `next-build-` antes de compilar.
|
|
20
|
+
|
|
11
21
|
## Base visual
|
|
12
22
|
|
|
13
23
|
`src/styles.css` é a fonte dos tokens de cor, tipografia, raio, bordas, foco, estados e estrutura. Preset base-luma do shadcn (o mesmo da home de ui.shadcn.com: cantos bem arredondados, campos com fundo suave, sombras leves) sobre o tema neutral, fonte Geist, foco visível e espaço consistente. Cores são semânticas: background, foreground, primary, muted, destructive, success e warning. Temas claro/escuro preservam a semântica. Tokens e padrões podem evoluir nesta biblioteca, nunca por overrides locais em um produto.
|
|
14
24
|
|
|
15
|
-
Primitivos shadcn ficam em src/components/ui (Button, Badge, Card, Input, Table, Sheet, Sidebar, Tooltip, DropdownMenu, ContextMenu, Breadcrumb, Avatar, Checkbox, Collapsible, Alert, Empty, Select, Separator, Skeleton, Tabs, Field e Label).
|
|
25
|
+
Primitivos shadcn ficam em src/components/ui (Button, Badge, Card, Input, Table, Sheet, Sidebar, Tooltip, DropdownMenu, ContextMenu, Breadcrumb, Avatar, Checkbox, Collapsible, Alert, Empty, Select, Separator, Skeleton, Tabs, Field e Label). Toast (com `toast` e `toastError`) é a notificação. Padrões compostos: AppShell (slots `sidebarHeader` e `footer`), WorkspaceSwitcher, UserMenu, PageHeader, MetricStrip, StatusBadge, DataTable, DetailsSheet, DetailList, Preferences, PreferenceControls e MajapiLogo. Templates React: AdminDashboard, AuthLayout, LoginForm e SignupForm. Marca, navegação, textos, dados, ações e slots são configuráveis. Todos os apps atuais e futuros devem consumir esta base pública; ela não conhece AWS ou outro domínio.
|
|
16
26
|
|
|
17
27
|
## Comportamentos de UX
|
|
18
28
|
|
|
@@ -25,7 +35,7 @@ DataTable mantém os resets de paginação fora da avaliação de row models dur
|
|
|
25
35
|
- Não repetir o que já está na tela: o breadcrumb nomeia a página, então ela não ganha um título `PageHeader` com o mesmo nome. Na sidebar, o grupo abre a página principal da ferramenta, que não aparece de novo como subitem. O mesmo vale para títulos de diálogo, rótulos e descrições que repetem um texto visível.
|
|
26
36
|
- Rótulos curtos, em uma linha: botões, itens de menu, abas e badges não quebram linha. Menus se ajustam à largura do conteúdo (não à do botão que os abre); se o texto não couber, encurte-o.
|
|
27
37
|
- Estados com texto e cor: sucesso, aviso, erro e desconhecido. Nunca traduzir ausência de informação em zero ou sucesso.
|
|
28
|
-
- Notificações usam
|
|
38
|
+
- Notificações usam o toast do shadcn (`components/toast`, sobre o Toast do Base UI), para informação e para erro: `toast.add({ description })` (ou `title` e `description`, `type` success/info/warning/loading) e `toastError(erro)` para falhas (tipo error, prioridade alta), com no máximo uma ação curta em `actionProps` (Desfazer, Tentar de novo). Preferences monta o `Toaster`. Falhas de ações (salvar, enviar, criar) vão para `toastError`, não para texto dentro do formulário ou do diálogo; o diálogo continua aberto para a pessoa corrigir e tentar de novo. Só a validação de um campo fica junto do campo (FieldError). `toast`/`Toaster` de `components/sonner` e `snackbar` de `components/snackbar` estão obsoletos e já aparecem como esse toast.
|
|
29
39
|
- Carregamento usa Skeleton, vazio usa Empty, falhas usam Alert e detalhes usam DetailsSheet com título, descrição, foco preso ao overlay, Escape e devolução do foco ao fechar.
|
|
30
40
|
- Em telas pequenas, controles têm texto de pelo menos 16px e alvo de 44px, navegação se reorganiza e tabelas têm rolagem interna, sem rolagem horizontal da página.
|
|
31
41
|
- Preferência por movimento reduzido é respeitada. A ordem de leitura deve acompanhar a ordem visual. Ícones sozinhos exigem nome acessível.
|
|
@@ -49,15 +59,16 @@ AGENTS.md nos apps exige contribuição upstream antes de uso. O verificador est
|
|
|
49
59
|
|
|
50
60
|
## Chat com agentes
|
|
51
61
|
|
|
52
|
-
Base do shadcn AI Elements (Base UI) instalada pelo CLI: `message-scroller` (`@shadcn/react`), `message`, `bubble`, `attachment`, `trace` e `
|
|
62
|
+
Base do shadcn AI Elements (Base UI) instalada pelo CLI: `message-scroller` (`@shadcn/react`; adaptação: o viewport usa `scroll-fade-y`, não só `scroll-fade-b`, para a transcrição não cortar seco no topo), `message`, `bubble`, `attachment`, `trace`, `item`, `code-block` (com `hooks/use-highlighted-code` e o Shiki carregado por linguagem sob demanda) e `marker`. A biblioteca cobre todos os 21 AI Elements (Base UI); cada receita do upstream vira um padrão com props de dados, do jeito que a página dela monta os primitivos. Padrões compostos, unindo o upstream ao chat da Numa:
|
|
53
63
|
|
|
54
|
-
- `patterns/chat`: `Chat` (layout em `AppShell fillHeight`), `ChatMessages` (Message Scroller com `autoScroll` e `defaultScrollPosition="last-anchor"`; cada linha em `MessageScrollerItem`, turnos da pessoa com `scrollAnchor`), `ChatComposer` (alinhado à transcrição mesmo com a calha da barra de rolagem, como na Numa), `ChatMessage` (pessoa em Bubble `muted` no fim; agente sem caixa), `MessageActions`/`MessageAction`/`CopyMessageAction` (ícones com tooltip; feedback com `aria-pressed`), `TypingIndicator` (Orb com texto) e `Suggestions`.
|
|
64
|
+
- `patterns/chat`: `Chat` (layout em `AppShell fillHeight`), `ChatMessages` (Message Scroller com `autoScroll` e `defaultScrollPosition="last-anchor"`; cada linha em `MessageScrollerItem`, turnos da pessoa com `scrollAnchor`), `ChatComposer` (alinhado à transcrição mesmo com a calha da barra de rolagem, como na Numa), `ChatMessage` (pessoa em Bubble `muted` no fim; agente sem caixa; o rodapé de ações e hora aparece no hover/foco, sempre visível no toque), `MessageActions`/`MessageAction`/`CopyMessageAction`/`ReplyMessageAction` (ícones com tooltip; feedback com `aria-pressed`), `ChatQuote` (resposta a uma mensagem, como nos apps de mensagem: autor e início do texto; em `ChatMessage quote` com `messageId` rola até a original, em `PromptInput quote` com `onDismiss` cancela; o campo ganha foco quando a citação aparece ou muda de `key`), `TypingIndicator` (Orb com texto) e `Suggestions`.
|
|
55
65
|
- `patterns/prompt-input`: InputGroup com Enter envia e Shift+Enter quebra linha (respeitando IME), anexar/colar/soltar arquivos com Attachment, foco preservado ao enviar, botão Parar durante `submitted`/`streaming` e rascunho restaurado quando o envio rejeita (Numa). Com `sendWhileBusy`, a pessoa envia enquanto o agente trabalha (direcionar uma execução, como no Workbench e na Numa): com texto o botão envia, com o campo vazio ele para.
|
|
56
|
-
- `patterns/chat-trace`: `ChatTrace`, `Reasoning` (abre enquanto pensa, fecha ao terminar salvo se a pessoa alternou; vários passos são várias linhas), `Tool` (estados pending/running/done/error/denied, saída sob demanda
|
|
66
|
+
- `patterns/chat-trace`: `ChatTrace`, `Reasoning` (abre enquanto pensa, fecha ao terminar salvo se a pessoa alternou; vários passos são várias linhas), `Tool` (estados pending/running/done/error/denied, saída sob demanda num `CodeBlock` pequeno), `Confirmation` (Aprovar/Negar; depois de respondida vira `Tool`), `Step` (uma ação do agente; abre para a saída ou para os resultados de busca em `badges`; `render` vira link), `ChainOfThought` (resumo "Pesquisou em N passos" que abre para os `Step`s, aberto enquanto roda), `Plan` (passos decididos antes, com "N de M feitos"), `Queue` (a fazer aberto, concluídos fechados), `Task` (passos que surgem do trabalho; aberta enquanto roda), `Sources` (links usados, fechado), `Subagent` (execução delegada: tarefa, modelo e ferramentas como Badge, chamadas e resultado), `Terminal` (comando e saída; abre quando chega saída, código diferente de 0 é erro), `TestResults` (contagens, suítes por arquivo, falhas abrem o erro) e `StackTrace` (`parseStack`; seus quadros primeiro, os do framework dobrados).
|
|
67
|
+
- `patterns/chat-citation` `InlineCitation` (hostname no meio do texto, hover com título e link), `patterns/chat-context` `ContextUsage` (porcentagem do contexto com contagens no hover, para as `actions` do PromptInput), `patterns/model-selector` `ModelSelector`/`EffortSelector` (menus de modelo por provedor e de esforço, nas `actions`), `patterns/chat-checkpoint` `Checkpoint` (separador com Restaurar) e `patterns/file-tree` `FileTree`/`fileTree` (pastas que abrem e arquivos a escolher, montados de caminhos).
|
|
57
68
|
- `patterns/chat-markdown`: `ChatMarkdown` com Streamdown (sanitiza a saída do modelo, completa markdown incompleto durante o streaming e traduz os controles). Substitui o react-markdown da Numa.
|
|
58
69
|
- `hooks/use-streamed-text`: revela progressivamente uma resposta que chega inteira (Numa), respeitando movimento reduzido.
|
|
59
70
|
|
|
60
|
-
Erros de resposta aparecem na própria mensagem (Bubble `destructive`) com Tentar novamente; erros de ações fora da conversa vão para o
|
|
71
|
+
Erros de resposta aparecem na própria mensagem (Bubble `destructive`) com Tentar novamente; erros de ações fora da conversa vão para o toast (`toastError`). O catálogo demonstra em `/chat` (conversa com raciocínio, ferramentas, aprovação, erro e retry) e `/chat/new` (vazio com sugestões); `/chat/elements` mostra cada AI Element.
|
|
61
72
|
|
|
62
73
|
Adaptações: `MessageScrollerItem` usa `-m-2 p-2` (e `MessageScrollerContent`, `p-2`) porque `content-visibility: auto` sempre aplica contenção de pintura e cortava sombras e anéis de foco na borda de cada linha; não remova essa margem nem coloque itens em contêineres sem o padding correspondente. `message-scroller` também traduz o nome da região e do botão, troca utilitários de barra de rolagem que não existem aqui por `[scrollbar-gutter:stable]` e exporta `useMessageScrollerGutterWidth`; `attachment` usa `no-scrollbar`. `styles.css` importa `streamdown/styles.css` e adiciona o `@source` do Streamdown. `hast-util-raw` 9.2 exige `parse5` 8.1+; mantenha o lockfile sem `parse5` 8.0.
|
|
63
74
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@majapisoftwares/ui",
|
|
3
|
-
"version": "6.
|
|
3
|
+
"version": "6.8.0",
|
|
4
4
|
"description": "Shared Majapi UI and UX standards based on shadcn/ui",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -42,7 +42,10 @@
|
|
|
42
42
|
"check:standards": "node scripts/check-standards.mjs",
|
|
43
43
|
"normalize:ui": "node scripts/normalize-ui.mjs && prettier --write src/components/ui src/hooks",
|
|
44
44
|
"test:preferences": "tsx --test scripts/preferences.test.tsx",
|
|
45
|
-
"test:data-table": "tsx --test scripts/data-table.test.tsx"
|
|
45
|
+
"test:data-table": "tsx --test scripts/data-table.test.tsx",
|
|
46
|
+
"test:chat-quote": "tsx --test scripts/chat-quote.test.tsx",
|
|
47
|
+
"test:ai-elements": "tsx --test scripts/ai-elements.test.tsx",
|
|
48
|
+
"verify": "node scripts/verify.mjs"
|
|
46
49
|
},
|
|
47
50
|
"peerDependencies": {
|
|
48
51
|
"react": "19.3.1",
|
|
@@ -65,6 +68,7 @@
|
|
|
65
68
|
"cn": "^0.5.0",
|
|
66
69
|
"lucide-react": "1.61.0",
|
|
67
70
|
"shadcn": "^4.22.1",
|
|
71
|
+
"shiki": "^4.6.0",
|
|
68
72
|
"sonner": "^2.0.8",
|
|
69
73
|
"streamdown": "2.7.1",
|
|
70
74
|
"tailwind-merge": "3.7.0",
|
|
@@ -29,8 +29,8 @@ async function visit(path) {
|
|
|
29
29
|
)
|
|
30
30
|
)
|
|
31
31
|
violations.push(`${name}: use semantic tokens instead of local colors`);
|
|
32
|
-
if (consumer && /from\s+["'](?:sonner|@majapisoftwares\/ui\/components\/sonner)["']/.test(text))
|
|
33
|
-
violations.push(`${name}: notify with
|
|
32
|
+
if (consumer && /from\s+["'](?:sonner|@majapisoftwares\/ui\/components\/(?:sonner|snackbar))["']/.test(text))
|
|
33
|
+
violations.push(`${name}: notify with toast from @majapisoftwares/ui/components/toast`);
|
|
34
34
|
if (!consumer && /from ["']@\//.test(text))
|
|
35
35
|
violations.push(`${name}: library internals must use portable imports`);
|
|
36
36
|
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
import * as React from "react";
|
|
4
|
+
import { cva, type VariantProps } from "class-variance-authority";
|
|
5
|
+
import { cn } from "cn";
|
|
6
|
+
|
|
7
|
+
import { Button } from "./button";
|
|
8
|
+
import { CheckIcon, CopyIcon } from "lucide-react";
|
|
9
|
+
|
|
10
|
+
const codeBlockVariants = cva(
|
|
11
|
+
"group/code-block relative flex w-full min-w-0 flex-col overflow-hidden rounded-2xl text-sm has-[>[data-slot=code-block-content]:focus-visible]:ring-3 has-[>[data-slot=code-block-content]:focus-visible]:ring-ring/30 data-[size=sm]:rounded-xl data-[size=sm]:text-xs",
|
|
12
|
+
{
|
|
13
|
+
variants: {
|
|
14
|
+
variant: {
|
|
15
|
+
default:
|
|
16
|
+
"bg-muted text-foreground ring-1 ring-foreground/5 dark:ring-foreground/10",
|
|
17
|
+
destructive:
|
|
18
|
+
"bg-destructive/5 text-destructive ring-1 ring-destructive/15 dark:bg-destructive/10 dark:ring-destructive/20",
|
|
19
|
+
},
|
|
20
|
+
},
|
|
21
|
+
defaultVariants: {
|
|
22
|
+
variant: "default",
|
|
23
|
+
},
|
|
24
|
+
},
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
function CodeBlock({
|
|
28
|
+
className,
|
|
29
|
+
variant = "default",
|
|
30
|
+
size = "default",
|
|
31
|
+
...props
|
|
32
|
+
}: React.ComponentProps<"div"> &
|
|
33
|
+
VariantProps<typeof codeBlockVariants> & { size?: "default" | "sm" }) {
|
|
34
|
+
return (
|
|
35
|
+
<div
|
|
36
|
+
data-slot="code-block"
|
|
37
|
+
data-variant={variant}
|
|
38
|
+
data-size={size}
|
|
39
|
+
className={cn(codeBlockVariants({ variant }), className)}
|
|
40
|
+
{...props}
|
|
41
|
+
/>
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function CodeBlockHeader({ className, ...props }: React.ComponentProps<"div">) {
|
|
46
|
+
return (
|
|
47
|
+
<div
|
|
48
|
+
data-slot="code-block-header"
|
|
49
|
+
className={cn(
|
|
50
|
+
"flex min-w-0 shrink-0 items-center gap-2 px-5 pt-5 text-muted-foreground group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:pt-3 group-data-[variant=destructive]/code-block:text-destructive *:has-[>[data-slot=code-block-title]]:min-w-0",
|
|
51
|
+
className,
|
|
52
|
+
)}
|
|
53
|
+
{...props}
|
|
54
|
+
/>
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function CodeBlockTitle({ className, ...props }: React.ComponentProps<"div">) {
|
|
59
|
+
return (
|
|
60
|
+
<div
|
|
61
|
+
data-slot="code-block-title"
|
|
62
|
+
className={cn(
|
|
63
|
+
"min-w-0 truncate font-sans text-sm font-medium text-foreground group-data-[size=sm]/code-block:text-xs group-data-[variant=destructive]/code-block:text-destructive [&_svg]:pointer-events-none [&_svg]:inline-block [&_svg]:align-middle [&_svg:not([class*='size-'])]:size-4 group-data-[size=sm]/code-block:[&_svg:not([class*='size-'])]:size-3.5 *:[svg]:me-1.5",
|
|
64
|
+
className,
|
|
65
|
+
)}
|
|
66
|
+
{...props}
|
|
67
|
+
/>
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function CodeBlockActions({
|
|
72
|
+
className,
|
|
73
|
+
...props
|
|
74
|
+
}: React.ComponentProps<"div">) {
|
|
75
|
+
return (
|
|
76
|
+
<div
|
|
77
|
+
data-slot="code-block-actions"
|
|
78
|
+
className={cn(
|
|
79
|
+
"-my-1 ms-auto -me-1.5 flex shrink-0 items-center gap-1 *:data-[slot=button]:hover:bg-foreground/5 dark:*:data-[slot=button]:hover:bg-foreground/10 [[data-slot=code-block]>&]:absolute [[data-slot=code-block]>&]:end-4 [[data-slot=code-block]>&]:top-4 [[data-slot=code-block]>&]:z-10 [[data-slot=code-block]>&]:m-0 [[data-slot=code-block]>&]:opacity-0 [[data-slot=code-block]>&]:transition-opacity [[data-slot=code-block]>&]:group-focus-within/code-block:opacity-100 [[data-slot=code-block]>&]:group-hover/code-block:opacity-100 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:end-2 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:top-2 [[data-slot=code-block]>&]:pointer-coarse:opacity-100 [[data-slot=code-block]>&]:*:[button]:bg-background [[data-slot=code-block]>&]:*:[button]:ring-1 [[data-slot=code-block]>&]:*:[button]:ring-foreground/10",
|
|
80
|
+
className,
|
|
81
|
+
)}
|
|
82
|
+
{...props}
|
|
83
|
+
/>
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function CodeBlockCopyButton({
|
|
88
|
+
value,
|
|
89
|
+
variant = "ghost",
|
|
90
|
+
size = "icon-xs",
|
|
91
|
+
className,
|
|
92
|
+
onClick,
|
|
93
|
+
...props
|
|
94
|
+
}: React.ComponentProps<typeof Button> & { value: string }) {
|
|
95
|
+
const [copied, setCopied] = React.useState(false);
|
|
96
|
+
|
|
97
|
+
React.useEffect(() => {
|
|
98
|
+
if (!copied) {
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const timeout = setTimeout(() => setCopied(false), 2000);
|
|
103
|
+
return () => clearTimeout(timeout);
|
|
104
|
+
}, [copied]);
|
|
105
|
+
|
|
106
|
+
return (
|
|
107
|
+
<>
|
|
108
|
+
<Button
|
|
109
|
+
data-slot="code-block-copy-button"
|
|
110
|
+
data-copied={copied || undefined}
|
|
111
|
+
variant={variant}
|
|
112
|
+
size={size}
|
|
113
|
+
aria-label={copied ? "Copied" : "Copy"}
|
|
114
|
+
className={cn(
|
|
115
|
+
"hover:bg-foreground/5 dark:hover:bg-foreground/10",
|
|
116
|
+
className,
|
|
117
|
+
)}
|
|
118
|
+
onClick={(event) => {
|
|
119
|
+
onClick?.(event);
|
|
120
|
+
navigator.clipboard
|
|
121
|
+
.writeText(value)
|
|
122
|
+
.then(() => setCopied(true))
|
|
123
|
+
.catch(() => {});
|
|
124
|
+
}}
|
|
125
|
+
{...props}
|
|
126
|
+
>
|
|
127
|
+
{copied ? <CheckIcon /> : <CopyIcon />}
|
|
128
|
+
</Button>
|
|
129
|
+
<span aria-live="polite" className="sr-only">
|
|
130
|
+
{copied ? "Copied" : ""}
|
|
131
|
+
</span>
|
|
132
|
+
</>
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function CodeBlockContent({
|
|
137
|
+
className,
|
|
138
|
+
children,
|
|
139
|
+
style,
|
|
140
|
+
wrap = false,
|
|
141
|
+
lineNumbers = false,
|
|
142
|
+
startLine = 1,
|
|
143
|
+
...props
|
|
144
|
+
}: React.ComponentProps<"pre"> & {
|
|
145
|
+
wrap?: boolean;
|
|
146
|
+
lineNumbers?: boolean;
|
|
147
|
+
startLine?: number;
|
|
148
|
+
}) {
|
|
149
|
+
return (
|
|
150
|
+
<pre
|
|
151
|
+
data-slot="code-block-content"
|
|
152
|
+
data-wrap={wrap || undefined}
|
|
153
|
+
data-numbered={lineNumbers || undefined}
|
|
154
|
+
dir="ltr"
|
|
155
|
+
tabIndex={0}
|
|
156
|
+
style={{ counterReset: `line ${startLine - 1}`, ...style }}
|
|
157
|
+
className={cn(
|
|
158
|
+
"min-h-0 min-w-0 scroll-fade-x scrollbar-thin overflow-auto px-5 py-5 text-start font-mono leading-relaxed outline-none group-has-data-[slot=code-block-footer]/code-block:pb-2 group-has-data-[slot=code-block-header]/code-block:pt-2 group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:py-3 group-data-[size=sm]/code-block:group-has-data-[slot=code-block-header]/code-block:pt-1.5 data-wrap:scroll-fade-y data-wrap:wrap-break-word data-wrap:whitespace-pre-wrap",
|
|
159
|
+
className,
|
|
160
|
+
)}
|
|
161
|
+
{...props}
|
|
162
|
+
>
|
|
163
|
+
<code
|
|
164
|
+
data-slot="code-block-code"
|
|
165
|
+
className="grid min-h-lh min-w-max content-start in-data-numbered:grid-cols-[auto_1fr] in-data-wrap:min-w-0"
|
|
166
|
+
>
|
|
167
|
+
{lineNumbers && typeof children === "string"
|
|
168
|
+
? children
|
|
169
|
+
.replace(/\n$/, "")
|
|
170
|
+
.split("\n")
|
|
171
|
+
.map((line, index) => (
|
|
172
|
+
<CodeBlockLine key={index}>{line}</CodeBlockLine>
|
|
173
|
+
))
|
|
174
|
+
: children}
|
|
175
|
+
</code>
|
|
176
|
+
</pre>
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const codeBlockLineVariants = cva(
|
|
181
|
+
"relative -mx-5 block min-h-lh px-5 group-data-[size=sm]/code-block:-mx-3 group-data-[size=sm]/code-block:px-3 before:min-w-6 before:text-end before:text-muted-foreground after:absolute after:start-1 after:top-0 after:text-muted-foreground after:select-none in-data-numbered:col-span-2 in-data-numbered:grid in-data-numbered:grid-cols-subgrid in-data-numbered:gap-x-3 in-data-numbered:[counter-increment:line] in-data-numbered:before:content-[counter(line)] in-data-numbered:before:select-none in-data-numbered:supports-[content:counter(line)_/_'']:before:content-[counter(line)_/_'']",
|
|
182
|
+
{
|
|
183
|
+
variants: {
|
|
184
|
+
variant: {
|
|
185
|
+
default: "",
|
|
186
|
+
added: "bg-foreground/5 after:content-['+']",
|
|
187
|
+
removed: "bg-destructive/10 after:text-destructive after:content-['−']",
|
|
188
|
+
highlighted: "bg-foreground/5",
|
|
189
|
+
},
|
|
190
|
+
},
|
|
191
|
+
defaultVariants: {
|
|
192
|
+
variant: "default",
|
|
193
|
+
},
|
|
194
|
+
},
|
|
195
|
+
);
|
|
196
|
+
|
|
197
|
+
function CodeBlockLine({
|
|
198
|
+
className,
|
|
199
|
+
variant = "default",
|
|
200
|
+
children,
|
|
201
|
+
...props
|
|
202
|
+
}: React.ComponentProps<"span"> & VariantProps<typeof codeBlockLineVariants>) {
|
|
203
|
+
// An empty line holds a newline so copying a selection keeps blank lines.
|
|
204
|
+
const empty =
|
|
205
|
+
children === undefined ||
|
|
206
|
+
children === null ||
|
|
207
|
+
children === "" ||
|
|
208
|
+
(Array.isArray(children) && children.length === 0);
|
|
209
|
+
|
|
210
|
+
return (
|
|
211
|
+
<span
|
|
212
|
+
data-slot="code-block-line"
|
|
213
|
+
data-variant={variant}
|
|
214
|
+
className={cn(codeBlockLineVariants({ variant }), className)}
|
|
215
|
+
{...props}
|
|
216
|
+
>
|
|
217
|
+
<span data-slot="code-block-line-content" className="min-w-0">
|
|
218
|
+
{empty ? "\n" : children}
|
|
219
|
+
</span>
|
|
220
|
+
</span>
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function CodeBlockFooter({ className, ...props }: React.ComponentProps<"div">) {
|
|
225
|
+
return (
|
|
226
|
+
<div
|
|
227
|
+
data-slot="code-block-footer"
|
|
228
|
+
className={cn(
|
|
229
|
+
"flex min-w-0 shrink-0 items-center gap-2 px-5 pb-5 text-muted-foreground group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:pb-3",
|
|
230
|
+
className,
|
|
231
|
+
)}
|
|
232
|
+
{...props}
|
|
233
|
+
/>
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export {
|
|
238
|
+
CodeBlock,
|
|
239
|
+
CodeBlockHeader,
|
|
240
|
+
CodeBlockTitle,
|
|
241
|
+
CodeBlockActions,
|
|
242
|
+
CodeBlockCopyButton,
|
|
243
|
+
CodeBlockContent,
|
|
244
|
+
CodeBlockLine,
|
|
245
|
+
CodeBlockFooter,
|
|
246
|
+
};
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
import * as React from "react";
|
|
4
|
+
import { mergeProps } from "@base-ui/react/merge-props";
|
|
5
|
+
import { useRender } from "@base-ui/react/use-render";
|
|
6
|
+
import { cva, type VariantProps } from "class-variance-authority";
|
|
7
|
+
import { cn } from "cn";
|
|
8
|
+
|
|
9
|
+
const markerVariants = cva(
|
|
10
|
+
"group/marker relative flex min-h-4 w-full items-center gap-2 text-left text-sm text-muted-foreground [&_svg:not([class*='size-'])]:size-4 [a]:underline [a]:underline-offset-3 [a]:hover:text-foreground",
|
|
11
|
+
{
|
|
12
|
+
variants: {
|
|
13
|
+
variant: {
|
|
14
|
+
default: "",
|
|
15
|
+
separator:
|
|
16
|
+
"before:mr-1 before:h-px before:min-w-0 before:flex-1 before:bg-border after:ml-1 after:h-px after:min-w-0 after:flex-1 after:bg-border",
|
|
17
|
+
border: "border-b border-border pb-2",
|
|
18
|
+
},
|
|
19
|
+
},
|
|
20
|
+
},
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
function Marker({
|
|
24
|
+
className,
|
|
25
|
+
variant = "default",
|
|
26
|
+
render,
|
|
27
|
+
...props
|
|
28
|
+
}: useRender.ComponentProps<"div"> & VariantProps<typeof markerVariants>) {
|
|
29
|
+
return useRender({
|
|
30
|
+
defaultTagName: "div",
|
|
31
|
+
props: mergeProps<"div">(
|
|
32
|
+
{
|
|
33
|
+
className: cn(markerVariants({ variant, className })),
|
|
34
|
+
},
|
|
35
|
+
props,
|
|
36
|
+
),
|
|
37
|
+
render,
|
|
38
|
+
state: {
|
|
39
|
+
slot: "marker",
|
|
40
|
+
variant,
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function MarkerIcon({ className, ...props }: React.ComponentProps<"span">) {
|
|
46
|
+
return (
|
|
47
|
+
<span
|
|
48
|
+
data-slot="marker-icon"
|
|
49
|
+
aria-hidden="true"
|
|
50
|
+
className={cn(
|
|
51
|
+
"size-4 shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
52
|
+
className,
|
|
53
|
+
)}
|
|
54
|
+
{...props}
|
|
55
|
+
/>
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function MarkerContent({ className, ...props }: React.ComponentProps<"span">) {
|
|
60
|
+
return (
|
|
61
|
+
<span
|
|
62
|
+
data-slot="marker-content"
|
|
63
|
+
className={cn(
|
|
64
|
+
"min-w-0 wrap-break-word group-data-[variant=separator]/marker:flex-none group-data-[variant=separator]/marker:text-center *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
|
|
65
|
+
className,
|
|
66
|
+
)}
|
|
67
|
+
{...props}
|
|
68
|
+
/>
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export { Marker, MarkerIcon, MarkerContent, markerVariants };
|
|
@@ -45,7 +45,7 @@ function MessageScrollerViewport({
|
|
|
45
45
|
data-slot="message-scroller-viewport"
|
|
46
46
|
aria-label={messages.messages}
|
|
47
47
|
className={cn(
|
|
48
|
-
"size-full min-h-0 min-w-0 scroll-fade-
|
|
48
|
+
"size-full min-h-0 min-w-0 scroll-fade-y overflow-y-auto overscroll-contain [scrollbar-gutter:stable] contain-content data-autoscrolling:[scrollbar-color:transparent_transparent] data-pending-scroll:invisible",
|
|
49
49
|
className,
|
|
50
50
|
)}
|
|
51
51
|
{...props}
|
|
@@ -1,18 +1,11 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
5
|
-
import { Toaster as Sonner, toast, type ToasterProps } from "sonner";
|
|
6
|
-
import { Orb } from "./orb";
|
|
3
|
+
import type { ReactNode } from "react";
|
|
4
|
+
import { errorMessage, toast, toastError } from "./toast";
|
|
7
5
|
|
|
8
6
|
/**
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* an optional action. Errors stay on screen longer and carry an icon; field
|
|
12
|
-
* validation stays next to its field.
|
|
13
|
-
*
|
|
14
|
-
* Mount `<Snackbar />` once (Preferences does) and call `snackbar(message)`
|
|
15
|
-
* or `snackbar.error(message)` from anywhere on the client.
|
|
7
|
+
* @deprecated Notifications are the shadcn toast: `toast.add({ description })`
|
|
8
|
+
* and `toastError(error)` from `components/toast`. These forward to it.
|
|
16
9
|
*/
|
|
17
10
|
|
|
18
11
|
export interface SnackbarAction {
|
|
@@ -20,81 +13,40 @@ export interface SnackbarAction {
|
|
|
20
13
|
onClick: () => void;
|
|
21
14
|
}
|
|
22
15
|
|
|
16
|
+
/** @deprecated Use `toast.add` options from `components/toast`. */
|
|
23
17
|
export interface SnackbarOptions {
|
|
24
|
-
/** One short action, such as Undo or Retry. */
|
|
25
18
|
action?: SnackbarAction;
|
|
26
|
-
/** Milliseconds on screen; info 4 s and errors 8 s by default. */
|
|
27
19
|
duration?: number;
|
|
28
|
-
/** Replaces the snackbar with the same id instead of queueing another. */
|
|
29
20
|
id?: string | number;
|
|
30
21
|
}
|
|
31
22
|
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
duration: value?.duration ?? duration,
|
|
37
|
-
...(value?.id !== undefined ? { id: value.id } : {}),
|
|
38
|
-
...(value?.action ? { action: { label: value.action.label, onClick: value.action.onClick } } : {}),
|
|
23
|
+
const options = (value: SnackbarOptions | undefined) => ({
|
|
24
|
+
...(value?.duration !== undefined ? { timeout: value.duration } : {}),
|
|
25
|
+
...(value?.id !== undefined ? { id: String(value.id) } : {}),
|
|
26
|
+
...(value?.action ? { actionProps: { children: value.action.label, onClick: value.action.onClick } } : {}),
|
|
39
27
|
});
|
|
40
28
|
|
|
41
|
-
/**
|
|
29
|
+
/** @deprecated Use `toast.add({ description })` from `components/toast`. */
|
|
42
30
|
function show(message: ReactNode, value?: SnackbarOptions) {
|
|
43
|
-
return toast(message, options(value
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** The message of an error or of anything thrown. */
|
|
47
|
-
export function errorMessage(error: unknown): string {
|
|
48
|
-
if (error instanceof Error) return error.message;
|
|
49
|
-
return typeof error === "string" ? error : String(error);
|
|
31
|
+
return toast.add({ description: message, ...options(value) });
|
|
50
32
|
}
|
|
51
33
|
|
|
34
|
+
/** @deprecated Use `toast` and `toastError` from `components/toast`. */
|
|
52
35
|
export const snackbar = Object.assign(show, {
|
|
53
|
-
/**
|
|
36
|
+
/** @deprecated Use `toastError(error)` from `components/toast`. */
|
|
54
37
|
error(message: unknown, value?: SnackbarOptions) {
|
|
55
|
-
|
|
56
|
-
return toast.error(text, options(value, ERROR_MS));
|
|
38
|
+
return value ? toast.add({ type: "error", priority: "high", description: errorMessage(message), ...options(value) }) : toastError(message);
|
|
57
39
|
},
|
|
58
|
-
/**
|
|
40
|
+
/** @deprecated Use `toast.close(id)` from `components/toast`. */
|
|
59
41
|
dismiss(id?: string | number) {
|
|
60
|
-
|
|
42
|
+
toast.close(id === undefined ? undefined : String(id));
|
|
61
43
|
},
|
|
62
44
|
});
|
|
63
45
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
visibleToasts={1}
|
|
71
|
-
offset={24}
|
|
72
|
-
mobileOffset={16}
|
|
73
|
-
className="snackbar group"
|
|
74
|
-
icons={{
|
|
75
|
-
success: null,
|
|
76
|
-
info: null,
|
|
77
|
-
warning: <TriangleAlertIcon className="size-4" />,
|
|
78
|
-
error: <CircleAlertIcon className="size-4 text-destructive" />,
|
|
79
|
-
loading: <Orb size={16} />,
|
|
80
|
-
}}
|
|
81
|
-
style={{ "--width": "min(36rem, calc(100vw - 2rem))" } as CSSProperties}
|
|
82
|
-
toastOptions={{
|
|
83
|
-
unstyled: true,
|
|
84
|
-
classNames: {
|
|
85
|
-
toast:
|
|
86
|
-
"cn-snackbar flex w-(--width) items-center gap-3 rounded-xl bg-foreground px-4 py-3 text-sm text-background shadow-lg data-[type=error]:pr-3",
|
|
87
|
-
content: "min-w-0 flex-1",
|
|
88
|
-
title: "leading-5 break-words",
|
|
89
|
-
description: "text-background/70",
|
|
90
|
-
icon: "flex shrink-0 items-center",
|
|
91
|
-
actionButton:
|
|
92
|
-
"shrink-0 rounded-full px-3 py-1.5 text-sm font-medium text-background underline-offset-4 hover:bg-background/10 focus-visible:outline-2 focus-visible:outline-background",
|
|
93
|
-
cancelButton: "shrink-0 rounded-full px-3 py-1.5 text-sm text-background/70 hover:bg-background/10",
|
|
94
|
-
closeButton: "hidden",
|
|
95
|
-
},
|
|
96
|
-
}}
|
|
97
|
-
{...props}
|
|
98
|
-
/>
|
|
99
|
-
);
|
|
46
|
+
export { errorMessage };
|
|
47
|
+
|
|
48
|
+
/** @deprecated Preferences mounts the toast `Toaster`; this renders nothing. */
|
|
49
|
+
export function Snackbar(props: { theme?: string }) {
|
|
50
|
+
void props;
|
|
51
|
+
return null;
|
|
100
52
|
}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import { Orb } from "./orb";
|
|
4
4
|
import { Toaster as Sonner, type ToasterProps } from "sonner";
|
|
5
|
+
import { toast as manager } from "./toast";
|
|
5
6
|
import {
|
|
6
7
|
CircleCheckIcon,
|
|
7
8
|
InfoIcon,
|
|
@@ -10,7 +11,7 @@ import {
|
|
|
10
11
|
} from "lucide-react";
|
|
11
12
|
|
|
12
13
|
// Theme comes from the caller (Preferences passes the active theme).
|
|
13
|
-
/** @deprecated Notifications are
|
|
14
|
+
/** @deprecated Notifications are the shadcn toast: Preferences mounts its `Toaster` from `components/toast`. */
|
|
14
15
|
const Toaster = ({ theme = "system", ...props }: ToasterProps) => {
|
|
15
16
|
return (
|
|
16
17
|
<Sonner
|
|
@@ -42,5 +43,37 @@ const Toaster = ({ theme = "system", ...props }: ToasterProps) => {
|
|
|
42
43
|
};
|
|
43
44
|
|
|
44
45
|
export { Toaster };
|
|
45
|
-
|
|
46
|
-
|
|
46
|
+
type Message = React.ReactNode;
|
|
47
|
+
interface LegacyOptions {
|
|
48
|
+
description?: React.ReactNode;
|
|
49
|
+
duration?: number;
|
|
50
|
+
id?: string | number;
|
|
51
|
+
action?: { label: React.ReactNode; onClick: () => void };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const legacy = (type: string | undefined, message: Message, options?: LegacyOptions) =>
|
|
55
|
+
manager.add({
|
|
56
|
+
...(type ? { type } : {}),
|
|
57
|
+
...(type === "error" ? { priority: "high" as const } : {}),
|
|
58
|
+
// A message with a description reads as a title over it, as in sonner.
|
|
59
|
+
...(options?.description ? { title: message, description: options.description } : { description: message }),
|
|
60
|
+
...(options?.duration !== undefined ? { timeout: options.duration } : {}),
|
|
61
|
+
...(options?.id !== undefined ? { id: String(options.id) } : {}),
|
|
62
|
+
...(options?.action ? { actionProps: { children: options.action.label, onClick: options.action.onClick } } : {}),
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* @deprecated Use `toast.add(...)` and `toastError(error)` from `components/toast`
|
|
67
|
+
* (the shadcn toast). These calls already show as that toast.
|
|
68
|
+
*/
|
|
69
|
+
const toast = Object.assign((message: Message, options?: LegacyOptions) => legacy(undefined, message, options), {
|
|
70
|
+
message: (message: Message, options?: LegacyOptions) => legacy(undefined, message, options),
|
|
71
|
+
success: (message: Message, options?: LegacyOptions) => legacy("success", message, options),
|
|
72
|
+
info: (message: Message, options?: LegacyOptions) => legacy("info", message, options),
|
|
73
|
+
warning: (message: Message, options?: LegacyOptions) => legacy("warning", message, options),
|
|
74
|
+
error: (message: Message, options?: LegacyOptions) => legacy("error", message, options),
|
|
75
|
+
loading: (message: Message, options?: LegacyOptions) => legacy("loading", message, options),
|
|
76
|
+
dismiss: (id?: string | number) => manager.close(id === undefined ? undefined : String(id)),
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
export { toast };
|