motion-dom 14.4.0 → 14.6.0

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.
Files changed (74) hide show
  1. package/dist/cjs/index.js +413 -79
  2. package/dist/cjs/index.js.map +1 -1
  3. package/dist/es/animation/NativeAnimation.mjs +10 -4
  4. package/dist/es/animation/NativeAnimation.mjs.map +1 -1
  5. package/dist/es/animation/animate/element.mjs +10 -1
  6. package/dist/es/animation/animate/element.mjs.map +1 -1
  7. package/dist/es/animation/generators/spring.mjs +11 -9
  8. package/dist/es/animation/generators/spring.mjs.map +1 -1
  9. package/dist/es/animation/keyframes/utils/unit-conversion.mjs +8 -7
  10. package/dist/es/animation/keyframes/utils/unit-conversion.mjs.map +1 -1
  11. package/dist/es/animation/optimized-appear/data-id.mjs +1 -3
  12. package/dist/es/animation/optimized-appear/data-id.mjs.map +1 -1
  13. package/dist/es/animation/waapi/supports/waapi.mjs +8 -2
  14. package/dist/es/animation/waapi/supports/waapi.mjs.map +1 -1
  15. package/dist/es/frameloop/process-frame.mjs +42 -0
  16. package/dist/es/frameloop/process-frame.mjs.map +1 -0
  17. package/dist/es/frameloop/render-step.mjs +15 -1
  18. package/dist/es/frameloop/render-step.mjs.map +1 -1
  19. package/dist/es/gestures/drag/VisualElementDragControls.mjs +16 -6
  20. package/dist/es/gestures/drag/VisualElementDragControls.mjs.map +1 -1
  21. package/dist/es/gestures/drag/index.mjs +16 -1
  22. package/dist/es/gestures/drag/index.mjs.map +1 -1
  23. package/dist/es/gestures/hover.mjs +2 -0
  24. package/dist/es/gestures/hover.mjs.map +1 -1
  25. package/dist/es/gestures/pan/PanSession.mjs +6 -0
  26. package/dist/es/gestures/pan/PanSession.mjs.map +1 -1
  27. package/dist/es/gestures/press/index.mjs +3 -1
  28. package/dist/es/gestures/press/index.mjs.map +1 -1
  29. package/dist/es/gestures/press/utils/keyboard.mjs +22 -12
  30. package/dist/es/gestures/press/utils/keyboard.mjs.map +1 -1
  31. package/dist/es/gestures/utils/setup.mjs +2 -1
  32. package/dist/es/gestures/utils/setup.mjs.map +1 -1
  33. package/dist/es/index.mjs +7 -2
  34. package/dist/es/index.mjs.map +1 -1
  35. package/dist/es/layout/LayoutAnimationBuilder.mjs +2 -1
  36. package/dist/es/layout/LayoutAnimationBuilder.mjs.map +1 -1
  37. package/dist/es/layout/animate-layout.mjs +7 -1
  38. package/dist/es/layout/animate-layout.mjs.map +1 -1
  39. package/dist/es/projection/node/DocumentProjectionNode.mjs +8 -3
  40. package/dist/es/projection/node/DocumentProjectionNode.mjs.map +1 -1
  41. package/dist/es/projection/node/HTMLProjectionNode.mjs +4 -5
  42. package/dist/es/projection/node/HTMLProjectionNode.mjs.map +1 -1
  43. package/dist/es/projection/node/create-projection-node.mjs +21 -12
  44. package/dist/es/projection/node/create-projection-node.mjs.map +1 -1
  45. package/dist/es/projection/node/root.mjs +6 -0
  46. package/dist/es/projection/node/root.mjs.map +1 -0
  47. package/dist/es/projection/styles/default-scale-correctors.mjs +3 -4
  48. package/dist/es/projection/styles/default-scale-correctors.mjs.map +1 -1
  49. package/dist/es/render/utils/animation-state.mjs +1 -2
  50. package/dist/es/render/utils/animation-state.mjs.map +1 -1
  51. package/dist/es/render/utils/variant-props.mjs +1 -1
  52. package/dist/es/render/utils/variant-props.mjs.map +1 -1
  53. package/dist/es/resize/index.mjs +2 -1
  54. package/dist/es/resize/index.mjs.map +1 -1
  55. package/dist/es/scope/active.mjs +39 -0
  56. package/dist/es/scope/active.mjs.map +1 -0
  57. package/dist/es/scope/index.mjs +122 -0
  58. package/dist/es/scope/index.mjs.map +1 -0
  59. package/dist/es/scope/media.mjs +42 -0
  60. package/dist/es/scope/media.mjs.map +1 -0
  61. package/dist/es/utils/delay.mjs +3 -1
  62. package/dist/es/utils/delay.mjs.map +1 -1
  63. package/dist/es/utils/resolve-elements.mjs +5 -4
  64. package/dist/es/utils/resolve-elements.mjs.map +1 -1
  65. package/dist/es/view/index.mjs +4 -1
  66. package/dist/es/view/index.mjs.map +1 -1
  67. package/dist/index.d.ts +178 -15
  68. package/dist/motion-dom.dev.js +413 -79
  69. package/dist/motion-dom.js +1 -1
  70. package/dist/size-rollup-motion-value.js +1 -1
  71. package/dist/size-rollup-motion-value.js.map +1 -1
  72. package/dist/size-rollup-style-effect.js +1 -1
  73. package/dist/size-rollup-style-effect.js.map +1 -1
  74. package/package.json +4 -4
@@ -0,0 +1,6 @@
1
+ const rootProjectionNode = {
2
+ current: undefined,
3
+ };
4
+
5
+ export { rootProjectionNode };
6
+ //# sourceMappingURL=root.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"root.mjs","sources":["../../../../src/projection/node/root.ts"],"sourcesContent":["import type { IProjectionNode } from \"./types\"\n\nexport const rootProjectionNode: { current: IProjectionNode | undefined } = {\n current: undefined,\n}\n"],"names":[],"mappings":"AAEO,MAAM,kBAAkB,GAA6C;AACxE,IAAA,OAAO,EAAE,SAAS;;;;;"}
@@ -3,10 +3,9 @@ import { correctBorderRadius } from './scale-border-radius.mjs';
3
3
  import { correctBoxShadow } from './scale-box-shadow.mjs';
4
4
 
