@majapisoftwares/ui 6.8.0 → 6.8.2

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.
@@ -12,6 +12,8 @@ The above copyright notice and this permission notice shall be included in all c
12
12
 
13
13
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
14
 
15
+ src/lib/message-scroller is the source of @shadcn/react's Message Scroller (packages/react/src/message-scroller and use-render, shadcn-ui/ui commit 4aaea19, newer than the 0.3.1 release), under the MIT License above. Change: a scroll anchor counts as new only when its element was never in the list, so a same-count change no longer scrolls to the oldest turn.
16
+
15
17
  src/components/ui/orb.tsx and orb.css are adapted from AICSS Orbs (https://github.com/kvnkld/aicss, registry https://www.aicss.dev/r/orbs.json): colors mapped to theme tokens, labels translated, CSS module turned into orb-prefixed global CSS. MIT License:
16
18
 
17
19
  MIT License
package/docs/STANDARDS.md CHANGED
@@ -52,6 +52,7 @@ AGENTS.md nos apps exige contribuição upstream antes de uso. O verificador est
52
52
  - Imports internos relativos e `"use client"` são aplicados por `npm run normalize:ui` após o CLI do shadcn.
53
53
  - Sheet traduz o nome acessível do fechamento pelo idioma ativo.
54
54
  - Sidebar: três modos (open/compact/closed), largura redimensionável (208–448px) com troca de modo por largura, menu de clique direito, tooltip que fecha ao clicar e textos traduzidos.
55
+ - Tabelas nunca alargam a página: `SidebarInset` tem `min-w-0` (sem ele, um conteúdo largo mantinha o inset na largura inteira e a página rolava para o lado pela largura da sidebar) e o contêiner de `Table` usa `contain-inline-size`, então a largura das linhas não entra no tamanho de nenhum ancestral (flex ou grid): a tabela rola dentro do próprio contêiner. O contêiner ocupa a largura que o pai dá; dentro de um pai que encolhe ao conteúdo (`w-fit`, inline, trilha `auto` de grid), dê largura ao pai. Não remova nenhum dos dois.
55
56
  - use-mobile usa useSyncExternalStore (compatível com SSR e com a regra de hooks).
56
57
  - Field usa imports relativos. Button assume type=button para evitar submissões acidentais; formulários declaram type=submit. Badge inclui variantes success e warning reutilizadas por StatusBadge.
57
58
  - Tokens de identidade, estados semânticos e padrões compostos são mantidos aqui.
@@ -59,7 +60,7 @@ AGENTS.md nos apps exige contribuição upstream antes de uso. O verificador est
59
60
 
60
61
  ## Chat com agentes
61
62
 
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:
63
+ Base do shadcn AI Elements (Base UI) instalada pelo CLI: `message-scroller` (o código do `@shadcn/react` vem copiado em `src/lib/message-scroller`, do commit 4aaea19 do shadcn-ui/ui, que traz correções ainda não publicadas; adaptações: uma âncora só conta como nova se o elemento nunca esteve na lista, senão a troca de "escrevendo" pela resposta, com a mesma contagem, rolava até o primeiro turno; e 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:
63
64
 
64
65
  - `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`.
65
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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@majapisoftwares/ui",
3
- "version": "6.8.0",
3
+ "version": "6.8.2",
4
4
  "description": "Shared Majapi UI and UX standards based on shadcn/ui",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -61,7 +61,6 @@
61
61
  "@dnd-kit/sortable": "10.0.0",
62
62
  "@dnd-kit/utilities": "3.2.2",
63
63
  "@fontsource-variable/geist": "^5.3.0",
64
- "@shadcn/react": "0.3.1",
65
64
  "@tanstack/react-table": "8.21.3",
66
65
  "class-variance-authority": "0.7.1",
67
66
  "clsx": "2.1.1",
@@ -6,7 +6,7 @@ import {
6
6
  useMessageScroller,
7
7
  useMessageScrollerScrollable,
8
8
  useMessageScrollerVisibility,
9
- } from "@shadcn/react/message-scroller";
9
+ } from "../../lib/message-scroller";
10
10
  import { cn } from "cn";
11
11
 
12
12
  import { Button } from "./button";
@@ -615,12 +615,14 @@ function SidebarRail({ className, ...props }: React.ComponentProps<"div">) {
615
615
  );
616
616
  }
