@sigx/lynx-zero 0.4.9

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.
Files changed (100) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +25 -0
  3. package/dist/components/SwiperIndicator.d.ts +43 -0
  4. package/dist/components/SwiperIndicator.d.ts.map +1 -0
  5. package/dist/components/SwiperIndicator.js +272 -0
  6. package/dist/components/SwiperIndicator.js.map +1 -0
  7. package/dist/contract.d.ts +95 -0
  8. package/dist/contract.d.ts.map +1 -0
  9. package/dist/contract.js +30 -0
  10. package/dist/contract.js.map +1 -0
  11. package/dist/index.d.ts +30 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +41 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/layout/Center.d.ts +7 -0
  16. package/dist/layout/Center.d.ts.map +1 -0
  17. package/dist/layout/Center.js +25 -0
  18. package/dist/layout/Center.js.map +1 -0
  19. package/dist/layout/Col.d.ts +8 -0
  20. package/dist/layout/Col.d.ts.map +1 -0
  21. package/dist/layout/Col.js +34 -0
  22. package/dist/layout/Col.js.map +1 -0
  23. package/dist/layout/Row.d.ts +8 -0
  24. package/dist/layout/Row.d.ts.map +1 -0
  25. package/dist/layout/Row.js +34 -0
  26. package/dist/layout/Row.js.map +1 -0
  27. package/dist/layout/ScrollView.d.ts +6 -0
  28. package/dist/layout/ScrollView.d.ts.map +1 -0
  29. package/dist/layout/ScrollView.js +19 -0
  30. package/dist/layout/ScrollView.js.map +1 -0
  31. package/dist/layout/Spacer.d.ts +4 -0
  32. package/dist/layout/Spacer.d.ts.map +1 -0
  33. package/dist/layout/Spacer.js +12 -0
  34. package/dist/layout/Spacer.js.map +1 -0
  35. package/dist/preset/index.d.ts +31 -0
  36. package/dist/preset/index.d.ts.map +1 -0
  37. package/dist/preset/index.js +72 -0
  38. package/dist/preset/index.js.map +1 -0
  39. package/dist/shared/press.d.ts +3 -0
  40. package/dist/shared/press.d.ts.map +1 -0
  41. package/dist/shared/press.js +7 -0
  42. package/dist/shared/press.js.map +1 -0
  43. package/dist/shared/styles.d.ts +27 -0
  44. package/dist/shared/styles.d.ts.map +1 -0
  45. package/dist/shared/styles.js +62 -0
  46. package/dist/shared/styles.js.map +1 -0
  47. package/dist/shared/tabs-selection.d.ts +25 -0
  48. package/dist/shared/tabs-selection.d.ts.map +1 -0
  49. package/dist/shared/tabs-selection.js +45 -0
  50. package/dist/shared/tabs-selection.js.map +1 -0
  51. package/dist/styles/tokens.css +98 -0
  52. package/dist/theme/StatusBarSync.d.ts +42 -0
  53. package/dist/theme/StatusBarSync.d.ts.map +1 -0
  54. package/dist/theme/StatusBarSync.js +89 -0
  55. package/dist/theme/StatusBarSync.js.map +1 -0
  56. package/dist/theme/ThemeProvider.d.ts +144 -0
  57. package/dist/theme/ThemeProvider.d.ts.map +1 -0
  58. package/dist/theme/ThemeProvider.js +328 -0
  59. package/dist/theme/ThemeProvider.js.map +1 -0
  60. package/dist/theme/color-mix.d.ts +21 -0
  61. package/dist/theme/color-mix.d.ts.map +1 -0
  62. package/dist/theme/color-mix.js +65 -0
  63. package/dist/theme/color-mix.js.map +1 -0
  64. package/dist/theme/registry.d.ts +182 -0
  65. package/dist/theme/registry.d.ts.map +1 -0
  66. package/dist/theme/registry.js +182 -0
  67. package/dist/theme/registry.js.map +1 -0
  68. package/dist/theme/theme-state.d.ts +43 -0
  69. package/dist/theme/theme-state.d.ts.map +1 -0
  70. package/dist/theme/theme-state.js +94 -0
  71. package/dist/theme/theme-state.js.map +1 -0
  72. package/dist/theme/use-screen-theme.d.ts +4 -0
  73. package/dist/theme/use-screen-theme.d.ts.map +1 -0
  74. package/dist/theme/use-screen-theme.js +43 -0
  75. package/dist/theme/use-screen-theme.js.map +1 -0
  76. package/dist/theme/use-theme-colors.d.ts +48 -0
  77. package/dist/theme/use-theme-colors.d.ts.map +1 -0
  78. package/dist/theme/use-theme-colors.js +69 -0
  79. package/dist/theme/use-theme-colors.js.map +1 -0
  80. package/package.json +80 -0
  81. package/src/components/SwiperIndicator.tsx +519 -0
  82. package/src/contract.ts +136 -0
  83. package/src/index.ts +101 -0
  84. package/src/layout/Center.tsx +41 -0
  85. package/src/layout/Col.tsx +53 -0
  86. package/src/layout/Row.tsx +53 -0
  87. package/src/layout/ScrollView.tsx +38 -0
  88. package/src/layout/Spacer.tsx +18 -0
  89. package/src/preset/index.ts +77 -0
  90. package/src/shared/press.ts +6 -0
  91. package/src/shared/styles.ts +82 -0
  92. package/src/shared/tabs-selection.ts +57 -0
  93. package/src/styles/tokens.css +98 -0
  94. package/src/theme/StatusBarSync.tsx +104 -0
  95. package/src/theme/ThemeProvider.tsx +492 -0
  96. package/src/theme/color-mix.ts +68 -0
  97. package/src/theme/registry.ts +290 -0
  98. package/src/theme/theme-state.ts +112 -0
  99. package/src/theme/use-screen-theme.ts +42 -0
  100. package/src/theme/use-theme-colors.ts +99 -0
