@jskit-ai/material-web 0.1.4 → 0.1.6

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.
@@ -0,0 +1,37 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import process from "node:process";
3
+ import { fileURLToPath } from "node:url";
4
+ import vue from "@vitejs/plugin-vue";
5
+ import { defineConfig } from "vite";
6
+ import { PATCH, TARGETS, patchSource } from "../scripts/patch-vuetify-loaders.mjs";
7
+
8
+ // JSKIT_VUETIFY_LOADERS=published serves Vuetify's three loader modules as Vuetify publishes them, and =patched as
9
+ // material-web's install patch leaves them, whatever this checkout's install did to node_modules. Vuetify stays out of
10
+ // dependency pre-bundling, so its modules come through this plugin.
11
+ const LOADERS = process.env.JSKIT_VUETIFY_LOADERS;
12
+ if (!["published", "patched"].includes(LOADERS)) throw new Error("Set JSKIT_VUETIFY_LOADERS to published or patched.");
13
+ const LOADER_MODULES = Object.entries(TARGETS).filter(([file]) => file.startsWith("lib/"));
14
+
15
+ function vuetifyLoaders() {
16
+ return {
17
+ name: "jskit-vuetify-loaders",
18
+ enforce: "pre",
19
+ async load(id) {
20
+ const file = id.split("?")[0];
21
+ const [target, loaders] = LOADER_MODULES.find(([module]) => file.endsWith(`/vuetify/${module}`)) ?? [];
22
+ if (!target) return null;
23
+ const published = (await readFile(file, "utf8")).replaceAll(PATCH, "");
24
+ if (LOADERS === "published") return published;
25
+ const patched = patchSource(published, loaders);
26
+ if (!patched.source) throw new Error(`${target}: ${patched.changed}`);
27
+ return patched.source;
28
+ }
29
+ };
30
+ }
31
+
32
+ export default defineConfig({
33
+ root: fileURLToPath(new URL("./fixtures/idle-loaders", import.meta.url)),
34
+ plugins: [vuetifyLoaders(), vue()],
35
+ optimizeDeps: { exclude: ["vuetify"], include: ["vue", "@vuetify/v0"] },
36
+ server: { host: "127.0.0.1" }
37
+ });
@@ -0,0 +1,102 @@
1
+ import assert from "node:assert/strict";
2
+ import process from "node:process";
3
+ import test from "node:test";
4
+ import { fileURLToPath } from "node:url";
5
+ import { chromium, expect } from "@playwright/test";
6
+ import { createChromiumLaunchOptions, startViteFixture, stopProcess } from "../../../tooling/testUtils/browserFixture.mjs";
7
+
8
+ const TEST_ROOT = fileURLToPath(new URL(".", import.meta.url));
9
+ const SKIP = process.env.JSKIT_MATERIAL_WEB_BROWSER === "1" ? false : "set JSKIT_MATERIAL_WEB_BROWSER=1";
10
+ const FIELDS = 300;
11
+
12
+ // Opens the fixture with Vuetify's loader modules as published or as material-web's install patch leaves them
13
+ // (vite.config.js), and fails on any page error.
14
+ async function withLoaders(loaders, run) {
15
+ const vite = await startViteFixture({ fixtureRoot: TEST_ROOT, configFile: "vite.config.js", env: { JSKIT_VUETIFY_LOADERS: loaders } });
16
+ let browser;
17
+ try {
18
+ browser = await chromium.launch(createChromiumLaunchOptions());
19
+ const page = await browser.newPage({ baseURL: vite.baseURL, viewport: { width: 1280, height: 800 } });
20
+ const errors = [];
21
+ page.on("pageerror", (error) => errors.push(error.message));
22
+ const result = await run(page);
23
+ assert.deepEqual(errors, [], `${loaders}: page errors`);
24
+ return result;
25
+ } finally {
26
+ await browser?.close();
27
+ await stopProcess(vite);
28
+ }
29
+ }
30
+
31
+ async function mountFields(page) {
32
+ await page.goto("/?view=fields", { waitUntil: "networkidle" });
33
+ await page.waitForFunction(() => typeof window.mountFields === "function");
34
+ return page.evaluate((count) => window.mountFields(count), FIELDS);
35
+ }
36
+
37
+ const runningAnimations = (locator) => locator.evaluate(
38
+ (element) => element.getAnimations({ subtree: true }).filter((animation) => animation.playState === "running").length
39
+ );
40
+
41
+ // A progress indicator's classes (without the reveal transition's passing one) and size.
42
+ async function describeProgress(locator) {
43
+ return locator.evaluate((element) => {
44
+ const { width, height } = element.getBoundingClientRect();
45
+ return { classes: [...element.classList].filter((name) => !name.endsWith("--revealing")).sort(), width, height };
46
+ });
47
+ }
48
+
49
+ async function expectAnimating(locator, name) {
50
+ await expect.poll(() => runningAnimations(locator), { message: `${name} animates` }).toBeGreaterThan(0);
51
+ }
52
+
53
+ // What the three loaders show once they settle: the loading field's bar and the circular progress at the top, and the
54
+ // bar below the fold before and after it scrolls into view (which takes the other two out of view); each animates
55
+ // while in view.
56
+ async function showLoaders(page) {
57
+ await page.goto("/?view=loaders", { waitUntil: "networkidle" });
58
+ const loadingBar = page.getByTestId("loading-field").locator(".v-field__loader .v-progress-linear");
59
+ const circular = page.getByTestId("circular").locator(".v-progress-circular");
60
+ const belowFold = page.getByTestId("below-fold").locator(".v-progress-linear");
61
+ await expect(loadingBar).toHaveClass(/v-progress-linear--active/u);
62
+ await expectAnimating(loadingBar, "the loading field's bar");
63
+ await expect(circular).toHaveClass(/v-progress-circular--visible/u);
64
+ await expect(circular.locator("svg circle")).not.toHaveCount(0);
65
+ await expectAnimating(circular, "the circular progress");
66
+ const shown = { loadingBar: await describeProgress(loadingBar), circular: await describeProgress(circular) };
67
+ // Off screen, the intersection observer reports the bar hidden, so it stays inactive until it scrolls into view.
68
+ await expect(belowFold).not.toHaveClass(/v-progress-linear--active/u);
69
+ shown.belowFoldBefore = await describeProgress(belowFold);
70
+ await belowFold.scrollIntoViewIfNeeded();
71
+ await expect(belowFold).toHaveClass(/v-progress-linear--active/u);
72
+ await expectAnimating(belowFold, "the bar scrolled into view");
73
+ shown.belowFoldAfter = await describeProgress(belowFold);
74
+ return shown;
75
+ }
76
+
77
+ test("300 fields mount with no layout read from their idle loaders once patched; Vuetify as published reads one per field", {
78
+ skip: SKIP,
79
+ timeout: 180_000
80
+ }, async (t) => {
81
+ const published = await withLoaders("published", mountFields);
82
+ const patched = await withLoaders("patched", mountFields);
83
+ t.diagnostic(`${FIELDS} fields, getBoundingClientRect() on .v-progress-linear while mounting: as published ` +
84
+ `${published.progressReads} (${Math.round(published.milliseconds)} ms to mount), patched ${patched.progressReads} ` +
85
+ `(${Math.round(patched.milliseconds)} ms); reads of anything else ${published.otherReads} and ${patched.otherReads}`);
86
+ assert.equal(patched.progressReads, 0, "the patched idle loaders read no layout while the fields mount");
87
+ assert.equal(
88
+ published.progressReads,
89
+ FIELDS,
90
+ "Vuetify as published no longer reads layout in its idle loaders, so vuetifyjs/vuetify#23393 is fixed: remove " +
91
+ "material-web's install patch (scripts/patch-vuetify-loaders.mjs), its tests and this one"
92
+ );
93
+ });
94
+
95
+ test("patched loaders look as published: a loading field's bar, a circular progress and a bar scrolled into view show and animate", {
96
+ skip: SKIP,
97
+ timeout: 180_000
98
+ }, async () => {
99
+ const published = await withLoaders("published", showLoaders);
100
+ const patched = await withLoaders("patched", showLoaders);
101
+ assert.deepEqual(patched, published);
102
+ });
@@ -0,0 +1,202 @@
1
+ import assert from "node:assert/strict";
2
+ import { execFile } from "node:child_process";
3
+ import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import process from "node:process";
7
+ import test from "node:test";
8
+ import { fileURLToPath } from "node:url";
9
+ import { promisify } from "node:util";
10
+ import { PATCH, TARGETS, main, patchSource, patchVuetify } from "../scripts/patch-vuetify-loaders.mjs";
11
+
12
+ const execFileAsync = promisify(execFile);
13
+ const PACKAGE_ROOT = fileURLToPath(new URL("..", import.meta.url));
14
+ // Vuetify 4.3.3's three loader modules as published (sha-256 checked against its npm tarball); the test install holds
15
+ // the Vuetify JSKIT pins, whole.
16
+ const FIXTURE_4_3_3 = fileURLToPath(new URL("./fixtures/vuetify-4.3.3/", import.meta.url));
17
+ // Vuetify's other callers of useElementIntersection, which the patch leaves alone, in lib and in every bundle.
18
+ const OTHER_CALLS = Object.freeze({
19
+ "lib/components/VOtpInput/VOtpInput.js": "useElementIntersection(inputRef)",
20
+ "lib/components/VAlert/autoDismiss.js": "useElementIntersection(rootEl)",
21
+ "lib/components/VInfiniteScroll/VInfiniteScroll.js": "useElementIntersection(el)",
22
+ "lib/components/VParallax/VParallax.js": "useElementIntersection(el)"
23
+ });
24
+ const UNTOUCHED = Object.freeze([...Object.keys(OTHER_CALLS), "dist/vuetify.min.js"]);
25
+ const LINE = "@jskit-ai/material-web:";
26
+
27
+ async function installedVuetify() {
28
+ for (let directory = PACKAGE_ROOT; ; directory = path.dirname(directory)) {
29
+ const candidate = path.join(directory, "node_modules", "vuetify");
30
+ if (await stat(path.join(candidate, "package.json")).then(() => true, () => false)) return candidate;
31
+ assert.notEqual(path.dirname(directory), directory, "the test install has no vuetify");
32
+ }
33
+ }
34
+
35
+ // The installed Vuetify's files as Vuetify publishes them: the install may have patched them already.
36
+ async function publishedVuetify() {
37
+ const vuetify = await installedVuetify();
38
+ const files = {};
39
+ for (const file of ["package.json", ...Object.keys(TARGETS), ...UNTOUCHED]) {
40
+ files[file] = (await readFile(path.join(vuetify, file), "utf8")).replaceAll(PATCH, "");
41
+ }
42
+ return files;
43
+ }
44
+
45
+ async function writeVuetify(directory, files) {
46
+ for (const [file, text] of Object.entries(files)) {
47
+ await mkdir(path.dirname(path.join(directory, file)), { recursive: true });
48
+ await writeFile(path.join(directory, file), text);
49
+ }
50
+ }
51
+
52
+ async function readVuetify(directory, files) {
53
+ return Object.fromEntries(await Promise.all(files.map(async (file) => [file, await readFile(path.join(directory, file), "utf8")])));
54
+ }
55
+
56
+ async function temporaryDirectory(t) {
57
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jskit-vuetify-loaders-"));
58
+ t.after(() => rm(directory, { recursive: true, force: true }));
59
+ return directory;
60
+ }
61
+
62
+ async function runPatch(project) {
63
+ const lines = [];
64
+ await main({ env: { INIT_CWD: project }, cwd: project, log: (line) => lines.push(line) });
65
+ return lines;
66
+ }
67
+
68
+ const count = (text, part) => text.split(part).length - 1;
69
+
70
+ test("the patch passes { immediate: false } to the three loaders' calls in lib and every bundle, and to no other call", async (t) => {
71
+ const published = await publishedVuetify();
72
+ const vuetify = path.join(await temporaryDirectory(t), "node_modules", "vuetify");
73
+ await writeVuetify(vuetify, published);
74
+
75
+ const result = await patchVuetify(vuetify);
76
+ assert.deepEqual(result.patched, Object.keys(TARGETS));
77
+ const now = await readVuetify(vuetify, Object.keys(published));
78
+ for (const [file, loaders] of Object.entries(TARGETS)) {
79
+ assert.equal(count(now[file], `useElementIntersection(root${PATCH})`), loaders.length, file);
80
+ assert.equal(count(now[file], PATCH), loaders.length, file);
81
+ assert.equal(now[file].replaceAll(PATCH, ""), published[file], `${file}: only the loaders' calls change`);
82
+ assert.deepEqual(patchSource(now[file], loaders), { source: now[file], patched: 0 }, `${file}: every loader is patched`);
83
+ if (file.startsWith("dist/")) {
84
+ for (const call of new Set(Object.values(OTHER_CALLS))) {
85
+ assert.equal(count(now[file], call), count(published[file], call), `${file} keeps ${call}`);
86
+ }
87
+ }
88
+ }
89
+ for (const file of UNTOUCHED) assert.equal(now[file], published[file], `${file} is left alone`);
90
+ });
91
+
92
+ test("Vuetify 4.3.3's loader modules, as published, take the same patch", async () => {
93
+ for (const [file, loaders] of Object.entries(TARGETS).filter(([file]) => file.startsWith("lib/"))) {
94
+ const published = await readFile(path.join(FIXTURE_4_3_3, file), "utf8");
95
+ const result = patchSource(published, loaders);
96
+ assert.equal(result.patched, 1, file);
97
+ assert.equal(count(result.source, `useElementIntersection(root${PATCH})`), 1, file);
98
+ assert.equal(result.source.replaceAll(PATCH, ""), published, file);
99
+ }
100
+ });
101
+
102
+ test("a second run changes nothing, and a reinstalled Vuetify is patched again", async (t) => {
103
+ const published = await publishedVuetify();
104
+ const project = await temporaryDirectory(t);
105
+ const vuetify = path.join(project, "node_modules", "vuetify");
106
+ await writeVuetify(vuetify, published);
107
+ const version = JSON.parse(published["package.json"]).version;
108
+
109
+ assert.deepEqual(await runPatch(project), [
110
+ `${LINE} patched the idle loaders of Vuetify ${version} (node_modules/vuetify) in 9 files for vuetifyjs/vuetify#23393.`
111
+ ]);
112
+ const patched = await readVuetify(vuetify, Object.keys(TARGETS));
113
+ const times = await Promise.all(Object.keys(TARGETS).map(async (file) => (await stat(path.join(vuetify, file))).mtimeMs));
114
+ assert.deepEqual(await runPatch(project), [
115
+ `${LINE} the idle loaders of Vuetify ${version} (node_modules/vuetify) are already patched for vuetifyjs/vuetify#23393.`
116
+ ]);
117
+ assert.deepEqual(await readVuetify(vuetify, Object.keys(TARGETS)), patched);
118
+ assert.deepEqual(await Promise.all(Object.keys(TARGETS).map(async (file) => (await stat(path.join(vuetify, file))).mtimeMs)), times);
119
+
120
+ await writeVuetify(vuetify, published);
121
+ assert.match((await runPatch(project)).join("\n"), /^@jskit-ai\/material-web: patched the idle loaders of Vuetify .* in 9 files/u);
122
+ assert.deepEqual(await readVuetify(vuetify, Object.keys(TARGETS)), patched);
123
+ });
124
+
125
+ test("a Vuetify whose loaders are fixed or rewritten is left exactly as it is, with one line naming #23393", async (t) => {
126
+ const published = await publishedVuetify();
127
+ const lib = "lib/components/VProgressLinear/VProgressLinear.js";
128
+ const labs = "dist/vuetify-labs.esm.js";
129
+ const variants = {
130
+ "fixed upstream": [lib, (text) => text.replace("useElementIntersection(root)", "useElementIntersection(root, { immediate: false })"),
131
+ `${lib}: VProgressLinear calls useElementIntersection with other arguments`],
132
+ "a loader calling it twice": [labs, (text) => text.replace(/useElementIntersection\(root\);(?=\n\s*const elapsed)/u, "$&\n useElementIntersection(root);"),
133
+ `${labs}: VLoadingIndicator does not call useElementIntersection exactly once`],
134
+ "a loader gone": [labs, (text) => text.replace("name: 'VLoadingIndicator',", "name: 'VLoadingDots',"),
135
+ `${labs}: 0 definitions of VLoadingIndicator`],
136
+ "a bundle gone": ["dist/vuetify.cjs", () => null, "dist/vuetify.cjs: missing"]
137
+ };
138
+ for (const [variant, [file, change, reason]] of Object.entries(variants)) {
139
+ const project = await temporaryDirectory(t);
140
+ const vuetify = path.join(project, "node_modules", "vuetify");
141
+ const files = { ...published, [file]: change(published[file]) };
142
+ assert.notEqual(files[file], published[file], variant);
143
+ if (files[file] === null) delete files[file];
144
+ await writeVuetify(vuetify, files);
145
+
146
+ const version = JSON.parse(published["package.json"]).version;
147
+ assert.deepEqual(await runPatch(project), [
148
+ `${LINE} Vuetify ${version} (node_modules/vuetify) does not have the idle-loader code patched for vuetifyjs/vuetify#23393 ` +
149
+ `(${reason}); left it unchanged.`
150
+ ], variant);
151
+ assert.deepEqual(await readVuetify(vuetify, Object.keys(files)), files, `${variant}: no file changed`);
152
+ }
153
+ });
154
+
155
+ test("Vuetify's copies nested under other packages are patched with the one INIT_CWD resolves to, and no other", async (t) => {
156
+ const published = await publishedVuetify();
157
+ const root = await temporaryDirectory(t);
158
+ const project = path.join(root, "app");
159
+ const copies = ["node_modules/vuetify", "node_modules/@scope/widgets/node_modules/vuetify", "node_modules/table/node_modules/vuetify"];
160
+ for (const copy of copies) await writeVuetify(path.join(project, copy), published);
161
+ await writeVuetify(path.join(root, "elsewhere", "node_modules", "vuetify"), published);
162
+ await mkdir(path.join(project, "packages", "main"), { recursive: true });
163
+
164
+ const lines = await runPatch(path.join(project, "packages", "main"));
165
+ assert.equal(lines.length, 3, lines.join("\n"));
166
+ for (const copy of copies) {
167
+ assert.ok(lines.some((line) => line.includes(`(${path.join("..", "..", copy)}) in 9 files`)), `${copy}: ${lines.join("\n")}`);
168
+ assert.equal(count(await readFile(path.join(project, copy, "dist/vuetify-labs.esm.js"), "utf8"), PATCH), 3, copy);
169
+ }
170
+ assert.equal(count(await readFile(path.join(root, "elsewhere/node_modules/vuetify/dist/vuetify.esm.js"), "utf8"), PATCH), 0);
171
+ });
172
+
173
+ test("the postinstall never fails an install: no Vuetify, an unreadable file or a broken package.json is one line or none, exit 0", async (t) => {
174
+ const { postinstall } = JSON.parse(await readFile(path.join(PACKAGE_ROOT, "package.json"), "utf8")).scripts;
175
+ assert.equal(postinstall, "node ./scripts/patch-vuetify-loaders.mjs");
176
+ const install = async (project) => {
177
+ const { stdout, stderr } = await execFileAsync(process.execPath, ["./scripts/patch-vuetify-loaders.mjs"], {
178
+ cwd: PACKAGE_ROOT,
179
+ env: { ...process.env, INIT_CWD: project, npm_config_local_prefix: project }
180
+ });
181
+ return { lines: stdout.split("\n").filter(Boolean), stderr };
182
+ };
183
+
184
+ const empty = await temporaryDirectory(t);
185
+ assert.deepEqual(await install(empty), { lines: [], stderr: "" });
186
+ assert.deepEqual(await readdir(empty), []);
187
+
188
+ const published = await publishedVuetify();
189
+ const unreadable = await temporaryDirectory(t);
190
+ const { "dist/vuetify.cjs": cjs, ...rest } = published;
191
+ assert.ok(cjs);
192
+ await writeVuetify(path.join(unreadable, "node_modules", "vuetify"), { ...rest, "dist/vuetify.cjs/index.js": "" });
193
+ const broken = await temporaryDirectory(t);
194
+ await writeVuetify(path.join(broken, "node_modules", "vuetify"), { ...published, "package.json": "{" });
195
+ for (const project of [unreadable, broken]) {
196
+ const { lines, stderr } = await install(project);
197
+ assert.equal(stderr, "");
198
+ assert.equal(lines.length, 1, lines.join("\n"));
199
+ assert.match(lines[0], /^@jskit-ai\/material-web: could not patch Vuetify's idle loaders for vuetifyjs\/vuetify#23393: /u);
200
+ }
201
+ assert.equal(count(await readFile(path.join(unreadable, "node_modules/vuetify/dist/vuetify.esm.js"), "utf8"), PATCH), 0);
202
+ });