@ng-native/tailwind 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ashley Hunter
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,91 @@
1
1
  # @ng-native/tailwind
2
2
 
3
- A placeholder: this version has no code. See https://ng-native.com.
3
+ A Tailwind CSS preset for Angular Native, for Tailwind 4 on native and web and Tailwind 3 on
4
+ native: `<view class="flex-1 bg-blue-500 p-4">` works because
5
+ [`@ng-native/fabric`](https://github.com/ng-native/ng-native/blob/main/packages/fabric) already has
6
+ a real cascade, and `class` already matches against it.
7
+
8
+ Alpha: APIs may change before 1.0.
9
+
10
+ ## Install (Tailwind 4)
11
+
12
+ ```sh
13
+ npm install @ng-native/tailwind @ng-native/metro @tailwindcss/cli tailwindcss
14
+ ```
15
+
16
+ ## Example (Tailwind 4)
17
+
18
+ ```css
19
+ /* styles.css */
20
+ @import 'tailwindcss/theme.css';
21
+ @import 'tailwindcss/utilities.css';
22
+ @import '@ng-native/tailwind/native.css';
23
+ ```
24
+
25
+ ```js
26
+ // metro.config.js
27
+ const { getDefaultConfig } = require('expo/metro-config');
28
+ const { withAngularNative } = require('@ng-native/metro/config.cjs');
29
+ const { withTailwind } = require('@ng-native/tailwind/config.cjs');
30
+
31
+ module.exports = withTailwind(withAngularNative(getDefaultConfig(__dirname)), {
32
+ input: './styles.css',
33
+ });
34
+ ```
35
+
36
+ ```ts
37
+ // index.ts
38
+ import tailwind from './.angular-native/app.tailwind.js';
39
+ import { mount } from '@ng-native/platform';
40
+
41
+ mount(rootTag, App, fabric, { globalStyles: tailwind });
42
+ ```
43
+
44
+ Import `theme.css` and `utilities.css`, not the plain `tailwindcss` entry point - that also pulls
45
+ in preflight, a browser reset that means nothing on a phone.
46
+
47
+ ## Tailwind 3 (native only)
48
+
49
+ ```sh
50
+ npm install @ng-native/tailwind @ng-native/metro tailwindcss@3
51
+ ```
52
+
53
+ ```js
54
+ // tailwind.config.js
55
+ module.exports = {
56
+ presets: [require('@ng-native/tailwind/preset.cjs')],
57
+ content: ['./src/**/*.{ts,html}'],
58
+ };
59
+ ```
60
+
61
+ ```css
62
+ /* styles.css */
63
+ @tailwind base;
64
+ @tailwind components;
65
+ @tailwind utilities;
66
+ ```
67
+
68
+ `metro.config.js` and `index.ts` are the same as above: `withTailwind` sees Tailwind 3 and runs its
69
+ own CLI, so there is no `@tailwindcss/cli` to install. The preset turns preflight off.
70
+
71
+ ## What's in the package
72
+
73
+ - `./native.css` - the preset: platform variants, safe-area and hairline utilities, and
74
+ touch-appropriate `hover:`/`focus-visible:` meanings.
75
+ - `./web.css` - the same preset's web entry point, for `@ng-native/web`.
76
+ - `./preset.cjs` - the native preset for Tailwind 3, used from `tailwind.config.js`.
77
+ - `./config.cjs` - `withTailwind`, the Metro config step that runs the app's Tailwind CLI and
78
+ flattens its output for the CSS compiler.
79
+
80
+ ## Docs
81
+
82
+ - [Tailwind](https://ng-native.com/packages/tailwind), including
83
+ [Tailwind 3](https://ng-native.com/packages/tailwind#tailwind-3)
84
+ - [Variants](https://ng-native.com/packages/tailwind/variants) and
85
+ [safe area and hairlines](https://ng-native.com/packages/tailwind/utilities)
86
+ - [Root README](https://github.com/ng-native/ng-native/blob/main/README.md) and
87
+ [ARCHITECTURE.md](https://github.com/ng-native/ng-native/blob/main/ARCHITECTURE.md)
88
+
89
+ ## License
90
+
91
+ MIT
package/config.cjs ADDED
@@ -0,0 +1,238 @@
1
+ /**
2
+ * Tailwind, wired into Metro.
3
+ *
4
+ * ```js
5
+ * const config = withAngularNative(getDefaultConfig(__dirname), { workspaceRoot });
6
+ * module.exports = withTailwind(config, { input: './styles.css' });
7
+ * ```
8
+ *
9
+ * and in the app:
10
+ *
11
+ * ```ts
12
+ * import tailwind from './.angular-native/app.tailwind.css';
13
+ * mount(rootTag, App, fabric, { globalStyles: tailwind });
14
+ * ```
15
+ *
16
+ * The CLI is run rather than the JavaScript API used: scanning source files for class names is
17
+ * most of what Tailwind does, its own binary is the thing that does it properly, and a bundler
18
+ * plugin that reimplements the scan is a bundler plugin that disagrees with the CLI eventually.
19
+ */
20
+ const { execFileSync, spawn } = require('node:child_process');
21
+ const {
22
+ existsSync,
23
+ mkdirSync,
24
+ readFileSync,
25
+ realpathSync,
26
+ utimesSync,
27
+ watchFile,
28
+ writeFileSync,
29
+ } = require('node:fs');
30
+ const path = require('node:path');
31
+ const { compileCss } = require('@ng-native/metro/css/compile.cjs');
32
+ const { flattenTailwind } = require('./flatten.cjs');
33
+
34
+ /** Where the generated module goes if the app does not say. */
35
+ const DEFAULT_OUTPUT = '.angular-native/app.tailwind.js';
36
+
37
+ /**
38
+ * @param {object} config a Metro config, after `withAngularNative`
39
+ * @param {{ input: string, output?: string, watch?: boolean }} options
40
+ * `input` is the app's Tailwind entry - the file with the `@import`s. `output` is the module the
41
+ * app imports, and must be JavaScript: Expo's own transform worker claims every `.css` file
42
+ * before ours is asked, and hands back an empty module on any platform but web, so a stylesheet
43
+ * that arrived as CSS would silently contain nothing. `watch` is what makes a newly written
44
+ * class appear without restarting the dev server; it defaults to on for a dev server and off
45
+ * for a one-off build (see `watchesByDefault`).
46
+ */
47
+ function withTailwind(config, options) {
48
+ const projectRoot = config.projectRoot ?? process.cwd();
49
+ const input = path.resolve(projectRoot, options.input);
50
+ const output = path.resolve(projectRoot, options.output ?? DEFAULT_OUTPUT);
51
+ if (!/\.[cm]?js$/.test(output)) {
52
+ throw new Error(
53
+ `[angular-native] the Tailwind output has to be a .js module, because Expo's transform ` +
54
+ `worker turns every .css file into an empty one on native. Got ${output}`,
55
+ );
56
+ }
57
+ // The CLI's own output, kept beside the module: useful to read when a utility goes missing.
58
+ const css = output.replace(/\.[cm]?js$/, '.css');
59
+
60
+ mkdirSync(path.dirname(output), { recursive: true });
61
+ run([cliPath(projectRoot), '-i', input, '-o', css], projectRoot);
62
+ generate(css, output);
63
+ // Without it TypeScript infers the sheet from its literal, which is not assignable to the type
64
+ // `globalStyles` takes. `.js` -> `.d.ts`, `.mjs` -> `.d.mts`, `.cjs` -> `.d.cts`.
65
+ writeFileSync(
66
+ output.replace(/\.([cm]?)js$/, '.d.$1ts'),
67
+ "declare const sheet: import('@ng-native/fabric').StyleSheet;\nexport default sheet;\n",
68
+ );
69
+ if (options.watch ?? watchesByDefault()) watch(input, css, output, projectRoot);
70
+
71
+ return config;
72
+ }
73
+
74
+ /** The Expo and React Native commands that build once and exit, rather than serve. */
75
+ const ONE_OFF_COMMANDS = new Set(['export', 'export:embed', 'bundle', 'prebuild']);
76
+
77
+ /**
78
+ * Whether to watch when the app does not say: not in CI, and not for a one-off build.
79
+ *
80
+ * `npx expo export` loads the Metro config like a dev server does, and a watcher started for it
81
+ * kept the process alive after the bundles were written, until Expo gave up and killed it with
82
+ * "Detected 1 process preventing Expo from exiting". A build has nothing to watch for, and in CI
83
+ * Metro watches nothing either.
84
+ */
85
+ function watchesByDefault(argv = process.argv, env = process.env) {
86
+ const ci = env['CI'];
87
+ if (ci && ci !== 'false' && ci !== '0') return false;
88
+ // `node metro.config.js`, run to build the sheet before a typecheck, is a one-off too.
89
+ if (/^metro\.config\.[cm]?js$/.test(path.basename(argv[1] ?? ''))) return false;
90
+ return !argv.slice(2).some((arg) => ONE_OFF_COMMANDS.has(arg));
91
+ }
92
+
93
+ /** The CLI's CSS, compiled into the module the app imports. */
94
+ function generate(css, output) {
95
+ writeFileSync(output, compileSheetModule(readFileSync(css, 'utf8'), css));
96
+ }
97
+
98
+ /**
99
+ * Tailwind's CSS as a module exporting the compiled stylesheet.
100
+ *
101
+ * Exported because it is the whole of the build step worth testing: everything else here is
102
+ * process wrangling.
103
+ */
104
+ function compileSheetModule(css, context = 'tailwind') {
105
+ const dropped = [];
106
+ const sheet = compileCss(flattenTailwind(css), context, {
107
+ onUnsupported: (message) => dropped.push(message),
108
+ });
109
+ for (const message of dropped) {
110
+ // A leftover custom property was already substituted; anything else is a utility the app used
111
+ // and native cannot express, which is worth saying while it is still being written.
112
+ if (!message.includes("dropped '--")) console.warn(`[angular-native] ${message}`);
113
+ }
114
+ return `// Generated from ${path.basename(context)}. Edit the Tailwind entry, not this.\nexport default ${JSON.stringify(sheet)};\n`;
115
+ }
116
+
117
+ /**
118
+ * The entry's own `@import`s that live in this repository, resolved past any symlink.
119
+ *
120
+ * The CLI re-reads the entry on a change and resolves its imports from a cache, so editing one of
121
+ * them rebuilds nothing: the sheet on disk stays as it was, with no error and no warning, and the
122
+ * device goes on wearing styles from before the edit. Touching the entry makes it re-read
123
+ * everything, so these are watched and a change to one touches it.
124
+ *
125
+ * Local means in the source tree rather than in `node_modules`. Through pnpm a workspace package
126
+ * is a symlink, so it resolves back into the repository - which is exactly the set that changes
127
+ * while someone is working on it. Tailwind's own stylesheets do not.
128
+ *
129
+ * Exported for the test: everything else here is process wrangling, and this is the one part with
130
+ * a rule in it.
131
+ */
132
+ function localImports(css, cwd) {
133
+ const found = [];
134
+ for (const match of css.matchAll(/@import\s+['"]([^'"]+)['"]/g)) {
135
+ const specifier = match[1];
136
+ try {
137
+ const resolved = specifier.startsWith('.')
138
+ ? path.resolve(cwd, specifier)
139
+ : require.resolve(specifier, { paths: [cwd] });
140
+ const real = realpathSync(resolved);
141
+ // A typo is the CLI's error to report, with a line number. Throwing here would replace that
142
+ // with a stack trace out of Metro's config, which names nothing useful.
143
+ if (!real.split(path.sep).includes('node_modules')) found.push(real);
144
+ } catch {
145
+ continue;
146
+ }
147
+ }
148
+ return found;
149
+ }
150
+
151
+ /** Build once, synchronously, so the module exists before Metro resolves the first import. */
152
+ function run(args, cwd) {
153
+ execFileSync(process.execPath, args, { cwd, stdio: 'pipe' });
154
+ }
155
+
156
+ /**
157
+ * The CLI, left running, and the generated module kept in step with what it writes.
158
+ *
159
+ * Metro watches the module, so a class written in a template reaches the device the way an edited
160
+ * template does: the CLI notices the source, rewrites the CSS, this rewrites the module.
161
+ */
162
+ function watch(input, css, output, cwd) {
163
+ let stopping = false;
164
+ const child = spawn(process.execPath, [cliPath(cwd), '-i', input, '-o', css, '--watch'], {
165
+ cwd,
166
+ // A pipe for stdin, never written to, rather than `ignore`.
167
+ //
168
+ // `ignore` gives the child `/dev/null`, which reads EOF immediately - and the CLI treats a
169
+ // closed stdin as "the thing that started me has gone" and exits, cleanly, with code 0, about
170
+ // a second after being spawned. An open pipe never reaches EOF, so it stays up.
171
+ //
172
+ // This is what made every class written after the dev server started go missing on the
173
+ // device while being present in Node, which is a confusing shape of bug: the app is running
174
+ // the code you just wrote, styled by a sheet from hours ago.
175
+ stdio: ['pipe', 'ignore', 'ignore'],
176
+ });
177
+ // Nothing here keeps the process alive on its own: a dev server does that, and a process that
178
+ // is done should be able to exit with the watcher still up.
179
+ child.unref();
180
+ child.stdin?.unref?.();
181
+
182
+ /*
183
+ * Say so when it dies, because the failure is otherwise invisible and looks like anything else.
184
+ *
185
+ * A dead watcher does not break the build: the stylesheet on disk is still the last good one, so
186
+ * everything written before it died keeps working and only new classes are missing. What that
187
+ * looks like on a device is one component laid out as though a class had been misspelt, which is
188
+ * where anybody would start looking - and it cost an afternoon before this line existed.
189
+ */
190
+ child.once('exit', (code, signal) => {
191
+ if (stopping) return;
192
+ console.error(
193
+ `[angular-native] the Tailwind watcher exited (${signal ?? `code ${code}`}). Classes written ` +
194
+ 'from now on will not reach the device until Metro is restarted.',
195
+ );
196
+ });
197
+
198
+ watchFile(css, { interval: 200, persistent: false }, () => generate(css, output));
199
+
200
+ // A change inside an imported sheet is invisible to the CLI's cache. Touching the entry is what
201
+ // makes it read them all again.
202
+ for (const file of localImports(readFileSync(input, 'utf8'), path.dirname(input))) {
203
+ watchFile(file, { interval: 200, persistent: false }, () => {
204
+ const now = new Date();
205
+ utimesSync(input, now, now);
206
+ });
207
+ }
208
+ const stop = () => {
209
+ stopping = true;
210
+ child.kill();
211
+ };
212
+ process.once('exit', stop);
213
+ process.once('SIGINT', stop);
214
+ process.once('SIGTERM', stop);
215
+ }
216
+
217
+ /**
218
+ * The app's Tailwind CLI, resolved from the app rather than from here: it is the app's dependency.
219
+ *
220
+ * Tailwind 3 ships its CLI inside `tailwindcss` itself; Tailwind 4 moved it to `@tailwindcss/cli`.
221
+ * The app's `tailwindcss` says which it is on.
222
+ */
223
+ function cliPath(cwd) {
224
+ const paths = { paths: [cwd, __dirname] };
225
+ const tailwind = require.resolve('tailwindcss/package.json', paths);
226
+ const from = require(tailwind).version.startsWith('3.')
227
+ ? tailwind
228
+ : require.resolve('@tailwindcss/cli/package.json', paths);
229
+ const { bin, name } = require(from);
230
+ const entry = typeof bin === 'string' ? bin : bin[Object.keys(bin)[0]];
231
+ const resolved = path.join(path.dirname(from), entry);
232
+ if (!existsSync(resolved)) {
233
+ throw new Error(`[angular-native] found ${name} but not its binary at ${resolved}`);
234
+ }
235
+ return resolved;
236
+ }
237
+
238
+ module.exports = { withTailwind, compileSheetModule, localImports, watchesByDefault };