@widgetic/design-system 0.5.41 → 0.5.42

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.
Files changed (35) hide show
  1. package/dist/components/EmptyState.svelte +6 -2
  2. package/dist/components/creator/CreatorBar.svelte +54 -1
  3. package/dist/components/creator/CreatorBar.svelte.d.ts +5 -0
  4. package/dist/components/modals/BaseModal.svelte +9 -0
  5. package/dist/components/modals/BaseModal.svelte.d.ts +5 -0
  6. package/dist/components/search-input/SearchInput.svelte +38 -3
  7. package/dist/components/search-input/recentSearches.d.ts +5 -1
  8. package/dist/components/search-input/recentSearches.js +18 -1
  9. package/dist/components/shell/NavRow.svelte +53 -10
  10. package/dist/components/shell/NavRow.svelte.d.ts +23 -2
  11. package/dist/components/shell/NotificationRow.svelte +3 -2
  12. package/dist/components/shell/ProfileRow.svelte +6 -4
  13. package/dist/components/shell/ProfileRow.svelte.d.ts +2 -2
  14. package/dist/components/shell/SettingsDialog.svelte +23 -1
  15. package/dist/components/shell/WidgetRow.svelte +4 -3
  16. package/dist/components/shell/WidgetRow.svelte.d.ts +2 -2
  17. package/dist/components/ui/accordion/accordion-trigger.svelte +19 -0
  18. package/dist/components/ui/button/button.svelte +4 -2
  19. package/dist/components/ui/dialog/dialog-content.svelte +24 -2
  20. package/dist/components/ui/dropdown-menu/dropdown-menu-content.svelte +2 -1
  21. package/dist/components/ui/dropdown-menu/dropdown-menu-sub-content.svelte +2 -1
  22. package/dist/components/ui/hover-card/hover-card-content.svelte +2 -1
  23. package/dist/components/ui/popover/popover-content.svelte +2 -1
  24. package/dist/components/ui/select/select-content.svelte +2 -1
  25. package/dist/components/ui/tooltip/tooltip-content.svelte +1 -1
  26. package/dist/styles/tokens.css +68 -1
  27. package/dist/utils/modalEnterKey.d.ts +139 -0
  28. package/dist/utils/modalEnterKey.js +276 -0
  29. package/dist/utils/modalFocusTrap.d.ts +7 -0
  30. package/dist/utils/modalFocusTrap.js +22 -0
  31. package/dist/utils/overlayMotion.d.ts +9 -0
  32. package/dist/utils/overlayMotion.js +9 -0
  33. package/dist/utils/revealOpeningSection.d.ts +51 -0
  34. package/dist/utils/revealOpeningSection.js +109 -0
  35. package/package.json +1 -1
