@vvedantb/ui 0.5.0 → 0.5.1

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
@@ -248,7 +248,7 @@ import {
248
248
  - `SelectField`: a labelled single select built from `Select`. Children are `SelectItem`s. An empty `value` shows the placeholder. `id` goes to the trigger and the label points at it. `className` merges onto the trigger.
249
249
  - Motion: `springTransition`, `springFastTransition` and `fadeUpSpring` presets. `FadePresence` takes optional `variants` (`hidden`, `show`, `exit`); omitted, it keeps its opacity fade. `PanelTransition` wraps children in React `ViewTransition` with `default="none"` and `enter`/`exit` classes (`vt-panel-in`, `vt-panel-out` by default). It needs a React build that exports `ViewTransition`, and the app supplies the `::view-transition-*` CSS.
250
250
 
251
- ## App shell (0.5.0)
251
+ ## App shell (0.5.0, 0.5.1)
252
252
 
253
253
  A sidebar and main page layout, extracted from existing app markup. It is router-free: pass your own links (with `asChild`), state and media query result. Tooltips need a `TooltipProvider` above the shell.
254
254
 
@@ -298,6 +298,59 @@ import {
298
298
  - `SignOutDialog`: `open`, `onOpenChange` (not called with `false` while `pending`), `pending`, `onConfirm`, `description`, `contentClassName`, `title` (`"Sign out"`), `question` (`"Sign out of your account?"`).
299
299
  - Class helpers: `railTileClass`, `railTileStateClass(active)`, `railBadgeClass`, `sidebarNavRowClass(isIconOnly)`, `sidebarNavLinkTextClass(isActive)`, `sidebarSectionLabelClass`.
300
300
 
301
+ ### Resizable panel (0.5.1)
302
+
303
+ Pass `resizable` to `AppShell`. Widths are panel px, rail excluded. Without it nothing changes.
304
+
305
+ ```tsx
306
+ <AppShell
307
+ resizable={{ storageKey: "sidebar-width", defaultWidth: 256, minWidth: 200, maxWidth: 480 }}
308
+ sidebar={<AppSidebar /* as above */ />}
309
+ >
310
+ {page}
311
+ </AppShell>
312
+ ```
313
+
314
+ - `resizable`: `storageKey`, `defaultWidth`, `minWidth`, `maxWidth`, `label` (default `"Resize sidebar"`). The shell reads the stored width (a JSON number in `localStorage`) on mount, ignores invalid values, clamps it to the bounds and writes each change. Server and hydration renders use `defaultWidth`. `--app-shell-sidebar-width` becomes `calc(<railWidth> + <width>px)` and `sidebarWidth` is ignored. While resizing, the main margin and `<aside>` width transitions are off.
315
+ - `AppSidebar` adds the handle to the `<aside>` right edge on desktop while the panel shows (not `collapsed`, not `panelHidden`). The mobile drawer has none.
316
+ - `SidebarResizeHandle` (`className`): the handle, for custom layouts. Place it in a positioned parent. Dragging past the bounds rubber-bands and springs back on release. ArrowLeft and ArrowRight step 16px. Double-click resets to `defaultWidth`. It renders nothing outside a resizable `AppShell`.
317
+ - `useAppShellResize()`: `{ width, setWidth, isResizing, minWidth, maxWidth, defaultWidth }`, or `null` outside a resizable `AppShell`. `setWidth` takes a number or an updater.
318
+
319
+ ```tsx
320
+ function PanelWidth() {
321
+ const resize = useAppShellResize();
322
+ return resize ? <span>{Math.round(resize.width)}px</span> : null;
323
+ }
324
+ ```
325
+
326
+ ### Rail tabs (0.5.1)
327
+
328
+ `SidebarRail tabs` renders the body as a Radix tabs list (arrow-key roving focus, same classes). Wrap the sidebar in a Tabs root with `orientation="vertical"` (the package `Tabs` works). `RailTile tabValue` renders a tabs trigger: tile classes, the children, the label as sr-only text instead of `aria-label`, then the badge. `active` drives the state classes and other props (for example `aria-expanded`) go to the trigger. `asChild` is ignored with `tabValue`. Without `tabs` and `tabValue` the rail renders as before.
329
+
330
+ ```tsx
331
+ <Tabs value={tab} onValueChange={setTab} orientation="vertical">
332
+ <AppSidebar
333
+ /* … */
334
+ rail={
335
+ <SidebarRail tabs>
336
+ <RailTile tabValue="files" label="Files" active={tab === "files"} aria-expanded={tab === "files" ? !collapsed : undefined}>
337
+ <IconFiles size={22} />
338
+ </RailTile>
339
+ <RailTile tabValue="search" label="Search" active={tab === "search"}>
340
+ <IconSearch size={22} />
341
+ </RailTile>
342
+ </SidebarRail>
343
+ }
344
+ panel={
345
+ <>
346
+ <TabsContent value="files">{files}</TabsContent>
347
+ <TabsContent value="search">{search}</TabsContent>
348
+ </>
349
+ }
350
+ />
351
+ </Tabs>
352
+ ```
353
+
301
354
  ## Toaster
302
355
 
303
356
  ```tsx
package/app/README.md ADDED
@@ -0,0 +1,100 @@
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`, needed only for the app helpers: `@clerk/clerk-react` (`useStableAuth`), `@tanstack/react-hotkeys` and `zod`.
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`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vvedantb/ui",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "license": "MIT",
5
5
  "description": "Shared React 19 UI for web apps: one JavaScript entry (primitives, shell pieces, app helpers, native tokens), design-token CSS, shared Tailwind v4 CSS and a Tailwind preset.",
6
6
  "type": "module",
@@ -52,6 +52,15 @@
52
52
  "sideEffects": [
53
53
  "./src/ui/sonner.css"
54
54
  ],
55
+ "scripts": {
56
+ "check:tokens": "node tokens/scripts/check-component-tokens.mjs",
57
+ "build": "node tokens/scripts/check-exports.mjs && node tokens/scripts/check-component-tokens.mjs && tsc -p tsconfig.json",
58
+ "typecheck": "tsc -p tsconfig.json && tsc -p tokens/tsconfig.json",
59
+ "test": "node tokens/scripts/check-component-tokens.mjs && vitest run && node --test tokens/test/*.test.mjs",
60
+ "verify": "node tokens/scripts/check-component-tokens.mjs && node tokens/verify/run.mjs",
61
+ "analyze": "node tokens/verify/analyze.mjs",
62
+ "prepack": "node tokens/scripts/check-exports.mjs"
63
+ },
55
64
  "peerDependencies": {
56
65
  "@clerk/clerk-react": ">=5",
57
66
  "@radix-ui/react-accordion": "^1.2.12",
@@ -162,13 +171,5 @@
162
171
  "zod": {
163
172
  "optional": true
164
173
  }
165
- },
166
- "scripts": {
167
- "check:tokens": "node tokens/scripts/check-component-tokens.mjs",
168
- "build": "node tokens/scripts/check-exports.mjs && node tokens/scripts/check-component-tokens.mjs && tsc -p tsconfig.json",
169
- "typecheck": "tsc -p tsconfig.json && tsc -p tokens/tsconfig.json",
170
- "test": "node tokens/scripts/check-component-tokens.mjs && vitest run && node --test tokens/test/*.test.mjs",
171
- "verify": "node tokens/scripts/check-component-tokens.mjs && node tokens/verify/run.mjs",
172
- "analyze": "node tokens/verify/analyze.mjs"
173
174
  }
174
- }
175
+ }
@@ -1,5 +1,10 @@
1
1
  import type { CSSProperties, ReactNode } from "react";
2
2
  import { cn } from "../../src/utils/cn";
3
+ import {
4
+ SidebarResizeProvider,
5
+ useSidebarResizeState,
6
+ type SidebarResizeOptions,
7
+ } from "./SidebarResize";
3
8
 
4
9
  export type AppShellProps = {
5
10
  /** Rendered between the skip link and `<main>`, usually an `AppSidebar`. */
@@ -13,8 +18,14 @@ export type AppShellProps = {
13
18
  panelHidden?: boolean;
14
19
  /** Sets `--app-shell-rail-width`. Default `"4rem"`. */
15
20
  railWidth?: string;
16
- /** Sets `--app-shell-sidebar-width` (rail plus panel). Default `"20rem"`. */
21
+ /** Sets `--app-shell-sidebar-width` (rail plus panel). Default `"20rem"`. Ignored with `resizable`. */
17
22
  sidebarWidth?: string;
23
+ /**
24
+ * Opt-in resizable panel. The shell owns the persisted panel width, sets
25
+ * `--app-shell-sidebar-width` to `calc(<railWidth> + <width>px)` and shares
26
+ * the state with `AppSidebar`, `SidebarResizeHandle` and `useAppShellResize`.
27
+ */
28
+ resizable?: SidebarResizeOptions;
18
29
  /** Sets `--app-shell-mobile-header-height`. Default `"calc(3.5rem + env(safe-area-inset-top, 0px))"`. */
19
30
  mobileHeaderHeight?: string;
20
31
  /** Default `"Skip to main content"`. */
@@ -36,6 +47,7 @@ export function AppShell({
36
47
  panelHidden = false,
37
48
  railWidth = "4rem",
38
49
  sidebarWidth = "20rem",
50
+ resizable,
39
51
  mobileHeaderHeight = "calc(3.5rem + env(safe-area-inset-top, 0px))",
40
52
  skipLinkLabel = "Skip to main content",
41
53
  mainId = "main-content",
@@ -43,41 +55,45 @@ export function AppShell({
43
55
  mainClassName,
44
56
  contentClassName,
45
57
  }: AppShellProps) {
58
+ const resize = useSidebarResizeState(resizable);
46
59
  const style: ShellVars = {
47
60
  "--app-shell-rail-width": railWidth,
48
- "--app-shell-sidebar-width": sidebarWidth,
61
+ "--app-shell-sidebar-width": resize ? `calc(${railWidth} + ${resize.width}px)` : sidebarWidth,
49
62
  "--app-shell-mobile-header-height": mobileHeaderHeight,
50
63
  };
51
64
  return (
52
- <div className={cn("relative h-dvh overflow-hidden bg-background", className)} style={style}>
53
- <a
54
- href={`#${mainId}`}
55
- className="sr-only focus:absolute focus:left-3 focus:top-[max(0.75rem,env(safe-area-inset-top))] focus:z-[100] focus:block focus:rounded-lg focus:bg-surface-secondary focus:px-3 focus:py-2 focus:text-sm focus:font-medium focus:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
56
- >
57
- {skipLinkLabel}
58
- </a>
59
- {sidebar}
60
- <main
61
- id={mainId}
62
- tabIndex={-1}
63
- className={cn(
64
- "relative z-10 flex h-full min-h-0 outline-none md:p-2",
65
- panelHidden
66
- ? "md:ml-[var(--app-shell-rail-width)]"
67
- : "md:ml-[var(--app-shell-sidebar-width)]",
68
- "md:transition-[margin-left] md:[transition-duration:280ms] md:[transition-timing-function:cubic-bezier(0.22,1,0.36,1)]",
69
- mainClassName,
70
- )}
71
- >
72
- <div
65
+ <SidebarResizeProvider value={resize}>
66
+ <div className={cn("relative h-dvh overflow-hidden bg-background", className)} style={style}>
67
+ <a
68
+ href={`#${mainId}`}
69
+ className="sr-only focus:absolute focus:left-3 focus:top-[max(0.75rem,env(safe-area-inset-top))] focus:z-[100] focus:block focus:rounded-lg focus:bg-surface-secondary focus:px-3 focus:py-2 focus:text-sm focus:font-medium focus:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
70
+ >
71
+ {skipLinkLabel}
72
+ </a>
73
+ {sidebar}
74
+ <main
75
+ id={mainId}
76
+ tabIndex={-1}
73
77
  className={cn(
74
- "flex min-h-0 flex-1 flex-col overflow-hidden bg-surface pt-[var(--app-shell-mobile-header-height)] md:rounded-lg md:pt-0",
75
- contentClassName,
78
+ "relative z-10 flex h-full min-h-0 outline-none md:p-2",
79
+ panelHidden
80
+ ? "md:ml-[var(--app-shell-rail-width)]"
81
+ : "md:ml-[var(--app-shell-sidebar-width)]",
82
+ !resize?.isResizing &&
83
+ "md:transition-[margin-left] md:[transition-duration:280ms] md:[transition-timing-function:cubic-bezier(0.22,1,0.36,1)]",
84
+ mainClassName,
76
85
  )}
77
86
  >
78
- {children}
79
- </div>
80
- </main>
81
- </div>
87
+ <div
88
+ className={cn(
89
+ "flex min-h-0 flex-1 flex-col overflow-hidden bg-surface pt-[var(--app-shell-mobile-header-height)] md:rounded-lg md:pt-0",
90
+ contentClassName,
91
+ )}
92
+ >
93
+ {children}
94
+ </div>
95
+ </main>
96
+ </div>
97
+ </SidebarResizeProvider>
82
98
  );
83
99
  }
