@gecko-ui-kit/components 0.0.0-stage → 0.20.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/index.js ADDED
@@ -0,0 +1,198 @@
1
+ /* @gecko-ui-kit/components — HTML builders + behaviours.
2
+ Builders return HTML strings (drop them into innerHTML). After inserting, call bindAll(root)
3
+ to wire up segmented controls, switches, checkboxes, tabs and hover effects, and
4
+ animateBits(root) to play meters, rings, steps and count-ups. */
5
+ import { icon } from '@gecko-ui-kit/icons';
6
+ import * as M from '@gecko-ui-kit/motion';
7
+
8
+ const { $$ } = M;
9
+ export const esc = M.esc;
10
+ const attrs = (a) => (a ? ' ' + a : '');
11
+
12
+ /* ---------------- builders ---------------- */
13
+ /** btn('Save', { variant: 'primary'|'dark'|'ghost', size: 'sm', icon: 'check', block, magnetic, attrs }) */
14
+ export const btn = (label, { variant = '', size = '', icon: ic, iconRight, block = false, magnetic = false, cls = '', type = 'button', attrs: a = '' } = {}) =>
15
+ `<button type="${type}" class="btn ${variant ? 'btn--' + variant : ''} ${size ? 'btn--' + size : ''} ${block ? 'btn--block' : ''} ${magnetic ? 'magnetic' : ''} ${cls}"${attrs(a)}>${ic ? icon(ic) : ''}${label ? `<span>${label}</span>` : ''}${iconRight ? icon(iconRight) : ''}</button>`;
16
+ export const iconBtn = (ic, label, { size = '', cls = '', attrs: a = '' } = {}) =>
17
+ `<button type="button" class="iconbtn ${size ? 'iconbtn--' + size : ''} ${cls}" aria-label="${esc(label)}"${attrs(a)}>${icon(ic)}</button>`;
18
+ /** tag('Active', 'good'|'warn'|'bad'|'accent'|'plain', dot = true) */
19
+ export const tag = (txt, tone = 'plain', dot = true) => `<span class="tag tag--${tone}">${dot ? '<i></i>' : ''}${esc(txt)}</span>`;
20
+ export const badge = (n, tone = '') => `<span class="badge ${tone ? 'badge--' + tone : ''}">${n}</span>`;
21
+ /** av({ name, ini, tone }, 'sm'|'lg', online) — tone: indigo teal rose amber violet green slate sky */
22
+ export const av = (p, size = '', online = false) => p
23
+ ? `<span class="av av--${p.tone || 'indigo'} ${size ? 'av--' + size : ''}" title="${esc(p.name)}">${esc(p.ini ?? initials(p.name))}${online ? '<i class="av__on"></i>' : ''}</span>`
24
+ : `<span class="av av--open ${size ? 'av--' + size : ''}">${icon('plus')}</span>`;
25
+ export const initials = (name = '') => name.split(/\s+/).filter(Boolean).slice(0, 2).map((w) => w[0]).join('').toUpperCase();
26
+ export const avs = (people, max = 4) => `<span class="avs">${people.slice(0, max).map((p) => av(p, 'sm')).join('')}${people.length > max ? `<span class="av av--sm av--more">+${people.length - max}</span>` : ''}</span>`;
27
+ export const cell = (p, sub) => `<span class="cell">${av(p)}<span class="cell__text"><b>${esc(p?.name ?? '')}</b>${sub !== undefined ? `<small>${esc(sub)}</small>` : ''}</span></span>`;
28
+ /** card({ title, sub, right, body, flush, lift }) */
29
+ export const card = ({ title, sub = '', right = '', body = '', flush = false, lift = false, cls = '' } = {}) =>
30
+ `<section class="card ${flush ? 'card--flush' : ''} ${cls}"${lift ? ' data-lift' : ''}>${title ? chead(title, sub, right) : ''}${body}</section>`;
31
+ export const chead = (title, sub, right = '') => `<div class="chead"><div class="chead__text"><h2>${title}</h2>${sub ? `<p>${sub}</p>` : ''}</div>${right ? `<div class="chead__right">${right}</div>` : ''}</div>`;
32
+ export const kpi = (label, value, sub = '', cls = '') => `<div class="kpi ${cls}"><small>${label}</small><b>${value}</b>${sub ? `<span class="kpi__sub">${sub}</span>` : ''}</div>`;
33
+ /** A number that counts up when animateBits/countAll runs: num(1234, '฿', '', 0) */
34
+ export const num = (v, pre = '', suf = '', dec = 0) => `<span data-count="${v}" data-pre="${esc(pre)}" data-suf="${esc(suf)}" data-dec="${dec}">${esc(pre)}0${esc(suf)}</span>`;
35
+ /** seg('view', [['list','List','list'], ['grid','Grid','cards']], 'list') */
36
+ export const seg = (name, opts, value, { size = '' } = {}) => `<div class="seg ${size ? 'seg--' + size : ''}" data-seg="${esc(name)}" role="group"><span class="seg__thumb"></span>${opts.map((o) => { const [id, label, ic] = Array.isArray(o) ? o : [o, o]; return `<button type="button" data-v="${esc(id)}" aria-pressed="${id === value}">${ic ? icon(ic) : ''}${esc(label)}</button>`; }).join('')}</div>`;
37
+ export const sw = (on, label = '', a = '') => `<button type="button" class="switch" role="switch" aria-checked="${!!on}" aria-label="${esc(label)}"${attrs(a)}><i></i></button>`;
38
+ export const chk = (on, label = '', a = '') => `<button type="button" class="check" role="checkbox" aria-checked="${!!on}" aria-label="${esc(label)}"${attrs(a)}>${icon('check')}</button>`;
39
+ /** meter(0.7, 'good'|'warn'|'bad') — fills when animateBits runs */
40
+ export const meter = (f, tone = '') => `<span class="meter ${tone ? 'is-' + tone : ''}"><i data-f="${f}" style="transform:scaleX(0)"></i></span>`;
41
+ export const ring = (f, size = 56, stroke = 6, label = '') => { const r = (size - stroke) / 2, len = 2 * Math.PI * r; return `<span class="ring" style="width:${size}px;height:${size}px"><svg viewBox="0 0 ${size} ${size}"><circle cx="${size / 2}" cy="${size / 2}" r="${r}" stroke-width="${stroke}" class="ring__bg"/><circle cx="${size / 2}" cy="${size / 2}" r="${r}" stroke-width="${stroke}" class="ring__fg" data-len="${len}" data-f="${f}" stroke-dasharray="${len}" stroke-dashoffset="${len}"/></svg><b>${label}</b></span>`; };
42
+ export const steps = (labels, now) => `<ol class="steps">${labels.map((l, i) => `<li class="${i < now ? 'is-done' : i === now ? 'is-now' : ''}"><span class="steps__dot">${icon('check')}</span>${i < labels.length - 1 ? '<span class="steps__bar"><i class="steps__fill" style="transform:scaleX(0)"></i></span>' : ''}<small>${esc(l)}</small></li>`).join('')}</ol>`;
43
+ export const empty = (ic, title, body = '', action = '') => `<div class="empty"><span class="empty__icon">${icon(ic)}</span><b>${title}</b>${body ? `<p>${body}</p>` : ''}${action}</div>`;
44
+ /** tabs([['a','Overview'], ['b','Activity', 3]], 'a') — buttons; bindTabs makes the line follow */
45
+ export const tabs = (items, value, { name = 'tabs' } = {}) => `<div class="tabs" role="tablist" data-tabs="${esc(name)}"><span class="tabs__line"></span>${items.map(([id, label, count]) => `<button type="button" role="tab" data-v="${esc(id)}" aria-selected="${id === value}">${esc(label)}${count ? badge(count) : ''}</button>`).join('')}</div>`;
46
+ export const chips = (items, value, { name = 'chips', multi = false } = {}) => `<div class="chips" data-chips="${esc(name)}"${multi ? ' data-multi' : ''}>${items.map((o) => { const [id, label, ic] = Array.isArray(o) ? o : [o, o]; const on = multi ? (value || []).includes(id) : id === value; return `<button type="button" class="chip" data-v="${esc(id)}" aria-pressed="${on}">${ic ? icon(ic) : ''}${esc(label)}</button>`; }).join('')}</div>`;
47
+ export const field = (label, control, hint = '') => `<label class="field"><span>${label}</span>${control}${hint ? `<small class="field__hint">${hint}</small>` : ''}</label>`;
48
+ export const input = ({ value = '', placeholder = '', type = 'text', a = '' } = {}) => `<input class="input" type="${type}" value="${esc(value)}" placeholder="${esc(placeholder)}"${attrs(a)}>`;
49
+ export const select = (opts, v = '', a = '') => `<select class="input"${attrs(a)}>${opts.map((o) => { const [id, label] = Array.isArray(o) ? o : [o, o]; return `<option value="${esc(id)}" ${id === v ? 'selected' : ''}>${esc(label)}</option>`; }).join('')}</select>`;
50
+ /** Slider: range({ min, max, step, value, a }) — filled track, springy thumb (bindRanges keeps the fill in step). */
51
+ export const range = ({ min = 0, max = 100, step = 1, value = 50, a = '' } = {}) => `<input type="range" class="range" min="${min}" max="${max}" step="${step}" value="${value}"${attrs(a)}>`;
52
+ /** Colour picker drawn as a round swatch. */
53
+ export const swatch = (value = '#5b4cf0', a = '') => `<input type="color" class="swatch" value="${esc(value)}"${attrs(a)}>`;
54
+ export const searchbox = (placeholder = 'Search…') => `<label class="searchbox">${icon('search')}<input class="input" placeholder="${esc(placeholder)}" aria-label="${esc(placeholder)}"></label>`;
55
+
56
+ /* ---------------- behaviours ---------------- */
57
+ /* Each binder wires an element once, but every call may add its own onChange,
58
+ so a page can listen to a control that the app shell has already wired. */
59
+ const hook = (el, fn) => { const first = !el.__on; el.__on ||= []; if (fn && !el.__on.includes(fn)) el.__on.push(fn); return first; };
60
+ const fire = (el, ...args) => el.__on.forEach((fn) => fn(...args));
61
+ /** Segmented control: stretchy thumb follows the pressed button. onChange(name, value, button) */
62
+ export const bindSeg = (root, onChange) => $$(root.matches?.('.seg') ? [root] : $$('.seg', root)).forEach((s) => {
63
+ if (!hook(s, onChange)) return;
64
+ const th = s.querySelector('.seg__thumb'); const cur = () => s.querySelector('[aria-pressed="true"]');
65
+ M.indicator(th, cur(), { animate: false, radius: 99 }); M.trackIndicator(th, cur, { radius: 99 });
66
+ s.addEventListener('click', (e) => {
67
+ const b = e.target.closest('button[data-v]'); if (!b || b.getAttribute('aria-pressed') === 'true') return;
68
+ s.querySelectorAll('button[data-v]').forEach((x) => x.setAttribute('aria-pressed', x === b));
69
+ M.pop(b); M.indicator(th, b, { radius: 99 }); fire(s, s.dataset.seg, b.dataset.v, b);
70
+ });
71
+ });
72
+ /** Tabs: the underline stretches to the selected tab. onChange(name, value, button) */
73
+ export const bindTabs = (root, onChange) => $$(root.matches?.('.tabs') ? [root] : $$('.tabs[data-tabs]', root)).forEach((t) => {
74
+ if (!hook(t, onChange)) return;
75
+ const line = t.querySelector('.tabs__line'); const cur = () => t.querySelector('[aria-selected="true"], [aria-current="page"]');
76
+ M.indicator(line, cur(), { animate: false, radius: 2, line: true }); M.trackIndicator(line, cur, { radius: 2, line: true });
77
+ t.addEventListener('click', (e) => {
78
+ const b = e.target.closest('[data-v]'); if (!b || b.getAttribute('aria-selected') === 'true') return;
79
+ t.querySelectorAll('[data-v]').forEach((x) => x.setAttribute('aria-selected', x === b));
80
+ M.indicator(line, b, { radius: 2, line: true }); fire(t, t.dataset.tabs, b.dataset.v, b);
81
+ });
82
+ });
83
+ export const bindChips = (root, onChange) => $$('.chips[data-chips]', root).forEach((c) => {
84
+ if (!hook(c, onChange)) return; const multi = c.hasAttribute('data-multi');
85
+ c.addEventListener('click', (e) => {
86
+ const b = e.target.closest('.chip[data-v]'); if (!b) return;
87
+ if (multi) b.setAttribute('aria-pressed', b.getAttribute('aria-pressed') !== 'true');
88
+ else { if (b.getAttribute('aria-pressed') === 'true') return; c.querySelectorAll('.chip').forEach((x) => x.setAttribute('aria-pressed', x === b)); }
89
+ M.pop(b); fire(c, c.dataset.chips, multi ? $$('.chip[aria-pressed="true"]', c).map((x) => x.dataset.v) : b.dataset.v, b);
90
+ });
91
+ });
92
+ export const bindSwitches = (root, onChange) => $$(root.matches?.('.switch') ? [root] : $$('.switch', root)).forEach((b) => {
93
+ if (!hook(b, onChange)) return; M.switchKnob(b, b.getAttribute('aria-checked') === 'true', false);
94
+ b.addEventListener('click', () => { const on = b.getAttribute('aria-checked') !== 'true'; b.setAttribute('aria-checked', on); M.switchKnob(b, on); fire(b, b, on); });
95
+ });
96
+ export const bindChecks = (root, onChange) => $$(root.matches?.('.check') ? [root] : $$('.check', root)).forEach((b) => {
97
+ if (!hook(b, onChange)) return;
98
+ b.addEventListener('click', (e) => { e.stopPropagation(); const on = b.getAttribute('aria-checked') !== 'true'; b.setAttribute('aria-checked', on); M.pop(b); fire(b, b, on); });
99
+ });
100
+ /** Play meters, rings, steps and count-ups inside root. */
101
+ export const animateBits = (root) => {
102
+ $$('.meter > i', root).forEach((i, k) => M.meter(i, +i.dataset.f, 0.15 + k * 0.03));
103
+ $$('.ring__fg', root).forEach((c) => M.ring(c, +c.dataset.f));
104
+ $$('.steps', root).forEach((s) => M.steps(s, $$('li.is-done', s).length, -1));
105
+ M.countAll(root);
106
+ };
107
+ /** Sliders: keep the filled part of the track in step with the value; it fills up from zero when first shown. */
108
+ const rangeP = (r) => { const min = +r.min || 0, max = r.max === '' ? 100 : +r.max; return ((+r.value - min) / ((max - min) || 1)) * 100; };
109
+ export const bindRanges = (root) => $$(root.matches?.('.range') ? [root] : $$('.range', root)).forEach((r) => {
110
+ if (r.__rng) return; r.__rng = true;
111
+ const set = () => { M.g.killTweensOf(r); r.style.setProperty('--p', rangeP(r) + '%'); };
112
+ r.addEventListener('input', set);
113
+ if (M.RM()) set(); else M.g.fromTo(r, { '--p': '0%' }, { '--p': rangeP(r) + '%', duration: 0.9, ease: 'expo.out' });
114
+ r.__sync = set;
115
+ });
116
+ /** Colour swatches give a small pop when a colour is picked. */
117
+ export const bindSwatches = (root) => $$(root.matches?.('.swatch') ? [root] : $$('.swatch', root)).forEach((s) => {
118
+ if (s.__swt) return; s.__swt = true;
119
+ s.addEventListener('change', () => M.pop(s));
120
+ });
121
+ /** Extra binders other packages plug in (e.g. @gecko-ui-kit/overlays upgrades <select> into an animated dropdown). */
122
+ export const enhancers = [];
123
+ export const enhance = (fn) => { if (!enhancers.includes(fn)) enhancers.push(fn); };
124
+ /** Wire everything inside root. handlers: { seg, tabs, chips, sw, chk, otp } */
125
+ export const bindAll = (root, h = {}) => { bindSeg(root, h.seg); bindTabs(root, h.tabs); bindChips(root, h.chips); bindSwitches(root, h.sw); bindChecks(root, h.chk); _bindOtp(root, h.otp); bindRanges(root); bindSwatches(root); M.lift(root); M.magnetic(root); enhancers.forEach((fn) => fn(root)); };
126
+
127
+ export { icon };
128
+ /** Data grid: search, filter, sort, pages and edit-in-place. See src/grid.js. */
129
+ export { grid } from './src/grid.js';
130
+ /** Booking timeline: rows × days, bars you drag, stretch and undo. See src/timeline.js. */
131
+ export { timeline } from './src/timeline.js';
132
+ /** Swipe actions: slide a list row to show buttons behind it; a long swipe runs the edge one. See src/swipe.js. */
133
+ export { swipeItem, swipeActions } from './src/swipe.js';
134
+ /** Date range picker: a month calendar for one date or a start and an end. See src/daterange.js. */
135
+ export { dateRange, formatRange } from './src/daterange.js';
136
+ /** Kanban board: drag cards between columns and up and down, with limits and keyboard moves. See src/kanban.js. */
137
+ export { kanban } from './src/kanban.js';
138
+ /** Signature pad: sign with a finger, pen or mouse; undo, clear, replay, PNG/SVG/JSON. See src/signature.js. */
139
+ export { signaturePad } from './src/signature.js';
140
+
141
+ export { photoUpload } from './src/upload.js';
142
+
143
+ export { multiSelect } from './src/multiselect.js';
144
+
145
+ export { timePicker, formatTime } from './src/timepicker.js';
146
+
147
+ export { stepper } from './src/stepper.js';
148
+ /** Notification feed: grouped by day, unread dots, mark all as read, new ones slide in, row buttons. See src/notifications.js. */
149
+ export { notifications } from './src/notifications.js';
150
+ /** Accordion: headings that open to show more; one or many open, find-in-page, filter with highlights. See src/accordion.js. */
151
+ export { accordion } from './src/accordion.js';
152
+ /** Rating: pick or show a score with stars or hearts; halves, hover preview, drag on touch, partial fill read-only. See src/rating.js. */
153
+ export { rating } from './src/rating.js';
154
+ /** Carousel: swipe, drag or step through slides; stretchy dots that fill with autoplay; peek and focus looks. See src/carousel.js. */
155
+ export { carousel } from './src/carousel.js';
156
+ /** Tree view: nested items that open and close; stretchy selection, tri-state checkboxes, lazy branches, filter. See src/tree.js. */
157
+ export { tree } from './src/tree.js';
158
+ /** Range slider: two thumbs on one track; drag either, press the track or drag the middle; optional histogram, marks and number boxes. See src/rangeslider.js. */
159
+ export { rangeSlider } from './src/rangeslider.js';
160
+ /** Tags input: type or paste words and each becomes a tag; suggestions, max, no repeats, validate. See src/tagsinput.js. */
161
+ export { tagsInput } from './src/tagsinput.js';
162
+ /** Pagination: page numbers or “Page 3 of 24”, a stretchy current-page highlight, “21–30 of 240” and a page-size list. See src/pagination.js. */
163
+ export { pagination, pageWindow } from './src/pagination.js';
164
+ /** Breadcrumbs: the path to the current page; long paths fold into “…”, a new path slides in like a route change. See src/breadcrumbs.js. */
165
+ export { breadcrumbs } from './src/breadcrumbs.js';
166
+ /** combobox(el, { options | source, value, clearable, allowCustom, minChars, … }) — type to search, pick one; ARIA 1.2 combobox with a stretchy highlight. */
167
+ export { combobox } from './src/combobox.js';
168
+ /** fileDrop(el, { accept, multiple, maxSize, maxFiles, upload, auto, compact, … }) — a drop zone with a row per file, progress, retry and reasons. */
169
+ export { fileDrop } from './src/filedrop.js';
170
+ /** Skeleton: grey placeholders (list, cards, text, table or your own data-sk markup) with one shared shimmer; reveal() cross-fades into the content. See src/skeleton.js. */
171
+ export { skeleton, skeletonHtml } from './src/skeleton.js';
172
+ /** Alert / banner: a message in the page (info, good, warn, bad); grows open, update() changes it in place, close() folds it away. See src/alert.js. */
173
+ export { alert } from './src/alert.js';
174
+ /** Line / area chart: lines draw in, crosshair + tooltip snap to points, legend toggles rescale, update() morphs. See src/linechart.js. */
175
+ export { lineChart } from './src/linechart.js';
176
+ /** Virtual list: thousands of rows with only the visible ones in the page; fixed or measured rows, listbox keys, smooth scrollTo. See src/virtuallist.js. */
177
+ export { virtualList } from './src/virtuallist.js';
178
+ /** Month calendar: events as chips and bars across days, “+2 more”, drag to another day, sliding months. See src/calendar.js. */
179
+ export { calendar } from './src/calendar.js';
180
+ /** Wizard: a form in steps; panels slide, the progress line fills, Next checks each step (async too), a success panel draws its tick. See src/wizard.js. */
181
+ export { wizard } from './src/wizard.js';
182
+ /** Donut chart: slices draw in one by one, hover / focus lifts a slice and shows its share in the middle, set() morphs. See src/donut.js. */
183
+ export { donut } from './src/donut.js';
184
+ /** Goal gauge: half-circle dial, the arc fills, the needle swings with an overshoot and the number counts; set() swings from where it is. See src/gauge.js. */
185
+ export { gauge } from './src/gauge.js';
186
+ /** Password strength: bars that fill and change colour, rules that tick off, a padlock that clicks shut; passwordToggle is the show / hide eye. See src/password.js. */
187
+ export { passwordMeter, passwordToggle } from './src/password.js';
188
+ /** Sign in / create account card: sliding switch, fields that grow in for sign-up, strength meter, rolling submit label, checks + shake, busy spinner. See src/authform.js. */
189
+ export { authForm } from './src/authform.js';
190
+ /** spinner({ size, tone, speed, track, label, stack, words, decorative }) — orbit loader HTML: a comet with a glowing head circles a ring (pure CSS, breathes under reduced motion). See src/spinner.js. */
191
+ export { spinner } from './src/spinner.js';
192
+ /** Calendar heatmap: busy days as shaded squares (weeks × weekdays), a gliding hover card, grid keys, set() re-shades in a ripple. See src/heatmap.js. */
193
+ export { heatmap } from './src/heatmap.js';
194
+ /** Leaderboard: ranked rows with bars; set() glides rows to their new ranks, counts numbers, flashes climbers (“▲2”). See src/leaderboard.js. */
195
+ export { leaderboard } from './src/leaderboard.js';
196
+ /** Code field (one-time code / PIN). See src/otp.js. */
197
+ export { otp, bindOtp, otpState, otpClear, otpValue } from './src/otp.js';
198
+ import { bindOtp as _bindOtp } from './src/otp.js';
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@gecko-ui-kit/components",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.20.0",
4
+ "description": "Buttons, inputs, password strength, sign in / sign up, combobox, tags input, range slider, file drop, segmented, switch, tabs, pagination, breadcrumbs, tags, avatars, cards, tables, data grid, virtual list, tree view, calendar, heatmap, leaderboard, line, donut and gauge charts, code field, sliders, colour swatches, meters, rings, steps, wizard, skeleton, spinner, alerts.",
5
+ "keywords": [
6
+ "vanilla-js",
7
+ "ui",
8
+ "components",
9
+ "ui",
10
+ "gsap"
11
+ ],
12
+ "homepage": "https://woraphondev.github.io/UI-Package/playground/",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/WoraphonDev/UI-Package.git",
16
+ "directory": "packages/components"
17
+ },
18
+ "bugs": "https://github.com/WoraphonDev/UI-Package/issues",
19
+ "type": "module",
20
+ "license": "MIT",
21
+ "sideEffects": [
22
+ "*.css"
23
+ ],
24
+ "exports": {
25
+ ".": "./index.js",
26
+ "./style.css": "./style.css"
27
+ },
28
+ "files": [
29
+ "*.js",
30
+ "*.css",
31
+ "src/",
32
+ "README.md"
33
+ ],
34
+ "dependencies": {
35
+ "@gecko-ui-kit/icons": "^0.3.0",
36
+ "@gecko-ui-kit/motion": "^0.8.0"
37
+ },
38
+ "peerDependencies": {
39
+ "gsap": "^3.12.0"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
43
+ }
44
+ }
@@ -0,0 +1,208 @@
1
+ /* Accordion: a list of headings that open to show more. The panel grows to its height while its
2
+ content drops in; the chevron turns with a small overshoot (or a plus folds into a minus).
3
+ With one-at-a-time, the open one closes as the next opens, and the heading you clicked stays
4
+ where it was on screen instead of jumping up. Closed panels use hidden="until-found", so the
5
+ browser's find-in-page can still open them. filter(text) hides what doesn't match and marks hits. */
6
+ import * as M from '@gecko-ui-kit/motion';
7
+ import { icon } from '@gecko-ui-kit/icons';
8
+ import { esc } from '../index.js';
9
+
10
+ const { g, RM, $$ } = M;
11
+ const HID = typeof document !== 'undefined' && 'onbeforematch' in document.body ? 'until-found' : true;
12
+ let uid = 0;
13
+
14
+ /**
15
+ * const acc = accordion(el, {
16
+ * items: [{ id, title, sub, body, content, icon, badge, open, disabled }],
17
+ * // body is HTML (trusted); content is a Node to move in. No items? <details> inside el are used.
18
+ * multiple: false, // false: opening one closes the others
19
+ * collapsible: true, // false: one always stays open
20
+ * look: 'lines' | 'cards',
21
+ * marker: 'chevron' | 'plus',
22
+ * level: 3, // heading level around each button
23
+ * onToggle(id, open, acc)
24
+ * })
25
+ * acc.value (open ids) · acc.isOpen(id) · acc.open(id) · acc.close(id) · acc.toggle(id)
26
+ * acc.openAll() · acc.closeAll() · acc.filter(text, { open }) → matches · acc.destroy()
27
+ */
28
+ export const accordion = (el, opts = {}) => {
29
+ el = $$(el)[0];
30
+ if (!el) return null;
31
+ const o = { items: null, multiple: false, collapsible: true, look: 'lines', marker: 'chevron', level: 3, onToggle: null, ...opts };
32
+ const ac = new AbortController(), on = (t, ev, fn, x) => t.addEventListener(ev, fn, { signal: ac.signal, ...x });
33
+ const base = `acc${++uid}`;
34
+
35
+ /* items: given, or read from <details><summary> already in the page */
36
+ let src = o.items;
37
+ if (!src) {
38
+ src = [...el.querySelectorAll(':scope > details')].map((d, i) => {
39
+ const sum = d.querySelector(':scope > summary'), frag = document.createDocumentFragment();
40
+ [...d.childNodes].filter((n) => n !== sum).forEach((n) => frag.append(n));
41
+ return { id: d.id || `${i + 1}`, titleHtml: sum?.innerHTML ?? '', content: frag, open: d.open };
42
+ });
43
+ }
44
+ const level = Math.min(6, Math.max(1, +o.level || 3));
45
+ const markerHtml = o.marker === 'plus'
46
+ ? '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 12h12"/><path class="acc__v" d="M12 6v12"/></svg>'
47
+ : icon('down');
48
+
49
+ el.innerHTML = `<div class="acc acc--${o.look === 'cards' ? 'cards' : 'lines'} acc--${o.marker === 'plus' ? 'plus' : 'chevron'}"></div>`;
50
+ const root = el.firstElementChild;
51
+ const list = src.map((it, i) => {
52
+ const id = String(it.id ?? i + 1), hid = `${base}-h${i}`, pid = `${base}-p${i}`;
53
+ const item = document.createElement('div');
54
+ item.className = 'acc__item'; item.dataset.id = id;
55
+ const title = it.titleHtml ?? esc(it.title ?? '');
56
+ item.innerHTML = `<h${level} class="acc__h"><button type="button" class="acc__btn" id="${hid}" aria-controls="${pid}" aria-expanded="false"${it.disabled ? ' disabled' : ''}>`
57
+ + `${it.icon ? `<span class="acc__lead">${icon(it.icon)}</span>` : ''}`
58
+ + `<span class="acc__t"><span class="acc__title">${title}</span>${it.sub ? `<small class="acc__sub">${esc(it.sub)}</small>` : ''}</span>`
59
+ + `${it.badge != null && it.badge !== '' ? `<span class="acc__badge">${esc(it.badge)}</span>` : ''}`
60
+ + `<span class="acc__mk">${markerHtml}</span></button></h${level}>`
61
+ + `<div class="acc__panel" id="${pid}" role="region" aria-labelledby="${hid}"><div class="acc__body">${it.body ?? ''}</div></div>`;
62
+ const body = item.querySelector('.acc__body');
63
+ if (it.content) body.append(it.content);
64
+ root.append(item);
65
+ const x = { id, el: item, btn: item.querySelector('.acc__btn'), panel: item.querySelector('.acc__panel'), body, mk: item.querySelector('.acc__mk'), open: false, disabled: !!it.disabled, out: false };
66
+ x.panel.hidden = HID;
67
+ return x;
68
+ });
69
+ const byId = (id) => list.find((x) => x.id === String(id));
70
+
71
+ /* ---------- keep the clicked heading still while things above it close ---------- */
72
+ let anchor = null;
73
+ const scrollerOf = (n) => {
74
+ for (let p = n.parentElement; p && p !== document.body; p = p.parentElement) {
75
+ const s = getComputedStyle(p).overflowY;
76
+ if ((s === 'auto' || s === 'scroll') && p.scrollHeight > p.clientHeight) return p;
77
+ }
78
+ return document.scrollingElement || document.documentElement;
79
+ };
80
+ const pin = (x) => {
81
+ const r = x.btn.getBoundingClientRect();
82
+ if (r.bottom < 0 || r.top > innerHeight) { anchor = null; return; }
83
+ anchor = { btn: x.btn, top: r.top, sc: scrollerOf(root) };
84
+ };
85
+ const hold = () => {
86
+ if (!anchor) return;
87
+ const d = anchor.btn.getBoundingClientRect().top - anchor.top;
88
+ if (Math.abs(d) > 0.5) anchor.sc.scrollTop += d;
89
+ };
90
+
91
+ /* ---------- open / close ---------- */
92
+ const turn = (x, open, animate) => {
93
+ const t = o.marker === 'plus' ? x.mk.querySelector('.acc__v') : x.mk.querySelector('svg');
94
+ if (!t) return;
95
+ g.killTweensOf(t);
96
+ const v = o.marker === 'plus' ? { rotation: open ? 90 : 0, transformOrigin: '50% 50%' } : { rotation: open ? 180 : 0 };
97
+ if (!animate || RM()) g.set(t, v);
98
+ else g.to(t, { ...v, duration: 0.45, ease: open ? 'back.out(2.4)' : 'power2.out' });
99
+ };
100
+ const show = (x, animate) => {
101
+ const p = x.panel, was = p.hidden, h0 = was ? 0 : p.offsetHeight;
102
+ x.open = true; x.btn.setAttribute('aria-expanded', 'true'); x.el.classList.add('is-open');
103
+ g.killTweensOf([p, x.body]); g.set(x.body, { clearProps: 'opacity' });
104
+ p.hidden = false; turn(x, true, animate);
105
+ if (!animate || RM()) { g.set(p, { clearProps: 'height' }); return; }
106
+ g.fromTo(p, { height: h0 }, { height: 'auto', duration: 0.42, ease: 'power3.out', clearProps: 'height', onUpdate: hold });
107
+ if (was) {
108
+ const kids = x.body.children.length ? [...x.body.children].slice(0, 8) : [x.body];
109
+ g.fromTo(kids, { y: -8, opacity: 0 }, { y: 0, opacity: 1, duration: 0.4, delay: 0.05, stagger: 0.035, ease: 'power3.out', clearProps: 'transform,opacity' });
110
+ }
111
+ };
112
+ const hide = (x, animate) => {
113
+ const p = x.panel;
114
+ x.open = false; x.btn.setAttribute('aria-expanded', 'false'); x.el.classList.remove('is-open');
115
+ turn(x, false, animate);
116
+ if (p.hidden) return;
117
+ g.killTweensOf([p, x.body]);
118
+ if (!animate || RM()) { p.hidden = HID; g.set([p, x.body], { clearProps: 'height,opacity' }); return; }
119
+ g.to(x.body, { opacity: 0, duration: 0.2, ease: 'power1.out' });
120
+ g.fromTo(p, { height: p.offsetHeight }, { height: 0, duration: 0.32, ease: 'power2.inOut', onUpdate: hold,
121
+ onComplete: () => { if (!x.open) p.hidden = HID; g.set([p, x.body], { clearProps: 'height,opacity' }); } });
122
+ };
123
+ const set = (x, open, { animate = true, tell = true } = {}) => {
124
+ if (!x || x.disabled || x.open === open) return false;
125
+ if (!open && !o.collapsible && !list.some((y) => y !== x && y.open)) return false;
126
+ if (open) {
127
+ if (!o.multiple) list.forEach((y) => { if (y !== x && y.open) { hide(y, animate); if (tell) o.onToggle?.(y.id, false, api); } });
128
+ show(x, animate);
129
+ } else hide(x, animate);
130
+ if (tell) o.onToggle?.(x.id, open, api);
131
+ return true;
132
+ };
133
+
134
+ /* starting state */
135
+ src.forEach((it, i) => { if (it.open && (o.multiple || !list.some((y) => y.open))) show(list[i], false); });
136
+ if (!o.collapsible && !list.some((x) => x.open)) { const f = list.find((x) => !x.disabled); if (f) show(f, false); }
137
+ list.forEach((x) => { if (!x.open) turn(x, false, false); });
138
+
139
+ /* ---------- events ---------- */
140
+ const mine = (n) => n?.closest('.acc') === root;
141
+ on(root, 'click', (e) => {
142
+ const b = e.target.closest('.acc__btn'); if (!b || !mine(b)) return;
143
+ const x = list.find((y) => y.btn === b); if (!x) return;
144
+ if (!o.multiple && !x.open) pin(x); else anchor = null;
145
+ if (!set(x, !x.open) && !RM()) M.shake(x.mk);
146
+ });
147
+ on(root, 'keydown', (e) => {
148
+ const b = e.target.closest?.('.acc__btn'); if (!b || !mine(b)) return;
149
+ const bs = list.filter((x) => !x.disabled && !x.out).map((x) => x.btn), i = bs.indexOf(b);
150
+ const go = (k) => { e.preventDefault(); bs[(k + bs.length) % bs.length]?.focus(); };
151
+ if (e.key === 'ArrowDown') go(i + 1);
152
+ else if (e.key === 'ArrowUp') go(i - 1);
153
+ else if (e.key === 'Home') go(0);
154
+ else if (e.key === 'End') go(bs.length - 1);
155
+ });
156
+ list.forEach((x) => on(x.panel, 'beforematch', () => { anchor = null; set(x, true, { animate: false }); }));
157
+
158
+ /* ---------- filter ---------- */
159
+ const unmark = (n) => n.querySelectorAll('mark.acc__hit').forEach((m) => { const p = m.parentNode; m.replaceWith(document.createTextNode(m.textContent)); p.normalize(); });
160
+ const mark = (n, q) => {
161
+ const ql = q.toLowerCase(), tw = document.createTreeWalker(n, NodeFilter.SHOW_TEXT), hits = [];
162
+ while (tw.nextNode()) if (tw.currentNode.nodeValue.toLowerCase().includes(ql)) hits.push(tw.currentNode);
163
+ hits.forEach((t) => {
164
+ const s = t.nodeValue, sl = s.toLowerCase(), frag = document.createDocumentFragment();
165
+ let i = 0, j;
166
+ while ((j = sl.indexOf(ql, i)) >= 0) {
167
+ frag.append(s.slice(i, j));
168
+ const m = document.createElement('mark'); m.className = 'acc__hit'; m.textContent = s.slice(j, j + q.length); frag.append(m);
169
+ i = j + q.length;
170
+ }
171
+ frag.append(s.slice(i)); t.replaceWith(frag);
172
+ });
173
+ };
174
+ const fold = (n, out) => {
175
+ g.killTweensOf(n);
176
+ if (RM()) { n.hidden = out; g.set(n, { clearProps: 'height,opacity' }); return; }
177
+ if (out) { if (n.hidden) return; g.to(n, { height: 0, opacity: 0, duration: 0.26, ease: 'power2.inOut', onComplete: () => { n.hidden = true; g.set(n, { clearProps: 'height,opacity' }); } }); }
178
+ else { const was = n.hidden; n.hidden = false; if (was) g.set(n, { height: 0, opacity: 0 }); g.to(n, { height: 'auto', opacity: 1, duration: 0.34, ease: 'power3.out', clearProps: 'height,opacity' }); }
179
+ };
180
+ const filter = (text = '', { open = false } = {}) => {
181
+ const q = String(text).trim();
182
+ let n = 0, first = null;
183
+ anchor = null;
184
+ list.forEach((x) => {
185
+ unmark(x.el);
186
+ const hit = !q || x.el.textContent.toLowerCase().includes(q.toLowerCase());
187
+ if (hit) { n++; if (q) { mark(x.btn, q); mark(x.body, q); first ||= x; } }
188
+ if (x.out !== !hit) { x.out = !hit; fold(x.el, !hit); }
189
+ });
190
+ root.classList.toggle('is-filtered', !!q);
191
+ if (q && open) (o.multiple ? list.filter((x) => !x.out) : [first]).forEach((x) => x && set(x, true));
192
+ return n;
193
+ };
194
+
195
+ const api = {
196
+ root,
197
+ get value() { return list.filter((x) => x.open).map((x) => x.id); },
198
+ isOpen: (id) => !!byId(id)?.open,
199
+ open: (id) => { anchor = null; return set(byId(id), true); },
200
+ close: (id) => { anchor = null; return set(byId(id), false); },
201
+ toggle: (id) => { anchor = null; const x = byId(id); return x ? set(x, !x.open) : false; },
202
+ openAll() { if (!o.multiple) return false; anchor = null; list.forEach((x) => { if (!x.out) set(x, true); }); return true; },
203
+ closeAll() { anchor = null; list.forEach((x) => set(x, false)); },
204
+ filter,
205
+ destroy() { ac.abort(); g.killTweensOf(root.querySelectorAll('*')); el.innerHTML = ''; },
206
+ };
207
+ return api;
208
+ };