@@ -0,0 +1,276 @@
1
+ /**
2
+ * Enter in an open modal presses the modal's main button (owner, 18 Nov 2026: "when I have a modal open, if I click Enter,
3
+ * take it as the main CTA").
4
+ *
5
+ * Both modal shells of the design system (`BaseModal` and the bits-ui `Dialog.Content`) put the `modalEnterKey` action on
6
+ * their card, so every dialog built on them gets it without writing anything. A key press is for a card when it was pressed
7
+ * inside that card and no other card is closer to the focus: a modal that is open over another one never presses the buttons
8
+ * of the one under it.
9
+ *
10
+ * Which button: the one the person sees as the main one.
11
+ * 1. a button marked `data-modal-primary` (the last one, when several are), else
12
+ * 2. the last filled button of the card (design system `Button` with `variant` default, accent or destructive; the Button
13
+ * writes it as `data-variant`). The footer comes last in every dialog, so a filled button inside the body does not win.
14
+ * The last filled button is the one that counts even while it is disabled ("Create" waiting for a name): Enter then does
15
+ * nothing, it does not fall back on another button.
16
+ *
17
+ * When Enter belongs to the control it is pressed on, it is left alone: a focused button or link does its own thing (Enter on
18
+ * "Cancel" cancels), a textarea gets a new line (Cmd or Ctrl + Enter submits), a combobox, a list option that is not chosen
19
+ * yet, a select and a rich text field keep their Enter, and so does everything that has already handled the key
20
+ * (`defaultPrevented`, or a handler that stopped it from travelling on), which is how a dialog that has its own Enter in a
21
+ * field (the rename dialog) keeps working unchanged. A control can say it itself: `data-modal-enter="own"` on it or on something
22
+ * around it keeps Enter for the control, and `data-modal-enter="primary"` on a button hands its Enter to the main button
23
+ * instead (a choice that is only a step towards the main action).
24
+ *
25
+ * The listener is on the window, in the bubble phase, on purpose: Svelte 5 handles `onkeydown="…"` of an element once, at the
26
+ * root of the app, after the key has passed the card. A listener on the card would see the key before the field's own handler
27
+ * and take it from it; on the window it comes last, and sees what the field did with it.
28
+ */
29
+ /** Marks the button that Enter presses. Put it on a button that is not the last filled button of the card. */
30
+ export const modalPrimaryAttribute = 'data-modal-primary';
31
+ /** `own` on a control (or around it) keeps Enter for the control, `primary` on a button hands its Enter to the main button. */
32
+ export const modalEnterAttribute = 'data-modal-enter';
33
+ /** Written by the action on the card of every modal, so that a key press can tell which card is the closest to the focus. */
34
+ export const modalCardAttribute = 'data-modal-card';
35
+ /** The `Button` variants that are filled, that is, that are drawn as a main action. */
36
+ const filledButtonVariants = new Set(['default', 'accent', 'destructive']);
37
+ /** The types of `<input>` that are buttons or pick something themselves: Enter on them is not a "submit". */
38
+ const inputTypesThatKeepEnter = new Set(['button', 'submit', 'reset', 'image', 'file', 'color', 'range']);
39
+ /** Things that do something with Enter when they have the focus. */
40
+ const interactiveSelector = [
41
+ 'button',
42
+ 'a[href]',
43
+ 'summary',
44
+ 'select',
45
+ '[role="button"]',
46
+ '[role="link"]',
47
+ '[role="menuitem"]',
48
+ '[role="menuitemcheckbox"]',
49
+ '[role="menuitemradio"]',
50
+ '[role="tab"]',
51
+ '[role="switch"]',
52
+ '[role="checkbox"]',
53
+ '[role="radio"]',
54
+ '[role="option"]',
55
+ '[role="combobox"]',
56
+ '[role="listbox"]',
57
+ '[role="menu"]',
58
+ '[role="slider"]',
59
+ '[role="treeitem"]',
60
+ '[role="gridcell"]'
61
+ ].join(',');
62
+ /** True when `target` is a rich text field (anything `contenteditable`), where Enter is a new line. */
63
+ function isRichTextField(target) {
64
+ if (target.isContentEditable)
65
+ return true;
66
+ return target.closest('[contenteditable]:not([contenteditable="false"])') !== null;
67
+ }
68
+ /**
69
+ * Whether Enter, pressed with the focus on `target`, belongs to `target` (it does something there) and so is not for the
70
+ * main button. `submitShortcut` is Cmd or Ctrl + Enter, which a textarea gives to the dialog.
71
+ */
72
+ export function targetKeepsEnter(target, submitShortcut = false) {
73
+ // The card of the modal, the page behind it, or nothing: nothing there uses Enter
74
+ if (!target)
75
+ return false;
76
+ // The page says it itself
77
+ const mark = target.closest(`[${modalEnterAttribute}]`)?.getAttribute(modalEnterAttribute);
78
+ if (mark === 'own')
79
+ return true;
80
+ if (mark === 'primary')
81
+ return false;
82
+ if (isRichTextField(target))
83
+ return true;
84
+ const tagName = (target.tagName ?? '').toUpperCase();
85
+ if (tagName === 'TEXTAREA')
86
+ return !submitShortcut;
87
+ if (tagName === 'SELECT')
88
+ return true;
89
+ if (tagName === 'INPUT') {
90
+ const inputType = (target.type || target.getAttribute('type') || 'text').toLowerCase();
91
+ // A combobox is an input too: Enter picks its highlighted option
92
+ if (target.getAttribute('role') === 'combobox' || target.getAttribute('aria-expanded') === 'true')
93
+ return true;
94
+ return inputTypesThatKeepEnter.has(inputType);
95
+ }
96
+ // A list option or a radio that is already chosen: Enter on it is "yes, this one", which is the main button
97
+ const choice = target.closest('[role="option"],[role="radio"]');
98
+ if (choice) {
99
+ const isOption = choice.getAttribute('role') === 'option';
100
+ const isChosen = isOption ? choice.getAttribute('aria-selected') === 'true' : choice.getAttribute('aria-checked') === 'true';
101
+ return !isChosen;
102
+ }
103
+ if (target.getAttribute('aria-expanded') === 'true')
104
+ return true;
105
+ return target.closest(interactiveSelector) !== null;
106
+ }
107
+ /**
108
+ * Whether this key press is an Enter that the modal takes as "the main button": Enter, not handled by anything yet, not part of
109
+ * typing in another script (an IME choosing a character), not a held key (the main button is pressed once), not a line break
110
+ * (Shift or Alt + Enter), and not an Enter that the control it is on keeps for itself.
111
+ */
112
+ export function shouldTakeEnterAsPrimary(facts) {
113
+ if (facts.key !== 'Enter')
114
+ return false;
115
+ if (facts.defaultPrevented)
116
+ return false;
117
+ if (facts.isComposing || facts.keyCode === 229)
118
+ return false;
119
+ if (facts.repeat)
120
+ return false;
121
+ if (facts.shiftKey || facts.altKey)
122
+ return false;
123
+ const submitShortcut = facts.metaKey || facts.ctrlKey;
124
+ return !targetKeepsEnter(facts.target, submitShortcut);
125
+ }
126
+ /** True when the button can be pressed right now: not `disabled`, not `aria-disabled`. */
127
+ export function isActionEnabled(element) {
128
+ if (element.disabled === true)
129
+ return false;
130
+ if (element.hasAttribute?.('disabled'))
131
+ return false;
132
+ return element.getAttribute('aria-disabled') !== 'true';
133
+ }
134
+ function lastOf(items) {
135
+ return items.length > 0 ? items[items.length - 1] : null;
136
+ }
137
+ /** The page default of `isVisible`: the element takes room in the layout. */
138
+ function isDrawn(element) {
139
+ const drawable = element;
140
+ if (drawable.hidden)
141
+ return false;
142
+ return typeof drawable.getClientRects === 'function' ? drawable.getClientRects().length > 0 : true;
143
+ }
144
+ /**
145
+ * The main button of a modal card (see the rules at the top of this file), whether it can be pressed or not, and `null` when
146
+ * the card has none. The caller checks `isActionEnabled`.
147
+ *
148
+ * @param isVisible - Whether an element is drawn (a button inside a closed section is not). The page default reads the layout.
149
+ */
150
+ export function findModalPrimaryAction(card, isVisible = isDrawn) {
151
+ const keepsEnter = (element) => element.closest(`[${modalEnterAttribute}="own"]`) !== null;
152
+ const marked = Array.from(card.querySelectorAll(`[${modalPrimaryAttribute}]`)).filter((element) => isVisible(element) && !keepsEnter(element));
153
+ const markedButton = lastOf(marked);
154
+ if (markedButton)
155
+ return markedButton;
156
+ const filled = Array.from(card.querySelectorAll('[data-variant]')).filter((element) => {
157
+ const tagName = (element.tagName ?? '').toUpperCase();
158
+ if (tagName !== 'BUTTON' && tagName !== 'A')
159
+ return false;
160
+ if (!filledButtonVariants.has(element.getAttribute('data-variant') ?? ''))
161
+ return false;
162
+ return isVisible(element) && !keepsEnter(element);
163
+ });
164
+ return lastOf(filled);
165
+ }
166
+ /** The first element of the event's path: the one that really has the focus (inside a shadow root `event.target` is the host). */
167
+ function focusedElementOf(event) {
168
+ const path = event.composedPath?.();
169
+ const first = path && path.length > 0 ? path[0] : event.target;
170
+ return first && typeof first === 'object' && typeof first.closest === 'function'
171
+ ? first
172
+ : null;
173
+ }
174
+ /**
175
+ * What the decision reads of a key press. The properties are read one by one on purpose: a `KeyboardEvent` keeps them on its
176
+ * prototype, so spreading it into an object copies none of them.
177
+ */
178
+ export function enterKeyFactsOf(event) {
179
+ return {
180
+ key: event.key,
181
+ defaultPrevented: event.defaultPrevented,
182
+ isComposing: event.isComposing,
183
+ repeat: event.repeat,
184
+ shiftKey: event.shiftKey,
185
+ altKey: event.altKey,
186
+ metaKey: event.metaKey,
187
+ ctrlKey: event.ctrlKey,
188
+ keyCode: event.keyCode,
189
+ target: focusedElementOf(event)
190
+ };
191
+ }
192
+ /** How long after the main button was pressed a second Enter is not taken for another press (a double tap, a closing dialog). */
193
+ export const primaryPressCooldownMs = 400;
194
+ /** Whether a press at `lastPressAtMs` still counts as "just now" at `nowMs`. */
195
+ export function isWithinPressCooldown(lastPressAtMs, nowMs, cooldownMs = primaryPressCooldownMs) {
196
+ return nowMs - lastPressAtMs >= 0 && nowMs - lastPressAtMs < cooldownMs;
197
+ }
198
+ /**
199
+ * Presses the main button of `card` for an Enter key press, when the key press is one that the modal takes (see
200
+ * `shouldTakeEnterAsPrimary`) and the card has a main button that can be pressed.
201
+ *
202
+ * The key is then kept from everything else: `preventDefault` stops the browser from also submitting a form the focused field
203
+ * is in (the button's own press does that, once), `stopPropagation` stops the key from travelling on.
204
+ *
205
+ * @returns whether the main button was pressed
206
+ */
207
+ export function activateModalPrimaryOnEnter(event, card, isVisible) {
208
+ if (!shouldTakeEnterAsPrimary(enterKeyFactsOf(event)))
209
+ return false;
210
+ const primaryAction = findModalPrimaryAction(card, isVisible);
211
+ if (!primaryAction || !isActionEnabled(primaryAction))
212
+ return false;
213
+ event.preventDefault();
214
+ event.stopPropagation();
215
+ console.debug('[modal-enter] Enter pressed the main button:', primaryAction.textContent?.trim() ?? '');
216
+ primaryAction.click();
217
+ return true;
218
+ }
219
+ /**
220
+ * Whether the key press belongs to `card`: it was pressed inside it, and no other modal card is closer to the focus (a modal
221
+ * drawn inside another one's markup is the closest one).
222
+ */
223
+ export function keyPressBelongsToCard(path, card) {
224
+ let closestCard = null;
225
+ for (let index = 0; index < path.length; index += 1) {
226
+ const node = path[index];
227
+ if (node && typeof node.hasAttribute === 'function' && node.hasAttribute(modalCardAttribute)) {
228
+ closestCard = node;
229
+ break;
230
+ }
231
+ }
232
+ return closestCard !== null && closestCard === card;
233
+ }
234
+ /**
235
+ * Svelte action for the card of a modal: Enter pressed inside the card presses its main button (see the top of this file).
236
+ * `enabled: false` switches it off for a modal that wants Enter for itself.
237
+ */
238
+ export function modalEnterKey(card, options = {}) {
239
+ let enabled = options.enabled !== false;
240
+ let lastPressAtMs = Number.NEGATIVE_INFINITY;
241
+ card.setAttribute(modalCardAttribute, '');
242
+ function handleKeydown(event) {
243
+ if (!enabled || event.key !== 'Enter')
244
+ return;
245
+ try {
246
+ if (!keyPressBelongsToCard(event.composedPath(), card))
247
+ return;
248
+ const keyEvent = event;
249
+ // The main button was pressed a moment ago (a double tap, or the dialog is still closing): this Enter must not press
250
+ // it again, and must not be left to submit a form either
251
+ if (isWithinPressCooldown(lastPressAtMs, Date.now())) {
252
+ if (shouldTakeEnterAsPrimary(enterKeyFactsOf(keyEvent))) {
253
+ event.preventDefault();
254
+ event.stopPropagation();
255
+ }
256
+ return;
257
+ }
258
+ if (activateModalPrimaryOnEnter(keyEvent, card)) {
259
+ lastPressAtMs = Date.now();
260
+ }
261
+ }
262
+ catch (error) {
263
+ console.warn('[modal-enter] Could not press the main button for Enter:', error);
264
+ }
265
+ }
266
+ window.addEventListener('keydown', handleKeydown);
267
+ return {
268
+ update(nextOptions = {}) {
269
+ enabled = nextOptions.enabled !== false;
270
+ },
271
+ destroy() {
272
+ window.removeEventListener('keydown', handleKeydown);
273
+ card.removeAttribute(modalCardAttribute);
274
+ }
275
+ };
276
+ }
@@ -11,6 +11,13 @@ export declare function getTabbableElements(root: HTMLElement): HTMLElement[];
11
11
  * shadow root, and the file browser lives in one when an app embeds it).
