@gecko-ui-kit/react 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,403 @@
1
+ 'use client';
2
+ /* Form pieces from @gecko-ui-kit/components (multi-select, combobox, tags, sliders, rating, radio cards,
3
+ subscribe, password, sign-in, signature, uploads, pricing, date and time pickers, wizard).
4
+ Most are mounted pieces: the vanilla code builds them inside one element; these components pass props in
5
+ as options, keep `value` in step through the piece's own set(), and clean up on unmount.
6
+ PasswordToggle is drawn by React; Wizard draws your React step content into its panels through portals;
7
+ useValidation is a small hook for the red-field pattern (.gk-field.gk-is-bad + hint + shake). */
8
+ import { forwardRef, useId, useRef, useState, useCallback, useImperativeHandle, Fragment } from 'react';
9
+ import { createPortal } from 'react-dom';
10
+ import * as C from '@gecko-ui-kit/components';
11
+ import * as M from '@gecko-ui-kit/motion';
12
+ import { h, cx, mounted, same, useLatest, useControllable, useIsoLayoutEffect } from './core.js';
13
+
14
+ /* ---------- helpers ---------- */
15
+
16
+ /** An update for mounted(): apply changed props through the handle's own methods, in the order of `map`.
17
+ map: { prop: (handle, value, next, prev) => false | void } — null means "nothing to do" (e.g. defaultValue).
18
+ Any other prop that changed mounts the piece again. */
19
+ const inPlace = (map) => (hd, next, prev, el) => {
20
+ const changed = [...new Set([...Object.keys(next), ...Object.keys(prev)])].filter((k) => !same(next[k], prev[k]));
21
+ if (!changed.every((k) => k in map)) return false;
22
+ for (const k of Object.keys(map)) if (changed.includes(k) && map[k] && map[k](hd, next[k], next, prev, el) === false) return false;
23
+ return true;
24
+ };
25
+ /** Mount with `value` (controlled) or else `defaultValue` as the vanilla `value` option. */
26
+ const withDefault = (mount, key = 'value', from = 'defaultValue') => (el, o) => {
27
+ const x = { ...o }; delete x[from];
28
+ if (x[key] === undefined) { delete x[key]; if (o[from] !== undefined) x[key] = o[from]; } // undefined would hide the piece's own default
29
+ return mount(el, x);
30
+ };
31
+ /** A ref value that forwards to whatever the current handle is (stays the same object). */
32
+ function liveHandle(cur, extra = {}) {
33
+ return new Proxy({}, {
34
+ get(_, k) {
35
+ if (k in extra) return extra[k]();
36
+ const x = cur.current; if (!x) return undefined;
37
+ const v = x[k]; return typeof v === 'function' ? v.bind(x) : v;
38
+ },
39
+ has(_, k) { return k in extra || (!!cur.current && k in cur.current); },
40
+ });
41
+ }
42
+ const str = (v) => (v == null ? '' : String(v));
43
+
44
+ /* ---------- choosing ---------- */
45
+
46
+ /**
47
+ * <MultiSelect options={people} value={ids} onChange={setIds} max={3} creatable placeholder="Assign to…" />
48
+ * Every option of multiSelect(el, options). onChange(values, options, ms). ref → { value, selected, set, add, remove,
49
+ * clear, open, close, focus, setOptions, el }. Changing `value` or `options` updates it in place.
50
+ */
51
+ export const MultiSelect = mounted('MultiSelect', withDefault(C.multiSelect), {
52
+ update: inPlace({
53
+ defaultValue: null,
54
+ options: (ms, v) => { ms.setOptions(v ?? []); },
55
+ value: (ms, v) => { if (v !== undefined && !same(ms.value, (v ?? []).map(String))) ms.set(v ?? []); },
56
+ }),
57
+ });
58
+
59
+ /**
60
+ * <Combobox options={countries} value={country} onChange={(v) => setCountry(v)} label="Country" />
61
+ * or source={async (q, { signal }) => fetch(…)} to ask your server. onChange(value, option, cb), onInput(text, cb).
62
+ * ref → { value, option, isOpen, set, clear, open, close, focus, setOptions, el }.
63
+ */
64
+ export const Combobox = mounted('Combobox', withDefault(C.combobox), {
65
+ update: inPlace({
66
+ defaultValue: null,
67
+ options: (cb, v) => { cb.setOptions(v ?? []); },
68
+ value: (cb, v) => {
69
+ if (v === undefined) return;
70
+ const want = v == null || v === '' ? null : typeof v === 'object' ? str(v.value ?? v.label) : String(v);
71
+ if (cb.value !== want) cb.set(v ?? null);
72
+ },
73
+ }),
74
+ });
75
+
76
+ /**
77
+ * <TagsInput value={tags} onChange={setTags} suggestions={['design', 'bug']} max={5} />
78
+ * Every option of tagsInput(el, options). onChange(tags, ti). ref → { value, add, remove, clear, set, focus, el }.
79
+ */
80
+ export const TagsInput = mounted('TagsInput', withDefault(C.tagsInput), {
81
+ update: inPlace({
82
+ defaultValue: null,
83
+ value: (ti, v) => { if (v !== undefined && !same(ti.value, (v ?? []).map(String))) ti.set(v ?? []); },
84
+ }),
85
+ });
86
+
87
+ /* ---------- numbers ---------- */
88
+
89
+ /**
90
+ * <RangeSlider min={0} max={2000} step={50} value={price} onChange={setPrice} label="Price per day" histogram={bars} />
91
+ * onInput(value, rs) while dragging, onChange(value, rs) when it settles; value = [low, high]. ref → { value, set, el }.
92
+ */
93
+ export const RangeSlider = mounted('RangeSlider', withDefault(C.rangeSlider), {
94
+ update: inPlace({
95
+ defaultValue: null,
96
+ value: (rs, v) => { if (Array.isArray(v) && !same(rs.value, v.map(Number))) rs.set(v, { silent: true }); },
97
+ }),
98
+ });
99
+
100
+ /**
101
+ * <Stepper value={days} onChange={setDays} min={1} max={30} unit={(n) => (n === 1 ? 'day' : 'days')} />
102
+ * The digits roll like an odometer. onChange(value, st). ref → { value, set, stepBy, setRange, el }.
103
+ */
104
+ export const Stepper = mounted('Stepper', withDefault(C.stepper), {
105
+ update: inPlace({
106
+ defaultValue: null,
107
+ min: (st, _, next) => { st.setRange({ min: next.min ?? -Infinity, max: next.max ?? Infinity }); },
108
+ max: (st, _, next) => { st.setRange({ min: next.min ?? -Infinity, max: next.max ?? Infinity }); },
109
+ value: (st, v) => { if (v != null && Number.isFinite(+v) && +v !== st.value) st.set(+v, { silent: true }); },
110
+ }),
111
+ });
112
+
113
+ /**
114
+ * <Rating value={score} onChange={setScore} max={5} half labels={['Bad', …, 'Great']} />
115
+ * Every option of rating(el, options) is a prop. onChange(value, handle). ref → { value, set(n), setReadOnly(b), el }.
116
+ * A new `value` (or `readOnly`) is applied in place, without calling onChange.
117
+ */
118
+ export const Rating = mounted('Rating', withDefault(C.rating), {
119
+ update: inPlace({
120
+ defaultValue: null,
121
+ readOnly: (r, v) => { r.setReadOnly(!!v); },
122
+ value: (r, v) => { if (v !== undefined && (+v || 0) !== r.value) r.set(+v || 0, { silent: true }); },
123
+ }),
124
+ });
125
+
126
+ /**
127
+ * <RadioCards label="Delivery" value={how} onChange={setHow} options={[{ value: 'std', title: 'Standard', desc: '3–5 days', price: 'Free' }, …]} />
128
+ * Real radio buttons drawn as cards. onChange(value, option, plan). ref → { value, set, focus, el }.
129
+ */
130
+ export const RadioCards = mounted('RadioCards', withDefault(C.radioCards), {
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 plans={plans} value={period} onChange={setPeriod} onSelect={(plan, period) => checkout(plan.id, period)} />
139
+ * The period switch rolls every price. onChange(periodId, prices), onSelect(plan, periodId, prices).
140
+ * ref → { period, set(id), el }.
141
+ */
142
+ export const PricingToggle = mounted('PricingToggle', withDefault(C.pricingToggle), {
143
+ update: inPlace({
144
+ defaultValue: null,
145
+ value: (p, v) => { if (v && v !== p.period) p.set(v, { silent: true }); },
146
+ }),
147
+ });
148
+
149
+ /* ---------- dates and times ---------- */
150
+
151
+ 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));
152
+ const rangeOf = (v, single) => {
153
+ if (v == null) return { start: null, end: null };
154
+ if (typeof v === 'string' || v instanceof Date) return { start: ymd(v), end: single ? ymd(v) : null };
155
+ return { start: ymd(v.start), end: ymd(v.end ?? (single ? v.start : null)) };
156
+ };
157
+
158
+ /**
159
+ * <DateRange value={{ start: '2026-12-04', end: '2026-12-07' }} onChange={(r) => setDates(r)} min={today} disabled={booked} />
160
+ * mode="single" picks one date. onChange({ start, end, count }, dp) — end is null until the end is picked.
161
+ * onInvalid(reason, dp). ref → { value, set, clear, go, el }.
162
+ */
163
+ export const DateRange = mounted('DateRange', withDefault(C.dateRange), {
164
+ update: inPlace({
165
+ defaultValue: null,
166
+ value: (dp, v, next) => {
167
+ if (v === undefined) return;
168
+ const single = next.mode === 'single', want = rangeOf(v, single), now = rangeOf(dp.value, single);
169
+ if (want.start === now.start && want.end === now.end) return;
170
+ if (want.start == null) dp.clear(); else dp.set(single ? want.start : want);
171
+ },
172
+ }),
173
+ });
174
+
175
+ /**
176
+ * <TimePicker look="slots" value={time} onChange={setTime} min="09:00" max="18:00" disabled={taken} />
177
+ * A wheel (default) or a grid of slots. onChange(value, tp) with 'HH:MM'. ref → { value, set, setDisabled, format, el }.
178
+ */
179
+ export const TimePicker = mounted('TimePicker', withDefault(C.timePicker), {
180
+ update: inPlace({
181
+ defaultValue: null,
182
+ disabled: (tp, v) => { tp.setDisabled(v ?? null); },
183
+ value: (tp, v, next) => {
184
+ if (v === undefined || (v ?? null) === tp.value) return;
185
+ if (v == null && next.look !== 'slots') return; // the wheel always shows a time
186
+ tp.set(v, { silent: true });
187
+ },
188
+ }),
189
+ });
190
+
191
+ /* ---------- text, email, sign-in ---------- */
192
+
193
+ /**
194
+ * <SubscribeForm icon="mail" onSubmit={(email) => api.join(email)} words={{ button: 'Join' }} />
195
+ * onSubmit(email, sub) may return a Promise: resolve (a string replaces doneText), reject to show the error.
196
+ * defaultValue fills the field in to start with. ref → { value, state, setError, reset, el }.
197
+ */
198
+ export const SubscribeForm = mounted('SubscribeForm', withDefault(C.subscribeForm), {
199
+ update: inPlace({ defaultValue: null }),
200
+ });
201
+
202
+ /**
203
+ * <AuthForm mode={mode} onModeChange={setMode} onSubmit={(values, mode) => signIn(values)} fields={{ confirm: true }} />
204
+ * The sign-in / create-account card. `mode` ('in' | 'up') is applied in place; or defaultMode.
205
+ * `values` fills the fields in when it mounts. ref → { mode, setMode, values, busy, setError, reset, el }.
206
+ */
207
+ export const AuthForm = mounted('AuthForm', withDefault(C.authForm, 'mode', 'defaultMode'), {
208
+ update: inPlace({
209
+ defaultMode: null,
210
+ values: null,
211
+ mode: (f, v) => { if (v && f.mode !== v) f.setMode(v); },
212
+ }),
213
+ });
214
+
215
+ /** The eye with the slash (the same drawing as passwordToggle()). */
216
+ const EYE = h('svg', { viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true },
217
+ 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 }),
218
+ h('path', { className: 'gk-pwm__cut', pathLength: 1, d: 'M4.6 4.2l15.2 15.6' }), h('path', { className: 'gk-pwm__slash', pathLength: 1, d: 'M4.6 4.2l15.2 15.6' }));
219
+ const EYE_WORDS = { show: 'Show password', hide: 'Hide password' };
220
+
221
+ /**
222
+ * <PasswordToggle name="password" autoComplete="current-password" onToggle={(shown) => …} />
223
+ * A password field with the show / hide eye inside its right edge (same markup as passwordToggle(input)).
224
+ * shown / defaultShown / onToggle(shown). Every other prop goes on the <input>; ref → the <input>.
225
+ */
226
+ export const PasswordToggle = forwardRef(function PasswordToggle({ shown, defaultShown = false, onToggle, words, id, className, ...rest }, ref) {
227
+ const [on, setOn] = useControllable(shown, defaultShown, onToggle);
228
+ const autoId = useId(), inputId = id ?? autoId;
229
+ const W = { ...EYE_WORDS, ...words };
230
+ const btn = useRef(null), first = useRef(true);
231
+ useIsoLayoutEffect(() => {
232
+ const lines = btn.current.querySelectorAll('.gk-pwm__cut, .gk-pwm__slash');
233
+ M.g.killTweensOf(lines);
234
+ if (first.current || M.RM()) M.g.set(lines, { strokeDashoffset: on ? 0 : 1 });
235
+ else M.g.to(lines, { strokeDashoffset: on ? 0 : 1, duration: on ? 0.34 : 0.22, ease: on ? 'power2.out' : 'power2.in' });
236
+ first.current = false;
237
+ }, [on]);
238
+ useIsoLayoutEffect(() => () => M.g.killTweensOf(btn.current?.querySelectorAll('*') ?? []), []);
239
+ return h('span', { className: 'gk-pwm__wrap' },
240
+ h('input', { ref, id: inputId, ...rest, type: on ? 'text' : 'password', className: cx('gk-input', className) }),
241
+ h('button', {
242
+ ref: btn, type: 'button', className: cx('gk-pwm__eye', on && 'gk-is-on'), 'aria-controls': inputId, 'aria-label': on ? W.hide : W.show,
243
+ onMouseDown: (e) => e.preventDefault(), // a mouse click keeps the caret in the field
244
+ onClick: () => { M.pop(btn.current); setOn(!on); },
245
+ }, EYE));
246
+ });
247
+
248
+ const METER = ['rules', 'min', 'minScore', 'score', 'reveal', 'list', 'lock', 'words'];
249
+ /**
250
+ * <PasswordMeter value={pw} onValueChange={setPw} reveal onChange={(s) => setOk(s.valid)} id="new-password" />
251
+ * A password field with the strength meter after it (passwordMeter(input, options)). The meter's options are props;
252
+ * onChange({ score, level, valid, rules }, pw) is the meter's. The text: value / defaultValue / onValueChange(text, event).
253
+ * Every other prop goes on the <input>. ref → { score, level, valid, rules, check(), reveal(on), input, root }.
254
+ */
255
+ export const PasswordMeter = forwardRef(function PasswordMeter(props, ref) {
256
+ const { onChange, value, defaultValue, onValueChange, className, ...rest } = props;
257
+ const opts = {}, inputProps = {};
258
+ for (const k in rest) (METER.includes(k) ? opts : inputProps)[k] = rest[k];
259
+ const input = useRef(null), panel = useRef(null), cur = useRef(null);
260
+ const latest = useLatest({ ...opts, onChange });
261
+ /* what needs a new meter when it changes (functions are always called through the latest props) */
262
+ const key = { ...opts, score: !!opts.score, rules: opts.rules?.map(({ test, ...r }) => r) };
263
+ const stable = useRef(key); if (!same(stable.current, key)) stable.current = key;
264
+ const proxy = useRef(null); if (!proxy.current) proxy.current = liveHandle(cur);
265
+ useImperativeHandle(ref, () => proxy.current, []);
266
+ useIsoLayoutEffect(() => {
267
+ const o = latest.current;
268
+ const pw = C.passwordMeter(input.current, {
269
+ ...stable.current, panel: panel.current,
270
+ rules: o.rules?.map((r, i) => ({ ...r, test: (v) => !!latest.current.rules?.[i]?.test?.(v) })),
271
+ score: o.score ? (v, met) => latest.current.score(v, met) : null,
272
+ onChange: (s, p) => latest.current.onChange?.(s, p),
273
+ });
274
+ cur.current = pw;
275
+ return () => { cur.current = null; pw?.destroy(); };
276
+ }, [stable.current]);
277
+ useIsoLayoutEffect(() => { cur.current?.check(); }, [value]); // a value set from code (e.g. cleared)
278
+ return h('span', { style: { display: 'contents' }, 'data-gecko': 'PasswordMeter' },
279
+ h('input', {
280
+ ref: input, type: 'password', autoComplete: 'new-password', ...inputProps, className: cx('gk-input', className),
281
+ ...(value !== undefined ? { value } : { defaultValue }),
282
+ onChange: (e) => onValueChange?.(e.target.value, e),
283
+ }),
284
+ h('span', { ref: panel, style: { display: 'contents' }, suppressHydrationWarning: true }));
285
+ });
286
+
287
+ /* ---------- drawing and files ---------- */
288
+
289
+ const SignatureBase = mounted('SignaturePad', (el, o) => {
290
+ const s = C.signaturePad(el, o);
291
+ const data = o.keep?.() ?? o.defaultValue;
292
+ if (s && data) s.fromJSON(data);
293
+ return s;
294
+ }, {
295
+ update: inPlace({
296
+ keep: null,
297
+ defaultValue: (s, v) => { if (v && !same(v.strokes, s.toJSON().strokes)) s.fromJSON(v); },
298
+ }),
299
+ });
300
+ /**
301
+ * <SignaturePad onChange={(empty) => setSigned(!empty)} ref={sig} /> later: sig.current.toImage({ background: '#fff' })
302
+ * Every option of signaturePad(el, options). defaultValue: strokes saved with toJSON() (loaded again when it changes).
303
+ * Changing an option that needs a new pad (readOnly, guide…) keeps what was signed.
304
+ * ref → { isEmpty, undo, clear, replay, toJSON, fromJSON, toImage, toSVG, el }.
305
+ */
306
+ export const SignaturePad = forwardRef(function SignaturePad({ onChange, ...props }, ref) {
307
+ const last = useRef(null), cb = useLatest(onChange);
308
+ const keep = useCallback(() => last.current, []);
309
+ const change = useCallback((empty, sig) => { last.current = empty ? null : sig.toJSON(); cb.current?.(empty, sig); }, []);
310
+ return h(SignatureBase, { ...props, onChange: change, keep, ref });
311
+ });
312
+
313
+ /**
314
+ * <PhotoUpload upload={(file, { progress, signal }) => send(file, progress, signal)} max={8} defaultValue={bike.photos} />
315
+ * Tiles fly in, upload with a draining veil and can be dragged to reorder. value / defaultValue = photos already
316
+ * uploaded ([{ url }]); a new `value` is shown with setValue() unless it equals what the piece holds.
317
+ * onChange(items, up), onReject(file, reason, up), onUploaded(item, up), onError(item, error, up).
318
+ * ref → { items, value, busy, settled, add, remove, move, retry, clear, open, setValue, el }.
319
+ */
320
+ export const PhotoUpload = mounted('PhotoUpload', withDefault(C.photoUpload), {
321
+ update: inPlace({
322
+ defaultValue: null,
323
+ value: (up, v) => { if (v !== undefined && !same(v ?? [], up.value)) up.setValue(v ?? []); },
324
+ }),
325
+ });
326
+
327
+ /**
328
+ * <FileDrop accept=".pdf,image/*" maxSize={10 * 1024 * 1024} upload={sendReceipt} onChange={(files) => setFiles(files)} />
329
+ * A drop zone with a row per file. onChange(files, fd), onError({ id, file, name, reason, message, error }, fd).
330
+ * ref → { files, value, busy, add, remove, retry, cancel, clear, browse, upload, el }.
331
+ */
332
+ export const FileDrop = mounted('FileDrop', C.fileDrop);
333
+
334
+ /* ---------- wizard ---------- */
335
+
336
+ const WizardBase = mounted('Wizard', (el, o) => {
337
+ const wz = C.wizard(el, { ...o, start: o.index ?? o.start });
338
+ o.onPanels?.(wz ? [...wz.el.querySelectorAll('.gk-wz__panel:not(.gk-wz__fin) > .gk-wz__body')] : []);
339
+ return wz;
340
+ }, {
341
+ update: inPlace({
342
+ start: null,
343
+ index: (wz, v) => { if (v != null && wz.index !== +v) wz.go(+v); },
344
+ }),
345
+ });
346
+ /**
347
+ * <Wizard steps={[{ id: 'bike', title: 'Bike', content: <BikeStep /> }, { id: 'pay', title: 'Payment', content: <Pay />, validate }]}
348
+ * onFinish={(values) => book(values)} words={{ finish: 'Book' }} />
349
+ * Each step's `content` is any React node, drawn into its panel. validate(panel, wz) → true | 'message' | Promise.
350
+ * index (controlled step, applied with go()) or start. onStep(index, wz), onFinish(values, wz).
351
+ * ref → { index, values, finished, go, next, back, reset, setBusy, el }.
352
+ */
353
+ export const Wizard = forwardRef(function Wizard({ steps = [], ...props }, ref) {
354
+ const [bodies, setBodies] = useState([]);
355
+ const latest = useLatest(steps);
356
+ const plain = steps.map(({ content, validate, ...s }, i) => ({
357
+ ...s, ...(validate ? { validate: (panel, wz) => latest.current[i]?.validate?.(panel, wz) ?? true } : {}),
358
+ }));
359
+ return h(Fragment, null,
360
+ h(WizardBase, { ...props, steps: plain, onPanels: setBodies, ref }),
361
+ bodies.map((b, i) => (b && steps[i]?.content != null ? createPortal(steps[i].content, b, String(steps[i].id ?? i)) : null)));
362
+ });
363
+
364
+ /* ---------- validation (a pattern, not a piece) ---------- */
365
+
366
+ const okMsg = (m) => (m == null || m === true || m === false || m === '' ? '' : String(m));
367
+ /**
368
+ * const v = useValidation({ email: (value) => (/^\S+@\S+\.\S+$/.test(value) ? '' : 'That email looks incomplete.') })
369
+ * <label className={cx('field', v.errors.email && 'is-bad')}><span>Email</span>
370
+ * <input className="gk-input" {...v.field('email')} />
371
+ * <small className="gk-field__hint">{v.errors.email || 'We send one email a month.'}</small></label>
372
+ * <Button onClick={() => v.validate() && send(v.values())}>Join</Button>
373
+ * A rule gets (value, values) and returns '' (fine) or the message. validate() marks every bad field, shakes it and
374
+ * returns true when all are fine; with live (default) a red field is checked again on every key.
375
+ */
376
+ export function useValidation(rules, { live = true, shake = true } = {}) {
377
+ const [errors, setErrors] = useState({});
378
+ const els = useRef({}), cache = useRef({});
379
+ const latest = useLatest({ rules, live, shake, errors });
380
+ const valueOf = (k) => { const el = els.current[k]; return !el ? '' : el.type === 'checkbox' ? el.checked : el.value ?? ''; };
381
+ const values = useCallback(() => Object.fromEntries(Object.keys(latest.current.rules || {}).map((k) => [k, valueOf(k)])), []);
382
+ const messageOf = (k, all) => { const r = latest.current.rules?.[k]; return r ? okMsg(r(valueOf(k), all)) : ''; };
383
+ const set = (k, m) => setErrors((e) => { if ((e[k] || '') === m) return e; const n = { ...e }; if (m) n[k] = m; else delete n[k]; return n; });
384
+ const check = useCallback((k) => { const m = messageOf(k, values()); set(k, m); return !m; }, []);
385
+ const validate = useCallback((names) => {
386
+ const all = values(), keys = names ?? Object.keys(latest.current.rules || {}), bad = {};
387
+ keys.forEach((k) => { const m = messageOf(k, all); if (m) bad[k] = m; });
388
+ setErrors((e) => { const n = { ...e }; keys.forEach((k) => { if (bad[k]) n[k] = bad[k]; else delete n[k]; }); return n; });
389
+ if (latest.current.shake) Object.keys(bad).forEach((k) => els.current[k] && M.shake(els.current[k]));
390
+ return !Object.keys(bad).length;
391
+ }, []);
392
+ const field = (name) => {
393
+ const c = cache.current[name] ||= {
394
+ name,
395
+ ref: (el) => { if (el) els.current[name] = el; else if (els.current[name]) delete els.current[name]; },
396
+ onInput: () => { if (latest.current.live && latest.current.errors[name]) check(name); },
397
+ };
398
+ return { ...c, 'aria-invalid': errors[name] ? true : undefined };
399
+ };
400
+ const setError = useCallback((k, m) => set(k, okMsg(m)), []);
401
+ const reset = useCallback(() => setErrors({}), []);
402
+ return { errors, field, validate, check, setError, reset, values };
403
+ }
@@ -0,0 +1,130 @@
1
+ import type * as React from 'react';
2
+ import type { EnhancerProps } from './core.js';
3
+
4
+ /* ---------------- Rise ---------------- */
5
+
6
+ export interface RiseProps extends React.HTMLAttributes<HTMLElement> {
7
+ /** Element to render ('div'). */
8
+ as?: React.ElementType;
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
+ children?: React.ReactNode;
28
+ }
29
+ /** <Rise>{cards}</Rise> — the children arrive one after another (rise / slide / deal / reveal). ref → the element. */
30
+ export const Rise: React.ForwardRefExoticComponent<RiseProps & React.RefAttributes<HTMLElement>>;
31
+
32
+ /* ---------------- Magnetic & Lift ---------------- */
33
+
34
+ export interface MagneticOptions {
35
+ /** Share of the pointer's sideways distance it moves (0.2). */
36
+ strength?: number;
37
+ /** Share of the pointer's up / down distance it moves (0.28). */
38
+ strengthY?: number;
39
+ /** A multiplier for this element (data-magnet). */
40
+ magnet?: number;
41
+ }
42
+ /** <Magnetic><Button>Book</Button></Magnetic> — leans toward the pointer (mouse / trackpad). ref → the element. */
43
+ export const Magnetic: React.ForwardRefExoticComponent<EnhancerProps<MagneticOptions> & React.RefAttributes<HTMLElement>>;
44
+
45
+ export interface LiftOptions {
46
+ /** px it moves on hover (-4; the value goes on data-lift). */
47
+ y?: number;
48
+ }
49
+ /** <Lift as="article" y={-6}>…</Lift> — rises a few pixels on hover (mouse / trackpad). ref → the element. */
50
+ export const Lift: React.ForwardRefExoticComponent<EnhancerProps<LiftOptions> & React.RefAttributes<HTMLElement>>;
51
+
52
+ /* ---------------- Tilt ---------------- */
53
+
54
+ export interface TiltOptions {
55
+ /** Degrees at the card's edge (12). */
56
+ max?: number;
57
+ /** Size while the pointer is on it (1.03). */
58
+ scale?: number;
59
+ /** px of 3D depth; smaller = stronger (900). */
60
+ perspective?: number;
61
+ /** A soft light that follows the pointer (true). Colour: --gk-tilt-glare. */
62
+ glare?: boolean;
63
+ /** How far data-depth layers drift, as a share of their depth (0.25). */
64
+ parallax?: number;
65
+ /** Seconds the card takes to catch up with the pointer (0.35). */
66
+ follow?: number;
67
+ /** Seconds it takes to settle back (1). */
68
+ spring?: number;
69
+ }
70
+ /** <Tilt max={12} glare className="gk-card">…children with data-depth…</Tilt> */
71
+ export const Tilt: React.ForwardRefExoticComponent<EnhancerProps<TiltOptions> & React.RefAttributes<HTMLElement>>;
72
+
73
+ /* ---------------- Spotlight ---------------- */
74
+
75
+ export interface SpotlightOptions {
76
+ /** The cards: a selector inside, or elements (default: the children). */
77
+ items?: string | Element[];
78
+ /** px across the light (240). */
79
+ size?: number;
80
+ /** Seconds the light takes to catch up with the pointer; 0 = glued to it (0.2). */
81
+ follow?: number;
82
+ /** Light up the edges (true). */
83
+ border?: boolean;
84
+ /** A faint glow inside the cards (true). */
85
+ fill?: boolean;
86
+ /** A focused card pulls the light onto itself (true). */
87
+ focus?: boolean;
88
+ }
89
+ /** <Spotlight>{cards}</Spotlight> — a light follows the pointer across the cards. ref → the element. */
90
+ export const Spotlight: React.ForwardRefExoticComponent<EnhancerProps<SpotlightOptions> & React.RefAttributes<HTMLElement>>;
91
+
92
+ /* ---------------- Marquee ---------------- */
93
+
94
+ export interface MarqueeProps extends React.HTMLAttributes<HTMLElement> {
95
+ /** Element to render ('div'). */
96
+ as?: React.ElementType;
97
+ /** The list element ('ul'; items become <li>, with any other tag <div>). */
98
+ listAs?: 'ul' | 'ol' | 'div';
99
+ /** Pixels per second (50). */
100
+ speed?: number;
101
+ /** Which way it slides ('left'). */
102
+ direction?: 'left' | 'right';
103
+ /** Hover or keyboard focus slows it to a stop (true). */
104
+ pauseOnHover?: boolean;
105
+ /** Space between items: px, or any CSS length (default --gk-marquee-gap, 40px). */
106
+ gap?: number | string;
107
+ /** Soften the left and right edges (true). */
108
+ fade?: boolean;
109
+ /** A button that pauses and plays (element, ref or selector); it gets aria-pressed and a label. */
110
+ button?: Element | string | React.RefObject<Element | null> | null;
111
+ /** The button's labels. */
112
+ words?: { pause?: string; play?: string };
113
+ /** Stop it (true) and let it go on (false). */
114
+ paused?: boolean;
115
+ /** The items: each child becomes one. */
116
+ children?: React.ReactNode;
117
+ }
118
+ export interface MarqueeHandle {
119
+ play(): void;
120
+ pause(): void;
121
+ toggle(): void;
122
+ readonly paused: boolean;
123
+ /** Measure again. */
124
+ refresh(): void;
125
+ readonly el: HTMLElement;
126
+ }
127
+ /** <Marquee aria-label="Partners">{logos}</Marquee> — an endless sideways strip. ref → the handle. */
128
+ export const Marquee: React.ForwardRefExoticComponent<MarqueeProps & React.RefAttributes<MarqueeHandle>>;
129
+
130
+ export {};