From 0e88ead187715690e4d4d45a09906e9b84f45858 Mon Sep 17 00:00:00 2001 From: David Di Biase <1168397+davedbase@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:08:02 -0500 Subject: [PATCH 01/11] feat: add inert, dismissable, floating and post-message packages New stage-0 packages covering overlay/layer primitives that UI libraries otherwise hand-roll: aria-hidden/inert for content outside a modal layer, a dismissable layer stack, floating positioning and origin-checked postMessage channels. Co-Authored-By: Claude Sonnet 5.5 --- .changeset/dismissable-layer-stack.md | 7 + .changeset/inert-new-package.md | 5 + .changeset/new-floating-package.md | 5 + .changeset/post-message-initial.md | 5 + packages/dismissable/CHANGELOG.md | 1 + packages/dismissable/LICENSE | 21 + packages/dismissable/README.md | 127 ++++ packages/dismissable/deno.jsonc | 11 + packages/dismissable/dev/index.tsx | 50 ++ packages/dismissable/package.json | 79 +++ packages/dismissable/src/dismissable.ts | 225 +++++++ packages/dismissable/src/index.ts | 9 + packages/dismissable/src/layer-stack.ts | 142 +++++ .../stories/dismissable.stories.tsx | 90 +++ packages/dismissable/test/index.test.ts | 517 ++++++++++++++++ packages/dismissable/test/server.test.ts | 33 + packages/dismissable/tsconfig.json | 4 + packages/floating/CHANGELOG.md | 1 + packages/floating/LICENSE | 21 + packages/floating/README.md | 256 ++++++++ packages/floating/deno.jsonc | 11 + packages/floating/dev/index.tsx | 80 +++ packages/floating/package.json | 79 +++ packages/floating/src/autoUpdate.ts | 124 ++++ packages/floating/src/compute.ts | 439 ++++++++++++++ packages/floating/src/css.ts | 25 + packages/floating/src/floating.ts | 201 ++++++ packages/floating/src/index.ts | 16 + packages/floating/src/types.ts | 134 ++++ .../floating/stories/floating.stories.tsx | 75 +++ packages/floating/test/autoUpdate.test.ts | 262 ++++++++ packages/floating/test/compute.test.ts | 570 ++++++++++++++++++ packages/floating/test/css.test.ts | 28 + packages/floating/test/floating.test.ts | 413 +++++++++++++ packages/floating/test/helpers.ts | 35 ++ packages/floating/test/server.test.ts | 62 ++ packages/floating/tsconfig.json | 4 + packages/inert/CHANGELOG.md | 1 + packages/inert/LICENSE | 21 + packages/inert/README.md | 88 +++ packages/inert/deno.jsonc | 11 + packages/inert/dev/index.tsx | 24 + packages/inert/package.json | 74 +++ packages/inert/src/index.ts | 1 + packages/inert/src/inert.ts | 271 +++++++++ packages/inert/stories/inert.stories.tsx | 37 ++ packages/inert/test/index.test.ts | 447 ++++++++++++++ packages/inert/test/server.test.ts | 21 + packages/inert/tsconfig.json | 4 + packages/post-message/CHANGELOG.md | 1 + packages/post-message/LICENSE | 21 + packages/post-message/README.md | 103 ++++ packages/post-message/deno.jsonc | 11 + packages/post-message/dev/index.tsx | 33 + packages/post-message/package.json | 73 +++ packages/post-message/src/index.ts | 13 + packages/post-message/src/post-message.ts | 257 ++++++++ .../stories/post-message.stories.tsx | 58 ++ packages/post-message/test/index.test.ts | 343 +++++++++++ packages/post-message/test/server.test.ts | 22 + packages/post-message/tsconfig.json | 4 + 61 files changed, 6106 insertions(+) create mode 100644 .changeset/dismissable-layer-stack.md create mode 100644 .changeset/inert-new-package.md create mode 100644 .changeset/new-floating-package.md create mode 100644 .changeset/post-message-initial.md create mode 100644 packages/dismissable/CHANGELOG.md create mode 100644 packages/dismissable/LICENSE create mode 100644 packages/dismissable/README.md create mode 100644 packages/dismissable/deno.jsonc create mode 100644 packages/dismissable/dev/index.tsx create mode 100644 packages/dismissable/package.json create mode 100644 packages/dismissable/src/dismissable.ts create mode 100644 packages/dismissable/src/index.ts create mode 100644 packages/dismissable/src/layer-stack.ts create mode 100644 packages/dismissable/stories/dismissable.stories.tsx create mode 100644 packages/dismissable/test/index.test.ts create mode 100644 packages/dismissable/test/server.test.ts create mode 100644 packages/dismissable/tsconfig.json create mode 100644 packages/floating/CHANGELOG.md create mode 100644 packages/floating/LICENSE create mode 100644 packages/floating/README.md create mode 100644 packages/floating/deno.jsonc create mode 100644 packages/floating/dev/index.tsx create mode 100644 packages/floating/package.json create mode 100644 packages/floating/src/autoUpdate.ts create mode 100644 packages/floating/src/compute.ts create mode 100644 packages/floating/src/css.ts create mode 100644 packages/floating/src/floating.ts create mode 100644 packages/floating/src/index.ts create mode 100644 packages/floating/src/types.ts create mode 100644 packages/floating/stories/floating.stories.tsx create mode 100644 packages/floating/test/autoUpdate.test.ts create mode 100644 packages/floating/test/compute.test.ts create mode 100644 packages/floating/test/css.test.ts create mode 100644 packages/floating/test/floating.test.ts create mode 100644 packages/floating/test/helpers.ts create mode 100644 packages/floating/test/server.test.ts create mode 100644 packages/floating/tsconfig.json create mode 100644 packages/inert/CHANGELOG.md create mode 100644 packages/inert/LICENSE create mode 100644 packages/inert/README.md create mode 100644 packages/inert/deno.jsonc create mode 100644 packages/inert/dev/index.tsx create mode 100644 packages/inert/package.json create mode 100644 packages/inert/src/index.ts create mode 100644 packages/inert/src/inert.ts create mode 100644 packages/inert/stories/inert.stories.tsx create mode 100644 packages/inert/test/index.test.ts create mode 100644 packages/inert/test/server.test.ts create mode 100644 packages/inert/tsconfig.json create mode 100644 packages/post-message/CHANGELOG.md create mode 100644 packages/post-message/LICENSE create mode 100644 packages/post-message/README.md create mode 100644 packages/post-message/deno.jsonc create mode 100644 packages/post-message/dev/index.tsx create mode 100644 packages/post-message/package.json create mode 100644 packages/post-message/src/index.ts create mode 100644 packages/post-message/src/post-message.ts create mode 100644 packages/post-message/stories/post-message.stories.tsx create mode 100644 packages/post-message/test/index.test.ts create mode 100644 packages/post-message/test/server.test.ts create mode 100644 packages/post-message/tsconfig.json diff --git a/.changeset/dismissable-layer-stack.md b/.changeset/dismissable-layer-stack.md new file mode 100644 index 000000000..153051f93 --- /dev/null +++ b/.changeset/dismissable-layer-stack.md @@ -0,0 +1,7 @@ +--- +"@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. diff --git a/.changeset/inert-new-package.md b/.changeset/inert-new-package.md new file mode 100644 index 000000000..d37c3f51b --- /dev/null +++ b/.changeset/inert-new-package.md @@ -0,0 +1,5 @@ +--- +"@solid-primitives/inert": minor +--- + +Add `@solid-primitives/inert` with `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. diff --git a/.changeset/new-floating-package.md b/.changeset/new-floating-package.md new file mode 100644 index 000000000..35251b505 --- /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. diff --git a/.changeset/post-message-initial.md b/.changeset/post-message-initial.md new file mode 100644 index 000000000..6efde7dbf --- /dev/null +++ b/.changeset/post-message-initial.md @@ -0,0 +1,5 @@ +--- +"@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. diff --git a/packages/dismissable/CHANGELOG.md b/packages/dismissable/CHANGELOG.md new file mode 100644 index 000000000..a93cbc15c --- /dev/null +++ b/packages/dismissable/CHANGELOG.md @@ -0,0 +1 @@ +# @solid-primitives/dismissable diff --git a/packages/dismissable/LICENSE b/packages/dismissable/LICENSE new file mode 100644 index 000000000..38b41d975 --- /dev/null +++ b/packages/dismissable/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/dismissable/README.md b/packages/dismissable/README.md new file mode 100644 index 000000000..ea9b18a4d --- /dev/null +++ b/packages/dismissable/README.md @@ -0,0 +1,127 @@ +

+ Solid Primitives dismissable +

+ +# @solid-primitives/dismissable + +[![docs](https://img.shields.io/badge/-docs-blue?style=for-the-badge)](https://primitives.solidjs.community/package/dismissable) +[![version](https://img.shields.io/npm/v/@solid-primitives/dismissable?style=for-the-badge)](https://www.npmjs.com/package/@solid-primitives/dismissable) +[![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) + +Dismissable layers (dialogs, popovers, menus) that share one layer stack, so Escape and outside presses always close the topmost layer first. + +- **`makeDismissableLayer`** — non-reactive layer registration, returns `{ dismiss, cleanup, layer }`. +- **`createDismissableLayer`** — reactive layer, registers when `ref` resolves and unregisters on cleanup. +- **`getLayerStack` / `useLayerStack` / `getTopLayer` / `isTopLayer`** — read the shared stack. + +Outside press and outside focus detection is delegated to [`@solid-primitives/interaction`](../interaction#readme) (`makeInteractOutside`, shadow-DOM aware, touch-safe); the Escape listener uses [`@solid-primitives/event-listener`](../event-listener#readme). + +## Installation + +```bash +npm install @solid-primitives/dismissable +# or +yarn add @solid-primitives/dismissable +# or +pnpm add @solid-primitives/dismissable +``` + +## How the stack works + +- Layers are pushed on registration and removed on cleanup, in any order. +- Only the **topmost non-persistent** layer reacts to Escape, an outside pointer press and outside focus. Nested layers therefore close one at a time, even if a handler removes its layer synchronously. +- A press inside any layer opened after a layer (or registered with it as `parent`) is never "outside" that layer, so portaled children do not dismiss their parent. +- A **persistent** layer stays in the stack but is never auto-dismissed and never steals the top position. +- When a layer is not `dismissible`, the request goes to `onDismissAttempt` and does **not** fall through to the layer below. + +Dismiss reasons: `"escape" | "outside-pointer" | "outside-focus" | "programmatic"`. + +## `makeDismissableLayer` + +```ts +// Type +function makeDismissableLayer(options: { + element: Element; + onDismiss: (reason: DismissReason, event?: Event) => void; + dismissible?: boolean | (() => boolean | undefined); + onDismissAttempt?: (reason: DismissReason, event?: Event) => void; + exclude?: Element | readonly Element[] | ((element: Element) => boolean); + persistent?: boolean | (() => boolean | undefined); + disableOutsidePointerEvents?: boolean; + parent?: DismissableLayer; +}): { + dismiss: (reason?: DismissReason, event?: Event) => void; // defaults to "programmatic" + cleanup: () => void; // idempotent + layer: DismissableLayer; +}; + +// Example +import { makeDismissableLayer } from "@solid-primitives/dismissable"; + +const { cleanup } = makeDismissableLayer({ + element: dialogEl, + onDismiss: reason => closeDialog(reason), +}); +// later +cleanup(); +``` + +## `createDismissableLayer` + +Same options, with `ref` (an element or an accessor, e.g. a ref signal) instead of `element`. The layer registers once `ref` resolves, re-registers if it changes, and unregisters when the owner is disposed. `dismissible`, `persistent` and the callbacks are read when needed, so changing them does not re-register the layer (the stack position is kept). + +```ts +// Type +function createDismissableLayer(options: Omit & { + ref: Element | null | undefined | (() => Element | null | undefined); +}): { + dismiss: (reason?: DismissReason, event?: Event) => void; + isTop: () => boolean; +}; + +// Example +import { createSignal } from "solid-js"; +import { createDismissableLayer } from "@solid-primitives/dismissable"; + +function Dialog(props: { onClose: () => void }) { + const [el, setEl] = createSignal(); + const [shake, setShake] = createSignal(false); + + createDismissableLayer({ + ref: el, + onDismiss: () => props.onClose(), + dismissible: () => !busy(), + onDismissAttempt: () => setShake(true), // dismiss requested while not dismissible + exclude: triggerEl, // pressing the trigger is not an outside press + }); + + return
; +} +``` + +## Layer stack helpers + +```ts +// Type +function getLayerStack(): DismissableLayer[]; // bottom (oldest) first +function useLayerStack(): () => readonly DismissableLayer[]; // reactive +function getTopLayer(): DismissableLayer | undefined; // topmost non-persistent layer +function isTopLayer(layer: DismissableLayer): boolean; + +// Example +import { useLayerStack } from "@solid-primitives/dismissable"; + +const stack = useLayerStack(); +const hasOpenLayers = () => stack().length > 0; +``` + +### Notes + +- `disableOutsidePointerEvents` sets `pointer-events: none` on `document.body` while any such layer is registered and `auto` on the layers at or above it; previous values are restored when the last one is removed. +- Listeners are attached on the next tick (by `makeInteractOutside`) so the event that opened a layer does not immediately dismiss it. +- On the server, everything is a no-op: layers are not registered and the stack is always empty. + +## Changelog + +See [CHANGELOG.md](./CHANGELOG.md) diff --git a/packages/dismissable/deno.jsonc b/packages/dismissable/deno.jsonc new file mode 100644 index 000000000..f101461b1 --- /dev/null +++ b/packages/dismissable/deno.jsonc @@ -0,0 +1,11 @@ +{ + "name": "@solid-primitives/dismissable", + "version": "0.0.1", + "description": "Dismissable layers with a shared layer stack — Escape, outside press and outside focus handling", + "license": "MIT", + "exports": "./src/index.ts", + "publish": { + "include": ["README.md", "LICENSE", "src/**/*.ts", "src/**/*.tsx", "package.json"], + "exclude": ["dist", "dev", "test", "node_modules", "vitest.config.ts", "tsconfig.json"], + }, +} diff --git a/packages/dismissable/dev/index.tsx b/packages/dismissable/dev/index.tsx new file mode 100644 index 000000000..2e0a7bb5d --- /dev/null +++ b/packages/dismissable/dev/index.tsx @@ -0,0 +1,50 @@ +import { type Component, createSignal } from "solid-js"; +import { Show } from "@solidjs/web"; +import { createDismissableLayer, useLayerStack } from "../src/index.js"; + +const Panel: Component<{ title: string; onClose: () => void; children?: any }> = props => { + const [el, setEl] = createSignal(); + const [shake, setShake] = createSignal(false); + const { isTop } = createDismissableLayer({ + ref: el, + onDismiss: () => props.onClose(), + }); + return ( +
setShake(false)} + > +

{props.title}

