@majapisoftwares/ui 6.4.0 → 6.6.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
@@ -12,7 +12,7 @@ TypeScript em modo strict, React com componentes funcionais e composição. APIs
12
12
 
13
13
  `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
14
 
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). 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.
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). Snackbar (com a função `snackbar`) é 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
16
 
17
17
  ## Comportamentos de UX
18
18
 
@@ -25,6 +25,7 @@ DataTable mantém os resets de paginação fora da avaliação de row models dur
25
25
  - 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
26
  - 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
27
  - 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 snackbar (`components/snackbar`), para informação e para erro: uma por vez, embaixo no centro, com no máximo uma ação curta (Desfazer, Tentar de novo). Falhas de ações (salvar, enviar, criar) vão para `snackbar.error`, 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` e `Toaster` de `components/sonner` estão obsoletos e já aparecem como snackbar.
28
29
  - 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.
29
30
  - 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.
30
31
  - Preferência por movimento reduzido é respeitada. A ordem de leitura deve acompanhar a ordem visual. Ícones sozinhos exigem nome acessível.
@@ -51,12 +52,12 @@ AGENTS.md nos apps exige contribuição upstream antes de uso. O verificador est
51
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:
52
53
 
53
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`.
54
- - `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).
55
+ - `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.
55
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`).
56
57
  - `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.
57
58
  - `hooks/use-streamed-text`: revela progressivamente uma resposta que chega inteira (Numa), respeitando movimento reduzido.
58
59
 
59
- Erros de resposta aparecem na própria mensagem (Bubble `destructive`) com Tentar novamente; erros de ações fora da conversa seguem no toast. O catálogo demonstra em `/chat` (conversa com raciocínio, ferramentas, aprovação, erro e retry) e `/chat/new` (vazio com sugestões).
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 snackbar (`snackbar.error`). O catálogo demonstra em `/chat` (conversa com raciocínio, ferramentas, aprovação, erro e retry) e `/chat/new` (vazio com sugestões).
60
61
 
61
62
  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.
62
63
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@majapisoftwares/ui",
3
- "version": "6.4.0",
3
+ "version": "6.6.0",
4
4
  "description": "Shared Majapi UI and UX standards based on shadcn/ui",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -29,6 +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 snackbar from @majapisoftwares/ui/components/snackbar`);
32
34
  if (!consumer && /from ["']@\//.test(text))
33
35
  violations.push(`${name}: library internals must use portable imports`);
34
36
  }
@@ -0,0 +1,100 @@
1
+ "use client";
2
+
3
+ import { isValidElement, type CSSProperties, type ReactNode } from "react";
4
+ import { CircleAlertIcon, TriangleAlertIcon } from "lucide-react";
5
+ import { Toaster as Sonner, toast, type ToasterProps } from "sonner";
6
+ import { Orb } from "./orb";
7
+
8
+ /**
9
+ * Snackbar: the only way apps notify people, for information and for errors.
10
+ * One message at a time, at the bottom center, on the inverse surface, with
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.
16
+ */
17
+
18
+ export interface SnackbarAction {
19
+ label: string;
20
+ onClick: () => void;
21
+ }
22
+
23
+ export interface SnackbarOptions {
24
+ /** One short action, such as Undo or Retry. */
25
+ action?: SnackbarAction;
26
+ /** Milliseconds on screen; info 4 s and errors 8 s by default. */
27
+ duration?: number;
28
+ /** Replaces the snackbar with the same id instead of queueing another. */
29
+ id?: string | number;
30
+ }
31
+
32
+ const INFO_MS = 4000;
33
+ const ERROR_MS = 8000;
34
+
35
+ const options = (value: SnackbarOptions | undefined, duration: number) => ({
36
+ duration: value?.duration ?? duration,
37
+ ...(value?.id !== undefined ? { id: value.id } : {}),
38
+ ...(value?.action ? { action: { label: value.action.label, onClick: value.action.onClick } } : {}),
39
+ });
40
+
41
+ /** A message that something happened or needs attention. */
42
+ function show(message: ReactNode, value?: SnackbarOptions) {
43
+ return toast(message, options(value, INFO_MS));
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);
50
+ }
51
+
52
+ export const snackbar = Object.assign(show, {
53
+ /** Something failed: the reason, as the person can act on it. Accepts a thrown value. */
54
+ error(message: unknown, value?: SnackbarOptions) {
55
+ const text: ReactNode = typeof message === "string" || isValidElement(message) ? message : errorMessage(message);
56
+ return toast.error(text, options(value, ERROR_MS));
57
+ },
58
+ /** Removes one snackbar, or all of them. */
59
+ dismiss(id?: string | number) {
60
+ return toast.dismiss(id);
61
+ },
62
+ });
63
+
64
+ /** The snackbar host. Theme comes from the caller (Preferences passes the active theme). */
65
+ export function Snackbar({ theme = "system", ...props }: ToasterProps) {
66
+ return (
67
+ <Sonner
68
+ theme={theme}
69
+ position="bottom-center"
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
+ );
100
+ }
@@ -10,6 +10,7 @@ import {
10
10
  } from "lucide-react";
