@cyclone-ui/theme-builder 0.0.56 → 0.0.58

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/CHANGELOG.md CHANGED
@@ -2,6 +2,26 @@
2
2
 
3
3
  # Changelog for Cyclone UI - Theme Builder
4
4
 
5
+ ## [0.0.58](https://github.com/storm-software/cyclone-ui/releases/tag/theme-builder%400.0.58) (11/12/2026)
6
+
7
+ ### Updated Dependencies
8
+
9
+ - Updated **tokens** to **v0.3.57**
10
+
11
+ ## [0.0.57](https://github.com/storm-software/cyclone-ui/releases/tag/theme-builder%400.0.57) (11/11/2026)
12
+
13
+ ### Miscellaneous
14
+
15
+ - **theme-builder:** Added missing `tsconfig.json` update ([76875377f](https://github.com/storm-software/cyclone-ui/commit/76875377f))
16
+
17
+ ### Features
18
+
19
+ - **cli:** Update workspace support for using tailwindcss styling for the components library ([527d38a05](https://github.com/storm-software/cyclone-ui/commit/527d38a05))
20
+
21
+ ### Updated Dependencies
22
+
23
+ - Updated **tokens** to **v0.3.56**
24
+
5
25
  ## [0.0.51](https://github.com/storm-software/cyclone-ui/releases/tag/theme-builder%400.0.51) (11/08/2026)
6
26
 
7
27
  ### Features
package/README.md CHANGED
@@ -72,6 +72,8 @@ A package containing the theme building utilities and shared code used by the Cy
72
72
  - A Razorwind generator that wraps the Tamagui generator with Cyclone UI
73
73
  defaults and output fixes
74
74
  - Used by the Cyclone CLI `build` and `build-tokens` commands
75
+ - Builds a Tailwind CSS v4 theme from a Tamagui config, so Tailwind classes use
76
+ Cyclone theme and token names (`@cyclone-ui/theme-builder/tailwind`)
75
77
 
76
78
  ## Installing
77
79
 
@@ -123,6 +125,20 @@ export default defineConfig({
123
125
  See the [package documentation](../../docs/packages/theme-builder.md) for the
124
126
  details of each plugin.
125
127
 
128
+ To write a Tailwind theme for a Tamagui config file, as `@cyclone-ui/vite` and
129
+ `@cyclone-ui/nextjs` do for custom `tokens`:
130
+
131
+ ```ts
132
+ import { buildTailwindThemeCSS } from "@cyclone-ui/theme-builder/tailwind";
133
+
134
+ // Writes .cyclone-ui/tailwind.css; import it before `tailwindcss`.
135
+ await buildTailwindThemeCSS({ configPath: ".cyclone-ui/tamagui.config.ts" });
136
+ ```
137
+
138
+ `@cyclone-ui/tokens/tailwind.css` is generated the same way, by a file
139
+ snapshot in `test/tailwind.spec.ts`. Run `vitest run -u test/tailwind.spec.ts`
140
+ after a token change.
141
+
126
142
  ## Reduced Package Size
127
143
 
128
144
  This project uses [tsdown](https://tsdown.dev/) to package the source code
package/dist/build.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./generate.cjs"),t=require("./preprocessor.cjs");let n=require("@razorwind/core"),r=require("node:fs/promises"),i=require("node:path");async function a({tokens:a,cwd:o=process.cwd(),outputPath:s=`.cyclone-ui/tamagui.config.ts`}){let c=(0,i.resolve)(o),l=await(0,n.resolveConfig)(c,{mode:`production`});if(typeof a==`object`&&!Array.isArray(a)){let e=(0,i.join)((0,i.dirname)((0,i.resolve)(c,s)),`tokens.json`);await(0,r.mkdir)((0,i.dirname)(e),{recursive:!0}),await(0,r.writeFile)(e,JSON.stringify(a),`utf8`),l.tokensPath=e}else l.tokensPath=a;l.tokens=void 0,l.plugins=[t.default(),...l.plugins.filter(e=>!e.generate&&e.name!==`cyclone-ui:tamagui-preprocessor`),e({outputPath:s,animations:!1,importConfig:`@cyclone-ui/tokens/tamagui-defaults`})];let u=await(0,n.prepareSpec)({cwd:c,options:l});if((0,n.isEmptyTokens)(u.tokens))throw Error(`No design tokens found in ${JSON.stringify(l.tokensPath)}.`);return await(0,n.writeGeneratedDocuments)(await(0,n.generatePluginDocuments)(u,l),c),(0,i.resolve)(c,s)}exports.buildTamaguiConfig=a;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./generate.cjs"),t=require("./preprocessor.cjs");let n=require("node:fs/promises"),r=require("node:path"),i=require("@razorwind/core");async function a({tokens:a,cwd:o=process.cwd(),outputPath:s=`.cyclone-ui/tamagui.config.ts`}){let c=(0,r.resolve)(o),l=await(0,i.resolveConfig)(c,{mode:`production`});if(typeof a==`object`&&!Array.isArray(a)){let e=(0,r.join)((0,r.dirname)((0,r.resolve)(c,s)),`tokens.json`);await(0,n.mkdir)((0,r.dirname)(e),{recursive:!0}),await(0,n.writeFile)(e,JSON.stringify(a),`utf8`),l.tokensPath=e}else l.tokensPath=a;l.tokens=void 0,l.plugins=[t.default(),...l.plugins.filter(e=>!e.generate&&e.name!==`cyclone-ui:tamagui-preprocessor`),e({outputPath:s,animations:!1,importConfig:`@cyclone-ui/tokens/tamagui-defaults`})];let u=await(0,i.prepareSpec)({cwd:c,options:l});if((0,i.isEmptyTokens)(u.tokens))throw Error(`No design tokens found in ${JSON.stringify(l.tokensPath)}.`);return await(0,i.writeGeneratedDocuments)(await(0,i.generatePluginDocuments)(u,l),c),(0,r.resolve)(c,s)}exports.buildTamaguiConfig=a;
package/dist/build.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import e from"./generate.mjs";import t from"./preprocessor.mjs";import{generatePluginDocuments as n,isEmptyTokens as r,prepareSpec as i,resolveConfig as a,writeGeneratedDocuments as o}from"@razorwind/core";import{mkdir as s,writeFile as c}from"node:fs/promises";import{dirname as l,join as u,resolve as d}from"node:path";async function f({tokens:f,cwd:p=process.cwd(),outputPath:m=`.cyclone-ui/tamagui.config.ts`}){let h=d(p),g=await a(h,{mode:`production`});if(typeof f==`object`&&!Array.isArray(f)){let e=u(l(d(h,m)),`tokens.json`);await s(l(e),{recursive:!0}),await c(e,JSON.stringify(f),`utf8`),g.tokensPath=e}else g.tokensPath=f;g.tokens=void 0,g.plugins=[t(),...g.plugins.filter(e=>!e.generate&&e.name!==`cyclone-ui:tamagui-preprocessor`),e({outputPath:m,animations:!1,importConfig:`@cyclone-ui/tokens/tamagui-defaults`})];let _=await i({cwd:h,options:g});if(r(_.tokens))throw Error(`No design tokens found in ${JSON.stringify(g.tokensPath)}.`);return await o(await n(_,g),h),d(h,m)}export{f as buildTamaguiConfig};
1
+ import e from"./generate.mjs";import t from"./preprocessor.mjs";import{mkdir as n,writeFile as r}from"node:fs/promises";import{dirname as i,join as a,resolve as o}from"node:path";import{generatePluginDocuments as s,isEmptyTokens as c,prepareSpec as l,resolveConfig as u,writeGeneratedDocuments as d}from"@razorwind/core";async function f({tokens:f,cwd:p=process.cwd(),outputPath:m=`.cyclone-ui/tamagui.config.ts`}){let h=o(p),g=await u(h,{mode:`production`});if(typeof f==`object`&&!Array.isArray(f)){let e=a(i(o(h,m)),`tokens.json`);await n(i(e),{recursive:!0}),await r(e,JSON.stringify(f),`utf8`),g.tokensPath=e}else g.tokensPath=f;g.tokens=void 0,g.plugins=[t(),...g.plugins.filter(e=>!e.generate&&e.name!==`cyclone-ui:tamagui-preprocessor`),e({outputPath:m,animations:!1,importConfig:`@cyclone-ui/tokens/tamagui-defaults`})];let _=await l({cwd:h,options:g});if(c(_.tokens))throw Error(`No design tokens found in ${JSON.stringify(g.tokensPath)}.`);return await d(await s(_,g),h),o(h,m)}export{f as buildTamaguiConfig};
2
2
  //# sourceMappingURL=build.mjs.map
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./generate.cjs"),t=require("./preprocessor.cjs"),n=require("./build.cjs");exports.buildTamaguiConfig=n.buildTamaguiConfig,exports.generate=e,exports.preprocessor=t.default;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./generate.cjs"),t=require("./preprocessor.cjs"),n=require("./build.cjs"),r=require("./tailwind.cjs");exports.TAILWIND_LAYER_ORDER=r.TAILWIND_LAYER_ORDER,exports.buildTailwindThemeCSS=r.buildTailwindThemeCSS,exports.buildTamaguiConfig=n.buildTamaguiConfig,exports.createTailwindThemeCSS=r.createTailwindThemeCSS,exports.generate=e,exports.preprocessor=t.default,exports.readTailwindThemeNames=r.readTailwindThemeNames;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,5 @@
1
1
  import _default from "./generate.cjs";
2
2
  import _default$1 from "./preprocessor.cjs";
3
3
  import { BuildTamaguiConfigOptions, buildTamaguiConfig } from "./build.cjs";
4
- export { BuildTamaguiConfigOptions, buildTamaguiConfig, _default as generate, _default$1 as preprocessor };
4
+ import { BuildTailwindThemeOptions, TAILWIND_LAYER_ORDER, TailwindThemeOptions, TailwindThemeSource, buildTailwindThemeCSS, createTailwindThemeCSS, readTailwindThemeNames } from "./tailwind.cjs";
5
+ export { BuildTailwindThemeOptions, BuildTamaguiConfigOptions, TAILWIND_LAYER_ORDER, TailwindThemeOptions, TailwindThemeSource, buildTailwindThemeCSS, buildTamaguiConfig, createTailwindThemeCSS, _default as generate, _default$1 as preprocessor, readTailwindThemeNames };
package/dist/index.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  import _default from "./generate.mjs";
2
2
  import _default$1 from "./preprocessor.mjs";
3
3
  import { BuildTamaguiConfigOptions, buildTamaguiConfig } from "./build.mjs";
4
- export { BuildTamaguiConfigOptions, buildTamaguiConfig, _default as generate, _default$1 as preprocessor };
4
+ import { BuildTailwindThemeOptions, TAILWIND_LAYER_ORDER, TailwindThemeOptions, TailwindThemeSource, buildTailwindThemeCSS, createTailwindThemeCSS, readTailwindThemeNames } from "./tailwind.mjs";
5
+ export { BuildTailwindThemeOptions, BuildTamaguiConfigOptions, TAILWIND_LAYER_ORDER, TailwindThemeOptions, TailwindThemeSource, buildTailwindThemeCSS, buildTamaguiConfig, createTailwindThemeCSS, _default as generate, _default$1 as preprocessor, readTailwindThemeNames };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import e from"./generate.mjs";import t from"./preprocessor.mjs";import{buildTamaguiConfig as n}from"./build.mjs";export{n as buildTamaguiConfig,e as generate,t as preprocessor};
1
+ import e from"./generate.mjs";import t from"./preprocessor.mjs";import{buildTamaguiConfig as n}from"./build.mjs";import{TAILWIND_LAYER_ORDER as r,buildTailwindThemeCSS as i,createTailwindThemeCSS as a,readTailwindThemeNames as o}from"./tailwind.mjs";export{r as TAILWIND_LAYER_ORDER,i as buildTailwindThemeCSS,n as buildTamaguiConfig,a as createTailwindThemeCSS,e as generate,t as preprocessor,o as readTailwindThemeNames};
@@ -0,0 +1,20 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("node:fs/promises"),t=require("node:module"),n=require("node:path"),r=require("node:url");const i=`@layer theme, base, tamagui, components, utilities;`,a={space:[`padding`,`margin`,`gap`,`inset`,`translate`,`space`,`scroll-margin`,`scroll-padding`],size:[`width`,`min-width`,`max-width`,`height`,`size`],radius:[`radius`],fontSize:[`text`],fontWeight:[`font-weight`],blur:[`blur`],shadow:[`shadow`],insetShadow:[`inset-shadow`],dropShadow:[`drop-shadow`],textShadow:[`text-shadow`],zIndex:[`z-index`]},o={width:[`container`],"min-width":[`container`],"max-width":[`container`]},s=/* @__PURE__ */ new Set([`auto`,`current`,`dvh`,`dvw`,`fit`,`full`,`inherit`,`lvh`,`lvw`,`max`,`min`,`none`,`px`,`screen`,`svh`,`svw`,`transparent`]),c=e=>/^[\w-]+$/u.test(e)&&!/^\d+$/u.test(e)&&!s.has(e),l=({variable:e,name:t})=>e||`var(--${process.env.TAMAGUI_CSS_VARIABLE_PREFIX??``}${t})`;function u(e,{reserved:t=[]}={}){let n=new Set(t),r=[],s=(e,t)=>{let i=t.filter(([e])=>!n.has(e)).map(([e,t])=>(n.add(e),` ${e}: ${t};`));i.length>0&&r.push(` /* ${e} */\n${i.join(`
2
+ `)}`)},u=/* @__PURE__ */ new Map;for(let t of Object.values(e.themes))for(let[e,n]of Object.entries(t))!u.has(e)&&c(e)&&u.set(e,n);for(let[t,n]of Object.entries(e.tokens.color??{}))!u.has(t)&&c(t)&&u.set(t,n);s(`Colors: theme values, resolved where the class is used`,[...u].map(([e,t])=>[`--color-${e}`,l(t)]));for(let[t,r]of Object.entries(a)){let i=Object.entries(e.tokens[t]??{}).filter(([e])=>c(e));for(let e of r)s(`${e}: ${t} tokens`,i.filter(([t])=>!o[e]?.some(e=>n.has(`--${e}-${t}`))).map(([t,n])=>[`--${e}-${t}`,l(n)]))}return s(`Font families`,Object.entries(e.fonts??{}).filter(e=>c(e[0])&&typeof e[1].family==`string`).map(([e,t])=>[`--font-${e}`,t.family])),s(`Breakpoints: min-width media queries`,Object.entries(e.media??{}).filter(e=>c(e[0])&&Object.keys(e[1]).length===1&&typeof e[1].minWidth==`number`).map(([e,t])=>[`--breakpoint-${e}`,`${t.minWidth/16}rem`])),`/* Generated by @cyclone-ui/theme-builder from the Tamagui config. Do not edit by hand.
3
+ *
4
+ * Import it before Tailwind so the layer order comes first:
5
+ *
6
+ * @import "@cyclone-ui/tokens/tailwind.css";
7
+ * @import "tailwindcss";
8
+ */
9
+
10
+ ${i}
11
+
12
+ @theme inline {
13
+ ${r.join(`
14
+
15
+ `)}
16
+ }
17
+
18
+ /* Tamagui puts \`t_dark\` on <html> (and on dark <Theme> regions). */
19
+ @custom-variant dark (&:where(.t_dark, .t_dark *));
20
+ `}async function d(r=process.cwd()){let i;try{i=(0,t.createRequire)((0,n.join)((0,n.resolve)(r),`package.json`)).resolve(`tailwindcss/theme.css`)}catch{throw Error(`Cyclone UI's Tailwind theme needs tailwindcss v4, which isn't installed in ${(0,n.resolve)(r)}.`)}let a=await(0,e.readFile)(i,`utf8`);return new Set(Array.from(a.matchAll(/(--[\w-]+)\s*:/gu),e=>e[1]))}async function f({configPath:t,cwd:i=process.cwd(),outputPath:a=`.cyclone-ui/tailwind.css`}){let o=(0,n.resolve)(i),s=process.env.TAMAGUI_TARGET;process.env.TAMAGUI_TARGET=`web`;let c;try{c=await import(`${(0,r.pathToFileURL)((0,n.resolve)(o,t)).href}?t=${Date.now()}`)}catch(e){throw e.code===`ERR_UNKNOWN_FILE_EXTENSION`?Error(`Loading ${t} needs Node.js 22.18 or later, which runs TypeScript directly.`,{cause:e}):e}finally{s===void 0?delete process.env.TAMAGUI_TARGET:process.env.TAMAGUI_TARGET=s}let l=c.config??c.default;if(!l?.themes||!l.tokens)throw Error(`${t} doesn't export a Tamagui config.`);let f=(0,n.resolve)(o,a);return await(0,e.mkdir)((0,n.dirname)(f),{recursive:!0}),await(0,e.writeFile)(f,u(l,{reserved:await d(o)}),`utf8`),f}exports.TAILWIND_LAYER_ORDER=i,exports.buildTailwindThemeCSS=f,exports.createTailwindThemeCSS=u,exports.readTailwindThemeNames=d;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The cascade layer order a Tailwind app needs: Tamagui's CSS (wrapped in
3
+ * `@layer tamagui` by `TAMAGUI_CSS_LAYER`) above Tailwind's preflight
4
+ * (`base`), and Tailwind utilities above Tamagui.
5
+ */
6
+ declare const TAILWIND_LAYER_ORDER = "@layer theme, base, tamagui, components, utilities;";
7
+ /** A Tamagui token or theme value, as `createTamagui` returns it. */
8
+ interface TamaguiVariable {
9
+ name: string;
10
+ val: unknown;
11
+ /** `var(--name)`; only set when the config was evaluated for web. */
12
+ variable?: string;
13
+ }
14
+ /** The parts of a created Tamagui config the Tailwind theme is built from. */
15
+ interface TailwindThemeSource {
16
+ tokens: Record<string, Record<string, TamaguiVariable>>;
17
+ themes: Record<string, Record<string, TamaguiVariable>>;
18
+ fonts?: Record<string, {
19
+ family?: unknown;
20
+ }>;
21
+ media?: Record<string, Record<string, unknown>>;
22
+ }
23
+ interface TailwindThemeOptions {
24
+ /**
25
+ * Theme variables Tailwind already defines (`--container-lg`,
26
+ * `--text-lg`, …). Cyclone names that would change the meaning of a
27
+ * Tailwind class are left out.
28
+ *
29
+ * @defaultValue none
30
+ */
31
+ reserved?: Iterable<string>;
32
+ }
33
+ /**
34
+ * Build a Tailwind v4 stylesheet that maps Cyclone UI themes and tokens onto
35
+ * Tailwind's theme, so app classes use the same names as `@tamagui/tailwind`.
36
+ *
37
+ * @remarks
38
+ * The output contains:
39
+ * - The cascade layer order ({@link TAILWIND_LAYER_ORDER}).
40
+ * - An `@theme inline` block. Colors point at Tamagui theme variables
41
+ * (`--color-primary: var(--primary)`) and resolve where the class is used,
42
+ * so they follow light/dark and `<Theme>` sub-themes. Tokens point at
43
+ * Tamagui token variables. Breakpoints and font families are literal.
44
+ * - A `dark` variant that follows Tamagui's `t_dark` theme class instead of
45
+ * the operating system preference.
46
+ *
47
+ * Names in `options.reserved` are skipped, so standard Tailwind classes keep
48
+ * their meaning.
49
+ *
50
+ * @param config - A Tamagui config created with `createTamagui`, evaluated
51
+ * with `TAMAGUI_TARGET=web`.
52
+ * @param options - Tailwind's own theme variables to leave alone.
53
+ * @returns The stylesheet to import before `tailwindcss`.
54
+ */
55
+ declare function createTailwindThemeCSS(config: TailwindThemeSource, { reserved }?: TailwindThemeOptions): string;
56
+ /**
57
+ * Read the theme variable names Tailwind defines by default, from the
58
+ * `tailwindcss` package installed in `cwd`.
59
+ *
60
+ * @param cwd - The project root that depends on `tailwindcss`.
61
+ * @returns Names such as `--container-lg` and `--color-black`.
62
+ */
63
+ declare function readTailwindThemeNames(cwd?: string): Promise<Set<string>>;
64
+ interface BuildTailwindThemeOptions {
65
+ /** The Tamagui config file, such as the one `buildTamaguiConfig` writes. */
66
+ configPath: string;
67
+ /**
68
+ * The project root, which must depend on `tailwindcss`.
69
+ *
70
+ * @defaultValue `process.cwd()`
71
+ */
72
+ cwd?: string;
73
+ /**
74
+ * The generated stylesheet, relative to `cwd`.
75
+ *
76
+ * @defaultValue `".cyclone-ui/tailwind.css"`
77
+ */
78
+ outputPath?: string;
79
+ }
80
+ /**
81
+ * Write the Tailwind theme stylesheet ({@link createTailwindThemeCSS}) for a
82
+ * Tamagui config file.
83
+ *
84
+ * @remarks
85
+ * Node.js loads the config directly, so a TypeScript config needs Node.js
86
+ * 22.18 or later (type stripping).
87
+ *
88
+ * @returns The absolute path of the generated stylesheet.
89
+ */
90
+ declare function buildTailwindThemeCSS({ configPath, cwd, outputPath }: BuildTailwindThemeOptions): Promise<string>;
91
+ export { BuildTailwindThemeOptions, TAILWIND_LAYER_ORDER, TailwindThemeOptions, TailwindThemeSource, buildTailwindThemeCSS, createTailwindThemeCSS, readTailwindThemeNames };
92
+ //# sourceMappingURL=tailwind.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tailwind.d.cts","names":[],"sources":["../src/tailwind.ts"],"mappings":";;;;;cA4Ba;;UAIH;EACR;EACA;;EAEA;;;UAIe;EACf,QAAQ,eAAe,eAAe;EACtC,QAAQ,eAAe,eAAe;EACtC,QAAQ;IAAiB;;EACzB,QAAQ,eAAe;;UAGR;;;;;;;;EAQf,WAAW;;;;;;;;;;;;;;;;;;;;;;;;iBA4FG,uBACd,QAAQ,uBACN,aAAiB;;;;;;;;iBAuGC,uBACpB,eACC,QAAQ;UAmBM;;EAEf;;;;;;EAOA;;;;;;EAOA;;;;;;;;;;;;iBAaoB,wBACpB,YACA,KACA,cACC,4BAA4B"}
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The cascade layer order a Tailwind app needs: Tamagui's CSS (wrapped in
3
+ * `@layer tamagui` by `TAMAGUI_CSS_LAYER`) above Tailwind's preflight
4
+ * (`base`), and Tailwind utilities above Tamagui.
5
+ */
6
+ declare const TAILWIND_LAYER_ORDER = "@layer theme, base, tamagui, components, utilities;";
7
+ /** A Tamagui token or theme value, as `createTamagui` returns it. */
8
+ interface TamaguiVariable {
9
+ name: string;
10
+ val: unknown;
11
+ /** `var(--name)`; only set when the config was evaluated for web. */
12
+ variable?: string;
13
+ }
14
+ /** The parts of a created Tamagui config the Tailwind theme is built from. */
15
+ interface TailwindThemeSource {
16
+ tokens: Record<string, Record<string, TamaguiVariable>>;
17
+ themes: Record<string, Record<string, TamaguiVariable>>;
18
+ fonts?: Record<string, {
19
+ family?: unknown;
20
+ }>;
21
+ media?: Record<string, Record<string, unknown>>;
22
+ }
23
+ interface TailwindThemeOptions {
24
+ /**
25
+ * Theme variables Tailwind already defines (`--container-lg`,
26
+ * `--text-lg`, …). Cyclone names that would change the meaning of a
27
+ * Tailwind class are left out.
28
+ *
29
+ * @defaultValue none
30
+ */
31
+ reserved?: Iterable<string>;
32
+ }
33
+ /**
34
+ * Build a Tailwind v4 stylesheet that maps Cyclone UI themes and tokens onto
35
+ * Tailwind's theme, so app classes use the same names as `@tamagui/tailwind`.
36
+ *
37
+ * @remarks
38
+ * The output contains:
39
+ * - The cascade layer order ({@link TAILWIND_LAYER_ORDER}).
40
+ * - An `@theme inline` block. Colors point at Tamagui theme variables
41
+ * (`--color-primary: var(--primary)`) and resolve where the class is used,
42
+ * so they follow light/dark and `<Theme>` sub-themes. Tokens point at
43
+ * Tamagui token variables. Breakpoints and font families are literal.
44
+ * - A `dark` variant that follows Tamagui's `t_dark` theme class instead of
45
+ * the operating system preference.
46
+ *
47
+ * Names in `options.reserved` are skipped, so standard Tailwind classes keep
48
+ * their meaning.
49
+ *
50
+ * @param config - A Tamagui config created with `createTamagui`, evaluated
51
+ * with `TAMAGUI_TARGET=web`.
52
+ * @param options - Tailwind's own theme variables to leave alone.
53
+ * @returns The stylesheet to import before `tailwindcss`.
54
+ */
55
+ declare function createTailwindThemeCSS(config: TailwindThemeSource, { reserved }?: TailwindThemeOptions): string;
56
+ /**
57
+ * Read the theme variable names Tailwind defines by default, from the
58
+ * `tailwindcss` package installed in `cwd`.
59
+ *
60
+ * @param cwd - The project root that depends on `tailwindcss`.
61
+ * @returns Names such as `--container-lg` and `--color-black`.
62
+ */
63
+ declare function readTailwindThemeNames(cwd?: string): Promise<Set<string>>;
64
+ interface BuildTailwindThemeOptions {
65
+ /** The Tamagui config file, such as the one `buildTamaguiConfig` writes. */
66
+ configPath: string;
67
+ /**
68
+ * The project root, which must depend on `tailwindcss`.
69
+ *
70
+ * @defaultValue `process.cwd()`
71
+ */
72
+ cwd?: string;
73
+ /**
74
+ * The generated stylesheet, relative to `cwd`.
75
+ *
76
+ * @defaultValue `".cyclone-ui/tailwind.css"`
77
+ */
78
+ outputPath?: string;
79
+ }
80
+ /**
81
+ * Write the Tailwind theme stylesheet ({@link createTailwindThemeCSS}) for a
82
+ * Tamagui config file.
83
+ *
84
+ * @remarks
85
+ * Node.js loads the config directly, so a TypeScript config needs Node.js
86
+ * 22.18 or later (type stripping).
87
+ *
88
+ * @returns The absolute path of the generated stylesheet.
89
+ */
90
+ declare function buildTailwindThemeCSS({ configPath, cwd, outputPath }: BuildTailwindThemeOptions): Promise<string>;
91
+ export { BuildTailwindThemeOptions, TAILWIND_LAYER_ORDER, TailwindThemeOptions, TailwindThemeSource, buildTailwindThemeCSS, createTailwindThemeCSS, readTailwindThemeNames };
92
+ //# sourceMappingURL=tailwind.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tailwind.d.mts","names":[],"sources":["../src/tailwind.ts"],"mappings":""}
@@ -0,0 +1,21 @@
1
+ import{mkdir as e,readFile as t,writeFile as n}from"node:fs/promises";import{createRequire as r}from"node:module";import{dirname as i,join as a,resolve as o}from"node:path";import{pathToFileURL as s}from"node:url";const c=`@layer theme, base, tamagui, components, utilities;`,l={space:[`padding`,`margin`,`gap`,`inset`,`translate`,`space`,`scroll-margin`,`scroll-padding`],size:[`width`,`min-width`,`max-width`,`height`,`size`],radius:[`radius`],fontSize:[`text`],fontWeight:[`font-weight`],blur:[`blur`],shadow:[`shadow`],insetShadow:[`inset-shadow`],dropShadow:[`drop-shadow`],textShadow:[`text-shadow`],zIndex:[`z-index`]},u={width:[`container`],"min-width":[`container`],"max-width":[`container`]},d=/* @__PURE__ */ new Set([`auto`,`current`,`dvh`,`dvw`,`fit`,`full`,`inherit`,`lvh`,`lvw`,`max`,`min`,`none`,`px`,`screen`,`svh`,`svw`,`transparent`]),f=e=>/^[\w-]+$/u.test(e)&&!/^\d+$/u.test(e)&&!d.has(e),p=({variable:e,name:t})=>e||`var(--${process.env.TAMAGUI_CSS_VARIABLE_PREFIX??``}${t})`;function m(e,{reserved:t=[]}={}){let n=new Set(t),r=[],i=(e,t)=>{let i=t.filter(([e])=>!n.has(e)).map(([e,t])=>(n.add(e),` ${e}: ${t};`));i.length>0&&r.push(` /* ${e} */\n${i.join(`
2
+ `)}`)},a=/* @__PURE__ */ new Map;for(let t of Object.values(e.themes))for(let[e,n]of Object.entries(t))!a.has(e)&&f(e)&&a.set(e,n);for(let[t,n]of Object.entries(e.tokens.color??{}))!a.has(t)&&f(t)&&a.set(t,n);i(`Colors: theme values, resolved where the class is used`,[...a].map(([e,t])=>[`--color-${e}`,p(t)]));for(let[t,r]of Object.entries(l)){let a=Object.entries(e.tokens[t]??{}).filter(([e])=>f(e));for(let e of r)i(`${e}: ${t} tokens`,a.filter(([t])=>!u[e]?.some(e=>n.has(`--${e}-${t}`))).map(([t,n])=>[`--${e}-${t}`,p(n)]))}return i(`Font families`,Object.entries(e.fonts??{}).filter(e=>f(e[0])&&typeof e[1].family==`string`).map(([e,t])=>[`--font-${e}`,t.family])),i(`Breakpoints: min-width media queries`,Object.entries(e.media??{}).filter(e=>f(e[0])&&Object.keys(e[1]).length===1&&typeof e[1].minWidth==`number`).map(([e,t])=>[`--breakpoint-${e}`,`${t.minWidth/16}rem`])),`/* Generated by @cyclone-ui/theme-builder from the Tamagui config. Do not edit by hand.
3
+ *
4
+ * Import it before Tailwind so the layer order comes first:
5
+ *
6
+ * @import "@cyclone-ui/tokens/tailwind.css";
7
+ * @import "tailwindcss";
8
+ */
9
+
10
+ ${c}
11
+
12
+ @theme inline {
13
+ ${r.join(`
14
+
15
+ `)}
16
+ }
17
+
18
+ /* Tamagui puts \`t_dark\` on <html> (and on dark <Theme> regions). */
19
+ @custom-variant dark (&:where(.t_dark, .t_dark *));
20
+ `}async function h(e=process.cwd()){let n;try{n=r(a(o(e),`package.json`)).resolve(`tailwindcss/theme.css`)}catch{throw Error(`Cyclone UI's Tailwind theme needs tailwindcss v4, which isn't installed in ${o(e)}.`)}let i=await t(n,`utf8`);return new Set(Array.from(i.matchAll(/(--[\w-]+)\s*:/gu),e=>e[1]))}async function g({configPath:t,cwd:r=process.cwd(),outputPath:a=`.cyclone-ui/tailwind.css`}){let c=o(r),l=process.env.TAMAGUI_TARGET;process.env.TAMAGUI_TARGET=`web`;let u;try{u=await import(`${s(o(c,t)).href}?t=${Date.now()}`)}catch(e){throw e.code===`ERR_UNKNOWN_FILE_EXTENSION`?Error(`Loading ${t} needs Node.js 22.18 or later, which runs TypeScript directly.`,{cause:e}):e}finally{l===void 0?delete process.env.TAMAGUI_TARGET:process.env.TAMAGUI_TARGET=l}let d=u.config??u.default;if(!d?.themes||!d.tokens)throw Error(`${t} doesn't export a Tamagui config.`);let f=o(c,a);return await e(i(f),{recursive:!0}),await n(f,m(d,{reserved:await h(c)}),`utf8`),f}export{c as TAILWIND_LAYER_ORDER,g as buildTailwindThemeCSS,m as createTailwindThemeCSS,h as readTailwindThemeNames};
21
+ //# sourceMappingURL=tailwind.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tailwind.mjs","names":["TAILWIND_LAYER_ORDER","TOKEN_NAMESPACES","FALLBACK_NAMESPACES","TAILWIND_KEYWORDS","isThemeKey","key","cssVariable","variable","name","createTailwindThemeCSS","taken","reserved","sections","section","lines","entries","value","title","themeColors","theme","config","category","namespaces","tokens","namespace","fallback","entry","font","query","readTailwindThemeNames","themePath","createRequire","join","resolve","cwd","css","readFile","match","buildTailwindThemeCSS","root","previousTarget","module","pathToFileURL","configPath","error","outputFile","outputPath","mkdir","dirname","writeFile"],"sources":[],"mappings":""}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cyclone-ui/theme-builder",
3
- "version": "0.0.56",
3
+ "version": "0.0.58",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -68,6 +68,20 @@
68
68
  "types": "./dist/preprocessor.d.mts",
69
69
  "default": "./dist/preprocessor.mjs"
70
70
  }
71
+ },
72
+ "./tailwind": {
73
+ "require": {
74
+ "types": "./dist/tailwind.d.cts",
75
+ "default": "./dist/tailwind.cjs"
76
+ },
77
+ "import": {
78
+ "types": "./dist/tailwind.d.mts",
79
+ "default": "./dist/tailwind.mjs"
80
+ },
81
+ "default": {
82
+ "types": "./dist/tailwind.d.mts",
83
+ "default": "./dist/tailwind.mjs"
84
+ }
71
85
  }
72
86
  },
