@djangocfg/ui-core 2.1.404 → 2.1.408

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
@@ -33,7 +33,8 @@ Organized in `components/` by category — everything re-exported from the root
33
33
  | **Forms** | `Button`, `ButtonLink`, `ButtonGroup`, `Input`, `Textarea`, `Checkbox`, `RadioGroup`, `Switch`, `Slider`, `Label`, `Form`, `Field`, `InputOTP`, `PhoneInput`, `InputGroup`, `DownloadButton` |
34
34
  | **Select** | `Select`, `Combobox`, `ComboboxAsync`, `MultiSelect`, `MultiSelectPro`, `MultiSelectProAsync`, `CountrySelect`, `LanguageSelect` (all support icons + badges; `Select` accepts empty-string values; `ComboboxAsync` is the single-select counterpart to `MultiSelectProAsync` for server-side typeahead) |
35
35
  | **Overlay** | `Dialog`, `AlertDialog`, `Sheet`, `Drawer`, `Popover`, `Tooltip`, `HoverCard`, `ResponsiveSheet`, `SidePanel` |
36
- | **Navigation** | `Link`, `Breadcrumb`, `BreadcrumbNavigation`, `Pagination`, `StaticPagination`, `SSRPagination`, `Sidebar` (full shadcn primitives), `Tabs`, `Accordion`, `Collapsible`, `Command`, `DropdownMenu`, `ContextMenu`, `Menubar`, `NavigationMenu` |
36
+ | **Navigation** | `Link`, `Breadcrumb`, `BreadcrumbNavigation`, `Pagination`, `StaticPagination`, `SSRPagination`, `Sidebar` (full shadcn primitives), `Tabs`, `Accordion`, `Collapsible`, `Command`, `DropdownMenu`, `ContextMenu`, `Menubar`, `NavigationMenu`, `MenuBuilder` (declarative data-driven menu) |
37
+ | **Theme** | `ThemeProvider`, `ThemeToggle`, `ForceTheme`, `ThemeOverride`, `useThemeContext`, `useForcedTheme` — framework-agnostic theme runtime |
37
38
  | **Layout** | `Card`, `Section`, `Sticky`, `ScrollArea`, `Resizable`, `Separator`, `Skeleton`, `AspectRatio` |
38
39
  | **Data** | `Table`, `Badge`, `Avatar`, `Progress`, `Carousel`, `Calendar`, `DatePicker`, `DateRangePicker`, `Toggle`, `ToggleGroup`, `Chart*` |
39
40
  | **Feedback** | `Alert`, `Spinner`, `Empty`, `Preloader`, `Toaster` (Sonner) |
@@ -68,12 +69,12 @@ import { useNavigate, useLocation, useQueryParams, useRouter, useIsActive } from
68
69
 
69
70
  | Group | Hooks |
70
71
  |---|---|
71
- | **Router** (adapter-driven) | `useNavigate`, `useLocation`, `useQueryParams`, `useQueryState` (typed), `useRouter`, `useUrlBuilder`, `useSmartLink`, `useIsActive`, `useBackOrFallback` + parsers (`parseAsInteger`, `parseAsBoolean`, …) |
72
+ | **Router** (adapter-driven) | `useNavigate`, `useLocation`, `useLocationProperty`, `useQueryParams`, `useQueryState` (typed), `useRouter`, `useUrlBuilder`, `useSmartLink`, `useIsActive`, `useBackOrFallback` + parsers (`parseAsInteger`, `parseAsBoolean`, …) |
72
73
  | **Media** | `useIsMobile`, `useIsPhone`, `useIsTabletOrBelow`, `useMediaQuery` |
73
74
  | **Device** | `useDeviceDetect`, `useBrowserDetect`, `useShortcutModLabel` |
74
75
  | **State** | `useDebounce`, `useDebouncedCallback`, `useCountdown`, `useImageLoader`, `useMounted` |
75
76
  | **DOM** | `useEventListener` |
76
- | **Theme** | `useThemeColor`, `useThemePalette` (palette-aware hex colors for Canvas/SVG) |
77
+ | **Theme** | `useResolvedTheme` (light/dark detection), `useThemeColor`, `useThemePalette` (palette-aware hex colors for Canvas/SVG) |
77
78
  | **Hotkey** | `useHotkey` (smart `inInput` + `preventDefault` policy), `useHotkeyChord` (sequences), `formatHotkey('mod+k') → ⌘K`, `useHotkeyHelp` (auto cheat-sheet) |
78
79
  | **Audio** | `createSoundBus`, `useNotificationSounds`, `useAudioPrefs`, `useSoundEffect` — Safari unlock, mute persist, per-event toggles + volume scale, native-host bridge |
79
80
  | **Tabs** | `useActiveTab`, `useIsTabActive`, `useIsTabLeader` — cross-tab focus + leader election via BroadcastChannel |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@djangocfg/ui-core",
3
- "version": "2.1.404",
3
+ "version": "2.1.408",
4
4
  "description": "Pure React UI component library without Next.js dependencies - for Electron, Vite, CRA apps",
5
5
  "keywords": [
6
6
  "ui-components",
@@ -43,6 +43,11 @@
43
43
  "import": "./src/hooks/index.ts",
44
44
  "require": "./src/hooks/index.ts"
45
45
  },
46
+ "./theme": {
47
+ "types": "./src/theme/index.ts",
48
+ "import": "./src/theme/index.ts",
49
+ "require": "./src/theme/index.ts"
50
+ },
46
51
  "./adapters/nextjs": {
47
52
  "types": "./src/hooks/router/adapters/nextjs.tsx",
48
53
  "import": "./src/hooks/router/adapters/nextjs.tsx",
@@ -90,7 +95,7 @@
90
95
  "check": "tsc --noEmit"
91
96
  },
92
97
  "peerDependencies": {
93
- "@djangocfg/i18n": "^2.1.404",
98
+ "@djangocfg/i18n": "^2.1.408",
94
99
  "consola": "^3.4.2",
95
100
  "lucide-react": "^0.545.0",
96
101
  "moment": "^2.30.1",
@@ -149,6 +154,7 @@
149
154
  "i18n-iso-countries": "^7.14.0",
150
155
  "input-otp": "1.4.2",
151
156
  "libphonenumber-js": "^1.12.24",
157
+ "next-themes": "^0.4.6",
152
158
  "nextjs-toploader": "^3.9.17",
153
159
  "react-day-picker": "9.11.1",
154
160
  "react-hotkeys-hook": "^4.6.1",
@@ -160,8 +166,8 @@
160
166
  "vaul": "1.1.2"
161
167
  },
