@majapisoftwares/ui 6.8.2 → 6.10.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
@@ -4,6 +4,8 @@
4
4
  - Toda mudança na biblioteca que afete apps entra no mesmo commit no starter (`starters/next-app`) e no catálogo. O starter sempre depende da versão atual da biblioteca (o teste `npm run test:starter` falha se divergir) e deve compilar e passar lint/typecheck/build com ela.
5
5
  - Todo app é bilíngue: inglês (`en`) e português (`pt-BR`). Textos de UI ficam em catálogos `defineMessages` com as duas línguas; nada de texto fixo em componentes. Use `Preferences`/`PreferenceControls` da biblioteca para idioma e tema.
6
6
  - Mantenha o texto mínimo: sem descrições, avisos ou rótulos que não ajudem a tarefa.
7
+ - Navegação da página é do `AppShell`: passe `breadcrumbs` e não crie botões de voltar, breadcrumbs próprios nem títulos ou rótulos que repitam o nome da página (docs/STANDARDS.md, "Navegação da página"; o `check:standards` bloqueia).
8
+ - Telas com dados se atualizam sozinhas com `useLiveRefresh` (`hooks/use-live-refresh`); nunca botão de atualizar (docs/STANDARDS.md, "Dados ao vivo").
7
9
  - `patterns/data-table` (TanStack Table, vindo da Numa) é a única tabela de dados: filtros por coluna, ordenação múltipla, colunas reordenáveis/ocultáveis/redimensionáveis, seleção, persistência e estados. Melhorias de tabela são feitas aqui e chegam a todos os apps por versão; apps não mantêm cópias próprias.
8
10
  - Ao trazer componentes de outros apps, remova sobrescritas visuais (arredondamento, altura, sombra, padding, cores) e deixe os primitivos da biblioteca definirem o visual; containers usam os raios já adotados aqui (ex.: rounded-2xl em tabelas e listas).
9
11
  - Seleção usa sempre o Select (Base UI) da biblioteca; não use select nativo nem NativeSelect (o check:standards bloqueia).
package/docs/STANDARDS.md CHANGED
@@ -66,7 +66,7 @@ Base do shadcn AI Elements (Base UI) instalada pelo CLI: `message-scroller` (o c
66
66
  - `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.
67
67
  - `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).
