athena-ui-js 2.0.1 → 2.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.
Files changed (30) hide show
  1. package/README.md +58 -4
  2. package/docs/migration-2.0.md +1 -1
  3. package/docs/styling.md +24 -7
  4. package/package.json +5 -1
  5. package/src/athena-ui.js +2 -1
  6. package/src/libs/config/config.js +1 -1
  7. package/src/libs/core/motion.js +358 -0
  8. package/src/libs/core/popover.js +96 -0
  9. package/src/libs/core/theme.js +12 -0
  10. package/src/libs/hephaestus/chartGenerator/chartGenerator.js +9 -5
  11. package/src/libs/hephaestus/componentGenerator/componentGenerator.js +43 -2
  12. package/src/libs/hephaestus/dialogGenerator/dialogGenerator.js +2 -1
  13. package/src/libs/hephaestus/feedbackGenerator/feedbackGenerator.js +3 -1
  14. package/src/libs/hephaestus/navigationGenerator/navigationGenerator.js +45 -9
  15. package/src/libs/hephaestus/router/router.js +18 -9
  16. package/src/libs/hephaestus/tableGenerator/tableGenerator.js +25 -0
  17. package/src/motion.js +6 -0
  18. package/src/res/themes/default/style.css +260 -10
  19. package/src/res/themes/tokens.css +25 -0
  20. package/types/athena-ui.d.ts +97 -96
  21. package/types/libs/config/config.d.ts +3 -3
  22. package/types/libs/core/motion.d.ts +123 -0
  23. package/types/libs/core/popover.d.ts +36 -0
  24. package/types/libs/core/theme.d.ts +41 -39
  25. package/types/libs/hephaestus/chartGenerator/chartGenerator.d.ts +2 -0
  26. package/types/libs/hephaestus/componentGenerator/componentGenerator.d.ts +238 -222
  27. package/types/libs/hephaestus/navigationGenerator/navigationGenerator.d.ts +4 -1
  28. package/types/libs/hephaestus/router/router.d.ts +71 -67
  29. package/types/libs/hephaestus/tableGenerator/tableGenerator.d.ts +123 -120
  30. package/types/motion.d.ts +1 -0
package/README.md CHANGED
@@ -5,7 +5,7 @@ layout (header, menu, content wrapper, footer) from a single `init()` call, load
5
5
  and theme, and ships the building blocks of a multipurpose application: forms, tables, charts,
6
6
  feedback, navigation, a router and more.
7
7
 
8
- Current version: **2.0.1**
8
+ Current version: **2.2.0**
9
9
 