12
12
  */
13
13
  export declare function deepActiveElement(root?: Document | ShadowRoot): HTMLElement | null;
14
+ /**
15
+ * Where the focus goes when a dialog opens: the element that asks for it (`autofocus` or `data-autofocus`), else the first field
16
+ * to type in, else the card itself. Never a button: the first button of a confirm dialog is "Cancel", and with the focus on it
17
+ * Enter would cancel the dialog instead of pressing its main button (see `modalEnterKey`). The card is focusable
18
+ * (`tabindex="-1"`), so the screen reader reads the dialog first and Tab goes to its first control.
19
+ */
20
+ export declare function dialogInitialFocusTarget(card: HTMLElement): HTMLElement;
14
21
  /**
15
22
  * Where focus must wrap to when Tab (or Shift+Tab) would otherwise leave the modal. `null` means the browser's own Tab is fine:
16
23
  * the trap steps in only at the two ends of the modal (and when focus is not in the modal at all), so the tab order everywhere
@@ -89,6 +89,28 @@ export function deepActiveElement(root = document) {
89
89
  }
90
90
  return active instanceof HTMLElement ? active : null;
91
91
  }
92
+ /** Fields where a person types: where a dialog that has one puts the focus when it opens. */
93
+ const TEXT_ENTRY_SELECTOR = [
94
+ 'input:not([type="hidden"]):not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="checkbox"]):not([type="radio"]):not([type="file"]):not([type="image"]):not([type="color"]):not([type="range"]):not([disabled])',
95
+ 'textarea:not([disabled])',
96
+ '[contenteditable]:not([contenteditable="false"])'
97
+ ].join(',');
98
+ /**
99
+ * Where the focus goes when a dialog opens: the element that asks for it (`autofocus` or `data-autofocus`), else the first field
100
+ * to type in, else the card itself. Never a button: the first button of a confirm dialog is "Cancel", and with the focus on it
101
+ * Enter would cancel the dialog instead of pressing its main button (see `modalEnterKey`). The card is focusable
102
+ * (`tabindex="-1"`), so the screen reader reads the dialog first and Tab goes to its first control.
103
+ */
104
+ export function dialogInitialFocusTarget(card) {
105
+ const requested = card.querySelector('[autofocus],[data-autofocus]');
106
+ if (requested && isFocusable(requested))
107
+ return requested;
108
+ for (const field of card.querySelectorAll(TEXT_ENTRY_SELECTOR)) {
109
+ if (isFocusable(field))
110
+ return field;
111
+ }
112
+ return card;
113
+ }
92
114
  /**
93
115
  * Where focus must wrap to when Tab (or Shift+Tab) would otherwise leave the modal. `null` means the browser's own Tab is fine:
94
116
  * the trap steps in only at the two ends of the modal (and when focus is not in the modal at all), so the tab order everywhere
@@ -11,6 +11,15 @@ export declare const overlayContentScaleStart = 0.95;
11
11
  export declare const overlayContentSlideDistance = 5;
12
12
  export declare const overlayContentSlidePx: number;
13
13
  export declare const overlayDialogContentSlideClasses: readonly ["data-[state=closed]:slide-out-to-bottom-5", "data-[state=open]:slide-in-from-bottom-5"];
14
+ /**
15
+ * A floating surface that opens from a trigger (dropdown, sub-menu, popover, select list, hover card) fades in and slides 8px from
16
+ * the side it opens towards in 150ms: the quick cousin of the dialog's 20px, 200ms. The motion itself is the `floating-motion`
17
+ * utility of `styles/tokens.css` (`--duration-floating`, `--floating-slide`); these are the same numbers for tests and for code that
18
+ * has to wait for it.
19
+ */
20
+ export declare const overlayFloatingDurationMs = 150;
21
+ export declare const overlayFloatingSlidePx = 8;
22
+ export declare const overlayFloatingMotionClass = "floating-motion";
14
23
  export declare const overlayDurationClass = "duration-[200ms]";