68
68
  - `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).
69
- - `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.
69
+ - `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. Links externos abrem um Dialog da biblioteca (copiar, abrir este link, sempre abrir o host); `TrustedLinksProvider` recebe os hosts que abrem direto e `onTrust`, e o app guarda a lista. Sem o provider, todo link pergunta e não há "sempre abrir".
70
70
  - `hooks/use-streamed-text`: revela progressivamente uma resposta que chega inteira (Numa), respeitando movimento reduzido.
71
71
 
72
72
  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.
@@ -76,3 +76,19 @@ Adaptações: `MessageScrollerItem` usa `-m-2 p-2` (e `MessageScrollerContent`,
76
76
  ## Contextual tool navigation
77
77
 
78
78
  AppShell navigation items accept optional `children` for one level of related tool views. Only the active tool expands. The current destination alone receives aria-current. Navigation closes the mobile sidebar after selection. Sidebar subitems have 44px touch targets on mobile. Use route navigation here; reserve FilterTabs for filters or views of the current dataset. Use `fillHeight` for contained table/chat pages and ordinary page flow for long forms and card collections.
79
+
80
+ ## Navegação da página
81
+
82
+ Uma página tem um jeito só de subir: o breadcrumb do `AppShell`. Nunca dois controles para o mesmo destino.
83
+
84
+ - O app passa `breadcrumbs` (`{ label, href? }[]`, a página atual por último) e `onBreadcrumbNavigate`; o shell desenha o cabeçalho igual em todo app. Apps não montam breadcrumbs (`components/breadcrumb`) nem usam o slot `header`, que está obsoleto.
85
+ - A partir de `md`: a trilha inteira, sem botão de voltar. Nos telefones: só a página atual, numa linha, depois de uma seta de voltar para o pai com link mais próximo.
86
+ - Só pais de verdade ganham `href`. Um grupo que só reúne páginas irmãs (Configurações › Padrões) fica sem link: a sidebar abre essas páginas, e o telefone não mostra seta. Uma página que a sidebar abre não tem nenhum link no breadcrumb; só a página de um item tem.
87
+ - A página de um item (um quadro, uma sessão) fica abaixo da lista dele: `Quadros › Workbench launch`. Quando o caminho muda o lugar (uma sessão aberta de um quadro), a trilha mostra esse lugar (`Quadros › quadro › sessão`) em vez de um botão "Voltar ao quadro" no conteúdo.
88
+ - Páginas não têm botões nem links de voltar, nem `router.back()`. O nome da página aparece uma vez, no breadcrumb; o `h1` da página é `sr-only`. Nada no conteúdo repete esse nome: nem título, nem rótulo de campo (uma página com um campo Harness não se chama Harness). Enquanto o nome carrega, `label: null` mostra um Skeleton no lugar.
89
+ - Páginas fora do shell (`AuthLayout`: login, links abertos de fora) não têm breadcrumb e podem oferecer uma ação de retorno.
90
+ - `check:standards` bloqueia, no app: importar `components/breadcrumb`, link com seta para a esquerda ou rótulo `t.back…`, `router.back()`/`history.back()`, `h1` visível e botão de atualizar. Apps cobrem o resto com um teste e2e por rota: em desktop nenhum controle de voltar e, numa página da sidebar, nenhum link no breadcrumb; no telefone no máximo um voltar, no cabeçalho; nenhum botão de atualizar; e o nome da página não se repete no conteúdo.
91
+
92
+ ## Dados ao vivo
93
+
94
+ Listas e telas com dados se atualizam sozinhas: `useLiveRefresh(load, ms)` (`hooks/use-live-refresh`) chama `load` a cada `ms` (5 s por padrão) com a página visível e logo que a pessoa volta para ela. Não há botão de atualizar. Leituras caras usam um intervalo maior (um scan na nuvem a cada minutos, não segundos), nunca um botão. Tentar de novo depois de uma falha (`onRetry`) continua, porque é outra coisa.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@majapisoftwares/ui",
3
- "version": "6.8.2",
3
+ "version": "6.10.0",
4
4
  "description": "Shared Majapi UI and UX standards based on shadcn/ui",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -44,7 +44,9 @@
44
44
  "test:preferences": "tsx --test scripts/preferences.test.tsx",
45
45
  "test:data-table": "tsx --test scripts/data-table.test.tsx",
46
46
  "test:chat-quote": "tsx --test scripts/chat-quote.test.tsx",
47
+ "test:chat-markdown": "tsx --test scripts/chat-markdown.test.tsx",
47
48
  "test:ai-elements": "tsx --test scripts/ai-elements.test.tsx",
49
+ "test:navigation": "tsx --test scripts/navigation.test.tsx",
48
50
  "verify": "node scripts/verify.mjs"
49
51
  },
50
52
  "peerDependencies": {
@@ -1,8 +1,54 @@
1
1
  import { readdir, readFile } from "node:fs/promises";
2
2
  import { resolve, relative } from "node:path";
3
+ import { pathToFileURL } from "node:url";
3
4
  const consumer = process.argv[2];
4
5
  const root = resolve(consumer ?? "src");
5
6
  const violations = [];
7
+
8
+ // A link (or a Button rendering one) that goes back: a left arrow or a
9
+ // `back…` label. Inside the AppShell the breadcrumb is the way up, and the
10
+ // shell adds the phone's back arrow itself.
11
+ const backSign =
12
+ /\b(?:ArrowLeft|ChevronLeft|MoveLeft|CornerUpLeft|Undo2?)Icon\b|\bt\.back(?:[A-Z]\w*)?\b/;
13
+ export function backLink(text) {
14
+ for (const match of text.matchAll(/<(Button|Link|a|BreadcrumbLink)\b/g)) {
15
+ const close = text.indexOf(`</${match[1]}>`, match.index);
16
+ const block = text.slice(match.index, Math.min(close === -1 ? Infinity : close, match.index + 600));
17
+ if (/\bhref=|render=\{\s*<(?:Link|a)\b/.test(block) && backSign.test(block)) return true;
18
+ }
19
+ return false;
20
+ }
21
+
22
+ /** What a consumer file breaks of the page-navigation rules (docs/STANDARDS.md, "Navegação da página"). */
23
+ export function navigationViolations(text) {
24
+ const found = [];
25
+ if (/from\s+["']@majapisoftwares\/ui\/components\/breadcrumb["']/.test(text))
26
+ found.push("pass breadcrumbs to AppShell; the shell draws the page's navigation");
27
+ // Pages outside the shell (AuthLayout) have no breadcrumb; their one way back is theirs to show.
28
+ if (/<AuthLayout\b/.test(text)) return found;
29
+ if (backLink(text) || /\b(?:router|history)\.back\(/.test(text))
30
+ found.push("no back buttons in pages; the AppShell breadcrumb links up (with a back arrow on phones)");
31
+ if (/<h1\b(?![^>]*\bsr-only\b)/.test(text))
32
+ found.push("the breadcrumb names the page; keep its h1 for screen readers (sr-only)");
33
+ if (refreshButton(text))
34
+ found.push("no refresh buttons; keep the screen current with useLiveRefresh (@majapisoftwares/ui/hooks/use-live-refresh)");
35
+ return found;
36
+ }
37
+
38
+ // A Button that reloads what's on screen: a refresh label, or an icon-only
39
+ // button with a rotate icon. A retry after a failure, and actions with their
40
+ // own label (Sync now, Reconnect), aren't refresh buttons.
41
+ const rotateIcon = /\b(?:Refresh|Rotate)(?:Cw|Ccw)Icon\b/;
42
+ export function refreshButton(text) {
43
+ for (const match of text.matchAll(/<Button\b/g)) {
44
+ const close = text.indexOf("</Button>", match.index);
45
+ const block = text.slice(match.index, Math.min(close === -1 ? Infinity : close, match.index + 600));
46
+ if (/\b(?:t|ui|messages)\.retry\b/.test(block)) continue;
47
+ if (/\bt\.refresh\b/.test(block) || (/\bsize="icon[^"]*"/.test(block) && rotateIcon.test(block))) return true;
48
+ }
49
+ return false;
50
+ }
51
+
6
52
  async function visit(path) {
7
53
  for (const entry of await readdir(path, { withFileTypes: true })) {
8
54
  if (["node_modules", "dist", ".git"].includes(entry.name)) continue;
@@ -31,13 +77,19 @@ async function visit(path) {
31
77
  violations.push(`${name}: use semantic tokens instead of local colors`);
32
78
  if (consumer && /from\s+["'](?:sonner|@majapisoftwares\/ui\/components\/(?:sonner|snackbar))["']/.test(text))
33
79
  violations.push(`${name}: notify with toast from @majapisoftwares/ui/components/toast`);
80
+ if (consumer)
81
+ for (const rule of navigationViolations(text)) violations.push(`${name}: ${rule}`);
34
82
  if (!consumer && /from ["']@\//.test(text))
35
83
  violations.push(`${name}: library internals must use portable imports`);
36
84
  }
37
85
  }
38
- await visit(root);
39
- if (violations.length) {
40
- console.error(violations.join("\n"));
41
- process.exitCode = 1;
42
- } else
43
- console.log(`UI standards passed (${consumer ? "consumer" : "library"}).`);
86
+
87
+ // Imported by its test: only a direct run checks a tree.
88
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
89
+ await visit(root);
90
+ if (violations.length) {
91
+ console.error(violations.join("\n"));
92
+ process.exitCode = 1;
93
+ } else
94
+ console.log(`UI standards passed (${consumer ? "consumer" : "library"}).`);
95
+ }
@@ -0,0 +1,28 @@
1
+ "use client";
2
+
3
+ import { useEffect, useRef } from "react";
4
+
5
+ /**
6
+ * Keeps a screen current, so it never needs a refresh button: calls `refresh`
7
+ * every `ms` while the page is visible, and right away when the person comes
8
+ * back to it (focus or a visible tab). The first load stays with the caller.
9
+ */
10
+ export function useLiveRefresh(refresh: () => void, ms = 5000) {
11
+ const latest = useRef(refresh);
12
+ useEffect(() => {
13
+ latest.current = refresh;
14
+ });
15
+ useEffect(() => {
16
+ const run = () => {
17
+ if (!document.hidden) latest.current();
18
+ };
19
+ const timer = setInterval(run, ms);
20
+ document.addEventListener("visibilitychange", run);
21
+ window.addEventListener("focus", run);
22
+ return () => {
23
+ clearInterval(timer);
24
+ document.removeEventListener("visibilitychange", run);
25
+ window.removeEventListener("focus", run);
26
+ };
27
+ }, [ms]);
28
+ }
package/src/lib/i18n.tsx CHANGED
@@ -68,6 +68,8 @@ export const uiMessages = defineMessages({
68
68
  page: (page: number, total: number) => `Page ${page} of ${total}`,
69
69
  rows: (count: number) => `${count} ${count === 1 ? "row" : "rows"}`,
70
70
  close: "Close",
71
+ back: "Back",
72
+ backTo: (name: string) => `Back to ${name}`,
71
73
  language: "Language",
72
74
  toggleTheme: "Toggle theme",
73
75
  more: "More",
@@ -158,6 +160,8 @@ export const uiMessages = defineMessages({
158
160
  page: (page: number, total: number) => `Página ${page} de ${total}`,
159
161
  rows: (count: number) => `${count} ${count === 1 ? "linha" : "linhas"}`,
160
162
  close: "Fechar",
163
+ back: "Voltar",
164
+ backTo: (name: string) => `Voltar para ${name}`,
161
165
  language: "Idioma",
162
166
  toggleTheme: "Alternar tema",
163
167
  more: "Mais",
package/src/lib/utils.ts CHANGED
@@ -15,3 +15,18 @@ export function quoteText(markdown: string) {
15
15
  .replace(/\s+/g, " ")
16
16
  .trim();
17
17
  }
18
+
19
+ /**
20
+ * The host an "always open" choice for a link applies to (lowercase, no port),
21
+ * or null for anything but an absolute http(s) URL.
22
+ */
23
+ export function linkHost(url: string) {
24
+ try {
25
+ const parsed = new URL(url);
26
+ return parsed.protocol === "https:" || parsed.protocol === "http:"
27
+ ? parsed.hostname.toLowerCase()
28
+ : null;
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
@@ -1,7 +1,8 @@
1
1
  "use client";
2
2
 
3
- import type { MouseEvent, ReactNode } from "react";
3
+ import { Fragment, type MouseEvent, type ReactNode } from "react";
4
4
  import { cn } from "cn";
5
+ import { ArrowLeftIcon } from "lucide-react";
5
6
  import {
6
7
  Sidebar,
7
8
  SidebarCollapse,
@@ -25,6 +26,17 @@ import {
25
26
  } from "../components/ui/sidebar";
26
27
  import { Separator } from "../components/ui/separator";
27
28
  import { TooltipProvider } from "../components/ui/tooltip";
29
+ import { buttonVariants } from "../components/ui/button";
30
+ import { Skeleton } from "../components/ui/skeleton";
31
+ import {
32
+ Breadcrumb,
33
+ BreadcrumbItem,
34
+ BreadcrumbLink,
35
+ BreadcrumbList,
36
+ BreadcrumbPage,
37
+ BreadcrumbSeparator,
38
+ } from "../components/ui/breadcrumb";
39
+ import { useUiMessages } from "../lib/i18n";
28
40
 
29
41
  export interface NavigationItem {
30
42
  id: string;
@@ -41,6 +53,18 @@ export interface NavigationGroup {
41
53
  items: NavigationItem[];
42
54
  }
43
55
 
56
+ /** One step of the page's breadcrumb. */
57
+ export interface ShellBreadcrumb {
58
+ /** `null` while the name loads (a skeleton shows in its place). */
59
+ label: string | null;
60
+ /**
61
+ * A page above this one. Only real parents get an href: on phones the
62
+ * nearest one becomes the header's back arrow. A group that only collects
63
+ * sibling pages (the sidebar opens them) has none.
64
+ */
65
+ href?: string;
66
+ }
67
+
44
68
  export interface AppShellProps {
45
69
  /** Square logo; stays in place in every sidebar mode. */
46
70
  logo: ReactNode;
@@ -49,7 +73,19 @@ export interface AppShellProps {
49
73
  navigation: NavigationGroup[];
50
74
  activeId: string;
51
75
  onNavigate: (id: string) => void;
52
- /** Rendered in the header next to the sidebar trigger, e.g. breadcrumbs. */
76
+ /**
77
+ * Where the page sits, the current page last. The shell owns the page's
78
+ * navigation: from `md` up it shows the whole trail and no back button; on
79
+ * phones it shows the current page, after a back arrow to the nearest
80
+ * linked parent. Pages never add their own back buttons.
81
+ */
82
+ breadcrumbs?: ShellBreadcrumb[];
83
+ /** Client-side navigation for breadcrumb links and the back arrow (e.g. `router.push`). Without it they are plain links. */
84
+ onBreadcrumbNavigate?: (href: string) => void;
85
+ /**
86
+ * @deprecated Pass `breadcrumbs`: the shell draws them the same way in
87
+ * every app. Rendered only when `breadcrumbs` is not set.
88
+ */
53
89
  header?: ReactNode;
54
90
  /** Rendered at the end of the header, e.g. locale or theme switchers. */
55
91
  actions?: ReactNode;
@@ -96,6 +132,85 @@ function HeaderTrigger() {
96
132
  );
97
133
  }
98
134
 
135
+ const plainClick = (event: MouseEvent<HTMLElement>) =>
136
+ event.button === 0 &&
137
+ !event.metaKey &&
138
+ !event.ctrlKey &&
139
+ !event.shiftKey &&
140
+ !event.altKey;
141
+
142
+ function ShellBreadcrumbs({
143
+ items,
144
+ onNavigate,
145
+ }: {
146
+ items: ShellBreadcrumb[];
147
+ onNavigate?: (href: string) => void;
148
+ }) {
149
+ const t = useUiMessages();
150
+ const parent = items.slice(0, -1).reverse().find((item) => item.href);
151
+ const follow = (href: string) => (event: MouseEvent<HTMLElement>) => {
152
+ if (!onNavigate || !plainClick(event)) return;
153
+ event.preventDefault();
154
+ onNavigate(href);
155
+ };
156
+ const name = (item: ShellBreadcrumb) =>
157
+ item.label ?? <Skeleton className="h-4 w-24" />;
158
+ return (
159
+ <div className="flex min-w-0 items-center gap-1">
160
+ {/* Phones only: one way back, in place of the parents' links. A link
161
+ (it navigates), styled as the ghost icon button. */}
162
+ {parent?.href ? (
163
+ <a
164
+ href={parent.href}
165
+ onClick={follow(parent.href)}
166
+ aria-label={parent.label ? t.backTo(parent.label) : t.back}
167
+ className={cn(
168
+ buttonVariants({ variant: "ghost", size: "icon-sm" }),
169
+ "-ml-1.5 shrink-0 md:hidden",
170
+ )}
171
+ >
172
+ <ArrowLeftIcon />
173
+ </a>
174
+ ) : null}
175
+ <Breadcrumb className="min-w-0">
176
+ <BreadcrumbList className="flex-nowrap">
177
+ {items.map((item, index) => {
178
+ const last = index === items.length - 1;
179
+ return (
180
+ <Fragment key={index}>
181
+ {last ? (
182
+ <BreadcrumbItem className="min-w-0">
183
+ <BreadcrumbPage className="truncate">
184
+ {name(item)}
185
+ </BreadcrumbPage>
186
+ </BreadcrumbItem>
187
+ ) : (
188
+ <>
189
+ <BreadcrumbItem className="hidden max-w-48 min-w-0 shrink-0 md:inline-flex">
190
+ {item.href ? (
191
+ <BreadcrumbLink
192
+ className="truncate"
193
+ href={item.href}
194
+ onClick={follow(item.href)}
195
+ >
196
+ {name(item)}
197
+ </BreadcrumbLink>
198
+ ) : (
199
+ <span className="truncate">{name(item)}</span>
200
+ )}
201
+ </BreadcrumbItem>
202
+ <BreadcrumbSeparator className="hidden md:block" />
203
+ </>
204
+ )}
205
+ </Fragment>
206
+ );
207
+ })}
208
+ </BreadcrumbList>
209
+ </Breadcrumb>
210
+ </div>
211
+ );
212
+ }
213
+
99
214
  function ShellNavigation({
100
215
  navigation,
101
216
  activeId,
@@ -103,14 +218,7 @@ function ShellNavigation({
103
218
  }: Pick<AppShellProps, "navigation" | "activeId" | "onNavigate">) {
104
219
  const { isMobile, setOpenMobile } = useSidebar();
105
220
  const navigate = (id: string, event: MouseEvent<HTMLElement>) => {
106
- if (
107
- event.button !== 0 ||
108
- event.metaKey ||
109
- event.ctrlKey ||
110
- event.shiftKey ||
111
- event.altKey
112
- )
113
- return;
221
+ if (!plainClick(event)) return;
114
222
  event.preventDefault();
115
223
  onNavigate(id);
116
224
  if (isMobile) setOpenMobile(false);
@@ -174,6 +282,8 @@ export function AppShell({
174
282
  navigation,
175
283
  activeId,
176
284
  onNavigate,
285
+ breadcrumbs,
286
+ onBreadcrumbNavigate,
177
287
  header,
178
288
  actions,
179
289
  footer,
@@ -217,7 +327,16 @@ export function AppShell({
217
327
  <SidebarInset className={fillHeight ? "h-svh min-h-0" : undefined}>
218
328
  <header className="sticky top-0 z-10 flex h-14 shrink-0 items-center gap-2 border-b bg-background px-4 md:px-6">
219
329
  <HeaderTrigger />
220
- <div className="min-w-0 flex-1">{header}</div>
330
+ <div className="min-w-0 flex-1">
331
+ {breadcrumbs?.length ? (
332
+ <ShellBreadcrumbs
333
+ items={breadcrumbs}
334
+ onNavigate={onBreadcrumbNavigate}
335
+ />
336
+ ) : (
337
+ header
338
+ )}
339
+ </div>
221
340
  {actions ? (
222
341
  <div className="flex items-center gap-2">{actions}</div>
223
342
  ) : null}
@@ -1,7 +1,35 @@
1
1
  "use client";
2
2
 
3
- import { Streamdown, type StreamdownProps } from "streamdown";
4
- import { cn } from "../lib/utils";
3
+ import {
4
+ createContext,
5
+ useContext,
6
+ useEffect,
7
+ useMemo,
8
+ useRef,
9
+ useState,
10
+ type ReactNode,
11
+ } from "react";
12
+ import {
13
+ CheckIcon,
14
+ CopyIcon,
15
+ ExternalLinkIcon,
16
+ ShieldCheckIcon,
17
+ } from "lucide-react";
18
+ import {
19
+ Streamdown,
20
+ type LinkSafetyModalProps,
21
+ type StreamdownProps,
22
+ } from "streamdown";
23
+ import { Button } from "../components/ui/button";
24
+ import {
25
+ Dialog,
26
+ DialogContent,
27
+ DialogDescription,
28
+ DialogFooter,
29
+ DialogHeader,
30
+ DialogTitle,
31
+ } from "../components/ui/dialog";
32
+ import { cn, linkHost } from "../lib/utils";
5
33
  import { defineMessages, useMessages } from "../lib/i18n";
6
34
 
7
35
  // Streamdown ships English labels; the rest follow the active locale.
@@ -36,8 +64,124 @@ const translations = defineMessages<StreamdownProps["translations"]>({
36
64
  },
37
65
  });
38
66
 
39
- export interface ChatMarkdownProps
40
- extends Omit<StreamdownProps, "children" | "isAnimating"> {
67
+ const linkMessages = defineMessages({
68
+ en: {
69
+ title: "Open external link?",
70
+ description: "You're about to open an external site.",
71
+ copy: "Copy link",
72
+ copied: "Copied",
73
+ openOnce: "Open this link",
74
+ alwaysOpen: (host: string) => `Always open ${host}`,
75
+ },
76
+ "pt-BR": {
77
+ title: "Abrir link externo?",
78
+ description: "Você vai abrir um site externo.",
79
+ copy: "Copiar link",
80
+ copied: "Copiado",
81
+ openOnce: "Abrir este link",
82
+ alwaysOpen: (host: string) => `Sempre abrir ${host}`,
83
+ },
84
+ });
85
+
86
+ export interface TrustedLinks {
87
+ /** Hosts (such as "github.com") whose links open without asking. */
88
+ hosts: readonly string[];
89
+ /** The person chose to always open links to this host. */
90
+ onTrust: (host: string) => void;
91
+ }
92
+
93
+ const TrustedLinksContext = createContext<TrustedLinks | null>(null);
94
+
95
+ /**
96
+ * The sites a person always opens from ChatMarkdown links. Without it, every
97
+ * external link asks first and the dialog has no "always open" choice.
98
+ * Persisting the list (per person, per device) is up to the app.
99
+ */
100
+ export function TrustedLinksProvider({
101
+ hosts,
102
+ onTrust,
103
+ children,
104
+ }: TrustedLinks & { children: ReactNode }) {
105
+ const value = useMemo(() => ({ hosts, onTrust }), [hosts, onTrust]);
106
+ return (
107
+ <TrustedLinksContext.Provider value={value}>
108
+ {children}
109
+ </TrustedLinksContext.Provider>
110
+ );
111
+ }
112
+
113
+ function LinkDialog({
114
+ url,
115
+ isOpen,
116
+ onClose,
117
+ onConfirm,
118
+ onTrust,
119
+ }: LinkSafetyModalProps & { onTrust?: (host: string) => void }) {
120
+ const t = useMessages(linkMessages);
121
+ const [copied, setCopied] = useState(false);
122
+ const host = onTrust ? linkHost(url) : null;
123
+ const open = () => {
124
+ onConfirm();
125
+ onClose();
126
+ };
127
+ const copy = async () => {
128
+ try {
129
+ await navigator.clipboard.writeText(url);
130
+ setCopied(true);
131
+ setTimeout(() => setCopied(false), 2000);
132
+ } catch {
133
+ // The URL stays on screen to copy by hand.
134
+ }
135
+ };
136
+ return (
137
+ <Dialog open={isOpen} onOpenChange={(next) => !next && onClose()}>
138
+ <DialogContent>
139
+ <DialogHeader>
140
+ <DialogTitle className="flex items-center gap-2">
141
+ <ExternalLinkIcon className="size-4" aria-hidden="true" />
142
+ {t.title}
143
+ </DialogTitle>
144
+ <DialogDescription>{t.description}</DialogDescription>
145
+ </DialogHeader>
146
+ <div className="max-h-32 overflow-y-auto rounded-2xl bg-muted p-3 font-mono text-xs break-all">
147
+ {url}
148
+ </div>
149
+ <DialogFooter className="grid grid-cols-2">
150
+ <Button variant="outline" onClick={() => void copy()}>
151
+ {copied ? (
152
+ <CheckIcon aria-hidden="true" />
153
+ ) : (
154
+ <CopyIcon aria-hidden="true" />
155
+ )}
156
+ {copied ? t.copied : t.copy}
157
+ </Button>
158
+ <Button variant={host ? "outline" : "default"} onClick={open}>
159
+ <ExternalLinkIcon aria-hidden="true" />
160
+ {t.openOnce}
161
+ </Button>
162
+ {host ? (
163
+ <Button
164
+ className="col-span-2 min-w-0"
165
+ title={t.alwaysOpen(host)}
166
+ onClick={() => {
167
+ onTrust?.(host);
168
+ open();
169
+ }}
170
+ >
171
+ <ShieldCheckIcon aria-hidden="true" />
172
+ <span className="truncate">{t.alwaysOpen(host)}</span>
173
+ </Button>
174
+ ) : null}
175
+ </DialogFooter>
176
+ </DialogContent>
177
+ </Dialog>
178
+ );
179
+ }
180
+
181
+ export interface ChatMarkdownProps extends Omit<
182
+ StreamdownProps,
183
+ "children" | "isAnimating"
184
+ > {
41
185
  children: string;
42
186
  /** True while the text is still arriving: unfinished markdown is completed and new words fade in. */
43
187
  streaming?: boolean;
@@ -46,7 +190,8 @@ export interface ChatMarkdownProps
46
190
  /**
47
191
  * Agent reply as markdown (Streamdown, as in shadcn AI Elements Message).
48
192
  * Sanitizes model output, renders GFM tables and code with copy controls, and
49
- * tolerates half-streamed syntax.
193
+ * tolerates half-streamed syntax. External links ask before opening, unless
194
+ * their host is in TrustedLinksProvider.
50
195
  */
51
196
  export function ChatMarkdown({
52
197
  children,
@@ -55,11 +200,37 @@ export function ChatMarkdown({
55
200
  ...props
56
201
  }: ChatMarkdownProps) {
57
202
  const t = useMessages(translations);
203
+ const trusted = useContext(TrustedLinksContext);
204
+ // Read at click time, so a growing list doesn't re-render every link.
205
+ const trustedRef = useRef(trusted);
206
+ useEffect(() => {
207
+ trustedRef.current = trusted;
208
+ }, [trusted]);
209
+ const canTrust = trusted !== null;
210
+ const linkSafety = useMemo<StreamdownProps["linkSafety"]>(
211
+ () => ({
212
+ enabled: true,
213
+ onLinkCheck: (url) => {
214
+ const host = linkHost(url);
215
+ return !!host && !!trustedRef.current?.hosts.includes(host);
216
+ },
217
+ renderModal: (modal) => (
218
+ <LinkDialog
219
+ {...modal}
220
+ onTrust={
221
+ canTrust ? (host) => trustedRef.current?.onTrust(host) : undefined
222
+ }
223
+ />
224
+ ),
225
+ }),
226
+ [canTrust],
227
+ );
58
228
  return (
59
229
  <Streamdown
60
230
  isAnimating={streaming}
61
231
  animated
62
232
  translations={t}
233
+ linkSafety={linkSafety}
63
234
  className={cn(
64
235
  "min-w-0 text-sm leading-relaxed wrap-break-word *:first:mt-0 *:last:mb-0",
65
236
  className,
@@ -1473,8 +1473,9 @@ export function DataTable<TData extends RowData>(props: DataTableProps<TData>) {
1473
1473
  >
1474
1474
  <div className="flex min-w-0 flex-wrap items-center gap-2">
1475
1475
  {toolbarStartContent}
1476
- <div className="flex min-w-0 flex-1 basis-80 items-center gap-2">
1477
- <InputGroup className="flex-1">
1476
+ {/* On a phone the search takes its own row and the actions wrap below it. */}
1477
+ <div className="flex min-w-0 flex-1 basis-80 flex-wrap items-center gap-2">
1478
+ <InputGroup className="min-w-0 flex-1 basis-64">
1478
1479
  <InputGroupInput
1479
1480
  value={globalFilter}
1480
1481
  onChange={(event) => handleGlobalFilterChange(event.target.value)}
@@ -1483,18 +1484,23 @@ export function DataTable<TData extends RowData>(props: DataTableProps<TData>) {
1483
1484
  <InputGroupAddon className="pl-2">
1484
1485
  <SearchIcon />
1485
1486
  </InputGroupAddon>
1486
- <InputGroupAddon align="inline-end" className="pr-2">
1487
+ <InputGroupAddon
1488
+ align="inline-end"
1489
+ className="pr-2 whitespace-nowrap"
1490
+ >
1487
1491
  {formatResultCount(filteredRowCount)}
1488
1492
  </InputGroupAddon>
1489
1493
  </InputGroup>
1490
- {toolbarEndContent}
1491
- <ColumnSettings
1492
- defaultColumnOrder={defaultColumnOrder}
1493
- lockedEndColumnIds={lockedEndColumnIds}
1494
- lockedStartColumnIds={lockedStartColumnIds}
1495
- onResetColumns={resetColumns}
1496
- table={table}
1497
- />
1494
+ <div className="flex max-w-full flex-wrap items-center gap-2">
1495
+ {toolbarEndContent}
1496
+ <ColumnSettings
1497
+ defaultColumnOrder={defaultColumnOrder}
1498
+ lockedEndColumnIds={lockedEndColumnIds}
1499
+ lockedStartColumnIds={lockedStartColumnIds}
1500
+ onResetColumns={resetColumns}
1501
+ table={table}
1502
+ />
1503
+ </div>
1498
1504
  </div>
1499
1505
  </div>
1500
1506
 
@@ -1550,12 +1556,12 @@ export function DataTable<TData extends RowData>(props: DataTableProps<TData>) {
1550
1556
  )}
1551
1557
  >
1552
1558
  <Table
1553
- containerClassName={
1559
+ containerClassName={cn(
1560
+ // The empty state sizes itself to the visible width (cqw).
1561
+ "@container",
1554
1562
  // Bottom-only fade: a top fade would dissolve the sticky header.
1555
- fillHeight
1556
- ? "min-h-0 flex-1 overflow-auto scroll-fade-b"
1557
- : undefined
1558
- }
1563
+ fillHeight && "min-h-0 flex-1 overflow-auto scroll-fade-b",
1564
+ )}
1559
1565
  style={{ minWidth: "100%", width: table.getTotalSize() }}
1560
1566
  >
1561
1567
  {/* Solid background: rows scroll underneath the sticky header. */}
@@ -1641,6 +1647,8 @@ export function DataTable<TData extends RowData>(props: DataTableProps<TData>) {
1641
1647
  colSpan={table.getVisibleLeafColumns().length}
1642
1648
  className="text-muted-foreground h-24 text-center"
1643
1649
  >
1650
+ {/* A table wider than the screen: the message stays in view instead of centring on the full width. */}
1651
+ <div className="sticky left-3 w-[calc(100cqw-1.5rem)] whitespace-normal">
1644
1652
  {isFiltered ? (
1645
1653
  <Empty>
1646
1654
  <EmptyHeader>
@@ -1670,6 +1678,7 @@ export function DataTable<TData extends RowData>(props: DataTableProps<TData>) {
1670
1678
  </Empty>
1671
1679
  ))
1672
1680
  )}
1681
+ </div>
1673
1682
  </TableCell>
1674
1683
  </TableRow>
1675
1684
  )}