@jskit-ai/material-web 0.1.5 → 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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - Fields open fast again: material-web's install script (`postinstall`) stops Vuetify's idle loaders reading layout as they mount ([vuetifyjs/vuetify#23393](https://github.com/vuetifyjs/vuetify/issues/23393)). Every `VField`-based input mounts an idle `VProgressLinear`, whose `useElementIntersection(root)` read `getBoundingClientRect()` at once, a forced layout per field in a form that writes a style as it mounts: 300 fields took 15.9 s to mount, 1.3 s patched (the package's browser test). The script passes `{ immediate: false }` to the three loaders' calls (`VProgressLinear`, `VProgressCircular`, labs' `VLoadingIndicator`) in the installed Vuetify's `lib/` modules and its `dist/vuetify(-labs).esm.js`, `.cjs` and `.js` builds, all or nothing per Vuetify copy, and only where it finds exactly the calls it expects; otherwise it prints one line naming the issue and changes nothing. It never fails an install. Approve it in the app's root `package.json` (`"allowScripts": { "@jskit-ai/material-web": true }`, which `jskit update` adds): a strict install (`strict-allow-scripts`) fails without the approval, and an install with `--ignore-scripts` leaves Vuetify as published until `npm rebuild @jskit-ai/material-web`. Remove it once a fixed Vuetify is pinned; the README's Upstream workarounds says how.
5
6
  - `material.css` draws every `v-bottom-navigation` as Material 3's navigation bar: a destination (each of its stacked buttons) has its icon, its `prepend-icon` or the first icon in its content (bare or in a badge), 24dp in a 64x32 pill that is its active indicator (`secondary-container`, the icon `on-secondary-container`) and holds its hover, focus and pressed state layer, where Vuetify drew its overlay and ripple across the whole button; the label is label-medium, 4dp below, `on-surface-variant` at rest and `on-surface` when active. A comfortable bar (48dp) drops the 4dp and a compact one (40dp) has a 24dp pill, so neither clips a label. The colours apply only where the app set none: a bar's `bg-color` (other than a surface tone) or colour class, and a destination's `color`, `base-color` or colour class, keep the app's colour on label and icon, the active pill drawn in that colour. An append icon, a badge's own icon and `mode="horizontal"` keep Vuetify's look. It was drawn only by the shell's `ShellTabLinkItem`, so an app's own bar of `v-btn`s kept Vuetify's look.
6
7
  - **Breaking (visual).** Fields (`v-text-field`, `v-textarea`, `v-select`, `v-autocomplete`, `v-combobox`, `v-file-input`) keep Vuetify's line for their supporting text, as a Material 3 text field does: the defaults no longer set `hideDetails: "auto"`. With it, a field had no line until it had a message, so an error shown on blur or submit pushed the rest of the form down under the person's finger, and forms made up the space with a margin under each field. Upgrading: in a form, remove the `mb-*` margin under each field (the line is the gap now); a field outside a form (a search box, a filter, a toolbar select, a composer) sets `hide-details`, or `hide-details="auto"` to show a message only when it has one.
7
8
  - `material.css` has a `text-on-*` class for every `on-*` role of the scheme. It had them for the main roles, success, warning and info, but not for the fixed roles' (`on-primary-fixed`, `on-primary-fixed-variant` and the secondary and tertiary ones) or the surface tones' (`on-surface-dim`, `on-surface-bright`, `on-surface-container-lowest` to `-highest`), so `color="on-primary-fixed-variant"` found no class. Vuetify names an `on-*` role's class `.on-<role>` only; an app colour's `on-*` roles keep that class alone. material-web's node test checks the classes against the generated scheme's roles.
package/README.md CHANGED
@@ -130,6 +130,41 @@ Each one comes off when the upstream fix ships; its test says when.
130
130
  would make an inline style). shell-web's browser test "a virtual-scroll list
131
131
  in a dialog reaches its last item after the page around it re-renders"
132
132
  guards it; it fails with `VDialog: { VCard: {} }` in the defaults.
133
+ - **Vuetify 4.3.2 and 4.3.3 (measured): idle loaders read layout as they
134
+ mount.** Every field built on `VField` (`v-text-field`, `v-select`,
135
+ `v-textarea` and the others) mounts an idle `VProgressLinear` in its loader
136
+ slot, and Vuetify's loaders (`VProgressLinear`, `VProgressCircular` and labs'
137
+ `VLoadingIndicator`) call `useElementIntersection(root)`, whose first check
138
+ runs at once and reads `getBoundingClientRect()`. In a form that writes a
139
+ style as it mounts, that is a forced layout per field: in this package's
140
+ browser test, 300 fields took 15.9 s to mount as Vuetify publishes them and
141
+ 1.3 s patched. Upstream issue:
142
+ [vuetifyjs/vuetify#23393](https://github.com/vuetifyjs/vuetify/issues/23393).
143
+ material-web's install script (`scripts/patch-vuetify-loaders.mjs`, its
144
+ `postinstall`) passes `{ immediate: false }` to those three calls in the
145
+ installed Vuetify: its `lib/` modules and the builds `vuetify/dist/vuetify.js`
146
+ and `vuetify/dist/vuetify-labs.js` resolve to (`.esm.js`, `.cjs` and the UMD
147
+ build at that path). The intersection observer still reports what is in
148
+ view, so a loading field's bar still shows and a bar scrolled into view still
149
+ animates; no form needs a workaround of its own. `dist/vuetify.min.js` stays
150
+ as published: no export names it (it is the CDN script build), and its
151
+ minified names would need a looser match. So do Vuetify's other callers
152
+ (`VOtpInput`, `VAlert`'s auto-dismiss, `VInfiniteScroll`, `VParallax`). The
153
+ script patches a Vuetify copy only where it finds exactly the calls it
154
+ expects, all of them or none, and otherwise prints one line naming the issue
155
+ and changes nothing; a second run changes nothing, and it never fails an
156
+ install. It patches the Vuetify the installing project resolves and the
157
+ copies nested under that project's other packages.
158
+
159
+ The app's root `package.json` approves the script, as `jskit update` writes
160
+ it: `"allowScripts": { "@jskit-ai/material-web": true }`. Without it npm 11
161
+ runs it with a warning, and a strict install (`strict-allow-scripts`, as
162
+ JSKIT's CI runs) fails. An install with `--ignore-scripts` leaves Vuetify as
163
+ published; `npm rebuild @jskit-ai/material-web` patches it afterwards. The
164
+ browser test "300 fields mount with no layout read from their idle loaders
165
+ once patched; Vuetify as published reads one per field" fails once a Vuetify
166
+ release fixes the issue; then pin it and delete the script, its tests, the
167
+ `postinstall` and `jskit update`'s approval.
133
168
 
134
169
  ## Maintaining the icon set
135
170
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/material-web",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "type": "module",
5
5
  "description": "Exact Material 3 for JSKIT Vuetify apps: seed-generated light and dark schemes, Material Symbols Rounded icon aliases, Roboto Flex and Material 3 component defaults.",
6
6
  "exports": {
@@ -34,7 +34,8 @@
34
34
  }
35
35
  },
36
36
  "scripts": {
37
- "test": "jskit test",
37
+ "postinstall": "node ./scripts/patch-vuetify-loaders.mjs",
38
+ "test": "jskit test test/*.test.js",
38
39
  "symbols:generate": "node ./scripts/generate-symbols.mjs"
39
40
  }
40
41
  }
