@vvedantb/ui 0.12.0 → 0.13.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/README.md CHANGED
@@ -4,7 +4,7 @@ Shared React 19 web UI. Source-exported: no build step.
4
4
 
5
5
  | Import | What it is |
6
6
  | --- | --- |
7
- | `@vvedantb/ui` | The only JavaScript entry. Primitives (Radix-based), AI elements, audio (`playChime`, `useReplyChime`, `playTone`), `toast` and `SonnerToaster`, the composer (`InputArea`, deprecated 0.3 `Composer`), shell (`SidebarHeader`, `PillTabs`, `SessionsHoverCard`, and the app shell: `AppShell`, `AppSidebar`, `SidebarRail`, `RailTile`, `SidebarPanel`, `SidebarAccountMenu`, `SignOutDialog` and related helpers), app helpers (confirm skip, update watcher, settings chrome, `useStableAuth`, and from 0.8.0 `createThemeProvider`, `createPageTitleContext`, `PageMotionProvider` and `formatCompactRelativeTime`), marketing pieces from 0.9.0 (`createLandingKit` and the `Landing*` parts, `SiteFooter`, `PricingModal`), animated nav icons from 0.11.0 (`MemoryIcon`, `BoardIcon`, ... and `NavIconBase`; `SettingsIcon` `variant` from 0.12.0), `cn`, and the native tokens `tokens` and `Tokens`. See `app/README.md` in the repository for the app helpers. |
7
+ | `@vvedantb/ui` | The only JavaScript entry. Primitives (Radix-based), AI elements, audio (`playChime`, `useReplyChime`, `playTone`), `toast` and `SonnerToaster`, the composer (`InputArea`, deprecated 0.3 `Composer`), shell (`SidebarHeader`, `PillTabs`, `SessionsHoverCard`, and the app shell: `AppShell`, `AppSidebar`, `SidebarRail`, `RailTile`, `SidebarPanel`, `SidebarAccountMenu`, `SignOutDialog` and related helpers), app helpers (confirm skip, update watcher, settings chrome, `useStableAuth`, and from 0.8.0 `createThemeProvider`, `createPageTitleContext`, `PageMotionProvider` and `formatCompactRelativeTime`), marketing pieces from 0.9.0 (`createLandingKit` and the `Landing*` parts, `SiteFooter`, `PricingModal`), animated nav icons from 0.11.0 (`MemoryIcon`, `BoardIcon`, ... and `NavIconBase`; `SettingsIcon` `variant` from 0.12.0), artifact viewers from 0.13.0 (`ArtifactFrame`, `ArtifactList`, `ArtifactViewer`, ...), `cn`, and the native tokens `tokens` and `Tokens`. See `app/README.md` in the repository for the app helpers. |
8
8
  | `@vvedantb/ui/tokens` | `tokens.css`: colour, radius, shadow, ease and font tokens for Tailwind v4. CSS. |
9
9
  | `@vvedantb/ui/tokens/tokens.css` | Same file as `@vvedantb/ui/tokens`. CSS. |
10
10
  | `@vvedantb/ui/tokens/css/*.css` | `index`, `base`, `dialog`, `modal`, `tabs`, `tabs-pills`, `utilities`, `scrollbar-thin`, `animations`, `nav-icons`, `compat-shadcn-rgb`. CSS. |
@@ -936,6 +936,55 @@ Props (type `IconProps`; all optional):
936
936
 
937
937
  Other SVG props (`id`, `data-*`, handlers, `ref`) go to the svg. On group hover the svg scales to 1.15 (the first six icons, spring ease) or 1.12 (the rest). `NavIconBase` is the shared svg wrapper, for icons drawn in the same style. The stylesheet has no reduced-motion override.
938
938
 
