@kbach/react-native 1.0.0-beta.8 → 1.0.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 (51) hide show
  1. package/AGENTS.md +495 -0
  2. package/LICENSE +21 -0
  3. package/README.md +209 -249
  4. package/THIRD_PARTY_NOTICES.md +41 -0
  5. package/android/src/main/jniLibs/arm64-v8a/libkbach_core_engine.so +0 -0
  6. package/android/src/main/jniLibs/x86_64/libkbach_core_engine.so +0 -0
  7. package/dist/chunk-7CNURQSH.mjs +112 -0
  8. package/dist/{chunk-OIW7OQWO.mjs → chunk-HYQFT32E.mjs} +2 -2
  9. package/dist/chunk-MUPEQJRT.mjs +623 -0
  10. package/dist/darkModeStore.d.ts +73 -0
  11. package/dist/darkModeStore.js +118 -0
  12. package/dist/dynamicTokens.d.ts +53 -0
  13. package/dist/dynamicTokens.js +75 -0
  14. package/dist/index.d.ts +90 -71
  15. package/dist/index.js +1433 -606
  16. package/dist/index.web.d.ts +91 -1
  17. package/dist/index.web.js +323 -428
  18. package/dist/index.web.mjs +297 -11
  19. package/dist/jsx-dev-runtime.d.ts +2 -2
  20. package/dist/jsx-dev-runtime.js +1540 -589
  21. package/dist/jsx-dev-runtime.web.d.ts +2 -2
  22. package/dist/jsx-dev-runtime.web.js +20 -340
  23. package/dist/jsx-dev-runtime.web.mjs +18 -6
  24. package/dist/jsx-runtime.d.ts +3 -3
  25. package/dist/jsx-runtime.js +1530 -579
  26. package/dist/jsx-runtime.web.d.ts +3 -3
  27. package/dist/jsx-runtime.web.js +17 -340
  28. package/dist/jsx-runtime.web.mjs +2 -3
  29. package/dist/semanticElements-Bk3TB-vt.d.ts +334 -0
  30. package/dist/theme.d.ts +79 -0
  31. package/dist/{chunk-4BXM3QUV.mjs → theme.js} +120 -17
  32. package/llms.txt +38 -0
  33. package/package.json +15 -13
  34. package/src/babel-plugin.js +144 -2
  35. package/dist/ThemeContext-Dc5AC-m0.d.mts +0 -98
  36. package/dist/ThemeContext-Dc5AC-m0.d.ts +0 -98
  37. package/dist/chunk-CGU7UM2F.mjs +0 -66
  38. package/dist/chunk-DLIXI5OW.mjs +0 -53
  39. package/dist/chunk-JR3BLUAV.mjs +0 -1204
  40. package/dist/chunk-JS5KIGAB.mjs +0 -192
  41. package/dist/chunk-KV3ZIXSH.mjs +0 -14
  42. package/dist/chunk-Z664AKW7.mjs +0 -54
  43. package/dist/index.d.mts +0 -84
  44. package/dist/index.mjs +0 -34
  45. package/dist/index.web.d.mts +0 -15
  46. package/dist/jsx-dev-runtime.d.mts +0 -10
  47. package/dist/jsx-dev-runtime.mjs +0 -18
  48. package/dist/jsx-dev-runtime.web.d.mts +0 -10
  49. package/dist/jsx-runtime.d.mts +0 -7
  50. package/dist/jsx-runtime.mjs +0 -15
  51. package/dist/jsx-runtime.web.d.mts +0 -7
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kbach/react-native",
3
- "version": "1.0.0-beta.8",
3
+ "version": "1.0.0",
4
4
  "description": "Kbach's utility-class styling engine for React Native — the same class names as @kbach/react, resolved to a StyleSheet-ready style object via a Kotlin/JNI TurboModule (native), the same WASM engine @kbach/react uses (Expo Web / react-native-web), or a pure-JS fallback engine (Expo Go). Ships its own native Android module — one npm install, no separate native package. Beta. Native is Android-only (no iOS bridge yet); works with the React Native CLI, an Expo dev client, AND Expo Go (a reduced-coverage pure-JS fallback, since Expo Go can't load any custom native module).",
5
5
  "keywords": [
6
6
  "css",
@@ -20,7 +20,7 @@
20
20
  "url": "git+https://github.com/semsakadanupol/kbach.git",
21
21
  "directory": "packages/react-native"
22
22
  },
