Files
livewire-material/resources/js/popover-exit.js
T
Andreas Reinhold / reiniandClaude Opus 5 247c596c3a Cut duplicated and speculative code across the package
An over-engineering audit of the whole tree, applied in five reviewed
batches. Behaviour stays the same except where UPGRADE.md says otherwise.

PHP: the showcase and error-page stylesheets are prebuilt into
resources/dist by bin/stylesheets.mjs, through Vite's own postcss-import
(first occurrence kept, the order an application's build gives), instead
of Stylesheets::bundle() inlining imports on every request; only the
import walk DesignGuard needs stays. SchemeStylesheet::withProfiles()
replaces three copies of the scheme-plus-profiles loop, material:scheme
leaves spec and contrast checks to the node script that already made
them, and the error page's scheme cache, the hashed view namespace, the
translations path with no lang/ folder and DesignGuard's 1.x-name hints
are gone.

JS: the androidx shape port progress.js and both bin scripts each carried
lives once in resources/js/shapes.js (the generated SVGs are unchanged);
util.js holds ringIndex(), ms(), reopenGuard() and remember(), which
were written out several times; listeners are released through
AbortController; tooltip.js's hoverPopover() serves the rich tooltip too.

CSS: every rule for an element inside the navigation rail queries
`--md-navigation-rail-value` instead of repeating the seven collapsed
conditions under five media branches; badge, alert, progress, slider and
button read one non-inheriting colour-role table (components/color.css);
the dialog chrome, the submenu's popover chrome, the chip's state layer
and touch target, and the visually-hidden inputs use the shared rules
they copied; foundation/tokens.css is folded into foundation.css.

Views: Support\Field and Support\Link replace the error-key, bound-value
and link-attribute blocks copied into the fields and link components;
the timepicker period group, the menu filter and the showcase head are
partials; the datepicker's steppers and entry fields are loops; component
docblocks no longer restate SKILL.md.

Tests and tooling: one dataset-driven ComponentStylesheetsTest replaces
four per-group files, DesignGuardTest and the layout-component tests use
datasets, browser tests share one ready() helper, CSS parsing lives in
ComponentStylesheet alone. docs/audits and the finding IDs citing it are
removed, as are pestphp/pest-plugin-laravel, the unused composer scripts
and check:font; the lint job runs in the feature job, which now installs
node packages so the prebuilt-stylesheet staleness test runs in CI.

Feature suite 1177 passed, Chrome browser suite 299 passed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 19:29:21 +02:00

140 lines
5.7 KiB
JavaScript

/**
* Popover exits in every engine: a popover marked `data-md-popover-exit` fades or shrinks out on
* its own transitions, however it closes — `hidePopover()` from a component's script, Escape, a
* press outside it, or another popover opening.
*
* A closed popover leaves the top layer and takes `display: none` at once. Chrome and Safari could
* hold both for a transition (`transition-behavior: allow-discrete` on `display` and `overlay`);
* Firefox transitions neither (MDN browser-compat-data, `display.is_transitionable`), so there every
* exit vanished on its first frame. Nor can a script hold the popover open: `beforetoggle` cannot be
* cancelled on the way out, and the browser's own light dismiss never asks.
*
* So the popover closes for real, at once — its focus, `aria-expanded` and `toggle` event are the
* browser's as before — and a copy of it, taken in `beforetoggle` while it is still drawn, stands
* in its place for the exit. The copy is decoration: `popover="manual"` (the top layer, above what
* the popover was above, without closing any other popover), inert, hidden from assistive
* technology, without ids or nested popovers, and `x-ignore`, so Alpine does not start the
* components it holds. It is pinned to the popover's box, shown with its transitions off (its
* `@starting-style` would otherwise replay the entry), and then marked `data-md-popover-closing`,
* which the component's stylesheet turns into its closed values (`:popover-open:not(…)`), so the
* copy moves on the component's own durations and springs. It is removed when the longest of them
* has run; under reduced motion they are zero, and there is no copy at all.
*/
const EXIT = '[data-md-popover-exit]'
const GHOST = 'data-md-popover-ghost'
const CLOSING = 'data-md-popover-closing'
/** The copy each popover's exit is showing, so opening the popover again takes it away. */
const ghosts = new WeakMap()
/** The longest `transition-duration` + `transition-delay` pair on an element, in ms. */
const longestTransition = (element) => {
const style = getComputedStyle(element)
const durations = style.transitionDuration.split(',').map((value) => parseFloat(value) * (value.trim().endsWith('ms') ? 1 : 1000))
const delays = style.transitionDelay.split(',').map((value) => parseFloat(value) * (value.trim().endsWith('ms') ? 1 : 1000))
return Math.max(0, ...durations.map((duration, index) => duration + (delays[index % delays.length] || 0)))
}
/**
* A still copy of the popover, pinned where it is drawn. Colours come from custom properties an
* ancestor may set (a vibrant menu's `--material-menu-surface`), which the copy loses at the end of
* `<body>`, so the root's resolved colours travel with it.
*/
const copyOf = (popover) => {
const box = popover.getBoundingClientRect()
const style = getComputedStyle(popover)
const ghost = popover.cloneNode(true)
ghost.querySelectorAll('[popover]').forEach((nested) => nested.remove())
ghost.querySelectorAll('[id]').forEach((element) => element.removeAttribute('id'))
ghost.removeAttribute('id')
ghost.removeAttribute(EXIT.slice(1, -1))
ghost.setAttribute('popover', 'manual')
ghost.setAttribute(GHOST, '')
ghost.setAttribute('x-ignore', '')
ghost.setAttribute('aria-hidden', 'true')
ghost.inert = true
Object.assign(ghost.style, {
position: 'fixed',
inset: 'auto',
left: `${box.left}px`,
top: `${box.top}px`,
width: `${box.width}px`,
height: `${box.height}px`,
margin: '0',
positionAnchor: 'none',
positionArea: 'none',
positionTryFallbacks: 'none',
pointerEvents: 'none',
backgroundColor: style.backgroundColor,
color: style.color,
})
return { ghost, scrollTop: popover.scrollTop }
}
const exit = ({ ghost, scrollTop }, popover) => {
const still = [ghost, ...ghost.querySelectorAll('*')]
const transitions = still.map((element) => element.style.transition)
still.forEach((element) => (element.style.transition = 'none'))
document.body.append(ghost)
ghost.showPopover()
ghost.scrollTop = scrollTop
// Resolve the open values with no transition, then give the transitions back and close.
still.forEach((element) => getComputedStyle(element).opacity)
still.forEach((element, index) => (element.style.transition = transitions[index]))
ghost.setAttribute(CLOSING, '')
const duration = Math.max(...still.map(longestTransition))
ghosts.set(popover, ghost)
setTimeout(() => {
// Out of the DOM, which takes it off the top layer without a `beforetoggle` or `toggle` of its own.
ghost.remove()
if (ghosts.get(popover) === ghost) {
ghosts.delete(popover)
}
}, duration)
}
document.addEventListener(
'beforetoggle',
(event) => {
const popover = event.target
if (!(popover instanceof HTMLElement) || !popover.matches(EXIT)) {
return
}
const previous = ghosts.get(popover)
if (previous) {
ghosts.delete(popover)
previous.remove()
}
if (event.newState !== 'closed') {
return
}
// Under reduced motion every duration token is zero: nothing to show on the way out.
if (Math.max(...[popover, ...popover.querySelectorAll('*')].map(longestTransition)) === 0) {
return
}
// Taken now, while the popover is still drawn; shown in the next frame, before it is
// painted without the popover, so neither `showPopover()` runs inside the browser's own
// hiding nor a frame goes by with nothing on screen.
const copy = copyOf(popover)
requestAnimationFrame(() => exit(copy, popover))
},
true,
)