tailwind.com 0.4.0 → 0.6.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/js/page.js ADDED
@@ -0,0 +1,375 @@
1
+ // The default file of the npm package tailwind.com on a CDN (the field
2
+ // "jsdelivr" and "unpkg" of package.json). It builds the CSS of the page
3
+ // in the browser, as the browser build of Tailwind CSS (the Play CDN) does.
4
+ //
5
+ // The input CSS can be a file, as for a build on the disk:
6
+ //
7
+ // <link rel="stylesheet" type="text/tailwindcss" href="/assets/app.css">
8
+ // <script src="https://cdn.jsdelivr.net/npm/tailwind.com@0.6"></script>
9
+ //
10
+ // or a <style>, as for the Play CDN:
11
+ //
12
+ // <script src="https://cdn.jsdelivr.net/npm/tailwind.com@0.6"></script>
13
+ // <style type="text/tailwindcss">
14
+ // @theme { --color-brand: #0d9488; }
15
+ // </style>
16
+ //
17
+ // - A <link rel="stylesheet" type="text/tailwindcss">: the browser does
18
+ // not apply a stylesheet of this type. The script gets the file, and the
19
+ // files of its @import, @reference, @plugin and @config with a path
20
+ // ("./", "../" or "/"), and the files that a JavaScript or TypeScript
21
+ // file of a plugin imports with a path. A path with no extension tries
22
+ // the extensions, as Node.js does. The files go in memory at the path of
23
+ // their URL, so the paths in the CSS find them as on the disk.
24
+ // - A <style type="text/tailwindcss">: its text, as a file in the
25
+ // directory of the page. Its paths find the files from the URL of the
26
+ // page. With no <link> and no @import, `@import "tailwindcss";` comes
27
+ // first.
28
+ // - Each second, while the page is visible, the script gets the files of
29
+ // this site again (a server with ETag or Last-Modified answers 304), and
30
+ // builds again when one changes. A change of href gets the new files.
31
+ // - The classes are the classes of each element of the page. A class that
32
+ // goes from the page stays in the CSS, as in the browser build.
33
+ // - The output CSS goes in a <style> after the first such <link>, so it
34
+ // has the place of the file in the cascade. With no <link>, it goes at
35
+ // the end of <head>, as in the browser build.
36
+ // - A change of a class or of an element builds again. A change of a
37
+ // <style type="text/tailwindcss"> builds again too.
38
+ // - After each build, the document gets the event "tailwind.com:build".
39
+ // - The first build waits for the end of the HTML, so that it has all the
40
+ // classes. The downloads start at once.
41
+ // - The program has no JavaScript engine: for @plugin and @config, the
42
+ // plugins run in the JavaScript engine of the browser (js/engine.mjs),
43
+ // with JS Promise Integration.
44
+ // - The new CSS of the input (@function, @mixin, if(), @when,
45
+ // sibling-index(), round(), ...) is lowered for the browsers of Tailwind
46
+ // CSS, as with --optimize of the command line, with no Lightning CSS.
47
+ // - The last CSS of each page stays in localStorage. On the next load, it
48
+ // styles the page at once, and the build replaces it. With no such CSS
49
+ // and the script in <head>, the page stays hidden until the first CSS
50
+ // (at most 3 seconds), so it does not show with no style.
51
+ //
52
+ // To build on the disk later, remove the script and the attribute type,
53
+ // and set href to the output of the build.
54
+ //
55
+ // It is the same program as the command line: the plugins in the program
56
+ // (@tailwindcss/typography, @tailwindcss/forms and
57
+ // @tailwindcss/aspect-ratio) work with @plugin. The program
58
+ // (tailwind-browser.wasm) is about 0.8 MB with compression, so this script
59
+ // is for development, prototypes and editors, not for a production site.
60
+ //
61
+ // A classic script, not a module: a <script src> with no type loads it,
62
+ // as the Play CDN. It loads js/browser.mjs with import().
63
+ (() => {
64
+ const TYPE = 'text/tailwindcss';
65
+ const LINKS = `link[rel~="stylesheet"][type="${TYPE}"][href]`;
66
+ const STYLES = `style[type="${TYPE}"]`;
67
+ // The file of the classes of the page, in the root of the project.
68
+ const CLASSES = 'tailwind.com.classes.html';
69
+ // The references to other files in a CSS file, and in a JavaScript file.
70
+ const CSS_REFERENCE = /@(?:import|reference|plugin|config)\s+(?:url\(\s*)?(["'])(.*?)\1/g;
71
+ const JS_REFERENCE = /(?:\bfrom|\bimport|\brequire\s*\(|\bimport\s*\()\s*(["'])((?:\.{1,2})?\/[^"']*)\1/g;
72
+ const JS = /\.[cm]?[jt]s$/i;
73
+ // The files that a path with no extension can be, as Node.js resolves
74
+ // it: a CSS reference, then a reference of JavaScript.
75
+ const CSS_FILES = ['.css', '/index.css'];
76
+ const JS_FILES = ['.js', '.cjs', '.mjs', '.ts', '.cts', '.mts', '/index.js', '/index.cjs', '/index.mjs', '/index.ts'];
77
+ const POLL_MS = 1000;
78
+ // The longest time that the page stays hidden.
79
+ const HIDE_MS = 3000;
80
+
81
+ const script = document.currentScript;
82
+ const source = new URL(script?.src || location.href);
83
+ // The package root of a CDN URL ("/npm/tailwind.com@0.6", with no file),
84
+ // else the directory js/ of this file.
85
+ const found = source.pathname.match(/^(.*\/tailwind\.com(?:@[^/]*)?)(?:\/|$)/);
86
+ const js = found ? new URL(`${found[1]}/js/`, source) : new URL('./', source);
87
+
88
+ // The program for a browser: no optimizer and no JavaScript engine.
89
+ const wasm = new URL('../runtime/tailwind-browser.wasm', js).href;
90
+ const head = document.head ?? document.documentElement;
91
+
92
+ // Start the downloads now: the module of the API, its import, and the
93
+ // program. Else each one starts only when the one before it ends.
94
+ function preload(rel, href, as) {
95
+ const link = document.createElement('link');
96
+ link.rel = rel;
97
+ link.href = href;
98
+ if (as) link.as = as;
99
+ link.crossOrigin = 'anonymous';
100
+ head.append(link);
101
+ }
102
+ preload('modulepreload', new URL('wasi.mjs', js).href);
103
+ preload('modulepreload', new URL('engine.mjs', js).href);
104
+ preload('preload', wasm, 'fetch');
105
+ const loading = import(new URL('browser.mjs', js).href);
106
+ loading.catch(() => {});
107
+
108
+ // The CSS of the last build of this page, at once.
109
+ const output = document.createElement('style');
110
+ const KEY = `tailwind.com:${location.pathname}`;
111
+ let cached = null;
112
+ try {
113
+ cached = localStorage.getItem(KEY);
114
+ } catch {}
115
+ if (cached !== null) output.textContent = cached;
116
+ head.append(output);
117
+
118
+ // With no such CSS, hide the page until the first CSS. A script at the
119
+ // end of <body> comes after the first paint: then no hide.
120
+ const hide = document.createElement('style');
121
+ if (cached === null && !document.body) {
122
+ hide.textContent = 'html { visibility: hidden !important; }';
123
+ head.append(hide);
124
+ setTimeout(show, HIDE_MS);
125
+ }
126
+ function show() {
127
+ hide.remove();
128
+ }
129
+
130
+ const classes = new Set();
131
+ // The text of each file that the script got, by URL.
132
+ const texts = new Map();
133
+ // The URL of the file of a reference with no extension, by the URL of
134
+ // the reference.
135
+ const resolved = new Map();
136
+ // The URLs of the files of the last build.
137
+ let used = new Set();
138
+ // One more for each change of a file.
139
+ let version = 0;
140
+ let input = null;
141
+ let api = null;
142
+ let queue = Promise.resolve();
143
+ let pending = false;
144
+ // The first build waits for the end of the HTML.
145
+ let ready = document.readyState !== 'loading';
146
+
147
+ // The path of a URL in the project: the path of the URL.
148
+ const pathOf = (url) => decodeURIComponent(new URL(url).pathname);
149
+ const quote = (text) => `"${text.replace(/[\\"]/g, '\\$&')}"`;
150
+
151
+ async function get(url) {
152
+ const response = await fetch(url, { cache: 'no-cache' });
153
+ // A server for a single page can give its HTML for each path.
154
+ if (!response.ok || response.headers.get('content-type')?.startsWith('text/html')) return null;
155
+ return response.text();
156
+ }
157
+
158
+ // The URL of the file of a reference: the URL itself when it has an
159
+ // extension, else the first file that is there, as Node.js resolves it.
160
+ async function resolve(url, kind) {
161
+ const path = new URL(url).pathname;
162
+ if (/\.[^./]+$/.test(path)) return url;
163
+ if (!resolved.has(url)) {
164
+ for (const suffix of kind === 'css' ? CSS_FILES : JS_FILES) {
165
+ const candidate = new URL(url);
166
+ candidate.pathname = path.replace(/\/$/, '') + suffix;
167
+ const text = await get(candidate.href);
168
+ if (text !== null) {
169
+ texts.set(candidate.href, text);
170
+ resolved.set(url, candidate.href);
171
+ break;
172
+ }
173
+ }
174
+ }
175
+ if (!resolved.has(url)) throw new Error(`${url}: no such file`);
176
+ return resolved.get(url);
177
+ }
178
+
179
+ // Put a file and the files of its references in `files`.
180
+ async function load(url, kind, files) {
181
+ url = await resolve(url, kind);
182
+ const path = pathOf(url).slice(1);
183
+ if (path in files) return;
184
+ files[path] = '';
185
+ used.add(url);
186
+ if (!texts.has(url)) {
187
+ const text = await get(url);
188
+ if (text === null) throw new Error(`${url}: no such file`);
189
+ texts.set(url, text);
190
+ }
191
+ files[path] = texts.get(url);
192
+ await references(files[path], url, path, files);
193
+ }
194
+
195
+ // Load the files of the references of a text with a path.
196
+ async function references(text, url, path, files) {
197
+ const loads = [];
198
+ if (/\.css$/i.test(path)) {
199
+ for (const [whole, , target] of text.matchAll(CSS_REFERENCE)) {
200
+ const kind = /^@(?:import|reference)/.test(whole) ? 'css' : 'js';
201
+ if (/^(\.{1,2})?\//.test(target)) loads.push(load(new URL(target, url).href, kind, files));
202
+ }
203
+ } else if (JS.test(path)) {
204
+ for (const [, , target] of text.matchAll(JS_REFERENCE)) loads.push(load(new URL(target, url).href, 'js', files));
205
+ }
206
+ await Promise.all(loads);
207
+ }
208
+
209
+ // The files of the project and the input CSS: an @import of each link,
210
+ // then of the text of each <style>, as a file in the directory of the
211
+ // page.
212
+ async function project() {
213
+ used = new Set();
214
+ const files = {};
215
+ const imports = [];
216
+ for (const link of document.querySelectorAll(LINKS)) {
217
+ const url = new URL(link.getAttribute('href'), document.baseURI).href;
218
+ await load(url, 'css', files);
219
+ imports.push(pathOf(await resolve(url, 'css')));
220
+ }
221
+ let text = '';
222
+ for (const [i, style] of [...document.querySelectorAll(STYLES)].entries()) {
223
+ watchStyle(style);
224
+ const url = new URL(`tailwind.com.style.${i}.css`, document.baseURI).href;
225
+ const path = pathOf(url);
226
+ files[path.slice(1)] = style.textContent;
227
+ text += style.textContent;
228
+ await references(style.textContent, url, path, files);
229
+ imports.push(path);
230
+ }
231
+ let css = imports.map((path) => `@import ${quote(`.${path}`)};\n`).join('');
232
+ if (!document.querySelector(LINKS) && !text.includes('@import')) css = `@import "tailwindcss";\n${css}`;
233
+ // Forget the files that the page does not use now.
234
+ for (const url of texts.keys()) if (!used.has(url)) texts.delete(url);
235
+ return { css, files };
236
+ }
237
+
238
+ // Get the files of this site again. A change builds again.
239
+ async function poll() {
240
+ if (document.visibilityState === 'visible') {
241
+ for (const url of [...texts.keys()]) {
242
+ if (new URL(url).origin !== location.origin) continue;
243
+ const text = await get(url).catch(() => null);
244
+ if (text !== null && texts.has(url) && text !== texts.get(url)) {
245
+ texts.set(url, text);
246
+ version++;
247
+ }
248
+ }
249
+ if (version !== polled) {
250
+ polled = version;
251
+ schedule();
252
+ }
253
+ }
254
+ setTimeout(poll, POLL_MS);
255
+ }
256
+ let polled = 0;
257
+
258
+ // Add the classes of the page. The result is true when a class is new.
259
+ function collect() {
260
+ let added = false;
261
+ for (const element of document.querySelectorAll('[class]')) {
262
+ for (const name of element.classList) {
263
+ if (!classes.has(name)) {
264
+ classes.add(name);
265
+ added = true;
266
+ }
267
+ }
268
+ }
269
+ return added;
270
+ }
271
+
272
+ // The place of the output: after the first link, else at the end of
273
+ // <head>.
274
+ function place() {
275
+ const anchor = document.querySelector(LINKS);
276
+ if (anchor) {
277
+ if (anchor.nextSibling !== output) anchor.after(output);
278
+ } else if (output.parentNode !== document.head) {
279
+ document.head.append(output);
280
+ }
281
+ }
282
+
283
+ async function build() {
284
+ api ??= await loading;
285
+ const { css, files } = await project();
286
+ const added = collect();
287
+ place();
288
+ const key = `${version}\n${css}\n${JSON.stringify(files)}`;
289
+ if (key === input && !added) return;
290
+ input = key;
291
+ // The classes go in a file of the project. The scanner finds them
292
+ // there, as in a template of a project on the disk.
293
+ // --optimize: the program for a browser lowers the new CSS (functions,
294
+ // mixins, if(), @when, the sibling functions, the math functions) for
295
+ // the browsers of Tailwind CSS. With nothing to lower, the CSS does not
296
+ // change.
297
+ const result = await api.runWasm(['-i', '-', '--optimize'], {
298
+ input: `${css}@source ${quote(`./${CLASSES}`)};\n`,
299
+ files: { ...files, [CLASSES]: [...classes].join('\n') },
300
+ env: { NO_COLOR: '1' },
301
+ wasm,
302
+ });
303
+ // The program writes its version and its time to stderr. Show only the
304
+ // other lines: the warnings and the errors.
305
+ for (const line of result.stderr.split('\n')) {
306
+ if (line.trim() && !line.startsWith('≈ tailwindcss') && !/^Done in /.test(line)) {
307
+ (result.status === 0 ? console.warn : console.error)(`tailwind.com: ${line}`);
308
+ }
309
+ }
310
+ // The CSS of the browser build has no newline at the end.
311
+ if (result.status === 0) {
312
+ const css = result.stdout.replace(/\n$/, '');
313
+ output.textContent = css;
314
+ try {
315
+ localStorage.setItem(KEY, css);
316
+ } catch {}
317
+ }
318
+ show();
319
+ document.dispatchEvent(new CustomEvent('tailwind.com:build', { detail: { status: result.status } }));
320
+ }
321
+
322
+ // One build at a time. The changes while a build runs give one more
323
+ // build.
324
+ function schedule() {
325
+ if (!ready || pending) return;
326
+ pending = true;
327
+ queue = queue.then(() => {
328
+ pending = false;
329
+ return build().catch((error) => {
330
+ console.error('tailwind.com:', error);
331
+ show();
332
+ document.dispatchEvent(new CustomEvent('tailwind.com:build', { detail: { status: -1 } }));
333
+ });
334
+ });
335
+ }
336
+
337
+ const styles = new MutationObserver(schedule);
338
+ const watched = new WeakSet();
339
+ function watchStyle(style) {
340
+ if (watched.has(style)) return;
341
+ watched.add(style);
342
+ styles.observe(style, { attributes: true, attributeFilter: ['type'], characterData: true, subtree: true, childList: true });
343
+ }
344
+
345
+ new MutationObserver((records) => {
346
+ for (const record of records) {
347
+ if (record.type === 'attributes') return schedule();
348
+ for (const node of record.addedNodes) {
349
+ // The realm of the JavaScript engine is a hidden <iframe>.
350
+ if (node !== output && node.nodeType === Node.ELEMENT_NODE && !node.hasAttribute('data-tailwind-com')) return schedule();
351
+ }
352
+ for (const node of record.removedNodes) {
353
+ if (node.nodeType === Node.ELEMENT_NODE && node.matches(`${LINKS}, ${STYLES}`)) return schedule();
354
+ }
355
+ }
356
+ }).observe(document.documentElement, {
357
+ attributes: true,
358
+ attributeFilter: ['class', 'href', 'rel', 'type'],
359
+ childList: true,
360
+ subtree: true,
361
+ });
362
+
363
+ if (ready) schedule();
364
+ else {
365
+ document.addEventListener(
366
+ 'DOMContentLoaded',
367
+ () => {
368
+ ready = true;
369
+ schedule();
370
+ },
371
+ { once: true },
372
+ );
373
+ }
374
+ setTimeout(poll, POLL_MS);
375
+ })();