nitrowind 0.0.0-stage → 0.1.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.
Files changed (155) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE +21 -0
  3. package/README.md +44 -2
  4. package/css.d.ts +6 -0
  5. package/dist/color.d.ts +24 -0
  6. package/dist/color.d.ts.map +1 -0
  7. package/dist/color.js +158 -0
  8. package/dist/color.js.map +1 -0
  9. package/dist/core.d.ts +121 -0
  10. package/dist/core.d.ts.map +1 -0
  11. package/dist/core.js +1026 -0
  12. package/dist/core.js.map +1 -0
  13. package/dist/css/compile.d.ts +18 -0
  14. package/dist/css/compile.d.ts.map +1 -0
  15. package/dist/css/compile.js +1018 -0
  16. package/dist/css/compile.js.map +1 -0
  17. package/dist/css/declarations.d.ts +18 -0
  18. package/dist/css/declarations.d.ts.map +1 -0
  19. package/dist/css/declarations.js +1173 -0
  20. package/dist/css/declarations.js.map +1 -0
  21. package/dist/css/index.d.ts +7 -0
  22. package/dist/css/index.d.ts.map +1 -0
  23. package/dist/css/index.js +7 -0
  24. package/dist/css/index.js.map +1 -0
  25. package/dist/css/parser.d.ts +9 -0
  26. package/dist/css/parser.d.ts.map +1 -0
  27. package/dist/css/parser.js +188 -0
  28. package/dist/css/parser.js.map +1 -0
  29. package/dist/css/tokenizer.d.ts +14 -0
  30. package/dist/css/tokenizer.d.ts.map +1 -0
  31. package/dist/css/tokenizer.js +200 -0
  32. package/dist/css/tokenizer.js.map +1 -0
  33. package/dist/css/types.d.ts +128 -0
  34. package/dist/css/types.d.ts.map +1 -0
  35. package/dist/css/types.js +19 -0
  36. package/dist/css/types.js.map +1 -0
  37. package/dist/css/values.d.ts +37 -0
  38. package/dist/css/values.d.ts.map +1 -0
  39. package/dist/css/values.js +343 -0
  40. package/dist/css/values.js.map +1 -0
  41. package/dist/environment.d.ts +5 -0
  42. package/dist/environment.d.ts.map +1 -0
  43. package/dist/environment.js +99 -0
  44. package/dist/environment.js.map +1 -0
  45. package/dist/hooks.d.ts +22 -0
  46. package/dist/hooks.d.ts.map +1 -0
  47. package/dist/hooks.js +140 -0
  48. package/dist/hooks.js.map +1 -0
  49. package/dist/index.d.ts +26 -0
  50. package/dist/index.d.ts.map +1 -0
  51. package/dist/index.js +16 -0
  52. package/dist/index.js.map +1 -0
  53. package/dist/jsx-dev-runtime.d.ts +17 -0
  54. package/dist/jsx-dev-runtime.d.ts.map +1 -0
  55. package/dist/jsx-dev-runtime.js +12 -0
  56. package/dist/jsx-dev-runtime.js.map +1 -0
  57. package/dist/jsx-namespace.d.ts +29 -0
  58. package/dist/jsx-namespace.d.ts.map +1 -0
  59. package/dist/jsx-namespace.js +2 -0
  60. package/dist/jsx-namespace.js.map +1 -0
  61. package/dist/jsx-runtime.d.ts +22 -0
  62. package/dist/jsx-runtime.d.ts.map +1 -0
  63. package/dist/jsx-runtime.js +21 -0
  64. package/dist/jsx-runtime.js.map +1 -0
  65. package/dist/math.d.ts +50 -0
  66. package/dist/math.d.ts.map +1 -0
  67. package/dist/math.js +442 -0
  68. package/dist/math.js.map +1 -0
  69. package/dist/plugin.d.ts +45 -0
  70. package/dist/plugin.d.ts.map +1 -0
  71. package/dist/plugin.js +172 -0
  72. package/dist/plugin.js.map +1 -0
  73. package/dist/props.d.ts +29 -0
  74. package/dist/props.d.ts.map +1 -0
  75. package/dist/props.js +163 -0
  76. package/dist/props.js.map +1 -0
  77. package/dist/scope.d.ts +99 -0
  78. package/dist/scope.d.ts.map +1 -0
  79. package/dist/scope.js +228 -0
  80. package/dist/scope.js.map +1 -0
  81. package/dist/store.d.ts +18 -0
  82. package/dist/store.d.ts.map +1 -0
  83. package/dist/store.js +244 -0
  84. package/dist/store.js.map +1 -0
  85. package/dist/tokens/index.d.ts +12 -0
  86. package/dist/tokens/index.d.ts.map +1 -0
  87. package/dist/tokens/index.js +237 -0
  88. package/dist/tokens/index.js.map +1 -0
  89. package/dist/tokens/tailwind.generated.d.ts +3 -0
  90. package/dist/tokens/tailwind.generated.d.ts.map +1 -0
  91. package/dist/tokens/tailwind.generated.js +610 -0
  92. package/dist/tokens/tailwind.generated.js.map +1 -0
  93. package/dist/tokens/types.d.ts +95 -0
  94. package/dist/tokens/types.d.ts.map +1 -0
  95. package/dist/tokens/types.js +2 -0
  96. package/dist/tokens/types.js.map +1 -0
  97. package/dist/transform.d.ts +22 -0
  98. package/dist/transform.d.ts.map +1 -0
  99. package/dist/transform.js +79 -0
  100. package/dist/transform.js.map +1 -0
  101. package/dist/transition.d.ts +7 -0
  102. package/dist/transition.d.ts.map +1 -0
  103. package/dist/transition.js +355 -0
  104. package/dist/transition.js.map +1 -0
  105. package/dist/types.d.ts +214 -0
  106. package/dist/types.d.ts.map +1 -0
  107. package/dist/types.js +2 -0
  108. package/dist/types.js.map +1 -0
  109. package/dist/utilities.d.ts +109 -0
  110. package/dist/utilities.d.ts.map +1 -0
  111. package/dist/utilities.js +2000 -0
  112. package/dist/utilities.js.map +1 -0
  113. package/dist/variables.d.ts +65 -0
  114. package/dist/variables.d.ts.map +1 -0
  115. package/dist/variables.js +408 -0
  116. package/dist/variables.js.map +1 -0
  117. package/dist/version.d.ts +3 -0
  118. package/dist/version.d.ts.map +1 -0
  119. package/dist/version.js +3 -0
  120. package/dist/version.js.map +1 -0
  121. package/dist/withNitroWind.d.ts +11 -0
  122. package/dist/withNitroWind.d.ts.map +1 -0
  123. package/dist/withNitroWind.js +27 -0
  124. package/dist/withNitroWind.js.map +1 -0
  125. package/package.json +89 -4
  126. package/src/color.ts +164 -0
  127. package/src/core.ts +1248 -0
  128. package/src/css/compile.ts +1198 -0
  129. package/src/css/declarations.ts +1141 -0
  130. package/src/css/index.ts +22 -0
  131. package/src/css/parser.ts +196 -0
  132. package/src/css/tokenizer.ts +227 -0
  133. package/src/css/types.ts +178 -0
  134. package/src/css/values.ts +330 -0
  135. package/src/environment.ts +112 -0
  136. package/src/hooks.ts +190 -0
  137. package/src/index.ts +61 -0
  138. package/src/jsx-dev-runtime.ts +43 -0
  139. package/src/jsx-namespace.ts +23 -0
  140. package/src/jsx-runtime.ts +39 -0
  141. package/src/math.ts +488 -0
  142. package/src/plugin.ts +230 -0
  143. package/src/props.ts +173 -0
  144. package/src/scope.ts +331 -0
  145. package/src/store.ts +288 -0
  146. package/src/tokens/index.ts +252 -0
  147. package/src/tokens/tailwind.generated.ts +613 -0
  148. package/src/tokens/types.ts +99 -0
  149. package/src/transform.ts +115 -0
  150. package/src/transition.ts +414 -0
  151. package/src/types.ts +248 -0
  152. package/src/utilities.ts +1992 -0
  153. package/src/variables.ts +509 -0
  154. package/src/version.ts +2 -0
  155. package/src/withNitroWind.ts +36 -0