73
87
  "main": "./dist/index.cjs",
@@ -81,6 +95,7 @@
81
95
  "devDependencies": {
82
96
  "@powerlines/plugin-tsdown": "^0.1.620",
83
97
  "@types/node": "^25.9.9",
84
- "powerlines": "^0.47.219"
98
+ "powerlines": "^0.47.219",
99
+ "tailwindcss": "4.3.0"
85
100
  }
86
101
  }
package/src/index.ts CHANGED
@@ -20,4 +20,5 @@ import generate from "./generate";
20
20
  import preprocessor from "./preprocessor";
21
21
 
22
22
  export * from "./build";
23
+ export * from "./tailwind";
23
24
  export { generate, preprocessor };
@@ -0,0 +1,347 @@
1
+ /* -------------------------------------------------------------------
2
+
3
+ 🗲 Storm Software - Cyclone UI
4
+
5
+ This code was released as part of the Cyclone UI project. Cyclone UI
6
+ is maintained by Storm Software under the Apache-2.0 license, and is
7
+ free for commercial and private use. For more information, please visit
8
+ our licensing page at https://stormsoftware.com/licenses/projects/cyclone-ui.
9
+
10
+ Website: https://stormsoftware.com
11
+ Repository: https://github.com/storm-software/cyclone-ui
12
+ Documentation: https://docs.stormsoftware.com/projects/cyclone-ui
13
+ Contact: https://stormsoftware.com/contact
14
+
15
+ SPDX-License-Identifier: Apache-2.0
16
+
17
+ ------------------------------------------------------------------- */
18
+
19
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
20
+ import { createRequire } from "node:module";
21
+ import { dirname, join, resolve } from "node:path";
22
+ import { pathToFileURL } from "node:url";
23
+
24
+ /**
25
+ * The cascade layer order a Tailwind app needs: Tamagui's CSS (wrapped in
26
+ * `@layer tamagui` by `TAMAGUI_CSS_LAYER`) above Tailwind's preflight
27
+ * (`base`), and Tailwind utilities above Tamagui.
28
+ */
29
+ export const TAILWIND_LAYER_ORDER =
30
+ "@layer theme, base, tamagui, components, utilities;";
31
+
32
+ /** A Tamagui token or theme value, as `createTamagui` returns it. */
33
+ interface TamaguiVariable {
34
+ name: string;
35
+ val: unknown;
36
+ /** `var(--name)`; only set when the config was evaluated for web. */
37
+ variable?: string;
38
+ }
39
+
40
+ /** The parts of a created Tamagui config the Tailwind theme is built from. */
41
+ export interface TailwindThemeSource {
42
+ tokens: Record<string, Record<string, TamaguiVariable>>;
43
+ themes: Record<string, Record<string, TamaguiVariable>>;
44
+ fonts?: Record<string, { family?: unknown }>;
45
+ media?: Record<string, Record<string, unknown>>;
46
+ }
47
+
48
+ export interface TailwindThemeOptions {
49
+ /**
50
+ * Theme variables Tailwind already defines (`--container-lg`,
51
+ * `--text-lg`, …). Cyclone names that would change the meaning of a
52
+ * Tailwind class are left out.
53
+ *
54
+ * @defaultValue none
55
+ */
56
+ reserved?: Iterable<string>;
57
+ }
58
+
59
+ // Tailwind namespaces fed by each Tamagui token category, matching how
60
+ // `@tamagui/tailwind` reads the same classes: spacing utilities use `space`
61
+ // tokens, sizing utilities use `size` tokens. Using each utility's own
62
+ // namespace (not `--spacing-*`) keeps `max-w-lg` and `w-lg` on Tailwind's
63
+ // container scale.
64
+ const TOKEN_NAMESPACES: Record<string, string[]> = {
65
+ space: [
66
+ "padding",
67
+ "margin",
68
+ "gap",
69
+ "inset",
70
+ "translate",
71
+ "space",
72
+ "scroll-margin",
73
+ "scroll-padding"
74
+ ],
75
+ size: ["width", "min-width", "max-width", "height", "size"],
76
+ radius: ["radius"],
77
+ fontSize: ["text"],
78
+ fontWeight: ["font-weight"],
79
+ blur: ["blur"],
80
+ shadow: ["shadow"],
81
+ insetShadow: ["inset-shadow"],
82
+ dropShadow: ["drop-shadow"],
83
+ textShadow: ["text-shadow"],
84
+ zIndex: ["z-index"]
85
+ };
86
+
87
+ // Namespaces Tailwind falls back to for a utility (`w-lg` reads `--width-lg`,
88
+ // then `--spacing-lg`, then `--container-lg`).
89
+ const FALLBACK_NAMESPACES: Record<string, string[]> = {
90
+ width: ["container"],
91
+ "min-width": ["container"],
92
+ "max-width": ["container"]
93
+ };
94
+
95
+ // Keywords Tailwind handles itself (`rounded-full`, `w-screen`, `bg-current`)
96
+ // rather than through the theme.
97
+ const TAILWIND_KEYWORDS = new Set([
98
+ "auto",
99
+ "current",
100
+ "dvh",
101
+ "dvw",
102
+ "fit",
103
+ "full",
104
+ "inherit",
105
+ "lvh",
106
+ "lvw",
107
+ "max",
108
+ "min",
109
+ "none",
110
+ "px",
111
+ "screen",
112
+ "svh",
113
+ "svw",
114
+ "transparent"
115
+ ]);
116
+
117
+ // Tailwind reads numeric keys as values (`z-10` is `z-index: 10`), so a
118
+ // numeric Cyclone key would change those classes. Other keys must be valid
119
+ // in a custom property name without escaping.
120
+ const isThemeKey = (key: string) =>
121
+ /^[\w-]+$/u.test(key) && !/^\d+$/u.test(key) && !TAILWIND_KEYWORDS.has(key);
122
+
123
+ const cssVariable = ({ variable, name }: TamaguiVariable) =>
124
+ variable || `var(--${process.env.TAMAGUI_CSS_VARIABLE_PREFIX ?? ""}${name})`;
125
+
126
+ /**
127
+ * Build a Tailwind v4 stylesheet that maps Cyclone UI themes and tokens onto
128
+ * Tailwind's theme, so app classes use the same names as `@tamagui/tailwind`.
129
+ *
130
+ * @remarks
131
+ * The output contains:
132
+ * - The cascade layer order ({@link TAILWIND_LAYER_ORDER}).
133
+ * - An `@theme inline` block. Colors point at Tamagui theme variables
134
+ * (`--color-primary: var(--primary)`) and resolve where the class is used,
135
+ * so they follow light/dark and `<Theme>` sub-themes. Tokens point at
136
+ * Tamagui token variables. Breakpoints and font families are literal.
137
+ * - A `dark` variant that follows Tamagui's `t_dark` theme class instead of
138
+ * the operating system preference.
139
+ *
140
+ * Names in `options.reserved` are skipped, so standard Tailwind classes keep
141
+ * their meaning.
142
+ *
143
+ * @param config - A Tamagui config created with `createTamagui`, evaluated
144
+ * with `TAMAGUI_TARGET=web`.
145
+ * @param options - Tailwind's own theme variables to leave alone.
146
+ * @returns The stylesheet to import before `tailwindcss`.
147
+ */
148
+ export function createTailwindThemeCSS(
149
+ config: TailwindThemeSource,
150
+ { reserved = [] }: TailwindThemeOptions = {}
151
+ ): string {
152
+ const taken = new Set(reserved);
153
+ const sections: string[] = [];
154
+ const section = (title: string, entries: [string, string][]) => {
155
+ const lines = entries
156
+ .filter(([name]) => !taken.has(name))
157
+ .map(([name, value]) => {
158
+ taken.add(name);
159
+ return ` ${name}: ${value};`;
160
+ });
161
+ if (lines.length > 0) {
162
+ sections.push(` /* ${title} */\n${lines.join("\n")}`);
163
+ }
164
+ };
165
+
166
+ const themeColors = new Map<string, TamaguiVariable>();
167
+ for (const theme of Object.values(config.themes)) {
168
+ for (const [key, value] of Object.entries(theme)) {
169
+ if (!themeColors.has(key) && isThemeKey(key)) themeColors.set(key, value);
170
+ }
171
+ }
172
+ for (const [key, value] of Object.entries(config.tokens.color ?? {})) {
173
+ if (!themeColors.has(key) && isThemeKey(key)) themeColors.set(key, value);
174
+ }
175
+ section(
176
+ "Colors: theme values, resolved where the class is used",
177
+ [...themeColors].map(([key, value]) => [
178
+ `--color-${key}`,
179
+ cssVariable(value)
180
+ ])
181
+ );
182
+
183
+ for (const [category, namespaces] of Object.entries(TOKEN_NAMESPACES)) {
184
+ const tokens = Object.entries(config.tokens[category] ?? {}).filter(
185
+ ([key]) => isThemeKey(key)
186
+ );
187
+ for (const namespace of namespaces) {
188
+ section(
189
+ `${namespace}: ${category} tokens`,
190
+ tokens
191
+ .filter(
192
+ ([key]) =>
193
+ !FALLBACK_NAMESPACES[namespace]?.some(fallback =>
194
+ taken.has(`--${fallback}-${key}`)
195
+ )
196
+ )
197
+ .map(([key, value]) => [`--${namespace}-${key}`, cssVariable(value)])
198
+ );
199
+ }
200
+ }
201
+
202
+ section(
203
+ "Font families",
204
+ Object.entries(config.fonts ?? {})
205
+ .filter(
206
+ (entry): entry is [string, { family: string }] =>
207
+ isThemeKey(entry[0]) && typeof entry[1].family === "string"
208
+ )
209
+ .map(([key, font]) => [`--font-${key}`, font.family])
210
+ );
211
+
212
+ section(
213
+ "Breakpoints: min-width media queries",
214
+ Object.entries(config.media ?? {})
215
+ .filter(
216
+ (entry): entry is [string, { minWidth: number }] =>
217
+ isThemeKey(entry[0]) &&
218
+ Object.keys(entry[1]).length === 1 &&
219
+ typeof entry[1].minWidth === "number"
220
+ )
221
+ .map(([key, query]) => [
222
+ `--breakpoint-${key}`,
223
+ `${query.minWidth / 16}rem`
224
+ ])
225
+ );
226
+
227
+ return `/* Generated by @cyclone-ui/theme-builder from the Tamagui config. Do not edit by hand.
228
+ *
229
+ * Import it before Tailwind so the layer order comes first:
230
+ *
231
+ * @import "@cyclone-ui/tokens/tailwind.css";
232
+ * @import "tailwindcss";
233
+ */
234
+
235
+ ${TAILWIND_LAYER_ORDER}
236
+
237
+ @theme inline {
238
+ ${sections.join("\n\n")}
239
+ }
240
+
241
+ /* Tamagui puts \`t_dark\` on <html> (and on dark <Theme> regions). */
242
+ @custom-variant dark (&:where(.t_dark, .t_dark *));
243
+ `;
244
+ }
245
+
246
+ /**
247
+ * Read the theme variable names Tailwind defines by default, from the
248
+ * `tailwindcss` package installed in `cwd`.
249
+ *
250
+ * @param cwd - The project root that depends on `tailwindcss`.
251
+ * @returns Names such as `--container-lg` and `--color-black`.
252
+ */
253
+ export async function readTailwindThemeNames(
254
+ cwd: string = process.cwd()
255
+ ): Promise<Set<string>> {
256
+ let themePath: string;
257
+ try {
258
+ themePath = createRequire(join(resolve(cwd), "package.json")).resolve(
259
+ "tailwindcss/theme.css"
260
+ );
261
+ } catch {
262
+ throw new Error(
263
+ `Cyclone UI's Tailwind theme needs tailwindcss v4, which isn't installed in ${resolve(cwd)}.`
264
+ );
265
+ }
266
+
267
+ const css = await readFile(themePath, "utf8");
268
+
269
+ return new Set(
270
+ Array.from(css.matchAll(/(--[\w-]+)\s*:/gu), match => match[1]!)
271
+ );
272
+ }
273
+
274
+ export interface BuildTailwindThemeOptions {
275
+ /** The Tamagui config file, such as the one `buildTamaguiConfig` writes. */
276
+ configPath: string;
277
+
278
+ /**
279
+ * The project root, which must depend on `tailwindcss`.
280
+ *
281
+ * @defaultValue `process.cwd()`
282
+ */
283
+ cwd?: string;
284
+
285
+ /**
286
+ * The generated stylesheet, relative to `cwd`.
287
+ *
288
+ * @defaultValue `".cyclone-ui/tailwind.css"`
289
+ */
290
+ outputPath?: string;
291
+ }
292
+
293
+ /**
294
+ * Write the Tailwind theme stylesheet ({@link createTailwindThemeCSS}) for a
295
+ * Tamagui config file.
296
+ *
297
+ * @remarks
298
+ * Node.js loads the config directly, so a TypeScript config needs Node.js
299
+ * 22.18 or later (type stripping).
300
+ *
301
+ * @returns The absolute path of the generated stylesheet.
302
+ */
303
+ export async function buildTailwindThemeCSS({
304
+ configPath,
305
+ cwd = process.cwd(),
306
+ outputPath = ".cyclone-ui/tailwind.css"
307
+ }: BuildTailwindThemeOptions): Promise<string> {
308
+ const root = resolve(cwd);
309
+ const previousTarget = process.env.TAMAGUI_TARGET;
310
+ // Tamagui only creates CSS variable names for web.
311
+ process.env.TAMAGUI_TARGET = "web";
312
+ let module: { config?: TailwindThemeSource; default?: TailwindThemeSource };
313
+ try {
314
+ // The query re-evaluates a config regenerated in the same process.
315
+ module = (await import(
316
+ `${pathToFileURL(resolve(root, configPath)).href}?t=${Date.now()}`
317
+ )) as typeof module;
318
+ } catch (error) {
319
+ if ((error as { code?: string }).code === "ERR_UNKNOWN_FILE_EXTENSION") {
320
+ throw new Error(
321
+ `Loading ${configPath} needs Node.js 22.18 or later, which runs TypeScript directly.`,
322
+ { cause: error }
323
+ );
324
+ }
325
+ throw error;
326
+ } finally {
327
+ if (previousTarget === undefined) delete process.env.TAMAGUI_TARGET;
328
+ else process.env.TAMAGUI_TARGET = previousTarget;
329
+ }
330
+
331
+ const config = module.config ?? module.default;
332
+ if (!config?.themes || !config.tokens) {
333
+ throw new Error(`${configPath} doesn't export a Tamagui config.`);
334
+ }
335
+
336
+ const outputFile = resolve(root, outputPath);
337
+ await mkdir(dirname(outputFile), { recursive: true });
338
+ await writeFile(
339
+ outputFile,
340
+ createTailwindThemeCSS(config, {
341
+ reserved: await readTailwindThemeNames(root)
342
+ }),
343
+ "utf8"
344
+ );
345
+
346
+ return outputFile;
347
+ }
@@ -0,0 +1,224 @@
1
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { createRequire } from "node:module";
3
+ import { tmpdir } from "node:os";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { compile } from "tailwindcss";
6
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
7
+
8
+ import type { TailwindThemeSource } from "../src/tailwind";
9
+ import {
10
+ buildTailwindThemeCSS,
11
+ createTailwindThemeCSS,
12
+ readTailwindThemeNames
13
+ } from "../src/tailwind";
14
+
15
+ const require = createRequire(import.meta.url);
16
+
17
+ // Compile a Tailwind entry the way @tailwindcss/vite and /postcss do, and
18
+ // return the CSS generated for `candidates`.
19
+ async function tailwind(entry: string, candidates: string[]) {
20
+ const compiler = await compile(entry, {
21
+ base: import.meta.dirname,
22
+ loadStylesheet: async (id: string, base: string) => {
23
+ const path = id.startsWith(".")
24
+ ? resolve(base, id)
25
+ : require.resolve(id === "tailwindcss" ? "tailwindcss/index.css" : id);
26
+ return {
27
+ path,
28
+ base: dirname(path),
29
+ content: await readFile(path, "utf8")
30
+ };
31
+ }
32
+ });
33
+ return compiler.build(candidates);
34
+ }
35
+
36
+ // The CSS rule Tailwind generates for one class.
37
+ function rule(css: string, className: string) {
38
+ const selector = `.${className.replace(/[:/]/gu, "\\$&")} {`;
39
+ const start = css.indexOf(selector);
40
+ if (start === -1) return undefined;
41
+
42
+ let depth = 0;
43
+ for (let index = start + selector.length - 1; index < css.length; index++) {
44
+ if (css[index] === "{") depth++;
45
+ if (css[index] === "}" && --depth === 0) {
46
+ return css.slice(start, index + 1).replace(/\s+/gu, " ");
47
+ }
48
+ }
49
+ return undefined;
50
+ }
51
+
52
+ describe("createTailwindThemeCSS", () => {
53
+ let config: TailwindThemeSource;
54
+ let reserved: Set<string>;
55
+ let css: string;
56
+
57
+ beforeAll(async () => {
58
+ // Tamagui only names CSS variables when it's configured for web.
59
+ process.env.TAMAGUI_TARGET = "web";
60
+ ({ config } = (await import("../../tokens/src/tamagui/index")) as {
61
+ config: TailwindThemeSource;
62
+ });
63
+ reserved = await readTailwindThemeNames(import.meta.dirname);
64
+ css = createTailwindThemeCSS(config, { reserved });
65
+ });
66
+
67
+ it("matches the stylesheet @cyclone-ui/tokens ships", async () => {
68
+ // `vitest -u` regenerates packages/tokens/tailwind.css after a token change.
69
+ await expect(css).toMatchFileSnapshot("../../tokens/tailwind.css");
70
+ });
71
+
72
+ it("orders the Tamagui layer between preflight and utilities", () => {
73
+ expect(css).toContain(
74
+ "@layer theme, base, tamagui, components, utilities;"
75
+ );
76
+ expect(css.indexOf("@layer theme")).toBeLessThan(css.indexOf("@theme"));
77
+ });
78
+
79
+ it("gives Cyclone class names the values @tamagui/tailwind uses", async () => {
80
+ const output = await tailwind(`${css}\n@import "tailwindcss";`, [
81
+ "bg-primary",
82
+ "bg-primary/50",
83
+ "text-on-primary",
84
+ "border-hairline",
85
+ "bg-blue5",
86
+ "p-lg",
87
+ "-mt-xl",
88
+ "gap-5xl",
89
+ "top-lg",
90
+ "translate-x-lg",
91
+ "h-lg",
92
+ "min-h-7xl",
93
+ "size-lg",
94
+ "w-8xl",
95
+ "rounded-container",
96
+ "text-xxs",
97
+ "font-body",
98
+ "xs:p-lg",
99
+ "dark:bg-canvas"
100
+ ]);
101
+
102
+ expect(rule(output, "bg-primary")).toContain(
103
+ "background-color: var(--primary);"
104
+ );
105
+ expect(rule(output, "bg-primary/50")).toContain(
106
+ "color-mix(in oklab, var(--primary) 50%, transparent)"
107
+ );
108
+ expect(rule(output, "text-on-primary")).toContain(
109
+ "color: var(--on-primary);"
110
+ );
111
+ expect(rule(output, "border-hairline")).toContain(
112
+ "border-color: var(--hairline);"
113
+ );
114
+ expect(rule(output, "bg-blue5")).toContain(
115
+ "background-color: var(--blue5);"
116
+ );
117
+ expect(rule(output, "p-lg")).toContain("padding: var(--t-space-lg);");
118
+ expect(rule(output, "-mt-xl")).toContain(
119
+ "margin-top: calc(var(--t-space-xl) * -1);"
120
+ );
121
+ expect(rule(output, "gap-5xl")).toContain("gap: var(--t-space-5xl);");
122
+ expect(rule(output, "top-lg")).toContain("top: var(--t-space-lg);");
123
+ expect(rule(output, "translate-x-lg")).toContain(
124
+ "--tw-translate-x: var(--t-space-lg);"
125
+ );
126
+ expect(rule(output, "h-lg")).toContain("height: var(--t-size-lg);");
127
+ expect(rule(output, "min-h-7xl")).toContain(
128
+ "min-height: var(--t-size-7xl);"
129
+ );
130
+ expect(rule(output, "size-lg")).toContain("width: var(--t-size-lg);");
131
+ expect(rule(output, "w-8xl")).toContain("width: var(--t-size-8xl);");
132
+ expect(rule(output, "rounded-container")).toContain(
133
+ "border-radius: var(--t-radius-container);"
134
+ );
135
+ expect(rule(output, "text-xxs")).toContain(
136
+ "font-size: var(--t-fontSize-xxs);"
137
+ );
138
+ expect(rule(output, "font-body")).toContain('font-family: "Storm Sans";');
139
+ expect(rule(output, "xs:p-lg")).toContain("@media (width >= 28.75rem)");
140
+ expect(rule(output, "dark:bg-canvas")).toContain(
141
+ "&:where(.t_dark, .t_dark *) { background-color: var(--canvas); }"
142
+ );
143
+ });
144
+
145
+ it("leaves classes Tailwind already defines alone", async () => {
146
+ const candidates = [
147
+ "max-w-lg",
148
+ "w-lg",
149
+ "text-lg",
150
+ "rounded-lg",
151
+ "rounded-full",
152
+ "z-10",
153
+ "p-4",
154
+ "bg-black",
155
+ "shadow-lg",
156
+ "font-sans",
157
+ "sm:p-4",
158
+ "dark:p-4"
159
+ ];
160
+ const stock = await tailwind('@import "tailwindcss";', candidates);
161
+ const bridged = await tailwind(
162
+ `${css}\n@import "tailwindcss";`,
163
+ candidates
164
+ );
165
+
166
+ // `dark:` deliberately follows Tamagui's theme class instead.
167
+ for (const candidate of candidates.filter(name => name !== "dark:p-4")) {
168
+ expect(rule(bridged, candidate), candidate).toBe(rule(stock, candidate));
169
+ }
170
+ expect(css).not.toMatch(/--(?:z-index|container|radius-lg|color-black)\b/u);
171
+ });
172
+
173
+ it("skips keys Tailwind reads as values or keywords", () => {
174
+ const variable = (name: string) => ({
175
+ name,
176
+ val: 0,
177
+ variable: `var(--${name})`
178
+ });
179
+ const output = createTailwindThemeCSS({
180
+ tokens: {
181
+ zIndex: { "10": variable("t-zIndex-10") },
182
+ radius: { full: variable("t-radius-full"), pill: variable("t-pill") },
183
+ color: { "brand.500": variable("c-brand") }
184
+ },
185
+ themes: { light: { transparent: variable("transparent") } }
186
+ });
187
+
188
+ expect(output).toContain("--radius-pill: var(--t-pill);");
189
+ expect(output).not.toMatch(/--z-index-10|--radius-full|brand|transparent/u);
190
+ });
191
+ });
192
+
193
+ describe("buildTailwindThemeCSS", () => {
194
+ let cwd: string;
195
+ beforeAll(async () => {
196
+ cwd = await mkdtemp(join(tmpdir(), "cyclone-ui-tailwind-"));
197
+ });
198
+ afterAll(async () => rm(cwd, { recursive: true, force: true }));
199
+
200
+ it("writes the stylesheet for a config file", async () => {
201
+ const configPath = join(cwd, "tamagui.config.mjs");
202
+ await writeFile(
203
+ configPath,
204
+ `export const config = {
205
+ tokens: { space: { lg: { name: "t-space-lg", val: 4, variable: process.env.TAMAGUI_TARGET === "web" ? "var(--t-space-lg)" : "" } } },
206
+ themes: { light: { canvas: { name: "canvas", val: "white" } } }
207
+ };`
208
+ );
209
+ delete process.env.TAMAGUI_TARGET;
210
+
211
+ const file = await buildTailwindThemeCSS({
212
+ configPath,
213
+ // Resolves tailwindcss from this package.
214
+ cwd: import.meta.dirname,
215
+ outputPath: join(cwd, ".cyclone-ui/tailwind.css")
216
+ });
217
+ const output = await readFile(file, "utf8");
218
+
219
+ expect(file).toBe(join(cwd, ".cyclone-ui/tailwind.css"));
220
+ expect(output).toContain("--padding-lg: var(--t-space-lg);");
221
+ expect(output).toContain("--color-canvas: var(--canvas);");
222
+ expect(process.env.TAMAGUI_TARGET).toBeUndefined();
223
+ });
224
+ });
package/tsconfig.json CHANGED
@@ -8,6 +8,7 @@
8
8
  "outDir": "../../dist/out-tsc/packages/theme-builder",
9
9
  "ignoreDeprecations": "6.0"
10
10
  },
11
+ "references": [{ "path": "../tokens" }],
11
12
  "include": ["src/**/*", "powerlines.config.ts", "powerlines.d.ts"],
12
13
  "exclude": ["vitest.config.mts", "src/**/*.spec.ts", "src/**/*.test.ts"]
13
14
  }