@polyfen/polykit-react 0.1.0 → 0.2.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
@@ -30,7 +30,18 @@ Components that hold state or use hooks are marked `"use client"`, so they work
30
30
  ## Use
31
31
 
32
32
  ```tsx
33
- import { Button, Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, Field, Input, Toaster, toast } from '@polyfen/polykit-react';
33
+ import {
34
+ Button,
35
+ Dialog,
36
+ DialogContent,
37
+ DialogHeader,
38
+ DialogTitle,
39
+ DialogTrigger,
40
+ Field,
41
+ Input,
42
+ Toaster,
43
+ toast,
44
+ } from '@polyfen/polykit-react';
34
45
 
35
46
  <Dialog>
36
47
  <DialogTrigger asChild>
@@ -46,37 +57,99 @@ import { Button, Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger
46
57
  </DialogContent>
47
58
  </Dialog>;
48
59
 
49
- <Button variant="primary" onClick={() => toast('Saved')}>Save</Button>;
60
+ <Button variant="primary" onClick={() => toast('Saved')}>
61
+ Save
62
+ </Button>;
50
63
  <Toaster />;
51
64
  ```
52
65
 
53
66
  ## Components
54
67
 
55
- | Polykit React | CSS | Behavior | shadcn/ui equivalent |
56
- | --- | --- | --- | --- |
57
- | `Button`, `buttonClassName()` | `.pk-button` | native | Button |
58
- | `IconButton` | `.pk-icon-button` | native | Button `size="icon"` |
59
- | `Link` | `.pk-link` | native | Button `variant="link"` |
60
- | `Icon`, `IconProvider` | `.pk-icon` | sprite `<use>` | (lucide-react) |
61
- | `Badge`, `StatusPill` | `.pk-badge`, `.pk-status` | — | Badge |
62
- | `Card` | `.pk-card` | — | Card (the surface only) |
63
- | `Banner`, `BannerText`, `BannerActions` | `.pk-banner` | — | Alert |
64
- | `Callout`, `Empty`, `Progress`, `Separator` | `.pk-callout`, `.pk-empty`, `.pk-progress`, `.pk-separator` | — | —, Empty, Progress, Separator |
65
- | `Avatar`, `AvatarImage`, `AvatarFallback` | `.pk-avatar`, `.pk-monogram` | — | Avatar |
66
- | `Field`, `Label`, `Input`, `Textarea`, `NativeSelect`, `FormGrid`, `FormActions` | `.pk-field`, `.pk-input` … | native | Field, Label, Input, Textarea, NativeSelect |
67
- | `Checkbox`, `RadioGroup`, `RadioGroupItem`, `Choice` | `.pk-checkbox`, `.pk-radio`, `.pk-choice` | native inputs | Checkbox, RadioGroup |
68
- | `Switch` | `.pk-switch` | Radix Switch | Switch |
69
- | `CheckRound` | `.pk-check-round` | Radix Toggle | Checkbox (round) |
70
- | `Chip` | `.pk-chip` | Radix Toggle | Toggle |
71
- | `SegmentedControl`, `SegmentedControlItem` | `.pk-segmented` | Radix ToggleGroup (single) | ToggleGroup `type="single"` |
72
- | `Tabs`, `TabsList`, `TabsTrigger`, `TabsContent`, `TabsCount` | `.pk-tabs` | Radix Tabs | Tabs |
73
- | `NavTabs`, `NavTab` | `.pk-tabs` (links) | native | NavigationMenu |
74
- | `DropdownMenu*` | `.pk-menu` | Radix DropdownMenu | DropdownMenu |
75
- | `ContextMenu*` | `.pk-menu` | Radix ContextMenu | ContextMenu |
76
- | `Popover*` | `.pk-popover` | Radix Popover | Popover |
77
- | `Dialog*`, `AlertDialog*` | `.pk-dialog` | native `<dialog>` | Dialog, AlertDialog |
78
- | `Toaster`, `toast()` | `.pk-toast` | own (one at a time, as `toast.js`) | Sonner |
79
- | `Table*` | `.pk-table` | native | Table |
68
+ | Polykit React | CSS | Behavior | shadcn/ui equivalent |
69
+ | -------------------------------------------------------------------------------- | ----------------------------------------------------------- | ---------------------------------- | ------------------------------------------- |
70
+ | `Button`, `buttonClassName()` | `.pk-button` | native | Button |
71
+ | `IconButton` | `.pk-icon-button` | native | Button `size="icon"` |
72
+ | `Link` | `.pk-link` | native | Button `variant="link"` |
73
+ | `Icon`, `IconProvider` | `.pk-icon` | sprite `<use>` | (lucide-react) |
74
+ | `Badge`, `StatusPill` | `.pk-badge`, `.pk-status` | — | Badge |
75
+ | `Card` | `.pk-card` | — | Card (the surface only) |
76
+ | `Banner`, `BannerText`, `BannerActions` | `.pk-banner` | — | Alert |
77
+ | `Callout`, `Empty`, `Progress`, `Separator` | `.pk-callout`, `.pk-empty`, `.pk-progress`, `.pk-separator` | — | —, Empty, Progress, Separator |
78
+ | `Avatar`, `AvatarImage`, `AvatarFallback` | `.pk-avatar`, `.pk-monogram` | — | Avatar |
79
+ | `Field`, `Label`, `Input`, `Textarea`, `NativeSelect`, `FormGrid`, `FormActions` | `.pk-field`, `.pk-input` … | native | Field, Label, Input, Textarea, NativeSelect |
80
+ | `Checkbox`, `RadioGroup`, `RadioGroupItem`, `Choice` | `.pk-checkbox`, `.pk-radio`, `.pk-choice` | native inputs | Checkbox, RadioGroup |
81
+ | `Switch` | `.pk-switch` | Radix Switch | Switch |
82
+ | `CheckRound` | `.pk-check-round` | Radix Toggle | Checkbox (round) |
83
+ | `Chip` | `.pk-chip` | Radix Toggle | Toggle |
84
+ | `SegmentedControl`, `SegmentedControlItem` | `.pk-segmented` | Radix ToggleGroup (single) | ToggleGroup `type="single"` |
85
+ | `Tabs`, `TabsList`, `TabsTrigger`, `TabsContent`, `TabsCount` | `.pk-tabs` | Radix Tabs | Tabs |
86
+ | `NavTabs`, `NavTab` | `.pk-tabs` (links) | native | NavigationMenu |
87
+ | `DropdownMenu*` | `.pk-menu` | Radix DropdownMenu | DropdownMenu |
88
+ | `ContextMenu*` | `.pk-menu` | Radix ContextMenu | ContextMenu |
89
+ | `Popover*` | `.pk-popover` | Radix Popover | Popover |
90
+ | `Dialog*`, `AlertDialog*` | `.pk-dialog` | native `<dialog>` | Dialog, AlertDialog |
91
+ | `Toaster`, `toast()` | `.pk-toast` | own (one at a time, as `toast.js`) | Sonner |
92
+ | `Table*` | `.pk-table` | native | Table |
93
+
94
+ ### App shell and page parts
95
+
96
+ | Polykit React | CSS | shadcn/ui equivalent |
97
+ | --- | --- | --- |
98
+ | `AppShell`, `ShellMain`, `useAppShell()` | `.pk-shell`, `.pk-scrim` | SidebarProvider |
99
+ | `Sidebar`, `SidebarBrand`, `Wordmark`, `SidebarNav`, `SidebarGroup`, `SidebarItem`, `SidebarSubItem`, `SidebarFoot`, `SidebarCollapse`, `SidebarThemeToggle` | `.pk-sidebar` | Sidebar |
100
+ | `Topbar`, `TopbarStart`, `TopbarMid`, `TopbarEnd`, `TopbarContext`, `TopbarMenuButton`, `Search` | `.pk-topbar`, `.pk-search` | — |
101
+ | `Content`, `Page` | `.pk-content`, `.pk-page` | SidebarInset |
102
+ | `SidePanel`, `SidePanelHeader`, `SidePanelBody`, `SidePanelFooter` | `.pk-panel` | Sheet |
103
+ | `PageHeader`, `PageHeaderTitle`, `PageHeaderActions`, `PageHeaderDescription` | `.pk-page-header` | — |
104
+ | `Group`, `Count`, `Row`, `Meta`, `MetaItem` | `.pk-group`, `.pk-row`, `.pk-meta` | — |
105
+ | `Pagination`, `pageRange()` | `.pk-pagination` | Pagination |
106
+ | `useTheme()`, `polykitBootScript` | `boot.js`, `theme.js` | (next-themes) |
107
+
108
+ The shell keeps its state on `<html>` (`data-sidebar="rail"`, `data-sidebar-open`, `data-panel-open`), as the CSS expects ([ADR 0036](../../docs/adr/0036-react-app-shell.md)). Put the boot script in `<head>` so a saved theme and rail apply before the first paint:
109
+
110
+ ```tsx
111
+ // Next.js app/layout.tsx
112
+ import { polykitBootScript } from '@polyfen/polykit-react';
113
+
114
+ <html lang="en" suppressHydrationWarning>
115
+ <head>
116
+ <script dangerouslySetInnerHTML={{ __html: polykitBootScript }} />
117
+ </head>
118
+ <body>{children}</body>
119
+ </html>;
120
+ ```
121
+
122
+ ```tsx
123
+ <AppShell>
124
+ <Sidebar>
125
+ <SidebarBrand>
126
+ <Wordmark href="/">Lumen</Wordmark>
127
+ </SidebarBrand>
128
+ <SidebarNav aria-label="Projects">
129
+ <SidebarGroup label="Projects">
130
+ <SidebarItem asChild icon="grid" current>
131
+ <NextLink href="/">All projects</NextLink>
132
+ </SidebarItem>
133
+ </SidebarGroup>
134
+ </SidebarNav>
135
+ <SidebarFoot>
136
+ <SidebarThemeToggle />
137
+ <SidebarCollapse />
138
+ </SidebarFoot>
139
+ </Sidebar>
140
+ <ShellMain>
141
+ <Topbar>
142
+ <TopbarStart>
143
+ <TopbarMenuButton />
144
+ <TopbarContext>Week 47</TopbarContext>
145
+ </TopbarStart>
146
+ </Topbar>
147
+ <Content>
148
+ <Page>{children}</Page>
149
+ </Content>
150
+ </ShellMain>
151
+ </AppShell>
152
+ ```
80
153
 