+ {props.children} +
+ ); +}; + +const App: Component = () => { + const [outer, setOuter] = createSignal(false); + const [inner, setInner] = createSignal(false); + const stack = useLayerStack(); + + return ( +
+

Layers: {stack().length} — Escape / outside press closes the top one.

+ + + setOuter(false)}> + + + setInner(false)} /> + + + +
+ ); +}; + +export default App; diff --git a/packages/dismissable/package.json b/packages/dismissable/package.json new file mode 100644 index 000000000..687d2e857 --- /dev/null +++ b/packages/dismissable/package.json @@ -0,0 +1,79 @@ +{ + "name": "@solid-primitives/dismissable", + "version": "0.0.1", + "description": "Dismissable layers with a shared layer stack — Escape, outside press and outside focus handling", + "author": "David Di Biase ", + "contributors": [], + "license": "MIT", + "homepage": "https://primitives.solidjs.community/package/dismissable", + "repository": { + "type": "git", + "url": "git+https://github.com/solidjs-community/solid-primitives.git" + }, + "bugs": { + "url": "https://github.com/solidjs-community/solid-primitives/issues" + }, + "primitive": { + "name": "dismissable", + "stage": 0, + "list": [ + "makeDismissableLayer", + "createDismissableLayer", + "getLayerStack", + "useLayerStack", + "isTopLayer", + "getTopLayer" + ], + "category": "UI Patterns", + "gzip": 2557 + }, + "keywords": [ + "solid", + "primitives", + "dismissable", + "layer", + "overlay", + "escape", + "outside", + "click-outside" + ], + "private": false, + "sideEffects": false, + "files": [ + "dist" + ], + "type": "module", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "browser": {}, + "exports": { + "import": { + "@solid-primitives/source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "typesVersions": {}, + "tsdown": { + "entry": "src/**/*.{ts,tsx}", + "outDir": "dist" + }, + "scripts": { + "dev": "node --import=@nothing-but/node-resolve-ts ../../scripts/dev.ts", + "build": "pnpm -w build", + "vitest": "vitest -c ../../configs/vitest.config.ts", + "test": "pnpm run vitest", + "test:ssr": "pnpm run vitest --mode ssr" + }, + "dependencies": { + "@solid-primitives/event-listener": "workspace:^", + "@solid-primitives/interaction": "workspace:^", + "@solid-primitives/utils": "workspace:^" + }, + "peerDependencies": { + "solid-js": "catalog:peer" + }, + "devDependencies": { + "solid-js": "catalog:peer" + } +} diff --git a/packages/dismissable/src/dismissable.ts b/packages/dismissable/src/dismissable.ts new file mode 100644 index 000000000..f332cd46f --- /dev/null +++ b/packages/dismissable/src/dismissable.ts @@ -0,0 +1,225 @@ +import { createEffect, createMemo, type Accessor } from "solid-js"; +import { isServer } from "@solidjs/web"; +import { access, noop, type MaybeAccessor } from "@solid-primitives/utils"; +import { makeEventListener } from "@solid-primitives/event-listener"; +import { makeInteractOutside } from "@solid-primitives/interaction"; +import { + getTopLayer, + isInsideLayer, + registerLayer, + useLayerStack, + type DismissableLayer, + type DismissReason, + type LayerRecord, +} from "./layer-stack.ts"; + +/** Which elements an outside press / focus should be ignored for. */ +export type DismissableExclude = Element | readonly Element[] | ((element: Element) => boolean); + +export interface DismissableLayerOptions { + /** Called when the layer should close. The layer is not removed from the stack automatically. */ + onDismiss: (reason: DismissReason, event?: Event) => void; + /** + * Whether the layer may be dismissed. When `false`, a dismiss request calls + * {@link DismissableLayerOptions.onDismissAttempt} instead of `onDismiss`. Default: `true`. + */ + dismissible?: MaybeAccessor; + /** + * Called when a dismiss was requested while `dismissible` is `false` — e.g. to shake the dialog. + * Only the topmost layer is ever asked, so it fires once per request. + */ + onDismissAttempt?: (reason: DismissReason, event?: Event) => void; + /** Elements (or a predicate) whose presses / focus must not count as outside, e.g. the trigger. */ + exclude?: DismissableExclude; + /** + * A persistent layer stays registered (so content inside it is never "outside" its parents) but + * is never auto-dismissed and does not take over Escape / outside presses from the layer below. + * Programmatic `dismiss()` still works. + */ + persistent?: MaybeAccessor; + /** Disable pointer events on everything outside the layer (and layers below) while registered. */ + disableOutsidePointerEvents?: boolean; + /** + * Register this layer as a descendant of `parent`: presses inside it never dismiss `parent`, + * even if it is portaled elsewhere in the DOM. + */ + parent?: DismissableLayer | undefined; +} + +export interface MakeDismissableLayerOptions extends DismissableLayerOptions { + /** The layer's root element. */ + element: Element; +} + +export interface DismissableLayerControls { + /** Request dismissal. Respects `dismissible` (calls `onDismissAttempt` when it is `false`). */ + dismiss: (reason?: DismissReason, event?: Event) => void; + /** Remove the layer from the stack and detach all listeners. Idempotent. */ + cleanup: () => void; + /** The layer's handle, usable with {@link isTopLayer}. */ + layer: DismissableLayer; +} + +// An event may reach several layers' listeners (each layer listens on its own); the first layer to +// act on it wins, so a handler that removes its layer synchronously can't cascade to the parent. +const handled = new WeakSet(); + +const matchesExclude = (exclude: DismissableExclude | undefined, el: Element): boolean => { + if (!exclude) return false; + if (typeof exclude === "function") return exclude(el); + if (Array.isArray(exclude)) return (exclude as readonly Element[]).some(e => e.contains(el)); + return (exclude as Element).contains(el); +}; + +const serverLayer = (): DismissableLayerControls => ({ + dismiss: noop, + cleanup: noop, + layer: { + element: undefined as never, + parent: undefined, + persistent: false, + disableOutsidePointerEvents: false, + }, +}); + +/** + * Registers `element` as a dismissable layer on the shared layer stack. Only the topmost + * non-persistent layer reacts to Escape, an outside pointer press and focus moving outside. + * Outside detection is delegated to `makeInteractOutside` from `@solid-primitives/interaction`. + * + * @returns `dismiss` (programmatic request), `cleanup` (unregister and detach), and the `layer` handle. + */ +export function makeDismissableLayer( + options: MakeDismissableLayerOptions, +): DismissableLayerControls { + if (isServer) return serverLayer(); + + const { element } = options; + + const layer: LayerRecord = { + element, + parent: options.parent, + get persistent() { + return !!access(options.persistent); + }, + disableOutsidePointerEvents: !!options.disableOutsidePointerEvents, + }; + + const request = (reason: DismissReason, event?: Event) => { + if (access(options.dismissible) === false) options.onDismissAttempt?.(reason, event); + else options.onDismiss(reason, event); + }; + + /** Handles an automatic dismissal source, only for the layer that is currently on top. */ + const auto = (reason: DismissReason, event: Event) => { + if (handled.has(event) || getTopLayer() !== layer) return; + handled.add(event); + request(reason, event); + }; + + const unregister = registerLayer(layer); + + const stopEscape = makeEventListener( + element.ownerDocument, + "keydown", + (e: KeyboardEvent) => { + if (e.key !== "Escape" || e.isComposing) return; + auto("escape", e); + }, + { capture: true }, + ); + + const stopOutside = makeInteractOutside(element, { + shouldExcludeElement: el => matchesExclude(options.exclude, el) || isInsideLayer(layer, el), + onPointerDownOutside: e => auto("outside-pointer", e.detail.originalEvent), + onFocusOutside: e => auto("outside-focus", e.detail.originalEvent), + }); + + let cleaned = false; + const cleanup = () => { + if (cleaned) return; + cleaned = true; + stopEscape(); + stopOutside(); + unregister(); + }; + + return { + dismiss: (reason = "programmatic", event) => request(reason, event), + cleanup, + layer, + }; +} + +export interface CreateDismissableLayerOptions extends DismissableLayerOptions { + /** The layer's root element (or an accessor of it, e.g. a ref signal). Registered once defined. */ + ref: MaybeAccessor; +} + +export interface CreateDismissableLayerReturn { + /** Request dismissal of this layer. Respects `dismissible`. A no-op until the element exists. */ + dismiss: (reason?: DismissReason, event?: Event) => void; + /** Whether this layer is currently the one reacting to Escape / outside presses. */ + isTop: Accessor; +} + +/** + * Reactive {@link makeDismissableLayer}: registers the layer when `ref` resolves to an element, + * re-registers if the element changes, and unregisters on cleanup. On the server it is a no-op. + * + * @example + * ```tsx + * const [el, setEl] = createSignal(); + * createDismissableLayer({ ref: el, onDismiss: () => setOpen(false) }); + * return
…
; + * ``` + */ +export function createDismissableLayer( + options: CreateDismissableLayerOptions, +): CreateDismissableLayerReturn { + if (isServer) return { dismiss: noop, isTop: () => false }; + + let current: DismissableLayerControls | undefined; + const stack = useLayerStack(); + + createEffect( + () => access(options.ref) ?? undefined, + el => { + if (!el) return; + const controls = makeDismissableLayer({ + element: el, + get onDismiss() { + return options.onDismiss; + }, + get onDismissAttempt() { + return options.onDismissAttempt; + }, + get dismissible() { + return options.dismissible; + }, + get exclude() { + return options.exclude; + }, + get persistent() { + return options.persistent; + }, + get parent() { + return options.parent; + }, + disableOutsidePointerEvents: options.disableOutsidePointerEvents, + } as MakeDismissableLayerOptions); + current = controls; + return () => { + controls.cleanup(); + if (current === controls) current = undefined; + }; + }, + ); + + const isTop = createMemo(() => { + stack(); + return !!current && getTopLayer() === current.layer; + }); + + return { dismiss: (reason, event) => current?.dismiss(reason, event), isTop }; +} diff --git a/packages/dismissable/src/index.ts b/packages/dismissable/src/index.ts new file mode 100644 index 000000000..78e5b256b --- /dev/null +++ b/packages/dismissable/src/index.ts @@ -0,0 +1,9 @@ +export { + getLayerStack, + useLayerStack, + getTopLayer, + isTopLayer, + type DismissReason, + type DismissableLayer, +} from "./layer-stack.ts"; +export * from "./dismissable.ts"; diff --git a/packages/dismissable/src/layer-stack.ts b/packages/dismissable/src/layer-stack.ts new file mode 100644 index 000000000..d07b90ee5 --- /dev/null +++ b/packages/dismissable/src/layer-stack.ts @@ -0,0 +1,142 @@ +import { createSignal, type Accessor } from "solid-js"; +import { isServer } from "@solidjs/web"; + +/** Why a dismissable layer is being asked to close. */ +export type DismissReason = "escape" | "outside-pointer" | "outside-focus" | "programmatic"; + +/** + * A layer registered in the shared layer stack. Instances are created by + * {@link makeDismissableLayer} / {@link createDismissableLayer}; treat them as opaque handles. + */ +export interface DismissableLayer { + /** The layer's root element. */ + readonly element: Element; + /** A layer that is registered as the parent of this one (e.g. the dialog that opened a portaled popover). */ + readonly parent: DismissableLayer | undefined; + /** A persistent layer stays in the stack but is never the layer that reacts to Escape / outside presses. */ + readonly persistent: boolean; + /** Whether this layer disables pointer events outside of itself while registered. */ + readonly disableOutsidePointerEvents: boolean; +} + +/** Internal: layer data the stack needs but consumers should not see. */ +export interface LayerRecord extends DismissableLayer { + prevPointerEvents?: string | undefined; +} + +const layers: LayerRecord[] = []; + +// `useLayerStack` is a reactive view of `layers`; created lazily on the client only. +let stackSignal: [Accessor, (v: readonly DismissableLayer[]) => void]; +const getSignal = () => + (stackSignal ??= createSignal([], { + ownedWrite: true, + }) as unknown as typeof stackSignal); + +const notify = () => getSignal()[1](layers.slice()); + +let bodyPointerEvents: string | undefined; +let bodyLocked = false; + +function updatePointerEvents(): void { + const firstDisabling = layers.findIndex(l => l.disableOutsidePointerEvents); + const doc = + layers[0]?.element.ownerDocument ?? (typeof document !== "undefined" ? document : undefined); + const body = doc?.body; + if (firstDisabling === -1) { + if (bodyLocked && body) { + body.style.pointerEvents = bodyPointerEvents ?? ""; + } + bodyLocked = false; + bodyPointerEvents = undefined; + } else if (body) { + if (!bodyLocked) { + bodyPointerEvents = body.style.pointerEvents; + bodyLocked = true; + } + body.style.pointerEvents = "none"; + } + // Layers at or above the lowest disabling layer must stay interactive. + layers.forEach((layer, i) => { + const el = layer.element as HTMLElement; + if (!el.style) return; + if (firstDisabling !== -1 && i >= firstDisabling) { + if (layer.prevPointerEvents === undefined) layer.prevPointerEvents = el.style.pointerEvents; + el.style.pointerEvents = "auto"; + } else if (layer.prevPointerEvents !== undefined) { + el.style.pointerEvents = layer.prevPointerEvents; + layer.prevPointerEvents = undefined; + } + }); +} + +/** @internal Adds a layer to the top of the stack. Returns a function removing it (idempotent, any order). */ +export function registerLayer(layer: LayerRecord): () => void { + if (isServer) return () => {}; + layers.push(layer); + updatePointerEvents(); + notify(); + return () => { + const i = layers.indexOf(layer); + if (i === -1) return; + layers.splice(i, 1); + // restore this layer's own element before recomputing the others + const el = layer.element as HTMLElement; + if (layer.prevPointerEvents !== undefined && el.style) { + el.style.pointerEvents = layer.prevPointerEvents; + layer.prevPointerEvents = undefined; + } + updatePointerEvents(); + notify(); + }; +} + +/** A snapshot of the layer stack, bottom (oldest) first. Empty on the server. */ +export function getLayerStack(): DismissableLayer[] { + return layers.slice(); +} + +/** A reactive accessor of the layer stack, bottom (oldest) first. Always `[]` on the server. */ +export function useLayerStack(): Accessor { + if (isServer) return () => []; + return getSignal()[0]; +} + +/** + * The topmost non-persistent layer: the only one that reacts to Escape, outside presses and + * outside focus. `undefined` when there is none. + */ +export function getTopLayer(): DismissableLayer | undefined { + for (let i = layers.length - 1; i >= 0; i--) if (!layers[i]!.persistent) return layers[i]; + return undefined; +} + +/** Whether `layer` is the topmost non-persistent layer (see {@link getTopLayer}). */ +export function isTopLayer(layer: DismissableLayer): boolean { + return getTopLayer() === layer; +} + +/** `true` if `ancestor` is `layer` or one of its registered `parent`s. */ +function isSelfOrAncestor( + ancestor: DismissableLayer, + layer: DismissableLayer | undefined, +): boolean { + for (let l = layer; l; l = l.parent) if (l === ancestor) return true; + return false; +} + +/** + * Whether `target` lies inside `layer`, or inside a layer that belongs to it: any layer opened + * after it (above it in the stack), or one registered with it as an ancestor `parent`. Portaled + * children therefore never read as "outside" their parent. + */ +export function isInsideLayer(layer: DismissableLayer, target: Node): boolean { + if (layer.element.contains(target)) return true; + const index = layers.indexOf(layer as LayerRecord); + return layers.some( + (other, i) => + other !== layer && + (i > index || isSelfOrAncestor(layer, other.parent)) && + other.element.contains(target), + ); +} diff --git a/packages/dismissable/stories/dismissable.stories.tsx b/packages/dismissable/stories/dismissable.stories.tsx new file mode 100644 index 000000000..6249b4736 --- /dev/null +++ b/packages/dismissable/stories/dismissable.stories.tsx @@ -0,0 +1,90 @@ +import { createSignal } from "solid-js"; +import { Show } from "@solidjs/web"; +import preview from "../../../.storybook/preview.js"; +import { createDismissableLayer, useLayerStack } from "../src/index.js"; +import readme from "../README.md?raw"; +import { Button, Container, EventLog, StatRow } from "../../../.storybook/ui/index.js"; + +const meta = preview.meta({ + title: "UI Patterns/Dismissable", + tags: ["autodocs"], + parameters: { + layout: "centered", + docs: { description: { component: readme } }, + }, +}); + +export default meta; + +export const NestedLayers = meta.story({ + name: "Nested layers", + parameters: { + docs: { + description: { + story: + "Escape and outside presses dismiss only the topmost layer. The inner layer can be made non-dismissible; the attempt is reported instead of closing it.", + }, + }, + }, + render: () => { + const [outer, setOuter] = createSignal(false); + const [inner, setInner] = createSignal(false); + const [locked, setLocked] = createSignal(false); + const [log, setLog] = createSignal([]); + const stack = useLayerStack(); + const push = (m: string) => setLog(l => [m, ...l].slice(0, 8)); + + const Layer = (p: { + name: string; + close: () => void; + dismissible?: () => boolean; + children?: any; + }) => { + const [el, setEl] = createSignal(); + createDismissableLayer({ + ref: el, + onDismiss: reason => { + push(`${p.name}: dismissed (${reason})`); + p.close(); + }, + ...(p.dismissible && { dismissible: p.dismissible }), + onDismissAttempt: reason => push(`${p.name}: blocked (${reason})`), + }); + return ( +
+ {p.name} + {p.children} +
+ ); + }; + + return ( + + + + + setOuter(false)}> +
+ + + + setInner(false)} dismissible={() => !locked()} /> + +
+
+
+ ({ label, time: "" }))} /> +
+ ); + }, +}); diff --git a/packages/dismissable/test/index.test.ts b/packages/dismissable/test/index.test.ts new file mode 100644 index 000000000..6537d4304 --- /dev/null +++ b/packages/dismissable/test/index.test.ts @@ -0,0 +1,517 @@ +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { createRoot, createSignal, flush } from "solid-js"; +import { + createDismissableLayer, + getLayerStack, + getTopLayer, + isTopLayer, + makeDismissableLayer, + useLayerStack, + type DismissReason, +} from "../src/index.js"; + +beforeAll(() => { + if (!("PointerEvent" in window)) { + class MockPointerEvent extends MouseEvent { + readonly pointerId: number; + readonly pointerType: string; + constructor(type: string, init: PointerEventInit = {}) { + super(type, init); + this.pointerId = init.pointerId ?? 0; + this.pointerType = init.pointerType ?? "mouse"; + } + } + (global as unknown as Record)["PointerEvent"] = MockPointerEvent; + } +}); + +beforeEach(() => { + vi.useFakeTimers(); +}); + +const mount = (id: string, parent: Element = document.body) => { + const el = document.createElement("div"); + el.id = id; + el.tabIndex = 0; + parent.appendChild(el); + return el; +}; + +/** Listeners of `makeInteractOutside` register after a 0ms timeout. */ +const ready = () => vi.advanceTimersByTime(1); + +const press = (target: Element) => + target.dispatchEvent( + new PointerEvent("pointerdown", { bubbles: true, cancelable: true, pointerType: "mouse" }), + ); +const escape = (target: EventTarget = document.body) => + target.dispatchEvent( + new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }), + ); + +const cleanups: (() => void)[] = []; +afterEach(() => { + cleanups.splice(0).forEach(fn => fn()); + document.body.innerHTML = ""; + document.body.style.pointerEvents = ""; + vi.useRealTimers(); +}); + +function layerAt(el: Element, opts: Partial[0]> = {}) { + const onDismiss = vi.fn<(r: DismissReason, e?: Event) => void>(); + const controls = makeDismissableLayer({ element: el, onDismiss, ...opts }); + cleanups.push(controls.cleanup); + return { ...controls, onDismiss }; +} + +describe("layer stack", () => { + it("registers layers bottom-first and cleans up in any order", () => { + const [a, b, c] = [mount("a"), mount("b"), mount("c")]; + const la = layerAt(a); + const lb = layerAt(b); + const lc = layerAt(c); + expect(getLayerStack()).toEqual([la.layer, lb.layer, lc.layer]); + expect(getTopLayer()).toBe(lc.layer); + + lb.cleanup(); + expect(getLayerStack()).toEqual([la.layer, lc.layer]); + la.cleanup(); + expect(getLayerStack()).toEqual([lc.layer]); + lc.cleanup(); + expect(getLayerStack()).toEqual([]); + expect(getTopLayer()).toBeUndefined(); + }); + + it("cleanup is idempotent", () => { + const l = layerAt(mount("a")); + l.cleanup(); + l.cleanup(); + expect(getLayerStack()).toEqual([]); + }); + + it("isTopLayer follows the stack", () => { + const la = layerAt(mount("a")); + const lb = layerAt(mount("b")); + expect(isTopLayer(la.layer)).toBe(false); + expect(isTopLayer(lb.layer)).toBe(true); + lb.cleanup(); + expect(isTopLayer(la.layer)).toBe(true); + }); + + it("persistent layers are never the top layer", () => { + const la = layerAt(mount("a")); + const lp = layerAt(mount("p"), { persistent: true }); + expect(getLayerStack()).toHaveLength(2); + expect(isTopLayer(lp.layer)).toBe(false); + expect(getTopLayer()).toBe(la.layer); + }); + + it("useLayerStack is reactive", () => { + let stack!: ReturnType; + const dispose = createRoot(d => { + stack = useLayerStack(); + return d; + }); + cleanups.push(dispose); + flush(); + expect(stack()).toHaveLength(0); + const l = layerAt(mount("a")); + flush(); + expect(stack()).toEqual([l.layer]); + l.cleanup(); + flush(); + expect(stack()).toEqual([]); + }); +}); + +describe("escape", () => { + it("dismisses with reason 'escape'", () => { + const l = layerAt(mount("a")); + ready(); + escape(); + expect(l.onDismiss).toHaveBeenCalledTimes(1); + expect(l.onDismiss.mock.calls[0]![0]).toBe("escape"); + }); + + it("ignores other keys", () => { + const l = layerAt(mount("a")); + document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + expect(l.onDismiss).not.toHaveBeenCalled(); + }); + + it("only the topmost layer reacts, one at a time", () => { + const la = layerAt(mount("a")); + const lb = layerAt(mount("b")); + ready(); + escape(); + expect(lb.onDismiss).toHaveBeenCalledTimes(1); + expect(la.onDismiss).not.toHaveBeenCalled(); + lb.cleanup(); + escape(); + expect(la.onDismiss).toHaveBeenCalledTimes(1); + expect(lb.onDismiss).toHaveBeenCalledTimes(1); + }); + + it("does not cascade to the parent when the child removes itself synchronously", () => { + const la = layerAt(mount("a")); + const lb = layerAt(mount("b"), { onDismiss: () => lb2.cleanup() }); + const lb2 = lb; + ready(); + escape(); + expect(la.onDismiss).not.toHaveBeenCalled(); + expect(getLayerStack()).toEqual([la.layer]); + }); + + it("skips persistent layers", () => { + const la = layerAt(mount("a")); + const lp = layerAt(mount("p"), { persistent: true }); + ready(); + escape(); + expect(la.onDismiss).toHaveBeenCalledTimes(1); + expect(lp.onDismiss).not.toHaveBeenCalled(); + }); + + it("stops listening after cleanup", () => { + const l = layerAt(mount("a")); + l.cleanup(); + escape(); + expect(l.onDismiss).not.toHaveBeenCalled(); + }); +}); + +describe("outside pointer / focus", () => { + it("outside press dismisses with 'outside-pointer'", () => { + const inside = mount("in"); + const outside = mount("out"); + const l = layerAt(inside); + ready(); + press(inside); + expect(l.onDismiss).not.toHaveBeenCalled(); + press(outside); + expect(l.onDismiss).toHaveBeenCalledTimes(1); + expect(l.onDismiss.mock.calls[0]![0]).toBe("outside-pointer"); + expect(l.onDismiss.mock.calls[0]![1]).toBeInstanceOf(Event); + }); + + it("focus moving outside dismisses with 'outside-focus'", () => { + const inside = mount("in"); + const outside = mount("out"); + const l = layerAt(inside); + ready(); + outside.focus(); + expect(l.onDismiss).toHaveBeenCalledTimes(1); + expect(l.onDismiss.mock.calls[0]![0]).toBe("outside-focus"); + }); + + it("only the topmost layer reacts to an outside press", () => { + const [a, b, out] = [mount("a"), mount("b"), mount("out")]; + const la = layerAt(a); + const lb = layerAt(b); + ready(); + press(out); + expect(lb.onDismiss).toHaveBeenCalledTimes(1); + expect(la.onDismiss).not.toHaveBeenCalled(); + }); + + it("a press inside the parent but outside the child dismisses only the child", () => { + const [a, b] = [mount("a"), mount("b")]; + const la = layerAt(a); + const lb = layerAt(b); + ready(); + press(a); + expect(lb.onDismiss).toHaveBeenCalledTimes(1); + expect(la.onDismiss).not.toHaveBeenCalled(); + }); + + it("a press inside a portaled child (separate DOM tree) does not dismiss the parent", () => { + const [a, portal, out] = [mount("a"), mount("portal"), mount("out")]; + const la = layerAt(a); + const lc = layerAt(portal, { persistent: true, parent: la.layer }); + ready(); + press(portal); + expect(la.onDismiss).not.toHaveBeenCalled(); + expect(lc.onDismiss).not.toHaveBeenCalled(); + press(out); + expect(la.onDismiss).toHaveBeenCalledTimes(1); + }); + + it("a press inside a persistent layer above does not dismiss the layer below", () => { + const [a, p] = [mount("a"), mount("p")]; + const la = layerAt(a); + layerAt(p, { persistent: true }); + ready(); + press(p); + expect(la.onDismiss).not.toHaveBeenCalled(); + }); + + it("a registered parent also covers a child that sits lower in the stack", () => { + const [a, b] = [mount("a"), mount("b")]; + const lb = layerAt(b); + const la = layerAt(a); + // child `b` registered later than `a`'s record but declared as a's descendant + const child = mount("child"); + const lc = layerAt(child, { parent: lb.layer, persistent: true }); + ready(); + press(child); + expect(lb.onDismiss).not.toHaveBeenCalled(); + expect(la.onDismiss).not.toHaveBeenCalled(); + expect(lc.onDismiss).not.toHaveBeenCalled(); + }); + + it("exclude: element, array and predicate", () => { + const inside = mount("in"); + const trigger = mount("trigger"); + const other = mount("other"); + const out = mount("out"); + + const l1 = layerAt(inside, { exclude: trigger }); + ready(); + press(trigger); + expect(l1.onDismiss).not.toHaveBeenCalled(); + l1.cleanup(); + + const l2 = layerAt(inside, { exclude: [trigger, other] }); + ready(); + press(other); + expect(l2.onDismiss).not.toHaveBeenCalled(); + l2.cleanup(); + + const l3 = layerAt(inside, { exclude: el => el.id === "out" }); + ready(); + press(out); + expect(l3.onDismiss).not.toHaveBeenCalled(); + press(trigger); + expect(l3.onDismiss).toHaveBeenCalledTimes(1); + }); + + it("stops listening after cleanup", () => { + const inside = mount("in"); + const out = mount("out"); + const l = layerAt(inside); + ready(); + l.cleanup(); + press(out); + expect(l.onDismiss).not.toHaveBeenCalled(); + }); + + it("cleanup before listeners are attached cancels the pending registration", () => { + const inside = mount("in"); + const out = mount("out"); + const l = layerAt(inside); + l.cleanup(); + ready(); + press(out); + expect(l.onDismiss).not.toHaveBeenCalled(); + }); +}); + +describe("dismissible", () => { + it("calls onDismissAttempt instead of onDismiss when dismissible is false", () => { + const inside = mount("in"); + const out = mount("out"); + const onDismissAttempt = vi.fn(); + const l = layerAt(inside, { dismissible: false, onDismissAttempt }); + ready(); + escape(); + press(out); + inside.focus(); + expect(l.onDismiss).not.toHaveBeenCalled(); + expect(onDismissAttempt).toHaveBeenCalledTimes(2); + expect(onDismissAttempt.mock.calls.map(c => c[0])).toEqual(["escape", "outside-pointer"]); + expect(onDismissAttempt.mock.calls[0]![1]).toBeInstanceOf(KeyboardEvent); + }); + + it("a non-dismissible top layer blocks the parent (no fall-through)", () => { + const [a, b] = [mount("a"), mount("b")]; + const la = layerAt(a); + const attempt = vi.fn(); + layerAt(b, { dismissible: false, onDismissAttempt: attempt }); + ready(); + escape(); + expect(attempt).toHaveBeenCalledTimes(1); + expect(la.onDismiss).not.toHaveBeenCalled(); + }); + + it("dismissible accessor is read at request time", () => { + const [ok, setOk] = createSignal(false); + const attempt = vi.fn(); + const l = layerAt(mount("a"), { dismissible: ok, onDismissAttempt: attempt }); + ready(); + escape(); + expect(attempt).toHaveBeenCalledTimes(1); + setOk(true); + flush(); + escape(); + expect(l.onDismiss).toHaveBeenCalledTimes(1); + }); + + it("without onDismissAttempt a blocked request is a silent no-op", () => { + const l = layerAt(mount("a"), { dismissible: false }); + ready(); + expect(() => escape()).not.toThrow(); + expect(l.onDismiss).not.toHaveBeenCalled(); + }); +}); + +describe("programmatic dismiss", () => { + it("dismiss() defaults to 'programmatic', regardless of stack position", () => { + const la = layerAt(mount("a")); + layerAt(mount("b")); + la.dismiss(); + expect(la.onDismiss.mock.calls).toEqual([["programmatic", undefined]]); + }); + + it("dismiss() respects dismissible", () => { + const attempt = vi.fn(); + const l = layerAt(mount("a"), { dismissible: false, onDismissAttempt: attempt }); + l.dismiss(); + expect(l.onDismiss).not.toHaveBeenCalled(); + expect(attempt).toHaveBeenCalledWith("programmatic", undefined); + }); + + it("works on a persistent layer", () => { + const l = layerAt(mount("a"), { persistent: true }); + l.dismiss(); + expect(l.onDismiss).toHaveBeenCalledWith("programmatic", undefined); + }); +}); + +describe("disableOutsidePointerEvents", () => { + it("disables body pointer events while registered and restores them", () => { + document.body.style.pointerEvents = "auto"; + const el = mount("a"); + el.style.pointerEvents = ""; + const l = layerAt(el, { disableOutsidePointerEvents: true }); + expect(document.body.style.pointerEvents).toBe("none"); + expect(el.style.pointerEvents).toBe("auto"); + l.cleanup(); + expect(document.body.style.pointerEvents).toBe("auto"); + expect(el.style.pointerEvents).toBe(""); + }); + + it("stays disabled until the last disabling layer is removed (any order)", () => { + const [a, b] = [mount("a"), mount("b")]; + const la = layerAt(a, { disableOutsidePointerEvents: true }); + const lb = layerAt(b, { disableOutsidePointerEvents: true }); + la.cleanup(); + expect(document.body.style.pointerEvents).toBe("none"); + expect(b.style.pointerEvents).toBe("auto"); + lb.cleanup(); + expect(document.body.style.pointerEvents).toBe(""); + }); + + it("layers above a disabling layer stay interactive", () => { + const [a, b] = [mount("a"), mount("b")]; + layerAt(a, { disableOutsidePointerEvents: true }); + layerAt(b); + expect(b.style.pointerEvents).toBe("auto"); + }); +}); + +describe("createDismissableLayer", () => { + it("registers once the ref resolves and unregisters on dispose", () => { + const [ref, setRef] = createSignal(); + const onDismiss = vi.fn(); + let ctl!: ReturnType; + const dispose = createRoot(d => { + ctl = createDismissableLayer({ ref, onDismiss }); + return d; + }); + flush(); + expect(getLayerStack()).toHaveLength(0); + expect(ctl.isTop()).toBe(false); + ctl.dismiss(); // no element yet: no-op + expect(onDismiss).not.toHaveBeenCalled(); + + setRef(mount("a")); + flush(); + expect(getLayerStack()).toHaveLength(1); + expect(ctl.isTop()).toBe(true); + ready(); + escape(); + expect(onDismiss.mock.calls[0]![0]).toBe("escape"); + ctl.dismiss(); + expect(onDismiss).toHaveBeenLastCalledWith("programmatic", undefined); + + dispose(); + expect(getLayerStack()).toHaveLength(0); + escape(); + expect(onDismiss).toHaveBeenCalledTimes(2); + }); + + it("re-registers when the element changes", () => { + const [ref, setRef] = createSignal(mount("a")); + const second = mount("b"); + const dispose = createRoot(d => { + createDismissableLayer({ ref, onDismiss: () => {} }); + return d; + }); + cleanups.push(dispose); + flush(); + expect(getLayerStack().map(l => l.element.id)).toEqual(["a"]); + setRef(second); + flush(); + expect(getLayerStack().map(l => l.element.id)).toEqual(["b"]); + }); + + it("accepts a plain element and tracks isTop across layers", () => { + const tops: boolean[] = []; + let a!: ReturnType; + let b!: ReturnType; + const dispA = createRoot(d => { + a = createDismissableLayer({ ref: mount("a"), onDismiss: () => {} }); + return d; + }); + flush(); + const dispB = createRoot(d => { + b = createDismissableLayer({ ref: mount("b"), onDismiss: () => {} }); + return d; + }); + flush(); + tops.push(a.isTop(), b.isTop()); + expect(tops).toEqual([false, true]); + dispB(); + flush(); + expect(a.isTop()).toBe(true); + dispA(); + }); + + it("disposing in non-stack order leaves a consistent stack", () => { + const disposers = ["a", "b", "c"].map(id => + createRoot(d => { + createDismissableLayer({ ref: mount(id), onDismiss: () => {} }); + return d; + }), + ); + flush(); + expect(getLayerStack()).toHaveLength(3); + disposers[1]!(); + flush(); + expect(getLayerStack().map(l => l.element.id)).toEqual(["a", "c"]); + disposers[0]!(); + disposers[2]!(); + flush(); + expect(getLayerStack()).toEqual([]); + }); + + it("reads dismissible / callbacks reactively without re-registering", () => { + const [ok, setOk] = createSignal(false); + const onDismiss = vi.fn(); + const onDismissAttempt = vi.fn(); + const dispose = createRoot(d => { + createDismissableLayer({ ref: mount("a"), onDismiss, onDismissAttempt, dismissible: ok }); + return d; + }); + cleanups.push(dispose); + flush(); + const first = getLayerStack()[0]; + ready(); + escape(); + expect(onDismissAttempt).toHaveBeenCalledTimes(1); + setOk(true); + flush(); + escape(); + expect(onDismiss).toHaveBeenCalledTimes(1); + expect(getLayerStack()[0]).toBe(first); + }); +}); diff --git a/packages/dismissable/test/server.test.ts b/packages/dismissable/test/server.test.ts new file mode 100644 index 000000000..dcf1c60fb --- /dev/null +++ b/packages/dismissable/test/server.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it, vi } from "vitest"; +import { + createDismissableLayer, + getLayerStack, + getTopLayer, + isTopLayer, + makeDismissableLayer, + useLayerStack, +} from "../src/index.js"; + +describe("dismissable on the server", () => { + it("makeDismissableLayer returns inert controls", () => { + const onDismiss = vi.fn(); + const controls = makeDismissableLayer({ element: {} as Element, onDismiss }); + expect(() => controls.dismiss()).not.toThrow(); + expect(() => controls.cleanup()).not.toThrow(); + expect(onDismiss).not.toHaveBeenCalled(); + expect(getLayerStack()).toEqual([]); + }); + + it("createDismissableLayer is a no-op", () => { + const ctl = createDismissableLayer({ ref: () => undefined, onDismiss: () => {} }); + expect(ctl.isTop()).toBe(false); + expect(() => ctl.dismiss("escape")).not.toThrow(); + }); + + it("stack helpers return empty results", () => { + const controls = makeDismissableLayer({ element: {} as Element, onDismiss: () => {} }); + expect(getTopLayer()).toBeUndefined(); + expect(isTopLayer(controls.layer)).toBe(false); + expect(useLayerStack()()).toEqual([]); + }); +}); diff --git a/packages/dismissable/tsconfig.json b/packages/dismissable/tsconfig.json new file mode 100644 index 000000000..674e85d9a --- /dev/null +++ b/packages/dismissable/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig.json", + "include": ["src"] +} \ No newline at end of file diff --git a/packages/floating/CHANGELOG.md b/packages/floating/CHANGELOG.md new file mode 100644 index 000000000..66e618a22 --- /dev/null +++ b/packages/floating/CHANGELOG.md @@ -0,0 +1 @@ +# @solid-primitives/floating diff --git a/packages/floating/LICENSE b/packages/floating/LICENSE new file mode 100644 index 000000000..38b41d975 --- /dev/null +++ b/packages/floating/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/floating/README.md b/packages/floating/README.md new file mode 100644 index 000000000..dfd6223a1 --- /dev/null +++ b/packages/floating/README.md @@ -0,0 +1,256 @@ +

+ Solid Primitives floating +

+ +# @solid-primitives/floating + +[![size](https://img.shields.io/bundlephobia/minzip/@solid-primitives/floating?style=for-the-badge&label=size)](https://bundlephobia.com/package/@solid-primitives/floating) +[![version](https://img.shields.io/npm/v/@solid-primitives/floating?style=for-the-badge)](https://www.npmjs.com/package/@solid-primitives/floating) +[![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) + +Positioning for popovers, tooltips, dropdowns and other floating elements: placement, offset, flip, shift, available-space sizing and arrows, self-contained and with no positioning library underneath. + +- [`computePosition`](#computeposition) - measure two elements and get coordinates back. +- [`computePositionFromRects`](#computepositionfromrects) - the same geometry on plain rects, with no DOM. +- [`makeAutoUpdate`](#makeautoupdate) - call `update` when scrolling, resizing or moving makes the position stale. +- [`createFloating`](#createfloating) - reactive positioning with styles, wired to auto-updating. +- [`getSizeCssVars` / `applySizeCssVars`](#size-css-variables) - expose the available space to CSS. + +## Installation + +```bash +npm install @solid-primitives/floating +# or +yarn add @solid-primitives/floating +# or +pnpm add @solid-primitives/floating +``` + +## `computePosition` + +Computes where `floating` goes relative to `reference`. It measures with `getBoundingClientRect`, applies no styles and keeps no state. `x` / `y` are relative to the floating element's offset parent for `strategy: "absolute"` and to the viewport for `"fixed"`. + +`flip` and `shift` are opt-in. `rootBoundary` defaults to the viewport (`visualViewport` when the browser has it); `boundary` narrows that further and is intersected with it. + +```ts +// Type +function computePosition( + reference: Element | VirtualElement, + floating: HTMLElement, + options?: { + placement?: Placement; // "top" | "right" | "bottom" | "left", each with "-start" | "-end". Default "bottom" + strategy?: "absolute" | "fixed"; // default "absolute" + rtl?: boolean; // default: the floating element's computed `direction` + offset?: number | { mainAxis?: number; crossAxis?: number }; + flip?: boolean | { fallbackPlacements?: Placement[]; padding?: Padding }; + shift?: + | boolean + | { + padding?: Padding; + crossAxis?: boolean; // default true + mainAxis?: boolean; // default false + limit?: boolean | { offset?: number }; + }; + size?: { padding?: Padding; apply?: (args: SizeApplyArgs) => void }; + arrow?: { element: Element | null; padding?: number }; + boundary?: Element | Element[] | Rect; + rootBoundary?: "viewport" | "document" | Rect; + }, +): { + x: number; + y: number; + placement: Placement; // the placement used, after flipping + strategy: Strategy; + middlewareData: { + flipped: boolean; + shifted: boolean; + shift: { x: number; y: number }; + availableWidth: number; + availableHeight: number; + transformOrigin: string; + arrow?: { x?: number; y?: number; centerOffset: number }; + }; +}; + +// Example +import { computePosition } from "@solid-primitives/floating"; + +const { x, y, placement } = computePosition(button, tooltip, { + placement: "top", + offset: 8, + flip: true, + shift: { padding: 8 }, +}); +Object.assign(tooltip.style, { position: "absolute", left: `${x}px`, top: `${y}px` }); +``` + +### Notes + +- A virtual element is anything with `getBoundingClientRect()`, such as the pointer. Give it a `contextElement` so `makeAutoUpdate` can find its scroll ancestors. +- `flip` takes the first candidate (the requested placement, then `fallbackPlacements`, which defaults to the opposite side) whose side does not overflow. If none fits, it takes the one that overflows least. +- `shift.limit` keeps the floating element attached to the reference when the reference is scrolled out of the boundary. +- In RTL, `-start` / `-end` on `top` and `bottom` are mirrored. `left` and `right` placements are not affected. +- `size.apply` runs after the position is solved. If it changes the floating element's size, the position is solved once more. +- `arrow.x` / `arrow.y` are offsets inside the floating element along the cross axis; the arrow sits on the side opposite `placement`. `centerOffset` is non-zero when padding stopped it from pointing at the reference center. +- `availableWidth` / `availableHeight` are the room the floating element has before it hits the boundary, minus `size.padding`: on top/bottom placements the height is measured on the placement side, and the width towards the side the element can grow. + +## `computePositionFromRects` + +The geometry behind `computePosition`, on plain numbers. All rects share one coordinate space; `origin` converts the result into the coordinates of a positioned ancestor. + +```ts +// Type +function computePositionFromRects( + reference: Rect, + floating: { width: number; height: number }, + clipping: Rect, + options?: PositionOptions, // computePosition's options, without `arrow`, `boundary` and `rootBoundary` + extras?: { origin?: Point; arrow?: { width: number; height: number; padding?: number } }, +): ComputePositionResult; + +// Example +import { computePositionFromRects } from "@solid-primitives/floating"; + +computePositionFromRects( + { x: 400, y: 770, width: 100, height: 20 }, + { width: 60, height: 30 }, + { x: 0, y: 0, width: 1000, height: 800 }, + { placement: "bottom", flip: true }, +); // { x: 420, y: 740, placement: "top", ... } +``` + +## `makeAutoUpdate` + +Calls `update` while the position can go stale: when a scrollable ancestor of either element (or the window and visual viewport) scrolls, when the window resizes, and when either element changes size. Returns a cleanup. It does not call `update` on setup, and does nothing on the server. + +Its signature matches `whileElementsMounted`, so it can be passed to `createFloating` as is. `autoUpdate` is an alias. + +```ts +// Type +function makeAutoUpdate( + reference: Element | VirtualElement, + floating: HTMLElement, + update: () => void, + options?: { + ancestorScroll?: boolean; // default true + ancestorResize?: boolean; // default true + elementResize?: boolean; // default true + animationFrame?: boolean; // default false + }, +): () => void; + +// Example +import { makeAutoUpdate, computePosition } from "@solid-primitives/floating"; + +const stop = makeAutoUpdate(button, tooltip, () => { + const { x, y } = computePosition(button, tooltip, { placement: "top" }); + Object.assign(tooltip.style, { left: `${x}px`, top: `${y}px` }); +}); +// later +stop(); +``` + +### Notes + +- `animationFrame: true` checks the reference and floating boxes every frame and calls `update` only when they changed. Use it when the reference is animated, as scroll and resize events cannot see that. +- A `ResizeObserver` firing right after it starts observing triggers one extra `update`. + +## `createFloating` + +Reactive positioning. Every option may be a value or an accessor, and the position is recomputed when an element or option changes. On the server nothing is measured: `styles()` is the unpositioned `{ position, top: "0", left: "0" }`. + +```ts +// Type +function createFloating(options: { + reference: MaybeAccessor; + floating: MaybeAccessor; + placement?: MaybeAccessor; + strategy?: MaybeAccessor; + rtl?: MaybeAccessor; + offset?: MaybeAccessor; + flip?: MaybeAccessor; + shift?: MaybeAccessor; + size?: MaybeAccessor; + arrow?: MaybeAccessor<{ element: MaybeAccessor; padding?: number }>; + boundary?: MaybeAccessor; + rootBoundary?: MaybeAccessor; + transform?: MaybeAccessor; // translate() instead of top/left, default true + whileElementsMounted?: (reference, floating, update) => (() => void) | void; + autoUpdate?: MaybeAccessor; // shorthand for makeAutoUpdate +}): { + x: Accessor; + y: Accessor; + placement: Accessor; + strategy: Accessor; + middlewareData: Accessor; + isPositioned: Accessor; + styles: Accessor<{ position: Strategy; top: string; left: string; transform?: string }>; + update: () => void; +}; + +// Example +import { createSignal } from "solid-js"; +import { createFloating } from "@solid-primitives/floating"; + +function Tooltip() { + const [reference, setReference] = createSignal(null); + const [floating, setFloating] = createSignal(null); + + const position = createFloating({ + reference, + floating, + placement: "top", + offset: 8, + flip: true, + shift: { padding: 8 }, + autoUpdate: true, + }); + + return ( + <> + +
+ {position.placement()} +
+ + ); +} +``` + +### Notes + +- Pass the elements as signals (`ref={setReference}`) so a new element repositions. +- `whileElementsMounted` runs while both elements exist and is cleaned up when one goes away or the owner is disposed. Option changes do not restart it. It wins over `autoUpdate`. +- `styles()` values are rounded to the device pixel ratio to keep text sharp. Read `x()` / `y()` for the exact numbers. +- `isPositioned()` is `false` until the first measurement, so you can hide the element until then. +- `update()` is safe to call from event handlers and does nothing when an element is missing. +- The position signals only change when the result differs, so polling with `animationFrame` does not cause extra updates. + +## Size CSS variables + +`getSizeCssVars` turns `middlewareData` into `--available-width`, `--available-height` and `--transform-origin`; `applySizeCssVars` writes them to an element's inline style. + +```ts +// Type +function getSizeCssVars( + data: Pick, +): Record<"--available-width" | "--available-height" | "--transform-origin", string>; +function applySizeCssVars(element: HTMLElement, data: typeof data): void; + +// Example +const position = createFloating({ reference, floating, flip: true }); + +
; +``` + +## Changelog + +See [CHANGELOG.md](./CHANGELOG.md) diff --git a/packages/floating/deno.jsonc b/packages/floating/deno.jsonc new file mode 100644 index 000000000..7fe2c368b --- /dev/null +++ b/packages/floating/deno.jsonc @@ -0,0 +1,11 @@ +{ + "name": "@solid-primitives/floating", + "version": "0.0.1", + "description": "Floating element positioning — placement, offset, flip, shift, size and arrow, with auto-updating", + "license": "MIT", + "exports": "./src/index.ts", + "publish": { + "include": ["README.md", "LICENSE", "src/**/*.ts", "src/**/*.tsx", "package.json"], + "exclude": ["dist", "dev", "test", "node_modules", "vitest.config.ts", "tsconfig.json"], + }, +} diff --git a/packages/floating/dev/index.tsx b/packages/floating/dev/index.tsx new file mode 100644 index 000000000..2f0db0fd9 --- /dev/null +++ b/packages/floating/dev/index.tsx @@ -0,0 +1,80 @@ +import { type Component, createSignal } from "solid-js"; +import { Show } from "@solidjs/web"; +import { createFloating, getSizeCssVars, makeAutoUpdate, type Placement } from "../src/index.js"; + +const placements: Placement[] = [ + "top-start", + "top", + "top-end", + "right-start", + "right", + "right-end", + "bottom-start", + "bottom", + "bottom-end", + "left-start", + "left", + "left-end", +]; + +const App: Component = () => { + const [reference, setReference] = createSignal(null); + const [floating, setFloating] = createSignal(null); + const [arrow, setArrow] = createSignal(null); + const [placement, setPlacement] = createSignal("bottom"); + const [open, setOpen] = createSignal(true); + + const f = createFloating({ + reference, + floating, + placement, + offset: 10, + flip: true, + shift: { padding: 8, limit: true }, + arrow: { element: arrow, padding: 6 }, + whileElementsMounted: makeAutoUpdate, + }); + + return ( +
+

Floating Primitive

+ + + +
+ Placed {f.placement()} {f.middlewareData()?.flipped ? "(flipped)" : ""} +
+
+ +
+ ); +}; + +export default App; diff --git a/packages/floating/package.json b/packages/floating/package.json new file mode 100644 index 000000000..0575907ff --- /dev/null +++ b/packages/floating/package.json @@ -0,0 +1,79 @@ +{ + "name": "@solid-primitives/floating", + "version": "0.0.1", + "description": "Floating element positioning — placement, offset, flip, shift, size and arrow, with auto-updating", + "author": "David Di Biase ", + "contributors": [], + "license": "MIT", + "homepage": "https://primitives.solidjs.community/package/floating", + "repository": { + "type": "git", + "url": "git+https://github.com/solidjs-community/solid-primitives.git" + }, + "bugs": { + "url": "https://github.com/solidjs-community/solid-primitives/issues" + }, + "primitive": { + "name": "floating", + "stage": 0, + "list": [ + "computePosition", + "computePositionFromRects", + "makeAutoUpdate", + "createFloating", + "getSizeCssVars", + "applySizeCssVars" + ], + "category": "UI Patterns", + "gzip": 3730 + }, + "keywords": [ + "solid", + "primitives", + "floating", + "positioning", + "popover", + "tooltip", + "dropdown", + "anchor" + ], + "private": false, + "sideEffects": false, + "files": [ + "dist" + ], + "type": "module", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "browser": {}, + "exports": { + "import": { + "@solid-primitives/source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "typesVersions": {}, + "tsdown": { + "entry": "src/**/*.{ts,tsx}", + "outDir": "dist" + }, + "scripts": { + "dev": "node --import=@nothing-but/node-resolve-ts ../../scripts/dev.ts", + "build": "pnpm -w build", + "vitest": "vitest -c ../../configs/vitest.config.ts", + "test": "pnpm run vitest", + "test:ssr": "pnpm run vitest --mode ssr" + }, + "dependencies": { + "@solid-primitives/utils": "workspace:^" + }, + "peerDependencies": { + "@solidjs/web": "catalog:peer", + "solid-js": "catalog:peer" + }, + "devDependencies": { + "@solidjs/web": "catalog:", + "solid-js": "catalog:peer" + } +} diff --git a/packages/floating/src/autoUpdate.ts b/packages/floating/src/autoUpdate.ts new file mode 100644 index 000000000..354cc1567 --- /dev/null +++ b/packages/floating/src/autoUpdate.ts @@ -0,0 +1,124 @@ +import type { ReferenceElement } from "./types.ts"; + +export type AutoUpdateOptions = { + /** Update when any scrollable ancestor, the window or the visual viewport scrolls. Default `true`. */ + ancestorScroll?: boolean; + /** Update when the window or the visual viewport resizes. Default `true`. */ + ancestorResize?: boolean; + /** Update when the reference or floating element changes size. Default `true`. */ + elementResize?: boolean; + /** Poll every animation frame and update when the reference moves. Default `false`. */ + animationFrame?: boolean; +}; + +const SCROLLABLE = /auto|scroll|overlay|hidden|clip/; + +function getParent(node: Element): Element | null { + if (node.assignedSlot) return node.assignedSlot; + if (node.parentElement) return node.parentElement; + const root = node.getRootNode(); + return root instanceof ShadowRoot ? root.host : null; +} + +function getScrollParents(node: Element): Element[] { + const win = node.ownerDocument.defaultView; + const { body, documentElement } = node.ownerDocument; + const result: Element[] = []; + let el = getParent(node); + while (el && el !== body && el !== documentElement) { + const style = win?.getComputedStyle(el); + if (style && SCROLLABLE.test(style.overflow + style.overflowX + style.overflowY)) + result.push(el); + el = getParent(el); + } + return result; +} + +const getContext = (reference: ReferenceElement): Element | undefined => + "nodeType" in reference ? reference : reference.contextElement; + +const rectKey = (reference: ReferenceElement, floating: HTMLElement): string => { + const r = reference.getBoundingClientRect(); + const f = floating.getBoundingClientRect(); + return `${r.x ?? r.left},${r.y ?? r.top},${r.width},${r.height}|${f.width},${f.height}`; +}; + +/** + * Keeps a floating element's position fresh: calls `update` when the reference or floating + * element resizes, when an ancestor scrolls, when the window resizes, and optionally on every + * animation frame in which the reference moved. + * + * Does not call `update` itself on setup. Returns a cleanup that removes every listener and + * observer; calling it more than once is safe. A no-op on the server. + * + * Matches the `whileElementsMounted` signature, so it can be passed to `createFloating` directly. + */ +export function makeAutoUpdate( + reference: ReferenceElement, + floating: HTMLElement, + update: () => void, + options: AutoUpdateOptions = {}, +): VoidFunction { + const { + ancestorScroll = true, + ancestorResize = true, + elementResize = true, + animationFrame = false, + } = options; + + const win = floating.ownerDocument?.defaultView; + if (!win) return () => {}; + + const cleanups: VoidFunction[] = []; + const listen = (target: EventTarget | null | undefined, type: string): void => { + if (!target) return; + target.addEventListener(type, update, { passive: true }); + cleanups.push(() => target.removeEventListener(type, update)); + }; + + const context = getContext(reference); + + if (ancestorScroll) { + const targets = new Set([win]); + if (win.visualViewport) targets.add(win.visualViewport); + if (context) for (const el of getScrollParents(context)) targets.add(el); + for (const el of getScrollParents(floating)) targets.add(el); + for (const target of targets) listen(target, "scroll"); + } + + if (ancestorResize) { + listen(win, "resize"); + listen(win.visualViewport, "resize"); + } + + if (elementResize && typeof win.ResizeObserver === "function") { + const observer = new win.ResizeObserver(() => update()); + if (context) observer.observe(context); + observer.observe(floating); + cleanups.push(() => observer.disconnect()); + } + + if (animationFrame && typeof win.requestAnimationFrame === "function") { + let previous = rectKey(reference, floating); + let frame = win.requestAnimationFrame(function tick() { + const next = rectKey(reference, floating); + if (next !== previous) { + previous = next; + update(); + } + frame = win.requestAnimationFrame(tick); + }); + cleanups.push(() => win.cancelAnimationFrame(frame)); + } + + let done = false; + return () => { + if (done) return; + done = true; + for (const cleanup of cleanups) cleanup(); + cleanups.length = 0; + }; +} + +/** Alias of `makeAutoUpdate`, named as in other positioning libraries. */ +export const autoUpdate: typeof makeAutoUpdate = makeAutoUpdate; diff --git a/packages/floating/src/compute.ts b/packages/floating/src/compute.ts new file mode 100644 index 000000000..f632df577 --- /dev/null +++ b/packages/floating/src/compute.ts @@ -0,0 +1,439 @@ +import type { + Alignment, + ArrowData, + ComputePositionOptions, + ComputePositionResult, + Padding, + Placement, + Point, + PositionOptions, + Rect, + ReferenceElement, + Side, + Sides, + Size, + Strategy, +} from "./types.ts"; + +const OPPOSITE: Record = { + top: "bottom", + bottom: "top", + left: "right", + right: "left", +}; + +export const getSide = (placement: Placement): Side => placement.split("-")[0] as Side; +export const getAlignment = (placement: Placement): Alignment | undefined => + placement.split("-")[1] as Alignment | undefined; + +/** Swaps the side, keeps the alignment: `top-start` -> `bottom-start`. */ +export const getOppositePlacement = (placement: Placement): Placement => { + const alignment = getAlignment(placement); + const side = OPPOSITE[getSide(placement)]; + return (alignment ? `${side}-${alignment}` : side) as Placement; +}; + +/** `true` for top/bottom placements, where the cross axis is horizontal. */ +const isVerticalPlacement = (side: Side): boolean => side === "top" || side === "bottom"; + +const clamp = (min: number, value: number, max: number): number => + Math.max(min, Math.min(value, max)); + +export function normalizePadding(padding: Padding | undefined): Sides { + if (typeof padding === "number") + return { top: padding, right: padding, bottom: padding, left: padding }; + return { top: 0, right: 0, bottom: 0, left: 0, ...padding }; +} + +type RectLike = { + x?: number; + y?: number; + left?: number; + top?: number; + width: number; + height: number; +}; + +export const toRect = (r: RectLike): Rect => ({ + x: r.x ?? r.left ?? 0, + y: r.y ?? r.top ?? 0, + width: r.width, + height: r.height, +}); + +/** Intersection of two rects; never negative in size. */ +function intersect(a: Rect, b: Rect): Rect { + const x = Math.max(a.x, b.x); + const y = Math.max(a.y, b.y); + const right = Math.min(a.x + a.width, b.x + b.width); + const bottom = Math.min(a.y + a.height, b.y + b.height); + return { x, y, width: Math.max(0, right - x), height: Math.max(0, bottom - y) }; +} + +/** Coordinates of the floating element's top-left corner for one placement, offset included. */ +function getCoords( + ref: Rect, + fl: Size, + placement: Placement, + rtl: boolean, + mainAxisOffset: number, + crossAxisOffset: number, +): Point { + const side = getSide(placement); + const alignment = getAlignment(placement); + const vertical = isVerticalPlacement(side); + + const commonX = ref.x + ref.width / 2 - fl.width / 2; + const commonY = ref.y + ref.height / 2 - fl.height / 2; + + let x: number; + let y: number; + switch (side) { + case "top": + x = commonX; + y = ref.y - fl.height; + break; + case "bottom": + x = commonX; + y = ref.y + ref.height; + break; + case "right": + x = ref.x + ref.width; + y = commonY; + break; + default: + x = ref.x - fl.width; + y = commonY; + } + + // Alignment moves the element along the cross axis. In RTL, top/bottom start is the right edge. + const flip = rtl && vertical ? -1 : 1; + if (alignment) { + const common = vertical + ? (ref.width / 2 - fl.width / 2) * flip + : ref.height / 2 - fl.height / 2; + const dir = alignment === "start" ? -1 : 1; + if (vertical) x += dir * common; + else y += dir * common; + } + + const main = side === "top" || side === "left" ? -mainAxisOffset : mainAxisOffset; + const cross = (alignment === "end" ? -crossAxisOffset : crossAxisOffset) * flip; + if (vertical) { + x += cross; + y += main; + } else { + x += main; + y += cross; + } + return { x, y }; +} + +/** How far the element sticks out past each clipping edge. Positive means overflowing. */ +function getOverflow(coords: Point, fl: Size, clip: Rect, padding: Sides): Sides { + return { + top: clip.y - coords.y + padding.top, + bottom: coords.y + fl.height - (clip.y + clip.height) + padding.bottom, + left: clip.x - coords.x + padding.left, + right: coords.x + fl.width - (clip.x + clip.width) + padding.right, + }; +} + +export type SolveExtras = { + /** Viewport coordinates of the origin that `x`/`y` are measured from. Default `{0, 0}`. */ + origin?: Point; + /** Arrow element size and padding; enables `middlewareData.arrow`. */ + arrow?: Size & { padding?: number }; +}; + +/** + * Pure geometry: all rects are in the same coordinate space (viewport coordinates when called + * through `computePosition`). No DOM access, no reactivity. + * + * @param reference reference rect + * @param floating floating element size + * @param clipping rect the floating element should stay within + */ +export function computePositionFromRects( + reference: Rect, + floating: Size, + clipping: Rect, + options: PositionOptions = {}, + extras: SolveExtras = {}, +): ComputePositionResult { + const initialPlacement = options.placement ?? "bottom"; + const strategy: Strategy = options.strategy ?? "absolute"; + const rtl = options.rtl ?? false; + const origin = extras.origin ?? { x: 0, y: 0 }; + + const offset = + typeof options.offset === "number" + ? { mainAxis: options.offset, crossAxis: 0 } + : { mainAxis: options.offset?.mainAxis ?? 0, crossAxis: options.offset?.crossAxis ?? 0 }; + + const coordsFor = (placement: Placement) => + getCoords(reference, floating, placement, rtl, offset.mainAxis, offset.crossAxis); + + // --- flip --- + let placement = initialPlacement; + let coords = coordsFor(placement); + const flipOptions = options.flip === true ? {} : options.flip || undefined; + if (flipOptions) { + const padding = normalizePadding(flipOptions.padding); + const candidates = [ + initialPlacement, + ...(flipOptions.fallbackPlacements ?? [getOppositePlacement(initialPlacement)]), + ].filter((p, i, all) => all.indexOf(p) === i); + let best: { placement: Placement; coords: Point; overflow: number } | undefined; + let fits = false; + for (const candidate of candidates) { + const c = coordsFor(candidate); + const overflow = getOverflow(c, floating, clipping, padding)[getSide(candidate)]; + if (overflow <= 0) { + placement = candidate; + coords = c; + fits = true; + break; + } + if (!best || overflow < best.overflow) best = { placement: candidate, coords: c, overflow }; + } + if (!fits && best) { + placement = best.placement; + coords = best.coords; + } + } + + const side = getSide(placement); + const alignment = getAlignment(placement); + const vertical = isVerticalPlacement(side); + + // --- shift --- + const shiftOptions = options.shift === true ? {} : options.shift || undefined; + const shift: Point = { x: 0, y: 0 }; + if (shiftOptions) { + const padding = normalizePadding(shiftOptions.padding); + const limit = shiftOptions.limit === true ? {} : shiftOptions.limit || undefined; + const axes: ("x" | "y")[] = []; + const crossAxis = vertical ? "x" : "y"; + const mainAxis = vertical ? "y" : "x"; + if (shiftOptions.crossAxis ?? true) axes.push(crossAxis); + if (shiftOptions.mainAxis ?? false) axes.push(mainAxis); + for (const axis of axes) { + const len = axis === "x" ? "width" : "height"; + const [startPad, endPad] = + axis === "x" ? [padding.left, padding.right] : [padding.top, padding.bottom]; + const min = clipping[axis] + startPad; + const max = clipping[axis] + clipping[len] - endPad - floating[len]; + const original = coords[axis]; + let value = clamp(min, original, max); + if (limit) { + const limitOffset = limit.offset ?? 0; + // The unshifted coordinate always stays reachable: limiting only restricts the shift. + const lo = Math.min(reference[axis] - floating[len] + limitOffset, original); + const hi = Math.max(reference[axis] + reference[len] - limitOffset, original); + value = clamp(lo, value, hi); + } + shift[axis] = value - original; + coords = { ...coords, [axis]: value }; + } + } + + // --- size / available space --- + const sizePadding = normalizePadding(options.size?.padding); + const overflow = getOverflow(coords, floating, clipping, sizePadding); + let heightSide: "top" | "bottom"; + let widthSide: "left" | "right"; + if (vertical) { + heightSide = side as "top" | "bottom"; + widthSide = alignment === (rtl ? "start" : "end") ? "left" : "right"; + } else { + widthSide = side as "left" | "right"; + heightSide = alignment === "end" ? "top" : "bottom"; + } + const availableHeight = Math.max( + 0, + Math.min( + floating.height - overflow[heightSide], + floating.height - overflow.top - overflow.bottom, + ), + ); + const availableWidth = Math.max( + 0, + Math.min(floating.width - overflow[widthSide], floating.width - overflow.left - overflow.right), + ); + + // --- arrow --- + let arrow: ArrowData | undefined; + let arrowCenter: number | undefined; + if (extras.arrow) { + const axis = vertical ? "x" : "y"; + const len = vertical ? "width" : "height"; + const arrowLen = extras.arrow[len]; + const padding = extras.arrow.padding ?? 0; + const desired = reference[axis] + reference[len] / 2 - coords[axis] - arrowLen / 2; + const clamped = clamp(padding, desired, floating[len] - arrowLen - padding); + arrow = { [axis]: clamped, centerOffset: desired - clamped } as ArrowData; + arrowCenter = clamped + arrowLen / 2; + } + + // --- transform origin --- + const crossAxisKey = vertical ? "x" : "y"; + const crossLen = vertical ? "width" : "height"; + const crossOrigin = + arrowCenter ?? + clamp( + 0, + reference[crossAxisKey] + reference[crossLen] / 2 - coords[crossAxisKey], + floating[crossLen], + ); + const mainOrigin = side === "top" ? floating.height : side === "left" ? floating.width : 0; + const transformOrigin = vertical + ? `${crossOrigin}px ${mainOrigin}px` + : `${mainOrigin}px ${crossOrigin}px`; + + return { + x: coords.x - origin.x, + y: coords.y - origin.y, + placement, + strategy, + middlewareData: { + ...(arrow && { arrow }), + flipped: placement !== initialPlacement, + shifted: shift.x !== 0 || shift.y !== 0, + shift, + availableWidth, + availableHeight, + transformOrigin, + }, + }; +} + +// ---------- DOM measuring ---------- + +function getViewportRect(doc: Document): Rect { + const win = doc.defaultView; + const vv = win?.visualViewport; + if (vv) return { x: vv.offsetLeft, y: vv.offsetTop, width: vv.width, height: vv.height }; + const el = doc.documentElement; + return { + x: 0, + y: 0, + width: el.clientWidth || win?.innerWidth || 0, + height: el.clientHeight || win?.innerHeight || 0, + }; +} + +function getDocumentRect(doc: Document): Rect { + const win = doc.defaultView; + const el = doc.documentElement; + return { + x: -(win?.scrollX ?? 0), + y: -(win?.scrollY ?? 0), + width: Math.max(el.scrollWidth, el.clientWidth), + height: Math.max(el.scrollHeight, el.clientHeight), + }; +} + +const isRect = (value: unknown): value is Rect => + typeof value === "object" && + value !== null && + "width" in value && + !("getBoundingClientRect" in value); + +/** The rect, in viewport coordinates, that the floating element has to stay within. */ +export function getClippingRect( + floating: Element, + boundary: PositionOptions["boundary"], + rootBoundary: PositionOptions["rootBoundary"] = "viewport", +): Rect { + const doc = floating.ownerDocument; + let rect: Rect = + rootBoundary === "viewport" + ? getViewportRect(doc) + : rootBoundary === "document" + ? getDocumentRect(doc) + : rootBoundary; + if (boundary) { + const rects = isRect(boundary) + ? [boundary] + : (Array.isArray(boundary) ? boundary : [boundary]).map((el: Element) => + toRect(el.getBoundingClientRect()), + ); + for (const r of rects) rect = intersect(rect, r); + } + return rect; +} + +/** Viewport coordinates of the point that `position: absolute` coordinates are measured from. */ +export function getOrigin(floating: HTMLElement, strategy: Strategy): Point { + if (strategy === "fixed") return { x: 0, y: 0 }; + const doc = floating.ownerDocument; + const win = doc.defaultView; + const parent = floating.offsetParent; + if ( + !parent || + parent === doc.documentElement || + (parent === doc.body && win?.getComputedStyle(parent).position === "static") + ) { + return { x: -(win?.scrollX ?? 0), y: -(win?.scrollY ?? 0) }; + } + const rect = parent.getBoundingClientRect(); + return { + x: rect.left + parent.clientLeft - parent.scrollLeft, + y: rect.top + parent.clientTop - parent.scrollTop, + }; +} + +const measure = (el: HTMLElement | Element): Size => { + const { width, height } = el.getBoundingClientRect(); + return { width, height }; +}; + +/** + * Computes where to place `floating` relative to `reference`. Non-reactive and safe to call + * from anywhere with mounted elements; the caller applies the result. + * + * `x` / `y` are relative to the floating element's offset parent for `"absolute"`, and to the + * viewport for `"fixed"`. + */ +export function computePosition( + reference: ReferenceElement, + floating: HTMLElement, + options: ComputePositionOptions = {}, +): ComputePositionResult { + const strategy = options.strategy ?? "absolute"; + const rtl = + options.rtl ?? + floating.ownerDocument.defaultView?.getComputedStyle(floating).direction === "rtl"; + const solveOptions = { ...options, strategy, rtl }; + + const solve = (): ComputePositionResult => + computePositionFromRects( + toRect(reference.getBoundingClientRect()), + measure(floating), + getClippingRect(floating, options.boundary, options.rootBoundary), + solveOptions, + { + origin: getOrigin(floating, strategy), + arrow: options.arrow?.element + ? { ...measure(options.arrow.element), padding: options.arrow.padding } + : undefined, + }, + ); + + let result = solve(); + const apply = options.size?.apply; + if (apply) { + const before = measure(floating); + apply({ + availableWidth: result.middlewareData.availableWidth, + availableHeight: result.middlewareData.availableHeight, + transformOrigin: result.middlewareData.transformOrigin, + placement: result.placement, + elements: { reference, floating }, + }); + const after = measure(floating); + if (after.width !== before.width || after.height !== before.height) result = solve(); + } + return result; +} diff --git a/packages/floating/src/css.ts b/packages/floating/src/css.ts new file mode 100644 index 000000000..3fbf87ba7 --- /dev/null +++ b/packages/floating/src/css.ts @@ -0,0 +1,25 @@ +import type { MiddlewareData } from "./types.ts"; + +/** + * Turns the computed space into CSS variables, ready to spread into a `style` prop: + * `max-height: var(--available-height)`, `transform-origin: var(--transform-origin)`. + */ +export function getSizeCssVars( + data: Pick, +): Record<"--available-width" | "--available-height" | "--transform-origin", string> { + return { + "--available-width": `${data.availableWidth}px`, + "--available-height": `${data.availableHeight}px`, + "--transform-origin": data.transformOrigin, + }; +} + +/** Writes `getSizeCssVars(data)` onto an element's inline style. */ +export function applySizeCssVars( + element: HTMLElement, + data: Pick, +): void { + for (const [name, value] of Object.entries(getSizeCssVars(data))) { + element.style.setProperty(name, value); + } +} diff --git a/packages/floating/src/floating.ts b/packages/floating/src/floating.ts new file mode 100644 index 000000000..31ec8438d --- /dev/null +++ b/packages/floating/src/floating.ts @@ -0,0 +1,201 @@ +import { type Accessor, createEffect, createMemo, createSignal, untrack } from "solid-js"; +import { isServer } from "@solidjs/web"; +import { access, INTERNAL_OPTIONS, type MaybeAccessor } from "@solid-primitives/utils"; +import { computePosition } from "./compute.ts"; +import { type AutoUpdateOptions, makeAutoUpdate } from "./autoUpdate.ts"; +import type { + ArrowOptions, + Boundary, + ComputePositionOptions, + ComputePositionResult, + FlipOptions, + MiddlewareData, + OffsetOptions, + Placement, + ReferenceElement, + RootBoundary, + ShiftOptions, + SizeOptions, + Strategy, +} from "./types.ts"; + +export type FloatingStyles = { + position: Strategy; + top: string; + left: string; + transform?: string; +}; + +export type CreateFloatingOptions = { + reference: MaybeAccessor; + floating: MaybeAccessor; + /** Default `"bottom"`. */ + placement?: MaybeAccessor; + /** Default `"absolute"`. */ + strategy?: MaybeAccessor; + rtl?: MaybeAccessor; + offset?: MaybeAccessor; + flip?: MaybeAccessor; + shift?: MaybeAccessor; + size?: MaybeAccessor; + arrow?: MaybeAccessor< + { element: MaybeAccessor; padding?: number } | undefined + >; + boundary?: MaybeAccessor; + rootBoundary?: MaybeAccessor; + /** + * Position with `transform: translate()` (default) instead of `top` / `left`. + */ + transform?: MaybeAccessor; + /** + * Runs while both elements exist, e.g. `makeAutoUpdate`. Receives `update`; returns a cleanup. + * Takes precedence over `autoUpdate`. + */ + whileElementsMounted?: ( + reference: ReferenceElement, + floating: HTMLElement, + update: () => void, + ) => VoidFunction | void; + /** Shorthand for `whileElementsMounted: makeAutoUpdate` with these options. */ + autoUpdate?: MaybeAccessor; +}; + +export type FloatingReturn = { + x: Accessor; + y: Accessor; + /** The placement actually used; differs from the requested one after a flip. */ + placement: Accessor; + strategy: Accessor; + middlewareData: Accessor; + /** `false` until the first position has been computed on the client. */ + isPositioned: Accessor; + /** Inline styles for the floating element. */ + styles: Accessor; + /** Recompute now. Safe to call from event handlers; does nothing without both elements. */ + update: () => void; +}; + +type Config = { + reference: ReferenceElement | null | undefined; + floating: HTMLElement | null | undefined; + options: ComputePositionOptions; + transform: boolean; +}; + +function sameResult(a: ComputePositionResult | undefined, b: ComputePositionResult | undefined) { + if (!a || !b) return a === b; + const am = a.middlewareData; + const bm = b.middlewareData; + return ( + a.x === b.x && + a.y === b.y && + a.placement === b.placement && + a.strategy === b.strategy && + am.flipped === bm.flipped && + am.shifted === bm.shifted && + am.availableWidth === bm.availableWidth && + am.availableHeight === bm.availableHeight && + am.transformOrigin === bm.transformOrigin && + am.arrow?.x === bm.arrow?.x && + am.arrow?.y === bm.arrow?.y && + am.arrow?.centerOffset === bm.arrow?.centerOffset + ); +} + +/** + * Reactive floating-element positioning. Recomputes whenever the elements or any option + * changes. SSR-safe: the server renders the unpositioned styles and never measures. + */ +export function createFloating(options: CreateFloatingOptions): FloatingReturn { + const readConfig = (): Config => { + const arrow = access(options.arrow); + return { + reference: access(options.reference), + floating: access(options.floating), + transform: access(options.transform) ?? true, + options: { + placement: access(options.placement), + strategy: access(options.strategy), + rtl: access(options.rtl), + offset: access(options.offset), + flip: access(options.flip), + shift: access(options.shift), + size: access(options.size), + boundary: access(options.boundary), + rootBoundary: access(options.rootBoundary), + arrow: + arrow && + ({ + element: access(arrow.element), + padding: arrow.padding, + } satisfies ArrowOptions), + }, + }; + }; + + const config = createMemo(readConfig); + const [result, setResult] = createSignal(undefined, { + ...INTERNAL_OPTIONS, + equals: sameResult, + }); + + // The latest config the first effect has seen; lets `update` run from untracked contexts. + let current: Config | undefined; + + const run = (cfg: Config) => { + if (isServer || !cfg.reference || !cfg.floating) return; + setResult(computePosition(cfg.reference, cfg.floating, cfg.options)); + }; + const update = () => run(current ?? untrack(config)); + + createEffect(config, cfg => { + current = cfg; + run(cfg); + }); + + createEffect( + () => + [access(options.reference), access(options.floating), access(options.autoUpdate)] as const, + ([reference, floating, auto]) => { + if (!reference || !floating) return; + if (options.whileElementsMounted) { + return options.whileElementsMounted(reference, floating, update) || undefined; + } + if (auto) { + return makeAutoUpdate(reference, floating, update, auto === true ? {} : auto); + } + }, + ); + + const strategy = createMemo(() => access(options.strategy) ?? "absolute"); + const x = createMemo(() => result()?.x ?? 0); + const y = createMemo(() => result()?.y ?? 0); + const placement = createMemo(() => result()?.placement ?? access(options.placement) ?? "bottom"); + + const styles = createMemo(() => { + const position = strategy(); + if (!result()) return { position, top: "0", left: "0" }; + const dpr = (!isServer && globalThis.devicePixelRatio) || 1; + const round = (v: number) => Math.round(v * dpr) / dpr; + if (access(options.transform) ?? true) { + return { + position, + top: "0", + left: "0", + transform: `translate(${round(x())}px, ${round(y())}px)`, + }; + } + return { position, top: `${round(y())}px`, left: `${round(x())}px` }; + }); + + return { + x, + y, + placement, + strategy, + middlewareData: () => result()?.middlewareData, + isPositioned: () => result() !== undefined, + styles, + update, + }; +} diff --git a/packages/floating/src/index.ts b/packages/floating/src/index.ts new file mode 100644 index 000000000..07dad29b6 --- /dev/null +++ b/packages/floating/src/index.ts @@ -0,0 +1,16 @@ +export * from "./types.ts"; +export { + computePosition, + computePositionFromRects, + getClippingRect, + getOppositePlacement, + type SolveExtras, +} from "./compute.ts"; +export { makeAutoUpdate, autoUpdate, type AutoUpdateOptions } from "./autoUpdate.ts"; +export { getSizeCssVars, applySizeCssVars } from "./css.ts"; +export { + createFloating, + type CreateFloatingOptions, + type FloatingReturn, + type FloatingStyles, +} from "./floating.ts"; diff --git a/packages/floating/src/types.ts b/packages/floating/src/types.ts new file mode 100644 index 000000000..d141c676a --- /dev/null +++ b/packages/floating/src/types.ts @@ -0,0 +1,134 @@ +export type Side = "top" | "right" | "bottom" | "left"; +export type Alignment = "start" | "end"; +export type Placement = Side | `${Side}-${Alignment}`; +export type Strategy = "absolute" | "fixed"; + +export type Point = { x: number; y: number }; +export type Size = { width: number; height: number }; +export type Rect = Point & Size; +export type Sides = { top: number; right: number; bottom: number; left: number }; +/** A single number applies to all four sides. */ +export type Padding = number | Partial; + +/** Anything with a bounding box: a DOM element, or a virtual anchor such as the cursor. */ +export type VirtualElement = { + getBoundingClientRect(): { + x?: number; + y?: number; + left?: number; + top?: number; + width: number; + height: number; + }; + /** Used by `makeAutoUpdate` to find scrollable ancestors for a virtual anchor. */ + contextElement?: Element; +}; +export type ReferenceElement = Element | VirtualElement; + +export type OffsetOptions = number | { mainAxis?: number; crossAxis?: number }; + +export type FlipOptions = { + /** + * Placements to try, in order, when the preferred one overflows. + * Defaults to the opposite side with the same alignment. + */ + fallbackPlacements?: readonly Placement[]; + /** Distance kept between the floating element and the boundary. Default `0`. */ + padding?: Padding; +}; + +export type ShiftOptions = { + /** Distance kept between the floating element and the boundary. Default `0`. */ + padding?: Padding; + /** Shift along the axis perpendicular to the placement side. Default `true`. */ + crossAxis?: boolean; + /** Shift along the placement axis, letting the element overlap the reference. Default `false`. */ + mainAxis?: boolean; + /** + * Keep the floating element attached to the reference: shifting never moves it past the + * reference edges. `true` or `{ offset }` (distance that must stay overlapping). + */ + limit?: boolean | { offset?: number }; +}; + +export type SizeApplyArgs = { + availableWidth: number; + availableHeight: number; + transformOrigin: string; + placement: Placement; + elements: { reference: ReferenceElement; floating: HTMLElement }; +}; + +export type SizeOptions = { + /** Distance kept between the floating element and the boundary. Default `0`. */ + padding?: Padding; + /** + * Called after the position is solved. Mutating the floating element's size here makes + * `computePosition` measure again and re-solve once. + */ + apply?: (args: SizeApplyArgs) => void; +}; + +export type ArrowOptions = { + element: Element | null | undefined; + /** Minimum distance between the arrow and the floating element's edges. Default `0`. */ + padding?: number; +}; + +export type Boundary = Element | readonly Element[] | Rect; +export type RootBoundary = "viewport" | "document" | Rect; + +export type PositionOptions = { + /** Default `"bottom"`. */ + placement?: Placement; + /** Default `"absolute"`. */ + strategy?: Strategy; + /** Flips what `-start` / `-end` mean on top and bottom placements. */ + rtl?: boolean; + offset?: OffsetOptions; + /** Opt in with `true` or options. */ + flip?: boolean | FlipOptions; + /** Opt in with `true` or options. */ + shift?: boolean | ShiftOptions; + size?: SizeOptions; + /** Elements (or a rect, in viewport coordinates) the floating element must stay within. */ + boundary?: Boundary; + /** Default `"viewport"`, using `visualViewport` when available. */ + rootBoundary?: RootBoundary; +}; + +export type ComputePositionOptions = PositionOptions & { + arrow?: ArrowOptions; +}; + +export type ArrowData = { + /** Set for top/bottom placements. */ + x?: number; + /** Set for left/right placements. */ + y?: number; + /** Non-zero when the arrow had to be clamped and no longer points at the reference center. */ + centerOffset: number; +}; + +export type MiddlewareData = { + arrow?: ArrowData; + /** The final placement differs from the requested one. */ + flipped: boolean; + /** The floating element was moved by `shift`. */ + shifted: boolean; + /** How far `shift` moved the element on each axis. */ + shift: Point; + /** Space between the floating element's start and the boundary edge, in px. */ + availableWidth: number; + availableHeight: number; + /** Origin pointing at the reference (or arrow) center, e.g. `"24px 0px"`. */ + transformOrigin: string; +}; + +export type ComputePositionResult = { + x: number; + y: number; + placement: Placement; + strategy: Strategy; + middlewareData: MiddlewareData; +}; diff --git a/packages/floating/stories/floating.stories.tsx b/packages/floating/stories/floating.stories.tsx new file mode 100644 index 000000000..9be1de60a --- /dev/null +++ b/packages/floating/stories/floating.stories.tsx @@ -0,0 +1,75 @@ +import { createSignal } from "solid-js"; +import preview from "../../../.storybook/preview.js"; +import { createFloating, makeAutoUpdate, type Placement } from "../src/index.js"; +import readme from "../README.md?raw"; +import { + BoolRow, + Button, + ButtonRow, + Container, + StatRow, + popoverStyle, +} from "../../../.storybook/ui/index.js"; + +const meta = preview.meta({ + title: "UI Patterns/Floating", + tags: ["autodocs"], + parameters: { + layout: "centered", + docs: { description: { component: readme } }, + }, +}); + +export default meta; + +const PLACEMENTS: Placement[] = ["top", "right", "bottom", "left"]; + +export const Popover = meta.story({ + name: "Popover with flip and shift", + parameters: { + docs: { + description: { + story: + "The popover starts on the chosen side, flips when it would leave the viewport and shifts to stay inside it. Resize the window or scroll to watch it follow the button.", + }, + }, + }, + render: () => { + const [reference, setReference] = createSignal(null); + const [floating, setFloating] = createSignal(null); + const [placement, setPlacement] = createSignal("bottom"); + const f = createFloating({ + reference, + floating, + placement, + offset: 8, + flip: true, + shift: { padding: 8 }, + whileElementsMounted: makeAutoUpdate, + }); + + return ( + + + + + + {PLACEMENTS.map(p => ( + + ))} + +
+ +
+
+ Floating content +
+
+ ); + }, +}); diff --git a/packages/floating/test/autoUpdate.test.ts b/packages/floating/test/autoUpdate.test.ts new file mode 100644 index 000000000..26f978bf8 --- /dev/null +++ b/packages/floating/test/autoUpdate.test.ts @@ -0,0 +1,262 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { autoUpdate, makeAutoUpdate } from "../src/index.js"; +import { defineGlobal, mockRect, rect } from "./helpers.js"; + +const restore: (() => void)[] = []; +let observers: MockResizeObserver[] = []; + +class MockResizeObserver { + observed = new Set(); + disconnected = false; + constructor(public callback: () => void) { + observers.push(this); + } + observe(el: Element) { + this.observed.add(el); + } + unobserve(el: Element) { + this.observed.delete(el); + } + disconnect() { + this.disconnected = true; + this.observed.clear(); + } +} + +beforeEach(() => { + observers = []; + restore.push(defineGlobal(window, "ResizeObserver", MockResizeObserver)); +}); +afterEach(() => { + restore.splice(0).forEach(fn => fn()); + document.body.innerHTML = ""; +}); + +function tree() { + const scroller = document.createElement("div"); + scroller.style.overflow = "auto"; + const plain = document.createElement("div"); + const reference = mockRect(document.createElement("button"), rect(10, 10, 10, 10)); + scroller.append(plain, reference); + const floating = mockRect(document.createElement("div"), rect(0, 0, 10, 10)); + document.body.append(scroller, floating); + return { scroller, plain, reference, floating }; +} + +describe("makeAutoUpdate", () => { + test("autoUpdate is an alias", () => { + expect(autoUpdate).toBe(makeAutoUpdate); + }); + + test("does not call update on setup", () => { + const { reference, floating } = tree(); + const update = vi.fn(); + makeAutoUpdate(reference, floating, update)(); + expect(update).not.toHaveBeenCalled(); + }); + + test("updates on scroll of scrollable ancestors and the window", () => { + const { scroller, plain, reference, floating } = tree(); + const update = vi.fn(); + const stop = makeAutoUpdate(reference, floating, update); + scroller.dispatchEvent(new Event("scroll")); + expect(update).toHaveBeenCalledTimes(1); + window.dispatchEvent(new Event("scroll")); + expect(update).toHaveBeenCalledTimes(2); + // not scrollable: not listened to + plain.dispatchEvent(new Event("scroll")); + expect(update).toHaveBeenCalledTimes(2); + stop(); + }); + + test("scroll ancestors of the floating element are observed too", () => { + const { reference } = tree(); + const portalScroller = document.createElement("div"); + portalScroller.style.overflowY = "scroll"; + const floating = mockRect(document.createElement("div"), rect(0, 0, 1, 1)); + portalScroller.append(floating); + document.body.append(portalScroller); + const update = vi.fn(); + const stop = makeAutoUpdate(reference, floating, update); + portalScroller.dispatchEvent(new Event("scroll")); + expect(update).toHaveBeenCalledTimes(1); + stop(); + }); + + test("a virtual reference uses its contextElement", () => { + const { scroller, reference, floating } = tree(); + const update = vi.fn(); + const virtual = { + getBoundingClientRect: () => reference.getBoundingClientRect(), + contextElement: reference, + }; + const stop = makeAutoUpdate(virtual, floating, update); + scroller.dispatchEvent(new Event("scroll")); + expect(update).toHaveBeenCalledTimes(1); + expect(observers[0]!.observed.has(reference)).toBe(true); + stop(); + }); + + test("a virtual reference without context still tracks the window", () => { + const { floating } = tree(); + const update = vi.fn(); + const stop = makeAutoUpdate( + { getBoundingClientRect: () => rect(0, 0, 0, 0) }, + floating, + update, + ); + window.dispatchEvent(new Event("resize")); + expect(update).toHaveBeenCalledTimes(1); + expect([...observers[0]!.observed]).toEqual([floating]); + stop(); + }); + + test("updates on window resize and visualViewport events", () => { + const { reference, floating } = tree(); + const vv = new EventTarget(); + restore.push(defineGlobal(window, "visualViewport", vv)); + const update = vi.fn(); + const stop = makeAutoUpdate(reference, floating, update); + window.dispatchEvent(new Event("resize")); + vv.dispatchEvent(new Event("resize")); + vv.dispatchEvent(new Event("scroll")); + expect(update).toHaveBeenCalledTimes(3); + stop(); + vv.dispatchEvent(new Event("resize")); + expect(update).toHaveBeenCalledTimes(3); + }); + + test("observes both elements for resize", () => { + const { reference, floating } = tree(); + const update = vi.fn(); + const stop = makeAutoUpdate(reference, floating, update); + expect(observers).toHaveLength(1); + expect([...observers[0]!.observed]).toEqual([reference, floating]); + observers[0]!.callback(); + expect(update).toHaveBeenCalledTimes(1); + stop(); + expect(observers[0]!.disconnected).toBe(true); + }); + + test("cleanup removes every listener", () => { + const { scroller, reference, floating } = tree(); + const update = vi.fn(); + const stop = makeAutoUpdate(reference, floating, update); + stop(); + scroller.dispatchEvent(new Event("scroll")); + window.dispatchEvent(new Event("scroll")); + window.dispatchEvent(new Event("resize")); + expect(update).not.toHaveBeenCalled(); + }); + + test("cleanup is idempotent", () => { + const { reference, floating } = tree(); + const stop = makeAutoUpdate(reference, floating, vi.fn()); + stop(); + expect(() => stop()).not.toThrow(); + }); + + test("adds and removes the same listeners", () => { + const { reference, floating } = tree(); + const add = vi.spyOn(window, "addEventListener"); + const remove = vi.spyOn(window, "removeEventListener"); + const stop = makeAutoUpdate(reference, floating, vi.fn()); + stop(); + const added = add.mock.calls.map(c => c[0]).sort(); + const removed = remove.mock.calls.map(c => c[0]).sort(); + expect(added).toEqual(["resize", "scroll"]); + expect(removed).toEqual(added); + add.mockRestore(); + remove.mockRestore(); + }); + + test("options turn individual sources off", () => { + const { scroller, reference, floating } = tree(); + const update = vi.fn(); + const stop = makeAutoUpdate(reference, floating, update, { + ancestorScroll: false, + ancestorResize: false, + elementResize: false, + }); + scroller.dispatchEvent(new Event("scroll")); + window.dispatchEvent(new Event("scroll")); + window.dispatchEvent(new Event("resize")); + expect(update).not.toHaveBeenCalled(); + expect(observers).toHaveLength(0); + stop(); + }); + + test("works without ResizeObserver", () => { + restore.push(defineGlobal(window, "ResizeObserver", undefined)); + const { reference, floating } = tree(); + const stop = makeAutoUpdate(reference, floating, vi.fn()); + expect(observers).toHaveLength(0); + stop(); + }); + + describe("animationFrame", () => { + let frames: Map; + let id: number; + const flushFrame = () => { + const pending = [...frames.entries()]; + frames.clear(); + pending.forEach(([, cb]) => cb(0)); + }; + beforeEach(() => { + frames = new Map(); + id = 0; + restore.push( + defineGlobal(window, "requestAnimationFrame", (cb: FrameRequestCallback) => { + frames.set(++id, cb); + return id; + }), + defineGlobal(window, "cancelAnimationFrame", (n: number) => frames.delete(n)), + ); + }); + + test("is off by default", () => { + const { reference, floating } = tree(); + makeAutoUpdate(reference, floating, vi.fn())(); + expect(frames.size).toBe(0); + }); + + test("updates only on frames where the reference moved", () => { + const { reference, floating } = tree(); + let box = rect(10, 10, 10, 10); + mockRect(reference, () => box); + const update = vi.fn(); + const stop = makeAutoUpdate(reference, floating, update, { animationFrame: true }); + flushFrame(); + flushFrame(); + expect(update).not.toHaveBeenCalled(); + box = rect(15, 10, 10, 10); + flushFrame(); + expect(update).toHaveBeenCalledTimes(1); + flushFrame(); + expect(update).toHaveBeenCalledTimes(1); + stop(); + }); + + test("also notices floating size changes", () => { + const { reference, floating } = tree(); + let box = rect(0, 0, 10, 10); + mockRect(floating, () => box); + const update = vi.fn(); + const stop = makeAutoUpdate(reference, floating, update, { animationFrame: true }); + box = rect(0, 0, 20, 10); + flushFrame(); + expect(update).toHaveBeenCalledTimes(1); + stop(); + }); + + test("cleanup cancels the loop", () => { + const { reference, floating } = tree(); + const stop = makeAutoUpdate(reference, floating, vi.fn(), { animationFrame: true }); + expect(frames.size).toBe(1); + flushFrame(); + expect(frames.size).toBe(1); + stop(); + expect(frames.size).toBe(0); + }); + }); +}); diff --git a/packages/floating/test/compute.test.ts b/packages/floating/test/compute.test.ts new file mode 100644 index 000000000..cad4120f1 --- /dev/null +++ b/packages/floating/test/compute.test.ts @@ -0,0 +1,570 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; +import { + computePosition, + computePositionFromRects, + getOppositePlacement, + type Placement, +} from "../src/index.js"; +import { defineGlobal, mockRect, rect } from "./helpers.js"; + +const ref = rect(400, 300, 100, 40); +const fl = { width: 60, height: 30 }; +const clip = rect(0, 0, 1000, 800); + +const at = (placement: Placement, extra = {}, r = ref, size = fl, c = clip) => + computePositionFromRects(r, size, c, { placement, ...extra }); + +describe("placements", () => { + const expected: [Placement, number, number][] = [ + ["top", 420, 270], + ["top-start", 400, 270], + ["top-end", 440, 270], + ["bottom", 420, 340], + ["bottom-start", 400, 340], + ["bottom-end", 440, 340], + ["left", 340, 305], + ["left-start", 340, 300], + ["left-end", 340, 310], + ["right", 500, 305], + ["right-start", 500, 300], + ["right-end", 500, 310], + ]; + test.each(expected)("%s", (placement, x, y) => { + const r = at(placement); + expect([r.x, r.y, r.placement]).toEqual([x, y, placement]); + expect(r.middlewareData.flipped).toBe(false); + expect(r.middlewareData.shifted).toBe(false); + }); + + test("defaults to bottom / absolute", () => { + const r = computePositionFromRects(ref, fl, clip); + expect([r.x, r.y, r.placement, r.strategy]).toEqual([420, 340, "bottom", "absolute"]); + }); + + test("getOppositePlacement keeps alignment", () => { + expect(getOppositePlacement("top-start")).toBe("bottom-start"); + expect(getOppositePlacement("left")).toBe("right"); + expect(getOppositePlacement("right-end")).toBe("left-end"); + }); +}); + +describe("rtl", () => { + test.each<[Placement, number]>([ + ["top-start", 440], + ["top-end", 400], + ["bottom-start", 440], + ["bottom-end", 400], + ["bottom", 420], + ])("%s aligns to the mirrored edge", (placement, x) => { + expect(at(placement, { rtl: true }).x).toBe(x); + }); + + test("left/right alignment is unaffected", () => { + expect(at("left-start", { rtl: true }).y).toBe(300); + expect(at("right-end", { rtl: true }).y).toBe(310); + }); + + test("cross-axis offset mirrors on top/bottom only", () => { + expect(at("bottom-start", { offset: { crossAxis: 5 } }).x).toBe(405); + expect(at("bottom-start", { offset: { crossAxis: 5 }, rtl: true }).x).toBe(435); + expect(at("right-start", { offset: { crossAxis: 5 }, rtl: true }).y).toBe(305); + }); +}); + +describe("offset", () => { + test("number is main axis", () => { + expect(at("bottom", { offset: 10 }).y).toBe(350); + expect(at("top", { offset: 10 }).y).toBe(260); + expect(at("left", { offset: 10 }).x).toBe(330); + expect(at("right", { offset: 10 }).x).toBe(510); + }); + + test("crossAxis moves inward for end alignment", () => { + expect(at("bottom-end", { offset: { crossAxis: 5 } }).x).toBe(435); + expect(at("bottom", { offset: { crossAxis: 5 } }).x).toBe(425); + expect(at("right-start", { offset: { mainAxis: 2, crossAxis: 5 } })).toMatchObject({ + x: 502, + y: 305, + }); + expect(at("right-end", { offset: { crossAxis: 5 } }).y).toBe(305); + }); +}); + +describe("flip", () => { + test("is opt-in", () => { + const r = at("bottom", {}, rect(400, 770, 100, 20)); + expect(r.placement).toBe("bottom"); + }); + + test("flips to the opposite side when the preferred one overflows", () => { + const r = at("bottom-start", { flip: true }, rect(400, 770, 100, 20)); + expect([r.x, r.y, r.placement, r.middlewareData.flipped]).toEqual([ + 400, + 740, + "top-start", + true, + ]); + }); + + test("flips on every side", () => { + expect(at("top", { flip: true }, rect(400, 10, 100, 20)).placement).toBe("bottom"); + expect(at("left", { flip: true }, rect(10, 300, 20, 40)).placement).toBe("right"); + expect(at("right", { flip: true }, rect(970, 300, 20, 40)).placement).toBe("left"); + }); + + test("stays put when it fits", () => { + const r = at("bottom", { flip: true }); + expect(r.middlewareData.flipped).toBe(false); + }); + + test("flip padding makes a near-miss overflow", () => { + const near = rect(400, 730, 100, 20); // floating bottom edge at 780 + expect(at("bottom", { flip: true }, near).placement).toBe("bottom"); + expect(at("bottom", { flip: { padding: 30 } }, near).placement).toBe("top"); + }); + + test("offset counts towards overflow", () => { + const near = rect(400, 740, 100, 20); // 760 + 30 = 790 fits, +20 offset overflows + expect(at("bottom", { flip: true }, near).placement).toBe("bottom"); + expect(at("bottom", { flip: true, offset: 20 }, near).placement).toBe("top"); + }); + + test("tries fallbackPlacements in order and takes the first that fits", () => { + // no room below, room above is also tight: only `right` fits + const r = at( + "bottom", + { flip: { fallbackPlacements: ["top", "right"] } }, + rect(400, 10, 100, 785), + fl, + rect(0, 0, 1000, 800), + ); + expect(r.placement).toBe("right"); + expect(r.middlewareData.flipped).toBe(true); + }); + + test("picks the least-overflowing placement when none fit", () => { + const tiny = rect(0, 0, 1000, 50); + const r = at("top", { flip: true }, rect(400, 10, 100, 20), fl, tiny); // top: 20, bottom: 10 + expect(r.placement).toBe("bottom"); + const keep = at("bottom", { flip: true }, rect(400, 10, 100, 20), fl, tiny); + expect(keep.placement).toBe("bottom"); + expect(keep.middlewareData.flipped).toBe(false); + }); + + test("empty fallbackPlacements disables flipping", () => { + expect( + at("bottom", { flip: { fallbackPlacements: [] } }, rect(400, 770, 100, 20)).placement, + ).toBe("bottom"); + }); + + test("works with rtl alignment", () => { + const r = at("bottom-start", { flip: true, rtl: true }, rect(400, 770, 100, 20)); + expect([r.placement, r.x]).toEqual(["top-start", 440]); + }); +}); + +describe("shift", () => { + test("is opt-in", () => { + expect(at("bottom", {}, rect(980, 300, 10, 40)).x).toBe(955); + }); + + test("keeps the element inside the right and left edges", () => { + const right = at("bottom", { shift: true }, rect(980, 300, 10, 40)); + expect([right.x, right.middlewareData.shifted, right.middlewareData.shift]).toEqual([ + 940, + true, + { x: -15, y: 0 }, + ]); + const left = at("bottom", { shift: true }, rect(0, 300, 10, 40)); + expect([left.x, left.middlewareData.shift.x]).toEqual([0, 25]); + }); + + test("keeps the element inside the top and bottom edges for side placements", () => { + expect(at("right", { shift: true }, rect(400, 790, 10, 10)).y).toBe(770); + expect(at("left", { shift: true }, rect(400, 0, 10, 10)).y).toBe(0); + }); + + test("padding", () => { + expect(at("bottom", { shift: { padding: 8 } }, rect(980, 300, 10, 40)).x).toBe(932); + expect(at("bottom", { shift: { padding: { left: 20 } } }, rect(0, 300, 10, 40)).x).toBe(20); + }); + + test("does nothing when it already fits", () => { + const r = at("bottom", { shift: true }); + expect(r.middlewareData.shifted).toBe(false); + expect(r.middlewareData.shift).toEqual({ x: 0, y: 0 }); + }); + + test("does not move the main axis by default; mainAxis lets it overlap the reference", () => { + const edge = rect(400, 790, 100, 10); // bottom: y = 800, 30 tall + expect(at("bottom", { shift: true }, edge).y).toBe(800); + expect(at("bottom", { shift: { mainAxis: true } }, edge).y).toBe(770); + }); + + test("crossAxis: false", () => { + expect(at("bottom", { shift: { crossAxis: false } }, rect(980, 300, 10, 40)).x).toBe(955); + }); + + test("without a limiter the element detaches from an off-screen reference", () => { + expect(at("bottom", { shift: true }, rect(1100, 300, 10, 40)).x).toBe(940); + expect(at("bottom", { shift: true }, rect(-50, 300, 10, 40)).x).toBe(0); + }); + + test("limit keeps the element attached to the reference", () => { + expect(at("bottom", { shift: { limit: true } }, rect(1100, 300, 10, 40)).x).toBe(1040); + expect(at("bottom", { shift: { limit: true } }, rect(-50, 300, 10, 40)).x).toBe(-40); + }); + + test("limit offset keeps some overlap", () => { + const r = at("bottom", { shift: { limit: { offset: 4 } } }, rect(1100, 300, 10, 40)); + expect(r.x).toBe(1044); + }); + + test("limit does not undo an unshifted position", () => { + expect(at("bottom", { shift: { limit: true } }).x).toBe(420); + }); + + test("element larger than the boundary pins to the start edge", () => { + expect(at("bottom", { shift: true }, ref, { width: 2000, height: 30 }).x).toBe(0); + }); + + test("works after a flip", () => { + const r = at("bottom", { flip: true, shift: true }, rect(980, 770, 10, 20)); + expect([r.placement, r.x, r.y]).toEqual(["top", 940, 740]); + }); +}); + +describe("size / available space", () => { + test("available height below and above", () => { + expect(at("bottom").middlewareData.availableHeight).toBe(800 - 340); + expect(at("top").middlewareData.availableHeight).toBe(300); + }); + + test("available width on the side placements", () => { + expect(at("right").middlewareData.availableWidth).toBe(1000 - 500); + expect(at("left").middlewareData.availableWidth).toBe(400); + }); + + test("grows towards the alignment side", () => { + // bottom-start: floating starts at ref.x, so it can grow to the right + expect(at("bottom-start").middlewareData.availableWidth).toBe(600); + // bottom-end: its right edge is at ref right, so it can grow to the left + expect(at("bottom-end").middlewareData.availableWidth).toBe(500); + expect(at("bottom-end", { rtl: true }).middlewareData.availableWidth).toBe(600); + // right-end: bottom aligned, grows up + expect(at("right-end").middlewareData.availableHeight).toBe(340); + expect(at("right-start").middlewareData.availableHeight).toBe(500); + }); + + test("padding is subtracted", () => { + expect(at("bottom", { size: { padding: 10 } }).middlewareData.availableHeight).toBe(450); + expect(at("bottom", { size: { padding: { bottom: 20 } } }).middlewareData.availableHeight).toBe( + 440, + ); + }); + + test("never negative", () => { + expect(at("bottom", {}, rect(400, 900, 100, 10)).middlewareData.availableHeight).toBe(0); + }); + + test("measured after flip and shift", () => { + const r = at("bottom", { flip: true }, rect(400, 770, 100, 20)); + expect(r.middlewareData.availableHeight).toBe(770); + const s = at("bottom", { shift: true }, rect(980, 300, 10, 40)); + expect(s.middlewareData.availableWidth).toBe(60); + }); +}); + +describe("transform origin", () => { + test("points at the reference center", () => { + expect(at("bottom").middlewareData.transformOrigin).toBe("30px 0px"); + expect(at("top").middlewareData.transformOrigin).toBe("30px 30px"); + expect(at("right").middlewareData.transformOrigin).toBe("0px 15px"); + expect(at("left").middlewareData.transformOrigin).toBe("60px 15px"); + }); + + test("is clamped to the floating element", () => { + expect(at("bottom-start", {}, rect(400, 300, 300, 40)).middlewareData.transformOrigin).toBe( + "60px 0px", + ); + expect(at("bottom-end", {}, rect(400, 300, 300, 40)).middlewareData.transformOrigin).toBe( + "0px 0px", + ); + }); +}); + +describe("arrow", () => { + const arrow = { width: 10, height: 10 }; + const solve = (placement: Placement, extra = {}, padding?: number, r = ref) => + computePositionFromRects( + r, + fl, + clip, + { placement, ...extra }, + { arrow: { ...arrow, padding } }, + ); + + test("is absent without an arrow", () => { + expect(at("bottom").middlewareData.arrow).toBeUndefined(); + }); + + test("points at the reference center", () => { + expect(solve("bottom").middlewareData.arrow).toEqual({ x: 25, centerOffset: 0 }); + expect(solve("bottom-start").middlewareData.arrow).toEqual({ x: 45, centerOffset: 0 }); + expect(solve("right-start").middlewareData.arrow).toEqual({ y: 15, centerOffset: 0 }); + }); + + test("clamps to padding and reports the center offset", () => { + // bottom-end: floating x=440, ref center 450 -> desired 5; padding 8 -> 8 + expect(solve("bottom-end", {}, 8).middlewareData.arrow).toEqual({ x: 8, centerOffset: -3 }); + // bottom-start on a wide reference: desired is past the far edge + const wide = solve("bottom-start", {}, 4, rect(400, 300, 300, 40)).middlewareData.arrow!; + expect(wide.x).toBe(46); + expect(wide.centerOffset).toBe(150 - 5 - 46); + }); + + test("follows the shifted position", () => { + const r = solve("bottom", { shift: true }, 0, rect(980, 300, 10, 40)); + // floating x = 940; reference center 985 -> 985 - 940 - 5 = 40 + expect(r.middlewareData.arrow).toEqual({ x: 40, centerOffset: 0 }); + }); + + test("moves the transform origin to the arrow", () => { + expect(solve("bottom-start").middlewareData.transformOrigin).toBe("50px 0px"); + }); + + test("rtl", () => { + // bottom-start in rtl: floating x = 440, center 450 -> 5 + expect(solve("bottom-start", { rtl: true }).middlewareData.arrow).toEqual({ + x: 5, + centerOffset: 0, + }); + }); +}); + +describe("computePosition (DOM)", () => { + const cleanups: (() => void)[] = []; + afterEach(() => { + cleanups.splice(0).forEach(fn => fn()); + document.body.innerHTML = ""; + vi.restoreAllMocks(); + }); + const global = (target: object, key: string, value: unknown) => + cleanups.push(defineGlobal(target, key, value)); + + const setup = (refRect = ref, flRect = rect(0, 0, 60, 30)) => { + const reference = mockRect(document.createElement("button"), refRect); + const floating = mockRect(document.createElement("div"), flRect); + document.body.append(reference, floating); + global(window, "innerWidth", 1000); + global(window, "innerHeight", 800); + return { reference, floating }; + }; + + test("measures elements and defaults to the viewport", () => { + const { reference, floating } = setup(rect(400, 770, 100, 20)); + const r = computePosition(reference, floating, { placement: "bottom", flip: true }); + expect([r.x, r.y, r.placement]).toEqual([420, 740, "top"]); + }); + + test("accepts a virtual reference", () => { + const { floating } = setup(); + const r = computePosition( + { getBoundingClientRect: () => ({ x: 100, y: 100, width: 0, height: 0 }) } as never, + floating, + { placement: "bottom" }, + ); + expect([r.x, r.y]).toEqual([70, 100]); + }); + + test("virtual references may use left/top", () => { + const { floating } = setup(); + const r = computePosition( + { getBoundingClientRect: () => ({ left: 100, top: 100, width: 0, height: 0 }) }, + floating, + { placement: "bottom" }, + ); + expect([r.x, r.y]).toEqual([70, 100]); + }); + + describe("strategy", () => { + test("fixed uses viewport coordinates", () => { + const { reference, floating } = setup(); + global(window, "scrollY", 200); + global(window, "scrollX", 50); + const r = computePosition(reference, floating, { strategy: "fixed" }); + expect([r.x, r.y, r.strategy]).toEqual([420, 340, "fixed"]); + }); + + test("absolute adds the document scroll when there is no positioned ancestor", () => { + const { reference, floating } = setup(); + global(window, "scrollY", 200); + global(window, "scrollX", 50); + const r = computePosition(reference, floating, { strategy: "absolute" }); + expect([r.x, r.y]).toEqual([470, 540]); + }); + + test("absolute is relative to the offset parent", () => { + const { reference, floating } = setup(); + const parent = mockRect(document.createElement("div"), rect(50, 60, 500, 500)); + global(parent, "clientLeft", 2); + global(parent, "clientTop", 3); + global(parent, "scrollLeft", 10); + global(parent, "scrollTop", 20); + global(floating, "offsetParent", parent); + const r = computePosition(reference, floating, { strategy: "absolute" }); + // origin = (50 + 2 - 10, 60 + 3 - 20) + expect([r.x, r.y]).toEqual([420 - 42, 340 - 43]); + }); + + test("a static body is treated as the document", () => { + const { reference, floating } = setup(); + global(floating, "offsetParent", document.body); + global(window, "scrollY", 100); + expect(computePosition(reference, floating).y).toBe(440); + }); + + test("a positioned body is the offset parent", () => { + const { reference, floating } = setup(); + mockRect(document.body, rect(0, -100, 1000, 2000)); + document.body.style.position = "relative"; + global(floating, "offsetParent", document.body); + expect(computePosition(reference, floating).y).toBe(440); + document.body.style.position = ""; + }); + + test("fixed and absolute agree on size and flip results", () => { + const { reference, floating } = setup(rect(400, 770, 100, 20)); + global(window, "scrollY", 300); + const a = computePosition(reference, floating, { flip: true, strategy: "absolute" }); + const f = computePosition(reference, floating, { flip: true, strategy: "fixed" }); + expect(a.placement).toBe(f.placement); + expect(a.y - f.y).toBe(300); + }); + }); + + describe("boundaries", () => { + test("uses visualViewport when available", () => { + const { reference, floating } = setup(rect(280, 300, 10, 20)); + global(window, "visualViewport", { offsetLeft: 10, offsetTop: 20, width: 300, height: 400 }); + const r = computePosition(reference, floating, { placement: "bottom", shift: true }); + // viewport right edge is 310 -> floating x max 250 + expect(r.x).toBe(250); + }); + + test("falls back to documentElement client size", () => { + const { reference, floating } = setup(rect(280, 300, 10, 20)); + global(document.documentElement, "clientWidth", 300); + global(document.documentElement, "clientHeight", 400); + global(window, "visualViewport", undefined); + const r = computePosition(reference, floating, { shift: true }); + expect(r.x).toBe(240); + }); + + test("boundary element is intersected with the viewport", () => { + const { reference, floating } = setup(rect(400, 300, 20, 20)); + const boundary = mockRect(document.createElement("div"), rect(100, 100, 340, 400)); + const r = computePosition(reference, floating, { shift: true, boundary }); + // boundary right = 440 -> x max 380 + expect(r.x).toBe(380); + }); + + test("multiple boundary elements are intersected", () => { + const { reference, floating } = setup(rect(400, 300, 20, 20)); + const a = mockRect(document.createElement("div"), rect(0, 0, 500, 500)); + const b = mockRect(document.createElement("div"), rect(0, 0, 440, 500)); + expect(computePosition(reference, floating, { shift: true, boundary: [a, b] }).x).toBe(380); + }); + + test("boundary rect", () => { + const { reference, floating } = setup(rect(400, 300, 20, 20)); + expect( + computePosition(reference, floating, { shift: true, boundary: rect(0, 0, 430, 800) }).x, + ).toBe(370); + }); + + test("rootBoundary rect replaces the viewport", () => { + const { reference, floating } = setup(rect(400, 300, 20, 20)); + const r = computePosition(reference, floating, { + shift: true, + rootBoundary: rect(0, 0, 410, 800), + }); + expect(r.x).toBe(350); + }); + + test("rootBoundary: document spans the scrollable area", () => { + const { reference, floating } = setup(rect(1500, 300, 20, 20)); + global(document.documentElement, "scrollWidth", 2000); + global(document.documentElement, "scrollHeight", 3000); + const doc = computePosition(reference, floating, { shift: true, rootBoundary: "document" }); + expect(doc.x).toBe(1500 + 10 - 30); + const viewport = computePosition(reference, floating, { shift: true }); + expect(viewport.x).toBe(940); + }); + + test("disjoint boundaries leave no room", () => { + const { reference, floating } = setup(); + const boundary = rect(2000, 2000, 10, 10); + const r = computePosition(reference, floating, { boundary }); + expect(r.middlewareData.availableHeight).toBe(0); + }); + }); + + describe("rtl detection", () => { + test("reads direction from the floating element when not given", () => { + const { reference, floating } = setup(); + floating.style.direction = "rtl"; + expect(computePosition(reference, floating, { placement: "bottom-start" }).x).toBe(440); + expect( + computePosition(reference, floating, { placement: "bottom-start", rtl: false }).x, + ).toBe(400); + }); + }); + + describe("arrow", () => { + test("measures the arrow element", () => { + const { reference, floating } = setup(); + const arrow = mockRect(document.createElement("div"), rect(0, 0, 10, 10)); + const r = computePosition(reference, floating, { arrow: { element: arrow } }); + expect(r.middlewareData.arrow).toEqual({ x: 25, centerOffset: 0 }); + }); + + test("a missing arrow element is ignored", () => { + const { reference, floating } = setup(); + const r = computePosition(reference, floating, { arrow: { element: null } }); + expect(r.middlewareData.arrow).toBeUndefined(); + }); + }); + + describe("size.apply", () => { + test("is called with the available space and triggers a re-solve when the size changed", () => { + const { reference, floating } = setup(rect(400, 300, 100, 40)); + let size = { width: 60, height: 30 }; + mockRect(floating, () => ({ x: 0, y: 0, ...size })); + const apply = vi.fn(({ availableHeight }: { availableHeight: number }) => { + size = { width: 60, height: Math.min(size.height, 20) }; + expect(availableHeight).toBe(300); + }); + const r = computePosition(reference, floating, { placement: "top", size: { apply } }); + expect(apply).toHaveBeenCalledTimes(1); + expect(apply.mock.calls[0]![0]).toMatchObject({ + availableWidth: expect.any(Number), + placement: "top", + elements: { reference, floating }, + }); + // re-solved with the 20px tall element + expect(r.y).toBe(280); + }); + + test("does not re-solve when nothing changed", () => { + const { reference, floating } = setup(); + const spy = vi.spyOn(floating, "getBoundingClientRect"); + computePosition(reference, floating, { size: { apply: () => {} } }); + const withApply = spy.mock.calls.length; + spy.mockClear(); + computePosition(reference, floating, {}); + // one solve, plus the before/after size measurements around `apply` + expect(withApply).toBe(spy.mock.calls.length + 2); + }); + }); +}); diff --git a/packages/floating/test/css.test.ts b/packages/floating/test/css.test.ts new file mode 100644 index 000000000..5afaa4cfd --- /dev/null +++ b/packages/floating/test/css.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, test } from "vitest"; +import { applySizeCssVars, computePositionFromRects, getSizeCssVars } from "../src/index.js"; +import { rect } from "./helpers.js"; + +describe("size css vars", () => { + const { middlewareData } = computePositionFromRects( + rect(400, 300, 100, 40), + { width: 60, height: 30 }, + rect(0, 0, 1000, 800), + { placement: "bottom" }, + ); + + test("getSizeCssVars", () => { + expect(getSizeCssVars(middlewareData)).toEqual({ + "--available-width": "580px", + "--available-height": "460px", + "--transform-origin": "30px 0px", + }); + }); + + test("applySizeCssVars writes inline custom properties", () => { + const el = document.createElement("div"); + applySizeCssVars(el, middlewareData); + expect(el.style.getPropertyValue("--available-height")).toBe("460px"); + expect(el.style.getPropertyValue("--available-width")).toBe("580px"); + expect(el.style.getPropertyValue("--transform-origin")).toBe("30px 0px"); + }); +}); diff --git a/packages/floating/test/floating.test.ts b/packages/floating/test/floating.test.ts new file mode 100644 index 000000000..87afd8eab --- /dev/null +++ b/packages/floating/test/floating.test.ts @@ -0,0 +1,413 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { createEffect, createRoot, createSignal, flush } from "solid-js"; +import { createFloating, makeAutoUpdate, type Placement } from "../src/index.js"; +import { defineGlobal, mockRect, rect } from "./helpers.js"; + +const restore: (() => void)[] = []; +const disposers: (() => void)[] = []; + +beforeEach(() => { + restore.push(defineGlobal(window, "innerWidth", 1000), defineGlobal(window, "innerHeight", 800)); +}); +afterEach(() => { + disposers.splice(0).forEach(fn => fn()); + restore.splice(0).forEach(fn => fn()); + document.body.innerHTML = ""; +}); + +const root = (fn: () => T): T => + createRoot(dispose => { + disposers.push(dispose); + return fn(); + }); + +function els(refRect = rect(400, 300, 100, 40)) { + const reference = mockRect(document.createElement("button"), refRect); + const floating = mockRect(document.createElement("div"), rect(0, 0, 60, 30)); + document.body.append(reference, floating); + return { reference, floating }; +} + +describe("createFloating", () => { + test("is unpositioned until both elements exist", () => { + const [reference, setReference] = createSignal(null); + const [floating, setFloating] = createSignal(null); + const f = root(() => createFloating({ reference, floating })); + flush(); + expect(f.isPositioned()).toBe(false); + expect([f.x(), f.y(), f.placement()]).toEqual([0, 0, "bottom"]); + expect(f.styles()).toEqual({ position: "absolute", top: "0", left: "0" }); + expect(f.middlewareData()).toBeUndefined(); + + const e = els(); + setReference(e.reference); + flush(); + expect(f.isPositioned()).toBe(false); + setFloating(e.floating); + flush(); + expect(f.isPositioned()).toBe(true); + expect([f.x(), f.y(), f.placement()]).toEqual([420, 340, "bottom"]); + }); + + test("computes from plain elements and values", () => { + const e = els(); + const f = root(() => + createFloating({ + reference: e.reference, + floating: e.floating, + placement: "top-start", + offset: 10, + }), + ); + flush(); + expect([f.x(), f.y(), f.placement()]).toEqual([400, 260, "top-start"]); + }); + + test("styles use transform by default and top/left on request", () => { + const e = els(); + const [transform, setTransform] = createSignal(true); + const f = root(() => + createFloating({ reference: e.reference, floating: e.floating, transform }), + ); + flush(); + expect(f.styles()).toEqual({ + position: "absolute", + top: "0", + left: "0", + transform: "translate(420px, 340px)", + }); + setTransform(false); + flush(); + expect(f.styles()).toEqual({ position: "absolute", top: "340px", left: "420px" }); + }); + + test("strategy fixed", () => { + const e = els(); + restore.push(defineGlobal(window, "scrollY", 100)); + const [strategy, setStrategy] = createSignal<"absolute" | "fixed">("fixed"); + const f = root(() => + createFloating({ reference: e.reference, floating: e.floating, strategy }), + ); + flush(); + expect(f.strategy()).toBe("fixed"); + expect(f.styles().position).toBe("fixed"); + expect(f.y()).toBe(340); + setStrategy("absolute"); + flush(); + expect([f.strategy(), f.y()]).toEqual(["absolute", 440]); + }); + + test("reacts to option changes", () => { + const e = els(); + const [placement, setPlacement] = createSignal("bottom"); + const [offset, setOffset] = createSignal(0); + const [rtl, setRtl] = createSignal(false); + const f = root(() => + createFloating({ reference: e.reference, floating: e.floating, placement, offset, rtl }), + ); + flush(); + expect([f.x(), f.y()]).toEqual([420, 340]); + setPlacement("right-start"); + flush(); + expect([f.x(), f.y(), f.placement()]).toEqual([500, 300, "right-start"]); + setOffset(8); + flush(); + expect(f.x()).toBe(508); + setPlacement("bottom-start"); + setOffset(0); + flush(); + expect(f.x()).toBe(400); + setRtl(true); + flush(); + expect(f.x()).toBe(440); + }); + + test("flip and shift options", () => { + const e = els(rect(960, 770, 20, 20)); + const f = root(() => + createFloating({ + reference: e.reference, + floating: e.floating, + placement: "bottom", + flip: true, + shift: { padding: 4 }, + }), + ); + flush(); + expect(f.placement()).toBe("top"); + expect(f.middlewareData()).toMatchObject({ flipped: true, shifted: true }); + expect([f.x(), f.y()]).toEqual([936, 740]); + }); + + test("shift can be toggled live", () => { + const e = els(rect(960, 300, 20, 20)); + const [shift, setShift] = createSignal(false); + const f = root(() => createFloating({ reference: e.reference, floating: e.floating, shift })); + flush(); + expect(f.x()).toBe(940); // 960 + 10 - 30 fits, shift changes nothing + setShift(true); + flush(); + expect(f.x()).toBe(940); + }); + + test("arrow element may be a signal", () => { + const e = els(); + const [arrowEl, setArrowEl] = createSignal(null); + const f = root(() => + createFloating({ + reference: e.reference, + floating: e.floating, + arrow: { element: arrowEl, padding: 4 }, + }), + ); + flush(); + expect(f.middlewareData()?.arrow).toBeUndefined(); + setArrowEl(mockRect(document.createElement("i"), rect(0, 0, 10, 10))); + flush(); + expect(f.middlewareData()?.arrow).toEqual({ x: 25, centerOffset: 0 }); + }); + + test("size apply and css vars flow through", () => { + const e = els(); + const apply = vi.fn(); + root(() => createFloating({ reference: e.reference, floating: e.floating, size: { apply } })); + flush(); + expect(apply).toHaveBeenCalledWith( + expect.objectContaining({ availableHeight: 460, availableWidth: 580 }), + ); + }); + + test("update() recomputes after the layout changed", () => { + let box = rect(400, 300, 100, 40); + const e = els(); + mockRect(e.reference, () => box); + const f = root(() => createFloating({ reference: e.reference, floating: e.floating })); + flush(); + expect(f.y()).toBe(340); + box = rect(400, 500, 100, 40); + f.update(); + flush(); + expect(f.y()).toBe(540); + }); + + test("update() is a no-op without elements", () => { + const f = root(() => createFloating({ reference: undefined, floating: () => null })); + expect(() => f.update()).not.toThrow(); + flush(); + expect(f.isPositioned()).toBe(false); + }); + + test("a new element for the reference repositions", () => { + const a = els(rect(100, 100, 20, 20)); + const b = mockRect(document.createElement("span"), rect(600, 600, 20, 20)); + document.body.append(b); + const [reference, setReference] = createSignal(a.reference); + const f = root(() => createFloating({ reference, floating: a.floating })); + flush(); + expect(f.x()).toBe(100 + 10 - 30); + setReference(b); + flush(); + expect([f.x(), f.y()]).toEqual([580, 620]); + }); + + test("does not re-notify when the result is unchanged", () => { + const e = els(); + const f = root(() => createFloating({ reference: e.reference, floating: e.floating })); + flush(); + const seen: unknown[] = []; + root(() => { + createEffect(f.middlewareData, v => { + seen.push(v); + }); + }); + flush(); + expect(seen).toHaveLength(1); + f.update(); + f.update(); + flush(); + expect(seen).toHaveLength(1); + }); + + describe("whileElementsMounted", () => { + test("runs with the elements and an update function, cleans up on dispose", () => { + const e = els(); + const cleanup = vi.fn(); + const mounted = vi.fn(() => cleanup); + const dispose = root(() => { + createFloating({ + reference: e.reference, + floating: e.floating, + whileElementsMounted: mounted, + }); + return disposers.pop()!; + }); + flush(); + expect(mounted).toHaveBeenCalledTimes(1); + expect(mounted).toHaveBeenCalledWith(e.reference, e.floating, expect.any(Function)); + expect(cleanup).not.toHaveBeenCalled(); + dispose(); + expect(cleanup).toHaveBeenCalledTimes(1); + }); + + test("waits for both elements and cleans up when one goes away", () => { + const e = els(); + const [floating, setFloating] = createSignal(null); + const cleanup = vi.fn(); + const mounted = vi.fn(() => cleanup); + root(() => + createFloating({ reference: e.reference, floating, whileElementsMounted: mounted }), + ); + flush(); + expect(mounted).not.toHaveBeenCalled(); + setFloating(e.floating); + flush(); + expect(mounted).toHaveBeenCalledTimes(1); + setFloating(null); + flush(); + expect(cleanup).toHaveBeenCalledTimes(1); + }); + + test("may return nothing", () => { + const e = els(); + expect(() => { + root(() => + createFloating({ + reference: e.reference, + floating: e.floating, + whileElementsMounted: () => {}, + }), + ); + flush(); + }).not.toThrow(); + }); + + test("is not restarted by option changes", () => { + const e = els(); + const [placement, setPlacement] = createSignal("bottom"); + const mounted = vi.fn(() => () => {}); + root(() => + createFloating({ + reference: e.reference, + floating: e.floating, + placement, + whileElementsMounted: mounted, + }), + ); + flush(); + setPlacement("top"); + flush(); + expect(mounted).toHaveBeenCalledTimes(1); + }); + + test("update passed in recomputes with the latest options", () => { + const e = els(); + const [placement, setPlacement] = createSignal("bottom"); + let update!: () => void; + const f = root(() => + createFloating({ + reference: e.reference, + floating: e.floating, + placement, + whileElementsMounted: (_r, _f, u) => { + update = u; + }, + }), + ); + flush(); + setPlacement("top"); + flush(); + expect(f.placement()).toBe("top"); + update(); + flush(); + expect(f.placement()).toBe("top"); + }); + + test("works with makeAutoUpdate: repositions on window scroll", () => { + let box = rect(400, 300, 100, 40); + const e = els(); + mockRect(e.reference, () => box); + const f = root(() => + createFloating({ + reference: e.reference, + floating: e.floating, + whileElementsMounted: makeAutoUpdate, + }), + ); + flush(); + expect(f.y()).toBe(340); + box = rect(400, 100, 100, 40); + window.dispatchEvent(new Event("scroll")); + flush(); + expect(f.y()).toBe(140); + }); + }); + + describe("autoUpdate option", () => { + test("true subscribes to scroll and unsubscribes on dispose", () => { + let box = rect(400, 300, 100, 40); + const e = els(); + mockRect(e.reference, () => box); + const dispose = root(() => { + const f = createFloating({ + reference: e.reference, + floating: e.floating, + autoUpdate: true, + }); + return Object.assign(disposers.pop()!, { f }); + }); + flush(); + box = rect(400, 100, 100, 40); + window.dispatchEvent(new Event("scroll")); + flush(); + expect(dispose.f.y()).toBe(140); + dispose(); + box = rect(400, 50, 100, 40); + window.dispatchEvent(new Event("scroll")); + flush(); + expect(dispose.f.y()).toBe(140); + }); + + test("takes options and can be toggled", () => { + const e = els(); + let box = rect(400, 300, 100, 40); + mockRect(e.reference, () => box); + const [auto, setAuto] = createSignal(false); + const f = root(() => + createFloating({ reference: e.reference, floating: e.floating, autoUpdate: auto }), + ); + flush(); + box = rect(400, 100, 100, 40); + window.dispatchEvent(new Event("scroll")); + flush(); + expect(f.y()).toBe(340); + setAuto({ ancestorScroll: false }); + flush(); + window.dispatchEvent(new Event("scroll")); + flush(); + expect(f.y()).toBe(340); + setAuto(true); + flush(); + window.dispatchEvent(new Event("scroll")); + flush(); + expect(f.y()).toBe(140); + }); + + test("whileElementsMounted takes precedence", () => { + const e = els(); + const mounted = vi.fn(); + const add = vi.spyOn(window, "addEventListener"); + root(() => + createFloating({ + reference: e.reference, + floating: e.floating, + autoUpdate: true, + whileElementsMounted: mounted, + }), + ); + flush(); + expect(mounted).toHaveBeenCalledTimes(1); + expect(add.mock.calls.filter(c => c[0] === "scroll")).toHaveLength(0); + add.mockRestore(); + }); + }); +}); diff --git a/packages/floating/test/helpers.ts b/packages/floating/test/helpers.ts new file mode 100644 index 000000000..7497cd564 --- /dev/null +++ b/packages/floating/test/helpers.ts @@ -0,0 +1,35 @@ +import type { Rect } from "../src/index.js"; + +export type RectInput = { x: number; y: number; width: number; height: number }; + +/** Gives an element a fixed (or live, when a function) bounding box; jsdom has no layout. */ +export function mockRect(el: T, rect: RectInput | (() => RectInput)): T { + el.getBoundingClientRect = () => { + const r = typeof rect === "function" ? rect() : rect; + return { + ...r, + left: r.x, + top: r.y, + right: r.x + r.width, + bottom: r.y + r.height, + toJSON() {}, + } as DOMRect; + }; + return el; +} + +export const rect = (x: number, y: number, width: number, height: number): Rect => ({ + x, + y, + width, + height, +}); + +export function defineGlobal(target: object, key: string, value: unknown) { + const original = Object.getOwnPropertyDescriptor(target, key); + Object.defineProperty(target, key, { value, configurable: true, writable: true }); + return () => { + if (original) Object.defineProperty(target, key, original); + else delete (target as Record)[key]; + }; +} diff --git a/packages/floating/test/server.test.ts b/packages/floating/test/server.test.ts new file mode 100644 index 000000000..d090888ce --- /dev/null +++ b/packages/floating/test/server.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, test, vi } from "vitest"; +import { createRoot } from "solid-js"; +import { + applySizeCssVars, + computePositionFromRects, + createFloating, + makeAutoUpdate, +} from "../src/index.js"; + +describe("floating — SSR", () => { + test("computePositionFromRects is pure and works without a DOM", () => { + const r = computePositionFromRects( + { x: 400, y: 300, width: 100, height: 40 }, + { width: 60, height: 30 }, + { x: 0, y: 0, width: 1000, height: 800 }, + { placement: "top-start", flip: true, shift: true }, + ); + expect([r.x, r.y, r.placement]).toEqual([400, 270, "top-start"]); + }); + + test("createFloating renders stable unpositioned styles", () => { + createRoot(dispose => { + const f = createFloating({ + reference: () => null, + floating: () => null, + placement: "top", + strategy: "fixed", + autoUpdate: true, + }); + expect(f.isPositioned()).toBe(false); + expect([f.x(), f.y(), f.placement(), f.strategy()]).toEqual([0, 0, "top", "fixed"]); + expect(f.styles()).toEqual({ position: "fixed", top: "0", left: "0" }); + expect(f.middlewareData()).toBeUndefined(); + expect(() => f.update()).not.toThrow(); + dispose(); + }); + }); + + test("createFloating never measures on the server", () => { + const getBoundingClientRect = vi.fn(); + createRoot(dispose => { + const el = { getBoundingClientRect } as unknown as HTMLElement; + const whileElementsMounted = vi.fn(); + const f = createFloating({ reference: el, floating: el, whileElementsMounted }); + f.update(); + expect(f.isPositioned()).toBe(false); + expect(getBoundingClientRect).not.toHaveBeenCalled(); + dispose(); + }); + }); + + test("makeAutoUpdate is a no-op without a window", () => { + const update = vi.fn(); + const stop = makeAutoUpdate({} as Element, {} as HTMLElement, update); + expect(() => stop()).not.toThrow(); + expect(update).not.toHaveBeenCalled(); + }); + + test("css var helpers are safe to import", () => { + expect(typeof applySizeCssVars).toBe("function"); + }); +}); diff --git a/packages/floating/tsconfig.json b/packages/floating/tsconfig.json new file mode 100644 index 000000000..674e85d9a --- /dev/null +++ b/packages/floating/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig.json", + "include": ["src"] +} \ No newline at end of file diff --git a/packages/inert/CHANGELOG.md b/packages/inert/CHANGELOG.md new file mode 100644 index 000000000..176fafbee --- /dev/null +++ b/packages/inert/CHANGELOG.md @@ -0,0 +1 @@ +# @solid-primitives/inert diff --git a/packages/inert/LICENSE b/packages/inert/LICENSE new file mode 100644 index 000000000..38b41d975 --- /dev/null +++ b/packages/inert/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/inert/README.md b/packages/inert/README.md new file mode 100644 index 000000000..ef4ed80cc --- /dev/null +++ b/packages/inert/README.md @@ -0,0 +1,88 @@ +

+ Solid Primitives inert +

+ +# @solid-primitives/inert + +[![docs](https://img.shields.io/badge/-docs-blue?style=for-the-badge)](https://primitives.solidjs.community/package/inert) +[![version](https://img.shields.io/npm/v/@solid-primitives/inert?style=for-the-badge)](https://www.npmjs.com/package/@solid-primitives/inert) +[![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) + +Hide everything outside a modal layer from assistive technology and user interaction by marking it `aria-hidden` and/or `inert`. + +- [`makeInertOthers`](#makeinertothers) - non-reactive, returns a cleanup function. +- [`createInertOthers`](#createinertothers) - reactive and owner-aware, toggled by a signal. + +Both walk from the target element(s) up to the root and hide every sibling subtree that does not contain a target. Previous attribute values are restored on cleanup, stacked layers are ref-counted per node, and a `MutationObserver` covers nodes added later. On the server both are no-ops. + +## Installation + +```bash +npm install @solid-primitives/inert +# or +yarn add @solid-primitives/inert +# or +pnpm add @solid-primitives/inert +``` + +## `makeInertOthers` + +```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/inert"; + +const restore = makeInertOthers(dialogEl, { strategy: "both", ignore: toastRegionEl }); +// ...when the dialog closes +restore(); +``` + +## `createInertOthers` + +```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/inert"; + +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`, `enabled` or `ignore` restores the DOM and re-applies it. Disposal of the owner restores it too. + +## Behavior + +- **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. 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. +- **Dynamic content:** nodes appended to a walked parent are hidden, and nodes removed from the document are released. +- **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. + +## Changelog + +See [CHANGELOG.md](./CHANGELOG.md) diff --git a/packages/inert/deno.jsonc b/packages/inert/deno.jsonc new file mode 100644 index 000000000..1ac563dbe --- /dev/null +++ b/packages/inert/deno.jsonc @@ -0,0 +1,11 @@ +{ + "name": "@solid-primitives/inert", + "version": "0.0.1", + "description": "Hide everything outside a modal layer from assistive technology and user interaction (aria-hidden / inert)", + "license": "MIT", + "exports": "./src/index.ts", + "publish": { + "include": ["README.md", "LICENSE", "src/**/*.ts", "src/**/*.tsx", "package.json"], + "exclude": ["dist", "dev", "test", "node_modules", "vitest.config.ts", "tsconfig.json"], + }, +} diff --git a/packages/inert/dev/index.tsx b/packages/inert/dev/index.tsx new file mode 100644 index 000000000..e4cc24cb9 --- /dev/null +++ b/packages/inert/dev/index.tsx @@ -0,0 +1,24 @@ +import { type Component, createSignal } from "solid-js"; +import { createInertOthers } from "../src/index.js"; + +const App: Component = () => { + const [dialog, setDialog] = createSignal(); + const [open, setOpen] = createSignal(false); + createInertOthers(dialog, open, { strategy: "both" }); + + return ( +
+
+

Inert Others

+ +

Content outside the layer becomes aria-hidden and inert while it is open.

+
+ +
+ ); +}; + +export default App; diff --git a/packages/inert/package.json b/packages/inert/package.json new file mode 100644 index 000000000..f237d82e7 --- /dev/null +++ b/packages/inert/package.json @@ -0,0 +1,74 @@ +{ + "name": "@solid-primitives/inert", + "version": "0.0.1", + "description": "Hide everything outside a modal layer from assistive technology and user interaction (aria-hidden / inert)", + "author": "David Di Biase ", + "contributors": [], + "license": "MIT", + "homepage": "https://primitives.solidjs.community/package/inert", + "repository": { + "type": "git", + "url": "git+https://github.com/solidjs-community/solid-primitives.git" + }, + "bugs": { + "url": "https://github.com/solidjs-community/solid-primitives/issues" + }, + "primitive": { + "name": "inert", + "stage": 0, + "list": [ + "makeInertOthers", + "createInertOthers" + ], + "category": "UI Patterns", + "gzip": 1327 + }, + "keywords": [ + "solid", + "primitives", + "inert", + "aria-hidden", + "modal", + "a11y", + "dialog" + ], + "private": false, + "sideEffects": false, + "files": [ + "dist" + ], + "type": "module", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "browser": {}, + "exports": { + "import": { + "@solid-primitives/source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "typesVersions": {}, + "tsdown": { + "entry": "src/**/*.{ts,tsx}", + "outDir": "dist" + }, + "scripts": { + "dev": "node --import=@nothing-but/node-resolve-ts ../../scripts/dev.ts", + "build": "pnpm -w build", + "vitest": "vitest -c ../../configs/vitest.config.ts", + "test": "pnpm run vitest", + "test:ssr": "pnpm run vitest --mode ssr" + }, + "dependencies": { + "@solid-primitives/utils": "workspace:^" + }, + "peerDependencies": { + "@solidjs/web": "catalog:peer", + "solid-js": "catalog:peer" + }, + "devDependencies": { + "@solidjs/web": "catalog:", + "solid-js": "catalog:peer" + } +} diff --git a/packages/inert/src/index.ts b/packages/inert/src/index.ts new file mode 100644 index 000000000..05240ab54 --- /dev/null +++ b/packages/inert/src/index.ts @@ -0,0 +1 @@ +export * from "./inert.ts"; diff --git a/packages/inert/src/inert.ts b/packages/inert/src/inert.ts new file mode 100644 index 000000000..a0ca52f91 --- /dev/null +++ b/packages/inert/src/inert.ts @@ -0,0 +1,271 @@ +import { createEffect } from "solid-js"; +import { isServer } from "@solidjs/web"; +import { access, noop, type MaybeAccessor } 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. + * @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. + * @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 }; +type Layer = { + targets: HTMLElement[]; + sweep: () => void; +}; + +/** Shared per-node ref counts: the reason stacked layers can close in any order. */ +const states = new WeakMap(); +/** Open layers, lowest first. Upper layers' targets are protected from lower layers. */ +const layers: Layer[] = []; + +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); +} + +function acquire(el: Element, strategy: InertStrategy): Hold | undefined { + let state = states.get(el); + if (!state) { + state = { ariaCount: 0, ariaPrev: null, inertCount: 0, inertPrev: null }; + states.set(el, state); + } + const hold: Hold = { aria: false, inert: false }; + if (strategy !== "inert") { + 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 + state.ariaPrev = el.getAttribute("aria-hidden"); + el.setAttribute("aria-hidden", "true"); + state.ariaCount = 1; + hold.aria = true; + } + } + if (strategy !== "aria-hidden") { + 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; + } + } + return hold.aria || hold.inert ? hold : undefined; +} + +function release(el: Element, hold: Hold): void { + const state = states.get(el); + if (!state) 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; + } + 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; + + const strategy = options.strategy ?? "aria-hidden"; + const root = options.root ?? 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(); + }); + + const layer: Layer = { + targets: own, + sweep() { + if (disposed) return; + // protected = own targets + ignore + live regions + targets of layers opened above this one + const protectedEls: Element[] = [...own, ...toList(options.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. + if (strategy === "aria-hidden") { + const lower = layers.slice(0, layers.indexOf(layer)).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 = layers.indexOf(layer) + 1; i < layers.length; i++) + protectedEls.push(...layers[i]!.targets); + const inRoot = protectedEls.filter(el => root.contains(el)); + + const parents = new Set(); + const desired = new Set(); + for (const el of own) { + if (!root.contains(el)) continue; + for (let p = el.parentElement; p; p = p.parentElement) { + parents.add(p); + if (p === root) break; + } + } + // protected elements other than targets also need their own ancestors walked + for (const el of inRoot) + 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; + if (inRoot.some(p => child.contains(p))) 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 }); + }, + }; + + layers.push(layer); + for (const l of [...layers]) l.sweep(); + + return () => { + if (disposed) return; + observer.disconnect(); + for (const [el, hold] of held) release(el, hold); + held.clear(); + disposed = true; + 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, when the targets change, or when the owner is disposed. + * + * @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; + 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) return; + return makeInertOthers(state.list, { + strategy: options.strategy, + root: options.root, + ignore: state.ignore, + }); + }, + ); +} diff --git a/packages/inert/stories/inert.stories.tsx b/packages/inert/stories/inert.stories.tsx new file mode 100644 index 000000000..3244df93a --- /dev/null +++ b/packages/inert/stories/inert.stories.tsx @@ -0,0 +1,37 @@ +import { createSignal } from "solid-js"; +import preview from "../../../.storybook/preview.js"; +import { createInertOthers } from "../src/index.js"; +import readme from "../README.md?raw"; + +const meta = preview.meta({ + title: "UI Patterns/Inert", + tags: ["autodocs"], + parameters: { + layout: "centered", + docs: { description: { component: readme } }, + }, +}); + +export default meta; + +export const InertOutsideLayer = meta.story({ + name: "Inert outside a layer", + 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/inert/test/index.test.ts b/packages/inert/test/index.test.ts new file mode 100644 index 000000000..08e3e0d58 --- /dev/null +++ b/packages/inert/test/index.test.ts @@ -0,0 +1,447 @@ +import { afterEach, beforeEach, describe, expect, test } 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("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("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(); + }); +}); diff --git a/packages/inert/test/server.test.ts b/packages/inert/test/server.test.ts new file mode 100644 index 000000000..04ceafdec --- /dev/null +++ b/packages/inert/test/server.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, test } from "vitest"; +import { createRoot } from "solid-js"; +import { createInertOthers, makeInertOthers } from "../src/index.js"; + +describe("inert — SSR", () => { + test("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(); + }); + + test("createInertOthers does nothing on the server", () => { + expect(() => + createRoot(dispose => { + createInertOthers(() => undefined, true, { strategy: "inert" }); + dispose(); + }), + ).not.toThrow(); + }); +}); diff --git a/packages/inert/tsconfig.json b/packages/inert/tsconfig.json new file mode 100644 index 000000000..674e85d9a --- /dev/null +++ b/packages/inert/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig.json", + "include": ["src"] +} \ No newline at end of file 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, +}); + +