athena-ui-js 2.1.0 → 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.
- package/README.md +39 -3
- package/docs/styling.md +21 -6
- package/package.json +5 -1
- package/src/athena-ui.js +2 -1
- package/src/libs/config/config.js +1 -1
- package/src/libs/core/motion.js +358 -0
- package/src/libs/core/theme.js +12 -0
- package/src/libs/hephaestus/chartGenerator/chartGenerator.js +9 -5
- package/src/libs/hephaestus/componentGenerator/componentGenerator.js +17 -0
- package/src/libs/hephaestus/dialogGenerator/dialogGenerator.js +2 -1
- package/src/libs/hephaestus/feedbackGenerator/feedbackGenerator.js +3 -1
- package/src/libs/hephaestus/router/router.js +18 -9
- package/src/libs/hephaestus/tableGenerator/tableGenerator.js +25 -0
- package/src/motion.js +6 -0
- package/src/res/themes/default/style.css +228 -10
- package/src/res/themes/tokens.css +25 -0
- package/types/athena-ui.d.ts +97 -96
- package/types/libs/config/config.d.ts +3 -3
- package/types/libs/core/motion.d.ts +123 -0
- package/types/libs/core/popover.d.ts +36 -36
- package/types/libs/core/theme.d.ts +41 -39
- package/types/libs/hephaestus/chartGenerator/chartGenerator.d.ts +95 -93
- package/types/libs/hephaestus/componentGenerator/componentGenerator.d.ts +14 -0
- package/types/libs/hephaestus/navigationGenerator/navigationGenerator.d.ts +153 -153
- package/types/libs/hephaestus/router/router.d.ts +71 -67
- package/types/libs/hephaestus/tableGenerator/tableGenerator.d.ts +123 -120
- 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.
|
|
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
|
|
|
@@ -67,7 +67,7 @@ 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.
|
|
@@ -149,7 +149,7 @@ It takes the options of `init()`. The header and footer follow the settings `gen
|
|
|
149
149
|
| `header_title_text` | `"Athena UI"` | Title in the header |
|
|
150
150
|
| `header_img_url` | | Header logo URL |
|
|
151
151
|
| `copyright` | placeholder text | Footer text, the version is appended |
|
|
152
|
-
| `version` | `"2.
|
|
152
|
+
| `version` | `"2.2.0"` | Version shown in the footer |
|
|
153
153
|
| `bordered` | `true` | Draw a border around the layout blocks |
|
|
154
154
|
| `generateHeader`, `generateFooter` | `true` | Generate the header / footer block |
|
|
155
155
|
| `generateHeadercontent`, `generateFooterContent`, `generateWrappercontent` | `true` | Generate the content of the block |
|
|
@@ -194,6 +194,7 @@ Everything is exported from `athena-ui.js`:
|
|
|
194
194
|
| `generatePageHeader`, `generateFacts`, `generateEmptyState`, `generateLoading`, `copyToClipboard` | See [Page parts and formatting](#page-parts-and-formatting) |
|
|
195
195
|
| `formatBytes`, `formatNumber`, `formatDuration`, `formatRelativeTime`, `formatDate` | Format helpers on top of `Intl`, in the current language |
|
|
196
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) |
|
|
197
198
|
| `generateCard`, `generateSection`, `generateGrid`, `generateBadge`, `generateAvatar`, `generateStat`, `generateLink`, `generateTooltip` | See [Components](#components) |
|
|
198
199
|
| `generateAutocomplete`, `generateMultiSelect`, `generateFileUpload`, `generateDropZone`, `generateStepper`, `generateDateRange`, `generateRichText`, `generateWysiwyg` | See [Inputs](#inputs) |
|
|
199
200
|
| `sanitizeHtml(html)`, `htmlToText(html)`, `isSafeUrl(url)` | The allow-list sanitizer behind the rich text editor |
|
|
@@ -658,6 +659,41 @@ await copyToClipboard(token); // an
|
|
|
658
659
|
formatBytes(1536); formatNumber(1234567.891); formatDuration(7500000); formatRelativeTime(date); formatDate(date, { time: true }); // Intl, in the current language
|
|
659
660
|
```
|
|
660
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
|
+
|
|
661
697
|
### Safe DOM building
|
|
662
698
|
|
|
663
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
|
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,19 +61,19 @@ 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` |
|
|
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` |
|
|
64
71
|
| Dropdown | `.dropdown` `.dropdown-menu` `.dropdown-right` | `--athena-bg` `--athena-border-width` `--athena-line` `--athena-radius` `--athena-shadow` |
|
|
65
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` |
|
|
66
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` |
|
|
67
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` |
|
|
68
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` |
|
|
69
|
-
| Tooltip | `.has-tooltip` `.tooltip-text` `.tooltip-wrap` | - |
|
|
76
|
+
| Tooltip | `.has-tooltip` `.tooltip-text` `.tooltip-wrap` | `--athena-duration-fast` `--athena-ease-standard` |
|
|
70
77
|
| As a popover it is only drawn while it is open, so it is always visible; the position comes from placePopover() | `.tooltip-text` | - |
|
|
71
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` |
|
|
72
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` |
|
|
@@ -74,7 +81,8 @@ Dark colours: set `data-mode="dark"` on `<html>` (or let `createThemeManager` do
|
|
|
74
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` |
|
|
75
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` |
|
|
76
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` |
|
|
77
|
-
| Responsive | `.athena-form` `.athena-grid` `.file-item` `.file-progress` `.modal` `.modal-content` `.
|
|
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` | - |
|
|
78
86
|
| Menu submenus | `.has-submenu` `.menu-parent` `.submenu` `.submenu-item` | `--athena-bg` `--athena-border-width` `--athena-hover` `--athena-line` `--athena-radius` `--athena-shadow` |
|
|
79
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` |
|
|
80
88
|
| Date range | `.daterange` `.daterange-part` | - |
|
|
@@ -85,4 +93,11 @@ Dark colours: set `data-mode="dark"` on `<html>` (or let `createThemeManager` do
|
|
|
85
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` |
|
|
86
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` |
|
|
87
95
|
| Charts: pointer layer, zoom | `.athena-chart` `.chart-hit` `.chart-marker` `.chart-reset` `.chart-selection` | `--athena-accent` `--athena-focus` `--athena-focus-width` `--athena-muted` |
|
|
88
|
-
| 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.
|
|
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.
|
|
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";
|
|
@@ -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
|
+
}
|
package/src/libs/core/theme.js
CHANGED
|
@@ -15,6 +15,8 @@
|
|
|
15
15
|
// Nothing is sent to a server. theme-boot.js (a classic script of its own) sets the two attributes before the page is
|
|
16
16
|
// drawn, so the wrong colours never flash.
|
|
17
17
|
|
|
18
|
+
import { prefersReducedMotion, readDuration } from "./motion.js";
|
|
19
|
+
|
|
18
20
|
export const DEFAULT_MODES = [
|
|
19
21
|
{ id: "system", name: "Like the system" },
|
|
20
22
|
{ id: "light", name: "Light" },
|
|
@@ -29,6 +31,7 @@ export const DEFAULT_MODES = [
|
|
|
29
31
|
* @param {string} [options.themeColorVariable] CSS variable whose value becomes <meta name="theme-color"> (the bar of a phone browser)
|
|
30
32
|
* @param {HTMLElement} [options.root] element that gets the attributes (default: <html>)
|
|
31
33
|
* @param {Storage} [options.storage] default: localStorage
|
|
34
|
+
* @param {boolean} [options.transition=true] colours cross-fade when the theme or the mode changes (not under reduced motion)
|
|
32
35
|
* @returns {{themes, modes, appearance: () => object, setTheme: (id) => boolean, setMode: (id) => boolean,
|
|
33
36
|
* onChange: (listener) => Function, refresh: Function, destroy: Function}}
|
|
34
37
|
*/
|
|
@@ -58,7 +61,16 @@ export function createThemeManager(options = {}) {
|
|
|
58
61
|
let current = read();
|
|
59
62
|
const appearance = () => ({ ...current, dark: root.dataset.mode === "dark" });
|
|
60
63
|
|
|
64
|
+
let fade = 0;
|
|
65
|
+
let started = false;
|
|
61
66
|
function apply() {
|
|
67
|
+
// A change after the first one cross-fades: the class makes every colour transition for a moment
|
|
68
|
+
if (started && options.transition !== false && !prefersReducedMotion()) {
|
|
69
|
+
root.classList.add("athena-switching");
|
|
70
|
+
clearTimeout(fade);
|
|
71
|
+
fade = setTimeout(() => root.classList.remove("athena-switching"), readDuration("--athena-duration-slow", root) + 60);
|
|
72
|
+
}
|
|
73
|
+
started = true;
|
|
62
74
|
const dark = current.mode === "dark" || (current.mode === "system" && Boolean(systemDark()?.matches));
|
|
63
75
|
root.dataset.theme = current.theme;
|
|
64
76
|
root.dataset.mode = dark ? "dark" : "light";
|