@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/forms.js ADDED
@@ -0,0 +1,481 @@
1
+ /* Form pieces from @gecko-ui-kit/components (multi-select, combobox, tags, sliders, rating, radio cards,
2
+ subscribe, password, sign-in, signature, uploads, pricing, date and time pickers, wizard).
3
+ Most are mounted pieces: the vanilla code builds them inside one element; these components pass props in
4
+ as options, keep the v-model value in step through the piece's own set(), and clean up on unmount.
5
+ PasswordToggle and PasswordMeter's field are drawn by Vue; Wizard teleports your step slots into its panels;
6
+ useValidation is a small composable for the red-field pattern (.gk-field.gk-is-bad + hint + shake). */
7
+ import { defineComponent, ref, shallowRef, reactive, watch, onMounted, onBeforeUnmount, useId, mergeProps, getCurrentInstance, Teleport } from 'vue';
8
+ import * as C from '@gecko-ui-kit/components';
9
+ import * as M from '@gecko-ui-kit/motion';
10
+ import { h, mounted, inPlace, withDefault, anyProps, B, ANY, same, snap, useModel, modelProps } from './core.js';
11
+
12
+ /* ---------- helpers ---------- */
13
+
14
+ const str = (v) => (v == null ? '' : String(v));
15
+ /** An object for expose() that forwards to whatever get() returns now (a vanilla handle or a child's ref). */
16
+ function live(get) {
17
+ return new Proxy({}, {
18
+ get(t, k) {
19
+ if (k in t) return t[k]; // Vue's own marks (__v_skip)
20
+ const x = get(); if (x == null) return undefined;
21
+ const v = x[k]; return typeof v === 'function' ? v.bind(x) : v;
22
+ },
23
+ has(t, k) { if (k in t) return true; const x = get(); return x != null && k in Object(x); },
24
+ });
25
+ }
26
+
27
+ /* ---------- choosing ---------- */
28
+
29
+ /**
30
+ * <MultiSelect v-model="ids" :options="people" :max="3" creatable placeholder="Assign to…" />
31
+ * Every option of multiSelect(el, options). @change(values, options, ms), @create(option, ms).
32
+ * ref → { value, selected, set, add, remove, clear, open, close, focus, setOptions, el }.
33
+ * A new v-model value or new `options` are applied in place.
34
+ */
35
+ export const MultiSelect = mounted('MultiSelect', withDefault(C.multiSelect), {
36
+ props: { ...anyProps('options', 'placeholder', 'max', 'creatable', 'name', 'words'), closeOnSelect: B, disabled: B, onChange: Function, onCreate: Function },
37
+ model: { event: 'onChange' },
38
+ update: inPlace({
39
+ defaultValue: null,
40
+ options: (ms, v) => { ms.setOptions(v ?? []); },
41
+ value: (ms, v) => { if (v !== undefined && !same(ms.value, (v ?? []).map(String))) ms.set(v ?? []); },
42
+ }),
43
+ });
44
+
45
+ /**
46
+ * <Combobox v-model="country" :options="countries" label="Country" />
47
+ * or :source="(q, { signal }) => $fetch(…)" to ask your server. @change(value, option, cb), @input(text, cb).
48
+ * ref → { value, option, isOpen, set, clear, open, close, focus, setOptions, el }.
49
+ */
50
+ export const Combobox = mounted('Combobox', withDefault(C.combobox), {
51
+ props: { ...anyProps('options', 'source', 'placeholder', 'minChars', 'debounce', 'maxResults', 'name', 'label', 'words'), clearable: B, allowCustom: B, disabled: B, onChange: Function, onInput: Function },
52
+ model: { event: 'onChange' },
53
+ update: inPlace({
54
+ defaultValue: null,
55
+ options: (cb, v) => { cb.setOptions(v ?? []); },
56
+ value: (cb, v) => {
57
+ if (v === undefined) return;
58
+ const want = v == null || v === '' ? null : typeof v === 'object' ? str(v.value ?? v.label) : String(v);
59
+ if (cb.value !== want) cb.set(v ?? null);
60
+ },
61
+ }),
62
+ });
63
+
64
+ /**
65
+ * <TagsInput v-model="tags" :suggestions="['design', 'bug']" :max="5" />
66
+ * Every option of tagsInput(el, options). @change(tags, ti). ref → { value, add, remove, clear, set, focus, el }.
67
+ */
68
+ export const TagsInput = mounted('TagsInput', withDefault(C.tagsInput), {
69
+ props: { ...anyProps('placeholder', 'suggestions', 'max', 'separators', 'validate', 'transform', 'name', 'words'), unique: B, disabled: B, onChange: Function },
70
+ model: { event: 'onChange' },
71
+ update: inPlace({
72
+ defaultValue: null,
73
+ value: (ti, v) => { if (v !== undefined && !same(ti.value, (v ?? []).map(String))) ti.set(v ?? []); },
74
+ }),
75
+ });
76
+
77
+ /* ---------- numbers ---------- */
78
+
79
+ /**
80
+ * <RangeSlider v-model="price" :min="0" :max="2000" :step="50" label="Price per day" :histogram="bars" />
81
+ * @input(value, rs) while dragging, @change(value, rs) when it settles (v-model follows @change); value = [low, high].
82
+ * ref → { value, set, el }.
83
+ */
84
+ export const RangeSlider = mounted('RangeSlider', withDefault(C.rangeSlider), {
85
+ props: { ...anyProps('min', 'max', 'step', 'minGap', 'format', 'parse', 'marks', 'histogram', 'name', 'label', 'words'), inputs: B, disabled: B, onInput: Function, onChange: Function },
86
+ model: { event: 'onChange' },
87
+ update: inPlace({
88
+ defaultValue: null,
89
+ value: (rs, v) => { if (Array.isArray(v) && !same(rs.value, v.map(Number))) rs.set(v, { silent: true }); },
90
+ }),
91
+ });
92
+
93
+ /**
94
+ * <Stepper v-model="days" :min="1" :max="30" :unit="(n) => (n === 1 ? 'day' : 'days')" />
95
+ * The digits roll like an odometer. @change(value, st). ref → { value, set, stepBy, setRange, el }.
96
+ * min / max are applied in place (a value outside is pulled in).
97
+ */
98
+ export const Stepper = mounted('Stepper', withDefault(C.stepper), {
99
+ props: { ...anyProps('min', 'max', 'step', 'unit', 'prefix', 'format', 'locale', 'size', 'name', 'words'), disabled: B, onChange: Function },
100
+ model: { event: 'onChange' },
101
+ update: inPlace({
102
+ defaultValue: null,
103
+ min: (st, _, next) => { st.setRange({ min: next.min ?? -Infinity, max: next.max ?? Infinity }); },
104
+ max: (st, _, next) => { st.setRange({ min: next.min ?? -Infinity, max: next.max ?? Infinity }); },
105
+ value: (st, v) => { if (v != null && Number.isFinite(+v) && +v !== st.value) st.set(+v, { silent: true }); },
106
+ }),
107
+ });
108
+
109
+ /**
110
+ * <Rating v-model="score" :max="5" half :labels="['Bad', …, 'Great']" />
111
+ * Every option of rating(el, options) is a prop. @change(value, handle). ref → { value, set(n), setReadOnly(b), el }.
112
+ * A new v-model value (or `read-only`) is applied in place, without calling @change.
113
+ */
114
+ export const Rating = mounted('Rating', withDefault(C.rating), {
115
+ props: { ...anyProps('max', 'icon', 'size', 'labels', 'name', 'words'), half: B, readOnly: B, clearable: B, showValue: B, disabled: B, onChange: Function },
116
+ model: { event: 'onChange' },
117
+ update: inPlace({
118
+ defaultValue: null,
119
+ readOnly: (r, v) => { r.setReadOnly(!!v); },
120
+ value: (r, v) => { if (v !== undefined && (+v || 0) !== r.value) r.set(+v || 0, { silent: true }); },
121
+ }),
122
+ });
123
+
124
+ /**
125
+ * <RadioCards v-model="how" label="Delivery" :options="[{ value: 'std', title: 'Standard', desc: '3–5 days', price: 'Free' }, …]" />
126
+ * Real radio buttons drawn as cards. @change(value, option, plan). ref → { value, set, focus, el }.
127
+ */
128
+ export const RadioCards = mounted('RadioCards', withDefault(C.radioCards), {
129
+ props: { ...anyProps('label', 'options', 'layout', 'min', 'name', 'words'), hideLabel: B, required: B, disabled: B, onChange: Function },
130
+ model: { event: 'onChange' },
131
+ update: inPlace({
132
+ defaultValue: null,
133
+ value: (rc, v) => { if (v !== undefined && str(v) !== rc.value) rc.set(str(v)); },
134
+ }),
135
+ });
136
+
137
+ /**
138
+ * <PricingToggle v-model="period" :plans="plans" @select="(plan, period) => checkout(plan.id, period)" />
139
+ * The period switch rolls every price. @change(periodId, prices), @select(plan, periodId, prices).
140
+ * ref → { period, set(id), el }.
141
+ */
142
+ export const PricingToggle = mounted('PricingToggle', withDefault(C.pricingToggle), {
143
+ props: { ...anyProps('periods', 'plans', 'format', 'locale', 'motion', 'words'), strike: B, onChange: Function, onSelect: Function },
144
+ model: { event: 'onChange' },
145
+ update: inPlace({
146
+ defaultValue: null,
147
+ value: (p, v) => { if (v && v !== p.period) p.set(v, { silent: true }); },
148
+ }),
149
+ });
150
+
151
+ /* ---------- dates and times ---------- */
152
+
153
+ const ymd = (d) => (d instanceof Date ? `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` : d == null || d === '' ? null : String(d).slice(0, 10));
154
+ const rangeOf = (v, single) => {
155
+ if (v == null) return { start: null, end: null };
156
+ if (typeof v === 'string' || v instanceof Date) return { start: ymd(v), end: single ? ymd(v) : null };
157
+ return { start: ymd(v.start), end: ymd(v.end ?? (single ? v.start : null)) };
158
+ };
159
+
160
+ /**
161
+ * <DateRange v-model="dates" :min="today" :disabled="booked" /> dates = { start: '2026-12-04', end: '2026-12-07' }
162
+ * mode="single" picks one date. @change({ start, end, count }, dp) — end is null until the end is picked; v-model
163
+ * gets the same object. @invalid(reason, dp). ref → { value, set, clear, go, el }.
164
+ */
165
+ export const DateRange = mounted('DateRange', withDefault(C.dateRange), {
166
+ props: { ...anyProps('mode', 'months', 'min', 'max', 'disabled', 'count', 'minDays', 'maxDays', 'presets', 'locale', 'weekStart', 'words'), blockSpan: B, onChange: Function, onInvalid: Function },
167
+ model: { event: 'onChange' },
168
+ update: inPlace({
169
+ defaultValue: null,
170
+ value: (dp, v, next) => {
171
+ if (v === undefined) return;
172
+ const single = next.mode === 'single', want = rangeOf(v, single), now = rangeOf(dp.value, single);
173
+ if (want.start === now.start && want.end === now.end) return;
174
+ if (want.start == null) dp.clear(); else dp.set(single ? want.start : want);
175
+ },
176
+ }),
177
+ });
178
+
179
+ /**
180
+ * <TimePicker v-model="time" look="slots" min="09:00" max="18:00" :disabled="taken" />
181
+ * A wheel (default) or a grid of slots. @change(value, tp) with 'HH:MM'. ref → { value, set, setDisabled, format, el }.
182
+ * `disabled` (the taken times) is applied in place.
183
+ */
184
+ export const TimePicker = mounted('TimePicker', withDefault(C.timePicker), {
185
+ props: { ...anyProps('look', 'step', 'min', 'max', 'disabled', 'words'), hour12: B, onChange: Function },
186
+ model: { event: 'onChange' },
187
+ update: inPlace({
188
+ defaultValue: null,
189
+ disabled: (tp, v) => { tp.setDisabled(v ?? null); },
190
+ value: (tp, v, next) => {
191
+ if (v === undefined || (v ?? null) === tp.value) return;
192
+ if (v == null && next.look !== 'slots') return; // the wheel always shows a time
193
+ tp.set(v, { silent: true });
194
+ },
195
+ }),
196
+ });
197
+
198
+ /* ---------- text, email, sign-in ---------- */
199
+
200
+ /**
201
+ * <SubscribeForm icon="mail" :words="{ button: 'Join' }" @submit="(email) => api.join(email)" />
202
+ * @submit(email, sub) may return a Promise: resolve (a string replaces doneText), reject to show the error.
203
+ * default-value fills the field in to start with. ref → { value, state, setError, reset, el }.
204
+ */
205
+ export const SubscribeForm = mounted('SubscribeForm', withDefault(C.subscribeForm), {
206
+ props: { ...anyProps('defaultValue', 'name', 'icon', 'layout', 'validate', 'resetAfter', 'words'), onSubmit: Function },
207
+ update: inPlace({ defaultValue: null }),
208
+ });
209
+
210
+ /**
211
+ * <AuthForm v-model:mode="mode" :fields="{ confirm: true }" @submit="(values, mode) => signIn(values)" />
212
+ * The sign-in / create-account card. `mode` ('in' | 'up') is applied in place; or default-mode. Switching inside
213
+ * sets v-model:mode and calls @mode-change(mode, f). `values` fills the fields in when it mounts.
214
+ * ref → { mode, setMode, values, busy, setError, reset, el }.
215
+ */
216
+ export const AuthForm = mounted('AuthForm', withDefault(C.authForm, 'mode', 'defaultMode'), {
217
+ props: { ...anyProps('mode', 'defaultMode', 'fields', 'meter', 'min', 'values', 'validate', 'words'), onSubmit: Function, onModeChange: Function, onForgot: Function, 'onUpdate:mode': Function },
218
+ options: (o, props) => {
219
+ const x = { ...o };
220
+ delete x['onUpdate:mode'];
221
+ x.onModeChange = (m, f) => { props['onUpdate:mode']?.(m); return props.onModeChange?.(m, f); };
222
+ return x;
223
+ },
224
+ update: inPlace({
225
+ defaultMode: null,
226
+ values: null,
227
+ mode: (f, v) => { if (v && f.mode !== v) f.setMode(v); },
228
+ }),
229
+ });
230
+
231
+ const EYE_WORDS = { show: 'Show password', hide: 'Hide password' };
232
+ /** The eye with the slash (the same drawing as passwordToggle()). */
233
+ const eye = () => h('svg', { viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': 2, 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' }, [
234
+ h('path', { d: 'M2.5 12C4.7 8.1 8 6.2 12 6.2s7.3 1.9 9.5 5.8c-2.2 3.9-5.5 5.8-9.5 5.8S4.7 15.9 2.5 12z' }), h('circle', { cx: 12, cy: 12, r: 2.9 }),
235
+ h('path', { class: 'gk-pwm__cut', pathLength: 1, d: 'M4.6 4.2l15.2 15.6' }), h('path', { class: 'gk-pwm__slash', pathLength: 1, d: 'M4.6 4.2l15.2 15.6' }),
236
+ ]);
237
+
238
+ /**
239
+ * <PasswordToggle v-model="password" name="password" autocomplete="current-password" @toggle="(shown) => …" />
240
+ * A password field with the show / hide eye inside its right edge (same markup as passwordToggle(input)).
241
+ * v-model (or default-value) is the text; v-model:shown (or default-shown) and @toggle(shown) the eye.
242
+ * Every other attribute (name, placeholder, class, @blur…) goes on the <input>. ref → { input, focus() }.
243
+ */
244
+ export const PasswordToggle = defineComponent({
245
+ name: 'PasswordToggle',
246
+ inheritAttrs: false,
247
+ props: { ...modelProps(), shown: B, defaultShown: B, 'onUpdate:shown': Function, onToggle: Function, words: ANY, id: String },
248
+ setup(props, { attrs, expose }) {
249
+ const [text, setText] = useModel(props, { initial: '', event: null });
250
+ const [on, setOn] = useModel(props, { prop: 'shown', def: 'defaultShown', event: 'onToggle', initial: false });
251
+ const autoId = useId();
252
+ const input = ref(null), btn = ref(null);
253
+ expose({ input, focus: () => input.value?.focus() });
254
+ const lines = () => btn.value?.querySelectorAll('.gk-pwm__cut, .gk-pwm__slash') ?? [];
255
+ onMounted(() => {
256
+ let first = true;
257
+ watch(() => !!on.value, (v) => {
258
+ const l = lines();
259
+ M.g.killTweensOf(l);
260
+ if (first || M.RM()) M.g.set(l, { strokeDashoffset: v ? 0 : 1 });
261
+ else M.g.to(l, { strokeDashoffset: v ? 0 : 1, duration: v ? 0.34 : 0.22, ease: v ? 'power2.out' : 'power2.in' });
262
+ first = false;
263
+ }, { immediate: true, flush: 'post' });
264
+ });
265
+ onBeforeUnmount(() => { if (btn.value) M.g.killTweensOf([btn.value, ...btn.value.querySelectorAll('*')]); });
266
+ return () => {
267
+ const W = { ...EYE_WORDS, ...props.words };
268
+ const inputId = props.id ?? autoId;
269
+ return h('span', { class: 'gk-pwm__wrap' }, [
270
+ h('input', mergeProps({ class: 'gk-input' }, attrs, {
271
+ ref: input, id: inputId, type: on.value ? 'text' : 'password', value: text.value,
272
+ onInput: (e) => setText(e.target.value, e),
273
+ })),
274
+ h('button', {
275
+ ref: btn, type: 'button', class: ['gk-pwm__eye', on.value && 'gk-is-on'], 'aria-controls': inputId, 'aria-label': on.value ? W.hide : W.show,
276
+ onMousedown: (e) => e.preventDefault(), // a mouse click keeps the caret in the field
277
+ onClick: () => { M.pop(btn.value); setOn(!on.value); },
278
+ }, [eye()]),
279
+ ]);
280
+ };
281
+ },
282
+ });
283
+
284
+ const METER = ['rules', 'min', 'minScore', 'score', 'reveal', 'list', 'lock', 'words'];
285
+ /**
286
+ * <PasswordMeter v-model="pw" reveal :min="10" id="new-password" @change="(s) => (ok = s.valid)" />
287
+ * A password field with the strength meter after it (passwordMeter(input, options)). The meter's options are props;
288
+ * @change({ score, level, valid, rules }, pw) is the meter's. The text: v-model (or default-value), and
289
+ * @value-change(text, event). Every other attribute goes on the <input>.
290
+ * ref → { score, level, valid, rules, check(), reveal(on), input, root }.
291
+ */
292
+ export const PasswordMeter = defineComponent({
293
+ name: 'PasswordMeter',
294
+ inheritAttrs: false,
295
+ props: { ...modelProps(), ...anyProps('rules', 'min', 'minScore', 'score', 'words'), reveal: B, list: B, lock: B, onChange: Function, onValueChange: Function },
296
+ setup(props, { attrs, expose }) {
297
+ const [text, setText] = useModel(props, { initial: '', event: 'onValueChange' });
298
+ const input = ref(null), panel = ref(null);
299
+ let pw = null;
300
+ expose(live(() => pw));
301
+ /* what needs a new meter when it changes (functions are always called through the latest props) */
302
+ const opts = () => { const o = {}; for (const k of METER) if (props[k] !== undefined) o[k] = snap(props[k]); if (o.score) o.score = true; return o; };
303
+ const create = () => {
304
+ pw = C.passwordMeter(input.value, {
305
+ ...opts(), panel: panel.value,
306
+ rules: props.rules?.map((r, i) => ({ ...r, test: (v) => !!props.rules?.[i]?.test?.(v) })),
307
+ score: props.score ? (v, met) => props.score(v, met) : null,
308
+ onChange: (s, p) => props.onChange?.(s, p),
309
+ });
310
+ };
311
+ const destroy = () => { const p = pw; pw = null; p?.destroy(); };
312
+ onMounted(() => {
313
+ create();
314
+ watch(opts, (n, o) => { if (!same(n, o)) { destroy(); create(); } }, { deep: true, flush: 'post' });
315
+ watch(() => text.value, () => { pw?.check(); }, { flush: 'post' }); // a value set from code (e.g. cleared)
316
+ });
317
+ onBeforeUnmount(destroy);
318
+ return () => h('span', { style: { display: 'contents' }, 'data-gecko': 'PasswordMeter' }, [
319
+ h('input', mergeProps({ type: 'password', autocomplete: 'new-password', class: 'gk-input' }, attrs, {
320
+ ref: input, value: text.value, onInput: (e) => setText(e.target.value, e),
321
+ })),
322
+ h('span', { ref: panel, style: { display: 'contents' } }),
323
+ ]);
324
+ },
325
+ });
326
+
327
+ /* ---------- drawing and files ---------- */
328
+
329
+ const SignatureBase = mounted('SignaturePad', (el, o) => {
330
+ const { keep, ...opts } = o;
331
+ const s = C.signaturePad(el, opts);
332
+ const data = keep?.() ?? o.defaultValue;
333
+ if (s && data) s.fromJSON(data);
334
+ return s;
335
+ }, {
336
+ props: { ...anyProps('color', 'width', 'defaultValue', 'words', 'keep'), pressure: B, guide: B, tools: B, readOnly: B, onChange: Function, onEnd: Function },
337
+ update: inPlace({
338
+ keep: null,
339
+ defaultValue: (s, v) => { if (v && !same(v.strokes, s.toJSON().strokes)) s.fromJSON(v); },
340
+ }),
341
+ });
342
+ /**
343
+ * <SignaturePad ref="sig" @change="(empty) => (signed = !empty)" /> later: sig.value.toImage({ background: '#fff' })
344
+ * Every option of signaturePad(el, options). default-value: strokes saved with toJSON() (loaded again when it changes).
345
+ * Changing an option that needs a new pad (read-only, guide…) keeps what was signed.
346
+ * ref → { isEmpty, undo, clear, replay, toJSON, fromJSON, toImage, toSVG, el }.
347
+ */
348
+ export const SignaturePad = defineComponent({
349
+ name: 'SignaturePad',
350
+ inheritAttrs: false,
351
+ props: { onChange: Function },
352
+ setup(props, { attrs, expose }) {
353
+ const inner = shallowRef(null);
354
+ let last = null;
355
+ const keep = () => last;
356
+ const change = (empty, sig) => { last = empty ? null : sig.toJSON(); return props.onChange?.(empty, sig); };
357
+ expose(live(() => inner.value));
358
+ return () => h(SignatureBase, { ...attrs, keep, onChange: change, ref: inner });
359
+ },
360
+ });
361
+
362
+ /**
363
+ * <PhotoUpload v-model="bike.photos" :upload="(file, { progress, signal }) => send(file, progress, signal)" :max="8" />
364
+ * Tiles fly in, upload with a draining veil and can be dragged to reorder. v-model (or default-value) = the photos
365
+ * already uploaded ([{ url }]); it gets each photo's upload result, in order, after every change (ref.value).
366
+ * A new v-model value is shown with setValue() unless it equals what the piece holds.
367
+ * @change(items, up), @reject(file, reason, up), @uploaded(item, up), @error(item, error, up).
368
+ * ref → { items, value, busy, settled, add, remove, move, retry, clear, open, setValue, el }.
369
+ */
370
+ export const PhotoUpload = mounted('PhotoUpload', withDefault(C.photoUpload), {
371
+ props: { ...anyProps('accept', 'max', 'maxSize', 'upload', 'concurrent', 'resize', 'capture', 'words'), cover: B, sortable: B, readOnly: B, onChange: Function, onReject: Function, onUploaded: Function, onError: Function },
372
+ model: { event: 'onChange', arg: (items, up) => up.value },
373
+ update: inPlace({
374
+ defaultValue: null,
375
+ value: (up, v) => { if (v !== undefined && !same(v ?? [], up.value)) up.setValue(v ?? []); },
376
+ }),
377
+ });
378
+
379
+ /**
380
+ * <FileDrop accept=".pdf,image/*" :max-size="10 * 1024 * 1024" :upload="sendReceipt" @change="(files) => (receipts = files)" />
381
+ * A drop zone with a row per file. @change(files, fd), @error({ id, file, name, reason, message, error }, fd).
382
+ * ref → { files, value, busy, add, remove, retry, cancel, clear, browse, upload, el }.
383
+ */
384
+ export const FileDrop = mounted('FileDrop', C.fileDrop, {
385
+ props: { ...anyProps('accept', 'maxSize', 'maxFiles', 'upload', 'concurrent', 'words'), multiple: B, auto: B, compact: B, onChange: Function, onError: Function },
386
+ });
387
+
388
+ /* ---------- wizard ---------- */
389
+
390
+ const WizardBase = mounted('Wizard', (el, o) => {
391
+ const { onPanels, index, ...opts } = o;
392
+ const wz = C.wizard(el, { ...opts, start: index ?? opts.start });
393
+ onPanels?.(wz ? [...el.querySelectorAll('.gk-wz__panel:not(.gk-wz__fin) > .gk-wz__body')] : []);
394
+ return wz;
395
+ }, {
396
+ props: { ...anyProps('steps', 'index', 'start', 'header', 'level', 'label', 'words'), linear: B, onStep: Function, onFinish: Function, onPanels: Function },
397
+ update: inPlace({
398
+ start: null,
399
+ index: (wz, v) => { if (v != null && wz.index !== +v) wz.go(+v); },
400
+ }),
401
+ });
402
+ /**
403
+ * <Wizard v-model:index="step" :steps="[{ id: 'bike', title: 'Bike' }, { id: 'pay', title: 'Payment', validate }]"
404
+ * :words="{ finish: 'Book' }" @finish="(values) => book(values)">
405
+ * <template #bike><BikePicker /></template>
406
+ * <template #pay="{ index }">…</template>
407
+ * </Wizard>
408
+ * Each step's content is the slot named after its id (or the #step="{ step, index }" slot for every step, or the
409
+ * step's `content` text), teleported into its panel. validate(panel, wz) → true | 'message' | Promise.
410
+ * v-model:index (applied with go(), without checking) or start. @step(index, wz), @finish(values, wz).
411
+ * ref → { index, values, finished, go, next, back, reset, setBusy, el }.
412
+ */
413
+ export const Wizard = defineComponent({
414
+ name: 'Wizard',
415
+ inheritAttrs: false,
416
+ props: { steps: { type: Array, default: () => [] }, index: ANY, 'onUpdate:index': Function, onStep: Function },
417
+ setup(props, { attrs, slots, expose }) {
418
+ const inner = shallowRef(null);
419
+ const bodies = shallowRef([]);
420
+ expose(live(() => inner.value));
421
+ const onPanels = (b) => { bodies.value = b; };
422
+ const onStep = (i, wz) => { props['onUpdate:index']?.(i); return props.onStep?.(i, wz); };
423
+ return () => {
424
+ const plain = props.steps.map(({ content, validate, ...s }, i) => ({
425
+ ...s, ...(validate ? { validate: (panel, wz) => props.steps[i]?.validate?.(panel, wz) ?? true } : {}),
426
+ }));
427
+ return [
428
+ h(WizardBase, { ...attrs, key: 'wz', steps: plain, index: props.index, onPanels, onStep, ref: inner }),
429
+ ...bodies.value.map((b, i) => {
430
+ const s = props.steps[i]; if (!b || !s) return null;
431
+ const slot = (s.id != null && slots[s.id]) || slots.step;
432
+ const kids = slot ? slot({ step: s, index: i }) : s.content != null ? String(s.content) : null;
433
+ return kids == null ? null : h(Teleport, { to: b, key: 'p' + String(s.id ?? i) }, Array.isArray(kids) ? kids : [kids]);
434
+ }),
435
+ ];
436
+ };
437
+ },
438
+ });
439
+
440
+ /* ---------- validation (a pattern, not a piece) ---------- */
441
+
442
+ const okMsg = (m) => (m == null || m === true || m === false || m === '' ? '' : String(m));
443
+ /**
444
+ * const v = useValidation({ email: (value) => (/^\S+@\S+\.\S+$/.test(value) ? '' : 'That email looks incomplete.') })
445
+ * <label :class="['field', { 'is-bad': v.errors.email }]"><span>Email</span>
446
+ * <input class="gk-input" v-bind="v.field('email')" />
447
+ * <small class="gk-field__hint">{{ v.errors.email || 'We send one email a month.' }}</small></label>
448
+ * <Button @click="v.validate() && send(v.values())">Join</Button>
449
+ * A rule gets (value, values) and returns '' (fine) or the message. validate() marks every bad field, shakes it and
450
+ * returns true when all are fine; with live (default) a red field is checked again on every key.
451
+ * errors is reactive. Call it in setup().
452
+ */
453
+ export function useValidation(rules, { live: liveCheck = true, shake = true } = {}) {
454
+ const errors = reactive({});
455
+ const els = {}, cache = {}, shakes = new Set();
456
+ const ruleSet = () => rules || {};
457
+ const valueOf = (k) => { const el = els[k]; return !el ? '' : el.type === 'checkbox' ? el.checked : el.value ?? ''; };
458
+ const values = () => Object.fromEntries(Object.keys(ruleSet()).map((k) => [k, valueOf(k)]));
459
+ const messageOf = (k, all) => { const r = ruleSet()[k]; return r ? okMsg(r(valueOf(k), all)) : ''; };
460
+ const set = (k, m) => { if ((errors[k] || '') === m) return; if (m) errors[k] = m; else delete errors[k]; };
461
+ const check = (k) => { const m = messageOf(k, values()); set(k, m); return !m; };
462
+ const validate = (names) => {
463
+ const all = values(), keys = names ?? Object.keys(ruleSet()), bad = {};
464
+ keys.forEach((k) => { const m = messageOf(k, all); if (m) bad[k] = m; });
465
+ keys.forEach((k) => set(k, bad[k] || ''));
466
+ if (shake) Object.keys(bad).forEach((k) => { if (els[k]) { const tw = M.shake(els[k]); if (tw) shakes.add(tw); } });
467
+ return !Object.keys(bad).length;
468
+ };
469
+ const field = (name) => {
470
+ const c = cache[name] ||= {
471
+ name,
472
+ ref: (el) => { const node = el && el.$el !== undefined ? el.$el : el; if (node) els[name] = node; else delete els[name]; },
473
+ onInput: () => { if (liveCheck && errors[name]) check(name); },
474
+ };
475
+ return { ...c, 'aria-invalid': errors[name] ? true : undefined };
476
+ };
477
+ const setError = (k, m) => set(k, okMsg(m));
478
+ const reset = () => { Object.keys(errors).forEach((k) => delete errors[k]); };
479
+ if (getCurrentInstance()) onBeforeUnmount(() => { shakes.forEach((tw) => tw?.kill?.()); shakes.clear(); });
480
+ return { errors, field, validate, check, setError, reset, values };
481
+ }
@@ -0,0 +1,127 @@
1
+ import type { Ref } from 'vue';
2
+ import type { GeckoComponent, EnhancerProps, DefaultSlot } from './core.js';
3
+
4
+ /* ---------------- Rise ---------------- */
5
+
6
+ export interface RiseProps {
7
+ /** Element to render ('div'). */
8
+ as?: string;
9
+ /** rise: fade in and float up · slide: from a side · deal: drop in tilted · reveal: small fade-down of the element itself. */
10
+ kind?: 'rise' | 'slide' | 'deal' | 'reveal';
11
+ /** A selector inside: animate the matches instead of the direct children. */
12
+ items?: string;
13
+ /** px it comes from below (rise 26, slide 12; reveal -4 = from above). */
14
+ y?: number;
15
+ /** slide: px it comes from the side (0; below 0 = from the left). */
16
+ x?: number;
17
+ /** Seconds between items (rise 0.06, slide 0.04, deal 0.07). */
18
+ stagger?: number;
19
+ /** Seconds before it starts on mount (0). */
20
+ delay?: number;
21
+ /** Seconds per item (rise 0.8, slide 0.55). */
22
+ duration?: number;
23
+ /** deal: degrees the cards start tilted (2.5). */
24
+ tilt?: number;
25
+ /** Children added later arrive the same way (true). */
26
+ animateNew?: boolean;
27
+ }
28
+ /** <Rise class="gk-grid">…cards…</Rise> — the children arrive one after another (rise / slide / deal / reveal). */
29
+ export const Rise: GeckoComponent<RiseProps, DefaultSlot>;
30
+
31
+ /* ---------------- Magnetic & Lift ---------------- */
32
+
33
+ export interface MagneticOptions {
34
+ /** Share of the pointer's sideways distance it moves (0.2). */
35
+ strength?: number;
36
+ /** Share of the pointer's up / down distance it moves (0.28). */
37
+ strengthY?: number;
38
+ /** A multiplier for this element (data-magnet). */
39
+ magnet?: number;
40
+ }
41
+ /** <Magnetic><Button>Book</Button></Magnetic> — leans toward the pointer (mouse / trackpad). Renders a <span> unless `as`. */
42
+ export const Magnetic: GeckoComponent<EnhancerProps<MagneticOptions>, DefaultSlot>;
43
+
44
+ export interface LiftOptions {
45
+ /** px it moves on hover (-4; the value goes on data-lift). */
46
+ y?: number;
47
+ }
48
+ /** <Lift as="article" :y="-6">…</Lift> — rises a few pixels on hover (mouse / trackpad). */
49
+ export const Lift: GeckoComponent<EnhancerProps<LiftOptions>, DefaultSlot>;
50
+
51
+ /* ---------------- Tilt ---------------- */
52
+
53
+ export interface TiltOptions {
54
+ /** Degrees at the card's edge (12). */
55
+ max?: number;
56
+ /** Size while the pointer is on it (1.03). */
57
+ scale?: number;
58
+ /** px of 3D depth; smaller = stronger (900). */
59
+ perspective?: number;
60
+ /** A soft light that follows the pointer (true). Colour: --gk-tilt-glare. */
61
+ glare?: boolean;
62
+ /** How far data-depth layers drift, as a share of their depth (0.25). */
63
+ parallax?: number;
64
+ /** Seconds the card takes to catch up with the pointer (0.35). */
65
+ follow?: number;
66
+ /** Seconds it takes to settle back (1). */
67
+ spring?: number;
68
+ }
69
+ /** <Tilt :max="12" glare class="gk-card">…children with data-depth…</Tilt> */
70
+ export const Tilt: GeckoComponent<EnhancerProps<TiltOptions>, DefaultSlot>;
71
+
72
+ /* ---------------- Spotlight ---------------- */
73
+
74
+ export interface SpotlightOptions {
75
+ /** The cards: a selector inside, or elements (default: the children). */
76
+ items?: string | Element[];
77
+ /** px across the light (240). */
78
+ size?: number;
79
+ /** Seconds the light takes to catch up with the pointer; 0 = glued to it (0.2). */
80
+ follow?: number;
81
+ /** Light up the edges (true). */
82
+ border?: boolean;
83
+ /** A faint glow inside the cards (true). */
84
+ fill?: boolean;
85
+ /** A focused card pulls the light onto itself (true). */
86
+ focus?: boolean;
87
+ }
88
+ /** <Spotlight class="plans">…cards…</Spotlight> — a light follows the pointer across the cards. */
89
+ export const Spotlight: GeckoComponent<EnhancerProps<SpotlightOptions>, DefaultSlot>;
90
+
91
+ /* ---------------- Marquee ---------------- */
92
+
93
+ export interface MarqueeProps {
94
+ /** Element to render ('div'). */
95
+ as?: string;
96
+ /** The list element ('ul'; items become <li>, with any other tag <div>). */
97
+ listAs?: 'ul' | 'ol' | 'div';
98
+ /** Pixels per second (50). */
99
+ speed?: number;
100
+ /** Which way it slides ('left'). */
101
+ direction?: 'left' | 'right';
102
+ /** Hover or keyboard focus slows it to a stop (true). */
103
+ pauseOnHover?: boolean;
104
+ /** Space between items: px, or any CSS length (default --gk-marquee-gap, 40px). */
105
+ gap?: number | string;
106
+ /** Soften the left and right edges (true). */
107
+ fade?: boolean;
108
+ /** A button that pauses and plays (element, template ref, component or selector); it gets aria-pressed and a label. */
109
+ button?: Element | string | Ref<Element | null | undefined> | { $el: Element } | null;
110
+ /** The button's labels. */
111
+ words?: { pause?: string; play?: string };
112
+ /** Stop it (true) and let it go on (false). */
113
+ paused?: boolean;
114
+ }
115
+ export interface MarqueeHandle {
116
+ play(): void;
117
+ pause(): void;
118
+ toggle(): void;
119
+ readonly paused: boolean;
120
+ /** Measure again. */
121
+ refresh(): void;
122
+ readonly el: HTMLElement;
123
+ }
124
+ /** <Marquee aria-label="Partners">…items…</Marquee> — an endless sideways strip; each child is one item. Template ref → MarqueeHandle. */
125
+ export const Marquee: GeckoComponent<MarqueeProps, DefaultSlot>;
126
+
127
+ export {};