cookie-prefs 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -87,6 +87,15 @@ export function SidebarToggle() {
87
87
  }
88
88
  ```
89
89
 
90
+ Several at once with `usePrefs`, which takes a partial patch:
91
+
92
+ ```tsx
93
+ import { usePrefs } from 'cookie-prefs/react'
94
+
95
+ const [{ theme, sidebar }, set] = usePrefs(prefs)
96
+ set({ sidebar: false, theme: 'dark' })
97
+ ```
98
+
90
99
  Read it in a Server Component (this makes the route dynamic):
91
100
 
92
101
  ```tsx
@@ -114,12 +123,24 @@ export async function setLocale(locale: string) {
114
123
 
115
124
  ## The entries
116
125
 
117
- | Import | What it is | Guide |
118
- | -------------------- | ------------------------------------------------------------------------------------------- | ----- |
119
- | `cookie-prefs` | Core, no DOM required: `definePrefs`, `pref.*`, `readPrefs`, `snapshotPrefs`, `prefsScript` | [Core](docs/core.md) |
120
- | `cookie-prefs/react` | `usePref`, and `PrefsProvider` for SSR outside Next.js | [Core](docs/core.md#cookie-prefsreact-outside-nextjs) |
121
- | `cookie-prefs/next` | Server-only: `PrefsProvider`, `getPrefs` (App Router) | [Next.js](docs/nextjs.md) |
122
- | `cookie-prefs/theme` | next-themes compatible `ThemeProvider` and `useTheme` | [Theme](docs/theme.md) |
126
+ | Import | What it is | Guide |
127
+ | --------------------- | ------------------------------------------------------------------------------ | ----- |
128
+ | `cookie-prefs` | Core, no DOM required: `definePrefs`, `pref.*`, `readPrefs`, `snapshotPrefs` | [Core](docs/core.md) |
129
+ | `cookie-prefs/react` | `usePref`, `usePrefs`, and `PrefsProvider` for SSR outside Next.js | [Core](docs/core.md#cookie-prefsreact-outside-nextjs) |
130
+ | `cookie-prefs/script` | `prefsScript`, the pre-paint script for `PrefsProvider` outside Next.js | [Core](docs/core.md#cookie-prefsreact-outside-nextjs) |
131
+ | `cookie-prefs/next` | Server-only: `PrefsProvider`, `getPrefs` (App Router) | [Next.js](docs/nextjs.md) |
132
+ | `cookie-prefs/theme` | next-themes compatible `ThemeProvider` and `useTheme` | [Theme](docs/theme.md) |
133
+ | `cookie-prefs/theme/next` | Server-only: `getTheme`, the stored theme in the App Router (opt-in) | [Theme](docs/theme.md#reading-the-theme-on-the-server) |
134
+ | `cookie-prefs/theme/server` | `readTheme`, the stored theme from request cookies on any server | [Theme](docs/theme.md#reading-the-theme-on-the-server) |
135
+ | `cookie-prefs/theme/color` | `ThemeColor`, keeps `<meta name="theme-color">` in sync with the theme (opt-in) | [Theme](docs/theme.md#browser-ui-colour-theme-color) |
136
+
137
+ ## Renaming an enum value
138
+
139
+ Users keep their choice when an enum value is renamed: a cookie holding an old name reads as its new value on the server, on the client and in the pre-paint script, and the next `set()` writes the new name.
140
+
141
+ ```ts
142
+ density: pref.enum(['compact', 'comfortable']).default('comfortable').migrate({ cozy: 'comfortable' }),
143
+ ```
123
144
 
124
145
  ## Next.js modes
125
146
 
@@ -138,6 +159,10 @@ export async function setLocale(locale: string) {
138
159
 
139
160
  Props and hook fields keep their next-themes names and defaults; the choice lives in a cookie, and existing `localStorage` themes are moved once. Setup and the full list of differences are in the [Theme guide](docs/theme.md).
140
161
 
162
+ To render from the stored theme on the server (`<html className>`), opt in with `await getTheme({ themes })` from `cookie-prefs/theme/next`, or `readTheme(cookieHeader, { themes })` from `cookie-prefs/theme/server` outside Next.js. It makes the route dynamic, returns `'system'` unresolved, and the inline script stays in charge before hydration; see [Reading the theme on the server](docs/theme.md#reading-the-theme-on-the-server).
163
+
164
+ To colour the browser UI per theme (`<meta name="theme-color">`, next-themes #78), render `<ThemeColor colors={{ light: '#ffffff', dark: '#0a0a0a' }} />` from `cookie-prefs/theme/color` inside `ThemeProvider`. It is right before hydration, follows `setTheme`, the OS scheme, `forcedTheme` and other tabs, and takes precedence over `viewport.themeColor`; see [Browser UI colour](docs/theme.md#browser-ui-colour-theme-color).
165
+
141
166
  ## Security and platform notes
142
167
 
143
168
  Prefs are readable by every script on the page: never store secrets. The pre-paint script needs a CSP nonce under strict policies, and Safari caps script-written cookies at 7 days (cookie-prefs refreshes the long-lived ones once per page load). Details, Trusted Types, iframes and non-goals are in [Security and platform notes](docs/security.md).
@@ -152,3 +177,5 @@ Prefs are readable by every script on the page: never store secrets. The pre-pai
152
177
  ## More
153
178
 
154
179
  Guides: [Core and React](docs/core.md), [Next.js](docs/nextjs.md), [Reflection](docs/reflection.md), [Theme](docs/theme.md), [Security and non-goals](docs/security.md). Design decisions, verified facts and limitations: [docs/design.md](docs/design.md). Contributing: [CONTRIBUTING.md](CONTRIBUTING.md). License: [MIT](LICENSE).
180
+
181
+ Roadmap to 1.0: [docs/roadmap.md](docs/roadmap.md).
package/dist/index.cjs CHANGED
@@ -20,6 +20,7 @@ var builder = (def) => ({
20
20
  ...def,
21
21
  default: (d) => builder({ ...def, d }),
22
22
  options: (o) => builder({ ...def, o: merge(def.o, o) }),
23
+ migrate: (a) => builder({ ...def, a: merge(def.a, a) }),
23
24
  reflect: (r, m) => builder({ ...def, r: [].concat(r), m })
24
25
  });
25
26
 
@@ -40,11 +41,6 @@ var apply = (targets, kind, s) => {
40
41
  } catch {
41
42
  }
42
43
  };
43
- var SOURCE = '(function(P){var r=document.documentElement,C="; "+document.cookie,k=0,j,p,t,n,i,e;for(P=JSON.parse(P);p=P[k++];)try{t=p[2];n=C.split("; "+p[0]+"=")[1];if(n!=null)try{n=decodeURIComponent(n.split(";")[0].replace(/^"(.*)"$/,"$1"));if(t===1){t=parseFloat(n);n=t===+n&&isFinite(t)?""+t:null}else if(t)n={}.hasOwnProperty.call(t,n)?t[n]:null}catch(e){n=null}if(n==null)n=p[3];for(j=0;i=p[1][j++];)if(i=="class"){for(e in t)r.classList.remove(t[e]);n!=null&&r.classList.add(n)}else i[0]=="-"?n==null?r.style.removeProperty(i):r.style.setProperty(i,n):n==null?r.removeAttribute(i):r.setAttribute(i,n)}catch(e){}})(';
44
- var script = (config) => config.length ? SOURCE + JSON.stringify(JSON.stringify(config)).replace(
45
- /[<>&\u2028\u2029]/g,
46
- (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
47
- ) + ")" : "";
48
44
 
49
45
  // src/core/sync.ts
50
46
  var open = () => {
@@ -55,16 +51,23 @@ var open = () => {
55
51
  };
56
52
  var subs = /* @__PURE__ */ new Set();
57
53
  var channel;
54
+ var timer;
58
55
  var changed = () => subs.forEach((check) => check());
59
56
  var shown = () => document.visibilityState == "visible" && changed();
57
+ var retry = (delay) => {
58
+ clearTimeout(timer);
59
+ if (delay < 4096 && document.visibilityState == "visible") timer = setTimeout(retry, delay, delay * 2);
60
+ changed();
61
+ };
60
62
  var hub = (check, on) => {
61
63
  if (on ? subs.add(check).size == 1 : subs.delete(check) && !subs.size) {
62
64
  const method = on ? "addEventListener" : "removeEventListener";
63
65
  globalThis.cookieStore?.[method]("change", changed);
64
66
  document[method]("visibilitychange", shown);
67
+ clearTimeout(timer);
65
68
  channel?.close();
66
69
  channel = on ? open() : void 0;
67
- if (channel) channel.onmessage = changed;
70
+ if (channel) channel.onmessage = () => retry(16);
68
71
  }
69
72
  };
70
73
  var post = () => {
@@ -80,7 +83,14 @@ var bind = (key, def, prefix, options) => {
80
83
  const attrs = merge(defaults, options, def.o, { name });
81
84
  const fallback = def.d;
82
85
  const targets = def.r;
83
- const kind = def.values ? Object.fromEntries(def.values.map((v) => [v, merge({ [v]: v }, def.m)[v]])) : def.k;
86
+ const values = def.values;
87
+ const enums = values && new Map(
88
+ Object.entries({ ...def.a }).filter((e) => values.includes(e[1])).concat(values.map((v) => [v, v]))
89
+ );
90
+ const kind = enums ? Object.fromEntries(
91
+ [...enums].map(([raw, v]) => [raw, merge({ [v]: v }, def.m)[v]])
92
+ ) : def.k;
93
+ const parse = enums ? (raw) => enums.get(raw) : def.p;
84
94
  if (typeof process == "object" && process.env.NODE_ENV != "production") {
85
95
  if (!name) throw TypeError(`cookie-prefs: ${key} needs a non-empty cookie name`);
86
96
  if (targets?.includes("class") && Object.values({ ...kind }).some((c) => !/^[^\t\n\f\r ]+$/.test(c)))
@@ -95,7 +105,7 @@ var bind = (key, def, prefix, options) => {
95
105
  if (typeof raw == "string" && raw.length <= 4096) {
96
106
  if (!cache.has(raw) || typeof document == "undefined") {
97
107
  if (cache.size > 9) cache.clear();
98
- cache.set(raw, def.p(raw));
108
+ cache.set(raw, parse(raw));
99
109
  }
100
110
  const value = cache.get(raw);
101
111
  if (value !== void 0) return value;
@@ -179,7 +189,7 @@ var bind = (key, def, prefix, options) => {
179
189
 
180
190
  // src/index.ts
181
191
  var pref = {
182
- enum: (values) => builder({ values, p: (raw) => values.includes(raw) ? raw : void 0, s: String }),
192
+ enum: (values) => builder({ values, s: String }),
183
193
  boolean: () => builder({
184
194
  k: { true: "true", false: "false" },
185
195
  p: (raw) => raw == "true" || (raw == "false" ? false : void 0),
@@ -223,14 +233,8 @@ function snapshotPrefs(prefs, source) {
223
233
  })
224
234
  );
225
235
  }
226
- function prefsScript(prefs) {
227
- return script(
228
- Object.values(prefs).map((handle) => handle[REFLECTION]).filter((r) => !!r)
229
- );
230
- }
231
236
 
232
237
  exports.definePrefs = definePrefs;
233
238
  exports.pref = pref;
234
- exports.prefsScript = prefsScript;
235
239
  exports.readPrefs = readPrefs;
236
240
  exports.snapshotPrefs = snapshotPrefs;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as EnumPrefBuilder, S as ScalarPrefBuilder, P as PrefBuilder, a as PrefCodec, b as PrefShape, c as PrefsOptions, d as Prefs, e as PrefsRecord, C as CookieSource, f as PrefValues, g as PrefsSnapshot } from './types-CQ_6o7nc.cjs';
2
- export { A as AnyPref, h as AnyPrefBuilder, i as CookieGetter, j as CookieInit, k as CookieOptions, l as CookieSameSite, m as EnumReflectTarget, n as Pref, o as PrefOptions, p as PrefSetter, q as PrefTypes, r as PrefValue, R as ReflectTarget } from './types-CQ_6o7nc.cjs';
1
+ import { E as EnumPrefBuilder, S as ScalarPrefBuilder, P as PrefBuilder, a as PrefCodec, b as PrefShape, c as PrefsOptions, d as Prefs, e as PrefsRecord, C as CookieSource, f as PrefValues, g as PrefsSnapshot } from './types-BITLlZeg.cjs';
2
+ export { A as AnyPref, h as AnyPrefBuilder, i as CookieGetter, j as CookieInit, k as CookieOptions, l as CookieSameSite, m as EnumReflectTarget, n as Pref, o as PrefOptions, p as PrefSetter, q as PrefTypes, r as PrefValue, R as ReflectTarget } from './types-BITLlZeg.cjs';
3
3
 
4
4
  /**
5
5
  * Structural copy of the Standard Schema v1 interface (https://standardschema.dev, MIT).
@@ -113,14 +113,6 @@ declare function readPrefs<P extends PrefsRecord>(prefs: P, source: CookieSource
113
113
  * <PrefsProvider snapshot={snapshotPrefs(prefs, request.headers.get('cookie'))}>
114
114
  */
115
115
  declare function snapshotPrefs(prefs: PrefsRecord, source: CookieSource): PrefsSnapshot;
116
- /**
117
- * Source of a blocking inline script that applies every `.reflect()` declaration to
118
- * `<html>` from `document.cookie` before first paint. Returns `''` when no pref
119
- * reflects. The output is fixed code plus escaped JSON config, safe to inline.
120
- * @example
121
- * <script nonce={nonce} dangerouslySetInnerHTML={{ __html: prefsScript(prefs) }} />
122
- */
123
- declare function prefsScript(prefs: PrefsRecord): string;
124
116
 
125
- export { CookieSource, EnumPrefBuilder, PrefBuilder, PrefCodec, PrefShape, PrefValues, Prefs, PrefsOptions, PrefsRecord, PrefsSnapshot, ScalarPrefBuilder, definePrefs, pref, prefsScript, readPrefs, snapshotPrefs };
117
+ export { CookieSource, EnumPrefBuilder, PrefBuilder, PrefCodec, PrefShape, PrefValues, Prefs, PrefsOptions, PrefsRecord, PrefsSnapshot, ScalarPrefBuilder, definePrefs, pref, readPrefs, snapshotPrefs };
126
118
  export type { PrefFactory, StandardSchemaV1 };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as EnumPrefBuilder, S as ScalarPrefBuilder, P as PrefBuilder, a as PrefCodec, b as PrefShape, c as PrefsOptions, d as Prefs, e as PrefsRecord, C as CookieSource, f as PrefValues, g as PrefsSnapshot } from './types-CQ_6o7nc.js';
2
- export { A as AnyPref, h as AnyPrefBuilder, i as CookieGetter, j as CookieInit, k as CookieOptions, l as CookieSameSite, m as EnumReflectTarget, n as Pref, o as PrefOptions, p as PrefSetter, q as PrefTypes, r as PrefValue, R as ReflectTarget } from './types-CQ_6o7nc.js';
1
+ import { E as EnumPrefBuilder, S as ScalarPrefBuilder, P as PrefBuilder, a as PrefCodec, b as PrefShape, c as PrefsOptions, d as Prefs, e as PrefsRecord, C as CookieSource, f as PrefValues, g as PrefsSnapshot } from './types-BITLlZeg.js';
2
+ export { A as AnyPref, h as AnyPrefBuilder, i as CookieGetter, j as CookieInit, k as CookieOptions, l as CookieSameSite, m as EnumReflectTarget, n as Pref, o as PrefOptions, p as PrefSetter, q as PrefTypes, r as PrefValue, R as ReflectTarget } from './types-BITLlZeg.js';
3
3
 
4
4
  /**
5
5
  * Structural copy of the Standard Schema v1 interface (https://standardschema.dev, MIT).
@@ -113,14 +113,6 @@ declare function readPrefs<P extends PrefsRecord>(prefs: P, source: CookieSource
113
113
  * <PrefsProvider snapshot={snapshotPrefs(prefs, request.headers.get('cookie'))}>
114
114
  */
115
115
  declare function snapshotPrefs(prefs: PrefsRecord, source: CookieSource): PrefsSnapshot;
116
- /**
117
- * Source of a blocking inline script that applies every `.reflect()` declaration to
118
- * `<html>` from `document.cookie` before first paint. Returns `''` when no pref
119
- * reflects. The output is fixed code plus escaped JSON config, safe to inline.
120
- * @example
121
- * <script nonce={nonce} dangerouslySetInnerHTML={{ __html: prefsScript(prefs) }} />
122
- */
123
- declare function prefsScript(prefs: PrefsRecord): string;
124
116
 
125
- export { CookieSource, EnumPrefBuilder, PrefBuilder, PrefCodec, PrefShape, PrefValues, Prefs, PrefsOptions, PrefsRecord, PrefsSnapshot, ScalarPrefBuilder, definePrefs, pref, prefsScript, readPrefs, snapshotPrefs };
117
+ export { CookieSource, EnumPrefBuilder, PrefBuilder, PrefCodec, PrefShape, PrefValues, Prefs, PrefsOptions, PrefsRecord, PrefsSnapshot, ScalarPrefBuilder, definePrefs, pref, readPrefs, snapshotPrefs };
126
118
  export type { PrefFactory, StandardSchemaV1 };
package/dist/index.js CHANGED
@@ -18,6 +18,7 @@ var builder = (def) => ({
18
18
  ...def,
19
19
  default: (d) => builder({ ...def, d }),
20
20
  options: (o) => builder({ ...def, o: merge(def.o, o) }),
21
+ migrate: (a) => builder({ ...def, a: merge(def.a, a) }),
21
22
  reflect: (r, m) => builder({ ...def, r: [].concat(r), m })
22
23
  });
23
24
 
@@ -38,11 +39,6 @@ var apply = (targets, kind, s) => {
38
39
  } catch {
39
40
  }
40
41
  };
41
- var SOURCE = '(function(P){var r=document.documentElement,C="; "+document.cookie,k=0,j,p,t,n,i,e;for(P=JSON.parse(P);p=P[k++];)try{t=p[2];n=C.split("; "+p[0]+"=")[1];if(n!=null)try{n=decodeURIComponent(n.split(";")[0].replace(/^"(.*)"$/,"$1"));if(t===1){t=parseFloat(n);n=t===+n&&isFinite(t)?""+t:null}else if(t)n={}.hasOwnProperty.call(t,n)?t[n]:null}catch(e){n=null}if(n==null)n=p[3];for(j=0;i=p[1][j++];)if(i=="class"){for(e in t)r.classList.remove(t[e]);n!=null&&r.classList.add(n)}else i[0]=="-"?n==null?r.style.removeProperty(i):r.style.setProperty(i,n):n==null?r.removeAttribute(i):r.setAttribute(i,n)}catch(e){}})(';
42
- var script = (config) => config.length ? SOURCE + JSON.stringify(JSON.stringify(config)).replace(
43
- /[<>&\u2028\u2029]/g,
44
- (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
45
- ) + ")" : "";
46
42
 
47
43
  // src/core/sync.ts
48
44
  var open = () => {
@@ -53,16 +49,23 @@ var open = () => {
53
49
  };
54
50
  var subs = /* @__PURE__ */ new Set();
55
51
  var channel;
52
+ var timer;
56
53
  var changed = () => subs.forEach((check) => check());
57
54
  var shown = () => document.visibilityState == "visible" && changed();
55
+ var retry = (delay) => {
56
+ clearTimeout(timer);
57
+ if (delay < 4096 && document.visibilityState == "visible") timer = setTimeout(retry, delay, delay * 2);
58
+ changed();
59
+ };
58
60
  var hub = (check, on) => {
59
61
  if (on ? subs.add(check).size == 1 : subs.delete(check) && !subs.size) {
60
62
  const method = on ? "addEventListener" : "removeEventListener";
61
63
  globalThis.cookieStore?.[method]("change", changed);
62
64
  document[method]("visibilitychange", shown);
65
+ clearTimeout(timer);
63
66
  channel?.close();
64
67
  channel = on ? open() : void 0;
65
- if (channel) channel.onmessage = changed;
68
+ if (channel) channel.onmessage = () => retry(16);
66
69
  }
67
70
  };
68
71
  var post = () => {
@@ -78,7 +81,14 @@ var bind = (key, def, prefix, options) => {
78
81
  const attrs = merge(defaults, options, def.o, { name });
79
82
  const fallback = def.d;
80
83
  const targets = def.r;
81
- const kind = def.values ? Object.fromEntries(def.values.map((v) => [v, merge({ [v]: v }, def.m)[v]])) : def.k;
84
+ const values = def.values;
85
+ const enums = values && new Map(
86
+ Object.entries({ ...def.a }).filter((e) => values.includes(e[1])).concat(values.map((v) => [v, v]))
87
+ );
88
+ const kind = enums ? Object.fromEntries(
89
+ [...enums].map(([raw, v]) => [raw, merge({ [v]: v }, def.m)[v]])
90
+ ) : def.k;
91
+ const parse = enums ? (raw) => enums.get(raw) : def.p;
82
92
  if (typeof process == "object" && process.env.NODE_ENV != "production") {
83
93
  if (!name) throw TypeError(`cookie-prefs: ${key} needs a non-empty cookie name`);
84
94
  if (targets?.includes("class") && Object.values({ ...kind }).some((c) => !/^[^\t\n\f\r ]+$/.test(c)))
@@ -93,7 +103,7 @@ var bind = (key, def, prefix, options) => {
93
103
  if (typeof raw == "string" && raw.length <= 4096) {
94
104
  if (!cache.has(raw) || typeof document == "undefined") {
95
105
  if (cache.size > 9) cache.clear();
96
- cache.set(raw, def.p(raw));
106
+ cache.set(raw, parse(raw));
97
107
  }
98
108
  const value = cache.get(raw);
99
109
  if (value !== void 0) return value;
@@ -177,7 +187,7 @@ var bind = (key, def, prefix, options) => {
177
187
 
178
188
  // src/index.ts
179
189
  var pref = {
180
- enum: (values) => builder({ values, p: (raw) => values.includes(raw) ? raw : void 0, s: String }),
190
+ enum: (values) => builder({ values, s: String }),
181
191
  boolean: () => builder({
182
192
  k: { true: "true", false: "false" },
183
193
  p: (raw) => raw == "true" || (raw == "false" ? false : void 0),
@@ -221,10 +231,5 @@ function snapshotPrefs(prefs, source) {
221
231
  })
222
232
  );
223
233
  }
224
- function prefsScript(prefs) {
225
- return script(
226
- Object.values(prefs).map((handle) => handle[REFLECTION]).filter((r) => !!r)
227
- );
228
- }
229
234
 
230
- export { definePrefs, pref, prefsScript, readPrefs, snapshotPrefs };
235
+ export { definePrefs, pref, readPrefs, snapshotPrefs };
@@ -2,6 +2,7 @@
2
2
 
3
3
  var headers_js = require('next/headers.js');
4
4
  var cookiePrefs = require('cookie-prefs');
5
+ var script = require('cookie-prefs/script');
5
6
  var react = require('cookie-prefs/react');
6
7
  var jsxRuntime = require('react/jsx-runtime');
7
8
 
@@ -32,16 +33,14 @@ async function getPrefs(prefs) {
32
33
  async function PrefsProvider({
33
34
  prefs,
34
35
  mode,
35
- nonce,
36
- children
36
+ ...props
37
37
  }) {
38
38
  return /* @__PURE__ */ jsxRuntime.jsx(
39
39
  react.PrefsProvider,
40
40
  {
41
+ ...props,
41
42
  snapshot: mode == "server" ? await requestSnapshot(prefs) : void 0,
42
- script: cookiePrefs.prefsScript(prefs),
43
- nonce,
44
- children
43
+ script: script.prefsScript(prefs)
45
44
  }
46
45
  );
47
46
  }
@@ -42,7 +42,7 @@ interface NextPrefsProviderProps<P extends PrefsRecord> {
42
42
  * </body>
43
43
  * </html>
44
44
  */
45
- declare function PrefsProvider<P extends PrefsRecord>({ prefs, mode, nonce, children, }: NextPrefsProviderProps<P>): Promise<ReactElement>;
45
+ declare function PrefsProvider<P extends PrefsRecord>({ prefs, mode, ...props }: NextPrefsProviderProps<P>): Promise<ReactElement>;
46
46
 
47
47
  export { PrefsProvider, getPrefs };
48
48
  export type { NextPrefsProviderProps };
@@ -42,7 +42,7 @@ interface NextPrefsProviderProps<P extends PrefsRecord> {
42
42
  * </body>
43
43
  * </html>
44
44
  */
45
- declare function PrefsProvider<P extends PrefsRecord>({ prefs, mode, nonce, children, }: NextPrefsProviderProps<P>): Promise<ReactElement>;
45
+ declare function PrefsProvider<P extends PrefsRecord>({ prefs, mode, ...props }: NextPrefsProviderProps<P>): Promise<ReactElement>;
46
46
 
47
47
  export { PrefsProvider, getPrefs };
48
48
  export type { NextPrefsProviderProps };
@@ -1,5 +1,6 @@
1
1
  import { headers, cookies } from 'next/headers.js';
2
- import { readPrefs, prefsScript, snapshotPrefs } from 'cookie-prefs';
2
+ import { readPrefs, snapshotPrefs } from 'cookie-prefs';
3
+ import { prefsScript } from 'cookie-prefs/script';
3
4
  import { PrefsProvider as PrefsProvider$1 } from 'cookie-prefs/react';
4
5
  import { jsx } from 'react/jsx-runtime';
5
6
 
@@ -30,16 +31,14 @@ async function getPrefs(prefs) {
30
31
  async function PrefsProvider({
31
32
  prefs,
32
33
  mode,
33
- nonce,
34
- children
34
+ ...props
35
35
  }) {
36
36
  return /* @__PURE__ */ jsx(
37
37
  PrefsProvider$1,
38
38
  {
39
+ ...props,
39
40
  snapshot: mode == "server" ? await requestSnapshot(prefs) : void 0,
40
- script: prefsScript(prefs),
41
- nonce,
42
- children
41
+ script: prefsScript(prefs)
43
42
  }
44
43
  );
45
44
  }
@@ -46,11 +46,7 @@ var useLayout = typeof document == "undefined" ? react.useEffect : react.useLayo
46
46
  var seen = /* @__PURE__ */ new WeakSet();
47
47
  function usePref(pref) {
48
48
  const snapshot = react.useContext(Snapshot);
49
- const value = react.useSyncExternalStore(
50
- pref.subscribe,
51
- pref.get,
52
- () => snapshot ? pref.read(snapshot) : pref.defaultValue
53
- );
49
+ const value = react.useSyncExternalStore(pref.subscribe, pref.get, () => pref.read(snapshot));
54
50
  react.useEffect(() => {
55
51
  if (seen.has(pref)) return;
56
52
  seen.add(pref);
@@ -63,12 +59,24 @@ function usePref(pref) {
63
59
  }, [pref]);
64
60
  return [value, pref.set];
65
61
  }
62
+ function usePrefs(prefs) {
63
+ const entries = Object.entries(prefs);
64
+ const values = entries.map(([key, handle]) => [key, usePref(handle)[0]]);
65
+ return [
66
+ // Keys and values as dependencies: a new object only when a value (or the record's
67
+ // shape) changes. Built with `fromEntries`, so a key named `__proto__` stays a key.
68
+ react.useMemo(() => Object.fromEntries(values), values.flat()),
69
+ react.useMemo(
70
+ () => (patch) => {
71
+ for (const [key, value] of Object.entries(patch)) if (value !== void 0) prefs[key].set(value);
72
+ },
73
+ entries.flat()
74
+ )
75
+ ];
76
+ }
66
77
  function PrefsProvider({ children, snapshot, script, nonce }) {
67
78
  const outer = react.useContext(Snapshot);
68
- const merged = react.useMemo(
69
- () => outer && snapshot ? { ...outer, ...snapshot } : snapshot ?? outer,
70
- [outer, snapshot]
71
- );
79
+ const merged = react.useMemo(() => snapshot ? { ...outer, ...snapshot } : outer, [outer, snapshot]);
72
80
  useLayout(() => {
73
81
  if (!script) return;
74
82
  const onVisible = () => {
@@ -96,3 +104,4 @@ function PrefsProvider({ children, snapshot, script, nonce }) {
96
104
 
97
105
  exports.PrefsProvider = PrefsProvider;
98
106
  exports.usePref = usePref;
107
+ exports.usePrefs = usePrefs;
@@ -1,6 +1,6 @@
1
1
  import { ReactNode, ReactElement } from 'react';
2
- import { p as PrefSetter } from '../types-CQ_6o7nc.cjs';
3
- import { PrefsSnapshot, Pref } from '../index.cjs';
2
+ import { p as PrefSetter } from '../types-BITLlZeg.cjs';
3
+ import { PrefsSnapshot, PrefsRecord, PrefTypes, Pref, PrefValues } from '../index.cjs';
4
4
 
5
5
  /**
6
6
  * Read and write one pref, like `useState`. Built on `useSyncExternalStore`, so every
@@ -23,6 +23,31 @@ import { PrefsSnapshot, Pref } from '../index.cjs';
23
23
  * <button onClick={() => setSidebar((open) => !open)}>Toggle</button>
24
24
  */
25
25
  declare function usePref<T, V>(pref: Pref<T, V>): [value: V, setValue: PrefSetter<T, V>];
26
+ /**
27
+ * Writes several prefs of a record at once: each key takes what that pref's `set()`
28
+ * takes, a value or an updater of the previous value. Keys left out (or `undefined`)
29
+ * are not touched.
30
+ */
31
+ type PrefsSetter<P extends PrefsRecord> = (patch: {
32
+ [K in keyof P]?: P[K] extends {
33
+ readonly '~types'?: PrefTypes<infer T, infer V>;
34
+ } ? T | ((prev: V) => T) : never;
35
+ }) => void;
36
+ /**
37
+ * Read and write several prefs at once: `usePref` for every handle in `prefs` (the
38
+ * record from `definePrefs()`, or any record of its handles), with the same server
39
+ * snapshot, hydration, cross-tab sync and Safari refresh. `values` is typed like
40
+ * `readPrefs()` and stays the same object until one of the prefs changes, so it is safe
41
+ * in dependency arrays. The setter takes a partial patch and passes each entry to that
42
+ * pref's `set()`, in order: a value or an updater of the previous value. An entry set
43
+ * to `undefined` is skipped like a missing key; clear a pref with `reset()`. The setter
44
+ * stays the same function while the record holds the same handles. Like any hook, it
45
+ * needs the same keys on every render.
46
+ * @example
47
+ * const [{ theme, sidebar }, set] = usePrefs(prefs)
48
+ * <button onClick={() => set({ sidebar: (open) => !open, theme: 'dark' })}>Focus</button>
49
+ */
50
+ declare function usePrefs<P extends PrefsRecord>(prefs: P): [values: PrefValues<P>, setValues: PrefsSetter<P>];
26
51
  interface PrefsProviderProps {
27
52
  children?: ReactNode;
28
53
  /**
@@ -33,14 +58,14 @@ interface PrefsProviderProps {
33
58
  */
34
59
  snapshot?: PrefsSnapshot | undefined;
35
60
  /**
36
- * Inline script from `prefsScript()`. Rendered once as the provider's first child, so
37
- * place the provider at the top of `<body>`. Only the first value is rendered; a
38
- * later one is still applied on `<html>`. It runs before paint on the initial
39
- * document and is inert on the client, so React does not warn about it. The
40
- * provider applies its reflections again with plain DOM calls, without running it,
41
- * on mount (React can reset `<html>` attributes on remount) and whenever the tab
42
- * becomes visible, so reflections also follow changes made in other tabs to prefs
43
- * that nothing in this tab subscribes to.
61
+ * Inline script from `prefsScript()` (`cookie-prefs/script`). Rendered once as the
62
+ * provider's first child, so place the provider at the top of `<body>`. Only the
63
+ * first value is rendered; a later one is still applied on `<html>`. It runs before
64
+ * paint on the initial document and is inert on the client, so React does not warn
65
+ * about it. The provider applies its reflections again with plain DOM calls, without
66
+ * running it, on mount (React can reset `<html>` attributes on remount) and whenever
67
+ * the tab becomes visible, so reflections also follow changes made in other tabs to
68
+ * prefs that nothing in this tab subscribes to.
44
69
  */
45
70
  script?: string | undefined;
46
71
  /**
@@ -63,5 +88,5 @@ interface PrefsProviderProps {
63
88
  */
64
89
  declare function PrefsProvider({ children, snapshot, script, nonce }: PrefsProviderProps): ReactElement;
65
90
 
66
- export { PrefSetter, PrefsProvider, usePref };
67
- export type { PrefsProviderProps };
91
+ export { PrefSetter, PrefsProvider, usePref, usePrefs };
92
+ export type { PrefsProviderProps, PrefsSetter };
@@ -1,6 +1,6 @@
1
1
  import { ReactNode, ReactElement } from 'react';
2
- import { p as PrefSetter } from '../types-CQ_6o7nc.js';
3
- import { PrefsSnapshot, Pref } from '../index.js';
2
+ import { p as PrefSetter } from '../types-BITLlZeg.js';
3
+ import { PrefsSnapshot, PrefsRecord, PrefTypes, Pref, PrefValues } from '../index.js';
4
4
 
5
5
  /**
6
6
  * Read and write one pref, like `useState`. Built on `useSyncExternalStore`, so every
@@ -23,6 +23,31 @@ import { PrefsSnapshot, Pref } from '../index.js';
23
23
  * <button onClick={() => setSidebar((open) => !open)}>Toggle</button>
24
24
  */
25
25
  declare function usePref<T, V>(pref: Pref<T, V>): [value: V, setValue: PrefSetter<T, V>];
26
+ /**
27
+ * Writes several prefs of a record at once: each key takes what that pref's `set()`
28
+ * takes, a value or an updater of the previous value. Keys left out (or `undefined`)
29
+ * are not touched.
30
+ */
31
+ type PrefsSetter<P extends PrefsRecord> = (patch: {
32
+ [K in keyof P]?: P[K] extends {
33
+ readonly '~types'?: PrefTypes<infer T, infer V>;
34
+ } ? T | ((prev: V) => T) : never;
35
+ }) => void;
36
+ /**
37
+ * Read and write several prefs at once: `usePref` for every handle in `prefs` (the
38
+ * record from `definePrefs()`, or any record of its handles), with the same server
39
+ * snapshot, hydration, cross-tab sync and Safari refresh. `values` is typed like
40
+ * `readPrefs()` and stays the same object until one of the prefs changes, so it is safe
41
+ * in dependency arrays. The setter takes a partial patch and passes each entry to that
42
+ * pref's `set()`, in order: a value or an updater of the previous value. An entry set
43
+ * to `undefined` is skipped like a missing key; clear a pref with `reset()`. The setter
44
+ * stays the same function while the record holds the same handles. Like any hook, it
45
+ * needs the same keys on every render.
46
+ * @example
47
+ * const [{ theme, sidebar }, set] = usePrefs(prefs)
48
+ * <button onClick={() => set({ sidebar: (open) => !open, theme: 'dark' })}>Focus</button>
49
+ */
50
+ declare function usePrefs<P extends PrefsRecord>(prefs: P): [values: PrefValues<P>, setValues: PrefsSetter<P>];
26
51
  interface PrefsProviderProps {
27
52
  children?: ReactNode;
28
53
  /**
@@ -33,14 +58,14 @@ interface PrefsProviderProps {
33
58
  */
34
59
  snapshot?: PrefsSnapshot | undefined;
35
60
  /**
36
- * Inline script from `prefsScript()`. Rendered once as the provider's first child, so
37
- * place the provider at the top of `<body>`. Only the first value is rendered; a
38
- * later one is still applied on `<html>`. It runs before paint on the initial
39
- * document and is inert on the client, so React does not warn about it. The
40
- * provider applies its reflections again with plain DOM calls, without running it,
41
- * on mount (React can reset `<html>` attributes on remount) and whenever the tab
42
- * becomes visible, so reflections also follow changes made in other tabs to prefs
43
- * that nothing in this tab subscribes to.
61
+ * Inline script from `prefsScript()` (`cookie-prefs/script`). Rendered once as the
62
+ * provider's first child, so place the provider at the top of `<body>`. Only the
63
+ * first value is rendered; a later one is still applied on `<html>`. It runs before
64
+ * paint on the initial document and is inert on the client, so React does not warn
65
+ * about it. The provider applies its reflections again with plain DOM calls, without
66
+ * running it, on mount (React can reset `<html>` attributes on remount) and whenever
67
+ * the tab becomes visible, so reflections also follow changes made in other tabs to
68
+ * prefs that nothing in this tab subscribes to.
44
69
  */
45
70
  script?: string | undefined;
46
71
  /**
@@ -63,5 +88,5 @@ interface PrefsProviderProps {
63
88
  */
64
89
  declare function PrefsProvider({ children, snapshot, script, nonce }: PrefsProviderProps): ReactElement;
65
90
 
66
- export { PrefSetter, PrefsProvider, usePref };
67
- export type { PrefsProviderProps };
91
+ export { PrefSetter, PrefsProvider, usePref, usePrefs };
92
+ export type { PrefsProviderProps, PrefsSetter };
@@ -44,11 +44,7 @@ var useLayout = typeof document == "undefined" ? useEffect : useLayoutEffect;
44
44
  var seen = /* @__PURE__ */ new WeakSet();
45
45
  function usePref(pref) {
46
46
  const snapshot = useContext(Snapshot);
47
- const value = useSyncExternalStore(
48
- pref.subscribe,
49
- pref.get,
50
- () => snapshot ? pref.read(snapshot) : pref.defaultValue
51
- );
47
+ const value = useSyncExternalStore(pref.subscribe, pref.get, () => pref.read(snapshot));
52
48
  useEffect(() => {
53
49
  if (seen.has(pref)) return;
54
50
  seen.add(pref);
@@ -61,12 +57,24 @@ function usePref(pref) {
61
57
  }, [pref]);
62
58
  return [value, pref.set];
63
59
  }
60
+ function usePrefs(prefs) {
61
+ const entries = Object.entries(prefs);
62
+ const values = entries.map(([key, handle]) => [key, usePref(handle)[0]]);
63
+ return [
64
+ // Keys and values as dependencies: a new object only when a value (or the record's
65
+ // shape) changes. Built with `fromEntries`, so a key named `__proto__` stays a key.
66
+ useMemo(() => Object.fromEntries(values), values.flat()),
67
+ useMemo(
68
+ () => (patch) => {
69
+ for (const [key, value] of Object.entries(patch)) if (value !== void 0) prefs[key].set(value);
70
+ },
71
+ entries.flat()
72
+ )
73
+ ];
74
+ }
64
75
  function PrefsProvider({ children, snapshot, script, nonce }) {
65
76
  const outer = useContext(Snapshot);
66
- const merged = useMemo(
67
- () => outer && snapshot ? { ...outer, ...snapshot } : snapshot ?? outer,
68
- [outer, snapshot]
69
- );
77
+ const merged = useMemo(() => snapshot ? { ...outer, ...snapshot } : outer, [outer, snapshot]);
70
78
  useLayout(() => {
71
79
  if (!script) return;
72
80
  const onVisible = () => {
@@ -92,4 +100,4 @@ function PrefsProvider({ children, snapshot, script, nonce }) {
92
100
  ] });
93
101
  }
94
102
 
95
- export { PrefsProvider, usePref };
103
+ export { PrefsProvider, usePref, usePrefs };
@@ -0,0 +1,14 @@
1
+ 'use strict';
2
+
3
+ // src/script/index.ts
4
+ var REFLECTION = /* @__PURE__ */ Symbol.for("cookie-prefs.reflection.1");
5
+ var SOURCE = '(function(P){var r=document.documentElement,C="; "+document.cookie,k=0,j,p,t,n,i,e;for(P=JSON.parse(P);p=P[k++];)try{t=p[2];n=C.split("; "+p[0]+"=")[1];if(n!=null)try{n=decodeURIComponent(n.split(";")[0].replace(/^"(.*)"$/,"$1"));if(t===1){t=parseFloat(n);n=t===+n&&isFinite(t)?""+t:null}else if(t)n={}.hasOwnProperty.call(t,n)?t[n]:null}catch(e){n=null}if(n==null)n=p[3];for(j=0;i=p[1][j++];)if(i=="class"){for(e in t)r.classList.remove(t[e]);n!=null&&r.classList.add(n)}else i[0]=="-"?n==null?r.style.removeProperty(i):r.style.setProperty(i,n):n==null?r.removeAttribute(i):r.setAttribute(i,n)}catch(e){}})(';
6
+ function prefsScript(prefs) {
7
+ const config = Object.values(prefs).map((handle) => handle[REFLECTION]).filter((r) => !!r);
8
+ return config.length ? SOURCE + JSON.stringify(JSON.stringify(config)).replace(
9
+ /[<>&\u2028\u2029]/g,
10
+ (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
11
+ ) + ")" : "";
12
+ }
13
+
14
+ exports.prefsScript = prefsScript;
@@ -0,0 +1,12 @@
1
+ import { PrefsRecord } from '../index.cjs';
2
+
3
+ /**
4
+ * Source of a blocking inline script that applies every `.reflect()` declaration to
5
+ * `<html>` from `document.cookie` before first paint. Returns `''` when no pref
6
+ * reflects. The output is fixed code plus escaped JSON config, safe to inline.
7
+ * @example
8
+ * <script nonce={nonce} dangerouslySetInnerHTML={{ __html: prefsScript(prefs) }} />
9
+ */
10
+ declare function prefsScript(prefs: PrefsRecord): string;
11
+
12
+ export { prefsScript };
@@ -0,0 +1,12 @@
1
+ import { PrefsRecord } from '../index.js';
2
+
3
+ /**
4
+ * Source of a blocking inline script that applies every `.reflect()` declaration to
5
+ * `<html>` from `document.cookie` before first paint. Returns `''` when no pref
6
+ * reflects. The output is fixed code plus escaped JSON config, safe to inline.
7
+ * @example
8
+ * <script nonce={nonce} dangerouslySetInnerHTML={{ __html: prefsScript(prefs) }} />
9
+ */
10
+ declare function prefsScript(prefs: PrefsRecord): string;
11
+
12
+ export { prefsScript };
@@ -0,0 +1,12 @@
1
+ // src/script/index.ts
2
+ var REFLECTION = /* @__PURE__ */ Symbol.for("cookie-prefs.reflection.1");
3
+ var SOURCE = '(function(P){var r=document.documentElement,C="; "+document.cookie,k=0,j,p,t,n,i,e;for(P=JSON.parse(P);p=P[k++];)try{t=p[2];n=C.split("; "+p[0]+"=")[1];if(n!=null)try{n=decodeURIComponent(n.split(";")[0].replace(/^"(.*)"$/,"$1"));if(t===1){t=parseFloat(n);n=t===+n&&isFinite(t)?""+t:null}else if(t)n={}.hasOwnProperty.call(t,n)?t[n]:null}catch(e){n=null}if(n==null)n=p[3];for(j=0;i=p[1][j++];)if(i=="class"){for(e in t)r.classList.remove(t[e]);n!=null&&r.classList.add(n)}else i[0]=="-"?n==null?r.style.removeProperty(i):r.style.setProperty(i,n):n==null?r.removeAttribute(i):r.setAttribute(i,n)}catch(e){}})(';
4
+ function prefsScript(prefs) {
5
+ const config = Object.values(prefs).map((handle) => handle[REFLECTION]).filter((r) => !!r);
6
+ return config.length ? SOURCE + JSON.stringify(JSON.stringify(config)).replace(
7
+ /[<>&\u2028\u2029]/g,
8
+ (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
9
+ ) + ")" : "";
10
+ }
11
+
12
+ export { prefsScript };
@@ -0,0 +1,53 @@
1
+ 'use client';
2
+ 'use strict';
3
+
4
+ var theme = require('cookie-prefs/theme');
5
+ var react = require('react');
6
+ var jsxRuntime = require('react/jsx-runtime');
7
+
8
+ // src/theme/color/index.tsx
9
+ var MARK = "cookie-prefs";
10
+ var OURS = `meta[property="${MARK}"]`;
11
+ var FIRST = 'meta[name="theme-color"]';
12
+ var SOURCE = `(function(C){var n=document.scripts,i=n.length,t;while(i--)if(!(t=n[i].text).indexOf('(function(k,l,a,m,d,f,s,c){')){(function(k,l,a,m,d,f,s,c){var x,h,y;if(!f){x=('; '+document.cookie).split('; '+k+'=')[1];try{x=x!=null?decodeURIComponent(x.split(';')[0].replace(/^"(.*)"$/,'$1')):localStorage.getItem(l)}catch(e){x=null}f=x!=null&&{}.hasOwnProperty.call(m,x)?x:d}if(f=='system'&&s)f=matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';if(x={}.hasOwnProperty.call(C,f)&&C[f]){h=document.querySelector('` + OURS + "')||document.createElement('meta');h.name='theme-color';h.content=x;h.setAttribute('property','" + MARK + "');y=document.querySelector('" + FIRST + "');y?y!=h&&y.parentNode.insertBefore(h,y):document.head.appendChild(h)}}).apply(0,JSON.parse(JSON.parse(t.slice(t.indexOf('JSON.parse(')+11,-2))));break}})(JSON.parse(";
13
+ var colorScript = (colors) => SOURCE + JSON.stringify(JSON.stringify(colors)).replace(
14
+ /[<>&\u2028\u2029]/g,
15
+ (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
16
+ ) + "))";
17
+ var set = (color) => {
18
+ let meta = document.querySelector(OURS);
19
+ if (!color) return meta?.remove();
20
+ meta ||= document.createElement("meta");
21
+ meta.name = "theme-color";
22
+ meta.content = color;
23
+ meta.setAttribute("property", MARK);
24
+ const first = document.querySelector(FIRST);
25
+ if (!first) document.head.append(meta);
26
+ else if (first != meta) first.before(meta);
27
+ };
28
+ var useLayout = typeof document == "undefined" ? react.useEffect : react.useLayoutEffect;
29
+ function ThemeColor({ colors, nonce }) {
30
+ const { theme: theme$1, resolvedTheme, forcedTheme, systemTheme } = theme.useTheme();
31
+ let name = forcedTheme || resolvedTheme;
32
+ if (name == "system" && systemTheme) name = systemTheme;
33
+ const color = theme$1 == null ? void 0 : {}.hasOwnProperty.call(colors, name) ? colors[name] || "" : "";
34
+ const [first] = react.useState(() => ({ __html: colorScript(colors) }));
35
+ useLayout(() => {
36
+ if (color != null) {
37
+ set(color);
38
+ return set;
39
+ }
40
+ }, [color]);
41
+ const server = typeof document == "undefined";
42
+ return /* @__PURE__ */ jsxRuntime.jsx(
43
+ "script",
44
+ {
45
+ type: server ? "text/javascript" : "text/plain",
46
+ nonce: server ? nonce : void 0,
47
+ suppressHydrationWarning: true,
48
+ dangerouslySetInnerHTML: first
49
+ }
50
+ );
51
+ }
52
+
53
+ exports.ThemeColor = ThemeColor;
@@ -0,0 +1,32 @@
1
+ import { ReactElement } from 'react';
2
+
3
+ /** Props of `ThemeColor`. */
4
+ interface ThemeColorProps {
5
+ /**
6
+ * Theme name to the `<meta name="theme-color">` value (any CSS colour), keyed like
7
+ * the provider's `themes` (custom themes and `value` keys too). Looked up for the theme
8
+ * shown: `forcedTheme` first, `'system'` resolved to `'light'` or `'dark'`. A theme
9
+ * without a colour leaves the page's own theme-color tags in charge.
10
+ */
11
+ colors: Readonly<Record<string, string>>;
12
+ /** CSP nonce for the inline script, as passed to `ThemeProvider`. */
13
+ nonce?: string | undefined;
14
+ }
15
+ /**
16
+ * Keeps `<meta name="theme-color">` (the browser UI colour on mobile and of installed
17
+ * apps) in sync with the theme shown by `ThemeProvider`: before hydration through an
18
+ * inline script, afterwards through `useTheme()`, so it follows `setTheme`, the OS
19
+ * scheme for `'system'`, `forcedTheme` and other tabs. Render it once, anywhere inside
20
+ * `ThemeProvider`. It owns one tag and places it before the page's other theme-color
21
+ * tags (Next.js `viewport.themeColor`, for example), which stay in place and apply to
22
+ * themes without a colour.
23
+ * @example
24
+ * <ThemeProvider attribute="class">
25
+ * <ThemeColor colors={{ light: '#ffffff', dark: '#0a0a0a' }} />
26
+ * {children}
27
+ * </ThemeProvider>
28
+ */
29
+ declare function ThemeColor({ colors, nonce }: ThemeColorProps): ReactElement;
30
+
31
+ export { ThemeColor };
32
+ export type { ThemeColorProps };
@@ -0,0 +1,32 @@
1
+ import { ReactElement } from 'react';
2
+
3
+ /** Props of `ThemeColor`. */
4
+ interface ThemeColorProps {
5
+ /**
6
+ * Theme name to the `<meta name="theme-color">` value (any CSS colour), keyed like
7
+ * the provider's `themes` (custom themes and `value` keys too). Looked up for the theme
8
+ * shown: `forcedTheme` first, `'system'` resolved to `'light'` or `'dark'`. A theme
9
+ * without a colour leaves the page's own theme-color tags in charge.
10
+ */
11
+ colors: Readonly<Record<string, string>>;
12
+ /** CSP nonce for the inline script, as passed to `ThemeProvider`. */
13
+ nonce?: string | undefined;
14
+ }
15
+ /**
16
+ * Keeps `<meta name="theme-color">` (the browser UI colour on mobile and of installed
17
+ * apps) in sync with the theme shown by `ThemeProvider`: before hydration through an
18
+ * inline script, afterwards through `useTheme()`, so it follows `setTheme`, the OS
19
+ * scheme for `'system'`, `forcedTheme` and other tabs. Render it once, anywhere inside
20
+ * `ThemeProvider`. It owns one tag and places it before the page's other theme-color
21
+ * tags (Next.js `viewport.themeColor`, for example), which stay in place and apply to
22
+ * themes without a colour.
23
+ * @example
24
+ * <ThemeProvider attribute="class">
25
+ * <ThemeColor colors={{ light: '#ffffff', dark: '#0a0a0a' }} />
26
+ * {children}
27
+ * </ThemeProvider>
28
+ */
29
+ declare function ThemeColor({ colors, nonce }: ThemeColorProps): ReactElement;
30
+
31
+ export { ThemeColor };
32
+ export type { ThemeColorProps };
@@ -0,0 +1,51 @@
1
+ 'use client';
2
+ import { useTheme } from 'cookie-prefs/theme';
3
+ import { useState, useEffect, useLayoutEffect } from 'react';
4
+ import { jsx } from 'react/jsx-runtime';
5
+
6
+ // src/theme/color/index.tsx
7
+ var MARK = "cookie-prefs";
8
+ var OURS = `meta[property="${MARK}"]`;
9
+ var FIRST = 'meta[name="theme-color"]';
10
+ var SOURCE = `(function(C){var n=document.scripts,i=n.length,t;while(i--)if(!(t=n[i].text).indexOf('(function(k,l,a,m,d,f,s,c){')){(function(k,l,a,m,d,f,s,c){var x,h,y;if(!f){x=('; '+document.cookie).split('; '+k+'=')[1];try{x=x!=null?decodeURIComponent(x.split(';')[0].replace(/^"(.*)"$/,'$1')):localStorage.getItem(l)}catch(e){x=null}f=x!=null&&{}.hasOwnProperty.call(m,x)?x:d}if(f=='system'&&s)f=matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';if(x={}.hasOwnProperty.call(C,f)&&C[f]){h=document.querySelector('` + OURS + "')||document.createElement('meta');h.name='theme-color';h.content=x;h.setAttribute('property','" + MARK + "');y=document.querySelector('" + FIRST + "');y?y!=h&&y.parentNode.insertBefore(h,y):document.head.appendChild(h)}}).apply(0,JSON.parse(JSON.parse(t.slice(t.indexOf('JSON.parse(')+11,-2))));break}})(JSON.parse(";
11
+ var colorScript = (colors) => SOURCE + JSON.stringify(JSON.stringify(colors)).replace(
12
+ /[<>&\u2028\u2029]/g,
13
+ (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
14
+ ) + "))";
15
+ var set = (color) => {
16
+ let meta = document.querySelector(OURS);
17
+ if (!color) return meta?.remove();
18
+ meta ||= document.createElement("meta");
19
+ meta.name = "theme-color";
20
+ meta.content = color;
21
+ meta.setAttribute("property", MARK);
22
+ const first = document.querySelector(FIRST);
23
+ if (!first) document.head.append(meta);
24
+ else if (first != meta) first.before(meta);
25
+ };
26
+ var useLayout = typeof document == "undefined" ? useEffect : useLayoutEffect;
27
+ function ThemeColor({ colors, nonce }) {
28
+ const { theme, resolvedTheme, forcedTheme, systemTheme } = useTheme();
29
+ let name = forcedTheme || resolvedTheme;
30
+ if (name == "system" && systemTheme) name = systemTheme;
31
+ const color = theme == null ? void 0 : {}.hasOwnProperty.call(colors, name) ? colors[name] || "" : "";
32
+ const [first] = useState(() => ({ __html: colorScript(colors) }));
33
+ useLayout(() => {
34
+ if (color != null) {
35
+ set(color);
36
+ return set;
37
+ }
38
+ }, [color]);
39
+ const server = typeof document == "undefined";
40
+ return /* @__PURE__ */ jsx(
41
+ "script",
42
+ {
43
+ type: server ? "text/javascript" : "text/plain",
44
+ nonce: server ? nonce : void 0,
45
+ suppressHydrationWarning: true,
46
+ dangerouslySetInnerHTML: first
47
+ }
48
+ );
49
+ }
50
+
51
+ export { ThemeColor };
@@ -0,0 +1,13 @@
1
+ 'use strict';
2
+
3
+ var cookiePrefs = require('cookie-prefs');
4
+ var next = require('cookie-prefs/next');
5
+ var server = require('cookie-prefs/theme/server');
6
+
7
+ // src/theme/next/index.ts
8
+ async function getTheme(options = {}) {
9
+ const raw = cookiePrefs.definePrefs({ theme: cookiePrefs.pref.string().options({ name: options.storageKey ?? "theme" }) });
10
+ return server.readTheme({ [raw.theme.name]: (await next.getPrefs(raw)).theme }, options);
11
+ }
12
+
13
+ exports.getTheme = getTheme;
@@ -0,0 +1,20 @@
1
+ import { ThemeOptions } from '../server/index.cjs';
2
+ import 'cookie-prefs';
3
+
4
+ /**
5
+ * The stored theme for the current request: what `useTheme().theme` holds after
6
+ * hydration for the same cookie and the same `ThemeProvider` options (an unlisted or
7
+ * malformed value reads as `defaultTheme`; `'system'` is returned as is, since only the
8
+ * browser can resolve it; `forcedTheme` is not applied). Reads the request like
9
+ * `getPrefs` from `cookie-prefs/next`, so a theme cookie set earlier in the same request
10
+ * (a Server Function, middleware) is seen. Server-only (Server Components, Server
11
+ * Functions, Route Handlers). Reading request cookies makes the route dynamic, so this
12
+ * does not fit static rendering or Cache Components; the provider's inline script still
13
+ * applies the theme before paint, and `<html>` keeps `suppressHydrationWarning`.
14
+ * @example
15
+ * const theme = await getTheme({ themes: ['light', 'dark'] })
16
+ * <html lang="en" className={theme == 'system' ? undefined : theme} suppressHydrationWarning>
17
+ */
18
+ declare function getTheme<const T extends string = string>(options?: ThemeOptions<T>): Promise<T | 'system'>;
19
+
20
+ export { ThemeOptions, getTheme };
@@ -0,0 +1,20 @@
1
+ import { ThemeOptions } from '../server/index.js';
2
+ import 'cookie-prefs';
3
+
4
+ /**
5
+ * The stored theme for the current request: what `useTheme().theme` holds after
6
+ * hydration for the same cookie and the same `ThemeProvider` options (an unlisted or
7
+ * malformed value reads as `defaultTheme`; `'system'` is returned as is, since only the
8
+ * browser can resolve it; `forcedTheme` is not applied). Reads the request like
9
+ * `getPrefs` from `cookie-prefs/next`, so a theme cookie set earlier in the same request
10
+ * (a Server Function, middleware) is seen. Server-only (Server Components, Server
11
+ * Functions, Route Handlers). Reading request cookies makes the route dynamic, so this
12
+ * does not fit static rendering or Cache Components; the provider's inline script still
13
+ * applies the theme before paint, and `<html>` keeps `suppressHydrationWarning`.
14
+ * @example
15
+ * const theme = await getTheme({ themes: ['light', 'dark'] })
16
+ * <html lang="en" className={theme == 'system' ? undefined : theme} suppressHydrationWarning>
17
+ */
18
+ declare function getTheme<const T extends string = string>(options?: ThemeOptions<T>): Promise<T | 'system'>;
19
+
20
+ export { ThemeOptions, getTheme };
@@ -0,0 +1,11 @@
1
+ import { definePrefs, pref } from 'cookie-prefs';
2
+ import { getPrefs } from 'cookie-prefs/next';
3
+ import { readTheme } from 'cookie-prefs/theme/server';
4
+
5
+ // src/theme/next/index.ts
6
+ async function getTheme(options = {}) {
7
+ const raw = definePrefs({ theme: pref.string().options({ name: options.storageKey ?? "theme" }) });
8
+ return readTheme({ [raw.theme.name]: (await getPrefs(raw)).theme }, options);
9
+ }
10
+
11
+ export { getTheme };
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+
3
+ var cookiePrefs = require('cookie-prefs');
4
+
5
+ // src/theme/server/index.ts
6
+ function readTheme(source, {
7
+ themes = ["light", "dark"],
8
+ enableSystem = true,
9
+ storageKey = "theme",
10
+ defaultTheme = enableSystem ? "system" : "light",
11
+ value
12
+ } = {}) {
13
+ return cookiePrefs.definePrefs({
14
+ theme: cookiePrefs.pref.enum(
15
+ Object.keys(
16
+ Object.fromEntries(
17
+ (enableSystem ? [...themes, "system"] : themes).concat(Object.keys(value || {})).map((t) => [t, t])
18
+ )
19
+ )
20
+ ).default(defaultTheme).options({ name: storageKey })
21
+ }).theme.read(source);
22
+ }
23
+
24
+ exports.readTheme = readTheme;
@@ -0,0 +1,41 @@
1
+ import { CookieSource } from 'cookie-prefs';
2
+
3
+ /**
4
+ * The `ThemeProvider` props that decide which stored theme is valid. Pass the values
5
+ * the provider gets, with the same defaults; any other provider prop may be passed and
6
+ * is ignored, so one config object can feed both. When `themes` is a literal tuple,
7
+ * `defaultTheme` and the keys of `value` must be among them (or `'system'`), so the
8
+ * returned type is exactly the names that can come back.
9
+ */
10
+ interface ThemeOptions<T extends string = string> {
11
+ /** All theme names. `'system'` is added when `enableSystem` is on. @default ['light', 'dark'] */
12
+ themes?: readonly T[] | undefined;
13
+ /** Whether `'system'` is a valid stored theme. @default true */
14
+ enableSystem?: boolean | undefined;
15
+ /** Cookie name that stores the choice. @default 'theme' */
16
+ storageKey?: string | undefined;
17
+ /**
18
+ * Theme when nothing valid is stored. With `enableSystem` off and no `'light'` in
19
+ * `themes`, pass it: the next-themes default `'light'` is returned as is.
20
+ * @default enableSystem ? 'system' : 'light'
21
+ */
22
+ defaultTheme?: NoInfer<T> | 'system' | undefined;
23
+ /** Theme name to DOM value; its keys are valid stored themes too, as in the provider. */
24
+ value?: Readonly<Partial<Record<NoInfer<T> | 'system', string>>> | undefined;
25
+ }
26
+ /**
27
+ * The stored theme for a request, read from its cookies: what `useTheme().theme` holds
28
+ * after hydration for the same cookie and the same `ThemeProvider` options. A name the
29
+ * provider does not list, or a malformed cookie, reads as `defaultTheme`. `'system'` is
30
+ * returned as is: only the browser knows the OS scheme. `forcedTheme` is not applied.
31
+ * Works on any server: a `Cookie` header string, a cookie store with `get(name)` or a
32
+ * plain map, like the core's `readPrefs`. In the Next.js App Router use `getTheme()`
33
+ * from `cookie-prefs/theme/next`.
34
+ * @example
35
+ * // React Router loader
36
+ * const theme = readTheme(request.headers.get('cookie'), { themes: ['light', 'dark'] })
37
+ */
38
+ declare function readTheme<const T extends string = string>(source: CookieSource, options?: ThemeOptions<T>): T | 'system';
39
+
40
+ export { readTheme };
41
+ export type { ThemeOptions };
@@ -0,0 +1,41 @@
1
+ import { CookieSource } from 'cookie-prefs';
2
+
3
+ /**
4
+ * The `ThemeProvider` props that decide which stored theme is valid. Pass the values
5
+ * the provider gets, with the same defaults; any other provider prop may be passed and
6
+ * is ignored, so one config object can feed both. When `themes` is a literal tuple,
7
+ * `defaultTheme` and the keys of `value` must be among them (or `'system'`), so the
8
+ * returned type is exactly the names that can come back.
9
+ */
10
+ interface ThemeOptions<T extends string = string> {
11
+ /** All theme names. `'system'` is added when `enableSystem` is on. @default ['light', 'dark'] */
12
+ themes?: readonly T[] | undefined;
13
+ /** Whether `'system'` is a valid stored theme. @default true */
14
+ enableSystem?: boolean | undefined;
15
+ /** Cookie name that stores the choice. @default 'theme' */
16
+ storageKey?: string | undefined;
17
+ /**
18
+ * Theme when nothing valid is stored. With `enableSystem` off and no `'light'` in
19
+ * `themes`, pass it: the next-themes default `'light'` is returned as is.
20
+ * @default enableSystem ? 'system' : 'light'
21
+ */
22
+ defaultTheme?: NoInfer<T> | 'system' | undefined;
23
+ /** Theme name to DOM value; its keys are valid stored themes too, as in the provider. */
24
+ value?: Readonly<Partial<Record<NoInfer<T> | 'system', string>>> | undefined;
25
+ }
26
+ /**
27
+ * The stored theme for a request, read from its cookies: what `useTheme().theme` holds
28
+ * after hydration for the same cookie and the same `ThemeProvider` options. A name the
29
+ * provider does not list, or a malformed cookie, reads as `defaultTheme`. `'system'` is
30
+ * returned as is: only the browser knows the OS scheme. `forcedTheme` is not applied.
31
+ * Works on any server: a `Cookie` header string, a cookie store with `get(name)` or a
32
+ * plain map, like the core's `readPrefs`. In the Next.js App Router use `getTheme()`
33
+ * from `cookie-prefs/theme/next`.
34
+ * @example
35
+ * // React Router loader
36
+ * const theme = readTheme(request.headers.get('cookie'), { themes: ['light', 'dark'] })
37
+ */
38
+ declare function readTheme<const T extends string = string>(source: CookieSource, options?: ThemeOptions<T>): T | 'system';
39
+
40
+ export { readTheme };
41
+ export type { ThemeOptions };
@@ -0,0 +1,22 @@
1
+ import { definePrefs, pref } from 'cookie-prefs';
2
+
3
+ // src/theme/server/index.ts
4
+ function readTheme(source, {
5
+ themes = ["light", "dark"],
6
+ enableSystem = true,
7
+ storageKey = "theme",
8
+ defaultTheme = enableSystem ? "system" : "light",
9
+ value
10
+ } = {}) {
11
+ return definePrefs({
12
+ theme: pref.enum(
13
+ Object.keys(
14
+ Object.fromEntries(
15
+ (enableSystem ? [...themes, "system"] : themes).concat(Object.keys(value || {})).map((t) => [t, t])
16
+ )
17
+ )
18
+ ).default(defaultTheme).options({ name: storageKey })
19
+ }).theme.read(source);
20
+ }
21
+
22
+ export { readTheme };
@@ -141,6 +141,18 @@ interface EnumPrefBuilder<T extends string, V = T | undefined> extends PrefBuild
141
141
  * @example pref.enum(['compact', 'cozy']).default('cozy').reflect('data-density')
142
142
  */
143
143
  reflect(target: EnumReflectTarget | readonly EnumReflectTarget[], value?: Partial<Record<T, string>>): EnumPrefBuilder<T, V>;
144
+ /**
145
+ * Read old (renamed or removed) values as current ones: a cookie holding a key of
146
+ * `map` reads as its value everywhere (`get()`, `read()`, `readPrefs`, hydration from
147
+ * a snapshot, reflection and the inline script). Reads never rewrite the cookie; the
148
+ * next `set()` writes the current name. One level only: a value must be a current
149
+ * value, and a key must not be one (a current value always reads as itself).
150
+ * Repeated calls add to the map.
151
+ * @example pref.enum(['compact', 'comfortable']).default('comfortable').migrate({ cozy: 'comfortable' })
152
+ */
153
+ migrate<const M extends Readonly<Record<string, T>>>(map: M & {
154
+ readonly [K in keyof M & T]?: never;
155
+ }): EnumPrefBuilder<T, V>;
144
156
  }
145
157
  /** A custom codec for `pref.custom()`. */
146
158
  interface PrefCodec<T> {
@@ -141,6 +141,18 @@ interface EnumPrefBuilder<T extends string, V = T | undefined> extends PrefBuild
141
141
  * @example pref.enum(['compact', 'cozy']).default('cozy').reflect('data-density')
142
142
  */
143
143
  reflect(target: EnumReflectTarget | readonly EnumReflectTarget[], value?: Partial<Record<T, string>>): EnumPrefBuilder<T, V>;
144
+ /**
145
+ * Read old (renamed or removed) values as current ones: a cookie holding a key of
146
+ * `map` reads as its value everywhere (`get()`, `read()`, `readPrefs`, hydration from
147
+ * a snapshot, reflection and the inline script). Reads never rewrite the cookie; the
148
+ * next `set()` writes the current name. One level only: a value must be a current
149
+ * value, and a key must not be one (a current value always reads as itself).
150
+ * Repeated calls add to the map.
151
+ * @example pref.enum(['compact', 'comfortable']).default('comfortable').migrate({ cozy: 'comfortable' })
152
+ */
153
+ migrate<const M extends Readonly<Record<string, T>>>(map: M & {
154
+ readonly [K in keyof M & T]?: never;
155
+ }): EnumPrefBuilder<T, V>;
144
156
  }
145
157
  /** A custom codec for `pref.custom()`. */
146
158
  interface PrefCodec<T> {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cookie-prefs",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "Typed cookie-backed user preference state for React and Next.js",
5
5
  "keywords": [
6
6
  "react",
@@ -58,6 +58,16 @@
58
58
  "default": "./dist/next/index.cjs"
59
59
  }
60
60
  },
61
+ "./script": {
62
+ "import": {
63
+ "types": "./dist/script/index.d.ts",
64
+ "default": "./dist/script/index.js"
65
+ },
66
+ "require": {
67
+ "types": "./dist/script/index.d.cts",
68
+ "default": "./dist/script/index.cjs"
69
+ }
70
+ },
61
71
  "./theme": {
62
72
  "import": {
63
73
  "types": "./dist/theme/index.d.ts",
@@ -68,6 +78,36 @@
68
78
  "default": "./dist/theme/index.cjs"
69
79
  }
70
80
  },
81
+ "./theme/server": {
82
+ "import": {
83
+ "types": "./dist/theme/server/index.d.ts",
84
+ "default": "./dist/theme/server/index.js"
85
+ },
86
+ "require": {
87
+ "types": "./dist/theme/server/index.d.cts",
88
+ "default": "./dist/theme/server/index.cjs"
89
+ }
90
+ },
91
+ "./theme/next": {
92
+ "import": {
93
+ "types": "./dist/theme/next/index.d.ts",
94
+ "default": "./dist/theme/next/index.js"
95
+ },
96
+ "require": {
97
+ "types": "./dist/theme/next/index.d.cts",
98
+ "default": "./dist/theme/next/index.cjs"
99
+ }
100
+ },
101
+ "./theme/color": {
102
+ "import": {
103
+ "types": "./dist/theme/color/index.d.ts",
104
+ "default": "./dist/theme/color/index.js"
105
+ },
106
+ "require": {
107
+ "types": "./dist/theme/color/index.d.cts",
108
+ "default": "./dist/theme/color/index.cjs"
109
+ }
110
+ },
71
111
  "./package.json": "./package.json"
72
112
  },
73
113
  "typesVersions": {
@@ -78,8 +118,20 @@
78
118
  "next": [
79
119
  "./dist/next/index.d.ts"
80
120
  ],
121
+ "script": [
122
+ "./dist/script/index.d.ts"
123
+ ],
81
124
  "theme": [
82
125
  "./dist/theme/index.d.ts"
126
+ ],
127
+ "theme/server": [
128
+ "./dist/theme/server/index.d.ts"
129
+ ],
130
+ "theme/next": [
131
+ "./dist/theme/next/index.d.ts"
132
+ ],
133
+ "theme/color": [
134
+ "./dist/theme/color/index.d.ts"
83
135
  ]
84
136
  }
85
137
  },
@@ -106,7 +158,17 @@
106
158
  {
107
159
  "name": "cookie-prefs/react",
108
160
  "path": "dist/react/index.js",
109
- "limit": "980 B",
161
+ "limit": "1040 B",
162
+ "gzip": true,
163
+ "ignore": [
164
+ "cookie-prefs"
165
+ ]
166
+ },
167
+ {
168
+ "name": "cookie-prefs/react (usePref and PrefsProvider only)",
169
+ "path": "dist/react/index.js",
170
+ "import": "{ usePref, PrefsProvider }",
171
+ "limit": "930 B",
110
172
  "gzip": true,
111
173
  "ignore": [
112
174
  "cookie-prefs"
@@ -121,6 +183,12 @@
121
183
  "cookie-prefs"
122
184
  ]
123
185
  },
186
+ {
187
+ "name": "cookie-prefs/script",
188
+ "path": "dist/script/index.js",
189
+ "limit": "570 B",
190
+ "gzip": true
191
+ },
124
192
  {
125
193
  "name": "cookie-prefs/theme",
126
194
  "path": "dist/theme/index.js",
@@ -129,6 +197,33 @@
129
197
  "ignore": [
130
198
  "cookie-prefs"
131
199
  ]
200
+ },
201
+ {
202
+ "name": "cookie-prefs/theme/server",
203
+ "path": "dist/theme/server/index.js",
204
+ "limit": "255 B",
205
+ "gzip": true,
206
+ "ignore": [
207
+ "cookie-prefs"
208
+ ]
209
+ },
210
+ {
211
+ "name": "cookie-prefs/theme/next",
212
+ "path": "dist/theme/next/index.js",
213
+ "limit": "200 B",
214
+ "gzip": true,
215
+ "ignore": [
216
+ "cookie-prefs"
217
+ ]
218
+ },
219
+ {
220
+ "name": "cookie-prefs/theme/color",
221
+ "path": "dist/theme/color/index.js",
222
+ "limit": "1030 B",
223
+ "gzip": true,
224
+ "ignore": [
225
+ "cookie-prefs"
226
+ ]
132
227
  }
133
228
  ],
134
229
  "peerDependencies": {