11
11
 
12
12
  // Theme comes from the caller (Preferences passes the active theme).
13
+ /** @deprecated Notifications are snackbars: mount `Snackbar` from `components/snackbar` (Preferences already does). */
13
14
  const Toaster = ({ theme = "system", ...props }: ToasterProps) => {
14
15
  return (
15
16
  <Sonner
@@ -41,4 +42,5 @@ const Toaster = ({ theme = "system", ...props }: ToasterProps) => {
41
42
  };
42
43
 
43
44
  export { Toaster };
45
+ /** @deprecated Use `snackbar(message)` and `snackbar.error(error)` from `components/snackbar`; existing calls already show as snackbars. */
44
46
  export { toast } from "sonner";
@@ -16,7 +16,7 @@ import {
16
16
  type Locale,
17
17
  } from "../lib/i18n";
18
18
  import { Button } from "../components/ui/button";
19
- import { Toaster } from "../components/ui/sonner";
19
+ import { Snackbar } from "../components/ui/snackbar";
20
20
  import {
21
21
  DropdownMenu,
22
22
  DropdownMenuContent,
@@ -131,7 +131,7 @@ export function Preferences({
131
131
  <PreferencesReadyContext.Provider value={ready}>
132
132
  <LocaleProvider locale={locale}>
133
133
  {children}
134
- <Toaster theme={theme} />
134
+ <Snackbar theme={theme} />
135
135
  </LocaleProvider>
136
136
  </PreferencesReadyContext.Provider>
137
137
  </PreferencesContext.Provider>
@@ -52,6 +52,11 @@ export interface PromptInputProps {
52
52
  /** While submitted/streaming, Enter does not send and the button stops. */
53
53
  status?: ChatStatus;
54
54
  onStop?: () => void;
55
+ /**
56
+ * Lets the person send while a reply is in progress, e.g. to steer a
57
+ * running agent. With text the button sends; with an empty field it stops.
58
+ */
59
+ sendWhileBusy?: boolean;
55
60
  placeholder?: string;
56
61
  disabled?: boolean;
57
62
  autoFocus?: boolean;
@@ -112,8 +117,9 @@ function clipboardFiles(data: DataTransfer) {
112
117
  /**
113
118
  * Chat composer on InputGroup (shadcn AI Elements Prompt Input) with Numa's
114
119
  * behaviour: Enter sends and Shift+Enter breaks the line, files can be
115
- * attached, pasted or dropped, focus stays in the field after sending and a
116
- * failed send restores the draft.
120
+ * attached, pasted or dropped, focus stays in the field after sending, a
121
+ * failed send restores the draft and, with `sendWhileBusy`, messages can be
122
+ * sent while the agent works.
117
123
  */
118
124
  export function PromptInput({
119
125
  onSubmit,
@@ -122,6 +128,7 @@ export function PromptInput({
122
128
  onValueChange,
123
129
  status = "ready",
124
130
  onStop,
131
+ sendWhileBusy = false,
125
132
  placeholder,
126
133
  disabled = false,
127
134
  autoFocus = false,
@@ -141,8 +148,8 @@ export function PromptInput({
141
148
  const filesRef = useRef(files);
142
149
  const text = value ?? innerValue;
143
150
  const busy = status === "submitted" || status === "streaming";
144
- const canSend =
145
- !disabled && !busy && (text.trim().length > 0 || files.length > 0);
151
+ const hasContent = text.trim().length > 0 || files.length > 0;
152
+ const canSend = !disabled && (!busy || sendWhileBusy) && hasContent;
146
153
 
147
154
  useEffect(() => {
148
155
  filesRef.current = files;
@@ -226,7 +233,10 @@ export function PromptInput({
226
233
  const hasFiles = (event: DragEvent) =>
227
234
  attachments && !disabled && event.dataTransfer.types.includes("Files");
228
235
 
229
- const stopping = busy && onStop !== undefined;
236
+ // With sendWhileBusy, a draft turns the stop button back into send.
237
+ const stopping =
238
+ busy && onStop !== undefined && !(sendWhileBusy && hasContent);
239
+ const waiting = busy && !stopping && !canSend;
230
240
  const sendLabel = stopping ? messages.stop : messages.send;
231
241
  // Keeps focus (and the mobile keyboard) in the field while pressing buttons.
232
242
  const keepFocus = (event: { preventDefault: () => void }) =>
@@ -350,7 +360,7 @@ export function PromptInput({
350
360
  >
351
361
  {stopping ? (
352
362
  <SquareIcon className="fill-current" />
353
- ) : busy ? (
363
+ ) : waiting ? (
354
364
  <Spinner />
355
365
  ) : (
356
366
  <ArrowUpIcon />