15
24
  export declare const overlayScrimColorClass = "bg-muted-foreground/80";
16
25
  export declare const overlayBackdropBlurClass = "backdrop-blur-[3px]";
@@ -14,6 +14,15 @@ export const overlayDialogContentSlideClasses = [
14
14
  `data-[state=closed]:slide-out-to-bottom-${overlayContentSlideDistance}`,
15
15
  `data-[state=open]:slide-in-from-bottom-${overlayContentSlideDistance}`
16
16
  ];
17
+ /**
18
+ * A floating surface that opens from a trigger (dropdown, sub-menu, popover, select list, hover card) fades in and slides 8px from
19
+ * the side it opens towards in 150ms: the quick cousin of the dialog's 20px, 200ms. The motion itself is the `floating-motion`
20
+ * utility of `styles/tokens.css` (`--duration-floating`, `--floating-slide`); these are the same numbers for tests and for code that
21
+ * has to wait for it.
22
+ */
23
+ export const overlayFloatingDurationMs = 150;
24
+ export const overlayFloatingSlidePx = 8;
25
+ export const overlayFloatingMotionClass = 'floating-motion';
17
26
  export const overlayDurationClass = 'duration-[200ms]';
18
27
  export const overlayScrimColorClass = 'bg-muted-foreground/80';
