@majapisoftwares/ui 6.7.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 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 publicar: npm run typecheck, npm run lint, npm run check:standards, npm run build, git diff --check e revisão visual em desktop/mobile. Teste comportamentos novos de risco, sem testes que apenas espelhem markup.
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,6 +8,16 @@ 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.
@@ -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 `item`. Padrões compostos, unindo o upstream ao chat da Numa:
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) e `Confirmation` (Aprovar/Negar; depois de respondida vira `Tool`).
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 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).
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.7.0",
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",
@@ -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-b overflow-y-auto overscroll-contain [scrollbar-gutter:stable] contain-content data-autoscrolling:[scrollbar-color:transparent_transparent] data-pending-scroll:invisible",
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}
@@ -0,0 +1,77 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+
5
+ import { loadHighlighter } from "../lib/highlighter";
6
+
7
+ export function useHighlightedCode(value: string, language: string) {
8
+ // A trailing newline would render as an extra empty line.
9
+ const code = value.endsWith("\n") ? value.slice(0, -1) : value;
10
+ const [loaded, setLoaded] = React.useState<{
11
+ language: string;
12
+ highlighter: Awaited<ReturnType<typeof loadHighlighter>>;
13
+ } | null>(null);
14
+ const highlighter = loaded?.language === language ? loaded.highlighter : null;
15
+
16
+ React.useEffect(() => {
17
+ let cancelled = false;
18
+
19
+ loadHighlighter(language)
20
+ .then((next) => {
21
+ if (!cancelled) {
22
+ setLoaded({ language, highlighter: next });
23
+ }
24
+ })
25
+ .catch(() => {});
26
+
27
+ return () => {
28
+ cancelled = true;
29
+ };
30
+ }, [language]);
31
+
32
+ // The complete lines, highlighted. While the code streams, only the new
33
+ // lines are tokenized, starting from the grammar state of the last one.
34
+ const [done, setDone] = React.useState<{
35
+ highlighter: typeof highlighter;
36
+ text: string;
37
+ lines: React.ReactNode[];
38
+ state?: Parameters<NonNullable<typeof highlighter>["highlight"]>[1];
39
+ }>({ highlighter: null, text: "", lines: [] });
40
+
41
+ let next = done;
42
+
43
+ if (next.highlighter !== highlighter || !code.startsWith(next.text)) {
44
+ next = { highlighter, text: "", lines: [] };
45
+ }
46
+
47
+ const end = code.lastIndexOf("\n") + 1;
48
+
49
+ if (highlighter && end > next.text.length) {
50
+ const result = highlighter.highlight(
51
+ code.slice(next.text.length, end - 1),
52
+ next.state,
53
+ );
54
+
55
+ next = {
56
+ highlighter,
57
+ text: code.slice(0, end),
58
+ lines: [...next.lines, ...result.lines],
59
+ state: result.state,
60
+ };
61
+ }
62
+
63
+ if (next !== done) {
64
+ setDone(next);
65
+ }
66
+
67
+ // The last line is still being written, so it is tokenized on every render.
68
+ const tail = code.slice(end);
69
+
70
+ return React.useMemo(() => {
71
+ if (!highlighter) {
72
+ return code.split("\n");
73
+ }
74
+
75
+ return [...next.lines, highlighter.highlight(tail, next.state).lines[0]];
76
+ }, [code, highlighter, next, tail]);
77
+ }
@@ -0,0 +1,124 @@
1
+ import * as React from "react";
2
+ import {
3
+ createHighlighterCore,
4
+ type GrammarState,
5
+ type HighlighterCore,
6
+ } from "shiki/core";
7
+ import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
8
+
9
+ // Add the languages you need. Each one loads the first time it is used.
10
+ const languages = {
11
+ bash: () => import("shiki/langs/shellscript.mjs"),
12
+ css: () => import("shiki/langs/css.mjs"),
13
+ diff: () => import("shiki/langs/diff.mjs"),
14
+ html: () => import("shiki/langs/html.mjs"),
15
+ javascript: () => import("shiki/langs/javascript.mjs"),
16
+ json: () => import("shiki/langs/json.mjs"),
17
+ jsx: () => import("shiki/langs/jsx.mjs"),
18
+ markdown: () => import("shiki/langs/markdown.mjs"),
19
+ python: () => import("shiki/langs/python.mjs"),
20
+ sql: () => import("shiki/langs/sql.mjs"),
21
+ tsx: () => import("shiki/langs/tsx.mjs"),
22
+ typescript: () => import("shiki/langs/typescript.mjs"),
23
+ yaml: () => import("shiki/langs/yaml.mjs"),
24
+ };
25
+
26
+ const aliases: Record<string, keyof typeof languages> = {
27
+ js: "javascript",
28
+ md: "markdown",
29
+ py: "python",
30
+ sh: "bash",
31
+ shell: "bash",
32
+ shellscript: "bash",
33
+ ts: "typescript",
34
+ yml: "yaml",
35
+ zsh: "bash",
36
+ };
37
+
38
+ let highlighter: Promise<HighlighterCore> | undefined;
39
+
40
+ function getHighlighter() {
41
+ highlighter ??= createHighlighterCore({
42
+ themes: [
43
+ import("shiki/themes/github-light.mjs"),
44
+ import("shiki/themes/github-dark.mjs"),
45
+ ],
46
+ langs: [],
47
+ engine: createJavaScriptRegexEngine({ forgiving: true }),
48
+ });
49
+
50
+ return highlighter;
51
+ }
52
+
53
+ function getLanguage(language: string) {
54
+ const name = language.toLowerCase();
55
+
56
+ if (name === "ansi") {
57
+ return name;
58
+ }
59
+
60
+ if (name in languages) {
61
+ return name as keyof typeof languages;
62
+ }
63
+
64
+ return aliases[name] ?? null;
65
+ }
66
+
67
+ // Loads a language and returns a highlighter for it, or null for a language
68
+ // that is not listed.
69
+ export async function loadHighlighter(language: string) {
70
+ const lang = getLanguage(language);
71
+
72
+ if (!lang) {
73
+ return null;
74
+ }
75
+
76
+ const shiki = await getHighlighter();
77
+
78
+ if (lang !== "ansi" && !shiki.getLoadedLanguages().includes(lang)) {
79
+ await shiki.loadLanguage(languages[lang]);
80
+ }
81
+
82
+ return {
83
+ // Returns one React node per line, and the grammar state after the last
84
+ // line. Pass that state back to continue where the code left off.
85
+ highlight(code: string, state?: GrammarState) {
86
+ const tokenize = (text: string) =>
87
+ shiki.codeToTokens(text, {
88
+ lang,
89
+ themes: { light: "github-light", dark: "github-dark" },
90
+ defaultColor: false,
91
+ grammarState: state,
92
+ }).tokens;
93
+
94
+ // ANSI has no grammar state, so each line is tokenized on its own and
95
+ // gets the same colors whether it arrives in one piece or streams.
96
+ const tokens =
97
+ lang === "ansi"
98
+ ? code.split("\n").flatMap((line) => tokenize(line))
99
+ : tokenize(code);
100
+
101
+ return {
102
+ lines: tokens.map((line) =>
103
+ line.map((token, index) => (
104
+ <span
105
+ key={index}
106
+ style={token.htmlStyle as React.CSSProperties}
107
+ className="text-(--shiki-light) dark:text-(--shiki-dark)"
108
+ >
109
+ {token.content}
110
+ </span>
111
+ )),
112
+ ),
113
+ state: shiki.getLastGrammarState(tokens),
114
+ };
115
+ },
116
+ };
117
+ }
118
+
119
+ // Returns one React node per line, or null for a language that is not listed.
120
+ export async function highlightCode(code: string, language: string) {
121
+ const highlighter = await loadHighlighter(language);
122
+
123
+ return highlighter ? highlighter.highlight(code).lines : null;
124
+ }