@vvedantb/ui 0.30.1 → 0.30.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.
package/README.md CHANGED
@@ -1196,9 +1196,10 @@ Generic pieces lifted from an app. Components that use `m` need the app's `LazyM
1196
1196
 
1197
1197
  ```tsx
1198
1198
  import {
1199
- ErrorBoundary, ListEnter, useFirstPaintGate, CountPop, countLabel, UnreadDot,
1199
+ ErrorBoundary, ListEnter, useFirstPaintGate, CountPop, countLabel, UnreadDot, RollingNumber,
1200
1200
  MarqueeOnHover, RelativeDateTime, ImageLightbox, ImageGalleryPreview, ScreenshotPreview, VideoPreview,
1201
- useMediaQuery, useDocumentVisible, useIdleCallback, useSingleFlight, usePersistedScrollParent,
1201
+ useMediaQuery, useDocumentVisible, useDocumentAppearance, useIdleCallback, useSingleFlight, usePersistedScrollParent,
1202
+ useCountUpDisplay, parseCountable,
1202
1203
  convexErrorMessage, userFacingErrorMessage, useHeldResult,
1203
1204
  } from "@vvedantb/ui";
1204
1205
  ```
@@ -1206,12 +1207,16 @@ import {
1206
1207
  - `ErrorBoundary` (`fallback` node or `(retry) => node`, `onError`): contains a failure to its subtree; `retry` clears the error.
1207
1208
  - `ListEnter` (`index`, `fast`, `firstPaint`, `staggerStep`, `staggerMax`, `slide`, `as` `div | tr | li`) and `useFirstPaintGate()`: first-paint fade and 8px slide, staggered with `staggerDelay`. Pass `firstPaint={gate.current}` so recycled rows do not restagger.
1208
1209
  - `CountPop` (`label`, `className`, `children`): pop-in and shrink-out for a live count, re-popping on each change. `countLabel(n)` gives `null`, the number or `"99+"`. `UnreadDot` (`show`): a `bg-primary` dot on `CountPop`.
1210
+ - `RollingNumber` (`value`, `className`): shows an already formatted string ("1m 05s", "42%", "$1.20") and rolls each digit to its new value; other characters swap at once. Columns are keyed from the right, so "9s" → "10s" mounts only the new column. The full value stays in an `sr-only` span. For numbers that tick while the user watches; `CountPop` is for a badge that changes while the user looks elsewhere.
1209
1211
  - `MarqueeOnHover`: a single-line label that scrolls its hidden tail into view on hover (or on hover of a `group` ancestor). Import `@vvedantb/ui/tokens/css/marquee.css`; `--mq-delay` sets the dwell.
1210
1212
  - `RelativeDateTime` (`at`, `emptyLabel` default "—", `exactFormat` default "DD/MM/YYYY HH:mm"): "15m" / "2d" with the exact time in a tooltip.
1211
1213
  - `ImageLightbox` (`images`, `index` or `null`, `onIndexChange`, `onClose`): fullscreen viewer with arrow keys, buttons and swipe. `ImageGalleryPreview` (`images`): up to a 2×2 grid with a "+N" tile. `ScreenshotPreview` (`url`, `alt`) and `VideoPreview` (`url`).
1212
- - Hooks: `useMediaQuery(query)`, `useDocumentVisible()`, `useIdleCallback(ms, fn)` (trailing debounce; `createIdleCallback` is the React-free core), `useSingleFlight(fn)` (one call at a time, latest args run next), `usePersistedScrollParent(storageKey)` (restores a container's `scrollTop` from `sessionStorage`).
1214
+ - Hooks: `useMediaQuery(query)`, `useDocumentVisible()`, `useDocumentAppearance()` (`"light" | "dark"` from `<html>`'s `dark` class or `data-theme`; `readDocumentAppearance` / `subscribeDocumentAppearance` are the React-free core), `useIdleCallback(ms, fn)` (trailing debounce; `createIdleCallback` is the React-free core), `useSingleFlight(fn)` (one call at a time, latest args run next), `usePersistedScrollParent(storageKey)` (restores a container's `scrollTop` from `sessionStorage`).
1215
+ - `useCountUpDisplay(value)`: counts a number, or a label with one number ("45%", "12h", "$1.20"), from the last value to the new one over `tokenTransition.base`, keeping the prefix, suffix and decimal places. Where `RollingNumber` rolls each digit, this counts through the numbers between. The first value counts up from 0, and the same amount again does not replay. Labels it cannot count ("1h 12m", "—") show as they are, and so does every value while `PageMotionProvider` is `disabled`. `parseCountable(value)` is the parser: `{ amount, prefix, suffix, decimals }` or `null`.
1213
1216
  - Convex: `convexErrorMessage(error, fallback)` reads `ConvexError` data first; `userFacingErrorMessage(error, fallback)` strips the client envelope and stack. `useHeldResult(result, key)` keeps the last result while a query is skipped (`key` `null`). None of these import `convex`.
1214
1217
 
1218
+ Fixture for `RollingNumber`, `SendQueueIcon`, `PromptInputSubmit` `queued`, the `ActivityTasks` clock and `useCountUpDisplay`: `examples/motion-primitives/`.
1219
+
1215
1220
  ## Chrome extensions (0.28.0)
1216
1221
 
1217
1222
  Extension pages (popup, side panel, options, welcome) run under the MV3 extension-page CSP, which blocks remote font stylesheets, and should not load `@vvedantb/server`. Three pieces cover them. Web apps change nothing unless they opt in.
@@ -1497,6 +1502,7 @@ const config = {
1497
1502
  Outside a `StickToBottom` (for example a page outline) use `JumpRail` with `items` (`{ id, title, preview?, level? }`), a `scrollRef` or `getScrollElement`, and `targetAttribute="data-toc-id"` or `resolveTarget`. `onReveal` runs when a target is not in the DOM; `onBeforeScroll` runs just before it. `onSelect(id)` runs after a click or Enter/Space pick, once the scroll has started or `onReveal` has run, so an app can move focus to the target for keyboard users; `ChatJumpRail` accepts it too. `observeKey` re-observes when the rendered window changes. The geometry helpers (`resolveJumpRailTopPercent`, `resolveJumpRailIndexFromPointer`, `resolveJumpRailHeightStyle`, `resolveJumpRailTickWidthClass`, `resolveJumpRailTickLevelStyle`) are exported.
1498
1503
  - `Message`: `classes.root`, `classes.user`, `classes.assistant` (the role classes of `Message`), `classes.content` (all `MessageContent` classes), `classes.branchSelector`, `classes.branchIcon` (a class in place of the arrows' `size={14}`), and `lazyActionTooltips`: a `MessageAction` mounts its tooltip on first hover or focus (focus opens it), not with the button.
1499
1504
  - `PromptInput`: `classes.group` (the input group, default `overflow-hidden`), `classes.groupIdle` / `classes.groupDragOver` (added while no drag / an accepted drag is over the form), `classes.groupDefault` (added when no `containerClassName` is given), `classes.textarea`, `classes.footer`, `classes.submit`, `classes.tabItem`; `submitIcons.<send|submitted|streaming|error>`, `submitCrossfade` (cross-fade the submit icon on status change) and `menuTriggerAsChild` (`PromptInputActionMenuTrigger` becomes the Radix trigger instead of a button inside it). New `PromptInput` props: `dataDrop` (`{ type, onDrop }`: a non-file drag of that MIME type counts as a drag over the form and `onDrop` gets its string payload) and `inputGroupClassName` (same as `containerClassName`). The attachments context adds `replace(id, file)`; `accept` now matches extension patterns such as `.html` by file name; `useOptionalPromptInputController` is exported.
1505
+ - `PromptInputSubmit`: new prop `queued` (0.30.0). Set it when a send would join a queue (the agent is still working). The send icon becomes `SendQueueIcon`, an up arrow that morphs into a stack of bars while `queued` is `true`. Leave it unset to keep `submitIcons.send`. `SendQueueIcon` (`queued`, `className` default `size-4`) is exported for other send buttons. It uses `m`, so `queued` needs the app's `LazyMotion`.
1500
1506
  - `PromptInputSettings` (new): an overflow menu with a "Model" submenu (one radio list, or a submenu per provider). Entry: `providerLabel(provider)` (default the id), `providerIcon(provider)` (default none), `classes.trigger`.
1501
1507
  - `TraitsPanel` (new, with `isUltrathinkPrompt`, `applyUltrathinkPrefix`): reasoning, speed, context and thinking segments for a model picker; inside a `PromptInputProvider` it offers "Ultrathink" by editing the prompt. Entry: `classes.label`, `classes.empty`, `classes.option`, `classes.optionSelected`, `classes.optionIdle`, `classes.note`.
1502
1508
  - `PromptInputSpeech`, `useSpeechRecognition`, `getSpeechRecognition` (new): Web Speech API dictation; the button renders nothing without the API.
@@ -1518,7 +1524,7 @@ New dependency (installed with the package): `katex`. `streamdown` and the `@str
1518
1524
 
1519
1525
  AI surfaces that came from an app, exported from the root. Fills use `surface-secondary` (`bg-surface-secondary`, `from-surface-secondary/40`), which is the app's `--muted` under `compat-shadcn-rgb.css` and the secondary surface under `tokens.css`. They also use the shadcn colour names `bg-secondary`, `bg-popover` and `bg-card` and a few app utilities (`motion-press`, `smooth-shadow-*`, `scrollbar`, `scrollbar-none`, `text-2xs`, `text-3xs`), so they look as intended with `compat-shadcn-rgb.css` and an app that defines those utilities. They merge a caller `className` with `UiConfig.cn` when set.
1520
1526
 
1521
- - `ActivityTasks` (`steps`, `isStreaming`, `name`, `startedAt`, `duration`, `layout` `folded | inline`, `onOpenFile`, `onRequestFullDetail`): an agent turn as a timeline. Tool runs fold behind one summary line, reasoning and mid-turn text render as Markdown, subtasks nest their steps, long timelines cap behind "Show N more". `OpenSubagentContext` gives subtask rows a "View" link.
1527
+ - `ActivityTasks` (`steps`, `isStreaming`, `name`, `startedAt`, `duration`, `layout` `folded | inline`, `onOpenFile`, `onRequestFullDetail`): an agent turn as a timeline. Tool runs fold behind one summary line, reasoning and mid-turn text render as Markdown, subtasks nest their steps, long timelines cap behind "Show N more". While `isStreaming` and before the first row, a header shows the time since `startedAt` as a `RollingNumber` clock. `OpenSubagentContext` gives subtask rows a "View" link.
1522
1528
  - The step model: `ActivityStep`, `ActivityTodoItem`, `ActivityQuestion`, `ActivityQuestionOption`, `ActivityStepOutput`, `ActivityStepEdit`, `activityStepHasRichDetail`, `activityStepConfig` (glyph and fallback label per step type), `ActivityThinkingIcon`, `useActivitySpinnerVerb`, `getRandomActivityVerb`, `useActivityElapsedSeconds`, `formatActivityElapsed`, `useStreamingDisclosure`.
1523
1529
  - Tool-call details show files with `FileChip` and output in a `CodeBlock` (`plain`) with its copy button, so the `CodeBlock` entry (see "App config: AI chat") styles those frames too.
1524
1530
  - `ActivityQuestionCard` (`questions`, `answers`): the read-only record of a multiple-choice question and its answer.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vvedantb/ui",
3
- "version": "0.30.1",
3
+ "version": "0.30.2",
4
4
  "license": "MIT",
5
5
  "description": "Shared React 19 UI for web apps: one main JavaScript entry (primitives, shell pieces, app helpers including the Convex and Clerk provider, VITE env parsing and ensure-user, artifact viewers over the @vvedantb/server artifacts core, native tokens), a client entry without @vvedantb/server, convex or Clerk for Chrome extensions, design-token CSS, shared Tailwind v4 CSS, a Tailwind preset and packaged Instrument Sans fonts.",
6
6
  "type": "module",
@@ -1,5 +1,12 @@
1
1
  export { useMediaQuery } from "./use-media-query";
2
2
  export { useDocumentVisible } from "./use-document-visible";
3
+ export {
4
+ readDocumentAppearance,
5
+ subscribeDocumentAppearance,
6
+ useDocumentAppearance,
7
+ type DocumentAppearance,
8
+ } from "./use-document-appearance";
3
9
  export { createIdleCallback, useIdleCallback } from "./use-idle-callback";
4
10
  export { useSingleFlight } from "./use-single-flight";
5
11
  export { usePersistedScrollParent } from "./use-persisted-scroll-parent";
12
+ export { parseCountable, useCountUpDisplay } from "./use-count-up-display";
@@ -0,0 +1,80 @@
1
+ import { animate } from "motion/react";
2
+ import { useEffect, useRef, useState } from "react";
3
+ import { useDisablePageMotion } from "../../app/src/page-motion/PageMotionProvider";
4
+ import { motionEase, tokenTransition } from "../motion/presets";
5
+
6
+ /** Suffixes we will count; compound durations like "1h 12m" stay static. */
7
+ const COUNTABLE_SUFFIX = /^(?:%|h|k|m|s|ms)?$/i;
8
+
9
+ /**
10
+ * Splits a label into the number to count and the text around it. A finite
11
+ * number passes through; a string needs one number with an optional prefix
12
+ * ("$", "~") and a suffix of `%`, `h`, `k`, `m`, `s` or `ms`. Anything else
13
+ * (`—`, "1h 12m", "3 of 5") is `null`.
14
+ */
15
+ export function parseCountable(value: string | number): {
16
+ amount: number;
17
+ prefix: string;
18
+ suffix: string;
19
+ decimals: number;
20
+ } | null {
21
+ if (typeof value === "number") {
22
+ if (!Number.isFinite(value)) return null;
23
+ return { amount: value, prefix: "", suffix: "", decimals: 0 };
24
+ }
25
+ const match = value.trim().match(/^(\D*?)(-?\d+(?:\.\d+)?)(\D*)$/);
26
+ if (!match) return null;
27
+ const prefix = match[1] ?? "";
28
+ const raw = match[2] ?? "";
29
+ const suffix = (match[3] ?? "").trim();
30
+ if (!COUNTABLE_SUFFIX.test(suffix)) return null;
31
+ const amount = Number(raw);
32
+ if (!Number.isFinite(amount)) return null;
33
+ const decimals = raw.includes(".") ? (raw.split(".")[1]?.length ?? 0) : 0;
34
+ return { amount, prefix, suffix, decimals };
35
+ }
36
+
37
+ /**
38
+ * Counts from the last seen number to `value` on `--motion-base`
39
+ * (`tokenTransition.base`), keeping the prefix, suffix and decimal places. The
40
+ * first value counts up from 0. The same amount again (a refetch) is a no-op,
41
+ * so the number does not replay on every write. Labels `parseCountable` rejects
42
+ * (`—`, "1h 12m") render as they are, and so does every value while
43
+ * `PageMotionProvider` is `disabled`.
44
+ */
45
+ export function useCountUpDisplay(value: string | number): string | number {
46
+ const parsed = parseCountable(value);
47
+ const [display, setDisplay] = useState(value);
48
+ const lastAmount = useRef<number | null>(null);
49
+ const skipMotion = useDisablePageMotion();
50
+
51
+ useEffect(() => {
52
+ if (skipMotion) {
53
+ lastAmount.current = parsed?.amount ?? null;
54
+ setDisplay(value);
55
+ return;
56
+ }
57
+ if (!parsed) {
58
+ lastAmount.current = null;
59
+ setDisplay(value);
60
+ return;
61
+ }
62
+ if (lastAmount.current === parsed.amount) {
63
+ setDisplay(value);
64
+ return;
65
+ }
66
+ const from = lastAmount.current ?? 0;
67
+ lastAmount.current = parsed.amount;
68
+ const controls = animate(from, parsed.amount, {
69
+ duration: tokenTransition.base.duration,
70
+ ease: motionEase,
71
+ onUpdate: (latest) => {
72
+ const rounded = parsed.decimals > 0 ? latest.toFixed(parsed.decimals) : String(Math.round(latest));
73
+ setDisplay(`${parsed.prefix}${rounded}${parsed.suffix}`);
74
+ },
75
+ });
76
+ return () => controls.stop();
77
+ }, [parsed?.amount, parsed?.prefix, parsed?.suffix, parsed?.decimals, skipMotion, value]);
78
+
79
+ return display;
80
+ }
@@ -0,0 +1,46 @@
1
+ import { useSyncExternalStore } from "react";
2
+
3
+ /** Light or dark, as the page currently draws itself. Neutral is dark-family. */
4
+ export type DocumentAppearance = "light" | "dark";
5
+
6
+ /**
7
+ * Reads the appearance from `<html>`: the `dark` class (Tailwind's convention,
8
+ * set before paint by the app's boot script) or `data-theme="dark"`.
9
+ *
10
+ * Use this rather than a theme context when code can run outside the app's
11
+ * theme provider (a signed-out marketing page, a canvas effect): the class is
12
+ * the one source every page shares.
13
+ */
14
+ export function readDocumentAppearance(): DocumentAppearance {
15
+ const root = document.documentElement;
16
+ return root.classList.contains("dark") ||
17
+ root.getAttribute("data-theme") === "dark"
18
+ ? "dark"
19
+ : "light";
20
+ }
21
+
22
+ /** Calls `onChange` whenever `<html>`'s class or `data-theme` changes. */
23
+ export function subscribeDocumentAppearance(onChange: () => void): () => void {
24
+ const observer = new MutationObserver(onChange);
25
+ observer.observe(document.documentElement, {
26
+ attributes: true,
27
+ attributeFilter: ["class", "data-theme"],
28
+ });
29
+ return () => observer.disconnect();
30
+ }
31
+
32
+ function readServerAppearance(): DocumentAppearance {
33
+ return "light";
34
+ }
35
+
36
+ /**
37
+ * The page's appearance, re-rendering when it changes. Server snapshot is
38
+ * `"light"`, matching a page with no `dark` class.
39
+ */
40
+ export function useDocumentAppearance(): DocumentAppearance {
41
+ return useSyncExternalStore(
42
+ subscribeDocumentAppearance,
43
+ readDocumentAppearance,
44
+ readServerAppearance,
45
+ );
46
+ }
@@ -1,6 +1,10 @@
1
1
  import type { MermaidConfig } from "@streamdown/mermaid";
2
2
  import { useSyncExternalStore } from "react";
3
3
  import type { DiagramPlugin } from "streamdown";
4
+ import {
5
+ readDocumentAppearance,
6
+ subscribeDocumentAppearance,
7
+ } from "../hooks/use-document-appearance";
4
8
 
5
9
  /**
6
10
  * Mermaid for markdown, loaded on first use. `@streamdown/mermaid` imports
@@ -102,18 +106,9 @@ function subscribe(key: string, notify: () => void): () => void {
102
106
  };
103
107
  }
104
108
 
105
- /** The app theme lives as a `dark` class on `<html>` (neutral is dark-family). */
109
+ /** Mermaid's theme for the page's current appearance (neutral is dark-family). */
106
110
  function readTheme(): MermaidTheme {
107
- return document.documentElement.classList.contains("dark") ? "dark" : "default";
108
- }
109
-
110
- function subscribeTheme(notify: () => void): () => void {
111
- const observer = new MutationObserver(notify);
112
- observer.observe(document.documentElement, {
113
- attributes: true,
114
- attributeFilter: ["class"],
115
- });
116
- return () => observer.disconnect();
111
+ return readDocumentAppearance() === "dark" ? "dark" : "default";
117
112
  }
118
113
 
119
114
  /**
@@ -145,7 +140,7 @@ export function useMermaidRender(
145
140
  code: string,
146
141
  enabled: boolean,
147
142
  ): { theme: MermaidTheme; status: Entry["status"] } {
148
- const theme = useSyncExternalStore(subscribeTheme, readTheme);
143
+ const theme = useSyncExternalStore(subscribeDocumentAppearance, readTheme);
149
144
  const key = enabled ? cacheKey(theme, code) : "";
150
145
  const entry = useSyncExternalStore(
151
146
  (notify) => (key === "" ? () => {} : subscribe(key, notify)),
@@ -1,5 +1,7 @@
1
1
  /** transitions.dev input clear with dissolve — see 13-input-clear-dissolve.md */
2
2
 
3
+ import { readDocumentAppearance } from "../hooks/use-document-appearance";
4
+
3
5
  // Times come back in ms. CSS minifiers rewrite `1000ms` as `1s`, so a value
4
6
  // in seconds is converted rather than read as 1.
5
7
  export function readCssNumber(
@@ -53,13 +55,6 @@ export function readCssEase(root: HTMLElement, name: string): (t: number) => num
53
55
  };
54
56
  }
55
57
 
56
- function isDarkTheme(root: HTMLElement): boolean {
57
- return (
58
- root.classList.contains("dark") ||
59
- root.getAttribute("data-theme") === "dark"
60
- );
61
- }
62
-
63
58
  function measureCanvas(): CanvasRenderingContext2D | null {
64
59
  const canvas = document.createElement("canvas");
65
60
  return canvas.getContext("2d");
@@ -93,7 +88,7 @@ function buildGlowBackground(
93
88
  return "";
94
89
  }
95
90
  canvas.font = getComputedStyle(input).font;
96
- const dark = isDarkTheme(root);
91
+ const dark = readDocumentAppearance() === "dark";
97
92
  const rgb = dark ? "255,255,255" : "0,0,0";
98
93
  const width = wrap.clientWidth || 280;
99
94
  const padLeft = parseFloat(getComputedStyle(input).paddingLeft) || 12;