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