23
- "homepage": "https://github.com/semsakadanupol/kbach#readme",
23
+ "homepage": "https://kbach.vercel.app",
24
24
  "bugs": {
25
25
  "url": "https://github.com/semsakadanupol/kbach/issues"
26
26
  },
@@ -29,20 +29,21 @@
29
29
  },
30
30
  "files": [
31
31
  "dist",
32
+ "llms.txt",
32
33
  "src/babel-plugin.js",
33
34
  "android/build.gradle",
34
35
  "android/src",
35
36
  "specs",
36
- "react-native.config.js"
37
+ "react-native.config.js",
38
+ "AGENTS.md",
39
+ "THIRD_PARTY_NOTICES.md"
37
40
  ],
38
41
  "source": "./src/index.ts",
39
42
  "main": "./dist/index.js",
40
- "module": "./dist/index.mjs",
41
43
  "types": "./dist/index.d.ts",
42
44
  "exports": {
43
45
  ".": {
44
46
  "types": "./dist/index.d.ts",
45
- "source": "./src/index.ts",
46
47
  "browser": {
47
48
  "import": "./dist/index.web.mjs",
48
49
  "require": "./dist/index.web.js"
@@ -51,12 +52,11 @@
51
52
  "import": "./dist/index.web.mjs",
52
53
  "require": "./dist/index.web.js"
53
54
  },
54
- "import": "./dist/index.mjs",
55
+ "react-native": "./dist/index.js",
55
56
  "require": "./dist/index.js"
56
57
  },
57
58
  "./jsx-runtime": {
58
59
  "types": "./dist/jsx-runtime.d.ts",
59
- "source": "./src/jsx-runtime.tsx",
60
60
  "browser": {
61
61
  "import": "./dist/jsx-runtime.web.mjs",
62
62
  "require": "./dist/jsx-runtime.web.js"
@@ -65,12 +65,11 @@
65
65
  "import": "./dist/jsx-runtime.web.mjs",
66
66
  "require": "./dist/jsx-runtime.web.js"
67
67
  },
68
- "import": "./dist/jsx-runtime.mjs",
68
+ "react-native": "./dist/jsx-runtime.js",
69
69
  "require": "./dist/jsx-runtime.js"
70
70
  },
71
71
  "./jsx-dev-runtime": {
72
72
  "types": "./dist/jsx-dev-runtime.d.ts",
73
- "source": "./src/jsx-dev-runtime.tsx",
74
73
  "browser": {
75
74
  "import": "./dist/jsx-dev-runtime.web.mjs",
76
75
  "require": "./dist/jsx-dev-runtime.web.js"
@@ -79,15 +78,17 @@
79
78
  "import": "./dist/jsx-dev-runtime.web.mjs",
80
79
  "require": "./dist/jsx-dev-runtime.web.js"
81
80
  },
82
- "import": "./dist/jsx-dev-runtime.mjs",
81
+ "react-native": "./dist/jsx-dev-runtime.js",
83
82
  "require": "./dist/jsx-dev-runtime.js"
84
83
  },
85
- "./babel-plugin": "./src/babel-plugin.js"
84
+ "./babel-plugin": "./src/babel-plugin.js",
85
+ "./package.json": "./package.json"
86
86
  },