@@ -5,6 +5,7 @@ import { Button } from "../../src/ui/button";
5
5
  import { motionEase, motionTiming } from "../../src/motion/presets";
6
6
  import { cn } from "../../src/utils/cn";
7
7
  import { mobileMenuButtonClass } from "./app-shell-classes";
8
+ import { SidebarResizeHandle, useSidebarResizeContext } from "./SidebarResize";
8
9
 
9
10
  export type AppSidebarProps = {
10
11
  /** Icon rail, usually a `SidebarRail`. */
@@ -41,7 +42,8 @@ const defaultMobileMenuIcon = () => <IconMenu2 size={20} />;
41
42
  /**
42
43
  * Sidebar chrome: the mobile header, the drawer backdrop and the `<aside>`
43
44
  * (fixed on desktop, a swipe-to-close drawer below it). Reads the
44
- * `--app-shell-*` width variables set by `AppShell`.
45
+ * `--app-shell-*` width variables set by `AppShell`. Inside a resizable
46
+ * `AppShell` it adds the resize handle while the panel shows on desktop.
45
47
  */
46
48
  export function AppSidebar({
47
49
  rail,
@@ -62,6 +64,8 @@ export function AppSidebar({
62
64
  const autoId = useId();
63
65
  const drawerId = id ?? autoId;
64
66
  const layout = isDesktop ? "desktop" : "drawer";
67
+ const resize = useSidebarResizeContext();
68
+ const showResizeHandle = resize !== null && isDesktop && !collapsed && !panelHidden;
65
69
 
66
70
  // Reaching the desktop breakpoint closes the drawer, so it does not reopen
67
71
  // on the way back down. Runs on breakpoint change only.
@@ -142,7 +146,8 @@ export function AppSidebar({
142
146
  collapsed || panelHidden
143
147
  ? "md:w-[var(--app-shell-rail-width)]"
144
148
  : "md:w-[var(--app-shell-sidebar-width)]",
145
- "md:transition-[width] md:[transition-duration:280ms] md:[transition-timing-function:cubic-bezier(0.22,1,0.36,1)]",
149
+ !resize?.isResizing &&
150
+ "md:transition-[width] md:[transition-duration:280ms] md:[transition-timing-function:cubic-bezier(0.22,1,0.36,1)]",
146
151
  className,
147
152
  )}
148
153
  initial={false}
@@ -156,6 +161,7 @@ export function AppSidebar({
156
161
  >
157
162
  {rail}
158
163
  {panelHidden ? null : panel}
164
+ {showResizeHandle ? <SidebarResizeHandle /> : null}
159
165
  </motion.aside>
160
166
  </>
161
167
  );
@@ -1,5 +1,6 @@
1
1
  import type { ComponentPropsWithoutRef, ReactNode } from "react";
2
2
  import { Slot, Slottable } from "@radix-ui/react-slot";
3
+ import * as TabsPrimitive from "@radix-ui/react-tabs";
3
4
  import { Button } from "../../src/ui/button";
4
5
  import { cn } from "../../src/utils/cn";
5
6
  import { railTileClass, railTileStateClass } from "./app-shell-classes";
@@ -16,6 +17,12 @@ export type SidebarRailProps = Omit<ComponentPropsWithoutRef<"div">, "children"
16
17
  showDivider?: boolean;
17
18
  /** Render the body as its single child element (for example a tabs list), with the body classes merged. */
18
19
  bodyAsChild?: boolean;
20
+ /**
21
+ * Render the body as a Radix tabs list (arrow-key roving focus). Use it
22
+ * inside a Tabs root with `orientation="vertical"` and give each `RailTile`
23
+ * a `tabValue`. Default `false`.
24
+ */
25
+ tabs?: boolean;
19
26
  className?: string;
20
27
  topClassName?: string;
21
28
  bodyClassName?: string;
@@ -29,6 +36,7 @@ export function SidebarRail({
29
36
  footer,
30
37
  showDivider = false,
31
38
  bodyAsChild = false,
39
+ tabs = false,
32
40
  className,
33
41
  topClassName,
34
42
  bodyClassName,
@@ -36,6 +44,10 @@ export function SidebarRail({
36
44
  ...props
37
45
  }: SidebarRailProps) {
38
46
  const Body = bodyAsChild ? Slot : "div";
47
+ const bodyClass = cn(
48
+ "flex w-full flex-1 flex-col items-center gap-1.5 overflow-y-auto py-2",
49
+ bodyClassName,
50
+ );
39
51
  return (
40
52
  <div
41
53
  {...props}
@@ -50,14 +62,13 @@ export function SidebarRail({
50
62
  {top}
51
63
  </div>
52
64
  )}
53
- <Body
54
- className={cn(
55
- "flex w-full flex-1 flex-col items-center gap-1.5 overflow-y-auto py-2",
56
- bodyClassName,
57
- )}
58
- >
59
- {children}
60
- </Body>
65
+ {tabs ? (
66
+ <TabsPrimitive.List asChild={bodyAsChild} className={bodyClass}>
67
+ {children}
68
+ </TabsPrimitive.List>
69
+ ) : (
70
+ <Body className={bodyClass}>{children}</Body>
71
+ )}
61
72
  {footer == null ? null : (
62
73
  <div className={cn("flex w-full flex-col items-center gap-1.5 py-3", footerClassName)}>
63
74
  {footer}
@@ -80,10 +91,15 @@ export type RailTileProps = Omit<ComponentPropsWithoutRef<"button">, "children">
80
91
  badge?: ReactNode;
81
92
  /** Render the single child element (for example a router link) as the tile. */
82
93
  asChild?: boolean;
94
+ /**
95
+ * Render a Radix tabs trigger for this value (inside a `SidebarRail tabs`).
96
+ * The label is sr-only text instead of `aria-label`; `asChild` is ignored.
97
+ */
98
+ tabValue?: string;
83
99
  children: ReactNode;
84
100
  };
85
101
 
86
- /** Rail tile with a right-side tooltip. Renders a ghost `Button`, or its child with `asChild`. */
102
+ /** Rail tile with a right-side tooltip. Renders a ghost `Button`, its child with `asChild`, or a tabs trigger with `tabValue`. */
87
103
  export function RailTile({
88
104
  label,
89
105
  active = false,
@@ -91,13 +107,24 @@ export function RailTile({
91
107
  showTooltip = true,
92
108
  badge,
93
109
  asChild = false,
110
+ tabValue,
94
111
  className,
95
112
  children,
96
113
  ...props
97
114
  }: RailTileProps) {
98
115
  return (
99
116
  <SidebarIconTooltip label={tooltip ?? label} enabled={showTooltip}>
100
- {asChild ? (
117
+ {tabValue !== undefined ? (
118
+ <TabsPrimitive.Trigger
119
+ {...props}
120
+ value={tabValue}
121
+ className={cn(railTileClass, "group relative", railTileStateClass(active), className)}
122
+ >
123
+ {children}
124
+ <span className="sr-only">{label}</span>
125
+ {badge}
126
+ </TabsPrimitive.Trigger>
127
+ ) : asChild ? (
101
128
  <Slot
102
129
  {...props}
103
130
  aria-label={label}
@@ -0,0 +1,257 @@
1
+ import {
2
+ createContext,
3
+ useContext,
4
+ useEffect,
5
+ useRef,
6
+ useState,
7
+ useSyncExternalStore,
8
+ type KeyboardEvent,
9
+ type PointerEvent,
10
+ } from "react";
11
+ import { animate } from "motion";
12
+ import { cn } from "../../src/utils/cn";
13
+
14
+ /** Opt-in resizable sidebar panel. Widths are panel px, rail excluded. */
15
+ export type SidebarResizeOptions = {
16
+ /** `localStorage` key for the panel width (a JSON number). */
17
+ storageKey: string;
18
+ defaultWidth: number;
19
+ minWidth: number;
20
+ maxWidth: number;
21
+ /** Handle `aria-label`. Default `"Resize sidebar"`. */
22
+ label?: string;
23
+ };
24
+
25
+ type WidthUpdate = number | ((width: number) => number);
26
+ type Animation = ReturnType<typeof animate>;
27
+
28
+ type SidebarResizeState = {
29
+ width: number;
30
+ setWidth: (update: WidthUpdate) => void;
31
+ isResizing: boolean;
32
+ minWidth: number;
33
+ maxWidth: number;
34
+ defaultWidth: number;
35
+ label: string;
36
+ /** Latest width, readable between renders (pointer moves can outpace them). */
37
+ currentWidth: () => number;
38
+ stopAnimation: () => void;
39
+ startResizing: () => void;
40
+ settleToClamp: (velocity: number) => void;
41
+ };
42
+
43
+ const SidebarResizeContext = createContext<SidebarResizeState | null>(null);
44
+ export const SidebarResizeProvider = SidebarResizeContext.Provider;
45
+
46
+ const KEYBOARD_STEP = 16;
47
+
48
+ function rubberband(overshoot: number, dimension: number, constant = 0.55): number {
49
+ return (overshoot * dimension * constant) / (dimension + constant * Math.abs(overshoot));
50
+ }
51
+
52
+ type Sample = { x: number; t: number };
53
+
54
+ function releaseVelocity(samples: Sample[]): number {
55
+ if (samples.length < 2) return 0;
56
+ const newest = samples[samples.length - 1];
57
+ const oldest = samples[0];
58
+ if (!newest || !oldest) return 0;
59
+ const dt = newest.t - oldest.t;
60
+ if (dt <= 0) return 0;
61
+ return ((newest.x - oldest.x) / dt) * 1000;
62
+ }
63
+
64
+ function readStoredWidth(storageKey: string | undefined): number | null {
65
+ if (storageKey === undefined || typeof window === "undefined") return null;
66
+ try {
67
+ const raw = window.localStorage.getItem(storageKey);
68
+ if (raw === null || raw.trim() === "") return null;
69
+ // A JSON number parses the same with Number(); anything else is NaN.
70
+ const value = Number(raw);
71
+ return Number.isFinite(value) ? value : null;
72
+ } catch {
73
+ return null;
74
+ }
75
+ }
76
+
77
+ function writeStoredWidth(storageKey: string, width: number) {
78
+ try {
79
+ window.localStorage.setItem(storageKey, JSON.stringify(width));
80
+ } catch {
81
+ // Storage full or blocked: keep the in-memory width.
82
+ }
83
+ }
84
+
85
+ const subscribeNever = () => () => {};
86
+ const serverSnapshot = () => null;
87
+
88
+ /**
89
+ * Width and resize state for `AppShell`. Returns `null` without options. The
90
+ * stored width is read through `useSyncExternalStore` (the server snapshot is
91
+ * `null`, so SSR and hydration render `defaultWidth`); later writes go to
92
+ * local state and storage.
93
+ */
94
+ export function useSidebarResizeState(
95
+ options: SidebarResizeOptions | undefined,
96
+ ): SidebarResizeState | null {
97
+ const storageKey = options?.storageKey;
98
+ const stored = useSyncExternalStore(subscribeNever, () => readStoredWidth(storageKey), serverSnapshot);
99
+ const [override, setOverride] = useState<number | null>(null);
100
+ const [isResizing, setIsResizing] = useState(false);
101
+ const widthRef = useRef<number | null>(null);
102
+ const animRef = useRef<Animation | null>(null);
103
+
104
+ useEffect(() => () => animRef.current?.stop(), []);
105
+
106
+ if (!options) return null;
107
+ const { defaultWidth, minWidth, maxWidth } = options;
108
+ const clampWidth = (width: number) => Math.min(maxWidth, Math.max(minWidth, width));
109
+ const width = override ?? (stored === null ? defaultWidth : clampWidth(stored));
110
+ const currentWidth = () => widthRef.current ?? width;
111
+
112
+ const setWidth = (update: WidthUpdate) => {
113
+ const next = typeof update === "function" ? update(currentWidth()) : update;
114
+ widthRef.current = next;
115
+ setOverride(next);
116
+ writeStoredWidth(options.storageKey, next);
117
+ };
118
+
119
+ const stopAnimation = () => animRef.current?.stop();
120
+
121
+ const settleToClamp = (velocity: number) => {
122
+ const from = currentWidth();
123
+ const to = clampWidth(from);
124
+ setIsResizing(false);
125
+ if (from === to) return;
126
+ animRef.current?.stop();
127
+ animRef.current = animate(from, to, {
128
+ type: "spring",
129
+ bounce: 0.2,
130
+ duration: 0.35,
131
+ velocity,
132
+ onUpdate: (value) => setWidth(value),
133
+ });
134
+ };
135
+
136
+ return {
137
+ width,
138
+ setWidth,
139
+ isResizing,
140
+ minWidth,
141
+ maxWidth,
142
+ defaultWidth,
143
+ label: options.label ?? "Resize sidebar",
144
+ currentWidth,
145
+ stopAnimation,
146
+ startResizing: () => setIsResizing(true),
147
+ settleToClamp,
148
+ };
149
+ }
150
+
151
+ export function useSidebarResizeContext(): SidebarResizeState | null {
152
+ return useContext(SidebarResizeContext);
153
+ }
154
+
155
+ export type AppShellResize = {
156
+ /** Panel width in px (rail excluded). Can sit past the bounds mid-drag. */
157
+ width: number;
158
+ setWidth: (update: WidthUpdate) => void;
159
+ isResizing: boolean;
160
+ minWidth: number;
161
+ maxWidth: number;
162
+ defaultWidth: number;
163
+ };
164
+
165
+ /** Panel width and resize state of the nearest resizable `AppShell`, or `null`. */
166
+ export function useAppShellResize(): AppShellResize | null {
167
+ const resize = useContext(SidebarResizeContext);
168
+ if (!resize) return null;
169
+ const { width, setWidth, isResizing, minWidth, maxWidth, defaultWidth } = resize;
170
+ return { width, setWidth, isResizing, minWidth, maxWidth, defaultWidth };
171
+ }
172
+
173
+ export type SidebarResizeHandleProps = { className?: string };
174
+
175
+ /**
176
+ * Vertical separator on the right edge of its positioned parent. Drag past the
177
+ * bounds rubber-bands and springs back on release; arrow keys step 16px;
178
+ * double-click resets. Renders nothing outside a resizable `AppShell`.
179
+ */
180
+ export function SidebarResizeHandle({ className }: SidebarResizeHandleProps) {
181
+ const resize = useContext(SidebarResizeContext);
182
+ const samplesRef = useRef<Sample[]>([]);
183
+ if (!resize) return null;
184
+ const { width, setWidth, isResizing, minWidth, maxWidth, defaultWidth } = resize;
185
+ const clampWidth = (value: number) => Math.min(maxWidth, Math.max(minWidth, value));
186
+ const softWidth = (value: number) => {
187
+ if (value < minWidth) return minWidth - rubberband(minWidth - value, minWidth);
188
+ if (value > maxWidth) return maxWidth + rubberband(value - maxWidth, maxWidth);
189
+ return value;
190
+ };
191
+
192
+ const handlePointerDown = (event: PointerEvent<HTMLDivElement>) => {
193
+ event.preventDefault();
194
+ resize.stopAnimation();
195
+ event.currentTarget.setPointerCapture(event.pointerId);
196
+ samplesRef.current = [{ x: resize.currentWidth(), t: performance.now() }];
197
+ resize.startResizing();
198
+ };
199
+
200
+ const handlePointerMove = (event: PointerEvent<HTMLDivElement>) => {
201
+ if (!isResizing) return;
202
+ const next = softWidth(resize.currentWidth() + event.movementX);
203
+ const now = performance.now();
204
+ const samples = samplesRef.current;
205
+ samples.push({ x: next, t: now });
206
+ while (samples.length > 5 || now - (samples[0]?.t ?? now) > 80) samples.shift();
207
+ setWidth(next);
208
+ };
209
+
210
+ const handlePointerUp = (event: PointerEvent<HTMLDivElement>) => {
211
+ event.currentTarget.releasePointerCapture(event.pointerId);
212
+ resize.settleToClamp(releaseVelocity(samplesRef.current));
213
+ samplesRef.current = [];
214
+ };
215
+
216
+ const handlePointerCancel = (event: PointerEvent<HTMLDivElement>) => {
217
+ event.currentTarget.releasePointerCapture(event.pointerId);
218
+ resize.settleToClamp(0);
219
+ samplesRef.current = [];
220
+ };
221
+
222
+ const handleDoubleClick = () => {
223
+ resize.stopAnimation();
224
+ setWidth(defaultWidth);
225
+ };
226
+
227
+ const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
228
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
229
+ event.preventDefault();
230
+ resize.stopAnimation();
231
+ const step = event.key === "ArrowLeft" ? -KEYBOARD_STEP : KEYBOARD_STEP;
232
+ setWidth((current) => clampWidth(current + step));
233
+ };
234
+
235
+ return (
236
+ <div
237
+ role="separator"
238
+ aria-orientation="vertical"
239
+ aria-label={resize.label}
240
+ aria-valuenow={clampWidth(width)}
241
+ aria-valuemin={minWidth}
242
+ aria-valuemax={maxWidth}
243
+ tabIndex={0}
244
+ className={cn(
245
+ "absolute inset-y-0 right-0 z-50 h-full w-1.5 cursor-col-resize outline-hidden transition-[background-color] hover:bg-default focus-visible:bg-default",
246
+ isResizing && "bg-default",
247
+ className,
248
+ )}
249
+ onPointerDown={handlePointerDown}
250
+ onPointerMove={handlePointerMove}
251
+ onPointerUp={handlePointerUp}
252
+ onPointerCancel={handlePointerCancel}
253
+ onDoubleClick={handleDoubleClick}
254
+ onKeyDown={handleKeyDown}
255
+ />
256
+ );
257
+ }
@@ -16,6 +16,12 @@ export { AppSidebar } from "./AppSidebar.js";
16
16
  export type { AppSidebarProps } from "./AppSidebar.js";
17
17
  export { SidebarRail, RailTile, RailDivider } from "./SidebarRail.js";
18
18
  export type { SidebarRailProps, RailTileProps, RailDividerProps } from "./SidebarRail.js";
19
+ export { SidebarResizeHandle, useAppShellResize } from "./SidebarResize.js";
20
+ export type {
21
+ AppShellResize,
22
+ SidebarResizeHandleProps,
23
+ SidebarResizeOptions,
24
+ } from "./SidebarResize.js";
19
25
  export { SidebarIconTooltip } from "./SidebarIconTooltip.js";
20
26
  export type { SidebarIconTooltipProps } from "./SidebarIconTooltip.js";
21
27
  export { SidebarPanel } from "./SidebarPanel.js";
package/src/index.ts CHANGED
@@ -128,6 +128,12 @@ export { AppSidebar } from "../shell/src/AppSidebar";
128
128
  export type { AppSidebarProps } from "../shell/src/AppSidebar";
129
129
  export { SidebarRail, RailTile, RailDivider } from "../shell/src/SidebarRail";
130
130
  export type { SidebarRailProps, RailTileProps, RailDividerProps } from "../shell/src/SidebarRail";
131
+ export { SidebarResizeHandle, useAppShellResize } from "../shell/src/SidebarResize";
132
+ export type {
133
+ AppShellResize,
134
+ SidebarResizeHandleProps,
135
+ SidebarResizeOptions,
136
+ } from "../shell/src/SidebarResize";
131
137
  export { SidebarIconTooltip } from "../shell/src/SidebarIconTooltip";
132
138
  export type { SidebarIconTooltipProps } from "../shell/src/SidebarIconTooltip";
133
139
  export { SidebarPanel } from "../shell/src/SidebarPanel";
@@ -0,0 +1,98 @@
1
+ # `@vvedantb/ui/tokens`
2
+
3
+ Design tokens and shared Tailwind v4 CSS for the vvedantb web apps. The CSS and Tailwind preset are subpaths of `@vvedantb/ui`; the native JS tokens are named exports of the root (`tokens`, `Tokens`). Source-exported: no build step. Paths in the `File` column are relative to `packages/ui/tokens/`.
4
+
5
+ ## Exports
6
+
7
+ | Export | File | What it is |
8
+ | --- | --- | --- |
9
+ | `@vvedantb/ui/tokens`, `@vvedantb/ui/tokens/tokens.css` | `src/tokens.css` | Colour, radius, shadow, ease and font tokens (`@theme`), light/dark variables, `dark` variant, `*` border and `body` defaults. In 0.2.1 it also defines shadcn-style aliases (`primary`, `muted-foreground`, `secondary`, `destructive`, `card`, `popover`, `input`, `ring`) that point at the same tokens. |
10
+ | `tokens` and `Tokens` from `@vvedantb/ui` | `src/native.ts` | JS colours, radii and spacing for React Native. `@vvedantb/native-ui` keeps its own copy in `src/tokens.ts`; a test keeps the two equal. |
11
+ | `@vvedantb/ui/tokens/css/base.css` | `src/css/base.css` | `html` touch/accent, `::selection`, control transitions, pointer cursor, range accent (`@layer base`). |
12
+ | `@vvedantb/ui/tokens/css/dialog.css` | `src/css/dialog.css` | Unlayered `max-width: none` for `@vvedantb/ui` compact (bottom-sheet) dialogs. |
13
+ | `@vvedantb/ui/tokens/css/modal.css` | `src/css/modal.css` | `.t-modal`, `.is-open`, `.is-closing` and `t-modal-presence-wait` (`@layer components`). |
14
+ | `@vvedantb/ui/tokens/css/tabs.css` | `src/css/tabs.css` | `.t-tab`, active colour, `.t-tabs-pill`, small-screen `.t-tabs` scrolling. |
15
+ | `@vvedantb/ui/tokens/css/tabs-pills.css` | `src/css/tabs-pills.css` | `--tabs-*` colour variables, `.t-tabs--segmented`, `.t-tabs--pills` and pill hover / active fills. |
16
+ | `@vvedantb/ui/tokens/css/utilities.css` | `src/css/utilities.css` | `@utility hit-target`, `@utility reveal-on-hover` and `@utility rounded-surface` (`clamp(0.75rem, var(--radius), 1rem)`). |
17
+ | `@vvedantb/ui/tokens/css/scrollbar-thin.css` | `src/css/scrollbar-thin.css` | `.scrollbar-thin` (`@layer utilities`, always emitted). |
18
+ | `@vvedantb/ui/tokens/css/animations.css` | `src/css/animations.css` | `animate-aurora`, `animate-fade-in-up`, `animate-indeterminate` as `@theme` (CSS-first apps). |
19
+ | `@vvedantb/ui/tokens/css/compat-shadcn-rgb.css`, `@vvedantb/ui/tokens/compat/shadcn-rgb.css` | `src/css/compat-shadcn-rgb.css` | Replaces `tokens.css` for apps with shadcn-style `R G B` channel variables. Defines only the UI-only `--color-*` names as `rgb(var(--x) / alpha)` references, `--radius-field`, `--scrollbar`, `--field-radius` and a `glass-panel-strong` fallback. Import it **or** `tokens.css`, never both. |
20
+ | `@vvedantb/ui/tokens/css/index.css` | `src/css/index.css` | base + dialog + utilities + scrollbar-thin + animations, for new CSS-first apps. |
21
+ | `@vvedantb/ui/tokens/tailwind-preset` | `src/tailwind-preset.mjs` (+ `.d.mts`) | Tailwind preset for apps that load a JS config with `@config`. |
22
+
23
+ Every file was extracted because the same rule (same at-rule context, selector and body) sits in 3 or more of the five apps. The measured duplication is in `verify/ANALYSIS.md`, and the proof that each app compiles to the same CSS after migrating is in `verify/RESULTS.md`. Blocks that only 2 apps share, or that drift in a way that would change an app's CSS, stay in the apps; `verify/ANALYSIS.md` lists them.
24
+
25
+ ## Use
26
+
27
+ CSS-first app (no `tailwind.config`):
28
+
29
+ ```css
30
+ @import "tailwindcss";
31
+ @import "@vvedantb/ui/tokens";
32
+ @import "@vvedantb/ui/tokens/css/animations.css";
33
+ @import "@vvedantb/ui/tokens/css/base.css";
34
+ /* ...app @layer base rules... */
35
+ @import "@vvedantb/ui/tokens/css/modal.css";
36
+ @import "@vvedantb/ui/tokens/css/tabs.css";
37
+ /* ...app @layer components rules... */
38
+ ```
39
+
40
+ App with a JS config (`@config "../tailwind.config.ts"`):
41
+
42
+ ```ts
43
+ import { tokensPreset } from "@vvedantb/ui/tokens/tailwind-preset";
44
+
45
+ export default {
46
+ presets: [tokensPreset()],
47
+ // or tokensPreset({ color: (name) => `color-mix(in oklch, var(--${name}) calc(<alpha-value> * 100%), transparent)` })
48
+ content: ["./src/**/*.{ts,tsx}"],
49
+ theme: { extend: { /* app-only colours, fonts, animations */ } },
50
+ plugins: [tailwindcssAnimate],
51
+ };
52
+ ```
53
+
54
+ The preset holds `darkMode: "class"`, the shared colour map (`border`, `surface.*`, `danger.*`, `field.*`, shadcn aliases `primary`/`secondary`/`destructive`/`card`/`popover`/`input` ...), `borderRadius` lg/md/sm/field, `boxShadow` soft/panel/insetSoft, `ease-smooth`, `screens` xs to 2xl in px, and the aurora / fade-in-up / indeterminate / accordion keyframes. It does not hold plugins, `content`, fonts, `accent`/`muted`/`ring`/`sidebar` (they differ per app) or accordion timings.
55
+
56
+ Do not import `css/animations.css` in an app that uses the preset: the preset already defines the same keyframes and animations.
57
+
58
+ ### Where to put the imports
59
+
60
+ Tailwind inlines an `@import` where it sits, even in the middle of a file (it must be at top level, not inside an `@layer` block). Put each import where the app's own copy of the rules was. Within one layer, later rules win at equal specificity, so moving shared rules above or below app rules can flip the result for elements matched by both. `examples/migration.md` gives the exact position for each app, and `pnpm --filter @vvedantb/ui verify` checks it.
61
+
62
+ ### Variables each file needs
63
+
64
+ | File | Needs | Provided by |
65
+ | --- | --- | --- |
66
+ | `base.css` | `--accent`, `--foreground` | tokens.css or the app theme |
67
+ | `dialog.css` | none | |
68
+ | `modal.css` | `--modal-open-dur`, `--modal-close-dur`, `--modal-scale`, `--modal-scale-close`, `--modal-ease` | app `:root` |
69
+ | `tabs.css` | `--tabs-dur`, `--tabs-ease` (app `:root`); `--tabs-text-muted`, `--tabs-text-active`, `--tabs-pill-bg` | colours: tabs-pills.css or the app theme |
70
+ | `tabs-pills.css` | `--muted`, `--segment`, `--segment-foreground`, `--default` | tokens.css or the app theme |
71
+ | `utilities.css` | `--breakpoint-sm` (Tailwind default or app theme) | Tailwind |
72
+ | `scrollbar-thin.css` | `--scrollbar` | tokens.css or the app theme |
73
+ | `animations.css` | none | |
74
+ | `tailwind-preset` | the CSS variables named in its colour map, `--radius`, `--field-radius` | tokens.css or the app theme |
75
+
76
+ ### Using an existing shadcn RGB theme
77
+
78
+ See the package `README.md`. With the compat file, `base.css`, `scrollbar-thin.css`, `utilities.css`, `dialog.css`, `modal.css` and `tabs.css` need no `tokens.css`. `base.css` reads `--accent` and `--foreground` and `tabs-pills.css` reads `--muted`, `--segment` and `--default`. Those are not channel-compatible, so skip `tabs-pills.css` and `index.css` (which includes `base.css`) unless the app defines those variables as full colours.
79
+
80
+ ### Parameters
81
+
82
+ Where apps share a rule but drifted in one value, the value is a custom property whose fallback is the most common value. Set it on `:root` to keep a different value.
83
+
84
+ | File | Property | Default | Set by |
85
+ | --- | --- | --- | --- |
86
+ | `base.css` | `--tokens-control-transition-property` | `background-color, border-color, color, box-shadow, transform, opacity` | app-c: `background-color, color, transform, opacity` |
87
+ | `base.css` | `--tokens-control-transition-duration` | `240ms` | app-c: `100ms` |
88
+
89
+ ## Develop
90
+
91
+ ```sh
92
+ pnpm --filter @vvedantb/ui build # export targets exist + tsc (primitives, shell, app)
93
+ pnpm --filter @vvedantb/ui test # vitest (app helpers) + offline node --test: exports, CSS structure, Tailwind compile, preset
94
+ pnpm --filter @vvedantb/ui analyze # rule-level duplication across the app clones -> verify/ANALYSIS.tables.md
95
+ pnpm --filter @vvedantb/ui verify # before/after compile of every app -> verify/RESULTS.md, examples/migration.md
96
+ ```
97
+
98
+ `analyze` and `verify` need the app clones (`APPS_DIR`, default `/workspace/cvx`; name or symlink the clones `app-a` to `app-e` inside it) and network access the first time: they install Tailwind 4.3.3, the plugins, postcss and jiti into a scratch directory (`VERIFY_DIR`, default `/workspace/pk-tokens-verify`, outside the repo). The migration for each app is data in `verify/migrations/<app>.json`. Each removed block must equal the shared file's block with the same context and selector, or the run fails.