5
5
  const defaultScaleCorrectors = {
6
- borderRadius: {
7
- ...correctBorderRadius,
8
- applyTo: [...cornerRadiusProps],
9
- },
6
+ borderRadius: /* @__PURE__ */ Object.assign({}, correctBorderRadius, {
7
+ applyTo: /* @__PURE__ */ cornerRadiusProps.slice(),
8
+ }),
10
9
  borderTopLeftRadius: correctBorderRadius,
11
10
  borderTopRightRadius: correctBorderRadius,
12
11
  borderBottomLeftRadius: correctBorderRadius,
@@ -1 +1 @@
1
- {"version":3,"file":"default-scale-correctors.mjs","sources":["../../../../src/projection/styles/default-scale-correctors.ts"],"sourcesContent":["import { cornerRadiusProps } from \"../../utils/border-radius\"\nimport { correctBorderRadius } from \"./scale-border-radius\"\nimport { correctBoxShadow } from \"./scale-box-shadow\"\nimport type { ScaleCorrectorMap } from \"./types\"\n\nexport const defaultScaleCorrectors: ScaleCorrectorMap = {\n borderRadius: {\n ...correctBorderRadius,\n applyTo: [...cornerRadiusProps],\n },\n borderTopLeftRadius: correctBorderRadius,\n borderTopRightRadius: correctBorderRadius,\n borderBottomLeftRadius: correctBorderRadius,\n borderBottomRightRadius: correctBorderRadius,\n boxShadow: correctBoxShadow,\n}\n"],"names":[],"mappings":";;;;AAKO,MAAM,sBAAsB,GAAsB;AACrD,IAAA,YAAY,EAAE;AACV,QAAA,GAAG,mBAAmB;AACtB,QAAA,OAAO,EAAE,CAAC,GAAG,iBAAiB,CAAC;AAClC,KAAA;AACD,IAAA,mBAAmB,EAAE,mBAAmB;AACxC,IAAA,oBAAoB,EAAE,mBAAmB;AACzC,IAAA,sBAAsB,EAAE,mBAAmB;AAC3C,IAAA,uBAAuB,EAAE,mBAAmB;AAC5C,IAAA,SAAS,EAAE,gBAAgB;;;;;"}
1
+ {"version":3,"file":"default-scale-correctors.mjs","sources":["../../../../src/projection/styles/default-scale-correctors.ts"],"sourcesContent":["import { cornerRadiusProps } from \"../../utils/border-radius\"\nimport { correctBorderRadius } from \"./scale-border-radius\"\nimport { correctBoxShadow } from \"./scale-box-shadow\"\nimport type { ScaleCorrectorMap } from \"./types\"\n\nexport const defaultScaleCorrectors: ScaleCorrectorMap = {\n borderRadius: /* @__PURE__ */ Object.assign({}, correctBorderRadius, {\n applyTo: /* @__PURE__ */ cornerRadiusProps.slice(),\n }),\n borderTopLeftRadius: correctBorderRadius,\n borderTopRightRadius: correctBorderRadius,\n borderBottomLeftRadius: correctBorderRadius,\n borderBottomRightRadius: correctBorderRadius,\n boxShadow: correctBoxShadow,\n}\n"],"names":[],"mappings":";;;;AAKO,MAAM,sBAAsB,GAAsB;IACrD,YAAY,kBAAkB,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,mBAAmB,EAAE;AACjE,QAAA,OAAO,kBAAkB,iBAAiB,CAAC,KAAK,EAAE;KACrD,CAAC;AACF,IAAA,mBAAmB,EAAE,mBAAmB;AACxC,IAAA,oBAAoB,EAAE,mBAAmB;AACzC,IAAA,sBAAsB,EAAE,mBAAmB;AAC3C,IAAA,uBAAuB,EAAE,mBAAmB;AAC5C,IAAA,SAAS,EAAE,gBAAgB;;;;;"}
@@ -122,8 +122,7 @@ function createAnimationState(visualElement) {
122
122
  const valueHasChanged = Array.isArray(next) && Array.isArray(prev)
123
123
  ? !shallowCompare(next, prev) || variantDidChange
124
124
  : next !== prev;
125
- if (valueHasChanged &&
126
- (next === undefined || next === null)) {
125
+ if (valueHasChanged && (next === undefined || next === null)) {
127
126
  removedKeys.add(key);
128
127
  }
129
128
  else if (valueHasChanged ||
@@ -1 +1 @@
1
- {"version":3,"file":"animation-state.mjs","sources":["../../../../src/render/utils/animation-state.ts"],"sourcesContent":["import type {\n AnimationDefinition,\n TargetAndTransition,\n VariantLabels,\n} from \"../../node/types\"\nimport type { AnimationType } from \"../types\"\nimport type { VisualElementAnimationOptions } from \"../../animation/interfaces/types\"\nimport { animateVisualElement } from \"../../animation/interfaces/visual-element\"\nimport { calcChildStagger } from \"../../animation/utils/calc-child-stagger\"\nimport { isMotionValue } from \"../../value/utils/is-motion-value\"\nimport { isAnimationControls } from \"./is-animation-controls\"\nimport { isVariantLabel } from \"./is-variant-label\"\nimport { getTypeCustom, resolveVariant } from \"./resolve-dynamic-variants\"\nimport { shallowCompare } from \"./shallow-compare\"\nimport { variantPriorityOrder } from \"./variant-props\"\n\nexport type { VisualElementAnimationOptions }\n\nexport interface AnimationState {\n animateChanges: (type?: AnimationType) => Promise<any>\n setActive: (\n type: AnimationType,\n isActive: boolean,\n options?: VisualElementAnimationOptions\n ) => Promise<any>\n setAnimateFunction: (fn: any) => void\n getState: () => { [key: string]: AnimationTypeState }\n reset: () => void\n}\n\ninterface DefinitionAndOptions {\n animation: AnimationDefinition\n options?: VisualElementAnimationOptions\n}\n\nexport type AnimationList = string[] | TargetAndTransition[]\n\n/**\n * Type for the animate function that can be injected.\n * This allows the animation implementation to be provided by the framework layer.\n */\nexport type AnimateFunction = (animations: DefinitionAndOptions[]) => Promise<any>\n\nconst reversePriorityOrder = [...variantPriorityOrder].reverse()\n\n/**\n * Diffs the element's animation props (one layer per AnimationType, highest\n * priority wins each value) against the previous call and starts animations\n * for what changed.\n *\n * Uses `any` type for visualElement to avoid circular dependencies. It reads\n * props, parent, presenceContext, variantChildren, enteringChildren,\n * manuallyAnimateOnMount, blockInitialAnimation, getValue(),\n * getBaseTargetFromProps(), baseTarget and initialValues.\n */\nexport function createAnimationState(visualElement: any): AnimationState {\n let animate: AnimateFunction = (animations) =>\n Promise.all(\n animations.map(({ animation, options }) =>\n animateVisualElement(visualElement, animation, options)\n )\n )\n let state = createState()\n let isInitialRender = true\n\n /**\n * After a reset (StrictMode, Suspense, AnimatePresence re-entry) the next\n * animateChanges() mounts again, but initial={false} no longer applies.\n */\n let wasReset = false\n\n function animateChanges(changedActiveType?: AnimationType) {\n const { props, parent, manuallyAnimateOnMount } = visualElement\n const isMounting = isInitialRender || wasReset\n const animations: DefinitionAndOptions[] = []\n\n /**\n * Values removed from a type. A lower-priority type that defines\n * them animates them back, otherwise they fall back to a base target.\n */\n const removedKeys = new Set<string>()\n\n /**\n * Values claimed by active, higher-priority types.\n */\n let encounteredKeys: { [key: string]: any } = {}\n\n /**\n * Once a type has been deactivated, lower-priority variant labels\n * re-animate so variant children animate back too.\n */\n let removedVariantIndex = Infinity\n\n /**\n * Variant labels are inherited from the closest variant-controlling\n * ancestor, unless an element on the way has inherit={false}.\n */\n let source = visualElement\n do source = source.props.inherit !== false && source.parent\n while (source && !source.isControllingVariants)\n\n reversePriorityOrder.forEach((type, i) => {\n const typeState = state[type]\n const ownProp = props[type]\n const inheritedProp = source && source.props[type]\n const prop =\n ownProp !== undefined\n ? ownProp\n : isVariantLabel(inheritedProp) || inheritedProp === false\n ? inheritedProp\n : undefined\n const propIsVariant = isVariantLabel(prop)\n const activeDelta =\n type === changedActiveType ? typeState.isActive : null\n\n if (activeDelta === false) removedVariantIndex = i\n\n /**\n * Inherited labels are animated by the parent through\n * variantChildren, unless this element mounted after its parent.\n */\n const isInherited =\n propIsVariant &&\n ownProp === undefined &&\n !(isMounting && manuallyAnimateOnMount)\n\n typeState.protectedKeys = { ...encounteredKeys }\n\n if (\n (!typeState.isActive && activeDelta === null) ||\n (!prop && !typeState.prevProp) ||\n isAnimationControls(prop) ||\n typeof prop === \"boolean\"\n ) {\n return\n }\n\n /**\n * Don't re-resolve a running exit: a changed custom would start\n * new value animations that stop the originals, leaving the exit\n * promise unresolved and the element stuck in the DOM.\n */\n if (type === \"exit\" && typeState.isActive && activeDelta !== true) {\n encounteredKeys = {\n ...encounteredKeys,\n ...typeState.prevResolvedValues,\n }\n return\n }\n\n const variantDidChange = checkVariantsDidChange(\n typeState.prevProp,\n prop\n )\n let shouldAnimateType =\n variantDidChange ||\n (propIsVariant &&\n ((activeDelta && !isInherited) || i > removedVariantIndex))\n let handledRemovedValues = false\n const definitionList = Array.isArray(prop) ? prop : [prop]\n let resolvedValues: { [key: string]: any } = {}\n\n if (activeDelta !== false) {\n for (const definition of definitionList) {\n const { transition, transitionEnd, ...target } =\n resolveVariant(\n visualElement,\n definition,\n getTypeCustom(visualElement, type)\n ) || {}\n resolvedValues = {\n ...resolvedValues,\n ...target,\n ...transitionEnd,\n }\n }\n }\n\n const { prevResolvedValues } = typeState\n\n for (const key in { ...prevResolvedValues, ...resolvedValues }) {\n if (key in encounteredKeys) continue\n\n const next = resolvedValues[key]\n const prev = prevResolvedValues[key]\n\n /**\n * Keyframes compare by value, but replay whenever the\n * variant label changed.\n */\n const valueHasChanged =\n Array.isArray(next) && Array.isArray(prev)\n ? !shallowCompare(next, prev) || variantDidChange\n : next !== prev\n\n if (\n valueHasChanged &&\n (next === undefined || next === null)\n ) {\n removedKeys.add(key)\n } else if (\n valueHasChanged ||\n (next !== undefined && removedKeys.has(key))\n ) {\n shouldAnimateType = true\n if (removedKeys.delete(key)) handledRemovedValues = true\n typeState.needsAnimating[key] = true\n\n const motionValue = visualElement.getValue(key)\n if (motionValue) motionValue.liveStyle = false\n } else {\n typeState.protectedKeys[key] = true\n }\n }\n\n typeState.prevProp = prop\n typeState.prevResolvedValues = resolvedValues\n\n if (typeState.isActive) {\n encounteredKeys = { ...encounteredKeys, ...resolvedValues }\n }\n\n if (\n shouldAnimateType &&\n (!(isInherited && variantDidChange) || handledRemovedValues)\n ) {\n for (const animation of definitionList) {\n const options: VisualElementAnimationOptions = { type }\n\n /**\n * Elements that mount into an already-mounted parent\n * animate themselves, staggered by the parent variant's\n * delayChildren.\n */\n if (\n typeof animation === \"string\" &&\n isMounting &&\n manuallyAnimateOnMount &&\n parent?.enteringChildren\n ) {\n const delayChildren = resolveVariant(parent, animation)\n ?.transition?.delayChildren\n\n options.delay = calcChildStagger(\n parent.enteringChildren,\n visualElement,\n delayChildren\n )\n }\n\n animations.push({ animation, options })\n }\n }\n })\n\n /**\n * Removed values that no lower-priority type defines animate back to\n * initial, then style, then the value as first read. If initial no\n * longer defines a value it once did, it stays where it is.\n */\n if (removedKeys.size) {\n const { initial } = props\n const fallbackAnimation: { [key: string]: any } = {}\n const resolvedInitial =\n typeof initial !== \"boolean\" &&\n resolveVariant(\n visualElement,\n Array.isArray(initial) ? initial[0] : initial,\n visualElement.presenceContext?.custom\n )\n\n if (resolvedInitial && resolvedInitial.transition) {\n fallbackAnimation.transition = resolvedInitial.transition\n }\n\n removedKeys.forEach((key) => {\n const motionValue = visualElement.getValue(key)\n if (motionValue) motionValue.liveStyle = true\n\n const fromInitial =\n resolvedInitial && !Array.isArray(initial)\n ? (resolvedInitial as any)[key]\n : undefined\n const fromProps = visualElement.getBaseTargetFromProps(\n props,\n key\n )\n\n fallbackAnimation[key] =\n (fromInitial !== undefined\n ? fromInitial\n : fromProps !== undefined && !isMotionValue(fromProps)\n ? fromProps\n : visualElement.initialValues[key] === undefined\n ? visualElement.baseTarget[key]\n : undefined) ?? null\n\n /**\n * If it stays where it is, that's now its base. Otherwise a\n * later removal (like a gesture ending) would also stay,\n * leaving the value stuck. Stop first so accelerated\n * animations sync the value they reached. In practice initial\n * only changes like this with Fast Refresh, so this is\n * dev-only (#3787).\n */\n if (\n process.env.NODE_ENV !== \"production\" &&\n fallbackAnimation[key] === null &&\n visualElement.initialValues[key] !== undefined\n ) {\n delete visualElement.initialValues[key]\n motionValue?.stop()\n visualElement.baseTarget[key] = motionValue?.get()\n }\n })\n\n animations.push({ animation: fallbackAnimation })\n }\n\n const blockAnimation =\n (isMounting && visualElement.blockInitialAnimation) ||\n (isInitialRender &&\n !manuallyAnimateOnMount &&\n (props.initial === false || props.initial === props.animate))\n\n isInitialRender = wasReset = false\n\n return !blockAnimation && animations.length\n ? animate(animations)\n : Promise.resolve()\n }\n\n /**\n * Change whether a certain animation type is active.\n */\n function setActive(type: AnimationType, isActive: boolean) {\n if (state[type].isActive === isActive) return Promise.resolve()\n\n visualElement.variantChildren?.forEach((child: any) =>\n child.animationState?.setActive(type, isActive)\n )\n\n state[type].isActive = isActive\n\n const animations = animateChanges(type)\n\n for (const key in state) {\n state[key as AnimationType].protectedKeys = {}\n }\n\n return animations\n }\n\n return {\n animateChanges,\n setActive,\n /**\n * Allows tests to inject a mocked animate function.\n * @internal\n */\n setAnimateFunction: (makeAnimator) => {\n animate = makeAnimator(visualElement)\n },\n getState: () => state,\n reset: () => {\n state = createState()\n wasReset = true\n },\n }\n}\n\nexport function checkVariantsDidChange(prev: any, next: any) {\n if (typeof next === \"string\") {\n return next !== prev\n } else if (Array.isArray(next)) {\n return !shallowCompare(next, prev)\n }\n\n return false\n}\n\nexport interface AnimationTypeState {\n isActive: boolean\n protectedKeys: { [key: string]: true }\n needsAnimating: { [key: string]: boolean }\n prevResolvedValues: { [key: string]: any }\n prevProp?: VariantLabels | TargetAndTransition\n}\n\nfunction createState() {\n const state = {} as { [K in AnimationType]: AnimationTypeState }\n\n for (const type of variantPriorityOrder) {\n state[type] = {\n isActive: type === \"animate\",\n protectedKeys: {},\n needsAnimating: {},\n prevResolvedValues: {},\n }\n }\n\n return state\n}\n"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AAU;IACrB;IAEA,OAAO;QACH,cAAc;QACd,SAAS;AACT;;;AAGG;AACH,QAAA,kBAAkB,EAAE,CAAC,YAAY,KAAI;AACjC,YAAA,OAAO,GAAG,YAAY,CAAC,aAAa,CAAC;QACzC,CAAC;AACD,QAAA,QAAQ,EAAE,MAAM,KAAK;QACrB,KAAK,EAAE,MAAK;YACR,KAAK,GAAG,WAAW,EAAE;YACrB,QAAQ,GAAG,IAAI;QACnB,CAAC;KACJ;AACL;AAEM,SAAU,sBAAsB,CAAC,IAAS,EAAE,IAAS,EAAA;AACvD,IAAA,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QAC1B,OAAO,IAAI,KAAK,IAAI;IACxB;AAAO,SAAA,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;AAC5B,QAAA,OAAO,CAAC,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC;IACtC;AAEA,IAAA,OAAO,KAAK;AAChB;AAUA,SAAS,WAAW,GAAA;IAChB,MAAM,KAAK,GAAG,EAAkD;AAEhE,IAAA,KAAK,MAAM,IAAI,IAAI,oBAAoB,EAAE;QACrC,KAAK,CAAC,IAAI,CAAC,GAAG;YACV,QAAQ,EAAE,IAAI,KAAK,SAAS;AAC5B,YAAA,aAAa,EAAE,EAAE;AACjB,YAAA,cAAc,EAAE,EAAE;AAClB,YAAA,kBAAkB,EAAE,EAAE;SACzB;IACL;AAEA,IAAA,OAAO,KAAK;AAChB;;;;"}
1
+ {"version":3,"file":"animation-state.mjs","sources":["../../../../src/render/utils/animation-state.ts"],"sourcesContent":["import type {\n AnimationDefinition,\n TargetAndTransition,\n VariantLabels,\n} from \"../../node/types\"\nimport type { AnimationType } from \"../types\"\nimport type { VisualElementAnimationOptions } from \"../../animation/interfaces/types\"\nimport { animateVisualElement } from \"../../animation/interfaces/visual-element\"\nimport { calcChildStagger } from \"../../animation/utils/calc-child-stagger\"\nimport { isMotionValue } from \"../../value/utils/is-motion-value\"\nimport { isAnimationControls } from \"./is-animation-controls\"\nimport { isVariantLabel } from \"./is-variant-label\"\nimport { getTypeCustom, resolveVariant } from \"./resolve-dynamic-variants\"\nimport { shallowCompare } from \"./shallow-compare\"\nimport { variantPriorityOrder } from \"./variant-props\"\n\nexport type { VisualElementAnimationOptions }\n\nexport interface AnimationState {\n animateChanges: (type?: AnimationType) => Promise<any>\n setActive: (\n type: AnimationType,\n isActive: boolean,\n options?: VisualElementAnimationOptions\n ) => Promise<any>\n setAnimateFunction: (fn: any) => void\n getState: () => { [key: string]: AnimationTypeState }\n reset: () => void\n}\n\ninterface DefinitionAndOptions {\n animation: AnimationDefinition\n options?: VisualElementAnimationOptions\n}\n\nexport type AnimationList = string[] | TargetAndTransition[]\n\n/**\n * Type for the animate function that can be injected.\n * This allows the animation implementation to be provided by the framework layer.\n */\nexport type AnimateFunction = (\n animations: DefinitionAndOptions[]\n) => Promise<any>\n\nconst reversePriorityOrder = [...variantPriorityOrder].reverse()\n\n/**\n * Diffs the element's animation props (one layer per AnimationType, highest\n * priority wins each value) against the previous call and starts animations\n * for what changed.\n *\n * Uses `any` type for visualElement to avoid circular dependencies. It reads\n * props, parent, presenceContext, variantChildren, enteringChildren,\n * manuallyAnimateOnMount, blockInitialAnimation, getValue(),\n * getBaseTargetFromProps(), baseTarget and initialValues.\n */\nexport function createAnimationState(visualElement: any): AnimationState {\n let animate: AnimateFunction = (animations) =>\n Promise.all(\n animations.map(({ animation, options }) =>\n animateVisualElement(visualElement, animation, options)\n )\n )\n let state = createState()\n let isInitialRender = true\n\n /**\n * After a reset (StrictMode, Suspense, AnimatePresence re-entry) the next\n * animateChanges() mounts again, but initial={false} no longer applies.\n */\n let wasReset = false\n\n function animateChanges(changedActiveType?: AnimationType) {\n const { props, parent, manuallyAnimateOnMount } = visualElement\n const isMounting = isInitialRender || wasReset\n const animations: DefinitionAndOptions[] = []\n\n /**\n * Values removed from a type. A lower-priority type that defines\n * them animates them back, otherwise they fall back to a base target.\n */\n const removedKeys = new Set<string>()\n\n /**\n * Values claimed by active, higher-priority types.\n */\n let encounteredKeys: { [key: string]: any } = {}\n\n /**\n * Once a type has been deactivated, lower-priority variant labels\n * re-animate so variant children animate back too.\n */\n let removedVariantIndex = Infinity\n\n /**\n * Variant labels are inherited from the closest variant-controlling\n * ancestor, unless an element on the way has inherit={false}.\n */\n let source = visualElement\n do source = source.props.inherit !== false && source.parent\n while (source && !source.isControllingVariants)\n\n reversePriorityOrder.forEach((type, i) => {\n const typeState = state[type]\n const ownProp = props[type]\n const inheritedProp = source && source.props[type]\n const prop =\n ownProp !== undefined\n ? ownProp\n : isVariantLabel(inheritedProp) || inheritedProp === false\n ? inheritedProp\n : undefined\n const propIsVariant = isVariantLabel(prop)\n const activeDelta =\n type === changedActiveType ? typeState.isActive : null\n\n if (activeDelta === false) removedVariantIndex = i\n\n /**\n * Inherited labels are animated by the parent through\n * variantChildren, unless this element mounted after its parent.\n */\n const isInherited =\n propIsVariant &&\n ownProp === undefined &&\n !(isMounting && manuallyAnimateOnMount)\n\n typeState.protectedKeys = { ...encounteredKeys }\n\n if (\n (!typeState.isActive && activeDelta === null) ||\n (!prop && !typeState.prevProp) ||\n isAnimationControls(prop) ||\n typeof prop === \"boolean\"\n ) {\n return\n }\n\n /**\n * Don't re-resolve a running exit: a changed custom would start\n * new value animations that stop the originals, leaving the exit\n * promise unresolved and the element stuck in the DOM.\n */\n if (type === \"exit\" && typeState.isActive && activeDelta !== true) {\n encounteredKeys = {\n ...encounteredKeys,\n ...typeState.prevResolvedValues,\n }\n return\n }\n\n const variantDidChange = checkVariantsDidChange(\n typeState.prevProp,\n prop\n )\n let shouldAnimateType =\n variantDidChange ||\n (propIsVariant &&\n ((activeDelta && !isInherited) || i > removedVariantIndex))\n let handledRemovedValues = false\n const definitionList = Array.isArray(prop) ? prop : [prop]\n let resolvedValues: { [key: string]: any } = {}\n\n if (activeDelta !== false) {\n for (const definition of definitionList) {\n const { transition, transitionEnd, ...target } =\n resolveVariant(\n visualElement,\n definition,\n getTypeCustom(visualElement, type)\n ) || {}\n resolvedValues = {\n ...resolvedValues,\n ...target,\n ...transitionEnd,\n }\n }\n }\n\n const { prevResolvedValues } = typeState\n\n for (const key in { ...prevResolvedValues, ...resolvedValues }) {\n if (key in encounteredKeys) continue\n\n const next = resolvedValues[key]\n const prev = prevResolvedValues[key]\n\n /**\n * Keyframes compare by value, but replay whenever the\n * variant label changed.\n */\n const valueHasChanged =\n Array.isArray(next) && Array.isArray(prev)\n ? !shallowCompare(next, prev) || variantDidChange\n : next !== prev\n\n if (valueHasChanged && (next === undefined || next === null)) {\n removedKeys.add(key)\n } else if (\n valueHasChanged ||\n (next !== undefined && removedKeys.has(key))\n ) {\n shouldAnimateType = true\n if (removedKeys.delete(key)) handledRemovedValues = true\n typeState.needsAnimating[key] = true\n\n const motionValue = visualElement.getValue(key)\n if (motionValue) motionValue.liveStyle = false\n } else {\n typeState.protectedKeys[key] = true\n }\n }\n\n typeState.prevProp = prop\n typeState.prevResolvedValues = resolvedValues\n\n if (typeState.isActive) {\n encounteredKeys = { ...encounteredKeys, ...resolvedValues }\n }\n\n if (\n shouldAnimateType &&\n (!(isInherited && variantDidChange) || handledRemovedValues)\n ) {\n for (const animation of definitionList) {\n const options: VisualElementAnimationOptions = { type }\n\n /**\n * Elements that mount into an already-mounted parent\n * animate themselves, staggered by the parent variant's\n * delayChildren.\n */\n if (\n typeof animation === \"string\" &&\n isMounting &&\n manuallyAnimateOnMount &&\n parent?.enteringChildren\n ) {\n const delayChildren = resolveVariant(parent, animation)\n ?.transition?.delayChildren\n\n options.delay = calcChildStagger(\n parent.enteringChildren,\n visualElement,\n delayChildren\n )\n }\n\n animations.push({ animation, options })\n }\n }\n })\n\n /**\n * Removed values that no lower-priority type defines animate back to\n * initial, then style, then the value as first read. If initial no\n * longer defines a value it once did, it stays where it is.\n */\n if (removedKeys.size) {\n const { initial } = props\n const fallbackAnimation: { [key: string]: any } = {}\n const resolvedInitial =\n typeof initial !== \"boolean\" &&\n resolveVariant(\n visualElement,\n Array.isArray(initial) ? initial[0] : initial,\n visualElement.presenceContext?.custom\n )\n\n if (resolvedInitial && resolvedInitial.transition) {\n fallbackAnimation.transition = resolvedInitial.transition\n }\n\n removedKeys.forEach((key) => {\n const motionValue = visualElement.getValue(key)\n if (motionValue) motionValue.liveStyle = true\n\n const fromInitial =\n resolvedInitial && !Array.isArray(initial)\n ? (resolvedInitial as any)[key]\n : undefined\n const fromProps = visualElement.getBaseTargetFromProps(\n props,\n key\n )\n\n fallbackAnimation[key] =\n (fromInitial !== undefined\n ? fromInitial\n : fromProps !== undefined && !isMotionValue(fromProps)\n ? fromProps\n : visualElement.initialValues[key] === undefined\n ? visualElement.baseTarget[key]\n : undefined) ?? null\n\n /**\n * If it stays where it is, that's now its base. Otherwise a\n * later removal (like a gesture ending) would also stay,\n * leaving the value stuck. Stop first so accelerated\n * animations sync the value they reached. In practice initial\n * only changes like this with Fast Refresh, so this is\n * dev-only (#3787).\n */\n if (\n process.env.NODE_ENV !== \"production\" &&\n fallbackAnimation[key] === null &&\n visualElement.initialValues[key] !== undefined\n ) {\n delete visualElement.initialValues[key]\n motionValue?.stop()\n visualElement.baseTarget[key] = motionValue?.get()\n }\n })\n\n animations.push({ animation: fallbackAnimation })\n }\n\n const blockAnimation =\n (isMounting && visualElement.blockInitialAnimation) ||\n (isInitialRender &&\n !manuallyAnimateOnMount &&\n (props.initial === false || props.initial === props.animate))\n\n isInitialRender = wasReset = false\n\n return !blockAnimation && animations.length\n ? animate(animations)\n : Promise.resolve()\n }\n\n /**\n * Change whether a certain animation type is active.\n */\n function setActive(type: AnimationType, isActive: boolean) {\n if (state[type].isActive === isActive) return Promise.resolve()\n\n visualElement.variantChildren?.forEach((child: any) =>\n child.animationState?.setActive(type, isActive)\n )\n\n state[type].isActive = isActive\n\n const animations = animateChanges(type)\n\n for (const key in state) {\n state[key as AnimationType].protectedKeys = {}\n }\n\n return animations\n }\n\n return {\n animateChanges,\n setActive,\n /**\n * Allows tests to inject a mocked animate function.\n * @internal\n */\n setAnimateFunction: (makeAnimator) => {\n animate = makeAnimator(visualElement)\n },\n getState: () => state,\n reset: () => {\n state = createState()\n wasReset = true\n },\n }\n}\n\nexport function checkVariantsDidChange(prev: any, next: any) {\n if (typeof next === \"string\") {\n return next !== prev\n } else if (Array.isArray(next)) {\n return !shallowCompare(next, prev)\n }\n\n return false\n}\n\nexport interface AnimationTypeState {\n isActive: boolean\n protectedKeys: { [key: string]: true }\n needsAnimating: { [key: string]: boolean }\n prevResolvedValues: { [key: string]: any }\n prevProp?: VariantLabels | TargetAndTransition\n}\n\nfunction createState() {\n const state = {} as { [K in AnimationType]: AnimationTypeState }\n\n for (const type of variantPriorityOrder) {\n state[type] = {\n isActive: type === \"animate\",\n protectedKeys: {},\n needsAnimating: {},\n prevResolvedValues: {},\n }\n }\n\n return state\n}\n"],"names":[],"mappings":";;;;;;;;;AA6CA,MAAM,oBAAoB,GAAG,CAAC,GAAG,oBAAoB,CAAC,CAAC,OAAO,EAAE;AAEhE;;;;;;;;;AASG;AACG,SAAU,oBAAoB,CAAC,aAAkB,EAAA;AACnD,IAAA,IAAI,OAAO,GAAoB,CAAC,UAAU,KACtC,OAAO,CAAC,GAAG,CACP,UAAU,CAAC,GAAG,CAAC,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,KAClC,oBAAoB,CAAC,aAAa,EAAE,SAAS,EAAE,OAAO,CAAC,CAC1D,CACJ;AACL,IAAA,IAAI,KAAK,GAAG,WAAW,EAAE;IACzB,IAAI,eAAe,GAAG,IAAI;AAE1B;;;AAGG;IACH,IAAI,QAAQ,GAAG,KAAK;IAEpB,SAAS,cAAc,CAAC,iBAAiC,EAAA;QACrD,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,sBAAsB,EAAE,GAAG,aAAa;AAC/D,QAAA,MAAM,UAAU,GAAG,eAAe,IAAI,QAAQ;QAC9C,MAAM,UAAU,GAA2B,EAAE;AAE7C;;;AAGG;AACH,QAAA,MAAM,WAAW,GA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C,KAAK,CAAC,IAAI,CAAC,GAAG;YACV,QAAQ,EAAE,IAAI,KAAK,SAAS;AAC5B,YAAA,aAAa,EAAE,EAAE;AACjB,YAAA,cAAc,EAAE,EAAE;AAClB,YAAA,kBAAkB,EAAE,EAAE;SACzB;IACL;AAEA,IAAA,OAAO,KAAK;AAChB;;;;"}
@@ -7,7 +7,7 @@ const variantPriorityOrder = [
7
7
  "whileDrag",
8
8
  "exit",
9
9
  ];
10
- const variantProps = ["initial", ...variantPriorityOrder];
10
+ const variantProps = /* @__PURE__ */ ["initial"].concat(variantPriorityOrder);
11
11
 
12
12
  export { variantPriorityOrder, variantProps };
13
13
  //# sourceMappingURL=variant-props.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"variant-props.mjs","sources":["../../../../src/render/utils/variant-props.ts"],"sourcesContent":["import type { AnimationType } from \"../types\"\n\nexport const variantPriorityOrder: AnimationType[] = [\n \"animate\",\n \"whileInView\",\n \"whileFocus\",\n \"whileHover\",\n \"whileTap\",\n \"whileDrag\",\n \"exit\",\n]\n\nexport const variantProps = [\"initial\", ...variantPriorityOrder]\n"],"names":[],"mappings":"AAEO,MAAM,oBAAoB,GAAoB;IACjD,SAAS;IACT,aAAa;IACb,YAAY;IACZ,YAAY;IACZ,UAAU;IACV,WAAW;IACX,MAAM;;AAGH,MAAM,YAAY,GAAG,CAAC,SAAS,EAAE,GAAG,oBAAoB;;;;"}
1
+ {"version":3,"file":"variant-props.mjs","sources":["../../../../src/render/utils/variant-props.ts"],"sourcesContent":["import type { AnimationType } from \"../types\"\n\nexport const variantPriorityOrder: AnimationType[] = [\n \"animate\",\n \"whileInView\",\n \"whileFocus\",\n \"whileHover\",\n \"whileTap\",\n \"whileDrag\",\n \"exit\",\n]\n\nexport const variantProps = /* @__PURE__ */ [\"initial\"].concat(\n variantPriorityOrder\n)\n"],"names":[],"mappings":"AAEO,MAAM,oBAAoB,GAAoB;IACjD,SAAS;IACT,aAAa;IACb,YAAY;IACZ,YAAY;IACZ,UAAU;IACV,WAAW;IACX,MAAM;;AAGH,MAAM,YAAY,mBAAmB,CAAC,SAAS,CAAC,CAAC,MAAM,CAC1D,oBAAoB;;;;"}
@@ -1,8 +1,9 @@
1
+ import { addToScope } from '../scope/active.mjs';
1
2
  import { resizeElement } from './handle-element.mjs';
2
3
  import { resizeWindow } from './handle-window.mjs';
3
4
 
4
5
  function resize(a, b) {
5
- return typeof a === "function" ? resizeWindow(a) : resizeElement(a, b);
6
+ return addToScope(typeof a === "function" ? resizeWindow(a) : resizeElement(a, b));
6
7
  }
7
8
 
8
9
  export { resize };
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../../../src/resize/index.ts"],"sourcesContent":["import { ElementOrSelector } from \"../utils/resolve-elements\"\nimport { resizeElement } from \"./handle-element\"\nimport { resizeWindow } from \"./handle-window\"\nimport { ResizeHandler, WindowResizeHandler } from \"./types\"\n\nexport function resize(onResize: WindowResizeHandler): VoidFunction\nexport function resize(\n target: ElementOrSelector,\n onResize: ResizeHandler<Element>\n): VoidFunction\nexport function resize(\n a: WindowResizeHandler | ElementOrSelector,\n b?: ResizeHandler<Element>\n) {\n return typeof a === \"function\" ? resizeWindow(a) : resizeElement(a, b!)\n}\n"],"names":[],"mappings":";;;AAUM,SAAU,MAAM,CAClB,CAA0C,EAC1C,CAA0B,EAAA;IAE1B,OAAO,OAAO,CAAC,KAAK,UAAU,GAAG,YAAY,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC,EAAE,CAAE,CAAC;AAC3E;;;;"}
1
+ {"version":3,"file":"index.mjs","sources":["../../../src/resize/index.ts"],"sourcesContent":["import { addToScope } from \"../scope/active\"\nimport { ElementOrSelector } from \"../utils/resolve-elements\"\nimport { resizeElement } from \"./handle-element\"\nimport { resizeWindow } from \"./handle-window\"\nimport { ResizeHandler, WindowResizeHandler } from \"./types\"\n\nexport function resize(onResize: WindowResizeHandler): VoidFunction\nexport function resize(\n target: ElementOrSelector,\n onResize: ResizeHandler<Element>\n): VoidFunction\nexport function resize(\n a: WindowResizeHandler | ElementOrSelector,\n b?: ResizeHandler<Element>\n) {\n return addToScope(\n typeof a === \"function\" ? resizeWindow(a) : resizeElement(a, b!)\n )\n}\n"],"names":[],"mappings":";;;;AAWM,SAAU,MAAM,CAClB,CAA0C,EAC1C,CAA0B,EAAA;IAE1B,OAAO,UAAU,CACb,OAAO,CAAC,KAAK,UAAU,GAAG,YAAY,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC,EAAE,CAAE,CAAC,CACnE;AACL;;;;"}
@@ -0,0 +1,39 @@
1
+ const activeScope = {};
2
+ /**
3
+ * Register `cleanup` with the active scope, if there is one, so stopping
4
+ * the scope also runs it.
5
+ */
6
+ function addToScope(cleanup) {
7
+ activeScope.current?.add(cleanup);
8
+ return cleanup;
9
+ }
10
+ /**
11
+ * Collect the animation a builder like `animateLayout()` or
12
+ * `animateView()` resolves with. If the scope stops first, the animation
13
+ * is stopped as soon as it starts.
14
+ */
15
+ function addBuilderToScope(builder) {
16
+ const scope = activeScope.current;
17
+ if (!scope)
18
+ return;
19
+ let isStopped = false;
20
+ let stop;
21
+ const remove = scope.add(() => {
22
+ isStopped = true;
23
+ stop?.();
24
+ });
25
+ builder.then((animation) => {
26
+ if (!animation)
27
+ return;
28
+ stop = () => animation.stop();
29
+ isStopped ? stop() : animation.finished.then(remove);
30
+ }, remove);
31
+ }
32
+ /**
33
+ * Bind `callback` to the active scope, so anything it starts later (for
34
+ * instance an animation in an `inView()` callback) is collected too.
35
+ */
36
+ const bindToScope = (callback) => activeScope.current ? activeScope.current.bind(callback) : callback;
37
+
38
+ export { activeScope, addBuilderToScope, addToScope, bindToScope };
39
+ //# sourceMappingURL=active.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"active.mjs","sources":["../../../src/scope/active.ts"],"sourcesContent":["import type { AnimationOptions } from \"../animation/types\"\n\n/**\n * The scope that `animate()`, `scroll()`, `inView()`, gestures and\n * `resize()` register their cleanups with while it runs. Set by\n * `scopeMotion()`.\n */\nexport interface ActiveScope {\n root?: Element\n transition?: AnimationOptions\n add(cleanup: VoidFunction): VoidFunction\n bind<F extends (...args: any[]) => any>(callback: F): F\n track(element: Element): void\n}\n\nexport const activeScope: { current?: ActiveScope } = {}\n\n/**\n * Register `cleanup` with the active scope, if there is one, so stopping\n * the scope also runs it.\n */\nexport function addToScope<T extends VoidFunction>(cleanup: T): T {\n activeScope.current?.add(cleanup)\n return cleanup\n}\n\n/**\n * Collect the animation a builder like `animateLayout()` or\n * `animateView()` resolves with. If the scope stops first, the animation\n * is stopped as soon as it starts.\n */\nexport function addBuilderToScope(builder: {\n then(resolve: (animation?: any) => void, reject?: () => void): unknown\n}) {\n const scope = activeScope.current\n if (!scope) return\n\n let isStopped = false\n let stop: VoidFunction | undefined\n const remove = scope.add(() => {\n isStopped = true\n stop?.()\n })\n\n builder.then((animation?: { stop(): void; finished: Promise<any> }) => {\n if (!animation) return\n stop = () => animation.stop()\n isStopped ? stop() : animation.finished.then(remove)\n }, remove)\n}\n\n/**\n * Bind `callback` to the active scope, so anything it starts later (for\n * instance an animation in an `inView()` callback) is collected too.\n */\nexport const bindToScope = <F extends (...args: any[]) => any>(callback: F) =>\n activeScope.current ? activeScope.current.bind(callback) : callback\n"],"names":[],"mappings":"AAeO,MAAM,WAAW,GAA8B;AAEtD;;;AAGG;AACG,SAAU,UAAU,CAAyB,OAAU,EAAA;AACzD,IAAA,WAAW,CAAC,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC;AACjC,IAAA,OAAO,OAAO;AAClB;AAEA;;;;AAIG;AACG,SAAU,iBAAiB,CAAC,OAEjC,EAAA;AACG,IAAA,MAAM,KAAK,GAAG,WAAW,CAAC,OAAO;AACjC,IAAA,IAAI,CAAC,KAAK;QAAE;IAEZ,IAAI,SAAS,GAAG,KAAK;AACrB,IAAA,IAAI,IAA8B;AAClC,IAAA,MAAM,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,MAAK;QAC1B,SAAS,GAAG,IAAI;QAChB,IAAI,IAAI;AACZ,IAAA,CAAC,CAAC;AAEF,IAAA,OAAO,CAAC,IAAI,CAAC,CAAC,SAAoD,KAAI;AAClE,QAAA,IAAI,CAAC,SAAS;YAAE;QAChB,IAAI,GAAG,MAAM,SAAS,CAAC,IAAI,EAAE;AAC7B,QAAA,SAAS,GAAG,IAAI,EAAE,GAAG,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC;IACxD,CAAC,EAAE,MAAM,CAAC;AACd;AAEA;;;AAGG;AACI,MAAM,WAAW,GAAG,CAAoC,QAAW,KACtE,WAAW,CAAC,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG;;;;"}
@@ -0,0 +1,122 @@
1
+ import { removeItem } from 'motion-utils';
2
+ import { releaseElement } from '../animation/animate/element.mjs';
3
+ import { resolveElements } from '../utils/resolve-elements.mjs';
4
+ import { addToScope, activeScope } from './active.mjs';
5
+ import { toMediaQuery } from './media.mjs';
6
+
7
+ function scopeMotion(...args) {
8
+ const root = typeof args[0] === "function" ? undefined : args.shift();
9
+ const [setup, options = {}] = args;
10
+ const { transition, matchMedia } = options;
11
+ const queries = [];
12
+ const styles = new Map();
13
+ let cleanups = [];
14
+ let isPending = false;
15
+ const active = {
16
+ root: resolveElements(root)[0],
17
+ transition,
18
+ add(cleanup) {
19
+ cleanups.push(cleanup);
20
+ return () => removeItem(cleanups, cleanup);
21
+ },
22
+ bind: (callback) => ((...args) => {
23
+ const result = scope.run(() => callback(...args));
24
+ return typeof result === "function"
25
+ ? active.bind(result)
26
+ : result;
27
+ }),
28
+ track(element) {
29
+ styles.has(element) ||
30
+ styles.set(element, element.getAttribute("style"));
31
+ },
32
+ };
33
+ const clear = (restore) => {
34
+ const current = cleanups;
35
+ cleanups = [];
36
+ for (let i = current.length - 1; i >= 0; i--)
37
+ current[i]();
38
+ restore &&
39
+ styles.forEach((style, element) => {
40
+ releaseElement(element);
41
+ style === null
42
+ ? element.removeAttribute("style")
43
+ : element.setAttribute("style", style);
44
+ });
45
+ styles.clear();
46
+ };
47
+ const start = () => {
48
+ scope.state = "active";
49
+ let matches = !queries.length;
50
+ scope.media = {};
51
+ for (const [name, query] of queries) {
52
+ matches = (scope.media[name] = query.matches) || matches;
53
+ }
54
+ if (matches && setup) {
55
+ const cleanup = scope.run(() => setup(scope));
56
+ typeof cleanup === "function" && active.add(cleanup);
57
+ }
58
+ };
59
+ const onChange = () => {
60
+ if (isPending)
61
+ return;
62
+ isPending = true;
63
+ /**
64
+ * Several conditions can change together, for instance two
65
+ * breakpoints crossed by one resize. Refresh once.
66
+ */
67
+ queueMicrotask(() => {
68
+ isPending = false;
69
+ queries.length && scope.refresh();
70
+ });
71
+ };
72
+ const kill = (restore) => {
73
+ scope.state = restore ? "cancelled" : "stopped";
74
+ for (const [, query] of queries) {
75
+ query.removeEventListener("change", onChange);
76
+ }
77
+ queries.length = 0;
78
+ clear(restore);
79
+ };
80
+ const runIn = (target, callback) => {
81
+ const prev = activeScope.current;
82
+ activeScope.current = target;
83
+ try {
84
+ return callback();
85
+ }
86
+ finally {
87
+ activeScope.current = prev;
88
+ }
89
+ };
90
+ const scope = {
91
+ state: "active",
92
+ media: {},
93
+ run: (callback) => runIn(active, callback),
94
+ ignore: (callback) => runIn(undefined, callback),
95
+ bind: active.bind,
96
+ stop: () => kill(),
97
+ cancel: () => kill(true),
98
+ refresh() {
99
+ clear(true);
100
+ start();
101
+ },
102
+ };
103
+ if (matchMedia && typeof window !== "undefined") {
104
+ const conditions = typeof matchMedia === "string"
105
+ ? { matches: matchMedia }
106
+ : matchMedia;
107
+ for (const name in conditions) {
108
+ const query = window.matchMedia(toMediaQuery(conditions[name]));
109
+ query.addEventListener("change", onChange);
110
+ queries.push([name, query]);
111
+ }
112
+ }
113
+ /**
114
+ * A scope created inside another is cancelled with it.
115
+ */
116
+ addToScope(scope.cancel);
117
+ start();
118
+ return scope;
119
+ }
120
+
121
+ export { scopeMotion };
122
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":["../../../src/scope/index.ts"],"sourcesContent":["import { removeItem } from \"motion-utils\"\nimport { releaseElement } from \"../animation/animate/element\"\nimport type { AnimationOptions } from \"../animation/types\"\nimport { ElementOrSelector, resolveElements } from \"../utils/resolve-elements\"\nimport { activeScope, ActiveScope, addToScope } from \"./active\"\nimport { toMediaQuery } from \"./media\"\n\n/**\n * A media query or shorthand (see `toMediaQuery`), or named conditions.\n * With named conditions, setup runs when any of them match, and their\n * state is available as `scope.media`.\n */\nexport type MediaConditions = string | Record<string, string>\n\nexport interface ScopeOptions {\n /**\n * Default transition for every `animate()` call made in this scope.\n */\n transition?: AnimationOptions\n\n /**\n * Only run setup while these conditions match. When they change, the\n * scope is cancelled and setup runs again.\n */\n matchMedia?: MediaConditions\n}\n\nexport type ScopeState = \"active\" | \"stopped\" | \"cancelled\"\n\nexport interface MotionScope {\n /**\n * `\"active\"` until `stop()` or `cancel()` is called. Lets async work\n * check whether its scope has gone before it starts animating.\n */\n state: ScopeState\n\n /**\n * Whether each named `matchMedia` condition matched when setup last ran.\n */\n media: Record<string, boolean>\n\n /**\n * Run `callback` in this scope, so animations, scroll and view\n * listeners and gestures it starts are collected.\n */\n run<R>(callback: () => R): R\n\n /**\n * Return a function that runs `callback` in this scope, for instance\n * as an event handler.\n */\n bind<F extends (...args: any[]) => any>(callback: F): F\n\n /**\n * Run `callback` outside of any scope, so what it starts is not\n * collected and survives this scope being stopped or cancelled.\n */\n ignore<R>(callback: () => R): R\n\n /**\n * Stop everything in this scope and remove its media listeners.\n * Styles are left as they are.\n */\n stop(): void\n\n /**\n * As `stop()`, and restore the inline styles of every element\n * animated in this scope to what they were before.\n */\n cancel(): void\n\n /**\n * Cancel, then run setup again if the media conditions match.\n */\n refresh(): void\n}\n\nexport type ScopeSetup = (scope: MotionScope) => void | VoidFunction\n\n/**\n * Create a scope that collects the animations, scroll and view\n * listeners, gestures and resize observers started inside it, so they\n * can be stopped or cancelled together.\n *\n * An optional root element or selector comes first. Selectors used\n * inside the scope resolve within it.\n *\n * ```js\n * const scope = scopeMotion(\n * \".list\",\n * ({ media }) => {\n * animate(\"li\", { x: media.desktop ? 100 : 0 })\n * },\n * { transition: { duration: 0.5 }, matchMedia: { desktop: \">=800\" } }\n * )\n * ```\n *\n * @public\n */\nexport function scopeMotion(\n setup?: ScopeSetup,\n options?: ScopeOptions\n): MotionScope\nexport function scopeMotion(\n root: ElementOrSelector,\n setup?: ScopeSetup,\n options?: ScopeOptions\n): MotionScope\nexport function scopeMotion(...args: [any?, any?, any?]): MotionScope {\n const root: ElementOrSelector =\n typeof args[0] === \"function\" ? undefined : args.shift()\n const [setup, options = {}] = args as [ScopeSetup?, ScopeOptions?]\n\n const { transition, matchMedia } = options\n const queries: [string, MediaQueryList][] = []\n const styles = new Map<Element, string | null>()\n let cleanups: VoidFunction[] = []\n let isPending = false\n\n const active: ActiveScope = {\n root: resolveElements(root)[0],\n transition,\n add(cleanup) {\n cleanups.push(cleanup)\n return () => removeItem(cleanups, cleanup)\n },\n bind: (callback) =>\n ((...args: any[]) => {\n const result = scope.run(() => callback(...args))\n return typeof result === \"function\"\n ? active.bind(result)\n : result\n }) as typeof callback,\n track(element) {\n styles.has(element) ||\n styles.set(element, element.getAttribute(\"style\"))\n },\n }\n\n const clear = (restore?: boolean) => {\n const current = cleanups\n cleanups = []\n for (let i = current.length - 1; i >= 0; i--) current[i]()\n\n restore &&\n styles.forEach((style, element) => {\n releaseElement(element)\n style === null\n ? element.removeAttribute(\"style\")\n : element.setAttribute(\"style\", style)\n })\n styles.clear()\n }\n\n const start = () => {\n scope.state = \"active\"\n let matches = !queries.length\n scope.media = {}\n\n for (const [name, query] of queries) {\n matches = (scope.media[name] = query.matches) || matches\n }\n\n if (matches && setup) {\n const cleanup = scope.run(() => setup(scope))\n typeof cleanup === \"function\" && active.add(cleanup)\n }\n }\n\n const onChange = () => {\n if (isPending) return\n isPending = true\n\n /**\n * Several conditions can change together, for instance two\n * breakpoints crossed by one resize. Refresh once.\n */\n queueMicrotask(() => {\n isPending = false\n queries.length && scope.refresh()\n })\n }\n\n const kill = (restore?: boolean) => {\n scope.state = restore ? \"cancelled\" : \"stopped\"\n for (const [, query] of queries) {\n query.removeEventListener(\"change\", onChange)\n }\n queries.length = 0\n clear(restore)\n }\n\n const runIn = <R>(target: ActiveScope | undefined, callback: () => R) => {\n const prev = activeScope.current\n activeScope.current = target\n try {\n return callback()\n } finally {\n activeScope.current = prev\n }\n }\n\n const scope: MotionScope = {\n state: \"active\",\n media: {},\n run: (callback) => runIn(active, callback),\n ignore: (callback) => runIn(undefined, callback),\n bind: active.bind,\n stop: () => kill(),\n cancel: () => kill(true),\n refresh() {\n clear(true)\n start()\n },\n }\n\n if (matchMedia && typeof window !== \"undefined\") {\n const conditions =\n typeof matchMedia === \"string\"\n ? { matches: matchMedia }\n : matchMedia\n\n for (const name in conditions) {\n const query = window.matchMedia(toMediaQuery(conditions[name]))\n query.addEventListener(\"change\", onChange)\n queries.push([name, query])\n }\n }\n\n /**\n * A scope created inside another is cancelled with it.\n */\n addToScope(scope.cancel)\n\n start()\n\n return scope\n}\n"],"names":[],"mappings":";;;;;;AA4GM,SAAU,WAAW,CAAC,GAAG,IAAwB,EAAA;IACnD,MAAM,IAAI,GACN,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,UAAU,GAAG,SAAS,GAAG,IAAI,CAAC,KAAK,EAAE;IAC5D,MAAM,CAAC,KAAK,EAAE,OAAO,GAAG,EAAE,CAAC,GAAG,IAAoC;AAElE,IAAA,MAAM,EAAE,UAAU,EAAE,UAAU,EAAE,GAAG,OAAO;IAC1C,MAAM,OAAO,GAA+B,EAAE;AAC9C,IAAA,MAAM,MAAM,GAAG,IAAI,GAAG,EAA0B;IAChD,IAAI,QAAQ,GAAmB,EAAE;IACjC,IAAI,SAAS,GAAG,KAAK;AAErB,IAAA,MAAM,MAAM,GAAg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AK;AAChB;;;;"}
@@ -0,0 +1,42 @@
1
+ const keywords = {
2
+ reducedMotion: "(prefers-reduced-motion: reduce)",
3
+ motion: "(prefers-reduced-motion: no-preference)",
4
+ dark: "(prefers-color-scheme: dark)",
5
+ light: "(prefers-color-scheme: light)",
6
+ hover: "(hover: hover) and (pointer: fine)",
7
+ touch: "(pointer: coarse)",
8
+ portrait: "(orientation: portrait)",
9
+ landscape: "(orientation: landscape)",
10
+ };
11
+ /**
12
+ * Turn a condition into a media query. Full media queries pass through
13
+ * unchanged. Otherwise each space-separated token must match:
14
+ *
15
+ * - A width comparison: `">=800"`, `"<1200px"`, `"> 40em"`
16
+ * - A keyword: `reducedMotion`, `motion`, `dark`, `light`, `hover`,
17
+ * `touch`, `portrait`, `landscape`
18
+ *
19
+ * Prefix a token with `!` to negate it, for instance `">=800 !touch"`.
20
+ */
21
+ function toMediaQuery(condition) {
22
+ if (condition.includes("("))
23
+ return condition;
24
+ return condition
25
+ .replace(/([<>!]=?)\s+/g, "$1")
26
+ .trim()
27
+ .split(/\s+/)
28
+ .map((token) => {
29
+ const isNot = token[0] === "!";
30
+ if (isNot)
31
+ token = token.slice(1);
32
+ const width = /^([<>]=?)([\d.]+)([a-z]*)$/.exec(token);
33
+ const query = width
34
+ ? `(width ${width[1]} ${width[2]}${width[3] || "px"})`
35
+ : keywords[token] || token;
36
+ return isNot ? `(not (${query}))` : query;
37
+ })
38
+ .join(" and ");
39
+ }
40
+
41
+ export { toMediaQuery };
42
+ //# sourceMappingURL=media.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"media.mjs","sources":["../../../src/scope/media.ts"],"sourcesContent":["const keywords: Record<string, string> = {\n reducedMotion: \"(prefers-reduced-motion: reduce)\",\n motion: \"(prefers-reduced-motion: no-preference)\",\n dark: \"(prefers-color-scheme: dark)\",\n light: \"(prefers-color-scheme: light)\",\n hover: \"(hover: hover) and (pointer: fine)\",\n touch: \"(pointer: coarse)\",\n portrait: \"(orientation: portrait)\",\n landscape: \"(orientation: landscape)\",\n}\n\n/**\n * Turn a condition into a media query. Full media queries pass through\n * unchanged. Otherwise each space-separated token must match:\n *\n * - A width comparison: `\">=800\"`, `\"<1200px\"`, `\"> 40em\"`\n * - A keyword: `reducedMotion`, `motion`, `dark`, `light`, `hover`,\n * `touch`, `portrait`, `landscape`\n *\n * Prefix a token with `!` to negate it, for instance `\">=800 !touch\"`.\n */\nexport function toMediaQuery(condition: string) {\n if (condition.includes(\"(\")) return condition\n\n return condition\n .replace(/([<>!]=?)\\s+/g, \"$1\")\n .trim()\n .split(/\\s+/)\n .map((token) => {\n const isNot = token[0] === \"!\"\n if (isNot) token = token.slice(1)\n\n const width = /^([<>]=?)([\\d.]+)([a-z]*)$/.exec(token)\n const query = width\n ? `(width ${width[1]} ${width[2]}${width[3] || \"px\"})`\n : keywords[token] || token\n\n return isNot ? `(not (${query}))` : query\n })\n .join(\" and \")\n}\n"],"names":[],"mappings":"AAAA,MAAM,QAAQ,GAA2B;AACrC,IAAA,aAAa,EAAE,kCAAkC;AACjD,IAAA,MAAM,EAAE,yCAAyC;AACjD,IAAA,IAAI,EAAE,8BAA8B;AACpC,IAAA,KAAK,EAAE,+BAA+B;AACtC,IAAA,KAAK,EAAE,oCAAoC;AAC3C,IAAA,KAAK,EAAE,mBAAmB;AAC1B,IAAA,QAAQ,EAAE,yBAAyB;AACnC,IAAA,SAAS,EAAE,0BAA0B;CACxC;AAED;;;;;;;;;AASG;AACG,SAAU,YAAY,CAAC,SAAiB,EAAA;AAC1C,IAAA,IAAI,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC;AAAE,QAAA,OAAO,SAAS;AAE7C,IAAA,OAAO;AACF,SAAA,OAAO,CAAC,eAAe,EAAE,IAAI;AAC7B,SAAA,IAAI;SACJ,KAAK,CAAC,KAAK;AACX,SAAA,GAAG,CAAC,CAAC,KAAK,KAAI;QACX,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,KAAK,GAAG;AAC9B,QAAA,IAAI,KAAK;AAAE,YAAA,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;QAEjC,MAAM,KAAK,GAAG,4BAA4B,CAAC,IAAI,CAAC,KAAK,CAAC;QACtD,MAAM,KAAK,GAAG;AACV,cAAE,CAAA,OAAA,EAAU,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAA,CAAA;AACnD,cAAE,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK;QAE9B,OAAO,KAAK,GAAG,CAAA,MAAA,EAAS,KAAK,CAAA,EAAA,CAAI,GAAG,KAAK;AAC7C,IAAA,CAAC;SACA,IAAI,CAAC,OAAO,CAAC;AACtB;;;;"}
@@ -1,5 +1,6 @@
1
1
  import { time } from '../frameloop/sync-time.mjs';
2
2
  import { secondsToMilliseconds } from 'motion-utils';
3
+ import { bindToScope, addToScope } from '../scope/active.mjs';
3
4
  import { frame, cancelFrame } from '../frameloop/frame.mjs';
4
5
 
5
6
  /**
@@ -7,6 +8,7 @@ import { frame, cancelFrame } from '../frameloop/frame.mjs';
7
8
  */
8
9
  function delay(callback, timeout) {
9
10
  const start = time.now();
11
+ callback = bindToScope(callback);
10
12
  const checkElapsed = ({ timestamp }) => {
11
13
  const elapsed = timestamp - start;
12
14
  if (elapsed >= timeout) {
@@ -15,7 +17,7 @@ function delay(callback, timeout) {
15
17
  }
16
18
  };
17
19
  frame.setup(checkElapsed, true);
18
- return () => cancelFrame(checkElapsed);
20
+ return addToScope(() => cancelFrame(checkElapsed));
19
21
  }
20
22
  function delayInSeconds(callback, timeout) {
21
23
  return delay(callback, secondsToMilliseconds(timeout));
@@ -1 +1 @@
1
- {"version":3,"file":"delay.mjs","sources":["../../../src/utils/delay.ts"],"sourcesContent":["import { cancelFrame, frame } from \"../frameloop\"\nimport { time } from \"../frameloop/sync-time\"\nimport type { FrameData } from \"../frameloop/types\"\nimport { secondsToMilliseconds } from \"motion-utils\"\n\nexport type DelayedFunction = (overshoot: number) => void\n\n/**\n * Timeout defined in ms\n */\nexport function delay(callback: DelayedFunction, timeout: number) {\n const start = time.now()\n\n const checkElapsed = ({ timestamp }: FrameData) => {\n const elapsed = timestamp - start\n\n if (elapsed >= timeout) {\n cancelFrame(checkElapsed)\n callback(elapsed - timeout)\n }\n }\n\n frame.setup(checkElapsed, true)\n\n return () => cancelFrame(checkElapsed)\n}\n\nexport function delayInSeconds(callback: DelayedFunction, timeout: number) {\n return delay(callback, secondsToMilliseconds(timeout))\n}\n"],"names":[],"mappings":";;;;AAOA;;AAEG;AACG,SAAU,KAAK,CAAC,QAAyB,EAAE,OAAe,EAAA;AAC5D,IAAA,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE;AAExB,IAAA,MAAM,YAAY,GAAG,CAAC,EAAE,SAAS,EAAa,KAAI;AAC9C,QAAA,MAAM,OAAO,GAAG,SAAS,GAAG,KAAK;AAEjC,QAAA,IAAI,OAAO,IAAI,OAAO,EAAE;YACpB,WAAW,CAAC,YAAY,CAAC;AACzB,YAAA,QAAQ,CAAC,OAAO,GAAG,OAAO,CAAC;QAC/B;AACJ,IAAA,CAAC;AAED,IAAA,KAAK,CAAC,KAAK,CAAC,YAAY,EAAE,IAAI,CAAC;AAE/B,IAAA,OAAO,MAAM,WAAW,CAAC,YAAY,CAAC;AAC1C;AAEM,SAAU,cAAc,CAAC,QAAyB,EAAE,OAAe,EAAA;IACrE,OAAO,KAAK,CAAC,QAAQ,EAAE,qBAAqB,CAAC,OAAO,CAAC,CAAC;AAC1D;;;;"}
1
+ {"version":3,"file":"delay.mjs","sources":["../../../src/utils/delay.ts"],"sourcesContent":["import { cancelFrame, frame } from \"../frameloop\"\nimport { time } from \"../frameloop/sync-time\"\nimport type { FrameData } from \"../frameloop/types\"\nimport { secondsToMilliseconds } from \"motion-utils\"\nimport { addToScope, bindToScope } from \"../scope/active\"\n\nexport type DelayedFunction = (overshoot: number) => void\n\n/**\n * Timeout defined in ms\n */\nexport function delay(callback: DelayedFunction, timeout: number) {\n const start = time.now()\n callback = bindToScope(callback)\n\n const checkElapsed = ({ timestamp }: FrameData) => {\n const elapsed = timestamp - start\n\n if (elapsed >= timeout) {\n cancelFrame(checkElapsed)\n callback(elapsed - timeout)\n }\n }\n\n frame.setup(checkElapsed, true)\n\n return addToScope(() => cancelFrame(checkElapsed))\n}\n\nexport function delayInSeconds(callback: DelayedFunction, timeout: number) {\n return delay(callback, secondsToMilliseconds(timeout))\n}\n"],"names":[],"mappings":";;;;;AAQA;;AAEG;AACG,SAAU,KAAK,CAAC,QAAyB,EAAE,OAAe,EAAA;AAC5D,IAAA,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE;AACxB,IAAA,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC;AAEhC,IAAA,MAAM,YAAY,GAAG,CAAC,EAAE,SAAS,EAAa,KAAI;AAC9C,QAAA,MAAM,OAAO,GAAG,SAAS,GAAG,KAAK;AAEjC,QAAA,IAAI,OAAO,IAAI,OAAO,EAAE;YACpB,WAAW,CAAC,YAAY,CAAC;AACzB,YAAA,QAAQ,CAAC,OAAO,GAAG,OAAO,CAAC;QAC/B;AACJ,IAAA,CAAC;AAED,IAAA,KAAK,CAAC,KAAK,CAAC,YAAY,EAAE,IAAI,CAAC;IAE/B,OAAO,UAAU,CAAC,MAAM,WAAW,CAAC,YAAY,CAAC,CAAC;AACtD;AAEM,SAAU,cAAc,CAAC,QAAyB,EAAE,OAAe,EAAA;IACrE,OAAO,KAAK,CAAC,QAAQ,EAAE,qBAAqB,CAAC,OAAO,CAAC,CAAC;AAC1D;;;;"}
@@ -1,3 +1,5 @@
1
+ import { activeScope } from '../scope/active.mjs';
2
+
1
3
  function resolveElements(elementOrSelector, scope, selectorCache) {
2
4
  if (elementOrSelector == null) {
3
5
  return [];
@@ -6,10 +8,9 @@ function resolveElements(elementOrSelector, scope, selectorCache) {
6
8
  return [elementOrSelector];
7
9
  }
8
10
  else if (typeof elementOrSelector === "string") {
9
- let root = document;
10
- if (scope) {
11
- root = scope.current;
12
- }
11
+ const root = scope
12
+ ? scope.current
13
+ : activeScope.current?.root || document;
13
14
  const elements = selectorCache?.[elementOrSelector] ??
14
15
  root.querySelectorAll(elementOrSelector);
15
16
  return elements ? Array.from(elements) : [];
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-elements.mjs","sources":["../../../src/utils/resolve-elements.ts"],"sourcesContent":["export type ElementOrSelector =\n | Element\n | Element[]\n | NodeListOf<Element>\n | string\n | null\n | undefined\n\nexport interface WithQuerySelectorAll {\n querySelectorAll: Element[\"querySelectorAll\"]\n}\n\nexport interface AnimationScope<T = any> {\n readonly current: T\n animations: any[] // TODO: Refactor to types package AnimationPlaybackControls[]\n}\n\nexport interface SelectorCache {\n [key: string]: NodeListOf<Element>\n}\n\nexport function resolveElements(\n elementOrSelector: ElementOrSelector,\n scope?: AnimationScope,\n selectorCache?: SelectorCache\n): Element[] {\n if (elementOrSelector == null) {\n return []\n }\n\n if (elementOrSelector instanceof EventTarget) {\n return [elementOrSelector]\n } else if (typeof elementOrSelector === \"string\") {\n let root: WithQuerySelectorAll = document\n\n if (scope) {\n root = scope.current\n }\n\n const elements =\n selectorCache?.[elementOrSelector] ??\n root.querySelectorAll(elementOrSelector)\n\n return elements ? Array.from(elements) : []\n }\n\n return Array.from(elementOrSelector).filter(\n (element): element is Element => element != null\n )\n}\n"],"names":[],"mappings":"SAqBgB,eAAe,CAC3B,iBAAoC,EACpC,KAAsB,EACtB,aAA6B,EAAA;AAE7B,IAAA,IAAI,iBAAiB,IAAI,IAAI,EAAE;AAC3B,QAAA,OAAO,EAAE;IACb;AAEA,IAAA,IAAI,iBAAiB,YAAY,WAAW,EAAE;QAC1C,OAAO,CAAC,iBAAiB,CAAC;IAC9B;AAAO,SAAA,IAAI,OAAO,iBAAiB,KAAK,QAAQ,EAAE;QAC9C,IAAI,IAAI,GAAyB,QAAQ;QAEzC,IAAI,KAAK,EAAE;AACP,YAAA,IAAI,GAAG,KAAK,CAAC,OAAO;QACxB;AAEA,QAAA,MAAM,QAAQ,GACV,aAAa,GAAG,iBAAiB,CAAC;AAClC,YAAA,IAAI,CAAC,gBAAgB,CAAC,iBAAiB,CAAC;AAE5C,QAAA,OAAO,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE;IAC/C;AAEA,IAAA,OAAO,KAAK,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,MAAM,CACvC,CAAC,OAAO,KAAyB,OAAO,IAAI,IAAI,CACnD;AACL;;;;"}
1
+ {"version":3,"file":"resolve-elements.mjs","sources":["../../../src/utils/resolve-elements.ts"],"sourcesContent":["import { activeScope } from \"../scope/active\"\n\nexport type ElementOrSelector =\n | Element\n | Element[]\n | NodeListOf<Element>\n | string\n | null\n | undefined\n\nexport interface WithQuerySelectorAll {\n querySelectorAll: Element[\"querySelectorAll\"]\n}\n\nexport interface AnimationScope<T = any> {\n readonly current: T\n animations: any[] // TODO: Refactor to types package AnimationPlaybackControls[]\n}\n\nexport interface SelectorCache {\n [key: string]: NodeListOf<Element>\n}\n\nexport function resolveElements(\n elementOrSelector: ElementOrSelector,\n scope?: AnimationScope,\n selectorCache?: SelectorCache\n): Element[] {\n if (elementOrSelector == null) {\n return []\n }\n\n if (elementOrSelector instanceof EventTarget) {\n return [elementOrSelector]\n } else if (typeof elementOrSelector === \"string\") {\n const root: WithQuerySelectorAll = scope\n ? scope.current\n : activeScope.current?.root || document\n\n const elements =\n selectorCache?.[elementOrSelector] ??\n root.querySelectorAll(elementOrSelector)\n\n return elements ? Array.from(elements) : []\n }\n\n return Array.from(elementOrSelector).filter(\n (element): element is Element => element != null\n )\n}\n"],"names":[],"mappings":";;SAuBgB,eAAe,CAC3B,iBAAoC,EACpC,KAAsB,EACtB,aAA6B,EAAA;AAE7B,IAAA,IAAI,iBAAiB,IAAI,IAAI,EAAE;AAC3B,QAAA,OAAO,EAAE;IACb;AAEA,IAAA,IAAI,iBAAiB,YAAY,WAAW,EAAE;QAC1C,OAAO,CAAC,iBAAiB,CAAC;IAC9B;AAAO,SAAA,IAAI,OAAO,iBAAiB,KAAK,QAAQ,EAAE;QAC9C,MAAM,IAAI,GAAyB;cAC7B,KAAK,CAAC;cACN,WAAW,CAAC,OAAO,EAAE,IAAI,IAAI,QAAQ;AAE3C,QAAA,MAAM,QAAQ,GACV,aAAa,GAAG,iBAAiB,CAAC;AAClC,YAAA,IAAI,CAAC,gBAAgB,CAAC,iBAAiB,CAAC;AAE5C,QAAA,OAAO,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE;IAC/C;AAEA,IAAA,OAAO,KAAK,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,MAAM,CACvC,CAAC,OAAO,KAAyB,OAAO,IAAI,IAAI,CACnD;AACL;;;;"}
@@ -1,4 +1,5 @@
1
1
  import { noop } from 'motion-utils';
2
+ import { addBuilderToScope } from '../scope/active.mjs';
2
3
  import { addToQueue } from './queue.mjs';
3
4
 
4
5
  class ViewTransitionBuilder {
@@ -168,7 +169,9 @@ class ViewTransitionBuilder {
168
169
  }
169
170
  }
170
171
  function animateView(update, options = {}) {
171
- return new ViewTransitionBuilder(update, options);
172
+ const builder = new ViewTransitionBuilder(update, options);
173
+ addBuilderToScope(builder);
174
+ return builder;
172
175
  }
173
176
 
174
177
  export { ViewTransitionBuilder, animateView };
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../../../src/view/index.ts"],"sourcesContent":["import { noop } from \"motion-utils\"\nimport type { GroupAnimation } from \"../animation/GroupAnimation\"\nimport { AnimationOptions, DOMKeyframesDefinition } from \"../animation/types\"\nimport { addToQueue } from \"./queue\"\nimport {\n ViewTransitionOptions,\n ViewTransitionTarget,\n ViewTransitionTargetDefinition,\n} from \"./types\"\nimport \"./types.global\"\n\n// Re-export the public view-transition types so they flow out through\n// motion-dom -> framer-motion -> motion alongside `animateView`.\nexport type * from \"./types\"\n\nexport class ViewTransitionBuilder {\n private currentSubject: ViewTransitionTargetDefinition = \"root\"\n\n targets = new Map<ViewTransitionTargetDefinition, ViewTransitionTarget>()\n\n /**\n * Definitions that must be resolved to elements (and assigned a\n * `view-transition-name`) rather than treated as pre-named layers.\n */\n resolveDefs = new Set<ViewTransitionTargetDefinition>()\n\n /**\n * Per-subject crop override: `true` forces the crop (clip + object-fit:\n * cover + animated corner radii) on, `false` forces it off. A subject with\n * no entry uses the default - crop only a genuine morph (a layer present in\n * both snapshots), so a fade-only enter/exit isn't clipped to nothing.\n */\n cropOverride = new Map<ViewTransitionTargetDefinition, boolean>()\n\n /**\n * Subjects paired with a different new-snapshot target (the second `.add()`\n * argument), so two distinct elements share one name and morph into each\n * other - a shared-element transition.\n */\n pairs = new Map<\n ViewTransitionTargetDefinition,\n ViewTransitionTargetDefinition\n >()\n\n /**\n * A `view-transition-class` to apply to each subject's resolved elements,\n * so authors can target the generated layers from CSS by class rather than\n * the opaque generated name.\n */\n classNames = new Map<ViewTransitionTargetDefinition, string>()\n\n /**\n * Subjects opted out of automatic group nesting via `.group(false)`. Their\n * layer stays a flat top-level group (`view-transition-group: none`) instead\n * of nesting under its DOM-ancestor layer - so it animates independently and\n * escapes an ancestor's clip/transform (e.g. an element that lifts out of a\n * card and flies across, which nesting would clip to the card).\n */\n flatGroups = new Set<ViewTransitionTargetDefinition>()\n\n update: () => void | Promise<void>\n\n options: ViewTransitionOptions\n\n notifyReady: (value: GroupAnimation) => void = noop\n\n notifyReject: (error: unknown) => void = noop\n\n private readyPromise = new Promise<GroupAnimation>((resolve, reject) => {\n this.notifyReady = resolve\n this.notifyReject = reject\n })\n\n constructor(\n update: () => void | Promise<void>,\n options: ViewTransitionOptions = {}\n ) {\n this.update = update\n this.options = {\n interrupt: \"wait\",\n ...options,\n }\n // Avoid an unhandled rejection when a failed transition has no\n // `.then(_, reject)` handler attached (e.g. fire-and-forget).\n this.readyPromise.catch(noop)\n addToQueue(this)\n }\n\n /**\n * Target elements resolved from a selector or Element, each assigned a\n * `view-transition-name` automatically.\n *\n * Passing a second target pairs them: the first is resolved in the old\n * snapshot and the second in the new, sharing one name so two *different*\n * elements morph into each other (e.g. `.add(card, \".modal\")`). Symmetric -\n * pass them the other way round to morph back.\n */\n add(\n subject: ViewTransitionTargetDefinition,\n newSubject?: ViewTransitionTargetDefinition\n ) {\n this.currentSubject = subject\n this.resolveDefs.add(subject)\n if (newSubject !== undefined) this.pairs.set(subject, newSubject)\n // Register the subject so it participates (and gets an automatic\n // layout/morph animation) even without an explicit enter/exit/layout.\n if (!this.targets.has(subject)) this.targets.set(subject, {})\n\n return this\n }\n\n /**\n * Control this subject's crop (clip + `object-fit: cover` + animated\n * corners). By default a subject auto-crops only when it actually morphs -\n * present in both snapshots (a survivor, or an `.add(a, b)` pair). A\n * fade-only enter/exit has no second box to crop against, so it's left to\n * the browser default; in particular the `overflow: clip` a crop adds would\n * otherwise clip a mis-sized enter/exit layer to nothing.\n *\n * `.crop(false)` forces the crop off (e.g. a text morph, where\n * `object-fit: cover` clips glyphs as the box grows); `.crop(true)` forces\n * it on for a non-morph the default wouldn't otherwise crop.\n */\n crop(enabled = true) {\n this.cropOverride.set(this.currentSubject, enabled)\n\n return this\n }\n\n /**\n * By default a subject's layer nests under its nearest DOM-ancestor layer\n * (`view-transition-group: contain`), so the ancestor's clip/transform/opacity\n * apply to it through the transition - mirroring how the DOM actually paints,\n * and letting a wrapper crop its child for the whole morph rather than only\n * once the live DOM takes back over. (Needs a browser that supports nested\n * view-transition groups; elsewhere it degrades to the flat default.)\n *\n * Call `.group(false)` to opt out: the layer stays flat and top-level, so it\n * animates independently and escapes an ancestor's clip - e.g. an element\n * that should lift out of a card and fly across, which nesting would clip.\n */\n group(enabled = true) {\n enabled\n ? this.flatGroups.delete(this.currentSubject)\n : this.flatGroups.add(this.currentSubject)\n\n return this\n }\n\n /**\n * Tag this subject's generated layers with a `view-transition-class`, so\n * they can be targeted from CSS - `::view-transition-group(.name)`,\n * `::view-transition-old/new(.name)`, `::view-transition-image-pair(.name)`\n * - without the opaque generated `view-transition-name`. Because `.add()`\n * can match many elements, a shared class targets them all at once (and,\n * for a pair, both ends). The escape hatch for z-index / custom keyframes\n * on a morph layer.\n */\n class(name: string) {\n this.classNames.set(this.currentSubject, name)\n\n return this\n }\n\n /**\n * Set the transition for this subject's morph. The morph is enabled\n * automatically by `.add()`; this just customises its timing (duration,\n * easing, a `delay`/`stagger`, …). On the implicit `root` subject it also\n * opts the page into the transition (the root crossfade).\n */\n layout(options: AnimationOptions = {}) {\n this.updateTarget(\"layout\", {}, options)\n\n return this\n }\n\n enter(keyframes: DOMKeyframesDefinition, options?: AnimationOptions) {\n this.updateTarget(\"enter\", keyframes, options)\n\n return this\n }\n\n exit(keyframes: DOMKeyframesDefinition, options?: AnimationOptions) {\n this.updateTarget(\"exit\", keyframes, options)\n\n return this\n }\n\n /**\n * Animate the new view directly, whether the element is appearing or\n * persisting (unlike `.enter()`, which only fires for a pure newcomer).\n * Pair with `.old()` for a crossfade or slide-through.\n */\n new(keyframes: DOMKeyframesDefinition, options?: AnimationOptions) {\n this.updateTarget(\"new\", keyframes, options)\n\n return this\n }\n\n /**\n * Animate the old view directly, whether the element is leaving or\n * persisting (unlike `.exit()`, which only fires for a pure leaver).\n */\n old(keyframes: DOMKeyframesDefinition, options?: AnimationOptions) {\n this.updateTarget(\"old\", keyframes, options)\n\n return this\n }\n\n updateTarget(\n target: \"enter\" | \"exit\" | \"layout\" | \"new\" | \"old\",\n keyframes: DOMKeyframesDefinition,\n options: AnimationOptions = {}\n ) {\n const { currentSubject, targets } = this\n\n if (!targets.has(currentSubject)) {\n targets.set(currentSubject, {})\n }\n\n const targetData = targets.get(currentSubject)!\n\n targetData[target] = { keyframes, options }\n }\n\n then(resolve: () => void, reject?: () => void) {\n return this.readyPromise.then(resolve, reject)\n }\n}\n\nexport function animateView(\n update: () => void | Promise<void>,\n options: ViewTransitionOptions = {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AAO,CAAC;AAE7C,QAAA,OAAO,IAAI;IACf;AAEA;;;;AAIG;IACH,GAAG,CAAC,SAAiC,EAAE,OAA0B,EAAA;QAC7D,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,SAAS,EAAE,OAAO,CAAC;AAE5C,QAAA,OAAO,IAAI;IACf;AAEA;;;AAGG;IACH,GAAG,CAAC,SAAiC,EAAE,OAA0B,EAAA;QAC7D,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,SAAS,EAAE,OAAO,CAAC;AAE5C,QAAA,OAAO,IAAI;IACf;AAEA,IAAA,YAAY,CACR,MAAmD,EACnD,SAAiC,EACjC,UAA4B,EAAE,EAAA;AAE9B,QAAA,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,GAAG,IAAI;QAExC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,EAAE;AAC9B,YAAA,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,EAAE,CAAC;QACnC;QAEA,MAAM,UAAU,GAAG,OAAO,CAAC,GAAG,CAAC,cAAc,CAAE;QAE/C,UAAU,CAAC,MAAM,CAAC,GAAG,EAAE,SAAS,EAAE,OAAO,EAAE;IAC/C;IAEA,IAAI,CAAC,OAAmB,EAAE,MAAmB,EAAA;QACzC,OAAO,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC;IAClD;AACH;SAEe,WAAW,CACvB,MAAkC,EAClC,UAAiC,EAAE,EAAA;AAEnC,IAAA,OAAO,IAAI,qBAAqB,CAAC,MAAM,EAAE,OAAO,CAAC;AACrD;;;;"}
1
+ {"version":3,"file":"index.mjs","sources":["../../../src/view/index.ts"],"sourcesContent":["import { noop } from \"motion-utils\"\nimport type { GroupAnimation } from \"../animation/GroupAnimation\"\nimport { AnimationOptions, DOMKeyframesDefinition } from \"../animation/types\"\nimport { addBuilderToScope } from \"../scope/active\"\nimport { addToQueue } from \"./queue\"\nimport {\n ViewTransitionOptions,\n ViewTransitionTarget,\n ViewTransitionTargetDefinition,\n} from \"./types\"\nimport \"./types.global\"\n\n// Re-export the public view-transition types so they flow out through\n// motion-dom -> framer-motion -> motion alongside `animateView`.\nexport type * from \"./types\"\n\nexport class ViewTransitionBuilder {\n private currentSubject: ViewTransitionTargetDefinition = \"root\"\n\n targets = new Map<ViewTransitionTargetDefinition, ViewTransitionTarget>()\n\n /**\n * Definitions that must be resolved to elements (and assigned a\n * `view-transition-name`) rather than treated as pre-named layers.\n */\n resolveDefs = new Set<ViewTransitionTargetDefinition>()\n\n /**\n * Per-subject crop override: `true` forces the crop (clip + object-fit:\n * cover + animated corner radii) on, `false` forces it off. A subject with\n * no entry uses the default - crop only a genuine morph (a layer present in\n * both snapshots), so a fade-only enter/exit isn't clipped to nothing.\n */\n cropOverride = new Map<ViewTransitionTargetDefinition, boolean>()\n\n /**\n * Subjects paired with a different new-snapshot target (the second `.add()`\n * argument), so two distinct elements share one name and morph into each\n * other - a shared-element transition.\n */\n pairs = new Map<\n ViewTransitionTargetDefinition,\n ViewTransitionTargetDefinition\n >()\n\n /**\n * A `view-transition-class` to apply to each subject's resolved elements,\n * so authors can target the generated layers from CSS by class rather than\n * the opaque generated name.\n */\n classNames = new Map<ViewTransitionTargetDefinition, string>()\n\n /**\n * Subjects opted out of automatic group nesting via `.group(false)`. Their\n * layer stays a flat top-level group (`view-transition-group: none`) instead\n * of nesting under its DOM-ancestor layer - so it animates independently and\n * escapes an ancestor's clip/transform (e.g. an element that lifts out of a\n * card and flies across, which nesting would clip to the card).\n */\n flatGroups = new Set<ViewTransitionTargetDefinition>()\n\n update: () => void | Promise<void>\n\n options: ViewTransitionOptions\n\n notifyReady: (value: GroupAnimation) => void = noop\n\n notifyReject: (error: unknown) => void = noop\n\n private readyPromise = new Promise<GroupAnimation>((resolve, reject) => {\n this.notifyReady = resolve\n this.notifyReject = reject\n })\n\n constructor(\n update: () => void | Promise<void>,\n options: ViewTransitionOptions = {}\n ) {\n this.update = update\n this.options = {\n interrupt: \"wait\",\n ...options,\n }\n // Avoid an unhandled rejection when a failed transition has no\n // `.then(_, reject)` handler attached (e.g. fire-and-forget).\n this.readyPromise.catch(noop)\n addToQueue(this)\n }\n\n /**\n * Target elements resolved from a selector or Element, each assigned a\n * `view-transition-name` automatically.\n *\n * Passing a second target pairs them: the first is resolved in the old\n * snapshot and the second in the new, sharing one name so two *different*\n * elements morph into each other (e.g. `.add(card, \".modal\")`). Symmetric -\n * pass them the other way round to morph back.\n */\n add(\n subject: ViewTransitionTargetDefinition,\n newSubject?: ViewTransitionTargetDefinition\n ) {\n this.currentSubject = subject\n this.resolveDefs.add(subject)\n if (newSubject !== undefined) this.pairs.set(subject, newSubject)\n // Register the subject so it participates (and gets an automatic\n // layout/morph animation) even without an explicit enter/exit/layout.\n if (!this.targets.has(subject)) this.targets.set(subject, {})\n\n return this\n }\n\n /**\n * Control this subject's crop (clip + `object-fit: cover` + animated\n * corners). By default a subject auto-crops only when it actually morphs -\n * present in both snapshots (a survivor, or an `.add(a, b)` pair). A\n * fade-only enter/exit has no second box to crop against, so it's left to\n * the browser default; in particular the `overflow: clip` a crop adds would\n * otherwise clip a mis-sized enter/exit layer to nothing.\n *\n * `.crop(false)` forces the crop off (e.g. a text morph, where\n * `object-fit: cover` clips glyphs as the box grows); `.crop(true)` forces\n * it on for a non-morph the default wouldn't otherwise crop.\n */\n crop(enabled = true) {\n this.cropOverride.set(this.currentSubject, enabled)\n\n return this\n }\n\n /**\n * By default a subject's layer nests under its nearest DOM-ancestor layer\n * (`view-transition-group: contain`), so the ancestor's clip/transform/opacity\n * apply to it through the transition - mirroring how the DOM actually paints,\n * and letting a wrapper crop its child for the whole morph rather than only\n * once the live DOM takes back over. (Needs a browser that supports nested\n * view-transition groups; elsewhere it degrades to the flat default.)\n *\n * Call `.group(false)` to opt out: the layer stays flat and top-level, so it\n * animates independently and escapes an ancestor's clip - e.g. an element\n * that should lift out of a card and fly across, which nesting would clip.\n */\n group(enabled = true) {\n enabled\n ? this.flatGroups.delete(this.currentSubject)\n : this.flatGroups.add(this.currentSubject)\n\n return this\n }\n\n /**\n * Tag this subject's generated layers with a `view-transition-class`, so\n * they can be targeted from CSS - `::view-transition-group(.name)`,\n * `::view-transition-old/new(.name)`, `::view-transition-image-pair(.name)`\n * - without the opaque generated `view-transition-name`. Because `.add()`\n * can match many elements, a shared class targets them all at once (and,\n * for a pair, both ends). The escape hatch for z-index / custom keyframes\n * on a morph layer.\n */\n class(name: string) {\n this.classNames.set(this.currentSubject, name)\n\n return this\n }\n\n /**\n * Set the transition for this subject's morph. The morph is enabled\n * automatically by `.add()`; this just customises its timing (duration,\n * easing, a `delay`/`stagger`, …). On the implicit `root` subject it also\n * opts the page into the transition (the root crossfade).\n */\n layout(options: AnimationOptions = {}) {\n this.updateTarget(\"layout\", {}, options)\n\n return this\n }\n\n enter(keyframes: DOMKeyframesDefinition, options?: AnimationOptions) {\n this.updateTarget(\"enter\", keyframes, options)\n\n return this\n }\n\n exit(keyframes: DOMKeyframesDefinition, options?: AnimationOptions) {\n this.updateTarget(\"exit\", keyframes, options)\n\n return this\n }\n\n /**\n * Animate the new view directly, whether the element is appearing or\n * persisting (unlike `.enter()`, which only fires for a pure newcomer).\n * Pair with `.old()` for a crossfade or slide-through.\n */\n new(keyframes: DOMKeyframesDefinition, options?: AnimationOptions) {\n this.updateTarget(\"new\", keyframes, options)\n\n return this\n }\n\n /**\n * Animate the old view directly, whether the element is leaving or\n * persisting (unlike `.exit()`, which only fires for a pure leaver).\n */\n old(keyframes: DOMKeyframesDefinition, options?: AnimationOptions) {\n this.updateTarget(\"old\", keyframes, options)\n\n return this\n }\n\n updateTarget(\n target: \"enter\" | \"exit\" | \"layout\" | \"new\" | \"old\",\n keyframes: DOMKeyframesDefinition,\n options: AnimationOptions = {}\n ) {\n const { currentSubject, targets } = this\n\n if (!targets.has(currentSubject)) {\n targets.set(currentSubject, {})\n }\n\n const targetData = targets.get(currentSubject)!\n\n targetData[target] = { keyframes, options }\n }\n\n then(resolve: () => void, reject?: () => void) {\n return this.readyPromise.then(resolve, reject)\n }\n}\n\nexport function animateView(\n update: () => void | Promise<void>,\n options: ViewTransitionOptions = {}\n) {\n const builder = new ViewTransitionBuilder(update, options)\n addBuilderToScope(builder)\n return builder\n}\n"],"names":[],"mappings":";;;;MAgBa,qBAAqB,CAAA;IA0D9B,WAAA,CACI,MAAkC,EAClC,OAAA,GAAiC,EAAE,EAAA;QA3D/B,IAAA,CAAA,cAAc,GAAmC,MAAM;AAE/D,QAAA,IAAA,CAAA,OAAO,GAAG,IAAI,GAAG,EAAwD;AAEzE;;;AAGG;AACH,QAAA,IAAA,CAAA,WAAW,GAAG,IAAI,GAAG,EAAkC;AAEvD;;;;;AAKG;AACH,QAAA,IAAA,CAAA,YAAY,GAAG,IAAI,GAAG,EAA2C;AAEjE;;;;AAIG;AACH,QAAA,IAAA,CAAA,KAAK,GAAG,IAAI,GAAG,EAGZ;AAEH;;;;AAIG;AACH,QAAA,IAAA,CAAA,UAAU,GAAG,IAAI,GAAG,EAA0C;AAE9D;;;;;;AAMG;AACH,QAAA,IAAA,CAAA,UAAU,GAAG,IAAI,GAAG,EAAkC;QAMtD,IAAA,CAAA,WAAW,GAAoC,IAAI;QAEnD,IAAA,CAAA,YAAY,GAA6B,IAAI;QAErC,IAAA,CAAA,YAAY,GAAG,IAAI,OAAO,CAAiB,CAAC,OAAO,EAAE,MAAM,KAAI;AACnE,YAAA,IAAI,CAAC,WAAW,GAAG,OAAO;AAC1B,YAAA,IAAI,CAAC,YAAY,GAAG,MAAM;AAC9B,QAAA,CAAC,CAAC;AAME,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM;QACpB,IAAI,CAAC,OAAO,GAAG;AACX,YAAA,SAAS,EAAE,MAAM;AACjB,YAAA,GAAG,OAAO;SACb;;;AAGD,QAAA,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,IAAI,CAAC;QAC7B,UAAU,CAAC,IAAI,CAAC;IACpB;AAEA;;;;;;;;AAQG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