Files
Rosea/packages/domi-ui/src/lib/strike.ts
T

51 lines
2.0 KiB
TypeScript

import type { Action } from 'svelte/action';
/**
* The press flow of every Domi button: on pointer down it places the seal impression where the press landed
* (--_px, --_py) and replays it (data-struck); Enter and Space show the sunk plate while held (data-pressed), so a
* keyboard press looks like a pointer press. Reduced motion is handled in CSS (no impression, no movement).
*/
export const strike: Action<HTMLElement> = (node) => {
const replay = (x: string, y: string) => {
node.style.setProperty('--_px', x);
node.style.setProperty('--_py', y);
node.removeAttribute('data-struck');
// Force a style flush so the animation restarts on a quick second press.
void node.offsetWidth;
node.setAttribute('data-struck', '');
};
const down = (e: PointerEvent) => {
if (e.button !== 0 || isInert(node)) return;
const r = node.getBoundingClientRect();
replay(`${e.clientX - r.left}px`, `${e.clientY - r.top}px`);
};
const keydown = (e: KeyboardEvent) => {
if ((e.key === 'Enter' || e.key === ' ') && !e.repeat && !isInert(node)) {
node.setAttribute('data-pressed', '');
replay('50%', '50%');
}
};
const release = () => node.removeAttribute('data-pressed');
const end = (e: AnimationEvent) => {
if (e.target === node && e.pseudoElement === '::after') node.removeAttribute('data-struck');
};
node.addEventListener('pointerdown', down);
node.addEventListener('keydown', keydown);
node.addEventListener('keyup', release);
node.addEventListener('blur', release);
node.addEventListener('animationend', end);
return {
destroy() {
node.removeEventListener('pointerdown', down);
node.removeEventListener('keydown', keydown);
node.removeEventListener('keyup', release);
node.removeEventListener('blur', release);
node.removeEventListener('animationend', end);
},
};
};
function isInert(node: HTMLElement): boolean {
return (node as HTMLButtonElement).disabled === true || node.getAttribute('aria-disabled') === 'true';
}