939
+ ## Artifact viewers (0.13.0)
940
+
941
+ Web viewers for artifacts: standalone HTML, Markdown, SVG, code or typed JSON (quiz, flashcards) documents with per-user state. The pure core (schemas, state limits and ops, the document wrapper, the guest bridge) lives in `@vvedantb/server` (see its `docs/artifacts.md`); install `@vvedantb/server` 0.6.1 or later next to this package. The components hold no data: rows come in through props and changes leave through callbacks, so any backend works.
942
+
943
+ ```tsx
944
+ import { ArtifactList, ArtifactListToolbar, ArtifactViewer, type ArtifactStateStore } from "@vvedantb/ui";
945
+
946
+ <ArtifactListToolbar query={query} onQueryChange={setQuery} type={type} onTypeChange={setType} layout={layout} onLayoutChange={setLayout} />
947
+ <ArtifactList
948
+ artifacts={rows}
949
+ layout={layout}
950
+ getHref={(a) => `/artifacts/${a.id}`}
951
+ onOpen={(a) => navigate(a.id)}
952
+ getBody={(a) => fetchBody(a.id)}
953
+ onRename={(a, title) => rename(a.id, title)}
954
+ onDelete={(a) => remove(a.id)}
955
+ />
956
+
957
+ const store: ArtifactStateStore = {
958
+ load: async () => (await getState(id))?.data ?? {},
959
+ save: (data) => putState({ id, sets: data, reset: true }),
960
+ onError: (error) => toast.error(error.message),
961
+ };
962
+ <ArtifactViewer
963
+ artifact={detail}
964
+ store={store}
965
+ stateGlobalAliases={["app"]}
966
+ versions={history}
967
+ viewingVersion={version}
968
+ onViewVersion={setVersion}
969
+ onRestoreVersion={(v) => restore(id, v)}
970
+ href={`/artifacts/${id}`}
971
+ headerStart={<BackLink />}
972
+ onRename={(title) => rename(id, title)}
973
+ onDelete={() => remove(id)}
974
+ />
975
+ ```
976
+
977
+ - `ArtifactFrame`: the body in an iframe with `sandbox="allow-scripts"` (never `allow-same-origin`) and the CSP from `wrapArtifactDocument`. Props `body`, `format`, `title` (the iframe name, and a template's heading), `template` (`stateSpec.template`), `store`, `stateGlobalAliases`, `saveDelayMs` (5 s) and `saveMaxWaitMs` (30 s); other iframe props pass through. It calls `store.load()` once per document and writes the snapshot into the `srcdoc`, answers the guest's `window.artifactState` requests over a `MessageChannel` with the core's ops and limits, and calls `store.save(data)` with the whole map (replace, not merge) after the debounce, on `pagehide`, when the page is hidden and on unmount. A reload waits for a save in flight. If `load` fails, the frame starts empty and never saves, so it cannot overwrite stored state; `store.onError(error, "load" | "save")` hears about failures. Without a store, state lives until unmount. Keep `store` stable per artifact (a new object reloads the frame); a new `stateGlobalAliases` array with the same names does not.
978
+ - `ArtifactStateStore`: `{ load(): Promise<Record<string, string>>, save(data): Promise<void>, onError?(error, phase) }`.
979
+ - `ArtifactRender`: the body by format. Markdown renders with Streamdown, code with `CodeBlock` (`language`), and HTML, SVG and JSON in an `ArtifactFrame`.
980
+ - `ArtifactCard`: a grid tile (type icon, title, description, compact updated time) or a `layout="list"` row. With `getHref` it is an `<a>`; a plain left click then calls `onOpen` instead of following the link, and modified clicks stay native. The actions menu (dots button and right-click) lists Open (`onOpen`), Open in new tab (`getHref`), Rename (`onRename`), Copy and Download (`getBody`, since list rows carry no body) and Delete (`onDelete`). Each shows only when its callback is set; with none, there is no menu.
981
+ - `ArtifactList`: `ArtifactCard`s in a grid (one to three columns) or a list, with the card callbacks passed through. With no artifacts it shows an `EmptyState` (`emptyTitle`, `emptyDescription`, `emptyActions`).
982
+ - `ArtifactListToolbar`: controlled `ToolbarSearchInput` (`query`, `onQueryChange`), a type filter menu (`type`, `onTypeChange`, `types`; `undefined` is "All types") and a grid or list toggle (`layout`, `onLayoutChange`). The filter and the toggle show only with their callbacks. `children` go at the end.
983
+ - `ArtifactViewer`: the ai-elements `Artifact` container with a header (`headerStart`, type icon, title) and actions: versions menu (`versions`), Rename, Copy, Download (the format's extension and MIME type from `ARTIFACT_FORMAT_FILES`), Open in new tab (`href`), your `actions`, and Delete. Below it, `ArtifactRender` of `artifact.body`. Pass the body of the version on screen.
984
+ - `ArtifactVersionsMenu`: a "vN" button listing `versions` newest first, with the current one marked. With `onViewVersion`, picking a version shows it, and "Restore vN" (`onRestoreVersion`) appears while an older version is on screen. Without it, picking an older version restores it.
985
+ - Rename and delete use `ConfirmDialog` (`ArtifactRenameDialog`, `ArtifactDeleteDialog`, and `useArtifactEditDialogs` for custom surfaces). Rename sends the trimmed title, and does nothing when it is unchanged. Alt-click on Delete skips the dialog, as with `useRequestConfirm`. A callback that rejects keeps its dialog open and shows an error toast; copy and load failures toast too, so mount `SonnerToaster`.
986
+ - `ArtifactTypeIcon` (`type`, `size`, `stroke`) and `ARTIFACT_TYPE_LABELS` (`mindmap` is "Mind map"). Helpers `downloadArtifactBody(title, format, body)`, `copyArtifactBody(body)`, `openArtifactInNewTab(href)`. Row types: `ArtifactSummary` (any `ArtifactListRow` fits), `ArtifactDocument`, `ArtifactVersionSummary`.
987
+
939
988
  ## Toaster
940
989
 
941
990
  ```tsx
@@ -999,6 +1048,6 @@ The compat file includes a fallback `glass-panel-strong` (`rgb(var(--card) / 0.9
999
1048
 
1000
1049
  A fixture that renders the main components against sample light and dark RGB variables is in `tokens/examples/compat-shadcn-rgb/`.
1001
1050
 
1002
- `@clerk/clerk-react`, `convex`, `@tanstack/react-hotkeys`, `motion` and `zod` are optional peers (`peerDependenciesMeta`), so the package manager does not install or warn about them. The root still imports each of them statically from some module (`useStableAuth` and `ConvexClerkProvider` import Clerk; `ConvexClerkProvider` and `useEnsureUser` import `convex/react`; the motion presets, `ConfirmSkipHint` and others import the rest). So an app that imports `@vvedantb/ui` must have all five resolvable, even if it uses none of those exports: a bundler resolves every import before it tree-shakes. `app/tests-node/convex-esm.test.mjs` pins which root modules import `convex` and Clerk.
1051
+ `@clerk/clerk-react`, `convex`, `@tanstack/react-hotkeys`, `motion`, `zod` and `@vvedantb/server` (0.13.0) are optional peers (`peerDependenciesMeta`), so the package manager does not install or warn about them. The root still imports each of them statically from some module (`useStableAuth` and `ConvexClerkProvider` import Clerk; `ConvexClerkProvider` and `useEnsureUser` import `convex/react`; the artifact viewers import `@vvedantb/server`; the motion presets, `ConfirmSkipHint` and others import the rest). So an app that imports `@vvedantb/ui` must have all six resolvable, even if it uses none of those exports: a bundler resolves every import before it tree-shakes. `app/tests-node/convex-esm.test.mjs` pins which root modules import `convex` and Clerk, and `app/tests-node/artifacts-esm.test.mjs` which import `@vvedantb/server`.
1003
1052
 
1004
1053
  Full documentation: the repository `README.md`. Upgrading from `@vvedantb/tokens`, `@vvedantb/shell` or `@vvedantb/app-kit`: `MIGRATION.md`.
package/app/README.md ADDED
@@ -0,0 +1,259 @@
1
+ # App helpers (`@vvedantb/ui`)
2
+
3
+ Shared web React helpers that were duplicated across apps. Source-exported as the `./app` subpath of `@vvedantb/ui`.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @vvedantb/ui
9
+ ```
10
+
11
+ ## Peers
12
+
13
+ Required: `react` and `react-dom` (>=19). Optional peers of `@vvedantb/ui` used by the app helpers: `@clerk/clerk-react` (`useStableAuth`, `ConvexClerkProvider`), `convex` (`ConvexClerkProvider`, `useEnsureUser`), `@tanstack/react-hotkeys` and `zod` (your `z` for `parseClientEnv`). The root imports Clerk and `convex/react` statically, so they must be installed even if you do not use these helpers; see the package README.
14
+
15
+ `sonner` is not a dependency. The update watcher takes the toast API as an option. The app source uses a local class join, which the root does not export (the root `cn` is the clsx and tailwind-merge one). Tailwind must scan `node_modules/@vvedantb/ui/app/src/**/*.{ts,tsx}` so the class names are generated, and the app needs the `@vvedantb/ui/tokens` names (`bg-surface-card`, `divide-separator`, `text-muted-foreground` and so on).
16
+
17
+ ```css
18
+ @source "../node_modules/@vvedantb/ui/app/src/**/*.{ts,tsx}";
19
+ ```
20
+
21
+ ## Confirm skip (Alt-click)
22
+
23
+ ```tsx
24
+ import { ConfirmSkipHint, skipConfirmTitle, useRequestConfirm } from "@vvedantb/ui";
25
+
26
+ const { request } = useRequestConfirm();
27
+
28
+ <DropdownMenuItem
29
+ title={skipConfirmTitle("Delete")}
30
+ onSelect={(event) => request(() => setOpen(true), () => remove(), event)}
31
+ >
32
+ Delete <ConfirmSkipHint />
33
+ </DropdownMenuItem>
34
+ ```
35
+
36
+ - `useRequestConfirm` does not subscribe to Alt. It reads `getAltHeld()` when the request happens, so the menu owner does not re-render when Alt goes down. It returns `{ request }` only.
37
+ - `ConfirmSkipHint` stays mounted and gains a `hidden` class when Alt is not held, so an open Radix menu keeps a stable child tree.
38
+ - The Alt store resets when the last subscriber leaves, clears on blur and tab hide, and cancels a bare Alt keydown only inside `[role='menu']` or `[data-radix-menu-content]`.
39
+ - Also exported: `useAltHeld`, `getAltHeld`, `createAltHeldStore`, `bindToWindow`, `shouldSkipConfirm`, `requestConfirm`.
40
+
41
+ ## Update available watcher
42
+
43
+ ```ts
44
+ import { toast } from "sonner";
45
+ import { startUpdateAvailableWatcher } from "@vvedantb/ui";
46
+
47
+ useEffect(
48
+ () =>
49
+ startUpdateAvailableWatcher({
50
+ origin: window.location.origin,
51
+ toast,
52
+ closeConvex: () => void convex.close(),
53
+ enabled: !import.meta.env.DEV,
54
+ }),
55
+ [],
56
+ );
57
+ ```
58
+
59
+ Options: `origin`, `toast`, `closeConvex?`, `pollMs?` (default 60000), `toastId?` (default `app-update-available`), `enabled?` (default true), `reload?` (default `window.location.reload`). On a changed asset fingerprint it shows a sticky "Update available" toast. Refresh calls `closeConvex` (errors ignored), then reloads. `fingerprintFromHtml` and `fetchDeployFingerprint` are exported too. The fingerprint looks for Vite `/assets/*.js` URLs in the index HTML.
60
+
61
+ ## Settings chrome
62
+
63
+ ```tsx
64
+ import { SettingsPage, SettingsSection, SettingsToggleRow } from "@vvedantb/ui";
65
+
66
+ <SettingsPage
67
+ title="Notifications"
68
+ layout={({ title, headerRight, toolbar, tabs, fillHeight, children }) => (
69
+ <PageContainer title={title} rightSection={headerRight} toolbar={toolbar} tabs={tabs} noScroll={fillHeight}>
70
+ {children}
71
+ </PageContainer>
72
+ )}
73
+ >
74
+ <SettingsSection title="Email" bodyVariant="list">
75
+ <SettingsToggleRow title="Weekly digest" action={<Switch />} />
76
+ </SettingsSection>
77
+ </SettingsPage>
78
+ ```
79
+
80
+ Exports: `SettingsSection`, `SettingsField`, `SettingsStack`, `SettingsToggleRow`, `SettingsEmptyState` (icon is `ComponentType<{ size?: number; className?: string }>`), `SettingsPage`. `SettingsField` `layout`: `"stacked"` (default) puts the label above the control. `"horizontal"` renders one row with the label and description on the left and the control on the right. Without `layout`, `SettingsPage` renders a plain `div` with a heading and the optional slots.
81
+
82
+ ## useStableAuth
83
+
84
+ ```ts
85
+ import { useStableAuth } from "@vvedantb/ui"; // 2000 ms debounce, wraps Clerk useAuth
86
+ import { createUseStableAuth } from "@vvedantb/ui";
87
+
88
+ const useAuth = createUseStableAuth(useClerkAuth, { debounceMs: 3000 });
89
+ ```
90
+
91
+ After a signed-in session, a drop to signed-out reports `isLoaded: false` for the debounce window so Convex does not cascade. State is module-level. `resetStableAuthSession()` clears it and is for tests only.
92
+
93
+ ## Develop
94
+
95
+ ```sh
96
+ pnpm --filter @vvedantb/ui typecheck
97
+ pnpm --filter @vvedantb/ui test
98
+ ```
99
+
100
+ Source is in `app/src` and tests in `app/tests`. Publish steps are in the root `README.md`.
101
+
102
+ ## Theme
103
+
104
+ ```tsx
105
+ import { createThemeProvider } from "@vvedantb/ui";
106
+
107
+ // One kit per app, at module level.
108
+ export const { ThemeProvider, useTheme } = createThemeProvider();
109
+
110
+ <ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
111
+ <App />
112
+ </ThemeProvider>;
113
+
114
+ const { theme, resolvedTheme, setTheme, isDark, toggleTheme, mounted } = useTheme();
115
+ ```
116
+
117
+ `createThemeProvider` is a port of next-themes 0.4.6. An app that uses next-themes can switch without a change in behaviour: the same localStorage writes, `<html>` classes and attributes, `style.colorScheme`, `prefers-color-scheme` listener, cross-tab `storage` sync and transition blocking. Parity tests run both side by side.
118
+
119
+ - Props, as in next-themes: `storageKey` (`"theme"`), `defaultTheme` (`"system"` with `enableSystem`, else `"light"`), `enableSystem` (`true`), `enableColorScheme` (`true`), `attribute` (`"data-theme"`; `"class"`, any `data-*`, or an array), `themes` (`["light", "dark"]`), `value` (theme name to written value), `forcedTheme`, `disableTransitionOnChange` (`false`) and `nonce`.
120
+ - State: `theme`, `setTheme` (a value or a function of the current theme), `resolvedTheme`, `systemTheme`, `forcedTheme` and `themes`, as in next-themes. Added: `mounted` (after the provider's first effect), `isDark` (`mounted && resolvedTheme === "dark"`) and `toggleTheme` (from `resolvedTheme`).
121
+ - `setTheme` is a new function each time `theme` changes and stable otherwise, as in next-themes, so effects that list it re-run at the same times.
122
+ - next-themes reads the DOM options (`attribute`, `themes`, `value`, `enableSystem`, `enableColorScheme`, `defaultTheme`, `disableTransitionOnChange`, `nonce`) once, on the first render, and so does this port. If `enableSystem` starts `false` and later turns `true`, a stored `"system"` is written as the class `system`. `forcedTheme` follows props.
123
+ - A nested `ThemeProvider` from the same kit renders only its children.
124
+ - `createThemeProvider({ missingProviderMessage })`: `useTheme()` outside the provider throws that message. Without it, `useTheme()` returns an empty state with no-op setters, as next-themes does.
125
+ - No inline script is rendered. next-themes renders one for server rendering; React does not run it in a client-rendered app. Keep a pre-paint script in `index.html` if the app has one.
126
+
127
+ For an app with its own theme state (for example a theme synced from the server), two helpers:
128
+
129
+ - `getSystemTheme()`: `"dark"` or `"light"` from `prefers-color-scheme`; `"light"` without `window`.
130
+ - `applyThemeClass(theme)`: removes `light` and `dark` from `<html>`, then adds `theme`. No-op without `document`.
131
+
132
+ ## Page title
133
+
134
+ ```tsx
135
+ import { createPageTitleContext } from "@vvedantb/ui";
136
+
137
+ export const { PageTitleProvider, usePageTitle, usePageTitleSync } = createPageTitleContext({
138
+ missingProviderMessage: "usePageTitle must be used within a PageTitleProvider",
139
+ });
140
+
141
+ // The shell reads it:
142
+ const { pageTitle } = usePageTitle();
143
+ // A page publishes it while mounted:
144
+ usePageTitleSync(title);
145
+ ```
146
+
147
+ - `usePageTitle()` returns `{ pageTitle, setPageTitle, mobileActionsSlot, setMobileActionsSlot }`. `mobileActionsSlot` is an element a mobile top bar registers (pass `setMobileActionsSlot` as its `ref`) so pages can portal actions into it.
148
+ - `usePageTitleSync(title)` sets the title while the caller is mounted and clears it on unmount. Titles that are not strings publish `""`.
149
+ - `missingProviderMessage`: `usePageTitle()` outside the provider throws it. Without it, `usePageTitle()` returns an empty title and no-op setters.
150
+ - `documentTitle` (off by default; without it `document.title` is never touched): `{ suffix?, separator? = " · ", fallback? }`. While a page title is set, `document.title` is `` `${pageTitle}${separator}${suffix}` `` (just the page title without a suffix). While it is empty, `fallback`, else the title at mount. The mount-time title comes back on unmount.
151
+
152
+ ## Page motion
153
+
154
+ ```tsx
155
+ import { MotionConfig } from "motion/react";
156
+ import { PageMotionProvider, useDisablePageMotion } from "@vvedantb/ui";
157
+
158
+ <PageMotionProvider disabled={flags?.disablePageMotion === true} motionConfig={MotionConfig}>
159
+ <App />
160
+ </PageMotionProvider>;
161
+ ```
162
+
163
+ - Sets `html[data-page-motion]` to `"off"` or `"on"` in a layout effect (CSS can skip page and route transitions on `"off"`). The attribute stays after unmount.
164
+ - Renders `motionConfig` with `reducedMotion` `"always"` when disabled, else `"never"`.
165
+ - `useDisablePageMotion()`: the `disabled` value, `false` outside the provider.
166
+ - This module does not import `motion`. Pass `MotionConfig`, or an app component that wraps it, defined at module level, for example with `LazyMotion`:
167
+
168
+ ```tsx
169
+ function LazyMotionConfig({ reducedMotion, children }: PageMotionConfigProps) {
170
+ return (
171
+ <LazyMotion features={domAnimation}>
172
+ <MotionConfig reducedMotion={reducedMotion}>{children}</MotionConfig>
173
+ </LazyMotion>
174
+ );
175
+ }
176
+ ```
177
+
178
+ ## Compact relative time
179
+
180
+ ```ts
181
+ import { formatCompactRelativeTime } from "@vvedantb/ui";
182
+
183
+ formatCompactRelativeTime(createdAt, { justNow: "now" }); // "now", "5m", "3h", "2d", "4mo", "1y"
184
+ formatCompactRelativeTime(updatedAt, { calendar: true }); // "42s", ..., calendar months and years
185
+ ```
186
+
187
+ Pure TypeScript, no dependencies. Options:
188
+
189
+ - `now`: clock in ms, default `Date.now()`.
190
+ - `justNow`: returned for anything under a minute old, future times included. Without it the result is whole seconds (`"42s"`), and a future time gives `"0s"` or a negative count.
191
+ - `calendar`: `false` (default) counts elapsed time: a day is 24 hours, a month 30 days, a year 12 such months. `true` counts as `dayjs().diff(date, unit)` does: days by the local calendar across DST changes, and calendar months and years.
192
+
193
+ Strings are parsed with `new Date(string)`. dayjs parses a date-only string such as `"2026-03-01"` as local midnight, `new Date` as UTC midnight; numbers, `Date` objects and ISO strings with a time give the same result either way. An invalid date gives `"NaNy"` (`"0mo"` with `calendar`).
194
+
195
+ ## Convex provider, VITE env and ensure-user (0.10.0)
196
+
197
+ React and VITE env helpers for Convex apps. The non-React Convex helpers (`mapLoadedQuery`, `forEachLoadedQuery`, `updateAllCachedQueries`, `patchLoadedQuery`, `OptimisticStore`, `tempId`, `createMemoryOptimisticStore`) live in `@vvedantb/server`, so backend packages, tests and React Native can use them without loading this package.
198
+
199
+ ### `ConvexClerkProvider`
200
+
201
+ ```tsx
202
+ import { ConvexClerkProvider, useStableAuth } from "@vvedantb/ui";
203
+ import { ConvexReactClient } from "convex/react";
204
+
205
+ const convex = new ConvexReactClient(env.VITE_CONVEX_URL);
206
+
207
+ <ClerkProvider publishableKey={env.VITE_CLERK_PUBLISHABLE_KEY}>
208
+ <ConvexClerkProvider client={convex} useAuth={useStableAuth}>
209
+ <App />
210
+ </ConvexClerkProvider>
211
+ </ClerkProvider>;
212
+ ```
213
+
214
+ | Props | Renders |
215
+ | --- | --- |
216
+ | `client` is `null` or `undefined` | `children` alone (no provider). |
217
+ | `clerk={false}` | `<ConvexProvider client={client}>`. |
218
+ | otherwise | `<ConvexProviderWithClerk client={client} useAuth={useAuth}>`; `useAuth` defaults to `@clerk/clerk-react`'s. |
219
+
220
+ `clerk` defaults to `true`. Render it inside `ClerkProvider` unless `clerk` is `false`. Types: `ConvexClerkProviderProps`, `ConvexClerkUseAuth`.
221
+
222
+ ### `parseClientEnv`
223
+
224
+ ```ts
225
+ import { z } from "zod";
226
+ import { parseClientEnv } from "@vvedantb/ui";
227
+
228
+ export const clientEnv = parseClientEnv(import.meta.env, { z, viteEnv: "fallback" });
229
+ // { VITE_CONVEX_URL: string; VITE_CLERK_PUBLISHABLE_KEY: string; VITE_ENV: "development" | "staging" | "production" }
230
+
231
+ export const extensionEnv = parseClientEnv(import.meta.env, {
232
+ z,
233
+ viteEnv: false,
234
+ extend: { VITE_CLERK_SYNC_HOST: z.string().url() },
235
+ });
236
+ ```
237
+
238
+ The schema is `z.object({ VITE_CONVEX_URL: z.string().min(1), VITE_CLERK_PUBLISHABLE_KEY: z.string().min(1), VITE_ENV: z.enum(["development", "staging", "production"]), ...extend })`, built with your `z` (zod 3.25+ or 4; the package never imports zod at runtime). Only the schema's keys are read from `rawEnv`. Failure throws the `ZodError` from `.parse`.
239
+
240
+ | `viteEnv` | `VITE_ENV` |
241
+ | --- | --- |
242
+ | `"strict"` (default) | Must be one of `VITE_ENV_NAMES`. |
243
+ | `"fallback"` | Any other value, or none, becomes `"development"` before parsing. |
244
+ | `false` | Not in the schema or the result. |
245
+
246
+ Types: `ClientEnv`, `ClientEnvWithoutViteEnv`, `ClientEnvOptions`, `ClientEnvSource`, `ViteEnvMode`, `ViteEnvName`.
247
+
248
+ ### `useEnsureUser`
249
+
250
+ ```tsx
251
+ function EnsureUser() {
252
+ useEnsureUser(api.users.ensureUserExists);
253
+ return null;
254
+ }
255
+ ```
256
+
257
+ Calls `mutation({})` every time `useConvexAuth().isAuthenticated` becomes `true` (once on mount if already signed in), and logs a rejection with `console.error`. Needs a Convex auth provider above it (`ConvexClerkProvider` with Clerk on). Pair it with `ensureUser` from `@vvedantb/server`. Type: `EnsureUserMutation`.
258
+
259
+ Tests: `app/tests/convex/` ports each app's copy and runs it beside the helper (env with zod 4 and zod 3.25; provider variants; ensure-user calls over auth sequences). `app/tests-node/convex-esm.test.mjs` loads the helpers in plain Node.
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@vvedantb/ui",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "license": "MIT",
5
- "description": "Shared React 19 UI for web apps: one JavaScript entry (primitives, shell pieces, app helpers including the Convex and Clerk provider, VITE env parsing and ensure-user, native tokens), design-token CSS, shared Tailwind v4 CSS and a Tailwind preset.",
5
+ "description": "Shared React 19 UI for web apps: one 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), design-token CSS, shared Tailwind v4 CSS and a Tailwind preset.",
6
6
  "type": "module",
7
7
  "publishConfig": {
8
8
  "access": "public"
@@ -55,6 +55,15 @@
55
55
  "./src/ui/sonner.css",
56
56
  "./src/marketing/landing.css"
57
57
  ],
58
+ "scripts": {
59
+ "check:tokens": "node tokens/scripts/check-component-tokens.mjs",
60
+ "build": "node tokens/scripts/check-exports.mjs && node tokens/scripts/check-component-tokens.mjs && tsc -p tsconfig.json",
61
+ "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.consumer.json && tsc -p tokens/tsconfig.json",
62
+ "test": "node tokens/scripts/check-component-tokens.mjs && vitest run && node --test tokens/test/*.test.mjs app/tests-node/*.test.mjs",
63
+ "verify": "node tokens/scripts/check-component-tokens.mjs && node tokens/verify/run.mjs",
64
+ "analyze": "node tokens/verify/analyze.mjs",
65
+ "prepack": "node tokens/scripts/check-exports.mjs"
66
+ },
58
67
  "peerDependencies": {
59
68
  "@clerk/clerk-react": ">=5",
60
69
  "@radix-ui/react-accordion": "^1.2.12",
@@ -82,6 +91,7 @@
82
91
  "@streamdown/mermaid": "*",
83
92
  "@tabler/icons-react": "^3.35.0",
84
93
  "@tanstack/react-hotkeys": "*",
94
+ "@vvedantb/server": ">=0.6.1",
85
95
  "ai": ">=5.0.0",
86
96
  "class-variance-authority": "^0.7.1",
87
97
  "clsx": "^2.1.1",
@@ -131,6 +141,7 @@
131
141
  "@tanstack/react-hotkeys": "^0.13.0",
132
142
  "@types/react": "^19.1.0",
133
143
  "@types/react-dom": "^19.1.0",
144
+ "@vvedantb/server": "workspace:*",
134
145
  "ai": "^5.0.0",
135
146
  "class-variance-authority": "^0.7.1",
136
147
  "clsx": "^2.1.1",
@@ -172,14 +183,9 @@
172
183
  },
173
184
  "zod": {
174
185
  "optional": true
186
+ },
187
+ "@vvedantb/server": {
188
+ "optional": true
175
189
  }
176
- },
177
- "scripts": {
178
- "check:tokens": "node tokens/scripts/check-component-tokens.mjs",
179
- "build": "node tokens/scripts/check-exports.mjs && node tokens/scripts/check-component-tokens.mjs && tsc -p tsconfig.json",
180
- "typecheck": "tsc -p tsconfig.json && tsc -p tokens/tsconfig.json",
181
- "test": "node tokens/scripts/check-component-tokens.mjs && vitest run && node --test tokens/test/*.test.mjs app/tests-node/*.test.mjs",
182
- "verify": "node tokens/scripts/check-component-tokens.mjs && node tokens/verify/run.mjs",
183
- "analyze": "node tokens/verify/analyze.mjs"
184
190
  }
185
- }
191
+ }
@@ -5,21 +5,16 @@ import { Button } from "../ui/button";
5
5
  import { Spinner } from "../ui/spinner";
6
6
  import { cn } from "../utils/cn";
7
7
  import { useEffect, useRef, useState } from "react";
8
- interface SpeechRecognition extends EventTarget {
8
+ // Only the members this component uses, so an app's own (wider or narrower)
9
+ // speech recognition typings stay assignable to it.
10
+ interface SpeechRecognitionInstance extends EventTarget {
9
11
  continuous: boolean;
10
12
  interimResults: boolean;
11
13
  lang: string;
12
14
  start(): void;
13
15
  stop(): void;
14
- onstart: ((this: SpeechRecognition, ev: Event) => void) | null;
15
- onend: ((this: SpeechRecognition, ev: Event) => void) | null;
16
- onresult:
17
- | ((this: SpeechRecognition, ev: SpeechRecognitionEvent) => void)
18
- | null;
19
- onerror:
20
- | ((this: SpeechRecognition, ev: SpeechRecognitionErrorEvent) => void)
21
- | null;
22
16
  }
17
+ type SpeechRecognitionConstructor = new () => SpeechRecognitionInstance;
23
18
  interface SpeechRecognitionEvent extends Event {
24
19
  results: SpeechRecognitionResultList;
25
20
  resultIndex: number;
@@ -39,15 +34,18 @@ interface SpeechRecognitionAlternative {
39
34
  transcript: string;
40
35
  confidence: number;
41
36
  }
42
- interface SpeechRecognitionErrorEvent extends Event {
43
- error: string;
44
- }
45
- declare global {
46
- interface Window {
47
- SpeechRecognition: new () => SpeechRecognition;
48
- webkitSpeechRecognition: new () => SpeechRecognition;
49
- }
50
- }
37
+ // Read the constructors through a local type: a package must not augment the
38
+ // global Window, which would clash with apps and the DOM lib.
39
+ type SpeechRecognitionWindow = Window & {
40
+ SpeechRecognition?: SpeechRecognitionConstructor;
41
+ webkitSpeechRecognition?: SpeechRecognitionConstructor;
42
+ };
43
+ const getSpeechRecognitionConstructor = ():
44
+ | SpeechRecognitionConstructor
45
+ | undefined => {
46
+ const speechWindow: SpeechRecognitionWindow = window;
47
+ return speechWindow.SpeechRecognition || speechWindow.webkitSpeechRecognition;
48
+ };
51
49
  type SpeechInputMode = "speech-recognition" | "media-recorder" | "none";
52
50
  export type SpeechInputProps = ComponentProps<typeof Button> & {
53
51
  onTranscriptionChange?: (text: string) => void;
@@ -77,7 +75,7 @@ export const SpeechInput = ({
77
75
  const [isProcessing, setIsProcessing] = useState(false);
78
76
  const [mode] = useState<SpeechInputMode>(detectSpeechInputMode);
79
77
  const [isRecognitionReady, setIsRecognitionReady] = useState(false);
80
- const recognitionRef = useRef<SpeechRecognition | null>(null);
78
+ const recognitionRef = useRef<SpeechRecognitionInstance | null>(null);
81
79
  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
82
80
  const streamRef = useRef<MediaStream | null>(null);
83
81
  const audioChunksRef = useRef<Blob[]>([]);
@@ -92,8 +90,10 @@ export const SpeechInput = ({
92
90
  if (mode !== "speech-recognition") {
93
91
  return;
94
92
  }
95
- const SpeechRecognitionCtor =
96
- window.SpeechRecognition || window.webkitSpeechRecognition;
93
+ const SpeechRecognitionCtor = getSpeechRecognitionConstructor();
94
+ if (!SpeechRecognitionCtor) {
95
+ return;
96
+ }
97
97
  const speechRecognition = new SpeechRecognitionCtor();
98
98
  speechRecognition.continuous = true;
99
99
  speechRecognition.interimResults = true;