@@ -0,0 +1,290 @@
1
+ /**
2
+ * Theme registry — the single source of truth for registered themes.
3
+ *
4
+ * A theme is *data*: a name, a light/dark variant, and a full color palette
5
+ * (plus an optional toggle `pair` and roundness overrides). Both rendering and
6
+ * any DS-specific consumers (e.g. icon tinting) read from here —
7
+ * `<ThemeProvider>` applies a theme's `colors` as inline CSS custom properties
8
+ * on its host view (Lynx inherits custom properties to descendants, so
9
+ * component classes resolve `var(--color-*)`). There is no per-theme CSS or
10
+ * parallel JS palette to keep in sync.
11
+ *
12
+ * The registry starts **empty** — design-system packages seed it at module
13
+ * load (e.g. `@sigx/lynx-daisyui` registers its six built-ins on import).
14
+ * Register more — including tenant themes fetched at runtime — with
15
+ * `registerTheme()`, or `extendTheme()` to derive one from a base. Order
16
+ * matters for `pickThemeFor()`: the first theme of a given variant is the
17
+ * follow-system default for that variant.
18
+ *
19
+ * Structural tokens (radius, sizing, component dimensions) are theme-agnostic
20
+ * and ship once in the bundled `.lynx-zero` base class (`styles/tokens.css`);
21
+ * a theme may override roundness via `radius` and base size units via `sizes`.
22
+ *
23
+ * Colors are engine-safe strings — hex or `rgb()`. Lynx's CSS engine does not
24
+ * parse `oklch()`, so convert before registering.
25
+ */
26
+ import {
27
+ COLOR_VARIANT_LIST,
28
+ type ColorToken,
29
+ type CoreColorToken,
30
+ type SoftColorToken,
31
+ } from '../contract.js';
32
+ import { mixColors } from './color-mix.js';
33
+
34
+ export type ThemeVariant = 'light' | 'dark';
35
+
36
+ /**
37
+ * Full *registered* color palette — every semantic token including the
38
+ * `*-soft` tints, no holes. This is what `colorsOf()` returns.
39
+ */
40
+ export type ThemePalette = Record<ColorToken, string>;
41
+
42
+ /**
43
+ * What a theme *author* writes: every core token, with the `*-soft` tints
44
+ * optional — any omitted soft is computed at registration (`softMix` of the
45
+ * variant color into `base-100`).
46
+ */
47
+ export type ThemePaletteInput =
48
+ & Record<CoreColorToken, string>
49
+ & Partial<Record<SoftColorToken, string>>;
50
+
51
+ /**
52
+ * Roundness token overrides. Emitted as `--radius-selector` /
53
+ * `--radius-field` / `--radius-box`. Defaults live in the bundled
54
+ * `.lynx-zero` base.
55
+ */
56
+ export interface ThemeRadius {
57
+ /** Small selectable controls — checkbox, toggle, badge. */
58
+ selector?: string;
59
+ /** Fields — button, input, select, textarea. */
60
+ field?: string;
61
+ /** Boxes — card, modal, alert. */
62
+ box?: string;
63
+ }
64
+
65
+ /**
66
+ * Base size-unit overrides. Emitted as `--size-selector` / `--size-field`;
67
+ * component dimensions are integer multiples of these. Defaults live in the
68
+ * bundled `.lynx-zero` base.
69
+ */
70
+ export interface ThemeSizes {
71
+ /** Base unit for selector controls (checkbox, toggle, badge). */
72
+ selector?: string;
73
+ /** Base unit for fields (button, input, select). */
74
+ field?: string;
75
+ }
76
+
77
+ export interface ThemeInput {
78
+ /** Unique id — also the value of `theme.name`. */
79
+ name: string;
80
+ /** Light or dark — drives follow-system selection and status-bar tint. */
81
+ variant: ThemeVariant;
82
+ /** Color palette — core tokens required, `*-soft` tints optional. */
83
+ colors: ThemePaletteInput;
84
+ /**
85
+ * Which theme `toggle()` flips to. Defaults to the first registered theme of
86
+ * the opposite variant.
87
+ */
88
+ pair?: string;
89
+ /** Optional roundness overrides; unspecified tokens fall back to the base. */
90
+ radius?: ThemeRadius;
91
+ /** Optional base size-unit overrides; unspecified tokens fall back to the base. */
92
+ sizes?: ThemeSizes;
93
+ /**
94
+ * Whether this theme ships a build-time CSS class named after it (the DS
95
+ * package generates `.theme-name { --color-*: … }` at build time, e.g. via
96
+ * daisyui's `gen-theme-css.mjs`). Such themes paint correctly on the very
97
+ * first frame; themes without it apply via the runtime `setProperty` path
98
+ * post-mount, with their variant's static theme class as the first-frame
99
+ * fallback.
100
+ */
101
+ staticCss?: boolean;
102
+ /**
103
+ * How strong the computed `*-soft` tints are: the ratio of the variant
104
+ * color mixed into `base-100` for any soft token the palette doesn't set
105
+ * explicitly. Design-system flavor, carried as theme data — daisy's
106
+ * built-ins use `0.08` (daisyUI v5's ~8% tints), hero's use `0.2`
107
+ * (HeroUI's `color/20`). Default `0.16`.
108
+ */
109
+ softMix?: number;
110
+ }
111
+
112
+ /** A registered theme — same shape as the input, with the palette completed. */
113
+ export interface Theme extends Omit<ThemeInput, 'colors'> {
114
+ colors: ThemePalette;
115
+ }
116
+
117
+ const DEFAULT_SOFT_MIX = 0.16;
118
+
119
+ /**
120
+ * Complete a theme's palette: any `*-soft` token the author didn't set is
121
+ * computed as `softMix` of the variant color mixed into `base-100` (in JS —
122
+ * Lynx CSS can't alpha-compose `var()` colors, so the tints are materialized
123
+ * in the palette). Idempotent; explicitly provided softs are kept verbatim.
124
+ *
125
+ * DS packages run their builtin arrays through this before exporting them so
126
+ * build scripts (gen-theme-css) see the same palette the registry serves.
127
+ */
128
+ export function completeTheme(input: ThemeInput): Theme {
129
+ const mix = input.softMix ?? DEFAULT_SOFT_MIX;
130
+ const colors = { ...input.colors } as ThemePalette;
131
+ for (const variant of COLOR_VARIANT_LIST) {
132
+ const soft: SoftColorToken = `${variant}-soft`;
133
+ if (colors[soft] === undefined) {
134
+ colors[soft] = mixColors(colors[variant], colors['base-100'], mix);
135
+ }
136
+ }
137
+ return { ...input, colors };
138
+ }
139
+
140
+ const registry: Theme[] = [];
141
+
142
+ /**
143
+ * Whether `name` is a registered theme that ships a build-time CSS class —
144
+ * i.e. it paints correctly on the first frame. Themes registered without
145
+ * `staticCss` return `false`; `<ThemeProvider>` falls back to their variant's
146
+ * static class for first paint and swaps in the exact palette via
147
+ * `setProperty`.
148
+ */
149
+ export function hasStaticCss(name: string | undefined): boolean {
150
+ return findTheme(name)?.staticCss === true;
151
+ }
152
+
153
+ /**
154
+ * Resolve a `theme.name` to its registered `Theme`. Supports multi-class names
155
+ * like `'daisy-light daisy-rounded'` by matching the first registered id found.
156
+ */
157
+ function findTheme(name: string | undefined): Theme | undefined {
158
+ if (!name) return undefined;
159
+ for (const part of name.split(/\s+/)) {
160
+ const hit = registry.find((t) => t.name === part);
161
+ if (hit) return hit;
162
+ }
163
+ return undefined;
164
+ }
165
+
166
+ /**
167
+ * All registered themes in insertion order. Returns a shallow copy so callers
168
+ * can't mutate the internal registry — re-registration goes through
169
+ * `registerTheme()`. Each entry is a full `Theme` (name, variant, palette),
170
+ * so consumers can render swatches in a picker.
171
+ */
172
+ export function listThemes(): readonly Theme[] {
173
+ return registry.slice();
174
+ }
175
+
176
+ /**
177
+ * Register (or replace, by `name`) a theme. Call at module-load time before
178
+ * mounting `<ThemeProvider>` so it shows up in `listThemes()` / `pickThemeFor()`.
179
+ * The palette is completed on the way in (`completeTheme`): any `*-soft`
180
+ * token the author didn't set is computed from `softMix`.
181
+ */
182
+ export function registerTheme(theme: ThemeInput): void {
183
+ const complete = completeTheme(theme);
184
+ const i = registry.findIndex((t) => t.name === complete.name);
185
+ if (i >= 0) registry[i] = complete;
186
+ else registry.push(complete);
187
+ }
188
+
189
+ /**
190
+ * Derive a new theme from a registered base, overriding any colors / roundness.
191
+ * Ergonomic for "tenant tweaks a few tokens": the result is a full `Theme` you
192
+ * pass to `registerTheme()`. Throws if `base` isn't registered.
193
+ *
194
+ * ```ts
195
+ * registerTheme(extendTheme('daisy-dark', {
196
+ * name: 'acme-dark',
197
+ * colors: { primary: '#fb7185' },
198
+ * }));
199
+ * ```
200
+ */
201
+ export function extendTheme(
202
+ base: string,
203
+ patch: {
204
+ name: string;
205
+ variant?: ThemeVariant;
206
+ pair?: string;
207
+ colors?: Partial<ThemePalette>;
208
+ radius?: ThemeRadius;
209
+ sizes?: ThemeSizes;
210
+ softMix?: number;
211
+ },
212
+ ): Theme {
213
+ const src = findTheme(base);
214
+ if (!src) {
215
+ throw new Error(
216
+ `[lynx-zero] extendTheme: unknown base theme "${base}". `
217
+ + `Register it first, or extend a theme your design system registered.`,
218
+ );
219
+ }
220
+ // Merge core tokens, then RECOMPUTE every soft tint the patch didn't set
221
+ // explicitly — patching `primary` must not leave the base's stale
222
+ // `primary-soft` behind. (A soft the base author set explicitly is
223
+ // indistinguishable from a computed one post-registration; explicit softs
224
+ // therefore live in the patch when extending.)
225
+ const merged: Record<string, string> = { ...src.colors };
226
+ for (const variant of COLOR_VARIANT_LIST) delete merged[`${variant}-soft`];
227
+ Object.assign(merged, patch.colors);
228
+ return completeTheme({
229
+ name: patch.name,
230
+ variant: patch.variant ?? src.variant,
231
+ pair: patch.pair ?? src.pair,
232
+ colors: merged as ThemePaletteInput,
233
+ radius: patch.radius ?? src.radius,
234
+ sizes: patch.sizes ?? src.sizes,
235
+ softMix: patch.softMix ?? src.softMix,
236
+ });
237
+ }
238
+
239
+ /** The variant of a registered theme, or `undefined` if not registered. */
240
+ export function variantOf(name: string | undefined): ThemeVariant | undefined {
241
+ return findTheme(name)?.variant;
242
+ }
243
+
244
+ /** The color palette of a registered theme, or `undefined` if not registered. */
245
+ export function colorsOf(name: string | undefined): ThemePalette | undefined {
246
+ return findTheme(name)?.colors;
247
+ }
248
+
249
+ /** The roundness overrides of a registered theme, if any. */
250
+ export function radiusOf(name: string | undefined): ThemeRadius | undefined {
251
+ return findTheme(name)?.radius;
252
+ }
253
+
254
+ /** The base size-unit overrides of a registered theme, if any. */
255
+ export function sizesOf(name: string | undefined): ThemeSizes | undefined {
256
+ return findTheme(name)?.sizes;
257
+ }
258
+
259
+ /**
260
+ * The first registered palette — the engine's last-resort fallback when an
261
+ * active theme name isn't registered. `undefined` only when no design system
262
+ * has seeded the registry yet.
263
+ * @internal
264
+ */
265
+ export function fallbackPalette(): ThemePalette | undefined {
266
+ return registry[0]?.colors;
267
+ }
268
+
269
+ /**
270
+ * Pick a default theme for a given system color scheme — the first registered
271
+ * theme of that variant. Falls back to the first registered theme of any
272
+ * variant, or `''` while the registry is empty (a design-system package seeds
273
+ * it at module load, so this is only reachable before any DS import).
274
+ */
275
+ export function pickThemeFor(scheme: ThemeVariant): string {
276
+ const hit = registry.find((t) => t.variant === scheme);
277
+ return hit?.name ?? registry[0]?.name ?? '';
278
+ }
279
+
280
+ /**
281
+ * Resolve the paired theme of a given name — used by `theme.toggle()`. Follows
282
+ * `pair` if set, otherwise the first theme of the opposite variant. Returns the
283
+ * input unchanged when the theme isn't registered.
284
+ */
285
+ export function pairOf(name: string): string {
286
+ const hit = findTheme(name);
287
+ if (!hit) return name;
288
+ if (hit.pair) return hit.pair;
289
+ return pickThemeFor(hit.variant === 'light' ? 'dark' : 'light');
290
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Global theme state — the headless DI singleton behind `useTheme()`.
3
+ *
4
+ * The active selection (current theme name + follow-system flag) lives here as
5
+ * a module-level signal, mirroring how `./registry.ts` is already a global
6
+ * module singleton. This is what makes theme control reachable from *headless*
7
+ * code — a store, a service, app-boot logic, an effect — not just from a
8
+ * component mounted under `<ThemeProvider>`.
9
+ *
10
+ * The root `<ThemeProvider>` (depth 0) binds to this state: it renders its host
11
+ * view from it, owns the system-color-scheme follow effect that writes to it
12
+ * while `following`, and seeds an `initial` prop into it. Nested providers
13
+ * (depth >= 1) build their own local state via `makeThemeController` so a
14
+ * subtree can be overridden without touching the global — see
15
+ * `./ThemeProvider.tsx`.
16
+ *
17
+ * `followSystem()` here only flips the flag; the actual re-apply on an OS color
18
+ * scheme change is driven by the root provider's follow effect (which has the
19
+ * appearance signal in scope).
20
+ */
21
+ import { signal } from '@sigx/lynx';
22
+ import { pairOf, pickThemeFor } from './registry.js';
23
+ import type { ThemeController, ThemeName } from './ThemeProvider.js';
24
+
25
+ /** The mutable selection a `ThemeController` reads from and writes to. */
26
+ export interface ThemeState {
27
+ name: ThemeName;
28
+ following: boolean;
29
+ /**
30
+ * Global text-scale multiplier applied on top of the theme's `--text-*`
31
+ * ramp. Orthogonal to `name`: a theme switch / `toggle()` leaves it
32
+ * untouched, so a user/accessibility scale persists across appearance
33
+ * changes. `1` = the default ramp.
34
+ */
35
+ fontScale: number;
36
+ }
37
+
38
+ /**
39
+ * Coerce a font-scale input to a valid positive, finite multiplier. Rejects
40
+ * `NaN`, `±Infinity`, and non-positive values — which would otherwise emit
41
+ * invalid CSS (`NaNpx`, negative font sizes) and break `fontScale === 1`
42
+ * comparisons — by returning `fallback` instead.
43
+ */
44
+ export function normalizeFontScale(value: unknown, fallback = 1): number {
45
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
46
+ ? value
47
+ : fallback;
48
+ }
49
+
50
+ /**
51
+ * Build a `ThemeController` over a given state object. Used for both the global
52
+ * singleton (below) and each nested `<ThemeProvider>`'s local state — same
53
+ * behaviour, different backing store. `followSystem()` only flips the flag; the
54
+ * owning provider's follow effect performs the re-apply.
55
+ */
56
+ export function makeThemeController(state: ThemeState): ThemeController {
57
+ return {
58
+ get name() {
59
+ return state.name;
60
+ },
61
+ get followingSystem() {
62
+ return state.following;
63
+ },
64
+ get fontScale() {
65
+ return state.fontScale;
66
+ },
67
+ set(next) {
68
+ state.name = next;
69
+ state.following = false;
70
+ },
71
+ toggle() {
72
+ state.name = pairOf(state.name);
73
+ state.following = false;
74
+ },
75
+ followSystem() {
76
+ state.following = true;
77
+ },
78
+ setFontScale(scale) {
79
+ // Ignore invalid input (keep the current scale) so state stays valid.
80
+ state.fontScale = normalizeFontScale(scale, state.fontScale);
81
+ },
82
+ };
83
+ }
84
+
85
+ // Object signal (not primitive) so theme-name literal unions a DS layers on
86
+ // top survive — `signal<T>` widens primitive literals to plain `string` via
87
+ // `Widen<T>`. Seeded from whatever is registered at first import (a DS package
88
+ // seeds the registry at its own module load; until then the name is '') —
89
+ // the root <ThemeProvider> re-seeds from the system color scheme + its props
90
+ // on mount.
91
+ const state = signal<ThemeState>({
92
+ name: pickThemeFor('light'),
93
+ following: true,
94
+ fontScale: 1,
95
+ });
96
+
97
+ /**
98
+ * The backing signal for the global theme. Read/written by the root
99
+ * `<ThemeProvider>` and shared with `themeController`; not part of the public
100
+ * API.
101
+ * @internal
102
+ */
103
+ export const globalThemeState = state;
104
+
105
+ /**
106
+ * The global theme controller — the headless handle. Import and call from
107
+ * anywhere (no `<ThemeProvider>` ancestor required); `useTheme()`'s default
108
+ * factory returns this same instance, and the root `<ThemeProvider>` provides
109
+ * it to its subtree. `StatusBarSync` binds to it so the OS bars always follow
110
+ * the global/screen theme, never a content sub-scope.
111
+ */
112
+ export const themeController: ThemeController = makeThemeController(state);
@@ -0,0 +1,42 @@
1
+ /**
2
+ * `useScreenTheme(name)` — pin the **global** theme while a navigation
3
+ * screen is focused, restoring the previous selection when it blurs.
4
+ *
5
+ * This is the right tool for *per-screen* theming — "this screen is dark, that
6
+ * one is light." Because it drives the global theme (not a content sub-scope),
7
+ * the OS status/navigation bars follow automatically via `<StatusBarSync>`, so
8
+ * the bar icons stay legible against each screen's background. For recoloring a
9
+ * *region within* a screen without touching the bars, nest a `<ThemeProvider>`
10
+ * instead.
11
+ *
12
+ * Built on `useFocusEffect` from `@sigx/lynx-navigation` (an optional peer
13
+ * dependency): it must be called from inside a component rendered as a route by
14
+ * `<Stack>` / `<Tabs>` — the same constraint as `useFocusEffect`/`useIsFocused`.
15
+ *
16
+ * Save/restore composes with the stack (LIFO focus/blur): pushing a themed
17
+ * screen saves whatever was live, applies its own theme, and restores on pop —
18
+ * including resuming follow-system if that's what was active.
19
+ *
20
+ * ```tsx
21
+ * const Gallery = component(() => {
22
+ * useScreenTheme('daisy-dark'); // dark while this screen is on top
23
+ * return () => <view>…</view>;
24
+ * });
25
+ * ```
26
+ */
27
+ import { useFocusEffect } from '@sigx/lynx-navigation';
28
+ import { themeController } from './theme-state.js';
29
+ import type { ThemeName } from './ThemeProvider.js';
30
+
31
+ /** Pin the global theme to `name` while this screen is focused; restore on blur. */
32
+ export function useScreenTheme(name: ThemeName): void {
33
+ useFocusEffect(() => {
34
+ const prevName = themeController.name;
35
+ const prevFollowing = themeController.followingSystem;
36
+ themeController.set(name);
37
+ return () => {
38
+ if (prevFollowing) themeController.followSystem();
39
+ else themeController.set(prevName);
40
+ };
41
+ });
42
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * `useThemeColors()` — resolve the *active, scoped* theme palette to concrete
3
+ * color values for consumers that can't read CSS custom properties.
4
+ *
5
+ * Native widgets are the audience: platform text inputs, `<sigx-richtext>`,
6
+ * SVG fills — anything where `var(--color-*)` never resolves because the
7
+ * value is consumed outside Lynx's CSS pipeline. Components pass these
8
+ * resolved literals via inline `style` or native props instead.
9
+ *
10
+ * Scoped + reactive: resolves through `useTheme()` (the nearest
11
+ * `<ThemeProvider>`'s controller, falling back to the global one), and the
12
+ * getters read `theme.name` — call them inside render and a theme switch
13
+ * recolors the consumer.
14
+ *
15
+ * ```tsx
16
+ * const colors = useThemeColors();
17
+ * return () => (
18
+ * <input style={{
19
+ * color: colors.colorOf('base-content'),
20
+ * '-x-placeholder-color': colors.colorOf('base-content', 0.45),
21
+ * }} />
22
+ * );
23
+ * ```
24
+ */
25
+ import type { ColorToken } from '../contract.js';
26
+ import { colorsOf, fallbackPalette } from './registry.js';
27
+ import { useTheme } from './ThemeProvider.js';
28
+
29
+ export interface ThemeColors {
30
+ /**
31
+ * The active palette's value for `token`, normalized to hex — optionally
32
+ * with `alpha` (0–1) appended as a hex byte (`#RRGGBBAA`). Returns `''`
33
+ * when no theme is registered yet (pre-DS-import edge case).
34
+ */
35
+ colorOf(token: ColorToken, alpha?: number): string;
36
+ }
37
+
38
+ export function useThemeColors(): ThemeColors {
39
+ const theme = useTheme();
40
+ return {
41
+ colorOf(token, alpha) {
42
+ // Reading `theme.name` here is what makes call sites reactive.
43
+ const palette = colorsOf(theme.name) ?? fallbackPalette();
44
+ const raw = palette?.[token];
45
+ if (!raw) return '';
46
+ const hex = toHexColor(raw);
47
+ return alpha === undefined ? hex : withAlpha(hex, alpha);
48
+ },
49
+ };
50
+ }
51
+
52
+ /**
53
+ * Normalize an engine-safe palette color to full-form hex
54
+ * (`#RRGGBB`/`#RRGGBBAA`) — the registry allows `rgb()`/`rgba()` entries and
55
+ * shorthand hex, but native color parsers may accept only the full forms.
56
+ * Unknown notations pass through unchanged.
57
+ */
58
+ export function toHexColor(color: string): string {
59
+ const c = color.trim();
60
+ if (c.startsWith('#')) {
61
+ const h = c.slice(1);
62
+ // Expand #RGB / #RGBA to the full form; leave other lengths as-is.
63
+ if (h.length === 3 || h.length === 4) {
64
+ return `#${h.split('').map((ch) => ch + ch).join('')}`;
65
+ }
66
+ return c;
67
+ }
68
+ const m = /^rgba?\(\s*(\d+)\s*[, ]\s*(\d+)\s*[, ]\s*(\d+)\s*(?:[,/]\s*([\d.]+%?)\s*)?\)$/i.exec(c);
69
+ if (!m) return c;
70
+ const byte = (v: number): string =>
71
+ Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0');
72
+ let hex = `#${byte(Number(m[1]))}${byte(Number(m[2]))}${byte(Number(m[3]))}`;
73
+ if (m[4] !== undefined) {
74
+ const a = m[4].endsWith('%') ? Number(m[4].slice(0, -1)) / 100 : Number(m[4]);
75
+ hex += byte(Math.max(0, Math.min(1, a)) * 255);
76
+ }
77
+ return hex;
78
+ }
79
+
80
+ /**
81
+ * Append an alpha channel (0–1) to a hex color
82
+ * (`#RGB`/`#RRGGBB`/`#RRGGBBAA` → `#RRGGBBAA`). Non-hex input passes
83
+ * through unchanged; non-finite alpha is treated as opaque.
84
+ */
85
+ export function withAlpha(hex: string, alpha: number): string {
86
+ const input = hex.trim();
87
+ if (!input.startsWith('#')) return input;
88
+ if (!Number.isFinite(alpha)) return input;
89
+ let h = input.slice(1);
90
+ if (h.length === 3) h = h.split('').map((c) => c + c).join('');
91
+ if (h.length === 8) h = h.slice(0, 6);
92
+ // Anything that isn't #RRGGBB by now (#RGBA, bad lengths) is not a shape
93
+ // we can safely re-alpha — return it unchanged rather than corrupt it.
94
+ if (h.length !== 6) return input;
95
+ const byte = Math.round(Math.max(0, Math.min(1, alpha)) * 255)
96
+ .toString(16)
97
+ .padStart(2, '0');
98
+ return `#${h}${byte}`;
99
+ }