package/src/scope.ts ADDED
@@ -0,0 +1,331 @@
1
+ import {
2
+ createContext,
3
+ createElement,
4
+ type ReactElement,
5
+ type ReactNode,
6
+ useContext,
7
+ useLayoutEffect,
8
+ useMemo,
9
+ } from 'react'
10
+ import { getNitroWind } from './core'
11
+ import type { ColorScheme, CSSVariables, ThemeName, Unsubscribe } from './types'
12
+ import { mergeScopedVariables, referencedVariableNames } from './variables'
13
+
14
+ /**
15
+ * Scoped variable layers split around the nearest enclosing `ScopedTheme`:
16
+ * `inner` holds variables from `ScopedVariables` inside that `ScopedTheme` (win over the theme),
17
+ * and `outer` holds variables from `ScopedVariables` outside it (the theme wins over `outer`,
18
+ * while variables the theme doesn't declare inherit from `outer` before shared defaults).
19
+ */
20
+ export interface ScopedVariableLayers {
21
+ readonly inner?: Readonly<CSSVariables>
22
+ readonly outer?: Readonly<CSSVariables>
23
+ }
24
+
25
+ /**
26
+ * The merged variables of a variable scope and every variable scope above it.
27
+ * One per mounted `ScopedVariables`, so its identity stays stable while its values change:
28
+ * a change notifies subscribers (classes and `useCSSVariable` calls that read variables)
29
+ * instead of re-rendering every element under the scope through the context.
30
+ */
31
+ export interface VariableScope {
32
+ /** The merged variables as frozen plain data (all enclosing `ScopedVariables`, innermost wins). */
33
+ readonly getVariables: () => Readonly<CSSVariables>
34
+ /** The scoped variables split into `inner` (below the nearest `ScopedTheme`) and `outer` (above it). */
35
+ readonly getLayers: () => ScopedVariableLayers
36
+ /**
37
+ * Notified when this scope's or any enclosing variable scope's values change, and when
38
+ * `updateCSSVariables` changes a variable that those values read through `var()` in `theme`
39
+ * (or the active global theme when `theme` is omitted).
40
+ */
41
+ readonly subscribe: (listener: () => void, theme?: ThemeName) => Unsubscribe
42
+ /** Referentially stable subscriber for `useSyncExternalStore` in `theme` (or the active global theme). */
43
+ readonly getSubscriber: (theme?: ThemeName) => (listener: () => void) => Unsubscribe
44
+ }
45
+
46
+ interface WritableVariableScope extends VariableScope {
47
+ /**
48
+ * Stores this scope's own values without notifying, so children rendering after this call
49
+ * read them. `ScopedVariables` calls it during render.
50
+ */
51
+ setOwn(own: Readonly<CSSVariables>): void
52
+ /**
53
+ * Notifies subscribers when the own values differ from the last committed ones.
54
+ * `ScopedVariables` calls it in a layout effect, after commit and before paint.
55
+ */
56
+ commit(): void
57
+ }
58
+
59
+ const NO_NAMES: readonly string[] = Object.freeze([])
60
+
61
+ function sameNames(a: readonly string[], b: readonly string[]): boolean {
62
+ return a.length === b.length && a.every((name, i) => name === b[i])
63
+ }
64
+
65
+ /**
66
+ * Memoized scope value shared by `ScopedTheme` and `ScopedVariables`: the scoped theme
67
+ * plus the merged variables. Stored in a single React context so scoped subtrees pay one context lookup.
68
+ */
69
+ export interface NitroWindScopeValue {
70
+ readonly theme?: ThemeName
71
+ readonly colorScheme?: ColorScheme
72
+ readonly variables?: VariableScope
73
+ }
74
+
75
+ export const ScopeContext = createContext<NitroWindScopeValue | null>(null)
76
+
77
+ /** Reads the nearest NitroWind scope, or `null` outside any scope. */
78
+ export function useNitroWindScope(): NitroWindScopeValue | null {
79
+ return useContext(ScopeContext)
80
+ }
81
+
82
+ function sameValues(a: Readonly<CSSVariables>, b: Readonly<CSSVariables>): boolean {
83
+ const aKeys = Object.keys(a)
84
+ if (aKeys.length !== Object.keys(b).length) return false
85
+ for (const key of aKeys) {
86
+ if (!Object.prototype.hasOwnProperty.call(b, key)) return false
87
+ if (!Object.is(a[key as keyof CSSVariables], b[key as keyof CSSVariables])) return false
88
+ }
89
+ return true
90
+ }
91
+
92
+ interface ScopeChannel {
93
+ readonly listeners: Set<() => void>
94
+ storeNames: readonly string[]
95
+ unsubscribeStore: Unsubscribe | undefined
96
+ }
97
+
98
+ /** Creates the variable scope behind one `ScopedVariables`, merged over `parent` (innermost wins). */
99
+ export function createVariableScope(
100
+ parent: VariableScope | undefined,
101
+ initialOwn: Readonly<CSSVariables>,
102
+ ): WritableVariableScope {
103
+ let own = initialOwn
104
+ let committed = initialOwn
105
+ let committedNames = referencedVariableNames(committed)
106
+ const channels = new Map<ThemeName | undefined, ScopeChannel>()
107
+ const subscribersByTheme = new Map<ThemeName, (listener: () => void) => Unsubscribe>()
108
+ let mergedFrom: { outer: Readonly<CSSVariables> | undefined; inner: Readonly<CSSVariables> } | undefined
109
+ let merged: Readonly<CSSVariables>
110
+ let layersFrom: { parent: ScopedVariableLayers | undefined; own: Readonly<CSSVariables> } | undefined
111
+ let layers: ScopedVariableLayers
112
+
113
+ const getLayers = (): ScopedVariableLayers => {
114
+ const parentLayers = parent?.getLayers()
115
+ if (layersFrom === undefined || layersFrom.parent !== parentLayers || layersFrom.own !== own) {
116
+ const inner = mergeScopedVariables(parentLayers?.inner, own)
117
+ layers =
118
+ parentLayers?.outer !== undefined
119
+ ? Object.freeze({ inner, outer: parentLayers.outer })
120
+ : Object.freeze({ inner })
121
+ layersFrom = { parent: parentLayers, own }
122
+ }
123
+ return layers
124
+ }
125
+
126
+ const getVariables = (): Readonly<CSSVariables> => {
127
+ const currentLayers = getLayers()
128
+ const inner = currentLayers.inner!
129
+ const outer = currentLayers.outer
130
+ if (outer === undefined) return inner
131
+ if (mergedFrom === undefined || mergedFrom.outer !== outer || mergedFrom.inner !== inner) {
132
+ merged = mergeScopedVariables(outer, inner)
133
+ mergedFrom = { outer, inner }
134
+ }
135
+ return merged
136
+ }
137
+
138
+ const notifyChannel = (channel: ScopeChannel): void => {
139
+ for (const listener of [...channel.listeners]) listener()
140
+ }
141
+
142
+ const notifyAll = (): void => {
143
+ const toNotify = new Set<() => void>()
144
+ for (const channel of channels.values()) {
145
+ for (const listener of channel.listeners) toNotify.add(listener)
146
+ }
147
+ for (const listener of toNotify) listener()
148
+ }
149
+
150
+ // A scoped `--brand: var(--accent)` changes when `updateCSSVariables` changes `--accent`, but the
151
+ // store only notifies readers of `--accent`. So, while anyone listens in a theme (or the active
152
+ // theme), the scope listens to the store for the names its own values read in that theme and
153
+ // passes the change on. Enclosing scopes do the same for theirs, and a listener here is also
154
+ // subscribed to each of them.
155
+ const syncChannelStoreSubscription = (theme: ThemeName | undefined, channel: ScopeChannel): void => {
156
+ const names = channel.listeners.size > 0 ? committedNames : NO_NAMES
157
+ if (sameNames(names, channel.storeNames)) return
158
+ channel.unsubscribeStore?.()
159
+ channel.unsubscribeStore =
160
+ names.length > 0 ? getNitroWind().store.subscribeVariables(names, () => notifyChannel(channel), theme) : undefined
161
+ channel.storeNames = names
162
+ }
163
+
164
+ const subscribe = (listener: () => void, theme?: ThemeName): Unsubscribe => {
165
+ let channel = channels.get(theme)
166
+ if (channel === undefined) {
167
+ channel = { listeners: new Set(), storeNames: NO_NAMES, unsubscribeStore: undefined }
168
+ channels.set(theme, channel)
169
+ }
170
+ channel.listeners.add(listener)
171
+ const unsubscribeParent = parent?.subscribe(listener, theme)
172
+ syncChannelStoreSubscription(theme, channel)
173
+ return () => {
174
+ channel.listeners.delete(listener)
175
+ unsubscribeParent?.()
176
+ syncChannelStoreSubscription(theme, channel)
177
+ if (channel.listeners.size === 0 && channels.get(theme) === channel) {
178
+ channels.delete(theme)
179
+ }
180
+ }
181
+ }
182
+
183
+ const getSubscriber = (theme?: ThemeName): ((listener: () => void) => Unsubscribe) => {
184
+ if (theme === undefined) return subscribe
185
+ let subscriber = subscribersByTheme.get(theme)
186
+ if (subscriber === undefined) {
187
+ subscriber = (listener: () => void) => subscribe(listener, theme)
188
+ subscribersByTheme.set(theme, subscriber)
189
+ }
190
+ return subscriber
191
+ }
192
+
193
+ const setOwn = (next: Readonly<CSSVariables>): void => {
194
+ if (next !== own && !sameValues(next, own)) own = next
195
+ }
196
+
197
+ const commit = (): void => {
198
+ if (own === committed) return
199
+ const changed = !sameValues(own, committed)
200
+ committed = own
201
+ if (!changed) return
202
+ committedNames = referencedVariableNames(committed)
203
+ for (const [theme, channel] of channels) {
204
+ syncChannelStoreSubscription(theme, channel)
205
+ }
206
+ notifyAll()
207
+ }
208
+
209
+ return { getVariables, getLayers, subscribe, getSubscriber, setOwn, commit }
210
+ }
211
+
212
+ /**
213
+ * Wraps an enclosing `VariableScope` at a `ScopedTheme` boundary so every variable declared
214
+ * outside the `ScopedTheme` moves to the `outer` layer (below the theme's own variables,
215
+ * above shared defaults) while keeping subscriptions wired through to the enclosing scopes.
216
+ */
217
+ export function createThemeBoundaryScope(parent: VariableScope): VariableScope {
218
+ let cachedParentVars: Readonly<CSSVariables> | undefined
219
+ let cachedLayers: ScopedVariableLayers | undefined
220
+
221
+ const getLayers = (): ScopedVariableLayers => {
222
+ const parentVars = parent.getVariables()
223
+ if (cachedLayers === undefined || cachedParentVars !== parentVars) {
224
+ cachedParentVars = parentVars
225
+ cachedLayers = Object.freeze({ outer: parentVars })
226
+ }
227
+ return cachedLayers
228
+ }
229
+
230
+ return {
231
+ getVariables: parent.getVariables,
232
+ getLayers,
233
+ subscribe: parent.subscribe,
234
+ getSubscriber: parent.getSubscriber,
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Validates that `theme` is a registered theme name (not `'system'`) and returns
240
+ * its resolved `{ theme, colorScheme }`.
241
+ */
242
+ export function validateScopedTheme(theme: string): { readonly theme: ThemeName; readonly colorScheme: ColorScheme } {
243
+ if (theme === 'system') {
244
+ throw new Error('[nitrowind] ScopedTheme requires a registered theme name, not "system"')
245
+ }
246
+ const nitroWind = getNitroWind()
247
+ if (!Object.prototype.hasOwnProperty.call(nitroWind.themes, theme)) {
248
+ throw new Error(`[nitrowind] Unregistered theme "${theme}"`)
249
+ }
250
+ return {
251
+ theme: theme as ThemeName,
252
+ colorScheme: nitroWind.themes[theme]!.colorScheme,
253
+ }
254
+ }
255
+
256
+ export interface ScopedThemeProps {
257
+ /** Registered theme name for this subtree (`'system'` is not allowed). */
258
+ readonly theme: ThemeName
259
+ readonly children?: ReactNode
260
+ }
261
+
262
+ /**
263
+ * Renders a subtree in another registered theme without changing the rest of the app
264
+ * or the native color scheme. Inside the scope, `<name>:` matches `theme`, and
265
+ * `dark:` / `light:` match that theme's declared `colorScheme`.
266
+ */
267
+ export function ScopedTheme({ theme, children }: ScopedThemeProps): ReactElement {
268
+ const parent = useContext(ScopeContext)
269
+ const validated = validateScopedTheme(theme)
270
+ const parentVariables = parent?.variables
271
+ const boundary = useMemo(
272
+ () => (parentVariables !== undefined ? createThemeBoundaryScope(parentVariables) : undefined),
273
+ [parentVariables],
274
+ )
275
+ const value = useMemo<NitroWindScopeValue>(() => {
276
+ if (
277
+ parent !== null &&
278
+ parent.theme === validated.theme &&
279
+ parent.colorScheme === validated.colorScheme &&
280
+ parentVariables === undefined
281
+ ) {
282
+ return parent
283
+ }
284
+ return parent !== null
285
+ ? Object.freeze({
286
+ ...parent,
287
+ theme: validated.theme,
288
+ colorScheme: validated.colorScheme,
289
+ ...(boundary !== undefined ? { variables: boundary } : undefined),
290
+ })
291
+ : Object.freeze({ theme: validated.theme, colorScheme: validated.colorScheme })
292
+ }, [parent, parentVariables, boundary, validated.theme, validated.colorScheme])
293
+
294
+ return createElement(ScopeContext.Provider, { value }, children)
295
+ }
296
+
297
+ export interface ScopedVariablesProps {
298
+ /** CSS variables to override for this subtree. Nested scopes merge, and the innermost wins. */
299
+ readonly variables: Readonly<CSSVariables>
300
+ readonly children?: ReactNode
301
+ }
302
+
303
+ /**
304
+ * Overrides CSS variables for a subtree following the CSS cascade ("closest override wins"):
305
+ * nested scopes merge with the innermost winning, a `ScopedVariables` inside a `ScopedTheme`
306
+ * wins over that theme's values, and a `ScopedTheme` inside a `ScopedVariables` wins for
307
+ * variables the theme declares while outer scoped variables still inherit through for the rest.
308
+ * `useTw` and `useCSSVariable` see the scope; `tw()` and `getCSSVariable()` don't. Changing
309
+ * `variables` re-renders only the elements inside that read a variable whose value changed.
310
+ */
311
+ export function ScopedVariables({ variables, children }: ScopedVariablesProps): ReactElement {
312
+ const parent = useContext(ScopeContext)
313
+ const parentVariables = parent?.variables
314
+ // One scope per mount (and per enclosing variable scope): the context value stays stable
315
+ // while `variables` changes, so only subscribers whose signature changed re-render.
316
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `variables` only seeds the scope; later values go through `setOwn`.
317
+ const scope = useMemo(() => createVariableScope(parentVariables, variables), [parentVariables])
318
+
319
+ // Store this render's values before the children render, so a child that renders now
320
+ // (including one that mounts in this commit) reads them the first time. Subscribers that
321
+ // didn't re-render are notified after commit, before paint.
322
+ scope.setOwn(variables)
323
+ // biome-ignore lint/correctness/useExhaustiveDependencies: commit after every render that changed `variables`.
324
+ useLayoutEffect(() => {
325
+ scope.commit()
326
+ }, [scope, variables])
327
+
328
+ const value = useMemo<NitroWindScopeValue>(() => Object.freeze({ ...parent, variables: scope }), [parent, scope])
329
+
330
+ return createElement(ScopeContext.Provider, { value }, children)
331
+ }
package/src/store.ts ADDED
@@ -0,0 +1,288 @@
1
+ import type {
2
+ ColorScheme,
3
+ NitroWindEnvironment,
4
+ ThemeDefinition,
5
+ ThemeName,
6
+ ThemePreference,
7
+ ThemeState,
8
+ Unsubscribe,
9
+ ViewportSize,
10
+ } from './types'
11
+
12
+ export interface NitroWindStore {
13
+ getTheme(): ThemeState
14
+ getColorScheme(): ColorScheme
15
+ setTheme(preference: ThemePreference): void
16
+ getViewportSize(): ViewportSize | undefined
17
+ getReducedMotion(): boolean
18
+ readonly subscribeTheme: (listener: () => void) => Unsubscribe
19
+ readonly subscribeViewport: (listener: () => void) => Unsubscribe
20
+ readonly subscribeReducedMotion: (listener: () => void) => Unsubscribe
21
+ readonly subscribeVariables: (names: readonly string[], listener: () => void, theme?: string) => Unsubscribe
22
+ readonly getVariablesSubscriber: (names: readonly string[], theme?: string) => (listener: () => void) => Unsubscribe
23
+ readonly getSubscribedVariableThemes: () => Iterable<string>
24
+ notifyVariables(names: Iterable<string>, theme?: string): void
25
+ }
26
+
27
+ interface Channel<T> {
28
+ get(): T
29
+ readonly subscribe: (listener: () => void) => Unsubscribe
30
+ }
31
+
32
+ function createChannel<T>(
33
+ read: () => T,
34
+ listen: (onChange: (next: T) => void) => Unsubscribe,
35
+ isEqual: (a: T, b: T) => boolean,
36
+ eagerListenOnRead = false,
37
+ ): Channel<T> {
38
+ const listeners = new Set<() => void>()
39
+ let hasValue = false
40
+ let current: T
41
+ let unsubscribeSource: Unsubscribe | undefined
42
+
43
+ const attachSource = (): void => {
44
+ if (unsubscribeSource !== undefined) return
45
+ current = read()
46
+ hasValue = true
47
+ unsubscribeSource = listen((next) => {
48
+ if (hasValue && isEqual(current, next)) return
49
+ current = next
50
+ hasValue = true
51
+ for (const fn of [...listeners]) fn()
52
+ })
53
+ }
54
+
55
+ const subscribe = (listener: () => void): Unsubscribe => {
56
+ if (listeners.size === 0) attachSource()
57
+ listeners.add(listener)
58
+ return () => {
59
+ listeners.delete(listener)
60
+ if (listeners.size > 0 || eagerListenOnRead) return
61
+ unsubscribeSource?.()
62
+ unsubscribeSource = undefined
63
+ hasValue = false
64
+ }
65
+ }
66
+
67
+ return {
68
+ get: () => {
69
+ if (eagerListenOnRead) attachSource()
70
+ return hasValue ? current : read()
71
+ },
72
+ subscribe,
73
+ }
74
+ }
75
+
76
+ function sameViewport(a: ViewportSize | undefined, b: ViewportSize | undefined): boolean {
77
+ if (a === b) return true
78
+ return a !== undefined && b !== undefined && a.width === b.width && a.height === b.height
79
+ }
80
+
81
+ function sameThemeState(a: ThemeState, b: ThemeState): boolean {
82
+ return a.theme === b.theme && a.colorScheme === b.colorScheme && a.preference === b.preference
83
+ }
84
+
85
+ /** Creates the channel store backed by an injected environment. */
86
+ export function createStore(
87
+ environment: NitroWindEnvironment,
88
+ themes: Readonly<Record<string, ThemeDefinition>>,
89
+ initialTheme: ThemePreference = 'system',
90
+ ): NitroWindStore {
91
+ const themeListeners = new Set<() => void>()
92
+ let preference: ThemePreference = initialTheme
93
+ let currentTheme: ThemeState | undefined
94
+ let unsubscribeColorScheme: Unsubscribe | undefined
95
+ let suppressOsListener = false
96
+
97
+ function makeThemeState(pref: ThemePreference, osScheme?: ColorScheme): ThemeState {
98
+ if (pref === 'system') {
99
+ const scheme = osScheme ?? environment.getColorScheme()
100
+ return Object.freeze({ theme: scheme as ThemeName, colorScheme: scheme, preference: 'system' })
101
+ }
102
+ const def = themes[pref]!
103
+ return Object.freeze({ theme: pref as ThemeName, colorScheme: def.colorScheme, preference: pref })
104
+ }
105
+
106
+ function notifyTheme(): void {
107
+ for (const fn of [...themeListeners]) fn()
108
+ }
109
+
110
+ if (initialTheme !== 'system') {
111
+ currentTheme = makeThemeState(initialTheme)
112
+ environment.setColorScheme(currentTheme.colorScheme)
113
+ }
114
+
115
+ function getTheme(): ThemeState {
116
+ if (preference !== 'system') return currentTheme!
117
+ if (themeListeners.size > 0 && currentTheme !== undefined) return currentTheme
118
+ const scheme = environment.getColorScheme()
119
+ if (currentTheme !== undefined && currentTheme.preference === 'system' && currentTheme.colorScheme === scheme) {
120
+ return currentTheme
121
+ }
122
+ currentTheme = makeThemeState('system', scheme)
123
+ return currentTheme
124
+ }
125
+
126
+ const subscribeTheme = (listener: () => void): Unsubscribe => {
127
+ if (themeListeners.size === 0) {
128
+ if (preference === 'system') {
129
+ const scheme = environment.getColorScheme()
130
+ if (currentTheme === undefined || currentTheme.preference !== 'system' || currentTheme.colorScheme !== scheme) {
131
+ currentTheme = makeThemeState('system', scheme)
132
+ }
133
+ }
134
+ unsubscribeColorScheme = environment.subscribeColorScheme((nextScheme) => {
135
+ if (suppressOsListener || preference !== 'system') return
136
+ const next = makeThemeState('system', nextScheme)
137
+ if (currentTheme !== undefined && sameThemeState(currentTheme, next)) return
138
+ currentTheme = next
139
+ notifyTheme()
140
+ })
141
+ }
142
+ themeListeners.add(listener)
143
+ return () => {
144
+ themeListeners.delete(listener)
145
+ if (themeListeners.size > 0) return
146
+ unsubscribeColorScheme?.()
147
+ unsubscribeColorScheme = undefined
148
+ }
149
+ }
150
+
151
+ function setTheme(nextPreference: ThemePreference): void {
152
+ if (nextPreference !== 'system' && !Object.prototype.hasOwnProperty.call(themes, nextPreference)) {
153
+ throw new Error(`[nitrowind] Unregistered theme "${nextPreference}"`)
154
+ }
155
+ const prev = currentTheme
156
+ preference = nextPreference
157
+ if (nextPreference === 'system') {
158
+ suppressOsListener = true
159
+ try {
160
+ environment.setColorScheme('auto')
161
+ } finally {
162
+ suppressOsListener = false
163
+ }
164
+ const next = makeThemeState('system', environment.getColorScheme())
165
+ const changed = prev === undefined || !sameThemeState(prev, next)
166
+ currentTheme = next
167
+ if (changed) notifyTheme()
168
+ return
169
+ }
170
+ const next = makeThemeState(nextPreference)
171
+ const changed = prev === undefined || !sameThemeState(prev, next)
172
+ currentTheme = next
173
+ suppressOsListener = true
174
+ try {
175
+ environment.setColorScheme(next.colorScheme)
176
+ } finally {
177
+ suppressOsListener = false
178
+ }
179
+ if (changed) notifyTheme()
180
+ }
181
+
182
+ const viewport = createChannel(
183
+ () => environment.getViewportSize(),
184
+ (onChange) => environment.subscribeViewportSize(onChange),
185
+ sameViewport,
186
+ true,
187
+ )
188
+ const reducedMotion = createChannel(
189
+ () => environment.native?.getReducedMotion() ?? false,
190
+ (onChange) => environment.native?.subscribeReducedMotion(onChange) ?? (() => {}),
191
+ Object.is,
192
+ )
193
+
194
+ const activeVariableListeners = new Map<string, Set<() => void>>()
195
+ const scopedVariableListeners = new Map<string, Map<string, Set<() => void>>>()
196
+ const variableSubscribersByRef = new WeakMap<readonly string[], (listener: () => void) => Unsubscribe>()
197
+ const variableSubscribersByKey = new Map<string, (listener: () => void) => Unsubscribe>()
198
+ const MAX_VARIABLE_SUBSCRIBER_KEYS = 256
199
+
200
+ const subscribeVariables = (names: readonly string[], listener: () => void, theme?: string): Unsubscribe => {
201
+ if (names.length === 0) return () => {}
202
+ let listenersMap: Map<string, Set<() => void>>
203
+ if (theme === undefined) {
204
+ listenersMap = activeVariableListeners
205
+ } else {
206
+ let existing = scopedVariableListeners.get(theme)
207
+ if (existing === undefined) {
208
+ existing = new Map()
209
+ scopedVariableListeners.set(theme, existing)
210
+ }
211
+ listenersMap = existing
212
+ }
213
+ for (const name of names) {
214
+ let set = listenersMap.get(name)
215
+ if (set === undefined) {
216
+ set = new Set()
217
+ listenersMap.set(name, set)
218
+ }
219
+ set.add(listener)
220
+ }
221
+ return () => {
222
+ for (const name of names) {
223
+ const set = listenersMap.get(name)
224
+ if (set === undefined) continue
225
+ set.delete(listener)
226
+ if (set.size === 0) listenersMap.delete(name)
227
+ }
228
+ if (theme !== undefined && listenersMap.size === 0 && scopedVariableListeners.get(theme) === listenersMap) {
229
+ scopedVariableListeners.delete(theme)
230
+ }
231
+ }
232
+ }
233
+
234
+ const getVariablesSubscriber = (
235
+ names: readonly string[],
236
+ theme?: string,
237
+ ): ((listener: () => void) => Unsubscribe) => {
238
+ if (theme === undefined) {
239
+ const byRef = variableSubscribersByRef.get(names)
240
+ if (byRef !== undefined) return byRef
241
+ }
242
+ const key = theme === undefined ? names.join('\0') : `${theme}\x01${names.join('\0')}`
243
+ let subscriber = variableSubscribersByKey.get(key)
244
+ if (subscriber === undefined) {
245
+ const snapshotNames = [...names]
246
+ subscriber = (listener: () => void) => subscribeVariables(snapshotNames, listener, theme)
247
+ if (variableSubscribersByKey.size >= MAX_VARIABLE_SUBSCRIBER_KEYS) {
248
+ const oldest = variableSubscribersByKey.keys().next().value
249
+ if (oldest !== undefined) variableSubscribersByKey.delete(oldest)
250
+ }
251
+ variableSubscribersByKey.set(key, subscriber)
252
+ }
253
+ if (theme === undefined) {
254
+ variableSubscribersByRef.set(names, subscriber)
255
+ }
256
+ return subscriber
257
+ }
258
+
259
+ const getSubscribedVariableThemes = (): Iterable<string> => scopedVariableListeners.keys()
260
+
261
+ function notifyVariables(names: Iterable<string>, theme?: string): void {
262
+ const listenersMap = theme === undefined ? activeVariableListeners : scopedVariableListeners.get(theme)
263
+ if (listenersMap === undefined) return
264
+ const toNotify = new Set<() => void>()
265
+ for (const name of names) {
266
+ const set = listenersMap.get(name)
267
+ if (set !== undefined) {
268
+ for (const fn of set) toNotify.add(fn)
269
+ }
270
+ }
271
+ for (const fn of toNotify) fn()
272
+ }
273
+
274
+ return {
275
+ getTheme,
276
+ getColorScheme: () => getTheme().colorScheme,
277
+ setTheme,
278
+ getViewportSize: viewport.get,
279
+ getReducedMotion: reducedMotion.get,
280
+ subscribeTheme,
281
+ subscribeViewport: viewport.subscribe,
282
+ subscribeReducedMotion: reducedMotion.subscribe,
283
+ subscribeVariables,
284
+ getVariablesSubscriber,
285
+ getSubscribedVariableThemes,
286
+ notifyVariables,
287
+ }
288
+ }