@m3ui-vue/m3ui-vue 1.2.1 → 1.2.2

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.
Files changed (56) hide show
  1. package/dist/API.md +152 -11
  2. package/dist/{MMenuItem-DI351kIf.js → MMenuItem-D4Gx_l3F.js} +2 -2
  3. package/dist/{MMenuItem-DI351kIf.js.map → MMenuItem-D4Gx_l3F.js.map} +1 -1
  4. package/dist/{MSlider-BnEy5ieZ.js → MSlider-Dx_S3vJ9.js} +227 -221
  5. package/dist/{MSlider-BnEy5ieZ.js.map → MSlider-Dx_S3vJ9.js.map} +1 -1
  6. package/dist/{MTextField-BBmkaIbO.js → MTextField-Bz8JIsnl.js} +4 -4
  7. package/dist/{MTextField-BBmkaIbO.js.map → MTextField-Bz8JIsnl.js.map} +1 -1
  8. package/dist/api.json +1 -1
  9. package/dist/chart.js +1 -1
  10. package/dist/components/MMap.vue.d.ts +1 -1
  11. package/dist/components/MSlider.vue.d.ts +2 -2
  12. package/dist/composables/_effectCanvas.d.ts +23 -0
  13. package/dist/composables/_storageKeys.d.ts +9 -0
  14. package/dist/composables/themeInitScript.d.ts +2 -0
  15. package/dist/composables/useConfetti.d.ts +19 -8
  16. package/dist/composables/useFireworks.d.ts +37 -0
  17. package/dist/composables/useReactions.d.ts +32 -0
  18. package/dist/composables/viewportHints.d.ts +2 -0
  19. package/dist/directives/vSparkle.d.ts +27 -0
  20. package/dist/index.d.ts +7 -1
  21. package/dist/m3ui.js +5403 -5022
  22. package/dist/m3ui.js.map +1 -1
  23. package/dist/map.js +572 -572
  24. package/dist/map.js.map +1 -1
  25. package/dist/plugin.d.ts +10 -0
  26. package/dist/rich-text-editor.js +2 -2
  27. package/dist/{useThemeTokens-Bv-Uv8eX.js → useThemeTokens-y0HZpyhL.js} +23 -8
  28. package/dist/useThemeTokens-y0HZpyhL.js.map +1 -0
  29. package/package.json +1 -1
  30. package/src/__tests__/MSlider.test.ts +36 -0
  31. package/src/__tests__/plugin.test.ts +56 -1
  32. package/src/__tests__/ssr.test.ts +1 -1
  33. package/src/__tests__/themeInitScript.test.ts +10 -0
  34. package/src/__tests__/useConfetti.test.ts +33 -2
  35. package/src/__tests__/useFireworks.test.ts +104 -0
  36. package/src/__tests__/useReactions.test.ts +51 -0
  37. package/src/__tests__/vSparkle.test.ts +83 -0
  38. package/src/components/MEmojiSelector.vue +3 -2
  39. package/src/components/MMap.vue +3 -2
  40. package/src/components/MSlider.vue +22 -4
  41. package/src/components/MTextField.vue +8 -4
  42. package/src/composables/_colorUtils.ts +4 -2
  43. package/src/composables/_effectCanvas.ts +109 -0
  44. package/src/composables/_ssrState.ts +2 -2
  45. package/src/composables/_storageKeys.ts +28 -0
  46. package/src/composables/themeInitScript.ts +5 -2
  47. package/src/composables/useColorPalette.ts +36 -8
  48. package/src/composables/useConfetti.ts +84 -107
  49. package/src/composables/useFireworks.ts +360 -0
  50. package/src/composables/useReactions.ts +131 -0
  51. package/src/composables/useTheme.ts +21 -4
  52. package/src/composables/viewportHints.ts +6 -5
  53. package/src/directives/vSparkle.ts +180 -0
  54. package/src/index.ts +7 -1
  55. package/src/plugin.ts +21 -5
  56. package/dist/useThemeTokens-Bv-Uv8eX.js.map +0 -1
package/dist/plugin.d.ts CHANGED
@@ -13,6 +13,7 @@ import { vLongPress } from './directives/vLongPress';
13
13
  import { vSwipe } from './directives/vSwipe';
14
14
  import { vClickOutside } from './directives/vClickOutside';
15
15
  import { vSkeleton } from './directives/vSkeleton';
16
+ import { vSparkle } from './directives/vSparkle';
16
17
  import { type M3InitialState } from './composables/_ssrState';
