@42-central/vite-plugin-theme 0.0.0 → 0.17.1

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
@@ -1,3 +1,153 @@
1
- # @42-central/vite-plugin-theme
1
+ <p align="center">
2
+ <img alt="@42-central/vite-plugin-theme" src="https://shieldcn.dev/header/dots.svg?title=Vite+Plugin+Theme&subtitle=Flash-free+theme+init+for+Vite&logo=data%3Aimage%2Fpng%3Bbase64%2CiVBORw0KGgoAAAANSUhEUgAAAMgAAADIBAMAAABfdrOtAAAAMFBMVEUAAAD%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F87TQQwAAAAD3RSTlMAAw4fKzNGVm%2BMn73c6vz7344aAAACqklEQVR42u3ZMWsUQRjG8ed9jaA2N5fWQswnEMVG1I9gpXZKvsGdnVZ3VpdClBQi2KlgI5b2fgobI3baOXOI3mJgx5Bb8Hb21tkwN2%2BMef%2BQIrs7PPyyaY6DpmmapmmapmmHnUH%2BiDbCMG89vH4xvHC%2BM%2BTqp6APNL%2FxOLzxKLzwlQBGPPr%2BaiPoeQ%2F7hcSzjScNuo30rpzz1ju4%2Bc9es22Hee7Pde%2B929p7cvGa9egWnfhs%2FWKl3zTYzzyxtRsFrvt65YwA7gQxWGxavHBY1nTLYFnc4Y28nGIxbx70sCx%2F%2BiFiI90h222QXnwkHeJaRgQgYAEIWAACFoCABSBgAQhYAAIWgIAFIGABCFgAAhaAgAUgYAEIWAACFoCABSDgdMiZGAScDnkWg4DTIfdcdEQAAhaAgBMh1AECToOgCwScBkEIMS0jKZDdEOLQMXOt9LXsjLC8C%2BHRgQ2O%2FqCun0eGBp2ik7Z5NBUSZu42jirkH4P8lIBsKkQhhwwpJCBjhShEIX%2BDWAHIN4Xov9YRfiMSEF9QP1IKpGqIlUFMC6T8dflWpJvV0Rvh3%2BBLACGqnhyFkNLH2qXgm6Aq%2Bz6ETKjtIzYiebRFrv7rbAiAkbXefWQfodmoGskOAeeFjF01khPiTe4RKsZT5B7pTbzJPULFcA4BC0DAAhCwAAQsAAHng1iTe4SKASEYyQBxJhjJCwELQMACELAABCwAAQtAwAIQcDZIOOJtrCQI1gCgv1rIaGrQkHx8E%2ButPxDEoDHiXt%2BOdedAb2QKNCXUj7SOJAg4%2Bb3HIWCsuGKA7CN%2B4gzC1rDSzKkhsOIR9%2FQd6pFHvdInS3Z20CFGUtSPZZAs8VZAAuiIjuiIjuiIjuiIjhyfEVvLIUN8KQxHtX6QgaZpmqZpmqZpmvbf9xsJbA7rTAka4wAAAABJRU5ErkJggg%3D%3D&mode=dark&font=fira-code">
3
+ </p>
2
4
 
