ab-nextjs-components 0.1.13 → 0.2.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/CHANGELOG.md +70 -0
- package/README.md +35 -0
- package/ab-app-bar/index.tsx +53 -13
- package/ab-app-bar/styles.module.css +68 -4
- package/ab-bottom-drawer/index.tsx +71 -0
- package/ab-bottom-drawer/styles.module.css +66 -0
- package/ab-breadcrumbs/index.tsx +92 -0
- package/ab-breadcrumbs/styles.module.css +54 -0
- package/ab-button/helpers.ts +6 -1
- package/ab-button/index.tsx +8 -2
- package/ab-button/styles.module.css +39 -0
- package/ab-card/styles.module.css +1 -1
- package/ab-carousel/styles.module.css +1 -1
- package/ab-chip/index.tsx +16 -4
- package/ab-chip/styles.module.css +12 -1
- package/ab-confirm-drawer/index.tsx +97 -0
- package/ab-confirm-drawer/styles.module.css +41 -0
- package/ab-drawer/gestures.ts +134 -0
- package/ab-drawer/index.tsx +458 -0
- package/ab-drawer/kit.module.css +204 -0
- package/ab-drawer/styles.module.css +166 -0
- package/ab-drawer/use-ab-drawer.ts +89 -0
- package/ab-drawer/use-ab-edge-swipe.ts +155 -0
- package/ab-drawer-list/index.tsx +118 -0
- package/ab-drawer-list/styles.module.css +65 -0
- package/ab-flow-diagram/styles.module.css +2 -2
- package/ab-icon/builtin.ts +4 -0
- package/ab-icon-button/index.tsx +13 -2
- package/ab-icon-button/styles.module.css +1 -1
- package/ab-install-snippet/index.tsx +51 -29
- package/ab-install-snippet/styles.module.css +34 -2
- package/ab-kbd/styles.module.css +1 -1
- package/ab-list/index.tsx +107 -0
- package/ab-list/styles.module.css +82 -0
- package/ab-locale-switcher/index.tsx +103 -10
- package/ab-locale-switcher/styles.module.css +24 -4
- package/ab-mobile-header/index.tsx +100 -0
- package/ab-nav-drawer/index.tsx +158 -0
- package/ab-navbar/index.tsx +1 -1
- package/ab-navbar/styles.module.css +20 -2
- package/ab-navbar/view.tsx +7 -4
- package/ab-package-card/index.tsx +49 -2
- package/ab-package-card/styles.module.css +40 -0
- package/ab-search-drawer/index.tsx +279 -0
- package/ab-search-trigger/index.tsx +22 -2
- package/ab-search-trigger/styles.module.css +30 -1
- package/ab-settings-drawer/index.tsx +160 -0
- package/ab-sidebar/index.tsx +6 -3
- package/ab-sidebar/styles.module.css +53 -5
- package/ab-sidebar/view.tsx +18 -4
- package/ab-theme-toggle/index.tsx +21 -6
- package/ab-theme-toggle/styles.module.css +18 -3
- package/ab-toc/index.tsx +9 -2
- package/ab-toc/styles.module.css +20 -8
- package/ab-toc-drawer/index.tsx +129 -0
- package/ab-version-switcher/index.tsx +143 -0
- package/ab-version-switcher/styles.module.css +76 -0
- package/index.ts +50 -0
- package/package.json +28 -3
- package/server/ab-button/index.tsx +6 -2
- package/server/ab-button/styles.module.css +39 -0
- package/types/index.d.ts +37 -0
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* @license MIT
|
|
3
|
+
* ~~~~~~~~~~~~
|
|
4
|
+
* ab-nextjs-components
|
|
5
|
+
* ~~~~~~~~~~~~
|
|
6
|
+
* Copyright (c) 2026 Abraham Ukachi. The abElements Project.
|
|
7
|
+
*
|
|
8
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
9
|
+
* of this software and associated documentation files (the 'Software'), to deal
|
|
10
|
+
* in the Software without restriction, including without limitation the rights
|
|
11
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
12
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
13
|
+
* furnished to do so, subject to the following conditions:
|
|
14
|
+
*
|
|
15
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
16
|
+
* copies or substantial portions of the Software.
|
|
17
|
+
*
|
|
18
|
+
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
19
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
20
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
21
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
22
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
23
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
24
|
+
* SOFTWARE.
|
|
25
|
+
*
|
|
26
|
+
* @project: ab-nextjs-components
|
|
27
|
+
* @name: AbDrawer (G53)
|
|
28
|
+
* @file: ab-drawer/index.tsx
|
|
29
|
+
* @type: Client component (SSR: in-flow no-JS fallback)
|
|
30
|
+
* @authors: Abraham Ukachi <abrahamukachi@gmail.com>
|
|
31
|
+
*
|
|
32
|
+
* Example usage:
|
|
33
|
+
* 1+|> const drawer = useAbDrawer('main')
|
|
34
|
+
* -|> <button {...drawer.triggerProps}>Filters</button>
|
|
35
|
+
* -|> <AbDrawer {...drawer.drawerProps} side="end" title="Filters">…</AbDrawer>
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
/*
|
|
39
|
+
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
|
40
|
+
* MOTTO: We'll always do more 😜!!!
|
|
41
|
+
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
'use client';
|
|
46
|
+
|
|
47
|
+
// ⚛️ React
|
|
48
|
+
import { useCallback, useEffect, useId, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent, type ReactElement, type ReactNode } from 'react';
|
|
49
|
+
// 🌀 portal into the scope's drawer layer
|
|
50
|
+
import { createPortal } from 'react-dom';
|
|
51
|
+
// 🧵 classes
|
|
52
|
+
import clsx from 'clsx';
|
|
53
|
+
// 🎨 styles
|
|
54
|
+
import styles from './styles.module.css';
|
|
55
|
+
// 🎬 motion classes (ab-nextjs-animations >= 0.2.4): the slide + the scrim fade, reduced motion included
|
|
56
|
+
import { AB_MOTION } from 'ab-nextjs-animations/motion';
|
|
57
|
+
import 'ab-nextjs-animations/motion/styles.css';
|
|
58
|
+
// 🎛️ the controller hook + scope type
|
|
59
|
+
import { useAbDrawer, type AbDrawerScope, type UseAbDrawer } from './use-ab-drawer';
|
|
60
|
+
// 🤏 drawers v2: the pure swipe / snap rules
|
|
61
|
+
import { AB_SWIPE, createAbVelocityTracker, resolveAbSheetRelease, resolveAbSideRelease, type AbSheetSnap } from './gestures';
|
|
62
|
+
|
|
63
|
+
// 📦 re-exports: one import for the whole drawer API
|
|
64
|
+
export { useAbDrawer };
|
|
65
|
+
export type { AbDrawerScope, UseAbDrawer, AbSheetSnap };
|
|
66
|
+
// 🤏 0.2.0: edge swipes + the pure rules, from the same entry
|
|
67
|
+
export { useAbEdgeSwipe, type UseAbEdgeSwipeOptions } from './use-ab-edge-swipe';
|
|
68
|
+
export { AB_SWIPE, resolveAbSheetRelease, resolveAbSideRelease } from './gestures';
|
|
69
|
+
|
|
70
|
+
/** 🥞 drawers v2 stacking tiers (spec z-order): aside (right) < nav (left) < sheet (bottom). Unset = the old single level. */
|
|
71
|
+
export type AbDrawerTier = 'aside' | 'nav' | 'sheet';
|
|
72
|
+
|
|
73
|
+
/** 🧭 where it slides in from. `start` / `end` follow the writing direction (RTL-aware). */
|
|
74
|
+
export type AbDrawerSide = 'top' | 'bottom' | 'left' | 'right' | 'start' | 'end';
|
|
75
|
+
|
|
76
|
+
/** ⚙️ props */
|
|
77
|
+
export interface AbDrawerProps {
|
|
78
|
+
open: boolean; // 🚪 controlled
|
|
79
|
+
onClose: () => void; // ⎋ Escape, scrim click and the close button call it
|
|
80
|
+
scope?: AbDrawerScope; // 🗺️ which box clips it (default `app`)
|
|
81
|
+
side?: AbDrawerSide; // 🧭 default `bottom`
|
|
82
|
+
title?: ReactNode; // 🏷️ a string becomes the `<h2>` that labels the dialog
|
|
83
|
+
'aria-labelledby'?: string; // ♿ your own visible title id (wins over `title`)
|
|
84
|
+
'aria-label'?: string; // ♿ when there is no visible title
|
|
85
|
+
id?: string; // 🆔 the dialog id (`aria-controls` target)
|
|
86
|
+
children?: ReactNode; // 📄 the body (it scrolls on its own)
|
|
87
|
+
footer?: ReactNode; // 🔚 actions row (stays put)
|
|
88
|
+
size?: string; // 📏 width (start/end/left/right) or height (top/bottom), e.g. `360px`
|
|
89
|
+
modal?: boolean; // 🔒 trap focus + make the rest of the scope inert (default `true`)
|
|
90
|
+
closeLabel?: string; // 🌍 default "Close"
|
|
91
|
+
noJsFallback?: boolean; // 🧩 D41: without JS, render the content in flow (default `true`)
|
|
92
|
+
initialFocus?: 'first' | 'panel' | (string & {}); // 🎯 on open: the first control (default), the panel itself, or (0.2.0) a CSS selector inside the panel, e.g. `[role=radio][aria-checked=true]`
|
|
93
|
+
// 🆕 0.2.0 drawers v2 (John, God 01:22): all opt-in, the defaults keep the old drawer
|
|
94
|
+
tier?: AbDrawerTier; // 🥞 stacking tier: 'aside' (z 60) < 'nav' (61) < 'sheet' (62)
|
|
95
|
+
swipe?: boolean; // 🤏 side drawers: swipe the sheet back toward its edge to close (30% of the width or ≥ 0.5px/ms)
|
|
96
|
+
snapPoints?: boolean; // 🧲 bottom only, below 768px: snaps at 70% (S1) and full height (S2) with a handle; gestures per the spec
|
|
97
|
+
defaultSnap?: AbSheetSnap; // 🧲 where it opens (default 'partial'; e.g. 'full' for a search sheet)
|
|
98
|
+
fullOnly?: boolean; // 🧲 no 70% stop: opens at full height, a gentle drag springs back, a hard one closes (search: the keyboard is up)
|
|
99
|
+
onSnapChange?: (snap: AbSheetSnap) => void; // 🔔
|
|
100
|
+
handleLabels?: { expand: string; collapse: string }; // ♿ the handle button (default "Expand" / "Collapse")
|
|
101
|
+
centerIn?: 'main'; // 💻 bottom only, 768px and up: centred in the main pane, min(640px, main width) wide, ≤ 70% tall
|
|
102
|
+
returnFocus?: string; // ↩️ selector focused on close when there was no focusable opener (an edge swipe), e.g. the header logo link
|
|
103
|
+
closeIcon?: ReactNode; // ✕ the close glyph (default a text ✕)
|
|
104
|
+
headerStart?: ReactNode; // 🏷️ header content that does NOT label the dialog (e.g. a logo; then use `aria-label`). `title` wins
|
|
105
|
+
className?: string; // 🏷️
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** ⏱️ the slide, same as the panes aside (core 0.1.6) */
|
|
109
|
+
export const AB_DRAWER_DURATION = 240;
|
|
110
|
+
|
|
111
|
+
// 🔎 the element each scope is clipped by (core 0.1.6 data-ab-part hooks)
|
|
112
|
+
const SCOPE_SELECTOR: Record<AbDrawerScope, string> = {
|
|
113
|
+
app: '.AbAppLayout', // 🏠 the whole app box
|
|
114
|
+
main: '[data-ab-part="main"]', // 📄 the main pane (not its scroller, so the drawer doesn't scroll away)
|
|
115
|
+
aside: '[data-ab-part="aside"]', // 📑 the aside pane
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* 🗺️ getAbDrawerHost — the box a drawer of `scope` is clipped by: the scope element that contains `from`
|
|
120
|
+
* (so two layouts on a page each get their own), else the first one in the document, else `<body>`.
|
|
121
|
+
* Effects / handlers only (it reads the DOM).
|
|
122
|
+
*/
|
|
123
|
+
export function getAbDrawerHost(scope: AbDrawerScope, from?: Element | null): HTMLElement {
|
|
124
|
+
const sel = SCOPE_SELECTOR[scope]; // 🔎
|
|
125
|
+
return from?.closest<HTMLElement>(sel) ?? document.querySelector<HTMLElement>(sel) ?? document.body; // 🎯
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// ♿ everything that can take focus inside the panel
|
|
129
|
+
const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]), [contenteditable="true"]';
|
|
130
|
+
|
|
131
|
+
// 📍 hosts with a drawer layer, ref-counted: `data-ab-drawer-host` stays while ANY drawer still uses the box.
|
|
132
|
+
// CSS (`:where([data-ab-drawer-host])`, zero specificity) gives a static host `position: relative`; no inline
|
|
133
|
+
// styles are written. A core rule on its layout boxes could replace this later.
|
|
134
|
+
const hostCount = new WeakMap<HTMLElement, number>();
|
|
135
|
+
const holdHost = (host: HTMLElement) => { const n = (hostCount.get(host) ?? 0) + 1; hostCount.set(host, n); host.setAttribute('data-ab-drawer-host', ''); };
|
|
136
|
+
const releaseHost = (host: HTMLElement) => {
|
|
137
|
+
const n = (hostCount.get(host) ?? 1) - 1;
|
|
138
|
+
if (n > 0) { hostCount.set(host, n); return; }
|
|
139
|
+
hostCount.delete(host); host.removeAttribute('data-ab-drawer-host'); // 🧹 last one out
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
// 🥞 open drawers, newest last: only the top one answers Escape / Tab (a drawer opened from a drawer)
|
|
143
|
+
const openStack: symbol[] = [];
|
|
144
|
+
/** 🥞 is `token` the topmost open drawer? */
|
|
145
|
+
const isTopDrawer = (token: symbol): boolean => openStack[openStack.length - 1] === token;
|
|
146
|
+
|
|
147
|
+
// ♿ reduced-motion check, read once per open / close on purpose: it only picks the unmount delay for THAT
|
|
148
|
+
// toggle (the slide itself is CSS, which follows the media query live), so a listener would buy nothing
|
|
149
|
+
const reducedMotion = (): boolean => typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* 🗄️ AbDrawer (G53) — a panel that slides in from any side, clipped by its **scope** (app / main / aside).
|
|
153
|
+
*
|
|
154
|
+
* - 📐 Rendered into an absolute `inset: 0` layer INSIDE the scope box, so it never makes the document scroll
|
|
155
|
+
* (the D34 rule); its body is its own scroller (`overscroll-behavior: contain`).
|
|
156
|
+
* - ♿ `role="dialog"` + `aria-modal`, labelled by `title` / `aria-labelledby`; focus moves in on open, is
|
|
157
|
+
* trapped (Tab / Shift+Tab), and returns to the opener on close; Escape and a scrim click close it;
|
|
158
|
+
* the rest of the scope is `inert` while it's open (only the scope, unless `scope="app"`).
|
|
159
|
+
* - 🎞️ 240ms slide; no motion and instant open/close under `prefers-reduced-motion`.
|
|
160
|
+
* - 🧱 Scopes need **ab-nextjs-core 0.1.6+** markup (`.AbAppLayout`, `[data-ab-part="main"]`, `[data-ab-part="aside"]`);
|
|
161
|
+
* with older core (or no layout) it falls back to a viewport layer on `<body>`.
|
|
162
|
+
* - 🧩 D41 no-JS: the server renders the content as an in-flow `<section>` (hidden as soon as scripting runs).
|
|
163
|
+
*/
|
|
164
|
+
const AbDrawer = (props: AbDrawerProps): ReactElement => {
|
|
165
|
+
const { open, onClose, scope = 'app', side = 'bottom', title, id, children, footer, size, modal = true, closeLabel = 'Close', noJsFallback = true, initialFocus = 'first', className } = props;
|
|
166
|
+
const { tier, swipe = false, snapPoints = false, defaultSnap = 'partial', onSnapChange, handleLabels, centerIn, returnFocus, closeIcon, headerStart, fullOnly = false } = props; // 🆕 0.2.0
|
|
167
|
+
const auto = useId().replace(/[^A-Za-z0-9_-]/g, ''); // 🆔 SSR-stable
|
|
168
|
+
const dialogId = id ?? `ab-drawer-${auto}`; // 🆔
|
|
169
|
+
const titleId = `${dialogId}-title`; // 🏷️
|
|
170
|
+
const labelledBy = props['aria-labelledby'] ?? (title != null ? titleId : undefined); // ♿
|
|
171
|
+
const anchor = useRef<HTMLDivElement>(null); // 📍 where we are in the tree (picks the right layout)
|
|
172
|
+
const panel = useRef<HTMLDivElement>(null); // 🗄️
|
|
173
|
+
const opener = useRef<Element | null>(null); // ↩️ focus goes back here
|
|
174
|
+
const close = useRef(onClose); // 🔁 latest onClose for the listeners
|
|
175
|
+
useEffect(() => { close.current = onClose; }, [onClose]); // 🔁 synced after render, never during
|
|
176
|
+
|
|
177
|
+
// 🧭 client-only state: the layer we portal into, whether the panel is in the DOM, whether it's slid in
|
|
178
|
+
const [layer, setLayer] = useState<HTMLElement | null>(null);
|
|
179
|
+
const [present, setPresent] = useState(open); // 🧱 mounted (open, or sliding out)
|
|
180
|
+
const [shown, setShown] = useState(false); // 🎞️ slid in
|
|
181
|
+
const [token] = useState(() => Symbol('ab-drawer')); // 🥞 our place in the open stack
|
|
182
|
+
|
|
183
|
+
// 🗺️ find the scope box once we're on the client and make a layer in it
|
|
184
|
+
useEffect(() => {
|
|
185
|
+
const host = getAbDrawerHost(scope, anchor.current); // 🎯
|
|
186
|
+
const el = document.createElement('div'); // 🧱 one layer per drawer (no shared state to clean up)
|
|
187
|
+
el.setAttribute('data-ab-drawer-layer', scope);
|
|
188
|
+
el.className = clsx('AbDrawerLayer', styles.abDrawerLayer);
|
|
189
|
+
if (host === document.body) el.setAttribute('data-host', 'body'); // 📌 no layout: cover the viewport
|
|
190
|
+
host.appendChild(el);
|
|
191
|
+
// eslint-disable-next-line react-hooks/set-state-in-effect -- 🌀 the layer is external DOM that only exists after mount (SSR keeps the in-flow fallback); one extra render on hydration is the point
|
|
192
|
+
setLayer(el);
|
|
193
|
+
return () => { el.remove(); setLayer(null); }; // 🧹
|
|
194
|
+
}, [scope]);
|
|
195
|
+
|
|
196
|
+
// 📍 hold the host (position context) while the panel is in the DOM (open or sliding out)
|
|
197
|
+
useEffect(() => {
|
|
198
|
+
const host = layer?.parentElement;
|
|
199
|
+
if (!present || !host || host === document.body) return; // 📌 body layer is fixed: no context needed
|
|
200
|
+
holdHost(host);
|
|
201
|
+
return () => releaseHost(host);
|
|
202
|
+
}, [present, layer]);
|
|
203
|
+
|
|
204
|
+
// 🧮 derived during render (React's "adjust state on prop change"): open mounts at once, close starts the slide out
|
|
205
|
+
if (open && !present) setPresent(true);
|
|
206
|
+
if (!open && shown) setShown(false);
|
|
207
|
+
|
|
208
|
+
// 🎞️ open → mount, then slide in on the next frame; close → slide out, then unmount
|
|
209
|
+
useEffect(() => {
|
|
210
|
+
const ms = reducedMotion() ? 0 : AB_DRAWER_DURATION; // ♿
|
|
211
|
+
if (open) {
|
|
212
|
+
const raf = requestAnimationFrame(() => requestAnimationFrame(() => setShown(true))); // 🛝 two frames: start state painted first
|
|
213
|
+
return () => cancelAnimationFrame(raf);
|
|
214
|
+
}
|
|
215
|
+
const t = window.setTimeout(() => setPresent(false), ms); // ⏱️ one timer, so quick toggles never race
|
|
216
|
+
return () => window.clearTimeout(t);
|
|
217
|
+
}, [open]);
|
|
218
|
+
|
|
219
|
+
// ↩️ remember the trigger the moment we open (before the scope turns inert and blurs it)
|
|
220
|
+
useEffect(() => { if (open && !panel.current?.contains(document.activeElement)) opener.current = document.activeElement; }, [open]);
|
|
221
|
+
|
|
222
|
+
// ♿ focus in on open, back to the opener on close
|
|
223
|
+
useEffect(() => {
|
|
224
|
+
if (!open || !present || !panel.current) return;
|
|
225
|
+
const pick = initialFocus === 'panel' ? null : initialFocus === 'first' ? FOCUSABLE : initialFocus; // 🎯 0.2.0: or a selector
|
|
226
|
+
const first = pick ? panel.current.querySelector<HTMLElement>(pick) ?? (pick !== FOCUSABLE ? panel.current.querySelector<HTMLElement>(FOCUSABLE) : null) : null; // 🎯 that, else the first control, else the panel
|
|
227
|
+
// 👀 e.g. the checked language in view: scroll ONLY the drawer body (scrollIntoView would also scroll the clipped
|
|
228
|
+
// layer and undo the 70% snap offset, WebKit e2e 2026-10-21)
|
|
229
|
+
const body = panel.current.querySelector<HTMLElement>('[data-ab-part="drawer-body"]');
|
|
230
|
+
if (first && body && body.contains(first)) { const b = body.getBoundingClientRect(); const r = first.getBoundingClientRect(); if (r.bottom > b.bottom) body.scrollTop += r.bottom - b.bottom; else if (r.top < b.top) body.scrollTop -= b.top - r.top; }
|
|
231
|
+
(first ?? panel.current).focus({ preventScroll: true });
|
|
232
|
+
return () => {
|
|
233
|
+
const had = opener.current as HTMLElement | null; // ↩️
|
|
234
|
+
const usable = had && had !== document.body && had.isConnected ? had : null; // 🤏 a swipe has no opener
|
|
235
|
+
// ↩️ 0.2.0 fallback: the first VISIBLE match (an app often renders the logo twice, one hidden per breakpoint)
|
|
236
|
+
const back = usable ?? (returnFocus ? Array.from(document.querySelectorAll<HTMLElement>(returnFocus)).find((el) => el.getClientRects().length > 0) ?? null : null);
|
|
237
|
+
// ⏭️ a microtask later: the inert cleanup below runs after this one, and an inert opener can't take focus
|
|
238
|
+
queueMicrotask(() => { if (back && back.isConnected && typeof back.focus === 'function') back.focus({ preventScroll: true }); });
|
|
239
|
+
};
|
|
240
|
+
}, [open, present, layer, initialFocus, returnFocus]); // 🎯 static in practice
|
|
241
|
+
|
|
242
|
+
// 🔒 the rest of the scope is inert while open (modal only); we only undo what we set
|
|
243
|
+
useEffect(() => {
|
|
244
|
+
if (!open || !modal || !layer?.parentElement) return;
|
|
245
|
+
const touched: HTMLElement[] = [];
|
|
246
|
+
for (const sib of Array.from(layer.parentElement.children) as HTMLElement[]) {
|
|
247
|
+
if (sib === layer || sib.hasAttribute('inert') || sib.hasAttribute('data-ab-drawer-layer')) continue; // 🙅 ours / already inert / other drawers
|
|
248
|
+
sib.setAttribute('inert', ''); touched.push(sib); // 🧊
|
|
249
|
+
}
|
|
250
|
+
return () => { for (const el of touched) el.removeAttribute('inert'); }; // 🔓
|
|
251
|
+
}, [open, modal, layer]);
|
|
252
|
+
|
|
253
|
+
// 🥞 join the open stack while open (StrictMode-safe: cleanup removes exactly us)
|
|
254
|
+
useEffect(() => {
|
|
255
|
+
if (!open) return;
|
|
256
|
+
openStack.push(token);
|
|
257
|
+
return () => { const i = openStack.lastIndexOf(token); if (i >= 0) openStack.splice(i, 1); };
|
|
258
|
+
}, [open, token]);
|
|
259
|
+
|
|
260
|
+
// 🧲 0.2.0: snap state (bottom + snapPoints, below 768px) and the laptop centring (centerIn="main", 768px and up)
|
|
261
|
+
const [mobile, setMobile] = useState(false); // 📱 below 768px?
|
|
262
|
+
const [snap, setSnapState] = useState<AbSheetSnap>(fullOnly ? 'full' : defaultSnap); // 🧲 S1 / S2
|
|
263
|
+
const [returned, setReturned] = useState(false); // ✌️ came back to S1 from S2 with a gentle drag
|
|
264
|
+
const [geo, setGeo] = useState<Record<string, string>>({}); // 📐 measured CSS vars (px)
|
|
265
|
+
const snapping = snapPoints && side === 'bottom' && mobile; // 🧲 live?
|
|
266
|
+
const centring = centerIn === 'main' && side === 'bottom' && !mobile; // 💻 live?
|
|
267
|
+
const setSnap = useCallback((next: AbSheetSnap) => { setSnapState(next); onSnapChange?.(next); }, [onSnapChange]);
|
|
268
|
+
// 🔁 every open starts at defaultSnap (derived during render, like `present`)
|
|
269
|
+
const [lastOpen, setLastOpen] = useState(open);
|
|
270
|
+
if (open !== lastOpen) { setLastOpen(open); if (open) { setSnapState(fullOnly ? 'full' : defaultSnap); setReturned(false); } }
|
|
271
|
+
// 📱 follow the 768px breakpoint (the same edge core uses)
|
|
272
|
+
useEffect(() => {
|
|
273
|
+
if (!(snapPoints || centerIn) || typeof window.matchMedia !== 'function') return;
|
|
274
|
+
const mq = window.matchMedia('(max-width: 767px)'); // 📱
|
|
275
|
+
const on = () => setMobile(mq.matches);
|
|
276
|
+
on(); mq.addEventListener?.('change', on);
|
|
277
|
+
return () => mq.removeEventListener?.('change', on);
|
|
278
|
+
}, [snapPoints, centerIn]);
|
|
279
|
+
// 📐 measure: S1 offset (100% − 70% of the app) and the main pane box inside the host
|
|
280
|
+
useEffect(() => {
|
|
281
|
+
const host = layer?.parentElement;
|
|
282
|
+
if (!present || !host || !(snapping || centring)) return;
|
|
283
|
+
const measure = () => {
|
|
284
|
+
const hb = host === document.body ? { top: 0, left: 0, width: window.innerWidth, height: window.innerHeight } : host.getBoundingClientRect(); // 📏
|
|
285
|
+
const next: Record<string, string> = { '--ab-drawer-host-h': `${hb.height}px` };
|
|
286
|
+
if (snapping) {
|
|
287
|
+
const ph = panel.current?.getBoundingClientRect().height ?? hb.height; // 📏 the full-height sheet
|
|
288
|
+
next['--ab-drawer-partial-offset'] = `${Math.max(0, ph - 0.7 * hb.height)}px`; // 🧲 S1 = 70% of the app visible
|
|
289
|
+
}
|
|
290
|
+
if (centring) {
|
|
291
|
+
const main = host.querySelector<HTMLElement>('[data-ab-part="main"]')?.getBoundingClientRect(); // 📄 the main pane
|
|
292
|
+
next['--ab-drawer-main-left'] = `${main ? main.left - hb.left : 0}px`;
|
|
293
|
+
next['--ab-drawer-main-width'] = `${main ? main.width : hb.width}px`;
|
|
294
|
+
}
|
|
295
|
+
setGeo((g) => (JSON.stringify(g) === JSON.stringify(next) ? g : next)); // 🧮 no loop
|
|
296
|
+
};
|
|
297
|
+
measure();
|
|
298
|
+
const ro = typeof ResizeObserver === 'function' ? new ResizeObserver(measure) : null; // 👀 resizes
|
|
299
|
+
ro?.observe(host); if (panel.current) ro?.observe(panel.current);
|
|
300
|
+
return () => ro?.disconnect();
|
|
301
|
+
}, [present, layer, snapping, centring]);
|
|
302
|
+
|
|
303
|
+
// 🤏 0.2.0 drags: side sheets swipe toward their edge to close; the snap sheet follows the finger and resolves
|
|
304
|
+
const drag = useRef<{ x: number; y: number; t: number; axis: 0 | 1 | 2; v: ReturnType<typeof createAbVelocityTracker>; el?: Element; id?: number } | null>(null); // 0 = undecided, 1 = ours, 2 = not ours
|
|
305
|
+
const edgeSign = side === 'left' || side === 'start' ? -1 : side === 'right' || side === 'end' ? 1 : 0; // ⬅️ / ➡️ the closing direction
|
|
306
|
+
const setDragTransform = (value: string | null) => {
|
|
307
|
+
const el = panel.current; if (!el) return;
|
|
308
|
+
el.toggleAttribute('data-dragging', value != null); // 🫳 CSS drops the transition while the finger leads
|
|
309
|
+
if (value != null) el.style.removeProperty('--ab-motion-duration'); // 🧹 last release's speed must not beat the 0ms drag rule
|
|
310
|
+
if (value == null) el.style.removeProperty('transform'); else el.style.setProperty('transform', value);
|
|
311
|
+
};
|
|
312
|
+
const onDragStart = (e: { clientX: number; clientY: number; timeStamp: number }, from: 'grip' | 'body') => {
|
|
313
|
+
if (!(swipe && edgeSign !== 0) && !snapping) return; // 🙅 nothing to drag
|
|
314
|
+
if (from === 'body' && snapping && (panel.current?.querySelector('[data-ab-part="drawer-body"]')?.scrollTop ?? 0) > 0) return; // 📜 content not at the top: let it scroll
|
|
315
|
+
const v = createAbVelocityTracker(); v.add(snapping && edgeSign === 0 ? e.clientY : e.clientX, e.timeStamp);
|
|
316
|
+
drag.current = { x: e.clientX, y: e.clientY, t: e.timeStamp, axis: 0, v };
|
|
317
|
+
};
|
|
318
|
+
const onDragMove = (e: { clientX: number; clientY: number; timeStamp: number; preventDefault?: () => void; cancelable?: boolean }) => {
|
|
319
|
+
const d = drag.current; if (!d || d.axis === 2) return;
|
|
320
|
+
const dx = e.clientX - d.x; const dy = e.clientY - d.y; // ↔️ ↕️
|
|
321
|
+
const vertical = edgeSign === 0; // 🧲 the bottom sheet moves on y
|
|
322
|
+
if (d.axis === 0) {
|
|
323
|
+
if (Math.max(Math.abs(dx), Math.abs(dy)) < AB_SWIPE.slop) return; // 🫳 still a tap
|
|
324
|
+
const mine = vertical ? Math.abs(dy) > Math.abs(dx) : Math.abs(dx) > Math.abs(dy); // 🧭 our axis?
|
|
325
|
+
d.axis = mine ? 1 : 2; if (!mine) return;
|
|
326
|
+
if (d.el && d.id != null) d.el.setPointerCapture?.(d.id); // 📌 captured only once it IS a drag (taps on links still click)
|
|
327
|
+
}
|
|
328
|
+
if (e.cancelable) e.preventDefault?.(); // 🚫 no page scroll while we lead
|
|
329
|
+
d.v.add(vertical ? e.clientY : e.clientX, e.timeStamp); // ⚡
|
|
330
|
+
if (vertical) {
|
|
331
|
+
const base = snap === 'full' ? 0 : parseFloat(geo['--ab-drawer-partial-offset'] ?? '0'); // 🧲 where it rests
|
|
332
|
+
setDragTransform(`translateY(${Math.max(0, base + dy)}px)`); // ⬇️⬆️ follow (never above S2)
|
|
333
|
+
} else {
|
|
334
|
+
const along = dx * edgeSign; // ↔️ + = toward the edge
|
|
335
|
+
setDragTransform(`translateX(${Math.max(0, along) * edgeSign}px)`); // ↔️ follow, never past open
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
const onDragEnd = (e: { clientX: number; clientY: number; timeStamp: number }) => {
|
|
339
|
+
const d = drag.current; drag.current = null;
|
|
340
|
+
if (!d || d.axis !== 1) { setDragTransform(null); return; }
|
|
341
|
+
const vertical = edgeSign === 0;
|
|
342
|
+
const vel = d.v.velocity(); // ⚡ px/ms
|
|
343
|
+
setDragTransform(null); // 🛬 hand back to CSS (the attribute transition carries on)
|
|
344
|
+
if (!vertical) {
|
|
345
|
+
const dist = (e.clientX - d.x) * edgeSign; // ↔️ toward the edge
|
|
346
|
+
if (resolveAbSideRelease({ distance: dist, velocity: vel * edgeSign, width: panel.current?.offsetWidth ?? 320 })) close.current(); // ✅
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
const hostH = parseFloat(geo['--ab-drawer-host-h'] ?? '0') || window.innerHeight; // 📏
|
|
350
|
+
const ph = panel.current?.offsetHeight || hostH; // 📏 S2 height
|
|
351
|
+
const resolved = resolveAbSheetRelease({ from: snap, dy: e.clientY - d.y, velocity: vel, partialHeight: 0.7 * hostH, fullHeight: ph, returned }); // 🧲
|
|
352
|
+
const to = fullOnly && resolved === 'partial' ? 'full' : resolved; // 🧲 fullOnly: no S1, spring back to S2
|
|
353
|
+
// ⏱️ carry the release speed: the remaining distance at that speed, between 120 and 240ms
|
|
354
|
+
const ms = Math.abs(vel) > 0.05 ? Math.round(Math.min(AB_DRAWER_DURATION, Math.max(120, (0.3 * hostH) / Math.abs(vel)))) : AB_DRAWER_DURATION;
|
|
355
|
+
panel.current?.style.setProperty('--ab-motion-duration', `${ms}ms`); // 🎞️ the ab-nextjs-animations token
|
|
356
|
+
if (to === 'closed') { close.current(); return; }
|
|
357
|
+
setReturned(snap === 'full' && to === 'partial'); // ✌️ remember the gentle return
|
|
358
|
+
if (to !== snap) setSnap(to);
|
|
359
|
+
};
|
|
360
|
+
// 🖐️ pointer handlers (touch / pen / mouse). The grip kind rides on `data-ab-grip`, so these are plain handlers
|
|
361
|
+
// (never called during render); the pointer is captured only once the press becomes a drag
|
|
362
|
+
const onGripDown = (e: ReactPointerEvent) => {
|
|
363
|
+
if (e.button !== 0) return;
|
|
364
|
+
onDragStart(e, (e.currentTarget as Element).getAttribute('data-ab-grip') === 'body' ? 'body' : 'grip');
|
|
365
|
+
if (drag.current) { drag.current.el = e.currentTarget as Element; drag.current.id = e.pointerId; } // 📌 for the capture
|
|
366
|
+
};
|
|
367
|
+
const onGripMove = (e: ReactPointerEvent) => onDragMove(e);
|
|
368
|
+
const onGripUp = (e: ReactPointerEvent) => onDragEnd(e);
|
|
369
|
+
const gripProps = { onPointerDown: onGripDown, onPointerMove: onGripMove, onPointerUp: onGripUp, onPointerCancel: onGripUp }; // 🖐️
|
|
370
|
+
|
|
371
|
+
// ⎋ Escape closes (skips events an inner menu already handled); Tab stays inside (modal). Topmost drawer only
|
|
372
|
+
const onKeyDown = useCallback((e: KeyboardEvent) => {
|
|
373
|
+
if (!panel.current || !isTopDrawer(token)) return; // 🥞 a drawer under another one stays put
|
|
374
|
+
if (e.key === 'Escape' && !e.defaultPrevented) { e.preventDefault(); close.current(); return; } // ⎋
|
|
375
|
+
if (e.key !== 'Tab' || !modal) return;
|
|
376
|
+
const items = Array.from(panel.current.querySelectorAll<HTMLElement>(FOCUSABLE)).filter((el) => el.getClientRects().length > 0 || el === document.activeElement); // 👀 rendered (keeps position: fixed, which has no offsetParent)
|
|
377
|
+
if (items.length === 0) { e.preventDefault(); panel.current.focus(); return; } // 🔒 nothing to tab to
|
|
378
|
+
const [a, z] = [items[0], items[items.length - 1]];
|
|
379
|
+
const inside = panel.current.contains(document.activeElement);
|
|
380
|
+
if (e.shiftKey && (document.activeElement === a || !inside)) { e.preventDefault(); z.focus(); } // ⬅️ wrap
|
|
381
|
+
else if (!e.shiftKey && (document.activeElement === z || !inside)) { e.preventDefault(); a.focus(); } // ➡️ wrap
|
|
382
|
+
}, [modal, token]);
|
|
383
|
+
useEffect(() => {
|
|
384
|
+
if (!open) return;
|
|
385
|
+
document.addEventListener('keydown', onKeyDown); // 🎧 document-level, so Escape works wherever focus is
|
|
386
|
+
return () => document.removeEventListener('keydown', onKeyDown);
|
|
387
|
+
}, [open, onKeyDown]);
|
|
388
|
+
|
|
389
|
+
// 🏷️ a plain-string title becomes the labelling heading
|
|
390
|
+
const heading = title == null ? null : typeof title === 'string' || typeof title === 'number'
|
|
391
|
+
? <h2 id={titleId} className={styles.abDrawerTitle}>{title}</h2>
|
|
392
|
+
: <div id={props['aria-labelledby'] ? undefined : titleId} className={styles.abDrawerTitle}>{title}</div>;
|
|
393
|
+
const head = heading ?? (headerStart != null ? <div className={styles.abDrawerTitle} data-ab-part="drawer-header-start">{headerStart}</div> : null); // 🏷️ 0.2.0
|
|
394
|
+
const sizeVar = (size || snapping || centring ? { ...(size ? { '--ab-drawer-size': size } : {}), ...(snapping || centring ? geo : {}) } : undefined) as CSSProperties | undefined; // 📏 + 🧲 measured vars
|
|
395
|
+
const grip = snapping || (swipe && edgeSign !== 0); // 🤏 drags on
|
|
396
|
+
const handle = snapPoints && side === 'bottom'; // ➖ the handle strip
|
|
397
|
+
|
|
398
|
+
// 🧩 D41: before hydration (and with no JS at all) the content is an in-flow section
|
|
399
|
+
if (!layer) {
|
|
400
|
+
return (
|
|
401
|
+
<div ref={anchor} className={styles.abDrawerAnchor} data-ab-part="drawer-anchor">
|
|
402
|
+
{noJsFallback ? (
|
|
403
|
+
<section className={clsx('AbDrawerFallback', styles.abDrawerFallback)} data-ab-part="drawer-fallback" aria-labelledby={labelledBy} aria-label={labelledBy ? undefined : props['aria-label']}>
|
|
404
|
+
{heading}
|
|
405
|
+
<div className={styles.abDrawerBody}>{children}</div>
|
|
406
|
+
{footer != null && <div className={styles.abDrawerFooter}>{footer}</div>}
|
|
407
|
+
</section>
|
|
408
|
+
) : null}
|
|
409
|
+
</div>
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
return (
|
|
414
|
+
<div ref={anchor} className={styles.abDrawerAnchor} data-ab-part="drawer-anchor">
|
|
415
|
+
{present && createPortal(
|
|
416
|
+
<div className={styles.abDrawerFrame} data-state={shown ? 'open' : 'closed'} data-side={side} data-scope={scope} data-tier={tier}>
|
|
417
|
+
{/* 🌫️ scrim: a click closes (pointer only; keyboard users have Escape and the close button) */}
|
|
418
|
+
<div className={clsx(styles.abDrawerScrim, AB_MOTION.colors)} data-ab-part="drawer-scrim" aria-hidden="true" onClick={() => close.current()} />
|
|
419
|
+
<div
|
|
420
|
+
ref={panel}
|
|
421
|
+
id={dialogId}
|
|
422
|
+
role="dialog"
|
|
423
|
+
aria-modal={modal ? 'true' : undefined}
|
|
424
|
+
aria-labelledby={labelledBy}
|
|
425
|
+
aria-label={labelledBy ? undefined : props['aria-label']}
|
|
426
|
+
tabIndex={-1} // 🎯 focus target when there are no controls
|
|
427
|
+
className={clsx('AbDrawer', styles.abDrawer, AB_MOTION.transform, className)}
|
|
428
|
+
data-ab-part="drawer"
|
|
429
|
+
data-side={side}
|
|
430
|
+
data-snap={snapping ? snap : undefined} // 🧲 0.2.0: CSS places S1 / S2
|
|
431
|
+
data-center={centring ? 'main' : undefined} // 💻 0.2.0: centred in the main pane
|
|
432
|
+
data-swipe={grip ? 'true' : undefined} // 🤏 touch-action hooks
|
|
433
|
+
style={sizeVar}
|
|
434
|
+
{...(swipe && edgeSign !== 0 ? { ...gripProps, 'data-ab-grip': 'body' } : {})}
|
|
435
|
+
>
|
|
436
|
+
{handle && (snapping && !fullOnly ? (
|
|
437
|
+
// ➖ 0.2.0: the handle (40×4 bar in a 24px strip, 44px touch zone): a button that toggles S1 / S2
|
|
438
|
+
<button type="button" className={styles.abDrawerHandle} data-ab-part="drawer-handle" aria-expanded={snap === 'full'} aria-label={snap === 'full' ? handleLabels?.collapse ?? 'Collapse' : handleLabels?.expand ?? 'Expand'} onClick={() => { setReturned(false); setSnap(snap === 'full' ? 'partial' : 'full'); }} data-ab-grip="grip" {...gripProps} />
|
|
439
|
+
) : <div className={styles.abDrawerHandle} data-ab-part="drawer-handle" aria-hidden="true" {...(snapping ? { ...gripProps, 'data-ab-grip': 'grip' } : {})} />)}
|
|
440
|
+
<div className={styles.abDrawerHeader} data-ab-part="drawer-header" {...(snapping ? { ...gripProps, 'data-ab-grip': 'grip' } : {})}>
|
|
441
|
+
{head}
|
|
442
|
+
<button type="button" className={styles.abDrawerClose} data-ab-part="drawer-close" aria-label={closeLabel} onClick={() => close.current()}>
|
|
443
|
+
{closeIcon ?? <span aria-hidden="true">✕</span>}
|
|
444
|
+
</button>
|
|
445
|
+
</div>
|
|
446
|
+
<div className={styles.abDrawerBody} data-ab-part="drawer-body" {...(snapping ? { ...gripProps, 'data-ab-grip': 'body' } : {})}>{children}</div>
|
|
447
|
+
{footer != null && <div className={styles.abDrawerFooter} data-ab-part="drawer-footer">{footer}</div>}
|
|
448
|
+
</div>
|
|
449
|
+
</div>,
|
|
450
|
+
layer,
|
|
451
|
+
)}
|
|
452
|
+
</div>
|
|
453
|
+
);
|
|
454
|
+
};
|
|
455
|
+
|
|
456
|
+
// 📦 exports
|
|
457
|
+
export default AbDrawer;
|
|
458
|
+
export { AbDrawer };
|