@vielzeug/necromancer 26.10.0 → 26.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/layout.cjs.map +1 -1
- package/dist/layout.d.ts +1 -1
- package/dist/layout.js.map +1 -1
- package/dist/necromancer.cjs.map +1 -1
- package/dist/necromancer.iife.js.map +1 -1
- package/dist/necromancer.js.map +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.js.map +1 -1
- package/dist/types.d.ts +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -40,4 +40,4 @@ handle.dispose();
|
|
|
40
40
|
|
|
41
41
|
## License
|
|
42
42
|
|
|
43
|
-
MIT © [Helmuth Saatkamp](https://github.com/helmuthdu)
|
|
43
|
+
MIT © [Helmuth Saatkamp](https://github.com/helmuthdu): part of the [Vielzeug](https://github.com/helmuthdu/vielzeug) monorepo.
|
package/dist/layout.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"layout.cjs","names":[],"sources":["../src/layout.ts"],"sourcesContent":["import { uniqueElements } from './_elements';\nimport { animateEach } from './animate-each';\nimport { NecromancerConfigError } from './errors';\nimport type { LayoutAnimationOptions, LayoutCaptureOptions, LayoutTransition } from './types';\n\ntype LayoutRect = Readonly<Pick<DOMRectReadOnly, 'height' | 'width' | 'x' | 'y'>>;\ntype LayoutEntry<ElementType extends Element> = Readonly<{ element: ElementType; rect: LayoutRect }>;\ntype LayoutChange<ElementType extends Element> = Readonly<{\n element: ElementType;\n scaleX: number;\n scaleY: number;\n x: number;\n y: number;\n}>;\n\n// Rounds before templating into a keyframe string purely for DevTools readability
|
|
1
|
+
{"version":3,"file":"layout.cjs","names":[],"sources":["../src/layout.ts"],"sourcesContent":["import { uniqueElements } from './_elements';\nimport { animateEach } from './animate-each';\nimport { NecromancerConfigError } from './errors';\nimport type { LayoutAnimationOptions, LayoutCaptureOptions, LayoutTransition } from './types';\n\ntype LayoutRect = Readonly<Pick<DOMRectReadOnly, 'height' | 'width' | 'x' | 'y'>>;\ntype LayoutEntry<ElementType extends Element> = Readonly<{ element: ElementType; rect: LayoutRect }>;\ntype LayoutChange<ElementType extends Element> = Readonly<{\n element: ElementType;\n scaleX: number;\n scaleY: number;\n x: number;\n y: number;\n}>;\n\n// Rounds before templating into a keyframe string purely for DevTools readability: a `getBoundingClientRect()`\n// subtraction routinely produces values like `12.340000000000002`, which is noise once rendered as CSS.\n// Pixels only need whole-number precision; scale factors (close to 1) need finer precision to stay visually exact.\nfunction round(value: number, precision: number): number {\n const factor = 10 ** precision;\n\n return Math.round(value * factor) / factor;\n}\n\n// `getBoundingClientRect()`'s width/height is the rotated, axis-aligned bounding box: using it\n// for size would distort the scale ratio under any rotation. `offsetWidth`/`offsetHeight` report\n// the box's own untransformed layout size instead. Elements without an offset box (e.g. SVG)\n// fall back to the bounding rect, accepting that same distortion as the only option available.\nfunction measureSize(element: Element): Readonly<{ height: number; width: number }> {\n if ('offsetWidth' in element && 'offsetHeight' in element) {\n return { height: (element as HTMLElement).offsetHeight, width: (element as HTMLElement).offsetWidth };\n }\n\n const rect = element.getBoundingClientRect();\n\n return { height: rect.height, width: rect.width };\n}\n\nfunction measureLayout(element: Element): LayoutRect {\n const rect = element.getBoundingClientRect();\n const size = measureSize(element);\n\n return { height: size.height, width: size.width, x: rect.x, y: rect.y };\n}\n\n// `next` is 0 exactly when the element has collapsed (e.g. `display: none` mid-transition);\n// there's no meaningful ratio to compute then, so treat it as unscaled rather than producing Infinity/NaN.\nfunction computeScale(captured: number, next: number): number {\n return next === 0 ? 1 : captured / next;\n}\n\nfunction readKey<ElementType extends Element>(\n element: ElementType,\n getKey: (element: ElementType) => string,\n phase: string,\n): string {\n const key = getKey(element);\n\n if (typeof key !== 'string' || key.length === 0) {\n throw new NecromancerConfigError(`getKey must return a non-empty string for every ${phase} element.`);\n }\n\n return key;\n}\n\nfunction createKeyMap<ElementType extends Element>(\n entries: readonly LayoutEntry<ElementType>[],\n getKey: (element: ElementType) => string,\n phase: string,\n) {\n const keys = new Map<string, LayoutEntry<ElementType>>();\n\n for (const entry of entries) {\n const key = readKey(entry.element, getKey, phase);\n\n if (keys.has(key)) {\n throw new NecromancerConfigError(`getKey returned duplicate keys for the ${phase} elements.`);\n }\n\n keys.set(key, entry);\n }\n\n return keys;\n}\n\nfunction changedElement<ElementType extends Element>(\n element: ElementType,\n rect: LayoutRect,\n): LayoutChange<ElementType> | undefined {\n if (!element.isConnected) return undefined;\n\n const next = measureLayout(element);\n const x = rect.x - next.x;\n const y = rect.y - next.y;\n const scaleX = computeScale(rect.width, next.width);\n const scaleY = computeScale(rect.height, next.height);\n\n return x === 0 && y === 0 && scaleX === 1 && scaleY === 1 ? undefined : { element, scaleX, scaleY, x, y };\n}\n\nfunction matchByIdentity<ElementType extends Element>(\n entries: readonly LayoutEntry<ElementType>[],\n elements: readonly ElementType[],\n): LayoutChange<ElementType>[] {\n const captured = new Map(entries.map((entry) => [entry.element, entry]));\n\n return elements.flatMap((element) => {\n const entry = captured.get(element);\n\n return entry\n ? [changedElement(element, entry.rect)].filter((change): change is LayoutChange<ElementType> => Boolean(change))\n : [];\n });\n}\n\nfunction matchByKey<ElementType extends Element>(\n captured: ReadonlyMap<string, LayoutEntry<ElementType>>,\n elements: readonly ElementType[],\n getKey: (element: ElementType) => string,\n): LayoutChange<ElementType>[] {\n const committed = new Set<string>();\n\n return elements.flatMap((element) => {\n const key = readKey(element, getKey, 'committed');\n const entry = captured.get(key);\n\n if (committed.has(key)) {\n throw new NecromancerConfigError('getKey returned duplicate keys for the committed elements.');\n }\n\n committed.add(key);\n\n return entry\n ? [changedElement(element, entry.rect)].filter((change): change is LayoutChange<ElementType> => Boolean(change))\n : [];\n });\n}\n\n/**\n * Captures the current position and size of unique elements for a later FLIP animation.\n *\n * Each element's `x`/`y` position and `width`/`height` are captured. Rotation and other\n * transforms are not captured or compensated. Capture before mutating the DOM, then call\n * the returned transition's `animate()` method after the browser has applied the resulting\n * layout: position changes animate via translate, and size changes via scale, both\n * additively composed on top of any authored transform.\n */\nexport function captureLayout<ElementType extends Element>(\n elements: Iterable<ElementType>,\n options: LayoutCaptureOptions<ElementType> = {},\n): LayoutTransition<ElementType> {\n const entries: LayoutEntry<ElementType>[] = uniqueElements(elements).map((element) => ({\n element,\n rect: measureLayout(element),\n }));\n const getKey = options.getKey;\n const captured = getKey ? createKeyMap(entries, getKey, 'captured') : undefined;\n\n let consumed = false;\n\n return {\n animate(options: LayoutAnimationOptions<ElementType> = {}) {\n if (consumed) throw new NecromancerConfigError('This layout transition has already been animated.');\n\n const { elements: committedElements, ...animationOptions } = options;\n const elements = uniqueElements(committedElements ?? entries.map(({ element }) => element));\n const changed = getKey && captured ? matchByKey(captured, elements, getKey) : matchByIdentity(entries, elements);\n\n consumed = true;\n\n return animateEach(\n changed.map(({ element }) => element),\n (_, index) => {\n // `changed` was mapped directly into the elements array above, so this index is always in range.\n const change = changed[index]!;\n const translate = `${round(change.x, 2)}px ${round(change.y, 2)}px`;\n const scale = `${round(change.scaleX, 4)} ${round(change.scaleY, 4)}`;\n\n return [\n { composite: 'add', scale, translate },\n { composite: 'add', scale: '1 1', translate: '0px 0px' },\n ];\n },\n animationOptions,\n );\n },\n };\n}\n"],"mappings":"6FAkBA,SAAS,MAAM,EAAe,EAA2B,CACvD,IAAM,EAAS,IAAM,EAErB,OAAO,KAAK,MAAM,EAAQ,CAAM,EAAI,CACtC,CAMA,SAAS,YAAY,EAA+D,CAClF,GAAI,gBAAiB,GAAW,iBAAkB,EAChD,MAAO,CAAE,OAAS,EAAwB,aAAc,MAAQ,EAAwB,WAAY,EAGtG,IAAM,EAAO,EAAQ,sBAAsB,EAE3C,MAAO,CAAE,OAAQ,EAAK,OAAQ,MAAO,EAAK,KAAM,CAClD,CAEA,SAAS,cAAc,EAA8B,CACnD,IAAM,EAAO,EAAQ,sBAAsB,EACrC,EAAO,YAAY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Q,CAAC,EAAE,GAAG,MAAM,EAAO,OAAQ,CAAC,IAGrC,WAAU,EACrC,CAAE,UAAW,MAAO,MAAO,MAAO,UAAW,SAAU,CACzD,CACF,EACA,CACF,CACF,CACF,CACF"}
|
package/dist/layout.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ import type { LayoutCaptureOptions, LayoutTransition } from './types';
|
|
|
5
5
|
* Each element's `x`/`y` position and `width`/`height` are captured. Rotation and other
|
|
6
6
|
* transforms are not captured or compensated. Capture before mutating the DOM, then call
|
|
7
7
|
* the returned transition's `animate()` method after the browser has applied the resulting
|
|
8
|
-
* layout
|
|
8
|
+
* layout: position changes animate via translate, and size changes via scale, both
|
|
9
9
|
* additively composed on top of any authored transform.
|
|
10
10
|
*/
|
|
11
11
|
export declare function captureLayout<ElementType extends Element>(elements: Iterable<ElementType>, options?: LayoutCaptureOptions<ElementType>): LayoutTransition<ElementType>;
|
package/dist/layout.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"layout.js","names":[],"sources":["../src/layout.ts"],"sourcesContent":["import { uniqueElements } from './_elements';\nimport { animateEach } from './animate-each';\nimport { NecromancerConfigError } from './errors';\nimport type { LayoutAnimationOptions, LayoutCaptureOptions, LayoutTransition } from './types';\n\ntype LayoutRect = Readonly<Pick<DOMRectReadOnly, 'height' | 'width' | 'x' | 'y'>>;\ntype LayoutEntry<ElementType extends Element> = Readonly<{ element: ElementType; rect: LayoutRect }>;\ntype LayoutChange<ElementType extends Element> = Readonly<{\n element: ElementType;\n scaleX: number;\n scaleY: number;\n x: number;\n y: number;\n}>;\n\n// Rounds before templating into a keyframe string purely for DevTools readability
|
|
1
|
+
{"version":3,"file":"layout.js","names":[],"sources":["../src/layout.ts"],"sourcesContent":["import { uniqueElements } from './_elements';\nimport { animateEach } from './animate-each';\nimport { NecromancerConfigError } from './errors';\nimport type { LayoutAnimationOptions, LayoutCaptureOptions, LayoutTransition } from './types';\n\ntype LayoutRect = Readonly<Pick<DOMRectReadOnly, 'height' | 'width' | 'x' | 'y'>>;\ntype LayoutEntry<ElementType extends Element> = Readonly<{ element: ElementType; rect: LayoutRect }>;\ntype LayoutChange<ElementType extends Element> = Readonly<{\n element: ElementType;\n scaleX: number;\n scaleY: number;\n x: number;\n y: number;\n}>;\n\n// Rounds before templating into a keyframe string purely for DevTools readability: a `getBoundingClientRect()`\n// subtraction routinely produces values like `12.340000000000002`, which is noise once rendered as CSS.\n// Pixels only need whole-number precision; scale factors (close to 1) need finer precision to stay visually exact.\nfunction round(value: number, precision: number): number {\n const factor = 10 ** precision;\n\n return Math.round(value * factor) / factor;\n}\n\n// `getBoundingClientRect()`'s width/height is the rotated, axis-aligned bounding box: using it\n// for size would distort the scale ratio under any rotation. `offsetWidth`/`offsetHeight` report\n// the box's own untransformed layout size instead. Elements without an offset box (e.g. SVG)\n// fall back to the bounding rect, accepting that same distortion as the only option available.\nfunction measureSize(element: Element): Readonly<{ height: number; width: number }> {\n if ('offsetWidth' in element && 'offsetHeight' in element) {\n return { height: (element as HTMLElement).offsetHeight, width: (element as HTMLElement).offsetWidth };\n }\n\n const rect = element.getBoundingClientRect();\n\n return { height: rect.height, width: rect.width };\n}\n\nfunction measureLayout(element: Element): LayoutRect {\n const rect = element.getBoundingClientRect();\n const size = measureSize(element);\n\n return { height: size.height, width: size.width, x: rect.x, y: rect.y };\n}\n\n// `next` is 0 exactly when the element has collapsed (e.g. `display: none` mid-transition);\n// there's no meaningful ratio to compute then, so treat it as unscaled rather than producing Infinity/NaN.\nfunction computeScale(captured: number, next: number): number {\n return next === 0 ? 1 : captured / next;\n}\n\nfunction readKey<ElementType extends Element>(\n element: ElementType,\n getKey: (element: ElementType) => string,\n phase: string,\n): string {\n const key = getKey(element);\n\n if (typeof key !== 'string' || key.length === 0) {\n throw new NecromancerConfigError(`getKey must return a non-empty string for every ${phase} element.`);\n }\n\n return key;\n}\n\nfunction createKeyMap<ElementType extends Element>(\n entries: readonly LayoutEntry<ElementType>[],\n getKey: (element: ElementType) => string,\n phase: string,\n) {\n const keys = new Map<string, LayoutEntry<ElementType>>();\n\n for (const entry of entries) {\n const key = readKey(entry.element, getKey, phase);\n\n if (keys.has(key)) {\n throw new NecromancerConfigError(`getKey returned duplicate keys for the ${phase} elements.`);\n }\n\n keys.set(key, entry);\n }\n\n return keys;\n}\n\nfunction changedElement<ElementType extends Element>(\n element: ElementType,\n rect: LayoutRect,\n): LayoutChange<ElementType> | undefined {\n if (!element.isConnected) return undefined;\n\n const next = measureLayout(element);\n const x = rect.x - next.x;\n const y = rect.y - next.y;\n const scaleX = computeScale(rect.width, next.width);\n const scaleY = computeScale(rect.height, next.height);\n\n return x === 0 && y === 0 && scaleX === 1 && scaleY === 1 ? undefined : { element, scaleX, scaleY, x, y };\n}\n\nfunction matchByIdentity<ElementType extends Element>(\n entries: readonly LayoutEntry<ElementType>[],\n elements: readonly ElementType[],\n): LayoutChange<ElementType>[] {\n const captured = new Map(entries.map((entry) => [entry.element, entry]));\n\n return elements.flatMap((element) => {\n const entry = captured.get(element);\n\n return entry\n ? [changedElement(element, entry.rect)].filter((change): change is LayoutChange<ElementType> => Boolean(change))\n : [];\n });\n}\n\nfunction matchByKey<ElementType extends Element>(\n captured: ReadonlyMap<string, LayoutEntry<ElementType>>,\n elements: readonly ElementType[],\n getKey: (element: ElementType) => string,\n): LayoutChange<ElementType>[] {\n const committed = new Set<string>();\n\n return elements.flatMap((element) => {\n const key = readKey(element, getKey, 'committed');\n const entry = captured.get(key);\n\n if (committed.has(key)) {\n throw new NecromancerConfigError('getKey returned duplicate keys for the committed elements.');\n }\n\n committed.add(key);\n\n return entry\n ? [changedElement(element, entry.rect)].filter((change): change is LayoutChange<ElementType> => Boolean(change))\n : [];\n });\n}\n\n/**\n * Captures the current position and size of unique elements for a later FLIP animation.\n *\n * Each element's `x`/`y` position and `width`/`height` are captured. Rotation and other\n * transforms are not captured or compensated. Capture before mutating the DOM, then call\n * the returned transition's `animate()` method after the browser has applied the resulting\n * layout: position changes animate via translate, and size changes via scale, both\n * additively composed on top of any authored transform.\n */\nexport function captureLayout<ElementType extends Element>(\n elements: Iterable<ElementType>,\n options: LayoutCaptureOptions<ElementType> = {},\n): LayoutTransition<ElementType> {\n const entries: LayoutEntry<ElementType>[] = uniqueElements(elements).map((element) => ({\n element,\n rect: measureLayout(element),\n }));\n const getKey = options.getKey;\n const captured = getKey ? createKeyMap(entries, getKey, 'captured') : undefined;\n\n let consumed = false;\n\n return {\n animate(options: LayoutAnimationOptions<ElementType> = {}) {\n if (consumed) throw new NecromancerConfigError('This layout transition has already been animated.');\n\n const { elements: committedElements, ...animationOptions } = options;\n const elements = uniqueElements(committedElements ?? entries.map(({ element }) => element));\n const changed = getKey && captured ? matchByKey(captured, elements, getKey) : matchByIdentity(entries, elements);\n\n consumed = true;\n\n return animateEach(\n changed.map(({ element }) => element),\n (_, index) => {\n // `changed` was mapped directly into the elements array above, so this index is always in range.\n const change = changed[index]!;\n const translate = `${round(change.x, 2)}px ${round(change.y, 2)}px`;\n const scale = `${round(change.scaleX, 4)} ${round(change.scaleY, 4)}`;\n\n return [\n { composite: 'add', scale, translate },\n { composite: 'add', scale: '1 1', translate: '0px 0px' },\n ];\n },\n animationOptions,\n );\n },\n };\n}\n"],"mappings":"qJAkBA,SAAS,MAAM,EAAe,EAA2B,CACvD,IAAM,EAAS,IAAM,EAErB,OAAO,KAAK,MAAM,EAAQ,CAAM,EAAI,CACtC,CAMA,SAAS,YAAY,EAA+D,CAClF,GAAI,gBAAiB,GAAW,iBAAkB,EAChD,MAAO,CAAE,OAAS,EAAwB,aAAc,MAAQ,EAAwB,WAAY,EAGtG,IAAM,EAAO,EAAQ,sBAAsB,EAE3C,MAAO,CAAE,OAAQ,EAAK,OAAQ,MAAO,EAAK,KAAM,CAClD,CAEA,SAAS,cAAc,EAA8B,CACnD,IAAM,EAAO,EAAQ,sBAAsB,EACrC,EAAO,YAAY,CAAO,EAEhC,MAAO,CAAE,OAAQ,EAAK,OAAQ,MAAO,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W,SAAU,CACzD,CACF,EACA,CACF,CACF,CACF,CACF"}
|
package/dist/necromancer.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"necromancer.cjs","names":[],"sources":["../src/_handle.ts","../src/errors.ts","../src/motion.ts","../src/animate.ts","../src/_elements.ts","../src/animate-each.ts","../src/layout.ts"],"sourcesContent":["import type { AnimationGroup, AnimationHandle, AnimationResult } from './types';\n\n/**\n * Attaches an abort listener to a signal and returns a function that removes it.\n * When the signal aborts, calls the dispose function with the signal's reason.\n */\nfunction attachAbortSignalListener(signal: AbortSignal, dispose: (reason?: unknown) => void): () => void {\n const abort = () => dispose(signal.reason);\n\n signal.addEventListener('abort', abort, { once: true });\n\n if (signal.aborted) {\n signal.removeEventListener('abort', abort);\n dispose(signal.reason);\n return () => undefined;\n }\n\n return () => signal.removeEventListener('abort', abort);\n}\n\nfunction createResultPromise(animation: Animation, onSettled: () => void, reduced: boolean): Promise<AnimationResult> {\n return animation.finished.then(\n () => {\n onSettled();\n\n return { status: reduced ? 'reduced' : 'finished' };\n },\n (reason: unknown) => {\n onSettled();\n\n return { reason, status: 'cancelled' };\n },\n );\n}\n\n/** Wraps a native Animation with Necromancer's lifecycle contract. */\nexport function createAnimationHandle(animation: Animation, signal?: AbortSignal, reduced = false): AnimationHandle {\n let disposed = false;\n let disposeReason: unknown;\n let hasDisposeReason = false;\n let removeAbortListener: (() => void) | undefined;\n\n const result: Promise<AnimationResult> = createResultPromise(\n animation,\n () => {\n removeAbortListener?.();\n removeAbortListener = undefined;\n },\n reduced,\n ).then((outcome): AnimationResult => {\n if (disposed && hasDisposeReason && outcome.status === 'cancelled') {\n return { reason: disposeReason, status: 'cancelled' };\n }\n\n return outcome;\n });\n\n const dispose = (reason?: unknown): void => {\n if (disposed) return;\n\n disposed = true;\n disposeReason = reason;\n hasDisposeReason = reason !== undefined;\n removeAbortListener?.();\n removeAbortListener = undefined;\n animation.cancel();\n };\n\n if (signal) {\n removeAbortListener = attachAbortSignalListener(signal, dispose);\n }\n\n return {\n animation,\n dispose,\n get disposed() {\n return disposed;\n },\n result,\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n}\n\n/** Combines child animation handles under one disposal owner. */\nexport function createAnimationGroup(handles: readonly AnimationHandle[], signal?: AbortSignal): AnimationGroup {\n let disposed = false;\n let removeAbortListener: (() => void) | undefined;\n\n const results: Promise<readonly AnimationResult[]> = Promise.all(handles.map((handle) => handle.result)).then(\n (childResults): readonly AnimationResult[] => {\n removeAbortListener?.();\n removeAbortListener = undefined;\n\n return childResults;\n },\n );\n\n const dispose = (reason?: unknown): void => {\n if (disposed) return;\n\n disposed = true;\n removeAbortListener?.();\n removeAbortListener = undefined;\n for (const handle of handles) handle.dispose(reason);\n };\n\n if (signal) {\n removeAbortListener = attachAbortSignalListener(signal, dispose);\n }\n\n return {\n dispose,\n get disposed() {\n return disposed;\n },\n handles,\n results,\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n}\n","/** Base class for errors raised by `@vielzeug/necromancer`. */\nexport class NecromancerError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a Necromancer-owned option is invalid. */\nexport class NecromancerConfigError extends NecromancerError {}\n\n/** Thrown when the runtime does not implement the Web Animations API. */\nexport class NecromancerUnsupportedError extends NecromancerError {}\n","import { NecromancerConfigError } from './errors';\nimport type { AnimateOptions, MotionMode } from './types';\n\n/** Reports whether the requested motion preference reduces visible movement. */\nexport function shouldReduceMotion(mode: MotionMode): boolean {\n if (mode === 'full') return false;\n\n if (mode === 'reduced') return true;\n\n return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n}\n\n/** Converts ownership options to native timing, collapsing reduced motion to an instant transition. */\nexport function resolveAnimationOptions(options: AnimateOptions = {}, reduced = false): KeyframeAnimationOptions {\n const { motion: _motion, signal: _signal, ...nativeOptions } = options;\n\n return reduced ? { ...nativeOptions, delay: 0, duration: 0, endDelay: 0, iterations: 1 } : nativeOptions;\n}\n\n/** Adds an element's stagger offset without changing native nonnumeric delays when no offset is needed. */\nexport function withStaggeredDelay(options: AnimateOptions, offset: number): AnimateOptions {\n if (offset === 0) return options;\n\n const delay = options.delay ?? 0;\n\n if (typeof delay !== 'number') {\n throw new NecromancerConfigError(`A non-zero stagger requires a numeric delay; received ${typeof delay}.`);\n }\n\n return { ...options, delay: delay + offset };\n}\n","import { createAnimationHandle } from './_handle';\nimport { NecromancerUnsupportedError } from './errors';\nimport { resolveAnimationOptions, shouldReduceMotion } from './motion';\nimport type { AnimateOptions, AnimationHandle, Keyframes } from './types';\n\n/**\n * Starts a lifecycle-owned native Web Animation for one element.\n *\n * The returned handle cancels its native animation when disposed. By default, the\n * operating system's reduced-motion preference suppresses movement.\n */\nexport function animate(element: Element, keyframes: Keyframes, options: AnimateOptions = {}): AnimationHandle {\n if (options.signal?.aborted) throw options.signal.reason;\n\n if (typeof element.animate !== 'function') {\n throw new NecromancerUnsupportedError('The Web Animations API is not available in this environment.');\n }\n\n const reduced = shouldReduceMotion(options.motion ?? 'system');\n const nativeAnimation = element.animate(\n keyframes as Keyframe[] | PropertyIndexedKeyframes,\n resolveAnimationOptions(options, reduced),\n );\n return createAnimationHandle(nativeAnimation, options.signal, reduced);\n}\n","/** Deduplicates elements while preserving first-seen order. Shared by `animateEach()` and `captureLayout()`. */\nexport function uniqueElements<ElementType extends Element>(elements: Iterable<ElementType>): ElementType[] {\n return [...new Set(elements)];\n}\n","import { uniqueElements } from './_elements';\nimport { createAnimationGroup } from './_handle';\nimport { animate } from './animate';\nimport { NecromancerConfigError } from './errors';\nimport { withStaggeredDelay } from './motion';\nimport type { AnimateEachOptions, AnimationGroup, AnimationHandle, KeyframeFactory, Keyframes } from './types';\n\nfunction validateStagger(stagger: number): void {\n if (!Number.isFinite(stagger) || stagger < 0) {\n throw new NecromancerConfigError('stagger must be a finite, non-negative number.');\n }\n}\n\n/**\n * Starts lifecycle-owned animations for unique elements in iteration order.\n *\n * Each subsequent element starts after `stagger` milliseconds. A keyframe factory\n * receives the stable unique-element index and total before any animation starts.\n */\nexport function animateEach<ElementType extends Element>(\n elements: Iterable<ElementType>,\n keyframes: Keyframes | KeyframeFactory<ElementType>,\n options: AnimateEachOptions = {},\n): AnimationGroup {\n const { signal, stagger = 0, ...animationOptions } = options;\n\n validateStagger(stagger);\n\n if (signal?.aborted) throw signal.reason;\n\n const unique = uniqueElements(elements);\n const frames = unique.map((element, index) =>\n typeof keyframes === 'function' ? keyframes(element, index, unique.length) : keyframes,\n );\n\n if (signal?.aborted) throw signal.reason;\n\n const handles: AnimationHandle[] = [];\n\n try {\n for (const [index, element] of unique.entries()) {\n // `frames` was built above from `unique`, one entry per element, so this index is always in range.\n const currentFrames = frames[index]!;\n\n handles.push(animate(element, currentFrames, withStaggeredDelay(animationOptions, index * stagger)));\n }\n } catch (error) {\n for (const handle of handles) handle.dispose(error);\n\n throw error;\n }\n\n return createAnimationGroup(handles, signal);\n}\n","import { uniqueElements } from './_elements';\nimport { animateEach } from './animate-each';\nimport { NecromancerConfigError } from './errors';\nimport type { LayoutAnimationOptions, LayoutCaptureOptions, LayoutTransition } from './types';\n\ntype LayoutRect = Readonly<Pick<DOMRectReadOnly, 'height' | 'width' | 'x' | 'y'>>;\ntype LayoutEntry<ElementType extends Element> = Readonly<{ element: ElementType; rect: LayoutRect }>;\ntype LayoutChange<ElementType extends Element> = Readonly<{\n element: ElementType;\n scaleX: number;\n scaleY: number;\n x: number;\n y: number;\n}>;\n\n// Rounds before templating into a keyframe string purely for DevTools readability — a `getBoundingClientRect()`\n// subtraction routinely produces values like `12.340000000000002`, which is noise once rendered as CSS.\n// Pixels only need whole-number precision; scale factors (close to 1) need finer precision to stay visually exact.\nfunction round(value: number, precision: number): number {\n const factor = 10 ** precision;\n\n return Math.round(value * factor) / factor;\n}\n\n// `getBoundingClientRect()`'s width/height is the rotated, axis-aligned bounding box — using it\n// for size would distort the scale ratio under any rotation. `offsetWidth`/`offsetHeight` report\n// the box's own untransformed layout size instead. Elements without an offset box (e.g. SVG)\n// fall back to the bounding rect, accepting that same distortion as the only option available.\nfunction measureSize(element: Element): Readonly<{ height: number; width: number }> {\n if ('offsetWidth' in element && 'offsetHeight' in element) {\n return { height: (element as HTMLElement).offsetHeight, width: (element as HTMLElement).offsetWidth };\n }\n\n const rect = element.getBoundingClientRect();\n\n return { height: rect.height, width: rect.width };\n}\n\nfunction measureLayout(element: Element): LayoutRect {\n const rect = element.getBoundingClientRect();\n const size = measureSize(element);\n\n return { height: size.height, width: size.width, x: rect.x, y: rect.y };\n}\n\n// `next` is 0 exactly when the element has collapsed (e.g. `display: none` mid-transition);\n// there's no meaningful ratio to compute then, so treat it as unscaled rather than producing Infinity/NaN.\nfunction computeScale(captured: number, next: number): number {\n return next === 0 ? 1 : captured / next;\n}\n\nfunction readKey<ElementType extends Element>(\n element: ElementType,\n getKey: (element: ElementType) => string,\n phase: string,\n): string {\n const key = getKey(element);\n\n if (typeof key !== 'string' || key.length === 0) {\n throw new NecromancerConfigError(`getKey must return a non-empty string for every ${phase} element.`);\n }\n\n return key;\n}\n\nfunction createKeyMap<ElementType extends Element>(\n entries: readonly LayoutEntry<ElementType>[],\n getKey: (element: ElementType) => string,\n phase: string,\n) {\n const keys = new Map<string, LayoutEntry<ElementType>>();\n\n for (const entry of entries) {\n const key = readKey(entry.element, getKey, phase);\n\n if (keys.has(key)) {\n throw new NecromancerConfigError(`getKey returned duplicate keys for the ${phase} elements.`);\n }\n\n keys.set(key, entry);\n }\n\n return keys;\n}\n\nfunction changedElement<ElementType extends Element>(\n element: ElementType,\n rect: LayoutRect,\n): LayoutChange<ElementType> | undefined {\n if (!element.isConnected) return undefined;\n\n const next = measureLayout(element);\n const x = rect.x - next.x;\n const y = rect.y - next.y;\n const scaleX = computeScale(rect.width, next.width);\n const scaleY = computeScale(rect.height, next.height);\n\n return x === 0 && y === 0 && scaleX === 1 && scaleY === 1 ? undefined : { element, scaleX, scaleY, x, y };\n}\n\nfunction matchByIdentity<ElementType extends Element>(\n entries: readonly LayoutEntry<ElementType>[],\n elements: readonly ElementType[],\n): LayoutChange<ElementType>[] {\n const captured = new Map(entries.map((entry) => [entry.element, entry]));\n\n return elements.flatMap((element) => {\n const entry = captured.get(element);\n\n return entry\n ? [changedElement(element, entry.rect)].filter((change): change is LayoutChange<ElementType> => Boolean(change))\n : [];\n });\n}\n\nfunction matchByKey<ElementType extends Element>(\n captured: ReadonlyMap<string, LayoutEntry<ElementType>>,\n elements: readonly ElementType[],\n getKey: (element: ElementType) => string,\n): LayoutChange<ElementType>[] {\n const committed = new Set<string>();\n\n return elements.flatMap((element) => {\n const key = readKey(element, getKey, 'committed');\n const entry = captured.get(key);\n\n if (committed.has(key)) {\n throw new NecromancerConfigError('getKey returned duplicate keys for the committed elements.');\n }\n\n committed.add(key);\n\n return entry\n ? [changedElement(element, entry.rect)].filter((change): change is LayoutChange<ElementType> => Boolean(change))\n : [];\n });\n}\n\n/**\n * Captures the current position and size of unique elements for a later FLIP animation.\n *\n * Each element's `x`/`y` position and `width`/`height` are captured. Rotation and other\n * transforms are not captured or compensated. Capture before mutating the DOM, then call\n * the returned transition's `animate()` method after the browser has applied the resulting\n * layout — position changes animate via translate, and size changes via scale, both\n * additively composed on top of any authored transform.\n */\nexport function captureLayout<ElementType extends Element>(\n elements: Iterable<ElementType>,\n options: LayoutCaptureOptions<ElementType> = {},\n): LayoutTransition<ElementType> {\n const entries: LayoutEntry<ElementType>[] = uniqueElements(elements).map((element) => ({\n element,\n rect: measureLayout(element),\n }));\n const getKey = options.getKey;\n const captured = getKey ? createKeyMap(entries, getKey, 'captured') : undefined;\n\n let consumed = false;\n\n return {\n animate(options: LayoutAnimationOptions<ElementType> = {}) {\n if (consumed) throw new NecromancerConfigError('This layout transition has already been animated.');\n\n const { elements: committedElements, ...animationOptions } = options;\n const elements = uniqueElements(committedElements ?? entries.map(({ element }) => element));\n const changed = getKey && captured ? matchByKey(captured, elements, getKey) : matchByIdentity(entries, elements);\n\n consumed = true;\n\n return animateEach(\n changed.map(({ element }) => element),\n (_, index) => {\n // `changed` was mapped directly into the elements array above, so this index is always in range.\n const change = changed[index]!;\n const translate = `${round(change.x, 2)}px ${round(change.y, 2)}px`;\n const scale = `${round(change.scaleX, 4)} ${round(change.scaleY, 4)}`;\n\n return [\n { composite: 'add', scale, translate },\n { composite: 'add', scale: '1 1', translate: '0px 0px' },\n ];\n },\n animationOptions,\n );\n },\n };\n}\n"],"mappings":"mEAMA,SAAS,0BAA0B,EAAqB,EAAiD,CACvG,IAAM,UAAc,EAAQ,EAAO,MAAM,EAUzC,OARA,EAAO,iBAAiB,QAAS,MAAO,CAAE,KAAM,EAAK,CAAC,EAElD,EAAO,SACT,EAAO,oBAAoB,QAAS,KAAK,EACzC,EAAQ,EAAO,MAAM,MACR,IAAA,QAGF,EAAO,oBAAoB,QAAS,KAAK,CACxD,CAEA,SAAS,oBAAoB,EAAsB,EAAuB,EAA4C,CACpH,OAAO,EAAU,SAAS,UAEtB,EAAU,EAEH,CAAE,OAAQ,EAAU,UAAY,UAAW,GAEnD,IACC,EAAU,EAEH,CAAE,SAAQ,OAAQ,WAAY,EAEzC,CACF,CAGA,SAAgB,sBAAsB,EAAsB,EAAsB,EAAU,GAAwB,CAClH,IAAI,EAAW,GACX,EACA,EAAmB,GACnB,EAEE,EAAmC,oBACvC,MACM,CACJ,IAAsB,EACtB,EAAsB,IAAA,EACxB,EACA,CACF,CAAC,CAAC,KAAM,GACF,GAAY,GAAoB,EAAQ,SAAW,YAC9C,CAAE,OAAQ,EAAe,OAAQ,WAAY,EAG/C,CACR,EAEK,QAAW,GAA2B,CACtC,IAEJ,EAAW,GACX,EAAgB,EAChB,EAAmB,IAAW,IAAA,GAC9B,IAAsB,EACtB,EAAsB,IAAA,GACtB,EAAU,OAAO,EACnB,EAMA,OAJI,IACF,EAAsB,0BAA0B,EAAQ,OAAO,GAG1D,CACL,YACA,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,mDAAmD,EAElG,GAAM,CAAE,SAAU,EAAmB,GAAG,GAAqB,EACvD,EAAW,eAAe,GAAqB,EAAQ,KAAK,CAAE,aAAc,CAAO,CAAC,EACpF,EAAU,GAAU,EAAW,WAAW,EAAU,EAAU,CAAM,EAAI,gBAAgB,EAAS,CAAQ,EAI/G,MAFA,GAAW,GAEJ,YACL,EAAQ,KAAK,CAAE,aAAc,CAAO,GACnC,EAAG,IAAU,CAEZ,IAAM,EAAS,EAAQ,GACjB,EAAY,GAAG,MAAM,EAAO,EAAG,CAAC,EAAE,KAAK,MAAM,EAAO,EAAG,CAAC,EAAE,IAGhE,MAAO,CACL,CAAE,UAAW,MAAO,MAAA,GAHL,MAAM,EAAO,OAAQ,CAAC,EAAE,GAAG,MAAM,EAAO,OAAQ,CAAC,IAGrC,WAAU,EACrC,CAAE,UAAW,MAAO,MAAO,MAAO,UAAW,SAAU,CACzD,CACF,EACA,CACF,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"necromancer.cjs","names":[],"sources":["../src/_handle.ts","../src/errors.ts","../src/motion.ts","../src/animate.ts","../src/_elements.ts","../src/animate-each.ts","../src/layout.ts"],"sourcesContent":["import type { AnimationGroup, AnimationHandle, AnimationResult } from './types';\n\n/**\n * Attaches an abort listener to a signal and returns a function that removes it.\n * When the signal aborts, calls the dispose function with the signal's reason.\n */\nfunction attachAbortSignalListener(signal: AbortSignal, dispose: (reason?: unknown) => void): () => void {\n const abort = () => dispose(signal.reason);\n\n signal.addEventListener('abort', abort, { once: true });\n\n if (signal.aborted) {\n signal.removeEventListener('abort', abort);\n dispose(signal.reason);\n return () => undefined;\n }\n\n return () => signal.removeEventListener('abort', abort);\n}\n\nfunction createResultPromise(animation: Animation, onSettled: () => void, reduced: boolean): Promise<AnimationResult> {\n return animation.finished.then(\n () => {\n onSettled();\n\n return { status: reduced ? 'reduced' : 'finished' };\n },\n (reason: unknown) => {\n onSettled();\n\n return { reason, status: 'cancelled' };\n },\n );\n}\n\n/** Wraps a native Animation with Necromancer's lifecycle contract. */\nexport function createAnimationHandle(animation: Animation, signal?: AbortSignal, reduced = false): AnimationHandle {\n let disposed = false;\n let disposeReason: unknown;\n let hasDisposeReason = false;\n let removeAbortListener: (() => void) | undefined;\n\n const result: Promise<AnimationResult> = createResultPromise(\n animation,\n () => {\n removeAbortListener?.();\n removeAbortListener = undefined;\n },\n reduced,\n ).then((outcome): AnimationResult => {\n if (disposed && hasDisposeReason && outcome.status === 'cancelled') {\n return { reason: disposeReason, status: 'cancelled' };\n }\n\n return outcome;\n });\n\n const dispose = (reason?: unknown): void => {\n if (disposed) return;\n\n disposed = true;\n disposeReason = reason;\n hasDisposeReason = reason !== undefined;\n removeAbortListener?.();\n removeAbortListener = undefined;\n animation.cancel();\n };\n\n if (signal) {\n removeAbortListener = attachAbortSignalListener(signal, dispose);\n }\n\n return {\n animation,\n dispose,\n get disposed() {\n return disposed;\n },\n result,\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n}\n\n/** Combines child animation handles under one disposal owner. */\nexport function createAnimationGroup(handles: readonly AnimationHandle[], signal?: AbortSignal): AnimationGroup {\n let disposed = false;\n let removeAbortListener: (() => void) | undefined;\n\n const results: Promise<readonly AnimationResult[]> = Promise.all(handles.map((handle) => handle.result)).then(\n (childResults): readonly AnimationResult[] => {\n removeAbortListener?.();\n removeAbortListener = undefined;\n\n return childResults;\n },\n );\n\n const dispose = (reason?: unknown): void => {\n if (disposed) return;\n\n disposed = true;\n removeAbortListener?.();\n removeAbortListener = undefined;\n for (const handle of handles) handle.dispose(reason);\n };\n\n if (signal) {\n removeAbortListener = attachAbortSignalListener(signal, dispose);\n }\n\n return {\n dispose,\n get disposed() {\n return disposed;\n },\n handles,\n results,\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n}\n","/** Base class for errors raised by `@vielzeug/necromancer`. */\nexport class NecromancerError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a Necromancer-owned option is invalid. */\nexport class NecromancerConfigError extends NecromancerError {}\n\n/** Thrown when the runtime does not implement the Web Animations API. */\nexport class NecromancerUnsupportedError extends NecromancerError {}\n","import { NecromancerConfigError } from './errors';\nimport type { AnimateOptions, MotionMode } from './types';\n\n/** Reports whether the requested motion preference reduces visible movement. */\nexport function shouldReduceMotion(mode: MotionMode): boolean {\n if (mode === 'full') return false;\n\n if (mode === 'reduced') return true;\n\n return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n}\n\n/** Converts ownership options to native timing, collapsing reduced motion to an instant transition. */\nexport function resolveAnimationOptions(options: AnimateOptions = {}, reduced = false): KeyframeAnimationOptions {\n const { motion: _motion, signal: _signal, ...nativeOptions } = options;\n\n return reduced ? { ...nativeOptions, delay: 0, duration: 0, endDelay: 0, iterations: 1 } : nativeOptions;\n}\n\n/** Adds an element's stagger offset without changing native nonnumeric delays when no offset is needed. */\nexport function withStaggeredDelay(options: AnimateOptions, offset: number): AnimateOptions {\n if (offset === 0) return options;\n\n const delay = options.delay ?? 0;\n\n if (typeof delay !== 'number') {\n throw new NecromancerConfigError(`A non-zero stagger requires a numeric delay; received ${typeof delay}.`);\n }\n\n return { ...options, delay: delay + offset };\n}\n","import { createAnimationHandle } from './_handle';\nimport { NecromancerUnsupportedError } from './errors';\nimport { resolveAnimationOptions, shouldReduceMotion } from './motion';\nimport type { AnimateOptions, AnimationHandle, Keyframes } from './types';\n\n/**\n * Starts a lifecycle-owned native Web Animation for one element.\n *\n * The returned handle cancels its native animation when disposed. By default, the\n * operating system's reduced-motion preference suppresses movement.\n */\nexport function animate(element: Element, keyframes: Keyframes, options: AnimateOptions = {}): AnimationHandle {\n if (options.signal?.aborted) throw options.signal.reason;\n\n if (typeof element.animate !== 'function') {\n throw new NecromancerUnsupportedError('The Web Animations API is not available in this environment.');\n }\n\n const reduced = shouldReduceMotion(options.motion ?? 'system');\n const nativeAnimation = element.animate(\n keyframes as Keyframe[] | PropertyIndexedKeyframes,\n resolveAnimationOptions(options, reduced),\n );\n return createAnimationHandle(nativeAnimation, options.signal, reduced);\n}\n","/** Deduplicates elements while preserving first-seen order. Shared by `animateEach()` and `captureLayout()`. */\nexport function uniqueElements<ElementType extends Element>(elements: Iterable<ElementType>): ElementType[] {\n return [...new Set(elements)];\n}\n","import { uniqueElements } from './_elements';\nimport { createAnimationGroup } from './_handle';\nimport { animate } from './animate';\nimport { NecromancerConfigError } from './errors';\nimport { withStaggeredDelay } from './motion';\nimport type { AnimateEachOptions, AnimationGroup, AnimationHandle, KeyframeFactory, Keyframes } from './types';\n\nfunction validateStagger(stagger: number): void {\n if (!Number.isFinite(stagger) || stagger < 0) {\n throw new NecromancerConfigError('stagger must be a finite, non-negative number.');\n }\n}\n\n/**\n * Starts lifecycle-owned animations for unique elements in iteration order.\n *\n * Each subsequent element starts after `stagger` milliseconds. A keyframe factory\n * receives the stable unique-element index and total before any animation starts.\n */\nexport function animateEach<ElementType extends Element>(\n elements: Iterable<ElementType>,\n keyframes: Keyframes | KeyframeFactory<ElementType>,\n options: AnimateEachOptions = {},\n): AnimationGroup {\n const { signal, stagger = 0, ...animationOptions } = options;\n\n validateStagger(stagger);\n\n if (signal?.aborted) throw signal.reason;\n\n const unique = uniqueElements(elements);\n const frames = unique.map((element, index) =>\n typeof keyframes === 'function' ? keyframes(element, index, unique.length) : keyframes,\n );\n\n if (signal?.aborted) throw signal.reason;\n\n const handles: AnimationHandle[] = [];\n\n try {\n for (const [index, element] of unique.entries()) {\n // `frames` was built above from `unique`, one entry per element, so this index is always in range.\n const currentFrames = frames[index]!;\n\n handles.push(animate(element, currentFrames, withStaggeredDelay(animationOptions, index * stagger)));\n }\n } catch (error) {\n for (const handle of handles) handle.dispose(error);\n\n throw error;\n }\n\n return createAnimationGroup(handles, signal);\n}\n","import { uniqueElements } from './_elements';\nimport { animateEach } from './animate-each';\nimport { NecromancerConfigError } from './errors';\nimport type { LayoutAnimationOptions, LayoutCaptureOptions, LayoutTransition } from './types';\n\ntype LayoutRect = Readonly<Pick<DOMRectReadOnly, 'height' | 'width' | 'x' | 'y'>>;\ntype LayoutEntry<ElementType extends Element> = Readonly<{ element: ElementType; rect: LayoutRect }>;\ntype LayoutChange<ElementType extends Element> = Readonly<{\n element: ElementType;\n scaleX: number;\n scaleY: number;\n x: number;\n y: number;\n}>;\n\n// Rounds before templating into a keyframe string purely for DevTools readability: a `getBoundingClientRect()`\n// subtraction routinely produces values like `12.340000000000002`, which is noise once rendered as CSS.\n// Pixels only need whole-number precision; scale factors (close to 1) need finer precision to stay visually exact.\nfunction round(value: number, precision: number): number {\n const factor = 10 ** precision;\n\n return Math.round(value * factor) / factor;\n}\n\n// `getBoundingClientRect()`'s width/height is the rotated, axis-aligned bounding box: using it\n// for size would distort the scale ratio under any rotation. `offsetWidth`/`offsetHeight` report\n// the box's own untransformed layout size instead. Elements without an offset box (e.g. SVG)\n// fall back to the bounding rect, accepting that same distortion as the only option available.\nfunction measureSize(element: Element): Readonly<{ height: number; width: number }> {\n if ('offsetWidth' in element && 'offsetHeight' in element) {\n return { height: (element as HTMLElement).offsetHeight, width: (element as HTMLElement).offsetWidth };\n }\n\n const rect = element.getBoundingClientRect();\n\n return { height: rect.height, width: rect.width };\n}\n\nfunction measureLayout(element: Element): LayoutRect {\n const rect = element.getBoundingClientRect();\n const size = measureSize(element);\n\n return { height: size.height, width: size.width, x: rect.x, y: rect.y };\n}\n\n// `next` is 0 exactly when the element has collapsed (e.g. `display: none` mid-transition);\n// there's no meaningful ratio to compute then, so treat it as unscaled rather than producing Infinity/NaN.\nfunction computeScale(captured: number, next: number): number {\n return next === 0 ? 1 : captured / next;\n}\n\nfunction readKey<ElementType extends Element>(\n element: ElementType,\n getKey: (element: ElementType) => string,\n phase: string,\n): string {\n const key = getKey(element);\n\n if (typeof key !== 'string' || key.length === 0) {\n throw new NecromancerConfigError(`getKey must return a non-empty string for every ${phase} element.`);\n }\n\n return key;\n}\n\nfunction createKeyMap<ElementType extends Element>(\n entries: readonly LayoutEntry<ElementType>[],\n getKey: (element: ElementType) => string,\n phase: string,\n) {\n const keys = new Map<string, LayoutEntry<ElementType>>();\n\n for (const entry of entries) {\n const key = readKey(entry.element, getKey, phase);\n\n if (keys.has(key)) {\n throw new NecromancerConfigError(`getKey returned duplicate keys for the ${phase} elements.`);\n }\n\n keys.set(key, entry);\n }\n\n return keys;\n}\n\nfunction changedElement<ElementType extends Element>(\n element: ElementType,\n rect: LayoutRect,\n): LayoutChange<ElementType> | undefined {\n if (!element.isConnected) return undefined;\n\n const next = measureLayout(element);\n const x = rect.x - next.x;\n const y = rect.y - next.y;\n const scaleX = computeScale(rect.width, next.width);\n const scaleY = computeScale(rect.height, next.height);\n\n return x === 0 && y === 0 && scaleX === 1 && scaleY === 1 ? undefined : { element, scaleX, scaleY, x, y };\n}\n\nfunction matchByIdentity<ElementType extends Element>(\n entries: readonly LayoutEntry<ElementType>[],\n elements: readonly ElementType[],\n): LayoutChange<ElementType>[] {\n const captured = new Map(entries.map((entry) => [entry.element, entry]));\n\n return elements.flatMap((element) => {\n const entry = captured.get(element);\n\n return entry\n ? [changedElement(element, entry.rect)].filter((change): change is LayoutChange<ElementType> => Boolean(change))\n : [];\n });\n}\n\nfunction matchByKey<ElementType extends Element>(\n captured: ReadonlyMap<string, LayoutEntry<ElementType>>,\n elements: readonly ElementType[],\n getKey: (element: ElementType) => string,\n): LayoutChange<ElementType>[] {\n const committed = new Set<string>();\n\n return elements.flatMap((element) => {\n const key = readKey(element, getKey, 'committed');\n const entry = captured.get(key);\n\n if (committed.has(key)) {\n throw new NecromancerConfigError('getKey returned duplicate keys for the committed elements.');\n }\n\n committed.add(key);\n\n return entry\n ? [changedElement(element, entry.rect)].filter((change): change is LayoutChange<ElementType> => Boolean(change))\n : [];\n });\n}\n\n/**\n * Captures the current position and size of unique elements for a later FLIP animation.\n *\n * Each element's `x`/`y` position and `width`/`height` are captured. Rotation and other\n * transforms are not captured or compensated. Capture before mutating the DOM, then call\n * the returned transition's `animate()` method after the browser has applied the resulting\n * layout: position changes animate via translate, and size changes via scale, both\n * additively composed on top of any authored transform.\n */\nexport function captureLayout<ElementType extends Element>(\n elements: Iterable<ElementType>,\n options: LayoutCaptureOptions<ElementType> = {},\n): LayoutTransition<ElementType> {\n const entries: LayoutEntry<ElementType>[] = uniqueElements(elements).map((element) => ({\n element,\n rect: measureLayout(element),\n }));\n const getKey = options.getKey;\n const captured = getKey ? createKeyMap(entries, getKey, 'captured') : undefined;\n\n let consumed = false;\n\n return {\n animate(options: LayoutAnimationOptions<ElementType> = {}) {\n if (consumed) throw new NecromancerConfigError('This layout transition has already been animated.');\n\n const { elements: committedElements, ...animationOptions } = options;\n const elements = uniqueElements(committedElements ?? entries.map(({ element }) => element));\n const changed = getKey && captured ? matchByKey(captured, elements, getKey) : matchByIdentity(entries, elements);\n\n consumed = true;\n\n return animateEach(\n changed.map(({ element }) => element),\n (_, index) => {\n // `changed` was mapped directly into the elements array above, so this index is always in range.\n const change = changed[index]!;\n const translate = `${round(change.x, 2)}px ${round(change.y, 2)}px`;\n const scale = `${round(change.scaleX, 4)} ${round(change.scaleY, 4)}`;\n\n return [\n { composite: 'add', scale, translate },\n { composite: 'add', scale: '1 1', translate: '0px 0px' },\n ];\n },\n animationOptions,\n );\n },\n };\n}\n"],"mappings":"mEAMA,SAAS,0BAA0B,EAAqB,EAAiD,CACvG,IAAM,UAAc,EAAQ,EAAO,MAAM,EAUzC,OARA,EAAO,iBAAiB,QAAS,MAAO,CAAE,KAAM,EAAK,CAAC,EAElD,EAAO,SACT,EAAO,oBAAoB,QAAS,KAAK,EACzC,EAAQ,EAAO,MAAM,MACR,IAAA,QAGF,EAAO,oBAAoB,QAAS,KAAK,CACxD,CAEA,SAAS,oBAAoB,EAAsB,EAAuB,EAA4C,CACpH,OAAO,EAAU,SAAS,UAEtB,EAAU,EAEH,CAAE,OAAQ,EAAU,UAAY,UAAW,GAEnD,IACC,EAAU,EAEH,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AAI,CAAG,EACnB,MAAM,IAAI,uBAAuB,4DAA4D,EAK/F,OAFA,EAAU,IAAI,CAAG,EAEV,EACH,CAAC,eAAe,EAAS,EAAM,IAAI,CAAC,CAAC,CAAC,OAAQ,GAAgD,EAAQ,CAAO,EAC7G,CAAC,CACP,CAAC,CACH,CAWA,SAAgB,cACd,EACA,EAA6C,CAAC,EACf,CAC/B,IAAM,EAAsC,eAAe,CAAQ,CAAC,CAAC,IAAK,IAAa,CACrF,UACA,KAAM,cAAc,CAAO,CAC7B,EAAE,EACI,EAAS,EAAQ,OACjB,EAAW,EAAS,aAAa,EAAS,EAAQ,UAAU,EAAI,IAAA,GAElE,EAAW,GAEf,MAAO,CACL,QAAQ,EAA+C,CAAC,EAAG,CACzD,GAAI,EAAU,MAAM,IAAI,uBAAuB,mDAAmD,EAElG,GAAM,CAAE,SAAU,EAAmB,GAAG,GAAqB,EACvD,EAAW,eAAe,GAAqB,EAAQ,KAAK,CAAE,aAAc,CAAO,CAAC,EACpF,EAAU,GAAU,EAAW,WAAW,EAAU,EAAU,CAAM,EAAI,gBAAgB,EAAS,CAAQ,EAI/G,MAFA,GAAW,GAEJ,YACL,EAAQ,KAAK,CAAE,aAAc,CAAO,GACnC,EAAG,IAAU,CAEZ,IAAM,EAAS,EAAQ,GACjB,EAAY,GAAG,MAAM,EAAO,EAAG,CAAC,EAAE,KAAK,MAAM,EAAO,EAAG,CAAC,EAAE,IAGhE,MAAO,CACL,CAAE,UAAW,MAAO,MAAA,GAHL,MAAM,EAAO,OAAQ,CAAC,EAAE,GAAG,MAAM,EAAO,OAAQ,CAAC,IAGrC,WAAU,EACrC,CAAE,UAAW,MAAO,MAAO,MAAO,UAAW,SAAU,CACzD,CACF,EACA,CACF,CACF,CACF,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"necromancer.iife.js","names":[],"sources":["../src/_handle.ts","../src/errors.ts","../src/motion.ts","../src/animate.ts","../src/_elements.ts","../src/animate-each.ts","../src/layout.ts"],"sourcesContent":["import type { AnimationGroup, AnimationHandle, AnimationResult } from './types';\n\n/**\n * Attaches an abort listener to a signal and returns a function that removes it.\n * When the signal aborts, calls the dispose function with the signal's reason.\n */\nfunction attachAbortSignalListener(signal: AbortSignal, dispose: (reason?: unknown) => void): () => void {\n const abort = () => dispose(signal.reason);\n\n signal.addEventListener('abort', abort, { once: true });\n\n if (signal.aborted) {\n signal.removeEventListener('abort', abort);\n dispose(signal.reason);\n return () => undefined;\n }\n\n return () => signal.removeEventListener('abort', abort);\n}\n\nfunction createResultPromise(animation: Animation, onSettled: () => void, reduced: boolean): Promise<AnimationResult> {\n return animation.finished.then(\n () => {\n onSettled();\n\n return { status: reduced ? 'reduced' : 'finished' };\n },\n (reason: unknown) => {\n onSettled();\n\n return { reason, status: 'cancelled' };\n },\n );\n}\n\n/** Wraps a native Animation with Necromancer's lifecycle contract. */\nexport function createAnimationHandle(animation: Animation, signal?: AbortSignal, reduced = false): AnimationHandle {\n let disposed = false;\n let disposeReason: unknown;\n let hasDisposeReason = false;\n let removeAbortListener: (() => void) | undefined;\n\n const result: Promise<AnimationResult> = createResultPromise(\n animation,\n () => {\n removeAbortListener?.();\n removeAbortListener = undefined;\n },\n reduced,\n ).then((outcome): AnimationResult => {\n if (disposed && hasDisposeReason && outcome.status === 'cancelled') {\n return { reason: disposeReason, status: 'cancelled' };\n }\n\n return outcome;\n });\n\n const dispose = (reason?: unknown): void => {\n if (disposed) return;\n\n disposed = true;\n disposeReason = reason;\n hasDisposeReason = reason !== undefined;\n removeAbortListener?.();\n removeAbortListener = undefined;\n animation.cancel();\n };\n\n if (signal) {\n removeAbortListener = attachAbortSignalListener(signal, dispose);\n }\n\n return {\n animation,\n dispose,\n get disposed() {\n return disposed;\n },\n result,\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n}\n\n/** Combines child animation handles under one disposal owner. */\nexport function createAnimationGroup(handles: readonly AnimationHandle[], signal?: AbortSignal): AnimationGroup {\n let disposed = false;\n let removeAbortListener: (() => void) | undefined;\n\n const results: Promise<readonly AnimationResult[]> = Promise.all(handles.map((handle) => handle.result)).then(\n (childResults): readonly AnimationResult[] => {\n removeAbortListener?.();\n removeAbortListener = undefined;\n\n return childResults;\n },\n );\n\n const dispose = (reason?: unknown): void => {\n if (disposed) return;\n\n disposed = true;\n removeAbortListener?.();\n removeAbortListener = undefined;\n for (const handle of handles) handle.dispose(reason);\n };\n\n if (signal) {\n removeAbortListener = attachAbortSignalListener(signal, dispose);\n }\n\n return {\n dispose,\n get disposed() {\n return disposed;\n },\n handles,\n results,\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n}\n","/** Base class for errors raised by `@vielzeug/necromancer`. */\nexport class NecromancerError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a Necromancer-owned option is invalid. */\nexport class NecromancerConfigError extends NecromancerError {}\n\n/** Thrown when the runtime does not implement the Web Animations API. */\nexport class NecromancerUnsupportedError extends NecromancerError {}\n","import { NecromancerConfigError } from './errors';\nimport type { AnimateOptions, MotionMode } from './types';\n\n/** Reports whether the requested motion preference reduces visible movement. */\nexport function shouldReduceMotion(mode: MotionMode): boolean {\n if (mode === 'full') return false;\n\n if (mode === 'reduced') return true;\n\n return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n}\n\n/** Converts ownership options to native timing, collapsing reduced motion to an instant transition. */\nexport function resolveAnimationOptions(options: AnimateOptions = {}, reduced = false): KeyframeAnimationOptions {\n const { motion: _motion, signal: _signal, ...nativeOptions } = options;\n\n return reduced ? { ...nativeOptions, delay: 0, duration: 0, endDelay: 0, iterations: 1 } : nativeOptions;\n}\n\n/** Adds an element's stagger offset without changing native nonnumeric delays when no offset is needed. */\nexport function withStaggeredDelay(options: AnimateOptions, offset: number): AnimateOptions {\n if (offset === 0) return options;\n\n const delay = options.delay ?? 0;\n\n if (typeof delay !== 'number') {\n throw new NecromancerConfigError(`A non-zero stagger requires a numeric delay; received ${typeof delay}.`);\n }\n\n return { ...options, delay: delay + offset };\n}\n","import { createAnimationHandle } from './_handle';\nimport { NecromancerUnsupportedError } from './errors';\nimport { resolveAnimationOptions, shouldReduceMotion } from './motion';\nimport type { AnimateOptions, AnimationHandle, Keyframes } from './types';\n\n/**\n * Starts a lifecycle-owned native Web Animation for one element.\n *\n * The returned handle cancels its native animation when disposed. By default, the\n * operating system's reduced-motion preference suppresses movement.\n */\nexport function animate(element: Element, keyframes: Keyframes, options: AnimateOptions = {}): AnimationHandle {\n if (options.signal?.aborted) throw options.signal.reason;\n\n if (typeof element.animate !== 'function') {\n throw new NecromancerUnsupportedError('The Web Animations API is not available in this environment.');\n }\n\n const reduced = shouldReduceMotion(options.motion ?? 'system');\n const nativeAnimation = element.animate(\n keyframes as Keyframe[] | PropertyIndexedKeyframes,\n resolveAnimationOptions(options, reduced),\n );\n return createAnimationHandle(nativeAnimation, options.signal, reduced);\n}\n","/** Deduplicates elements while preserving first-seen order. Shared by `animateEach()` and `captureLayout()`. */\nexport function uniqueElements<ElementType extends Element>(elements: Iterable<ElementType>): ElementType[] {\n return [...new Set(elements)];\n}\n","import { uniqueElements } from './_elements';\nimport { createAnimationGroup } from './_handle';\nimport { animate } from './animate';\nimport { NecromancerConfigError } from './errors';\nimport { withStaggeredDelay } from './motion';\nimport type { AnimateEachOptions, AnimationGroup, AnimationHandle, KeyframeFactory, Keyframes } from './types';\n\nfunction validateStagger(stagger: number): void {\n if (!Number.isFinite(stagger) || stagger < 0) {\n throw new NecromancerConfigError('stagger must be a finite, non-negative number.');\n }\n}\n\n/**\n * Starts lifecycle-owned animations for unique elements in iteration order.\n *\n * Each subsequent element starts after `stagger` milliseconds. A keyframe factory\n * receives the stable unique-element index and total before any animation starts.\n */\nexport function animateEach<ElementType extends Element>(\n elements: Iterable<ElementType>,\n keyframes: Keyframes | KeyframeFactory<ElementType>,\n options: AnimateEachOptions = {},\n): AnimationGroup {\n const { signal, stagger = 0, ...animationOptions } = options;\n\n validateStagger(stagger);\n\n if (signal?.aborted) throw signal.reason;\n\n const unique = uniqueElements(elements);\n const frames = unique.map((element, index) =>\n typeof keyframes === 'function' ? keyframes(element, index, unique.length) : keyframes,\n );\n\n if (signal?.aborted) throw signal.reason;\n\n const handles: AnimationHandle[] = [];\n\n try {\n for (const [index, element] of unique.entries()) {\n // `frames` was built above from `unique`, one entry per element, so this index is always in range.\n const currentFrames = frames[index]!;\n\n handles.push(animate(element, currentFrames, withStaggeredDelay(animationOptions, index * stagger)));\n }\n } catch (error) {\n for (const handle of handles) handle.dispose(error);\n\n throw error;\n }\n\n return createAnimationGroup(handles, signal);\n}\n","import { uniqueElements } from './_elements';\nimport { animateEach } from './animate-each';\nimport { NecromancerConfigError } from './errors';\nimport type { LayoutAnimationOptions, LayoutCaptureOptions, LayoutTransition } from './types';\n\ntype LayoutRect = Readonly<Pick<DOMRectReadOnly, 'height' | 'width' | 'x' | 'y'>>;\ntype LayoutEntry<ElementType extends Element> = Readonly<{ element: ElementType; rect: LayoutRect }>;\ntype LayoutChange<ElementType extends Element> = Readonly<{\n element: ElementType;\n scaleX: number;\n scaleY: number;\n x: number;\n y: number;\n}>;\n\n// Rounds before templating into a keyframe string purely for DevTools readability — a `getBoundingClientRect()`\n// subtraction routinely produces values like `12.340000000000002`, which is noise once rendered as CSS.\n// Pixels only need whole-number precision; scale factors (close to 1) need finer precision to stay visually exact.\nfunction round(value: number, precision: number): number {\n const factor = 10 ** precision;\n\n return Math.round(value * factor) / factor;\n}\n\n// `getBoundingClientRect()`'s width/height is the rotated, axis-aligned bounding box — using it\n// for size would distort the scale ratio under any rotation. `offsetWidth`/`offsetHeight` report\n// the box's own untransformed layout size instead. Elements without an offset box (e.g. SVG)\n// fall back to the bounding rect, accepting that same distortion as the only option available.\nfunction measureSize(element: Element): Readonly<{ height: number; width: number }> {\n if ('offsetWidth' in element && 'offsetHeight' in element) {\n return { height: (element as HTMLElement).offsetHeight, width: (element as HTMLElement).offsetWidth };\n }\n\n const rect = element.getBoundingClientRect();\n\n return { height: rect.height, width: rect.width };\n}\n\nfunction measureLayout(element: Element): LayoutRect {\n const rect = element.getBoundingClientRect();\n const size = measureSize(element);\n\n return { height: size.height, width: size.width, x: rect.x, y: rect.y };\n}\n\n// `next` is 0 exactly when the element has collapsed (e.g. `display: none` mid-transition);\n// there's no meaningful ratio to compute then, so treat it as unscaled rather than producing Infinity/NaN.\nfunction computeScale(captured: number, next: number): number {\n return next === 0 ? 1 : captured / next;\n}\n\nfunction readKey<ElementType extends Element>(\n element: ElementType,\n getKey: (element: ElementType) => string,\n phase: string,\n): string {\n const key = getKey(element);\n\n if (typeof key !== 'string' || key.length === 0) {\n throw new NecromancerConfigError(`getKey must return a non-empty string for every ${phase} element.`);\n }\n\n return key;\n}\n\nfunction createKeyMap<ElementType extends Element>(\n entries: readonly LayoutEntry<ElementType>[],\n getKey: (element: ElementType) => string,\n phase: string,\n) {\n const keys = new Map<string, LayoutEntry<ElementType>>();\n\n for (const entry of entries) {\n const key = readKey(entry.element, getKey, phase);\n\n if (keys.has(key)) {\n throw new NecromancerConfigError(`getKey returned duplicate keys for the ${phase} elements.`);\n }\n\n keys.set(key, entry);\n }\n\n return keys;\n}\n\nfunction changedElement<ElementType extends Element>(\n element: ElementType,\n rect: LayoutRect,\n): LayoutChange<ElementType> | undefined {\n if (!element.isConnected) return undefined;\n\n const next = measureLayout(element);\n const x = rect.x - next.x;\n const y = rect.y - next.y;\n const scaleX = computeScale(rect.width, next.width);\n const scaleY = computeScale(rect.height, next.height);\n\n return x === 0 && y === 0 && scaleX === 1 && scaleY === 1 ? undefined : { element, scaleX, scaleY, x, y };\n}\n\nfunction matchByIdentity<ElementType extends Element>(\n entries: readonly LayoutEntry<ElementType>[],\n elements: readonly ElementType[],\n): LayoutChange<ElementType>[] {\n const captured = new Map(entries.map((entry) => [entry.element, entry]));\n\n return elements.flatMap((element) => {\n const entry = captured.get(element);\n\n return entry\n ? [changedElement(element, entry.rect)].filter((change): change is LayoutChange<ElementType> => Boolean(change))\n : [];\n });\n}\n\nfunction matchByKey<ElementType extends Element>(\n captured: ReadonlyMap<string, LayoutEntry<ElementType>>,\n elements: readonly ElementType[],\n getKey: (element: ElementType) => string,\n): LayoutChange<ElementType>[] {\n const committed = new Set<string>();\n\n return elements.flatMap((element) => {\n const key = readKey(element, getKey, 'committed');\n const entry = captured.get(key);\n\n if (committed.has(key)) {\n throw new NecromancerConfigError('getKey returned duplicate keys for the committed elements.');\n }\n\n committed.add(key);\n\n return entry\n ? [changedElement(element, entry.rect)].filter((change): change is LayoutChange<ElementType> => Boolean(change))\n : [];\n });\n}\n\n/**\n * Captures the current position and size of unique elements for a later FLIP animation.\n *\n * Each element's `x`/`y` position and `width`/`height` are captured. Rotation and other\n * transforms are not captured or compensated. Capture before mutating the DOM, then call\n * the returned transition's `animate()` method after the browser has applied the resulting\n * layout — position changes animate via translate, and size changes via scale, both\n * additively composed on top of any authored transform.\n */\nexport function captureLayout<ElementType extends Element>(\n elements: Iterable<ElementType>,\n options: LayoutCaptureOptions<ElementType> = {},\n): LayoutTransition<ElementType> {\n const entries: LayoutEntry<ElementType>[] = uniqueElements(elements).map((element) => ({\n element,\n rect: measureLayout(element),\n }));\n const getKey = options.getKey;\n const captured = getKey ? createKeyMap(entries, getKey, 'captured') : undefined;\n\n let consumed = false;\n\n return {\n animate(options: LayoutAnimationOptions<ElementType> = {}) {\n if (consumed) throw new NecromancerConfigError('This layout transition has already been animated.');\n\n const { elements: committedElements, ...animationOptions } = options;\n const elements = uniqueElements(committedElements ?? entries.map(({ element }) => element));\n const changed = getKey && captured ? matchByKey(captured, elements, getKey) : matchByIdentity(entries, elements);\n\n consumed = true;\n\n return animateEach(\n changed.map(({ element }) => element),\n (_, index) => {\n // `changed` was mapped directly into the elements array above, so this index is always in range.\n const change = changed[index]!;\n const translate = `${round(change.x, 2)}px ${round(change.y, 2)}px`;\n const scale = `${round(change.scaleX, 4)} ${round(change.scaleY, 4)}`;\n\n return [\n { composite: 'add', scale, translate },\n { composite: 'add', scale: '1 1', translate: '0px 0px' },\n ];\n },\n animationOptions,\n );\n },\n };\n}\n"],"mappings":"0FAMA,SAAS,0BAA0B,EAAqB,EAAiD,CACvG,IAAM,UAAc,EAAQ,EAAO,MAAM,EAUzC,OARA,EAAO,iBAAiB,QAAS,MAAO,CAAE,KAAM,EAAK,CAAC,EAElD,EAAO,SACT,EAAO,oBAAoB,QAAS,KAAK,EACzC,EAAQ,EAAO,MAAM,MACR,IAAA,QAGF,EAAO,oBAAoB,QAAS,KAAK,CACxD,CAEA,SAAS,oBAAoB,EAAsB,EAAuB,EAA4C,CACpH,OAAO,EAAU,SAAS,UAEtB,EAAU,EAEH,CAAE,OAAQ,EAAU,UAAY,UAAW,GAEnD,IACC,EAAU,EAEH,CAAE,SAAQ,OAAQ,WAAY,EAEzC,CACF,CAGA,SAAgB,sBAAsB,EAAsB,EAAsB,EAAU,GAAwB,CAClH,IAAI,EAAW,GACX,EACA,EAAmB,GACnB,EAEE,EAAmC,oBACvC,MACM,CACJ,IAAsB,EACtB,EAAsB,IAAA,EACxB,EACA,CACF,CAAC,CAAC,KAAM,GACF,GAAY,GAAoB,EAAQ,SAAW,YAC9C,CAAE,OAAQ,EAAe,OAAQ,WAAY,EAG/C,CACR,EAEK,QAAW,GAA2B,CACtC,IAEJ,EAAW,GACX,EAAgB,EAChB,EAAmB,IAAW,IAAA,GAC9B,IAAsB,EACtB,EAAsB,IAAA,GACtB,EAAU,OAAO,EACnB,EAMA,OAJI,IACF,EAAsB,0BAA0B,EAAQ,OAAO,GAG1D,CACL,YACA,QACA,IAAI,UAAW,CACb,OAAO,CACT,EACA,SACA,CAAC,OAAO,UAAW,CACjB,KAAK,QAAQ,CACf,CACF,CACF,CAGA,SAAgB,qBAAqB,EAAqC,EAAsC,CAC9G,IAAI,EAAW,GACX,EAEE,EAA+C,QAAQ,IAAI,EAAQ,IAAK,GAAW,EAAO,MAAM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,GAEJ,YACL,EAAQ,KAAK,CAAE,aAAc,CAAO,GACnC,EAAG,IAAU,CAEZ,IAAM,EAAS,EAAQ,GACjB,EAAY,GAAG,MAAM,EAAO,EAAG,CAAC,EAAE,KAAK,MAAM,EAAO,EAAG,CAAC,EAAE,IAGhE,MAAO,CACL,CAAE,UAAW,MAAO,MAAA,GAHL,MAAM,EAAO,OAAQ,CAAC,EAAE,GAAG,MAAM,EAAO,OAAQ,CAAC,IAGrC,WAAU,EACrC,CAAE,UAAW,MAAO,MAAO,MAAO,UAAW,SAAU,CACzD,CACF,EACA,CACF,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"necromancer.iife.js","names":[],"sources":["../src/_handle.ts","../src/errors.ts","../src/motion.ts","../src/animate.ts","../src/_elements.ts","../src/animate-each.ts","../src/layout.ts"],"sourcesContent":["import type { AnimationGroup, AnimationHandle, AnimationResult } from './types';\n\n/**\n * Attaches an abort listener to a signal and returns a function that removes it.\n * When the signal aborts, calls the dispose function with the signal's reason.\n */\nfunction attachAbortSignalListener(signal: AbortSignal, dispose: (reason?: unknown) => void): () => void {\n const abort = () => dispose(signal.reason);\n\n signal.addEventListener('abort', abort, { once: true });\n\n if (signal.aborted) {\n signal.removeEventListener('abort', abort);\n dispose(signal.reason);\n return () => undefined;\n }\n\n return () => signal.removeEventListener('abort', abort);\n}\n\nfunction createResultPromise(animation: Animation, onSettled: () => void, reduced: boolean): Promise<AnimationResult> {\n return animation.finished.then(\n () => {\n onSettled();\n\n return { status: reduced ? 'reduced' : 'finished' };\n },\n (reason: unknown) => {\n onSettled();\n\n return { reason, status: 'cancelled' };\n },\n );\n}\n\n/** Wraps a native Animation with Necromancer's lifecycle contract. */\nexport function createAnimationHandle(animation: Animation, signal?: AbortSignal, reduced = false): AnimationHandle {\n let disposed = false;\n let disposeReason: unknown;\n let hasDisposeReason = false;\n let removeAbortListener: (() => void) | undefined;\n\n const result: Promise<AnimationResult> = createResultPromise(\n animation,\n () => {\n removeAbortListener?.();\n removeAbortListener = undefined;\n },\n reduced,\n ).then((outcome): AnimationResult => {\n if (disposed && hasDisposeReason && outcome.status === 'cancelled') {\n return { reason: disposeReason, status: 'cancelled' };\n }\n\n return outcome;\n });\n\n const dispose = (reason?: unknown): void => {\n if (disposed) return;\n\n disposed = true;\n disposeReason = reason;\n hasDisposeReason = reason !== undefined;\n removeAbortListener?.();\n removeAbortListener = undefined;\n animation.cancel();\n };\n\n if (signal) {\n removeAbortListener = attachAbortSignalListener(signal, dispose);\n }\n\n return {\n animation,\n dispose,\n get disposed() {\n return disposed;\n },\n result,\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n}\n\n/** Combines child animation handles under one disposal owner. */\nexport function createAnimationGroup(handles: readonly AnimationHandle[], signal?: AbortSignal): AnimationGroup {\n let disposed = false;\n let removeAbortListener: (() => void) | undefined;\n\n const results: Promise<readonly AnimationResult[]> = Promise.all(handles.map((handle) => handle.result)).then(\n (childResults): readonly AnimationResult[] => {\n removeAbortListener?.();\n removeAbortListener = undefined;\n\n return childResults;\n },\n );\n\n const dispose = (reason?: unknown): void => {\n if (disposed) return;\n\n disposed = true;\n removeAbortListener?.();\n removeAbortListener = undefined;\n for (const handle of handles) handle.dispose(reason);\n };\n\n if (signal) {\n removeAbortListener = attachAbortSignalListener(signal, dispose);\n }\n\n return {\n dispose,\n get disposed() {\n return disposed;\n },\n handles,\n results,\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n}\n","/** Base class for errors raised by `@vielzeug/necromancer`. */\nexport class NecromancerError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a Necromancer-owned option is invalid. */\nexport class NecromancerConfigError extends NecromancerError {}\n\n/** Thrown when the runtime does not implement the Web Animations API. */\nexport class NecromancerUnsupportedError extends NecromancerError {}\n","import { NecromancerConfigError } from './errors';\nimport type { AnimateOptions, MotionMode } from './types';\n\n/** Reports whether the requested motion preference reduces visible movement. */\nexport function shouldReduceMotion(mode: MotionMode): boolean {\n if (mode === 'full') return false;\n\n if (mode === 'reduced') return true;\n\n return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n}\n\n/** Converts ownership options to native timing, collapsing reduced motion to an instant transition. */\nexport function resolveAnimationOptions(options: AnimateOptions = {}, reduced = false): KeyframeAnimationOptions {\n const { motion: _motion, signal: _signal, ...nativeOptions } = options;\n\n return reduced ? { ...nativeOptions, delay: 0, duration: 0, endDelay: 0, iterations: 1 } : nativeOptions;\n}\n\n/** Adds an element's stagger offset without changing native nonnumeric delays when no offset is needed. */\nexport function withStaggeredDelay(options: AnimateOptions, offset: number): AnimateOptions {\n if (offset === 0) return options;\n\n const delay = options.delay ?? 0;\n\n if (typeof delay !== 'number') {\n throw new NecromancerConfigError(`A non-zero stagger requires a numeric delay; received ${typeof delay}.`);\n }\n\n return { ...options, delay: delay + offset };\n}\n","import { createAnimationHandle } from './_handle';\nimport { NecromancerUnsupportedError } from './errors';\nimport { resolveAnimationOptions, shouldReduceMotion } from './motion';\nimport type { AnimateOptions, AnimationHandle, Keyframes } from './types';\n\n/**\n * Starts a lifecycle-owned native Web Animation for one element.\n *\n * The returned handle cancels its native animation when disposed. By default, the\n * operating system's reduced-motion preference suppresses movement.\n */\nexport function animate(element: Element, keyframes: Keyframes, options: AnimateOptions = {}): AnimationHandle {\n if (options.signal?.aborted) throw options.signal.reason;\n\n if (typeof element.animate !== 'function') {\n throw new NecromancerUnsupportedError('The Web Animations API is not available in this environment.');\n }\n\n const reduced = shouldReduceMotion(options.motion ?? 'system');\n const nativeAnimation = element.animate(\n keyframes as Keyframe[] | PropertyIndexedKeyframes,\n resolveAnimationOptions(options, reduced),\n );\n return createAnimationHandle(nativeAnimation, options.signal, reduced);\n}\n","/** Deduplicates elements while preserving first-seen order. Shared by `animateEach()` and `captureLayout()`. */\nexport function uniqueElements<ElementType extends Element>(elements: Iterable<ElementType>): ElementType[] {\n return [...new Set(elements)];\n}\n","import { uniqueElements } from './_elements';\nimport { createAnimationGroup } from './_handle';\nimport { animate } from './animate';\nimport { NecromancerConfigError } from './errors';\nimport { withStaggeredDelay } from './motion';\nimport type { AnimateEachOptions, AnimationGroup, AnimationHandle, KeyframeFactory, Keyframes } from './types';\n\nfunction validateStagger(stagger: number): void {\n if (!Number.isFinite(stagger) || stagger < 0) {\n throw new NecromancerConfigError('stagger must be a finite, non-negative number.');\n }\n}\n\n/**\n * Starts lifecycle-owned animations for unique elements in iteration order.\n *\n * Each subsequent element starts after `stagger` milliseconds. A keyframe factory\n * receives the stable unique-element index and total before any animation starts.\n */\nexport function animateEach<ElementType extends Element>(\n elements: Iterable<ElementType>,\n keyframes: Keyframes | KeyframeFactory<ElementType>,\n options: AnimateEachOptions = {},\n): AnimationGroup {\n const { signal, stagger = 0, ...animationOptions } = options;\n\n validateStagger(stagger);\n\n if (signal?.aborted) throw signal.reason;\n\n const unique = uniqueElements(elements);\n const frames = unique.map((element, index) =>\n typeof keyframes === 'function' ? keyframes(element, index, unique.length) : keyframes,\n );\n\n if (signal?.aborted) throw signal.reason;\n\n const handles: AnimationHandle[] = [];\n\n try {\n for (const [index, element] of unique.entries()) {\n // `frames` was built above from `unique`, one entry per element, so this index is always in range.\n const currentFrames = frames[index]!;\n\n handles.push(animate(element, currentFrames, withStaggeredDelay(animationOptions, index * stagger)));\n }\n } catch (error) {\n for (const handle of handles) handle.dispose(error);\n\n throw error;\n }\n\n return createAnimationGroup(handles, signal);\n}\n","import { uniqueElements } from './_elements';\nimport { animateEach } from './animate-each';\nimport { NecromancerConfigError } from './errors';\nimport type { LayoutAnimationOptions, LayoutCaptureOptions, LayoutTransition } from './types';\n\ntype LayoutRect = Readonly<Pick<DOMRectReadOnly, 'height' | 'width' | 'x' | 'y'>>;\ntype LayoutEntry<ElementType extends Element> = Readonly<{ element: ElementType; rect: LayoutRect }>;\ntype LayoutChange<ElementType extends Element> = Readonly<{\n element: ElementType;\n scaleX: number;\n scaleY: number;\n x: number;\n y: number;\n}>;\n\n// Rounds before templating into a keyframe string purely for DevTools readability: a `getBoundingClientRect()`\n// subtraction routinely produces values like `12.340000000000002`, which is noise once rendered as CSS.\n// Pixels only need whole-number precision; scale factors (close to 1) need finer precision to stay visually exact.\nfunction round(value: number, precision: number): number {\n const factor = 10 ** precision;\n\n return Math.round(value * factor) / factor;\n}\n\n// `getBoundingClientRect()`'s width/height is the rotated, axis-aligned bounding box: using it\n// for size would distort the scale ratio under any rotation. `offsetWidth`/`offsetHeight` report\n// the box's own untransformed layout size instead. Elements without an offset box (e.g. SVG)\n// fall back to the bounding rect, accepting that same distortion as the only option available.\nfunction measureSize(element: Element): Readonly<{ height: number; width: number }> {\n if ('offsetWidth' in element && 'offsetHeight' in element) {\n return { height: (element as HTMLElement).offsetHeight, width: (element as HTMLElement).offsetWidth };\n }\n\n const rect = element.getBoundingClientRect();\n\n return { height: rect.height, width: rect.width };\n}\n\nfunction measureLayout(element: Element): LayoutRect {\n const rect = element.getBoundingClientRect();\n const size = measureSize(element);\n\n return { height: size.height, width: size.width, x: rect.x, y: rect.y };\n}\n\n// `next` is 0 exactly when the element has collapsed (e.g. `display: none` mid-transition);\n// there's no meaningful ratio to compute then, so treat it as unscaled rather than producing Infinity/NaN.\nfunction computeScale(captured: number, next: number): number {\n return next === 0 ? 1 : captured / next;\n}\n\nfunction readKey<ElementType extends Element>(\n element: ElementType,\n getKey: (element: ElementType) => string,\n phase: string,\n): string {\n const key = getKey(element);\n\n if (typeof key !== 'string' || key.length === 0) {\n throw new NecromancerConfigError(`getKey must return a non-empty string for every ${phase} element.`);\n }\n\n return key;\n}\n\nfunction createKeyMap<ElementType extends Element>(\n entries: readonly LayoutEntry<ElementType>[],\n getKey: (element: ElementType) => string,\n phase: string,\n) {\n const keys = new Map<string, LayoutEntry<ElementType>>();\n\n for (const entry of entries) {\n const key = readKey(entry.element, getKey, phase);\n\n if (keys.has(key)) {\n throw new NecromancerConfigError(`getKey returned duplicate keys for the ${phase} elements.`);\n }\n\n keys.set(key, entry);\n }\n\n return keys;\n}\n\nfunction changedElement<ElementType extends Element>(\n element: ElementType,\n rect: LayoutRect,\n): LayoutChange<ElementType> | undefined {\n if (!element.isConnected) return undefined;\n\n const next = measureLayout(element);\n const x = rect.x - next.x;\n const y = rect.y - next.y;\n const scaleX = computeScale(rect.width, next.width);\n const scaleY = computeScale(rect.height, next.height);\n\n return x === 0 && y === 0 && scaleX === 1 && scaleY === 1 ? undefined : { element, scaleX, scaleY, x, y };\n}\n\nfunction matchByIdentity<ElementType extends Element>(\n entries: readonly LayoutEntry<ElementType>[],\n elements: readonly ElementType[],\n): LayoutChange<ElementType>[] {\n const captured = new Map(entries.map((entry) => [entry.element, entry]));\n\n return elements.flatMap((element) => {\n const entry = captured.get(element);\n\n return entry\n ? [changedElement(element, entry.rect)].filter((change): change is LayoutChange<ElementType> => Boolean(change))\n : [];\n });\n}\n\nfunction matchByKey<ElementType extends Element>(\n captured: ReadonlyMap<string, LayoutEntry<ElementType>>,\n elements: readonly ElementType[],\n getKey: (element: ElementType) => string,\n): LayoutChange<ElementType>[] {\n const committed = new Set<string>();\n\n return elements.flatMap((element) => {\n const key = readKey(element, getKey, 'committed');\n const entry = captured.get(key);\n\n if (committed.has(key)) {\n throw new NecromancerConfigError('getKey returned duplicate keys for the committed elements.');\n }\n\n committed.add(key);\n\n return entry\n ? [changedElement(element, entry.rect)].filter((change): change is LayoutChange<ElementType> => Boolean(change))\n : [];\n });\n}\n\n/**\n * Captures the current position and size of unique elements for a later FLIP animation.\n *\n * Each element's `x`/`y` position and `width`/`height` are captured. Rotation and other\n * transforms are not captured or compensated. Capture before mutating the DOM, then call\n * the returned transition's `animate()` method after the browser has applied the resulting\n * layout: position changes animate via translate, and size changes via scale, both\n * additively composed on top of any authored transform.\n */\nexport function captureLayout<ElementType extends Element>(\n elements: Iterable<ElementType>,\n options: LayoutCaptureOptions<ElementType> = {},\n): LayoutTransition<ElementType> {\n const entries: LayoutEntry<ElementType>[] = uniqueElements(elements).map((element) => ({\n element,\n rect: measureLayout(element),\n }));\n const getKey = options.getKey;\n const captured = getKey ? createKeyMap(entries, getKey, 'captured') : undefined;\n\n let consumed = false;\n\n return {\n animate(options: LayoutAnimationOptions<ElementType> = {}) {\n if (consumed) throw new NecromancerConfigError('This layout transition has already been animated.');\n\n const { elements: committedElements, ...animationOptions } = options;\n const elements = uniqueElements(committedElements ?? entries.map(({ element }) => element));\n const changed = getKey && captured ? matchByKey(captured, elements, getKey) : matchByIdentity(entries, elements);\n\n consumed = true;\n\n return animateEach(\n changed.map(({ element }) => element),\n (_, index) => {\n // `changed` was mapped directly into the elements array above, so this index is always in range.\n const change = changed[index]!;\n const translate = `${round(change.x, 2)}px ${round(change.y, 2)}px`;\n const scale = `${round(change.scaleX, 4)} ${round(change.scaleY, 4)}`;\n\n return [\n { composite: 'add', scale, translate },\n { composite: 'add', scale: '1 1', translate: '0px 0px' },\n ];\n },\n animationOptions,\n );\n },\n };\n}\n"],"mappings":"0FAMA,SAAS,0BAA0B,EAAqB,EAAiD,CACvG,IAAM,UAAc,EAAQ,EAAO,MAAM,EAUzC,OARA,EAAO,iBAAiB,QAAS,MAAO,CAAE,KAAM,EAAK,CAAC,EAElD,EAAO,SACT,EAAO,oBAAoB,QAAS,KAAK,EACzC,EAAQ,EAAO,MAAM,MACR,IAAA,QAGF,EAAO,oBAAoB,QAAS,KAAK,CACxD,CAEA,SAAS,oBAAoB,EAAsB,EAAuB,EAA4C,CACpH,OAAO,EAAU,SAAS,UAEtB,EAAU,EAEH,CAAE,OAAQ,EAAU,UAAY,UAAW,GAEnD,IACC,EAAU,EAEH,CAAE,SAAQ,OAAQ,WAAY,EAEzC,CACF,CAGA,SAAgB,sBAAsB,EAAsB,EAAsB,EAAU,GAAwB,CAClH,IAAI,EAAW,GACX,EACA,EAAmB,GACnB,EAEE,EAAmC,oBACvC,MACM,CACJ,IAAsB,EACtB,EAAsB,IAAA,EACxB,EACA,CACF,CAAC,C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,EACA,EAA6C,CAAC,EACf,CAC/B,IAAM,EAAsC,eAAe,CAAQ,CAAC,CAAC,IAAK,IAAa,CACrF,UACA,KAAM,cAAc,CAAO,CAC7B,EAAE,EACI,EAAS,EAAQ,OACjB,EAAW,EAAS,aAAa,EAAS,EAAQ,UAAU,EAAI,IAAA,GAElE,EAAW,GAEf,MAAO,CACL,QAAQ,EAA+C,CAAC,EAAG,CACzD,GAAI,EAAU,MAAM,IAAI,uBAAuB,mDAAmD,EAElG,GAAM,CAAE,SAAU,EAAmB,GAAG,GAAqB,EACvD,EAAW,eAAe,GAAqB,EAAQ,KAAK,CAAE,aAAc,CAAO,CAAC,EACpF,EAAU,GAAU,EAAW,WAAW,EAAU,EAAU,CAAM,EAAI,gBAAgB,EAAS,CAAQ,EAI/G,MAFA,GAAW,GAEJ,YACL,EAAQ,KAAK,CAAE,aAAc,CAAO,GACnC,EAAG,IAAU,CAEZ,IAAM,EAAS,EAAQ,GACjB,EAAY,GAAG,MAAM,EAAO,EAAG,CAAC,EAAE,KAAK,MAAM,EAAO,EAAG,CAAC,EAAE,IAGhE,MAAO,CACL,CAAE,UAAW,MAAO,MAAA,GAHL,MAAM,EAAO,OAAQ,CAAC,EAAE,GAAG,MAAM,EAAO,OAAQ,CAAC,IAGrC,WAAU,EACrC,CAAE,UAAW,MAAO,MAAO,MAAO,UAAW,SAAU,CACzD,CACF,EACA,CACF,CACF,CACF,CACF"}
|
package/dist/necromancer.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"necromancer.js","names":[],"sources":["../src/_handle.ts","../src/errors.ts","../src/motion.ts","../src/animate.ts","../src/_elements.ts","../src/animate-each.ts","../src/layout.ts"],"sourcesContent":["import type { AnimationGroup, AnimationHandle, AnimationResult } from './types';\n\n/**\n * Attaches an abort listener to a signal and returns a function that removes it.\n * When the signal aborts, calls the dispose function with the signal's reason.\n */\nfunction attachAbortSignalListener(signal: AbortSignal, dispose: (reason?: unknown) => void): () => void {\n const abort = () => dispose(signal.reason);\n\n signal.addEventListener('abort', abort, { once: true });\n\n if (signal.aborted) {\n signal.removeEventListener('abort', abort);\n dispose(signal.reason);\n return () => undefined;\n }\n\n return () => signal.removeEventListener('abort', abort);\n}\n\nfunction createResultPromise(animation: Animation, onSettled: () => void, reduced: boolean): Promise<AnimationResult> {\n return animation.finished.then(\n () => {\n onSettled();\n\n return { status: reduced ? 'reduced' : 'finished' };\n },\n (reason: unknown) => {\n onSettled();\n\n return { reason, status: 'cancelled' };\n },\n );\n}\n\n/** Wraps a native Animation with Necromancer's lifecycle contract. */\nexport function createAnimationHandle(animation: Animation, signal?: AbortSignal, reduced = false): AnimationHandle {\n let disposed = false;\n let disposeReason: unknown;\n let hasDisposeReason = false;\n let removeAbortListener: (() => void) | undefined;\n\n const result: Promise<AnimationResult> = createResultPromise(\n animation,\n () => {\n removeAbortListener?.();\n removeAbortListener = undefined;\n },\n reduced,\n ).then((outcome): AnimationResult => {\n if (disposed && hasDisposeReason && outcome.status === 'cancelled') {\n return { reason: disposeReason, status: 'cancelled' };\n }\n\n return outcome;\n });\n\n const dispose = (reason?: unknown): void => {\n if (disposed) return;\n\n disposed = true;\n disposeReason = reason;\n hasDisposeReason = reason !== undefined;\n removeAbortListener?.();\n removeAbortListener = undefined;\n animation.cancel();\n };\n\n if (signal) {\n removeAbortListener = attachAbortSignalListener(signal, dispose);\n }\n\n return {\n animation,\n dispose,\n get disposed() {\n return disposed;\n },\n result,\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n}\n\n/** Combines child animation handles under one disposal owner. */\nexport function createAnimationGroup(handles: readonly AnimationHandle[], signal?: AbortSignal): AnimationGroup {\n let disposed = false;\n let removeAbortListener: (() => void) | undefined;\n\n const results: Promise<readonly AnimationResult[]> = Promise.all(handles.map((handle) => handle.result)).then(\n (childResults): readonly AnimationResult[] => {\n removeAbortListener?.();\n removeAbortListener = undefined;\n\n return childResults;\n },\n );\n\n const dispose = (reason?: unknown): void => {\n if (disposed) return;\n\n disposed = true;\n removeAbortListener?.();\n removeAbortListener = undefined;\n for (const handle of handles) handle.dispose(reason);\n };\n\n if (signal) {\n removeAbortListener = attachAbortSignalListener(signal, dispose);\n }\n\n return {\n dispose,\n get disposed() {\n return disposed;\n },\n handles,\n results,\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n}\n","/** Base class for errors raised by `@vielzeug/necromancer`. */\nexport class NecromancerError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a Necromancer-owned option is invalid. */\nexport class NecromancerConfigError extends NecromancerError {}\n\n/** Thrown when the runtime does not implement the Web Animations API. */\nexport class NecromancerUnsupportedError extends NecromancerError {}\n","import { NecromancerConfigError } from './errors';\nimport type { AnimateOptions, MotionMode } from './types';\n\n/** Reports whether the requested motion preference reduces visible movement. */\nexport function shouldReduceMotion(mode: MotionMode): boolean {\n if (mode === 'full') return false;\n\n if (mode === 'reduced') return true;\n\n return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n}\n\n/** Converts ownership options to native timing, collapsing reduced motion to an instant transition. */\nexport function resolveAnimationOptions(options: AnimateOptions = {}, reduced = false): KeyframeAnimationOptions {\n const { motion: _motion, signal: _signal, ...nativeOptions } = options;\n\n return reduced ? { ...nativeOptions, delay: 0, duration: 0, endDelay: 0, iterations: 1 } : nativeOptions;\n}\n\n/** Adds an element's stagger offset without changing native nonnumeric delays when no offset is needed. */\nexport function withStaggeredDelay(options: AnimateOptions, offset: number): AnimateOptions {\n if (offset === 0) return options;\n\n const delay = options.delay ?? 0;\n\n if (typeof delay !== 'number') {\n throw new NecromancerConfigError(`A non-zero stagger requires a numeric delay; received ${typeof delay}.`);\n }\n\n return { ...options, delay: delay + offset };\n}\n","import { createAnimationHandle } from './_handle';\nimport { NecromancerUnsupportedError } from './errors';\nimport { resolveAnimationOptions, shouldReduceMotion } from './motion';\nimport type { AnimateOptions, AnimationHandle, Keyframes } from './types';\n\n/**\n * Starts a lifecycle-owned native Web Animation for one element.\n *\n * The returned handle cancels its native animation when disposed. By default, the\n * operating system's reduced-motion preference suppresses movement.\n */\nexport function animate(element: Element, keyframes: Keyframes, options: AnimateOptions = {}): AnimationHandle {\n if (options.signal?.aborted) throw options.signal.reason;\n\n if (typeof element.animate !== 'function') {\n throw new NecromancerUnsupportedError('The Web Animations API is not available in this environment.');\n }\n\n const reduced = shouldReduceMotion(options.motion ?? 'system');\n const nativeAnimation = element.animate(\n keyframes as Keyframe[] | PropertyIndexedKeyframes,\n resolveAnimationOptions(options, reduced),\n );\n return createAnimationHandle(nativeAnimation, options.signal, reduced);\n}\n","/** Deduplicates elements while preserving first-seen order. Shared by `animateEach()` and `captureLayout()`. */\nexport function uniqueElements<ElementType extends Element>(elements: Iterable<ElementType>): ElementType[] {\n return [...new Set(elements)];\n}\n","import { uniqueElements } from './_elements';\nimport { createAnimationGroup } from './_handle';\nimport { animate } from './animate';\nimport { NecromancerConfigError } from './errors';\nimport { withStaggeredDelay } from './motion';\nimport type { AnimateEachOptions, AnimationGroup, AnimationHandle, KeyframeFactory, Keyframes } from './types';\n\nfunction validateStagger(stagger: number): void {\n if (!Number.isFinite(stagger) || stagger < 0) {\n throw new NecromancerConfigError('stagger must be a finite, non-negative number.');\n }\n}\n\n/**\n * Starts lifecycle-owned animations for unique elements in iteration order.\n *\n * Each subsequent element starts after `stagger` milliseconds. A keyframe factory\n * receives the stable unique-element index and total before any animation starts.\n */\nexport function animateEach<ElementType extends Element>(\n elements: Iterable<ElementType>,\n keyframes: Keyframes | KeyframeFactory<ElementType>,\n options: AnimateEachOptions = {},\n): AnimationGroup {\n const { signal, stagger = 0, ...animationOptions } = options;\n\n validateStagger(stagger);\n\n if (signal?.aborted) throw signal.reason;\n\n const unique = uniqueElements(elements);\n const frames = unique.map((element, index) =>\n typeof keyframes === 'function' ? keyframes(element, index, unique.length) : keyframes,\n );\n\n if (signal?.aborted) throw signal.reason;\n\n const handles: AnimationHandle[] = [];\n\n try {\n for (const [index, element] of unique.entries()) {\n // `frames` was built above from `unique`, one entry per element, so this index is always in range.\n const currentFrames = frames[index]!;\n\n handles.push(animate(element, currentFrames, withStaggeredDelay(animationOptions, index * stagger)));\n }\n } catch (error) {\n for (const handle of handles) handle.dispose(error);\n\n throw error;\n }\n\n return createAnimationGroup(handles, signal);\n}\n","import { uniqueElements } from './_elements';\nimport { animateEach } from './animate-each';\nimport { NecromancerConfigError } from './errors';\nimport type { LayoutAnimationOptions, LayoutCaptureOptions, LayoutTransition } from './types';\n\ntype LayoutRect = Readonly<Pick<DOMRectReadOnly, 'height' | 'width' | 'x' | 'y'>>;\ntype LayoutEntry<ElementType extends Element> = Readonly<{ element: ElementType; rect: LayoutRect }>;\ntype LayoutChange<ElementType extends Element> = Readonly<{\n element: ElementType;\n scaleX: number;\n scaleY: number;\n x: number;\n y: number;\n}>;\n\n// Rounds before templating into a keyframe string purely for DevTools readability — a `getBoundingClientRect()`\n// subtraction routinely produces values like `12.340000000000002`, which is noise once rendered as CSS.\n// Pixels only need whole-number precision; scale factors (close to 1) need finer precision to stay visually exact.\nfunction round(value: number, precision: number): number {\n const factor = 10 ** precision;\n\n return Math.round(value * factor) / factor;\n}\n\n// `getBoundingClientRect()`'s width/height is the rotated, axis-aligned bounding box — using it\n// for size would distort the scale ratio under any rotation. `offsetWidth`/`offsetHeight` report\n// the box's own untransformed layout size instead. Elements without an offset box (e.g. SVG)\n// fall back to the bounding rect, accepting that same distortion as the only option available.\nfunction measureSize(element: Element): Readonly<{ height: number; width: number }> {\n if ('offsetWidth' in element && 'offsetHeight' in element) {\n return { height: (element as HTMLElement).offsetHeight, width: (element as HTMLElement).offsetWidth };\n }\n\n const rect = element.getBoundingClientRect();\n\n return { height: rect.height, width: rect.width };\n}\n\nfunction measureLayout(element: Element): LayoutRect {\n const rect = element.getBoundingClientRect();\n const size = measureSize(element);\n\n return { height: size.height, width: size.width, x: rect.x, y: rect.y };\n}\n\n// `next` is 0 exactly when the element has collapsed (e.g. `display: none` mid-transition);\n// there's no meaningful ratio to compute then, so treat it as unscaled rather than producing Infinity/NaN.\nfunction computeScale(captured: number, next: number): number {\n return next === 0 ? 1 : captured / next;\n}\n\nfunction readKey<ElementType extends Element>(\n element: ElementType,\n getKey: (element: ElementType) => string,\n phase: string,\n): string {\n const key = getKey(element);\n\n if (typeof key !== 'string' || key.length === 0) {\n throw new NecromancerConfigError(`getKey must return a non-empty string for every ${phase} element.`);\n }\n\n return key;\n}\n\nfunction createKeyMap<ElementType extends Element>(\n entries: readonly LayoutEntry<ElementType>[],\n getKey: (element: ElementType) => string,\n phase: string,\n) {\n const keys = new Map<string, LayoutEntry<ElementType>>();\n\n for (const entry of entries) {\n const key = readKey(entry.element, getKey, phase);\n\n if (keys.has(key)) {\n throw new NecromancerConfigError(`getKey returned duplicate keys for the ${phase} elements.`);\n }\n\n keys.set(key, entry);\n }\n\n return keys;\n}\n\nfunction changedElement<ElementType extends Element>(\n element: ElementType,\n rect: LayoutRect,\n): LayoutChange<ElementType> | undefined {\n if (!element.isConnected) return undefined;\n\n const next = measureLayout(element);\n const x = rect.x - next.x;\n const y = rect.y - next.y;\n const scaleX = computeScale(rect.width, next.width);\n const scaleY = computeScale(rect.height, next.height);\n\n return x === 0 && y === 0 && scaleX === 1 && scaleY === 1 ? undefined : { element, scaleX, scaleY, x, y };\n}\n\nfunction matchByIdentity<ElementType extends Element>(\n entries: readonly LayoutEntry<ElementType>[],\n elements: readonly ElementType[],\n): LayoutChange<ElementType>[] {\n const captured = new Map(entries.map((entry) => [entry.element, entry]));\n\n return elements.flatMap((element) => {\n const entry = captured.get(element);\n\n return entry\n ? [changedElement(element, entry.rect)].filter((change): change is LayoutChange<ElementType> => Boolean(change))\n : [];\n });\n}\n\nfunction matchByKey<ElementType extends Element>(\n captured: ReadonlyMap<string, LayoutEntry<ElementType>>,\n elements: readonly ElementType[],\n getKey: (element: ElementType) => string,\n): LayoutChange<ElementType>[] {\n const committed = new Set<string>();\n\n return elements.flatMap((element) => {\n const key = readKey(element, getKey, 'committed');\n const entry = captured.get(key);\n\n if (committed.has(key)) {\n throw new NecromancerConfigError('getKey returned duplicate keys for the committed elements.');\n }\n\n committed.add(key);\n\n return entry\n ? [changedElement(element, entry.rect)].filter((change): change is LayoutChange<ElementType> => Boolean(change))\n : [];\n });\n}\n\n/**\n * Captures the current position and size of unique elements for a later FLIP animation.\n *\n * Each element's `x`/`y` position and `width`/`height` are captured. Rotation and other\n * transforms are not captured or compensated. Capture before mutating the DOM, then call\n * the returned transition's `animate()` method after the browser has applied the resulting\n * layout — position changes animate via translate, and size changes via scale, both\n * additively composed on top of any authored transform.\n */\nexport function captureLayout<ElementType extends Element>(\n elements: Iterable<ElementType>,\n options: LayoutCaptureOptions<ElementType> = {},\n): LayoutTransition<ElementType> {\n const entries: LayoutEntry<ElementType>[] = uniqueElements(elements).map((element) => ({\n element,\n rect: measureLayout(element),\n }));\n const getKey = options.getKey;\n const captured = getKey ? createKeyMap(entries, getKey, 'captured') : undefined;\n\n let consumed = false;\n\n return {\n animate(options: LayoutAnimationOptions<ElementType> = {}) {\n if (consumed) throw new NecromancerConfigError('This layout transition has already been animated.');\n\n const { elements: committedElements, ...animationOptions } = options;\n const elements = uniqueElements(committedElements ?? entries.map(({ element }) => element));\n const changed = getKey && captured ? matchByKey(captured, elements, getKey) : matchByIdentity(entries, elements);\n\n consumed = true;\n\n return animateEach(\n changed.map(({ element }) => element),\n (_, index) => {\n // `changed` was mapped directly into the elements array above, so this index is always in range.\n const change = changed[index]!;\n const translate = `${round(change.x, 2)}px ${round(change.y, 2)}px`;\n const scale = `${round(change.scaleX, 4)} ${round(change.scaleY, 4)}`;\n\n return [\n { composite: 'add', scale, translate },\n { composite: 'add', scale: '1 1', translate: '0px 0px' },\n ];\n },\n animationOptions,\n );\n },\n };\n}\n"],"mappings":"AAMA,SAAS,0BAA0B,EAAqB,EAAiD,CACvG,IAAM,UAAc,EAAQ,E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,CAAE,UAAW,MAAO,MAAA,GAHL,MAAM,EAAO,OAAQ,CAAC,EAAE,GAAG,MAAM,EAAO,OAAQ,CAAC,IAGrC,WAAU,EACrC,CAAE,UAAW,MAAO,MAAO,MAAO,UAAW,SAAU,CACzD,CACF,EACA,CACF,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"necromancer.js","names":[],"sources":["../src/_handle.ts","../src/errors.ts","../src/motion.ts","../src/animate.ts","../src/_elements.ts","../src/animate-each.ts","../src/layout.ts"],"sourcesContent":["import type { AnimationGroup, AnimationHandle, AnimationResult } from './types';\n\n/**\n * Attaches an abort listener to a signal and returns a function that removes it.\n * When the signal aborts, calls the dispose function with the signal's reason.\n */\nfunction attachAbortSignalListener(signal: AbortSignal, dispose: (reason?: unknown) => void): () => void {\n const abort = () => dispose(signal.reason);\n\n signal.addEventListener('abort', abort, { once: true });\n\n if (signal.aborted) {\n signal.removeEventListener('abort', abort);\n dispose(signal.reason);\n return () => undefined;\n }\n\n return () => signal.removeEventListener('abort', abort);\n}\n\nfunction createResultPromise(animation: Animation, onSettled: () => void, reduced: boolean): Promise<AnimationResult> {\n return animation.finished.then(\n () => {\n onSettled();\n\n return { status: reduced ? 'reduced' : 'finished' };\n },\n (reason: unknown) => {\n onSettled();\n\n return { reason, status: 'cancelled' };\n },\n );\n}\n\n/** Wraps a native Animation with Necromancer's lifecycle contract. */\nexport function createAnimationHandle(animation: Animation, signal?: AbortSignal, reduced = false): AnimationHandle {\n let disposed = false;\n let disposeReason: unknown;\n let hasDisposeReason = false;\n let removeAbortListener: (() => void) | undefined;\n\n const result: Promise<AnimationResult> = createResultPromise(\n animation,\n () => {\n removeAbortListener?.();\n removeAbortListener = undefined;\n },\n reduced,\n ).then((outcome): AnimationResult => {\n if (disposed && hasDisposeReason && outcome.status === 'cancelled') {\n return { reason: disposeReason, status: 'cancelled' };\n }\n\n return outcome;\n });\n\n const dispose = (reason?: unknown): void => {\n if (disposed) return;\n\n disposed = true;\n disposeReason = reason;\n hasDisposeReason = reason !== undefined;\n removeAbortListener?.();\n removeAbortListener = undefined;\n animation.cancel();\n };\n\n if (signal) {\n removeAbortListener = attachAbortSignalListener(signal, dispose);\n }\n\n return {\n animation,\n dispose,\n get disposed() {\n return disposed;\n },\n result,\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n}\n\n/** Combines child animation handles under one disposal owner. */\nexport function createAnimationGroup(handles: readonly AnimationHandle[], signal?: AbortSignal): AnimationGroup {\n let disposed = false;\n let removeAbortListener: (() => void) | undefined;\n\n const results: Promise<readonly AnimationResult[]> = Promise.all(handles.map((handle) => handle.result)).then(\n (childResults): readonly AnimationResult[] => {\n removeAbortListener?.();\n removeAbortListener = undefined;\n\n return childResults;\n },\n );\n\n const dispose = (reason?: unknown): void => {\n if (disposed) return;\n\n disposed = true;\n removeAbortListener?.();\n removeAbortListener = undefined;\n for (const handle of handles) handle.dispose(reason);\n };\n\n if (signal) {\n removeAbortListener = attachAbortSignalListener(signal, dispose);\n }\n\n return {\n dispose,\n get disposed() {\n return disposed;\n },\n handles,\n results,\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n}\n","/** Base class for errors raised by `@vielzeug/necromancer`. */\nexport class NecromancerError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a Necromancer-owned option is invalid. */\nexport class NecromancerConfigError extends NecromancerError {}\n\n/** Thrown when the runtime does not implement the Web Animations API. */\nexport class NecromancerUnsupportedError extends NecromancerError {}\n","import { NecromancerConfigError } from './errors';\nimport type { AnimateOptions, MotionMode } from './types';\n\n/** Reports whether the requested motion preference reduces visible movement. */\nexport function shouldReduceMotion(mode: MotionMode): boolean {\n if (mode === 'full') return false;\n\n if (mode === 'reduced') return true;\n\n return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n}\n\n/** Converts ownership options to native timing, collapsing reduced motion to an instant transition. */\nexport function resolveAnimationOptions(options: AnimateOptions = {}, reduced = false): KeyframeAnimationOptions {\n const { motion: _motion, signal: _signal, ...nativeOptions } = options;\n\n return reduced ? { ...nativeOptions, delay: 0, duration: 0, endDelay: 0, iterations: 1 } : nativeOptions;\n}\n\n/** Adds an element's stagger offset without changing native nonnumeric delays when no offset is needed. */\nexport function withStaggeredDelay(options: AnimateOptions, offset: number): AnimateOptions {\n if (offset === 0) return options;\n\n const delay = options.delay ?? 0;\n\n if (typeof delay !== 'number') {\n throw new NecromancerConfigError(`A non-zero stagger requires a numeric delay; received ${typeof delay}.`);\n }\n\n return { ...options, delay: delay + offset };\n}\n","import { createAnimationHandle } from './_handle';\nimport { NecromancerUnsupportedError } from './errors';\nimport { resolveAnimationOptions, shouldReduceMotion } from './motion';\nimport type { AnimateOptions, AnimationHandle, Keyframes } from './types';\n\n/**\n * Starts a lifecycle-owned native Web Animation for one element.\n *\n * The returned handle cancels its native animation when disposed. By default, the\n * operating system's reduced-motion preference suppresses movement.\n */\nexport function animate(element: Element, keyframes: Keyframes, options: AnimateOptions = {}): AnimationHandle {\n if (options.signal?.aborted) throw options.signal.reason;\n\n if (typeof element.animate !== 'function') {\n throw new NecromancerUnsupportedError('The Web Animations API is not available in this environment.');\n }\n\n const reduced = shouldReduceMotion(options.motion ?? 'system');\n const nativeAnimation = element.animate(\n keyframes as Keyframe[] | PropertyIndexedKeyframes,\n resolveAnimationOptions(options, reduced),\n );\n return createAnimationHandle(nativeAnimation, options.signal, reduced);\n}\n","/** Deduplicates elements while preserving first-seen order. Shared by `animateEach()` and `captureLayout()`. */\nexport function uniqueElements<ElementType extends Element>(elements: Iterable<ElementType>): ElementType[] {\n return [...new Set(elements)];\n}\n","import { uniqueElements } from './_elements';\nimport { createAnimationGroup } from './_handle';\nimport { animate } from './animate';\nimport { NecromancerConfigError } from './errors';\nimport { withStaggeredDelay } from './motion';\nimport type { AnimateEachOptions, AnimationGroup, AnimationHandle, KeyframeFactory, Keyframes } from './types';\n\nfunction validateStagger(stagger: number): void {\n if (!Number.isFinite(stagger) || stagger < 0) {\n throw new NecromancerConfigError('stagger must be a finite, non-negative number.');\n }\n}\n\n/**\n * Starts lifecycle-owned animations for unique elements in iteration order.\n *\n * Each subsequent element starts after `stagger` milliseconds. A keyframe factory\n * receives the stable unique-element index and total before any animation starts.\n */\nexport function animateEach<ElementType extends Element>(\n elements: Iterable<ElementType>,\n keyframes: Keyframes | KeyframeFactory<ElementType>,\n options: AnimateEachOptions = {},\n): AnimationGroup {\n const { signal, stagger = 0, ...animationOptions } = options;\n\n validateStagger(stagger);\n\n if (signal?.aborted) throw signal.reason;\n\n const unique = uniqueElements(elements);\n const frames = unique.map((element, index) =>\n typeof keyframes === 'function' ? keyframes(element, index, unique.length) : keyframes,\n );\n\n if (signal?.aborted) throw signal.reason;\n\n const handles: AnimationHandle[] = [];\n\n try {\n for (const [index, element] of unique.entries()) {\n // `frames` was built above from `unique`, one entry per element, so this index is always in range.\n const currentFrames = frames[index]!;\n\n handles.push(animate(element, currentFrames, withStaggeredDelay(animationOptions, index * stagger)));\n }\n } catch (error) {\n for (const handle of handles) handle.dispose(error);\n\n throw error;\n }\n\n return createAnimationGroup(handles, signal);\n}\n","import { uniqueElements } from './_elements';\nimport { animateEach } from './animate-each';\nimport { NecromancerConfigError } from './errors';\nimport type { LayoutAnimationOptions, LayoutCaptureOptions, LayoutTransition } from './types';\n\ntype LayoutRect = Readonly<Pick<DOMRectReadOnly, 'height' | 'width' | 'x' | 'y'>>;\ntype LayoutEntry<ElementType extends Element> = Readonly<{ element: ElementType; rect: LayoutRect }>;\ntype LayoutChange<ElementType extends Element> = Readonly<{\n element: ElementType;\n scaleX: number;\n scaleY: number;\n x: number;\n y: number;\n}>;\n\n// Rounds before templating into a keyframe string purely for DevTools readability: a `getBoundingClientRect()`\n// subtraction routinely produces values like `12.340000000000002`, which is noise once rendered as CSS.\n// Pixels only need whole-number precision; scale factors (close to 1) need finer precision to stay visually exact.\nfunction round(value: number, precision: number): number {\n const factor = 10 ** precision;\n\n return Math.round(value * factor) / factor;\n}\n\n// `getBoundingClientRect()`'s width/height is the rotated, axis-aligned bounding box: using it\n// for size would distort the scale ratio under any rotation. `offsetWidth`/`offsetHeight` report\n// the box's own untransformed layout size instead. Elements without an offset box (e.g. SVG)\n// fall back to the bounding rect, accepting that same distortion as the only option available.\nfunction measureSize(element: Element): Readonly<{ height: number; width: number }> {\n if ('offsetWidth' in element && 'offsetHeight' in element) {\n return { height: (element as HTMLElement).offsetHeight, width: (element as HTMLElement).offsetWidth };\n }\n\n const rect = element.getBoundingClientRect();\n\n return { height: rect.height, width: rect.width };\n}\n\nfunction measureLayout(element: Element): LayoutRect {\n const rect = element.getBoundingClientRect();\n const size = measureSize(element);\n\n return { height: size.height, width: size.width, x: rect.x, y: rect.y };\n}\n\n// `next` is 0 exactly when the element has collapsed (e.g. `display: none` mid-transition);\n// there's no meaningful ratio to compute then, so treat it as unscaled rather than producing Infinity/NaN.\nfunction computeScale(captured: number, next: number): number {\n return next === 0 ? 1 : captured / next;\n}\n\nfunction readKey<ElementType extends Element>(\n element: ElementType,\n getKey: (element: ElementType) => string,\n phase: string,\n): string {\n const key = getKey(element);\n\n if (typeof key !== 'string' || key.length === 0) {\n throw new NecromancerConfigError(`getKey must return a non-empty string for every ${phase} element.`);\n }\n\n return key;\n}\n\nfunction createKeyMap<ElementType extends Element>(\n entries: readonly LayoutEntry<ElementType>[],\n getKey: (element: ElementType) => string,\n phase: string,\n) {\n const keys = new Map<string, LayoutEntry<ElementType>>();\n\n for (const entry of entries) {\n const key = readKey(entry.element, getKey, phase);\n\n if (keys.has(key)) {\n throw new NecromancerConfigError(`getKey returned duplicate keys for the ${phase} elements.`);\n }\n\n keys.set(key, entry);\n }\n\n return keys;\n}\n\nfunction changedElement<ElementType extends Element>(\n element: ElementType,\n rect: LayoutRect,\n): LayoutChange<ElementType> | undefined {\n if (!element.isConnected) return undefined;\n\n const next = measureLayout(element);\n const x = rect.x - next.x;\n const y = rect.y - next.y;\n const scaleX = computeScale(rect.width, next.width);\n const scaleY = computeScale(rect.height, next.height);\n\n return x === 0 && y === 0 && scaleX === 1 && scaleY === 1 ? undefined : { element, scaleX, scaleY, x, y };\n}\n\nfunction matchByIdentity<ElementType extends Element>(\n entries: readonly LayoutEntry<ElementType>[],\n elements: readonly ElementType[],\n): LayoutChange<ElementType>[] {\n const captured = new Map(entries.map((entry) => [entry.element, entry]));\n\n return elements.flatMap((element) => {\n const entry = captured.get(element);\n\n return entry\n ? [changedElement(element, entry.rect)].filter((change): change is LayoutChange<ElementType> => Boolean(change))\n : [];\n });\n}\n\nfunction matchByKey<ElementType extends Element>(\n captured: ReadonlyMap<string, LayoutEntry<ElementType>>,\n elements: readonly ElementType[],\n getKey: (element: ElementType) => string,\n): LayoutChange<ElementType>[] {\n const committed = new Set<string>();\n\n return elements.flatMap((element) => {\n const key = readKey(element, getKey, 'committed');\n const entry = captured.get(key);\n\n if (committed.has(key)) {\n throw new NecromancerConfigError('getKey returned duplicate keys for the committed elements.');\n }\n\n committed.add(key);\n\n return entry\n ? [changedElement(element, entry.rect)].filter((change): change is LayoutChange<ElementType> => Boolean(change))\n : [];\n });\n}\n\n/**\n * Captures the current position and size of unique elements for a later FLIP animation.\n *\n * Each element's `x`/`y` position and `width`/`height` are captured. Rotation and other\n * transforms are not captured or compensated. Capture before mutating the DOM, then call\n * the returned transition's `animate()` method after the browser has applied the resulting\n * layout: position changes animate via translate, and size changes via scale, both\n * additively composed on top of any authored transform.\n */\nexport function captureLayout<ElementType extends Element>(\n elements: Iterable<ElementType>,\n options: LayoutCaptureOptions<ElementType> = {},\n): LayoutTransition<ElementType> {\n const entries: LayoutEntry<ElementType>[] = uniqueElements(elements).map((element) => ({\n element,\n rect: measureLayout(element),\n }));\n const getKey = options.getKey;\n const captured = getKey ? createKeyMap(entries, getKey, 'captured') : undefined;\n\n let consumed = false;\n\n return {\n animate(options: LayoutAnimationOptions<ElementType> = {}) {\n if (consumed) throw new NecromancerConfigError('This layout transition has already been animated.');\n\n const { elements: committedElements, ...animationOptions } = options;\n const elements = uniqueElements(committedElements ?? entries.map(({ element }) => element));\n const changed = getKey && captured ? matchByKey(captured, elements, getKey) : matchByIdentity(entries, elements);\n\n consumed = true;\n\n return animateEach(\n changed.map(({ element }) => element),\n (_, index) => {\n // `changed` was mapped directly into the elements array above, so this index is always in range.\n const change = changed[index]!;\n const translate = `${round(change.x, 2)}px ${round(change.y, 2)}px`;\n const scale = `${round(change.scaleX, 4)} ${round(change.scaleY, 4)}`;\n\n return [\n { composite: 'add', scale, translate },\n { composite: 'add', scale: '1 1', translate: '0px 0px' },\n ];\n },\n animationOptions,\n );\n },\n };\n}\n"],"mappings":"AAMA,SAAS,0BAA0B,EAAqB,EAAiD,CACvG,IAAM,UAAc,EAAQ,EAAO,MAAM,EAUzC,OARA,EAAO,iBAAiB,QAAS,MAAO,CAAE,KAAM,EAAK,CAAC,EAElD,EAAO,SACT,EAAO,oBAAoB,QAAS,KAAK,EACzC,EAAQ,EAAO,MAAM,MACR,IAAA,QAGF,EAAO,oBAAoB,QAAS,KAAK,CACxD,CAEA,SAAS,oBAAoB,EAAsB,EAAuB,EAA4C,CACpH,OAAO,EAAU,SAAS,UAEtB,EAAU,EAEH,CAAE,OAAQ,EAAU,UAAY,UAAW,GAEnD,IACC,EAAU,EAEH,CAAE,SAAQ,OAAQ,WAAY,EAEzC,CACF,CAGA,SAAgB,sBAAsB,EAAsB,EAAsB,EAAU,GAAwB,CAClH,IAAI,EAAW,GACX,EACA,EAAmB,GACnB,EAEE,EAAmC,oBACvC,MACM,CACJ,IAAsB,EACtB,EAAsB,IAAA,EACxB,EACA,CACF,CAAC,CAAC,KAAM,GACF,GAAY,GAAoB,EAAQ,SAAW,YAC9C,CAAE,OAAQ,EAAe,OAAQ,WAAY,EAG/C,CACR,EAEK,QAAW,GAA2B,CACtC,IAEJ,EAAW,GACX,EAAgB,EAChB,EAAmB,IAAW,IAAA,GAC9B,IAAsB,EACtB,EAAs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A,GAElE,EAAW,GAEf,MAAO,CACL,QAAQ,EAA+C,CAAC,EAAG,CACzD,GAAI,EAAU,MAAM,IAAI,uBAAuB,mDAAmD,EAElG,GAAM,CAAE,SAAU,EAAmB,GAAG,GAAqB,EACvD,EAAW,eAAe,GAAqB,EAAQ,KAAK,CAAE,aAAc,CAAO,CAAC,EACpF,EAAU,GAAU,EAAW,WAAW,EAAU,EAAU,CAAM,EAAI,gBAAgB,EAAS,CAAQ,EAI/G,MAFA,GAAW,GAEJ,YACL,EAAQ,KAAK,CAAE,aAAc,CAAO,GACnC,EAAG,IAAU,CAEZ,IAAM,EAAS,EAAQ,GACjB,EAAY,GAAG,MAAM,EAAO,EAAG,CAAC,EAAE,KAAK,MAAM,EAAO,EAAG,CAAC,EAAE,IAGhE,MAAO,CACL,CAAE,UAAW,MAAO,MAAA,GAHL,MAAM,EAAO,OAAQ,CAAC,EAAE,GAAG,MAAM,EAAO,OAAQ,CAAC,IAGrC,WAAU,EACrC,CAAE,UAAW,MAAO,MAAO,MAAO,UAAW,SAAU,CACzD,CACF,EACA,CACF,CACF,CACF,CACF"}
|
package/dist/testing/index.d.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* jsdom (and most non-browser DOM environments) do not implement `Element.animate()`,
|
|
5
5
|
* so any test that exercises `animate()`, `animateEach()`, or `captureLayout()` needs a
|
|
6
|
-
* substitute. This module has no test-runner import
|
|
6
|
+
* substitute. This module has no test-runner import: it works the same under Vitest,
|
|
7
7
|
* Jest, or any other runner; use your runner's own spy/mock APIs on top if needed.
|
|
8
8
|
*/
|
|
9
9
|
export type AnimationCall = {
|
package/dist/testing.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.cjs","names":[],"sources":["../src/testing/index.ts"],"sourcesContent":["/**\n * Testing utilities for code that calls Necromancer's animation functions.\n *\n * jsdom (and most non-browser DOM environments) do not implement `Element.animate()`,\n * so any test that exercises `animate()`, `animateEach()`, or `captureLayout()` needs a\n * substitute. This module has no test-runner import
|
|
1
|
+
{"version":3,"file":"testing.cjs","names":[],"sources":["../src/testing/index.ts"],"sourcesContent":["/**\n * Testing utilities for code that calls Necromancer's animation functions.\n *\n * jsdom (and most non-browser DOM environments) do not implement `Element.animate()`,\n * so any test that exercises `animate()`, `animateEach()`, or `captureLayout()` needs a\n * substitute. This module has no test-runner import: it works the same under Vitest,\n * Jest, or any other runner; use your runner's own spy/mock APIs on top if needed.\n */\n\nexport type AnimationCall = {\n readonly animation: FakeAnimation;\n readonly keyframes: Keyframe[] | PropertyIndexedKeyframes;\n readonly options?: KeyframeAnimationOptions;\n};\n\n/** A minimal `Animation` stand-in. Call `finish()`/`cancel()` to settle it like the real API would. */\nexport class FakeAnimation {\n #reject!: (reason?: unknown) => void;\n #resolve!: () => void;\n\n /** Number of times `cancel()` has been called. */\n cancelCallCount = 0;\n /** Number of times `finish()` has been called. */\n finishCallCount = 0;\n /** Mirrors the native `Animation.finished` promise. */\n finished: Promise<void>;\n\n constructor() {\n this.finished = new Promise<void>((resolve, reject) => {\n this.#resolve = resolve;\n this.#reject = reject;\n });\n }\n\n /** Rejects `finished` with an `AbortError`, like a real cancelled `Animation`. */\n cancel = (): void => {\n this.cancelCallCount += 1;\n this.#reject(new DOMException('The animation was canceled.', 'AbortError'));\n };\n\n /** Resolves `finished`, like a real completed `Animation`. */\n finish = (): void => {\n this.finishCallCount += 1;\n this.#resolve();\n };\n}\n\n/**\n * Replaces `Element.prototype.animate` with a deterministic lifecycle fake for a test.\n * Dispose the installation or call `restore()` to restore the original implementation.\n *\n * @example\n * using animations = installFakeAnimations();\n * const handle = animate(element, [{ opacity: 0 }, { opacity: 1 }]);\n * animations.calls[0]?.animation.finish();\n * await handle.result; // { status: 'finished' }\n */\nexport function installFakeAnimations(): {\n readonly calls: readonly AnimationCall[];\n restore(): void;\n [Symbol.dispose](): void;\n} {\n const calls: AnimationCall[] = [];\n const descriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'animate');\n let restored = false;\n\n Object.defineProperty(Element.prototype, 'animate', {\n configurable: true,\n value: (keyframes: Keyframe[] | PropertyIndexedKeyframes, options?: KeyframeAnimationOptions) => {\n const animation = new FakeAnimation();\n\n calls.push({ animation, keyframes, options });\n\n // Necromancer only consumes the documented Animation surface represented by FakeAnimation.\n return animation as unknown as Animation;\n },\n writable: true,\n });\n\n const restore = (): void => {\n if (restored) return;\n\n restored = true;\n if (descriptor) Object.defineProperty(Element.prototype, 'animate', descriptor);\n else Reflect.deleteProperty(Element.prototype, 'animate');\n };\n\n return {\n calls,\n restore,\n [Symbol.dispose]: restore,\n };\n}\n\n/** Builds a `DOMRect` for mocking `Element.getBoundingClientRect()` in `captureLayout()` tests. */\nexport function createRect(x: number, y: number, width = 20, height = 20): DOMRect {\n return new DOMRect(x, y, width, height);\n}\n"],"mappings":"mEAgBA,IAAa,cAAb,KAA2B,CACzB,GACA,GAGA,gBAAkB,EAElB,gBAAkB,EAElB,SAEA,aAAc,CACZ,KAAK,SAAW,IAAI,SAAe,EAAS,IAAW,CACrD,KAAK,GAAW,EAChB,KAAK,GAAU,CACjB,CAAC,CACH,CAGA,WAAqB,CACnB,KAAK,iBAAmB,EACxB,KAAK,GAAQ,IAAI,aAAa,8BAA+B,YAAY,CAAC,CAC5E,EAGA,WAAqB,CACnB,KAAK,iBAAmB,EACxB,KAAK,GAAS,CAChB,CACF,EAYA,SAAgB,uBAId,CACA,IAAM,EAAyB,CAAC,EAC1B,EAAa,OAAO,yBAAyB,QAAQ,UAAW,SAAS,EAC3E,EAAW,GAEf,OAAO,eAAe,QAAQ,UAAW,UAAW,CAClD,aAAc,GACd,OAAQ,EAAkD,IAAuC,CAC/F,IAAM,EAAY,IAAI,cAKtB,OAHA,EAAM,KAAK,CAAE,YAAW,YAAW,SAAQ,CAAC,EAGrC,CACT,EACA,SAAU,EACZ,CAAC,EAED,IAAM,YAAsB,CACtB,IAEJ,EAAW,GACP,EAAY,OAAO,eAAe,QAAQ,UAAW,UAAW,CAAU,EACzE,QAAQ,eAAe,QAAQ,UAAW,SAAS,EAC1D,EAEA,MAAO,CACL,QACA,SACC,OAAO,SAAU,OACpB,CACF,CAGA,SAAgB,WAAW,EAAW,EAAW,EAAQ,GAAI,EAAS,GAAa,CACjF,OAAO,IAAI,QAAQ,EAAG,EAAG,EAAO,CAAM,CACxC"}
|
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","names":[],"sources":["../src/testing/index.ts"],"sourcesContent":["/**\n * Testing utilities for code that calls Necromancer's animation functions.\n *\n * jsdom (and most non-browser DOM environments) do not implement `Element.animate()`,\n * so any test that exercises `animate()`, `animateEach()`, or `captureLayout()` needs a\n * substitute. This module has no test-runner import
|
|
1
|
+
{"version":3,"file":"testing.js","names":[],"sources":["../src/testing/index.ts"],"sourcesContent":["/**\n * Testing utilities for code that calls Necromancer's animation functions.\n *\n * jsdom (and most non-browser DOM environments) do not implement `Element.animate()`,\n * so any test that exercises `animate()`, `animateEach()`, or `captureLayout()` needs a\n * substitute. This module has no test-runner import: it works the same under Vitest,\n * Jest, or any other runner; use your runner's own spy/mock APIs on top if needed.\n */\n\nexport type AnimationCall = {\n readonly animation: FakeAnimation;\n readonly keyframes: Keyframe[] | PropertyIndexedKeyframes;\n readonly options?: KeyframeAnimationOptions;\n};\n\n/** A minimal `Animation` stand-in. Call `finish()`/`cancel()` to settle it like the real API would. */\nexport class FakeAnimation {\n #reject!: (reason?: unknown) => void;\n #resolve!: () => void;\n\n /** Number of times `cancel()` has been called. */\n cancelCallCount = 0;\n /** Number of times `finish()` has been called. */\n finishCallCount = 0;\n /** Mirrors the native `Animation.finished` promise. */\n finished: Promise<void>;\n\n constructor() {\n this.finished = new Promise<void>((resolve, reject) => {\n this.#resolve = resolve;\n this.#reject = reject;\n });\n }\n\n /** Rejects `finished` with an `AbortError`, like a real cancelled `Animation`. */\n cancel = (): void => {\n this.cancelCallCount += 1;\n this.#reject(new DOMException('The animation was canceled.', 'AbortError'));\n };\n\n /** Resolves `finished`, like a real completed `Animation`. */\n finish = (): void => {\n this.finishCallCount += 1;\n this.#resolve();\n };\n}\n\n/**\n * Replaces `Element.prototype.animate` with a deterministic lifecycle fake for a test.\n * Dispose the installation or call `restore()` to restore the original implementation.\n *\n * @example\n * using animations = installFakeAnimations();\n * const handle = animate(element, [{ opacity: 0 }, { opacity: 1 }]);\n * animations.calls[0]?.animation.finish();\n * await handle.result; // { status: 'finished' }\n */\nexport function installFakeAnimations(): {\n readonly calls: readonly AnimationCall[];\n restore(): void;\n [Symbol.dispose](): void;\n} {\n const calls: AnimationCall[] = [];\n const descriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'animate');\n let restored = false;\n\n Object.defineProperty(Element.prototype, 'animate', {\n configurable: true,\n value: (keyframes: Keyframe[] | PropertyIndexedKeyframes, options?: KeyframeAnimationOptions) => {\n const animation = new FakeAnimation();\n\n calls.push({ animation, keyframes, options });\n\n // Necromancer only consumes the documented Animation surface represented by FakeAnimation.\n return animation as unknown as Animation;\n },\n writable: true,\n });\n\n const restore = (): void => {\n if (restored) return;\n\n restored = true;\n if (descriptor) Object.defineProperty(Element.prototype, 'animate', descriptor);\n else Reflect.deleteProperty(Element.prototype, 'animate');\n };\n\n return {\n calls,\n restore,\n [Symbol.dispose]: restore,\n };\n}\n\n/** Builds a `DOMRect` for mocking `Element.getBoundingClientRect()` in `captureLayout()` tests. */\nexport function createRect(x: number, y: number, width = 20, height = 20): DOMRect {\n return new DOMRect(x, y, width, height);\n}\n"],"mappings":"AAgBA,IAAa,cAAb,KAA2B,CACzB,GACA,GAGA,gBAAkB,EAElB,gBAAkB,EAElB,SAEA,aAAc,CACZ,KAAK,SAAW,IAAI,SAAe,EAAS,IAAW,CACrD,KAAK,GAAW,EAChB,KAAK,GAAU,CACjB,CAAC,CACH,CAGA,WAAqB,CACnB,KAAK,iBAAmB,EACxB,KAAK,GAAQ,IAAI,aAAa,8BAA+B,YAAY,CAAC,CAC5E,EAGA,WAAqB,CACnB,KAAK,iBAAmB,EACxB,KAAK,GAAS,CAChB,CACF,EAYA,SAAgB,uBAId,CACA,IAAM,EAAyB,CAAC,EAC1B,EAAa,OAAO,yBAAyB,QAAQ,UAAW,SAAS,EAC3E,EAAW,GAEf,OAAO,eAAe,QAAQ,UAAW,UAAW,CAClD,aAAc,GACd,OAAQ,EAAkD,IAAuC,CAC/F,IAAM,EAAY,IAAI,cAKtB,OAHA,EAAM,KAAK,CAAE,YAAW,YAAW,SAAQ,CAAC,EAGrC,CACT,EACA,SAAU,EACZ,CAAC,EAED,IAAM,YAAsB,CACtB,IAEJ,EAAW,GACP,EAAY,OAAO,eAAe,QAAQ,UAAW,UAAW,CAAU,EACzE,QAAQ,eAAe,QAAQ,UAAW,SAAS,EAC1D,EAEA,MAAO,CACL,QACA,SACC,OAAO,SAAU,OACpB,CACF,CAGA,SAAgB,WAAW,EAAW,EAAW,EAAQ,GAAI,EAAS,GAAa,CACjF,OAAO,IAAI,QAAQ,EAAG,EAAG,EAAO,CAAM,CACxC"}
|
package/dist/types.d.ts
CHANGED
|
@@ -21,7 +21,7 @@ export type Keyframes = readonly Keyframe[] | PropertyIndexedKeyframes;
|
|
|
21
21
|
* string `delay`/`duration`, etc.) reaches `element.animate()` unchanged unless reduced motion
|
|
22
22
|
* normalizes timing. Callers already
|
|
23
23
|
* fluent in the Web Animations API bring that knowledge here directly, instead of learning
|
|
24
|
-
* a second, smaller timing vocabulary
|
|
24
|
+
* a second, smaller timing vocabulary: the option chain below only ever *adds* ownership
|
|
25
25
|
* fields on top, never narrows what's already native.
|
|
26
26
|
*
|
|
27
27
|
* Option chain: `AnimateOptions` -> `AnimateEachOptions` (+`stagger`) -> `LayoutAnimationOptions`
|
package/package.json
CHANGED