diff --git a/.changeset/clipboard-create-copy-to-clipboard.md b/.changeset/clipboard-create-copy-to-clipboard.md new file mode 100644 index 000000000..b65339999 --- /dev/null +++ b/.changeset/clipboard-create-copy-to-clipboard.md @@ -0,0 +1,5 @@ +--- +"@solid-primitives/clipboard": minor +--- + +Add `createCopyToClipboard`: copy with a transient, auto-resetting `copied`/`error` status (copy-button helper). diff --git a/.changeset/dismissable-layer-stack.md b/.changeset/dismissable-layer-stack.md new file mode 100644 index 000000000..e7356f9b7 --- /dev/null +++ b/.changeset/dismissable-layer-stack.md @@ -0,0 +1,9 @@ +--- +"@solid-primitives/dismissable": minor +--- + +New package: `@solid-primitives/dismissable` + +Dismissable layers with a shared layer stack. `makeDismissableLayer` / `createDismissableLayer` handle Escape, outside pointer presses and outside focus (reusing `makeInteractOutside` from `@solid-primitives/interaction`), report a reason (`escape`, `outside-pointer`, `outside-focus`, `programmatic`), and only let the topmost non-persistent layer react so nested layers close one at a time. Supports `dismissible` + `onDismissAttempt`, `exclude`, `persistent` layers, `parent` registration for portaled children and `disableOutsidePointerEvents`. `getLayerStack`, `useLayerStack`, `getTopLayer` and `isTopLayer` expose the stack. + +An outside press and the focus move it causes are one interaction (no double `onDismiss` / `onDismissAttempt` for a layer that stays registered), and a touch tap dismisses the layer that was on top when the press began even if the tapped trigger opened a new layer. diff --git a/.changeset/focus-roving-scope-press-keeps-focus.md b/.changeset/focus-roving-scope-press-keeps-focus.md new file mode 100644 index 000000000..5f05ce82f --- /dev/null +++ b/.changeset/focus-roving-scope-press-keeps-focus.md @@ -0,0 +1,5 @@ +--- +"@solid-primitives/focus": minor +--- + +Add `makeRovingScope` / `createRovingScope` (roving tabindex for container items with orientation, loop, RTL, disabled skipping, MutationObserver tracking, remembered active item and independent nested scopes) and `makePressKeepsFocus` / `createPressKeepsFocus` (pressing non-text controls does not steal focus from the focused element). Existing APIs are unchanged. diff --git a/.changeset/interaction-inert-others.md b/.changeset/interaction-inert-others.md new file mode 100644 index 000000000..36da50107 --- /dev/null +++ b/.changeset/interaction-inert-others.md @@ -0,0 +1,7 @@ +--- +"@solid-primitives/interaction": minor +--- + +Add `makeInertOthers` and `createInertOthers`: mark every subtree outside one or more modal layer elements as `aria-hidden` and/or `inert`, with restoration of previous attribute values, ref-counted stacking of layers, an `ignore` list, live-region protection and a `MutationObserver` that also covers nodes added later. Their shared state lives on `globalThis`, so duplicate copies of the package stay consistent. Protected elements inside a target no longer get their siblings hidden, a root equal to a target is handled, live regions added later inside hidden branches are re-evaluated, and `createInertOthers` keeps its stack position when its inputs change (stacking order is opening order: re-enabling a layer puts it on top). `aria-hidden` is deferred on nodes that contain the focused element until focus leaves them, because Chrome ignores it there, and when every target is removed the layer keeps what it holds until it is updated or closed. `ariaHideOutside` and `createHideOutside` are unchanged. + +`makeInteractOutside` (and `createInteractOutside` / `interactOutside`) no longer leave a touch press armed after it turns into a scroll or drag: the pending touch is dropped on `pointercancel` / `touchcancel`, on movement beyond 10px, on a key press and after a short timeout, and the click must match the stored press. diff --git a/.changeset/keyboard-shortcut-registry.md b/.changeset/keyboard-shortcut-registry.md new file mode 100644 index 000000000..01e676417 --- /dev/null +++ b/.changeset/keyboard-shortcut-registry.md @@ -0,0 +1,15 @@ +--- +"@solid-primitives/keyboard": minor +--- + +Add `createShortcuts` and `makeShortcutRegistry`: register many keyboard shortcuts through a single keydown/keyup listener pair, with dynamic registration, per-shortcut `enabled`/`ignoreInputs`/`requireReset`/`preventDefault`, an optional scope element, and a deterministic conflict policy (most recently registered eligible shortcut wins). `createShortcut` is unchanged. + +Fix pressed-key tracking: keys are now released by the value recorded at keydown per physical key (`event.code`), so releasing Shift before a digit (`!` -> `1`) no longer leaves a stuck key in `useKeyDownList`, `createShortcut` and the registry. A scoped registry now also tracks key releases on `window` and resets when focus leaves the scope, so Tab moving focus out no longer leaves a stuck key. A scope that is not an ancestor of `window` in the event path (a bare `EventTarget`) also listens for keyup on itself, so its releases are seen too. + +Key releases are now always tracked on `window` in the capture phase in `useKeyDownList`, `createShortcut` and the registry, so an app handler calling `stopPropagation()` on keyup no longer leaves keys stuck. `CapsLock`, `NumLock` and `ScrollLock` are ignored (macOS sends only one of keydown/keyup for CapsLock, which broke every shortcut afterwards). `ignoreWithinInputs` / `ignoreInputs` now work for inputs inside iframes and open shadow roots, and a registry scope may be an iframe document. + +Holding both physical keys of a modifier (for example ControlLeft and ControlRight) no longer drops the modifier from the pressed set when only one of them is released while its event flag (`ctrlKey`, `shiftKey`, `altKey`, `metaKey`) is still set. Previously a `requireReset` shortcut could fire again before every key was released, and `useKeyDownList` briefly omitted the held modifier. + +**Behavior change:** `ignoreWithinInputs` (`createShortcut`) and `ignoreInputs` (registry) no longer suppress shortcuts while an `` whose type never accepts typed characters has focus: `checkbox`, `button`, `submit`, `reset` and `image` (case-insensitive). Previously every `` was treated as editable. Text-like inputs, `radio`, `range`, `file`, `color`, `textarea`, `select` and `contenteditable` are still ignored, since they consume typed characters or keys such as arrows. + +Keys whose `event.code` is empty or `"Unidentified"` (virtual/IME and some Android keyboards) no longer share one tracking slot, so pressing and releasing several of them can no longer leave a key stuck in `useKeyDownList`, `createShortcut` or the registry; they are tracked by `event.key` instead. In `+`-joined shortcut strings a literal plus key is now recognised in any position (`"Control+++K"`, `"a+++b"`), not only at the end. diff --git a/.changeset/new-floating-package.md b/.changeset/new-floating-package.md new file mode 100644 index 000000000..23c9a9673 --- /dev/null +++ b/.changeset/new-floating-package.md @@ -0,0 +1,5 @@ +--- +"@solid-primitives/floating": minor +--- + +Initial release of `@solid-primitives/floating`: `computePosition` and `computePositionFromRects` (placement, offset, flip, shift, size, arrow, RTL, boundaries), `makeAutoUpdate`, the reactive `createFloating`, and size CSS variable helpers. `computePosition` handles transformed containing blocks for `strategy: "fixed"` and scaled offset parents. Containing-block detection covers `offset-path`, `content-visibility`, `transform-style: preserve-3d` and exact `will-change` tokens (`filter` is ignored on `html`), a positioned `html` is honoured for `"absolute"`, top-layer elements (popover, modal dialog, fullscreen) ignore ancestor transforms, slotted elements find their containing block across shadow roots, and an RTL scrollbar on the left is excluded from the viewport boundary. diff --git a/.changeset/post-message-initial.md b/.changeset/post-message-initial.md new file mode 100644 index 000000000..25d91c8d6 --- /dev/null +++ b/.changeset/post-message-initial.md @@ -0,0 +1,7 @@ +--- +"@solid-primitives/post-message": minor +--- + +Initial release of `@solid-primitives/post-message`: `makePostMessage` and `createPostMessage` for window, iframe and `MessagePort` messaging with `allowedOrigins`, explicit `targetOrigin`, source filtering, type-narrowing validators and namespaced channels. + +Target detection is cross-origin safe: a `Window` is recognised first via the cross-origin-accessible `window` property, so `iframe.contentWindow`, `window.opener` and `window.parent` of another origin work without throwing a `SecurityError`. diff --git a/.changeset/presence-animation-aware.md b/.changeset/presence-animation-aware.md new file mode 100644 index 000000000..71b2ad245 --- /dev/null +++ b/.changeset/presence-animation-aware.md @@ -0,0 +1,5 @@ +--- +"@solid-primitives/presence": minor +--- + +Add opt-in animation-aware transitions: `animations: true` waits for `element.getAnimations({ subtree: true })` to settle (CSS transitions, CSS animations, Web Animations) instead of the fixed duration, falling back to the timer when no element is known or `getAnimations` is unavailable. The element comes from the new `element` option or the returned `ref`. Also returns `attrs()` with `data-starting-style` / `data-ending-style` for styling hooks. Fully backward compatible. diff --git a/.changeset/resize-observer-visual-viewport.md b/.changeset/resize-observer-visual-viewport.md new file mode 100644 index 000000000..bb3392f78 --- /dev/null +++ b/.changeset/resize-observer-visual-viewport.md @@ -0,0 +1,5 @@ +--- +"@solid-primitives/resize-observer": minor +--- + +Add `getVisualViewport`, `makeVisualViewportListener`, `createVisualViewport` and `useVisualViewport` for tracking `window.visualViewport` (size, offsets, pinch-zoom scale) with a `window.innerWidth/innerHeight` fallback and SSR/hydration-safe defaults. diff --git a/.changeset/scroll-raf-throttle.md b/.changeset/scroll-raf-throttle.md new file mode 100644 index 000000000..5f5bfcb81 --- /dev/null +++ b/.changeset/scroll-raf-throttle.md @@ -0,0 +1,5 @@ +--- +"@solid-primitives/scroll": minor +--- + +Add opt-in `requestAnimationFrame` throttling: `createScrollPosition(target, { throttle: "raf" })`, a non-reactive `makeScrollPositionListener`, and `useWindowScrollPositionRaf`. Default behavior is unchanged. diff --git a/.changeset/timer-pausable-timer.md b/.changeset/timer-pausable-timer.md new file mode 100644 index 000000000..0a4d0bee5 --- /dev/null +++ b/.changeset/timer-pausable-timer.md @@ -0,0 +1,5 @@ +--- +"@solid-primitives/timer": minor +--- + +Add `makePausableTimer` and `createPausableTimer`: one-shot timeouts that track remaining time across pause/resume, with a reactive delay, signal accessors (`remaining`, `isActive`, `isPaused`) and an opt-in `pauseWhenHidden` option. diff --git a/.changeset/virtual-variable-row-heights.md b/.changeset/virtual-variable-row-heights.md new file mode 100644 index 000000000..4e8e2438c --- /dev/null +++ b/.changeset/virtual-variable-row-heights.md @@ -0,0 +1,5 @@ +--- +"@solid-primitives/virtual": minor +--- + +Support variable row heights: `rowHeight` can now be a `(index) => number` function, and an opt-in measured mode (`estimatedRowHeight` plus `measureElement`, using `ResizeObserver`) records real heights. `createVirtualList` returns a third `helpers` tuple element (`getRowOffset`, `getRowHeight`, `measureElement`, `unmeasureElement`, `resetMeasurements`, `scrollToIndex`) and the state gains `offsets`. The fixed-height path is unchanged. diff --git a/README.md b/README.md index 22fb81781..bdc7b03cf 100644 --- a/README.md +++ b/README.md @@ -41,13 +41,13 @@ See the [migration guide](https://primitives.solidjs.community/migration) and th |

*Inputs*

| |[a11y](https://github.com/solidjs-community/solid-primitives/tree/main/packages/a11y#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createFormControl](https://github.com/solidjs-community/solid-primitives/tree/main/packages/a11y#createformcontrol)
[createFormControlInput](https://github.com/solidjs-community/solid-primitives/tree/main/packages/a11y#createformcontrolinput)
[FormControlContext](https://github.com/solidjs-community/solid-primitives/tree/main/packages/a11y#formcontrolcontext)
[useFormControl](https://github.com/solidjs-community/solid-primitives/tree/main/packages/a11y#useformcontrol)
[makeAnnounce](https://github.com/solidjs-community/solid-primitives/tree/main/packages/a11y#makeannounce)
[createAnnounce](https://github.com/solidjs-community/solid-primitives/tree/main/packages/a11y#createannounce)
[createReducedMotion](https://github.com/solidjs-community/solid-primitives/tree/main/packages/a11y#createreducedmotion)|[![SIZE](https://img.shields.io/badge/size-1.35_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/a11y)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/a11y?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/a11y)|✓| |[active-element](https://github.com/solidjs-community/solid-primitives/tree/main/packages/active-element#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createActiveElement](https://github.com/solidjs-community/solid-primitives/tree/main/packages/active-element#createactiveelement)|[![SIZE](https://img.shields.io/badge/size-552_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/active-element)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/active-element?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/active-element)|✓| -|[focus](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[autofocus](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#autofocus)
[createAutofocus](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#createautofocus)
[createFocusTrap](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#createfocustrap)
[createFocusRestore](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#createfocusrestore)
[createFocusGroup](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#createfocusgroup)
[makeFocusListener](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#makefocuslistener)
[createFocusSignal](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#createfocussignal)|[![SIZE](https://img.shields.io/badge/size-3.21_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/focus)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/focus?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/focus)|✓| +|[focus](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[autofocus](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#autofocus)
[createAutofocus](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#createautofocus)
[createFocusTrap](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#createfocustrap)
[createFocusRestore](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#createfocusrestore)
[createFocusGroup](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#createfocusgroup)
[makeRovingScope](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#makerovingscope)
[createRovingScope](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#createrovingscope)
[makePressKeepsFocus](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#makepresskeepsfocus)
[createPressKeepsFocus](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#createpresskeepsfocus)
[makeFocusListener](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#makefocuslistener)
[createFocusSignal](https://github.com/solidjs-community/solid-primitives/tree/main/packages/focus#createfocussignal)|[![SIZE](https://img.shields.io/badge/size-3.21_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/focus)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/focus?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/focus)|✓| |[input-mask](https://github.com/solidjs-community/solid-primitives/tree/main/packages/input-mask#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createInputMask](https://github.com/solidjs-community/solid-primitives/tree/main/packages/input-mask#createinputmask)
[createMaskPattern](https://github.com/solidjs-community/solid-primitives/tree/main/packages/input-mask#createmaskpattern)|[![SIZE](https://img.shields.io/badge/size-694_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/input-mask)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/input-mask?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/input-mask)|✓| -|[keyboard](https://github.com/solidjs-community/solid-primitives/tree/main/packages/keyboard#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[useKeyDownEvent](https://github.com/solidjs-community/solid-primitives/tree/main/packages/keyboard#usekeydownevent)
[useKeyDownList](https://github.com/solidjs-community/solid-primitives/tree/main/packages/keyboard#usekeydownlist)
[useCurrentlyHeldKey](https://github.com/solidjs-community/solid-primitives/tree/main/packages/keyboard#usecurrentlyheldkey)
[useKeyDownSequence](https://github.com/solidjs-community/solid-primitives/tree/main/packages/keyboard#usekeydownsequence)
[createKeyHold](https://github.com/solidjs-community/solid-primitives/tree/main/packages/keyboard#createkeyhold)
[createShortcut](https://github.com/solidjs-community/solid-primitives/tree/main/packages/keyboard#createshortcut)|[![SIZE](https://img.shields.io/badge/size-1.77_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/keyboard)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/keyboard?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/keyboard)|✓| +|[keyboard](https://github.com/solidjs-community/solid-primitives/tree/main/packages/keyboard#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[useKeyDownEvent](https://github.com/solidjs-community/solid-primitives/tree/main/packages/keyboard#usekeydownevent)
[useKeyDownList](https://github.com/solidjs-community/solid-primitives/tree/main/packages/keyboard#usekeydownlist)
[useCurrentlyHeldKey](https://github.com/solidjs-community/solid-primitives/tree/main/packages/keyboard#usecurrentlyheldkey)
[useKeyDownSequence](https://github.com/solidjs-community/solid-primitives/tree/main/packages/keyboard#usekeydownsequence)
[createKeyHold](https://github.com/solidjs-community/solid-primitives/tree/main/packages/keyboard#createkeyhold)
[createShortcut](https://github.com/solidjs-community/solid-primitives/tree/main/packages/keyboard#createshortcut)
[createShortcuts](https://github.com/solidjs-community/solid-primitives/tree/main/packages/keyboard#createshortcuts)
[makeShortcutRegistry](https://github.com/solidjs-community/solid-primitives/tree/main/packages/keyboard#makeshortcutregistry)|[![SIZE](https://img.shields.io/badge/size-1.77_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/keyboard)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/keyboard?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/keyboard)|✓| |[list-state](https://github.com/solidjs-community/solid-primitives/tree/main/packages/list-state#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createListState](https://github.com/solidjs-community/solid-primitives/tree/main/packages/list-state#createliststate)
[createMultiSelectListState](https://github.com/solidjs-community/solid-primitives/tree/main/packages/list-state#createmultiselectliststate)|[![SIZE](https://img.shields.io/badge/size-1.35_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/list-state)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/list-state?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/list-state)|✓| |[mouse](https://github.com/solidjs-community/solid-primitives/tree/main/packages/mouse#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createMousePosition](https://github.com/solidjs-community/solid-primitives/tree/main/packages/mouse#createmouseposition)
[createPositionToElement](https://github.com/solidjs-community/solid-primitives/tree/main/packages/mouse#createpositiontoelement)|[![SIZE](https://img.shields.io/badge/size-1.77_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/mouse)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/mouse?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/mouse)|✓| |[pointer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/pointer#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createPointerListeners](https://github.com/solidjs-community/solid-primitives/tree/main/packages/pointer#createpointerlisteners)
[createPerPointerListeners](https://github.com/solidjs-community/solid-primitives/tree/main/packages/pointer#createperpointerlisteners)
[createPointerPosition](https://github.com/solidjs-community/solid-primitives/tree/main/packages/pointer#createpointerposition)
[createPointerList](https://github.com/solidjs-community/solid-primitives/tree/main/packages/pointer#createpointerlist)|[![SIZE](https://img.shields.io/badge/size-1.99_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/pointer)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/pointer?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/pointer)|✓| -|[scroll](https://github.com/solidjs-community/solid-primitives/tree/main/packages/scroll#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createScrollPosition](https://github.com/solidjs-community/solid-primitives/tree/main/packages/scroll#createscrollposition)
[useWindowScrollPosition](https://github.com/solidjs-community/solid-primitives/tree/main/packages/scroll#usewindowscrollposition)
[createPreventScroll](https://github.com/solidjs-community/solid-primitives/tree/main/packages/scroll#createpreventscroll)|[![SIZE](https://img.shields.io/badge/size-2.37_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/scroll)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/scroll?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/scroll)|✓| +|[scroll](https://github.com/solidjs-community/solid-primitives/tree/main/packages/scroll#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createScrollPosition](https://github.com/solidjs-community/solid-primitives/tree/main/packages/scroll#createscrollposition)
[useWindowScrollPosition](https://github.com/solidjs-community/solid-primitives/tree/main/packages/scroll#usewindowscrollposition)
[useWindowScrollPositionRaf](https://github.com/solidjs-community/solid-primitives/tree/main/packages/scroll#usewindowscrollpositionraf)
[makeScrollPositionListener](https://github.com/solidjs-community/solid-primitives/tree/main/packages/scroll#makescrollpositionlistener)
[createPreventScroll](https://github.com/solidjs-community/solid-primitives/tree/main/packages/scroll#createpreventscroll)|[![SIZE](https://img.shields.io/badge/size-2.37_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/scroll)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/scroll?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/scroll)|✓| |[selection](https://github.com/solidjs-community/solid-primitives/tree/main/packages/selection#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createSelection](https://github.com/solidjs-community/solid-primitives/tree/main/packages/selection#createselection)|[![SIZE](https://img.shields.io/badge/size-926_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/selection)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/selection?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/selection)|✓| |

*Utilities*

| |[analytics](https://github.com/solidjs-community/solid-primitives/tree/main/packages/analytics#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-2.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[makeAnalytics](https://github.com/solidjs-community/solid-primitives/tree/main/packages/analytics#makeanalytics)
[createAnalytics](https://github.com/solidjs-community/solid-primitives/tree/main/packages/analytics#createanalytics)
[AnalyticsProvider](https://github.com/solidjs-community/solid-primitives/tree/main/packages/analytics#analyticsprovider)
[useAnalytics](https://github.com/solidjs-community/solid-primitives/tree/main/packages/analytics#useanalytics)
[makeAnalyticsGuard](https://github.com/solidjs-community/solid-primitives/tree/main/packages/analytics#makeanalyticsguard)
[createAnalyticsGuard](https://github.com/solidjs-community/solid-primitives/tree/main/packages/analytics#createanalyticsguard)
[createServerPlugin](https://github.com/solidjs-community/solid-primitives/tree/main/packages/analytics#createserverplugin)|[![SIZE](https://img.shields.io/badge/size-1.89_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/analytics)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/analytics?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/analytics)|✓| @@ -99,12 +99,12 @@ See the [migration guide](https://primitives.solidjs.community/migration) and th |[intersection-observer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/intersection-observer#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createIntersectionObserver](https://github.com/solidjs-community/solid-primitives/tree/main/packages/intersection-observer#createintersectionobserver)
[createViewportObserver](https://github.com/solidjs-community/solid-primitives/tree/main/packages/intersection-observer#createviewportobserver)
[createVisibilityObserver](https://github.com/solidjs-community/solid-primitives/tree/main/packages/intersection-observer#createvisibilityobserver)|[![SIZE](https://img.shields.io/badge/size-1.75_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/intersection-observer)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/intersection-observer?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/intersection-observer)|✓| |[media](https://github.com/solidjs-community/solid-primitives/tree/main/packages/media#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[makeMediaQueryListener](https://github.com/solidjs-community/solid-primitives/tree/main/packages/media#makemediaquerylistener)
[createMediaQuery](https://github.com/solidjs-community/solid-primitives/tree/main/packages/media#createmediaquery)
[createBreakpoints](https://github.com/solidjs-community/solid-primitives/tree/main/packages/media#createbreakpoints)
[usePrefersDark](https://github.com/solidjs-community/solid-primitives/tree/main/packages/media#useprefersdark)|[![SIZE](https://img.shields.io/badge/size-1.32_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/media)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/media?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/media)|✓| |[page-utilities](https://github.com/solidjs-community/solid-primitives/tree/main/packages/page-utilities#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createPageVisibility](https://github.com/solidjs-community/solid-primitives/tree/main/packages/page-utilities#createpagevisibility)
[usePageVisibility](https://github.com/solidjs-community/solid-primitives/tree/main/packages/page-utilities#usepagevisibility)
[makePageLeave](https://github.com/solidjs-community/solid-primitives/tree/main/packages/page-utilities#makepageleave)
[createPageLeaveBlocker](https://github.com/solidjs-community/solid-primitives/tree/main/packages/page-utilities#createpageleaveblocker)|[![SIZE](https://img.shields.io/badge/size-741_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/page-utilities)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/page-utilities?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/page-utilities)|✓| -|[resize-observer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/resize-observer#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createResizeObserver](https://github.com/solidjs-community/solid-primitives/tree/main/packages/resize-observer#createresizeobserver)
[createWindowSize](https://github.com/solidjs-community/solid-primitives/tree/main/packages/resize-observer#createwindowsize)
[createElementSize](https://github.com/solidjs-community/solid-primitives/tree/main/packages/resize-observer#createelementsize)|[![SIZE](https://img.shields.io/badge/size-1.52_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/resize-observer)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/resize-observer?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/resize-observer)|✓| +|[resize-observer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/resize-observer#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createResizeObserver](https://github.com/solidjs-community/solid-primitives/tree/main/packages/resize-observer#createresizeobserver)
[createWindowSize](https://github.com/solidjs-community/solid-primitives/tree/main/packages/resize-observer#createwindowsize)
[createVisualViewport](https://github.com/solidjs-community/solid-primitives/tree/main/packages/resize-observer#createvisualviewport)
[createElementSize](https://github.com/solidjs-community/solid-primitives/tree/main/packages/resize-observer#createelementsize)|[![SIZE](https://img.shields.io/badge/size-1.52_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/resize-observer)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/resize-observer?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/resize-observer)|✓| |[styles](https://github.com/solidjs-community/solid-primitives/tree/main/packages/styles#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createRemSize](https://github.com/solidjs-community/solid-primitives/tree/main/packages/styles#createremsize)|[![SIZE](https://img.shields.io/badge/size-704_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/styles)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/styles?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/styles)|✓| |[video](https://github.com/solidjs-community/solid-primitives/tree/main/packages/video#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[makeVideo](https://github.com/solidjs-community/solid-primitives/tree/main/packages/video#makevideo)
[makeVideoPlayer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/video#makevideoplayer)
[createVideo](https://github.com/solidjs-community/solid-primitives/tree/main/packages/video#createvideo)
[createVideoPlayer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/video#createvideoplayer)
[makeVideoFrameCallback](https://github.com/solidjs-community/solid-primitives/tree/main/packages/video#makevideoframecallback)
[createVideoFrameCallback](https://github.com/solidjs-community/solid-primitives/tree/main/packages/video#createvideoframecallback)|[![SIZE](https://img.shields.io/badge/size-1.89_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/video)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/video?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/video)|✓| |

*Browser APIs*

| |[broadcast-channel](https://github.com/solidjs-community/solid-primitives/tree/main/packages/broadcast-channel#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[makeBroadcastChannel](https://github.com/solidjs-community/solid-primitives/tree/main/packages/broadcast-channel#makebroadcastchannel)
[createBroadcastChannel](https://github.com/solidjs-community/solid-primitives/tree/main/packages/broadcast-channel#createbroadcastchannel)|[![SIZE](https://img.shields.io/badge/size-568_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/broadcast-channel)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/broadcast-channel?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/broadcast-channel)|✓| -|[clipboard](https://github.com/solidjs-community/solid-primitives/tree/main/packages/clipboard#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[copyClipboard](https://github.com/solidjs-community/solid-primitives/tree/main/packages/clipboard#copyclipboard)
[writeClipboard](https://github.com/solidjs-community/solid-primitives/tree/main/packages/clipboard#writeclipboard)
[createClipboard](https://github.com/solidjs-community/solid-primitives/tree/main/packages/clipboard#createclipboard)|[![SIZE](https://img.shields.io/badge/size-927_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/clipboard)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/clipboard?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/clipboard)|✓| +|[clipboard](https://github.com/solidjs-community/solid-primitives/tree/main/packages/clipboard#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[copyClipboard](https://github.com/solidjs-community/solid-primitives/tree/main/packages/clipboard#copyclipboard)
[writeClipboard](https://github.com/solidjs-community/solid-primitives/tree/main/packages/clipboard#writeclipboard)
[createClipboard](https://github.com/solidjs-community/solid-primitives/tree/main/packages/clipboard#createclipboard)
[createCopyToClipboard](https://github.com/solidjs-community/solid-primitives/tree/main/packages/clipboard#createcopytoclipboard)|[![SIZE](https://img.shields.io/badge/size-927_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/clipboard)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/clipboard?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/clipboard)|✓| |[event-listener](https://github.com/solidjs-community/solid-primitives/tree/main/packages/event-listener#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createEventListener](https://github.com/solidjs-community/solid-primitives/tree/main/packages/event-listener#createeventlistener)
[createEventSignal](https://github.com/solidjs-community/solid-primitives/tree/main/packages/event-listener#createeventsignal)
[createEventListenerMap](https://github.com/solidjs-community/solid-primitives/tree/main/packages/event-listener#createeventlistenermap)
[WindowEventListener](https://github.com/solidjs-community/solid-primitives/tree/main/packages/event-listener#windoweventlistener)
[DocumentEventListener](https://github.com/solidjs-community/solid-primitives/tree/main/packages/event-listener#documenteventlistener)|[![SIZE](https://img.shields.io/badge/size-989_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/event-listener)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/event-listener?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/event-listener)|✓| |[event-props](https://github.com/solidjs-community/solid-primitives/tree/main/packages/event-props#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createEventProps](https://github.com/solidjs-community/solid-primitives/tree/main/packages/event-props#createeventprops)|[![SIZE](https://img.shields.io/badge/size-172_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/event-props)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/event-props?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/event-props)|✓| |[favicon](https://github.com/solidjs-community/solid-primitives/tree/main/packages/favicon#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[makeFavicon](https://github.com/solidjs-community/solid-primitives/tree/main/packages/favicon#makefavicon)
[createFavicon](https://github.com/solidjs-community/solid-primitives/tree/main/packages/favicon#createfavicon)
[makeFaviconAnimation](https://github.com/solidjs-community/solid-primitives/tree/main/packages/favicon#makefaviconanimation)
[createFaviconAnimation](https://github.com/solidjs-community/solid-primitives/tree/main/packages/favicon#createfaviconanimation)
[makeFaviconBadge](https://github.com/solidjs-community/solid-primitives/tree/main/packages/favicon#makefaviconbadge)
[createFaviconBadge](https://github.com/solidjs-community/solid-primitives/tree/main/packages/favicon#createfaviconbadge)
[makeFaviconScheme](https://github.com/solidjs-community/solid-primitives/tree/main/packages/favicon#makefaviconscheme)
[createFaviconScheme](https://github.com/solidjs-community/solid-primitives/tree/main/packages/favicon#createfaviconscheme)
[makeFaviconProgress](https://github.com/solidjs-community/solid-primitives/tree/main/packages/favicon#makefaviconprogress)
[createFaviconProgress](https://github.com/solidjs-community/solid-primitives/tree/main/packages/favicon#createfaviconprogress)
[FaviconLink](https://github.com/solidjs-community/solid-primitives/tree/main/packages/favicon#faviconlink)|[![SIZE](https://img.shields.io/badge/size-2.56_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/favicon)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/favicon?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/favicon)|✓| @@ -116,7 +116,7 @@ See the [migration guide](https://primitives.solidjs.community/migration) and th |[notification](https://github.com/solidjs-community/solid-primitives/tree/main/packages/notification#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[isNotificationSupported](https://github.com/solidjs-community/solid-primitives/tree/main/packages/notification#isnotificationsupported)
[makeNotification](https://github.com/solidjs-community/solid-primitives/tree/main/packages/notification#makenotification)
[createNotification](https://github.com/solidjs-community/solid-primitives/tree/main/packages/notification#createnotification)
[createNotificationPermission](https://github.com/solidjs-community/solid-primitives/tree/main/packages/notification#createnotificationpermission)|[![SIZE](https://img.shields.io/badge/size-1.24_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/notification)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/notification?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/notification)|✓| |[permission](https://github.com/solidjs-community/solid-primitives/tree/main/packages/permission#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createPermission](https://github.com/solidjs-community/solid-primitives/tree/main/packages/permission#createpermission)|[![SIZE](https://img.shields.io/badge/size-483_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/permission)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/permission?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/permission)|✓| |[storage](https://github.com/solidjs-community/solid-primitives/tree/main/packages/storage#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[makePersisted](https://github.com/solidjs-community/solid-primitives/tree/main/packages/storage#makepersisted)
[cookieStorage](https://github.com/solidjs-community/solid-primitives/tree/main/packages/storage#cookiestorage)
[tauriStorage](https://github.com/solidjs-community/solid-primitives/tree/main/packages/storage#tauristorage)
[multiplexStorage](https://github.com/solidjs-community/solid-primitives/tree/main/packages/storage#multiplexstorage)
[storageSync](https://github.com/solidjs-community/solid-primitives/tree/main/packages/storage#storagesync)
[messageSync](https://github.com/solidjs-community/solid-primitives/tree/main/packages/storage#messagesync)
[wsSync](https://github.com/solidjs-community/solid-primitives/tree/main/packages/storage#wssync)
[multiplexSync](https://github.com/solidjs-community/solid-primitives/tree/main/packages/storage#multiplexsync)
[addClearMethod](https://github.com/solidjs-community/solid-primitives/tree/main/packages/storage#addclearmethod)
[addWithOptionsMethod](https://github.com/solidjs-community/solid-primitives/tree/main/packages/storage#addwithoptionsmethod)
[makeObjectStorage](https://github.com/solidjs-community/solid-primitives/tree/main/packages/storage#makeobjectstorage)|[![SIZE](https://img.shields.io/badge/size-2.77_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/storage)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/storage?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/storage)|✓| -|[timer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/timer#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[makeTimer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/timer#maketimer)
[createTimer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/timer#createtimer)
[createTimeoutLoop](https://github.com/solidjs-community/solid-primitives/tree/main/packages/timer#createtimeoutloop)
[createPolled](https://github.com/solidjs-community/solid-primitives/tree/main/packages/timer#createpolled)
[createIntervalCounter](https://github.com/solidjs-community/solid-primitives/tree/main/packages/timer#createintervalcounter)|[![SIZE](https://img.shields.io/badge/size-577_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/timer)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/timer?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/timer)|✓| +|[timer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/timer#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[makeTimer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/timer#maketimer)
[createTimer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/timer#createtimer)
[createTimeoutLoop](https://github.com/solidjs-community/solid-primitives/tree/main/packages/timer#createtimeoutloop)
[createPolled](https://github.com/solidjs-community/solid-primitives/tree/main/packages/timer#createpolled)
[createIntervalCounter](https://github.com/solidjs-community/solid-primitives/tree/main/packages/timer#createintervalcounter)
[makePausableTimer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/timer#makepausabletimer)
[createPausableTimer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/timer#createpausabletimer)|[![SIZE](https://img.shields.io/badge/size-577_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/timer)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/timer?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/timer)|✓| |[upload](https://github.com/solidjs-community/solid-primitives/tree/main/packages/upload#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createFilePicker](https://github.com/solidjs-community/solid-primitives/tree/main/packages/upload#createfilepicker)
[createDropzone](https://github.com/solidjs-community/solid-primitives/tree/main/packages/upload#createdropzone)
[dropzone](https://github.com/solidjs-community/solid-primitives/tree/main/packages/upload#dropzone)
[createFileUploader](https://github.com/solidjs-community/solid-primitives/tree/main/packages/upload#createfileuploader)
[fileSender](https://github.com/solidjs-community/solid-primitives/tree/main/packages/upload#filesender)
[fileUploader](https://github.com/solidjs-community/solid-primitives/tree/main/packages/upload#fileuploader)|[![SIZE](https://img.shields.io/badge/size-2.31_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/upload)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/upload?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/upload)|✓| |[url](https://github.com/solidjs-community/solid-primitives/tree/main/packages/url#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createLocationState](https://github.com/solidjs-community/solid-primitives/tree/main/packages/url#createlocationstate)
[useSharedLocationState](https://github.com/solidjs-community/solid-primitives/tree/main/packages/url#usesharedlocationstate)
[updateLocation](https://github.com/solidjs-community/solid-primitives/tree/main/packages/url#updatelocation)
[setLocationFallback](https://github.com/solidjs-community/solid-primitives/tree/main/packages/url#setlocationfallback)
[createURL](https://github.com/solidjs-community/solid-primitives/tree/main/packages/url#createurl)
[createURLRecord](https://github.com/solidjs-community/solid-primitives/tree/main/packages/url#createurlrecord)
[ReactiveURL](https://github.com/solidjs-community/solid-primitives/tree/main/packages/url#reactiveurl)
[createSearchParams](https://github.com/solidjs-community/solid-primitives/tree/main/packages/url#createsearchparams)
[createLocationSearchParams](https://github.com/solidjs-community/solid-primitives/tree/main/packages/url#createlocationsearchparams)
[useSharedLocationSearchParams](https://github.com/solidjs-community/solid-primitives/tree/main/packages/url#usesharedlocationsearchparams)
[getSearchParamsRecord](https://github.com/solidjs-community/solid-primitives/tree/main/packages/url#getsearchparamsrecord)
[ReactiveSearchParams](https://github.com/solidjs-community/solid-primitives/tree/main/packages/url#reactivesearchparams)|[![SIZE](https://img.shields.io/badge/size-2.76_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/url)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/url?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/url)|✓| |[workers](https://github.com/solidjs-community/solid-primitives/tree/main/packages/workers#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createWorker](https://github.com/solidjs-community/solid-primitives/tree/main/packages/workers#createworker)
[createWorkerPool](https://github.com/solidjs-community/solid-primitives/tree/main/packages/workers#createworkerpool)
[createWorkerQuery](https://github.com/solidjs-community/solid-primitives/tree/main/packages/workers#createworkerquery)
[createReactiveWorker](https://github.com/solidjs-community/solid-primitives/tree/main/packages/workers#createreactiveworker)
[workerScope](https://github.com/solidjs-community/solid-primitives/tree/main/packages/workers#workerscope)|[![SIZE](https://img.shields.io/badge/size-1.4_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/workers)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/workers?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/workers)|✓| @@ -125,6 +125,7 @@ See the [migration guide](https://primitives.solidjs.community/migration) and th |[cookies](https://github.com/solidjs-community/solid-primitives/tree/main/packages/cookies#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createServerCookie](https://github.com/solidjs-community/solid-primitives/tree/main/packages/cookies#createservercookie)
[createUserTheme](https://github.com/solidjs-community/solid-primitives/tree/main/packages/cookies#createusertheme)
[getCookiesString](https://github.com/solidjs-community/solid-primitives/tree/main/packages/cookies#getcookiesstring)|[![SIZE](https://img.shields.io/badge/size-456_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/cookies)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/cookies?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/cookies)|✓| |[fetch](https://github.com/solidjs-community/solid-primitives/tree/main/packages/fetch#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createFetch](https://github.com/solidjs-community/solid-primitives/tree/main/packages/fetch#createfetch)|[![SIZE](https://img.shields.io/badge/size-2.29_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/fetch)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/fetch?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/fetch)|| |[graphql](https://github.com/solidjs-community/solid-primitives/tree/main/packages/graphql#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createGraphQLClient](https://github.com/solidjs-community/solid-primitives/tree/main/packages/graphql#creategraphqlclient)
[createGraphQLMutation](https://github.com/solidjs-community/solid-primitives/tree/main/packages/graphql#creategraphqlmutation)|[![SIZE](https://img.shields.io/badge/size-1.23_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/graphql)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/graphql?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/graphql)|✓| +|[post-message](https://github.com/solidjs-community/solid-primitives/tree/main/packages/post-message#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-0.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[makePostMessage](https://github.com/solidjs-community/solid-primitives/tree/main/packages/post-message#makepostmessage)
[createPostMessage](https://github.com/solidjs-community/solid-primitives/tree/main/packages/post-message#createpostmessage)|[![SIZE](https://img.shields.io/badge/size-1.02_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/post-message)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/post-message?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/post-message)|✓| |[sse](https://github.com/solidjs-community/solid-primitives/tree/main/packages/sse#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[makeSSE](https://github.com/solidjs-community/solid-primitives/tree/main/packages/sse#makesse)
[createSSE](https://github.com/solidjs-community/solid-primitives/tree/main/packages/sse#createsse)
[makeSSEWorker](https://github.com/solidjs-community/solid-primitives/tree/main/packages/sse#makesseworker)|[![SIZE](https://img.shields.io/badge/size-1.63_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/sse)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/sse?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/sse)|✓| |[websocket](https://github.com/solidjs-community/solid-primitives/tree/main/packages/websocket#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[makeWS](https://github.com/solidjs-community/solid-primitives/tree/main/packages/websocket#makews)
[createWS](https://github.com/solidjs-community/solid-primitives/tree/main/packages/websocket#createws)
[createWSState](https://github.com/solidjs-community/solid-primitives/tree/main/packages/websocket#createwsstate)
[createWSMessage](https://github.com/solidjs-community/solid-primitives/tree/main/packages/websocket#createwsmessage)
[makeReconnectingWS](https://github.com/solidjs-community/solid-primitives/tree/main/packages/websocket#makereconnectingws)
[createReconnectingWS](https://github.com/solidjs-community/solid-primitives/tree/main/packages/websocket#createreconnectingws)
[makeHeartbeatWS](https://github.com/solidjs-community/solid-primitives/tree/main/packages/websocket#makeheartbeatws)
[wsMessageIterable](https://github.com/solidjs-community/solid-primitives/tree/main/packages/websocket#wsmessageiterable)
[createWSData](https://github.com/solidjs-community/solid-primitives/tree/main/packages/websocket#createwsdata)
[createWSStore](https://github.com/solidjs-community/solid-primitives/tree/main/packages/websocket#createwsstore)|[![SIZE](https://img.shields.io/badge/size-1.09_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/websocket)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/websocket?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/websocket)|✓| |

*Control Flow*

| @@ -136,7 +137,9 @@ See the [migration guide](https://primitives.solidjs.community/migration) and th |[range](https://github.com/solidjs-community/solid-primitives/tree/main/packages/range#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createNumericRange](https://github.com/solidjs-community/solid-primitives/tree/main/packages/range#createnumericrange)
[repeat](https://github.com/solidjs-community/solid-primitives/tree/main/packages/range#repeat)
[mapRange](https://github.com/solidjs-community/solid-primitives/tree/main/packages/range#maprange)
[indexRange](https://github.com/solidjs-community/solid-primitives/tree/main/packages/range#indexrange)
[Repeat](https://github.com/solidjs-community/solid-primitives/tree/main/packages/range#repeat)
[IndexRange](https://github.com/solidjs-community/solid-primitives/tree/main/packages/range#indexrange)|[![SIZE](https://img.shields.io/badge/size-1.53_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/range)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/range?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/range)|✓| |[refs](https://github.com/solidjs-community/solid-primitives/tree/main/packages/refs#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[mergeRefs](https://github.com/solidjs-community/solid-primitives/tree/main/packages/refs#mergerefs)
[resolveElements](https://github.com/solidjs-community/solid-primitives/tree/main/packages/refs#resolveelements)
[resolveFirst](https://github.com/solidjs-community/solid-primitives/tree/main/packages/refs#resolvefirst)
[Ref](https://github.com/solidjs-community/solid-primitives/tree/main/packages/refs#ref)
[Refs](https://github.com/solidjs-community/solid-primitives/tree/main/packages/refs#refs)|[![SIZE](https://img.shields.io/badge/size-677_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/refs)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/refs?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/refs)|✓| |

*UI Patterns*

| +|[dismissable](https://github.com/solidjs-community/solid-primitives/tree/main/packages/dismissable#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-0.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[makeDismissableLayer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/dismissable#makedismissablelayer)
[createDismissableLayer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/dismissable#createdismissablelayer)
[getLayerStack](https://github.com/solidjs-community/solid-primitives/tree/main/packages/dismissable#getlayerstack)
[useLayerStack](https://github.com/solidjs-community/solid-primitives/tree/main/packages/dismissable#uselayerstack)
[isTopLayer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/dismissable#istoplayer)
[getTopLayer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/dismissable#gettoplayer)|[![SIZE](https://img.shields.io/badge/size-2.56_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/dismissable)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/dismissable?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/dismissable)|✓| |[drag-drop](https://github.com/solidjs-community/solid-primitives/tree/main/packages/drag-drop#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-2.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[makeDraggable](https://github.com/solidjs-community/solid-primitives/tree/main/packages/drag-drop#makedraggable)
[makeDroppable](https://github.com/solidjs-community/solid-primitives/tree/main/packages/drag-drop#makedroppable)
[makeNativeDroppable](https://github.com/solidjs-community/solid-primitives/tree/main/packages/drag-drop#makenativedroppable)
[createDraggable](https://github.com/solidjs-community/solid-primitives/tree/main/packages/drag-drop#createdraggable)
[createDroppable](https://github.com/solidjs-community/solid-primitives/tree/main/packages/drag-drop#createdroppable)
[createNativeDroppable](https://github.com/solidjs-community/solid-primitives/tree/main/packages/drag-drop#createnativedroppable)
[createSortable](https://github.com/solidjs-community/solid-primitives/tree/main/packages/drag-drop#createsortable)
[createDragContext](https://github.com/solidjs-community/solid-primitives/tree/main/packages/drag-drop#createdragcontext)
[closestCenter](https://github.com/solidjs-community/solid-primitives/tree/main/packages/drag-drop#closestcenter)
[closestCorners](https://github.com/solidjs-community/solid-primitives/tree/main/packages/drag-drop#closestcorners)
[rectIntersection](https://github.com/solidjs-community/solid-primitives/tree/main/packages/drag-drop#rectintersection)
[pointerWithin](https://github.com/solidjs-community/solid-primitives/tree/main/packages/drag-drop#pointerwithin)|[![SIZE](https://img.shields.io/badge/size-3.98_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/drag-drop)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/drag-drop?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/drag-drop)|✓| +|[floating](https://github.com/solidjs-community/solid-primitives/tree/main/packages/floating#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-0.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[computePosition](https://github.com/solidjs-community/solid-primitives/tree/main/packages/floating#computeposition)
[computePositionFromRects](https://github.com/solidjs-community/solid-primitives/tree/main/packages/floating#computepositionfromrects)
[makeAutoUpdate](https://github.com/solidjs-community/solid-primitives/tree/main/packages/floating#makeautoupdate)
[createFloating](https://github.com/solidjs-community/solid-primitives/tree/main/packages/floating#createfloating)
[getSizeCssVars](https://github.com/solidjs-community/solid-primitives/tree/main/packages/floating#getsizecssvars)
[applySizeCssVars](https://github.com/solidjs-community/solid-primitives/tree/main/packages/floating#applysizecssvars)|[![SIZE](https://img.shields.io/badge/size-3.73_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/floating)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/floating?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/floating)|✓| |[form](https://github.com/solidjs-community/solid-primitives/tree/main/packages/form#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-2.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createForm](https://github.com/solidjs-community/solid-primitives/tree/main/packages/form#createform)
[toFormData](https://github.com/solidjs-community/solid-primitives/tree/main/packages/form#toformdata)
[createFormResetListener](https://github.com/solidjs-community/solid-primitives/tree/main/packages/form#createformresetlistener)
[createFormControl](https://github.com/solidjs-community/solid-primitives/tree/main/packages/form#createformcontrol)
[createFormControlInput](https://github.com/solidjs-community/solid-primitives/tree/main/packages/form#createformcontrolinput)
[FormControlContext](https://github.com/solidjs-community/solid-primitives/tree/main/packages/form#formcontrolcontext)
[useFormControl](https://github.com/solidjs-community/solid-primitives/tree/main/packages/form#useformcontrol)|[![SIZE](https://img.shields.io/badge/size-2.61_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/form)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/form?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/form)|✓| |[marker](https://github.com/solidjs-community/solid-primitives/tree/main/packages/marker#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createMarker](https://github.com/solidjs-community/solid-primitives/tree/main/packages/marker#createmarker)|[![SIZE](https://img.shields.io/badge/size-510_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/marker)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/marker?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/marker)|✓| |[masonry](https://github.com/solidjs-community/solid-primitives/tree/main/packages/masonry#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createMasonry](https://github.com/solidjs-community/solid-primitives/tree/main/packages/masonry#createmasonry)|[![SIZE](https://img.shields.io/badge/size-637_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/masonry)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/masonry?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/masonry)|✓| diff --git a/deno.lock b/deno.lock index 09f51afb7..7a6e95ae5 100644 --- a/deno.lock +++ b/deno.lock @@ -2038,12 +2038,6 @@ "react" ] }, - "@napi-rs/wasm-runtime@1.2.6_@emnapi+core@1.11.0_@emnapi+runtime@1.11.0": { - "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", - "dependencies": [ - "@tybys/wasm-util" - ] - }, "@napi-rs/wasm-runtime@1.2.6_@emnapi+core@1.11.1_@emnapi+runtime@1.11.1": { "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", "dependencies": [ @@ -2052,12 +2046,6 @@ "@tybys/wasm-util" ] }, - "@napi-rs/wasm-runtime@1.2.6_@emnapi+core@1.11.3_@emnapi+runtime@1.11.3": { - "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", - "dependencies": [ - "@tybys/wasm-util" - ] - }, "@napi-rs/wasm-runtime@1.2.6_@emnapi+core@1.9.2_@emnapi+runtime@1.9.2": { "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", "dependencies": [ @@ -2535,7 +2523,7 @@ "dependencies": [ "@emnapi/core@1.11.0", "@emnapi/runtime@1.11.0", - "@napi-rs/wasm-runtime@1.2.6_@emnapi+core@1.11.0_@emnapi+runtime@1.11.0" + "@napi-rs/wasm-runtime@1.2.6_@emnapi+core@1.9.2_@emnapi+runtime@1.9.2" ], "cpu": ["wasm32"] }, @@ -3173,7 +3161,7 @@ "dependencies": [ "@emnapi/core@1.11.3", "@emnapi/runtime@1.11.3", - "@napi-rs/wasm-runtime@1.2.6_@emnapi+core@1.11.3_@emnapi+runtime@1.11.3" + "@napi-rs/wasm-runtime@1.2.6_@emnapi+core@1.9.2_@emnapi+runtime@1.9.2" ] }, "@solidjs/compiler-win32-x64-msvc@2.0.0": { @@ -8791,6 +8779,14 @@ ] } }, + "packages/dismissable": { + "packageJson": { + "dependencies": [ + "npm:@solidjs/web@2.0.0", + "npm:solid-js@2" + ] + } + }, "packages/drag-drop": { "packageJson": { "dependencies": [ @@ -8856,6 +8852,14 @@ ] } }, + "packages/floating": { + "packageJson": { + "dependencies": [ + "npm:@solidjs/web@2.0.0", + "npm:solid-js@2" + ] + } + }, "packages/flux-store": { "packageJson": { "dependencies": [ @@ -9149,6 +9153,14 @@ ] } }, + "packages/post-message": { + "packageJson": { + "dependencies": [ + "npm:@solidjs/web@2.0.0", + "npm:solid-js@2" + ] + } + }, "packages/presence": { "packageJson": { "dependencies": [ diff --git a/packages/clipboard/README.md b/packages/clipboard/README.md index 6daf290b9..99edb3c3c 100644 --- a/packages/clipboard/README.md +++ b/packages/clipboard/README.md @@ -14,6 +14,7 @@ Primitives for reading and writing to the [Clipboard API](https://developer.mozi - [`readClipboard`](#readclipboard) - One-shot async read of clipboard items. - [`writeClipboard`](#writeclipboard) - One-shot async write to the clipboard. - [`createClipboard`](#createclipboard) - Reactive clipboard backed by an async memo. Reads on demand, writes reactively from a signal. +- [`createCopyToClipboard`](#createcopytoclipboard) - Copy with a transient `copied` status that auto-resets, ideal for copy buttons. - [`copyToClipboard`](#copytoclipboard) - `ref` directive factory that copies an element's value to clipboard on click. ## Installation @@ -126,6 +127,37 @@ import { isPending } from "solid-js";

{isPending(() => clipboard()) ? "Reading…" : `${clipboard().length} items`}

; ``` +## `createCopyToClipboard` + +Writes to the clipboard and tracks a short-lived status (`"idle"`, `"copied"`, `"error"`) that returns to `"idle"` after `resetAfter` milliseconds. Copying again restarts the timer, the timer is cleared on disposal, and results arriving after disposal are ignored. On the server `copy` resolves `false` and the status stays `"idle"`. + +```ts +// Type +function createCopyToClipboard(options?: { + resetAfter?: number; // default 2000; 0 or Infinity disables auto-reset + onCopied?: (data: string | ClipboardItem[]) => void; + onError?: (error: unknown) => void; +}): { + copy: (data: string | ClipboardItem[]) => Promise; // never rejects + status: Accessor<"idle" | "copied" | "error">; + copied: Accessor; + error: Accessor; + reset: VoidFunction; +}; + +// Example: a copy button +import { createCopyToClipboard } from "@solid-primitives/clipboard"; + +function CopyButton(props: { text: string }) { + const { copy, copied, status } = createCopyToClipboard({ resetAfter: 1500 }); + return ( + + ); +} +``` + ## `copyToClipboard` A `ref` directive factory that writes an element's value to clipboard on click. On ``/`
x
`; + const q = (id: string) => document.getElementById(id)!; + q("editor").focus(); + return q; +} + +afterEach(() => { + document.body.innerHTML = ""; +}); + +describe("makePressKeepsFocus", () => { + it("prevents pointerdown and mousedown on buttons but not click", () => { + const q = setup(); + const clear = makePressKeepsFocus(q("bar")); + expect(fire(q("bold"), "pointerdown").defaultPrevented).toBe(true); + expect(fire(q("bold"), "mousedown").defaultPrevented).toBe(true); + const onClick = vi.fn(); + q("bold").addEventListener("click", onClick); + expect(fire(q("bold"), "click").defaultPrevented).toBe(false); + expect(onClick).toHaveBeenCalledOnce(); + clear(); + }); + + it("opts out for text inputs, textarea, select, contenteditable and checkbox-less inputs", () => { + const q = setup(); + makePressKeepsFocus(q("bar")); + for (const id of ["field", "ta", "sel", "inner"]) { + expect(fire(q(id), "mousedown").defaultPrevented, id).toBe(false); + } + // a checkbox is a non-text control + expect(fire(q("box"), "mousedown").defaultPrevented).toBe(true); + }); + + it("supports ignore and enabled", () => { + const q = setup(); + let enabled = true; + makePressKeepsFocus(q("bar"), { + ignore: t => t.hasAttribute("data-skip"), + enabled: () => enabled, + }); + expect(fire(q("skip"), "mousedown").defaultPrevented).toBe(false); + expect(fire(q("bold"), "mousedown").defaultPrevented).toBe(true); + enabled = false; + expect(fire(q("bold"), "mousedown").defaultPrevented).toBe(false); + }); + + it("does nothing when nothing is focused (unless onlyWhenFocused is false)", () => { + const q = setup(); + (document.activeElement as HTMLElement).blur(); + makePressKeepsFocus(q("bar")); + expect(fire(q("bold"), "mousedown").defaultPrevented).toBe(false); + makePressKeepsFocus(q("bar"), { onlyWhenFocused: false }); + expect(fire(q("bold"), "mousedown").defaultPrevented).toBe(true); + }); + + it("does not touch already-prevented events and stops after cleanup", () => { + const q = setup(); + const clear = makePressKeepsFocus(q("bar")); + clear(); + expect(fire(q("bold"), "mousedown").defaultPrevented).toBe(false); + }); +}); + +describe("createPressKeepsFocus", () => { + it("works as ref factory for several elements and cleans up with the owner", () => { + const q = setup(); + let ref!: (el: HTMLElement) => void; + const dispose = createRoot(d => { + ref = createPressKeepsFocus(); + return d; + }); + ref(q("bar")); + ref(q("editor")); + expect(fire(q("bold"), "pointerdown").defaultPrevented).toBe(true); + dispose(); + expect(fire(q("bold"), "pointerdown").defaultPrevented).toBe(false); + }); +}); diff --git a/packages/focus/test/rovingScope.test.ts b/packages/focus/test/rovingScope.test.ts new file mode 100644 index 000000000..7dcb52440 --- /dev/null +++ b/packages/focus/test/rovingScope.test.ts @@ -0,0 +1,351 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { createRoot, createSignal, flush } from "solid-js"; +import { createRovingScope, makeRovingScope } from "../src/index.js"; + +const tick = () => new Promise(r => setTimeout(r, 0)); + +const key = (el: Element, k: string, init: KeyboardEventInit = {}) => { + const e = new KeyboardEvent("keydown", { key: k, bubbles: true, cancelable: true, ...init }); + el.dispatchEvent(e); + return e; +}; + +const html = (inner: string) => { + document.body.innerHTML = `
${inner}
`; + return document.getElementById("root")!; +}; +const btn = (id: string) => document.getElementById(id) as HTMLElement; +const tabindexes = (root: Element) => + [...root.querySelectorAll("button")].map(b => b.getAttribute("tabindex")); + +afterEach(() => { + document.body.innerHTML = ""; +}); + +describe("makeRovingScope", () => { + it("makes only the first item tabbable and ignores non-matching elements", () => { + const root = html(`x`); + makeRovingScope(root, { selector: "button" }); + expect(tabindexes(root)).toEqual(["0", "-1"]); + expect(btn("s").hasAttribute("tabindex")).toBe(false); + }); + + it("honors initialActive and falls back when it is not navigable", () => { + const root = html(``); + const scope = makeRovingScope(root, { selector: "button", initialActive: i => i[1] }); + expect(tabindexes(root)).toEqual(["-1", "0"]); + expect(scope.active()).toBe(btn("b")); + }); + + it("navigates with arrows, Home and End and prevents default", () => { + const root = html( + ``, + ); + makeRovingScope(root, { selector: "button", orientation: "horizontal" }); + btn("a").focus(); + expect(key(btn("a"), "ArrowRight").defaultPrevented).toBe(true); + expect(document.activeElement).toBe(btn("b")); + expect(tabindexes(root)).toEqual(["-1", "0", "-1"]); + key(btn("b"), "End"); + expect(document.activeElement).toBe(btn("c")); + key(btn("c"), "Home"); + expect(document.activeElement).toBe(btn("a")); + key(btn("a"), "ArrowLeft"); // no loop: stays + expect(document.activeElement).toBe(btn("a")); + }); + + it("respects orientation", () => { + const root = html(``); + makeRovingScope(root, { selector: "button", orientation: "vertical" }); + btn("a").focus(); + expect(key(btn("a"), "ArrowRight").defaultPrevented).toBe(false); + expect(document.activeElement).toBe(btn("a")); + key(btn("a"), "ArrowDown"); + expect(document.activeElement).toBe(btn("b")); + key(btn("b"), "ArrowUp"); + expect(document.activeElement).toBe(btn("a")); + }); + + it("orientation both accepts all arrows", () => { + const root = html(``); + makeRovingScope(root, { selector: "button" }); + btn("a").focus(); + key(btn("a"), "ArrowDown"); + expect(document.activeElement).toBe(btn("b")); + key(btn("b"), "ArrowLeft"); + expect(document.activeElement).toBe(btn("a")); + }); + + it("loops when asked", () => { + const root = html(``); + makeRovingScope(root, { selector: "button", loop: true, orientation: "horizontal" }); + btn("a").focus(); + key(btn("a"), "ArrowLeft"); + expect(document.activeElement).toBe(btn("b")); + key(btn("b"), "ArrowRight"); + expect(document.activeElement).toBe(btn("a")); + }); + + it("flips horizontal arrows in rtl (option and [dir] detection)", () => { + const root = html(``); + const scope = makeRovingScope(root, { + selector: "button", + orientation: "horizontal", + textDirection: "rtl", + }); + btn("a").focus(); + key(btn("a"), "ArrowLeft"); + expect(document.activeElement).toBe(btn("b")); + scope.dispose(); + + document.body.innerHTML = `
`; + makeRovingScope(document.getElementById("root")!, { + selector: "button", + orientation: "horizontal", + }); + btn("a").focus(); + key(btn("a"), "ArrowRight"); + expect(document.activeElement).not.toBe(btn("b")); + key(btn("a"), "ArrowLeft"); + expect(document.activeElement).toBe(btn("b")); + }); + + it("skips disabled, aria-disabled and hidden items", () => { + const root = html( + ``, + ); + makeRovingScope(root, { selector: "button", orientation: "horizontal" }); + btn("a").focus(); + key(btn("a"), "ArrowRight"); + expect(document.activeElement).toBe(btn("e")); + }); + + it("can keep aria-disabled items navigable", () => { + const root = html(``); + makeRovingScope(root, { selector: "button", skipDisabled: false, orientation: "horizontal" }); + btn("a").focus(); + key(btn("a"), "ArrowRight"); + expect(document.activeElement).toBe(btn("c")); + }); + + it("does not start on a disabled first item", () => { + const root = html(``); + makeRovingScope(root, { selector: "button" }); + expect(tabindexes(root)).toEqual(["-1", "0"]); + }); + + it("remembers the last active item when focus leaves and returns", () => { + document.body.innerHTML = `
`; + const root = document.getElementById("root")!; + const scope = makeRovingScope(root, { selector: "button" }); + btn("a").focus(); + key(btn("a"), "ArrowRight"); + btn("out").focus(); + expect(scope.active()).toBe(btn("b")); + expect(tabindexes(root)).toEqual(["-1", "0"]); + expect(scope.focus()).toBe(btn("b")); + expect(document.activeElement).toBe(btn("b")); + }); + + it("follows focus moved by click/programmatically", () => { + const root = html(``); + const onActiveChange = vi.fn(); + makeRovingScope(root, { selector: "button", onActiveChange }); + btn("b").focus(); + expect(tabindexes(root)).toEqual(["-1", "0"]); + expect(onActiveChange).toHaveBeenLastCalledWith(btn("b")); + }); + + it("picks up added items and re-elects when the active one is removed", async () => { + const root = html( + ``, + ); + const scope = makeRovingScope(root, { selector: "button" }); + btn("b").focus(); + const d = document.createElement("button"); + d.id = "d"; + d.setAttribute("tabindex", "0"); + root.append(d); + await tick(); + expect(tabindexes(root)).toEqual(["-1", "0", "-1", "-1"]); + btn("b").remove(); + await tick(); + expect(scope.active()).toBe(btn("c")); + expect(tabindexes(root)).toEqual(["-1", "0", "-1"]); + btn("c").remove(); + btn("d").remove(); + await tick(); + expect(scope.active()).toBe(btn("a")); + }); + + it("re-elects when the active item becomes disabled", async () => { + const root = html(``); + const scope = makeRovingScope(root, { selector: "button" }); + btn("a").setAttribute("disabled", ""); + await tick(); + expect(scope.active()).toBe(btn("b")); + }); + + it("keeps nested scopes independent", () => { + const root = html( + `
`, + ); + const outer = makeRovingScope(root, { selector: "button", orientation: "horizontal" }); + const inner = makeRovingScope(document.getElementById("inner")!, { + selector: "button", + orientation: "vertical", + }); + expect(outer.items().map(i => i.id)).toEqual(["a", "b"]); + expect(inner.items().map(i => i.id)).toEqual(["x", "y"]); + expect(btn("x").getAttribute("tabindex")).toBe("0"); + expect(btn("y").getAttribute("tabindex")).toBe("-1"); + expect(btn("b").getAttribute("tabindex")).toBe("-1"); + + btn("x").focus(); + key(btn("x"), "ArrowRight"); // inner is vertical; outer must not react either + expect(document.activeElement).toBe(btn("x")); + key(btn("x"), "ArrowDown"); + expect(document.activeElement).toBe(btn("y")); + expect(outer.active()).toBe(btn("a")); + btn("a").focus(); + key(btn("a"), "ArrowRight"); + expect(document.activeElement).toBe(btn("b")); + expect(inner.active()).toBe(btn("y")); + }); + + it("an outer scope created before the inner one releases the inner items", () => { + const root = html(`
`); + const outer = makeRovingScope(root, { selector: "button" }); + expect(outer.items().length).toBe(2); + const inner = makeRovingScope(document.getElementById("inner")!, { selector: "button" }); + expect(outer.items().map(i => i.id)).toEqual(["a"]); + expect(btn("x").getAttribute("tabindex")).toBe("0"); + inner.dispose(); + expect(outer.items().map(i => i.id)).toEqual(["a", "x"]); + expect(btn("x").hasAttribute("tabindex")).toBe(true); + expect(btn("x").getAttribute("tabindex")).toBe("-1"); + }); + + it("ignores arrows inside text fields, modified keys and defaultPrevented events", () => { + const root = html(``); + makeRovingScope(root, { selector: "input, button", orientation: "horizontal" }); + btn("i").focus(); + expect(key(btn("i"), "ArrowRight").defaultPrevented).toBe(false); + expect(document.activeElement).toBe(btn("i")); + btn("b").focus(); + key(btn("b"), "ArrowLeft", { shiftKey: true }); + key(btn("b"), "ArrowLeft", { ctrlKey: true }); + expect(document.activeElement).toBe(btn("b")); + }); + + it("restores original tabindex values and removes listeners on dispose", async () => { + const root = html(``); + const scope = makeRovingScope(root, { selector: "button" }); + expect(btn("a").getAttribute("tabindex")).toBe("0"); + scope.dispose(); + expect(btn("a").getAttribute("tabindex")).toBe("3"); + expect(btn("b").hasAttribute("tabindex")).toBe(false); + btn("a").focus(); + key(btn("a"), "ArrowRight"); + expect(document.activeElement).toBe(btn("a")); + const d = document.createElement("button"); + root.append(d); + await tick(); + expect(d.hasAttribute("tabindex")).toBe(false); + scope.dispose(); // idempotent + }); + + it("can disable keyboard navigation and exposes imperative navigation", () => { + const root = html( + ``, + ); + const scope = makeRovingScope(root, { selector: "button", keyboardNavigation: false }); + btn("a").focus(); + key(btn("a"), "ArrowRight"); + expect(document.activeElement).toBe(btn("a")); + expect(scope.focusNext()).toBe(btn("b")); + expect(scope.focusLast()).toBe(btn("c")); + expect(scope.focusPrevious()).toBe(btn("b")); + expect(scope.focusFirst()).toBe(btn("a")); + expect(scope.setActive(btn("c"))).toBe(true); + expect(tabindexes(root)).toEqual(["-1", "-1", "0"]); + expect(scope.setActive(document.body)).toBe(false); + }); +}); + +describe("makeRovingScope owner cleanup", () => { + it("restores tabindex and detaches on owner disposal", () => { + const root = html(``); + createRoot(d => { + makeRovingScope(root, { selector: "button" }); + expect(tabindexes(root)).toEqual(["0", "-1"]); + d(); + }); + expect(tabindexes(root)).toEqual([null, null]); + }); +}); + +describe("createRovingScope", () => { + it("keeps the remembered item when non-structural options change", () => { + const root = html(``); + const [loop, setLoop] = createSignal(false); + let scope!: ReturnType; + createRoot(() => { + scope = createRovingScope(() => root, { selector: "button", loop }); + }); + flush(); + btn("b").focus(); + flush(); + expect(scope.active()).toBe(btn("b")); + setLoop(true); + flush(); + expect(scope.active()).toBe(btn("b")); + expect(tabindexes(root)).toEqual(["-1", "0"]); + }); + + it("is reactive in container and options, and cleans up", () => { + const root = html(``); + const [el, setEl] = createSignal(undefined); + const [loop, setLoop] = createSignal(false); + let scope!: ReturnType; + const dispose = createRoot(d => { + scope = createRovingScope(el, { selector: "button", loop, orientation: "horizontal" }); + return d; + }); + flush(); + expect(scope.active()).toBeUndefined(); + setEl(root); + flush(); + expect(scope.active()).toBe(btn("a")); + btn("a").focus(); + key(btn("a"), "ArrowLeft"); + expect(document.activeElement).toBe(btn("a")); + setLoop(true); + flush(); + expect(scope.active()).toBe(btn("a")); + key(btn("a"), "ArrowLeft"); + expect(document.activeElement).toBe(btn("b")); + flush(); + expect(scope.active()).toBe(btn("b")); + expect(scope.focusFirst()).toBe(btn("a")); + dispose(); + flush(); + expect(btn("a").hasAttribute("tabindex")).toBe(false); + expect(scope.focusNext()).toBeUndefined(); + }); + + it("enabled=false restores tabindex", () => { + const root = html(``); + const [enabled, setEnabled] = createSignal(true); + const dispose = createRoot(d => { + createRovingScope(() => root, { selector: "button", enabled }); + return d; + }); + flush(); + expect(tabindexes(root)).toEqual(["0", "-1"]); + setEnabled(false); + flush(); + expect(tabindexes(root)).toEqual([null, null]); + dispose(); + }); +}); diff --git a/packages/focus/test/server.test.ts b/packages/focus/test/server.test.ts index 3a7cf61f3..5e576ce0e 100644 --- a/packages/focus/test/server.test.ts +++ b/packages/focus/test/server.test.ts @@ -1,6 +1,14 @@ import { describe, expect, it } from "vitest"; import { createRoot } from "solid-js"; -import { createAutofocus, createFocusTrap, createFocusGroup } from "../src/index.js"; +import { + createAutofocus, + createFocusTrap, + createFocusGroup, + makePressKeepsFocus, + createPressKeepsFocus, + makeRovingScope, + createRovingScope, +} from "../src/index.js"; describe("API doesn't break in SSR", () => { it("createAutofocus() - SSR", () => { @@ -24,3 +32,33 @@ describe("API doesn't break in SSR", () => { }); }); }); + +describe("press keeps focus & roving scope - SSR", () => { + it("makePressKeepsFocus / createPressKeepsFocus are no-ops", () => { + createRoot(dispose => { + expect(makePressKeepsFocus(null as any)()).toBeUndefined(); + const ref = createPressKeepsFocus(); + expect(() => ref(null as any)).not.toThrow(); + dispose(); + }); + }); + + it("makeRovingScope returns an inert scope", () => { + const scope = makeRovingScope(null as any, { selector: "button" }); + expect(scope.active()).toBeUndefined(); + expect(scope.items()).toEqual([]); + expect(scope.focusNext()).toBeUndefined(); + expect(scope.setActive(null as any)).toBe(false); + expect(() => (scope.refresh(), scope.dispose())).not.toThrow(); + }); + + it("createRovingScope returns inert scope without touching the DOM", () => { + createRoot(dispose => { + const scope = createRovingScope(() => undefined); + expect(scope.active()).toBeUndefined(); + expect(scope.focusFirst()).toBeUndefined(); + expect(scope.items()).toEqual([]); + dispose(); + }); + }); +}); diff --git a/packages/interaction/README.md b/packages/interaction/README.md index 1b61f39cf..5284bf51a 100644 --- a/packages/interaction/README.md +++ b/packages/interaction/README.md @@ -63,6 +63,8 @@ function makeInteractOutside( A non-reactive, pure-ref primitive. Attaches outside-interaction listeners to `el` immediately and returns a cleanup function. Use this when you already have a stable element reference and don't need reactive re-attachment. +Mouse and pen presses report on `pointerdown`. A touch press is reported on the following `click`, so that a scroll never counts as an outside interaction. The pending touch is dropped when the pointer is cancelled (`pointercancel` / `touchcancel`), moves more than 10px, a key is pressed before the click (a keyboard-generated click), or no matching click arrives within about 700ms of the release. The click must also land on the pressed target or within 10px of the press. + ```ts import { makeInteractOutside } from "@solid-primitives/interaction"; @@ -519,6 +521,92 @@ function Modal(props: { open: boolean; onClose: () => void }) { } ``` +## `makeInertOthers` + +Hides everything outside a modal layer from assistive technology and user interaction by marking it `aria-hidden` and/or `inert`. Where [`ariaHideOutside`](#ariahideoutside) tags every node outside the targets, this one walks from each target up to the root and hides only the sibling subtrees that do not contain a target, and it is built for stacked layers. + +```ts +// Type +type InertStrategy = "aria-hidden" | "inert" | "both"; + +type InertOthersOptions = { + strategy?: InertStrategy; // default "aria-hidden" + ignore?: Element | readonly (Element | null | undefined)[] | null; + root?: Element; // default: the target's document.body +}; + +function makeInertOthers( + targets: HTMLElement | readonly HTMLElement[] | null | undefined, + options?: InertOthersOptions, +): VoidFunction; + +// Example +import { makeInertOthers } from "@solid-primitives/interaction"; + +const restore = makeInertOthers(dialogEl, { strategy: "both", ignore: toastRegionEl }); +// ...when the dialog closes +restore(); +``` + +## `createInertOthers` + +Reactive, owner-aware version of `makeInertOthers`, toggled by a signal. + +```ts +// Type +function createInertOthers( + targets: MaybeAccessor, + enabled?: MaybeAccessor, // default true + options?: Omit & { ignore?: MaybeAccessor<...> }, +): void; + +// Example +import { createSignal } from "solid-js"; +import { createInertOthers } from "@solid-primitives/interaction"; + +const [dialog, setDialog] = createSignal(); +const [open, setOpen] = createSignal(false); + +createInertOthers(dialog, open); + +
; +``` + +The layer is applied after render, so a ref signal works as `targets`. Changing `targets` or `ignore` updates the layer in place (it keeps its stack position); turning `enabled` off restores the DOM, and turning it on again opens a new layer on top. Disposal of the owner restores it too. Only `enabled`, `targets` and `ignore` are reactive: `strategy` and `root` are read once when the layer opens, so to change them disable and re-enable (which opens a new layer on top). + +### Behavior + +- **Root and ignore:** without an explicit `root`, the root follows the first target's document `body` (re-evaluated when reactive targets change). A layer's `ignore` elements also stay exposed to the layers below it. +- **Skipped nodes:** `ignore` elements, live regions (`aria-live` other than `off`, and `role` `alert` / `status` / `log`; only with the default `aria-hidden` strategy, and never a live region that contains a lower layer's target), `script` / `style` / `template` / `noscript` / `link` / `meta`, and nodes that were already `aria-hidden="true"` (or `inert`) before the layer opened. A branch that contains a protected element stays exposed and its other children are hidden. +- **Restore:** a node's previous `aria-hidden` / `inert` value (or absence) is put back when its last holder closes. +- **Stacking:** opening a second layer hides the first one and exposes the second. Stacking order is opening order, like a real modal stack: the layer that opened last is on top. A `createInertOthers` layer keeps its position while it stays open, however its `targets` or `ignore` change, but disabling it and enabling it again is a new open and puts it on top (a layer that was created first but enabled later is above the layers that opened before it, and the layers that were open in between are hidden by it). Each node keeps a shared per-strategy ref count, so the layers can close in any order and a node stays hidden until every layer that hides it is closed. A lower layer's `ignore` elements are still hidden by an upper layer, on purpose. +- **Dynamic content:** nodes appended to a walked parent are hidden, and nodes removed from the document are released. +- **Duplicate copies:** the shared state lives on `globalThis`, so it stays correct if more than one copy of this package ends up installed. +- **Server:** both are no-ops. +- **Notes:** `inert` is not supported in every older browser, use `"both"` for the widest coverage. Attributes set by other code on a node while a layer holds it are overwritten on restore. + +#### Focus and `aria-hidden` + +Browsers (Chrome logs "Blocked aria-hidden on an element because its descendant retained focus") do not apply `aria-hidden` to an ancestor of the focused element: after about 100ms the attribute is in the DOM but the accessibility tree keeps exposing the node, and it is not applied again later. So when a node to hide contains the focused element (open shadow roots included), the `aria-hidden` part of the hold is deferred until focus leaves that node (`focusin` / `focusout` on its document, or removal of the focused element from the node, for browsers that fire no blur on removal), and applied then. Closing the layer before that simply drops the deferred hold; ref counts and restored values stay exact. The `inert` part is never deferred, because `inert` blurs the focused element itself. + +- Prefer `strategy: "both"` or `"inert"` for modals. +- Move focus into the dialog right after opening it. The library never moves focus itself. + +#### Caveats + +- Only element children are hidden. Direct text nodes of a walked ancestor stay exposed. +- Nodes appended to the root after the layer opened (for example a select or popover dropdown portaled to `body` out of a modal) are hidden too, until they get their own layer or are passed in `ignore`. This is a common trap with portaled dropdowns inside a modal. +- If every target is removed from the document while the layer is open, what the layer already holds stays held until the layer is updated (new targets) or closed, instead of releasing the whole page. The one exception is a layer opened above it: holds that cover that upper layer's targets or `ignore` elements are released, and the frozen layer never adds new holds. +- The root is a single document: a target inside an iframe does not hide the parent document. A target moved to another document re-roots the layer there. +- Any value of the `inert` attribute counts as already inert, and such a node is left alone. + +### `ariaHideOutside` or `makeInertOthers`? + +They do not share state. Each one leaves alone a node the other already marked `aria-hidden="true"`, so mixing them will not fight over a node, but they will not stack with each other either. Prefer one per app. + +- Use `makeInertOthers` / `createInertOthers` for modal layers that can stack, need `inert`, an `ignore` list, or previous attribute values restored. +- Use `ariaHideOutside` / `createHideOutside` when you need `alwaysVisibleSelector`, or already rely on its behavior. + ## Changelog See [CHANGELOG.md](./CHANGELOG.md) diff --git a/packages/interaction/package.json b/packages/interaction/package.json index e0b6a6906..61b20b008 100644 --- a/packages/interaction/package.json +++ b/packages/interaction/package.json @@ -17,7 +17,9 @@ "interactOutside", "createInteractOutside", "ariaHideOutside", - "createHideOutside" + "createHideOutside", + "makeInertOthers", + "createInertOthers" ], "category": "Browser APIs", "gzip": 2010 @@ -54,6 +56,8 @@ "outside", "focus", "pointer", + "inert", + "aria-hidden", "solid", "primitives" ], diff --git a/packages/interaction/src/index.ts b/packages/interaction/src/index.ts index 8b006860a..7d14646db 100644 --- a/packages/interaction/src/index.ts +++ b/packages/interaction/src/index.ts @@ -29,6 +29,8 @@ import { noop, } from "@solid-primitives/utils"; +export * from "./inert.ts"; + // ---- ariaHideOutside / createHideOutside ---- /** @@ -435,6 +437,11 @@ export interface CreateInteractOutsideOptions { /** {@link CreateInteractOutsideOptions} without `disabled` — for use with {@link makeInteractOutside} and {@link interactOutside}. */ export type MakeInteractOutsideOptions = Omit; +/** Pixels a touch may drift before it counts as a scroll/drag rather than a tap. */ +const TOUCH_MOVE_THRESHOLD = 10; +/** How long after the touch is released its `click` may still arrive (ms). */ +const TOUCH_CLICK_TIMEOUT = 700; + const POINTER_DOWN_OUTSIDE_EVENT = "interactOutside.pointerDownOutside"; const FOCUS_OUTSIDE_EVENT = "interactOutside.focusOutside"; @@ -479,7 +486,20 @@ export function makeInteractOutside( ): () => void { if (isServer) return noop; - let clickHandler: () => void = noop; + // The touch press whose outside check is waiting for its `click`. `null` when none is pending. + let pending: { + handler: () => void; + pointerId: number; + x: number; + y: number; + target: EventTarget | null; + timer: number | undefined; + } | null = null; + + const dropPending = () => { + if (pending) window.clearTimeout(pending.timer); + pending = null; + }; // el.ownerDocument may be an about:blank document at ref-apply time if the element was // created by a renderer whose `document` global resolved before the real document was ready @@ -551,14 +571,61 @@ export function makeInteractOutside( }; if (e.pointerType === "touch") { - ownerDoc.removeEventListener("click", clickHandler); - clickHandler = handler; - ownerDoc.addEventListener("click", clickHandler, { once: true }); + // Held until the tap's `click` arrives (see `onClick`). Anything that proves no click is coming + // for this press (scroll / cancel / drift / a key press) drops it so it can't fire on a later, + // unrelated click. + dropPending(); + pending = { + handler, + pointerId: e.pointerId, + x: e.clientX, + y: e.clientY, + target: origin?.target ?? null, + timer: undefined, + }; } else { handler(); } }; + const onClick = (e: MouseEvent) => { + const p = pending; + dropPending(); + if (!p) return; + // The click must belong to the stored press: same target, or at (nearly) the same position. + const sameTarget = e.target === p.target; + const nearby = + Math.abs(e.clientX - p.x) <= TOUCH_MOVE_THRESHOLD && + Math.abs(e.clientY - p.y) <= TOUCH_MOVE_THRESHOLD; + if (sameTarget || nearby) p.handler(); + }; + + const onPointerMove = (e: PointerEvent) => { + if ( + pending && + e.pointerId === pending.pointerId && + (Math.abs(e.clientX - pending.x) > TOUCH_MOVE_THRESHOLD || + Math.abs(e.clientY - pending.y) > TOUCH_MOVE_THRESHOLD) + ) + dropPending(); + }; + + const onPointerUp = (e: PointerEvent) => { + if (!pending || e.pointerId !== pending.pointerId) return; + // The click follows the release immediately; if it hasn't arrived shortly, it never will. + window.clearTimeout(pending.timer); + pending.timer = window.setTimeout(dropPending, TOUCH_CLICK_TIMEOUT); + }; + + const onPointerCancel = (e: PointerEvent) => { + if (pending && e.pointerId === pending.pointerId) dropPending(); + }; + + const onTouchCancel = () => dropPending(); + + // A key press between the touch and the next click means that click is keyboard-generated. + const onKeyDown = () => dropPending(); + const onFocusIn = (e: FocusEvent) => { const target = getOutsideTarget(getEventOrigin(e)); if (!target) return; @@ -588,13 +655,25 @@ export function makeInteractOutside( ownerDoc = el.ownerDocument; ownerDoc.addEventListener("pointerdown", onPointerDown, true); ownerDoc.addEventListener("focusin", onFocusIn, true); + ownerDoc.addEventListener("click", onClick); + ownerDoc.addEventListener("pointermove", onPointerMove, true); + ownerDoc.addEventListener("pointerup", onPointerUp, true); + ownerDoc.addEventListener("pointercancel", onPointerCancel, true); + ownerDoc.addEventListener("touchcancel", onTouchCancel, true); + ownerDoc.addEventListener("keydown", onKeyDown, true); }, 0); return () => { window.clearTimeout(pointerDownTimeoutId); - ownerDoc.removeEventListener("click", clickHandler); + dropPending(); ownerDoc.removeEventListener("pointerdown", onPointerDown, true); ownerDoc.removeEventListener("focusin", onFocusIn, true); + ownerDoc.removeEventListener("click", onClick); + ownerDoc.removeEventListener("pointermove", onPointerMove, true); + ownerDoc.removeEventListener("pointerup", onPointerUp, true); + ownerDoc.removeEventListener("pointercancel", onPointerCancel, true); + ownerDoc.removeEventListener("touchcancel", onTouchCancel, true); + ownerDoc.removeEventListener("keydown", onKeyDown, true); }; } diff --git a/packages/interaction/src/inert.ts b/packages/interaction/src/inert.ts new file mode 100644 index 000000000..4a27fc4eb --- /dev/null +++ b/packages/interaction/src/inert.ts @@ -0,0 +1,456 @@ +import { createEffect, onCleanup } from "solid-js"; +import { + type MaybeAccessor, + access, + globalRegistry, + isServer, + noop, +} from "@solid-primitives/utils"; + +/** How outside nodes are hidden. */ +export type InertStrategy = "aria-hidden" | "inert" | "both"; + +/** One element, a list of elements, or nothing. */ +export type InertTargets = HTMLElement | readonly HTMLElement[] | null | undefined; + +export type InertOthersOptions = { + /** + * Which attribute(s) to apply to outside nodes. Read once when the layer opens; to change it + * with `createInertOthers`, disable and re-enable (a new layer on top). + * @default "aria-hidden" + */ + strategy?: InertStrategy; + /** + * Elements (and their subtrees) that must stay exposed in addition to the targets, + * for example a toast region rendered outside the modal. + */ + ignore?: Element | readonly (Element | null | undefined)[] | null; + /** + * Element whose subtree is walked. Everything outside the targets but inside this root is hidden. + * Read once when the layer opens. When omitted it follows the first target's document. + * @default the `body` of the first target's document + */ + root?: Element; +}; + +export type CreateInertOthersOptions = Omit & { + /** Reactive version of `ignore`. */ + ignore?: MaybeAccessor; +}; + +const LIVE_SELECTOR = + '[aria-live]:not([aria-live="off"]),[role="alert"],[role="status"],[role="log"]'; +const SKIPPED_TAGS = new Set(["SCRIPT", "STYLE", "TEMPLATE", "NOSCRIPT", "LINK", "META"]); + +type NodeState = { + ariaCount: number; + ariaPrev: string | null; + inertCount: number; + inertPrev: string | null; +}; +type Hold = { + aria: boolean; + inert: boolean; + /** aria-hidden is wanted but postponed because the node contains the focused element. */ + pendingAria: boolean; +}; +type Layer = { + targets: HTMLElement[]; + /** Elements the layer keeps exposed besides its targets; lower layers must not hide them either. */ + ignore: Element[]; + sweep: (force?: boolean) => void; +}; + +type InertRegistry = { + /** Shared per-node ref counts: the reason stacked layers can close in any order. */ + states: WeakMap; + /** Open layers in the order they opened, lowest first. Upper layers' targets are protected from lower layers. */ + layers: Layer[]; +}; + +// Lives on `globalThis` (not in module-scope bindings) so it stays correct when the app's dependency +// graph ends up with more than one copy of this package: module-scope state would be split across the +// copies, and one copy's cleanup could then restore attributes another copy still needs. +const getRegistry = (): InertRegistry => + globalRegistry("@solid-primitives/interaction:inert", () => ({ + states: new WeakMap(), + layers: [], + })); + +function toList( + value: T | readonly (T | null | undefined)[] | null | undefined, +): T[] { + if (value == null) return []; + const list = Array.isArray(value) ? (value as readonly (T | null | undefined)[]) : [value as T]; + return list.filter((el): el is T => el != null); +} + +/** True when `el` contains the focused element, looking through open shadow roots. */ +function containsFocus(el: Element): boolean { + let active: Element | null = el.ownerDocument.activeElement; + while (active) { + if (el.contains(active)) return true; + active = active.shadowRoot?.activeElement ?? null; + } + return false; +} + +function getState(el: Element): NodeState { + const { states } = getRegistry(); + let state = states.get(el); + if (!state) { + state = { ariaCount: 0, ariaPrev: null, inertCount: 0, inertPrev: null }; + states.set(el, state); + } + return state; +} + +/** + * Takes the aria-hidden part of a hold. Chrome refuses `aria-hidden` on an ancestor of the focused + * element (the attribute is set but the accessibility tree keeps exposing the node), so in that case + * the hold stays `pendingAria` and is retried once focus has left the node. + */ +function acquireAria(el: Element, hold: Hold): void { + const state = getState(el); + hold.pendingAria = false; + if (state.ariaCount > 0) { + state.ariaCount++; + hold.aria = true; + } else if (el.getAttribute("aria-hidden") !== "true") { + // an element that was already aria-hidden by someone else is left alone + if (containsFocus(el)) { + hold.pendingAria = true; + return; + } + state.ariaPrev = el.getAttribute("aria-hidden"); + el.setAttribute("aria-hidden", "true"); + state.ariaCount = 1; + hold.aria = true; + } +} + +function acquire(el: Element, strategy: InertStrategy): Hold | undefined { + const hold: Hold = { aria: false, inert: false, pendingAria: false }; + if (strategy !== "aria-hidden") { + const state = getState(el); + if (state.inertCount > 0) { + state.inertCount++; + hold.inert = true; + } else if (!el.hasAttribute("inert")) { + state.inertPrev = el.getAttribute("inert"); + el.setAttribute("inert", ""); + state.inertCount = 1; + hold.inert = true; + } + } + if (strategy !== "inert") acquireAria(el, hold); + return hold.aria || hold.inert || hold.pendingAria ? hold : undefined; +} + +function release(el: Element, hold: Hold): void { + const { states } = getRegistry(); + const state = states.get(el); + if (!state) { + hold.pendingAria = false; + return; + } + if (hold.aria && state.ariaCount > 0 && --state.ariaCount === 0) { + if (state.ariaPrev === null) el.removeAttribute("aria-hidden"); + else el.setAttribute("aria-hidden", state.ariaPrev); + state.ariaPrev = null; + } + if (hold.inert && state.inertCount > 0 && --state.inertCount === 0) { + if (state.inertPrev === null) el.removeAttribute("inert"); + else el.setAttribute("inert", state.inertPrev); + state.inertPrev = null; + } + hold.pendingAria = false; + if (state.ariaCount === 0 && state.inertCount === 0) states.delete(el); +} + +/** + * Marks every subtree outside of the target element(s) as `aria-hidden="true"` and/or `inert`, so that + * assistive technology and user interaction are confined to a modal layer. + * + * - Walks from each target up to the root and hides every sibling subtree that does not contain a target. + * - Skips `options.ignore` elements, live regions, and nodes that were already `aria-hidden="true"` / `inert`. + * - Restores each node's previous attribute value on cleanup. + * - Layers are ref-counted per node: closing an upper layer never unhides nodes a lower layer still hides, in any close order. + * - Nodes added later are hidden too (`MutationObserver`, disconnected on cleanup). + * + * @param targets the element(s) that stay accessible + * @param options see {@link InertOthersOptions} + * @returns a cleanup function that restores the DOM. Safe to call more than once. + * + * @example + * ```ts + * const cleanup = makeInertOthers(dialogEl); + * // later + * cleanup(); + * ``` + */ +export function makeInertOthers( + targets: InertTargets, + options: InertOthersOptions = {}, +): VoidFunction { + if (isServer) return noop; + const own = toList(targets); + if (own.length === 0) return noop; + return openLayer(own, toList(options.ignore), options).close; +} + +type LayerHandle = { + /** Replace the targets / ignore list in place (the layer keeps its stack position) and re-sweep. */ + update: (targets: HTMLElement[], ignore: Element[]) => void; + close: VoidFunction; +}; + +function openLayer( + initialTargets: HTMLElement[], + initialIgnore: Element[], + options: { strategy?: InertStrategy; root?: Element }, +): LayerHandle { + const { layers } = getRegistry(); + let own = initialTargets; + let ignore = initialIgnore; + + const strategy = options.strategy ?? "aria-hidden"; + const explicitRoot = options.root; + // without an explicit root it follows the first target (which may move to another document) + let root = explicitRoot ?? own[0]!.ownerDocument.body; + const held = new Map(); + let disposed = false; + + const observer = new MutationObserver(records => { + if (disposed) return; + for (const record of records) + record.removedNodes.forEach(node => { + const hold = held.get(node as Element); + if (hold && !(node as Element).isConnected) { + release(node as Element, hold); + held.delete(node as Element); + } + }); + layer.sweep(); + }); + + // Watches the hidden branches for two things. childList only, so our own attribute writes never + // retrigger it: + // - live regions added later (aria-hidden strategy only): only a live-region node causes a re-sweep; + // - removals inside a branch whose aria-hidden is deferred because it contains focus: Firefox and Safari + // dispatch no blur/focusout when the focused element leaves the DOM, so retry the pending holds here. + const deepObserver = new MutationObserver(records => { + if (disposed) return; + if ( + strategy === "aria-hidden" && + records.some(record => + Array.from(record.addedNodes).some( + node => + node.nodeType === 1 && + ((node as Element).matches(LIVE_SELECTOR) || + (node as Element).querySelector(LIVE_SELECTOR) !== null), + ), + ) + ) { + layer.sweep(); + return; + } + if ( + records.some(record => record.removedNodes.length > 0) && + Array.from(held.values()).some(h => h.pendingAria) + ) + retryPending(); + }); + + // Hold on to aria-hidden for nodes that contain focus until focus leaves them (see acquireAria). + let focusDoc: Document | undefined; + let focusTimer: ReturnType | undefined; + const retryPending = () => { + if (disposed) return; + let changed = false; + for (const [el, hold] of held) + if (hold.pendingAria && !containsFocus(el)) { + acquireAria(el, hold); + changed = true; + } + if (changed) syncFocusListeners(); + }; + const onFocusIn = () => retryPending(); + // during focusout the next focus target is not known yet, so look again afterwards + const onFocusOut = () => { + clearTimeout(focusTimer); + focusTimer = setTimeout(retryPending, 0); + }; + const syncFocusListeners = () => { + const needed = Array.from(held.values()).some(h => h.pendingAria); + const doc = root.ownerDocument; + if (focusDoc && (!needed || focusDoc !== doc)) { + focusDoc.removeEventListener("focusin", onFocusIn, true); + focusDoc.removeEventListener("focusout", onFocusOut, true); + clearTimeout(focusTimer); + focusDoc = undefined; + } + if (needed && !focusDoc) { + focusDoc = doc; + doc.addEventListener("focusin", onFocusIn, true); + doc.addEventListener("focusout", onFocusOut, true); + } + }; + + const layer: Layer = { + get targets() { + return own; + }, + get ignore() { + return ignore; + }, + sweep(force) { + if (disposed) return; + // Every target was removed from the document while the layer is open: freeze what is held until the + // layer is updated or closed (a modal unmounting a moment before its owner cleans up must not flash + // the page to assistive technology) instead of releasing the whole page. A frozen layer adds no holds + // and only lets go of holds that cover something an upper layer needs exposed. + const frozen = !force && held.size > 0 && own.every(t => !t.isConnected); + // protected = own targets + ignore + live regions + targets of layers opened above this one + const protectedEls: Element[] = [...own, ...ignore]; + // Live regions stay exposed only for aria-hidden (announcements still reach AT). With `inert` they + // would stay interactive behind the modal, so they are hidden like everything else. A live region + // that contains a lower layer's targets is never protected, so lower layers are always hidden. + const index = layers.indexOf(layer); + if (strategy === "aria-hidden" && !frozen) { + const lower = layers.slice(0, index).flatMap(l => l.targets); + for (const live of root.querySelectorAll(LIVE_SELECTOR)) + if (!lower.some(t => live.contains(t))) protectedEls.push(live); + } + for (let i = index + 1; i < layers.length; i++) + protectedEls.push(...layers[i]!.targets, ...layers[i]!.ignore); + const inRoot = protectedEls.filter(el => root.contains(el)); + + if (frozen) { + for (const [el, hold] of held) + if (inRoot.some(p => el.contains(p) || p.contains(el))) { + release(el, hold); + held.delete(el); + } + syncFocusListeners(); + return; + } + + const parents = new Set(); + const desired = new Set(); + // every protected element (targets included) needs its ancestors walked, up to and including `root`. + // An element that is `root` itself has nothing above it to walk. + for (const el of inRoot) { + if (el === root) continue; + for (let p = el.parentElement; p; p = p.parentElement) { + parents.add(p); + if (p === root) break; + } + } + for (const parent of parents) + for (const child of Array.from(parent.children)) { + if (SKIPPED_TAGS.has(child.tagName)) continue; + // skip anything that contains a protected element or lives inside one + if (inRoot.some(p => child.contains(p) || p.contains(child))) continue; + desired.add(child); + } + + for (const [el, hold] of held) + if (!desired.has(el)) { + release(el, hold); + held.delete(el); + } + for (const el of desired) + if (!held.has(el)) { + const hold = acquire(el, strategy); + if (hold) held.set(el, hold); + } + + // childList changes on the walked parents catch late additions; re-observe because the chain can change + observer.disconnect(); + for (const parent of parents) observer.observe(parent, { childList: true }); + deepObserver.disconnect(); + // aria-hidden: every held branch (live regions); otherwise only branches with a deferred aria-hidden + for (const [el, hold] of held) + if (strategy === "aria-hidden" || hold.pendingAria) + deepObserver.observe(el, { childList: true, subtree: true }); + syncFocusListeners(); + }, + }; + + // the stack is the order in which layers open; update() keeps the position, a re-open goes on top + layers.push(layer); + for (const l of [...layers]) l.sweep(); + + return { + update(nextTargets, nextIgnore) { + if (disposed) return; + own = nextTargets; + ignore = nextIgnore; + if (!explicitRoot) root = own[0]!.ownerDocument.body; + for (const l of [...layers]) l.sweep(l === layer); + }, + close() { + if (disposed) return; + observer.disconnect(); + deepObserver.disconnect(); + for (const [el, hold] of held) release(el, hold); + held.clear(); + disposed = true; + syncFocusListeners(); + const index = layers.indexOf(layer); + if (index !== -1) layers.splice(index, 1); + // layers below can now hide whatever this layer used to protect + for (const l of [...layers]) l.sweep(); + }, + }; +} + +/** + * Reactive {@link makeInertOthers}: hides everything outside the target(s) while `enabled` is true, + * and restores it when disabled or when the owner is disposed. `enabled`, `targets` and `ignore` are + * tracked (changing targets or ignore updates the layer in place); `strategy` and `root` are read when + * the layer opens, so changing them requires disabling and re-enabling (a new layer on top). + * + * @param targets element(s), or an accessor of them (for example a ref signal); `undefined`/`null` disables it + * @param enabled toggle, defaults to `true` + * @param options see {@link CreateInertOthersOptions}; `ignore` may be an accessor + * + * @example + * ```tsx + * const [dialog, setDialog] = createSignal(); + * createInertOthers(dialog, isOpen); + *
+ * ``` + */ +export function createInertOthers( + targets: MaybeAccessor, + enabled: MaybeAccessor = true, + options: CreateInertOthersOptions = {}, +): void { + if (isServer) return; + // The layer is updated in place while it stays open, so it keeps its stack position when its inputs + // change. Disabling and enabling again is a new open and goes on top, like a real modal stack. + let handle: LayerHandle | undefined; + createEffect( + () => { + if (!access(enabled)) return undefined; + const list = toList( + access(targets) as HTMLElement | readonly HTMLElement[] | null | undefined, + ); + if (list.length === 0) return undefined; + return { list, ignore: toList(access(options.ignore)) }; + }, + state => { + if (!state) { + handle?.close(); + handle = undefined; + } else if (handle) handle.update(state.list, state.ignore); + else handle = openLayer(state.list, state.ignore, options); + }, + ); + onCleanup(() => { + handle?.close(); + handle = undefined; + }); +} diff --git a/packages/interaction/stories/interaction.stories.tsx b/packages/interaction/stories/interaction.stories.tsx index d94f94afb..7ea2985b8 100644 --- a/packages/interaction/stories/interaction.stories.tsx +++ b/packages/interaction/stories/interaction.stories.tsx @@ -1,6 +1,7 @@ import { createSignal, Show } from "solid-js"; import preview from "../../../.storybook/preview.js"; import { + createInertOthers, createInteractOutside, interactOutside, makeInteractOutside, @@ -307,3 +308,25 @@ export const MakeInteractOutsideStory = meta.story({ ); }, }); + +export const InertOthersStory = meta.story({ + name: "createInertOthers", + render: () => { + const [dialog, setDialog] = createSignal(); + const [open, setOpen] = createSignal(false); + createInertOthers(dialog, open, { strategy: "both" }); + return ( +
+
+ +

Outside content: inert and aria-hidden while the layer is open.

+ +
+
+

Layer content stays interactive.

+ +
+
+ ); + }, +}); diff --git a/packages/interaction/test/inert.test.ts b/packages/interaction/test/inert.test.ts new file mode 100644 index 000000000..91f1afc08 --- /dev/null +++ b/packages/interaction/test/inert.test.ts @@ -0,0 +1,1105 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { createRoot, createSignal, flush } from "solid-js"; +import { createInertOthers, makeInertOthers } from "../src/index.js"; + +const el = (tag = "div", attrs: Record = {}, parent: Element = document.body) => { + const node = document.createElement(tag); + for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, v); + parent.appendChild(node); + return node; +}; +const tick = () => new Promise(r => setTimeout(r, 0)); + +let app: HTMLElement, dialog: HTMLElement; +beforeEach(() => { + document.body.innerHTML = ""; + app = el("div", { id: "app" }); + dialog = el("div", { id: "dialog" }); +}); +afterEach(() => { + document.body.innerHTML = ""; +}); + +describe("makeInertOthers", () => { + test("hides siblings of the target and every ancestor, not the target path", () => { + const wrapper = el("section"); + const inner = el("div", {}, wrapper); + const sibling = el("p", {}, wrapper); + const target = el("div", {}, inner); + const targetChild = el("span", {}, target); + const cleanup = makeInertOthers(target); + expect(app.getAttribute("aria-hidden")).toBe("true"); + expect(dialog.getAttribute("aria-hidden")).toBe("true"); + expect(sibling.getAttribute("aria-hidden")).toBe("true"); + for (const node of [wrapper, inner, target, targetChild, document.body]) + expect(node.hasAttribute("aria-hidden")).toBe(false); + expect(app.hasAttribute("inert")).toBe(false); + cleanup(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + expect(sibling.hasAttribute("aria-hidden")).toBe(false); + }); + + test("accepts several targets", () => { + const other = el("div"); + const cleanup = makeInertOthers([app, dialog]); + expect(other.getAttribute("aria-hidden")).toBe("true"); + expect(app.hasAttribute("aria-hidden")).toBe(false); + expect(dialog.hasAttribute("aria-hidden")).toBe(false); + cleanup(); + }); + + test("strategies", () => { + let c = makeInertOthers(dialog, { strategy: "inert" }); + expect(app.hasAttribute("inert")).toBe(true); + expect(app.hasAttribute("aria-hidden")).toBe(false); + c(); + expect(app.hasAttribute("inert")).toBe(false); + + c = makeInertOthers(dialog, { strategy: "both" }); + expect(app.hasAttribute("inert")).toBe(true); + expect(app.getAttribute("aria-hidden")).toBe("true"); + c(); + expect(app.hasAttribute("inert")).toBe(false); + expect(app.hasAttribute("aria-hidden")).toBe(false); + }); + + test("restores pre-existing attribute values", () => { + app.setAttribute("aria-hidden", "false"); + app.setAttribute("data-x", "1"); + const c = makeInertOthers(dialog, { strategy: "both" }); + expect(app.getAttribute("aria-hidden")).toBe("true"); + c(); + expect(app.getAttribute("aria-hidden")).toBe("false"); + expect(app.hasAttribute("inert")).toBe(false); + expect(app.getAttribute("data-x")).toBe("1"); + }); + + test("leaves already hidden/inert nodes untouched, including on cleanup", () => { + const hidden = el("div", { "aria-hidden": "true" }); + const inertEl = el("div", { inert: "" }); + const c = makeInertOthers(dialog, { strategy: "both" }); + expect(hidden.getAttribute("aria-hidden")).toBe("true"); + expect(hidden.hasAttribute("inert")).toBe(true); // still gets the other strategy + expect(inertEl.hasAttribute("inert")).toBe(true); + expect(inertEl.getAttribute("aria-hidden")).toBe("true"); + c(); + expect(hidden.getAttribute("aria-hidden")).toBe("true"); + expect(hidden.hasAttribute("inert")).toBe(false); + expect(inertEl.hasAttribute("inert")).toBe(true); + expect(inertEl.hasAttribute("aria-hidden")).toBe(false); + }); + + test("ignore list", () => { + const toast = el("div"); + const other = el("div"); + const c = makeInertOthers(dialog, { ignore: [toast, null] }); + expect(toast.hasAttribute("aria-hidden")).toBe(false); + expect(other.getAttribute("aria-hidden")).toBe("true"); + c(); + const c2 = makeInertOthers(dialog, { ignore: toast }); + expect(toast.hasAttribute("aria-hidden")).toBe(false); + c2(); + }); + + test("ignored element nested deep keeps its path exposed", () => { + const branch = el("div"); + const siblingInBranch = el("div", {}, branch); + const toast = el("div", {}, branch); + const c = makeInertOthers(dialog, { ignore: toast }); + expect(branch.hasAttribute("aria-hidden")).toBe(false); + expect(siblingInBranch.getAttribute("aria-hidden")).toBe("true"); + expect(toast.hasAttribute("aria-hidden")).toBe(false); + c(); + }); + + test("skips live regions", () => { + const polite = el("div", { "aria-live": "polite" }); + const off = el("div", { "aria-live": "off" }); + const status = el("div", { role: "status" }); + const c = makeInertOthers(dialog); + expect(polite.hasAttribute("aria-hidden")).toBe(false); + expect(status.hasAttribute("aria-hidden")).toBe(false); + expect(off.getAttribute("aria-hidden")).toBe("true"); + c(); + }); + + test("live regions are hidden under the inert strategy", () => { + const main = el("main", { "aria-live": "polite" }); + const c = makeInertOthers(dialog, { strategy: "inert" }); + expect(main.hasAttribute("inert")).toBe(true); + c(); + expect(main.hasAttribute("inert")).toBe(false); + }); + + test("an upper layer hides a lower alertdialog layer", () => { + const lower = el("div", { role: "alertdialog" }); + const upper = el("div", { role: "dialog" }); + const c1 = makeInertOthers(lower); + const c2 = makeInertOthers(upper, { strategy: "inert" }); + expect(lower.hasAttribute("inert")).toBe(true); + c2(); + expect(lower.hasAttribute("inert")).toBe(false); + c1(); + }); + + test("a live region containing a lower layer target does not shield it", () => { + const region = el("div", { "aria-live": "polite" }); + const lower = el("div", {}, region); + const upper = el("div"); + const c1 = makeInertOthers(lower); + const c2 = makeInertOthers(upper); + expect(region.getAttribute("aria-hidden")).toBe("true"); + c2(); + expect(region.hasAttribute("aria-hidden")).toBe(false); + c1(); + }); + + test("skips script/style", () => { + const script = el("script"); + const style = el("style"); + const c = makeInertOthers(dialog); + expect(script.hasAttribute("aria-hidden")).toBe(false); + expect(style.hasAttribute("aria-hidden")).toBe(false); + c(); + }); + + test("custom root", () => { + const outside = el("div"); + const root = el("main"); + const a = el("div", {}, root); + const target = el("div", {}, root); + const c = makeInertOthers(target, { root }); + expect(a.getAttribute("aria-hidden")).toBe("true"); + expect(outside.hasAttribute("aria-hidden")).toBe(false); + expect(root.hasAttribute("aria-hidden")).toBe(false); + c(); + }); + + test("targets outside the root are ignored", () => { + const root = el("main"); + const a = el("div", {}, root); + const c = makeInertOthers(dialog, { root }); + expect(a.hasAttribute("aria-hidden")).toBe(false); + c(); + }); + + test("no targets is a no-op", () => { + const c = makeInertOthers(undefined); + makeInertOthers([])(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + c(); + }); + + test("cleanup is idempotent and does not clobber later changes", () => { + const c = makeInertOthers(dialog); + c(); + app.setAttribute("aria-hidden", "true"); + c(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + }); + + describe("stacking", () => { + test("upper layer closes first", () => { + const lower = el("div"); + const upper = el("div"); + const closeLower = makeInertOthers(lower); + expect(upper.getAttribute("aria-hidden")).toBe("true"); // sibling of lower + const closeUpper = makeInertOthers(upper); + // opening the upper layer exposes it again, and hides the lower layer + expect(upper.hasAttribute("aria-hidden")).toBe(false); + expect(lower.getAttribute("aria-hidden")).toBe("true"); + expect(app.getAttribute("aria-hidden")).toBe("true"); + + closeUpper(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + expect(lower.hasAttribute("aria-hidden")).toBe(false); + expect(upper.getAttribute("aria-hidden")).toBe("true"); + closeLower(); + for (const n of [app, lower, upper, dialog]) + expect(n.hasAttribute("aria-hidden")).toBe(false); + }); + + test("lower layer closes first", () => { + const lower = el("div"); + const upper = el("div"); + const closeLower = makeInertOthers(lower); + const closeUpper = makeInertOthers(upper); + closeLower(); + // still hidden by the upper layer + expect(app.getAttribute("aria-hidden")).toBe("true"); + expect(lower.getAttribute("aria-hidden")).toBe("true"); + expect(upper.hasAttribute("aria-hidden")).toBe(false); + closeUpper(); + for (const n of [app, lower, upper, dialog]) + expect(n.hasAttribute("aria-hidden")).toBe(false); + }); + + test("nodes added while stacked are covered by both and restored once", () => { + const lower = el("div"); + const upper = el("div"); + const closeLower = makeInertOthers(lower); + const closeUpper = makeInertOthers(upper); + return tick().then(async () => { + const late = el("div"); + await tick(); + expect(late.getAttribute("aria-hidden")).toBe("true"); + closeUpper(); + expect(late.getAttribute("aria-hidden")).toBe("true"); + closeLower(); + expect(late.hasAttribute("aria-hidden")).toBe(false); + }); + }); + + test("pre-existing value survives stacked layers", () => { + app.setAttribute("aria-hidden", "false"); + const a = makeInertOthers(dialog); + const other = el("div"); + const b = makeInertOthers(other); + a(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + b(); + expect(app.getAttribute("aria-hidden")).toBe("false"); + }); + + test("three layers closed in the middle first", () => { + const l1 = el("div"); + const l2 = el("div"); + const l3 = el("div"); + const c1 = makeInertOthers(l1); + const c2 = makeInertOthers(l2); + const c3 = makeInertOthers(l3); + c2(); + expect(l1.getAttribute("aria-hidden")).toBe("true"); + expect(l2.getAttribute("aria-hidden")).toBe("true"); + expect(l3.hasAttribute("aria-hidden")).toBe(false); + c3(); + expect(l1.hasAttribute("aria-hidden")).toBe(false); + expect(l2.getAttribute("aria-hidden")).toBe("true"); + c1(); + for (const n of [app, dialog, l1, l2, l3]) expect(n.hasAttribute("aria-hidden")).toBe(false); + }); + }); + + describe("protected elements inside a target", () => { + test("children of a target that holds a live region / ignore element are not hidden", () => { + const button = el("button", {}, dialog); + const status = el("div", { role: "status" }, dialog); + const toast = el("div", {}, dialog); + const c = makeInertOthers(dialog, { strategy: "both", ignore: toast }); + for (const n of [button, status, toast, dialog]) { + expect(n.hasAttribute("aria-hidden")).toBe(false); + expect(n.hasAttribute("inert")).toBe(false); + } + expect(app.hasAttribute("inert")).toBe(true); + c(); + const c2 = makeInertOthers(dialog); + expect(button.hasAttribute("aria-hidden")).toBe(false); + c2(); + }); + }); + + describe("root handling", () => { + test("a target equal to root does not hide siblings outside root", () => { + const container = el("div", { id: "container" }); + const inside = el("div", {}, container); + const outside = el("div", { id: "outside" }); + const c = makeInertOthers(container, { root: container }); + for (const n of [container, inside, outside, document.body, app, dialog]) + expect(n.hasAttribute("aria-hidden")).toBe(false); + c(); + }); + + test("an ignored element equal to root does not walk above root", () => { + const container = el("div", { id: "container" }); + const inside = el("div", {}, container); + const target = el("div", {}, container); + const outside = el("div", { id: "outside" }); + const c = makeInertOthers(target, { root: container, ignore: container }); + expect(outside.hasAttribute("aria-hidden")).toBe(false); + expect(inside.hasAttribute("aria-hidden")).toBe(false); + c(); + }); + }); + + describe("dynamic nodes", () => { + test("hides nodes added later and restores them on cleanup", async () => { + const c = makeInertOthers(dialog); + const late = el("div"); + const nested = el("div", {}, dialog.parentElement!); + await tick(); + expect(late.getAttribute("aria-hidden")).toBe("true"); + expect(nested.getAttribute("aria-hidden")).toBe("true"); + c(); + expect(late.hasAttribute("aria-hidden")).toBe(false); + }); + + test("nodes added inside the target path (ancestor of target) are hidden", async () => { + const wrapper = el("section"); + const target = el("div", {}, wrapper); + const c = makeInertOthers(target); + const late = el("div", {}, wrapper); + await tick(); + expect(late.getAttribute("aria-hidden")).toBe("true"); + c(); + }); + + test("live regions added later stay exposed", async () => { + const c = makeInertOthers(dialog); + const live = el("div", { "aria-live": "assertive" }); + await tick(); + expect(live.hasAttribute("aria-hidden")).toBe(false); + c(); + }); + + test("live regions added later inside an already hidden branch are re-evaluated", async () => { + const wrapper = el("div", {}, app); + const sibling = el("p", {}, wrapper); + const c = makeInertOthers(dialog); + expect(app.getAttribute("aria-hidden")).toBe("true"); + const live = el("div", { role: "status" }, wrapper); + await tick(); + expect(live.hasAttribute("aria-hidden")).toBe(false); + expect(wrapper.hasAttribute("aria-hidden")).toBe(false); + expect(app.hasAttribute("aria-hidden")).toBe(false); + expect(sibling.getAttribute("aria-hidden")).toBe("true"); + // a subtree that contains a live region counts too + const host = el("section", {}, sibling); + const nested = document.createElement("div"); + nested.setAttribute("aria-live", "polite"); + const deep = el("div"); + deep.appendChild(nested); + host.appendChild(deep); + await tick(); + expect(nested.hasAttribute("aria-hidden")).toBe(false); + expect(deep.hasAttribute("aria-hidden")).toBe(false); + // plain nodes do not make anything visible, and cleanup restores everything + c(); + for (const n of [app, wrapper, sibling, host, deep]) + expect(n.hasAttribute("aria-hidden")).toBe(false); + const after = el("div", { role: "alert" }, app); + await tick(); + expect(after.hasAttribute("aria-hidden")).toBe(false); + }); + + test("removed nodes are released", async () => { + const c = makeInertOthers(dialog); + app.remove(); + await tick(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + c(); + }); + + test("moving a hidden node under a new hidden wrapper keeps it out of reach", async () => { + const c = makeInertOthers(dialog); + const holder = el("div"); + await tick(); + holder.appendChild(app); + await tick(); + expect(holder.getAttribute("aria-hidden")).toBe("true"); + expect(app.hasAttribute("aria-hidden")).toBe(false); // covered by its hidden ancestor + c(); + }); + + test("observer is disconnected on cleanup", async () => { + const c = makeInertOthers(dialog); + c(); + const late = el("div"); + await tick(); + expect(late.hasAttribute("aria-hidden")).toBe(false); + }); + + test("stops observing so later nodes are never touched after cleanup of stacked layers", async () => { + const a = makeInertOthers(dialog); + const other = el("div"); + const b = makeInertOthers(other); + a(); + b(); + const late = el("div"); + await tick(); + expect(late.hasAttribute("aria-hidden")).toBe(false); + }); + }); +}); + +describe("createInertOthers", () => { + test("reacts to enabled", () => { + const [enabled, setEnabled] = createSignal(false); + const dispose = createRoot(d => { + createInertOthers(dialog, enabled); + return d; + }); + flush(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + setEnabled(true); + flush(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + setEnabled(false); + flush(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + dispose(); + }); + + test("defaults to enabled and cleans up on dispose", () => { + const dispose = createRoot(d => { + createInertOthers(dialog); + return d; + }); + flush(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + dispose(); + flush(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + }); + + test("reacts to targets (accessor, appearing later, switching)", () => { + const other = el("div"); + const [target, setTarget] = createSignal(undefined); + const dispose = createRoot(d => { + createInertOthers(target); + return d; + }); + flush(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + setTarget(dialog); + flush(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + expect(dialog.hasAttribute("aria-hidden")).toBe(false); + setTarget(other); + flush(); + expect(dialog.getAttribute("aria-hidden")).toBe("true"); + expect(other.hasAttribute("aria-hidden")).toBe(false); + setTarget(undefined); + flush(); + expect(dialog.hasAttribute("aria-hidden")).toBe(false); + expect(app.hasAttribute("aria-hidden")).toBe(false); + dispose(); + }); + + test("accepts an array of targets and a reactive ignore + strategy", () => { + const toast = el("div"); + const [ignored, setIgnored] = createSignal(undefined); + const dispose = createRoot(d => { + createInertOthers([dialog], true, { strategy: "inert", ignore: ignored }); + return d; + }); + flush(); + expect(toast.hasAttribute("inert")).toBe(true); + expect(app.hasAttribute("aria-hidden")).toBe(false); + setIgnored(toast); + flush(); + expect(toast.hasAttribute("inert")).toBe(false); + expect(app.hasAttribute("inert")).toBe(true); + dispose(); + flush(); + expect(app.hasAttribute("inert")).toBe(false); + }); + + test("stacked reactive layers close in either order", () => { + const upperEl = el("div"); + const [lowerOn, setLowerOn] = createSignal(true); + const [upperOn, setUpperOn] = createSignal(true); + const dispose = createRoot(d => { + createInertOthers(dialog, lowerOn); + createInertOthers(upperEl, upperOn); + return d; + }); + flush(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + expect(dialog.getAttribute("aria-hidden")).toBe("true"); + setLowerOn(false); + flush(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + expect(dialog.getAttribute("aria-hidden")).toBe("true"); + setUpperOn(false); + flush(); + for (const n of [app, dialog, upperEl]) expect(n.hasAttribute("aria-hidden")).toBe(false); + dispose(); + }); + + test("a lower layer keeps its stack position across reactive input changes", () => { + const upperEl = el("div", { id: "upper" }); + const upperChild = el("button", {}, upperEl); + const lowerAlt = el("div", { id: "lower-alt" }); + const toast = el("div", { id: "toast" }); + const [lowerTarget, setLowerTarget] = createSignal(dialog); + const [lowerIgnore, setLowerIgnore] = createSignal(undefined); + const [lowerOn, setLowerOn] = createSignal(true); + const dispose = createRoot(d => { + createInertOthers(lowerTarget, lowerOn, { ignore: lowerIgnore }); + createInertOthers(upperEl); + return d; + }); + const upperExposed = () => { + for (const n of [upperEl, upperChild, document.body]) + expect(n.hasAttribute("aria-hidden")).toBe(false); + }; + flush(); + upperExposed(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + expect(dialog.getAttribute("aria-hidden")).toBe("true"); + + setLowerIgnore(toast); + flush(); + upperExposed(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + + setLowerTarget(lowerAlt); + flush(); + upperExposed(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + expect(lowerAlt.getAttribute("aria-hidden")).toBe("true"); + + setLowerOn(false); + flush(); + upperExposed(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + // Stacking order is opening order, like a real modal stack: disabling and enabling again is a NEW + // open, so the re-enabled layer goes on top and now hides the layer that opened in between. + setLowerOn(true); + flush(); + expect(upperEl.getAttribute("aria-hidden")).toBe("true"); + expect(lowerAlt.hasAttribute("aria-hidden")).toBe(false); + // and it keeps that position across further input changes + setLowerIgnore(undefined); + flush(); + expect(upperEl.getAttribute("aria-hidden")).toBe("true"); + expect(lowerAlt.hasAttribute("aria-hidden")).toBe(false); + dispose(); + flush(); + for (const n of [app, dialog, lowerAlt, upperEl, upperChild, toast]) + expect(n.hasAttribute("aria-hidden")).toBe(false); + }); + + test("the stack order is the order layers open, not the order they were created", () => { + // hi is created first but disabled; low opens; then hi opens on top of low + const hiEl = el("div", { id: "hi" }); + const hiChild = el("button", {}, hiEl); + const lowEl = el("div", { id: "low" }); + const [hiOn, setHiOn] = createSignal(false); + const run = (close: "hi-first" | "low-first") => { + let disposeHi!: VoidFunction; + createRoot(d => { + disposeHi = d; + createInertOthers(hiEl, hiOn); + }); + flush(); + const closeLow = makeInertOthers(lowEl); + expect(hiEl.getAttribute("aria-hidden")).toBe("true"); + setHiOn(true); + flush(); + for (const n of [hiEl, hiChild, document.body]) + expect(n.hasAttribute("aria-hidden")).toBe(false); + expect(lowEl.getAttribute("aria-hidden")).toBe("true"); + expect(app.getAttribute("aria-hidden")).toBe("true"); + if (close === "hi-first") { + setHiOn(false); + flush(); + expect(hiEl.getAttribute("aria-hidden")).toBe("true"); + expect(lowEl.hasAttribute("aria-hidden")).toBe(false); + closeLow(); + } else { + closeLow(); + expect(hiEl.hasAttribute("aria-hidden")).toBe(false); + expect(lowEl.getAttribute("aria-hidden")).toBe("true"); + disposeHi(); + flush(); + } + disposeHi(); + flush(); + for (const n of [app, dialog, hiEl, hiChild, lowEl]) + expect(n.hasAttribute("aria-hidden")).toBe(false); + setHiOn(false); + flush(); + }; + run("hi-first"); + run("low-first"); + }); + + test("layers closed in either order restore the original attributes after input changes", () => { + const upperEl = el("div"); + const [lowerIgnore, setLowerIgnore] = createSignal(undefined); + let disposeLower!: VoidFunction; + let disposeUpper!: VoidFunction; + createRoot(d => { + disposeLower = d; + createInertOthers(dialog, true, { ignore: lowerIgnore }); + }); + createRoot(d => { + disposeUpper = d; + createInertOthers(upperEl); + }); + flush(); + setLowerIgnore(el("div")); + flush(); + expect(upperEl.hasAttribute("aria-hidden")).toBe(false); + expect(app.getAttribute("aria-hidden")).toBe("true"); + disposeLower(); + flush(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + expect(dialog.getAttribute("aria-hidden")).toBe("true"); + disposeUpper(); + flush(); + for (const n of [app, dialog, upperEl]) expect(n.hasAttribute("aria-hidden")).toBe(false); + }); +}); + +describe("focus inside a branch that is about to be hidden", () => { + // Chrome ignores aria-hidden on an ancestor of the focused element (the attribute is set but the + // accessibility tree keeps exposing it, and it is never re-applied), so the attribute is deferred. + let bgButton: HTMLButtonElement, dialogButton: HTMLButtonElement; + beforeEach(() => { + bgButton = el("button", {}, app) as HTMLButtonElement; + dialogButton = el("button", {}, dialog) as HTMLButtonElement; + }); + + test("aria-hidden waits until focus leaves the branch, then applies", async () => { + bgButton.focus(); + const cleanup = makeInertOthers(dialog); + expect(app.hasAttribute("aria-hidden")).toBe(false); + dialogButton.focus(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + cleanup(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + }); + + test("focus leaving to nothing (blur) also applies it", async () => { + bgButton.focus(); + const cleanup = makeInertOthers(dialog); + bgButton.blur(); + await tick(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + cleanup(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + }); + + test("moving focus within the branch keeps it deferred", async () => { + const second = el("button", {}, app); + bgButton.focus(); + const cleanup = makeInertOthers(dialog); + second.focus(); + await tick(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + dialogButton.focus(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + cleanup(); + }); + + test("closing before it was ever applied leaves the node untouched and drops the listeners", () => { + const add = vi.spyOn(document, "addEventListener"); + const remove = vi.spyOn(document, "removeEventListener"); + bgButton.focus(); + const cleanup = makeInertOthers(dialog); + expect(add.mock.calls.filter(c => c[0] === "focusin")).toHaveLength(1); + cleanup(); + expect(remove.mock.calls.filter(c => c[0] === "focusin")).toHaveLength(1); + dialogButton.focus(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + add.mockRestore(); + remove.mockRestore(); + }); + + test("a deferred node restores its previous value exactly, with stacked layers closed in either order", () => { + for (const order of ["upper-first", "lower-first"]) { + app.setAttribute("aria-hidden", "false"); + const upperEl = el("div"); + const upperButton = el("button", {}, upperEl); + bgButton.focus(); + const lower = makeInertOthers(dialog); + const upper = makeInertOthers(upperEl); + expect(app.getAttribute("aria-hidden")).toBe("false"); + upperButton.focus(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + expect(dialog.getAttribute("aria-hidden")).toBe("true"); + if (order === "upper-first") { + upper(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + lower(); + } else { + lower(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + upper(); + } + expect(app.getAttribute("aria-hidden")).toBe("false"); + expect(dialog.hasAttribute("aria-hidden")).toBe(false); + app.removeAttribute("aria-hidden"); + upperEl.remove(); + } + }); + + test("a node already hidden by another layer is counted at once even if focus is inside", () => { + const upperEl = el("div"); + const upperButton = el("button", {}, upperEl); + dialogButton.focus(); + const lower = makeInertOthers(upperEl); // hides app and dialog (dialog contains focus: deferred) + upperButton.focus(); + expect(dialog.getAttribute("aria-hidden")).toBe("true"); + const upper = makeInertOthers(dialog); + // a second layer hides upperEl (focus is inside it: deferred) and app (already held: counted) + expect(app.getAttribute("aria-hidden")).toBe("true"); + dialogButton.focus(); + expect(upperEl.getAttribute("aria-hidden")).toBe("true"); + lower(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + upper(); + for (const n of [app, dialog, upperEl]) expect(n.hasAttribute("aria-hidden")).toBe(false); + }); + + test("the inert attribute is applied immediately even while focus is inside", () => { + bgButton.focus(); + const cleanup = makeInertOthers(dialog, { strategy: "inert" }); + expect(app.hasAttribute("inert")).toBe(true); + expect(app.hasAttribute("aria-hidden")).toBe(false); + cleanup(); + }); + + test("strategy both: inert at once, aria-hidden once focus has left", () => { + bgButton.focus(); + const cleanup = makeInertOthers(dialog, { strategy: "both" }); + expect(app.hasAttribute("inert")).toBe(true); + expect(app.hasAttribute("aria-hidden")).toBe(false); + dialogButton.focus(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + cleanup(); + expect(app.hasAttribute("inert")).toBe(false); + expect(app.hasAttribute("aria-hidden")).toBe(false); + }); + + test("focus inside an open shadow root counts for its host", () => { + const host = el("div", {}, app); + const input = document.createElement("input"); + host.attachShadow({ mode: "open" }).appendChild(input); + input.focus(); + expect(document.activeElement).toBe(host); + const cleanup = makeInertOthers(dialog); + expect(app.hasAttribute("aria-hidden")).toBe(false); + dialogButton.focus(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + cleanup(); + }); + + test("createInertOthers defers the same way", () => { + bgButton.focus(); + const [on, setOn] = createSignal(true); + const dispose = createRoot(d => { + createInertOthers(dialog, on); + return d; + }); + flush(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + dialogButton.focus(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + setOn(false); + flush(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + dispose(); + }); +}); + +describe("all targets removed while the layer is open", () => { + test("held nodes stay held until the layer is updated or closed", async () => { + const [target, setTarget] = createSignal(dialog); + const dispose = createRoot(d => { + createInertOthers(target); + return d; + }); + flush(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + dialog.remove(); + await tick(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + const next = el("div"); + setTarget(next); + flush(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + expect(next.hasAttribute("aria-hidden")).toBe(false); + next.remove(); + await tick(); + dispose(); + flush(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + }); + + test("makeInertOthers: cleanup restores after the target was removed", async () => { + const cleanup = makeInertOthers(dialog); + dialog.remove(); + await tick(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + cleanup(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + }); +}); + +describe("duplicate copies of the package", () => { + test("share per-node state, so one copy's cleanup never reveals what another still hides", async () => { + const wrapper = el("section"); + wrapper.appendChild(dialog); + const other = el("div", { id: "other" }); + const extra = el("div", { id: "extra" }); + + // a second, independent evaluation of the module, as with two installed copies + vi.resetModules(); + const copy = await import("../src/inert.ts?copy"); + expect(copy.makeInertOthers).not.toBe(makeInertOthers); + + const cleanupA = makeInertOthers(dialog); + const cleanupB = copy.makeInertOthers(extra); + // `extra` is the only target of B, so A's target `dialog` is hidden by B while A hides `extra` + expect(app.getAttribute("aria-hidden")).toBe("true"); + expect(other.getAttribute("aria-hidden")).toBe("true"); + + cleanupA(); + // B still hides everything that is not `extra`, even though A (another copy) just closed + expect(app.getAttribute("aria-hidden")).toBe("true"); + expect(other.getAttribute("aria-hidden")).toBe("true"); + expect(extra.hasAttribute("aria-hidden")).toBe(false); + + cleanupB(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + expect(other.hasAttribute("aria-hidden")).toBe(false); + }); +}); + +describe("inferred root follows the first target", () => { + test("a reactive target moving into an iframe document re-roots the layer", () => { + const iframe = el("iframe") as HTMLIFrameElement; + const idoc = iframe.contentDocument!; + const iTarget = idoc.createElement("div"); + const iOther = idoc.createElement("div"); + idoc.body.append(iTarget, iOther); + const [target, setTarget] = createSignal(dialog); + const dispose = createRoot(d => { + createInertOthers(target); + return d; + }); + flush(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + expect(iOther.hasAttribute("aria-hidden")).toBe(false); + setTarget(iTarget); + flush(); + expect(iOther.getAttribute("aria-hidden")).toBe("true"); + expect(iTarget.hasAttribute("aria-hidden")).toBe(false); + // the old document's holds are released + expect(app.hasAttribute("aria-hidden")).toBe(false); + dispose(); + flush(); + expect(iOther.hasAttribute("aria-hidden")).toBe(false); + }); + + test("an explicit root is preserved across updates", () => { + const container = el("div"); + const a = el("div", {}, container); + const b = el("div", {}, container); + const outside = el("div"); + const [target, setTarget] = createSignal(a); + const dispose = createRoot(d => { + createInertOthers(target, true, { root: container }); + return d; + }); + flush(); + expect(b.getAttribute("aria-hidden")).toBe("true"); + setTarget(b); + flush(); + expect(a.getAttribute("aria-hidden")).toBe("true"); + expect(outside.hasAttribute("aria-hidden")).toBe(false); + dispose(); + }); +}); + +describe("ignore elements of upper layers", () => { + for (const strategy of ["aria-hidden", "inert", "both"] as const) { + const hidden = (n: Element) => + strategy === "aria-hidden" + ? n.getAttribute("aria-hidden") === "true" + : n.hasAttribute("inert"); + const clean = (n: Element) => !n.hasAttribute("aria-hidden") && !n.hasAttribute("inert"); + + for (const order of ["upper first", "lower first"]) { + test(`makeInertOthers (${strategy}), closing ${order}`, () => { + const lower = el("div"); + const upper = el("div"); + const control = el("div"); + const unrelated = el("div"); + const closeA = makeInertOthers(lower, { strategy }); + expect(hidden(control)).toBe(true); + const closeB = makeInertOthers(upper, { strategy, ignore: control }); + expect(clean(control)).toBe(true); + expect(hidden(unrelated)).toBe(true); + expect(hidden(lower)).toBe(true); + if (order === "upper first") { + closeB(); + closeA(); + } else { + closeA(); + closeB(); + } + for (const n of [app, dialog, lower, upper, control, unrelated]) + expect(clean(n)).toBe(true); + }); + + test(`createInertOthers (${strategy}) with reactive ignore, closing ${order}`, () => { + const lower = el("div"); + const upper = el("div"); + const c1 = el("div"); + const c2 = el("div"); + const [ignore, setIgnore] = createSignal(c1); + const closeA = makeInertOthers(lower, { strategy }); + const disposeB = createRoot(d => { + createInertOthers(upper, true, { strategy, ignore }); + return d; + }); + flush(); + expect(clean(c1)).toBe(true); + expect(hidden(c2)).toBe(true); + setIgnore(c2); + flush(); + expect(clean(c2)).toBe(true); + expect(hidden(c1)).toBe(true); + if (order === "upper first") { + disposeB(); + flush(); + closeA(); + } else { + closeA(); + disposeB(); + flush(); + } + for (const n of [app, dialog, lower, upper, c1, c2]) expect(clean(n)).toBe(true); + }); + } + } +}); + +describe("deferred aria-hidden when the focused element is removed without focus events", () => { + // Firefox and Safari dispatch no blur/focusout when the focused element leaves the DOM, jsdom neither. + let bgButton: HTMLButtonElement, dialogButton: HTMLButtonElement; + beforeEach(() => { + bgButton = el("button", {}, app) as HTMLButtonElement; + dialogButton = el("button", {}, dialog) as HTMLButtonElement; + }); + + test("removing the focused element applies the deferred aria-hidden", async () => { + bgButton.focus(); + const cleanup = makeInertOthers(dialog); + expect(app.hasAttribute("aria-hidden")).toBe(false); + bgButton.remove(); + await tick(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + cleanup(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + }); + + test("an unrelated removal keeps the hold deferred while focus is still inside", async () => { + const other = el("span", {}, app); + bgButton.focus(); + const cleanup = makeInertOthers(dialog); + other.remove(); + await tick(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + bgButton.remove(); + await tick(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + cleanup(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + }); + + test("removing an ancestor of the focused element in a nested branch applies it", async () => { + const wrap = el("div", {}, app); + const inner = el("button", {}, wrap) as HTMLButtonElement; + inner.focus(); + const cleanup = makeInertOthers(dialog); + expect(app.hasAttribute("aria-hidden")).toBe(false); + wrap.remove(); + await tick(); + expect(app.getAttribute("aria-hidden")).toBe("true"); + cleanup(); + }); + + test("cleanup before removal leaves nothing applied and ignores later removals", async () => { + bgButton.focus(); + const cleanup = makeInertOthers(dialog); + cleanup(); + bgButton.remove(); + await tick(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + }); +}); + +describe("a layer whose targets are all detached", () => { + test("a newly opened upper layer exposes a held sibling (repro)", async () => { + const a = el("div"); + const b = el("div"); + const closeA = makeInertOthers(a); + expect(b.getAttribute("aria-hidden")).toBe("true"); + a.remove(); + await tick(); + expect(b.getAttribute("aria-hidden")).toBe("true"); + const closeB = makeInertOthers(b); + expect(b.hasAttribute("aria-hidden")).toBe(false); + // the frozen layer adds no new holds: app stays held by A (and now B) + expect(app.getAttribute("aria-hidden")).toBe("true"); + closeB(); + closeA(); + for (const n of [app, dialog, b]) expect(n.hasAttribute("aria-hidden")).toBe(false); + }); + + test("closing in the other order restores exact attributes", async () => { + const a = el("div"); + const b = el("div", { "aria-hidden": "false" }); + const closeA = makeInertOthers(a); + a.remove(); + await tick(); + const closeB = makeInertOthers(b); + closeA(); + closeB(); + expect(b.getAttribute("aria-hidden")).toBe("false"); + expect(app.hasAttribute("aria-hidden")).toBe(false); + expect(dialog.hasAttribute("aria-hidden")).toBe(false); + }); + + test("without an upper layer every hold stays, even after unrelated churn", async () => { + const a = el("div"); + const b = el("div"); + const closeA = makeInertOthers(a); + a.remove(); + await tick(); + const extra = el("div"); + await tick(); + expect(b.getAttribute("aria-hidden")).toBe("true"); + expect(app.getAttribute("aria-hidden")).toBe("true"); + expect(extra.hasAttribute("aria-hidden")).toBe(false); + closeA(); + expect(b.hasAttribute("aria-hidden")).toBe(false); + }); + + test("a held element that contains the upper layer target is released", async () => { + const a = el("div"); + const b = el("section"); + const bInner = el("div", {}, b); + const closeA = makeInertOthers(a); + a.remove(); + await tick(); + expect(b.getAttribute("aria-hidden")).toBe("true"); + const closeB = makeInertOthers(bInner); + expect(b.hasAttribute("aria-hidden")).toBe(false); + closeB(); + closeA(); + expect(app.hasAttribute("aria-hidden")).toBe(false); + }); + + test("re-sweeps normally once a target is reconnected", async () => { + const a = el("div"); + const b = el("div"); + const closeA = makeInertOthers(a); + a.remove(); + await tick(); + const late = el("div"); + await tick(); + expect(late.hasAttribute("aria-hidden")).toBe(false); + document.body.appendChild(a); + await tick(); + expect(late.getAttribute("aria-hidden")).toBe("true"); + expect(b.getAttribute("aria-hidden")).toBe("true"); + closeA(); + expect(late.hasAttribute("aria-hidden")).toBe(false); + }); +}); diff --git a/packages/interaction/test/interact-outside.test.ts b/packages/interaction/test/interact-outside.test.ts index a2c0aa4cb..35fe9d4f4 100644 --- a/packages/interaction/test/interact-outside.test.ts +++ b/packages/interaction/test/interact-outside.test.ts @@ -1,7 +1,11 @@ import { renderHydrationRoundTrip } from "../../../scripts/test-utils/hydration-harness.ts"; import { describe, it, expect, vi, beforeEach, afterEach, beforeAll } from "vitest"; import { createRoot, createSignal, flush } from "solid-js"; -import { createInteractOutside, type CreateInteractOutsideProps } from "../src/index.js"; +import { + createInteractOutside, + makeInteractOutside, + type CreateInteractOutsideProps, +} from "../src/index.js"; beforeAll(() => { if (!("PointerEvent" in window)) { @@ -695,3 +699,122 @@ it("hydrates primitive output and its following sibling", async () => { result.cleanup(); } }); + +describe("makeInteractOutside touch press lifecycle", () => { + let inside: HTMLElement; + let outside: HTMLElement; + let cleanup: () => void; + let onPointerDownOutside: ReturnType; + + beforeEach(() => { + vi.useFakeTimers(); + inside = document.createElement("button"); + outside = document.createElement("div"); + document.body.append(inside, outside); + onPointerDownOutside = vi.fn(); + cleanup = makeInteractOutside(inside, { onPointerDownOutside }); + vi.runAllTimers(); + }); + afterEach(() => { + cleanup(); + inside.remove(); + outside.remove(); + vi.useRealTimers(); + }); + + const down = (target: Element, x = 100, y = 100, type = "touch") => + target.dispatchEvent( + new PointerEvent("pointerdown", { + bubbles: true, + composed: true, + pointerType: type, + pointerId: 1, + clientX: x, + clientY: y, + }), + ); + const pointer = (type: string, target: Element, x = 100, y = 100) => + target.dispatchEvent( + new PointerEvent(type, { + bubbles: true, + pointerId: 1, + pointerType: "touch", + clientX: x, + clientY: y, + }), + ); + const click = (target: Element, x = 100, y = 100, detail = 1) => + target.dispatchEvent( + new MouseEvent("click", { bubbles: true, composed: true, clientX: x, clientY: y, detail }), + ); + + it("a tap (down, up, click on the same target) reports once", () => { + down(outside); + pointer("pointerup", outside); + expect(onPointerDownOutside).not.toHaveBeenCalled(); + click(outside); + expect(onPointerDownOutside).toHaveBeenCalledTimes(1); + }); + + it("a touch cancelled by a scroll does not dismiss on the next click", () => { + down(outside); + pointer("pointercancel", outside); + click(inside, 5, 5, 0); + expect(onPointerDownOutside).not.toHaveBeenCalled(); + }); + + it("a touchcancel drops the pending press", () => { + down(outside); + document.dispatchEvent(new Event("touchcancel", { bubbles: true })); + click(outside); + expect(onPointerDownOutside).not.toHaveBeenCalled(); + }); + + it("a touch that moved beyond the threshold is not a tap", () => { + down(outside); + pointer("pointermove", outside, 100, 140); + click(outside); + expect(onPointerDownOutside).not.toHaveBeenCalled(); + }); + + it("a small drift still counts as a tap", () => { + down(outside); + pointer("pointermove", outside, 103, 102); + click(outside, 103, 102); + expect(onPointerDownOutside).toHaveBeenCalledTimes(1); + }); + + it("a click that never follows the release expires", () => { + down(outside); + pointer("pointerup", outside); + vi.advanceTimersByTime(2000); + click(outside); + expect(onPointerDownOutside).not.toHaveBeenCalled(); + }); + + it("a keyboard-generated click after the touch does not dismiss", () => { + down(outside); + pointer("pointerup", outside); + inside.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + click(inside, 0, 0, 0); + expect(onPointerDownOutside).not.toHaveBeenCalled(); + }); + + it("a click on a different target at a different position is not this press", () => { + down(outside, 100, 100); + click(inside, 400, 400); + expect(onPointerDownOutside).not.toHaveBeenCalled(); + }); + + it("the pending press is dropped by cleanup", () => { + down(outside); + cleanup(); + click(outside); + expect(onPointerDownOutside).not.toHaveBeenCalled(); + }); + + it("mouse presses still report immediately", () => { + down(outside, 100, 100, "mouse"); + expect(onPointerDownOutside).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/interaction/test/server.test.ts b/packages/interaction/test/server.test.ts index 969b50261..c20c2e244 100644 --- a/packages/interaction/test/server.test.ts +++ b/packages/interaction/test/server.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, vi } from "vitest"; -import { createInteractOutside } from "../src/index.js"; +import { createRoot } from "solid-js"; +import { createInertOthers, createInteractOutside, makeInertOthers } from "../src/index.js"; describe("createInteractOutside on server", () => { it("can be called without error", () => { @@ -35,3 +36,21 @@ describe("createInteractOutside on server", () => { }).not.toThrow(); }); }); + +describe("inert on server", () => { + it("makeInertOthers returns a no-op cleanup", () => { + const cleanup = makeInertOthers({} as any); + expect(typeof cleanup).toBe("function"); + expect(() => cleanup()).not.toThrow(); + expect(() => makeInertOthers(undefined, { strategy: "both" })()).not.toThrow(); + }); + + it("createInertOthers does nothing", () => { + expect(() => + createRoot(dispose => { + createInertOthers(() => undefined, true, { strategy: "inert" }); + dispose(); + }), + ).not.toThrow(); + }); +}); diff --git a/packages/keyboard/README.md b/packages/keyboard/README.md index 2bd88d36c..2afba533b 100644 --- a/packages/keyboard/README.md +++ b/packages/keyboard/README.md @@ -19,6 +19,7 @@ A library of reactive primitives for handling user keyboard input. - [`createKeyHold`](#createkeyhold) — Provides a signal indicating if provided key is currently being held down. - [`createShortcut`](#createshortcut) — Creates a keyboard shortcut observer. - [`createKeyDown`](#createkeydown) — Listens for a keydown event for a specific key on a document. +- [`createShortcuts`](#createshortcuts) / [`makeShortcutRegistry`](#makeshortcutregistry) — Register many shortcuts through a single listener pair, with dynamic add/remove and a deterministic conflict policy. ## Installation @@ -261,8 +262,8 @@ render(() => , document.getElementById("app")!); - `callback` — callback to call when the specified keys are pressed - `options` — additional configuration: - `preventDefault` — call `e.preventDefault()` on the keyboard event, when the specified key is pressed. _(Defaults to `true`)_ - - `requireReset` — If `true`, the shortcut will only be triggered once until all of the keys stop being pressed. Disabled by default. - - `ignoreWithinInputs` — If `true`, the shortcut is ignored while focus is on an `input`, `textarea`, `select`, or `contenteditable` element, so it doesn't interrupt typing. Disabled by default. + - `requireReset` — If `true`, the shortcut will only be triggered once until all of the keys stop being pressed. Disabled by default. A modifier with two physical keys (for example both Control keys) counts as held until the last one is released. + - `ignoreWithinInputs` — If `true`, the shortcut is ignored while focus is on an `input`, `textarea`, `select`, or `contenteditable` element, so it doesn't interrupt typing. Inputs that never accept typed characters (`type` of `checkbox`, `button`, `submit`, `reset` or `image`) are not treated as editable, so the shortcut still fires there. Disabled by default. - `anyOrder` — If `true`, the keys can be pressed in any order (e.g. `Shift + Control` as well as `Control + Shift`), as long as they all end up held down together. Disabled by default, requiring `keys` to be pressed in order. ```tsx @@ -294,6 +295,17 @@ createShortcut(["S"], () => console.log("S was pressed"), { ignoreWithinInputs: Combos that include a modifier (e.g. `Control + S`) don't have this problem, since the modifier itself prevents a character from being typed — `ignoreWithinInputs` is usually unnecessary for those. +Inputs whose `type` never accepts typed characters (`checkbox`, `button`, `submit`, `reset`, `image`; case-insensitive) are **not** treated as editable, so a plain-key shortcut still fires while one of them has focus. All other inputs stay ignored: text-like types (`text`, `search`, `email`, `url`, `tel`, `password`, `number`, the date and time types, and an input with a missing or unknown `type`) as well as `radio`, `range`, `file` and `color`, which consume arrow and other keys. `textarea`, `select` and `contenteditable` are always ignored. The same rules apply to the registry's `ignoreInputs`. + +The check works for inputs inside **open** shadow roots (the real target is taken from `event.composedPath()`), and for inputs inside iframes whenever the key event reaches the listener's scope. Note that `createShortcut` listens for `keydown` on the calling `window` only: keys pressed while focus is inside an iframe never reach the parent window, so the shortcut does not fire there at all. For shortcuts that must work inside an iframe, use `createShortcuts` or `makeShortcutRegistry` with `scope` set to the iframe's `contentDocument` or `contentWindow`. **Closed** shadow roots hide their contents from the page, so inputs inside them cannot be detected. + +### Ignored keys and platform quirks + +- **Lock keys are ignored.** `CapsLock`, `NumLock` and `ScrollLock` are skipped by `useKeyDownList`, `createShortcut` and the shortcut registry (keydown and keyup). On macOS CapsLock sends only a keydown when switched on and only a keyup when switched off, so tracking it would leave it "held" and stop every exact-match shortcut from firing. They cannot be part of a shortcut. +- **Option/Alt on macOS.** Matching uses `event.key`, and with Option held macOS reports the composed character (`Option+E` gives `Dead`, `Option+S` gives `ß`) instead of the letter. A shortcut written as `["Alt", "S"]` therefore does not match on macOS. If you need such a shortcut, match the composed character, or use your own `keydown` listener and compare `event.code` (`"KeyS"`). `createKeyDown` is not an option here: it matches `event.key` too, so its callback never runs for `Option+S`. +- **Meta keyup.** macOS never sends keyup for keys pressed while Meta (Cmd) is held, only Meta's own. Releasing Meta therefore clears every tracked key. +- **Keyup is always observed on `window` in the capture phase**, so an app handler calling `stopPropagation()` on keyup cannot leave a key stuck. + ### Matching keys in any order By default, `keys` must be pressed in the order given — `["Control", "Shift", "M"]` only matches Control, then Shift, then M. Set `anyOrder: true` to match the combo regardless of press order, similar to how most editors handle shortcuts: @@ -329,6 +341,64 @@ createKeyDown("Escape", e => close(), { }); ``` +## `createShortcuts` + +Registers many shortcuts at once through a single `keydown`/`keyup` listener pair. Accepts a list, a map of key combination to handler, or an accessor of either; when the accessor changes, the shortcuts are re-registered. `createShortcut` is unchanged. + +```ts +// Type +function createShortcuts( + shortcuts: MaybeAccessor< + ShortcutDefinition[] | Record + >, + options?: { scope?: MaybeAccessor }, +): void; + +// Example +createShortcuts({ + "Control+K": () => openPalette(), + Escape: { handler: () => close(), enabled: isOpen, preventDefault: false }, +}); + +createShortcuts( + () => [{ keys: ["Control", "S"], handler: save, ignoreInputs: false }], + { scope: () => panelEl }, // only while focus is inside the element +); +``` + +Each definition is `{ keys, handler, preventDefault?, requireReset?, ignoreInputs?, enabled? }`: + +- `keys` — an array (`["Control", "K"]`) or a `+`-joined string (`"Ctrl+Shift+K"`, `"Control++"` for the plus key). A `+` right after a key name is a separator; a `+` right after a separator is the literal plus key, so `"Control+++K"` is Control, `+` and K, and `"+"` alone is the plus key. Case-insensitive; `Ctrl`, `Cmd`/`Command`, `Option` and `Space` are aliases. Matching is **exact and order-independent**: `Control+K` does not fire for `Control+Shift+K`. +- `handler(event)` — called with the `KeyboardEvent`. +- `preventDefault` — defaults to `true`. +- `requireReset` — fire once until all keys are released. Defaults to `false`. +- `ignoreInputs` — skip while focus is in an `input`, `textarea`, `select` or `contenteditable`. Like `ignoreWithinInputs`, it does not apply to `checkbox`, `button`, `submit`, `reset` and `image` inputs. Defaults to `false` (same as `createShortcut`'s `ignoreWithinInputs`). +- `enabled` — boolean or accessor, read at key time. A disabled shortcut never matches. + +Key repeat is ignored. Modifier state is taken from the event's `ctrlKey`/`shiftKey`/`altKey`/`metaKey` flags, and releasing `Meta` clears all held keys (macOS sends no keyup for keys held with Meta). + +### Conflict policy + +At most **one** shortcut fires per keydown. Because matching is on the exact key set, all candidates are equally specific, so the **most recently registered eligible shortcut wins** (for lists and maps: the last matching entry). "Eligible" means enabled, not suppressed by `ignoreInputs` and not blocked by `requireReset`, so a disabled or input-ignoring newer shortcut never shadows an older one. Only the winner's `preventDefault` applies. + +## `makeShortcutRegistry` + +The non-reactive base of `createShortcuts`. Listeners are attached when the first shortcut is registered and removed when the last is unregistered or on `clear()`. When `scope` is set, key releases are also observed on `window` (so a release after focus leaves the scope is seen) and on the scope itself, also in the capture phase (so a scope whose events never reach `window`, such as an iframe, still sees them even when an app handler stops keyup propagation). A `scope` may also be an iframe's `contentDocument` or `contentWindow`. It also clears itself when its owner is disposed. On the server it returns an inert registry. + +```ts +// Type +function makeShortcutRegistry(options?: { scope?: EventTarget }): { + register(definition: ShortcutDefinition): VoidFunction; // returns unregister + clear(): void; +}; + +// Example +const registry = makeShortcutRegistry({ scope: dialogEl }); +const unregister = registry.register({ keys: "Escape", handler: close }); +unregister(); // remove one +registry.clear(); // remove all and detach listeners +``` + ## Changelog See [CHANGELOG.md](./CHANGELOG.md) diff --git a/packages/keyboard/package.json b/packages/keyboard/package.json index 1884e682c..d37918d5e 100644 --- a/packages/keyboard/package.json +++ b/packages/keyboard/package.json @@ -22,7 +22,9 @@ "useCurrentlyHeldKey", "useKeyDownSequence", "createKeyHold", - "createShortcut" + "createShortcut", + "createShortcuts", + "makeShortcutRegistry" ], "category": "Inputs", "gzip": 1767 diff --git a/packages/keyboard/src/index.ts b/packages/keyboard/src/index.ts index c538e8e7b..8f3401ddb 100644 --- a/packages/keyboard/src/index.ts +++ b/packages/keyboard/src/index.ts @@ -1,6 +1,12 @@ import { makeEventListener } from "@solid-primitives/event-listener"; import { createSingletonRoot } from "@solid-primitives/rootless"; -import { arrayEquals, INTERNAL_OPTIONS, type MaybeAccessor, access } from "@solid-primitives/utils"; +import { + arrayEquals, + INTERNAL_OPTIONS, + type MaybeAccessor, + access, + tryOnCleanup, +} from "@solid-primitives/utils"; import { type Accessor, createEffect, createMemo, createSignal, untrack } from "solid-js"; import { isServer } from "@solidjs/web"; @@ -25,16 +31,117 @@ function isSameKeySet(a: string[], b: string[]): boolean { return new Set(a).symmetricDifference(new Set(b)).size === 0; } -/** Is the event target an editable form control, or inside a `contenteditable` element? */ +/** + * Remembers which logical key value was recorded at keydown for each PHYSICAL key, so the right + * one is removed on keyup. `KeyboardEvent.key` can change between press and release (hold Shift, + * press `1` -> `!`, release Shift, release `1` -> `1`), which would otherwise leave `!` stuck. + */ +function createKeyRecorder() { + const recorded = new Map(); + // `code` is the physical key; virtual/IME keyboards may report "" or "Unidentified" for every key, + // which would make all of them share one slot. Fall back to a key-based id that cannot collide + // with a real code name. + const id = (e: KeyboardEvent) => (e.code && e.code !== "Unidentified" ? e.code : `key:${e.key}`); + return { + /** Records the normalized `key` for the physical key of `e`. */ + down: (e: KeyboardEvent, key: string) => void recorded.set(id(e), key), + /** Returns the value recorded at keydown (falling back to the upper-cased `e.key`) and forgets it. */ + up(e: KeyboardEvent): string { + const physical = id(e); + const key = recorded.get(physical) ?? e.key.toUpperCase(); + recorded.delete(physical); + return key; + }, + clear: () => recorded.clear(), + }; +} + +/** + * True when `key` (a normalized key name) is a modifier whose event flag is still set after its + * keyup, meaning another physical key of the same modifier (e.g. ControlRight after ControlLeft) + * is still held. The modifier must then stay in the pressed list. + */ +function isModifierStillHeld(key: string, e: KeyboardEvent): boolean { + switch (key) { + case "CONTROL": + return e.ctrlKey; + case "SHIFT": + return e.shiftKey; + case "ALT": + return e.altKey; + case "META": + return e.metaKey; + default: + return false; + } +} + +/** + * Lock keys. macOS sends only a keydown when CapsLock is switched on and only a keyup when it is + * switched off, so they can never be tracked as "held". They are ignored entirely. + */ +function isLockKey(key: string): boolean { + switch (key.toUpperCase()) { + case "CAPSLOCK": + case "NUMLOCK": + case "SCROLLLOCK": + return true; + default: + return false; + } +} + +/** + * The element an event really originated from. `event.target` is retargeted to the shadow host + * when the listener sits outside an open shadow root; `composedPath()[0]` is the inner element. + */ +function getRealTarget(e: Event): EventTarget | null { + const path = typeof e.composedPath === "function" ? e.composedPath() : undefined; + return path && path.length ? path[0]! : e.target; +} + +/** Realm-safe `instanceof Node` (an iframe's nodes are not instances of this window's `Node`). */ +function isNode(value: unknown): value is Node { + return !!value && typeof (value as Node).nodeType === "number"; +} + +/** + * `` types that never accept typed characters. Everything else (including a missing or + * unknown type, which is a text input) is treated as editable, so types that consume keys such as + * arrows or typeahead (radio, range, file, color, ...) stay ignored. + */ +const NON_TEXT_INPUT_TYPES: ReadonlySet = new Set([ + "checkbox", + "button", + "submit", + "reset", + "image", +]); + +function getInputType(el: HTMLElement): string { + let type: unknown = (el as HTMLInputElement).type; + if (typeof type !== "string" && typeof el.getAttribute === "function") { + type = el.getAttribute("type"); + } + return typeof type === "string" ? type.toLowerCase() : ""; +} + +/** + * Is the event target an editable control, or inside a `contenteditable` element? + * `` types that never accept typed characters (checkbox, button, submit, reset, image) are + * not editable. Duck-typed, so it also works for elements that belong to another realm (iframes). + */ function isEditableTarget(target: EventTarget | null): boolean { - if (!(target instanceof HTMLElement)) return false; - switch (target.tagName) { + if (!isNode(target) || target.nodeType !== 1) return false; + const el = target as HTMLElement; + switch (typeof el.tagName === "string" ? el.tagName.toUpperCase() : "") { case "INPUT": + return !NON_TEXT_INPUT_TYPES.has(getInputType(el)); case "TEXTAREA": case "SELECT": return true; default: - return target.isContentEditable; + return !!el.isContentEditable; } } @@ -113,18 +220,23 @@ export const useKeyDownList: ReturnType([], INTERNAL_OPTIONS); - const reset = () => setPressedKeys([]); + const recorder = createKeyRecorder(); + const reset = () => { + recorder.clear(); + setPressedKeys([]); + }; makeEventListener(window, "keydown", e => { // e.key may be undefined when used with el // gh issue: https://github.com/solidjs-community/solid-primitives/issues/246 - if (e.repeat || typeof e.key !== "string") return; + if (e.repeat || typeof e.key !== "string" || isLockKey(e.key)) return; const key = e.key.toUpperCase(), currentKeys = pressedKeys(); if (currentKeys.includes(key)) return; + recorder.down(e, key); const keys = [...currentKeys, key]; // if the modifier is pressed before we start listening @@ -145,19 +257,26 @@ export const useKeyDownList: ReturnType { - if (typeof e.key !== "string") return; - const key = e.key.toUpperCase(); - // macOS never fires keyup for other keys held down together with Meta — - // only Meta's own keyup arrives — so its release must clear everything, - // or the other keys' stale state corrupts the next press. - // See https://github.com/solidjs-community/solid-primitives/issues/269 - if (key === "META") { - reset(); - } else { - setPressedKeys(prev => prev.filter(_key => _key !== key)); - } - }); + // Capture phase: an app handler calling stopPropagation() on keyup must not leave keys stuck. + makeEventListener( + window, + "keyup", + e => { + if (typeof e.key !== "string" || isLockKey(e.key)) return; + const key = recorder.up(e); + // macOS never fires keyup for other keys held down together with Meta — + // only Meta's own keyup arrives — so its release must clear everything, + // or the other keys' stale state corrupts the next press. + // See https://github.com/solidjs-community/solid-primitives/issues/269 + if (isModifierStillHeld(key, e)) return; + if (key === "META") { + reset(); + } else { + setPressedKeys(prev => prev.filter(_key => _key !== key)); + } + }, + { capture: true }, + ); makeEventListener(window, "blur", reset); makeEventListener(window, "contextmenu", e => { @@ -303,7 +422,9 @@ export function createKeyHold( * - `preventDefault` — Controls if the keydown event should have its default action prevented. Enabled by default. * - `requireReset` — If `true`, the shortcut will only be triggered once until all of the keys stop being pressed. Disabled by default. * - `ignoreWithinInputs` — If `true`, the shortcut is ignored while focus is on an `input`, `textarea`, `select`, - * or `contenteditable` element, so typing isn't interrupted. Disabled by default — enable it for shortcuts + * or `contenteditable` element, so typing isn't interrupted. Inputs that never accept typed characters + * (`type` = `checkbox`, `button`, `submit`, `reset`, `image`) do not count, so the shortcut still fires there; + * `radio`, `range`, `file` and `color` stay ignored because they use arrow and other keys. Disabled by default — enable it for shortcuts * made of plain, unmodified keys (e.g. a single letter); combos like `Control+S` are usually fine either way, * since the modifier prevents a character from being typed. * - `anyOrder` — If `true`, the keys can be pressed in any order (e.g. `Shift+Control` as well as `Control+Shift`), @@ -351,16 +472,18 @@ export function createShortcut( let pressedKeys: string[] = []; let sequence: string[][] = []; let reset = false; + const recorder = createKeyRecorder(); const resetAll = () => { + recorder.clear(); pressedKeys = []; sequence = []; reset = false; }; makeEventListener(window, "keydown", (e: KeyboardEvent) => { - if (e.repeat || typeof e.key !== "string") return; - if (ignoreWithinInputs && isEditableTarget(e.target)) return; + if (e.repeat || typeof e.key !== "string" || isLockKey(e.key)) return; + if (ignoreWithinInputs && isEditableTarget(getRealTarget(e))) return; const key = e.key.toUpperCase(); if (!pressedKeys.includes(key)) { @@ -379,6 +502,7 @@ export function createShortcut( if (e.metaKey && !newKeys.includes("META")) newKeys.unshift("META"); } newKeys.push(key); + recorder.down(e, key); pressedKeys = newKeys; sequence = [...sequence, [...pressedKeys]]; } @@ -433,14 +557,16 @@ export function createShortcut( } }); - makeEventListener(window, "keyup", (e: KeyboardEvent) => { - if (typeof e.key !== "string") return; - const key = e.key.toUpperCase(); + // Capture phase: an app handler calling stopPropagation() on keyup must not leave keys stuck. + const onKeyUp = (e: KeyboardEvent) => { + if (typeof e.key !== "string" || isLockKey(e.key)) return; + const key = recorder.up(e); // macOS never fires keyup for other keys held down together with Meta — // only Meta's own keyup arrives. Treat it as a signal that every other // tracked key must have been released too, or their stale state corrupts // the next press (see https://github.com/solidjs-community/solid-primitives/issues/269). + if (isModifierStillHeld(key, e)) return; if (key === "META") { resetAll(); return; @@ -455,7 +581,8 @@ export function createShortcut( // key can re-trigger the shortcut while modifier keys stay held. sequence = [[...pressedKeys]]; } - }); + }; + makeEventListener(window, "keyup", onKeyUp, { capture: true }); makeEventListener(window, "blur", resetAll); makeEventListener(window, "contextmenu", (e: MouseEvent) => { @@ -508,3 +635,311 @@ export function createKeyDown( { transparent: true }, ); } + +// --------------------------------------------------------------------------- +// Shortcut registry +// --------------------------------------------------------------------------- + +/** A shortcut definition accepted by {@link makeShortcutRegistry} and {@link createShortcuts}. */ +export interface ShortcutDefinition { + /** + * The keys that make up the shortcut, as an array (`["Control", "K"]`) or a `+`-joined string + * (`"Control+K"`, `"Ctrl+Shift++"`). Matching is case-insensitive, order-independent and exact: + * the held keys must be the same set. `Ctrl`, `Cmd`/`Command`, `Option` and `Space` are aliases. + */ + keys: KbdKey[] | string; + /** Called when the shortcut is triggered. */ + handler: (event: KeyboardEvent) => void; + /** Call `preventDefault()` on the triggering event. Defaults to `true`. */ + preventDefault?: boolean; + /** Fire only once until all keys have been released. Defaults to `false`. */ + requireReset?: boolean; + /** + * Ignore the shortcut while focus is in an input, textarea, select or contenteditable. Inputs that + * never accept typed characters (`checkbox`, `button`, `submit`, `reset`, `image`) do not count; + * `radio`, `range`, `file` and `color` stay ignored (they use arrow and other keys). Defaults to `false`. + */ + ignoreInputs?: boolean; + /** Read when a key is pressed; a disabled shortcut does not match and does not block others. Defaults to `true`. */ + enabled?: MaybeAccessor; +} + +export interface ShortcutRegistryOptions { + /** Element (or any event target) to listen on. Defaults to `window`. An element only sees keys while focus is inside it. */ + scope?: EventTarget; +} + +export interface ShortcutRegistry { + /** Registers a shortcut. Returns a function that unregisters it. */ + register(definition: ShortcutDefinition): VoidFunction; + /** Unregisters every shortcut and removes the underlying listeners. */ + clear(): void; +} + +const KEY_ALIASES: Record = { + CTRL: "CONTROL", + CMD: "META", + COMMAND: "META", + OPTION: "ALT", + SPACE: " ", +}; + +/** + * Splits a `+`-joined key string. The first character always starts a token; a `+` right after a + * token is a separator; a `+` right after a separator is a literal plus key (`"Control+++K"` is + * Control, `+`, K); a trailing `+` after a separator is a literal plus key (`"Control++"`). + */ +function splitKeyString(str: string): string[] { + const out: string[] = []; + let token = ""; + let afterSeparator = false; + for (let i = 0; i < str.length; i++) { + const ch = str[i]!; + if (ch === "+" && token !== "" && !afterSeparator) { + out.push(token); + token = ""; + afterSeparator = true; + } else { + token += ch; + afterSeparator = false; + } + } + if (token !== "") out.push(token); + return out; +} + +/** Normalises a key list or `+`-joined string to a de-duplicated list of upper-cased keys. */ +function normalizeShortcutKeys(keys: KbdKey[] | string): string[] { + const list = typeof keys === "string" ? splitKeyString(keys) : keys; + const out = new Set(); + for (const k of list) { + const key = k === " " ? k : k.trim(); + if (!key) continue; + const upper = key.toUpperCase(); + out.add(KEY_ALIASES[upper] ?? upper); + } + return [...out]; +} + +const MODIFIER_FLAGS = [ + ["SHIFT", "shiftKey"], + ["ALT", "altKey"], + ["CONTROL", "ctrlKey"], + ["META", "metaKey"], +] as const; + +interface RegistryEntry { + keys: Set; + def: ShortcutDefinition; + fired: boolean; +} + +/** + * Creates a registry of keyboard shortcuts that shares ONE `keydown`/`keyup` listener pair + * (plus `blur`/`contextmenu` resets) between all of them. Listeners are attached when the first + * shortcut is registered and removed when the last one is unregistered, or on `clear()`. + * + * **Conflict policy:** at most one shortcut fires per keydown. Shortcuts are matched on the exact + * key set, so all candidates are equally specific; among the *eligible* ones (enabled, not + * suppressed by `ignoreInputs`, not blocked by `requireReset`) the **most recently registered wins**. + * An ineligible shortcut never shadows an earlier one. Only the winner's `preventDefault` applies. + * + * If called inside an owner, the registry is cleared automatically on cleanup. Returns an inert + * registry on the server. + * + * @example + * ```ts + * const registry = makeShortcutRegistry(); + * const off = registry.register({ keys: "Control+K", handler: () => openPalette() }); + * off(); // unregister one + * registry.clear(); // remove everything + * ``` + */ +export function makeShortcutRegistry(options: ShortcutRegistryOptions = {}): ShortcutRegistry { + if (isServer) { + return { register: () => () => {}, clear: () => {} }; + } + + const entries: RegistryEntry[] = []; + let removeListeners: VoidFunction | undefined; + let pressed: string[] = []; + const recorder = createKeyRecorder(); + + const resetState = () => { + recorder.clear(); + pressed = []; + for (const entry of entries) entry.fired = false; + }; + + const onKeyDown = (e: KeyboardEvent) => { + if (e.repeat || typeof e.key !== "string" || isLockKey(e.key)) return; + const key = e.key.toUpperCase(); + + // modifier flags on the event are authoritative: adds modifiers held before we started + // listening and drops stale ones (e.g. a missed keyup on macOS) + const next = pressed.filter(k => !MODIFIER_FLAGS.some(([name]) => name === k)); + const isModifier = MODIFIER_FLAGS.some(([name]) => name === key); + const mods = MODIFIER_FLAGS.filter( + ([name, flag]) => e[flag] || (isModifier && name === key), + ).map(([name]) => name); + pressed = [...mods, ...next.filter(k => !mods.includes(k as never))]; + if (!pressed.includes(key)) pressed.push(key); + recorder.down(e, key); + + for (let i = entries.length - 1; i >= 0; i--) { + const entry = entries[i]!; + const { def } = entry; + if (entry.keys.size !== pressed.length || !entry.keys.has(key)) continue; + if (!pressed.every(k => entry.keys.has(k))) continue; + if (def.requireReset && entry.fired) continue; + if (def.ignoreInputs && isEditableTarget(getRealTarget(e))) continue; + if (access(def.enabled) === false) continue; + + entry.fired = true; + if (def.preventDefault !== false) e.preventDefault(); + def.handler(e); + return; // the winner takes it all + } + }; + + const onKeyUp = (e: KeyboardEvent) => { + if (typeof e.key !== "string" || isLockKey(e.key)) return; + const key = recorder.up(e); + // macOS fires no keyup for keys held together with Meta; its release clears everything + // (https://github.com/solidjs-community/solid-primitives/issues/269) + if (isModifierStillHeld(key, e)) return; + if (key === "META") return resetState(); + pressed = pressed.filter(k => k !== key); + if (pressed.length === 0) for (const entry of entries) entry.fired = false; + }; + + const attach = () => { + const scope = options.scope; + const keydownTarget = scope ?? window; + // Raw listeners: makeEventListener would bind cleanup to whichever owner happens to call + // register() first, silently killing the registry when that owner is disposed. + const onContextMenu = (e: MouseEvent) => { + e.defaultPrevented || resetState(); + }; + // Focus moving out of the scope (e.g. Tab) means the matching keyups land elsewhere. + // A null relatedTarget is the blur / window-switch case, which is reset by window "blur". + const onFocusOut = (e: FocusEvent) => { + const next = e.relatedTarget; + // duck-typed: scopes and focus targets may belong to another realm (iframe document) + if (isNode(scope) && isNode(next) && !scope.contains(next)) resetState(); + }; + keydownTarget.addEventListener("keydown", onKeyDown as (e: Event) => void); + // Activation is scoped, but releases are always tracked on window in the capture phase, so a + // key released after focus has moved outside the scope, or whose keyup an app handler stops + // from propagating, doesn't stay "pressed". + const keyupCapture = true; + // A scope whose events never reach window (bare EventTarget) needs its own keyup listener. + // Registered in the capture phase too, so an app handler stopping keyup inside an iframe scope + // cannot leave a key stuck. One event reaching both listeners is handled only once. + const ownKeyUp = !!scope && (scope as unknown) !== window; + let lastKeyUp: Event | undefined; + const handleKeyUp = (e: Event) => { + if (ownKeyUp) { + if (e === lastKeyUp) return; + lastKeyUp = e; + } + onKeyUp(e as KeyboardEvent); + }; + window.addEventListener("keyup", handleKeyUp, keyupCapture); + if (ownKeyUp) scope!.addEventListener("keyup", handleKeyUp, keyupCapture); + scope?.addEventListener("focusout", onFocusOut as (e: Event) => void); + window.addEventListener("blur", resetState); + window.addEventListener("contextmenu", onContextMenu as (e: Event) => void); + removeListeners = () => { + keydownTarget.removeEventListener("keydown", onKeyDown as (e: Event) => void); + window.removeEventListener("keyup", handleKeyUp, keyupCapture); + if (ownKeyUp) scope!.removeEventListener("keyup", handleKeyUp, keyupCapture); + scope?.removeEventListener("focusout", onFocusOut as (e: Event) => void); + window.removeEventListener("blur", resetState); + window.removeEventListener("contextmenu", onContextMenu as (e: Event) => void); + }; + }; + + const detach = () => { + removeListeners?.(); + removeListeners = undefined; + resetState(); + }; + + const clear = () => { + entries.length = 0; + detach(); + }; + + const register = (def: ShortcutDefinition): VoidFunction => { + const keys = normalizeShortcutKeys(def.keys); + if (!keys.length) return () => {}; + const entry: RegistryEntry = { keys: new Set(keys), def, fired: false }; + entries.push(entry); + if (!removeListeners) attach(); + return () => { + const i = entries.indexOf(entry); + if (i === -1) return; + entries.splice(i, 1); + if (!entries.length) detach(); + }; + }; + + tryOnCleanup(clear); + + return { register, clear }; +} + +export type ShortcutOptions = Omit; +/** Shortcuts as a list, or as a map of key combination to handler / handler + options. */ +export type ShortcutsInput = + | ShortcutDefinition[] + | Record< + string, + ShortcutDefinition["handler"] | (ShortcutOptions & Pick) + >; + +function toDefinitions(input: ShortcutsInput | undefined): ShortcutDefinition[] { + if (!input) return []; + if (Array.isArray(input)) return input; + return Object.entries(input).map(([keys, value]) => + typeof value === "function" ? { keys, handler: value } : { ...value, keys }, + ); +} + +/** + * Registers many keyboard shortcuts at once through a single listener pair + * (see {@link makeShortcutRegistry} for the conflict policy: most recently registered eligible + * shortcut wins, which here means the **last matching entry** of the list / map). + * + * The shortcuts may be an accessor; when it changes, the shortcuts are re-registered. + * Do not read signals from `handler`/`enabled` expecting tracking — they run on key events. + * Prefer an `enabled` accessor over swapping the list for toggling a shortcut. + * + * @param shortcuts A list of {@link ShortcutDefinition}, or a map of `"Control+K"` to handler or `{ handler, ...options }`; or an accessor of either. + * @param options `scope` — element to listen on instead of `window` (may be an accessor). + * + * @example + * ```ts + * createShortcuts({ + * "Control+K": () => openPalette(), + * "Escape": { handler: close, enabled: isOpen }, + * }); + * ``` + */ +export function createShortcuts( + shortcuts: MaybeAccessor, + options: { scope?: MaybeAccessor } = {}, +): void { + if (isServer) return; + + createEffect( + () => ({ defs: toDefinitions(access(shortcuts)), scope: access(options.scope) }), + ({ defs, scope }) => { + const registry = makeShortcutRegistry({ scope }); + for (const def of defs) registry.register(def); + return () => registry.clear(); + }, + { transparent: true }, + ); +} diff --git a/packages/keyboard/test/duplicate-modifiers.test.ts b/packages/keyboard/test/duplicate-modifiers.test.ts new file mode 100644 index 000000000..db583846f --- /dev/null +++ b/packages/keyboard/test/duplicate-modifiers.test.ts @@ -0,0 +1,107 @@ +import { createRoot, flush } from "solid-js"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { createShortcut, makeShortcutRegistry, useKeyDownList } from "../src/index.js"; + +const send = ( + type: "keydown" | "keyup", + key: string, + code: string, + flags: Partial = {}, +) => { + const ev = new Event(type, { cancelable: true, bubbles: true }) as any; + ev.key = key; + ev.code = code; + Object.assign(ev, flags); + window.dispatchEvent(ev); +}; + +const MODIFIERS = [ + ["Control", "ctrlKey", "CONTROL"], + ["Shift", "shiftKey", "SHIFT"], + ["Alt", "altKey", "ALT"], + ["Meta", "metaKey", "META"], +] as const; + +afterEach(() => { + window.dispatchEvent(new Event("blur")); +}); + +describe.each(MODIFIERS)("both %s keys held", (mod, flag, upper) => { + // Hold Left + Right + K, release K, release Left (flag still true), press K again. + const run = (probe: () => void) => { + const on = { [flag]: true }; + send("keydown", mod, `${mod}Left`, on); + send("keydown", mod, `${mod}Right`, on); + send("keydown", "k", "KeyK", on); + probe(); + send("keyup", "k", "KeyK", on); + send("keyup", mod, `${mod}Left`, on); + }; + + test("registry with requireReset does not re-fire until every modifier is released", () => { + const handler = vi.fn(); + const on = { [flag]: true }; + const registry = makeShortcutRegistry(); + registry.register({ keys: `${mod}+K`, handler, requireReset: true }); + run(() => expect(handler).toHaveBeenCalledTimes(1)); + send("keydown", "k", "KeyK", on); + expect(handler).toHaveBeenCalledTimes(1); + send("keyup", "k", "KeyK", on); + send("keyup", mod, `${mod}Right`, { [flag]: false }); + send("keydown", mod, `${mod}Left`, on); + send("keydown", "k", "KeyK", on); + expect(handler).toHaveBeenCalledTimes(2); + registry.clear(); + }); + + test("createShortcut with requireReset does not re-fire until every modifier is released", () => { + const handler = vi.fn(); + const on = { [flag]: true }; + const dispose = createRoot(d => { + createShortcut([mod, "K"], handler, { requireReset: true }); + return d; + }); + flush(); + run(() => expect(handler).toHaveBeenCalledTimes(1)); + send("keydown", "k", "KeyK", on); + expect(handler).toHaveBeenCalledTimes(1); + send("keyup", "k", "KeyK", on); + send("keyup", mod, `${mod}Right`, { [flag]: false }); + send("keydown", mod, `${mod}Left`, on); + send("keydown", "k", "KeyK", on); + expect(handler).toHaveBeenCalledTimes(2); + dispose(); + }); + + test("useKeyDownList keeps the modifier until the last physical key is released", () => + createRoot(dispose => { + const keys = useKeyDownList(); + const on = { [flag]: true }; + run(() => {}); + flush(); + expect(keys()).toEqual([upper]); + send("keydown", "k", "KeyK", on); + flush(); + expect(keys()).toEqual([upper, "K"]); + send("keyup", "k", "KeyK", on); + send("keyup", mod, `${mod}Right`, { [flag]: false }); + flush(); + expect(keys()).toEqual([]); + dispose(); + })); + + test("single modifier behaves as before", () => + createRoot(dispose => { + const keys = useKeyDownList(); + const on = { [flag]: true }; + send("keydown", mod, `${mod}Left`, on); + send("keydown", "k", "KeyK", on); + flush(); + expect(keys()).toEqual([upper, "K"]); + send("keyup", "k", "KeyK", on); + send("keyup", mod, `${mod}Left`, { [flag]: false }); + flush(); + expect(keys()).toEqual([]); + dispose(); + })); +}); diff --git a/packages/keyboard/test/index.test.ts b/packages/keyboard/test/index.test.ts index c2608a7bd..94da0eb64 100644 --- a/packages/keyboard/test/index.test.ts +++ b/packages/keyboard/test/index.test.ts @@ -38,6 +38,121 @@ const dispatchKeyEventOn = ( return ev as KeyboardEvent; }; +describe("keys with an unavailable physical code (virtual/IME keyboards)", () => { + for (const code of ["Unidentified", ""]) { + for (const order of ["same", "reverse"] as const) { + const tag = `code=${JSON.stringify(code)}, release ${order}`; + const release = () => { + if (order === "same") { + dispatchKeyEvent("a", "keyup", { code }); + dispatchKeyEvent("b", "keyup", { code }); + } else { + dispatchKeyEvent("b", "keyup", { code }); + dispatchKeyEvent("a", "keyup", { code }); + } + }; + + test(`useKeyDownList leaves an empty list: ${tag}`, () => + createRoot(dispose => { + const keys = useKeyDownList(); + dispatchKeyEvent("a", "keydown", { code }); + flush(); + dispatchKeyEvent("b", "keydown", { code }); + flush(); + expect(keys()).toEqual(["A", "B"]); + if (order === "same") { + dispatchKeyEvent("a", "keyup", { code }); + flush(); + dispatchKeyEvent("b", "keyup", { code }); + } else { + dispatchKeyEvent("b", "keyup", { code }); + flush(); + dispatchKeyEvent("a", "keyup", { code }); + } + flush(); + expect(keys()).toEqual([]); + dispose(); + })); + + test(`createShortcut state is clean afterwards: ${tag}`, () => + createRoot(dispose => { + let fired = 0; + createShortcut(["B"], () => fired++); + dispatchKeyEvent("a", "keydown", { code }); + dispatchKeyEvent("b", "keydown", { code }); + release(); + // a stuck "A" would make the held set [A, B] and block a lone B + dispatchKeyEvent("b", "keydown", { code }); + dispatchKeyEvent("b", "keyup", { code }); + expect(fired).toBe(1); + dispose(); + })); + } + } +}); + +describe("key value changes between keydown and keyup", () => { + const releaseCases: [string, "shift-first" | "digit-first", string, string, string, string][] = [ + ["Shift+1", "shift-first", "!", "1", "Digit1", "!"], + ["Shift+1", "digit-first", "!", "1", "Digit1", "!"], + ["Shift+A", "shift-first", "A", "a", "KeyA", "A"], + ["Shift+A", "digit-first", "A", "a", "KeyA", "A"], + ]; + + for (const [name, order, downKey, upKey, code, expected] of releaseCases) { + test(`useKeyDownList: ${name}, ${order}`, () => + createRoot(dispose => { + const keys = useKeyDownList(); + dispatchKeyEvent("Shift", "keydown", { code: "ShiftLeft", shiftKey: true }); + dispatchKeyEvent(downKey, "keydown", { code, shiftKey: true }); + flush(); + expect(keys()).toEqual(["SHIFT", expected]); + if (order === "shift-first") { + dispatchKeyEvent("Shift", "keyup", { code: "ShiftLeft" }); + dispatchKeyEvent(upKey, "keyup", { code }); + } else { + dispatchKeyEvent(downKey, "keyup", { code, shiftKey: true }); + dispatchKeyEvent("Shift", "keyup", { code: "ShiftLeft" }); + } + flush(); + expect(keys()).toEqual([]); + dispose(); + })); + + test(`createShortcut: ${name}, ${order}`, () => + createRoot(dispose => { + let fired = 0; + createShortcut(["X"], () => fired++); + dispatchKeyEvent("Shift", "keydown", { code: "ShiftLeft", shiftKey: true }); + dispatchKeyEvent(downKey, "keydown", { code, shiftKey: true }); + if (order === "shift-first") { + dispatchKeyEvent("Shift", "keyup", { code: "ShiftLeft" }); + dispatchKeyEvent(upKey, "keyup", { code }); + } else { + dispatchKeyEvent(downKey, "keyup", { code, shiftKey: true }); + dispatchKeyEvent("Shift", "keyup", { code: "ShiftLeft" }); + } + dispatchKeyEvent("x", "keydown", { code: "KeyX" }); + dispatchKeyEvent("x", "keyup", { code: "KeyX" }); + expect(fired).toBe(1); + dispose(); + })); + } + + test("useKeyDownList: Meta keyup still clears all keys", () => + createRoot(dispose => { + const keys = useKeyDownList(); + dispatchKeyEvent("Meta", "keydown", { code: "MetaLeft", metaKey: true }); + dispatchKeyEvent("k", "keydown", { code: "KeyK", metaKey: true }); + flush(); + expect(keys()).toEqual(["META", "K"]); + dispatchKeyEvent("Meta", "keyup", { code: "MetaLeft" }); + flush(); + expect(keys()).toEqual([]); + dispose(); + })); +}); + describe("useKeyDownList", () => { test("returns a list of currently held keys", () => createRoot(dispose => { diff --git a/packages/keyboard/test/input-types.test.ts b/packages/keyboard/test/input-types.test.ts new file mode 100644 index 000000000..0d75af0a7 --- /dev/null +++ b/packages/keyboard/test/input-types.test.ts @@ -0,0 +1,203 @@ +import { createRoot } from "solid-js"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { createShortcut, makeShortcutRegistry } from "../src/index.js"; + +type Win = Window & typeof globalThis; + +const fire = ( + target: EventTarget, + key: string, + type: "keydown" | "keyup" = "keydown", + EventCtor: typeof Event = Event, +) => { + const ev = new EventCtor(type, { cancelable: true, bubbles: true, composed: true }) as any; + ev.key = key; + target.dispatchEvent(ev); + return ev as KeyboardEvent; +}; + +afterEach(() => { + window.dispatchEvent(new Event("blur")); + document.body.innerHTML = ""; +}); + +/** input types that never accept typed characters: plain-key shortcuts must still fire */ +const EXEMPT = ["checkbox", "button", "submit", "reset", "image"]; +/** input types that consume typed characters or keys (arrows, typeahead): stay ignored */ +const EDITABLE = [ + "text", + "search", + "email", + "url", + "tel", + "password", + "number", + "date", + "time", + "datetime-local", + "month", + "week", + "radio", + "range", + "file", + "color", +]; + +const makeInput = (doc: Document, type?: string) => { + const input = doc.createElement("input"); + if (type !== undefined) input.setAttribute("type", type); + return input; +}; + +/** Runs one keystroke through createShortcut(ignoreWithinInputs) and a registry(ignoreInputs). */ +const probe = (target: EventTarget, EventCtor: typeof Event = Event, scope?: EventTarget) => { + const cs = vi.fn(); + const reg = vi.fn(); + let registry!: ReturnType; + createRoot(dispose => { + createShortcut(["S"], cs, { ignoreWithinInputs: true }); + registry = makeShortcutRegistry(scope ? { scope } : undefined); + registry.register({ keys: "S", ignoreInputs: true, handler: reg }); + fire(target, "s", "keydown", EventCtor); + fire(target, "s", "keyup", EventCtor); + registry.clear(); + dispose(); + }); + return { cs: cs.mock.calls.length, reg: reg.mock.calls.length }; +}; + +describe("input types that cannot receive typed characters", () => { + test.each(EXEMPT)("type=%s: ignoreWithinInputs and ignoreInputs do not suppress", type => { + const input = makeInput(document, type); + document.body.append(input); + expect(probe(input)).toEqual({ cs: 1, reg: 1 }); + }); + + test.each(EXEMPT)("type=%s: case-insensitive (uppercase attribute)", type => { + const input = makeInput(document, type.toUpperCase()); + document.body.append(input); + expect(probe(input)).toEqual({ cs: 1, reg: 1 }); + }); + + test("mixed-case type attribute values", () => { + for (const type of ["CheckBox", "SuBmIt", "BUTTON", "Reset", "ImAgE"]) { + const input = makeInput(document, type); + document.body.append(input); + expect(probe(input)).toEqual({ cs: 1, reg: 1 }); + input.remove(); + } + const text = makeInput(document, "TeXt"); + document.body.append(text); + expect(probe(text)).toEqual({ cs: 0, reg: 0 }); + }); + + test("falls back to getAttribute when the type property is not a string", () => { + const input = makeInput(document, "checkbox"); + Object.defineProperty(input, "type", { value: undefined }); + document.body.append(input); + expect(probe(input)).toEqual({ cs: 1, reg: 1 }); + }); +}); + +describe("input types that stay editable", () => { + test.each(EDITABLE)("type=%s: still ignored", type => { + const input = makeInput(document, type); + document.body.append(input); + expect(probe(input)).toEqual({ cs: 0, reg: 0 }); + }); + + test.each(EDITABLE)("type=%s: still ignored (uppercase attribute)", type => { + const input = makeInput(document, type.toUpperCase()); + document.body.append(input); + expect(probe(input)).toEqual({ cs: 0, reg: 0 }); + }); + + test("input with no type attribute is a text input", () => { + const input = makeInput(document); + document.body.append(input); + expect(probe(input)).toEqual({ cs: 0, reg: 0 }); + }); + + test("input with an unknown or empty type is a text input", () => { + for (const type of ["bogus", ""]) { + const input = makeInput(document, type); + document.body.append(input); + expect(probe(input)).toEqual({ cs: 0, reg: 0 }); + input.remove(); + } + }); + + test("textarea, select and contenteditable are still ignored", () => { + const textarea = document.createElement("textarea"); + const select = document.createElement("select"); + const editable = document.createElement("div"); + Object.defineProperty(editable, "isContentEditable", { value: true }); + document.body.append(textarea, select, editable); + for (const el of [textarea, select, editable]) expect(probe(el)).toEqual({ cs: 0, reg: 0 }); + }); +}); + +describe("input types inside open shadow roots", () => { + const shadowInput = (type?: string) => { + const host = document.createElement("div"); + document.body.append(host); + const root = host.attachShadow({ mode: "open" }); + const input = makeInput(document, type); + root.append(input); + return input; + }; + + test("checkbox in a shadow root does not suppress", () => { + expect(probe(shadowInput("checkbox"))).toEqual({ cs: 1, reg: 1 }); + }); + + test("text in a shadow root is still ignored", () => { + expect(probe(shadowInput("text"))).toEqual({ cs: 0, reg: 0 }); + expect(probe(shadowInput())).toEqual({ cs: 0, reg: 0 }); + }); +}); + +describe("input types inside iframes", () => { + const makeFrame = () => { + const iframe = document.createElement("iframe"); + document.body.append(iframe); + return { win: iframe.contentWindow as unknown as Win, doc: iframe.contentDocument! }; + }; + + test("checkbox in an iframe does not suppress (registry scoped to the iframe document)", () => { + const { win, doc } = makeFrame(); + const input = makeInput(doc, "checkbox"); + doc.body.append(input); + expect(input instanceof HTMLElement).toBe(false); + const registry = makeShortcutRegistry({ scope: doc }); + const h = vi.fn(); + registry.register({ keys: "S", ignoreInputs: true, handler: h }); + fire(input, "s", "keydown", win.Event); + fire(input, "s", "keyup", win.Event); + expect(h).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("text in an iframe is still ignored (registry scoped to the iframe document)", () => { + const { win, doc } = makeFrame(); + const input = makeInput(doc, "text"); + doc.body.append(input); + const registry = makeShortcutRegistry({ scope: doc }); + const h = vi.fn(); + registry.register({ keys: "S", ignoreInputs: true, handler: h }); + fire(input, "s", "keydown", win.Event); + fire(input, "s", "keyup", win.Event); + expect(h).not.toHaveBeenCalled(); + registry.clear(); + }); + + test("probe helper: registry scoped to an iframe document, checkbox fires and text is ignored", () => { + const { win, doc } = makeFrame(); + const checkbox = makeInput(doc, "checkbox"); + const text = makeInput(doc, "text"); + doc.body.append(checkbox, text); + // events inside the iframe never reach the parent window, so createShortcut (cs) sees none + expect(probe(checkbox, win.Event, doc)).toEqual({ cs: 0, reg: 1 }); + expect(probe(text, win.Event, doc)).toEqual({ cs: 0, reg: 0 }); + }); +}); diff --git a/packages/keyboard/test/realworld.test.ts b/packages/keyboard/test/realworld.test.ts new file mode 100644 index 000000000..194cab8bc --- /dev/null +++ b/packages/keyboard/test/realworld.test.ts @@ -0,0 +1,285 @@ +import { createRoot, flush } from "solid-js"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { createShortcut, makeShortcutRegistry, useKeyDownList } from "../src/index.js"; + +type Win = Window & typeof globalThis; + +const fire = ( + target: EventTarget, + key: string, + type: "keydown" | "keyup" = "keydown", + extra: Partial & { composed?: boolean } = {}, + EventCtor: typeof Event = Event, +) => { + const ev = new EventCtor(type, { + cancelable: true, + bubbles: true, + composed: extra.composed ?? true, + }) as any; + ev.key = key; + Object.assign(ev, extra); + target.dispatchEvent(ev); + return ev as KeyboardEvent; +}; + +afterEach(() => { + window.dispatchEvent(new Event("blur")); + document.body.innerHTML = ""; +}); + +describe("keyup is tracked in the capture phase", () => { + const stoppingInput = () => { + const input = document.createElement("input"); + input.addEventListener("keyup", e => e.stopPropagation()); + document.body.append(input); + return input; + }; + + test("registry: a keyup stopped by an app handler does not leave the key stuck", () => { + const input = stoppingInput(); + const registry = makeShortcutRegistry(); + const j = vi.fn(); + const k = vi.fn(); + registry.register({ keys: "J", handler: j }); + registry.register({ keys: "K", handler: k }); + fire(input, "j", "keydown"); + fire(input, "j", "keyup"); + fire(input, "k", "keydown"); + fire(input, "k", "keyup"); + expect(j).toHaveBeenCalledTimes(1); + expect(k).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("createShortcut: a keyup stopped by an app handler does not leave the key stuck", () => + createRoot(dispose => { + const input = stoppingInput(); + const j = vi.fn(); + const k = vi.fn(); + createShortcut(["J"], j); + createShortcut(["K"], k); + fire(input, "j", "keydown"); + fire(input, "j", "keyup"); + fire(input, "k", "keydown"); + fire(input, "k", "keyup"); + expect(j).toHaveBeenCalledTimes(1); + expect(k).toHaveBeenCalledTimes(1); + dispose(); + })); + + test("useKeyDownList: a keyup stopped by an app handler releases the key", () => + createRoot(dispose => { + const input = stoppingInput(); + const keys = useKeyDownList(); + fire(input, "j", "keydown"); + flush(); + expect(keys()).toEqual(["J"]); + fire(input, "j", "keyup"); + flush(); + expect(keys()).toEqual([]); + dispose(); + })); + + test("a scoped registry still handles each keyup only once", () => { + const scope = document.createElement("div"); + document.body.append(scope); + const registry = makeShortcutRegistry({ scope }); + const a = vi.fn(); + const b = vi.fn(); + registry.register({ keys: "a", handler: a }); + registry.register({ keys: "b", handler: b }); + fire(scope, "a", "keydown"); + fire(scope, "a", "keyup"); + fire(scope, "b", "keydown"); + expect(a).toHaveBeenCalledTimes(1); + expect(b).toHaveBeenCalledTimes(1); + registry.clear(); + }); +}); + +describe("lock keys are ignored", () => { + test.each(["CapsLock", "NumLock", "ScrollLock"])( + "%s keydown without a keyup does not break matching (all three primitives)", + lock => + createRoot(dispose => { + const cs = vi.fn(); + const reg = vi.fn(); + createShortcut(["Control", "K"], cs); + const registry = makeShortcutRegistry(); + registry.register({ keys: "Control+J", handler: reg }); + const keys = useKeyDownList(); + + fire(window, lock, "keydown"); + flush(); + expect(keys()).toEqual([]); + + fire(window, "Control", "keydown", { ctrlKey: true }); + fire(window, "k", "keydown", { ctrlKey: true }); + fire(window, "k", "keyup", { ctrlKey: true }); + fire(window, "j", "keydown", { ctrlKey: true }); + fire(window, "j", "keyup", { ctrlKey: true }); + fire(window, "Control", "keyup"); + expect(cs).toHaveBeenCalledTimes(1); + expect(reg).toHaveBeenCalledTimes(1); + + fire(window, lock, "keyup"); + flush(); + expect(keys()).toEqual([]); + registry.clear(); + dispose(); + }), + ); + + test("a lock key is not a shortcut key", () => { + const registry = makeShortcutRegistry(); + const h = vi.fn(); + registry.register({ keys: "CapsLock", handler: h }); + fire(window, "CapsLock", "keydown"); + expect(h).not.toHaveBeenCalled(); + registry.clear(); + }); +}); + +describe("ignoreInputs in iframes", () => { + const makeFrame = () => { + const iframe = document.createElement("iframe"); + document.body.append(iframe); + const win = iframe.contentWindow as unknown as Win; + const doc = iframe.contentDocument!; + return { iframe, win, doc }; + }; + + test("registry with an iframe document scope honours ignoreInputs", () => { + const { win, doc } = makeFrame(); + const input = doc.createElement("input"); + const button = doc.createElement("button"); + doc.body.append(input, button); + // sanity: a cross-realm element is not an instance of this realm's HTMLElement + expect(input instanceof HTMLElement).toBe(false); + + const registry = makeShortcutRegistry({ scope: doc }); + const h = vi.fn(); + registry.register({ keys: "S", ignoreInputs: true, handler: h }); + + fire(input, "s", "keydown", {}, win.Event); + fire(input, "s", "keyup", {}, win.Event); + expect(h).not.toHaveBeenCalled(); + + fire(button, "s", "keydown", {}, win.Event); + fire(button, "s", "keyup", {}, win.Event); + expect(h).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("registry with an iframe contenteditable honours ignoreInputs", () => { + const { win, doc } = makeFrame(); + const div = doc.createElement("div"); + Object.defineProperty(div, "isContentEditable", { value: true }); + doc.body.append(div); + const registry = makeShortcutRegistry({ scope: doc }); + const h = vi.fn(); + registry.register({ keys: "S", ignoreInputs: true, handler: h }); + fire(div, "s", "keydown", {}, win.Event); + expect(h).not.toHaveBeenCalled(); + registry.clear(); + }); + + test.each(["window", "document"] as const)( + "iframe %s scope: a keyup stopped by an app handler does not leave the key stuck", + kind => { + const { win, doc } = makeFrame(); + const input = doc.createElement("input"); + doc.body.append(input); + input.addEventListener("keyup", e => e.stopPropagation()); + const registry = makeShortcutRegistry({ scope: kind === "window" ? win : doc }); + const j = vi.fn(); + const k = vi.fn(); + registry.register({ keys: "J", handler: j }); + registry.register({ keys: "K", handler: k }); + + fire(input, "j", "keydown", {}, win.Event); + fire(input, "j", "keyup", {}, win.Event); + fire(input, "k", "keydown", {}, win.Event); + fire(input, "k", "keyup", {}, win.Event); + expect(j).toHaveBeenCalledTimes(1); + expect(k).toHaveBeenCalledTimes(1); + registry.clear(); + }, + ); + + test("focus leaving an iframe document scope resets pressed keys", () => { + const { win, doc } = makeFrame(); + const inside = doc.createElement("input"); + doc.body.append(inside); + const outside = document.createElement("input"); + document.body.append(outside); + const registry = makeShortcutRegistry({ scope: doc }); + const k = vi.fn(); + registry.register({ keys: "K", handler: k }); + + fire(inside, "j", "keydown", {}, win.Event); + const focusout = new win.Event("focusout", { bubbles: true }) as any; + focusout.relatedTarget = outside; + inside.dispatchEvent(focusout); + fire(inside, "k", "keydown", {}, win.Event); + expect(k).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("focus moving within an iframe document scope does not reset", () => { + const { win, doc } = makeFrame(); + const a = doc.createElement("input"); + const b = doc.createElement("input"); + doc.body.append(a, b); + const registry = makeShortcutRegistry({ scope: doc }); + const jk = vi.fn(); + registry.register({ keys: "J+K", handler: jk }); + fire(a, "j", "keydown", {}, win.Event); + const focusout = new win.Event("focusout", { bubbles: true }) as any; + focusout.relatedTarget = b; + a.dispatchEvent(focusout); + fire(b, "k", "keydown", {}, win.Event); + expect(jk).toHaveBeenCalledTimes(1); + registry.clear(); + }); +}); + +describe("ignoreInputs in open shadow roots", () => { + const makeShadow = () => { + const host = document.createElement("div"); + document.body.append(host); + const root = host.attachShadow({ mode: "open" }); + const input = document.createElement("input"); + const button = document.createElement("button"); + root.append(input, button); + return { host, input, button }; + }; + + test("registry ignoreInputs sees the input inside the shadow root", () => { + const { input, button } = makeShadow(); + const registry = makeShortcutRegistry(); + const h = vi.fn(); + registry.register({ keys: "X", ignoreInputs: true, handler: h }); + fire(input, "x", "keydown"); + fire(input, "x", "keyup"); + expect(h).not.toHaveBeenCalled(); + fire(button, "x", "keydown"); + fire(button, "x", "keyup"); + expect(h).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("createShortcut ignoreWithinInputs sees the input inside the shadow root", () => + createRoot(dispose => { + const { input, button } = makeShadow(); + const h = vi.fn(); + createShortcut(["S"], h, { ignoreWithinInputs: true }); + fire(input, "s", "keydown"); + fire(input, "s", "keyup"); + expect(h).not.toHaveBeenCalled(); + fire(button, "s", "keydown"); + fire(button, "s", "keyup"); + expect(h).toHaveBeenCalledTimes(1); + dispose(); + })); +}); diff --git a/packages/keyboard/test/server.test.ts b/packages/keyboard/test/server.test.ts index 3ceff5d0b..7a1a9fc68 100644 --- a/packages/keyboard/test/server.test.ts +++ b/packages/keyboard/test/server.test.ts @@ -51,3 +51,23 @@ describe("SSR", () => { dispose(); })); }); + +describe("SSR shortcut registry", async () => { + const { createShortcuts, makeShortcutRegistry } = await import("../src/index.js"); + + it("makeShortcutRegistry returns an inert registry", () => { + const registry = makeShortcutRegistry(); + const off = registry.register({ keys: "Control+K", handler: () => {} }); + expect(typeof off).toBe("function"); + expect(() => { + off(); + registry.clear(); + }).not.toThrow(); + }); + + it("createShortcuts is a no-op on the server", () => + createRoot(dispose => { + expect(() => createShortcuts({ "Control+K": () => {} })).not.toThrow(); + dispose(); + })); +}); diff --git a/packages/keyboard/test/shortcuts.test.ts b/packages/keyboard/test/shortcuts.test.ts new file mode 100644 index 000000000..5e35d3121 --- /dev/null +++ b/packages/keyboard/test/shortcuts.test.ts @@ -0,0 +1,782 @@ +import { createRoot, createSignal, flush } from "solid-js"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { createShortcuts, makeShortcutRegistry } from "../src/index.js"; + +const fire = ( + target: EventTarget, + key: string, + type: "keydown" | "keyup" = "keydown", + extra: Partial = {}, +) => { + const ev = new Event(type, { cancelable: true, bubbles: true }) as any; + ev.key = key; + Object.assign(ev, extra); + target.dispatchEvent(ev); + return ev as KeyboardEvent; +}; +const press = (key: string, extra: Partial = {}, target: EventTarget = window) => { + const down = fire(target, key, "keydown", extra); + fire(target, key, "keyup", extra); + return down; +}; + +afterEach(() => { + // make sure no test leaves pressed-key state behind on window + window.dispatchEvent(new Event("blur")); +}); + +describe("makeShortcutRegistry", () => { + test("survives disposal of a foreign owner that registered first", () => { + let registry!: ReturnType; + const dispose0 = createRoot(d => { + registry = makeShortcutRegistry(); + return d; + }); + const handler = vi.fn(); + let disposeB!: VoidFunction; + createRoot(d => { + disposeB = d; + registry.register({ keys: "A", handler }); + }); + press("a"); + expect(handler).toHaveBeenCalledTimes(1); + disposeB(); + press("a"); + expect(handler).toHaveBeenCalledTimes(2); + dispose0(); + press("a"); + expect(handler).toHaveBeenCalledTimes(2); + }); + + test("fires on exact key set, order independent, case-insensitive, aliases", () => { + const registry = makeShortcutRegistry(); + const a = vi.fn(); + registry.register({ keys: "Ctrl+Shift+k", handler: a }); + press("K", { ctrlKey: true, shiftKey: true }); + expect(a).toHaveBeenCalledTimes(1); + press("K", { ctrlKey: true }); + press("K"); + expect(a).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("array keys, and multi-key chords of non-modifiers", () => { + const registry = makeShortcutRegistry(); + const h = vi.fn(); + registry.register({ keys: ["a", "b"], handler: h }); + fire(window, "a"); + fire(window, "b"); + expect(h).toHaveBeenCalledTimes(1); + fire(window, "b", "keyup"); + fire(window, "a", "keyup"); + registry.clear(); + }); + + test('"+" key and empty definitions', () => { + const registry = makeShortcutRegistry(); + const plus = vi.fn(); + const mod = vi.fn(); + registry.register({ keys: "+", handler: plus }); + registry.register({ keys: "Control++", handler: mod }); + registry.register({ keys: [], handler: vi.fn() })(); + press("+"); + press("+", { ctrlKey: true }); + expect(plus).toHaveBeenCalledTimes(1); + expect(mod).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("keys with an Unidentified code do not get stuck (both release orders)", () => { + for (const order of ["same", "reverse"]) { + const registry = makeShortcutRegistry(); + const b = vi.fn(); + registry.register({ keys: "B", handler: b }); + const code = "Unidentified"; + fire(window, "a", "keydown", { code }); + fire(window, "b", "keydown", { code }); + const [first, second] = order === "same" ? ["a", "b"] : ["b", "a"]; + fire(window, first!, "keyup", { code }); + fire(window, second!, "keyup", { code }); + b.mockClear(); + // a stuck "A" would make the held set [A, B] and block a lone B + fire(window, "b", "keydown", { code }); + fire(window, "b", "keyup", { code }); + expect(b).toHaveBeenCalledTimes(1); + registry.clear(); + } + }); + + test("literal plus key in any position of a key string", () => { + const registry = makeShortcutRegistry(); + const mid = vi.fn(); + const shiftPlus = vi.fn(); + registry.register({ keys: "Control+++K", handler: mid }); + registry.register({ keys: "Shift+++", handler: shiftPlus }); + // Control, +, K held together (chord of non-modifiers + and K) + fire(window, "Control", "keydown", { ctrlKey: true, code: "ControlLeft" }); + fire(window, "+", "keydown", { ctrlKey: true, code: "Equal" }); + fire(window, "K", "keydown", { ctrlKey: true, code: "KeyK" }); + expect(mid).toHaveBeenCalledTimes(1); + for (const [k, c] of [ + ["K", "KeyK"], + ["+", "Equal"], + ["Control", "ControlLeft"], + ] as const) + fire(window, k, "keyup", { code: c }); + fire(window, "Shift", "keydown", { shiftKey: true, code: "ShiftLeft" }); + fire(window, "+", "keydown", { shiftKey: true, code: "Equal" }); + expect(shiftPlus).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("a+++b registers a, + and b; malformed strings do not throw", () => { + const registry = makeShortcutRegistry(); + const h = vi.fn(); + registry.register({ keys: "a+++b", handler: h }); + fire(window, "a"); + fire(window, "+"); + fire(window, "b"); + expect(h).toHaveBeenCalledTimes(1); + for (const k of ["b", "+", "a"]) fire(window, k, "keyup"); + for (const bad of ["", "+", "++", "+++", "a+", "+a", "a++b+", " ", "a+ +b"]) { + expect(() => registry.register({ keys: bad, handler: vi.fn() })()).not.toThrow(); + } + registry.clear(); + }); + + test("preventDefault defaults to true and can be disabled", () => { + const registry = makeShortcutRegistry(); + registry.register({ keys: "x", handler: () => {} }); + registry.register({ keys: "y", handler: () => {}, preventDefault: false }); + expect(press("x").defaultPrevented).toBe(true); + expect(press("y").defaultPrevented).toBe(false); + registry.clear(); + }); + + test("uses one keydown and one keyup listener on the scope for all shortcuts", () => { + const scope = document.createElement("div"); + const add = vi.spyOn(scope, "addEventListener"); + const registry = makeShortcutRegistry({ scope }); + registry.register({ keys: "a", handler: () => {} }); + registry.register({ keys: "b", handler: () => {} }); + registry.register({ keys: "c", handler: () => {} }); + // keyup is tracked on window (capture) so releases outside the scope are seen, and on the + // scope itself so a scope whose events never reach window still sees releases + expect(add.mock.calls.map(c => c[0]).sort()).toEqual(["focusout", "keydown", "keyup"]); + registry.clear(); + }); + + describe("conflict policy", () => { + test("most recently registered eligible shortcut wins; only one fires", () => { + const registry = makeShortcutRegistry(); + const first = vi.fn(); + const second = vi.fn(); + registry.register({ keys: "q", handler: first }); + registry.register({ keys: ["Q"], handler: second }); + press("q"); + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("a disabled newer shortcut does not shadow an older one", () => { + const registry = makeShortcutRegistry(); + const [enabled, setEnabled] = createSignal(false); + const older = vi.fn(); + const newer = vi.fn(); + registry.register({ keys: "q", handler: older }); + registry.register({ keys: "q", handler: newer, enabled }); + press("q"); + expect(older).toHaveBeenCalledTimes(1); + expect(newer).not.toHaveBeenCalled(); + setEnabled(true); + flush(); + press("q"); + expect(newer).toHaveBeenCalledTimes(1); + expect(older).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("input-ignoring newer shortcut falls through to older one inside inputs", () => { + const registry = makeShortcutRegistry(); + const input = document.createElement("input"); + document.body.append(input); + const older = vi.fn(); + const newer = vi.fn(); + registry.register({ keys: "q", handler: older }); + registry.register({ keys: "q", handler: newer, ignoreInputs: true }); + press("q", {}, input); + expect(older).toHaveBeenCalledTimes(1); + expect(newer).not.toHaveBeenCalled(); + press("q"); + expect(newer).toHaveBeenCalledTimes(1); + input.remove(); + registry.clear(); + }); + + test("different key sets never conflict (Ctrl+K vs K)", () => { + const registry = makeShortcutRegistry(); + const plain = vi.fn(); + const mod = vi.fn(); + registry.register({ keys: "k", handler: plain }); + registry.register({ keys: "Control+k", handler: mod }); + press("k", { ctrlKey: true }); + expect(mod).toHaveBeenCalledTimes(1); + expect(plain).not.toHaveBeenCalled(); + press("k"); + expect(plain).toHaveBeenCalledTimes(1); + registry.clear(); + }); + }); + + describe("dynamic registration", () => { + test("unregister stops one shortcut; others keep working", () => { + const registry = makeShortcutRegistry(); + const a = vi.fn(); + const b = vi.fn(); + const offA = registry.register({ keys: "a", handler: a }); + registry.register({ keys: "b", handler: b }); + offA(); + offA(); // idempotent + press("a"); + press("b"); + expect(a).not.toHaveBeenCalled(); + expect(b).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("unregistering the newest reveals the older shortcut", () => { + const registry = makeShortcutRegistry(); + const older = vi.fn(); + const newer = vi.fn(); + registry.register({ keys: "q", handler: older }); + const off = registry.register({ keys: "q", handler: newer }); + off(); + press("q"); + expect(older).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("register after clear works again; handlers added from within a handler", () => { + const registry = makeShortcutRegistry(); + const late = vi.fn(); + registry.register({ + keys: "a", + handler: () => { + registry.register({ keys: "b", handler: late }); + }, + }); + press("a"); + press("b"); + expect(late).toHaveBeenCalledTimes(1); + registry.clear(); + press("b"); + expect(late).toHaveBeenCalledTimes(1); + const again = vi.fn(); + registry.register({ keys: "b", handler: again }); + press("b"); + expect(again).toHaveBeenCalledTimes(1); + registry.clear(); + }); + }); + + test("enabled accessor is read at key time", () => { + const registry = makeShortcutRegistry(); + const [on, setOn] = createSignal(true); + const h = vi.fn(); + registry.register({ keys: "e", handler: h, enabled: on }); + press("e"); + setOn(false); + flush(); + press("e"); + expect(h).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("ignoreInputs skips input, textarea, select and contenteditable; default does not", () => { + const registry = makeShortcutRegistry(); + const ignoring = vi.fn(); + const normal = vi.fn(); + registry.register({ keys: "s", handler: ignoring, ignoreInputs: true }); + registry.register({ keys: "t", handler: normal }); + const els = ["input", "textarea", "select"].map(t => document.createElement(t)); + const editable = document.createElement("div"); + Object.defineProperty(editable, "isContentEditable", { value: true }); + els.push(editable); + document.body.append(...els); + for (const el of els) { + press("s", {}, el); + press("t", {}, el); + } + expect(ignoring).not.toHaveBeenCalled(); + expect(normal).toHaveBeenCalledTimes(4); + press("s", {}, document.body); + expect(ignoring).toHaveBeenCalledTimes(1); + els.forEach(el => el.remove()); + registry.clear(); + }); + + test("requireReset fires once until all keys are released", () => { + const registry = makeShortcutRegistry(); + const h = vi.fn(); + registry.register({ keys: "Control+k", handler: h, requireReset: true }); + fire(window, "Control", "keydown", { ctrlKey: true }); + fire(window, "k", "keydown", { ctrlKey: true }); + fire(window, "k", "keyup", { ctrlKey: true }); + fire(window, "k", "keydown", { ctrlKey: true }); // modifier still held + expect(h).toHaveBeenCalledTimes(1); + fire(window, "k", "keyup", { ctrlKey: true }); + fire(window, "Control", "keyup"); + fire(window, "Control", "keydown", { ctrlKey: true }); + fire(window, "k", "keydown", { ctrlKey: true }); + expect(h).toHaveBeenCalledTimes(2); + registry.clear(); + }); + + test("without requireReset, re-pressing the key with a held modifier retriggers; key repeat does not", () => { + const registry = makeShortcutRegistry(); + const h = vi.fn(); + registry.register({ keys: "Control+k", handler: h }); + fire(window, "Control", "keydown", { ctrlKey: true }); + fire(window, "k", "keydown", { ctrlKey: true }); + fire(window, "k", "keydown", { ctrlKey: true, repeat: true }); + expect(h).toHaveBeenCalledTimes(1); + fire(window, "k", "keyup", { ctrlKey: true }); + fire(window, "k", "keydown", { ctrlKey: true }); + expect(h).toHaveBeenCalledTimes(2); + registry.clear(); + }); + + test("Meta keyup clears stale state (macOS)", () => { + const registry = makeShortcutRegistry(); + const h = vi.fn(); + registry.register({ keys: "Meta+k", handler: h }); + fire(window, "Meta", "keydown", { metaKey: true }); + fire(window, "k", "keydown", { metaKey: true }); + expect(h).toHaveBeenCalledTimes(1); + // no keyup for k, as on macOS + fire(window, "Meta", "keyup"); + fire(window, "k", "keydown"); // must not be treated as Meta+k + expect(h).toHaveBeenCalledTimes(1); + fire(window, "k", "keyup"); + registry.clear(); + }); + + test("modifiers held before listening are picked up from event flags; stale ones dropped", () => { + const registry = makeShortcutRegistry(); + const h = vi.fn(); + registry.register({ keys: "Alt+Shift+z", handler: h }); + press("z", { altKey: true, shiftKey: true }); + expect(h).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("blur resets pressed state", () => { + const registry = makeShortcutRegistry(); + const h = vi.fn(); + registry.register({ keys: "z", handler: h }); + fire(window, "a", "keydown"); // stray key held + window.dispatchEvent(new Event("blur")); + fire(window, "z", "keydown"); + expect(h).toHaveBeenCalledTimes(1); + fire(window, "z", "keyup"); + registry.clear(); + }); + + describe("scope element", () => { + test("only reacts to events inside the scope", () => { + const scope = document.createElement("div"); + const child = document.createElement("button"); + const outside = document.createElement("div"); + scope.append(child); + document.body.append(scope, outside); + const registry = makeShortcutRegistry({ scope }); + const h = vi.fn(); + registry.register({ keys: "a", handler: h }); + press("a", {}, outside); + press("a"); + expect(h).not.toHaveBeenCalled(); + press("a", {}, child); + press("a", {}, scope); + expect(h).toHaveBeenCalledTimes(2); + registry.clear(); + press("a", {}, child); + expect(h).toHaveBeenCalledTimes(2); + scope.remove(); + outside.remove(); + }); + }); + + describe("scope keyup tracking", () => { + test("a bare EventTarget scope (events never reach window) sees key releases", () => { + const scope = new EventTarget(); + const registry = makeShortcutRegistry({ scope }); + const a = vi.fn(); + const b = vi.fn(); + registry.register({ keys: "a", handler: a }); + registry.register({ keys: "b", handler: b }); + fire(scope, "a", "keydown"); + fire(scope, "a", "keyup"); + fire(scope, "b", "keydown"); + expect(a).toHaveBeenCalledTimes(1); + expect(b).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("a keyup bubbling from the scope to window is processed exactly once", () => { + // count how often the registry reads `key` while handling one keyup event + const keyReads = (scope?: HTMLElement) => { + if (scope) document.body.append(scope); + const registry = makeShortcutRegistry({ scope }); + registry.register({ keys: "a", handler: () => {} }); + fire(scope ?? window, "a", "keydown"); + const up = new Event("keyup", { bubbles: true }) as any; + let reads = 0; + Object.defineProperty(up, "key", { + get() { + reads++; + return "a"; + }, + }); + (scope ?? window).dispatchEvent(up); + registry.clear(); + scope?.remove(); + return reads; + }; + const baseline = keyReads(); + expect(baseline).toBeGreaterThan(0); + expect(keyReads(document.createElement("div"))).toBe(baseline); + }); + + test("removes both keyup listeners on cleanup", () => { + const scope = new EventTarget(); + const sAdd = vi.spyOn(scope, "addEventListener"); + const sRemove = vi.spyOn(scope, "removeEventListener"); + const wAdd = vi.spyOn(window, "addEventListener"); + const wRemove = vi.spyOn(window, "removeEventListener"); + const registry = makeShortcutRegistry({ scope }); + registry.register({ keys: "a", handler: () => {} }); + const sUp = sAdd.mock.calls.filter(c => c[0] === "keyup"); + const wUp = wAdd.mock.calls.filter(c => c[0] === "keyup"); + expect(sUp).toHaveLength(1); + expect(wUp).toHaveLength(1); + registry.clear(); + expect(sRemove.mock.calls.filter(c => c[0] === "keyup" && c[1] === sUp[0]![1])).toHaveLength( + 1, + ); + expect(wRemove.mock.calls.filter(c => c[0] === "keyup" && c[1] === wUp[0]![1])).toHaveLength( + 1, + ); + vi.restoreAllMocks(); + }); + }); + + describe("scope element: focus leaving the scope", () => { + const setup = () => { + const scope = document.createElement("div"); + const child = document.createElement("button"); + const outside = document.createElement("button"); + scope.append(child); + document.body.append(scope, outside); + const registry = makeShortcutRegistry({ scope }); + const h = vi.fn(); + registry.register({ keys: "a", handler: h }); + const cleanup = () => { + registry.clear(); + scope.remove(); + outside.remove(); + }; + return { scope, child, outside, registry, h, cleanup }; + }; + + test("a keyup landing on an outside element still releases the key", () => { + const { child, outside, h, cleanup } = setup(); + fire(child, "Tab", "keydown"); + fire(outside, "Tab", "keyup"); // focus moved out, keyup lands outside + press("a", {}, child); + expect(h).toHaveBeenCalledTimes(1); + cleanup(); + }); + + test("focusout to an element outside the scope resets pressed state", () => { + const { child, outside, h, cleanup } = setup(); + fire(child, "Tab", "keydown"); + // no keyup is ever delivered (e.g. it was swallowed); focus just leaves the scope + const out = new Event("focusout", { bubbles: true }) as any; + out.relatedTarget = outside; + child.dispatchEvent(out); + press("a", {}, child); + expect(h).toHaveBeenCalledTimes(1); + cleanup(); + }); + + test("focusout to another element inside the scope does not reset, null relatedTarget is ignored", () => { + const { scope, child, h, cleanup } = setup(); + const other = document.createElement("input"); + scope.append(other); + fire(child, "Control", "keydown", { ctrlKey: true }); + const inside = new Event("focusout", { bubbles: true }) as any; + inside.relatedTarget = other; + child.dispatchEvent(inside); + const nul = new Event("focusout", { bubbles: true }) as any; + nul.relatedTarget = null; + child.dispatchEvent(nul); + // Control still held: Control+a would need a different shortcut; plain "a" must NOT match + fire(child, "a", "keydown", { ctrlKey: true }); + expect(h).not.toHaveBeenCalled(); + cleanup(); + }); + + test("still does not fire for keydown outside the scope", () => { + const { child, outside, h, cleanup } = setup(); + fire(child, "Tab", "keydown"); + fire(outside, "Tab", "keyup"); + fire(outside, "a", "keydown"); + fire(outside, "a", "keyup"); + expect(h).not.toHaveBeenCalled(); + cleanup(); + }); + + test("cleanup removes the window keyup listener with matching capture flag", () => { + const scope = document.createElement("div"); + const addW = vi.spyOn(window, "addEventListener"); + const remW = vi.spyOn(window, "removeEventListener"); + const addS = vi.spyOn(scope, "addEventListener"); + const remS = vi.spyOn(scope, "removeEventListener"); + const registry = makeShortcutRegistry({ scope }); + registry.register({ keys: "a", handler: () => {} }); + registry.clear(); + const up = (m: typeof addW) => m.mock.calls.filter(c => c[0] === "keyup"); + expect(up(addW).length).toBe(1); + expect(up(remW).length).toBe(1); + expect(up(remW)[0]![2]).toBe(up(addW)[0]![2]); + expect(up(addW)[0]![2]).toBe(true); + expect(addS.mock.calls.map(c => c[0]).sort()).toEqual(remS.mock.calls.map(c => c[0]).sort()); + press("a"); + vi.restoreAllMocks(); + }); + }); + + describe("changing key values between keydown and keyup", () => { + test("Shift+1: releasing Shift first, then the digit", () => { + const registry = makeShortcutRegistry(); + const h = vi.fn(); + registry.register({ keys: "a", handler: h }); + fire(window, "Shift", "keydown", { code: "ShiftLeft", shiftKey: true }); + fire(window, "!", "keydown", { code: "Digit1", shiftKey: true }); + fire(window, "Shift", "keyup", { code: "ShiftLeft" }); + fire(window, "1", "keyup", { code: "Digit1" }); + press("a"); + expect(h).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("Shift+1: releasing the digit first, then Shift", () => { + const registry = makeShortcutRegistry(); + const h = vi.fn(); + registry.register({ keys: "a", handler: h }); + fire(window, "Shift", "keydown", { code: "ShiftLeft", shiftKey: true }); + fire(window, "!", "keydown", { code: "Digit1", shiftKey: true }); + fire(window, "!", "keyup", { code: "Digit1", shiftKey: true }); + fire(window, "Shift", "keyup", { code: "ShiftLeft" }); + press("a"); + expect(h).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("letters: Shift+A released as Shift first then a", () => { + const registry = makeShortcutRegistry(); + const h = vi.fn(); + registry.register({ keys: "b", handler: h }); + fire(window, "Shift", "keydown", { code: "ShiftLeft", shiftKey: true }); + fire(window, "A", "keydown", { code: "KeyA", shiftKey: true }); + fire(window, "Shift", "keyup", { code: "ShiftLeft" }); + fire(window, "a", "keyup", { code: "KeyA" }); + press("b"); + expect(h).toHaveBeenCalledTimes(1); + registry.clear(); + }); + + test("Meta keyup still clears everything", () => { + const registry = makeShortcutRegistry(); + const h = vi.fn(); + registry.register({ keys: "a", handler: h }); + fire(window, "Meta", "keydown", { code: "MetaLeft", metaKey: true }); + fire(window, "x", "keydown", { code: "KeyX", metaKey: true }); + fire(window, "Meta", "keyup", { code: "MetaLeft" }); // no keyup for x on macOS + press("a", { code: "KeyA" }); + expect(h).toHaveBeenCalledTimes(1); + registry.clear(); + }); + }); + + describe("cleanup", () => { + test("clear removes all listeners from scope and window", () => { + const scope = document.createElement("div"); + const addW = vi.spyOn(window, "addEventListener"); + const remW = vi.spyOn(window, "removeEventListener"); + const addS = vi.spyOn(scope, "addEventListener"); + const remS = vi.spyOn(scope, "removeEventListener"); + const registry = makeShortcutRegistry({ scope }); + registry.register({ keys: "a", handler: () => {} }); + registry.register({ keys: "b", handler: () => {} }); + registry.clear(); + expect(remS.mock.calls.map(c => c[0]).sort()).toEqual(addS.mock.calls.map(c => c[0]).sort()); + const added = addW.mock.calls.map(c => c[0]).filter(t => t === "blur" || t === "contextmenu"); + const removed = remW.mock.calls + .map(c => c[0]) + .filter(t => t === "blur" || t === "contextmenu"); + expect(removed.sort()).toEqual(added.sort()); + expect(added.length).toBe(2); + vi.restoreAllMocks(); + }); + + test("listeners are removed once the last shortcut is unregistered", () => { + const scope = document.createElement("div"); + const rem = vi.spyOn(scope, "removeEventListener"); + const registry = makeShortcutRegistry({ scope }); + const off1 = registry.register({ keys: "a", handler: () => {} }); + const off2 = registry.register({ keys: "b", handler: () => {} }); + off1(); + expect(rem).not.toHaveBeenCalled(); + off2(); + expect(rem).toHaveBeenCalledTimes(3); + vi.restoreAllMocks(); + }); + + test("is cleared when the owner is disposed", () => { + const h = vi.fn(); + const dispose = createRoot(d => { + makeShortcutRegistry().register({ keys: "a", handler: h }); + return d; + }); + press("a"); + expect(h).toHaveBeenCalledTimes(1); + dispose(); + press("a"); + expect(h).toHaveBeenCalledTimes(1); + }); + }); +}); + +describe("createShortcuts", () => { + test("list form", () => { + const h = vi.fn(); + const dispose = createRoot(d => { + createShortcuts([{ keys: "Control+s", handler: h }]); + return d; + }); + flush(); + press("s", { ctrlKey: true }); + expect(h).toHaveBeenCalledTimes(1); + dispose(); + press("s", { ctrlKey: true }); + expect(h).toHaveBeenCalledTimes(1); + }); + + test("map form with handler and options objects", () => { + const a = vi.fn(); + const b = vi.fn(); + const dispose = createRoot(d => { + createShortcuts({ "Control+a": a, x: { handler: b, preventDefault: false } }); + return d; + }); + flush(); + press("a", { ctrlKey: true }); + expect(press("x").defaultPrevented).toBe(false); + expect(a).toHaveBeenCalledTimes(1); + expect(b).toHaveBeenCalledTimes(1); + dispose(); + }); + + test("later entries win conflicts", () => { + const a = vi.fn(); + const b = vi.fn(); + const dispose = createRoot(d => { + createShortcuts([ + { keys: "m", handler: a }, + { keys: "m", handler: b }, + ]); + return d; + }); + flush(); + press("m"); + expect(a).not.toHaveBeenCalled(); + expect(b).toHaveBeenCalledTimes(1); + dispose(); + }); + + test("accessor of shortcuts re-registers when it changes", () => { + const [list, setList] = createSignal([]); + const a = vi.fn(); + const b = vi.fn(); + const dispose = createRoot(d => { + createShortcuts(list); + return d; + }); + flush(); + press("a"); + setList([{ keys: "a", handler: a }]); + flush(); + press("a"); + expect(a).toHaveBeenCalledTimes(1); + setList([{ keys: "b", handler: b }]); + flush(); + press("a"); + press("b"); + expect(a).toHaveBeenCalledTimes(1); + expect(b).toHaveBeenCalledTimes(1); + dispose(); + }); + + test("reactive scope accessor moves the listeners", () => { + const s1 = document.createElement("div"); + const s2 = document.createElement("div"); + const [scope, setScope] = createSignal(s1); + const h = vi.fn(); + const dispose = createRoot(d => { + createShortcuts([{ keys: "a", handler: h }], { scope }); + return d; + }); + flush(); + press("a", {}, s1); + expect(h).toHaveBeenCalledTimes(1); + setScope(s2); + flush(); + press("a", {}, s1); + press("a", {}, s2); + expect(h).toHaveBeenCalledTimes(2); + dispose(); + }); + + test("enabled accessor per shortcut", () => { + const [on, setOn] = createSignal(false); + const h = vi.fn(); + const dispose = createRoot(d => { + createShortcuts([{ keys: "a", handler: h, enabled: on }]); + return d; + }); + flush(); + press("a"); + expect(h).not.toHaveBeenCalled(); + setOn(true); + flush(); + press("a"); + expect(h).toHaveBeenCalledTimes(1); + dispose(); + }); + + test("disposal removes listeners (no leaks)", () => { + const rem = vi.spyOn(window, "removeEventListener"); + const add = vi.spyOn(window, "addEventListener"); + const dispose = createRoot(d => { + createShortcuts([{ keys: "a", handler: () => {} }]); + return d; + }); + flush(); + const added = add.mock.calls.filter(c => c[0] === "keydown").length; + dispose(); + expect(rem.mock.calls.filter(c => c[0] === "keydown").length).toBe(added); + vi.restoreAllMocks(); + }); +}); diff --git a/packages/post-message/CHANGELOG.md b/packages/post-message/CHANGELOG.md new file mode 100644 index 000000000..1c61ee7d3 --- /dev/null +++ b/packages/post-message/CHANGELOG.md @@ -0,0 +1 @@ +# @solid-primitives/post-message diff --git a/packages/post-message/LICENSE b/packages/post-message/LICENSE new file mode 100644 index 000000000..38b41d975 --- /dev/null +++ b/packages/post-message/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Solid Primitives Working Group + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/packages/post-message/README.md b/packages/post-message/README.md new file mode 100644 index 000000000..a3d16ed65 --- /dev/null +++ b/packages/post-message/README.md @@ -0,0 +1,103 @@ +

+ Solid Primitives post-message +

+ +# @solid-primitives/post-message + +[![docs](https://img.shields.io/badge/-docs-blue?style=for-the-badge)](https://primitives.solidjs.community/package/post-message) +[![version](https://img.shields.io/npm/v/@solid-primitives/post-message?style=for-the-badge)](https://www.npmjs.com/package/@solid-primitives/post-message) +[![stage](https://img.shields.io/endpoint?style=for-the-badge&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-0.json)](https://github.com/solidjs-community/solid-primitives#contribution-process) +[![tested with vitest](https://img.shields.io/badge/tested_with-vitest-6E9F18?style=for-the-badge&logo=vitest)](https://vitest.dev) + +Secure messaging between windows, iframes and `MessagePort`s, with origin, source and channel checks. Built for cases like an editor talking to a preview iframe. + +- **`makePostMessage`** — non-reactive channel; call `close()` to clean up. +- **`createPostMessage`** — reactive channel; the target can be an accessor, it is torn down with the owner, and it returns inert stubs on the server. + +Security defaults: + +- Messages from a window or iframe are accepted only when `event.source` is the target window **and** `event.origin` is in `allowedOrigins`. An empty list accepts nothing; `"*"` only applies if you list it. +- Sending to a window requires an explicit `targetOrigin`. There is no `"*"` default; omitting it throws a `TypeError` (and is a type error). +- `validate` drops anything that is not the shape you expect and narrows the type of incoming data. +- `channel` wraps outgoing data in an envelope and ignores messages that do not carry the same channel, so unrelated traffic never reaches your handlers. +- `MessagePort`s have no origin; the port itself is the trust boundary. `close()` stops listening but does not close the port. + +## Installation + +```bash +npm install @solid-primitives/post-message +# or +yarn add @solid-primitives/post-message +# or +pnpm add @solid-primitives/post-message +``` + +## `makePostMessage` + +```ts +// Type +function makePostMessage( + target: Window | HTMLIFrameElement, + options: { + allowedOrigins: readonly string[]; + targetOrigin: string; + validate?: (data: unknown) => data is TIn; + channel?: string; + receiver?: Window; // where "message" events arrive, defaults to window + }, +): { + send: (data: TOut, transfer?: Transferable[]) => boolean; + onMessage: (listener: (data: TIn, event: MessageEvent) => void) => () => void; + close: () => void; +}; +// MessagePort targets: options are optional and only validate/channel apply +function makePostMessage(target: MessagePort, options?: { validate?; channel? }): /* same */; + +// Example +const origin = "https://preview.example.com"; +const channel = makePostMessage<{ type: "ready" }, { code: string }>(iframe, { + allowedOrigins: [origin], + targetOrigin: origin, + channel: "editor", + validate: (d): d is { type: "ready" } => (d as any)?.type === "ready", +}); +channel.onMessage(msg => console.log(msg.type)); +channel.send({ code: "console.log(1)" }); +channel.close(); +``` + +An iframe is resolved to its `contentWindow` each time it is needed, so navigations and late loads work. `send` returns `false` when there is nothing to send to (closed handle, iframe without a window). + +## `createPostMessage` + +```ts +// Type +function createPostMessage( + options: /* same options as makePostMessage */ & { + target: MaybeAccessor; + }, +): { + message: Accessor; // latest accepted message + send: (data: TOut, transfer?: Transferable[]) => boolean; + onMessage: (listener: (data: TIn, event: MessageEvent) => void) => () => void; + close: () => void; +}; + +// Example +const [iframe, setIframe] = createSignal(); +const { send, message } = createPostMessage({ + target: iframe, + allowedOrigins: [origin], + targetOrigin: origin, + validate: isReply, +}); + +