10
10
  [Quick start](#usage) · [API](#api) · [Components](#charts) · [Themes](#themes) · [Tests](#tests) · [Release notes](#releases)
11
11
 
@@ -22,7 +22,7 @@ Known limits are listed below, so you can judge whether it fits your project:
22
22
  - Athena UI has **no dependencies**: no jQuery, no bundled library, nothing is loaded at run time, and nothing is put on `window` unless you opt in with
23
23
  `athena-ui-js/classic`. The older generators (`generateLoginForm`, the layout and the header / footer menu built from `menuItems`) are plain DOM too.
24
24
  - The default theme follows the system's dark mode. Put `data-mode="light"` on `<html>` (or use `createThemeManager`) to choose.
25
- - Dialogs and the accordion use the native `<dialog>` and `<details>` elements, so they need a browser that supports cascade layers and `<dialog>` (2022 or later). The dropdown still has its own menu.
25
+ - Dialogs, the accordion, the dropdown menu and tooltips use the native `<dialog>`, `<details>` and popover elements, so they need a browser that supports cascade layers and `<dialog>` (2022 or later). The dropdown menu and the tooltips are native popovers (the `popover` attribute) in browsers that have them (Chrome / Edge 114, Safari 17, Firefox 125), and a plain fallback in older ones.
26
26
 
27
27
  ## Features
28
28
 
@@ -67,13 +67,15 @@ import { generateTable } from "athena-ui-js/table"; // or only what you u
67
67
  ```
68
68
 
69
69
  The entry points are `table`, `chart`, `dialog`, `menu`, `navigation`, `forms`, `feedback`, `components`, `inputs`, `router`, `session`, `theme`, `i18n`, `format`,
70
- `validation`, `sanitize`, `csv`, `dom` and `controls`. TypeScript definitions are included (`types/`, generated from the JSDoc with `npm run types`).
70
+ `validation`, `motion`, `sanitize`, `csv`, `dom` and `controls`. TypeScript definitions are included (`types/`, generated from the JSDoc with `npm run types`).
71
71
  The package has `"sideEffects"` for `classic.js`, `theme-boot.js` and CSS only, so a bundler drops everything you do not import.
72
72
 
73
73
  Without npm, serve the `src` folder with any static web server and open `index.html` to see the example.
74
74
 
75
75
  ### The demo application
76
76
 
77
+ **Try it live: https://athena-ui-js-demo-duc7dncrfhg5fxfs.northeurope-01.azurewebsites.net** (sign in with `demo` / `demo-pass`, or `admin` / `admin-pass`; the app sleeps when nobody visits, so the first request can take a few seconds).
78
+
77
79
  `demo/` is a demo and test application: tables with 100,000 rows from a server, a streaming chart, every field type, native dialogs, a menu with groups inside groups, themes
78
80
  and modes, and a real sign in, served by a small Node server (no dependencies) under a strict Content-Security-Policy.
79
81
 
@@ -147,7 +149,7 @@ It takes the options of `init()`. The header and footer follow the settings `gen
147
149
  | `header_title_text` | `"Athena UI"` | Title in the header |
148
150
  | `header_img_url` | | Header logo URL |
149
151
  | `copyright` | placeholder text | Footer text, the version is appended |
150
- | `version` | `"2.0.1"` | Version shown in the footer |
152
+ | `version` | `"2.2.0"` | Version shown in the footer |
151
153
  | `bordered` | `true` | Draw a border around the layout blocks |
152
154
  | `generateHeader`, `generateFooter` | `true` | Generate the header / footer block |
153
155
  | `generateHeadercontent`, `generateFooterContent`, `generateWrappercontent` | `true` | Generate the content of the block |
@@ -192,6 +194,7 @@ Everything is exported from `athena-ui.js`:
192
194
  | `generatePageHeader`, `generateFacts`, `generateEmptyState`, `generateLoading`, `copyToClipboard` | See [Page parts and formatting](#page-parts-and-formatting) |
193
195
  | `formatBytes`, `formatNumber`, `formatDuration`, `formatRelativeTime`, `formatDate` | Format helpers on top of `Intl`, in the current language |
194
196
  | `el`, `setContent`, `resolveElement`, `asHandle`, `createSafeBuilder` | See [Safe DOM building](#safe-dom-building) |
197
+ | `animate`, `flip`, `stagger`, `spring`, `tween`, `transition`, `viewTransition`, `setMotion`, `prefersReducedMotion`, `easings`, `generateSkeleton` | See [Motion](#motion-animations-and-transitions) |
195
198
  | `generateCard`, `generateSection`, `generateGrid`, `generateBadge`, `generateAvatar`, `generateStat`, `generateLink`, `generateTooltip` | See [Components](#components) |
196
199
  | `generateAutocomplete`, `generateMultiSelect`, `generateFileUpload`, `generateDropZone`, `generateStepper`, `generateDateRange`, `generateRichText`, `generateWysiwyg` | See [Inputs](#inputs) |
197
200
  | `sanitizeHtml(html)`, `htmlToText(html)`, `isSafeUrl(url)` | The allow-list sanitizer behind the rich text editor |
@@ -355,6 +358,11 @@ never parsed as HTML. `openModal` / `closeModal` got the same focus handling.
355
358
 
356
359
  ### Navigation
357
360
 
361
+ The **dropdown** menu and the **tooltip** are native popovers: they are drawn in the top layer, so no parent with `overflow: hidden` can cut them off and no `z-index` fight is possible;
362
+ a click outside and Esc close the dropdown, and the focus goes back to its button. They are placed next to their button by a small helper (it sets two CSS variables, which a strict
363
+ Content-Security-Policy allows): below, or above when there is no room below, and always kept inside the window. A tooltip shows on hover and on focus and goes on Esc; a touch does not show it.
364
+ Without the popover API the dropdown is a plain menu that is shown and hidden with `hidden`, and the tooltip a CSS one.
365
+
358
366
  ```js
359
367
  generateTabs({ parent: "wrapper", tabs: [{ id: "a", label: "A", content: "First" }, { id: "b", label: "B", content: () => lazyNode() }] });
360
368
  generateAccordion({ parent: "wrapper", items: [{ title: "Q", content: "A", open: true }], multiple: false });
@@ -651,6 +659,41 @@ await copyToClipboard(token); // an
651
659
  formatBytes(1536); formatNumber(1234567.891); formatDuration(7500000); formatRelativeTime(date); formatDate(date, { time: true }); // Intl, in the current language
652
660
  ```
653
661
 
662
+ ### Motion: animations and transitions
663
+
664
+ Motion is an enhancement. Every transition and animation of Athena UI reads the tokens `--athena-duration-fast` (120 ms), `--athena-duration-base` (200 ms) and `--athena-duration-slow` (360 ms),
665
+ and `--athena-ease-standard`, `-in`, `-out` and `-spring`, so one variable slows down or switches off all of it. They are **0 under reduced motion**: when the system asks for it
666
+ (`prefers-reduced-motion`), or the person does (`data-motion="reduce"` on `<html>`, which `setMotion("reduce")` sets; `"full"` keeps the motion although the system asks for less).
667
+ Nothing waits for a transition before it works, and nothing needs an inline style (a strict Content-Security-Policy is fine: CSS classes, custom properties and the Web Animations API).
668
+
669
+ What the components do by themselves:
670
+ - a **dialog** fades and rises in and fades out; the **dropdown menu** and the **tooltip** fade; a **toast** slides in and out; an **accordion** opens smoothly;
671
+ a **progress bar** moves smoothly; a **skeleton** (`generateSkeleton`) shimmers;
672
+ - a **chart** draws itself the first time (bars grow, the line is drawn, slices pop in; `animate: false` turns it off, and it never replays while streaming or zooming);
673
+ - the **theme manager** cross-fades colours when the theme or the mode changes (`createThemeManager({ transition: false })` turns it off);
674
+ - a **table** with `animateRows: true` slides its rows to their new place when sorted, filtered or paged (at most 60 rows, not in a virtual table);
675
+ - the **router** with `transition: true` makes a page change a view transition (`document.startViewTransition`): the old page cross-fades into the new one, and elements with a
676
+ `view-transition-name` move from one page to the next. The old page stays until the page function of the new one has finished, so a page that needs long should draw something first.
677
+
678
+ `athena-ui-js/motion` has the same tools for your own code; all of them resolve at once under reduced motion:
679
+
680
+ ```js
681
+ import { animate, flip, stagger, spring, tween, easings, transition, viewTransition, setMotion, prefersReducedMotion } from "athena-ui-js/motion";
682
+
683
+ await animate(card, [{ opacity: 0, translate: "0 16px" }, { opacity: 1, translate: "0 0" }]); // the Web Animations API, with the tokens as defaults; resolves at the end
684
+ await flip(list, () => list.append(...sorted)); // rows slide from where they were to where they are; new ones fade in
685
+ await stagger(items, (item, index, delay) => animate(item, frames, { delay }), { step: 40 }); // one after the other
686
+ const { easing, duration } = spring({ stiffness: 220, damping: 12 }); // a spring as a CSS easing (linear()), it overshoots
687
+ await animate(ball, [{ translate: "0 0" }, { translate: "240px 0" }], { easing, duration });
688
+ tween({ from: 0, to: 100, duration: 600, easing: easings.easeOutCubic, onUpdate: value => counter.textContent = Math.round(value) }); // numbers over time (games, counters)
689
+ await transition(panel, () => panel.classList.add("open")); // a change made with CSS: resolves when its transition is over
690
+ await viewTransition(() => swapContent()); // cross-fades the change where the browser can
691
+ setMotion("reduce"); // "system" | "reduce" | "full"
692
+ ```
693
+
694
+ In a page that is not drawn (a hidden tab) there are no frames: `animate` and `tween` finish by a timer, so nothing hangs. Dialogs and toasts stay in the page for the length of their
695
+ exit transition (none under reduced motion); in your tests call `setMotion("reduce")` first, so they are gone at once.
696
+
654
697
  ### Safe DOM building
655
698
 
656
699
  `el(tag, { class, id, text, attrs, on, prop }, ...children)` is the way Athena builds its own pages, and it is exported. Strings are only ever inserted as **text**, children can be
@@ -741,6 +784,17 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
741
784
 
742
785
  ## Releases
743
786
 
787
+ ### 2.1.0
788
+ #### Changed:
789
+ 1. The dropdown menu is a native popover (`popover="auto"`, opened by its button through `popovertarget`): it is drawn in the top layer, so no parent with `overflow: hidden` cuts it off; a click outside and Esc close it and the focus goes back to the button; `aria-expanded` follows every way of opening and closing it. Markup: the menu has the attribute `popover` and no `hidden` any more (use `:popover-open`)
790
+ 2. The tooltip is a native popover (`popover="manual"`): shown on hover and on keyboard focus, hidden on leave, blur and Esc, never shown by a touch, and never cut off by a parent
791
+ 3. Both are placed next to their button by a small helper that sets two CSS variables (`--athena-popover-left`, `--athena-popover-top`; allowed by a strict Content-Security-Policy): below, or above when there is no room below, centred or aligned to an edge, and always kept inside the window; they follow the button when the page scrolls or resizes
792
+ 4. Browsers without the popover API keep the previous behaviour (a plain menu shown with `hidden` and closed by a click outside, a CSS tooltip)
793
+ #### Added:
794
+ 1. `src/libs/core/popover.js` (placement helpers) and the CSS class `.athena-popover`
795
+ 2. The address of the live demo in the READMEs
796
+ 3. Section 3 ("Make it lighter") of the to-do list is complete: the native elements are `<dialog>`, `<details>` and the popover
797
+
744
798
  ### 2.0.1
745
799
  #### Added:
746
800
  1. `demo/`: a demo and test application of Athena UI (tables with 100,000 rows from a server, streaming charts, forms, dialogs, menus, themes, sign in) with a dependency free Node server, and end to end tests that drive a real browser (DevTools protocol) under a strict Content-Security-Policy
@@ -53,7 +53,7 @@ They are part of Athena UI (`athena-ui-js/controls`) and no longer git submodule
53
53
  `athena-ui-js/testing`, which gives jsdom `showModal()`; a synthetic Esc key does not close a native dialog, send the `cancel` event instead.
54
54
  - `generateAccordion` is `<details>` and `<summary>`: `.accordion-header` is a `<summary>`, there is no `aria-expanded` on a button, `.accordion-open` is the
55
55
  `[open]` attribute and `.accordion-title` is gone. `accordion.toggle(index, open)` works as before.
56
- - The dropdown keeps its own menu (a top-layer `popover` would need anchor positioning, which not every supported browser has yet).
56
+ - The dropdown and the tooltip became native popovers in 2.1 (see the release notes): the menu is `<div class="dropdown-menu" popover>` (no `hidden` attribute any more: use `:popover-open`), and the tooltip text is a `popover="manual"` element.
57
57
 
58
58
  ## 6. CSS: a layer, tokens and dark mode
59
59
 
package/docs/styling.md CHANGED
@@ -40,6 +40,13 @@ Start with the tokens, they cover most of what people want to change.
40
40
  | `--athena-dialog-medium` | `480px` |
41
41
  | `--athena-dialog-large` | `720px` |
42
42
  | `--athena-row-height` | `36px` |
43
+ | `--athena-duration-fast` | `120ms` |
44
+ | `--athena-duration-base` | `200ms` |
45
+ | `--athena-duration-slow` | `360ms` |
46
+ | `--athena-ease-standard` | `cubic-bezier(0.2, 0, 0, 1)` |
47
+ | `--athena-ease-in` | `cubic-bezier(0.4, 0, 1, 1)` |
48
+ | `--athena-ease-out` | `cubic-bezier(0, 0, 0.2, 1)` |
49
+ | `--athena-ease-spring` | `linear(0, 0.009, 0.035 2.1%, 0.141 4.4%, 0.723 12.9%, 0.938 16.7%, 1.017 19.4%, 1.077 22.8%, 1.121 26.7%, 1.149 31.2%, 1.159 36.2%, 1.138 49.9%, 1.115 56.3%, 1.043 69.7%, 1.009 81.2%, 0.998 92.1%, 1)` |
43
50
 
44
51
  Dark colours: set `data-mode="dark"` on `<html>` (or let `createThemeManager` do it); without the attribute the system decides. Themes: see `appearance.css`.
45
52
 
@@ -54,25 +61,28 @@ Dark colours: set `data-mode="dark"` on `<html>` (or let `createThemeManager` do
54
61
  | Modal close button | `.close` | `--athena-fg` `--athena-muted` |
55
62
  | Buttons | `.athena-button` `.button-danger` `.button-large` `.button-link` `.button-secondary` `.button-small` | `--athena-accent` `--athena-accent-fg` `--athena-danger` `--athena-fg` `--athena-line` `--athena-radius` `--athena-surface` |
56
63
  | Forms | `.athena-form` `.choice` `.choices` `.field` `.field-error` `.field-group` `.field-help` `.field-invalid` `.field-label` `.field-required` `.form-actions` `.form-message` `.form-message-error` `.form-message-success` | `--athena-border-width` `--athena-danger` `--athena-line` `--athena-muted` `--athena-radius` `--athena-space-1` `--athena-space-2` `--athena-space-3` `--athena-success` |
57
- | Switch: a checkbox drawn as a toggle | `.switch` `.switch-track` | `--athena-accent` `--athena-line` |
58
- | Spinner, alerts, toasts, progress | `.alert` `.alert-body` `.alert-close` `.alert-error` `.alert-info` `.alert-success` `.alert-warning` `.button-loading` `.progress-bar` `.progress-error` `.progress-fill` `.progress-indeterminate` `.progress-label` `.progress-success` `.progress-warning` `.spinner` `.spinner-large` `.spinner-small` `.toast` `.toast-container` | `--alert-color` `--athena-accent` `--athena-border-width` `--athena-danger` `--athena-fg` `--athena-info` `--athena-line` `--athena-muted` `--athena-radius` `--athena-shadow` `--athena-space-2` `--athena-space-3` `--athena-success` `--athena-surface` `--athena-surface-alt` `--athena-warning` `--progress-color` |
64
+ | Switch: a checkbox drawn as a toggle | `.switch` `.switch-track` | `--athena-accent` `--athena-duration-fast` `--athena-ease-standard` `--athena-line` |
65
+ | Spinner, alerts, toasts, progress | `.alert` `.alert-body` `.alert-close` `.alert-error` `.alert-info` `.alert-success` `.alert-warning` `.button-loading` `.progress-bar` `.progress-error` `.progress-fill` `.progress-indeterminate` `.progress-label` `.progress-success` `.progress-warning` `.spinner` `.spinner-large` `.spinner-small` `.toast` `.toast-container` | `--alert-color` `--athena-accent` `--athena-border-width` `--athena-danger` `--athena-duration-base` `--athena-ease-standard` `--athena-fg` `--athena-info` `--athena-line` `--athena-muted` `--athena-radius` `--athena-shadow` `--athena-space-2` `--athena-space-3` `--athena-success` `--athena-surface` `--athena-surface-alt` `--athena-warning` `--progress-color` |
59
66
  | Dialog: the native <dialog> element, opened with showModal() | `.dialog` | `--athena-bg` `--athena-border-width` `--athena-dialog-medium` `--athena-fg` `--athena-line` `--athena-overlay` `--athena-radius` `--athena-shadow` `--dialog-width` |
60
67
  | The content fills the dialog up to its edge, so a click on the backdrop is a click on the dialog element itself | `.dialog-body` `.dialog-close` `.dialog-footer` `.dialog-full` `.dialog-inner` `.dialog-large` `.dialog-medium` `.dialog-small` `.dialog-title` | `--athena-dialog-large` `--athena-dialog-medium` `--athena-dialog-small` `--athena-muted` `--athena-space-2` |
61
68
  | Tabs | `.tab` `.tab-active` `.tab-list` `.tab-panel` | `--athena-accent` `--athena-border-width` `--athena-fg` `--athena-line` |
62
69
  | Breadcrumbs, pagination | `.breadcrumb-item` `.breadcrumb-list` `.page-button` `.page-current` `.pagination` | `--athena-accent` `--athena-accent-fg` `--athena-bg` `--athena-border-width` `--athena-fg` `--athena-line` `--athena-muted` `--athena-space-1` |
63
- | Accordion: <details> and <summary> | `.accordion-header` `.accordion-icon` `.accordion-item` `.accordion-panel` `.sidebar-parent` | `--athena-accent` `--athena-border-width` `--athena-fg` `--athena-focus` `--athena-focus-width` `--athena-line` `--athena-surface` |
64
- | Dropdown | `.dropdown` `.dropdown-divider` `.dropdown-item` `.dropdown-menu` `.dropdown-right` | `--athena-bg` `--athena-border-width` `--athena-fg` `--athena-hover` `--athena-line` `--athena-radius` `--athena-shadow` |
70
+ | Accordion: <details> and <summary> | `.accordion-header` `.accordion-icon` `.accordion-item` `.accordion-panel` `.sidebar-parent` | `--athena-accent` `--athena-border-width` `--athena-duration-fast` `--athena-ease-standard` `--athena-fg` `--athena-focus` `--athena-focus-width` `--athena-line` `--athena-surface` |
71
+ | Dropdown | `.dropdown` `.dropdown-menu` `.dropdown-right` | `--athena-bg` `--athena-border-width` `--athena-line` `--athena-radius` `--athena-shadow` |
72
+ | A popover (the dropdown menu, the tooltip) is in the top layer, placed next to its anchor by script through two variables | `.athena-popover` `.athena-popover-above` `.athena-popover-center` `.athena-popover-end` `.dropdown-divider` `.dropdown-item` `.dropdown-menu` | `--athena-fg` `--athena-hover` `--athena-line` `--athena-popover-left` `--athena-popover-top` |
65
73
  | Sidebar | `.accordion-icon` `.sidebar` `.sidebar-link` `.sidebar-list` `.sidebar-parent` `.sidebar-sublist` `.sidebar-toggle` | `--athena-accent` `--athena-accent-fg` `--athena-fg` `--athena-hover` `--athena-space-2` |
66
74
  | Cards, sections, grid | `.athena-grid` `.card` `.card-body` `.card-footer` `.card-image` `.card-title` | `--athena-bg` `--athena-border-width` `--athena-line` `--athena-radius` `--athena-surface-alt` `--grid-columns` `--grid-gap` |
67
75
  | Badge, avatar, stat | `.avatar` `.avatar-large` `.avatar-small` `.badge` `.badge-error` `.badge-info` `.badge-pill` `.badge-success` `.badge-warning` `.stat` `.stat-bad` `.stat-good` `.stat-label` `.stat-neutral` `.stat-value` | `--athena-accent` `--athena-accent-fg` `--athena-bg` `--athena-border-width` `--athena-danger` `--athena-fg` `--athena-info` `--athena-line` `--athena-muted` `--athena-radius` `--athena-success` `--athena-surface` `--athena-warning` |
68
- | Tooltip | `.has-tooltip` `.tooltip-text` `.tooltip-wrap` | - |
76
+ | Tooltip | `.has-tooltip` `.tooltip-text` `.tooltip-wrap` | `--athena-duration-fast` `--athena-ease-standard` |
77
+ | As a popover it is only drawn while it is open, so it is always visible; the position comes from placePopover() | `.tooltip-text` | - |
69
78
  | Combobox (autocomplete, multi select) and chips | `.chip` `.chip-remove` `.combobox` `.combobox-active` `.combobox-chips` `.combobox-empty` `.combobox-input` `.combobox-list` `.combobox-multiple` `.combobox-option` `.combobox-selected` | `--athena-accent` `--athena-accent-fg` `--athena-bg` `--athena-border-width` `--athena-hover` `--athena-line` `--athena-muted` `--athena-radius` `--athena-shadow` `--athena-space-1` |
70
79
  | File upload | `.dropzone` `.dropzone-disabled` `.dropzone-input` `.dropzone-over` `.file-item` `.file-list` `.file-status` | `--athena-accent` `--athena-hover` `--athena-line` `--athena-muted` `--athena-radius` |
71
80
  | Stepper | `.form-actions` `.stepper` `.stepper-current` `.stepper-done` `.stepper-number` `.stepper-step` `.stepper-steps` | `--athena-accent` `--athena-accent-fg` `--athena-fg` `--athena-line` `--athena-muted` `--athena-space-2` `--athena-success` |
72
81
  | Tables | `.athena-table` `.athena-table-edit` `.athena-table-filter` `.athena-table-pager` `.athena-table-select` `.athena-table-wrapper` `.clickable` `.editable` `.selected` `.sortable` | `--athena-accent` `--athena-border-width` `--athena-hover` `--athena-line` `--athena-surface` `--athena-surface-alt` |
73
82
  | Table options: density, wrapping, alignment | `.athena-align-center` `.athena-align-right` `.athena-table` `.athena-table-compact` `.athena-table-nowrap` `.athena-table-wrap` | `--athena-focus` `--athena-focus-width` |
74
83
  | Charts | `.athena-chart` `.chart-axis` `.chart-bar` `.chart-grid` `.chart-legend` `.chart-slice` `.chart-tick` `.chart-title` | `--athena-bg` `--athena-fg` `--athena-line` `--athena-muted` |
75
- | Responsive | `.athena-form` `.athena-grid` `.file-item` `.file-progress` `.modal` `.modal-content` `.progress-fill` `.progress-indeterminate` `.sidebar` `.sidebar-list` `.sidebar-open` `.sidebar-toggle` `.spinner` `.stepper-title` | - |
84
+ | Responsive | `.athena-form` `.athena-grid` `.file-item` `.file-progress` `.modal` `.modal-content` `.sidebar` `.sidebar-list` `.sidebar-open` `.sidebar-toggle` `.stepper-title` | - |
85
+ | Reduced motion: a spinner and an indeterminate bar still have to say "busy", but slowly. The transitions read the duration tokens (0). | `.progress-fill` `.progress-indeterminate` `.spinner` | - |
76
86
  | Menu submenus | `.has-submenu` `.menu-parent` `.submenu` `.submenu-item` | `--athena-bg` `--athena-border-width` `--athena-hover` `--athena-line` `--athena-radius` `--athena-shadow` |
77
87
  | Table: resizable columns, virtual scrolling | `.athena-col-resizer` `.athena-table` `.athena-table-resizable` `.athena-table-scroll` `.athena-table-spacer` `.athena-table-virtual` `.resizing` | `--athena-accent` `--athena-border-width` `--athena-line` `--athena-row-height` `--row-height` |
78
88
  | Date range | `.daterange` `.daterange-part` | - |
@@ -83,4 +93,11 @@ Dark colours: set `data-mode="dark"` on `<html>` (or let `createThemeManager` do
83
93
  | Tabs at the bottom (layout "responsive" switches to it under 700px) | `.athena-menu-bottom-tabs` `.athena-menu-list` `.athena-menu-responsive` `.menu-control` `.menu-item` `.menu-item-end` `.menu-sheet` | `--athena-bg` `--athena-border-width` `--athena-line` `--athena-radius` |
84
94
  | Menu: groups inside groups, and badges | `.athena-menu` `.athena-menu-bottom-tabs` `.athena-menu-responsive` `.athena-table-placeholder` `.athena-table-status` `.menu-badge` `.menu-badge-bad` `.menu-badge-info` `.menu-badge-ok` `.menu-badge-warn` `.menu-caret` `.menu-sheet` `.menu-sheet-nested` | `--athena-accent` `--athena-accent-fg` `--athena-danger` `--athena-info` `--athena-muted` `--athena-success` `--athena-warning` |
85
95
  | Charts: pointer layer, zoom | `.athena-chart` `.chart-hit` `.chart-marker` `.chart-reset` `.chart-selection` | `--athena-accent` `--athena-focus` `--athena-focus-width` `--athena-muted` |
86
- | Page header, facts, empty state, loading, stat tone and note | `.empty-icon` `.empty-message` `.empty-state` `.empty-title` `.fact` `.facts` `.facts-inline` `.is-bad` `.is-ok` `.is-warn` `.loading-state` `.page-actions` `.page-description` `.page-header` `.page-header-row` `.page-title` `.stat` `.stat-note` `.stat-value` | `--athena-danger` `--athena-fg` `--athena-muted` `--athena-space-2` `--athena-space-3` `--athena-success` `--athena-warning` |
96
+ | Page header, facts, empty state, loading, stat tone and note | `.athena-popover` `.athena-popover-above` `.dialog` `.empty-icon` `.empty-message` `.empty-state` `.empty-title` `.fact` `.facts` `.facts-inline` `.is-bad` `.is-ok` `.is-warn` `.loading-state` `.page-actions` `.page-description` `.page-header` `.page-header-row` `.page-title` `.stat` `.stat-note` `.stat-value` | `--athena-danger` `--athena-duration-base` `--athena-duration-fast` `--athena-ease-out` `--athena-fg` `--athena-muted` `--athena-space-2` `--athena-space-3` `--athena-success` `--athena-warning` |
97
+ | Toasts slide in from the side, and out again when they are closed | `.is-leaving` `.toast` | `--athena-duration-base` `--athena-ease-out` |
98
+ | The panel of an accordion opens and closes smoothly (a browser without ::details-content opens it at once) | `.accordion-item` | `--athena-duration-base` `--athena-ease-standard` |
99
+ | The mark of the active item, and hover, move gently | `.athena-menu` `.menu-control` | `--athena-duration-fast` `--athena-ease-standard` |
100
+ | A place holder for what is loading: a skeleton with a shimmer (generateSkeleton) | `.athena-skeleton` `.athena-skeleton-line` | `--athena-hover` `--athena-radius` `--athena-space-2` `--athena-surface` |
101
+ | A theme or mode change cross-fades instead of flashing (the theme manager sets the class for a moment) | `.athena-switching` | `--athena-duration-slow` `--athena-ease-standard` |
102
+ | Page transitions of the router (router({ transition: true })) | - | `--athena-duration-base` `--athena-ease-standard` |
103
+ | Charts draw themselves when they appear: bars grow, lines are drawn, slices pop in (only the first time, not when a chart streams or is zoomed) | `.athena-chart-animated` `.chart-area` `.chart-bar` `.chart-line` `.chart-point` `.chart-slice` | `--athena-duration-slow` `--athena-ease-out` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "athena-ui-js",
3
- "version": "2.0.1",
3
+ "version": "2.2.0",
4
4
  "description": "A small, dependency-free UI framework: forms, tables, charts, menus, dialogs, themes and a router, written as ES modules.",
5
5
  "type": "module",
6
6
  "main": "./src/athena-ui.js",
@@ -87,6 +87,10 @@
87
87
  "types": "./types/validation.d.ts",
88
88
  "default": "./src/validation.js"
89
89
  },
90
+ "./motion": {
91
+ "types": "./types/motion.d.ts",
92
+ "default": "./src/motion.js"
93
+ },
90
94
  "./sanitize": {
91
95
  "types": "./types/sanitize.d.ts",
92
96
  "default": "./src/sanitize.js"
package/src/athena-ui.js CHANGED
@@ -2,7 +2,7 @@
2
2
  //Author: Csaba Tóth https://github.com/csabatibortoth/
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
- //Version: 2.0.1
5
+ //Version: 2.2.0
6
6
 
7
7
  // The whole API as ES module exports. There are no side effects: importing this file does not touch the page, does not load a script and does not
8
8
  // put anything on globalThis. For pages that need globals use `athena-ui-js/classic`, and to download only what you use import from the entry points
@@ -123,6 +123,7 @@ export * from "./libs/core/validation.js";
123
123
  export * from "./libs/core/csv.js";
124
124
  export * from "./libs/core/dateRange.js";
125
125
  export * from "./libs/core/format.js";
126
+ export * from "./libs/core/motion.js";
126
127
  export * from "./libs/hephaestus/modalGenerator/modalGenerator.js";
127
128
  export * from "./libs/core/theme.js";
128
129
  export * from "./libs/hephaestus/componentGenerator/themePicker.js";
@@ -6,7 +6,7 @@
6
6
  export const BORDERED_CLASS = "default-cointainer-bordered";
7
7
 
8
8
  export const defaults = Object.freeze({
9
- version: "2.0.1",
9
+ version: "2.2.0",
10
10
  container_class: "container",
11
11
  header_class: "header-container",
12
12
  header_menu_class: "header-menu menu",
@@ -0,0 +1,358 @@
1
+ //motion for Athena UI
2
+ //Author: Csaba Tóth https://github.com/csabatibortoth/
3
+ //LICENCE: MIT
4
+ //Repository: https://github.com/csabatibortoth/athena-ui
5
+
6
+ // Animations and transitions. The rule for everything here: motion is an enhancement. It is off when the person prefers reduced motion (the system setting,
7
+ // or setMotion("reduce")), nothing waits for an animation before it works (every function resolves at once under reduced motion), and nothing needs an inline
8
+ // style: CSS classes, custom properties, and the Web Animations API, which a strict Content-Security-Policy allows.
9
+
10
+ /* ------------------THE PREFERENCE------------------- */
11
+
12
+ const listeners = new Set();
13
+
14
+ // The choice lives on <html> as data-motion ("reduce" or "full"), where the CSS tokens read it too. No attribute: follow the system.
15
+ const chosen = () => {
16
+ const value = globalThis.document?.documentElement.dataset.motion;
17
+ return value === "reduce" || value === "full" ? value : "system";
18
+ };
19
+
20
+ /** Does the person want less motion? The choice made with setMotion wins over the setting of the system. */
21
+ export function prefersReducedMotion() {
22
+ const preference = chosen();
23
+ if (preference === "reduce") return true;
24
+ if (preference === "full") return false;
25
+ return Boolean(globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches);
26
+ }
27
+
28
+ /** "system" (follow the setting of the system), "reduce" or "full". */
29
+ export const getMotion = chosen;
30
+
31
+ /**
32
+ * Chooses how much motion there is: "system", "reduce" (none) or "full". It is put on <html> as data-motion, which the CSS tokens read (the durations
33
+ * become 0), and the functions of this module read it too.
34
+ */
35
+ export function setMotion(value) {
36
+ if (!["system", "reduce", "full"].includes(value)) return false;
37
+ const root = globalThis.document?.documentElement;
38
+ if (root) {
39
+ if (value === "system") delete root.dataset.motion;
40
+ else root.dataset.motion = value;
41
+ }
42
+ listeners.forEach(listener => listener({ preference: value, reduced: prefersReducedMotion() }));
43
+ return true;
44
+ }
45
+
46
+ /** Called with { preference, reduced } when setMotion changes it, and when the system setting changes. Returns a function that stops it. */
47
+ export function onMotionChange(listener) {
48
+ listeners.add(listener);
49
+ return () => listeners.delete(listener);
50
+ }
51
+
52
+ globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").addEventListener?.("change", () => {
53
+ if (chosen() === "system") listeners.forEach(listener => listener({ preference: "system", reduced: prefersReducedMotion() }));
54
+ });
55
+
56
+ /* ------------------TOKENS------------------- */
57
+
58
+ /** A duration token as milliseconds: readDuration("--athena-duration-base") -> 200. 0 under reduced motion. */
59
+ export function readDuration(token = "--athena-duration-base", element = globalThis.document?.documentElement) {
60
+ if (!element) return 0;
61
+ const value = getComputedStyle(element).getPropertyValue(token).trim();
62
+ return toMs(value);
63
+ }
64
+
65
+ const toMs = text => {
66
+ const match = /^(-?[\d.]+)(ms|s)$/.exec(String(text).trim());
67
+ return match ? Number(match[1]) * (match[2] === "s" ? 1000 : 1) : 0;
68
+ };
69
+
70
+ /** How long an element takes to finish its CSS transitions, delays included, in ms (0 when it has none, or under reduced motion). */
71
+ export function transitionTime(element) {
72
+ const style = getComputedStyle(element);
73
+ const durations = style.transitionDuration.split(",").map(toMs);
74
+ const delays = style.transitionDelay.split(",").map(toMs);
75
+ return Math.max(0, ...durations.map((duration, index) => duration + (delays[index % delays.length] ?? 0)));
76
+ }
77
+
78
+ /** Removes an element when its exit transition is over (at once when it has none, which is also what reduced motion gives). */
79
+ export function removeAfterTransition(element) {
80
+ const time = element.isConnected ? transitionTime(element) : 0;
81
+ if (time <= 0) element.remove();
82
+ else setTimeout(() => element.remove(), time + 30);
83
+ }
84
+
85
+ /* ------------------EASINGS------------------- */
86
+
87
+ /** Easing functions for numbers: f(t) with t from 0 to 1, for tweens. (CSS has its own, see the --athena-ease-* tokens.) */
88
+ export const easings = {
89
+ linear: t => t,
90
+ easeInQuad: t => t * t,
91
+ easeOutQuad: t => 1 - (1 - t) * (1 - t),
92
+ easeInOutQuad: t => (t < 0.5 ? 2 * t * t : 1 - ((-2 * t + 2) ** 2) / 2),
93
+ easeInCubic: t => t ** 3,
94
+ easeOutCubic: t => 1 - (1 - t) ** 3,
95
+ easeInOutCubic: t => (t < 0.5 ? 4 * t ** 3 : 1 - ((-2 * t + 2) ** 3) / 2),
96
+ easeOutBack: t => 1 + 2.70158 * (t - 1) ** 3 + 1.70158 * (t - 1) ** 2,
97
+ easeOutElastic: t => (t === 0 || t === 1 ? t : 2 ** (-10 * t) * Math.sin((t * 10 - 0.75) * ((2 * Math.PI) / 3)) + 1)
98
+ };
99
+
100
+ /**
101
+ * A spring as a CSS easing: simulates a damped spring and returns the points as a `linear()` easing (which can overshoot) and how long it takes.
102
+ * `element.animate(keyframes, { duration, easing })` then moves like a spring. Settles when it stays within `precision` of 1.
103
+ *
104
+ * @param {{stiffness?: number, damping?: number, mass?: number, precision?: number}} [options]
105
+ * @returns {{easing: string, duration: number}} duration in ms
106
+ */
107
+ export function spring({ stiffness = 170, damping = 15, mass = 1, precision = 0.002 } = {}) {
108
+ const step = 1 / 120;
109
+ let position = 0;
110
+ let velocity = 0;
111
+ const points = [0];
112
+ let settled = 0;
113
+ let time = 0;
114
+ while (time < 10 && settled < 12) {
115
+ const force = -stiffness * (position - 1) - damping * velocity;
116
+ velocity += (force / mass) * step;
117
+ position += velocity * step;
118
+ time += step;
119
+ points.push(position);
120
+ settled = Math.abs(position - 1) < precision && Math.abs(velocity) < precision * 10 ? settled + 1 : 0;
121
+ }
122
+ points[points.length - 1] = 1;
123
+ // About 40 points are enough for the eye
124
+ const every = Math.max(1, Math.floor(points.length / 40));
125
+ const sampled = points.filter((_, index) => index % every === 0 || index === points.length - 1).map(value => +value.toFixed(4));
126
+ return { easing: `linear(${sampled.join(", ")})`, duration: Math.round(time * 1000) };
127
+ }
128
+
129
+ /* ------------------ANIMATE------------------- */
130
+
131
+ /**
132
+ * Animates an element with the Web Animations API and resolves when it is over. Under reduced motion it does nothing and resolves at once.
133
+ * It resolves (never rejects) when the animation is cancelled, and `null` when there was none.
134
+ *
135
+ * @param {Element} element
136
+ * @param {Keyframe[]|PropertyIndexedKeyframes} keyframes e.g. [{ opacity: 0 }, { opacity: 1 }]
137
+ * @param {object} [options] the options of element.animate (duration, easing, delay, fill, ...), and
138
+ * @param {boolean} [options.commit=false] write the end state to the element's style when it is over (CSSOM: allowed by a strict policy)
139
+ * @param {AbortSignal} [options.signal] cancels the animation when aborted
140
+ * @returns {Promise<Animation|null>}
141
+ */
142
+ export async function animate(element, keyframes, options = {}) {
143
+ if (prefersReducedMotion() || typeof element?.animate !== "function") return null;
144
+ const { commit = false, signal, ...timing } = options;
145
+ const animation = element.animate(keyframes, {
146
+ duration: readDuration("--athena-duration-base"),
147
+ easing: getComputedStyle(globalThis.document.documentElement).getPropertyValue("--athena-ease-standard").trim() || "ease",
148
+ fill: "backwards",
149
+ ...timing
150
+ });
151
+ signal?.addEventListener("abort", () => animation.cancel(), { once: true });
152
+ // A page that is not drawn (a hidden tab) gets no frames, so its animations would never finish: a timer finishes it, a moment after it should be over
153
+ const length = (typeof timing.duration === "number" ? timing.duration : readDuration("--athena-duration-base")) * (timing.iterations ?? 1) + (timing.delay ?? 0) + (timing.endDelay ?? 0);
154
+ const timer = Number.isFinite(length) ? setTimeout(() => { if (animation.playState === "running") animation.finish(); }, length + 100) : 0;
155
+ try {
156
+ await animation.finished;
157
+ clearTimeout(timer);
158
+ if (commit) {
159
+ animation.commitStyles();
160
+ animation.cancel();
161
+ }
162
+ } catch {
163
+ return animation; // cancelled: not an error
164
+ }
165
+ return animation;
166
+ }
167
+
168
+ /** Fades an element in. */
169
+ export const fadeIn = (element, options) => animate(element, [{ opacity: 0 }, { opacity: 1 }], options);
170
+
171
+ /** Fades an element out and removes it. Under reduced motion it is removed at once. */
172
+ export async function fadeOut(element, options) {
173
+ await animate(element, [{ opacity: 1 }, { opacity: 0 }], { fill: "forwards", ...options });
174
+ element.remove();
175
+ }
176
+
177
+ /**
178
+ * A change that is done with CSS (a class, an attribute) and has a CSS transition: runs `change()` and resolves when the element's transition is over.
179
+ * It waits at most the length of the transition (plus a little), so a transition that never ends does not hang anything.
180
+ */
181
+ export function transition(element, change) {
182
+ return new Promise(resolve => {
183
+ change();
184
+ // The styles of the change are computed in the next frame
185
+ requestAnimationFrame(() => {
186
+ const time = transitionTime(element);
187
+ if (time <= 0) return resolve();
188
+ let done = false;
189
+ const finish = () => {
190
+ if (done) return;
191
+ done = true;
192
+ element.removeEventListener("transitionend", onEnd);
193
+ resolve();
194
+ };
195
+ const onEnd = event => { if (event.target === element) finish(); };
196
+ element.addEventListener("transitionend", onEnd);
197
+ setTimeout(finish, time + 50);
198
+ });
199
+ });
200
+ }
201
+
202
+ /* ------------------SEVERAL AT ONCE OR ONE AFTER THE OTHER------------------- */
203
+
204
+ /** Runs the functions one after the other, each when the one before is over. Resolves with their results. */
205
+ export async function sequence(steps) {
206
+ const results = [];
207
+ for (const step of steps) results.push(await (typeof step === "function" ? step() : step));
208
+ return results;
209
+ }
210
+
211
+ /** Runs the functions (or promises) together. Resolves with their results. */
212
+ export const parallel = steps => Promise.all(steps.map(step => (typeof step === "function" ? step() : step)));
213
+
214
+ /**
215
+ * The delays of a staggered animation: `count` items, `step` ms apart, starting from "start", "end" or "center".
216
+ * @returns {number[]}
217
+ */
218
+ export function staggerDelays(count, step = 40, from = "start") {
219
+ return Array.from({ length: count }, (_, index) => {
220
+ const distance = from === "end" ? count - 1 - index : from === "center" ? Math.abs(index - (count - 1) / 2) : index;
221
+ return Math.round(distance * step);
222
+ });
223
+ }
224
+
225
+ /**
226
+ * Calls `run(item, index, delay)` for every item with its delay, and resolves when all are over: `stagger(rows, (row, i, delay) => fadeIn(row, { delay }))`.
227
+ * No more than `limit` items are staggered (the rest run with the last delay), so a long list does not take long.
228
+ */
229
+ export function stagger(items, run, { step = 40, from = "start", limit = 30 } = {}) {
230
+ const list = [...items];
231
+ const delays = staggerDelays(Math.min(list.length, limit), step, from);
232
+ return Promise.all(list.map((item, index) => run(item, index, delays[Math.min(index, delays.length - 1)] ?? 0)));
233
+ }
234
+
235
+ /* ------------------LISTS: FLIP------------------- */
236
+
237
+ /**
238
+ * Lets the children of a container move smoothly when `change()` rearranges them (sorting, filtering, inserting, removing): First (measure), Last (do the change,
239
+ * measure), Invert and Play (each child that moved starts at its old place and slides to the new one). New children fade in. Under reduced motion `change()` is
240
+ * just done.
241
+ *
242
+ * @param {Element} container its children are what moves
243
+ * @param {() => void} change rearranges the children (synchronously)
244
+ * @param {object} [options]
245
+ * @param {(element: Element) => *} [options.key] what makes a child "the same" before and after, default: the element itself
246
+ * @param {number} [options.limit=60] at most this many children are animated (a long list does not need it, and costs time)
247
+ * @param {number} [options.duration] ms, default the token --athena-duration-base
248
+ * @returns {Promise<void>} resolves when the animations are over
249
+ */
250
+ export async function flip(container, change, { key = element => element, limit = 60, duration } = {}) {
251
+ if (prefersReducedMotion()) {
252
+ change();
253
+ return;
254
+ }
255
+ const first = new Map();
256
+ for (const child of [...container.children].slice(0, limit)) first.set(key(child), child.getBoundingClientRect());
257
+ change();
258
+ const animations = [];
259
+ for (const child of [...container.children].slice(0, limit)) {
260
+ const before = first.get(key(child));
261
+ const after = child.getBoundingClientRect();
262
+ if (!before) {
263
+ animations.push(animate(child, [{ opacity: 0 }, { opacity: 1 }], { duration }));
264
+ continue;
265
+ }
266
+ const dx = before.left - after.left;
267
+ const dy = before.top - after.top;
268
+ if (Math.abs(dx) < 1 && Math.abs(dy) < 1) continue;
269
+ animations.push(animate(child, [{ translate: `${dx}px ${dy}px` }, { translate: "0 0" }], { duration, easing: "cubic-bezier(0.2, 0, 0, 1)" }));
270
+ }
271
+ await Promise.all(animations);
272
+ }
273
+
274
+ /* ------------------TWEENS (for games and anything that is not CSS)------------------- */
275
+
276
+ /**
277
+ * Changes numbers over time with requestAnimationFrame: tween({ from: 0, to: 100, duration: 500, easing: easings.easeOutCubic, onUpdate: v => ... }).
278
+ * `from` and `to` can be numbers, or objects with the same keys ({ x: 0, y: 0 } to { x: 10, y: 5 }); onUpdate then gets an object.
279
+ * Under reduced motion it jumps to the end (one onUpdate call). It runs on animation frames; in a page that is not drawn a timer keeps it going slowly, so it still ends.
280
+ *
281
+ * @returns {Promise<void> & {cancel: () => void}} resolves when it is over (also when cancelled)
282
+ */
283
+ export function tween({ from = 0, to = 1, duration = 300, easing = easings.easeOutCubic, onUpdate, delay = 0 } = {}) {
284
+ let cancelled = false;
285
+ let frame = 0;
286
+ const value = progress => (typeof from === "number"
287
+ ? from + (to - from) * progress
288
+ : Object.fromEntries(Object.keys(from).map(name => [name, from[name] + (to[name] - from[name]) * progress])));
289
+ const promise = new Promise(resolve => {
290
+ if (prefersReducedMotion() || duration <= 0) {
291
+ onUpdate?.(value(1));
292
+ resolve();
293
+ return;
294
+ }
295
+ let start = null;
296
+ let timer = 0;
297
+ // The frame clock is the clock; the timer next to it keeps a tween going (more slowly) in a page that is not drawn, so it still ends
298
+ const schedule = () => {
299
+ frame = requestAnimationFrame(tick);
300
+ timer = setTimeout(tick, 100);
301
+ };
302
+ const tick = () => {
303
+ cancelAnimationFrame(frame);
304
+ clearTimeout(timer);
305
+ if (cancelled) return resolve();
306
+ const now = performance.now();
307
+ start ??= now + delay;
308
+ const t = Math.min(Math.max((now - start) / duration, 0), 1);
309
+ if (now >= start) onUpdate?.(value(easing(t)));
310
+ if (t >= 1) return resolve();
311
+ schedule();
312
+ };
313
+ schedule();
314
+ });
315
+ return Object.assign(promise, { cancel() { cancelled = true; cancelAnimationFrame(frame); } });
316
+ }
317
+
318
+ /* ------------------PAGES------------------- */
319
+
320
+ /**
321
+ * Runs `update()` (which changes the DOM) as a view transition when the browser can and motion is wanted: the old and the new state cross-fade
322
+ * (or whatever the CSS ::view-transition-* rules say). Elements with a `view-transition-name` move from one place to the other. Without the API,
323
+ * or under reduced motion, `update()` is just run. Resolves when it is over.
324
+ */
325
+ export async function viewTransition(update) {
326
+ if (prefersReducedMotion() || typeof globalThis.document?.startViewTransition !== "function") {
327
+ await update();
328
+ return;
329
+ }
330
+ let failure = null;
331
+ let started = false;
332
+ let done = false;
333
+ const run = async () => {
334
+ if (started) return;
335
+ started = true;
336
+ try {
337
+ await update();
338
+ } catch (error) {
339
+ failure = error;
340
+ }
341
+ done = true;
342
+ };
343
+ const transition = document.startViewTransition(run);
344
+ // A page that is not drawn (a hidden tab) never calls the update of a view transition: after a moment it is run here, so the page does not stay as it was
345
+ const guard = setTimeout(run, 400);
346
+ const later = ms => new Promise(resolve => setTimeout(resolve, ms));
347
+ try {
348
+ await Promise.race([transition.updateCallbackDone, later(2000)]);
349
+ // the animation needs frames: do not wait for it longer than it can last
350
+ await Promise.race([transition.finished, later(readDuration("--athena-duration-slow") + 1000)]);
351
+ } catch {
352
+ // skipped (for example the page was hidden): the update was run all the same
353
+ }
354
+ clearTimeout(guard);
355
+ await run();
356
+ while (!done) await later(10);
357
+ if (failure) throw failure;
358
+ }