@@ -0,0 +1,216 @@
1
+ #!/usr/bin/env node
2
+ // material-web's postinstall: stops Vuetify's idle loaders reading layout as they mount.
3
+ // https://github.com/vuetifyjs/vuetify/issues/23393 (open). Remove once a fixed Vuetify is pinned.
4
+ //
5
+ // Since Vuetify 4.3.0 every field (VTextField, VTextarea, VSelect, VAutocomplete, VCombobox, VNumberInput, VFileInput)
6
+ // renders an idle VProgressLinear, which, like VProgressCircular and the labs VLoadingIndicator, calls @vuetify/v0's
7
+ // useElementIntersection(root). Its default `immediate: true` calls root.getBoundingClientRect() on mount for a first
8
+ // entry that hard-codes isIntersecting: false, so the read tells it nothing; the IntersectionObserver sends its own
9
+ // first entry anyway. When anything writes to the page between two fields mounting, each read forces a layout: 300
10
+ // fields took about 15 s to mount instead of 0.4 s. This script passes `{ immediate: false }` to those three calls and
11
+ // to no other, in the copies of Vuetify the project installed:
12
+ // - lib/, which `vuetify`, `vuetify/components`, `vuetify/labs/*` and the auto-imports resolve to;
13
+ // - the dist/ bundles that `vuetify/dist/vuetify.js` and `vuetify/dist/vuetify-labs.js` resolve to (.esm.js on import,
14
+ // .cjs on require), and the UMD builds at those paths, which a tool that ignores `exports` loads for them.
15
+ // dist/vuetify.min.js stays as published: no export names it (only the `./*` catch-all, which reaches every file), it is
16
+ // the CDN script build, and its minified names would need a second, looser matcher.
17
+ // It changes a file only where it finds exactly the calls it expects, and nothing at all in a Vuetify where any is
18
+ // missing or different (fixed upstream, or rewritten). It never fails an install: every outcome is one line, exit 0.
19
+ import { realpathSync } from "node:fs";
20
+ import { chmod, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
21
+ import path from "node:path";
22
+ import process from "node:process";
23
+ import { fileURLToPath } from "node:url";
24
+
25
+ const ISSUE = "vuetifyjs/vuetify#23393";
26
+ // What the patch adds inside each call. The comment marks a call as patched here, so a second run changes nothing and
27
+ // a Vuetify that passes the option itself reads as changed, not as patched.
28
+ const PATCH = ", { immediate: false } /* @jskit-ai/material-web: vuetifyjs/vuetify#23393 */";
29
+ const LOADERS = Object.freeze(["VProgressLinear", "VProgressCircular", "VLoadingIndicator"]);
30
+ const CORE_LOADERS = LOADERS.slice(0, 2);
31
+ // Each file the patch changes, relative to the Vuetify package, with the loaders it defines.
32
+ const TARGETS = Object.freeze({
33
+ "lib/components/VProgressLinear/VProgressLinear.js": ["VProgressLinear"],
34
+ "lib/components/VProgressCircular/VProgressCircular.js": ["VProgressCircular"],
35
+ "lib/labs/VLoadingIndicator/VLoadingIndicator.js": ["VLoadingIndicator"],
36
+ "dist/vuetify.esm.js": CORE_LOADERS,
37
+ "dist/vuetify.cjs": CORE_LOADERS,
38
+ "dist/vuetify.js": CORE_LOADERS,
39
+ "dist/vuetify-labs.esm.js": LOADERS,
40
+ "dist/vuetify-labs.cjs": LOADERS,
41
+ "dist/vuetify-labs.js": LOADERS
42
+ });
43
+ const CALL = "useElementIntersection(";
44
+ const CALL_HEAD = /^useElementIntersection\([A-Za-z_$][\w$]*/u;
45
+
46
+ /**
47
+ * Where component `name` calls useElementIntersection in `source`: its definition runs from its one `name: '<name>'`
48
+ * line to the next line at its `const <name> = ...` indentation that is not a closing bracket (the next statement).
49
+ * It must hold exactly one call, on one variable, as published (`patched: false`) or as patched here (`patched: true`).
50
+ * @param {string} source
51
+ * @param {string} name
52
+ * @returns {{ end?: number, patched: boolean } | string} the published call's closing parenthesis, or what differs
53
+ */
54
+ function findLoaderCall(source, name) {
55
+ const definitions = [...source.matchAll(new RegExp(`^([ \\t]*)name: ['"]${name}['"],$`, "gmu"))];
56
+ if (definitions.length !== 1) return `${definitions.length} definitions of ${name}`;
57
+ const [{ index: start, 1: indent }] = definitions;
58
+ const nextStatement = new RegExp(`^${indent.replace(/ {2}$/u, "")}[^\\s})\\]]`, "gmu");
59
+ nextStatement.lastIndex = start + indent.length;
60
+ const definition = source.slice(start, nextStatement.exec(source)?.index ?? source.length);
61
+ const at = definition.indexOf(CALL);
62
+ if (at < 0 || definition.indexOf(CALL, at + 1) >= 0) return `${name} does not call useElementIntersection exactly once`;
63
+ const call = definition.slice(at);
64
+ const head = CALL_HEAD.exec(call)?.[0] ?? "";
65
+ if (head && call.startsWith(")", head.length)) return { end: start + at + head.length, patched: false };
66
+ if (head && call.startsWith(`${PATCH})`, head.length)) return { patched: true };
67
+ return `${name} calls useElementIntersection with other arguments`;
68
+ }
69
+
70
+ /**
71
+ * The patched text of one Vuetify file that defines `loaders`.
72
+ * @param {string} source
73
+ * @param {ReadonlyArray<string>} loaders
74
+ * @returns {{ source: string, patched: number } | { changed: string }} `patched` counts the calls patched now
75
+ */
76
+ function patchSource(source, loaders) {
77
+ const calls = [];
78
+ for (const name of loaders) {
79
+ const call = findLoaderCall(source, name);
80
+ if (typeof call === "string") return { changed: call };
81
+ calls.push(call);
82
+ }
83
+ const pending = calls.filter((call) => !call.patched).sort((left, right) => right.end - left.end);
84
+ let text = source;
85
+ for (const { end } of pending) text = `${text.slice(0, end)}${PATCH}${text.slice(end)}`;
86
+ return { source: text, patched: pending.length };
87
+ }
88
+
89
+ // Writes beside the file and renames it into place: an interrupted install leaves the old file, and a file
90
+ // hard-linked from a package store is replaced in this project only.
91
+ async function replaceFile(file, text) {
92
+ const { mode } = await stat(file);
93
+ const temporary = `${file}.jskit-${process.pid}.tmp`;
94
+ try {
95
+ await writeFile(temporary, text, "utf8");
96
+ await chmod(temporary, mode);
97
+ await rename(temporary, file);
98
+ } finally {
99
+ await rm(temporary, { force: true });
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Patches the Vuetify package in `directory`, or changes nothing in it when any target file differs from what the
105
+ * patch expects.
106
+ * @param {string} directory
107
+ * @returns {Promise<{ version: string, patched: string[] } | { version: string, changed: string }>}
108
+ */
109
+ async function patchVuetify(directory) {
110
+ const { version } = JSON.parse(await readFile(path.join(directory, "package.json"), "utf8"));
111
+ const files = [];
112
+ for (const [file, loaders] of Object.entries(TARGETS)) {
113
+ const source = await readFile(path.join(directory, file), "utf8").catch((error) => {
114
+ if (error.code === "ENOENT") return null;
115
+ throw error;
116
+ });
117
+ const result = source === null ? { changed: "missing" } : patchSource(source, loaders);
118
+ if (result.changed) return { version, changed: `${file}: ${result.changed}` };
119
+ if (result.patched > 0) files.push({ file, source: result.source });
120
+ }
121
+ for (const { file, source } of files) await replaceFile(path.join(directory, file), source);
122
+ return { version, patched: files.map(({ file }) => file) };
123
+ }
124
+
125
+ async function isFile(file) {
126
+ return stat(file).then((stats) => stats.isFile(), () => false);
127
+ }
128
+
129
+ async function nearestVuetify(start) {
130
+ for (let directory = path.resolve(start); ; directory = path.dirname(directory)) {
131
+ const candidate = path.join(directory, "node_modules", "vuetify");
132
+ if (await isFile(path.join(candidate, "package.json"))) return candidate;
133
+ if (path.dirname(directory) === directory) return null;
134
+ }
135
+ }
136
+
137
+ // The copies nested in the packages under `nodeModules` (<package>/node_modules/vuetify, at any depth), which those
138
+ // packages import instead of the app's. Linked packages (workspaces) are not followed.
139
+ async function nestedVuetify(nodeModules) {
140
+ const copies = [];
141
+ const entries = (directory) => readdir(directory, { withFileTypes: true }).then(
142
+ (found) => found.filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")),
143
+ () => []
144
+ );
145
+ for (const entry of await entries(nodeModules)) {
146
+ const packages = entry.name.startsWith("@")
147
+ ? (await entries(path.join(nodeModules, entry.name))).map((scoped) => path.join(entry.name, scoped.name))
148
+ : [entry.name];
149
+ for (const name of packages) {
150
+ const inner = path.join(nodeModules, name, "node_modules");
151
+ if (await isFile(path.join(inner, "vuetify", "package.json"))) copies.push(path.join(inner, "vuetify"));
152
+ copies.push(...await nestedVuetify(inner));
153
+ }
154
+ }
155
+ return copies;
156
+ }
157
+
158
+ /**
159
+ * The Vuetify copies the project uses: the one each start directory resolves `vuetify` to, and the copies nested under
160
+ * that one's node_modules, each once.
161
+ * @param {ReadonlyArray<string>} starts
162
+ * @returns {Promise<string[]>}
163
+ */
164
+ async function findVuetifyCopies(starts) {
165
+ const copies = new Map();
166
+ for (const start of starts) {
167
+ const found = await nearestVuetify(start);
168
+ if (!found) continue;
169
+ for (const copy of [found, ...await nestedVuetify(path.dirname(found))]) {
170
+ const real = await realpath(copy);
171
+ if (!copies.has(real)) copies.set(real, copy);
172
+ }
173
+ }
174
+ return [...copies.values()];
175
+ }
176
+
177
+ /**
178
+ * Patches the Vuetify of the project being installed (INIT_CWD, and npm's project root) and reports one line per copy.
179
+ * Never throws: an error is reported in one line too.
180
+ * @param {{ env?: Record<string, string | undefined>, cwd?: string, log?: (line: string) => void }} [options]
181
+ */
182
+ async function main({ env = process.env, cwd = process.cwd(), log = console.log } = {}) {
183
+ const prefix = "@jskit-ai/material-web:";
184
+ const failed = (error) => {
185
+ log(`${prefix} could not patch Vuetify's idle loaders for ${ISSUE}: ${String(error?.message || error).split("\n")[0]}`);
186
+ };
187
+ try {
188
+ const project = env.INIT_CWD || cwd;
189
+ for (const directory of await findVuetifyCopies([project, env.npm_config_local_prefix].filter(Boolean))) {
190
+ const where = path.relative(project, directory) || directory;
191
+ const result = await patchVuetify(directory).catch((error) => ({ error }));
192
+ const vuetify = `Vuetify ${result.version} (${where})`;
193
+ if (result.error) failed(result.error);
194
+ else if (result.changed) log(`${prefix} ${vuetify} does not have the idle-loader code patched for ${ISSUE} (${result.changed}); left it unchanged.`);
195
+ else if (result.patched.length > 0) log(`${prefix} patched the idle loaders of ${vuetify} in ${result.patched.length} files for ${ISSUE}.`);
196
+ else log(`${prefix} the idle loaders of ${vuetify} are already patched for ${ISSUE}.`);
197
+ }
198
+ } catch (error) {
199
+ failed(error);
200
+ }
201
+ }
202
+
203
+ function isEntrypoint() {
204
+ try {
205
+ return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
206
+ } catch {
207
+ return false;
208
+ }
209
+ }
210
+
211
+ if (isEntrypoint()) {
212
+ await main();
213
+ process.exitCode = 0;
214
+ }
215
+
216
+ export { ISSUE, LOADERS, PATCH, TARGETS, findVuetifyCopies, main, patchSource, patchVuetify };
@@ -0,0 +1,72 @@
1
+ <script setup>
2
+ import { defineComponent, h, nextTick, ref, shallowRef, watch } from "vue";
3
+
4
+ // `?view=fields` mounts fields on request and counts the layout reads their idle loaders make
5
+ // (vuetifyjs/vuetify#23393); `?view=loaders` shows a loading field, a circular progress and, below the fold, an
6
+ // indeterminate bar.
7
+ const view = new URLSearchParams(window.location.search).get("view");
8
+ const shownCount = ref(0);
9
+ const list = ref();
10
+
11
+ // getBoundingClientRect() calls while fields mount: on a progress bar (the loaders') or on anything else.
12
+ const reads = { on: false, progress: 0, other: 0 };
13
+ const getBoundingClientRect = Element.prototype.getBoundingClientRect;
14
+ Element.prototype.getBoundingClientRect = function countedGetBoundingClientRect() {
15
+ if (reads.on) {
16
+ if (this.classList?.contains("v-progress-linear")) reads.progress += 1;
17
+ else reads.other += 1;
18
+ }
19
+ return getBoundingClientRect.call(this);
20
+ };
21
+
22
+ // A row part that writes a style on the list when its element appears, as row code often does: after each write, the
23
+ // next field's read lays the page out again.
24
+ const RowStamp = defineComponent({
25
+ props: { index: { type: Number, required: true } },
26
+ setup(props) {
27
+ const element = shallowRef();
28
+ watch(element, (node) => {
29
+ if (node) list.value.style.setProperty("--rows-mounted", String(props.index));
30
+ });
31
+ return () => h("span", { ref: element, class: "stamp" });
32
+ }
33
+ });
34
+
35
+ window.mountFields = async (count) => {
36
+ Object.assign(reads, { on: true, progress: 0, other: 0 });
37
+ const started = performance.now();
38
+ shownCount.value = count;
39
+ await nextTick();
40
+ const milliseconds = performance.now() - started;
41
+ reads.on = false;
42
+ return { progressReads: reads.progress, otherReads: reads.other, milliseconds };
43
+ };
44
+ </script>
45
+
46
+ <template>
47
+ <v-app>
48
+ <div v-if="view === 'fields'" ref="list">
49
+ <div v-for="row in shownCount" :key="row" class="field-row">
50
+ <v-text-field :label="`Field ${row}`" density="compact" hide-details />
51
+ <RowStamp :index="row" />
52
+ </div>
53
+ </div>
54
+ <div v-else>
55
+ <div data-testid="loading-field">
56
+ <v-text-field label="Loading" loading />
57
+ </div>
58
+ <div data-testid="circular">
59
+ <v-progress-circular indeterminate />
60
+ </div>
61
+ <div class="below-fold" data-testid="below-fold">
62
+ <v-progress-linear indeterminate />
63
+ </div>
64
+ </div>
65
+ </v-app>
66
+ </template>
67
+
68
+ <style>
69
+ .field-row { display: flex; align-items: center; gap: 8px; margin-bottom: 4px; }
70
+ .stamp { min-width: 64px; }
71
+ .below-fold { margin-top: 200vh; }
72
+ </style>
@@ -0,0 +1,2 @@
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Vuetify idle loaders</title></head><body><div id="app"></div><script type="module" src="/main.js"></script></body></html>
@@ -0,0 +1,10 @@
1
+ import { createApp } from "vue";
2
+ import { createVuetify } from "vuetify";
3
+ import { VApp } from "vuetify/components/VApp";
4
+ import { VProgressCircular } from "vuetify/components/VProgressCircular";
5
+ import { VProgressLinear } from "vuetify/components/VProgressLinear";
6
+ import { VTextField } from "vuetify/components/VTextField";
7
+ import "vuetify/styles";
8
+ import App from "./App.vue";
9
+
10
+ createApp(App).use(createVuetify({ components: { VApp, VProgressCircular, VProgressLinear, VTextField } })).mount("#app");
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016-now Vuetify, LLC
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
13
+ all 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
21
+ THE SOFTWARE.
@@ -0,0 +1,209 @@
1
+ import { normalizeClass as _normalizeClass, normalizeStyle as _normalizeStyle, createElementVNode as _createElementVNode, Fragment as _Fragment, createVNode as _createVNode } from "vue";
2
+ // Styles
3
+ import "./VProgressCircular.css";
4
+
5
+ // Components
6
+ import { circularWavePath, hasWave } from "../VProgressLinear/waves.js"; // Composables
7
+ import { useTextColor } from "../../composables/color.js";
8
+ import { makeComponentProps } from "../../composables/component.js";
9
+ import { useElementIntersection } from "../../composables/intersectionObserver.js";
10
+ import { useElementSize } from "../../composables/resizeObserver.js";
11
+ import { makeRevealProps, useReveal } from "../../composables/reveal.js";
12
+ import { makeSizeProps, useSize } from "../../composables/size.js";
13
+ import { makeTagProps } from "../../composables/tag.js";
14
+ import { makeThemeProps, provideTheme } from "../../composables/theme.js"; // Utilities
15
+ import { computed, shallowRef, toRef } from 'vue';
16
+ import { clamp, convertToUnit, genericComponent, isObject, PREFERS_REDUCED_MOTION, propsFactory, useRender } from "../../util/index.js"; // Types
17
+ // in px, scaled to the viewBox
18
+ const WAVE_AMPLITUDE = 1.6;
19
+ const WAVELENGTH = 15;
20
+ const WAVE_GAP = 4;
21
+ export const makeVProgressCircularProps = propsFactory({
22
+ bgColor: String,
23
+ color: String,
24
+ indeterminate: [Boolean, String],
25
+ rounded: Boolean,
26
+ modelValue: {
27
+ type: [Number, String],
28
+ default: 0
29
+ },
30
+ rotate: {
31
+ type: [Number, String],
32
+ default: 0
33
+ },
34
+ shape: {
35
+ type: String,
36
+ default: 'flat',
37
+ validator: v => ['flat', 'wavy'].includes(v)
38
+ },
39
+ variant: {
40
+ type: String,
41
+ default: undefined,
42
+ validator: v => ['split'].includes(v)
43
+ },
44
+ transition: {
45
+ type: [Boolean, Object],
46
+ default: undefined
47
+ },
48
+ width: {
49
+ type: [Number, String],
50
+ default: 4
51
+ },
52
+ ...makeComponentProps(),
53
+ ...makeRevealProps(),
54
+ ...makeSizeProps(),
55
+ ...makeTagProps({
56
+ tag: 'div'
57
+ }),
58
+ ...makeThemeProps()
59
+ }, 'VProgressCircular');
60
+ export const VProgressCircular = genericComponent()({
61
+ name: 'VProgressCircular',
62
+ props: makeVProgressCircularProps(),
63
+ setup(props, {
64
+ slots
65
+ }) {
66
+ const MAGIC_RADIUS_CONSTANT = 20;
67
+ const CIRCUMFERENCE = 2 * Math.PI * MAGIC_RADIUS_CONSTANT;
68
+ const root = shallowRef();
69
+ const {
70
+ themeClasses
71
+ } = provideTheme(props);
72
+ const {
73
+ sizeClasses,
74
+ sizeStyles
75
+ } = useSize(props);
76
+ const {
77
+ textColorClasses,
78
+ textColorStyles
79
+ } = useTextColor(() => props.color);
80
+ const {
81
+ textColorClasses: underlayColorClasses,
82
+ textColorStyles: underlayColorStyles
83
+ } = useTextColor(() => props.bgColor);
84
+ const {
85
+ width: containerWidth
86
+ } = useElementSize(root);
87
+ const {
88
+ isIntersecting
89
+ } = useElementIntersection(root);
90
+ const {
91
+ state: revealState,
92
+ duration: revealDuration
93
+ } = useReveal(props);
94
+ const normalizedValue = toRef(() => revealState.value === 'initial' ? 0 : clamp(parseFloat(props.modelValue), 0, 100));
95
+ const width = toRef(() => Number(props.width));
96
+ const transitionDuration = toRef(() => props.transition === false ? undefined : convertToUnit(isObject(props.transition) ? props.transition.duration : undefined, 'ms'));
97
+ const size = toRef(() => {
98
+ // Get size from element if size prop value is small, large etc
99
+ return sizeStyles.value ? Number(props.size) : containerWidth.value ? containerWidth.value : Math.max(width.value, 32);
100
+ });
101
+ const diameter = toRef(() => MAGIC_RADIUS_CONSTANT / (1 - width.value / size.value) * 2);
102
+ const strokeWidth = toRef(() => width.value / size.value * diameter.value);
103
+ const strokeDashOffset = toRef(() => {
104
+ const baseLength = (100 - normalizedValue.value) / 100 * CIRCUMFERENCE;
105
+ return props.rounded && normalizedValue.value > 0 && normalizedValue.value < 100 ? convertToUnit(Math.min(CIRCUMFERENCE - 0.01, baseLength + strokeWidth.value)) : convertToUnit(baseLength);
106
+ });
107
+ const startAngle = computed(() => {
108
+ const baseAngle = Number(props.rotate);
109
+ return props.rounded ? baseAngle + strokeWidth.value / 2 / CIRCUMFERENCE * 360 : baseAngle;
110
+ });
111
+ const isWavy = toRef(() => props.shape === 'wavy');
112
+ const geometry = computed(() => {
113
+ if (props.variant !== 'split' && !isWavy.value) return undefined;
114
+ const scale = diameter.value / size.value;
115
+ const radius = MAGIC_RADIUS_CONSTANT;
116
+ const amplitude = isWavy.value && (props.indeterminate || hasWave(normalizedValue.value)) ? WAVE_AMPLITUDE * scale : 0;
117
+ const waves = Math.max(3, Math.floor(CIRCUMFERENCE / (WAVELENGTH * scale)));
118
+ const center = diameter.value / 2;
119
+ const arc = `A ${radius} ${radius} 0 1 1`;
120
+ const roundCaps = props.rounded || isWavy.value;
121
+ return {
122
+ waves,
123
+ linecap: roundCaps ? 'round' : 'butt',
124
+ // round caps reach half a stroke into the gap from each side
125
+ gap: (WAVE_GAP * scale + (roundCaps ? strokeWidth.value : 0)) / CIRCUMFERENCE * 100,
126
+ // two turns so the indeterminate track can wrap past the start
127
+ track: `M ${center + radius} ${center}` + ` ${arc} ${center - radius} ${center} ${arc} ${center + radius} ${center}`.repeat(2),
128
+ // peaks sit on the track and troughs dip inward, so a flat wave lands on the track
129
+ wave: circularWavePath(center, radius - amplitude, amplitude, waves)
130
+ };
131
+ });
132
+ useRender(() => _createVNode(props.tag, {
133
+ "ref": root,
134
+ "class": _normalizeClass(['v-progress-circular', {
135
+ 'v-progress-circular--indeterminate': !!props.indeterminate,
136
+ 'v-progress-circular--visible': isIntersecting.value,
137
+ 'v-progress-circular--variant-split': props.variant === 'split',
138
+ 'v-progress-circular--shape-wavy': isWavy.value,
139
+ 'v-progress-circular--disable-shrink': props.indeterminate && (props.indeterminate === 'disable-shrink' || PREFERS_REDUCED_MOTION()),
140
+ 'v-progress-circular--revealing': ['initial', 'pending'].includes(revealState.value),
141
+ 'v-progress-circular--no-transition': props.transition === false
142
+ }, themeClasses.value, sizeClasses.value, textColorClasses.value, props.class]),
143
+ "style": _normalizeStyle([sizeStyles.value, textColorStyles.value, {
144
+ '--v-progress-reveal-duration': `${revealDuration.value}ms`,
145
+ '--v-progress-circular-transition-duration': transitionDuration.value
146
+ }, props.style]),
147
+ "role": "progressbar",
148
+ "aria-valuemin": "0",
149
+ "aria-valuemax": "100",
150
+ "aria-valuenow": props.indeterminate ? undefined : normalizedValue.value
151
+ }, {
152
+ default: () => [_createElementVNode("svg", {
153
+ "style": {
154
+ transform: `rotate(calc(-90deg + ${startAngle.value}deg))`
155
+ },
156
+ "xmlns": "http://www.w3.org/2000/svg",
157
+ "viewBox": `0 0 ${diameter.value} ${diameter.value}`
158
+ }, [geometry.value ? _createElementVNode("g", {
159
+ "class": "v-progress-circular__split",
160
+ "style": {
161
+ '--v-progress-circular-value': normalizedValue.value,
162
+ '--v-progress-circular-stroke': convertToUnit(strokeWidth.value),
163
+ '--v-progress-circular-waves': geometry.value.waves,
164
+ '--v-progress-circular-gap': geometry.value.gap
165
+ }
166
+ }, [_createElementVNode("path", {
167
+ "class": _normalizeClass(['v-progress-circular__underlay', 'v-progress-circular__track', underlayColorClasses.value]),
168
+ "style": _normalizeStyle(underlayColorStyles.value),
169
+ "d": geometry.value.track,
170
+ "pathLength": "200",
171
+ "stroke-linecap": geometry.value.linecap
172
+ }, null), _createElementVNode("path", {
173
+ "class": "v-progress-circular__wave",
174
+ "style": {
175
+ d: `path("${geometry.value.wave}")`
176
+ },
177
+ "d": geometry.value.wave,
178
+ "pathLength": 100 + 100 / geometry.value.waves,
179
+ "stroke-linecap": geometry.value.linecap
180
+ }, null)]) : _createElementVNode(_Fragment, null, [_createElementVNode("circle", {
181
+ "class": _normalizeClass(['v-progress-circular__underlay', underlayColorClasses.value]),
182
+ "style": _normalizeStyle(underlayColorStyles.value),
183
+ "fill": "transparent",
184
+ "cx": "50%",
185
+ "cy": "50%",
186
+ "r": MAGIC_RADIUS_CONSTANT,
187
+ "stroke-width": strokeWidth.value,
188
+ "stroke-dasharray": CIRCUMFERENCE,
189
+ "stroke-dashoffset": 0
190
+ }, null), _createElementVNode("circle", {
191
+ "class": "v-progress-circular__overlay",
192
+ "fill": "transparent",
193
+ "cx": "50%",
194
+ "cy": "50%",
195
+ "r": MAGIC_RADIUS_CONSTANT,
196
+ "stroke-width": strokeWidth.value,
197
+ "stroke-dasharray": CIRCUMFERENCE,
198
+ "stroke-dashoffset": strokeDashOffset.value,
199
+ "stroke-linecap": props.rounded ? 'round' : undefined
200
+ }, null)])]), slots.default && _createElementVNode("div", {
201
+ "class": "v-progress-circular__content"
202
+ }, [slots.default({
203
+ value: normalizedValue.value
204
+ })])]
205
+ }));
206
+ return {};
207
+ }
208
+ });
209
+ //# sourceMappingURL=VProgressCircular.js.map