@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.
@@ -0,0 +1,710 @@
1
+ /* Overlays from @gecko-ui-kit/overlays as Vue components. The vanilla code still opens, places, animates,
2
+ stacks and closes them; your slot content is drawn into them with <Teleport>.
3
+
4
+ How slot content gets in: each overlay keeps a few empty "holder" elements (display: contents) that Vue
5
+ teleports your content into while they are still off the page. When the overlay opens, the holders are moved
6
+ inside it, so the vanilla code can already measure and focus the real content. Vue never shares an
7
+ element with the vanilla code, so neither one can break the other.
8
+
9
+ Open state is `v-model:open`: closing from inside (✕, scrim, Esc, a pick) sets it to false first, then calls
10
+ the callback (@close, @end, @open-change…).
11
+
12
+ Esc: the first overlay that opens calls bindEscape() from @gecko-ui-kit/overlays. It installs one listener
13
+ for the whole page (calling it again does nothing), and a single Esc press closes only the newest layer,
14
+ even next to AppShell's or createShell()'s own keys. */
15
+ import { defineComponent, ref, shallowRef, watch, toValue, toRaw, isRef, onMounted, onUpdated, onBeforeUnmount, Teleport, unref, useId } from 'vue';
16
+ import * as O from '@gecko-ui-kit/overlays';
17
+ import * as M from '@gecko-ui-kit/motion';
18
+ import { esc } from '@gecko-ui-kit/components';
19
+ import { h, B, ANY, anyProps, cx, same, snap, useClient, useModel, hasContent, enhancer } from './core.js';
20
+
21
+ const { g, RM, D } = M;
22
+
23
+ /* ---------------- shared helpers ---------------- */
24
+ /** An empty element Vue teleports into while it is off the page; display: contents keeps it out of the layout. */
25
+ const holder = (tag = 'div') => { const d = document.createElement(tag); d.style.display = 'contents'; return d; };
26
+ /** An element, a template ref or a component → its element (selectors and anything else as they are). */
27
+ const deref = (x) => { x = unref(x); return x && typeof x === 'object' && '$el' in x ? x.$el : x; };
28
+ const FOCUSABLE = '[data-autofocus], input, button, [href], select, textarea';
29
+ /** Slot content (or the text prop) teleported into a holder. */
30
+ const into = (el, nodes) => (el && nodes != null && nodes !== false && nodes !== '' ? h(Teleport, { to: el }, Array.isArray(nodes) ? nodes : [nodes]) : null);
31
+ /** The wrapper around a trigger: no box of its own, so the trigger lays out as if it were not there. */
32
+ const trigger = (wrap, name, onClick, kids) => h('span', { ref: wrap, style: { display: 'contents' }, 'data-gecko': name, onClick }, kids);
33
+ /** Only the given options that are set, as plain copies. */
34
+ const pick = (props, keys) => { const o = {}; for (const k of keys) { const v = k === 'mount' ? deref(props[k]) : snap(props[k]); if (v !== undefined) o[k] = v; } return o; };
35
+
36
+ /* ---------------- modal ---------------- */
37
+ /**
38
+ * <Modal v-model:open="open" title="Edit bike" sub="Honda Click" size="sm" :anchor="editBtn">
39
+ * …any content…
40
+ * <template #footer><Button variant="primary" @click="save">Save</Button></template>
41
+ * </Modal>
42
+ * Opens when `open` turns true (zooms out of `anchor` if given; bottom sheet on phones) and closes, animated,
43
+ * when it turns false. Closing from inside (✕, scrim, Esc) sets v-model:open to false and calls @close.
44
+ * title / sub: text props, or #title / #sub slots for richer content; they may change while it is open.
45
+ * words: { close } — the ✕ button's label (default 'Close'), e.g. :words="{ close: 'ปิด' }".
46
+ */
47
+ export const Modal = defineComponent({
48
+ name: 'Modal',
49
+ props: { open: B, title: ANY, sub: ANY, size: { type: String, default: '' }, anchor: ANY, words: Object, onClose: Function, 'onUpdate:open': Function },
50
+ setup(props, { slots }) {
51
+ const client = useClient();
52
+ let box = null, hasFoot = false;
53
+ const layer = { current: null };
54
+ const alive = ref(false);
55
+ const titleId = useId();
56
+
57
+ const open = () => {
58
+ const b = box;
59
+ O.bindEscape();
60
+ alive.value = true;
61
+ const l = O.modal({
62
+ title: '', size: props.size, anchor: deref(props.anchor), body: '', foot: ' ', words: props.words ?? {},
63
+ onMount: (el) => {
64
+ const h3 = el.querySelector('.gk-modal__head h3'); h3.id = titleId; h3.append(b.title);
65
+ const p = document.createElement('p'); p.append(b.sub); h3.after(p);
66
+ el.querySelector('.gk-modal__body').append(b.body);
67
+ const foot = el.querySelector('.gk-modal__foot'); foot.textContent = ''; foot.append(b.foot);
68
+ b.body.querySelector(FOCUSABLE)?.focus({ preventScroll: true });
69
+ },
70
+ onClose: () => {
71
+ if (layer.current === l) { layer.current = null; props['onUpdate:open']?.(false); props.onClose?.(); }
72
+ if (!layer.current) alive.value = false;
73
+ },
74
+ });
75
+ layer.current = l;
76
+ refresh();
77
+ };
78
+ const close = () => { const l = layer.current; if (l) { layer.current = null; l.close(); } };
79
+ // things that may change while it is open
80
+ const refresh = () => {
81
+ const el = layer.current?.el; if (!el || !box) return;
82
+ el.className = `gk-modal ${props.size ? 'gk-modal--' + props.size : ''}`;
83
+ el.querySelector('.gk-modal__head [data-close]')?.setAttribute('aria-label', props.words?.close ?? 'Close');
84
+ if (!slots.title && props.title != null) { el.setAttribute('aria-label', String(props.title)); el.removeAttribute('aria-labelledby'); }
85
+ else { el.removeAttribute('aria-label'); el.setAttribute('aria-labelledby', titleId); }
86
+ const p = box.sub.parentElement; if (p) p.hidden = !slots.sub && (props.sub == null || props.sub === '' || props.sub === false);
87
+ const foot = box.foot.parentElement; if (foot) foot.style.display = hasFoot ? '' : 'none';
88
+ };
89
+
90
+ onMounted(() => { box = { title: holder('span'), sub: holder('span'), body: holder(), foot: holder() }; });
91
+ // after the render that teleported the content into the holders (flush: 'post'), so it is there to focus
92
+ watch(() => client.value && !!props.open, (v) => (v ? open() : close()), { flush: 'post' });
93
+ onUpdated(refresh);
94
+ onBeforeUnmount(close);
95
+
96
+ return () => {
97
+ if (!client.value || !box || !(props.open || alive.value)) return null;
98
+ const foot = slots.footer?.();
99
+ hasFoot = hasContent(foot); // read here (in render), used by refresh() after the patch
100
+ return [
101
+ into(box.title, slots.title ? slots.title() : props.title),
102
+ into(box.sub, slots.sub ? slots.sub() : props.sub),
103
+ into(box.body, slots.default?.()),
104
+ into(box.foot, foot),
105
+ ];
106
+ };
107
+ },
108
+ });
109
+
110
+ /* ---------------- drawer ---------------- */
111
+ /**
112
+ * <Drawer v-model:open="open" title="Somchai K." sub="Customer since 2023" side="right">
113
+ * <template #head><Avatar name="Somchai K." /></template>
114
+ * …any content…
115
+ * <template #footer><Button>Message</Button></template>
116
+ * </Drawer>
117
+ * Slides in from the side (a bottom sheet on phones); its content drifts up as it lands. Opening a drawer
118
+ * closes any other drawer. Closing from inside (✕, scrim, Esc, another drawer) sets v-model:open to false and
119
+ * calls @close. title / sub / head: text props or slots of the same name. words: { close } — the ✕ button's label.
120
+ */
121
+ export const Drawer = defineComponent({
122
+ name: 'Drawer',
123
+ props: { open: B, title: ANY, sub: ANY, head: ANY, side: { type: String, default: 'right' }, words: Object, onClose: Function, 'onUpdate:open': Function },
124
+ setup(props, { slots }) {
125
+ const client = useClient();
126
+ let box = null, hasFoot = false;
127
+ const layer = { current: null };
128
+ const alive = ref(false);
129
+ const titleId = useId();
130
+
131
+ const open = () => {
132
+ const b = box;
133
+ O.bindEscape();
134
+ alive.value = true;
135
+ const l = O.drawer({
136
+ title: '', side: props.side, body: '', foot: ' ', words: props.words ?? {},
137
+ onMount: (el) => {
138
+ el.querySelector('.gk-drawer__title').prepend(b.head);
139
+ const h3 = el.querySelector('.gk-drawer__head h3'); h3.id = titleId; h3.append(b.title);
140
+ const p = document.createElement('p'); p.append(b.sub); h3.after(p);
141
+ el.querySelector('.gk-drawer__body').append(b.body);
142
+ const foot = el.querySelector('.gk-drawer__foot'); foot.textContent = ''; foot.append(b.foot);
143
+ if (!RM() && b.body.children.length) g.fromTo(b.body.children, { opacity: 0, y: 14 }, { opacity: 1, y: 0, duration: 0.5, delay: 0.12, stagger: 0.04, ease: 'power3.out', clearProps: 'transform,opacity' });
144
+ },
145
+ onClose: () => {
146
+ if (layer.current === l) { layer.current = null; props['onUpdate:open']?.(false); props.onClose?.(); }
147
+ if (!layer.current) alive.value = false;
148
+ },
149
+ });
150
+ layer.current = l;
151
+ refresh();
152
+ };
153
+ const close = () => { const l = layer.current; if (l) { layer.current = null; l.close(); } };
154
+ const refresh = () => {
155
+ const el = layer.current?.el; if (!el || !box) return;
156
+ el.querySelector('.gk-drawer__head [data-close]')?.setAttribute('aria-label', props.words?.close ?? 'Close');
157
+ if (!slots.title && props.title != null) { el.setAttribute('aria-label', String(props.title)); el.removeAttribute('aria-labelledby'); }
158
+ else { el.removeAttribute('aria-label'); el.setAttribute('aria-labelledby', titleId); }
159
+ const p = box.sub.parentElement; if (p) p.hidden = !slots.sub && (props.sub == null || props.sub === '' || props.sub === false);
160
+ const foot = box.foot.parentElement; if (foot) foot.style.display = hasFoot ? '' : 'none';
161
+ };
162
+
163
+ onMounted(() => { box = { head: holder('span'), title: holder('span'), sub: holder('span'), body: holder(), foot: holder() }; });
164
+ watch(() => client.value && !!props.open, (v) => (v ? open() : close()), { flush: 'post' });
165
+ onUpdated(refresh);
166
+ onBeforeUnmount(close);
167
+
168
+ return () => {
169
+ if (!client.value || !box || !(props.open || alive.value)) return null;
170
+ const foot = slots.footer?.();
171
+ hasFoot = hasContent(foot);
172
+ return [
173
+ into(box.head, slots.head ? slots.head() : props.head),
174
+ into(box.title, slots.title ? slots.title() : props.title),
175
+ into(box.sub, slots.sub ? slots.sub() : props.sub),
176
+ into(box.body, slots.default?.()),
177
+ into(box.foot, foot),
178
+ ];
179
+ };
180
+ },
181
+ });
182
+
183
+ /* ---------------- confirm ---------------- */
184
+ function openConfirm({ title = 'Are you sure?', body = '', ok = 'Confirm', cancel = 'Cancel', danger = false, anchor } = {}) {
185
+ let answered = false, layer = null;
186
+ O.bindEscape();
187
+ const promise = new Promise((res) => {
188
+ layer = O.modal({
189
+ title: esc(title), size: 'sm', anchor: deref(anchor), body: body ? `<p class="gk-muted">${esc(body)}</p>` : '',
190
+ foot: `<button type="button" class="gk-btn" data-close>${esc(cancel)}</button><button type="button" class="gk-btn ${danger ? 'gk-btn--danger' : 'gk-btn--primary'}" data-ok>${esc(ok)}</button>`,
191
+ onMount: (el, close) => {
192
+ el.setAttribute('aria-label', String(title));
193
+ el.querySelector('[data-ok]').addEventListener('click', () => { answered = true; res(true); close(); });
194
+ },
195
+ onClose: () => { if (!answered) res(false); },
196
+ });
197
+ });
198
+ return { promise, close: () => layer?.close() };
199
+ }
200
+ /**
201
+ * const ok = await confirm({ title: 'Cancel this booking?', body: 'The rider gets a refund.', ok: 'Cancel booking', danger: true })
202
+ * The same dialog as confirm() from @gecko-ui-kit/overlays, but title and body are always shown as plain text
203
+ * (safe for your data). Resolves true for OK, false for Cancel / ✕ / scrim / Esc. Call it from an event handler.
204
+ */
205
+ export const confirm = (opts) => openConfirm(opts).promise;
206
+
207
+ /**
208
+ * const confirm = useConfirm(); (in setup) … if (await confirm({ title: 'Delete project?', danger: true })) remove()
209
+ * Same as confirm(), and a dialog that is still open when the component unmounts is closed (answer: false).
210
+ */
211
+ export function useConfirm() {
212
+ const open = new Set();
213
+ onBeforeUnmount(() => { [...open].forEach((c) => c()); open.clear(); });
214
+ return (opts) => {
215
+ const c = openConfirm(opts);
216
+ open.add(c.close);
217
+ c.promise.finally(() => open.delete(c.close));
218
+ return c.promise;
219
+ };
220
+ }
221
+
222
+ /* ---------------- popover ---------------- */
223
+ /**
224
+ * <Popover align="end" label="Share" class-name="pop--wide" ref="share">
225
+ * <Button icon="send">Share</Button>
226
+ * <template #content="{ close }"><ShareForm @done="close" /></template>
227
+ * </Popover>
228
+ * A panel that pops out of its trigger (the default slot: one element). Clicking the trigger toggles it; a click
229
+ * outside, Esc or a resize closes it. With v-model:open, or on its own (default-open). @open-change(open) after
230
+ * every change. content: a text prop, or the #content slot (gets { close }).
231
+ * ref → { open(), close(), isOpen, el }.
232
+ */
233
+ export const Popover = defineComponent({
234
+ name: 'Popover',
235
+ props: {
236
+ open: B, defaultOpen: B, content: ANY, align: { type: String, default: 'start' }, className: { type: String, default: '' },
237
+ label: { type: String, default: '' }, onOpenChange: Function, 'onUpdate:open': Function,
238
+ },
239
+ setup(props, { slots, expose }) {
240
+ const client = useClient();
241
+ const [isOpen, set] = useModel(props, { prop: 'open', def: 'defaultOpen', event: 'onOpenChange', initial: false });
242
+ const wrap = ref(null);
243
+ let box = null;
244
+ const layer = { current: null };
245
+ const alive = ref(false);
246
+ const showing = () => !!layer.current && !layer.current.closing;
247
+ const closeIt = () => layer.current?.close();
248
+ expose({
249
+ open: () => set(true), close: () => set(false),
250
+ get isOpen() { return showing(); }, get el() { return layer.current?.el ?? null; },
251
+ });
252
+
253
+ const show = () => {
254
+ const anchor = wrap.value?.firstElementChild; if (!anchor) return;
255
+ O.bindEscape();
256
+ alive.value = true;
257
+ const l = O.popover(anchor, box, {
258
+ align: props.align, className: props.className, label: props.label, bind: false,
259
+ onClose: () => {
260
+ if (layer.current === l) { layer.current = null; set(false); }
261
+ if (!layer.current) alive.value = false;
262
+ },
263
+ });
264
+ layer.current = l;
265
+ };
266
+ const hide = () => { const l = layer.current; if (l) { layer.current = null; l.close(); } };
267
+ onMounted(() => { box = holder(); });
268
+ watch(() => client.value && !!isOpen.value, (v) => (v ? show() : hide()), { flush: 'post' });
269
+ onBeforeUnmount(hide);
270
+
271
+ return () => {
272
+ const body = client.value && box && (isOpen.value || alive.value)
273
+ ? into(box, slots.content ? slots.content({ close: closeIt }) : props.content) : null;
274
+ return trigger(wrap, 'Popover', (e) => { if (!e.defaultPrevented) set(!showing()); }, [...(slots.default?.() ?? []), body]);
275
+ };
276
+ },
277
+ });
278
+
279
+ /* ---------------- menu ---------------- */
280
+ const menuItems = (items, onPick) => (items || []).filter((it) => it != null && it !== false).map((it, i) => {
281
+ if (it === '-' || it.sep) return '-';
282
+ if (it.section != null) return { label: String(it.section) };
283
+ return { icon: it.icon, label: String(it.label ?? ''), kbd: it.kbd ? esc(it.kbd) : '', danger: !!it.danger, run: (anchor) => onPick(it, i, anchor) };
284
+ });
285
+
286
+ /**
287
+ * <Menu align="end" :items="[{ section: 'Booking' }, { icon: 'edit', label: 'Edit', kbd: 'E', run: edit }, '-',
288
+ * { icon: 'trash', label: 'Cancel booking', danger: true, run: cancel }]" @select="…">
289
+ * <IconButton icon="more" label="More" />
290
+ * </Menu>
291
+ * A popover with a list of actions that slide in; ↑ ↓ move between them. Picking one closes the menu, then
292
+ * calls item.run(trigger) and @select(item, index). { section } is a heading, '-' a line.
293
+ * ref → { open(), close(), isOpen }.
294
+ */
295
+ export const Menu = defineComponent({
296
+ name: 'Menu',
297
+ props: { items: { type: Array, default: () => [] }, onSelect: Function, align: { type: String, default: 'start' }, className: { type: String, default: '' }, label: { type: String, default: '' } },
298
+ setup(props, { slots, expose }) {
299
+ const wrap = ref(null);
300
+ let layer = null;
301
+ const show = () => {
302
+ const anchor = wrap.value?.firstElementChild; if (!anchor) return;
303
+ O.bindEscape();
304
+ const l = O.menu(anchor, menuItems(props.items, (it, i, a) => { it.run?.(a); props.onSelect?.(it, i); }), {
305
+ align: props.align, className: props.className, label: props.label, onClose: () => { if (layer === l) layer = null; },
306
+ });
307
+ layer = l;
308
+ };
309
+ const hide = () => { const l = layer; layer = null; l?.close(); };
310
+ const isOpen = () => !!layer && !layer.closing;
311
+ expose({ open: () => { if (!isOpen()) show(); }, close: hide, get isOpen() { return isOpen(); } });
312
+ onBeforeUnmount(hide);
313
+ return () => trigger(wrap, 'Menu', (e) => { if (e.defaultPrevented) return; isOpen() ? hide() : show(); }, slots.default?.());
314
+ },
315
+ });
316
+
317
+ /* ---------------- context menu ---------------- */
318
+ /* Copies of the items on every open, so checked items flip on the copy (never on your data), and run()
319
+ is always the latest one. */
320
+ const ctxCopy = (list, onPick) => (list || []).map((it) => {
321
+ if (it == null || it === false || it === '-' || it.sep || it.section != null) return it;
322
+ const c = { ...it };
323
+ if (Array.isArray(it.items)) c.items = ctxCopy(it.items, onPick);
324
+ else c.run = (el, item) => onPick(it, item, el);
325
+ return c;
326
+ });
327
+ const CTX_OPTS = ['selector', 'longPress', 'nativeOnShift', 'icons', 'shortcuts', 'words'];
328
+
329
+ /**
330
+ * <ContextMenu as="ul" selector="[data-row]" :items="(event, el) => [{ icon: 'edit', label: 'Rename', kbd: 'F2', run: rename }, '-', …]"
331
+ * @select="(item, el) => …">
332
+ * <li v-for="b in bikes" :key="b.id" :data-row="b.id">{{ b.name }}</li>
333
+ * </ContextMenu>
334
+ * Right-click, long-press (touch) or Shift+F10 inside it opens a menu that grows from the pointer, with
335
+ * submenus ({ items }), ticks ({ checked }), sections ({ section }) and lines ('-'). items may be a list or
336
+ * (event, el) => list (return [] for the browser's own menu). Picking calls item.run(el, item) and
337
+ * @select(item, el); for a checked item, item.checked is already flipped (on a copy).
338
+ * as="tbody" changes the wrapper element. ref → { open(x, y, el?), close(), isOpen, menu, el }.
339
+ */
340
+ export const ContextMenu = defineComponent({
341
+ name: 'ContextMenu',
342
+ props: {
343
+ items: ANY, onSelect: Function, onOpen: Function, onClose: Function, ...anyProps('selector', 'longPress', 'words'),
344
+ nativeOnShift: B, icons: B, shortcuts: B, as: { type: String, default: 'div' },
345
+ },
346
+ setup(props, { slots, expose }) {
347
+ const el = ref(null);
348
+ let cur = null, last = null;
349
+ expose({
350
+ open: (x, y, target) => cur?.open(x, y, target),
351
+ close: () => cur?.close(),
352
+ get isOpen() { return !!cur?.isOpen; },
353
+ get menu() { return cur?.el ?? null; },
354
+ get el() { return el.value; },
355
+ });
356
+ const create = () => {
357
+ const pickIt = (orig, copy, target) => { orig.run?.(target, copy); props.onSelect?.(copy, target); };
358
+ const source = (event, target) => { const it = props.items; return ctxCopy(typeof it === 'function' ? it(event, target) : it, pickIt); };
359
+ last = pick(props, CTX_OPTS);
360
+ cur = O.contextMenu(el.value, source, { ...last, onOpen: (x) => props.onOpen?.(x), onClose: (x) => props.onClose?.(x) });
361
+ };
362
+ const destroy = () => { const c = cur; cur = null; c?.destroy(); };
363
+ onMounted(() => {
364
+ create();
365
+ watch(() => pick(props, CTX_OPTS), (n) => { if (!same(n, last)) { destroy(); create(); } });
366
+ });
367
+ onBeforeUnmount(destroy);
368
+ return () => h(props.as, { ref: el }, slots.default?.());
369
+ },
370
+ });
371
+
372
+ /* ---------------- tooltip ---------------- */
373
+ /**
374
+ * <Tooltip text="Edit booking"><IconButton icon="edit" label="Edit" /></Tooltip>
375
+ * <Tooltip side="right"><template #text>Somchai K.<br />Mechanic</template><Avatar … /></Tooltip>
376
+ * The same small label as data-tip + initTips(): it fades in under its child (side="right": beside it) on
377
+ * hover or keyboard focus, and stays hidden on touch screens (narrower than config.mobile).
378
+ * text: a text prop or the #text slot. Inside an element with data-tips-right it opens to the right.
379
+ */
380
+ export const Tooltip = defineComponent({
381
+ name: 'Tooltip',
382
+ props: { text: ANY, side: { type: String, default: 'below' }, disabled: B },
383
+ setup(props, { slots }) {
384
+ const wrap = ref(null), tipEl = ref(null);
385
+ const tip = shallowRef(null);
386
+ const id = useId();
387
+ let off = null, tw = null;
388
+ const hasText = () => !!slots.text || !(props.text == null || props.text === '' || props.text === false);
389
+ onMounted(() => {
390
+ const t = wrap.value?.firstElementChild; if (!t) return;
391
+ const show = () => {
392
+ if (props.disabled || !hasText() || innerWidth <= O.config.mobile) return;
393
+ const r = t.getBoundingClientRect(), right = props.side === 'right' || !!t.closest('[data-tips-right]');
394
+ t.setAttribute('aria-describedby', id);
395
+ tip.value = right ? { right, left: r.right + 12, top: r.top + r.height / 2 } : { right, left: r.left + r.width / 2, top: r.bottom + 10 };
396
+ };
397
+ const hide = () => { t.removeAttribute('aria-describedby'); tip.value = null; };
398
+ const out = (e) => { if (!t.contains(e.relatedTarget)) hide(); };
399
+ t.addEventListener('pointerenter', show); t.addEventListener('focusin', show);
400
+ t.addEventListener('pointerleave', out); t.addEventListener('focusout', out); t.addEventListener('pointerdown', hide);
401
+ off = () => {
402
+ t.removeEventListener('pointerenter', show); t.removeEventListener('focusin', show);
403
+ t.removeEventListener('pointerleave', out); t.removeEventListener('focusout', out); t.removeEventListener('pointerdown', hide);
404
+ t.removeAttribute('aria-describedby');
405
+ };
406
+ });
407
+ // the fade-in, after the tip is drawn; centred on its element with xPercent / yPercent (GSAP owns the transform)
408
+ watch(tip, (s) => {
409
+ tw?.kill(); tw = null;
410
+ const el = tipEl.value; if (!s || !el) return;
411
+ const at = s.right ? { xPercent: 0, yPercent: -50 } : { xPercent: -50, yPercent: 0 };
412
+ tw = g.fromTo(el, { ...at, opacity: 0, x: s.right ? -4 : 0, y: s.right ? 0 : -4 }, { ...at, opacity: 1, x: 0, y: 0, duration: D(0.25), ease: 'power3.out', overwrite: true });
413
+ }, { flush: 'post' });
414
+ watch(() => props.disabled, (d) => { if (d && tip.value) { wrap.value?.firstElementChild?.removeAttribute('aria-describedby'); tip.value = null; } });
415
+ onBeforeUnmount(() => { off?.(); off = null; tw?.kill(); tw = null; });
416
+
417
+ return () => {
418
+ const s = tip.value;
419
+ const node = s ? h(Teleport, { to: 'body' }, [h('div', {
420
+ ref: tipEl, id, role: 'tooltip', class: cx('gk-tip', s.right && 'gk-is-side'),
421
+ style: { display: 'block', left: s.left + 'px', top: s.top + 'px' },
422
+ }, slots.text ? slots.text() : props.text)]) : null;
423
+ return trigger(wrap, 'Tooltip', undefined, [...(slots.default?.() ?? []), node]);
424
+ };
425
+ },
426
+ });
427
+
428
+ /* ---------------- toast ---------------- */
429
+ /**
430
+ * toast('Booking saved', { tone: 'good', icon: 'check', undo: () => restore(), duration: 4200 }) → close()
431
+ * The vanilla toast, callable from anywhere in the browser (event handlers, onMounted, after a fetch); no
432
+ * plugin or provider needed. The text is shown as plain text (safe for your data). tone: '' | 'good' | 'warn' | 'bad'.
433
+ */
434
+ export const toast = (text, opts = {}) => O.toast(esc(text == null ? '' : String(text)), { ...opts, ...(opts.undoneText != null ? { undoneText: esc(String(opts.undoneText)) } : null) });
435
+
436
+ /* ---------------- cookie banner ---------------- */
437
+ const COOKIE_OPTS = ['categories', 'storageKey', 'version', 'show', 'position', 'mount', 'policy', 'words'];
438
+ /**
439
+ * <CookieBanner ref="cookies" policy="/privacy" @change="(choices) => choices.analytics && loadAnalytics()" />
440
+ * Slides up from the bottom (position="start" | "end": a card in a corner) with Reject all / Accept all /
441
+ * Settings, remembers the answer in localStorage, and stays away on later visits until `version` goes up.
442
+ * Draws nothing where it is placed. ref → { choices, allowed(id), open({ settings }), close(), reset(), visible, el }
443
+ * (cookies.open() from a "Cookie settings" link brings it back). Changing an option builds it again.
444
+ */
445
+ export const CookieBanner = defineComponent({
446
+ name: 'CookieBanner',
447
+ inheritAttrs: false,
448
+ props: { ...anyProps(...COOKIE_OPTS), onChange: Function },
449
+ setup(props, { expose }) {
450
+ let cur = null, last = null;
451
+ expose({
452
+ get choices() { return cur?.choices ?? null; },
453
+ get visible() { return !!cur?.visible; },
454
+ get el() { return cur?.el ?? null; },
455
+ allowed: (id) => !!cur?.allowed(id),
456
+ open: (o) => { cur?.open(o); },
457
+ close: () => { cur?.close(); },
458
+ reset: () => { cur?.reset(); },
459
+ });
460
+ const create = () => { last = pick(props, COOKIE_OPTS); cur = O.cookieBanner({ ...last, onChange: (c, info) => props.onChange?.(c, info) }); };
461
+ const destroy = () => { const b = cur; cur = null; b?.destroy(); };
462
+ onMounted(() => {
463
+ create();
464
+ watch(() => pick(props, COOKIE_OPTS), (n) => { if (!same(n, last)) { destroy(); create(); } });
465
+ });
466
+ onBeforeUnmount(destroy);
467
+ return () => null;
468
+ },
469
+ });
470
+
471
+ /* ---------------- loading bar ---------------- */
472
+ /**
473
+ * const bar = useLoadingBar({ color: 'var(--gk-good)' }); (in setup) … bar.start(); await save(); bar.done()
474
+ * The thin loading line along the top of the page (or along the top of `mount`: an element, template ref or
475
+ * selector). options: an object, a ref or a getter; when they change the bar is made again. Returns a handle that
476
+ * stays the same for the component's life: start() · done() · done(true) · fail() · set(0..1) · inc(n) · value ·
477
+ * loads · active · el. Every start() needs its done(); quick loads never show it. Removed on unmount.
478
+ */
479
+ export function useLoadingBar(options = {}) {
480
+ let cur = null, live = false, last = null;
481
+ const read = () => { const src = toValue(options) || {}; return pick(src, Object.keys(src)); };
482
+ // the bar is made on the first start() / set() / inc(), so nothing is added to the page until it is needed
483
+ const make = () => { if (!cur && live) cur = O.loadingBar(read()); return cur; };
484
+ const call = (k, create) => (...a) => { (create ? make() : cur)?.[k](...a); return api; };
485
+ const api = {
486
+ start: call('start', true), done: call('done'), fail: call('fail', true), set: call('set', true), inc: call('inc', true),
487
+ get value() { return cur?.value ?? 0; }, get loads() { return cur?.loads ?? 0; },
488
+ get active() { return !!cur?.active; }, get el() { return cur?.el ?? null; },
489
+ };
490
+ const drop = () => { const b = cur; cur = null; b?.destroy(); };
491
+ onMounted(() => {
492
+ live = true; last = read();
493
+ watch(read, (n) => { if (same(n, last)) return; last = n; drop(); });
494
+ });
495
+ onBeforeUnmount(() => { live = false; drop(); });
496
+ return api;
497
+ }
498
+
499
+ const BAR_OPTS = ['mount', 'height', 'color', 'trickle', 'delay', 'label', 'words'];
500
+ /**
501
+ * <LoadingBar :active="saving" /> (or a template ref: bar.value.start() / done())
502
+ * The same bar as a component: it starts when `active` turns true and finishes when it turns false.
503
+ * Every option of loadingBar() is a prop (mount, height, color, trickle, delay, label, words).
504
+ */
505
+ export const LoadingBar = defineComponent({
506
+ name: 'LoadingBar',
507
+ inheritAttrs: false,
508
+ props: { ...anyProps('mount', 'height', 'color', 'delay', 'label', 'words'), trickle: { type: [Boolean, Number], default: undefined }, active: B },
509
+ setup(props, { expose }) {
510
+ const bar = useLoadingBar(() => { const o = {}; for (const k of BAR_OPTS) if (props[k] !== undefined) o[k] = props[k]; return o; });
511
+ expose(bar);
512
+ let was = false;
513
+ onMounted(() => {
514
+ watch(() => props.active, (a) => {
515
+ if (a === undefined) return;
516
+ if (a && !was) bar.start();
517
+ else if (!a && was) bar.done();
518
+ was = !!a;
519
+ }, { immediate: true });
520
+ });
521
+ return () => null;
522
+ },
523
+ });
524
+
525
+ /* ---------------- command palette ---------------- */
526
+ /**
527
+ * <CommandPalette v-model:open="open" placeholder="Search bikes, riders…"
528
+ * :search="(q) => [{ label: 'Bikes', items: bikes.filter(…).map((b) => ({ title: b.name, sub: b.plate, icon: 'bike', run: () => openBike(b) })) }]"
529
+ * @select="(item) => …" />
530
+ * The ⌘K search window: arrow keys move a stretchy highlight, Enter picks, Esc closes. search(q) gets the
531
+ * lowercased text and returns groups; picking an item closes the palette, then calls item.run() and @select(item).
532
+ * Closing by itself sets v-model:open to false and calls @close.
533
+ */
534
+ export const CommandPalette = defineComponent({
535
+ name: 'CommandPalette',
536
+ inheritAttrs: false,
537
+ props: {
538
+ open: B, search: Function, placeholder: { type: String, default: 'Search…' }, emptyTitle: String, emptyBody: String,
539
+ onClose: Function, onSelect: Function, 'onUpdate:open': Function,
540
+ },
541
+ setup(props) {
542
+ let layer = null;
543
+ const show = () => {
544
+ O.bindEscape();
545
+ const opts = {
546
+ placeholder: props.placeholder,
547
+ search: (q) => (props.search?.(q) || []).map((gr) => ({
548
+ label: gr.label ?? '',
549
+ items: (gr.items || []).map((it) => { const { html, ...safe } = it; return { ...safe, run: () => { it.run?.(); props.onSelect?.(it); } }; }),
550
+ })),
551
+ };
552
+ if (props.emptyTitle != null) opts.emptyTitle = props.emptyTitle;
553
+ if (props.emptyBody != null) opts.emptyBody = props.emptyBody;
554
+ const l = O.palette(opts);
555
+ if (!l) return; // another palette is open
556
+ l.onClose = () => { if (layer === l) { layer = null; props['onUpdate:open']?.(false); props.onClose?.(); } };
557
+ layer = l;
558
+ };
559
+ const hide = () => { const l = layer; if (l) { layer = null; l.close(); } };
560
+ onMounted(() => { watch(() => !!props.open, (v) => (v ? show() : hide()), { immediate: true }); });
561
+ onBeforeUnmount(hide);
562
+ return () => null;
563
+ },
564
+ });
565
+
566
+ /* ---------------- tour ---------------- */
567
+ const TOUR_OPTS = ['placement', 'padding', 'radius', 'backdrop', 'scroll', 'words'];
568
+ /** A step's target → what the vanilla tour wants: a selector, an element, false (a ref not on the page: skipped)
569
+ or undefined (no target: the bubble in the middle). */
570
+ const targetOf = (t) => (isRef(t) || (t && typeof t === 'object' && '$el' in t) ? deref(t) ?? false : t);
571
+
572
+ /**
573
+ * <Tour v-model:open="touring" :steps="[
574
+ * { title: 'Welcome', text: 'A quick look around.' }, // no target: in the middle
575
+ * { target: searchBtn, title: 'Find a bike', text: 'Search by name or plate.' },
576
+ * { target: '#calendar', title: 'Bookings', slot: 'drag' }, // content from the #drag slot
577
+ * ]" @end="(finished) => …">
578
+ * <template #drag><p>Drag a booking to <b>move</b> it.</p></template>
579
+ * </Tour>
580
+ * Dims the page except a spotlight around each stop; a bubble explains it. ← → move, Esc ends.
581
+ * target: a template ref, an element, a component or a selector (not on the page → skipped).
582
+ * slot: the name of a slot to show instead of text (it gets { step, index }).
583
+ * @step(index, step) · @end(finished) (finished = Done on the last step; v-model:open turns false first).
584
+ * Setting open to false ends it without @end. ref → { start(i), next(), prev(), go(i), stop(), index, active }.
585
+ */
586
+ export const Tour = defineComponent({
587
+ name: 'Tour',
588
+ inheritAttrs: false,
589
+ props: {
590
+ steps: { type: Array, default: () => [] }, open: B, start: { type: Number, default: 0 },
591
+ onStep: Function, onEnd: Function, 'onUpdate:open': Function,
592
+ ...anyProps('placement', 'padding', 'radius', 'words'), backdrop: B, scroll: B,
593
+ },
594
+ setup(props, { slots, expose }) {
595
+ const client = useClient();
596
+ const holders = [];
597
+ const holderFor = (i) => holders[i] || (holders[i] = holder());
598
+ const slotOf = (s) => (s && typeof s === 'object' && s.slot != null && slots[s.slot] ? slots[s.slot] : null);
599
+ let cur = null, quiet = false, last = null;
600
+ expose({
601
+ start: (i) => cur?.start(i ?? props.start) ?? false, next: () => cur?.next(), prev: () => cur?.prev(),
602
+ go: (i) => cur?.go(i), stop: () => cur?.stop(),
603
+ get index() { return cur?.index ?? -1; }, get active() { return !!cur?.active; },
604
+ });
605
+
606
+ // what makes the tour be built again: the steps (targets only by kind: an element may arrive later) and options
607
+ const key = () => ({
608
+ steps: props.steps.map((s) => {
609
+ if (!s || typeof s !== 'object') return s;
610
+ const { target, ...x } = s;
611
+ const t = toRaw(s).target;
612
+ return { ...snap(x), target: t === undefined ? undefined : t === null ? null : typeof t === 'string' ? t : 'el' };
613
+ }),
614
+ o: pick(props, TOUR_OPTS),
615
+ });
616
+ const create = () => {
617
+ last = key();
618
+ const list = props.steps.map((s, i) => {
619
+ if (!s || typeof s !== 'object') return s;
620
+ const { target, slot, ...x } = s;
621
+ const step = snap(x);
622
+ // read when the tour gets there, so a template ref filled in later still counts
623
+ Object.defineProperty(step, 'target', { enumerable: true, get: () => targetOf(toRaw(props.steps[i] ?? {}).target) });
624
+ if (slotOf(s)) step.html = holderFor(i);
625
+ return step;
626
+ });
627
+ cur = O.tour(list, {
628
+ ...last.o, start: false,
629
+ onStep: (i) => props.onStep?.(i, props.steps[i]),
630
+ onEnd: (finished) => { if (!quiet) { props['onUpdate:open']?.(false); props.onEnd?.(finished); } },
631
+ });
632
+ };
633
+ const destroy = () => { const t = cur; cur = null; t?.destroy(); };
634
+ const sync = () => {
635
+ const t = cur; if (!t || !client.value) return;
636
+ if (props.open && !t.active) t.start(props.start);
637
+ else if (!props.open && t.active) { quiet = true; t.stop(); quiet = false; }
638
+ };
639
+
640
+ onMounted(() => {
641
+ create();
642
+ watch(key, (n) => { if (same(n, last)) return; destroy(); create(); sync(); }, { flush: 'post' });
643
+ });
644
+ // after the render that teleported the step slots into their holders
645
+ watch(() => client.value && !!props.open, sync, { flush: 'post' });
646
+ onBeforeUnmount(() => { quiet = true; destroy(); });
647
+
648
+ return () => {
649
+ if (!client.value) return null;
650
+ return props.steps.map((s, i) => { const sl = slotOf(s); return sl ? h(Teleport, { key: i, to: holderFor(i) }, sl({ step: s, index: i })) : null; }).filter(Boolean);
651
+ };
652
+ },
653
+ });
654
+
655
+ /* ---------------- lightbox ---------------- */
656
+ const lbItems = (items) => (items || []).map((it) => {
657
+ if (typeof it === 'string') return it;
658
+ const { from, ...x } = it;
659
+ const raw = toRaw(it).from;
660
+ return raw === undefined ? snap(x) : { ...snap(x), from: deref(raw) };
661
+ });
662
+
663
+ /**
664
+ * <Lightbox v-model:open="shown" v-model:index="photo"
665
+ * :items="photos.map((p, k) => ({ src: p.big, alt: p.alt, caption: p.caption, from: thumbs[k] }))" />
666
+ * Full-screen images that grow out of their thumbnail (`from`: an element, a template ref or a selector) and
667
+ * shrink back on close. Swipe or ← → between them; double-tap, pinch or Ctrl + wheel zooms; drag down closes.
668
+ * @change(index) (v-model:index first) · @close(index) (✕, Esc, drag down; v-model:open turns false first).
669
+ * Changing index while open moves there.
670
+ */
671
+ export const Lightbox = defineComponent({
672
+ name: 'Lightbox',
673
+ inheritAttrs: false,
674
+ props: {
675
+ items: { type: Array, default: () => [] }, open: B, index: { type: Number, default: 0 },
676
+ onClose: Function, onChange: Function, 'onUpdate:open': Function, 'onUpdate:index': Function, ...anyProps('zoom', 'maxZoom', 'words'),
677
+ },
678
+ setup(props) {
679
+ let cur = null;
680
+ const show = () => {
681
+ O.bindEscape();
682
+ const o = {
683
+ start: props.index,
684
+ onChange: (i) => { props['onUpdate:index']?.(i); props.onChange?.(i); },
685
+ onClose: (i) => { if (cur === lb) { cur = null; props['onUpdate:open']?.(false); props.onClose?.(i); } },
686
+ ...pick(props, ['zoom', 'maxZoom', 'words']),
687
+ };
688
+ const lb = O.lightbox(lbItems(props.items), o);
689
+ cur = lb;
690
+ };
691
+ const hide = () => { const lb = cur; if (lb) { cur = null; lb.close(); } };
692
+ onMounted(() => {
693
+ watch(() => !!props.open, (v) => (v ? show() : hide()), { immediate: true });
694
+ watch(() => props.index, (i) => { const lb = cur; if (lb && lb.index !== i) lb.go(i); });
695
+ });
696
+ onBeforeUnmount(hide);
697
+ return () => null;
698
+ },
699
+ });
700
+
701
+ /**
702
+ * <LightboxGallery class="photos">
703
+ * <a v-for="p in photos" :key="p.id" :href="p.big" data-lightbox="bike" :data-caption="p.caption"><img :src="p.thumb" :alt="p.alt" /></a>
704
+ * </LightboxGallery>
705
+ * Same as lightboxAll(el): clicking an element with data-lightbox opens every element with the same value as
706
+ * one gallery (image: href, data-src or the inner <img>; caption: data-caption or title).
707
+ */
708
+ export const LightboxGallery = enhancer('LightboxGallery', (el, o) => O.lightboxAll(el, o), {
709
+ props: { ...anyProps('selector', 'zoom', 'maxZoom', 'words'), onChange: Function, onClose: Function },
710
+ });