@gecko-ui-kit/vue 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/effects.js ADDED
@@ -0,0 +1,699 @@
1
+ /* Interactive motion from @gecko-ui-kit/motion as Vue components and composables: Indicator, PageSwap, the
2
+ feedback composables, Confetti, Sortable (drag & drop), ThemeToggle + useTheme, Send / Delete / Download / Hold
3
+ buttons, ExpandSearch, LiquidTabs and Burger.
4
+ Vue draws the markup (the same HTML as the vanilla builders, so it renders on the server) and owns the
5
+ state; the vanilla code only animates it. Buttons whose label or look changes are drawn again (a new
6
+ element), because the vanilla motion writes into them while it plays. */
7
+ import {
8
+ defineComponent, ref, shallowRef, readonly, computed, watch, nextTick, toValue, unref, isVNode, useId,
9
+ onMounted, onUpdated, onBeforeUnmount, normalizeClass, normalizeStyle, Comment, Fragment,
10
+ } from 'vue';
11
+ import * as M from '@gecko-ui-kit/motion';
12
+ import { h, B, ANY, anyProps, iconNode, Icon, useModel, modelProps } from './core.js';
13
+ import { Button } from './basics.js';
14
+
15
+ /** Drop undefined values, so a prop left out keeps the vanilla default. */
16
+ const defined = (o) => { const out = {}; for (const k in o) if (o[k] !== undefined) out[k] = o[k]; return out; };
17
+ /** An element from an element, a template ref or a component (its $el); else null. */
18
+ const nodeOf = (x) => { x = unref(x); if (x && typeof x === 'object' && '$el' in x) x = x.$el; return x && x.nodeType === 1 ? x : null; };
19
+ /** An element from an element, a template ref, a component or an event (its currentTarget). */
20
+ const elOf = (x, fallback) => nodeOf(x) ?? (x && x.currentTarget && x.currentTarget.nodeType === 1 ? x.currentTarget : null) ?? fallback;
21
+ /** Stop every tween on an element and everything inside it. */
22
+ const killAll = (el) => { if (el) M.g.killTweensOf([el, ...el.querySelectorAll('*')]); };
23
+ /** The text of slot content (a label). */
24
+ const textOf = (c) => (c == null || typeof c === 'boolean' ? '' : Array.isArray(c) ? c.map(textOf).join('')
25
+ : isVNode(c) ? (c.type === Comment ? '' : typeof c.children === 'string' ? c.children : Array.isArray(c.children) ? textOf(c.children) : '')
26
+ : String(c));
27
+ /** An attribute given in camelCase or kebab-case. */
28
+ const at = (attrs, k) => attrs[k] ?? attrs[k.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase())];
29
+ /** A wrapper that draws the inner component again (new element) whenever sig(attrs, slots) changes. */
30
+ function keyed(name, Inner, sig) {
31
+ return defineComponent({
32
+ name, inheritAttrs: false,
33
+ setup(_, { attrs, slots }) { return () => h(Inner, { ...attrs, key: sig(attrs, slots) }, slots); },
34
+ });
35
+ }
36
+ /** An <svg> from one of the library's icon strings (constant markup, never app data). */
37
+ const svgOf = (html, cls) => {
38
+ const inner = html.slice(html.indexOf('>') + 1, html.lastIndexOf('</svg>'));
39
+ return () => h('svg', { class: cls, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': 2, 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true', innerHTML: inner });
40
+ };
41
+ const binSvg = svgOf(M.binIcon, 'gk-bin');
42
+ const downloadSvg = svgOf(M.downloadIcon, 'gk-dl');
43
+ const btnSig = (a, slots) => [at(a, 'variant'), at(a, 'size'), at(a, 'block'), normalizeClass(a.class), at(a, 'type'), textOf(slots.default?.()), typeof a.icon === 'string' ? a.icon : ''].join('|');
44
+
45
+ /* ------------------------------------------------------------------ indicator */
46
+
47
+ const ACTIVE = '[aria-current]:not([aria-current="false"]), [aria-selected="true"], [aria-pressed="true"], .gk-is-active';
48
+
49
+ /**
50
+ * const pill = useIndicator(() => page.value, { radius: 99, line: false, lead, trail, cross, selector })
51
+ * <nav class="gk-menu"><span ref="pill" class="gk-menu__pill" />…items with aria-current…</nav>
52
+ * Same as indicator(pill, active) + trackIndicator(): when `active` (a ref or getter) changes, the pill stretches
53
+ * to the element in its parent that matches `selector` (default: aria-current / aria-selected / aria-pressed / .gk-is-active).
54
+ * options: an object, a ref or a getter. Returns the template ref to put on the pill.
55
+ */
56
+ export function useIndicator(active, options) {
57
+ const pill = shallowRef(null);
58
+ const opts = {};
59
+ const read = () => { const o = toValue(options) || {}; const { radius, line, lead, trail, cross } = o; Object.assign(opts, defined({ radius, line, lead, trail, cross })); return o; };
60
+ const node = () => nodeOf(pill);
61
+ const target = () => node()?.parentElement?.querySelector(read().selector || ACTIVE) ?? null;
62
+ let stopTrack = null;
63
+ onMounted(() => {
64
+ let first = true;
65
+ watch([() => toValue(active), () => read().radius, () => read().line, () => read().selector], () => {
66
+ const p = node(); if (!p) return;
67
+ M.indicator(p, target(), { ...opts, animate: !first });
68
+ first = false;
69
+ }, { immediate: true, flush: 'post' });
70
+ const p = node();
71
+ if (p) stopTrack = M.trackIndicator(p, target, opts);
72
+ });
73
+ onBeforeUnmount(() => {
74
+ stopTrack?.(); stopTrack = null;
75
+ const p = node(); if (p) { M.g.killTweensOf(p); if (p.__st) M.g.killTweensOf(p.__st); }
76
+ });
77
+ return pill;
78
+ }
79
+
80
+ const PILL = { position: 'absolute', inset: 0, pointerEvents: 'none', opacity: 0, zIndex: -1 };
81
+ const BOX = { position: 'relative', isolation: 'isolate' };
82
+ /**
83
+ * <Indicator as="nav" :active="page" class="gk-menu" pill-class="gk-menu__pill" :radius="99">…buttons with aria-current…</Indicator>
84
+ * A box with a stretchy pill (or underline with line) that follows the active child.
85
+ */
86
+ export const Indicator = defineComponent({
87
+ name: 'Indicator',
88
+ props: {
89
+ as: { type: String, default: 'div' }, active: ANY, selector: String, radius: { type: Number, default: 13 }, line: { type: Boolean, default: false },
90
+ ...anyProps('lead', 'trail', 'cross', 'pillStyle'), pillClass: ANY,
91
+ },
92
+ setup(props, { slots }) {
93
+ const pill = useIndicator(() => props.active, () => ({ selector: props.selector, radius: props.radius, line: props.line, lead: props.lead, trail: props.trail, cross: props.cross }));
94
+ // the same style object on every render, so Vue does not write opacity: 0 back over the visible pill
95
+ const pillStyle = computed(() => normalizeStyle([props.pillClass ? PILL : { ...PILL, background: 'var(--gk-accent)' }, props.pillStyle]));
96
+ // isolation + z-index -1: the pill sits on the box's background but under the items, with no CSS needed
97
+ return () => h(props.as, { style: BOX }, [
98
+ h('span', { ref: pill, class: ['gk-indicator__pill', props.pillClass], 'aria-hidden': 'true', style: pillStyle.value }),
99
+ slots.default?.(),
100
+ ]);
101
+ },
102
+ });
103
+
104
+ /* ------------------------------------------------------------------ page swap */
105
+
106
+ /**
107
+ * <PageSwap :swap-key="route.path" :dir="forward ? 1 : -1"><RouterView /></PageSwap>
108
+ * Same as swap(view, dir, render): when swap-key changes, the old page (still drawn) steps back and fades, then
109
+ * the new slot content slides in from the side you are heading to. Blocks matching `leave` drop out, `head` lifts away.
110
+ * @swap(view) runs once the new page is in.
111
+ */
112
+ export const PageSwap = defineComponent({
113
+ name: 'PageSwap',
114
+ props: { as: { type: String, default: 'div' }, swapKey: ANY, dir: { type: Number, default: 1 }, ...anyProps('leave', 'head', 'timing'), onSwap: Function },
115
+ setup(props, { slots }) {
116
+ const view = ref(null);
117
+ const shown = ref(props.swapKey);
118
+ let kept = null;
119
+ onMounted(() => {
120
+ watch(() => props.swapKey, () => {
121
+ if (shown.value === props.swapKey || !view.value) return;
122
+ const T = M.swapTiming, before = { ...T }, timing = props.timing;
123
+ if (timing) Object.assign(T, timing);
124
+ // draw the new page (the latest key), then tell the app once it is in the DOM
125
+ const render = () => { shown.value = props.swapKey; nextTick(() => { if (view.value) props.onSwap?.(view.value); }); };
126
+ const p = M.swap(view.value, props.dir < 0 ? -1 : 1, render, defined({ leave: props.leave, head: props.head }));
127
+ if (timing) p.then(() => Object.assign(T, before));
128
+ }, { flush: 'post' });
129
+ });
130
+ onBeforeUnmount(() => { const v = view.value; if (v) { killAll(v); v.__swapping = null; v.__pending = null; } });
131
+ // until the old page has left, keep drawing it as it was; the new page gets new elements (keyed by its swap-key)
132
+ return () => {
133
+ if (shown.value === props.swapKey || kept == null) kept = { key: shown.value, nodes: slots.default?.() ?? [] };
134
+ return h(props.as, { ref: view }, [h(Fragment, { key: kept.key }, [...kept.nodes])]);
135
+ };
136
+ },
137
+ });
138
+
139
+ /* ------------------------------------------------------------------ feedback */
140
+
141
+ /**
142
+ * const fb = useFeedback(); <form :ref="fb.ref" @submit.prevent="bad && fb.shake()">
143
+ * (or const { ref: form, shake } = useFeedback() with <form ref="form">)
144
+ * fb.pop(), fb.shake(), fb.wiggle(), fb.flash(), fb.tick(up): run on fb.ref, or on what you pass
145
+ * (an element, a template ref or an event: @click="fb.pop" pops the clicked button). Cleaned up on unmount.
146
+ */
147
+ export function useFeedback() {
148
+ const el = shallowRef(null), used = new Set();
149
+ const on = (fn) => (x, ...a) => { const n = elOf(x, nodeOf(el)); if (!n) return undefined; used.add(n); return fn(n, ...a); };
150
+ onBeforeUnmount(() => {
151
+ for (const n of used) { M.g.killTweensOf([n, n.querySelector?.('svg')].filter(Boolean)); n.classList?.remove('gk-is-flash'); }
152
+ used.clear();
153
+ });
154
+ return {
155
+ ref: el,
156
+ pop: on((n) => M.pop(n)),
157
+ shake: on((n) => M.shake(n)),
158
+ wiggle: on((n) => M.wiggle(n)),
159
+ flash: on((n) => { M.flash(n); }),
160
+ tick: (up, x) => { const n = elOf(x, nodeOf(el)); if (n) M.tick(n, !!up); },
161
+ };
162
+ }
163
+
164
+ /** const total = useFlash(() => cart.total); <b ref="total">{{ cart.total }}</b> — bounces and lights up each time the value changes. */
165
+ export function useFlash(value) {
166
+ const el = shallowRef(null);
167
+ watch(() => toValue(value), () => { const n = nodeOf(el); if (n) M.flash(n); }, { flush: 'post' });
168
+ onBeforeUnmount(() => { const n = nodeOf(el); if (n) { M.g.killTweensOf(n); n.classList.remove('gk-is-flash'); } });
169
+ return el;
170
+ }
171
+
172
+ /** const qtyEl = useTick(qty); <b ref="qtyEl">{{ qty }}</b> — tints green when the number goes up, red when it goes down. */
173
+ export function useTick(value) {
174
+ const el = shallowRef(null);
175
+ watch(() => toValue(value), (v, p) => {
176
+ if (p === v || typeof p !== 'number' || typeof v !== 'number') return;
177
+ const n = nodeOf(el); if (n) M.tick(n, v > p);
178
+ }, { flush: 'post' });
179
+ return el;
180
+ }
181
+
182
+ /* ------------------------------------------------------------------ confetti */
183
+
184
+ /** confetti(origin, options) from @gecko-ui-kit/motion (a promise with stop(); confetti.clear() stops all). */
185
+ export const confetti = M.confetti;
186
+
187
+ /**
188
+ * const fire = useConfetti({ count: 150 }); <Button @click="fire">Pay</Button>
189
+ * fire(origin?, options?) shoots from an element, a template ref, an event's button or { x, y } (default: the
190
+ * screen centre). options: an object, a ref or a getter. Bursts still flying are stopped on unmount.
191
+ */
192
+ export function useConfetti(options) {
193
+ const live = new Set();
194
+ onBeforeUnmount(() => { for (const p of live) p.stop(); live.clear(); });
195
+ return (origin, more) => {
196
+ const o = origin && typeof origin.x === 'number' && typeof origin.y === 'number' && !origin.nodeType && !origin.currentTarget ? origin
197
+ : typeof origin === 'string' ? origin : elOf(origin, undefined);
198
+ const p = M.confetti(o, { ...defined(toValue(options) || {}), ...more });
199
+ live.add(p);
200
+ p.then(() => live.delete(p));
201
+ return p;
202
+ };
203
+ }
204
+
205
+ const CONFETTI = ['count', 'spread', 'angle', 'velocity', 'colors', 'shapes', 'gravity', 'duration', 'zIndex', 'reduced'];
206
+ /**
207
+ * <ConfettiButton variant="primary" icon="sparkle" :count="150" @click="…">Celebrate</ConfettiButton>
208
+ * A Button that bursts confetti from itself when clicked (call event.preventDefault() in @click to skip it).
209
+ * @done when the last piece has landed.
210
+ */
211
+ export const ConfettiButton = defineComponent({
212
+ name: 'ConfettiButton',
213
+ props: { ...anyProps(...CONFETTI), onDone: Function, onClick: Function },
214
+ setup(props, { slots }) {
215
+ const fire = useConfetti(() => Object.fromEntries(CONFETTI.map((k) => [k, props[k]])));
216
+ return () => h(Button, {
217
+ onClick: (e) => {
218
+ props.onClick?.(e); if (e.defaultPrevented) return;
219
+ const b = e.currentTarget; M.pop(b.querySelector('svg') ?? b);
220
+ fire(b).then(() => props.onDone?.());
221
+ },
222
+ }, slots);
223
+ },
224
+ });
225
+
226
+ /* ------------------------------------------------------------------ sortable */
227
+
228
+ const groups = new Map(); // group name → Map(zone id → live instance)
229
+ const pendings = new Map(); // group name → { key, rects, back, seen }
230
+ const sel = (v) => (typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(v) : String(v).replace(/["\\]/g, '\\$&'));
231
+ const arrayMove = (a, from, to) => { const b = a.slice(); const [x] = b.splice(from, 1); b.splice(to, 0, x); return b; };
232
+ const keyOfItem = (x) => x?.id ?? x;
233
+
234
+ /**
235
+ * <Sortable v-model="tasks" :get-key="(t) => t.id" @reorder="save">
236
+ * <template #item="{ item }"><TaskCard :task="item" /></template>
237
+ * </Sortable>
238
+ * A list you can reorder by dragging (mouse at once, touch after a long press), using drag() and landFrom():
239
+ * the card lifts and tilts in your hand, the others slide aside, and it lands with a squash.
240
+ * Vue stays in charge of the order: v-model gets the new list, @reorder(nextItems, { item, from, to, fromList, toList }).
241
+ * Lists with the same `group` (a kanban board's lanes) can pass items to each other; the default slot is drawn
242
+ * before the items, inside the drop zone (a lane title). Without v-model it keeps its own order (default-value).
243
+ */
244
+ export const Sortable = defineComponent({
245
+ name: 'Sortable',
246
+ props: {
247
+ ...modelProps(), getKey: Function, onReorder: Function, onItemClick: Function, group: String,
248
+ as: { type: String, default: 'div' }, itemAs: String, itemClass: ANY,
249
+ lift: ANY, squash: { type: Boolean, default: true }, rotate: { type: Number, default: 3 }, handle: String, onPointerdown: Function,
250
+ },
251
+ setup(props, { slots }) {
252
+ const [value, setList] = useModel(props, { event: 'onReorder', initial: [] });
253
+ const list = computed(() => value.value ?? []);
254
+ const zid = useId();
255
+ const g = computed(() => props.group ?? zid);
256
+ const zone = ref(null);
257
+ const getKey = (x) => (props.getKey ?? keyOfItem)(x);
258
+ const live = {
259
+ get list() { return list.value; }, setList, getKey,
260
+ get onItemClick() { return props.onItemClick; }, get lift() { return props.lift; }, get squash() { return props.squash; },
261
+ get rotate() { return props.rotate; }, get handle() { return props.handle; },
262
+ };
263
+ const join = (name) => { if (!groups.has(name)) groups.set(name, new Map()); groups.get(name).set(zid, { zone: () => zone.value, live }); };
264
+ const leave = (name) => { const m = groups.get(name); if (!m) return; m.delete(zid); if (!m.size) groups.delete(name); };
265
+ onMounted(() => {
266
+ join(g.value);
267
+ watch(g, (next, prev) => { leave(prev); join(next); });
268
+ });
269
+
270
+ // after Vue has drawn the new order: land the dropped card, slide the others to their new places
271
+ onUpdated(() => {
272
+ const p = pendings.get(g.value); if (!p || !zone.value) return;
273
+ for (const el of zone.value.querySelectorAll(':scope > [data-sort-item]')) {
274
+ const k = el.getAttribute('data-sort-item'), r = p.rects.get(k);
275
+ if (!r) continue;
276
+ p.rects.delete(k);
277
+ if (k === p.key) { p.seen = true; M.g.set(el, { clearProps: 'transform' }); M.landFrom(el, r, { squash: props.squash, rotate: props.rotate }); continue; }
278
+ const n = el.getBoundingClientRect(), dx = r.left - n.left, dy = r.top - n.top;
279
+ if (!M.RM() && (Math.abs(dx) > 1 || Math.abs(dy) > 1)) M.g.fromTo(el, { x: dx, y: dy }, { x: 0, y: 0, duration: 0.35, ease: 'power3.out', clearProps: 'transform' });
280
+ }
281
+ });
282
+ onBeforeUnmount(() => { leave(g.value); if (zone.value) killAll(zone.value); });
283
+
284
+ const onPointerdown = (e) => {
285
+ props.onPointerdown?.(e);
286
+ if (e.defaultPrevented) return;
287
+ const el = e.target.closest('[data-sort-item]');
288
+ if (!el || el.parentElement !== zone.value || e.target.closest('button, input, textarea, select, a, [data-no-drag]')) return;
289
+ if (live.handle && !e.target.closest(live.handle)) return;
290
+ const key = el.getAttribute('data-sort-item');
291
+ const gr = g.value, scope = `[data-sort-group="${sel(gr)}"]`;
292
+ const drag = M.drag(el, e, {
293
+ ...(live.lift ? { lift: live.lift } : {}),
294
+ targets: `${scope} > [data-sort-item], ${scope}`,
295
+ onClick: () => { const it = live.list.find((x) => String(getKey(x)) === key); if (it !== undefined) props.onItemClick?.(it); },
296
+ onDrop: (t) => {
297
+ const srcList = live.list;
298
+ const from = srcList.findIndex((x) => String(getKey(x)) === key); if (from < 0) return false;
299
+ const zoneEl = t.matches('[data-sort-zone]') ? t : t.parentElement;
300
+ const dst = groups.get(gr)?.get(zoneEl?.getAttribute('data-sort-zone'));
301
+ if (!dst) return false;
302
+ const onItem = t !== zoneEl, tk = onItem ? t.getAttribute('data-sort-item') : null;
303
+ if (tk === key) return false;
304
+ // remember where every card in the group is now, so each can glide from there after Vue re-draws
305
+ const rects = new Map();
306
+ for (const it of document.querySelectorAll(`${scope} > [data-sort-item]`)) rects.set(it.getAttribute('data-sort-item'), it.getBoundingClientRect());
307
+ const item = srcList[from];
308
+ if (dst.live === live) {
309
+ if (!onItem) return false; // dropped on its own list's empty space: snap back
310
+ const to = srcList.findIndex((x) => String(getKey(x)) === tk);
311
+ pendings.set(gr, { key, rects, back: () => drag?.back(), seen: false });
312
+ setList(arrayMove(srcList, from, to), { item, from, to, fromList: srcList, toList: srcList });
313
+ } else {
314
+ const D = dst.live, dl = D.list;
315
+ const to = onItem ? Math.max(0, dl.findIndex((x) => String(D.getKey(x)) === tk)) : dl.length;
316
+ const nextSrc = srcList.filter((_, i) => i !== from), nextDst = dl.slice(); nextDst.splice(to, 0, item);
317
+ pendings.set(gr, { key, rects, back: () => drag?.back(), seen: false });
318
+ setList(nextSrc, { item, from, to: -1, fromList: srcList, toList: nextDst });
319
+ D.setList(nextDst, { item, from: -1, to, fromList: srcList, toList: nextDst });
320
+ }
321
+ // nobody took the new order (a v-model list that did not change): fly home
322
+ requestAnimationFrame(() => requestAnimationFrame(() => {
323
+ const p = pendings.get(gr); if (!p || p.key !== key) return;
324
+ pendings.delete(gr);
325
+ if (!p.seen && el.isConnected) p.back();
326
+ }));
327
+ return true;
328
+ },
329
+ });
330
+ };
331
+
332
+ return () => {
333
+ const tag = props.itemAs ?? (props.as === 'ul' || props.as === 'ol' ? 'li' : 'div');
334
+ return h(props.as, { ref: zone, 'data-sort-zone': zid, 'data-sort-group': g.value, onPointerdown }, [
335
+ ...(slots.default?.() ?? []),
336
+ ...list.value.map((it, i) => {
337
+ const k = String(getKey(it));
338
+ return h(tag, { key: k, 'data-sort-item': k, 'data-drag': '', class: props.itemClass }, slots.item ? slots.item({ item: it, index: i }) : k);
339
+ }),
340
+ ]);
341
+ };
342
+ },
343
+ });
344
+
345
+ /* ------------------------------------------------------------------ theme */
346
+
347
+ /**
348
+ * const [theme, setTheme] = useTheme({ storageKey: 'gecko:theme', duration: 450 })
349
+ * The page theme ('light' | 'dark', the <html data-theme> attribute) as a read-only ref. setTheme('dark', fromElementOrEvent)
350
+ * switches with the circular reveal growing from that element and saves the choice. It is 'light' on the server
351
+ * and during hydration, and reads the real theme (and the saved one) once mounted, so nothing mismatches.
352
+ */
353
+ export function useTheme(options) {
354
+ const t = ref('light');
355
+ const o = () => ({ storageKey: 'gecko:theme', ...defined(toValue(options) || {}) });
356
+ const sync = () => { t.value = M.getTheme(); };
357
+ let mo = null;
358
+ onMounted(() => {
359
+ const root = document.documentElement, key = o().storageKey;
360
+ if (!root.dataset.theme && key) M.restoreTheme(key);
361
+ sync();
362
+ addEventListener('gk:themechange', sync);
363
+ mo = new MutationObserver(sync); mo.observe(root, { attributes: true, attributeFilter: ['data-theme'] });
364
+ });
365
+ onBeforeUnmount(() => { removeEventListener('gk:themechange', sync); mo?.disconnect(); mo = null; });
366
+ const set = (next, from) => {
367
+ const v = typeof next === 'function' ? next(M.getTheme()) : next;
368
+ const { storageKey, duration, easing } = o();
369
+ return M.theme(v === 'dark' ? 'dark' : 'light', elOf(from, undefined), defined({ storageKey, duration, easing }));
370
+ };
371
+ return [readonly(t), set];
372
+ }
373
+
374
+ /**
375
+ * <ThemeToggle @change="(t) => save(t)" /> — a round button (moon / sun) that switches light ↔ dark with the
376
+ * circular reveal from the button. Same as toggleTheme(button, { storageKey, duration, easing }).
377
+ */
378
+ export const ThemeToggle = defineComponent({
379
+ name: 'ThemeToggle',
380
+ props: { storageKey: String, duration: Number, easing: String, label: { type: String, default: 'Switch theme' }, size: String, onChange: Function, onClick: Function },
381
+ setup(props) {
382
+ const [theme, setTheme] = useTheme(() => ({ storageKey: props.storageKey, duration: props.duration, easing: props.easing }));
383
+ return () => {
384
+ const dark = theme.value === 'dark';
385
+ return h('button', {
386
+ type: 'button', 'aria-label': props.label, class: ['gk-iconbtn', props.size && 'gk-iconbtn--' + props.size],
387
+ onClick: (e) => {
388
+ props.onClick?.(e); if (e.defaultPrevented) return;
389
+ const next = dark ? 'light' : 'dark', b = e.currentTarget;
390
+ M.pop(b); setTheme(next, b); props.onChange?.(next);
391
+ },
392
+ }, [h(Icon, { name: dark ? 'sun' : 'moon', class: dark ? 'gk-i-sun' : 'gk-i-moon' })]);
393
+ };
394
+ },
395
+ });
396
+
397
+ /* ------------------------------------------------------------------ send / delete */
398
+
399
+ /* Shared life of a one-shot button motion (send, delete): play on click (uncontrolled) or follow a boolean
400
+ prop (controlled); come back after `back` seconds when uncontrolled; stop everything on unmount. */
401
+ function useOneShot(node, { on, controlled, back, play, reset }) {
402
+ let tl = null, timer = 0, prev = false;
403
+ const undo = () => { clearTimeout(timer); tl?.kill(); tl = reset(); };
404
+ const go = () => {
405
+ clearTimeout(timer);
406
+ tl = play(() => { if (!controlled() && back() > 0) timer = setTimeout(undo, back() * 1000); });
407
+ };
408
+ onMounted(() => {
409
+ watch([() => !!on(), controlled], ([v, c]) => {
410
+ if (!c) return;
411
+ if (v && !prev) go(); else if (!v && prev) undo();
412
+ prev = v;
413
+ }, { immediate: true, flush: 'post' });
414
+ });
415
+ onBeforeUnmount(() => { clearTimeout(timer); tl?.kill(); tl = null; killAll(node()); });
416
+ return go;
417
+ }
418
+ const BTN_LOOK = { variant: String, size: String, block: B };
419
+
420
+ const SendInner = defineComponent({
421
+ name: 'SendButtonInner',
422
+ props: { sent: B, done: { type: String, default: 'Sent' }, path: { type: String, default: 'up' }, trail: { type: Boolean, default: true }, back: { type: Number, default: 2.4 }, duration: Number, onDone: Function, icon: { type: ANY.type, default: 'send' }, onClick: Function },
423
+ setup(props, { slots }) {
424
+ const el = shallowRef(null), node = () => nodeOf(el);
425
+ const controlled = () => props.sent !== undefined;
426
+ const go = useOneShot(node, {
427
+ on: () => props.sent, controlled, back: () => props.back,
428
+ play: (after) => {
429
+ const b = node(); if (!b || b.__flying) return null;
430
+ return M.sendOff(b, defined({ done: props.done, path: props.path, trail: props.trail, duration: props.duration, back: 0, onDone: (x) => { props.onDone?.(x); after(); } }));
431
+ },
432
+ reset: () => (node()?.__flying ? M.sendOff.reset(node()) : null),
433
+ });
434
+ return () => h(Button, { ref: el, icon: props.icon, onClick: (e) => { props.onClick?.(e); if (!e.defaultPrevented && !controlled()) go(); } },
435
+ { default: () => (slots.default ? slots.default() : 'Send') });
436
+ },
437
+ });
438
+ /**
439
+ * <SendButton variant="primary" @click="send">Send</SendButton> or <SendButton :sent="status === 'sent'" type="submit" />
440
+ * Same as sendOff(button, options): the plane winds back and flies off, "Sent" rolls in with a tick. Click plays it
441
+ * (unless @click calls preventDefault) and it comes back after `back` seconds; with `sent` it follows the prop instead.
442
+ */
443
+ export const SendButton = keyed('SendButton', SendInner, btnSig);
444
+
445
+ const DeleteInner = defineComponent({
446
+ name: 'DeleteButtonInner',
447
+ props: { deleted: B, done: { type: String, default: 'Deleted' }, order: { type: String, default: 'first' }, chew: { type: Boolean, default: true }, back: { type: Number, default: 2.4 }, onDone: Function, onClick: Function },
448
+ setup(props, { slots }) {
449
+ const el = shallowRef(null), node = () => nodeOf(el);
450
+ const controlled = () => props.deleted !== undefined;
451
+ const go = useOneShot(node, {
452
+ on: () => props.deleted, controlled, back: () => props.back,
453
+ play: (after) => {
454
+ const b = node(); if (!b || b.__eating) return null;
455
+ return M.binEat(b, { done: props.done, order: props.order, chew: props.chew, back: 0, onDone: (x) => { props.onDone?.(x); after(); } });
456
+ },
457
+ reset: () => (node()?.__binText ? M.binEat.reset(node()) : null),
458
+ });
459
+ return () => h(Button, { ref: el, icon: binSvg(), onClick: (e) => { props.onClick?.(e); if (!e.defaultPrevented && !controlled()) go(); } },
460
+ { default: () => textOf(slots.default?.()) || 'Delete' });
461
+ },
462
+ });
463
+ /**
464
+ * <DeleteButton variant="danger" @done="removeRow(id)">Delete</DeleteButton>
465
+ * Same as binEat(button, options): the bin opens and eats its own label letter by letter, chews, and "Deleted" rises in.
466
+ * Click plays it (unless @click calls preventDefault); with `deleted` it follows the prop instead.
467
+ */
468
+ export const DeleteButton = keyed('DeleteButton', DeleteInner, btnSig);
469
+
470
+ /* ------------------------------------------------------------------ download */
471
+
472
+ const DownloadInner = defineComponent({
473
+ name: 'DownloadButtonInner',
474
+ props: { progress: ANY, state: String, label: Function, ...anyProps('wait', 'done', 'fail', 'back', 'width') },
475
+ setup(props, { slots }) {
476
+ const el = shallowRef(null);
477
+ let api = null;
478
+ const opts = () => defined({ wait: props.wait, done: props.done, fail: props.fail, back: props.back, width: props.width });
479
+ onMounted(() => {
480
+ api = M.edgeProgress(nodeOf(el), { ...opts(), ...(props.label ? { label: (p) => (props.label ? props.label(p) : `${Math.round(p * 100)}%`) } : {}) });
481
+ watch(opts, (o) => { if (api) Object.assign(api.opts, o); }, { deep: true });
482
+ watch([() => props.state, () => props.progress], () => {
483
+ const a = api; if (!a) return;
484
+ const progress = props.progress;
485
+ const want = props.state ?? (progress === undefined ? 'idle' : 'loading');
486
+ if (want === 'idle') { if (a.state !== 'idle') a.reset(); }
487
+ else if (want === 'loading') { if (a.state === 'done') a.reset(true); a.set(progress ?? null); }
488
+ else if (want === 'done') a.done();
489
+ else if (want === 'failed') { if (a.state === 'idle' || a.state === 'done') { a.reset(true); a.set(progress ?? 0); } a.fail(); }
490
+ }, { immediate: true, flush: 'post' });
491
+ });
492
+ onBeforeUnmount(() => { api?.destroy?.(); api = null; });
493
+ return () => h(Button, { ref: el, icon: downloadSvg() }, { default: () => textOf(slots.default?.()) || 'Download' });
494
+ },
495
+ });
496
+ /**
497
+ * <DownloadButton :progress="p" :state="failed ? 'failed' : p === 1 ? 'done' : undefined" @click="start">Download</DownloadButton>
498
+ * Same as edgeProgress(button, options): the button's own outline fills as `progress` (0–1) grows; null = size unknown
499
+ * (a segment chases round). state 'done' glows, fills and ticks; 'failed' turns red and shakes; 'idle' puts it back.
500
+ */
501
+ export const DownloadButton = keyed('DownloadButton', DownloadInner, btnSig);
502
+
503
+ /* ------------------------------------------------------------------ hold to confirm */
504
+
505
+ const HoldInner = defineComponent({
506
+ name: 'HoldButtonInner',
507
+ props: {
508
+ confirmed: B, ...anyProps('duration', 'hint', 'done', 'back'), haptic: B, look: { type: String, default: 'fill' }, tone: { type: String, default: 'bad' },
509
+ onConfirm: Function, onCancel: Function, icon: { type: ANY.type, default: 'trash' }, ...BTN_LOOK,
510
+ },
511
+ setup(props, { slots }) {
512
+ const el = shallowRef(null), node = () => nodeOf(el);
513
+ let api = null, prev = false;
514
+ const opts = () => defined({ duration: props.duration, hint: props.hint, done: props.done, back: props.back, haptic: props.haptic });
515
+ onMounted(() => {
516
+ api = M.holdConfirm(node(), { ...opts(), look: props.look, tone: props.tone, onConfirm: (b, x) => props.onConfirm?.(b, x), onCancel: (b, x, p) => props.onCancel?.(b, x, p) });
517
+ watch(opts, (o) => { if (api) Object.assign(api.opts, o); }, { deep: true });
518
+ watch(() => props.confirmed, (c) => {
519
+ if (c === undefined || !api) return;
520
+ if (c && api.state !== 'done') api.confirm();
521
+ else if (!c && prev && api.state === 'done') api.reset();
522
+ prev = !!c;
523
+ }, { immediate: true, flush: 'post' });
524
+ });
525
+ onBeforeUnmount(() => {
526
+ const a = api; api = null; if (!a) return;
527
+ if (a.state === 'done') a.reset(); // put the icon and label back
528
+ killAll(a.el); M.g.set(a.el, { clearProps: 'width,transform' }); a.destroy();
529
+ });
530
+ return () => {
531
+ const text = textOf(slots.default?.());
532
+ if (props.look === 'ring') {
533
+ return h('button', { ref: el, type: 'button', 'aria-label': text, class: ['gk-iconbtn', props.size && 'gk-iconbtn--' + props.size] }, [iconNode(props.icon)]);
534
+ }
535
+ return h(Button, { ref: el, variant: props.variant, size: props.size, block: props.block, icon: props.icon }, { default: () => text });
536
+ };
537
+ },
538
+ });
539
+ /**
540
+ * <HoldButton tone="bad" hint="Hold to delete" done="Deleted" @confirm="deleteBike(id)">Delete bike</HoldButton>
541
+ * Same as holdConfirm(button, options): press and hold, colour floods the button (look="ring": a circle fills round a
542
+ * round icon button) and only a full hold calls @confirm. Letting go early drains it, shows the hint and calls @cancel.
543
+ */
544
+ export const HoldButton = keyed('HoldButton', HoldInner, (a, s) => [btnSig(a, s), at(a, 'look'), at(a, 'tone')].join('|'));
545
+
546
+ /* ------------------------------------------------------------------ expanding search */
547
+
548
+ const GLASS_IN = '<g class="gk-xs__glass"><circle cx="10.5" cy="10.5" r="6"/><path d="M15 15l4.5 4.5"/></g>';
549
+ const CROSS_IN = '<path class="gk-xs__x" d="M7 7l10 10" pathLength="1" stroke-dasharray="1" stroke-dashoffset="1"/><path class="gk-xs__x" d="M17 7 7 17" pathLength="1" stroke-dasharray="1" stroke-dashoffset="1"/>';
550
+ const svg2 = (cls, html) => h('svg', { class: cls, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': 2, 'stroke-linecap': 'round', 'aria-hidden': 'true', innerHTML: html });
551
+
552
+ const SearchInner = defineComponent({
553
+ name: 'ExpandSearchInner',
554
+ props: {
555
+ placeholder: { type: String, default: 'Search…' }, label: { type: String, default: 'Search' }, closeLabel: { type: String, default: 'Close search' },
556
+ name: { type: String, default: 'q' }, look: { type: String, default: 'outline' }, size: { type: String, default: 'md' },
557
+ width: ANY, typing: B, autoClose: B, shortcut: String,
558
+ ...modelProps(), onChange: Function, onSearch: Function,
559
+ open: B, defaultOpen: B, 'onUpdate:open': Function, onOpen: Function, onClose: Function,
560
+ },
561
+ setup(props) {
562
+ const box = ref(null), id = useId();
563
+ const [text, setText] = useModel(props, { initial: '' });
564
+ const start = props.modelValue ?? props.defaultValue; // Vue draws the first text only; the field owns it after that
565
+ let api = null;
566
+ const opts = () => defined({ width: props.width, typing: props.typing, autoClose: props.autoClose, placeholder: props.placeholder, key: props.shortcut });
567
+ onMounted(() => {
568
+ api = M.expandSearch(box.value, {
569
+ ...opts(),
570
+ onInput: (v) => { if (v !== text.value) setText(v); },
571
+ onSearch: (v) => props.onSearch?.(v),
572
+ onOpen: () => { if (props.open !== true) props['onUpdate:open']?.(true); props.onOpen?.(); },
573
+ onClose: () => { if (props.open !== false) props['onUpdate:open']?.(false); props.onClose?.(); },
574
+ });
575
+ if (props.open ?? props.defaultOpen) api.open();
576
+ watch(opts, (o) => { if (api) Object.assign(api.opts, { key: '', ...o }); }, { deep: true });
577
+ watch(() => props.modelValue, (v) => { const a = api; if (a && v !== undefined && a.input.value !== v) a.input.value = v; }, { flush: 'post' });
578
+ watch(() => props.open, (o) => { const a = api; if (!a || o === undefined || a.isOpen === o) return; o ? a.open() : a.close(); }, { flush: 'post' });
579
+ });
580
+ onBeforeUnmount(() => {
581
+ const a = api; api = null; if (!a) return;
582
+ killAll(a.el); a.destroy();
583
+ // leave the markup closed, as Vue drew it
584
+ a.el.classList.remove('gk-is-open', 'gk-is-closing'); M.g.set([a.el, a.input], { clearProps: 'width,transform,opacity' });
585
+ a.el.querySelector('.gk-xs__btn')?.setAttribute('aria-expanded', 'false');
586
+ a.input.tabIndex = -1; a.input.placeholder = ''; const c = a.el.querySelector('.gk-xs__close'); if (c) c.tabIndex = -1;
587
+ a.el.querySelectorAll('.gk-xs__x').forEach((x) => x.setAttribute('stroke-dashoffset', '1'));
588
+ });
589
+ return () => h('form', {
590
+ ref: box, role: 'search', 'data-placeholder': props.placeholder,
591
+ class: ['gk-xs', props.look === 'quiet' && 'gk-xs--quiet', props.size === 'sm' && 'gk-xs--sm'],
592
+ }, [
593
+ h('button', { type: 'button', class: 'gk-xs__btn', 'aria-label': props.label, 'aria-expanded': 'false', 'aria-controls': id }, [svg2('gk-xs__ic', GLASS_IN)]),
594
+ h('input', { class: 'gk-xs__input', id, type: 'search', name: props.name, 'aria-label': props.label, autocomplete: 'off', spellcheck: 'false', enterkeyhint: 'search', tabindex: '-1', value: start }),
595
+ h('button', { type: 'button', class: 'gk-xs__close', 'aria-label': props.closeLabel, tabindex: '-1' }, [svg2(undefined, CROSS_IN)]),
596
+ ]);
597
+ },
598
+ });
599
+ /**
600
+ * <ExpandSearch v-model="query" placeholder="Search bikes…" :width="280" shortcut="/" @search="go" />
601
+ * Same as expandSearch(searchField(…)): a round magnifier that stretches into a field, types its hint in and draws a ×.
602
+ * Escape clears, then closes. v-model (or default-value) + @change(text) for the text; v-model:open (or default-open)
603
+ * + @open / @close for the open state.
604
+ */
605
+ export const ExpandSearch = keyed('ExpandSearch', SearchInner, (a) => [at(a, 'look'), at(a, 'size'), at(a, 'name'), at(a, 'label'), at(a, 'closeLabel'), normalizeClass(a.class)].join('|'));
606
+
607
+ /* ------------------------------------------------------------------ liquid tab bar */
608
+
609
+ const LiquidInner = defineComponent({
610
+ name: 'LiquidTabsInner',
611
+ props: {
612
+ items: { type: Array, default: () => [] }, ...modelProps(), onChange: Function, mode: String, splash: B,
613
+ label: { type: String, default: 'Main' }, labels: { type: Boolean, default: true }, goo: { type: Boolean, default: true }, linkAs: ANY,
614
+ },
615
+ setup(props, { slots }) {
616
+ const [v, set] = useModel(props, { initial: 0 });
617
+ const first = v.value; // Vue draws the starting tab only; the vanilla code moves it after that
618
+ const nav = ref(null);
619
+ const fid = 'lq-goo-' + useId().replace(/[^\w-]/g, '_');
620
+ const opts = () => defined({ mode: props.mode, splash: props.splash });
621
+ let api = null;
622
+ onMounted(() => {
623
+ api = M.liquidTabs(nav.value, { ...opts(), onChange: (i, tab) => set(i, tab) });
624
+ watch(opts, (o) => { if (api) Object.assign(api.opts, o); }, { deep: true });
625
+ watch(v, (x) => { const a = api; if (a && typeof x === 'number' && a.index !== x) a.select(x); }, { flush: 'post' });
626
+ });
627
+ onBeforeUnmount(() => { const a = api; api = null; if (a) { killAll(a.el); a.destroy(); } });
628
+ return () => h('nav', {
629
+ ref: nav, 'aria-label': props.label,
630
+ class: ['gk-lq', !props.labels && 'gk-lq--icons', !props.goo && 'gk-lq--plain'], style: { '--gk-lq-goo': `url(#${fid})` },
631
+ }, [
632
+ h('svg', { class: 'gk-lq__defs', width: 0, height: 0, 'aria-hidden': 'true', focusable: 'false' }, [
633
+ h('filter', { id: fid, x: '-10%', y: '-90%', width: '120%', height: '280%', 'color-interpolation-filters': 'sRGB' }, [
634
+ h('feGaussianBlur', { in: 'SourceGraphic', stdDeviation: 7 }),
635
+ h('feColorMatrix', { values: '1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 24 -11' }),
636
+ ]),
637
+ ]),
638
+ h('span', { class: 'gk-lq__goo', 'aria-hidden': 'true' }, [h('span', { class: 'gk-lq__body' }), h('span', { class: 'gk-lq__drop' }), h('span', { class: 'gk-lq__drop' }), h('span', { class: 'gk-lq__bub' })]),
639
+ h('span', { class: 'gk-lq__dot', 'aria-hidden': 'true' }),
640
+ ...props.items.map((it, i) => h(it.href ? (props.linkAs || 'a') : 'button', {
641
+ key: i, class: ['gk-lq__tab', i === first && 'gk-is-on'],
642
+ ...(it.href ? (props.linkAs ? { to: it.href } : { href: it.href }) : { type: 'button' }), 'aria-current': i === first ? 'page' : undefined,
643
+ }, [h('span', { class: 'gk-lq__ic', 'aria-hidden': 'true' }, [iconNode(it.icon)]), h('span', { class: 'gk-lq__lb' }, slots.label ? slots.label({ item: it, index: i }) : it.label)])),
644
+ ]);
645
+ },
646
+ });
647
+ /**
648
+ * <LiquidTabs v-model="tab" :items="[{ label: 'Home', icon: 'home' }, { label: 'Bikes', icon: 'box' }]" mode="dip" />
649
+ * Same as liquidTabs(liquidBar(items, …)): the bar and a bubble over the active tab move like one liquid.
650
+ * v-model is the active index (or default-value); @change(index, tabElement). Items with href are links
651
+ * (:link-as="NuxtLink" gets `to`). #label="{ item, index }" draws a label yourself.
652
+ */
653
+ export const LiquidTabs = keyed('LiquidTabs', LiquidInner, (a) => [at(a, 'labels') !== false, at(a, 'goo') !== false, (a.items || []).map((it) => [textOf(it.label), typeof it.icon === 'string' ? it.icon : '', it.href ?? ''].join('~')).join('/')].join('|'));
654
+
655
+ /* ------------------------------------------------------------------ burger */
656
+
657
+ const BURGER_WORDS = { open: 'Open menu', close: 'Close menu' };
658
+ /**
659
+ * <Burger v-model:open="menuOpen" controls="main-menu" />
660
+ * Same as burger(button, open): three lines that turn into an ✕ and back. Vue owns `open` (v-model:open, or
661
+ * default-open); a click or Escape asks for the other state (@toggle(next, button)). words: { open, close }
662
+ * labels the button. icon-class styles the lines.
663
+ */
664
+ export const Burger = defineComponent({
665
+ name: 'Burger',
666
+ props: {
667
+ open: B, defaultOpen: B, 'onUpdate:open': Function, onToggle: Function, words: ANY, duration: { type: Number, default: 0.45 },
668
+ controls: String, escape: { type: Boolean, default: true }, size: String, iconClass: ANY, onClick: Function,
669
+ },
670
+ setup(props) {
671
+ const [on, set] = useModel(props, { prop: 'open', def: 'defaultOpen', event: 'onToggle', initial: false });
672
+ const el = ref(null);
673
+ onMounted(() => {
674
+ let first = true;
675
+ watch(() => !!on.value, (v) => { M.burger(el.value, v, { duration: first ? 0 : props.duration }); first = false; }, { immediate: true, flush: 'post' });
676
+ watch(() => props.escape, (esc, _, onCleanup) => {
677
+ if (!esc) return;
678
+ const key = (e) => {
679
+ if (e.key !== 'Escape' || !on.value || e.defaultPrevented) return;
680
+ set(false, el.value); el.value?.focus();
681
+ };
682
+ document.addEventListener('keydown', key);
683
+ onCleanup(() => document.removeEventListener('keydown', key));
684
+ }, { immediate: true });
685
+ });
686
+ onBeforeUnmount(() => {
687
+ const b = el.value; if (!b) return;
688
+ b.__burger?.tl?.kill(); M.g.set(b.querySelectorAll('.gk-burger > i'), { clearProps: 'all' }); delete b.__burger;
689
+ });
690
+ return () => {
691
+ const w = { ...BURGER_WORDS, ...props.words }, o = !!on.value;
692
+ return h('button', {
693
+ ref: el, type: 'button', 'aria-expanded': String(o), 'aria-label': o ? w.close : w.open, 'aria-controls': props.controls || undefined,
694
+ class: ['gk-iconbtn', props.size && 'gk-iconbtn--' + props.size, o && 'gk-is-open'],
695
+ onClick: (e) => { props.onClick?.(e); if (!e.defaultPrevented) set(!o, e.currentTarget); },
696
+ }, [h('span', { class: ['gk-burger', props.iconClass], 'aria-hidden': 'true' }, [h('i'), h('i'), h('i')])]);
697
+ };
698
+ },
699
+ });