19
28
  export const overlayBackdropBlurClass = 'backdrop-blur-[3px]';
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Keeps a section that is opening (an accordion item) in view.
3
+ *
4
+ * A section that opens near the bottom of a scrolling box grows below the edge of it, and the person has to scroll to read what
5
+ * they just opened. While the section opens (its height animation, and a moment after for content that arrives late), its
6
+ * bottom edge is followed: the box is scrolled by the few pixels that are missing, every frame, so the content comes into view
7
+ * with the motion of the opening instead of after it. The top of the section is never pushed out of the box: a section that is
8
+ * taller than the box shows its title and as much of its content as fits.
9
+ *
10
+ * It stops by itself, and as soon as the person takes the scrolling over (wheel, touch, pressing the scrollbar).
11
+ */
12
+ /** Room kept under the content that is brought into view, so its last row does not touch the edge of the box. */
13
+ export declare const revealBottomMarginPx = 16;
14
+ /** How long an opening section is followed: its height animation (200 ms) plus a moment for content that arrives late. */
15
+ export declare const revealFollowDurationMs = 1200;
16
+ /** The vertical edges of an element, in the coordinates of the window (what `getBoundingClientRect` returns). */
17
+ export interface RevealEdges {
18
+ topPx: number;
19
+ bottomPx: number;
20
+ }
21
+ /**
22
+ * How many pixels the box has to scroll down so that the bottom of the section is visible, with `marginPx` of room under it.
23
+ * Never more than what keeps the top of the section in the box, and `0` when the section is already in view or the person
24
+ * has scrolled past its top.
25
+ */
26
+ export declare function scrollDeltaToRevealSection(section: RevealEdges, viewport: RevealEdges, marginPx?: number): number;
27
+ /** The values of `overflow-y` that make an element a scrolling box. */
28
+ export declare function isScrollingOverflow(overflowY: string): boolean;
29
+ /** What `findScrollParent` needs from an element: its parent. */
30
+ interface ElementWithParent {
31
+ parentElement: ElementWithParent | null;
32
+ }
33
+ /**
34
+ * The nearest ancestor that scrolls (`overflow-y: auto | scroll | overlay`), or `null` when the page itself is what scrolls.
35
+ * The section is not asked: its own `overflow-hidden` clips its content and does not scroll it.
36
+ */
37
+ export declare function findScrollParent<T extends ElementWithParent>(element: T, readOverflowY?: (candidate: T) => string): T | null;
38
+ export interface FollowOpeningSectionOptions {
39
+ /** How long the section is followed, in milliseconds. */
40
+ durationMs?: number;
41
+ /** Room kept under the section, in pixels. */
42
+ marginPx?: number;
43
+ /** Reads `overflow-y` of an element (the computed style by default); a test gives its own. */
44
+ readOverflowY?: (candidate: HTMLElement) => string;
45
+ }
46
+ /**
47
+ * Follows `section` while it opens and scrolls its scrolling box so the bottom of the section stays in view.
48
+ * Returns a function that stops the follow (it also stops by itself after `durationMs` and when the person scrolls).
49
+ */
50
+ export declare function followOpeningSection(section: HTMLElement, options?: FollowOpeningSectionOptions): () => void;
51
+ export {};
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Keeps a section that is opening (an accordion item) in view.
3
+ *
4
+ * A section that opens near the bottom of a scrolling box grows below the edge of it, and the person has to scroll to read what
5
+ * they just opened. While the section opens (its height animation, and a moment after for content that arrives late), its
6
+ * bottom edge is followed: the box is scrolled by the few pixels that are missing, every frame, so the content comes into view
7
+ * with the motion of the opening instead of after it. The top of the section is never pushed out of the box: a section that is
8
+ * taller than the box shows its title and as much of its content as fits.
9
+ *
10
+ * It stops by itself, and as soon as the person takes the scrolling over (wheel, touch, pressing the scrollbar).
11
+ */
12
+ /** Room kept under the content that is brought into view, so its last row does not touch the edge of the box. */
13
+ export const revealBottomMarginPx = 16;
14
+ /** How long an opening section is followed: its height animation (200 ms) plus a moment for content that arrives late. */
15
+ export const revealFollowDurationMs = 1200;
16
+ /**
17
+ * How many pixels the box has to scroll down so that the bottom of the section is visible, with `marginPx` of room under it.
18
+ * Never more than what keeps the top of the section in the box, and `0` when the section is already in view or the person
19
+ * has scrolled past its top.
20
+ */
21
+ export function scrollDeltaToRevealSection(section, viewport, marginPx = revealBottomMarginPx) {
22
+ const hiddenBelowPx = section.bottomPx + marginPx - viewport.bottomPx;
23
+ if (hiddenBelowPx <= 0)
24
+ return 0;
25
+ const roomAbovePx = section.topPx - viewport.topPx;
26
+ if (roomAbovePx <= 0)
27
+ return 0;
28
+ return Math.min(hiddenBelowPx, roomAbovePx);
29
+ }
30
+ /** The values of `overflow-y` that make an element a scrolling box. */
31
+ export function isScrollingOverflow(overflowY) {
32
+ return overflowY === 'auto' || overflowY === 'scroll' || overflowY === 'overlay';
33
+ }
34
+ /**
35
+ * The nearest ancestor that scrolls (`overflow-y: auto | scroll | overlay`), or `null` when the page itself is what scrolls.
36
+ * The section is not asked: its own `overflow-hidden` clips its content and does not scroll it.
37
+ */
38
+ export function findScrollParent(element, readOverflowY = (candidate) => getComputedStyle(candidate).overflowY) {
39
+ let candidate = element.parentElement;
40
+ while (candidate) {
41
+ if (isScrollingOverflow(readOverflowY(candidate)))
42
+ return candidate;
43
+ candidate = candidate.parentElement;
44
+ }
45
+ return null;
46
+ }
47
+ /** The follow that runs for a section: a second toggle of the same section replaces it. */
48
+ const followsBySection = new WeakMap();
49
+ /** The events with which the person takes the scrolling over: the follow stops at the first one. */
50
+ const takeOverEventNames = ['wheel', 'touchstart', 'pointerdown'];
51
+ /**
52
+ * Follows `section` while it opens and scrolls its scrolling box so the bottom of the section stays in view.
53
+ * Returns a function that stops the follow (it also stops by itself after `durationMs` and when the person scrolls).
54
+ */
55
+ export function followOpeningSection(section, options = {}) {
56
+ const { durationMs = revealFollowDurationMs, marginPx = revealBottomMarginPx, readOverflowY } = options;
57
+ // A new toggle of the same section replaces the follow that is still running.
58
+ followsBySection.get(section)?.();
59
+ if (typeof window === 'undefined' || typeof ResizeObserver === 'undefined')
60
+ return () => { };
61
+ try {
62
+ const scrollParent = findScrollParent(section, readOverflowY);
63
+ function readViewportEdges() {
64
+ if (scrollParent) {
65
+ const box = scrollParent.getBoundingClientRect();
66
+ return { topPx: box.top, bottomPx: box.bottom };
67
+ }
68
+ return { topPx: 0, bottomPx: window.innerHeight };
69
+ }
70
+ function revealSection() {
71
+ try {
72
+ const box = section.getBoundingClientRect();
73
+ const deltaPx = scrollDeltaToRevealSection({ topPx: box.top, bottomPx: box.bottom }, readViewportEdges(), marginPx);
74
+ if (deltaPx <= 0)
75
+ return;
76
+ if (scrollParent)
77
+ scrollParent.scrollTop += deltaPx;
78
+ else
79
+ window.scrollBy(0, deltaPx);
80
+ }
81
+ catch (error) {
82
+ console.warn('[reveal-opening-section] could not keep the opening section in view:', error);
83
+ }
84
+ }
85
+ // The section grows every frame while its content opens: each change of size is a frame in which the missing pixels are scrolled.
86
+ const sizeObserver = new ResizeObserver(revealSection);
87
+ sizeObserver.observe(section);
88
+ const takeOverTarget = scrollParent ?? window;
89
+ const stopTimer = setTimeout(stopFollowing, durationMs);
90
+ function stopFollowing() {
91
+ sizeObserver.disconnect();
92
+ clearTimeout(stopTimer);
93
+ for (const eventName of takeOverEventNames) {
94
+ takeOverTarget.removeEventListener(eventName, stopFollowing);
95
+ }
96
+ if (followsBySection.get(section) === stopFollowing)
97
+ followsBySection.delete(section);
98
+ }
99
+ for (const eventName of takeOverEventNames) {
100
+ takeOverTarget.addEventListener(eventName, stopFollowing, { passive: true });
101
+ }
102
+ followsBySection.set(section, stopFollowing);
103
+ return stopFollowing;
104
+ }
105
+ catch (error) {
106
+ console.warn('[reveal-opening-section] could not follow the opening section:', error);
107
+ return () => { };
108
+ }
109
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/design-system",
3
- "version": "0.5.41",
3
+ "version": "0.5.42",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "svelte": "./dist/index.js",