3
- Placeholder that reserves the package name. Install `>=0.17.0`.
5
+ <p align="center">
6
+ <a href="https://www.npmjs.com/package/@42-central/vite-plugin-theme"><img src="https://shieldcn.dev/npm/v/@42-central/vite-plugin-theme.svg" alt="npm version" /></a>
7
+ <a href="https://vite.dev"><img src="https://shieldcn.dev/badge/Vite-7_%7C_8-9135ff.svg?logo=vite" alt="Vite 7 | 8" /></a>
8
+ <img src="https://shieldcn.dev/badge/module-ESM--only-F7DF1E.svg" alt="ESM only" />
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="#install">Install</a> ·
13
+ <a href="#usage">Usage</a> ·
14
+ <a href="#options">Options</a> ·
15
+ <a href="https://42kit.dev/docs/theming"><strong>Theming docs ↗</strong></a>
16
+ </p>
17
+
18
+ ---
19
+
20
+ A Vite plugin that stops
21
+ [`@42-central/ui-react`](https://www.npmjs.com/package/@42-central/ui-react)
22
+ apps from flashing the wrong theme on load. It puts the kit's theme-init script
23
+ at the top of `<head>` in `index.html`, in both `vite dev` and `vite build`.
24
+
25
+ ## Why
26
+
27
+ `useTheme()` stores the visitor's `"light" | "dark" | "system"` choice and
28
+ keeps `data-theme` on `<html>` in sync. React only runs after first paint,
29
+ though. So without help, a dark-mode visitor sees one light frame before the
30
+ hook catches up.
31
+
32
+ In Next.js, `<ThemeScript />` covers that gap from the server render. A Vite
33
+ SPA has no server render, so the script has to sit in `index.html` and block
34
+ parsing. It also can't be `type="module"`, because Vite defers module
35
+ scripts, and the flash comes back. This plugin injects a classic inline
36
+ `<script>` through Vite's `transformIndexHtml` hook, so you never edit the
37
+ HTML by hand.
38
+
39
+ ## Install
40
+
41
+ Install it as a dev dependency, next to the kit:
42
+
43
+ ```bash
44
+ npm install -D @42-central/vite-plugin-theme
45
+ pnpm add -D @42-central/vite-plugin-theme
46
+ yarn add --dev @42-central/vite-plugin-theme
47
+ bun add --dev @42-central/vite-plugin-theme
48
+ ```
49
+
50
+ `vite` 7 or 8 is a peer dependency. The plugin builds its script with
51
+ `@42-central/ui-react`, which it lists as its own dependency. Keep both
52
+ packages on the same version: they are released together.
53
+
54
+ ## Usage
55
+
56
+ ```ts
57
+ // vite.config.ts
58
+ import { defineConfig } from "vite";
59
+ import react from "@vitejs/plugin-react";
60
+ import { themeInitPlugin } from "@42-central/vite-plugin-theme";
61
+
62
+ export default defineConfig({
63
+ plugins: [react(), themeInitPlugin()],
64
+ });
65
+ ```
66
+
67
+ Then read and change the theme from any component with the kit's hook:
68
+
69
+ ```tsx
70
+ import { useTheme } from "@42-central/ui-react";
71
+
72
+ export function ThemeToggle() {
73
+ const { resolvedTheme, setMode } = useTheme();
74
+ return (
75
+ <button onClick={() => setMode(resolvedTheme === "dark" ? "light" : "dark")}>
76
+ Toggle theme
77
+ </button>
78
+ );
79
+ }
80
+ ```
81
+
82
+ ## Options
83
+
84
+ `themeInitPlugin(options?)` takes the same options as the kit's
85
+ `buildThemeInitScript()`, plus `nonce`:
86
+
87
+ | Option | Type | Default | What it does |
88
+ | -------------------- | ---------------------------------------------------- | -------------- | ----------------------------------------------------------------------------------- |
89
+ | `storageKey` | `string` | `"ui-theme"` | `localStorage` key that holds the stored mode. |
90
+ | `defaultColorScheme` | `"light" \| "dark" \| "system"` | `"system"` | Mode used when nothing is stored yet. |
91
+ | `forceColorScheme` | `"light" \| "dark"` | – | Pins the theme and ignores both storage and the OS preference. |
92
+ | `attribute` | `"data-theme" \| "class"`, or an array of them | `"data-theme"` | What to write on `<html>`: the `data-theme` attribute, a `.dark` class, or both. |
93
+ | `nonce` | `string` | – | CSP nonce added to the injected `<script>`. |
94
+
95
+ ### Keep it in sync with `useTheme()`
96
+
97
+ There is no provider holding this configuration, so the script and the hook
98
+ can't share it. Pass `storageKey`, `defaultColorScheme`, `forceColorScheme`
99
+ and `attribute` with the **same values** to the plugin and to every
100
+ `useTheme()` call. If they differ, the script and the hook disagree on first
101
+ load.
102
+
103
+ ```ts
104
+ // vite.config.ts
105
+ themeInitPlugin({ forceColorScheme: "dark", attribute: ["class", "data-theme"] });
106
+ ```
107
+
108
+ ```tsx
109
+ // anywhere in the app
110
+ useTheme({ forceColorScheme: "dark", attribute: ["class", "data-theme"] });
111
+ ```
112
+
113
+ A shared `const THEME_OPTIONS = { … }` imported by both files is the easiest
114
+ way to keep them aligned.
115
+
116
+ ### Content Security Policy
117
+
118
+ If your CSP blocks inline scripts, pass the nonce your server puts in the
119
+ `script-src` directive:
120
+
121
+ ```ts
122
+ themeInitPlugin({ nonce: "{{CSP_NONCE}}" });
123
+ ```
124
+
125
+ The value goes into the built `index.html` verbatim. Use whatever placeholder
126
+ your server or edge function replaces per request.
127
+
128
+ ## What it injects
129
+
130
+ One tag, first in `<head>`:
131
+
132
+ ```html
133
+ <head>
134
+ <script>/* ~600 bytes: read localStorage, resolve "system", set data-theme */</script>
135
+ <!-- the rest of your head -->
136
+ </head>
137
+ ```
138
+
139
+ The script runs once and registers no listeners. Following the OS preference
140
+ live after load is `useTheme()`'s job.
141
+
142
+ ## Not using Vite?
143
+
144
+ The [ui-react README](https://github.com/42staff/kit/blob/main/packages/react/README.md#vite-client-only-spa)
145
+ covers the alternatives: a prebuilt `theme-init.js` you copy into `public/`,
146
+ or pasting the output of `buildThemeInitScript()` by hand. Next.js apps use
147
+ `<ThemeScript />` instead.
148
+
149
+ ## Links
150
+
151
+ - [Theming docs](https://42kit.dev/docs/theming)
152
+ - [`@42-central/ui-react`](https://www.npmjs.com/package/@42-central/ui-react)
153
+ - [Source on GitHub](https://github.com/42staff/kit/tree/main/packages/vite-plugin-theme)
@@ -0,0 +1,21 @@
1
+ import { type BuildThemeInitScriptOptions } from "@42-central/ui-react";
2
+ import type { Plugin } from "vite";
3
+ export interface ThemeInitPluginOptions extends BuildThemeInitScriptOptions {
4
+ /** CSP nonce for the injected `<script>`. */
5
+ nonce?: string;
6
+ }
7
+ /**
8
+ * Injects `@42-central/ui-react`'s blocking anti-FOUC theme-init script as the
9
+ * first tag in `<head>`, at both `vite dev` and `vite build` time — via
10
+ * Vite's `transformIndexHtml` hook, so `index.html` itself never needs
11
+ * manual editing. Must render a plain classic script, not `type="module"`
12
+ * (Vite treats module scripts as deferred, which would reintroduce the
13
+ * flash this exists to prevent) — which is why this goes through the tag
14
+ * descriptor API rather than a hand-authored `<script>` in `index.html`.
15
+ *
16
+ * // vite.config.ts
17
+ * import { themeInitPlugin } from "@42-central/vite-plugin-theme"
18
+ * export default defineConfig({ plugins: [themeInitPlugin()] })
19
+ */
20
+ export declare function themeInitPlugin(options?: ThemeInitPluginOptions): Plugin;
21
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,2BAA2B,EAAwB,MAAM,cAAc,CAAA;AACrF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAElC,MAAM,WAAW,sBAAuB,SAAQ,2BAA2B;IACzE,6CAA6C;IAC7C,KAAK,CAAC,EAAE,MAAM,CAAA;CACf;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,CAAC,OAAO,GAAE,sBAA2B,GAAG,MAAM,CAe5E"}
package/dist/index.js ADDED
@@ -0,0 +1,23 @@
1
+ import { buildThemeInitScript } from '@42-central/ui-react';
2
+
3
+ // src/index.ts
4
+ function themeInitPlugin(options = {}) {
5
+ const { nonce, ...scriptOptions } = options;
6
+ return {
7
+ name: "42-theme-init",
8
+ transformIndexHtml() {
9
+ return [
10
+ {
11
+ tag: "script",
12
+ injectTo: "head-prepend",
13
+ attrs: nonce ? { nonce } : void 0,
14
+ children: buildThemeInitScript(scriptOptions)
15
+ }
16
+ ];
17
+ }
18
+ };
19
+ }
20
+
21
+ export { themeInitPlugin };
22
+ //# sourceMappingURL=index.js.map
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;AAqBO,SAAS,eAAA,CAAgB,OAAA,GAAkC,EAAC,EAAW;AAC5E,EAAA,MAAM,EAAE,KAAA,EAAO,GAAG,aAAA,EAAc,GAAI,OAAA;AACpC,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,eAAA;AAAA,IACN,kBAAA,GAAqB;AACnB,MAAA,OAAO;AAAA,QACL;AAAA,UACE,GAAA,EAAK,QAAA;AAAA,UACL,QAAA,EAAU,cAAA;AAAA,UACV,KAAA,EAAO,KAAA,GAAQ,EAAE,KAAA,EAAM,GAAI,MAAA;AAAA,UAC3B,QAAA,EAAU,qBAAqB,aAAa;AAAA;AAC9C,OACF;AAAA,IACF;AAAA,GACF;AACF","file":"index.js","sourcesContent":["import { type BuildThemeInitScriptOptions, buildThemeInitScript } from \"@42-central/ui-react\"\nimport type { Plugin } from \"vite\"\n\nexport interface ThemeInitPluginOptions extends BuildThemeInitScriptOptions {\n /** CSP nonce for the injected `<script>`. */\n nonce?: string\n}\n\n/**\n * Injects `@42-central/ui-react`'s blocking anti-FOUC theme-init script as the\n * first tag in `<head>`, at both `vite dev` and `vite build` time — via\n * Vite's `transformIndexHtml` hook, so `index.html` itself never needs\n * manual editing. Must render a plain classic script, not `type=\"module\"`\n * (Vite treats module scripts as deferred, which would reintroduce the\n * flash this exists to prevent) — which is why this goes through the tag\n * descriptor API rather than a hand-authored `<script>` in `index.html`.\n *\n * // vite.config.ts\n * import { themeInitPlugin } from \"@42-central/vite-plugin-theme\"\n * export default defineConfig({ plugins: [themeInitPlugin()] })\n */\nexport function themeInitPlugin(options: ThemeInitPluginOptions = {}): Plugin {\n const { nonce, ...scriptOptions } = options\n return {\n name: \"42-theme-init\",\n transformIndexHtml() {\n return [\n {\n tag: \"script\",\n injectTo: \"head-prepend\",\n attrs: nonce ? { nonce } : undefined,\n children: buildThemeInitScript(scriptOptions),\n },\n ]\n },\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@42-central/vite-plugin-theme",
3
- "version": "0.0.0",
4
- "description": "Placeholder that reserves the name for trusted publishing. Real releases start at 0.17.0.",
5
- "license": "UNLICENSED"
3
+ "version": "0.17.1",
4
+ "description": "Vite plugin that injects @42/ui-react's anti-FOUC theme init script into index.html",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "files": [
8
+ "dist",
9
+ "src",
10
+ "README.md"
11
+ ],
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js"
16
+ }
17
+ },
18
+ "scripts": {
19
+ "build": "tsup && tsc -p tsconfig.build.json",
20
+ "dev": "tsup --watch",
21
+ "typecheck": "tsc --noEmit",
22
+ "test": "vitest run",
23
+ "test:watch": "vitest",
24
+ "clean": "rm -rf dist .turbo"
25
+ },
26
+ "peerDependencies": {
27
+ "vite": "^7.0.0 || ^8.0.0"
28
+ },
29
+ "dependencies": {
30
+ "@42-central/ui-react": "0.17.1"
31
+ },
32
+ "devDependencies": {
33
+ "@42/tsconfig": "workspace:*",
34
+ "@42/tsup-config": "workspace:*",
35
+ "jsdom": "^30.0.1",
36
+ "tsup": "^8.5.1",
37
+ "typescript": "catalog:",
38
+ "vite": "^8.3.0",
39
+ "vitest": "^5.0.1"
40
+ }
6
41
  }
@@ -0,0 +1,73 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest"
2
+ import { themeInitPlugin } from "./index"
3
+
4
+ function mockMatchMedia(matches: boolean) {
5
+ Object.defineProperty(window, "matchMedia", {
6
+ writable: true,
7
+ value: vi.fn().mockReturnValue({ matches }),
8
+ })
9
+ }
10
+
11
+ afterEach(() => {
12
+ localStorage.clear()
13
+ document.documentElement.removeAttribute("data-theme")
14
+ })
15
+
16
+ function getInjectedScript(options?: Parameters<typeof themeInitPlugin>[0]) {
17
+ const plugin = themeInitPlugin(options)
18
+ const transform = plugin.transformIndexHtml
19
+ const hook = typeof transform === "function" ? transform : transform?.handler
20
+ if (typeof hook !== "function") throw new Error("expected a transformIndexHtml function")
21
+ const tags = hook.call({} as ThisParameterType<typeof hook>, "", {} as never)
22
+ if (!Array.isArray(tags)) throw new Error("expected an array of tag descriptors")
23
+ const [tag] = tags
24
+ if (!tag) throw new Error("expected at least one tag descriptor")
25
+ return tag
26
+ }
27
+
28
+ describe("themeInitPlugin", () => {
29
+ it("returns a single script tag, prepended to head", () => {
30
+ const tag = getInjectedScript()
31
+ expect(tag.tag).toBe("script")
32
+ expect(tag.injectTo).toBe("head-prepend")
33
+ })
34
+
35
+ it("the injected script applies the persisted mode when executed", () => {
36
+ localStorage.setItem("ui-theme", JSON.stringify("dark"))
37
+ mockMatchMedia(false)
38
+
39
+ const tag = getInjectedScript()
40
+ new Function(tag.children as string)()
41
+
42
+ expect(document.documentElement.getAttribute("data-theme")).toBe("dark")
43
+ })
44
+
45
+ it("forwards forceColorScheme through to the generated script", () => {
46
+ localStorage.setItem("ui-theme", JSON.stringify("dark"))
47
+ mockMatchMedia(true)
48
+
49
+ const tag = getInjectedScript({ forceColorScheme: "light" })
50
+ new Function(tag.children as string)()
51
+
52
+ expect(document.documentElement.getAttribute("data-theme")).toBe("light")
53
+ })
54
+
55
+ it("forwards defaultColorScheme through to the generated script", () => {
56
+ mockMatchMedia(true) // OS prefers dark — should be ignored
57
+
58
+ const tag = getInjectedScript({ defaultColorScheme: "light" })
59
+ new Function(tag.children as string)()
60
+
61
+ expect(document.documentElement.getAttribute("data-theme")).toBe("light")
62
+ })
63
+
64
+ it("sets a CSP nonce attribute when provided", () => {
65
+ const tag = getInjectedScript({ nonce: "abc123" })
66
+ expect(tag.attrs).toEqual({ nonce: "abc123" })
67
+ })
68
+
69
+ it("omits attrs entirely when no nonce is given", () => {
70
+ const tag = getInjectedScript()
71
+ expect(tag.attrs).toBeUndefined()
72
+ })
73
+ })
package/src/index.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { type BuildThemeInitScriptOptions, buildThemeInitScript } from "@42/ui-react"
2
+ import type { Plugin } from "vite"
3
+
4
+ export interface ThemeInitPluginOptions extends BuildThemeInitScriptOptions {
5
+ /** CSP nonce for the injected `<script>`. */
6
+ nonce?: string
7
+ }
8
+
9
+ /**
10
+ * Injects `@42/ui-react`'s blocking anti-FOUC theme-init script as the
11
+ * first tag in `<head>`, at both `vite dev` and `vite build` time — via
12
+ * Vite's `transformIndexHtml` hook, so `index.html` itself never needs
13
+ * manual editing. Must render a plain classic script, not `type="module"`
14
+ * (Vite treats module scripts as deferred, which would reintroduce the
15
+ * flash this exists to prevent) — which is why this goes through the tag
16
+ * descriptor API rather than a hand-authored `<script>` in `index.html`.
17
+ *
18
+ * // vite.config.ts
19
+ * import { themeInitPlugin } from "@42/vite-plugin-theme"
20
+ * export default defineConfig({ plugins: [themeInitPlugin()] })
21
+ */
22
+ export function themeInitPlugin(options: ThemeInitPluginOptions = {}): Plugin {
23
+ const { nonce, ...scriptOptions } = options
24
+ return {
25
+ name: "42-theme-init",
26
+ transformIndexHtml() {
27
+ return [
28
+ {
29
+ tag: "script",
30
+ injectTo: "head-prepend",
31
+ attrs: nonce ? { nonce } : undefined,
32
+ children: buildThemeInitScript(scriptOptions),
33
+ },
34
+ ]
35
+ },
36
+ }
37
+ }