162
168
  "devDependencies": {
163
- "@djangocfg/i18n": "^2.1.404",
164
- "@djangocfg/typescript-config": "^2.1.404",
169
+ "@djangocfg/i18n": "^2.1.408",
170
+ "@djangocfg/typescript-config": "^2.1.408",
165
171
  "@types/node": "^24.7.2",
166
172
  "@types/react": "^19.1.0",
167
173
  "@types/react-dom": "^19.1.0",
@@ -41,7 +41,7 @@ const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
41
41
  return (
42
42
  <textarea
43
43
  className={cn(
44
- "flex min-h-[60px] w-full rounded-[var(--radius)] border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
44
+ "flex min-h-[60px] w-full rounded-[var(--radius)] border border-input bg-transparent px-3 py-2 text-sm text-foreground shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
45
45
  className
46
46
  )}
47
47
  ref={ref}
@@ -56,6 +56,8 @@ export { navigationMenuTriggerStyle, NavigationMenu, NavigationMenuList, Navigat
56
56
  export { Menubar, MenubarMenu, MenubarTrigger, MenubarContent, MenubarItem, MenubarSeparator, MenubarLabel, MenubarCheckboxItem, MenubarRadioGroup, MenubarRadioItem, MenubarPortal, MenubarSubContent, MenubarSubTrigger, MenubarGroup, MenubarSub, MenubarShortcut } from './navigation/menubar';
57
57
  export { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuCheckboxItem, DropdownMenuRadioItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuGroup, DropdownMenuPortal, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuRadioGroup } from './navigation/dropdown-menu';
58
58
  export { ContextMenu, ContextMenuCheckboxItem, ContextMenuContent, ContextMenuItem, ContextMenuLabel, ContextMenuRadioGroup, ContextMenuRadioItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger } from './navigation/context-menu';
59
+ export { MenuBuilder } from './navigation/menu';
60
+ export type { MenuItem, MenuActionItem, MenuSubmenuItem, MenuCheckboxItem, MenuRadioGroup, MenuRadioOption, MenuSeparator, MenuLabel, MenuSection, MenuCustom, MenuRowBase, MenuBuilderProps } from './navigation/menu';
59
61
  export { Tabs, TabsContent, TabsList, TabsTrigger } from './navigation/tabs';
60
62
  export { useTabsState } from './navigation/tabs/useTabsState';
61
63
  export type { UseTabsStateOptions, UseTabsStateResult } from './navigation/tabs/useTabsState';
@@ -0,0 +1,15 @@
1
+ export { MenuBuilder } from './menu-builder';
2
+ export type {
3
+ MenuItem,
4
+ MenuActionItem,
5
+ MenuSubmenuItem,
6
+ MenuCheckboxItem,
7
+ MenuRadioGroup,
8
+ MenuRadioOption,
9
+ MenuSeparator,
10
+ MenuLabel,
11
+ MenuSection,
12
+ MenuCustom,
13
+ MenuRowBase,
14
+ MenuBuilderProps,
15
+ } from './types';
@@ -0,0 +1,56 @@
1
+ 'use client';
2
+
3
+ import { cn } from '../../../lib';
4
+ import {
5
+ DropdownMenu,
6
+ DropdownMenuContent,
7
+ DropdownMenuTrigger,
8
+ } from '../dropdown-menu';
9
+ import { renderItems } from './render-items';
10
+ import type { MenuBuilderProps } from './types';
11
+
12
+ /**
13
+ * MenuBuilder — declarative menu.
14
+ *
15
+ * Pass `items: MenuItem[]` and a trigger; it renders a fully accessible
16
+ * menu through the existing Radix `DropdownMenu*` primitives (items,
17
+ * submenus, radio groups, checkboxes, separators, section labels,
18
+ * shortcuts, icons, descriptions).
19
+ *
20
+ * @example
21
+ * <MenuBuilder items={menu} side="top" align="start">
22
+ * <Button variant="ghost" size="icon"><Plus /></Button>
23
+ * </MenuBuilder>
24
+ */
25
+ export function MenuBuilder({
26
+ items,
27
+ children,
28
+ open,
29
+ onOpenChange,
30
+ defaultOpen,
31
+ side,
32
+ align = 'start',
33
+ sideOffset,
34
+ alignOffset,
35
+ contentClassName,
36
+ showDescriptions = true,
37
+ }: MenuBuilderProps) {
38
+ return (
39
+ <DropdownMenu
40
+ open={open}
41
+ onOpenChange={onOpenChange}
42
+ defaultOpen={defaultOpen}
43
+ >
44
+ <DropdownMenuTrigger asChild>{children}</DropdownMenuTrigger>
45
+ <DropdownMenuContent
46
+ side={side}
47
+ align={align}
48
+ sideOffset={sideOffset}
49
+ alignOffset={alignOffset}
50
+ className={cn('min-w-56 max-w-xs', contentClassName)}
51
+ >
52
+ {renderItems(items, { showDescriptions })}
53
+ </DropdownMenuContent>
54
+ </DropdownMenu>
55
+ );
56
+ }
@@ -0,0 +1,95 @@
1
+ import { createElement, isValidElement, type ReactNode } from 'react';
2
+
3
+ import { cn } from '../../../lib';
4
+ import { DropdownMenuShortcut } from '../dropdown-menu';
5
+ import type { MenuRowBase } from './types';
6
+
7
+ /**
8
+ * Resolve the `icon` field to a node. `icon` may be:
9
+ * - a ready React element (`<Foo />`)
10
+ * - a component *type*: a plain function component OR a
11
+ * `forwardRef`/`memo` object (lucide-react icons are forwardRef
12
+ * objects, so a bare `typeof === 'function'` check misses them).
13
+ */
14
+ function renderIcon(icon: MenuRowBase['icon']): ReactNode {
15
+ if (!icon) return null;
16
+ if (isValidElement(icon)) return icon;
17
+
18
+ const isFunctionComponent = typeof icon === 'function';
19
+ const isObjectComponent =
20
+ typeof icon === 'object' && icon !== null && '$$typeof' in icon;
21
+
22
+ if (isFunctionComponent || isObjectComponent) {
23
+ return createElement(
24
+ icon as React.ComponentType<{ className?: string }>,
25
+ { className: 'size-4 shrink-0' },
26
+ );
27
+ }
28
+ return icon as ReactNode;
29
+ }
30
+
31
+ export interface MenuRowProps {
32
+ icon?: MenuRowBase['icon'];
33
+ label: ReactNode;
34
+ description?: ReactNode;
35
+ shortcut?: string;
36
+ showDescription?: boolean;
37
+ }
38
+
39
+ /**
40
+ * Inner layout shared by every menu row kind: leading icon, label with
41
+ * an optional muted description line, trailing shortcut. Sits inside the
42
+ * Radix `Item` / `SubTrigger` / `CheckboxItem` wrappers.
43
+ */
44
+ export function MenuRow({
45
+ icon,
46
+ label,
47
+ description,
48
+ shortcut,
49
+ showDescription = true,
50
+ }: MenuRowProps) {
51
+ const iconNode = renderIcon(icon);
52
+
53
+ return (
54
+ <>
55
+ {iconNode}
56
+ <span className="flex min-w-0 flex-1 flex-col">
57
+ <span className="truncate">{label}</span>
58
+ {showDescription && description ? (
59
+ <span className="truncate text-xs text-muted-foreground">
60
+ {description}
61
+ </span>
62
+ ) : null}
63
+ </span>
64
+ {shortcut ? <DropdownMenuShortcut>{shortcut}</DropdownMenuShortcut> : null}
65
+ </>
66
+ );
67
+ }
68
+
69
+ /** Row layout for radio/checkbox rows — the Radix wrapper reserves the
70
+ * indicator column (`pl-8`) so the icon is placed inside the flex flow
71
+ * after that reserved space rather than as a leading element. */
72
+ export function MenuIndicatorRow({
73
+ icon,
74
+ label,
75
+ description,
76
+ shortcut,
77
+ showDescription = true,
78
+ }: MenuRowProps) {
79
+ const iconNode = renderIcon(icon);
80
+
81
+ return (
82
+ <span className={cn('flex min-w-0 flex-1 items-center gap-2')}>
83
+ {iconNode}
84
+ <span className="flex min-w-0 flex-1 flex-col">
85
+ <span className="truncate">{label}</span>
86
+ {showDescription && description ? (
87
+ <span className="truncate text-xs text-muted-foreground">
88
+ {description}
89
+ </span>
90
+ ) : null}
91
+ </span>
92
+ {shortcut ? <DropdownMenuShortcut>{shortcut}</DropdownMenuShortcut> : null}
93
+ </span>
94
+ );
95
+ }
@@ -0,0 +1,166 @@
1
+ import { Fragment, type ReactNode } from 'react';
2
+
3
+ import {
4
+ DropdownMenuCheckboxItem,
5
+ DropdownMenuGroup,
6
+ DropdownMenuItem,
7
+ DropdownMenuLabel,
8
+ DropdownMenuPortal,
9
+ DropdownMenuRadioGroup,
10
+ DropdownMenuRadioItem,
11
+ DropdownMenuSeparator,
12
+ DropdownMenuSub,
13
+ DropdownMenuSubContent,
14
+ DropdownMenuSubTrigger,
15
+ } from '../dropdown-menu';
16
+ import { MenuIndicatorRow, MenuRow } from './menu-row';
17
+ import type { MenuItem } from './types';
18
+
19
+ interface RenderOptions {
20
+ showDescriptions: boolean;
21
+ }
22
+
23
+ /** Drop `hidden` rows before rendering. */
24
+ function isVisible(item: MenuItem): boolean {
25
+ return !('hidden' in item && item.hidden);
26
+ }
27
+
28
+ /**
29
+ * Recursive renderer — powers both the root content and every
30
+ * `SubContent`. Pure: it only maps data to Radix elements.
31
+ */
32
+ export function renderItems(
33
+ items: MenuItem[],
34
+ opts: RenderOptions,
35
+ ): ReactNode {
36
+ return items.filter(isVisible).map((item, index) => {
37
+ switch (item.kind) {
38
+ case 'separator':
39
+ return <DropdownMenuSeparator key={item.id ?? `sep-${index}`} />;
40
+
41
+ case 'label':
42
+ return (
43
+ <DropdownMenuLabel key={item.id ?? `label-${index}`}>
44
+ {item.label}
45
+ </DropdownMenuLabel>
46
+ );
47
+
48
+ case 'custom':
49
+ return <Fragment key={item.id}>{item.render()}</Fragment>;
50
+
51
+ case 'item':
52
+ return (
53
+ <DropdownMenuItem
54
+ key={item.id}
55
+ href={item.href}
56
+ variant={item.variant}
57
+ disabled={item.disabled}
58
+ onSelect={(event) => {
59
+ // closeOnSelect=false → keep the menu open.
60
+ if (item.closeOnSelect === false) event.preventDefault();
61
+ item.onSelect?.(event);
62
+ }}
63
+ >
64
+ <MenuRow
65
+ icon={item.icon}
66
+ label={item.label}
67
+ description={item.description}
68
+ shortcut={item.shortcut}
69
+ showDescription={opts.showDescriptions}
70
+ />
71
+ </DropdownMenuItem>
72
+ );
73
+
74
+ case 'submenu':
75
+ return (
76
+ <DropdownMenuSub key={item.id}>
77
+ <DropdownMenuSubTrigger disabled={item.disabled}>
78
+ <MenuRow
79
+ icon={item.icon}
80
+ label={item.label}
81
+ description={item.description}
82
+ showDescription={opts.showDescriptions}
83
+ />
84
+ </DropdownMenuSubTrigger>
85
+ <DropdownMenuPortal>
86
+ <DropdownMenuSubContent>
87
+ {renderItems(item.items, opts)}
88
+ </DropdownMenuSubContent>
89
+ </DropdownMenuPortal>
90
+ </DropdownMenuSub>
91
+ );
92
+
93
+ case 'checkbox':
94
+ return (
95
+ <DropdownMenuCheckboxItem
96
+ key={item.id}
97
+ checked={item.checked}
98
+ disabled={item.disabled}
99
+ onCheckedChange={item.onCheckedChange}
100
+ >
101
+ <MenuIndicatorRow
102
+ icon={item.icon}
103
+ label={item.label}
104
+ description={item.description}
105
+ shortcut={item.shortcut}
106
+ showDescription={opts.showDescriptions}
107
+ />
108
+ </DropdownMenuCheckboxItem>
109
+ );
110
+
111
+ case 'radio-group':
112
+ return (
113
+ <Fragment key={item.id}>
114
+ {item.label ? (
115
+ <DropdownMenuLabel>{item.label}</DropdownMenuLabel>
116
+ ) : null}
117
+ <DropdownMenuRadioGroup
118
+ value={item.value}
119
+ onValueChange={item.onValueChange}
120
+ >
121
+ {item.options.filter((o) => !o.hidden).map((option) => (
122
+ <DropdownMenuRadioItem
123
+ key={option.id}
124
+ value={option.value}
125
+ disabled={option.disabled}
126
+ >
127
+ <MenuIndicatorRow
128
+ icon={option.icon}
129
+ label={option.label}
130
+ description={option.description}
131
+ shortcut={option.shortcut}
132
+ showDescription={opts.showDescriptions}
133
+ />
134
+ </DropdownMenuRadioItem>
135
+ ))}
136
+ </DropdownMenuRadioGroup>
137
+ </Fragment>
138
+ );
139
+
140
+ case 'section': {
141
+ // A separator follows the section unless explicitly disabled or
142
+ // it is the last visible item.
143
+ const isLast =
144
+ index === items.filter(isVisible).length - 1;
145
+ const withSeparator = item.separator !== false && !isLast;
146
+ return (
147
+ <Fragment key={item.id}>
148
+ <DropdownMenuGroup>
149
+ {item.label ? (
150
+ <DropdownMenuLabel>{item.label}</DropdownMenuLabel>
151
+ ) : null}
152
+ {renderItems(item.items, opts)}
153
+ </DropdownMenuGroup>
154
+ {withSeparator ? <DropdownMenuSeparator /> : null}
155
+ </Fragment>
156
+ );
157
+ }
158
+
159
+ default: {
160
+ // Exhaustiveness guard — a new `kind` without a branch fails here.
161
+ const _never: never = item;
162
+ return _never;
163
+ }
164
+ }
165
+ });
166
+ }
@@ -0,0 +1,137 @@
1
+ import type { ComponentType, ReactNode } from 'react';
2
+
3
+ /**
4
+ * Declarative menu model. A host passes `MenuItem[]` and a trigger to
5
+ * `MenuBuilder`; it renders through the existing Radix `DropdownMenu*`
6
+ * primitives. The `kind` field is the discriminator.
7
+ */
8
+
9
+ /** Shared fields for any selectable row. */
10
+ export interface MenuRowBase {
11
+ /** Stable identity — used as the React key. */
12
+ id: string;
13
+ label: ReactNode;
14
+ /** Leading icon: a lucide-react component or any node. */
15
+ icon?: ComponentType<{ className?: string }> | ReactNode;
16
+ /** Secondary muted line under the label. */
17
+ description?: ReactNode;
18
+ /** Keyboard hint, right-aligned (display only), e.g. "⌘U". */
19
+ shortcut?: string;
20
+ disabled?: boolean;
21
+ /** When true the row is filtered out before render. */
22
+ hidden?: boolean;
23
+ }
24
+
25
+ /** Plain action row. */
26
+ export interface MenuActionItem extends MenuRowBase {
27
+ kind: 'item';
28
+ onSelect?: (event: Event) => void;
29
+ /** Renders the row as a link. */
30
+ href?: string;
31
+ variant?: 'default' | 'destructive';
32
+ /** Keep the menu open after select. Default: true (closes). */
33
+ closeOnSelect?: boolean;
34
+ }
35
+
36
+ /** Nested menu. */
37
+ export interface MenuSubmenuItem extends MenuRowBase {
38
+ kind: 'submenu';
39
+ items: MenuItem[];
40
+ }
41
+
42
+ /** A single checkbox row. */
43
+ export interface MenuCheckboxItem extends MenuRowBase {
44
+ kind: 'checkbox';
45
+ checked: boolean;
46
+ onCheckedChange: (checked: boolean) => void;
47
+ }
48
+
49
+ /** One option inside a radio group. */
50
+ export interface MenuRadioOption {
51
+ id: string;
52
+ value: string;
53
+ label: ReactNode;
54
+ icon?: MenuRowBase['icon'];
55
+ description?: ReactNode;
56
+ shortcut?: string;
57
+ disabled?: boolean;
58
+ hidden?: boolean;
59
+ }
60
+
61
+ /** Controlled radio group with an optional heading. */
62
+ export interface MenuRadioGroup {
63
+ kind: 'radio-group';
64
+ id: string;
65
+ label?: ReactNode;
66
+ value: string;
67
+ onValueChange: (value: string) => void;
68
+ options: MenuRadioOption[];
69
+ }
70
+
71
+ /** Visual divider. */
72
+ export interface MenuSeparator {
73
+ kind: 'separator';
74
+ id?: string;
75
+ }
76
+
77
+ /** Non-interactive section header. */
78
+ export interface MenuLabel {
79
+ kind: 'label';
80
+ id?: string;
81
+ label: ReactNode;
82
+ hidden?: boolean;
83
+ }
84
+
85
+ /**
86
+ * A labelled group of items — sugar over label + items + a trailing
87
+ * separator.
88
+ */
89
+ export interface MenuSection {
90
+ kind: 'section';
91
+ id: string;
92
+ label?: ReactNode;
93
+ items: MenuItem[];
94
+ /** Draw a separator after the section. Default: true. */
95
+ separator?: boolean;
96
+ }
97
+
98
+ /**
99
+ * Escape hatch — arbitrary node wrapped in a non-focusable row. Use for
100
+ * static content (banners, inline inputs), never for actions: it is not
101
+ * a Radix `Item` and cannot receive keyboard focus.
102
+ */
103
+ export interface MenuCustom {
104
+ kind: 'custom';
105
+ id: string;
106
+ render: () => ReactNode;
107
+ }
108
+
109
+ export type MenuItem =
110
+ | MenuActionItem
111
+ | MenuSubmenuItem
112
+ | MenuCheckboxItem
113
+ | MenuRadioGroup
114
+ | MenuSeparator
115
+ | MenuLabel
116
+ | MenuSection
117
+ | MenuCustom;
118
+
119
+ export interface MenuBuilderProps {
120
+ /** Declarative menu tree. */
121
+ items: MenuItem[];
122
+ /** Trigger element — rendered via Radix `asChild`. */
123
+ children: ReactNode;
124
+ /** Controlled open state. */
125
+ open?: boolean;
126
+ onOpenChange?: (open: boolean) => void;
127
+ defaultOpen?: boolean;
128
+ /** Positioning — forwarded to the content panel. */
129
+ side?: 'top' | 'right' | 'bottom' | 'left';
130
+ align?: 'start' | 'center' | 'end';
131
+ sideOffset?: number;
132
+ alignOffset?: number;
133
+ /** Extra class for the content panel. */
134
+ contentClassName?: string;
135
+ /** Render the muted description line on rows that have one. Default: true. */
136
+ showDescriptions?: boolean;
137
+ }
@@ -35,6 +35,7 @@ export {
35
35
  useRouterAdapter,
36
36
  // useLocation
37
37
  useLocation,
38
+ useLocationProperty,
38
39
  NAVIGATE_EVENT,
39
40
  // useNavigate
40
41
  useNavigate,
@@ -5,62 +5,77 @@ import { useEffect, useState } from 'react';
5
5
  export type ResolvedTheme = 'light' | 'dark';
6
6
 
7
7
  /**
8
- * Hook to detect the current resolved theme (light or dark)
8
+ * Detect the current resolved theme (light or dark).
9
9
  *
10
- * Standalone hook - doesn't require ThemeProvider.
11
- * Detects theme from:
12
- * 1. 'dark' class on html element
13
- * 2. System preference (prefers-color-scheme)
10
+ * Standalone hook does not require ThemeProvider. Resolution order:
11
+ * 1. Explicit `dark` / `light` class on `<html>`.
12
+ * 2. Explicit `data-theme` attribute on `<html>`.
13
+ * 3. The *rendered* page background — sampled from `--background`.
14
+ * This covers hosts where "light" is the absence of a class
15
+ * (e.g. Storybook's `withThemeByClassName({ light: '', dark:
16
+ * 'dark' })`): without this step the hook would fall through to
17
+ * the system preference and report `dark` for a light page on a
18
+ * dark OS.
19
+ * 4. System `prefers-color-scheme` — last resort, only when no theme
20
+ * tokens have been applied yet.
14
21
  *
15
- * For full theme control (setTheme, toggleTheme), use useThemeContext instead.
22
+ * For full theme control (setTheme, toggleTheme), use useThemeContext.
16
23
  *
17
24
  * @example
18
- * ```tsx
19
25
  * const theme = useResolvedTheme(); // 'light' | 'dark'
20
- * ```
21
26
  */
22
27
  export const useResolvedTheme = (): ResolvedTheme => {
23
28
  const [theme, setTheme] = useState<ResolvedTheme>('light');
24
29
 
25
30
  useEffect(() => {
31
+ const sampleBackground = (): ResolvedTheme | null => {
32
+ const probe = document.createElement('div');
33
+ probe.style.cssText =
34
+ 'background-color:var(--background);position:absolute;width:0;height:0;pointer-events:none;';
35
+ document.body.appendChild(probe);
36
+ const rgb = getComputedStyle(probe).backgroundColor;
37
+ probe.remove();
38
+
39
+ const match = rgb.match(/\d+(\.\d+)?/g);
40
+ if (!match || match.length < 3) return null;
41
+ const [r, g, b] = match.map(Number) as [number, number, number];
42
+ // Perceived luminance (ITU-R BT.601).
43
+ const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
44
+ return luminance > 0.5 ? 'light' : 'dark';
45
+ };
46
+
26
47
  const checkTheme = (): ResolvedTheme => {
27
- // Check if dark class is applied to html element
28
- if (document.documentElement.classList.contains('dark')) {
29
- return 'dark';
30
- }
48
+ const root = document.documentElement;
31
49
 
32
- // Check if light class is explicitly applied (takes precedence over system)
33
- if (document.documentElement.classList.contains('light')) {
34
- return 'light';
35
- }
50
+ if (root.classList.contains('dark')) return 'dark';
51
+ if (root.classList.contains('light')) return 'light';
52
+
53
+ const dataTheme = root.getAttribute('data-theme');
54
+ if (dataTheme === 'dark') return 'dark';
55
+ if (dataTheme === 'light') return 'light';
56
+
57
+ // No explicit theme class/attr — infer from the painted surface.
58
+ const sampled = sampleBackground();
59
+ if (sampled) return sampled;
36
60
 
37
- // Check system preference only if no explicit theme class
38
61
  if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
39
62
  return 'dark';
40
63
  }
41
-
42
64
  return 'light';
43
65
  };
44
66
 
45
- // Set initial theme
46
67
  setTheme(checkTheme());
47
68
 
48
- // Listen for class changes on html element
49
69
  const observer = new MutationObserver(() => {
50
70
  setTheme(checkTheme());
51
71
  });
52
-
53
72
  observer.observe(document.documentElement, {
54
73
  attributes: true,
55
- attributeFilter: ['class']
74
+ attributeFilter: ['class', 'data-theme', 'style'],
56
75
  });
57
76
 
58
- // Listen for system theme changes
59
77
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
60
- const handleMediaChange = () => {
61
- setTheme(checkTheme());
62
- };
63
-
78
+ const handleMediaChange = () => setTheme(checkTheme());
64
79
  mediaQuery.addEventListener('change', handleMediaChange);
65
80
 
66
81
  return () => {
@@ -0,0 +1,116 @@
1
+ /**
2
+ * ForceTheme - Force a specific theme for a section
3
+ *
4
+ * Wraps content to override the global theme setting.
5
+ * Works by adding both the theme class and inline CSS variables
6
+ * to ensure proper theme application regardless of parent context.
7
+ */
8
+
9
+ 'use client';
10
+
11
+ import React, { ReactNode } from 'react';
12
+
13
+ import { cn } from '../lib/utils';
14
+
15
+ interface ForceThemeProps {
16
+ theme: 'light' | 'dark';
17
+ children: ReactNode;
18
+ className?: string;
19
+ }
20
+
21
+ // Dark theme CSS variables
22
+ const darkThemeVars = {
23
+ // Base HSL values
24
+ '--background': '0 0% 4%',
25
+ '--foreground': '0 0% 98%',
26
+ '--card': '0 0% 8%',
27
+ '--card-foreground': '0 0% 98%',
28
+ '--popover': '0 0% 12%',
29
+ '--popover-foreground': '0 0% 98%',
30
+ '--primary': '217 91% 60%',
31
+ '--primary-foreground': '0 0% 100%',
32
+ '--secondary': '0 0% 98%',
33
+ '--secondary-foreground': '0 0% 9%',
34
+ '--muted': '0 0% 10%',
35
+ '--muted-foreground': '0 0% 60%',
36
+ '--accent': '0 0% 15%',
37
+ '--accent-foreground': '0 0% 98%',
38
+ '--destructive': '0 84% 60%',
39
+ '--destructive-foreground': '0 0% 98%',
40
+ '--border': '0 0% 15%',
41
+ '--input': '0 0% 15%',
42
+ '--ring': '217 91% 60%',
43
+ // Tailwind color tokens (used by bg-*, text-*, etc)
44
+ '--color-background': 'hsl(0 0% 4%)',
45
+ '--color-foreground': 'hsl(0 0% 98%)',
46
+ '--color-card': 'hsl(0 0% 8%)',
47
+ '--color-card-foreground': 'hsl(0 0% 98%)',
48
+ '--color-primary': 'hsl(217 91% 60%)',
49
+ '--color-primary-foreground': 'hsl(0 0% 100%)',
50
+ '--color-secondary': 'hsl(0 0% 98%)',
51
+ '--color-secondary-foreground': 'hsl(0 0% 9%)',
52
+ '--color-muted': 'hsl(0 0% 10%)',
53
+ '--color-muted-foreground': 'hsl(0 0% 60%)',
54
+ '--color-accent': 'hsl(0 0% 15%)',
55
+ '--color-accent-foreground': 'hsl(0 0% 98%)',
56
+ '--color-destructive': 'hsl(0 84% 60%)',
57
+ '--color-destructive-foreground': 'hsl(0 0% 98%)',
58
+ '--color-border': 'hsl(0 0% 15%)',
59
+ '--color-input': 'hsl(0 0% 15%)',
60
+ '--color-ring': 'hsl(217 91% 60%)',
61
+ } as React.CSSProperties;
62
+
63
+ // Light theme CSS variables
64
+ const lightThemeVars = {
65
+ // Base HSL values
66
+ '--background': '0 0% 96%',
67
+ '--foreground': '0 0% 9%',
68
+ '--card': '0 0% 100%',
69
+ '--card-foreground': '0 0% 9%',
70
+ '--popover': '0 0% 100%',
71
+ '--popover-foreground': '0 0% 9%',
72
+ '--primary': '217 91% 60%',
73
+ '--primary-foreground': '0 0% 100%',
74
+ '--secondary': '0 0% 9%',
75
+ '--secondary-foreground': '0 0% 98%',
76
+ '--muted': '0 0% 96%',
77
+ '--muted-foreground': '0 0% 40%',
78
+ '--accent': '0 0% 92%',
79
+ '--accent-foreground': '0 0% 9%',
80
+ '--destructive': '0 84% 60%',
81
+ '--destructive-foreground': '0 0% 98%',
82
+ '--border': '0 0% 90%',
83
+ '--input': '0 0% 90%',
84
+ '--ring': '217 91% 60%',
85
+ // Tailwind color tokens (used by bg-*, text-*, etc)
86
+ '--color-background': 'hsl(0 0% 96%)',
87
+ '--color-foreground': 'hsl(0 0% 9%)',
88
+ '--color-card': 'hsl(0 0% 100%)',
89
+ '--color-card-foreground': 'hsl(0 0% 9%)',
90
+ '--color-primary': 'hsl(217 91% 60%)',
91
+ '--color-primary-foreground': 'hsl(0 0% 100%)',
92
+ '--color-secondary': 'hsl(0 0% 9%)',
93
+ '--color-secondary-foreground': 'hsl(0 0% 98%)',
94
+ '--color-muted': 'hsl(0 0% 96%)',
95
+ '--color-muted-foreground': 'hsl(0 0% 40%)',
96
+ '--color-accent': 'hsl(0 0% 92%)',
97
+ '--color-accent-foreground': 'hsl(0 0% 9%)',
98
+ '--color-destructive': 'hsl(0 84% 60%)',
99
+ '--color-destructive-foreground': 'hsl(0 0% 98%)',
100
+ '--color-border': 'hsl(0 0% 90%)',
101
+ '--color-input': 'hsl(0 0% 90%)',
102
+ '--color-ring': 'hsl(217 91% 60%)',
103
+ } as React.CSSProperties;
104
+
105
+ export function ForceTheme({ theme, children, className }: ForceThemeProps) {
106
+ const themeVars = theme === 'dark' ? darkThemeVars : lightThemeVars;
107
+
108
+ return (
109
+ <div
110
+ className={cn(theme, className)}
111
+ style={themeVars}
112
+ >
113
+ {children}
114
+ </div>
115
+ );
116
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * ForcedThemeContext
3
+ *
4
+ * Published by `ThemeOverride` so downstream UI (theme switchers, toggles,
5
+ * indicators) can tell whether the current route forces a specific theme and
6
+ * adapt accordingly — typically by disabling or hiding their controls.
7
+ *
8
+ * Default value is `null` (no override) — consumers outside a `ThemeOverride`
9
+ * mount see the same shape as consumers on an unforced route, so there's no
10
+ * need to guard against the provider being absent.
11
+ */
12
+
13
+ 'use client';
14
+
15
+ import { createContext, useContext, type ReactNode } from 'react';
16
+
17
+ import type { ForcedTheme } from './ThemeOverride';
18
+
19
+ const ForcedThemeContext = createContext<ForcedTheme | null>(null);
20
+
21
+ interface ForcedThemeProviderProps {
22
+ value: ForcedTheme | null;
23
+ children: ReactNode;
24
+ }
25
+
26
+ export function ForcedThemeProvider({ value, children }: ForcedThemeProviderProps) {
27
+ return (
28
+ <ForcedThemeContext.Provider value={value}>
29
+ {children}
30
+ </ForcedThemeContext.Provider>
31
+ );
32
+ }
33
+
34
+ /**
35
+ * Read the currently-forced theme. `null` means the user is free to choose.
36
+ *
37
+ * @example
38
+ * ```tsx
39
+ * const forced = useForcedTheme();
40
+ * if (forced) return <p>Theme is locked to {forced} on this page.</p>;
41
+ * ```
42
+ */
43
+ export function useForcedTheme(): ForcedTheme | null {
44
+ return useContext(ForcedThemeContext);
45
+ }
@@ -0,0 +1,163 @@
1
+ /**
2
+ * ThemeOverride - Pathname-aware forced theme
3
+ *
4
+ * Applies a forced `light` or `dark` theme via `next-themes` while the current
5
+ * pathname matches any of the supplied rules, and restores the user's prior
6
+ * choice when the pathname no longer matches.
7
+ *
8
+ * Unlike `ForceTheme` (which scopes CSS vars to a wrapper div), this component
9
+ * mutates the real `next-themes` value — so the `html.dark` class is applied
10
+ * and every surface (navbar, footer, body, page) picks the new theme up
11
+ * consistently.
12
+ *
13
+ * The matcher is **dependency-free** and understands:
14
+ * - Exact match (`/` matches `/`)
15
+ * - Prefix match (`/docs` matches `/docs/getting-started`)
16
+ * - Glob wildcards (`*` for a single segment, `**` for any depth)
17
+ *
18
+ * Consumers pass the pathname already stripped of the locale prefix — matching
19
+ * is not locale-aware here.
20
+ *
21
+ * @example
22
+ * ```tsx
23
+ * <ThemeOverride
24
+ * pathname={pathname}
25
+ * rules={[
26
+ * { path: '/', theme: 'dark' },
27
+ * { path: ['/legal', '/legal/**'], theme: 'light' },
28
+ * ]}
29
+ * />
30
+ * ```
31
+ */
32
+
33
+ 'use client';
34
+
35
+ import { useEffect, useMemo, useRef } from 'react';
36
+
37
+ import { useThemeContext } from './ThemeProvider';
38
+
39
+ import type { Theme } from './ThemeProvider';
40
+
41
+ export type ForcedTheme = Exclude<Theme, 'system'>;
42
+
43
+ export interface ThemeOverrideRule {
44
+ /** Path (or array of paths) to match against. Supports `*` and `**` globs. */
45
+ path: string | string[];
46
+ /** Theme to apply while the path matches. */
47
+ theme: ForcedTheme;
48
+ }
49
+
50
+ export interface ThemeOverrideProps {
51
+ /** Pathname stripped of locale prefix. Use `usePathnameWithoutLocale()` if you have it. */
52
+ pathname: string;
53
+ /** Rules evaluated top-to-bottom — first match wins. */
54
+ rules?: ThemeOverrideRule[];
55
+ }
56
+
57
+ /**
58
+ * Resolve the first matching rule's forced theme for a pathname, or `null`.
59
+ * Pure helper — use this to render a `ForcedThemeProvider` in the same tree
60
+ * where you mount `ThemeOverride`.
61
+ */
62
+ export function resolveForcedTheme(
63
+ pathname: string,
64
+ rules?: ThemeOverrideRule[],
65
+ ): ForcedTheme | null {
66
+ if (!rules || rules.length === 0) return null;
67
+ for (const rule of rules) {
68
+ if (matchesAny(pathname, rule.path)) return rule.theme;
69
+ }
70
+ return null;
71
+ }
72
+
73
+ // --- inlined matcher (no dep on @djangocfg/layouts) -------------------------
74
+
75
+ function matchGlob(pathname: string, pattern: string): boolean {
76
+ const pathParts = pathname.replace(/\/+$/, '').split('/').filter(Boolean);
77
+ const patternParts = pattern.replace(/\/+$/, '').split('/').filter(Boolean);
78
+
79
+ let pi = 0;
80
+ let ti = 0;
81
+
82
+ while (ti < patternParts.length && pi < pathParts.length) {
83
+ const pat = patternParts[ti];
84
+ if (pat === '**') {
85
+ if (ti === patternParts.length - 1) return true;
86
+ const next = patternParts[ti + 1];
87
+ while (pi < pathParts.length) {
88
+ if (pathParts[pi] === next || next === '*') break;
89
+ pi++;
90
+ }
91
+ ti++;
92
+ } else if (pat === '*') {
93
+ pi++;
94
+ ti++;
95
+ } else {
96
+ if (pathParts[pi] !== pat) return false;
97
+ pi++;
98
+ ti++;
99
+ }
100
+ }
101
+
102
+ if (ti < patternParts.length) {
103
+ for (let i = ti; i < patternParts.length; i++) {
104
+ if (patternParts[i] !== '**') return false;
105
+ }
106
+ }
107
+
108
+ return pi === pathParts.length;
109
+ }
110
+
111
+ function matchOne(pathname: string, pattern: string): boolean {
112
+ const p = pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname;
113
+ const q = pattern.length > 1 ? pattern.replace(/\/+$/, '') : pattern;
114
+ if (q.includes('*')) return matchGlob(p, q);
115
+ return p === q || p.startsWith(q + '/');
116
+ }
117
+
118
+ function matchesAny(pathname: string, path: string | string[]): boolean {
119
+ return Array.isArray(path) ? path.some((p) => matchOne(pathname, p)) : matchOne(pathname, path);
120
+ }
121
+
122
+ // --- component --------------------------------------------------------------
123
+
124
+ export function ThemeOverride({ pathname, rules }: ThemeOverrideProps) {
125
+ const { theme, setTheme } = useThemeContext();
126
+
127
+ // First rule whose path matches the current pathname. null = no override.
128
+ const forced = useMemo<ForcedTheme | null>(
129
+ () => resolveForcedTheme(pathname, rules),
130
+ [pathname, rules],
131
+ );
132
+
133
+ // Stash the user's own pick so we can restore it when they leave a forced route.
134
+ // We capture only non-override theme values (from renders where `forced === null`).
135
+ // Stored as a ref so it doesn't drive the effect.
136
+ const userThemeRef = useRef<string | undefined>(undefined);
137
+
138
+ // Keep userThemeRef in sync with what next-themes reports **while not forcing**.
139
+ // Every render where the route isn't overridden, the current `theme` IS the user's
140
+ // own pick — snapshot it. During a forced render we leave the ref alone so the
141
+ // original value survives until we hand control back.
142
+ useEffect(() => {
143
+ if (forced === null && theme) {
144
+ userThemeRef.current = theme;
145
+ }
146
+ }, [forced, theme]);
147
+
148
+ // Apply / revert the forced theme. Intentionally driven only by `forced` — the
149
+ // user may toggle the theme manually while forcing is off, and that's fine
150
+ // (the sync effect above records the new value).
151
+ useEffect(() => {
152
+ if (forced) {
153
+ setTheme(forced);
154
+ return;
155
+ }
156
+ const restore = userThemeRef.current ?? 'system';
157
+ setTheme(restore);
158
+ // setTheme from next-themes is stable by ref; omit on purpose.
159
+ // eslint-disable-next-line react-hooks/exhaustive-deps
160
+ }, [forced]);
161
+
162
+ return null;
163
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * ThemeProvider - Universal theme management
3
+ *
4
+ * Re-exports next-themes ThemeProvider with sensible defaults.
5
+ * Supports light, dark, and system themes with localStorage persistence.
6
+ *
7
+ * Framework-agnostic: works in any React app (Electron, Vite, Next.js).
8
+ *
9
+ * @example
10
+ * ```tsx
11
+ * import { ThemeProvider } from '@djangocfg/ui-core/theme';
12
+ *
13
+ * <ThemeProvider
14
+ * attribute="class"
15
+ * defaultTheme="system"
16
+ * enableSystem
17
+ * >
18
+ * {children}
19
+ * </ThemeProvider>
20
+ * ```
21
+ */
22
+
23
+ 'use client';
24
+
25
+ import { ThemeProvider as NextThemesProvider, useTheme as useNextTheme } from 'next-themes';
26
+
27
+ import type { ThemeProviderProps as NextThemesProviderProps } from 'next-themes';
28
+
29
+ // Re-export types
30
+ export type Theme = 'light' | 'dark' | 'system';
31
+ export type ThemeProviderProps = NextThemesProviderProps;
32
+
33
+ /**
34
+ * ThemeProvider wraps next-themes with sensible defaults
35
+ */
36
+ export function ThemeProvider({
37
+ children,
38
+ attribute = 'class',
39
+ defaultTheme = 'system',
40
+ enableSystem = true,
41
+ disableTransitionOnChange = true,
42
+ ...props
43
+ }: ThemeProviderProps) {
44
+ return (
45
+ <NextThemesProvider
46
+ attribute={attribute}
47
+ defaultTheme={defaultTheme}
48
+ enableSystem={enableSystem}
49
+ disableTransitionOnChange={disableTransitionOnChange}
50
+ {...props}
51
+ >
52
+ {children}
53
+ </NextThemesProvider>
54
+ );
55
+ }
56
+
57
+ /**
58
+ * Hook to access theme context
59
+ * Returns theme, setTheme, resolvedTheme, systemTheme, and themes
60
+ */
61
+ export function useThemeContext() {
62
+ const { theme, setTheme, resolvedTheme, systemTheme, themes } = useNextTheme();
63
+
64
+ const toggleTheme = () => {
65
+ // Toggle between light and dark (ignore system)
66
+ const currentResolved = resolvedTheme || 'light';
67
+ setTheme(currentResolved === 'light' ? 'dark' : 'light');
68
+ };
69
+
70
+ return {
71
+ theme: theme as Theme | undefined,
72
+ setTheme,
73
+ resolvedTheme: resolvedTheme as 'light' | 'dark' | undefined,
74
+ systemTheme: systemTheme as 'light' | 'dark' | undefined,
75
+ themes,
76
+ toggleTheme,
77
+ };
78
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * ThemeToggle - Theme switcher component
3
+ *
4
+ * Switches between light and dark themes.
5
+ * Must be used within ThemeProvider.
6
+ *
7
+ * @example
8
+ * ```tsx
9
+ * import { ThemeToggle } from '@djangocfg/ui-core/theme';
10
+ *
11
+ * // Default
12
+ * <ThemeToggle />
13
+ *
14
+ * // Compact (for mobile/tight spaces)
15
+ * <ThemeToggle size="compact" />
16
+ *
17
+ * // Custom className
18
+ * <ThemeToggle className="ml-auto" />
19
+ * ```
20
+ */
21
+
22
+ 'use client';
23
+
24
+ import { Moon, Sun } from 'lucide-react';
25
+ import { useEffect, useState } from 'react';
26
+
27
+ import { Button } from '../components/forms/button';
28
+ import { useIsMobile } from '../hooks/media/useMobile';
29
+ import { cn } from '../lib/utils';
30
+ import { useForcedTheme } from './ForcedThemeContext';
31
+ import { useThemeContext } from './ThemeProvider';
32
+
33
+ export type ThemeLockBehavior = 'disable' | 'hide';
34
+
35
+ export interface ThemeToggleProps {
36
+ /** Custom className */
37
+ className?: string;
38
+ /** Size variant (auto-detects mobile if not specified) */
39
+ size?: 'default' | 'compact' | 'auto';
40
+ /**
41
+ * What to do when the current route forces a theme via `ThemeOverride`.
42
+ * - `disable` (default): render the toggle disabled with a tooltip.
43
+ * - `hide`: render nothing.
44
+ */
45
+ lockedBehavior?: ThemeLockBehavior;
46
+ /** Title shown when the control is locked. */
47
+ lockedTitle?: string;
48
+ }
49
+
50
+ export function ThemeToggle({
51
+ className,
52
+ size = 'auto',
53
+ lockedBehavior = 'disable',
54
+ lockedTitle = 'Theme is set for this page',
55
+ }: ThemeToggleProps) {
56
+ const { resolvedTheme, toggleTheme } = useThemeContext();
57
+ const forcedTheme = useForcedTheme();
58
+ const [mounted, setMounted] = useState(false);
59
+ const isMobile = useIsMobile();
60
+
61
+ // Prevent hydration mismatch
62
+ useEffect(() => {
63
+ setMounted(true);
64
+ }, []);
65
+
66
+ const isLocked = Boolean(forcedTheme);
67
+ // Determine actual size based on prop and screen size
68
+ const actualSize = size === 'auto' ? (isMobile ? 'compact' : 'default') : size;
69
+ const buttonSize = actualSize === 'compact' ? 'h-8 w-8' : 'h-9 w-9';
70
+ const iconSize = actualSize === 'compact' ? 'h-3.5 w-3.5' : 'h-4 w-4';
71
+
72
+ // The icon always reflects what's on screen (forced or not) — that is
73
+ // `resolvedTheme`. When locked, it shows the forced theme's icon.
74
+ const showSun = mounted ? resolvedTheme === 'light' : true;
75
+
76
+ if (isLocked && lockedBehavior === 'hide') {
77
+ return null;
78
+ }
79
+
80
+ if (!mounted) {
81
+ return (
82
+ <Button
83
+ variant="ghost"
84
+ size="icon"
85
+ className={cn(buttonSize, className)}
86
+ disabled
87
+ >
88
+ <Sun className={iconSize} />
89
+ <span className="sr-only">Toggle theme</span>
90
+ </Button>
91
+ );
92
+ }
93
+
94
+ return (
95
+ <Button
96
+ variant="ghost"
97
+ size="icon"
98
+ onClick={isLocked ? undefined : toggleTheme}
99
+ disabled={isLocked}
100
+ title={isLocked ? lockedTitle : undefined}
101
+ aria-label={isLocked ? lockedTitle : 'Toggle theme'}
102
+ className={cn(buttonSize, isLocked && 'cursor-not-allowed opacity-60', className)}
103
+ >
104
+ {showSun ? <Sun className={iconSize} /> : <Moon className={iconSize} />}
105
+ <span className="sr-only">{isLocked ? lockedTitle : 'Toggle theme'}</span>
106
+ </Button>
107
+ );
108
+ }
@@ -0,0 +1,10 @@
1
+ 'use client';
2
+
3
+ export { ThemeProvider, useThemeContext } from './ThemeProvider';
4
+ export type { Theme, ThemeProviderProps } from './ThemeProvider';
5
+ export { ThemeToggle } from './ThemeToggle';
6
+ export type { ThemeToggleProps, ThemeLockBehavior } from './ThemeToggle';
7
+ export { ForceTheme } from './ForceTheme';
8
+ export { ThemeOverride, resolveForcedTheme } from './ThemeOverride';
9
+ export type { ThemeOverrideRule, ThemeOverrideProps, ForcedTheme } from './ThemeOverride';
10
+ export { ForcedThemeProvider, useForcedTheme } from './ForcedThemeContext';