87
87
  "scripts": {
88
- "build": "tsup",
89
- "dev": "tsup --watch",
88
+ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsup && node scripts/append-classname-types.mjs",
89
+ "dev": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsup --watch",
90
90
  "test": "vitest run --passWithNoTests",
91
+ "test:coverage": "vitest run --coverage --passWithNoTests",
91
92
  "lint": "tsc --noEmit",
92
93
  "generate:colors": "node ../core-engine/scripts/generate-palette.mjs src/generatedPalette.ts",
93
94
  "generate:wasm-base64": "node ../core-engine/scripts/generate-wasm-base64.mjs src/wasmBinary.generated.ts",
@@ -96,6 +97,7 @@
96
97
  "devDependencies": {
97
98
  "@types/react": "^19.2.0",
98
99
  "@types/react-test-renderer": "^19.1.0",
100
+ "@vitest/coverage-v8": "^1.6.1",
99
101
  "jsdom": "^30.0.1",
100
102
  "react-native": "^0.87.0",
101
103
  "react-test-renderer": "^19.2.0",
@@ -1,5 +1,9 @@
1
1
  'use strict';
2
2
 
3
+ const path = require('path');
4
+ const fs = require('fs');
5
+ const template = require('@babel/template').default;
6
+
3
7
  /**
4
8
  * Injects a per-file `@jsxImportSource @kbach/react-native` pragma comment
5
9
  * so Metro's JSX transform routes className resolution through
@@ -19,21 +23,159 @@
19
23
  * Deliberately NOT porting old-kbach's build-time class-resolution half
20
24
  * (the __kbachStyles fast path) — resolution happens at the (already
21
25
  * synchronous) native-bridge call inside the jsx-runtime instead (see
22
- * nativeBridge.ts), so this plugin's only job is the pragma injection.
26
+ * nativeBridge.ts), so this plugin's only job is the pragma injection —
27
+ * PLUS one more, added later: auto-applying `kbach.config.js` if one
28
+ * exists (see `buildConfigStatement`'s own doc comment), so a project never
29
+ * needs its own explicit `applyKbachConfig(kbachConfig)` call at all. That
30
+ * addition deliberately still stops short of old-kbach's own version of
31
+ * this (an mtime-polling live-reload of the config, re-checked on every
32
+ * file) — a Babel-plugin-level change needs a dev-server restart to take
33
+ * effect either way, so a one-time check per (root, process) pair is
34
+ * enough, and much simpler to reason about.
35
+ */
36
+
37
+ // Keyed by the root directory checked — undefined = not checked yet for
38
+ // that root, null = checked, no kbach.config.js found there. A Babel/Metro
39
+ // worker process transforms many files over its lifetime — this makes the
40
+ // existsSync check happen ONCE per root, not on every single file `pre()`
41
+ // runs for. Caches only the resolved PATH (or null) — never the built AST
42
+ // statement itself; see `buildConfigStatement`'s own doc comment for why
43
+ // that distinction is load-bearing, not a style preference.
44
+ const _configPathCache = new Map();
45
+
46
+ function resolveConfigPath(root) {
47
+ if (_configPathCache.has(root)) return _configPathCache.get(root);
48
+ const configPath = path.join(root, 'kbach.config.js');
49
+ const resolved = fs.existsSync(configPath) ? configPath : null;
50
+ _configPathCache.set(root, resolved);
51
+ return resolved;
52
+ }
53
+
54
+ // Windows' filesystem is case-insensitive but case-preserving, and Metro's
55
+ // own `file.opts.filename` isn't guaranteed to share the exact casing/
56
+ // separator normalization `path.join` produces — comparing case-sensitively
57
+ // risked a false NEGATIVE (kbach.config.js not recognized as itself,
58
+ // re-introducing the self-require bug `buildConfigStatement`'s doc comment
59
+ // describes) far more than a false positive risks colliding two genuinely
60
+ // different files, which would require two paths differing ONLY by case in
61
+ // the same project — effectively never happens in practice.
62
+ function samePath(a, b) {
63
+ return !!a && !!b && path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase();
64
+ }
65
+
66
+ /**
67
+ * Builds a FRESH (uncompiled) AST statement that applies `kbach.config.js`
68
+ * — a NEW node on every single call, deliberately never cached or reused
69
+ * across files. `root` defaults to `process.cwd()` (how `metro start`/
70
+ * `expo start` are conventionally invoked) at the plugin's own call site
71
+ * below; pass `{ configRoot: '...' }` as this plugin's Babel options if
72
+ * your `kbach.config.js` lives somewhere else (a monorepo where Metro's
73
+ * actual working directory isn't the app's own root, for instance).
74
+ *
75
+ * `null` if no such file exists at `root` (checked via the cached
76
+ * `resolveConfigPath` above — `fs.existsSync` itself is cheap enough to
77
+ * memoize per root without any of the risk rebuilding the AST fresh here
78
+ * guards against).
79
+ *
80
+ * An EARLIER version of this function built the statement once per root
81
+ * and cached/reused that SAME AST node object across every file's `pre()`
82
+ * call. That's unsafe with Babel: a node spliced into one file's AST gets
83
+ * mutated in place as THAT file's own transform pipeline runs (location
84
+ * info, scope bindings, hoisting markers, ...) — sharing one mutable node
85
+ * instance across many independently-processed file ASTs corrupts it after
86
+ * the first file. Confirmed as the actual cause of a real bundling failure
87
+ * (not a hypothetical): Metro's own dependency collector needs a require()
88
+ * call's location info to validate/instrument it, and once the shared
89
+ * node's location got corrupted by an earlier file's pass, Metro rejected
90
+ * a LATER file's copy with "Invalid call at line <unknown>". Rebuilding
91
+ * fresh per call fixes this at negligible cost — `@babel/template`'s own
92
+ * parse is cheap, and this runs once per file Metro transforms regardless.
93
+ *
94
+ * The injected statement is a plain `require(...).applyKbachConfig(require(...))`
95
+ * — no try/catch around it. `kbach.config.js`'s own path is only ever
96
+ * baked in here after `existsSync` already confirmed it exists, so the
97
+ * only way this could still throw is a genuine bug in that file (a syntax
98
+ * error, a bad nested require) — letting that surface as a real, visible
99
+ * Metro bundling error is far better than silently swallowing it: a
100
+ * developer's real customization would otherwise go missing with zero
101
+ * indication why, exactly the kind of headache a good default should avoid.
102
+ *
103
+ * `@babel/template` builds this from a plain string with the absolute path
104
+ * JSON-escaped directly into it (correct on Windows too, backslashes and
105
+ * all) — simpler than building the equivalent `@babel/types` node graph by
106
+ * hand for one straightforward statement.
23
107
  */
24
- module.exports = function kbachReactNativeBabelPlugin() {
108
+ function buildConfigStatement(root) {
109
+ const configPath = resolveConfigPath(root);
110
+ if (configPath === null) return null;
111
+
112
+ const buildStatement = template(
113
+ `require('@kbach/react-native').applyKbachConfig(require(${JSON.stringify(configPath)}));`,
114
+ );
115
+ return buildStatement();
116
+ }
117
+
118
+ module.exports = function kbachReactNativeBabelPlugin(_babel, options) {
119
+ const configRoot = (options && options.configRoot) || process.cwd();
120
+
25
121
  return {
26
122
  name: 'kbach-react-native',
27
123
  pre(file) {
28
124
  const filename = file.opts && file.opts.filename;
29
125
  if (filename && filename.indexOf('node_modules') !== -1) return;
30
126
 
127
+ // Metro/Expo's own internal polyfills (the Node.js-external-require
128
+ // shim, the assets-registry shim, node:/weak-ref virtualizations, ...)
129
+ // are synthetic "virtual modules" with no real file on disk. Expo's
130
+ // own Metro config marks every one of these with an embedded NUL
131
+ // control character in its module ID (Rollup's/Metro's own
132
+ // convention for "this isn't a real file"). These never sit inside
133
+ // node_modules, so the check above doesn't catch them — and Metro
134
+ // places them directly in the bundle PRELUDE, entirely outside any
135
+ // wrapped module, where `require` isn't defined as a real function
136
+ // at all. Confirmed as a real, reproducible runtime crash (not a
137
+ // hypothetical): injecting this plugin's applyKbachConfig() require()
138
+ // call into that exact polyfill produced Expo's own "[runtime not
139
+ // ready]: ReferenceError: Property 'require' doesn't exist" at app
140
+ // startup, verified by exporting a real dev bundle and finding the
141
+ // offending, un-instrumented require() call sitting inside
142
+ // withMetroMultiPlatform.js's own external-require polyfill — a file
143
+ // this plugin was never meant to touch at all.
144
+ //
145
+ // The control character is NOT at the start of `filename`, so
146
+ // `startsWith`/`charCodeAt(0)` (what an earlier version of this
147
+ // check used) never matches — confirmed by actually logging Babel's
148
+ // real `filename` for this file, not assumed: Metro joins the
149
+ // project root onto the raw virtual module ID first, so the control
150
+ // character ends up in the MIDDLE of the full string, right after
151
+ // the trailing path separator, not at index 0. A search anywhere in
152
+ // the string (rather than just its start) is what actually catches
153
+ // it — see this file's own test suite for the exact filename shape
154
+ // this was verified against.
155
+ if (filename && filename.indexOf(String.fromCharCode(0)) !== -1) return;
156
+
31
157
  const comments = file.ast.comments || (file.ast.comments = []);
32
158
  const alreadySet = comments.some((c) => /@jsxImportSource|@jsxRuntime/.test(c.value));
33
159
  if (!alreadySet) {
34
160
  comments.unshift({ type: 'CommentLine', value: ' @jsxImportSource @kbach/react-native' });
35
161
  }
162
+
163
+ // Never inject the auto-apply statement into kbach.config.js itself —
164
+ // it would require() its own absolute path, a real self-reference
165
+ // cycle in Metro's dependency graph for a statement that makes no
166
+ // sense there anyway (a config file applying itself to itself).
167
+ if (samePath(filename, resolveConfigPath(configRoot))) return;
168
+
169
+ const configStatement = buildConfigStatement(configRoot);
170
+ if (configStatement) {
171
+ file.ast.program.body.unshift(configStatement);
172
+ }
36
173
  },
37
174
  visitor: {},
38
175
  };
39
176
  };
177
+
178
+ /** Exported for tests only — clears the per-root config-path cache between test cases. */
179
+ module.exports._resetForTests = function resetForTests() {
180
+ _configPathCache.clear();
181
+ };
@@ -1,98 +0,0 @@
1
- import * as react from 'react';
2
- import { ReactNode } from 'react';
3
-
4
- interface ThemeConfig {
5
- /** Plain hex only, this pass — e.g. "blue-6" -> "#2563eb" */
6
- colors: Record<string, string>;
7
- spacing: Record<string, number>;
8
- screens: Record<string, number>;
9
- darkMode: 'attribute' | 'class' | 'media';
10
- }
11
- declare const defaultTheme: ThemeConfig;
12
- declare function setTheme(theme: ThemeConfig): void;
13
- declare function getTheme(): ThemeConfig;
14
-
15
- /**
16
- * Native port of @kbach/react's darkModeStore.ts — same architecture (a
17
- * single module-level store is the real source of truth;
18
- * ThemeProvider/useTheme are a thin, OPTIONAL wrapper around it; every
19
- * function here works standalone with no provider mounted anywhere), with
20
- * two real platform differences from the web version:
21
- *
22
- * 1. No persistence. There's no React-Native-builtin equivalent of
23
- * localStorage — adding one would mean forcing a real native dependency
24
- * (e.g. @react-native-async-storage/async-storage) on every consumer,
25
- * even ones that don't want it. The mode always starts at 'system' on a
26
- * fresh app launch. If you want persistence, read your own storage at
27
- * startup (before your first render) and call setGlobalThemeMode() with
28
- * the result — same "seed once, no built-in write-back" shape as
29
- * seedDefaultMode() below, just driven by your own storage instead of
30
- * one this package picks for you.
31
- * 2. No DOM to "apply" the resolved mode to. On web, applyToDom() flips a
32
- * class/attribute the generated CSS's `dark:` selectors match against.
33
- * On native there's no CSS at all — nativeBridge.ts's resolveStyle()
34
- * reads getGlobalDarkMode() directly on every call instead of querying
35
- * Appearance.getColorScheme() itself, which is what actually makes an
36
- * explicit override affect rendering (previously that function always
37
- * read the raw OS setting, so it had no way to reflect a user choice —
38
- * see nativeBridge.ts's own comment on this for why that's the one
39
- * genuinely fixed bug this change introduces, not just a new feature).
40
- */
41
- type ThemeMode = 'light' | 'dark' | 'system';
42
- declare function getGlobalDarkMode(): boolean;
43
- declare function getGlobalThemeMode(): ThemeMode;
44
- /** Explicit user choice — takes priority over any later `<ThemeProvider defaultMode>` seed (see `seedDefaultMode` below). Not persisted; see this module's own doc comment. */
45
- declare function setGlobalThemeMode(nextMode: ThemeMode): void;
46
- declare function toggleGlobalDarkMode(): void;
47
- declare function subscribeGlobalDarkMode(listener: () => void): () => void;
48
-
49
- /**
50
- * Reactive read of the global dark-mode store — works with or without a
51
- * `<ThemeProvider>` mounted anywhere in the tree, since it subscribes to
52
- * `darkModeStore.ts` directly. No server-snapshot argument (unlike
53
- * @kbach/react's web version) — React Native has no SSR concept at all,
54
- * so there's no third argument for `useSyncExternalStore` to need.
55
- */
56
- declare function useGlobalDarkMode(): boolean;
57
-
58
- interface ThemeProviderProps {
59
- children: ReactNode;
60
- /**
61
- * Applied once, on this provider's first mount, but ONLY if nothing has
62
- * made an explicit mode choice yet (see
63
- * `darkModeStore.ts::seedDefaultMode`) — an explicit prior choice always
64
- * wins over a component's own default. Unlike @kbach/react's web
65
- * version, there's no persisted value to check here — see
66
- * darkModeStore.ts's own doc comment on why this package doesn't persist
67
- * the mode across app launches.
68
- */
69
- defaultMode?: ThemeMode;
70
- }
71
- /**
72
- * Native port of @kbach/react's `ThemeProvider` — a thin, OPTIONAL React
73
- * Context wrapper around `darkModeStore.ts`'s single global store, not the
74
- * source of truth itself. Because the store is global, MULTIPLE mounted
75
- * providers share the exact same `mode`/`isDark` state rather than each
76
- * getting their own scoped value — mounting more than one is very likely a
77
- * mistake (each fighting over the same state via a different
78
- * `defaultMode`), so this warns once in dev, matching the web version's
79
- * identical guard.
80
- */
81
- declare function ThemeProvider({ children, defaultMode }: ThemeProviderProps): react.JSX.Element;
82
-
83
- interface ThemeContextValue {
84
- mode: ThemeMode;
85
- isDark: boolean;
86
- setMode: (mode: ThemeMode) => void;
87
- toggle: () => void;
88
- }
89
- /**
90
- * Requires a `<ThemeProvider>` ancestor — throws otherwise, since a
91
- * component that destructures `{ mode, setMode }` genuinely needs Context
92
- * (unlike a component that just wants the dark/light boolean, which should
93
- * reach for `useGlobalDarkMode()` instead and never needs a provider at
94
- * all).
95
- */
96
- declare function useTheme(): ThemeContextValue;
97
-
98
- export { type ThemeConfig as T, type ThemeContextValue as a, type ThemeMode as b, ThemeProvider as c, type ThemeProviderProps as d, defaultTheme as e, getGlobalThemeMode as f, getGlobalDarkMode as g, getTheme as h, setTheme as i, subscribeGlobalDarkMode as j, useTheme as k, setGlobalThemeMode as s, toggleGlobalDarkMode as t, useGlobalDarkMode as u };
@@ -1,98 +0,0 @@
1
- import * as react from 'react';
2
- import { ReactNode } from 'react';
3
-
4
- interface ThemeConfig {
5
- /** Plain hex only, this pass — e.g. "blue-6" -> "#2563eb" */
6
- colors: Record<string, string>;
7
- spacing: Record<string, number>;
8
- screens: Record<string, number>;
9
- darkMode: 'attribute' | 'class' | 'media';
10
- }
11
- declare const defaultTheme: ThemeConfig;
12
- declare function setTheme(theme: ThemeConfig): void;
13
- declare function getTheme(): ThemeConfig;
14
-
15
- /**
16
- * Native port of @kbach/react's darkModeStore.ts — same architecture (a
17
- * single module-level store is the real source of truth;
18
- * ThemeProvider/useTheme are a thin, OPTIONAL wrapper around it; every
19
- * function here works standalone with no provider mounted anywhere), with
20
- * two real platform differences from the web version:
21
- *
22
- * 1. No persistence. There's no React-Native-builtin equivalent of
23
- * localStorage — adding one would mean forcing a real native dependency
24
- * (e.g. @react-native-async-storage/async-storage) on every consumer,
25
- * even ones that don't want it. The mode always starts at 'system' on a
26
- * fresh app launch. If you want persistence, read your own storage at
27
- * startup (before your first render) and call setGlobalThemeMode() with
28
- * the result — same "seed once, no built-in write-back" shape as
29
- * seedDefaultMode() below, just driven by your own storage instead of
30
- * one this package picks for you.
31
- * 2. No DOM to "apply" the resolved mode to. On web, applyToDom() flips a
32
- * class/attribute the generated CSS's `dark:` selectors match against.
33
- * On native there's no CSS at all — nativeBridge.ts's resolveStyle()
34
- * reads getGlobalDarkMode() directly on every call instead of querying
35
- * Appearance.getColorScheme() itself, which is what actually makes an
36
- * explicit override affect rendering (previously that function always
37
- * read the raw OS setting, so it had no way to reflect a user choice —
38
- * see nativeBridge.ts's own comment on this for why that's the one
39
- * genuinely fixed bug this change introduces, not just a new feature).
40
- */
41
- type ThemeMode = 'light' | 'dark' | 'system';
42
- declare function getGlobalDarkMode(): boolean;
43
- declare function getGlobalThemeMode(): ThemeMode;
44
- /** Explicit user choice — takes priority over any later `<ThemeProvider defaultMode>` seed (see `seedDefaultMode` below). Not persisted; see this module's own doc comment. */
45
- declare function setGlobalThemeMode(nextMode: ThemeMode): void;
46
- declare function toggleGlobalDarkMode(): void;
47
- declare function subscribeGlobalDarkMode(listener: () => void): () => void;
48
-
49
- /**
50
- * Reactive read of the global dark-mode store — works with or without a
51
- * `<ThemeProvider>` mounted anywhere in the tree, since it subscribes to
52
- * `darkModeStore.ts` directly. No server-snapshot argument (unlike
53
- * @kbach/react's web version) — React Native has no SSR concept at all,
54
- * so there's no third argument for `useSyncExternalStore` to need.
55
- */
56
- declare function useGlobalDarkMode(): boolean;
57
-
58
- interface ThemeProviderProps {
59
- children: ReactNode;
60
- /**
61
- * Applied once, on this provider's first mount, but ONLY if nothing has
62
- * made an explicit mode choice yet (see
63
- * `darkModeStore.ts::seedDefaultMode`) — an explicit prior choice always
64
- * wins over a component's own default. Unlike @kbach/react's web
65
- * version, there's no persisted value to check here — see
66
- * darkModeStore.ts's own doc comment on why this package doesn't persist
67
- * the mode across app launches.
68
- */
69
- defaultMode?: ThemeMode;
70
- }
71
- /**
72
- * Native port of @kbach/react's `ThemeProvider` — a thin, OPTIONAL React
73
- * Context wrapper around `darkModeStore.ts`'s single global store, not the
74
- * source of truth itself. Because the store is global, MULTIPLE mounted
75
- * providers share the exact same `mode`/`isDark` state rather than each
76
- * getting their own scoped value — mounting more than one is very likely a
77
- * mistake (each fighting over the same state via a different
78
- * `defaultMode`), so this warns once in dev, matching the web version's
79
- * identical guard.
80
- */
81
- declare function ThemeProvider({ children, defaultMode }: ThemeProviderProps): react.JSX.Element;
82
-
83
- interface ThemeContextValue {
84
- mode: ThemeMode;
85
- isDark: boolean;
86
- setMode: (mode: ThemeMode) => void;
87
- toggle: () => void;
88
- }
89
- /**
90
- * Requires a `<ThemeProvider>` ancestor — throws otherwise, since a
91
- * component that destructures `{ mode, setMode }` genuinely needs Context
92
- * (unlike a component that just wants the dark/light boolean, which should
93
- * reach for `useGlobalDarkMode()` instead and never needs a provider at
94
- * all).
95
- */
96
- declare function useTheme(): ThemeContextValue;
97
-
98
- export { type ThemeConfig as T, type ThemeContextValue as a, type ThemeMode as b, ThemeProvider as c, type ThemeProviderProps as d, defaultTheme as e, getGlobalThemeMode as f, getGlobalDarkMode as g, getTheme as h, setTheme as i, subscribeGlobalDarkMode as j, useTheme as k, setGlobalThemeMode as s, toggleGlobalDarkMode as t, useGlobalDarkMode as u };
@@ -1,66 +0,0 @@
1
- import {
2
- getGlobalDarkMode,
3
- getGlobalThemeMode,
4
- seedDefaultMode,
5
- setGlobalThemeMode,
6
- subscribeGlobalDarkMode,
7
- toggleGlobalDarkMode
8
- } from "./chunk-Z664AKW7.mjs";
9
-
10
- // src/useGlobalDarkMode.ts
11
- import { useSyncExternalStore } from "react";
12
- function useGlobalDarkMode() {
13
- return useSyncExternalStore(subscribeGlobalDarkMode, getGlobalDarkMode);
14
- }
15
-
16
- // src/ThemeContext.tsx
17
- import { createContext, useContext } from "react";
18
- var ThemeContext = createContext(null);
19
- function useTheme() {
20
- const ctx = useContext(ThemeContext);
21
- if (!ctx) {
22
- throw new Error(
23
- 'useTheme() must be called within a <ThemeProvider>. For dark-mode state without a provider, use useGlobalDarkMode() (read) or toggleGlobalDarkMode()/setGlobalThemeMode() (write) from "@kbach/react-native" instead.'
24
- );
25
- }
26
- return ctx;
27
- }
28
-
29
- // src/ThemeProvider.tsx
30
- import { useEffect, useMemo, useRef, useSyncExternalStore as useSyncExternalStore2 } from "react";
31
- import { jsx } from "react/jsx-runtime";
32
- var mountedProviderCount = 0;
33
- var warnedMultipleProviders = false;
34
- function ThemeProvider({ children, defaultMode = "system" }) {
35
- useEffect(() => {
36
- mountedProviderCount++;
37
- if (mountedProviderCount > 1 && !warnedMultipleProviders) {
38
- warnedMultipleProviders = true;
39
- console.warn(
40
- "[kbach] Multiple <ThemeProvider> instances are mounted at once. Dark-mode state is one global store (the same one useGlobalDarkMode()/toggleGlobalDarkMode() read and write), not scoped per-provider, so they will fight over the same state instead of each getting their own."
41
- );
42
- }
43
- return () => {
44
- mountedProviderCount--;
45
- };
46
- }, []);
47
- const seeded = useRef(false);
48
- useEffect(() => {
49
- if (seeded.current) return;
50
- seeded.current = true;
51
- seedDefaultMode(defaultMode);
52
- }, []);
53
- const isDark = useSyncExternalStore2(subscribeGlobalDarkMode, getGlobalDarkMode);
54
- const mode = useSyncExternalStore2(subscribeGlobalDarkMode, getGlobalThemeMode);
55
- const value = useMemo(
56
- () => ({ mode, isDark, setMode: setGlobalThemeMode, toggle: toggleGlobalDarkMode }),
57
- [mode, isDark]
58
- );
59
- return /* @__PURE__ */ jsx(ThemeContext.Provider, { value, children });
60
- }
61
-
62
- export {
63
- useGlobalDarkMode,
64
- useTheme,
65
- ThemeProvider
66
- };
@@ -1,53 +0,0 @@
1
- // src/jsxRuntimeCore.ts
2
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { Fragment } from "react";
4
- import { Pressable } from "react-native";
5
- function makeElement(isStaticChildren, type, props, key) {
6
- return (isStaticChildren ? _jsxs : _jsx)(type, props, key);
7
- }
8
- function resolvedStyleFor(resolveStyle, classStrRaw, userStyle, pressed) {
9
- const resolved = resolveStyle(classStrRaw, pressed);
10
- if (userStyle === void 0) {
11
- return resolved;
12
- }
13
- if (typeof userStyle === "function") {
14
- return [resolved, userStyle({ pressed })];
15
- }
16
- return [resolved, userStyle];
17
- }
18
- function processElement(resolveStyle, type, rawProps, key, isStaticChildren) {
19
- if (type === null || typeof type === "symbol" || !rawProps) {
20
- return makeElement(isStaticChildren, type, rawProps ?? {}, key);
21
- }
22
- const { className: classStrRaw, style: userStyle, ...rest } = rawProps;
23
- if (typeof classStrRaw !== "string") {
24
- return makeElement(isStaticChildren, type, rawProps, key);
25
- }
26
- const finalStyle = type === Pressable ? (state) => resolvedStyleFor(resolveStyle, classStrRaw, userStyle, state.pressed) : resolvedStyleFor(resolveStyle, classStrRaw, userStyle, false);
27
- return makeElement(isStaticChildren, type, { ...rest, style: finalStyle }, key);
28
- }
29
- function createJsxFunctions(resolveStyle) {
30
- function jsx(type, props, key) {
31
- return processElement(resolveStyle, type, props, key, false);
32
- }
33
- function jsxs(type, props, key) {
34
- return processElement(resolveStyle, type, props, key, true);
35
- }
36
- return { jsx, jsxs };
37
- }
38
- function createJsxDEV(jsx, jsxs) {
39
- return function jsxDEV(type, props, key, isStaticChildren, source, self) {
40
- const element = (isStaticChildren ? jsxs : jsx)(type, props, key);
41
- if (source && element && typeof element === "object" && Object.isExtensible(element)) {
42
- element._source = source;
43
- element._self = self;
44
- }
45
- return element;
46
- };
47
- }
48
-
49
- export {
50
- Fragment,
51
- createJsxFunctions,
52
- createJsxDEV
53
- };