617
617
 
618
+ // Majapi UI: `min-w-0` lets the inset shrink beside the sidebar; without it a
619
+ // wide child (a table) keeps it at full width and the page scrolls sideways.
618
620
  function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
619
621
  return (
620
622
  <main
621
623
  data-slot="sidebar-inset"
622
624
  className={cn(
623
- "relative flex w-full flex-1 flex-col bg-background md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-2xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
625
+ "relative flex w-full min-w-0 flex-1 flex-col bg-background md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-2xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
624
626
  className,
625
627
  )}
626
628
  {...props}
@@ -4,7 +4,10 @@ import * as React from "react";
4
4
  import { cn } from "cn";
5
5
 
6
6
  // Majapi UI: `containerClassName` styles the scroll container (e.g. to fill
7
- // the available height and scroll vertically).
7
+ // the available height and scroll vertically). `contain-inline-size` keeps the
8
+ // table's width out of every ancestor's sizing: however wide the rows, the
9
+ // table scrolls inside its own container and never widens the page, in any
10
+ // flex or grid layout. The container takes the width its parent gives it.
8
11
  function Table({
9
12
  className,
10
13
  containerClassName,
@@ -13,7 +16,7 @@ function Table({
13
16
  return (
14
17
  <div
15
18
  data-slot="table-container"
16
- className={cn("relative w-full overflow-x-auto", containerClassName)}
19
+ className={cn("relative w-full overflow-x-auto contain-inline-size", containerClassName)}
17
20
  >
18
21
  <table
19
22
  data-slot="table"
@@ -0,0 +1,446 @@
1
+ import * as React from "react"
2
+
3
+ import { composeRefs, mergeProps, useRender } from "./use-render"
4
+ import { USER_SCROLL_KEYS } from "./types"
5
+ import type {
6
+ MessageScrollerButtonProps,
7
+ MessageScrollerContentProps,
8
+ MessageScrollerContextValue,
9
+ MessageScrollerItemProps,
10
+ MessageScrollerProps,
11
+ MessageScrollerProviderProps,
12
+ MessageScrollerRegisterMessage,
13
+ MessageScrollerViewportProps,
14
+ } from "./types"
15
+ import { useMessageScrollerController } from "./use-message-scroller-controller"
16
+ import { useLatest } from "./utils"
17
+
18
+ const MessageScrollerContext =
19
+ React.createContext<MessageScrollerContextValue | null>(null)
20
+ const MessageScrollerItemContext =
21
+ React.createContext<MessageScrollerRegisterMessage | null>(null)
22
+
23
+ function useMessageScrollerContext() {
24
+ const context = React.useContext(MessageScrollerContext)
25
+
26
+ if (!context) {
27
+ throw new Error("useMessageScroller must be used within a MessageScroller.")
28
+ }
29
+
30
+ return context
31
+ }
32
+
33
+ function useMessageScrollerItemContext() {
34
+ const context = React.useContext(MessageScrollerItemContext)
35
+
36
+ if (!context) {
37
+ throw new Error(
38
+ "MessageScrollerItem must be used within a MessageScroller."
39
+ )
40
+ }
41
+
42
+ return context
43
+ }
44
+
45
+ function useMessageScroller() {
46
+ const { scrollToEnd, scrollToMessage, scrollToStart } =
47
+ useMessageScrollerContext()
48
+
49
+ return React.useMemo(
50
+ () => ({
51
+ scrollToEnd,
52
+ scrollToMessage,
53
+ scrollToStart,
54
+ }),
55
+ [scrollToEnd, scrollToMessage, scrollToStart]
56
+ )
57
+ }
58
+
59
+ function useMessageScrollerScrollable() {
60
+ const { stateStore } = useMessageScrollerContext()
61
+
62
+ return React.useSyncExternalStore(
63
+ stateStore.subscribe,
64
+ stateStore.getSnapshot,
65
+ stateStore.getSnapshot
66
+ )
67
+ }
68
+
69
+ function useMessageScrollerVisibility() {
70
+ const { observeVisibility, unobserveVisibility, visibilityStore } =
71
+ useMessageScrollerContext()
72
+ const subscribe = React.useCallback(
73
+ (listener: () => void) =>
74
+ visibilityStore.subscribe(
75
+ listener,
76
+ observeVisibility,
77
+ unobserveVisibility
78
+ ),
79
+ [observeVisibility, unobserveVisibility, visibilityStore]
80
+ )
81
+
82
+ return React.useSyncExternalStore(
83
+ subscribe,
84
+ visibilityStore.getSnapshot,
85
+ visibilityStore.getSnapshot
86
+ )
87
+ }
88
+
89
+ function MessageScrollerProvider({
90
+ autoScroll = false,
91
+ children,
92
+ defaultScrollPosition = "end",
93
+ scrollEdgeThreshold,
94
+ scrollPreviousItemPeek,
95
+ scrollMargin,
96
+ }: MessageScrollerProviderProps) {
97
+ const { context, registerMessage } = useMessageScrollerController({
98
+ autoScroll,
99
+ defaultScrollPosition,
100
+ scrollEdgeThreshold,
101
+ scrollPreviousItemPeek,
102
+ scrollMargin,
103
+ })
104
+
105
+ return (
106
+ <MessageScrollerContext.Provider value={context}>
107
+ <MessageScrollerItemContext.Provider value={registerMessage}>
108
+ {children}
109
+ </MessageScrollerItemContext.Provider>
110
+ </MessageScrollerContext.Provider>
111
+ )
112
+ }
113
+
114
+ function usePendingDefaultScroll() {
115
+ const { pendingDefaultScrollStore } = useMessageScrollerContext()
116
+
117
+ return React.useSyncExternalStore(
118
+ pendingDefaultScrollStore.subscribe,
119
+ pendingDefaultScrollStore.getSnapshot,
120
+ pendingDefaultScrollStore.getSnapshot
121
+ )
122
+ }
123
+
124
+ function MessageScroller({ children, ...props }: MessageScrollerProps) {
125
+ const { setRootElement } = useMessageScrollerContext()
126
+ const pendingDefaultScroll = usePendingDefaultScroll()
127
+
128
+ return (
129
+ <div
130
+ ref={setRootElement}
131
+ {...props}
132
+ {...(pendingDefaultScroll ? { "data-pending-scroll": "" } : null)}
133
+ >
134
+ {children}
135
+ </div>
136
+ )
137
+ }
138
+
139
+ function MessageScrollerViewport({
140
+ "aria-label": ariaLabel,
141
+ children,
142
+ onKeyDown,
143
+ onScroll,
144
+ onTouchMove,
145
+ onWheel,
146
+ preserveScrollOnPrepend = true,
147
+ ref,
148
+ role,
149
+ tabIndex,
150
+ ...props
151
+ }: MessageScrollerViewportProps) {
152
+ const {
153
+ handleResize,
154
+ preserveScrollOnPrependRef,
155
+ setViewportElement,
156
+ syncAfterScroll,
157
+ userScrollIntent,
158
+ viewportRef,
159
+ } = useMessageScrollerContext()
160
+ const pendingDefaultScroll = usePendingDefaultScroll()
161
+
162
+ preserveScrollOnPrependRef.current = preserveScrollOnPrepend
163
+
164
+ const setViewportRef = React.useCallback(
165
+ (element: HTMLDivElement | null) => {
166
+ setViewportElement(element)
167
+ composeRefs(ref)?.(element)
168
+ },
169
+ [ref, setViewportElement]
170
+ )
171
+
172
+ function handleScroll(event: React.UIEvent<HTMLDivElement>) {
173
+ syncAfterScroll()
174
+ onScroll?.(event)
175
+ }
176
+
177
+ function handleWheel(event: React.WheelEvent<HTMLDivElement>) {
178
+ userScrollIntent()
179
+ onWheel?.(event)
180
+ }
181
+
182
+ function handleTouchMove(event: React.TouchEvent<HTMLDivElement>) {
183
+ userScrollIntent()
184
+ onTouchMove?.(event)
185
+ }
186
+
187
+ function handleKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
188
+ if (USER_SCROLL_KEYS.has(event.key)) {
189
+ userScrollIntent()
190
+ }
191
+
192
+ onKeyDown?.(event)
193
+ }
194
+
195
+ React.useEffect(() => {
196
+ const viewport = viewportRef.current
197
+
198
+ if (!viewport || typeof ResizeObserver === "undefined") {
199
+ return
200
+ }
201
+
202
+ // Coalesce into rAF: handleResize mutates the spacer inside the observed
203
+ // content, and resizing an observed element during delivery fires
204
+ // "ResizeObserver loop completed with undelivered notifications".
205
+ let frame = 0
206
+
207
+ const observer = new ResizeObserver(() => {
208
+ window.cancelAnimationFrame(frame)
209
+ frame = window.requestAnimationFrame(handleResize)
210
+ })
211
+
212
+ observer.observe(viewport)
213
+
214
+ return () => {
215
+ window.cancelAnimationFrame(frame)
216
+ observer.disconnect()
217
+ }
218
+ }, [handleResize, viewportRef])
219
+
220
+ return (
221
+ <div
222
+ ref={setViewportRef}
223
+ role={role ?? "region"}
224
+ aria-label={ariaLabel ?? "Messages"}
225
+ tabIndex={tabIndex ?? 0}
226
+ onKeyDown={handleKeyDown}
227
+ onScroll={handleScroll}
228
+ onTouchMove={handleTouchMove}
229
+ onWheel={handleWheel}
230
+ {...props}
231
+ {...(pendingDefaultScroll ? { "data-pending-scroll": "" } : null)}
232
+ >
233
+ {children}
234
+ </div>
235
+ )
236
+ }
237
+
238
+ function MessageScrollerContent({
239
+ "aria-relevant": ariaRelevant,
240
+ children,
241
+ ref,
242
+ role,
243
+ spacerClassName,
244
+ ...props
245
+ }: MessageScrollerContentProps) {
246
+ const {
247
+ handleContentChange,
248
+ handleResize,
249
+ setContentElement,
250
+ setSpacerElement,
251
+ } = useMessageScrollerContext()
252
+ const contentRef = React.useRef<HTMLDivElement | null>(null)
253
+
254
+ const setContentRef = React.useCallback(
255
+ (element: HTMLDivElement | null) => {
256
+ contentRef.current = element
257
+ setContentElement(element)
258
+ composeRefs(ref)?.(element)
259
+ },
260
+ [ref, setContentElement]
261
+ )
262
+
263
+ React.useLayoutEffect(() => {
264
+ const content = contentRef.current
265
+
266
+ if (!content) {
267
+ return
268
+ }
269
+
270
+ handleContentChange()
271
+
272
+ if (typeof MutationObserver === "undefined") {
273
+ return
274
+ }
275
+
276
+ const observer = new MutationObserver(() => {
277
+ handleContentChange()
278
+ })
279
+
280
+ observer.observe(content, { childList: true })
281
+
282
+ return () => observer.disconnect()
283
+ }, [handleContentChange])
284
+
285
+ React.useEffect(() => {
286
+ const content = contentRef.current
287
+
288
+ if (!content || typeof ResizeObserver === "undefined") {
289
+ return
290
+ }
291
+
292
+ // Coalesce into rAF: handleResize mutates the spacer inside this observed
293
+ // element, and resizing an observed element during delivery fires
294
+ // "ResizeObserver loop completed with undelivered notifications".
295
+ let frame = 0
296
+
297
+ const observer = new ResizeObserver(() => {
298
+ window.cancelAnimationFrame(frame)
299
+ frame = window.requestAnimationFrame(handleResize)
300
+ })
301
+
302
+ observer.observe(content)
303
+
304
+ return () => {
305
+ window.cancelAnimationFrame(frame)
306
+ observer.disconnect()
307
+ }
308
+ }, [handleResize])
309
+
310
+ return (
311
+ <div
312
+ ref={setContentRef}
313
+ role={role ?? "log"}
314
+ aria-relevant={ariaRelevant ?? "additions"}
315
+ {...props}
316
+ >
317
+ {children}
318
+ <div
319
+ ref={setSpacerElement}
320
+ aria-hidden="true"
321
+ data-message-scroller-spacer=""
322
+ hidden
323
+ className={spacerClassName}
324
+ />
325
+ </div>
326
+ )
327
+ }
328
+
329
+ function MessageScrollerItem({
330
+ messageId,
331
+ ref,
332
+ scrollAnchor = false,
333
+ ...props
334
+ }: MessageScrollerItemProps) {
335
+ const registerMessage = useMessageScrollerItemContext()
336
+ const elementRef = React.useRef<HTMLDivElement | null>(null)
337
+
338
+ const setItemRef = React.useCallback(
339
+ (element: HTMLDivElement | null) => {
340
+ const previousElement = elementRef.current
341
+
342
+ elementRef.current = element
343
+
344
+ if (messageId) {
345
+ registerMessage(messageId, element, previousElement)
346
+ }
347
+
348
+ composeRefs(ref)?.(element)
349
+ },
350
+ [messageId, ref, registerMessage]
351
+ )
352
+
353
+ return (
354
+ <div
355
+ ref={setItemRef}
356
+ data-message-id={messageId}
357
+ data-scroll-anchor={scrollAnchor ? "true" : "false"}
358
+ {...props}
359
+ />
360
+ )
361
+ }
362
+
363
+ function MessageScrollerButton({
364
+ behavior = "smooth",
365
+ children,
366
+ direction = "end",
367
+ onClick,
368
+ render,
369
+ tabIndex,
370
+ type = "button",
371
+ ...props
372
+ }: MessageScrollerButtonProps) {
373
+ const { scrollToEnd, scrollToStart, stateStore } = useMessageScrollerContext()
374
+ const onClickRef = useLatest(onClick)
375
+ const subscribe = React.useCallback(
376
+ (listener: () => void) => stateStore.subscribe(listener),
377
+ [stateStore]
378
+ )
379
+ const getSnapshot = React.useCallback(() => {
380
+ const state = stateStore.getSnapshot()
381
+
382
+ return direction === "start" ? state.start : state.end
383
+ }, [direction, stateStore])
384
+ const isActive = React.useSyncExternalStore(
385
+ subscribe,
386
+ getSnapshot,
387
+ getSnapshot
388
+ )
389
+
390
+ const handleClick = React.useCallback(
391
+ (event: React.MouseEvent<HTMLButtonElement>) => {
392
+ if (!isActive) {
393
+ return
394
+ }
395
+
396
+ onClickRef.current?.(event)
397
+
398
+ if (!event.defaultPrevented) {
399
+ event.currentTarget.blur()
400
+
401
+ if (direction === "start") {
402
+ scrollToStart({ behavior })
403
+ } else {
404
+ scrollToEnd({ behavior })
405
+ }
406
+ }
407
+ },
408
+ [behavior, direction, isActive, onClickRef, scrollToEnd, scrollToStart]
409
+ )
410
+
411
+ return useRender({
412
+ defaultTagName: "button",
413
+ props: mergeProps<"button">(
414
+ {
415
+ type,
416
+ inert: !isActive,
417
+ tabIndex: isActive ? tabIndex : -1,
418
+ children: children ?? <span>Scroll to {direction}</span>,
419
+ onClick: handleClick,
420
+ },
421
+ props
422
+ ),
423
+ render,
424
+ state: {
425
+ active: isActive,
426
+ direction,
427
+ },
428
+ stateAttributesMapping: {
429
+ active: (value) => ({
430
+ "data-active": value ? "true" : "false",
431
+ }),
432
+ },
433
+ })
434
+ }
435
+
436
+ export {
437
+ MessageScroller,
438
+ MessageScrollerButton,
439
+ MessageScrollerContent,
440
+ MessageScrollerItem,
441
+ MessageScrollerProvider,
442
+ MessageScrollerViewport,
443
+ useMessageScroller,
444
+ useMessageScrollerScrollable,
445
+ useMessageScrollerVisibility,
446
+ }