@m3ui-vue/m3ui-vue 1.8.0 → 1.8.1

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 @@
1
+ {"version":3,"file":"MProgressBar-BWly1UKN.js","names":["_openBlock","_createElementBlock","_normalizeStyle","_toDisplayString","_normalizeClass","_Fragment","_createElementVNode","_unref","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","PERIOD","AMP","STEP","MARGIN_PX","WAVE_START","VALUE_TAU","MProgressBar_default","defineComponent","props","__props","isIndeterminate","computed","clampedValue","ROLES","roleOr","c","colorVars","effectiveThickness","waveMid","waveViewH","waveWidth","staticWavePath","d","x","y","displayedValue","appearanceF","animPhase","appearAnim","easeInOut","t","startAnim","from","to","now","tickAnim","a","v","waveClipEl","ref","trackEl","wavePath","lastTime","rafId","PHASE_PER_MS","buildWavePath","mid","pts","factor","ph","tick","dt","k","margin","dv","prev","initAndStart","stopRaf","onMounted","onUnmounted","watch","nextTick","openBlock","createElementBlock","normalizeStyle","toDisplayString","createCommentVNode","normalizeClass","Fragment","createElementVNode","unref","\"top\"","\"transform\""],"sources":["../src/components/MProgressBar.vue"],"sourcesContent":["<script setup lang=\"ts\">\n/**\n * A linear progress indicator — determinate, indeterminate, or the M3 Expressive wavy variant.\n */\nimport { computed, ref, watch, onMounted, onUnmounted, nextTick } from \"vue\";\n\nconst props = withDefaults(\n defineProps<{\n /** Progress 0–100 (omit for indeterminate) */\n value?: number;\n /** Indeterminate animation — also implied by omitting value */\n indeterminate?: boolean;\n /** Bar color: an M3 role or any CSS color (`#fff` over a photo, say) */\n color?: \"primary\" | \"secondary\" | \"tertiary\" | \"error\" | (string & {});\n /** Track color: an M3 role or any CSS color. Default the role's container, or the bar color at 24% for a CSS color */\n trackColor?: string;\n /** Bar style */\n variant?: \"linear\" | \"wavy\";\n /** Label text above the bar */\n label?: string;\n /** Stroke width in px. Defaults to 4dp, matching the real M3 token for both variants. */\n thickness?: number;\n }>(),\n { color: \"primary\", variant: \"linear\" },\n);\n\nconst isIndeterminate = computed(() => props.indeterminate || props.value === undefined);\nconst clampedValue = computed(() => Math.min(100, Math.max(0, props.value ?? 0)));\n\nconst ROLES = [\"primary\", \"secondary\", \"tertiary\", \"error\"];\nconst roleOr = (c: string) => (ROLES.includes(c) || c.endsWith(\"-container\") ? `var(--color-${c})` : c);\n// Both colors go through custom properties on the root, read by the bar/track/wave below.\nconst colorVars = computed(() => {\n const bar = roleOr(props.color);\n const track = props.trackColor\n ? roleOr(props.trackColor)\n : ROLES.includes(props.color)\n ? `var(--color-${props.color}-container)`\n : `color-mix(in srgb, ${props.color} 24%, transparent)`;\n return { \"--m3-progress-bar\": bar, \"--m3-progress-track\": track };\n});\n\n// ── Wave geometry ─────────────────────────────────────────────────────────\nconst PERIOD = 20;\nconst AMP = 2.5;\nconst PERIODS = 80;\nconst STEP = 2;\nconst MARGIN_PX = 4; // gap between wave right-end and track start\nconst WAVE_START = 10; // threshold % below which wave collapses to line\n\n// thickness-derived (computed so they react to prop changes)\nconst effectiveThickness = computed(() => props.thickness ?? 4);\nconst waveMid = computed(() => AMP + effectiveThickness.value / 2);\nconst waveViewH = computed(() => 2 * AMP + effectiveThickness.value);\n\nconst waveWidth = PERIOD * PERIODS; // 1600px — covers any container width\n\n// Static path for indeterminate — built once with the wavy default (thickness=3)\nconst STATIC_MID = AMP + 3 / 2; // = 4\nconst staticWavePath = (() => {\n let d = \"\";\n for (let x = 0; x <= waveWidth; x += STEP) {\n const y = STATIC_MID - AMP * Math.sin((x / PERIOD) * Math.PI * 2);\n d += `${x === 0 ? \"M\" : \"L\"}${x},${y.toFixed(2)} `;\n }\n return d.trim();\n})();\n\n// ── rAF state (plain JS — no Vue refs to avoid 60fps reactive overhead) ───\n//\n// Architecture mirrors MCircleProgressBar:\n// • displayedValue follows clampedValue with exponential smoothing (~300ms)\n// • appearanceF animates 0↔1 at the WAVE_START threshold and at 100%\n// • animPhase advances every frame to scroll the wave leftward\n// clip-path and track.left are written via direct DOM setAttribute/style\n// to avoid the CSS-transition vs rAF conflict.\nlet displayedValue = 0;\nlet appearanceF = 0;\nlet animPhase = 0;\n\ntype Anim = { from: number; to: number; t0: number; dur: number };\nconst appearAnim: Anim = { from: 0, to: 0, t0: -1, dur: 500 };\n\nfunction easeInOut(t: number) {\n return t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;\n}\nfunction startAnim(a: Anim, from: number, to: number, now: number) {\n if (Math.abs(from - to) < 0.001) { a.t0 = -1; a.to = to; return; }\n a.from = from; a.to = to; a.t0 = now;\n}\nfunction tickAnim(a: Anim, now: number): number {\n if (a.t0 < 0) return a.to;\n const t = Math.min(1, (now - a.t0) / a.dur);\n const v = a.from + (a.to - a.from) * easeInOut(t);\n if (t >= 1) a.t0 = -1;\n return v;\n}\n\n// ── Template refs for direct DOM updates ─────────────────────────────────\nconst waveClipEl = ref<HTMLDivElement | null>(null);\nconst trackEl = ref<HTMLDivElement | null>(null);\nconst wavePath = ref(\"\"); // updated in tick → drives path's :d binding\n\n// ── rAF tick ─────────────────────────────────────────────────────────────\nlet lastTime: number | null = null;\nlet rafId = 0;\nconst PHASE_PER_MS = (2 * Math.PI) / 800; // one full PERIOD scroll per 800ms\nconst VALUE_TAU = 130; // exponential τ → ~300ms 90%-settle\n\nfunction buildWavePath(factor: number, ph: number): string {\n const mid = waveMid.value;\n const pts: string[] = [];\n for (let x = 0; x <= waveWidth; x += STEP) {\n const y = mid - AMP * factor * Math.sin((x / PERIOD) * Math.PI * 2 + ph);\n pts.push(`${x === 0 ? \"M\" : \"L\"}${x},${y.toFixed(2)}`);\n }\n return pts.join(\" \");\n}\n\nfunction tick(now: number) {\n const dt = lastTime !== null ? now - lastTime : 0;\n lastTime = now;\n\n // 1. Wave phase scrolls leftward\n animPhase -= dt * PHASE_PER_MS;\n\n // 2. Smooth displayed value (exponential interpolation)\n if (dt > 0) {\n const k = 1 - Math.exp(-dt / VALUE_TAU);\n displayedValue += (clampedValue.value - displayedValue) * k;\n }\n\n // 3. Advance appearance animation\n appearanceF = tickAnim(appearAnim, now);\n\n // 4. Update DOM directly\n const margin = MARGIN_PX * appearanceF;\n const dv = displayedValue;\n\n if (waveClipEl.value)\n waveClipEl.value.style.clipPath = `inset(0 ${(100 - dv).toFixed(3)}% 0 0)`;\n\n if (trackEl.value) {\n trackEl.value.style.left = `calc(${dv.toFixed(3)}% + ${margin.toFixed(2)}px)`;\n trackEl.value.style.height = `${effectiveThickness.value}px`;\n }\n\n // 5. Rebuild wave path (drives :d via Vue ref)\n wavePath.value = buildWavePath(appearanceF, animPhase);\n\n rafId = requestAnimationFrame(tick);\n}\n\n// ── Watchers ─────────────────────────────────────────────────────────────\nwatch(clampedValue, (v, prev) => {\n if (props.variant !== \"wavy\" || isIndeterminate.value) return;\n const now = performance.now();\n\n if (prev <= WAVE_START && v > WAVE_START && v < 100) startAnim(appearAnim, appearanceF, 1, now);\n else if (prev > WAVE_START && v <= WAVE_START) startAnim(appearAnim, appearanceF, 0, now);\n else if (v === 100) startAnim(appearAnim, appearanceF, 0, now);\n else if (prev === 100 && v > WAVE_START) startAnim(appearAnim, appearanceF, 1, now);\n});\n\nfunction initAndStart() {\n displayedValue = clampedValue.value;\n const v = clampedValue.value;\n appearanceF = (v > WAVE_START && v < 100) ? 1 : 0;\n appearAnim.to = appearanceF;\n appearAnim.t0 = -1;\n\n // Set initial DOM values immediately to avoid a one-frame flash\n const margin = MARGIN_PX * appearanceF;\n if (waveClipEl.value)\n waveClipEl.value.style.clipPath = `inset(0 ${(100 - v).toFixed(3)}% 0 0)`;\n if (trackEl.value) {\n trackEl.value.style.left = `calc(${v.toFixed(3)}% + ${margin.toFixed(2)}px)`;\n trackEl.value.style.height = `${effectiveThickness.value}px`;\n }\n wavePath.value = buildWavePath(appearanceF, animPhase);\n\n if (!rafId) rafId = requestAnimationFrame(tick);\n}\n\nfunction stopRaf() {\n cancelAnimationFrame(rafId);\n rafId = 0; lastTime = null;\n appearAnim.t0 = -1;\n}\n\nonMounted(() => {\n if (props.variant === \"wavy\" && !isIndeterminate.value) initAndStart();\n});\nonUnmounted(stopRaf);\n\nwatch(() => props.variant, async (v) => {\n if (v === \"wavy\" && !isIndeterminate.value) { await nextTick(); initAndStart(); }\n else stopRaf();\n});\nwatch(isIndeterminate, async (v) => {\n if (!v && props.variant === \"wavy\") { await nextTick(); initAndStart(); }\n else stopRaf();\n});\n</script>\n\n<template>\n <div class=\"flex flex-col gap-1\" :style=\"colorVars\">\n <span v-if=\"label\" class=\"text-label-small text-on-surface-variant\">{{ label }}</span>\n\n <!-- ── Linear variant ────────────────────────────────────────────────── -->\n <div\n v-if=\"variant === 'linear'\"\n class=\"relative w-full overflow-hidden rounded-full\"\n :class=\"isIndeterminate ? 'bg-(--m3-progress-track)' : ''\"\n :style=\"{ height: `${effectiveThickness}px` }\"\n role=\"progressbar\"\n :aria-valuenow=\"isIndeterminate ? undefined : clampedValue\"\n aria-valuemin=\"0\"\n aria-valuemax=\"100\"\n >\n <!-- LinearProgressIndicatorTokens.TrackActiveSpace=4dp: the track starts\n a fixed gap after the active bar, not flush against it. -->\n <template v-if=\"!isIndeterminate\">\n <div\n class=\"absolute inset-y-0 left-0 rounded-full transition-[width] duration-300 ease-in-out bg-(--m3-progress-bar)\"\n :style=\"{ width: `${clampedValue}%` }\"\n />\n <div\n class=\"absolute inset-y-0 right-0 rounded-full transition-[left] duration-300 ease-in-out bg-(--m3-progress-track)\"\n :style=\"{ left: `calc(${clampedValue}% + 4px)` }\"\n />\n </template>\n <div\n v-else\n class=\"absolute inset-y-0 w-2/5 rounded-full animate-[m3-progress-indeterminate_1.6s_ease-in-out_infinite] bg-(--m3-progress-bar)\"\n />\n </div>\n\n <!-- ── Wavy variant ───────────────────────────────────────────────────── -->\n <div\n v-else\n class=\"relative w-full overflow-visible\"\n :style=\"{ height: `${waveViewH}px` }\"\n role=\"progressbar\"\n :aria-valuenow=\"isIndeterminate ? undefined : clampedValue\"\n aria-valuemin=\"0\"\n aria-valuemax=\"100\"\n >\n <!-- DETERMINATE — rAF drives clip-path, track.left, and wave path -->\n <template v-if=\"!isIndeterminate\">\n <!-- Active wave, clipped to displayedValue% -->\n <div\n ref=\"waveClipEl\"\n class=\"absolute inset-0 overflow-hidden\"\n style=\"clip-path: inset(0 100% 0 0)\"\n >\n <svg\n class=\"absolute top-0 left-0 h-full text-(--m3-progress-bar)\"\n :width=\"waveWidth\"\n :height=\"waveViewH\"\n :viewBox=\"`0 0 ${waveWidth} ${waveViewH}`\"\n >\n <path\n :d=\"wavePath\"\n fill=\"none\"\n stroke=\"currentColor\"\n :stroke-width=\"effectiveThickness\"\n stroke-linecap=\"round\"\n />\n </svg>\n </div>\n\n <!-- Inactive track — rAF owns left and height; no Vue-managed left -->\n <div\n ref=\"trackEl\"\n class=\"absolute right-0 bg-(--m3-progress-track)\"\n style=\"border-radius: 9999px; top: 50%; transform: translateY(-50%);\"\n />\n\n <!-- Stop dot at far right -->\n <div\n class=\"absolute rounded-full bg-(--m3-progress-bar)\"\n :style=\"{\n right: '0',\n top: '50%',\n transform: 'translateY(-50%)',\n width: `${effectiveThickness}px`,\n height: `${effectiveThickness}px`,\n }\"\n />\n </template>\n\n <!-- INDETERMINATE — keeps original CSS-animated wide strip -->\n <div v-else class=\"absolute inset-0 overflow-hidden rounded-full\">\n <div\n class=\"absolute top-0 left-0 h-full animate-[m3-wave-flow_0.9s_linear_infinite] text-(--m3-progress-bar)\"\n :style=\"{ width: `${waveWidth}px` }\"\n >\n <svg\n :width=\"waveWidth\"\n :height=\"waveViewH\"\n :viewBox=\"`0 0 ${waveWidth} ${waveViewH}`\"\n class=\"h-full\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n :d=\"staticWavePath\"\n fill=\"none\"\n stroke=\"currentColor\"\n :stroke-width=\"effectiveThickness\"\n stroke-linecap=\"round\"\n />\n </svg>\n </div>\n </div>\n </div>\n </div>\n</template>\n\n<style>\n@keyframes m3-wave-flow {\n from { transform: translateX(0); }\n to { transform: translateX(-20px); }\n}\n\n@keyframes m3-progress-indeterminate {\n 0% { left: -40%; }\n 100% { left: 100%; }\n}\n\n@media (prefers-reduced-motion: reduce) {\n .animate-\\[m3-wave-flow_1\\.2s_linear_infinite\\],\n .animate-\\[m3-wave-flow_0\\.9s_linear_infinite\\],\n .animate-\\[m3-progress-indeterminate_1\\.6s_ease-in-out_infinite\\] {\n animation: none !important;\n }\n}\n</style>\n"],"mappings":";;;;;;;;;;;A,0DA2CMiB,IAAa,IACbC,IAAa,KAEbC,IAAa,GACbC,IAAa,GACbC,IAAa,IA2DbC,IAAe,K;;;;;;;;;;;;EArGrB,IAAMG,IAAQC,GAoBRC,IAAkBC,QAAeH,EAAM,iBAAiBA,EAAM,UAAU,KAAA,CAAS,GACjFI,IAAkBD,QAAe,KAAK,IAAI,KAAK,KAAK,IAAI,GAAGH,EAAM,SAAS,CAAC,CAAC,CAAC,GAE7EK,IAAQ;GAAC;GAAW;GAAa;GAAY;EAAO,GACpDC,KAAU,MAAeD,EAAM,SAASE,CAAC,KAAKA,EAAE,SAAS,YAAY,IAAI,eAAeA,EAAE,KAAKA,GAE/FC,KAAYL,SAOT;GAAE,qBANGG,EAAON,EAAM,KAMK;GAAK,uBALrBA,EAAM,aAChBM,EAAON,EAAM,UAAU,IACvBK,EAAM,SAASL,EAAM,KAAK,IACxB,eAAeA,EAAM,MAAM,eAC3B,sBAAsBA,EAAM,MAAM;EACwB,EACjE,GAWKS,IAAqBN,QAAeH,EAAM,aAAa,CAAC,GACxDU,IAAWP,QAAeV,IAAMgB,EAAmB,QAAQ,CAAC,GAC5DE,IAAYR,QAAe,IAAIV,IAAMgB,EAAmB,KAAK,GAE7DG,IAAY,MAIZC,WAAwB;GAC5B,IAAIC,IAAI;GACR,KAAK,IAAIC,IAAI,GAAGA,KAAKH,GAAW,KAAKlB,GAAM;IACzC,IAAMsB,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AM;IACN,OAAA,EAAA,aAAA,oBAAA;G,KAEAvD,EAAA,GAAAC,EAaM,OAAA;IAZJ,OAAM;IACL,OAAOoC;IACP,QAAQD,EAAA;IACR,SAAO,OAASC,EAAS,GAAID,EAAA;G,IAE9B9B,EAME,QAAA;IALC,GAAGoD,EAAA;IACJ,MAAK;IACL,QAAO;IACN,gBAAcxB,EAAA;IACf,kBAAe;;GAMrB5B,EAIE,OAAA;IAHI,SAAA;IAAJ,KAAImD;IACJ,OAAM;IACN,OAAA;KAAA,iBAAA;KAAA+B,KAAA;KAAAC,WAAA;IAAA;;GAIFnF,EASE,OAAA;IARA,OAAM;IACL,OAAKJ,EAAA;;;;KAAqH,OAAA,GAAAgC,EAAA,MAAkB;KAA6B,QAAA,GAAAA,EAAA,MAAkB"}
@@ -0,0 +1,140 @@
1
+ import { n as e } from "./_useFieldValidation-B0B44M_t.js";
2
+ import { Fragment as t, computed as n, createCommentVNode as r, createElementBlock as i, createElementVNode as a, defineComponent as o, mergeProps as s, onMounted as c, openBlock as l, ref as u, toDisplayString as d, unref as f, watch as p } from "vue";
3
+ // src/components/MSignaturePad.vue?vue&type=script&setup=true&lang.ts
4
+ var m = [
5
+ "width",
6
+ "height",
7
+ "aria-invalid",
8
+ "aria-describedby"
9
+ ], h = ["id"], g = /* @__PURE__ */ o({
10
+ inheritAttrs: !1,
11
+ __name: "MSignaturePad",
12
+ props: {
13
+ width: { default: 400 },
14
+ height: { default: 200 },
15
+ lineWidth: { default: 2.5 },
16
+ color: { default: "#000000" },
17
+ background: { default: "#ffffff" },
18
+ variant: { default: "outlined" },
19
+ disabled: {
20
+ type: Boolean,
21
+ default: !1
22
+ },
23
+ error: { type: [Boolean, String] },
24
+ errorLabel: {},
25
+ required: { type: Boolean },
26
+ rules: {},
27
+ validateOn: {},
28
+ validateDebounce: {},
29
+ name: {}
30
+ },
31
+ emits: [
32
+ "begin",
33
+ "end",
34
+ "change"
35
+ ],
36
+ setup(o, { expose: g, emit: _ }) {
37
+ let v = o, y = _, b = u(null), x = u(null), S = e({
38
+ value: () => b.value,
39
+ rules: () => v.rules,
40
+ required: () => v.required,
41
+ error: () => v.error,
42
+ errorLabel: () => v.errorLabel,
43
+ name: () => v.name,
44
+ validateOn: () => v.validateOn,
45
+ validateDebounce: () => v.validateDebounce,
46
+ disabled: () => v.disabled,
47
+ focus: () => x.value?.scrollIntoView({
48
+ block: "center",
49
+ behavior: "smooth"
50
+ }),
51
+ el: () => x.value,
52
+ setValue: () => L()
53
+ }), C = S.disabled, { hasError: w, message: T, messageId: E } = S, D = u(null), O = u([]), k = u(!1), A = n(() => O.value.length === 0);
54
+ function j() {
55
+ return D.value?.getContext("2d") ?? null;
56
+ }
57
+ function M() {
58
+ let e = j(), t = D.value;
59
+ if (e && t) {
60
+ e.clearRect(0, 0, t.width, t.height), e.fillStyle = v.background, e.fillRect(0, 0, t.width, t.height), e.strokeStyle = v.color, e.lineWidth = v.lineWidth, e.lineCap = "round", e.lineJoin = "round";
61
+ for (let t of O.value) if (!(t.length < 2)) {
62
+ e.beginPath(), e.moveTo(t[0].x, t[0].y);
63
+ for (let n of t.slice(1)) e.lineTo(n.x, n.y);
64
+ e.stroke();
65
+ }
66
+ }
67
+ }
68
+ function N(e) {
69
+ let t = D.value.getBoundingClientRect();
70
+ return {
71
+ x: e.clientX - t.left,
72
+ y: e.clientY - t.top
73
+ };
74
+ }
75
+ function P(e) {
76
+ C.value || (k.value = !0, O.value.push([N(e)]), y("begin"), D.value?.setPointerCapture(e.pointerId));
77
+ }
78
+ function F(e) {
79
+ k.value && (O.value[O.value.length - 1].push(N(e)), M());
80
+ }
81
+ function I() {
82
+ if (!k.value) return;
83
+ k.value = !1;
84
+ let e = B();
85
+ b.value = e, y("end", e), y("change", e), S.onBlur();
86
+ }
87
+ function L() {
88
+ O.value = [], b.value = null, M();
89
+ }
90
+ function R() {
91
+ O.value = O.value.slice(0, -1), M();
92
+ let e = B();
93
+ b.value = A.value ? null : e, y("change", e);
94
+ }
95
+ function z() {
96
+ return A.value;
97
+ }
98
+ function B(e, t) {
99
+ return D.value?.toDataURL(e, t) ?? "";
100
+ }
101
+ p([
102
+ () => v.color,
103
+ () => v.background,
104
+ () => v.lineWidth
105
+ ], M), c(M), g({
106
+ clear: L,
107
+ undo: R,
108
+ isEmpty: z,
109
+ toDataURL: B,
110
+ validate: S.validate,
111
+ resetValidation: S.resetValidation
112
+ });
113
+ let V = n(() => v.variant === "outlined" ? ["rounded-sm border", w.value ? "border-error" : "border-outline"] : ["rounded-t-sm bg-surface-container-highest border-b", w.value ? "border-error" : "border-on-surface-variant"]);
114
+ return (e, n) => (l(), i(t, null, [a("div", s({
115
+ ref_key: "rootEl",
116
+ ref: x
117
+ }, e.$attrs, { class: ["inline-block touch-none", [V.value, f(C) ? "cursor-not-allowed opacity-[0.38]" : "cursor-crosshair"]] }), [a("canvas", {
118
+ ref_key: "canvasEl",
119
+ ref: D,
120
+ width: o.width,
121
+ height: o.height,
122
+ role: "img",
123
+ "aria-label": "Signature pad",
124
+ "aria-invalid": f(w) || void 0,
125
+ "aria-describedby": f(T) ? f(E) : void 0,
126
+ onPointerdown: P,
127
+ onPointermove: F,
128
+ onPointerup: I,
129
+ onPointerleave: I
130
+ }, null, 40, m)], 16), f(T) ? (l(), i("p", {
131
+ key: 0,
132
+ id: f(E),
133
+ role: "alert",
134
+ class: "mt-1 text-body-small text-error"
135
+ }, d(f(T)), 9, h)) : r("", !0)], 64));
136
+ }
137
+ });
138
+ export { g as t };
139
+
140
+ //# sourceMappingURL=MSignaturePad-CxOtelzE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MSignaturePad-CxOtelzE.js","names":["$attrs","_openBlock","_createElementBlock","_createElementVNode","_mergeProps","_unref","_toDisplayString","useFieldValidation","_hoisted_1","_hoisted_2","MSignaturePad_default","defineComponent","__expose","__emit","props","__props","emit","signature","ref","rootEl","validation","clear","isDisabled","errorMessage","canvasEl","strokes","drawing","empty","computed","getContext","redraw","ctx","canvas","stroke","point","pointFromEvent","rect","onPointerDown","onPointerMove","onPointerUp","dataUrl","toDataURL","undo","isEmpty","type","quality","watch","onMounted","containerClasses","hasError","openBlock","createElementBlock","Fragment","createElementVNode","mergeProps","_ctx","unref","messageId","toDisplayString","createCommentVNode"],"sources":["../src/components/MSignaturePad.vue"],"sourcesContent":["<script setup lang=\"ts\">\n/**\n * A bordered canvas that captures pointer strokes for signature capture. There's no v-model, since a signature\n * isn't a simple value — read it out via events or the exposed methods.\n *\n * @event end Fires after a stroke ends, with a PNG data: URL of the canvas\n * @event change Fires alongside end, and also after undo() — same data: URL payload\n * @event begin Fires on the first pointerdown of a new stroke\n *\n * In an `MForm` it validates as a field whose value is the PNG data: URL (null while empty): `required` asks for a\n * signature, and the form's values carry it under `name`.\n */\nimport { computed, onMounted, ref, watch } from 'vue'\nimport { useFieldValidation } from '../composables/_useFieldValidation'\nimport type { ValidateOn, ValidationRule } from '../composables/validation'\n\nconst props = withDefaults(\n defineProps<{\n /** Canvas width in px */\n width?: number\n /** Canvas height in px */\n height?: number\n /** Stroke width */\n lineWidth?: number\n /** Stroke color */\n color?: string\n /** Canvas background color */\n background?: string\n /** Container border style */\n variant?: 'filled' | 'outlined'\n /** Disables drawing */\n disabled?: boolean\n /** Error state. A string is also the message */\n error?: boolean | string\n /** Error message shown when `error` is true */\n errorLabel?: string\n /** Inside an `MForm` or with `rules`, a signature must be drawn */\n required?: boolean\n /** Validation rules (functions or a Standard Schema); see `MForm` */\n rules?: ValidationRule | ValidationRule[]\n /** When the rules are checked and shown: after each stroke (default), or only on submit */\n validateOn?: ValidateOn\n /** Wait this long (ms) after the value stops changing before re-checking (one request for an async rule, not one per key). Defaults to its `MForm`'s */\n validateDebounce?: number\n /** The key of this field in its `MForm` */\n name?: string\n }>(),\n {\n width: 400,\n height: 200,\n lineWidth: 2.5,\n color: '#000000',\n background: '#ffffff',\n variant: 'outlined',\n disabled: false,\n },\n)\n\n// Pad + its message: attributes go on the pad\ndefineOptions({ inheritAttrs: false })\n\nconst emit = defineEmits<{ begin: []; end: [string]; change: [string] }>()\n\n/** The signature as a data: URL, null while empty: what validation checks and an MForm submits */\nconst signature = ref<string | null>(null)\nconst rootEl = ref<HTMLElement | null>(null)\nconst validation = useFieldValidation({\n value: () => signature.value,\n rules: () => props.rules,\n required: () => props.required,\n error: () => props.error,\n errorLabel: () => props.errorLabel,\n name: () => props.name,\n validateOn: () => props.validateOn,\n validateDebounce: () => props.validateDebounce,\n disabled: () => props.disabled,\n // A canvas takes no focus: bring it into view instead\n focus: () => rootEl.value?.scrollIntoView({ block: 'center', behavior: 'smooth' }),\n el: () => rootEl.value,\n // MForm's reset(): back to empty\n setValue: () => clear(),\n})\n/** Its own `disabled` or its MForm's */\nconst isDisabled = validation.disabled\nconst { hasError, message: errorMessage, messageId } = validation\n\ntype Point = { x: number; y: number }\n\nconst canvasEl = ref<HTMLCanvasElement | null>(null)\nconst strokes = ref<Point[][]>([])\nconst drawing = ref(false)\nconst empty = computed(() => strokes.value.length === 0)\n\nfunction getContext() {\n return canvasEl.value?.getContext('2d') ?? null\n}\n\nfunction redraw() {\n const ctx = getContext()\n const canvas = canvasEl.value\n if (!ctx || !canvas) return\n\n ctx.clearRect(0, 0, canvas.width, canvas.height)\n ctx.fillStyle = props.background\n ctx.fillRect(0, 0, canvas.width, canvas.height)\n\n ctx.strokeStyle = props.color\n ctx.lineWidth = props.lineWidth\n ctx.lineCap = 'round'\n ctx.lineJoin = 'round'\n\n for (const stroke of strokes.value) {\n if (stroke.length < 2) continue\n ctx.beginPath()\n ctx.moveTo(stroke[0]!.x, stroke[0]!.y)\n for (const point of stroke.slice(1)) ctx.lineTo(point.x, point.y)\n ctx.stroke()\n }\n}\n\nfunction pointFromEvent(e: PointerEvent): Point {\n const rect = canvasEl.value!.getBoundingClientRect()\n return { x: e.clientX - rect.left, y: e.clientY - rect.top }\n}\n\nfunction onPointerDown(e: PointerEvent) {\n if (isDisabled.value) return\n drawing.value = true\n strokes.value.push([pointFromEvent(e)])\n emit('begin')\n canvasEl.value?.setPointerCapture(e.pointerId)\n}\n\nfunction onPointerMove(e: PointerEvent) {\n if (!drawing.value) return\n strokes.value[strokes.value.length - 1]!.push(pointFromEvent(e))\n redraw()\n}\n\nfunction onPointerUp() {\n if (!drawing.value) return\n drawing.value = false\n const dataUrl = toDataURL()\n signature.value = dataUrl\n emit('end', dataUrl)\n emit('change', dataUrl)\n // A finished stroke counts as having used the field\n validation.onBlur()\n}\n\nfunction clear() {\n strokes.value = []\n signature.value = null\n redraw()\n}\n\nfunction undo() {\n strokes.value = strokes.value.slice(0, -1)\n redraw()\n const dataUrl = toDataURL()\n signature.value = empty.value ? null : dataUrl\n emit('change', dataUrl)\n}\n\nfunction isEmpty(): boolean {\n return empty.value\n}\n\nfunction toDataURL(type?: string, quality?: number): string {\n return canvasEl.value?.toDataURL(type, quality) ?? ''\n}\n\nwatch([() => props.color, () => props.background, () => props.lineWidth], redraw)\n\nonMounted(redraw)\n\ndefineExpose({\n clear,\n undo,\n isEmpty,\n toDataURL,\n /** Checks its rules and shows the result; resolves to whether they pass */\n validate: validation.validate,\n /** Hides its validation error (until the next check) */\n resetValidation: validation.resetValidation,\n})\n\nconst containerClasses = computed(() => {\n if (props.variant === 'outlined') {\n return ['rounded-sm border', hasError.value ? 'border-error' : 'border-outline']\n }\n return ['rounded-t-sm bg-surface-container-highest border-b', hasError.value ? 'border-error' : 'border-on-surface-variant']\n})\n</script>\n\n<template>\n <div\n ref=\"rootEl\"\n v-bind=\"$attrs\"\n class=\"inline-block touch-none\"\n :class=\"[containerClasses, isDisabled ? 'cursor-not-allowed opacity-[0.38]' : 'cursor-crosshair']\"\n >\n <canvas\n ref=\"canvasEl\"\n :width=\"width\"\n :height=\"height\"\n role=\"img\"\n aria-label=\"Signature pad\"\n :aria-invalid=\"hasError || undefined\"\n :aria-describedby=\"errorMessage ? messageId : undefined\"\n @pointerdown=\"onPointerDown\"\n @pointermove=\"onPointerMove\"\n @pointerup=\"onPointerUp\"\n @pointerleave=\"onPointerUp\"\n />\n </div>\n <p v-if=\"errorMessage\" :id=\"messageId\" role=\"alert\" class=\"mt-1 text-body-small text-error\">{{ errorMessage }}</p>\n</template>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAgBA,IAAMc,IAAQC,GA6CRC,IAAOH,GAGPI,IAAYC,EAAmB,IAAI,GACnCC,IAASD,EAAwB,IAAI,GACrCE,IAAab,EAAmB;GACpC,aAAaU,EAAU;GACvB,aAAaH,EAAM;GACnB,gBAAgBA,EAAM;GACtB,aAAaA,EAAM;GACnB,kBAAkBA,EAAM;GACxB,YAAYA,EAAM;GAClB,kBAAkBA,EAAM;GACxB,wBAAwBA,EAAM;GAC9B,gBAAgBA,EAAM;GAEtB,aAAaK,EAAO,OAAO,eAAe;IAAE,OAAO;IAAU,UAAU;GAAS,CAAC;GACjF,UAAUA,EAAO;GAEjB,gBAAgBE,EAAM;EACxB,CAAC,GAEKC,IAAaF,EAAW,UACxB,EAAE,aAAU,SAASG,GAAc,iBAAcH,GAIjDI,IAAWN,EAA8B,IAAI,GAC7CO,IAAUP,EAAe,CAAC,CAAC,GAC3BQ,IAAUR,EAAI,EAAK,GACnBS,IAAQC,QAAeH,EAAQ,MAAM,WAAW,CAAC;EAEvD,SAASI,IAAa;GACpB,OAAOL,EAAS,OAAO,WAAW,IAAI,KAAK;EAC7C;EAEA,SAASM,IAAS;GAChB,IAAMC,IAAMF,EAAW,GACjBG,IAASR,EAAS;GACxB,IAAKO,KAAQC,GAEb;IAOA,AAPAD,EAAI,UAAU,GAAG,GAAGC,EAAO,OAAOA,EAAO,MAAM,GAC/C,EAAI,YAAYlB,EAAM,YACtBiB,EAAI,SAAS,GAAG,GAAGC,EAAO,OAAOA,EAAO,MAAM,GAE9C,EAAI,cAAclB,EAAM,OACxB,EAAI,YAAYA,EAAM,WACtB,EAAI,UAAU,SACd,EAAI,WAAW;IAEf,KAAK,IAAMmB,KAAUR,EAAQ,OAC3B,IAAI,I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