@majapisoftwares/ui 6.8.2 → 6.9.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/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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@majapisoftwares/ui",
3
- "version": "6.8.2",
3
+ "version": "6.9.0",
4
4
  "description": "Shared Majapi UI and UX standards based on shadcn/ui",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -44,6 +44,7 @@
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",
48
49
  "verify": "node scripts/verify.mjs"
49
50
  },
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,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,