@gecko-ui-kit/vue 0.0.0-stage → 0.1.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/core.js ADDED
@@ -0,0 +1,414 @@
1
+ /* The shared parts every Vue component in this package is built from (Vue 3.4+, works in Nuxt).
2
+
3
+ The library's pieces come in three kinds, and each has a helper here:
4
+
5
+ 1. Markup pieces (button, tag, switch, tabs…): written as Vue components that draw the same HTML as the
6
+ vanilla builders, so the same CSS styles them. Small animations run after mount (see Switch).
7
+ 2. Mounted pieces (rating, data grid, calendar…): the vanilla code builds and owns everything inside one
8
+ element. `mounted(name, mount, spec)` turns such a function into a component: it mounts into an element
9
+ Vue never touches, passes the props as options, keeps callbacks fresh, applies prop changes in place
10
+ when it can (spec.update) or mounts again, and calls destroy() when the component goes away.
11
+ 3. Enhancers (tilt, spotlight, magnetic…): a motion that adds itself to elements you already have.
12
+ `enhancer(name, fn, spec)` renders your slot content inside one element and runs the motion on it.
13
+
14
+ Vue words used here:
15
+ - The main value is `v-model` (prop `modelValue` + `onUpdate:modelValue`); without v-model a piece keeps its own
16
+ value, starting from `defaultValue`.
17
+ - Callbacks are props named like the vanilla options (`onChange`, `onSelect`…), so `@change="…"` in a template
18
+ reaches them, and they may return a value (e.g. `onBeforeClose` → false).
19
+ - App content goes in through slots (default slot, `#title`, `#footer`…).
20
+ - A template ref on a mounted piece is its vanilla handle (`ratingRef.value.set(4)`, `.el` = its element).
21
+
22
+ Nothing here touches `document` or `window` during setup or render, so every component renders on the
23
+ server (Nuxt) and wakes up in the browser. */
24
+ import { PATHS } from '@gecko-ui-kit/icons';
25
+ import {
26
+ defineComponent, h, ref, shallowRef, computed, watch, toRaw, isRef, unref, isVNode,
27
+ onMounted, onBeforeUnmount, onBeforeUpdate, onUpdated, normalizeClass, normalizeStyle, Comment, Fragment, Text,
28
+ } from 'vue';
29
+
30
+ export { h };
31
+
32
+ /** Join class names, skipping empty ones: cx('btn', on && 'is-on'). (Vue's own class binding also works.) */
33
+ export const cx = (...a) => a.flat(Infinity).filter(Boolean).join(' ');
34
+
35
+ /** A Boolean prop that stays `undefined` when it is not given (Vue would make it false), so the vanilla default
36
+ applies; `<Rating half>` still gives true. Use it for every on/off option. */
37
+ export const B = { type: Boolean, default: undefined };
38
+ /** A prop of any type (string, number, array, object, function…). */
39
+ export const ANY = { type: null, default: undefined };
40
+ /** Props for a list of names: props('max', 'labels') → { max: ANY, labels: ANY }. */
41
+ export const anyProps = (...names) => Object.fromEntries(names.map((n) => [n, ANY]));
42
+
43
+ /** Deep "same data" test: plain objects, arrays, dates and primitives by content; functions always count
44
+ as the same (they are called through the latest props); anything else (DOM nodes, Files) by identity. */
45
+ export function same(a, b) {
46
+ if (Object.is(a, b)) return true;
47
+ if (typeof a === 'function' && typeof b === 'function') return true;
48
+ if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false;
49
+ if (a instanceof Date || b instanceof Date) return a instanceof Date && b instanceof Date && +a === +b;
50
+ if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((x, i) => same(x, b[i]));
51
+ if (Object.getPrototypeOf(a) !== Object.prototype || Object.getPrototypeOf(b) !== Object.prototype) return false;
52
+ const ka = Object.keys(a), kb = Object.keys(b);
53
+ return ka.length === kb.length && ka.every((k) => Object.prototype.hasOwnProperty.call(b, k) && same(a[k], b[k]));
54
+ }
55
+
56
+ /** A plain copy of data that may be reactive: arrays and plain objects are copied (so a later in-place change
57
+ by the app is noticed, and the vanilla code never writes into the app's reactive state); refs are read;
58
+ dates, DOM nodes, functions and everything else are kept as they are. */
59
+ export function snap(v) {
60
+ v = toRaw(unref(v));
61
+ if (Array.isArray(v)) return v.map(snap);
62
+ if (v && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype) {
63
+ const o = {}; for (const k in v) o[k] = snap(v[k]); return o;
64
+ }
65
+ return v;
66
+ }
67
+
68
+ /** True when only these keys changed between two option objects. */
69
+ export function changedOnly(next, prev, keys) {
70
+ const all = new Set([...Object.keys(next), ...Object.keys(prev)]);
71
+ let any = false;
72
+ for (const k of all) {
73
+ if (same(next[k], prev[k])) continue;
74
+ if (!keys.includes(k)) return false;
75
+ any = true;
76
+ }
77
+ return any;
78
+ }
79
+
80
+ /** Stop whatever a vanilla call returned: a handle with destroy(), a GSAP tween/timeline, a stop function. */
81
+ export function stop(x) {
82
+ if (!x) return;
83
+ if (typeof x === 'function') { x(); return; }
84
+ if (typeof x.destroy === 'function') x.destroy();
85
+ else if (typeof x.revert === 'function') x.revert();
86
+ else if (typeof x.kill === 'function') x.kill();
87
+ else if (typeof x.stop === 'function') x.stop();
88
+ }
89
+
90
+ /** false on the server and during hydration, true once mounted in the browser. */
91
+ export function useClient() { const c = ref(false); onMounted(() => { c.value = true; }); return c; }
92
+
93
+ /**
94
+ * The main value of a markup piece, with or without v-model:
95
+ * const [value, set] = useModel(props) // props.modelValue / props.defaultValue / props.onChange
96
+ * set(next, event) // updates its own copy (no v-model), then calls
97
+ * // onUpdate:modelValue(next) and onChange(next, event)
98
+ * Declare the props with modelProps() (or by hand). opts: { prop = 'modelValue', def = 'defaultValue',
99
+ * event = 'onChange', initial } — initial is used when neither is given.
100
+ */
101
+ export function useModel(props, { prop = 'modelValue', def = 'defaultValue', event = 'onChange', initial } = {}) {
102
+ const inner = ref(props[def] !== undefined ? props[def] : initial);
103
+ const controlled = () => props[prop] !== undefined;
104
+ const value = computed(() => (controlled() ? props[prop] : inner.value));
105
+ const set = (next, ...extra) => {
106
+ if (!controlled()) inner.value = next;
107
+ props['onUpdate:' + prop]?.(next);
108
+ if (event) props[event]?.(next, ...extra);
109
+ };
110
+ return [value, set];
111
+ }
112
+ /** The props useModel / mounted({ model }) need: modelValue, defaultValue and onUpdate:modelValue. */
113
+ export const modelProps = (prop = 'modelValue') => ({ [prop]: ANY, defaultValue: ANY, ['onUpdate:' + prop]: Function });
114
+
115
+ /* Keep host attributes (class, style, id, aria-…, data-…, listeners) in step on an element Vue does not render. */
116
+ function applyHost(el, next, prev = {}) {
117
+ const pc = String(normalizeClass(prev.class) || '').split(/\s+/).filter(Boolean);
118
+ const nc = String(normalizeClass(next.class) || '').split(/\s+/).filter(Boolean);
119
+ pc.filter((c) => !nc.includes(c)).forEach((c) => el.classList.remove(c));
120
+ nc.forEach((c) => el.classList.add(c));
121
+ const ps = toStyle(prev.style), ns = toStyle(next.style);
122
+ for (const k in ps) if (!(k in ns)) el.style.removeProperty(cssName(k));
123
+ for (const k in ns) el.style.setProperty(cssName(k), ns[k] == null ? '' : String(ns[k]));
124
+ for (const k in prev) {
125
+ if (k === 'class' || k === 'style') continue;
126
+ if (isOn(k)) { if (prev[k] !== next[k]) el.removeEventListener(evName(k), prev[k]); }
127
+ else if (!(k in next)) el.removeAttribute(k);
128
+ }
129
+ for (const k in next) {
130
+ if (k === 'class' || k === 'style') continue;
131
+ const v = next[k];
132
+ if (isOn(k)) { if (prev[k] !== v && typeof v === 'function') el.addEventListener(evName(k), v); continue; }
133
+ if (v === false || v == null) el.removeAttribute(k); else el.setAttribute(k, v === true ? '' : String(v));
134
+ }
135
+ }
136
+ const isOn = (k) => /^on[A-Z]/.test(k);
137
+ const evName = (k) => k.slice(2).toLowerCase();
138
+ const cssName = (k) => (k.startsWith('--') ? k : k.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase()));
139
+ function toStyle(s) {
140
+ const n = normalizeStyle(s);
141
+ if (!n) return {};
142
+ if (typeof n === 'string') return Object.fromEntries(n.split(';').map((p) => p.split(':')).filter((p) => p.length > 1).map(([k, ...v]) => [k.trim(), v.join(':').trim()]));
143
+ return n;
144
+ }
145
+
146
+ /* An object that forwards to the live handle (stays the same object for the component's life), with .el. */
147
+ function handleProxy(cur) {
148
+ return new Proxy({}, {
149
+ get(t, k) {
150
+ if (k in t) return t[k]; // Vue's own marks (__v_skip)
151
+ const c = cur.current; if (!c) return undefined;
152
+ if (k === 'el') return c.el;
153
+ const x = c.handle; if (x == null || (typeof x !== 'object' && typeof x !== 'function')) return undefined;
154
+ const v = x[k]; return typeof v === 'function' ? v.bind(x) : v;
155
+ },
156
+ has(t, k) { if (k in t) return true; const c = cur.current; return !!c && (k === 'el' || (c.handle != null && k in Object(c.handle))); },
157
+ });
158
+ }
159
+
160
+ /* Options with every function swapped for a stable caller of the latest value, so the piece never calls an old
161
+ callback and a new arrow function in the template does not mount it again. */
162
+ function liveOptions(opts, latest) {
163
+ const out = {};
164
+ for (const k in opts) {
165
+ const v = opts[k];
166
+ out[k] = typeof v === 'function' ? (...a) => { const f = latest.current[k]; return typeof f === 'function' ? f(...a) : undefined; } : v;
167
+ }
168
+ return out;
169
+ }
170
+
171
+ /**
172
+ * Turn a vanilla mount function `mount(el, options) → handle` into a Vue component.
173
+ *
174
+ * export const Rating = mounted('Rating', withDefault(C.rating), {
175
+ * props: { ...anyProps('max', 'labels', 'words'), half: B, readOnly: B, onChange: Function },
176
+ * model: { event: 'onChange' }, // v-model → the `value` option, emitted from onChange(value, …)
177
+ * update: inPlace({ value: (r, v) => r.set(v, { silent: true }) }), // optional: apply changes in place
178
+ * });
179
+ * <Rating v-model="score" :max="5" half class="mb-2" ref="r" /> r.value.set(4), r.value.el
180
+ *
181
+ * spec:
182
+ * props the Vue props (the vanilla options). Use B for booleans, ANY or anyProps() for the rest and
183
+ * Function for callbacks. Anything not declared (class, style, id, aria-…, data-…, @click) goes on
184
+ * the element.
185
+ * model { key = 'value', event = 'onChange', arg = 0 }: adds v-model. The vanilla option `key` gets
186
+ * modelValue (the option `defaultValue` gets defaultValue, as in the React package); when the piece
187
+ * calls `event`, its argument number `arg` (or arg(...args)) goes to onUpdate:modelValue first.
188
+ * tag element to mount into (default 'div')
189
+ * options (opts, props) → the options object to pass (default: every declared prop that is set)
190
+ * prepare (el, options) → void: fill the element before mounting (e.g. markup the piece expects)
191
+ * update (handle, nextOptions, prevOptions, el) → true when the change was applied in place
192
+ * Changes inside arrays/objects you pass (rows.push(…)) are noticed too.
193
+ */
194
+ export function mounted(name, mount, spec = {}) {
195
+ const { tag = 'div', props: decl = {}, model, options: toOptions, prepare, update } = spec;
196
+ const mkey = model ? (model.key || 'value') : null;
197
+ const mevent = model ? (model.event || 'onChange') : null;
198
+ const marg = model ? (model.arg ?? 0) : 0;
199
+ const allProps = { ...decl, ...(model ? modelProps() : null), ...(mevent && !(mevent in decl) ? { [mevent]: Function } : null) };
200
+ return defineComponent({
201
+ name,
202
+ inheritAttrs: false,
203
+ props: allProps,
204
+ setup(props, { attrs, expose }) {
205
+ const slot = ref(null);
206
+ const cur = { current: null };
207
+ const read = () => {
208
+ const o = {};
209
+ for (const k in decl) { const v = snap(props[k]); if (v !== undefined) o[k] = v; }
210
+ if (model) {
211
+ if (props.modelValue !== undefined) o[mkey] = snap(props.modelValue);
212
+ if (props.defaultValue !== undefined) o.defaultValue = snap(props.defaultValue);
213
+ const user = props[mevent];
214
+ o[mevent] = (...a) => {
215
+ props['onUpdate:modelValue']?.(typeof marg === 'function' ? marg(...a) : a[marg]);
216
+ return (typeof user === 'function' ? user : props[mevent])?.(...a);
217
+ };
218
+ }
219
+ return toOptions ? toOptions(o, props) : o;
220
+ };
221
+ const latest = { current: read() };
222
+ let host = { ...attrs };
223
+ expose(handleProxy(cur));
224
+
225
+ const create = () => {
226
+ const el = document.createElement(tag);
227
+ applyHost(el, host);
228
+ slot.value.appendChild(el);
229
+ const o = liveOptions(latest.current, latest);
230
+ prepare?.(el, o);
231
+ cur.current = { el, handle: null, opts: latest.current };
232
+ cur.current.handle = mount(el, o) ?? null;
233
+ };
234
+ const destroy = () => {
235
+ const c = cur.current; if (!c) return; cur.current = null;
236
+ try { stop(c.handle); } finally { c.el.remove(); }
237
+ };
238
+ const sync = () => {
239
+ const c = cur.current; if (!c) return;
240
+ const next = latest.current = read();
241
+ const prev = c.opts;
242
+ const fns = (o) => Object.keys(o).filter((k) => typeof o[k] === 'function').sort().join();
243
+ if (fns(next) === fns(prev) && same(next, prev)) return;
244
+ if (fns(next) === fns(prev) && update && update(c.handle, next, prev, c.el) === true) { c.opts = next; return; }
245
+ destroy(); create();
246
+ };
247
+
248
+ onMounted(() => {
249
+ create();
250
+ // props (deep: also changes inside arrays/objects the app passed)
251
+ // watch the props themselves (not copies), so deep: true also tracks changes inside the app's arrays/objects;
252
+ // sync() compares plain copies, so it only acts on a real change
253
+ watch(() => { const o = {}; for (const k in allProps) o[k] = props[k]; return o; }, sync, { deep: true, flush: 'post' });
254
+ });
255
+ onUpdated(() => {
256
+ const c = cur.current; if (!c) return;
257
+ const next = { ...attrs };
258
+ if (!same(next, host)) { applyHost(c.el, next, host); host = next; }
259
+ });
260
+ onBeforeUnmount(destroy);
261
+ return () => h('div', { ref: slot, style: { display: 'contents' }, 'data-gecko': name });
262
+ },
263
+ });
264
+ }
265
+
266
+ /**
267
+ * Turn a motion `fn(el, options) → handle | tween | stop()` into a wrapper component around slot content.
268
+ *
269
+ * export const Tilt = enhancer('Tilt', tilt, { props: { ...anyProps('max', 'scale'), glare: B } });
270
+ * <Tilt :max="10" glare class="card"><h3>Lamp</h3></Tilt>
271
+ *
272
+ * spec:
273
+ * props the option props (B / ANY / Function); every other attribute goes on the element
274
+ * tag element to render (default 'div'; the `as` prop overrides it)
275
+ * update (handle, next, prev, el) → true when the change was applied in place; else it runs again
276
+ * rerunOnChildren run fn again when the slot content changes (for motions that read the text, e.g. split):
277
+ * the old run is stopped (its DOM changes undone) before Vue patches the content
278
+ * defaults option values used when a prop is not given
279
+ * class a class the element always has (e.g. 'tilt'); yours is added to it
280
+ * A template ref on it is the component; its element is `.$el`.
281
+ */
282
+ export function enhancer(name, fn, spec = {}) {
283
+ const { tag = 'div', props: decl = {}, update, rerunOnChildren = false, defaults = {}, class: baseClass } = spec;
284
+ return defineComponent({
285
+ name,
286
+ props: { ...decl, as: { type: String, default: undefined } },
287
+ setup(props, { slots, attrs }) {
288
+ const el = ref(null);
289
+ let cur = null, kidsKey = '', lastClass = normalizeClass(attrs.class), kept = null;
290
+ const read = () => {
291
+ const o = { ...defaults };
292
+ for (const k in decl) { const v = snap(props[k]); if (v !== undefined) o[k] = v; }
293
+ return o;
294
+ };
295
+ const latest = { current: read() };
296
+ const run = () => { cur = { handle: fn(el.value, liveOptions(latest.current, latest)) ?? null, opts: latest.current, kids: kidsKey }; };
297
+ const halt = () => { const c = cur; cur = null; c && stop(c.handle); };
298
+ onMounted(() => {
299
+ run();
300
+ watch(() => { const o = {}; for (const k in decl) o[k] = props[k]; return o; }, () => {
301
+ const next = latest.current = read();
302
+ const c = cur; if (!c) return;
303
+ if (same(next, c.opts)) return;
304
+ if (update && update(c.handle, next, c.opts, el.value) === true) { c.opts = next; return; }
305
+ halt(); run();
306
+ }, { deep: true, flush: 'post' });
307
+ });
308
+ // Vue rewrites the whole class attribute when `class` changes, which would drop classes the motion
309
+ // added (is-lit, is-armed…): note them before the patch and put them back after it.
310
+ onBeforeUpdate(() => {
311
+ const nc = normalizeClass(attrs.class);
312
+ if (nc !== lastClass && el.value) {
313
+ const was = new Set(String(lastClass || '').split(/\s+/));
314
+ kept = [...el.value.classList].filter((c) => !was.has(c));
315
+ }
316
+ lastClass = nc;
317
+ });
318
+ let rerun = false;
319
+ onUpdated(() => {
320
+ if (kept) { el.value?.classList.add(...kept); kept = null; }
321
+ if (rerun) { rerun = false; run(); }
322
+ });
323
+ onBeforeUnmount(halt);
324
+ return () => {
325
+ const kids = slots.default?.();
326
+ if (rerunOnChildren) {
327
+ const k = vnodeKey(kids);
328
+ // the content changed: undo the motion now (render runs before the patch), run it again after
329
+ if (cur && k !== cur.kids) { halt(); rerun = true; }
330
+ kidsKey = k;
331
+ }
332
+ return h(props.as || tag, { ref: el, class: baseClass }, kids);
333
+ };
334
+ },
335
+ });
336
+ }
337
+ /* A cheap fingerprint of slot content (text and element names), so a motion that reads the text runs again. */
338
+ export function vnodeKey(v) {
339
+ if (v == null || typeof v === 'boolean') return '';
340
+ if (typeof v === 'string' || typeof v === 'number') return String(v);
341
+ if (Array.isArray(v)) return v.map(vnodeKey).join('\u0001');
342
+ if (isVNode(v)) {
343
+ if (v.type === Comment) return '';
344
+ if (v.type === Text) return String(v.children);
345
+ const t = typeof v.type === 'string' ? v.type : v.type === Fragment ? '' : 'C';
346
+ return `<${t}>${typeof v.children === 'string' ? v.children : Array.isArray(v.children) ? vnodeKey(v.children) : ''}`;
347
+ }
348
+ return '?';
349
+ }
350
+
351
+ /**
352
+ * Run any motion helper on an element you render yourself. Returns a template ref to put on it.
353
+ * const card = useMotion(tilt, { max: 12 }) <div ref="card">…</div>
354
+ * const list = useMotion((el) => rise(el.children)) // a function of the element only
355
+ * const box = useMotion(spotlight, () => ({ size: size.value })) // options from a getter or ref: runs again on change
356
+ * The motion starts after mount and is stopped (destroy / revert / kill) on unmount and before each re-run.
357
+ */
358
+ export function useMotion(fn, opts) {
359
+ const el = shallowRef(null);
360
+ const read = () => snap(typeof opts === 'function' ? opts() : isRef(opts) ? opts.value : opts);
361
+ let out = null;
362
+ const go = () => { stop(out); out = null; const node = el.value?.$el ?? el.value; if (node && node.nodeType === 1) out = fn(node, read()); };
363
+ onMounted(() => {
364
+ go();
365
+ watch([el, () => (typeof opts === 'function' ? opts() : isRef(opts) ? opts.value : opts)], go, { deep: true, flush: 'post' });
366
+ });
367
+ onBeforeUnmount(() => { stop(out); out = null; });
368
+ return el;
369
+ }
370
+
371
+ /**
372
+ * <Icon name="search" /> — the same 24×24 stroke icon as icon('search') from @gecko-ui-kit/icons,
373
+ * as a real <svg class="ico">, so `.btn > svg` style rules keep working. size: px or any CSS length.
374
+ */
375
+ export const Icon = defineComponent({
376
+ name: 'Icon',
377
+ props: { name: { type: String, required: true }, size: ANY, stroke: { type: [Number, String], default: 1.7 } },
378
+ setup(props) {
379
+ return () => h('svg', {
380
+ class: 'ico', viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': props.stroke,
381
+ 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true',
382
+ ...(props.size != null ? { width: props.size, height: props.size, style: { width: px(props.size), height: px(props.size) } } : null),
383
+ innerHTML: PATHS[props.name] ?? PATHS.sparkle,
384
+ });
385
+ },
386
+ });
387
+ const px = (v) => (typeof v === 'number' ? v + 'px' : v);
388
+ /** An icon given as a name ('check'), a component or a ready VNode → something to render (or null). */
389
+ export const iconNode = (ic, extra) => (ic == null || ic === false || ic === '' ? null
390
+ : typeof ic === 'string' ? h(Icon, { name: ic, ...extra }) : isVNode(ic) ? ic : h(ic, extra));
391
+
392
+ /** Slot content if the slot is given, else the prop value (text): slotOr(slots.title, props.title). */
393
+ export const slotOr = (slot, fallback, ...args) => (slot ? slot(...args) : fallback);
394
+ /** True when a slot renders something other than comments / empty text. */
395
+ export function hasContent(nodes) {
396
+ return !!nodes && (Array.isArray(nodes) ? nodes : [nodes]).some((n) => !isVNode(n) ? n != null && n !== false && n !== ''
397
+ : n.type === Comment ? false : n.type === Fragment ? hasContent(n.children) : n.type === Text ? String(n.children).trim() !== '' : true);
398
+ }
399
+
400
+ /** An update for mounted(): apply changed options through the handle's own methods.
401
+ map: { option: (handle, value, next, prev, el) => false | void } — null means "nothing to do" (defaultValue).
402
+ Any other option that changed mounts the piece again; a function that returns false does too. */
403
+ export const inPlace = (map) => (hd, next, prev, el) => {
404
+ const changed = [...new Set([...Object.keys(next), ...Object.keys(prev)])].filter((k) => !same(next[k], prev[k]));
405
+ if (!changed.every((k) => k in map)) return false;
406
+ for (const k of Object.keys(map)) if (changed.includes(k) && map[k] && map[k](hd, next[k], next, prev, el) === false) return false;
407
+ return true;
408
+ };
409
+ /** Mount with the v-model value (option `key`) or else `defaultValue` as that option. */
410
+ export const withDefault = (mount, key = 'value', from = 'defaultValue') => (el, o) => {
411
+ const x = { ...o }; delete x[from];
412
+ if (x[key] === undefined) { delete x[key]; if (o[from] !== undefined) x[key] = o[from]; } // undefined would hide the piece's own default
413
+ return mount(el, x);
414
+ };