17
18
  export interface M3UIOptions {
18
19
  palette?: PaletteId | (string & {});
@@ -69,6 +70,14 @@ export interface M3UIOptions {
69
70
  * and render with the user's choice and for their screen through `initialState`.
70
71
  */
71
72
  cookies?: boolean;
73
+ /**
74
+ * A prefix for every key the library stores in localStorage and cookies (`'admin'` → `admin-m3-theme`,
75
+ * `admin-m3-palette`…), so apps served from the same origin under different paths (`example.com/admin`,
76
+ * `example.com/shop`) each keep their own theme, palette, contrast and recent colors/emoji instead of sharing them.
77
+ * Letters, digits, `-` and `_` (it's also part of the cookie names). Pass the same one to `themeInitScript()` and
78
+ * `viewportFromHeaders()` when you use them.
79
+ */
80
+ storagePrefix?: string;
72
81
  /**
73
82
  * Server-side rendering: the user's theme, palette and contrast as the server knows them (from the cookies that
74
83
  * `cookies` writes), on the server and on the client alike. `useTheme()` and `useColorPalette()` report them on
@@ -94,5 +103,6 @@ declare module 'vue' {
94
103
  vSwipe: typeof vSwipe;
95
104
  vClickOutside: typeof vClickOutside;
96
105
  vSkeleton: typeof vSkeleton;
106
+ vSparkle: typeof vSparkle;
97
107
  }
98
108
  }
@@ -1,8 +1,8 @@
1
1
  import { i as e } from "./useLocale-JYxDDeXC.js";
2
- import { t } from "./MTextField-BBmkaIbO.js";
2
+ import { t } from "./MTextField-Bz8JIsnl.js";
3
3
  import { t as n } from "./MIcon-Bxh9j135.js";
4
4
  import { t as r } from "./_plugin-vue_export-helper-B3ysoDQm.js";
5
- import { c as i, n as a, s as o, t as s } from "./MMenuItem-DI351kIf.js";
5
+ import { c as i, n as a, s as o, t as s } from "./MMenuItem-D4Gx_l3F.js";
6
6
  import { Fragment as c, computed as l, createCommentVNode as u, createElementBlock as d, createElementVNode as f, createTextVNode as p, createVNode as m, defineComponent as h, normalizeClass as g, normalizeStyle as _, onBeforeUnmount as v, onMounted as y, openBlock as b, ref as x, renderList as S, shallowRef as C, toDisplayString as w, watch as T, withCtx as E, withKeys as D } from "vue";
7
7
  //#region src/components/MRichTextEditor.vue?vue&type=script&setup=true&lang.ts
8
8
  var O = {
@@ -63,8 +63,23 @@ function d(e) {
63
63
  }
64
64
  //#endregion
65
65
  //#region src/composables/_storageKeys.ts
66
- var f = "m3-theme", p = "m3-dynamic-palette", m = "m3-viewport", h = e(.25, .1, .25, 1);
67
- function g(e) {
66
+ var f = "m3-theme", p = "m3-dynamic-palette", m = "m3-viewport", h = "", g = /* @__PURE__ */ new Set();
67
+ function _(e, t = h) {
68
+ return t ? `${t}-${e}` : e;
69
+ }
70
+ function v(e) {
71
+ if (e !== h) {
72
+ h = e;
73
+ for (let e of g) e();
74
+ }
75
+ }
76
+ function y(e) {
77
+ g.add(e);
78
+ }
79
+ //#endregion
80
+ //#region src/composables/useThemeTokens.ts
81
+ var b = e(.25, .1, .25, 1);
82
+ function x(e) {
68
83
  let t = e.trim(), n = /^#([0-9a-f]{3,8})$/i.exec(t)?.[1];
69
84
  if (n && n.length !== 5 && n.length !== 7) {
70
85
  let e = n.length <= 4 ? [...n].map((e) => e + e).join("") : n, t = (t) => parseInt(e.slice(t, t + 2), 16);
@@ -87,13 +102,13 @@ function g(e) {
87
102
  ];
88
103
  return s.every(Number.isFinite) ? s : null;
89
104
  }
90
- function _(e, t, n) {
91
- let r = g(e), i = g(t);
105
+ function S(e, t, n) {
106
+ let r = x(e), i = x(t);
92
107
  if (!r || !i) return n < 1 ? e : t;
93
108
  let [a, o, s, c] = r.map((e, t) => e + (i[t] - e) * n);
94
109
  return `rgba(${Math.round(a)}, ${Math.round(o)}, ${Math.round(s)}, ${+c.toFixed(3)})`;
95
110
  }
96
- function v(e, i = {}) {
111
+ function C(e, i = {}) {
97
112
  let a = () => {
98
113
  let t = getComputedStyle(document.documentElement);
99
114
  return Object.fromEntries(e.map((e) => [e, t.getPropertyValue(`--color-${e}`).trim()]));
@@ -104,7 +119,7 @@ function v(e, i = {}) {
104
119
  cancelAnimationFrame(l);
105
120
  let n = t.classList.contains("theme-switching"), r = { ...o.value }, i = n ? null : a(), s = performance.now(), c = (t) => {
106
121
  let n = Math.min(1, (t - s) / 250);
107
- i ? u(n < 1 ? Object.fromEntries(e.map((e) => [e, _(r[e], i[e], h(n))])) : i) : d(), n < 1 && (l = requestAnimationFrame(c));
122
+ i ? u(n < 1 ? Object.fromEntries(e.map((e) => [e, S(r[e], i[e], b(n))])) : i) : d(), n < 1 && (l = requestAnimationFrame(c));
108
123
  };
109
124
  l = requestAnimationFrame(c);
110
125
  }
@@ -130,6 +145,6 @@ function v(e, i = {}) {
130
145
  }), o;
131
146
  }
132
147
  //#endregion
133
- export { d as a, m as i, p as n, f as r, v as t };
148
+ export { y as a, d as c, m as i, p as n, v as o, f as r, _ as s, C as t };
134
149
 
135
- //# sourceMappingURL=useThemeTokens-Bv-Uv8eX.js.map
150
+ //# sourceMappingURL=useThemeTokens-y0HZpyhL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useThemeTokens-y0HZpyhL.js","names":[],"sources":["../src/composables/_themeTransition.ts","../src/composables/_storageKeys.ts","../src/composables/useThemeTokens.ts"],"sourcesContent":["// Internal: animates a theme change (dark mode, palette, contrast).\n//\n// Firefox (and any browser without @property) transitions six color properties on every element\n// (`.theme-transitioning` in theme.css): smooth there, but in Chromium it recalculates every element's transitions\n// each frame and stutters. Chromium and WebKit instead transition the color tokens themselves, once, on <html>:\n// registered as <color> with @property they interpolate, and every element follows them through var(). Components'\n// own color transitions (transition-colors) are turned off meanwhile, or they would restart on every frame of the\n// token's change and trail behind the rest (the navbar and buttons did). A view transition was tried first: it\n// cross-fades two snapshots, which looks washed out midway compared to the colors moving.\n\n// The tokens of theme.css, palettes.css and generated palettes\nconst COLOR_TOKENS = [\n 'background', 'on-background', 'surface', 'surface-dim', 'surface-bright', 'surface-variant', 'on-surface',\n 'on-surface-variant', 'surface-container-lowest', 'surface-container-low', 'surface-container',\n 'surface-container-high', 'surface-container-highest', 'inverse-surface', 'inverse-on-surface', 'inverse-primary',\n 'outline', 'outline-variant', 'shadow', 'scrim',\n ...['primary', 'secondary', 'tertiary', 'error', 'success'].flatMap((c) => [c, `on-${c}`, `${c}-container`, `on-${c}-container`]),\n ...['primary', 'secondary', 'tertiary'].flatMap((c) => [`${c}-fixed`, `${c}-fixed-dim`, `on-${c}-fixed`, `on-${c}-fixed-variant`]),\n].map((t) => `--color-${t}`)\n\nconst DURATION = 250\n/** How long a theme switch's color transition takes, in ms (both paths) */\nexport const THEME_TRANSITION_MS = DURATION\nconst STYLE_ID = 'm3-theme-transition'\n\n// Injected only while switching: a registered <color> computes to rgb(), and code reading a token with\n// getPropertyValue() expects it as written\nconst css = COLOR_TOKENS.map((t) => `@property ${t} { syntax: '<color>'; inherits: true; initial-value: transparent; }`).join('\\n')\n + `\\nhtml.theme-switching { transition: ${COLOR_TOKENS.map((t) => `${t} ${DURATION}ms ease`).join(', ')}; }`\n + '\\nhtml.theme-switching *, html.theme-switching *::before, html.theme-switching *::after { transition: none !important; }'\n\n// Gecko: a CSS feature only it has, or its user agent (\"Gecko/<version>\" or \"Firefox/\"; Chromium and WebKit only\n// say \"like Gecko\", and Firefox on iOS is WebKit and says \"FxiOS\")\nconst isGecko = () =>\n (typeof CSS !== 'undefined' && !!CSS.supports?.('-moz-appearance', 'none'))\n || (typeof navigator !== 'undefined' && /\\bGecko\\/\\d|\\bFirefox\\//.test(navigator.userAgent))\nconst hasProperty = () => typeof CSS !== 'undefined' && typeof CSS.registerProperty === 'function'\n\nlet timer: ReturnType<typeof setTimeout> | undefined\n\n/** Runs `apply` (the DOM writes of a theme change) with the theme transition. */\nexport function themeTransition(apply: () => void) {\n if (typeof document === 'undefined') return apply()\n const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches\n if (reduced) return apply()\n const root = document.documentElement\n\n if (!isGecko() && hasProperty()) {\n if (!document.getElementById(STYLE_ID)) {\n const style = document.createElement('style')\n style.id = STYLE_ID\n style.textContent = css\n document.head.appendChild(style)\n }\n root.classList.add('theme-switching')\n // Style flush: the tokens' current values are computed as registered colors and the transition is in place\n // before they change\n void root.offsetHeight\n apply()\n clearTimeout(timer)\n timer = setTimeout(() => {\n root.classList.remove('theme-switching')\n document.getElementById(STYLE_ID)?.remove()\n }, DURATION + 50)\n return\n }\n\n root.classList.add('theme-transitioning')\n // Force a style flush so the transition is in place before the colors change\n void root.offsetHeight\n apply()\n setTimeout(() => root.classList.remove('theme-transitioning'), 300)\n}\n","// Storage keys shared with modules that must not load useTheme (it applies the theme to <html> when it loads)\nexport const THEME_KEY = 'm3-theme'\n// The <style> useColorPalette writes a generated palette's CSS into\nexport const STYLE_ID = 'm3-dynamic-palette'\n// The window's size, a cookie only (createM3UI({ cookies: true })): `<width>x<height>`\nexport const VIEWPORT_KEY = 'm3-viewport'\n\n// ── Prefix ──────────────────────────────────────────────────────────────────────────────────────\n// `createM3UI({ storagePrefix: 'admin' })`: every key the library stores (localStorage and cookies) becomes\n// `admin-m3-…`, so apps on the same origin under different paths keep their own theme, palette and the rest\n// (localStorage is per origin and our cookies are on `Path=/`, so without it they share one).\n\nlet prefix = ''\nconst reloaders = new Set<() => void>()\n\n/** The name a key is stored under: the base key with the app's prefix, if any. */\nexport function storageKey(base: string, storagePrefix = prefix): string {\n return storagePrefix ? `${storagePrefix}-${base}` : base\n}\n\n/**\n * Sets the prefix and has every module that read its stored state on load (theme, palette, recent colors…) read\n * it again under the new keys. `createM3UI` calls it before applying anything else.\n */\nexport function setStoragePrefix(next: string) {\n if (next === prefix) return\n prefix = next\n for (const reload of reloaders) reload()\n}\n\n/** Registers what a module does to read its stored state again when the prefix changes. */\nexport function onStoragePrefix(reload: () => void) {\n reloaders.add(reload)\n}\n","import { onBeforeUnmount, onMounted, ref, type Ref } from 'vue'\nimport { STYLE_ID } from './_storageKeys'\nimport { THEME_TRANSITION_MS } from './_themeTransition'\nimport { cubicBezier } from './motion'\n\nexport interface ThemeTokensOptions {\n /**\n * Updates every animation frame while the theme switch's colors fade, so a canvas redrawn on change fades with\n * the page instead of jumping to the new colors. Off by default: what animates color changes itself (Chart.js,\n * MChart, maps) only needs the final values, and would otherwise redraw ~15 times per switch.\n */\n live?: boolean\n}\n\n// The CSS `ease` the switch uses (_themeTransition.ts, and `.theme-transitioning` in theme.css)\nconst ease = cubicBezier(0.25, 0.1, 0.25, 1)\n\ntype Rgba = [number, number, number, number]\n\n// Hex (#rgb, #rgba, #rrggbb, #rrggbbaa) or rgb()/rgba(), the forms tokens are written in or computed to; null for\n// anything else (that token then switches at once)\nfunction parseColor(value: string): Rgba | null {\n const v = value.trim()\n const hex = /^#([0-9a-f]{3,8})$/i.exec(v)?.[1]\n if (hex && hex.length !== 5 && hex.length !== 7) {\n const full = hex.length <= 4 ? [...hex].map((c) => c + c).join('') : hex\n const n = (i: number) => parseInt(full.slice(i, i + 2), 16)\n return [n(0), n(2), n(4), full.length === 8 ? n(6) / 255 : 1]\n }\n const fn = /^rgba?\\(([^)]+)\\)$/i.exec(v)?.[1]\n if (!fn) return null\n const parts = fn.split(/[\\s,/]+/).filter(Boolean)\n if (parts.length < 3) return null\n const channel = (p: string) => (p.endsWith('%') ? parseFloat(p) * 2.55 : parseFloat(p))\n const alpha = parts[3] == null ? 1 : parts[3].endsWith('%') ? parseFloat(parts[3]) / 100 : parseFloat(parts[3])\n const rgba = [channel(parts[0]!), channel(parts[1]!), channel(parts[2]!), alpha] as Rgba\n return rgba.every(Number.isFinite) ? rgba : null\n}\n\nfunction mix(from: string, to: string, t: number): string {\n const a = parseColor(from)\n const b = parseColor(to)\n if (!a || !b) return t < 1 ? from : to\n const [r, g, bl, al] = a.map((x, i) => x + (b[i]! - x) * t)\n return `rgba(${Math.round(r!)}, ${Math.round(g!)}, ${Math.round(bl!)}, ${+al!.toFixed(3)})`\n}\n\n/**\n * The current values of some color tokens (`['primary', 'surface']` → `--color-primary`…), kept up to date across\n * light/dark, palette, contrast and generated (seed) palette changes: for what can't use CSS variables, like a\n * Chart.js dataset, a canvas or a MapLibre layer's paint. Values settle after the theme switch's color transition;\n * with `{ live: true }` they also follow it frame by frame (as `rgba()` midway). Empty strings on the server.\n *\n * ```ts\n * const colors = useThemeTokens(['primary', 'tertiary', 'outline-variant'] as const)\n * const data = computed(() => ({ datasets: [{ data: sales, borderColor: colors.value.primary }] }))\n * ```\n */\nexport function useThemeTokens<T extends string>(names: readonly T[], options: ThemeTokensOptions = {}): Ref<Record<T, string>> {\n const read = () => {\n const style = getComputedStyle(document.documentElement)\n return Object.fromEntries(names.map((n) => [n, style.getPropertyValue(`--color-${n}`).trim()])) as Record<T, string>\n }\n const tokens = ref(typeof document === 'undefined' ? Object.fromEntries(names.map((n) => [n, ''])) as Record<T, string> : read()) as Ref<Record<T, string>>\n let observer: MutationObserver | undefined\n let settle: ReturnType<typeof setTimeout> | undefined\n let frame = 0\n\n const set = (next: Record<T, string>) => {\n if (names.some((n) => next[n] !== tokens.value[n])) tokens.value = next\n }\n const update = () => set(read())\n\n // Follows a switch already under way. Chromium/WebKit animate the tokens themselves (`theme-switching`), so\n // reading them each frame gives the page's own colors; Firefox fades each element's colors instead\n // (`theme-transitioning`) while the tokens jump, so the same `ease` is replayed here from the old values\n function follow(root: HTMLElement) {\n cancelAnimationFrame(frame)\n const native = root.classList.contains('theme-switching')\n const from = { ...tokens.value }\n const to = native ? null : read()\n const start = performance.now()\n const step = (now: number) => {\n const t = Math.min(1, (now - start) / THEME_TRANSITION_MS)\n // The last frame lands on the values as written, not their rgba() form\n if (to) set(t < 1 ? Object.fromEntries(names.map((n) => [n, mix(from[n], to[n], ease(t))])) as Record<T, string> : to)\n else update()\n if (t < 1) frame = requestAnimationFrame(step)\n }\n frame = requestAnimationFrame(step)\n }\n\n onMounted(() => {\n const root = document.documentElement\n // Dark mode (class), a palette or contrast (attributes), or a generated palette rewriting its <style> in <head>\n const isPaletteStyle = (node: Node | null) => (node instanceof Element ? node : node?.parentElement)?.id === STYLE_ID\n observer = new MutationObserver((records) => {\n if (!records.some((r) => r.target === root || isPaletteStyle(r.target)\n || Array.from(r.addedNodes).some(isPaletteStyle))) return\n if (options.live && (root.classList.contains('theme-switching') || root.classList.contains('theme-transitioning'))) follow(root)\n else update()\n // Chromium animates the tokens on a theme switch (_themeTransition, 250ms): read the settled values too\n clearTimeout(settle)\n settle = setTimeout(update, THEME_TRANSITION_MS + 50)\n })\n observer.observe(root, { attributes: true, attributeFilter: ['class', 'style', 'data-palette', 'data-contrast'] })\n observer.observe(document.head, { childList: true, characterData: true, subtree: true })\n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AiB;IAAC;IAAS;IAAS;IAAgB;GAAe;EAAE,CAAC,GACjH,EAAS,QAAQ,SAAS,MAAM;GAAE,WAAW;GAAM,eAAe;GAAM,SAAS;EAAK,CAAC;CACzF,CAAC,GACD,QAAsB;EAGpB,AAFA,GAAU,WAAW,GACrB,aAAa,CAAM,GACnB,qBAAqB,CAAK;CAC5B,CAAC,GAEM;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@m3ui-vue/m3ui-vue",
3
- "version": "1.2.1",
3
+ "version": "1.2.2",
4
4
  "description": "Material 3 component library for Vue 3 + Tailwind CSS v4",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -68,6 +68,42 @@ describe('MSlider', () => {
68
68
  expect(endDot(wrapper).style.opacity).toBe('1')
69
69
  })
70
70
 
71
+ describe('dragging', () => {
72
+ // The track is 100px long from 0. Where the thumb is, read off the active piece, which ends at it (happy-dom
73
+ // drops the thumb's own clamp() left)
74
+ const thumbLeft = (w: VueWrapper) => Number(/clamp\([^,]+, ([\d.]+)%/.exec(pieces(w)[0]!.style.width)![1])
75
+ const mountSingle = (props: Record<string, unknown>) => {
76
+ const w = mount(MSlider, {
77
+ props: { modelValue: 1, min: 1, max: 30, ...props, 'onUpdate:modelValue': (v: unknown) => w.setProps({ modelValue: v as number }) },
78
+ attachTo: document.body,
79
+ })
80
+ ;(track(w).element as HTMLElement).getBoundingClientRect = () => ({ left: 0, top: 0, width: 100, height: 46, right: 100, bottom: 46, x: 0, y: 0, toJSON() {} })
81
+ return w
82
+ }
83
+
84
+ it('follows the pointer smoothly while dragging, emitting stepped values, and settles on the step when released', async () => {
85
+ wrapper = mountSingle({})
86
+ track(wrapper).element.dispatchEvent(new PointerEvent('pointerdown', { clientX: 20, bubbles: true }))
87
+ window.dispatchEvent(new PointerEvent('pointermove', { clientX: 51 }))
88
+ await nextTick()
89
+ // 51% of 1–30 is 15.79: the value snaps to 16, the thumb stays under the pointer
90
+ expect(wrapper.props('modelValue')).toBe(16)
91
+ expect(thumbLeft(wrapper)).toBeCloseTo(51, 5)
92
+ window.dispatchEvent(new PointerEvent('pointerup', { clientX: 51 }))
93
+ await nextTick()
94
+ expect(thumbLeft(wrapper)).toBeCloseTo((15 / 29) * 100, 5)
95
+ })
96
+
97
+ it('snaps from step to step with stops, like a discrete slider', async () => {
98
+ wrapper = mountSingle({ stops: true })
99
+ track(wrapper).element.dispatchEvent(new PointerEvent('pointerdown', { clientX: 20, bubbles: true }))
100
+ window.dispatchEvent(new PointerEvent('pointermove', { clientX: 51 }))
101
+ await nextTick()
102
+ expect(thumbLeft(wrapper)).toBeCloseTo((15 / 29) * 100, 5)
103
+ window.dispatchEvent(new PointerEvent('pointerup', { clientX: 51 }))
104
+ })
105
+ })
106
+
71
107
  describe('range', () => {
72
108
  // The track is 100px long from 0 for the pointer
73
109
  const press = async (w: VueWrapper, at: number, moves: number[] = []) => {
@@ -1,7 +1,10 @@
1
1
  import { describe, it, expect, beforeEach, afterEach } from 'vitest'
2
- import { createApp, defineComponent, h } from 'vue'
2
+ import { createApp, defineComponent, h, nextTick } from 'vue'
3
3
  import { createM3UI } from '../plugin'
4
4
  import { useColorPalette, palettes } from '../composables/useColorPalette'
5
+ import { useTheme } from '../composables/useTheme'
6
+ import { recentColors } from '../composables/_colorUtils'
7
+ import { setStoragePrefix } from '../composables/_storageKeys'
5
8
 
6
9
  describe('createM3UI', () => {
7
10
  beforeEach(() => {
@@ -79,4 +82,56 @@ describe('createM3UI', () => {
79
82
  expect(document.documentElement.getAttribute('data-palette')).toBe('brand')
80
83
  })
81
84
  })
85
+
86
+ describe('storagePrefix', () => {
87
+ afterEach(() => {
88
+ setStoragePrefix('')
89
+ localStorage.clear()
90
+ document.documentElement.classList.remove('dark')
91
+ })
92
+
93
+ function mountWith(options: Parameters<typeof createM3UI>[0]) {
94
+ let result!: { theme: ReturnType<typeof useTheme>; palette: ReturnType<typeof useColorPalette> }
95
+ const app = createApp(defineComponent({
96
+ setup() {
97
+ result = { theme: useTheme(), palette: useColorPalette() }
98
+ return () => h('div')
99
+ },
100
+ }))
101
+ app.use(createM3UI(options))
102
+ app.mount(document.createElement('div'))
103
+ return { app, ...result }
104
+ }
105
+
106
+ it("ignores another app's choices on the same origin and stores its own under the prefix", async () => {
107
+ localStorage.setItem('m3-theme', 'dark')
108
+ localStorage.setItem('m3-palette', 'teal')
109
+ localStorage.setItem('m3-color-recent', '["#ff0000"]')
110
+ const { app, theme, palette } = mountWith({ storagePrefix: 'shop', palette: 'red' })
111
+ expect(theme.theme.value).toBe('system')
112
+ expect(document.documentElement.classList.contains('dark')).toBe(false)
113
+ expect(palette.palette.value).toBe('red')
114
+ expect(document.documentElement.getAttribute('data-palette')).toBe('red')
115
+ expect(recentColors.value).toEqual([])
116
+ theme.theme.value = 'light'
117
+ await nextTick()
118
+ expect(localStorage.getItem('shop-m3-theme')).toBe('light')
119
+ expect(localStorage.getItem('shop-m3-palette')).toBe('red')
120
+ expect(localStorage.getItem('m3-theme')).toBe('dark')
121
+ expect(localStorage.getItem('m3-palette')).toBe('teal')
122
+ app.unmount()
123
+ })
124
+
125
+ it("applies the app's own stored choices", () => {
126
+ localStorage.setItem('m3-palette', 'teal')
127
+ localStorage.setItem('admin-m3-theme', 'dark')
128
+ localStorage.setItem('admin-m3-palette', 'green')
129
+ const { app, theme, palette } = mountWith({ storagePrefix: 'admin', palette: 'red' })
130
+ expect(theme.theme.value).toBe('dark')
131
+ expect(document.documentElement.classList.contains('dark')).toBe(true)
132
+ expect(palette.palette.value).toBe('green')
133
+ expect(document.documentElement.getAttribute('data-palette')).toBe('green')
134
+ app.unmount()
135
+ })
136
+ })
82
137
  })
@@ -179,7 +179,7 @@ describe('SSR', () => {
179
179
  withDirectives(h('p', { id: 'skeleton' }, 'Ada'), [[d('skeleton'), true]]),
180
180
  withDirectives(h('p', { id: 'ring' }), [[d('focus-ring'), { within: true }]]),
181
181
  withDirectives(h('p', { id: 'layer' }), [[d('state-layer'), { dragged: true }]]),
182
- withDirectives(h('p'), [[d('ripple')], [d('reveal')], [d('tooltip'), 'Hi'], [d('scroll-elevation')], [d('long-press'), () => {}], [d('swipe'), () => {}], [d('click-outside'), () => {}]]),
182
+ withDirectives(h('p'), [[d('ripple')], [d('reveal')], [d('tooltip'), 'Hi'], [d('scroll-elevation')], [d('long-press'), () => {}], [d('swipe'), () => {}], [d('click-outside'), () => {}], [d('sparkle')]]),
183
183
  ]),
184
184
  })
185
185
  app.use(lib.createM3UI())
@@ -50,6 +50,16 @@ describe('themeInitScript', () => {
50
50
  expect(html.getAttribute('data-palette')).toBe('blue')
51
51
  })
52
52
 
53
+ it('reads the keys under storagePrefix, not another app\'s', () => {
54
+ matchMedia({})
55
+ localStorage.setItem('m3-theme', 'dark')
56
+ localStorage.setItem('m3-palette', 'blue')
57
+ localStorage.setItem('shop-m3-palette', 'green')
58
+ run({ storagePrefix: 'shop' })
59
+ expect(html.classList.contains('dark')).toBe(false)
60
+ expect(html.getAttribute('data-palette')).toBe('green')
61
+ })
62
+
53
63
  it('forces the palette with persistPalette: false', () => {
54
64
  localStorage.setItem('m3-palette', 'blue')
55
65
  run({ palette: 'red', persistPalette: false })
@@ -3,8 +3,12 @@ import { __resetConfetti, fireConfetti, useConfetti } from '../composables/useCo
3
3
 
4
4
  // happy-dom has no 2D canvas: a fake one that records what's drawn
5
5
  let fills: string[] = []
6
+ // Pieces drawn in the last full frame (each frame clears the canvas, then draws every piece)
7
+ let onScreen = 0
8
+ let drawing = 0
6
9
  beforeEach(() => {
7
10
  fills = []
11
+ onScreen = drawing = 0
8
12
  vi.stubGlobal('Path2D', class { constructor(public d: string) {} })
9
13
  vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(function () {
10
14
  const ctx = {
@@ -12,8 +16,8 @@ beforeEach(() => {
12
16
  globalAlpha: 1,
13
17
  setTransform: () => {},
14
18
  translate: () => {},
15
- clearRect: () => {},
16
- fill: () => fills.push(ctx.fillStyle),
19
+ clearRect: () => { onScreen = drawing; drawing = 0 },
20
+ fill: () => { drawing++; fills.push(ctx.fillStyle) },
17
21
  }
18
22
  return ctx as unknown as CanvasRenderingContext2D
19
23
  })
@@ -78,4 +82,31 @@ describe('useConfetti', () => {
78
82
  expect(new Set(fills)).toEqual(new Set(['blue', 'green']))
79
83
  button.remove()
80
84
  })
85
+
86
+ it('with a duration keeps adding pieces (count per second) until it ends, then lets them fall', async () => {
87
+ fireConfetti(undefined, { from: 'top', count: 100, duration: 500, colors: ['red'] })
88
+ await frames(150)
89
+ const early = onScreen
90
+ await frames(250)
91
+ // Still raining: more pieces than before, about count per second so far
92
+ expect(onScreen).toBeGreaterThan(early)
93
+ expect(onScreen).toBeGreaterThan(20)
94
+ expect(onScreen).toBeLessThan(60)
95
+ await frames(300)
96
+ // Over: no new pieces (at most the 50 a second's half gives), the canvas stays while they fall
97
+ expect(onScreen).toBeLessThanOrEqual(51)
98
+ expect(canvas()).not.toBeNull()
99
+ })
100
+
101
+ it('stop() ends a rain early (and Infinity runs until then)', async () => {
102
+ const stop = fireConfetti(undefined, { from: 'top', count: 200, duration: Infinity, colors: ['red'] })
103
+ await frames(200)
104
+ stop()
105
+ await frames(30)
106
+ const atStop = onScreen
107
+ expect(atStop).toBeGreaterThan(0)
108
+ await frames(300)
109
+ expect(onScreen).toBeLessThanOrEqual(atStop)
110
+ expect(onScreen).toBeGreaterThan(0)
111
+ })
81
112
  })
@@ -0,0 +1,104 @@
1
+ import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest'
2
+ import { __resetFireworks, launchFireworks, shapeOutline, useFireworks } from '../composables/useFireworks'
3
+
4
+ // happy-dom has no 2D canvas: a fake one that records the strokes
5
+ let strokes: string[] = []
6
+ beforeEach(() => {
7
+ strokes = []
8
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(function () {
9
+ const ctx = {
10
+ fillStyle: '',
11
+ strokeStyle: '',
12
+ globalAlpha: 1,
13
+ lineWidth: 1,
14
+ lineCap: 'butt',
15
+ setTransform: () => {},
16
+ clearRect: () => {},
17
+ beginPath: () => {},
18
+ moveTo: () => {},
19
+ lineTo: () => {},
20
+ arc: () => {},
21
+ fill: () => {},
22
+ stroke: () => strokes.push(ctx.strokeStyle),
23
+ }
24
+ return ctx as unknown as CanvasRenderingContext2D
25
+ })
26
+ })
27
+ afterEach(() => {
28
+ __resetFireworks()
29
+ vi.restoreAllMocks()
30
+ vi.unstubAllGlobals()
31
+ document.querySelectorAll('canvas').forEach((c) => c.remove())
32
+ })
33
+
34
+ const canvas = () => document.querySelector('canvas')
35
+ const wait = (ms: number) => new Promise((r) => setTimeout(r, ms))
36
+
37
+ describe('useFireworks', () => {
38
+ it('lays a burst out along the shape: n points, the farthest at 1', () => {
39
+ for (const shape of ['Circle', 'Heart', 'Flower'] as const) {
40
+ const out = shapeOutline(shape, 48)
41
+ expect(out).toHaveLength(96)
42
+ let max = 0
43
+ for (let i = 0; i < out.length; i += 2) max = Math.max(max, Math.hypot(out[i]!, out[i + 1]!))
44
+ expect(max).toBeCloseTo(1, 5)
45
+ }
46
+ // A circle's points all sit on it
47
+ const ring = shapeOutline('Circle', 32)
48
+ for (let i = 0; i < ring.length; i += 2) expect(Math.hypot(ring[i]!, ring[i + 1]!)).toBeGreaterThan(0.97)
49
+ })
50
+
51
+ it('launches rockets on the shared canvas in the given colors, and removes it after the last burst', async () => {
52
+ launchFireworks({ count: 2, colors: ['red'] })
53
+ expect(canvas()!.getAttribute('aria-hidden')).toBe('true')
54
+ await wait(200)
55
+ expect(strokes.length).toBeGreaterThan(0)
56
+ expect(new Set(strokes)).toEqual(new Set(['red']))
57
+ // Up to 0.5s of stagger, 1.3s of flight and 2.6s of burst
58
+ await wait(4600)
59
+ expect(canvas()).toBeNull()
60
+ }, 8000)
61
+
62
+ it("a classic burst throws streaks out in every direction that fall as they fade", async () => {
63
+ const segments: [number, number, number, number][] = []
64
+ let from: [number, number] = [0, 0]
65
+ vi.mocked(HTMLCanvasElement.prototype.getContext).mockImplementation(function () {
66
+ const ctx = {
67
+ fillStyle: '', strokeStyle: '', globalAlpha: 1, lineWidth: 1, lineCap: 'butt',
68
+ setTransform: () => {}, clearRect: () => {}, beginPath: () => {}, arc: () => {}, fill: () => {},
69
+ moveTo: (x: number, y: number) => { from = [x, y] },
70
+ lineTo: (x: number, y: number) => { segments.push([...from, x, y]) },
71
+ stroke: () => strokes.push(ctx.strokeStyle),
72
+ }
73
+ return ctx as unknown as CanvasRenderingContext2D
74
+ })
75
+ launchFireworks({ count: 1, shapes: ['classic'], colors: ['gold'], size: 100 })
76
+ // The rocket flies about a second, then the burst
77
+ await wait(1700)
78
+ const recent = segments.slice(-400)
79
+ const dx = recent.map((s) => s[2] - s[0])
80
+ const dy = recent.map((s) => s[3] - s[1])
81
+ // Streaks going left and right, and (with gravity winning) more of them going down than up by now
82
+ expect(dx.some((d) => d > 0) && dx.some((d) => d < 0)).toBe(true)
83
+ expect(dy.filter((d) => d > 0).length).toBeGreaterThan(dy.filter((d) => d < 0).length)
84
+ expect(new Set(strokes)).toEqual(new Set(['gold']))
85
+ await wait(3200)
86
+ expect(canvas()).toBeNull()
87
+ }, 8000)
88
+
89
+ it('keeps launching with a duration until stop()', async () => {
90
+ const stop = useFireworks().launch({ count: 20, duration: Infinity, colors: ['blue'] })
91
+ await wait(400)
92
+ stop()
93
+ // What's in the air finishes, then the canvas goes
94
+ expect(canvas()).not.toBeNull()
95
+ await wait(4200)
96
+ expect(canvas()).toBeNull()
97
+ }, 8000)
98
+
99
+ it('does nothing under reduced motion', () => {
100
+ vi.stubGlobal('matchMedia', (q: string) => ({ matches: q.includes('reduce') }))
101
+ launchFireworks()
102
+ expect(canvas()).toBeNull()
103
+ })
104
+ })
@@ -0,0 +1,51 @@
1
+ import { describe, it, expect, afterEach, vi } from 'vitest'
2
+ import { __resetReactions, fireReaction, useReactions } from '../composables/useReactions'
3
+
4
+ afterEach(() => {
5
+ __resetReactions()
6
+ vi.unstubAllGlobals()
7
+ })
8
+
9
+ const layer = () => document.querySelector<HTMLElement>('body > div[aria-hidden="true"]')
10
+ const items = () => Array.from(layer()?.querySelectorAll('span') ?? [])
11
+
12
+ describe('useReactions', () => {
13
+ it('floats an emoji up from the point in a layer that ignores the pointer and assistive technology', () => {
14
+ fireReaction({ x: 120, y: 300 }, '🎉')
15
+ const l = layer()!
16
+ expect(l.style.pointerEvents).toBe('none')
17
+ expect(l.style.position).toBe('fixed')
18
+ const [el] = items()
19
+ expect(el!.textContent).toBe('🎉')
20
+ expect(el!.style.left).toBe('120px')
21
+ expect(el!.style.top).toBe('300px')
22
+ const anim = el!.getAnimations()[0]!
23
+ const frames = anim.effect!.getKeyframes!()
24
+ // It rises: the last frame is well above the first
25
+ const y = (f: Keyframe) => Number(/translate\([-\d.]+px, ([-\d.]+)px\)/.exec(String(f.transform))![1])
26
+ expect(y(frames.at(-1)!)).toBeLessThan(-150)
27
+ })
28
+
29
+ it('renders an icon filled, in the theme primary where it starts, and removes everything when done', () => {
30
+ const el = document.createElement('div')
31
+ el.style.setProperty('--color-primary', '#c83228')
32
+ document.body.appendChild(el)
33
+ useReactions().react(el, { icon: 'favorite' }, { count: 3 })
34
+ const spans = items()
35
+ expect(spans).toHaveLength(3)
36
+ expect(spans[0]!.className).toBe('material-symbols-outlined')
37
+ expect(spans[0]!.textContent).toBe('favorite')
38
+ expect(spans[0]!.style.color).toBe('#c83228')
39
+ expect(spans[0]!.style.fontVariationSettings).toContain('FILL')
40
+ for (const s of spans) s.getAnimations().forEach((a) => a.finish())
41
+ expect(layer()).toBeNull()
42
+ el.remove()
43
+ })
44
+
45
+ it('only fades in place under reduced motion', () => {
46
+ vi.stubGlobal('matchMedia', (q: string) => ({ matches: q.includes('reduce') }))
47
+ fireReaction({ x: 10, y: 10 }, '👍')
48
+ const frames = items()[0]!.getAnimations()[0]!.effect!.getKeyframes!()
49
+ expect(frames.every((f) => f.transform === 'translate(-50%, -50%)')).toBe(true)
50
+ })
51
+ })
@@ -0,0 +1,83 @@
1
+ import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest'
2
+ import { mount } from '@vue/test-utils'
3
+ import { defineComponent, h, withDirectives } from 'vue'
4
+ import { vSparkle, type SparkleValue } from '../directives/vSparkle'
5
+
6
+ function host(value: SparkleValue) {
7
+ return mount(defineComponent({
8
+ setup() {
9
+ return () => withDirectives(h('div', { class: 'host' }, 'New'), [[vSparkle, value]])
10
+ },
11
+ }), { attachTo: document.body })
12
+ }
13
+
14
+ const sparkles = (el: Element) => el.querySelectorAll('.m3-sparkle-layer svg')
15
+
16
+ beforeEach(() => {
17
+ vi.useFakeTimers()
18
+ })
19
+ afterEach(() => {
20
+ vi.useRealTimers()
21
+ vi.unstubAllGlobals()
22
+ })
23
+
24
+ describe('vSparkle', () => {
25
+ it('keeps adding sparkles over the element, in a layer hidden from assistive technology', () => {
26
+ const w = host(undefined)
27
+ vi.advanceTimersByTime(3000)
28
+ const layer = w.element.querySelector('.m3-sparkle-layer')!
29
+ expect(layer.getAttribute('aria-hidden')).toBe('true')
30
+ expect((layer as HTMLElement).style.pointerEvents).toBe('none')
31
+ expect(sparkles(w.element).length).toBeGreaterThan(3)
32
+ expect((w.element as HTMLElement).style.position).toBe('relative')
33
+ w.unmount()
34
+ })
35
+
36
+ it('removes each sparkle when its animation ends, and the layer on unmount', () => {
37
+ const w = host(true)
38
+ vi.advanceTimersByTime(1000)
39
+ const first = sparkles(w.element)[0]!
40
+ first.getAnimations().forEach((a) => a.finish())
41
+ expect(first.isConnected).toBe(false)
42
+ const el = w.element
43
+ w.unmount()
44
+ expect(el.querySelector('.m3-sparkle-layer')).toBeNull()
45
+ })
46
+
47
+ it("'hover' sparkles only while the pointer is over it", () => {
48
+ const w = host('hover')
49
+ vi.advanceTimersByTime(2000)
50
+ expect(sparkles(w.element)).toHaveLength(0)
51
+ w.element.dispatchEvent(new PointerEvent('pointerenter'))
52
+ // One right away
53
+ expect(sparkles(w.element).length).toBe(1)
54
+ vi.advanceTimersByTime(2000)
55
+ const during = sparkles(w.element).length
56
+ expect(during).toBeGreaterThan(1)
57
+ w.element.dispatchEvent(new PointerEvent('pointerleave'))
58
+ vi.advanceTimersByTime(2000)
59
+ expect(sparkles(w.element).length).toBe(during)
60
+ w.unmount()
61
+ })
62
+
63
+ it('uses the given color and shapes', () => {
64
+ const w = host({ color: '#f5b400', shapes: ['Heart'] })
65
+ vi.advanceTimersByTime(1500)
66
+ const path = w.element.querySelector('.m3-sparkle-layer path') as SVGPathElement
67
+ expect(path.style.fill).toBe('#f5b400')
68
+ expect(path.getAttribute('d')).not.toContain('C54 34')
69
+ w.unmount()
70
+ })
71
+
72
+ it('nothing when disabled or under reduced motion', () => {
73
+ const off = host(false)
74
+ vi.advanceTimersByTime(2000)
75
+ expect(sparkles(off.element)).toHaveLength(0)
76
+ off.unmount()
77
+ vi.stubGlobal('matchMedia', (q: string) => ({ matches: q.includes('reduce') }))
78
+ const reduced = host(true)
79
+ vi.advanceTimersByTime(2000)
80
+ expect(sparkles(reduced.element)).toHaveLength(0)
81
+ reduced.unmount()
82
+ })
83
+ })
@@ -19,6 +19,7 @@ import { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch
19
19
  import MIcon from './MIcon.vue'
20
20
  import { useLocale, type M3Locale } from '../composables/useLocale'
21
21
  import { emojiCategories, toneableEmojis, withSkinTone, type EmojiCategory } from '../data/emojis'
22
+ import { storageKey } from '../composables/_storageKeys'
22
23
 
23
24
  const props = withDefaults(
24
25
  defineProps<{
@@ -92,14 +93,14 @@ const RECENT_KEY = 'm3-emoji-recent'
92
93
  const TONE_KEY = 'm3-emoji-tone'
93
94
  function read<T>(key: string, fallback: T): T {
94
95
  try {
95
- const v = localStorage.getItem(key)
96
+ const v = localStorage.getItem(storageKey(key))
96
97
  return v === null ? fallback : (JSON.parse(v) as T)
97
98
  } catch {
98
99
  return fallback
99
100
  }
100
101
  }
101
102
  function store(key: string, value: unknown) {
102
- try { localStorage.setItem(key, JSON.stringify(value)) } catch { /* storage blocked */ }
103
+ try { localStorage.setItem(storageKey(key), JSON.stringify(value)) } catch { /* storage blocked */ }
103
104
  }
104
105
  const recents = ref<string[]>(read<string[]>(RECENT_KEY, []))
105
106
  const tone = ref<number>(read<number>(TONE_KEY, 0))
@@ -23,6 +23,7 @@ import MMapAttribution from './_MMapAttribution.vue'
23
23
  import { useLocale } from '../composables/useLocale'
24
24
  import { MAP_KEY, type MapContext, type MaplibreModule } from '../composables/useMap'
25
25
  import { createLayerState, readLayerState } from '../composables/useMapLayers'
26
+ import { storageKey } from '../composables/_storageKeys'
26
27
  import type { MapAdapter, MapLayerModel } from '../composables/mapAdapters'
27
28
  import { carryRuntimeLayers, styleIds, type StyleIds } from '../composables/_mapStyle'
28
29
 
@@ -56,7 +57,7 @@ const props = withDefaults(
56
57
  pitch?: number
57
58
  /**
58
59
  * Remember the view (center, zoom, bearing, pitch) in localStorage and start from it on the next visit: `true`
59
- * under `m3-map-view`, or your own key (one per map)
60
+ * under `m3-map-view` (after `createM3UI`'s `storagePrefix`, if any), or your own key (one per map)
60
61
  */
61
62
  persist?: boolean | string
62
63
  /** Zoom and compass buttons: `false`, or a corner (`true` is top-right) */
@@ -123,7 +124,7 @@ const t = useLocale()
123
124
  // ── Remembered view ────────────────────────────────────────────────────────────────────────────
124
125
 
125
126
  interface View { center: [number, number]; zoom: number; bearing: number; pitch: number }
126
- const persistKey = () => (typeof props.persist === 'string' ? props.persist : props.persist ? 'm3-map-view' : null)
127
+ const persistKey = () => (typeof props.persist === 'string' ? props.persist : props.persist ? storageKey('m3-map-view') : null)
127
128
 
128
129
  function readView(): Partial<View> {
129
130
  const key = persistKey()