81
154
  ### Where Polykit differs from shadcn
82
155
 
@@ -87,7 +160,7 @@ import { Button, Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger
87
160
 
88
161
  ### Not here yet
89
162
 
90
- Anything else falls back to shadcn/ui, themed by `@polyfen/polykit-tokens/shadcn.css` ([fallback policy](../../docs/FALLBACK.md)): Tooltip, Select, Combobox, Command, Accordion, Sheet and the rest. The app shell, side panel, board, calendar and chat come in a later stage.
163
+ Anything else falls back to shadcn/ui, themed by `@polyfen/polykit-tokens/shadcn.css` ([fallback policy](../../docs/FALLBACK.md)): Tooltip, Select, Combobox, Command, Accordion and the rest. The board, calendar and chat come in a later stage.
91
164
 
92
165
  ## License
93
166
 
@@ -0,0 +1,97 @@
1
+ import { type HTMLAttributes, type MouseEvent, type ReactNode } from 'react';
2
+ import { type CategoryColor } from './display.js';
3
+ /**
4
+ * The head of a page (`.pk-page-header`): an optional icon, the title, the actions and a line of
5
+ * description, in that order. On a narrow page the actions move to their own row.
6
+ */
7
+ export declare const PageHeader: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLElement> & import("react").RefAttributes<HTMLElement>>;
8
+ /** The page's title (`h1.pk-page-header__title`); a count or badge may follow the words. */
9
+ export declare const PageHeaderTitle: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLHeadingElement> & import("react").RefAttributes<HTMLHeadingElement>>;
10
+ export declare const PageHeaderActions: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLDivElement> & import("react").RefAttributes<HTMLDivElement>>;
11
+ export declare const PageHeaderDescription: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLParagraphElement> & import("react").RefAttributes<HTMLParagraphElement>>;
12
+ /** A number beside a heading (`.pk-count`). */
13
+ export declare const Count: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLSpanElement> & import("react").RefAttributes<HTMLSpanElement>>;
14
+ export interface GroupProps extends Omit<HTMLAttributes<HTMLElement>, 'title'> {
15
+ title: ReactNode;
16
+ /** How many rows are in the group. */
17
+ count?: ReactNode;
18
+ /** The heading's level; 2 by default. */
19
+ level?: 2 | 3 | 4 | 5 | 6;
20
+ /** Put the children in a card (the default), or lay them out yourself. */
21
+ card?: boolean;
22
+ }
23
+ /** A titled section of a page (`.pk-group`): a heading with a count, then a card of rows. */
24
+ export declare const Group: import("react").ForwardRefExoticComponent<GroupProps & import("react").RefAttributes<HTMLElement>>;
25
+ /** The quiet line of facts under a row title (`.pk-meta`): one element per fact. */
26
+ export declare const Meta: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLDivElement> & import("react").RefAttributes<HTMLDivElement>>;
27
+ export interface MetaItemProps extends HTMLAttributes<HTMLSpanElement> {
28
+ /** The CSS adds a prefix or a color for each kind; write the words, not the symbols. */
29
+ kind?: 'owner' | 'due' | 'attention' | 'carried' | 'repeat';
30
+ /** For `due`: past due. Say "overdue" in the words too. */
31
+ overdue?: boolean;
32
+ }
33
+ export declare const MetaItem: import("react").ForwardRefExoticComponent<MetaItemProps & import("react").RefAttributes<HTMLSpanElement>>;
34
+ export interface RowProps extends Omit<HTMLAttributes<HTMLElement>, 'title'> {
35
+ title: ReactNode;
36
+ /** The line under the title: a `Meta`. */
37
+ meta?: ReactNode;
38
+ /** A body that opens: the row becomes a `<details>`. Its summary must not hold controls. */
39
+ body?: ReactNode;
40
+ /** With a body: open at first. */
41
+ defaultOpen?: boolean;
42
+ /** Make the title a link (a row that opens a page). */
43
+ href?: string;
44
+ /** Make the title a button (a row that opens a panel or dialog). */
45
+ onOpen?: (event: MouseEvent<HTMLButtonElement>) => void;
46
+ /** A completion control before the title (a `CheckRound`). Not with a body. */
47
+ check?: ReactNode;
48
+ /** A category tile or icon before the title. */
49
+ icon?: ReactNode;
50
+ /** A bar down the left edge: a category hue, or any color token. Say the category in words. */
51
+ color?: CategoryColor | (string & {});
52
+ /** A quiet delete button at the end; its name, such as "Delete Draft the brief". */
53
+ removeLabel?: string;
54
+ onRemove?: () => void;
55
+ done?: boolean;
56
+ /** Selected: the accent tint and ring. Also expose it (a checkbox, or `aria-selected`). */
57
+ selected?: boolean;
58
+ /** Only reports: no pointer, no hover. */
59
+ static?: boolean;
60
+ /** The element for a plain row; `li` inside a list. */
61
+ as?: 'div' | 'li';
62
+ }
63
+ /**
64
+ * A row in a list (`.pk-row`): a title, a line of meta, and optionally a body that opens. Put
65
+ * rows in a `Card` (or a `Group`) and they get separators.
66
+ */
67
+ export declare const Row: import("react").ForwardRefExoticComponent<RowProps & import("react").RefAttributes<HTMLElement>>;
68
+ /** The pages to show: the first, the last, the current and its neighbors, with gaps (null). */
69
+ export declare function pageRange(page: number, pageCount: number, siblings?: number): (number | null)[];
70
+ export interface PaginationProps extends Omit<HTMLAttributes<HTMLElement>, 'onChange'> {
71
+ /** The current page, from 1. */
72
+ page: number;
73
+ /** How many pages. Leave it out when the total is unknown: Previous, "Page N" and Next. */
74
+ pageCount?: number;
75
+ /** Pages are buttons that call this… */
76
+ onPageChange?: (page: number) => void;
77
+ /** …or links to this URL. */
78
+ getPageHref?: (page: number) => string;
79
+ /** The summary, such as "26–50 of 312". */
80
+ summary?: ReactNode;
81
+ /** Neighbors of the current page to show on each side. */
82
+ siblings?: number;
83
+ /** Rows per page, with a select to change it. */
84
+ pageSize?: number;
85
+ pageSizeOptions?: number[];
86
+ onPageSizeChange?: (size: number) => void;
87
+ /** The navigation's name. */
88
+ 'aria-label'?: string;
89
+ labels?: {
90
+ previous?: string;
91
+ next?: string;
92
+ rows?: string;
93
+ page?: (page: number) => string;
94
+ };
95
+ }
96
+ /** Pages of a list or table (`.pk-pagination`). */
97
+ export declare const Pagination: import("react").ForwardRefExoticComponent<PaginationProps & import("react").RefAttributes<HTMLElement>>;
@@ -0,0 +1,120 @@
1
+ 'use client';
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { forwardRef, useId, } from 'react';
4
+ import { cx } from '../lib/cx.js';
5
+ import { Card } from './display.js';
6
+ import { Icon } from './icon.js';
7
+ /* ---- page header ---- */
8
+ /**
9
+ * The head of a page (`.pk-page-header`): an optional icon, the title, the actions and a line of
10
+ * description, in that order. On a narrow page the actions move to their own row.
11
+ */
12
+ export const PageHeader = forwardRef(function PageHeader({ className, ...props }, ref) {
13
+ return _jsx("header", { ref: ref, className: cx('pk-page-header', className), ...props });
14
+ });
15
+ /** The page's title (`h1.pk-page-header__title`); a count or badge may follow the words. */
16
+ export const PageHeaderTitle = forwardRef(function PageHeaderTitle({ className, ...props }, ref) {
17
+ return _jsx("h1", { ref: ref, className: cx('pk-page-header__title', className), ...props });
18
+ });
19
+ export const PageHeaderActions = forwardRef(function PageHeaderActions({ className, ...props }, ref) {
20
+ return _jsx("div", { ref: ref, className: cx('pk-page-header__actions', className), ...props });
21
+ });
22
+ export const PageHeaderDescription = forwardRef(function PageHeaderDescription({ className, ...props }, ref) {
23
+ return _jsx("p", { ref: ref, className: cx('pk-page-header__description', className), ...props });
24
+ });
25
+ /* ---- group and count ---- */
26
+ /** A number beside a heading (`.pk-count`). */
27
+ export const Count = forwardRef(function Count({ className, ...props }, ref) {
28
+ return _jsx("span", { ref: ref, className: cx('pk-count', className), ...props });
29
+ });
30
+ /** A titled section of a page (`.pk-group`): a heading with a count, then a card of rows. */
31
+ export const Group = forwardRef(function Group({ title, count, level = 2, card = true, className, children, ...props }, ref) {
32
+ const headingId = `pk-group-${useId()}`;
33
+ const Heading = `h${level}`;
34
+ return (_jsxs("section", { ref: ref, className: cx('pk-group', className), "aria-labelledby": headingId, ...props, children: [_jsxs(Heading, { className: "pk-group__heading", id: headingId, children: [title, count != null && (_jsxs(_Fragment, { children: [' ', _jsx(Count, { children: count })] }))] }), card ? _jsx(Card, { children: children }) : children] }));
35
+ });
36
+ /* ---- meta ---- */
37
+ /** The quiet line of facts under a row title (`.pk-meta`): one element per fact. */
38
+ export const Meta = forwardRef(function Meta({ className, ...props }, ref) {
39
+ return _jsx("div", { ref: ref, className: cx('pk-meta', className), ...props });
40
+ });
41
+ export const MetaItem = forwardRef(function MetaItem({ kind, overdue, className, ...props }, ref) {
42
+ return (_jsx("span", { ref: ref, className: cx(kind && `pk-meta__${kind}`, kind === 'due' && overdue && 'pk-meta__due--overdue', className) || undefined, ...props }));
43
+ });
44
+ const CATEGORY = new Set(['rose', 'green', 'indigo', 'sky', 'purple', 'amber', 'teal', 'gray']);
45
+ /**
46
+ * A row in a list (`.pk-row`): a title, a line of meta, and optionally a body that opens. Put
47
+ * rows in a `Card` (or a `Group`) and they get separators.
48
+ */
49
+ export const Row = forwardRef(function Row({ title, meta, body, defaultOpen, href, onOpen, check, icon, color, removeLabel, onRemove, done, selected, static: isStatic, as = 'div', className, style, ...props }, ref) {
50
+ const titleEl = href !== undefined ? (_jsx("a", { className: "pk-row__title", href: href, children: title })) : onOpen ? (_jsx("button", { type: "button", className: "pk-row__title", onClick: onOpen, children: title })) : (_jsx("span", { className: "pk-row__title", children: title }));
51
+ const inside = (_jsxs(_Fragment, { children: [check != null && _jsx("span", { className: "pk-row__check", children: check }), icon != null && _jsx("span", { className: "pk-row__icon", children: icon }), titleEl, meta, onRemove && (_jsx("button", { type: "button", className: "pk-row__trailing", "aria-label": removeLabel ?? 'Remove', onClick: onRemove, children: "\u00D7" }))] }));
52
+ const shared = {
53
+ className: cx('pk-row', check != null && 'pk-row--with-check', icon != null && 'pk-row--with-icon', onRemove && 'pk-row--with-trailing', isStatic && 'pk-row--static', className),
54
+ style: color
55
+ ? {
56
+ '--pk-row-color': CATEGORY.has(color) ? `var(--pk-color-cat-${color})` : color,
57
+ ...style,
58
+ }
59
+ : style,
60
+ 'data-done': done ? '' : undefined,
61
+ 'data-selected': selected ? '' : undefined,
62
+ ...props,
63
+ };
64
+ if (body != null) {
65
+ return (_jsxs("details", { ref: ref, open: defaultOpen, ...shared, children: [_jsx("summary", { className: "pk-row__summary", children: inside }), _jsx("div", { className: "pk-row__body", children: body })] }));
66
+ }
67
+ const Tag = as;
68
+ return (_jsx(Tag, { ref: ref, ...shared, children: _jsx("div", { className: "pk-row__summary", children: inside }) }));
69
+ });
70
+ /* ---- pagination ---- */
71
+ /** The pages to show: the first, the last, the current and its neighbors, with gaps (null). */
72
+ export function pageRange(page, pageCount, siblings = 1) {
73
+ const pages = new Set([1, pageCount]);
74
+ for (let p = page - siblings; p <= page + siblings; p++) {
75
+ if (p >= 1 && p <= pageCount)
76
+ pages.add(p);
77
+ }
78
+ const sorted = [...pages].filter((p) => p >= 1).sort((a, b) => a - b);
79
+ const out = [];
80
+ sorted.forEach((p, i) => {
81
+ if (i > 0) {
82
+ const gap = p - sorted[i - 1];
83
+ if (gap === 2)
84
+ out.push(p - 1);
85
+ else if (gap > 2)
86
+ out.push(null);
87
+ }
88
+ out.push(p);
89
+ });
90
+ return out;
91
+ }
92
+ /** Pages of a list or table (`.pk-pagination`). */
93
+ export const Pagination = forwardRef(function Pagination({ page, pageCount, onPageChange, getPageHref, summary, siblings = 1, pageSize, pageSizeOptions, onPageSizeChange, 'aria-label': label = 'Pages', labels = {}, className, ...props }, ref) {
94
+ const sizeId = `pk-pagination-${useId()}-size`;
95
+ const { previous = 'Previous page', next = 'Next page', rows = 'Rows', page: pageLabel = (p) => `Page ${p}`, } = labels;
96
+ const link = (target, content, { name, current, disabled }) => {
97
+ const common = {
98
+ className: 'pk-pagination__page',
99
+ 'aria-label': name,
100
+ 'aria-current': current ? 'page' : undefined,
101
+ 'aria-disabled': disabled ? true : undefined,
102
+ };
103
+ if (getPageHref) {
104
+ return disabled ? (_jsx("a", { role: "link", ...common, children: content })) : (_jsx("a", { href: getPageHref(target), ...common, children: content }));
105
+ }
106
+ return (_jsx("button", { type: "button", ...common, onClick: () => {
107
+ if (!disabled && !current)
108
+ onPageChange?.(target);
109
+ }, children: content }));
110
+ };
111
+ const known = typeof pageCount === 'number';
112
+ const last = known ? Math.max(1, pageCount) : undefined;
113
+ return (_jsxs("nav", { ref: ref, className: cx('pk-pagination', className), "aria-label": label, ...props, children: [summary != null && _jsx("p", { className: "pk-pagination__summary", children: summary }), _jsxs("ul", { className: "pk-pagination__pages", children: [_jsx("li", { children: link(page - 1, _jsx(Icon, { name: "chevron-left" }), {
114
+ name: previous,
115
+ disabled: page <= 1,
116
+ }) }), known ? (pageRange(page, last, siblings).map((p, i) => (_jsx("li", { children: p === null ? (_jsx("span", { className: "pk-pagination__gap", "aria-hidden": "true", children: "\u2026" })) : (link(p, p, { current: p === page, name: p === page ? undefined : pageLabel(p) })) }, p ?? `gap-${i}`)))) : (_jsx("li", { children: _jsx("span", { className: "pk-pagination__page", "aria-current": "page", children: pageLabel(page) }) })), _jsx("li", { children: link(page + 1, _jsx(Icon, { name: "chevron-right" }), {
117
+ name: next,
118
+ disabled: known ? page >= last : false,
119
+ }) })] }), pageSize !== undefined && pageSizeOptions && (_jsxs("label", { className: "pk-pagination__size", htmlFor: sizeId, children: [rows, ' ', _jsx("select", { id: sizeId, className: "pk-select pk-select--compact", value: pageSize, onChange: (event) => onPageSizeChange?.(Number(event.currentTarget.value)), children: pageSizeOptions.map((size) => (_jsx("option", { value: size, children: size }, size))) })] }))] }));
120
+ });
@@ -0,0 +1,153 @@
1
+ import { type AnchorHTMLAttributes, type HTMLAttributes, type InputHTMLAttributes, type MouseEvent, type ReactNode } from 'react';
2
+ import { type IconName } from './icon.js';
3
+ interface ShellContextValue {
4
+ rail: boolean;
5
+ setRail: (rail: boolean) => void;
6
+ toggleRail: () => void;
7
+ narrow: boolean;
8
+ drawerOpen: boolean;
9
+ setDrawerOpen: (open: boolean, options?: {
10
+ restoreFocus?: boolean;
11
+ }) => void;
12
+ panelOpen: boolean;
13
+ setPanelOpen: (open: boolean) => void;
14
+ sidebarId: string;
15
+ sidebarRef: {
16
+ current: HTMLElement | null;
17
+ };
18
+ menuButtonRef: {
19
+ current: HTMLElement | null;
20
+ };
21
+ }
22
+ /** The app shell's state: the rail, the phone drawer and the side panel. Use it inside `AppShell`. */
23
+ export declare function useAppShell(): ShellContextValue;
24
+ export interface AppShellProps extends HTMLAttributes<HTMLDivElement> {
25
+ /** Start as the icon rail. Left out: the saved choice, else the rail on windows up to 1100px. */
26
+ defaultRail?: boolean;
27
+ /** Control the rail yourself. */
28
+ rail?: boolean;
29
+ onRailChange?: (rail: boolean) => void;
30
+ /** Save the rail choice as `pk.sidebar`, which the boot script reads. On by default. */
31
+ persist?: boolean;
32
+ }
33
+ /**
34
+ * The app shell (`.pk-shell`): the dark frame of sidebar and top bar around the content. Its
35
+ * state lives on `<html>` (`data-sidebar="rail"`, `data-sidebar-open`, `data-panel-open`), where
36
+ * the CSS and the boot script expect it. It also renders the scrim behind the phone drawer.
37
+ */
38
+ export declare const AppShell: import("react").ForwardRefExoticComponent<AppShellProps & import("react").RefAttributes<HTMLDivElement>>;
39
+ /** The column beside the sidebar (`.pk-shell__main`): the top bar, then the content. */
40
+ export declare const ShellMain: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLDivElement> & import("react").RefAttributes<HTMLDivElement>>;
41
+ /**
42
+ * The sidebar (`.pk-sidebar`): full width, an icon rail, or a drawer on phones. Following a link
43
+ * in the drawer closes it; a button closes it only with `data-pk-sidebar-close`.
44
+ */
45
+ export declare const Sidebar: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLElement> & import("react").RefAttributes<HTMLElement>>;
46
+ /** The top of the sidebar, as tall as the top bar (`.pk-sidebar__brand`). */
47
+ export declare const SidebarBrand: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLDivElement> & import("react").RefAttributes<HTMLDivElement>>;
48
+ export interface WordmarkProps extends AnchorHTMLAttributes<HTMLAnchorElement> {
49
+ /** The project's mark (an svg); it stays on the rail. It is decoration: the name is the text. */
50
+ mark?: ReactNode;
51
+ asChild?: boolean;
52
+ }
53
+ /** The product's name and mark (`.pk-wordmark`), usually a link home. */
54
+ export declare const Wordmark: import("react").ForwardRefExoticComponent<WordmarkProps & import("react").RefAttributes<HTMLAnchorElement>>;
55
+ export interface SidebarNavProps extends HTMLAttributes<HTMLElement> {
56
+ /** The navigation's name ("Projects", "Main"). */
57
+ 'aria-label': string;
58
+ }
59
+ /** The scrolling middle of the sidebar (`nav.pk-sidebar__groups`). */
60
+ export declare const SidebarNav: import("react").ForwardRefExoticComponent<SidebarNavProps & import("react").RefAttributes<HTMLElement>>;
61
+ export interface SidebarGroupProps extends HTMLAttributes<HTMLDivElement> {
62
+ /** The section's name. In the rail a short rule stands in for it. */
63
+ label?: ReactNode;
64
+ }
65
+ /** A section of the sidebar (`.pk-sidebar__group`): a label and a list of items. */
66
+ export declare const SidebarGroup: import("react").ForwardRefExoticComponent<SidebarGroupProps & import("react").RefAttributes<HTMLDivElement>>;
67
+ export interface SidebarItemProps extends AnchorHTMLAttributes<HTMLAnchorElement> {
68
+ /** An icon name from the sprite, or any icon element (a monogram). */
69
+ icon?: IconName | ReactNode;
70
+ /** The page this item opens is the one showing. */
71
+ current?: boolean;
72
+ /** A sub-item of this item is current: the rail, which hides sub-items, marks this one. */
73
+ currentParent?: boolean;
74
+ /** A count after the label. */
75
+ count?: ReactNode;
76
+ /** Sub-items (`SidebarSubItem`), listed under this item; the rail hides them. */
77
+ subItems?: ReactNode;
78
+ /** Render the child (a router's link) as the item; its children are the label. */
79
+ asChild?: boolean;
80
+ /** Without `href`, the item is a button (in the foot: Feedback, a theme switch). */
81
+ onClick?: (event: MouseEvent<HTMLElement>) => void;
82
+ }
83
+ /** A sidebar item (`.pk-sidebar__item`): a link (or a button without `href`). */
84
+ export declare const SidebarItem: import("react").ForwardRefExoticComponent<SidebarItemProps & import("react").RefAttributes<HTMLElement>>;
85
+ /** A sub-item under a `SidebarItem`: a shorter row with a dot where the icon goes. */
86
+ export declare const SidebarSubItem: import("react").ForwardRefExoticComponent<Omit<SidebarItemProps, "icon" | "subItems"> & import("react").RefAttributes<HTMLElement>>;
87
+ /** The bottom of the sidebar (`.pk-sidebar__foot`): feedback, theme, collapse. */
88
+ export declare const SidebarFoot: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLDivElement> & import("react").RefAttributes<HTMLDivElement>>;
89
+ export interface SidebarCollapseProps extends HTMLAttributes<HTMLButtonElement> {
90
+ /** The visible label. */
91
+ label?: string;
92
+ }
93
+ /** The rail toggle, in the foot (`.pk-sidebar__collapse`). Hidden on phones. */
94
+ export declare const SidebarCollapse: import("react").ForwardRefExoticComponent<SidebarCollapseProps & import("react").RefAttributes<HTMLButtonElement>>;
95
+ /** The theme switch, as a sidebar item: Auto, Light, Dark in turn. */
96
+ export declare const SidebarThemeToggle: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLButtonElement> & import("react").RefAttributes<HTMLButtonElement>>;
97
+ /** The top bar (`.pk-topbar`), in the frame: start, middle and end. */
98
+ export declare const Topbar: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLElement> & import("react").RefAttributes<HTMLElement>>;
99
+ export declare const TopbarStart: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLDivElement> & import("react").RefAttributes<HTMLDivElement>>;
100
+ export declare const TopbarMid: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLDivElement> & import("react").RefAttributes<HTMLDivElement>>;
101
+ export declare const TopbarEnd: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLDivElement> & import("react").RefAttributes<HTMLDivElement>>;
102
+ /** Where you are, in the top bar (`.pk-topbar__context`). */
103
+ export declare const TopbarContext: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLSpanElement> & import("react").RefAttributes<HTMLSpanElement>>;
104
+ export interface TopbarMenuButtonProps extends HTMLAttributes<HTMLButtonElement> {
105
+ 'aria-label'?: string;
106
+ }
107
+ /** Opens the sidebar drawer on phones (`.pk-topbar__menu`); hidden on wider screens. */
108
+ export declare const TopbarMenuButton: import("react").ForwardRefExoticComponent<TopbarMenuButtonProps & import("react").RefAttributes<HTMLButtonElement>>;
109
+ export interface SearchProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'type'> {
110
+ /** `frame` is for the dark top bar. */
111
+ variant?: 'default' | 'frame';
112
+ /** A search field has no visible label, so it needs a name. */
113
+ 'aria-label': string;
114
+ /** Classes for the wrapper. */
115
+ wrapperClassName?: string;
116
+ }
117
+ /** The search field (`.pk-search`): an icon inside a rounded input. */
118
+ export declare const Search: import("react").ForwardRefExoticComponent<SearchProps & import("react").RefAttributes<HTMLInputElement>>;
119
+ /**
120
+ * The page area (`main.pk-content`): it scrolls on its own, and its corner tightens once the
121
+ * content is under the top bar. Focusable, so the keyboard can scroll it.
122
+ */
123
+ export declare const Content: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLElement> & import("react").RefAttributes<HTMLElement>>;
124
+ export interface PageProps extends HTMLAttributes<HTMLDivElement> {
125
+ /** Fill the content's height (a board, a calendar). */
126
+ fill?: boolean;
127
+ }
128
+ /** The page inside the content (`.pk-page`), a size container for its parts. */
129
+ export declare const Page: import("react").ForwardRefExoticComponent<PageProps & import("react").RefAttributes<HTMLDivElement>>;
130
+ export interface SidePanelProps extends HTMLAttributes<HTMLElement> {
131
+ open: boolean;
132
+ onOpenChange: (open: boolean) => void;
133
+ }
134
+ /**
135
+ * A side panel under the top bar (`.pk-panel`): chat, details. Wide windows make room for it;
136
+ * narrower ones lay it over the page; phones give it the screen. Opening it focuses an element
137
+ * with `data-autofocus` or the first field; Escape and the close button close it and return
138
+ * focus to where it was. Inside an `AppShell` it sets `data-panel-open`.
139
+ */
140
+ export declare const SidePanel: import("react").ForwardRefExoticComponent<SidePanelProps & import("react").RefAttributes<HTMLElement>>;
141
+ export interface SidePanelHeaderProps extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {
142
+ /** An icon name or element before the title. */
143
+ icon?: IconName | ReactNode;
144
+ title: ReactNode;
145
+ /** A quiet note after the title (a model name, a count). */
146
+ meta?: ReactNode;
147
+ closeLabel?: string;
148
+ }
149
+ /** The panel's head (`.pk-panel__head`): icon, title, meta and the close button. */
150
+ export declare const SidePanelHeader: import("react").ForwardRefExoticComponent<SidePanelHeaderProps & import("react").RefAttributes<HTMLDivElement>>;
151
+ export declare const SidePanelBody: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLDivElement> & import("react").RefAttributes<HTMLDivElement>>;
152
+ export declare const SidePanelFooter: import("react").ForwardRefExoticComponent<HTMLAttributes<HTMLDivElement> & import("react").RefAttributes<HTMLDivElement>>;
153
+ export {};
@@ -0,0 +1,359 @@
1
+ 'use client';
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { Slot } from 'radix-ui';
4
+ import { Children, cloneElement, createContext, forwardRef, isValidElement, useCallback, useContext, useEffect, useId, useMemo, useRef, useState, } from 'react';
5
+ import { composeRefs } from '../lib/compose-refs.js';
6
+ import { cx } from '../lib/cx.js';
7
+ import { FIELD, FOCUSABLE, matches, readStorage, useIsomorphicLayoutEffect, writeStorage, } from '../lib/dom.js';
8
+ import { IconButton } from './button.js';
9
+ import { Icon } from './icon.js';
10
+ import { useTheme } from './theme.js';
11
+ /* The breakpoints the CSS uses: md (the drawer) and lg (the rail by default). Tests keep them
12
+ equal to the tokens. */
13
+ const DRAWER = '(max-width: 760px)';
14
+ const RAIL_BY_DEFAULT = '(max-width: 1100px)';
15
+ const SIDEBAR_KEY = 'pk.sidebar';
16
+ const ShellContext = createContext(null);
17
+ /** The app shell's state: the rail, the phone drawer and the side panel. Use it inside `AppShell`. */
18
+ export function useAppShell() {
19
+ const ctx = useContext(ShellContext);
20
+ if (!ctx)
21
+ throw new Error('useAppShell must be used inside an AppShell.');
22
+ return ctx;
23
+ }
24
+ /**
25
+ * The app shell (`.pk-shell`): the dark frame of sidebar and top bar around the content. Its
26
+ * state lives on `<html>` (`data-sidebar="rail"`, `data-sidebar-open`, `data-panel-open`), where
27
+ * the CSS and the boot script expect it. It also renders the scrim behind the phone drawer.
28
+ */
29
+ export const AppShell = forwardRef(function AppShell({ defaultRail, rail: railProp, onRailChange, persist = true, className, children, ...props }, ref) {
30
+ const [ownRail, setOwnRail] = useState(defaultRail ?? false);
31
+ const [ready, setReady] = useState(false);
32
+ const [narrow, setNarrow] = useState(false);
33
+ const [drawerOpen, setDrawerState] = useState(false);
34
+ const [panelOpen, setPanelOpen] = useState(false);
35
+ const rail = railProp ?? ownRail;
36
+ const sidebarId = `pk-sidebar-${useId()}`;
37
+ const sidebarRef = useRef(null);
38
+ const menuButtonRef = useRef(null);
39
+ const opener = useRef(null);
40
+ // First paint follows the boot script (or the saved choice, or the window), not the server.
41
+ useIsomorphicLayoutEffect(() => {
42
+ if (defaultRail === undefined && railProp === undefined) {
43
+ const attr = document.documentElement.getAttribute('data-sidebar');
44
+ const saved = readStorage(SIDEBAR_KEY);
45
+ setOwnRail(attr === 'rail' || saved === 'rail' || (saved === null && matches(RAIL_BY_DEFAULT)));
46
+ }
47
+ setNarrow(matches(DRAWER));
48
+ setReady(true);
49
+ // Only on mount: later changes come from the toggle.
50
+ }, []);
51
+ // Write the state where the CSS reads it.
52
+ useIsomorphicLayoutEffect(() => {
53
+ if (!ready)
54
+ return;
55
+ const html = document.documentElement;
56
+ if (rail)
57
+ html.setAttribute('data-sidebar', 'rail');
58
+ else
59
+ html.removeAttribute('data-sidebar');
60
+ html.toggleAttribute('data-sidebar-open', drawerOpen);
61
+ html.toggleAttribute('data-panel-open', panelOpen);
62
+ }, [ready, rail, drawerOpen, panelOpen]);
63
+ useEffect(() => () => {
64
+ const html = document.documentElement;
65
+ html.removeAttribute('data-sidebar-open');
66
+ html.removeAttribute('data-panel-open');
67
+ }, []);
68
+ const setRail = useCallback((next) => {
69
+ if (railProp === undefined)
70
+ setOwnRail(next);
71
+ if (persist)
72
+ writeStorage(SIDEBAR_KEY, next ? 'rail' : 'expanded');
73
+ onRailChange?.(next);
74
+ }, [railProp, persist, onRailChange]);
75
+ const drawerRef = useRef(false);
76
+ drawerRef.current = drawerOpen;
77
+ const setDrawerOpen = useCallback((open, { restoreFocus = false } = {}) => {
78
+ if (drawerRef.current === open)
79
+ return;
80
+ drawerRef.current = open;
81
+ if (open) {
82
+ opener.current = document.activeElement ?? null;
83
+ }
84
+ else {
85
+ const sidebar = sidebarRef.current;
86
+ const focusInside = !!sidebar && sidebar.contains(document.activeElement);
87
+ const back = opener.current ?? menuButtonRef.current;
88
+ opener.current = null;
89
+ if (restoreFocus || focusInside)
90
+ back?.focus();
91
+ }
92
+ setDrawerState(open);
93
+ }, []);
94
+ // Opening the drawer moves focus to the current item (or the first control).
95
+ useEffect(() => {
96
+ if (!drawerOpen)
97
+ return;
98
+ const sidebar = sidebarRef.current;
99
+ (sidebar?.querySelector('[aria-current="page"]') ??
100
+ sidebar?.querySelector(FOCUSABLE))?.focus();
101
+ }, [drawerOpen]);
102
+ // Escape closes the drawer; growing past the phone breakpoint closes it too.
103
+ useEffect(() => {
104
+ if (!drawerOpen)
105
+ return;
106
+ const onKey = (event) => {
107
+ if (event.key === 'Escape')
108
+ setDrawerOpen(false, { restoreFocus: true });
109
+ };
110
+ document.addEventListener('keydown', onKey);
111
+ return () => document.removeEventListener('keydown', onKey);
112
+ }, [drawerOpen, setDrawerOpen]);
113
+ useEffect(() => {
114
+ if (typeof window.matchMedia !== 'function')
115
+ return;
116
+ const query = window.matchMedia(DRAWER);
117
+ const onChange = () => {
118
+ setNarrow(query.matches);
119
+ if (!query.matches) {
120
+ drawerRef.current = false;
121
+ setDrawerState(false);
122
+ }
123
+ };
124
+ query.addEventListener?.('change', onChange);
125
+ return () => query.removeEventListener?.('change', onChange);
126
+ }, []);
127
+ const value = useMemo(() => ({
128
+ rail,
129
+ setRail,
130
+ toggleRail: () => setRail(!rail),
131
+ narrow,
132
+ drawerOpen,
133
+ setDrawerOpen,
134
+ panelOpen,
135
+ setPanelOpen,
136
+ sidebarId,
137
+ sidebarRef,
138
+ menuButtonRef,
139
+ }), [rail, setRail, narrow, drawerOpen, setDrawerOpen, panelOpen, sidebarId]);
140
+ return (_jsxs(ShellContext.Provider, { value: value, children: [_jsx("div", { ref: ref, className: cx('pk-shell', className), ...props, children: children }), _jsx("div", { className: "pk-scrim", hidden: !drawerOpen, onClick: () => setDrawerOpen(false) })] }));
141
+ });
142
+ /** The column beside the sidebar (`.pk-shell__main`): the top bar, then the content. */
143
+ export const ShellMain = forwardRef(function ShellMain({ className, ...props }, ref) {
144
+ return _jsx("div", { ref: ref, className: cx('pk-shell__main', className), ...props });
145
+ });
146
+ /* ---- sidebar ---- */
147
+ /**
148
+ * The sidebar (`.pk-sidebar`): full width, an icon rail, or a drawer on phones. Following a link
149
+ * in the drawer closes it; a button closes it only with `data-pk-sidebar-close`.
150
+ */
151
+ export const Sidebar = forwardRef(function Sidebar({ className, onClick, ...props }, ref) {
152
+ const shell = useAppShell();
153
+ return (_jsx("aside", { ref: composeRefs(shell.sidebarRef, ref), id: shell.sidebarId, className: cx('pk-sidebar', className), onClick: (event) => {
154
+ onClick?.(event);
155
+ const target = event.target;
156
+ if (shell.narrow && target.closest?.('a[href], [data-pk-sidebar-close]')) {
157
+ shell.setDrawerOpen(false);
158
+ }
159
+ }, ...props }));
160
+ });
161
+ /** The top of the sidebar, as tall as the top bar (`.pk-sidebar__brand`). */
162
+ export const SidebarBrand = forwardRef(function SidebarBrand({ className, ...props }, ref) {
163
+ return _jsx("div", { ref: ref, className: cx('pk-sidebar__brand', className), ...props });
164
+ });
165
+ /** The product's name and mark (`.pk-wordmark`), usually a link home. */
166
+ export const Wordmark = forwardRef(function Wordmark({ mark, asChild, className, children, ...props }, ref) {
167
+ const inner = (label) => (_jsxs(_Fragment, { children: [mark != null && (_jsx("span", { className: "pk-wordmark__mark", "aria-hidden": "true", children: mark })), _jsx("span", { className: "pk-wordmark__text", children: label })] }));
168
+ if (asChild) {
169
+ const child = Children.only(children);
170
+ return (_jsx(Slot.Root, { ref: ref, className: cx('pk-wordmark', className), ...props, children: cloneElement(child, undefined, inner(child.props.children)) }));
171
+ }
172
+ return (_jsx("a", { ref: ref, className: cx('pk-wordmark', className), ...props, children: inner(children) }));
173
+ });
174
+ /** The scrolling middle of the sidebar (`nav.pk-sidebar__groups`). */
175
+ export const SidebarNav = forwardRef(function SidebarNav({ className, ...props }, ref) {
176
+ return _jsx("nav", { ref: ref, className: cx('pk-sidebar__groups', className), ...props });
177
+ });
178
+ const InListContext = createContext(false);
179
+ /** A section of the sidebar (`.pk-sidebar__group`): a label and a list of items. */
180
+ export const SidebarGroup = forwardRef(function SidebarGroup({ label, className, children, ...props }, ref) {
181
+ const labelId = `pk-sidebar-label-${useId()}`;
182
+ return (_jsxs("div", { ref: ref, className: cx('pk-sidebar__group', className), ...props, children: [label != null && (_jsx("p", { className: "pk-sidebar__label", id: labelId, children: _jsx("span", { children: label }) })), _jsx("ul", { "aria-labelledby": label != null ? labelId : undefined, children: _jsx(InListContext.Provider, { value: true, children: children }) })] }));
183
+ });
184
+ function itemLabel(label) {
185
+ return typeof label === 'string' || typeof label === 'number' ? String(label) : undefined;
186
+ }
187
+ function renderIcon(icon) {
188
+ if (icon == null)
189
+ return null;
190
+ return typeof icon === 'string' ? _jsx(Icon, { name: icon }) : icon;
191
+ }
192
+ function SidebarEntry({ sub, icon, current, currentParent, count, subItems, asChild, className, children, title, href, innerRef, ...props }) {
193
+ const shell = useContext(ShellContext);
194
+ const inList = useContext(InListContext);
195
+ const tooltips = !!shell && shell.rail && !shell.narrow;
196
+ const classes = cx('pk-sidebar__item', sub && 'pk-sidebar__sub', currentParent && 'is-current-parent', className);
197
+ const inner = (label) => (_jsxs(_Fragment, { children: [sub ? _jsx("span", { className: "pk-sidebar__dot", "aria-hidden": "true" }) : renderIcon(icon), _jsx("span", { className: "pk-sidebar__text", children: label }), count != null && _jsx("span", { className: "pk-sidebar__count", children: count })] }));
198
+ const shared = {
199
+ className: classes,
200
+ 'aria-current': current ? 'page' : undefined,
201
+ // In the rail the labels are hidden, so a tooltip stands in for them.
202
+ title: title ?? (tooltips ? itemLabel(asChild ? undefined : children) : undefined),
203
+ };
204
+ let entry;
205
+ if (asChild && isValidElement(children)) {
206
+ const child = children;
207
+ entry = (_jsx(Slot.Root, { ref: innerRef, ...shared, title: shared.title ?? (tooltips ? itemLabel(child.props.children) : undefined), ...props, children: cloneElement(child, undefined, inner(child.props.children)) }));
208
+ }
209
+ else if (href !== undefined) {
210
+ entry = (_jsx("a", { ref: innerRef, href: href, ...shared, ...props, children: inner(children) }));
211
+ }
212
+ else {
213
+ entry = (_jsx("button", { ref: innerRef, type: "button", ...shared, ...props, children: inner(children) }));
214
+ }
215
+ const subs = subItems != null ? (_jsx("ul", { className: "pk-sidebar__subs", children: _jsx(InListContext.Provider, { value: true, children: subItems }) })) : null;
216
+ if (!inList)
217
+ return (_jsxs(_Fragment, { children: [entry, subs] }));
218
+ return (_jsx("li", { children: _jsxs(InListContext.Provider, { value: false, children: [entry, subs] }) }));
219
+ }
220
+ /** A sidebar item (`.pk-sidebar__item`): a link (or a button without `href`). */
221
+ export const SidebarItem = forwardRef(function SidebarItem(props, ref) {
222
+ return _jsx(SidebarEntry, { sub: false, innerRef: ref, ...props });
223
+ });
224
+ /** A sub-item under a `SidebarItem`: a shorter row with a dot where the icon goes. */
225
+ export const SidebarSubItem = forwardRef(function SidebarSubItem(props, ref) {
226
+ return _jsx(SidebarEntry, { sub: true, innerRef: ref, ...props });
227
+ });
228
+ /** The bottom of the sidebar (`.pk-sidebar__foot`): feedback, theme, collapse. */
229
+ export const SidebarFoot = forwardRef(function SidebarFoot({ className, ...props }, ref) {
230
+ return _jsx("div", { ref: ref, className: cx('pk-sidebar__foot', className), ...props });
231
+ });
232
+ /** The rail toggle, in the foot (`.pk-sidebar__collapse`). Hidden on phones. */
233
+ export const SidebarCollapse = forwardRef(function SidebarCollapse({ label = 'Collapse', className, onClick, ...props }, ref) {
234
+ const shell = useAppShell();
235
+ const name = shell.rail ? 'Expand sidebar' : 'Collapse sidebar';
236
+ return (_jsxs("button", { ref: ref, type: "button", className: cx('pk-sidebar__item', 'pk-sidebar__collapse', className), "aria-controls": shell.sidebarId, "aria-expanded": !shell.rail, "aria-label": name, title: shell.rail && !shell.narrow ? name : undefined, onClick: (event) => {
237
+ onClick?.(event);
238
+ if (!event.defaultPrevented)
239
+ shell.toggleRail();
240
+ }, ...props, children: [_jsx(Icon, { name: "sidebar" }), _jsx("span", { className: "pk-sidebar__text", children: label })] }));
241
+ });
242
+ const THEME_NAMES = { auto: 'Auto', light: 'Light', dark: 'Dark' };
243
+ const THEME_ICONS = { auto: 'circle-half', light: 'sun', dark: 'moon' };
244
+ /** The theme switch, as a sidebar item: Auto, Light, Dark in turn. */
245
+ export const SidebarThemeToggle = forwardRef(function SidebarThemeToggle({ className, onClick, ...props }, ref) {
246
+ const { theme, cycleTheme } = useTheme();
247
+ const shell = useContext(ShellContext);
248
+ const label = `Theme: ${THEME_NAMES[theme]}`;
249
+ return (_jsxs("button", { ref: ref, type: "button", className: cx('pk-sidebar__item', className), title: shell?.rail && !shell.narrow ? label : undefined, onClick: (event) => {
250
+ onClick?.(event);
251
+ if (!event.defaultPrevented)
252
+ cycleTheme();
253
+ }, ...props, children: [_jsx(Icon, { name: THEME_ICONS[theme] }), _jsx("span", { className: "pk-sidebar__text", children: label })] }));
254
+ });
255
+ /* ---- top bar ---- */
256
+ /** The top bar (`.pk-topbar`), in the frame: start, middle and end. */
257
+ export const Topbar = forwardRef(function Topbar({ className, ...props }, ref) {
258
+ return _jsx("header", { ref: ref, className: cx('pk-topbar', className), ...props });
259
+ });
260
+ const part = (name, displayName) => {
261
+ const Part = forwardRef(({ className, ...props }, ref) => _jsx("div", { ref: ref, className: cx(name, className), ...props }));
262
+ Part.displayName = displayName;
263
+ return Part;
264
+ };
265
+ export const TopbarStart = part('pk-topbar__start', 'TopbarStart');
266
+ export const TopbarMid = part('pk-topbar__mid', 'TopbarMid');
267
+ export const TopbarEnd = part('pk-topbar__end', 'TopbarEnd');
268
+ /** Where you are, in the top bar (`.pk-topbar__context`). */
269
+ export const TopbarContext = forwardRef(function TopbarContext({ className, ...props }, ref) {
270
+ return _jsx("span", { ref: ref, className: cx('pk-topbar__context', className), ...props });
271
+ });
272
+ /** Opens the sidebar drawer on phones (`.pk-topbar__menu`); hidden on wider screens. */
273
+ export const TopbarMenuButton = forwardRef(function TopbarMenuButton({ 'aria-label': label = 'Open navigation', className, onClick, ...props }, ref) {
274
+ const shell = useAppShell();
275
+ return (_jsx(IconButton, { ref: composeRefs(shell.menuButtonRef, ref), variant: "frame", className: cx('pk-topbar__menu', className), "aria-label": label, "aria-controls": shell.sidebarId, "aria-expanded": shell.drawerOpen, onClick: (event) => {
276
+ onClick?.(event);
277
+ if (!event.defaultPrevented)
278
+ shell.setDrawerOpen(!shell.drawerOpen);
279
+ }, ...props, children: _jsx(Icon, { name: "menu" }) }));
280
+ });
281
+ /** The search field (`.pk-search`): an icon inside a rounded input. */
282
+ export const Search = forwardRef(function Search({ variant = 'default', wrapperClassName, className, autoComplete = 'off', ...props }, ref) {
283
+ return (_jsxs("div", { className: cx('pk-search', variant === 'frame' && 'pk-search--frame', wrapperClassName), children: [_jsx(Icon, { name: "search", className: "pk-search__icon" }), _jsx("input", { ref: ref, type: "search", className: cx('pk-search__input', className), autoComplete: autoComplete, ...props })] }));
284
+ });
285
+ /* ---- content ---- */
286
+ /**
287
+ * The page area (`main.pk-content`): it scrolls on its own, and its corner tightens once the
288
+ * content is under the top bar. Focusable, so the keyboard can scroll it.
289
+ */
290
+ export const Content = forwardRef(function Content({ className, onScroll, tabIndex = 0, ...props }, ref) {
291
+ const [scrolled, setScrolled] = useState(false);
292
+ return (_jsx("main", { ref: ref, tabIndex: tabIndex, className: cx('pk-content', scrolled && 'is-scrolled', className), onScroll: (event) => {
293
+ onScroll?.(event);
294
+ setScrolled(event.currentTarget.scrollTop > 0);
295
+ }, ...props }));
296
+ });
297
+ /** The page inside the content (`.pk-page`), a size container for its parts. */
298
+ export const Page = forwardRef(function Page({ fill, className, ...props }, ref) {
299
+ return _jsx("div", { ref: ref, className: cx('pk-page', fill && 'pk-page--fill', className), ...props });
300
+ });
301
+ const PanelContext = createContext(null);
302
+ /**
303
+ * A side panel under the top bar (`.pk-panel`): chat, details. Wide windows make room for it;
304
+ * narrower ones lay it over the page; phones give it the screen. Opening it focuses an element
305
+ * with `data-autofocus` or the first field; Escape and the close button close it and return
306
+ * focus to where it was. Inside an `AppShell` it sets `data-panel-open`.
307
+ */
308
+ export const SidePanel = forwardRef(function SidePanel({ open, onOpenChange, className, onKeyDown, children, ...props }, ref) {
309
+ const shell = useContext(ShellContext);
310
+ const node = useRef(null);
311
+ const returnTo = useRef(null);
312
+ const titleId = `pk-panel-${useId()}-title`;
313
+ const setPanelOpen = shell?.setPanelOpen;
314
+ useIsomorphicLayoutEffect(() => {
315
+ if (setPanelOpen)
316
+ setPanelOpen(open);
317
+ else
318
+ document.documentElement.toggleAttribute('data-panel-open', open);
319
+ }, [open, setPanelOpen]);
320
+ useEffect(() => {
321
+ const panel = node.current;
322
+ if (!panel)
323
+ return;
324
+ if (open) {
325
+ returnTo.current = document.activeElement;
326
+ panel.querySelector(`[data-autofocus], ${FIELD}`)?.focus();
327
+ }
328
+ else if (returnTo.current) {
329
+ const back = returnTo.current;
330
+ returnTo.current = null;
331
+ if (!document.activeElement || document.activeElement === document.body)
332
+ back.focus();
333
+ }
334
+ }, [open]);
335
+ const close = useCallback(() => {
336
+ const panel = node.current;
337
+ const back = returnTo.current;
338
+ const focusInside = !!panel && panel.contains(document.activeElement);
339
+ onOpenChange(false);
340
+ if (focusInside && back?.isConnected) {
341
+ returnTo.current = null;
342
+ back.focus();
343
+ }
344
+ }, [onOpenChange]);
345
+ return (_jsx(PanelContext.Provider, { value: { titleId, close }, children: _jsx("aside", { ref: composeRefs(node, ref), className: cx('pk-panel', className), "aria-labelledby": titleId, hidden: !open, onKeyDown: (event) => {
346
+ onKeyDown?.(event);
347
+ if (event.key === 'Escape' && !event.defaultPrevented)
348
+ close();
349
+ }, ...props, children: children }) }));
350
+ });
351
+ /** The panel's head (`.pk-panel__head`): icon, title, meta and the close button. */
352
+ export const SidePanelHeader = forwardRef(function SidePanelHeader({ icon, title, meta, closeLabel = 'Close', className, ...props }, ref) {
353
+ const panel = useContext(PanelContext);
354
+ if (!panel)
355
+ throw new Error('SidePanelHeader must be inside a SidePanel.');
356
+ return (_jsxs("div", { ref: ref, className: cx('pk-panel__head', className), ...props, children: [renderIcon(icon), _jsx("h2", { className: "pk-panel__title", id: panel.titleId, children: title }), meta != null && _jsx("span", { className: "pk-panel__meta", children: meta }), _jsx(IconButton, { "aria-label": closeLabel, className: meta == null ? 'pk-push-right' : undefined, onClick: panel.close, children: _jsx(Icon, { name: "x" }) })] }));
357
+ });
358
+ export const SidePanelBody = part('pk-panel__body', 'SidePanelBody');
359
+ export const SidePanelFooter = part('pk-panel__foot', 'SidePanelFooter');
@@ -0,0 +1,10 @@
1
+ export type ThemeChoice = 'auto' | 'light' | 'dark';
2
+ /**
3
+ * The theme choice, as `behaviors/theme.js` keeps it: `data-theme` on `<html>` (none for auto),
4
+ * saved as `pk.theme`. With the boot script in `<head>` a saved choice applies before first paint.
5
+ */
6
+ export declare function useTheme(): {
7
+ theme: ThemeChoice;
8
+ setTheme: (next: ThemeChoice) => void;
9
+ cycleTheme: () => void;
10
+ };
@@ -0,0 +1,41 @@
1
+ 'use client';
2
+ import { useCallback, useState } from 'react';
3
+ import { readStorage, useIsomorphicLayoutEffect, writeStorage } from '../lib/dom.js';
4
+ const KEY = 'pk.theme';
5
+ const ORDER = ['auto', 'light', 'dark'];
6
+ /**
7
+ * The theme choice, as `behaviors/theme.js` keeps it: `data-theme` on `<html>` (none for auto),
8
+ * saved as `pk.theme`. With the boot script in `<head>` a saved choice applies before first paint.
9
+ */
10
+ export function useTheme() {
11
+ const [theme, setThemeState] = useState('auto');
12
+ useIsomorphicLayoutEffect(() => {
13
+ const attr = document.documentElement.getAttribute('data-theme');
14
+ const saved = readStorage(KEY);
15
+ const initial = attr === 'light' || attr === 'dark' ? attr : saved;
16
+ if (initial === 'light' || initial === 'dark')
17
+ setThemeState(initial);
18
+ }, []);
19
+ const setTheme = useCallback((next) => {
20
+ const html = document.documentElement;
21
+ if (next === 'auto')
22
+ html.removeAttribute('data-theme');
23
+ else
24
+ html.setAttribute('data-theme', next);
25
+ writeStorage(KEY, next);
26
+ setThemeState(next);
27
+ }, []);
28
+ const cycleTheme = useCallback(() => {
29
+ setThemeState((current) => {
30
+ const next = ORDER[(ORDER.indexOf(current) + 1) % ORDER.length];
31
+ const html = document.documentElement;
32
+ if (next === 'auto')
33
+ html.removeAttribute('data-theme');
34
+ else
35
+ html.setAttribute('data-theme', next);
36
+ writeStorage(KEY, next);
37
+ return next;
38
+ });
39
+ }, []);
40
+ return { theme, setTheme, cycleTheme };
41
+ }
package/dist/index.d.ts CHANGED
@@ -12,3 +12,7 @@ export { Popover, PopoverAnchor, PopoverClose, PopoverContent, PopoverTrigger, }
12
12
  export { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, Dialog, DialogBody, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogForm, DialogHeader, DialogTitle, DialogTrigger, type DialogContentProps, type DialogHeaderProps, type DialogProps, type DialogTitleProps, } from './components/dialog.js';
13
13
  export { Toaster, toast, type ToastOptions, type ToasterProps } from './components/toast.js';
14
14
  export { Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow, type TableCaptionProps, type TableCellProps, type TableHeadProps, type TableProps, type TableRowProps, } from './components/table.js';
15
+ export { polykitBootScript } from './lib/boot-script.js';
16
+ export { useTheme, type ThemeChoice } from './components/theme.js';
17
+ export { AppShell, Content, Page, Search, ShellMain, SidePanel, SidePanelBody, SidePanelFooter, SidePanelHeader, Sidebar, SidebarBrand, SidebarCollapse, SidebarFoot, SidebarGroup, SidebarItem, SidebarNav, SidebarSubItem, SidebarThemeToggle, Topbar, TopbarContext, TopbarEnd, TopbarMenuButton, TopbarMid, TopbarStart, Wordmark, useAppShell, type AppShellProps, type PageProps, type SearchProps, type SidePanelHeaderProps, type SidePanelProps, type SidebarCollapseProps, type SidebarGroupProps, type SidebarItemProps, type SidebarNavProps, type TopbarMenuButtonProps, type WordmarkProps, } from './components/shell.js';
18
+ export { Count, Group, Meta, MetaItem, PageHeader, PageHeaderActions, PageHeaderDescription, PageHeaderTitle, Pagination, Row, pageRange, type GroupProps, type MetaItemProps, type PaginationProps, type RowProps, } from './components/page.js';
package/dist/index.js CHANGED
@@ -14,3 +14,7 @@ export { Popover, PopoverAnchor, PopoverClose, PopoverContent, PopoverTrigger, }
14
14
  export { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, Dialog, DialogBody, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogForm, DialogHeader, DialogTitle, DialogTrigger, } from './components/dialog.js';
15
15
  export { Toaster, toast } from './components/toast.js';
16
16
  export { Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow, } from './components/table.js';
17
+ export { polykitBootScript } from './lib/boot-script.js';
18
+ export { useTheme } from './components/theme.js';
19
+ export { AppShell, Content, Page, Search, ShellMain, SidePanel, SidePanelBody, SidePanelFooter, SidePanelHeader, Sidebar, SidebarBrand, SidebarCollapse, SidebarFoot, SidebarGroup, SidebarItem, SidebarNav, SidebarSubItem, SidebarThemeToggle, Topbar, TopbarContext, TopbarEnd, TopbarMenuButton, TopbarMid, TopbarStart, Wordmark, useAppShell, } from './components/shell.js';
20
+ export { Count, Group, Meta, MetaItem, PageHeader, PageHeaderActions, PageHeaderDescription, PageHeaderTitle, Pagination, Row, pageRange, } from './components/page.js';
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The body of @polyfen/polykit-css's boot.js, for frameworks that render <head> themselves:
3
+ *
4
+ * <script dangerouslySetInnerHTML={{ __html: polykitBootScript }} />
5
+ *
6
+ * Run it as a blocking script in <head>, so the saved theme and sidebar apply before the first
7
+ * paint. A test keeps it equal to boot.js.
8
+ */
9
+ export declare const polykitBootScript = "(function () {\n var root = document.documentElement;\n var theme = null;\n var sidebar = null;\n try {\n theme = localStorage.getItem('pk.theme');\n sidebar = localStorage.getItem('pk.sidebar');\n } catch (e) {\n /* use the defaults */\n }\n if (theme === 'light' || theme === 'dark') root.setAttribute('data-theme', theme);\n if (\n sidebar === 'rail' ||\n (sidebar === null && window.matchMedia('(max-width: 1100px)').matches)\n ) {\n root.setAttribute('data-sidebar', 'rail');\n }\n})();";
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The body of @polyfen/polykit-css's boot.js, for frameworks that render <head> themselves:
3
+ *
4
+ * <script dangerouslySetInnerHTML={{ __html: polykitBootScript }} />
5
+ *
6
+ * Run it as a blocking script in <head>, so the saved theme and sidebar apply before the first
7
+ * paint. A test keeps it equal to boot.js.
8
+ */
9
+ export const polykitBootScript = `(function () {
10
+ var root = document.documentElement;
11
+ var theme = null;
12
+ var sidebar = null;
13
+ try {
14
+ theme = localStorage.getItem('pk.theme');
15
+ sidebar = localStorage.getItem('pk.sidebar');
16
+ } catch (e) {
17
+ /* use the defaults */
18
+ }
19
+ if (theme === 'light' || theme === 'dark') root.setAttribute('data-theme', theme);
20
+ if (
21
+ sidebar === 'rail' ||
22
+ (sidebar === null && window.matchMedia('(max-width: 1100px)').matches)
23
+ ) {
24
+ root.setAttribute('data-sidebar', 'rail');
25
+ }
26
+ })();`;
@@ -0,0 +1,10 @@
1
+ import { useLayoutEffect } from 'react';
2
+ /** useLayoutEffect in the browser, useEffect on the server (where neither runs). */
3
+ export declare const useIsomorphicLayoutEffect: typeof useLayoutEffect;
4
+ /** Reads localStorage; a per-viewer convenience, so storage that is missing or blocked is fine. */
5
+ export declare function readStorage(key: string): string | null;
6
+ export declare function writeStorage(key: string, value: string): void;
7
+ /** Matches a media query, if the browser can. */
8
+ export declare function matches(query: string): boolean;
9
+ export declare const FOCUSABLE = "a[href], button:not([disabled]), [tabindex]:not([tabindex=\"-1\"])";
10
+ export declare const FIELD = "input:not([type=\"hidden\"]):not([disabled]), select:not([disabled]), textarea:not([disabled])";
@@ -0,0 +1,29 @@
1
+ 'use client';
2
+ import { useEffect, useLayoutEffect } from 'react';
3
+ /** useLayoutEffect in the browser, useEffect on the server (where neither runs). */
4
+ export const useIsomorphicLayoutEffect = typeof document === 'undefined' ? useEffect : useLayoutEffect;
5
+ /** Reads localStorage; a per-viewer convenience, so storage that is missing or blocked is fine. */
6
+ export function readStorage(key) {
7
+ try {
8
+ return window.localStorage.getItem(key);
9
+ }
10
+ catch {
11
+ return null;
12
+ }
13
+ }
14
+ export function writeStorage(key, value) {
15
+ try {
16
+ window.localStorage.setItem(key, value);
17
+ }
18
+ catch {
19
+ /* storage may be missing or blocked */
20
+ }
21
+ }
22
+ /** Matches a media query, if the browser can. */
23
+ export function matches(query) {
24
+ return typeof window !== 'undefined' && typeof window.matchMedia === 'function'
25
+ ? window.matchMedia(query).matches
26
+ : false;
27
+ }
28
+ export const FOCUSABLE = 'a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"])';
29
+ export const FIELD = 'input:not([type="hidden"]):not([disabled]), select:not([disabled]), textarea:not([disabled])';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polyfen/polykit-react",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Polykit for React: components that render the Polykit CSS classes, with Radix Primitives for behavior and shadcn/ui-compatible names and props.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -29,8 +29,8 @@
29
29
  "peerDependencies": {
30
30
  "react": "^18.2.0 || ^19.0.0",
31
31
  "react-dom": "^18.2.0 || ^19.0.0",
32
- "@polyfen/polykit-tokens": "^0.4.0",
33
- "@polyfen/polykit-css": "^0.4.0"
32
+ "@polyfen/polykit-css": "^0.4.0",
33
+ "@polyfen/polykit-tokens": "^0.4.0"
34
34
  },
35
35
  "devDependencies": {
36
36
  "@testing-library/react": "^16.3.3",
@@ -43,8 +43,8 @@
43
43
  "react-dom": "^19.3.1",
44
44
  "typescript": "^7.0.2",
45
45
  "vitest": "^5.1.1",
46
- "@polyfen/polykit-tokens": "^0.4.0",
47
- "@polyfen/polykit-css": "^0.4.0"
46
+ "@polyfen/polykit-css": "^0.4.0",
47
+ "@polyfen/polykit-tokens": "^0.4.0"
48
48
  },
49
49
  "scripts": {
50
50
  "build": "node scripts/build.mjs",