@appfunnel-dev/sdk 2.0.0 → 2.0.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/CHANGELOG.md +41 -3
- package/dist/{checkout-BYcOfyg_.d.ts → checkout-B1K6ozwk.d.ts} +6 -0
- package/dist/{checkout-BM1T-u6_.d.cts → checkout-C4tFUEdF.d.cts} +6 -0
- package/dist/{chunk-MBTHQP4Z.cjs → chunk-DTSLJ24T.cjs} +11 -3
- package/dist/chunk-DTSLJ24T.cjs.map +1 -0
- package/dist/{chunk-NA7DRFOA.cjs → chunk-E7JXWUNV.cjs} +55 -17
- package/dist/chunk-E7JXWUNV.cjs.map +1 -0
- package/dist/{chunk-KVMNVX6J.js → chunk-USAECFWO.js} +11 -3
- package/dist/chunk-USAECFWO.js.map +1 -0
- package/dist/{chunk-PN7CRJAF.js → chunk-WCBVSZHJ.js} +55 -17
- package/dist/chunk-WCBVSZHJ.js.map +1 -0
- package/dist/driver-paddle.cjs +14 -14
- package/dist/driver-paddle.d.cts +1 -1
- package/dist/driver-paddle.d.ts +1 -1
- package/dist/driver-paddle.js +1 -1
- package/dist/driver-stripe.cjs +15 -15
- package/dist/driver-stripe.d.cts +1 -1
- package/dist/driver-stripe.d.ts +1 -1
- package/dist/driver-stripe.js +2 -2
- package/dist/index.cjs +78 -67
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +25 -6
- package/dist/index.d.ts +25 -6
- package/dist/index.js +13 -2
- package/dist/index.js.map +1 -1
- package/dist/{manifest-BajvtPWs.d.cts → manifest-Dp1oRvqp.d.cts} +23 -0
- package/dist/{manifest-BajvtPWs.d.ts → manifest-Dp1oRvqp.d.ts} +23 -0
- package/dist/manifest-entry.cjs +9 -1
- package/dist/manifest-entry.cjs.map +1 -1
- package/dist/manifest-entry.d.cts +15 -2
- package/dist/manifest-entry.d.ts +15 -2
- package/dist/manifest-entry.js +9 -1
- package/dist/manifest-entry.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-KVMNVX6J.js.map +0 -1
- package/dist/chunk-MBTHQP4Z.cjs.map +0 -1
- package/dist/chunk-NA7DRFOA.cjs.map +0 -1
- package/dist/chunk-PN7CRJAF.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/state/variableStore.ts","../src/state/store.ts","../src/state/context.ts","../src/tracking/tracking.ts","../src/tracking/bus.ts","../src/i18n/translation.ts","../src/commerce/catalog.ts","../src/modals/registry.tsx","../../../node_modules/framer-motion/dist/es/context/LayoutGroupContext.mjs","../../../node_modules/framer-motion/src/utils/use-constant.ts","../../../node_modules/framer-motion/src/utils/is-browser.ts","../../../node_modules/framer-motion/src/utils/use-isomorphic-effect.ts","../../../node_modules/framer-motion/src/context/PresenceContext.ts","../../../node_modules/motion-utils/src/array.ts","../../../node_modules/motion-utils/src/clamp.ts","../../../node_modules/motion-utils/src/format-error-message.ts","../../../node_modules/motion-utils/src/errors.ts","../../../node_modules/motion-utils/src/global-config.ts","../../../node_modules/motion-utils/src/is-numerical-string.ts","../../../node_modules/motion-utils/src/is-object.ts","../../../node_modules/motion-utils/src/is-zero-value-string.ts","../../../node_modules/motion-utils/src/memo.ts","../../../node_modules/motion-utils/src/noop.ts","../../../node_modules/motion-utils/src/pipe.ts","../../../node_modules/motion-utils/src/progress.ts","../../../node_modules/motion-utils/src/subscription-manager.ts","../../../node_modules/motion-utils/src/time-conversion.ts","../../../node_modules/motion-utils/src/velocity-per-second.ts","../../../node_modules/motion-utils/src/warn-once.ts","../../../node_modules/motion-utils/src/easing/cubic-bezier.ts","../../../node_modules/motion-utils/src/easing/modifiers/mirror.ts","../../../node_modules/motion-utils/src/easing/modifiers/reverse.ts","../../../node_modules/motion-utils/src/easing/back.ts","../../../node_modules/motion-utils/src/easing/anticipate.ts","../../../node_modules/motion-utils/src/easing/circ.ts","../../../node_modules/motion-utils/src/easing/ease.ts","../../../node_modules/motion-utils/src/easing/utils/is-easing-array.ts","../../../node_modules/motion-utils/src/easing/utils/is-bezier-definition.ts","../../../node_modules/motion-utils/src/easing/utils/map.ts","../../../node_modules/motion-dom/src/frameloop/order.ts","../../../node_modules/motion-dom/src/frameloop/render-step.ts","../../../node_modules/motion-dom/src/frameloop/batcher.ts","../../../node_modules/motion-dom/src/frameloop/frame.ts","../../../node_modules/motion-dom/src/frameloop/sync-time.ts","../../../node_modules/motion-dom/src/animation/utils/is-css-variable.ts","../../../node_modules/motion-dom/src/value/types/numbers/index.ts","../../../node_modules/motion-dom/src/value/types/utils/sanitize.ts","../../../node_modules/motion-dom/src/value/types/utils/float-regex.ts","../../../node_modules/motion-dom/src/value/types/utils/is-nullish.ts","../../../node_modules/motion-dom/src/value/types/utils/single-color-regex.ts","../../../node_modules/motion-dom/src/value/types/color/utils.ts","../../../node_modules/motion-dom/src/value/types/color/rgba.ts","../../../node_modules/motion-dom/src/value/types/color/hex.ts","../../../node_modules/motion-dom/src/value/types/numbers/units.ts","../../../node_modules/motion-dom/src/value/types/color/hsla.ts","../../../node_modules/motion-dom/src/value/types/color/index.ts","../../../node_modules/motion-dom/src/value/types/utils/color-regex.ts","../../../node_modules/motion-dom/src/value/types/complex/index.ts","../../../node_modules/motion-dom/src/value/types/color/hsla-to-rgba.ts","../../../node_modules/motion-dom/src/utils/mix/immediate.ts","../../../node_modules/motion-dom/src/utils/mix/number.ts","../../../node_modules/motion-dom/src/utils/mix/color.ts","../../../node_modules/motion-dom/src/utils/mix/visibility.ts","../../../node_modules/motion-dom/src/utils/mix/complex.ts","../../../node_modules/motion-dom/src/utils/mix/index.ts","../../../node_modules/motion-dom/src/animation/drivers/frame.ts","../../../node_modules/motion-dom/src/animation/waapi/utils/linear.ts","../../../node_modules/motion-dom/src/animation/generators/utils/calc-duration.ts","../../../node_modules/motion-dom/src/animation/generators/utils/create-generator-easing.ts","../../../node_modules/motion-dom/src/animation/generators/spring.ts","../../../node_modules/motion-dom/src/animation/generators/utils/velocity.ts","../../../node_modules/motion-dom/src/animation/generators/inertia.ts","../../../node_modules/motion-dom/src/utils/interpolate.ts","../../../node_modules/motion-dom/src/animation/keyframes/offsets/fill.ts","../../../node_modules/motion-dom/src/animation/keyframes/offsets/default.ts","../../../node_modules/motion-dom/src/animation/keyframes/offsets/time.ts","../../../node_modules/motion-dom/src/animation/generators/keyframes.ts","../../../node_modules/motion-dom/src/animation/keyframes/get-final.ts","../../../node_modules/motion-dom/src/animation/utils/replace-transition-type.ts","../../../node_modules/motion-dom/src/animation/utils/WithPromise.ts","../../../node_modules/motion-dom/src/animation/JSAnimation.ts","../../../node_modules/motion-dom/src/animation/keyframes/utils/fill-wildcards.ts","../../../node_modules/motion-dom/src/render/dom/parse-transform.ts","../../../node_modules/motion-dom/src/render/utils/keys-transform.ts","../../../node_modules/motion-dom/src/animation/keyframes/utils/unit-conversion.ts","../../../node_modules/motion-dom/src/animation/keyframes/KeyframesResolver.ts","../../../node_modules/motion-dom/src/render/dom/is-css-var.ts","../../../node_modules/motion-dom/src/render/dom/style-set.ts","../../../node_modules/motion-dom/src/utils/supports/flags.ts","../../../node_modules/motion-dom/src/utils/supports/memo.ts","../../../node_modules/motion-dom/src/utils/supports/scroll-timeline.ts","../../../node_modules/motion-dom/src/utils/supports/linear-easing.ts","../../../node_modules/motion-dom/src/animation/waapi/easing/cubic-bezier.ts","../../../node_modules/motion-dom/src/animation/waapi/easing/supported.ts","../../../node_modules/motion-dom/src/animation/waapi/easing/map-easing.ts","../../../node_modules/motion-dom/src/animation/waapi/start-waapi-animation.ts","../../../node_modules/motion-dom/src/animation/generators/utils/is-generator.ts","../../../node_modules/motion-dom/src/animation/waapi/utils/apply-generator.ts","../../../node_modules/motion-dom/src/animation/NativeAnimation.ts","../../../node_modules/motion-dom/src/animation/waapi/utils/unsupported-easing.ts","../../../node_modules/motion-dom/src/animation/NativeAnimationExtended.ts","../../../node_modules/motion-dom/src/animation/utils/is-animatable.ts","../../../node_modules/motion-dom/src/animation/utils/can-animate.ts","../../../node_modules/motion-dom/src/animation/utils/make-animation-instant.ts","../../../node_modules/motion-dom/src/animation/waapi/utils/accelerated-values.ts","../../../node_modules/motion-dom/src/animation/waapi/utils/is-browser-color.ts","../../../node_modules/motion-dom/src/animation/waapi/supports/waapi.ts","../../../node_modules/motion-dom/src/animation/AsyncMotionValueAnimation.ts","../../../node_modules/motion-dom/src/animation/utils/calc-child-stagger.ts","../../../node_modules/motion-dom/src/value/index.ts","../../../node_modules/motion-dom/src/animation/utils/resolve-transition.ts","../../../node_modules/motion-dom/src/animation/utils/get-value-transition.ts","../../../node_modules/motion-dom/src/animation/utils/default-transitions.ts","../../../node_modules/motion-dom/src/animation/utils/is-transition-defined.ts","../../../node_modules/motion-dom/src/animation/interfaces/motion-value.ts","../../../node_modules/motion-dom/src/animation/utils/css-variables-conversion.ts","../../../node_modules/motion-dom/src/render/utils/resolve-variants.ts","../../../node_modules/motion-dom/src/render/utils/resolve-dynamic-variants.ts","../../../node_modules/motion-dom/src/render/utils/keys-position.ts","../../../node_modules/motion-dom/src/render/utils/is-keyframes-target.ts","../../../node_modules/motion-dom/src/render/utils/setters.ts","../../../node_modules/motion-dom/src/value/utils/is-motion-value.ts","../../../node_modules/motion-dom/src/value/will-change/is.ts","../../../node_modules/motion-dom/src/value/will-change/add-will-change.ts","../../../node_modules/motion-dom/src/render/dom/utils/camel-to-dash.ts","../../../node_modules/motion-dom/src/animation/optimized-appear/data-id.ts","../../../node_modules/motion-dom/src/animation/optimized-appear/get-appear-id.ts","../../../node_modules/motion-dom/src/animation/interfaces/visual-element-target.ts","../../../node_modules/motion-dom/src/animation/interfaces/visual-element-variant.ts","../../../node_modules/motion-dom/src/animation/interfaces/visual-element.ts","../../../node_modules/motion-dom/src/value/types/auto.ts","../../../node_modules/motion-dom/src/value/types/test.ts","../../../node_modules/motion-dom/src/value/types/dimensions.ts","../../../node_modules/motion-dom/src/animation/keyframes/utils/is-none.ts","../../../node_modules/motion-dom/src/value/types/complex/filter.ts","../../../node_modules/motion-dom/src/value/types/complex/mask.ts","../../../node_modules/motion-dom/src/value/types/int.ts","../../../node_modules/motion-dom/src/value/types/maps/transform.ts","../../../node_modules/motion-dom/src/value/types/maps/number.ts","../../../node_modules/motion-dom/src/value/types/maps/defaults.ts","../../../node_modules/motion-dom/src/value/types/utils/animatable-none.ts","../../../node_modules/motion-dom/src/animation/keyframes/utils/make-none-animatable.ts","../../../node_modules/motion-dom/src/animation/keyframes/DOMKeyframesResolver.ts","../../../node_modules/motion-dom/src/utils/border-radius.ts","../../../node_modules/motion-dom/src/utils/resolve-elements.ts","../../../node_modules/motion-dom/src/value/types/utils/get-as-type.ts","../../../node_modules/motion-dom/src/utils/is-html-element.ts","../../../node_modules/motion-dom/src/frameloop/microtask.ts","../../../node_modules/motion-dom/src/gestures/drag/state/is-active.ts","../../../node_modules/motion-dom/src/gestures/utils/setup.ts","../../../node_modules/motion-dom/src/gestures/hover.ts","../../../node_modules/motion-dom/src/gestures/utils/is-node-or-child.ts","../../../node_modules/motion-dom/src/gestures/utils/is-primary-pointer.ts","../../../node_modules/motion-dom/src/gestures/press/utils/is-keyboard-accessible.ts","../../../node_modules/motion-dom/src/gestures/press/utils/state.ts","../../../node_modules/motion-dom/src/gestures/press/utils/keyboard.ts","../../../node_modules/motion-dom/src/gestures/press/index.ts","../../../node_modules/motion-dom/src/value/types/utils/find.ts","../../../node_modules/motion-dom/src/projection/geometry/models.ts","../../../node_modules/motion-dom/src/render/store.ts","../../../node_modules/motion-dom/src/render/utils/is-animation-controls.ts","../../../node_modules/motion-dom/src/render/utils/is-variant-label.ts","../../../node_modules/motion-dom/src/render/utils/variant-props.ts","../../../node_modules/motion-dom/src/render/utils/is-controlling-variants.ts","../../../node_modules/motion-dom/src/render/utils/motion-values.ts","../../../node_modules/motion-dom/src/render/utils/reduced-motion/state.ts","../../../node_modules/motion-dom/src/render/utils/reduced-motion/index.ts","../../../node_modules/motion-dom/src/render/VisualElement.ts","../../../node_modules/motion-dom/src/render/dom/DOMVisualElement.ts","../../../node_modules/motion-dom/src/render/Feature.ts","../../../node_modules/motion-dom/src/projection/geometry/conversion.ts","../../../node_modules/motion-dom/src/projection/utils/measure.ts","../../../node_modules/motion-dom/src/render/html/utils/build-transform.ts","../../../node_modules/motion-dom/src/render/html/utils/build-styles.ts","../../../node_modules/motion-dom/src/render/html/utils/render.ts","../../../node_modules/motion-dom/src/projection/styles/scale-border-radius.ts","../../../node_modules/motion-dom/src/projection/styles/scale-box-shadow.ts","../../../node_modules/motion-dom/src/projection/styles/scale-correction.ts","../../../node_modules/motion-dom/src/render/utils/is-forced-motion-value.ts","../../../node_modules/motion-dom/src/render/html/utils/scrape-motion-values.ts","../../../node_modules/motion-dom/src/render/html/HTMLVisualElement.ts","../../../node_modules/motion-dom/src/render/svg/utils/path.ts","../../../node_modules/motion-dom/src/render/svg/utils/build-attrs.ts","../../../node_modules/motion-dom/src/render/svg/utils/camel-case-attrs.ts","../../../node_modules/motion-dom/src/render/svg/utils/is-svg-tag.ts","../../../node_modules/motion-dom/src/render/svg/utils/render.ts","../../../node_modules/motion-dom/src/render/svg/utils/scrape-motion-values.ts","../../../node_modules/motion-dom/src/render/svg/SVGVisualElement.ts","../../../node_modules/motion-dom/src/render/utils/get-variant-context.ts","../../../node_modules/motion-dom/src/render/utils/shallow-compare.ts","../../../node_modules/motion-dom/src/render/utils/animation-state.ts","../../../node_modules/motion-dom/src/events/add-dom-event.ts","../../../node_modules/motion-dom/src/value/utils/resolve-motion-value.ts","../../../node_modules/framer-motion/src/context/MotionConfigContext.tsx","../../../node_modules/framer-motion/src/context/LazyContext.ts","../../../node_modules/framer-motion/src/motion/features/definitions.ts","../../../node_modules/framer-motion/src/motion/features/load-features.ts","../../../node_modules/framer-motion/src/components/LazyMotion/index.tsx","../../../node_modules/framer-motion/src/motion/utils/valid-prop.ts","../../../node_modules/framer-motion/src/render/dom/utils/filter-props.ts","../../../node_modules/framer-motion/src/context/MotionContext/index.ts","../../../node_modules/framer-motion/src/context/MotionContext/utils.ts","../../../node_modules/framer-motion/src/context/MotionContext/create.ts","../../../node_modules/framer-motion/src/render/html/utils/create-render-state.ts","../../../node_modules/framer-motion/src/render/html/use-props.ts","../../../node_modules/framer-motion/src/render/svg/utils/create-render-state.ts","../../../node_modules/framer-motion/src/render/svg/use-props.ts","../../../node_modules/framer-motion/src/render/svg/lowercase-elements.ts","../../../node_modules/framer-motion/src/render/dom/utils/is-svg-component.ts","../../../node_modules/framer-motion/src/render/dom/use-render.ts","../../../node_modules/framer-motion/src/motion/utils/use-visual-state.ts","../../../node_modules/framer-motion/src/render/html/use-html-visual-state.ts","../../../node_modules/framer-motion/src/render/svg/use-svg-visual-state.ts","../../../node_modules/framer-motion/src/motion/utils/symbol.ts","../../../node_modules/framer-motion/src/motion/utils/use-motion-ref.ts","../../../node_modules/framer-motion/src/utils/is-ref-object.ts","../../../node_modules/framer-motion/src/motion/utils/use-visual-element.ts","../../../node_modules/framer-motion/src/motion/index.tsx","../../../node_modules/framer-motion/src/render/components/create-proxy.ts","../../../node_modules/framer-motion/src/render/components/m/proxy.ts","../../../node_modules/framer-motion/src/render/dom/create-visual-element.ts","../../../node_modules/framer-motion/src/motion/features/animation/index.ts","../../../node_modules/framer-motion/src/motion/features/animation/exit.ts","../../../node_modules/framer-motion/src/motion/features/animations.ts","../../../node_modules/framer-motion/src/events/event-info.ts","../../../node_modules/framer-motion/src/gestures/hover.ts","../../../node_modules/framer-motion/src/gestures/focus.ts","../../../node_modules/framer-motion/src/gestures/press.ts","../../../node_modules/framer-motion/src/motion/features/viewport/observers.ts","../../../node_modules/framer-motion/src/motion/features/viewport/index.ts","../../../node_modules/framer-motion/src/motion/features/gestures.ts","../../../node_modules/framer-motion/src/render/dom/features-animation.ts","../../../node_modules/framer-motion/src/utils/reduced-motion/use-reduced-motion.ts","../src/modals/sheet.tsx","../src/commerce/checkout.tsx","../../../node_modules/sonner/dist/index.mjs","../src/toast/toast.tsx","../src/util/email.ts","../src/state/namespaces.ts","../src/flow/flow.tsx"],"names":["m","now","id","createContext","createElement","useContext","useMemo","useEffect","useCallback","ease","frameData","process","alpha","alphaType","progress","color","mixNumber","mixNumberImmediate","scale","undampedFreq","current","keyframes","spring","createSpring","interpolate","percent","motionValue","keyframesGenerator","KeyframeResolver","DefaultKeyframeResolver","animations","number","v","getAnimatableNone","isBrowser","checkIsControllingVariants","checkIsVariantNode","getComputedStyle","isSVGTag","scrapeMotionValuesFromProps","scrapeHTMLMotionValuesFromProps","context","featureDefinitions","useState","useRef","jsx","Fragment","viewport","vh","useIsomorphicLayoutEffect","useLayoutEffect","React","toast","height","heights","_toast_classNames","_toast_classNames1","defaultOffset","offset","Toaster","toasts","position","index","value","Activity","React2","page"],"mappings":";;;;;;;;;;;AAgBO,IAAM,gBAAN,MAAoB;AAAA,EAMzB,YAAY,OAAA,EAAwC;AAJpD,IAAA,IAAA,CAAQ,SAAA,uBAAgB,GAAA,EAAoB;AAE5C;AAAA,IAAA,IAAA,CAAQ,cAAwB,EAAC;AAG/B,IAAA,IAAA,CAAK,KAAA,GAAQ,EAAE,GAAG,OAAA,EAAQ;AAAA,EAC5B;AAAA,EAEA,QAAA,GAA0C;AACxC,IAAA,OAAO,IAAA,CAAK,KAAA;AAAA,EACd;AAAA,EAEA,IAAI,GAAA,EAA4B;AAC9B,IAAA,OAAO,IAAA,CAAK,MAAM,GAAG,CAAA;AAAA,EACvB;AAAA,EAEA,GAAA,CAAI,KAAa,KAAA,EAA4B;AAC3C,IAAA,IAAI,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA,KAAM,KAAA,EAAO;AAC/B,IAAA,IAAA,CAAK,KAAA,GAAQ,EAAE,GAAG,IAAA,CAAK,OAAO,CAAC,GAAG,GAAG,KAAA,EAAM;AAC3C,IAAA,IAAA,CAAK,WAAA,GAAc,CAAC,GAAG,CAAA;AACvB,IAAA,IAAA,CAAK,MAAA,EAAO;AAAA,EACd;AAAA,EAEA,SAAS,OAAA,EAAuF;AAC9F,IAAA,MAAM,OAAO,IAAA,CAAK,KAAA;AACl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,IAAA;AACzB;AAgBO,SAAS,gBAAA,GAAkC;AAChD,EAAA,MAAM,GAAA,GAAMF,WAAW,oBAAoB,CAAA;AAC3C,EAAA,IAAI,CAAC,GAAA,EAAK,MAAM,IAAI,MAAM,mDAAmD,CAAA;AAC7E,EAAA,OAAO,GAAA;AACT","file":"chunk-PN7CRJAF.js","sourcesContent":["import type { VariableValue } from '../types'\n\n/**\n * External variable store for funnel variables — the flat, reactive key/value\n * store under the v2 namespaces. Components subscribe selectively via\n * `useSyncExternalStore`, so only components depending on changed keys re-render.\n * (Seeding lives in {@link ./store}.`createFunnelStore`.)\n */\ninterface ScopedListener {\n listener: () => void\n /** Exact keys to watch, or null for all changes */\n keys: string[] | null\n /** Prefix to watch (e.g. 'answers.'), or null for all */\n prefix: string | null\n}\n\nexport class VariableStore {\n private state: Record<string, VariableValue>\n private listeners = new Set<ScopedListener>()\n /** Tracks which keys changed in the last mutation — used by scoped notify */\n private changedKeys: string[] = []\n\n constructor(initial: Record<string, VariableValue>) {\n this.state = { ...initial }\n }\n\n getState(): Record<string, VariableValue> {\n return this.state\n }\n\n get(key: string): VariableValue {\n return this.state[key]\n }\n\n set(key: string, value: VariableValue): void {\n if (this.state[key] === value) return\n this.state = { ...this.state, [key]: value }\n this.changedKeys = [key]\n this.notify()\n }\n\n setState(updater: (prev: Record<string, VariableValue>) => Record<string, VariableValue>): void {\n const prev = this.state\n const next = updater(prev)\n if (next === prev) return\n this.state = next\n // Compute changed keys\n this.changedKeys = []\n for (const key of Object.keys(next)) {\n if (next[key] !== prev[key]) this.changedKeys.push(key)\n }\n for (const key of Object.keys(prev)) {\n if (!(key in next) && prev[key] !== undefined) this.changedKeys.push(key)\n }\n this.notify()\n }\n\n /** Batch set multiple variables at once */\n setMany(updates: Record<string, VariableValue>): void {\n const changed: string[] = []\n const next = { ...this.state }\n for (const [key, value] of Object.entries(updates)) {\n if (next[key] !== value) {\n next[key] = value\n changed.push(key)\n }\n }\n if (changed.length === 0) return\n this.state = next\n this.changedKeys = changed\n this.notify()\n }\n\n /**\n * Subscribe to store changes.\n *\n * @param listener - callback fired when relevant keys change\n * @param scope - optional scope to limit notifications:\n * - `{ keys: ['data.x', 'user.email'] }` — only fire when these exact keys change\n * - `{ prefix: 'answers.' }` — only fire when any key starting with this prefix changes\n * - omit or `{}` — fire on every change (global listener)\n */\n subscribe(\n listener: () => void,\n scope?: { keys?: string[]; prefix?: string },\n ): () => void {\n const entry: ScopedListener = {\n listener,\n keys: scope?.keys || null,\n prefix: scope?.prefix || null,\n }\n this.listeners.add(entry)\n return () => this.listeners.delete(entry)\n }\n\n private notify(): void {\n const changed = this.changedKeys\n for (const entry of this.listeners) {\n // Global listener — no scope\n if (!entry.keys && !entry.prefix) {\n entry.listener()\n continue\n }\n // Key-scoped listener\n if (entry.keys) {\n if (changed.some((k) => entry.keys!.includes(k))) {\n entry.listener()\n }\n continue\n }\n // Prefix-scoped listener\n if (entry.prefix) {\n if (changed.some((k) => k.startsWith(entry.prefix!))) {\n entry.listener()\n }\n }\n }\n }\n}\n","/**\n * v2 store seeding — builds a {@link VariableStore} holding only the **writable**\n * namespaces (`user` / `responses` / `data`), each persisted to the backend.\n *\n * Seeds the {@link VariableStore} with v2 prefixes (no legacy `answers.`/`query.`\n * aliasing). Read-only computed values do NOT live\n * here — see {@link ./context}. Three deliberate namespaces:\n *\n * - `user.*` persistent identity attributes (cross-session)\n * - `responses.*` the clean, aggregated funnel answers\n * - `data.*` working/scratch state — persisted (so reload + return survive)\n * but kept separate from responses so analytics aggregates only\n * real answers and `data` can hold intermediate garbage\n */\n\nimport type { VariableValue, VariableConfig } from '../types'\nimport { VariableStore } from './variableStore'\n\n/** v2 namespace → store-key prefix (sans trailing dot). 1:1, no legacy aliasing. */\nexport const NAMESPACE_PREFIX = {\n user: 'user',\n responses: 'responses',\n data: 'data',\n} as const\n\nexport type WritableNamespace = keyof typeof NAMESPACE_PREFIX\n\n/** Built-in user attributes — always present so reads never `undefined`. */\nconst BUILTIN_USER: Record<string, VariableValue> = {\n 'user.email': '',\n 'user.name': '',\n}\n\nexport interface FunnelStoreConfig {\n responses?: Record<string, VariableConfig>\n data?: Record<string, VariableConfig>\n}\n\nfunction defaultFor(type: string): VariableValue {\n switch (type) {\n case 'string': return ''\n case 'number': return 0\n case 'boolean': return false\n case 'stringArray': return []\n default: return ''\n }\n}\n\n/**\n * Seed a store from a funnel's declared `responses`/`data` defaults, then layer\n * server / session-restored values on top (highest priority).\n */\nexport function createFunnelStore(\n config: FunnelStoreConfig = {},\n sessionValues?: Record<string, VariableValue>,\n): VariableStore {\n const initial: Record<string, VariableValue> = { ...BUILTIN_USER }\n\n for (const [key, cfg] of Object.entries(config.responses ?? {})) {\n initial[`responses.${key}`] = cfg.default ?? defaultFor(cfg.type)\n }\n for (const [key, cfg] of Object.entries(config.data ?? {})) {\n initial[`data.${key}`] = cfg.default ?? defaultFor(cfg.type)\n }\n\n if (sessionValues) {\n for (const [key, value] of Object.entries(sessionValues)) {\n if (value !== undefined) initial[key] = value\n }\n }\n\n return new VariableStore(initial)\n}\n","/**\n * v2 `context` — the **read-only, computed** namespace.\n *\n * Everything the funnel can *read* but never *write*: the device, the visitor's\n * locale, the current page, acquisition params (UTM), the session, and system\n * facts (funnel id, test/live mode, clock). It supersedes the v0 flat\n * `page.*`/`device.*`/`browser.*`/`os.*`/`query.*`/`metadata.*` system variables\n * (see {@link ./systemVariables}) by folding them into one nested object.\n *\n * Why it's *not* in the {@link ./variableStore}: the store holds **writable**\n * state (`user`/`responses`/`data`) that persists + re-renders per key. Context\n * is derived and read-only, so it lives as a plain object on a React context —\n * no subscriptions, no churn. The one moving part (`page`) is merged into the\n * snapshot from navigation state at read time.\n *\n * Authors read it through hooks (`useDevice()`, `useLocale()`, `usePage()`,\n * `useUtm()`) or inside routing/condition predicates as `s.context.*`.\n */\n\n// ── Shape ────────────────────────────────────────────────\n\nexport interface DeviceContext {\n type: 'mobile' | 'tablet' | 'desktop'\n isMobile: boolean\n isTablet: boolean\n screenWidth: number\n screenHeight: number\n viewportWidth: number\n viewportHeight: number\n colorDepth: number\n pixelRatio: number\n}\n\nexport interface BrowserContext {\n name: string\n version: string\n userAgent: string\n language: string\n cookieEnabled: boolean\n online: boolean\n}\n\nexport interface OsContext {\n name: string\n timezone: string\n}\n\nexport interface LocaleContext {\n /** Full locale, e.g. `en-US`. */\n locale: string\n /** Language subtag, e.g. `en`. */\n language: string\n /** Region subtag, e.g. `US` (may be empty). */\n region: string\n /** IANA timezone, e.g. `America/New_York`. */\n timeZone: string\n}\n\nexport interface PageContext {\n /** Current page key. */\n key: string\n /** Current page URL slug (`meta.slug`, defaults to the key) — what the renderer puts in the path. */\n slug: string\n /** Current page's progress-bar group label (`meta.group`), or undefined when ungrouped. */\n group?: string\n /** 0-based position in the visited history. */\n index: number\n /** Total pages in the (expected) flow. */\n total: number\n /** 0–100. */\n progressPercentage: number\n /** Epoch ms the current page was entered. */\n startedAt: number\n}\n\n/** Acquisition / ad params captured on entry (the old `query.*` utm slice). */\nexport interface UtmContext {\n source?: string\n medium?: string\n campaign?: string\n content?: string\n term?: string\n [key: string]: string | undefined\n}\n\n/**\n * Per-network ad **click-ids** captured from the entry URL — the matching signals\n * the server CAPI needs. Named per network (not a generic bag) so the platform +\n * each integration map them precisely; `[key]` catches any others.\n */\nexport interface ClickIdContext {\n /** Meta / Facebook */\n fbclid?: string\n /** Google Ads (+ gbraid/wbraid for app↔web) */\n gclid?: string\n gbraid?: string\n wbraid?: string\n /** Microsoft / Bing */\n msclkid?: string\n /** TikTok */\n ttclid?: string\n /** Twitter / X */\n twclid?: string\n /** Snapchat */\n sccid?: string\n /** LinkedIn */\n li_fat_id?: string\n /** Pinterest */\n epik?: string\n /** Reddit */\n rdt_cid?: string\n [key: string]: string | undefined\n}\n\n/**\n * The full acquisition snapshot captured once on entry — the funnel reads `utm` /\n * `clickIds` off {@link FunnelContext}; the SDK forwards this whole thing to the\n * tracker (`setAcquisition`) so the platform persists it **first-class**: per-visit\n * on the session + **first-touch (write-once) on the Customer**, and the click-ids /\n * `_fbp`/`_fbc` cookies feed CAPI. Not stored as a generic attribute/answer.\n */\nexport interface Acquisition {\n utm: UtmContext\n clickIds: ClickIdContext\n /** CAPI cookies (`_fbp`/`_fbc`) read from `document.cookie` (not funnel-readable). */\n cookies: { fbp?: string; fbc?: string }\n /** `document.referrer` at entry. */\n referrer: string\n /** Entry URL path (the landing page). */\n landingPath: string\n}\n\nexport interface SessionContext {\n /** Server session id; null until resolved. */\n id: string | null\n /** Epoch ms the session began. */\n startedAt: number\n /** `document.referrer` at entry. */\n referrer: string\n /**\n * URL path the visitor LANDED on, captured during `buildContext` (i.e. while the tree is being\n * built, before any effect). It must be read here and not later: the funnel now rewrites the path\n * as the visitor advances, and the very first rewrite happens in a commit effect that React runs\n * BEFORE the provider effect which assembles acquisition — so a later read would record the\n * corrected path (or page two) as first touch instead of the ad's landing URL.\n */\n landingPath: string\n}\n\n/**\n * Durable identity for **stable experiment bucketing** (phase-4 §4.2). The\n * preferred seed is the signed anonymous `visitorId` (stable from the first\n * pageload, matching the server-side FUNNEL split in resolve.ts); `customerId` is\n * only the fallback for cookieless SDK embeds. visitorId-FIRST is deliberate — the\n * anon customerId is minted server-side AFTER the first tracked event, so seeding\n * on it would flip a returning visitor's arm between visit 1 and 2 (see\n * {@link ../flow/experiments}.bucketingSeed). It is deliberately **not** the\n * session id or fingerprint — a returning visitor (e.g. via winback) must keep\n * their variant across sessions (landmine #4). Both null = unidentifiable traffic,\n * and the experiment layer falls back to control rather than bucket on nothing.\n */\nexport interface IdentityContext {\n /** Known customer id (post-identification). The fallback bucketing seed (cookieless embeds). */\n customerId: string | null\n /** Signed anonymous visitor id. The preferred bucketing seed (stable from visit 1). */\n visitorId: string | null\n}\n\nexport interface SystemContext {\n funnelId: string\n campaignId: string\n /** Render mode — `test` for preview/QA, `live` for public traffic. */\n mode: 'test' | 'live'\n /** Epoch ms captured at build time (stable per render, not a live clock). */\n now: number\n}\n\n/** The whole read-only computed namespace, as read in predicates: `s.context.*`. */\nexport interface FunnelContext {\n device: DeviceContext\n browser: BrowserContext\n os: OsContext\n locale: LocaleContext\n page: PageContext\n utm: UtmContext\n /** Per-network ad click-ids captured on entry (funnel-readable; also forwarded for CAPI). */\n clickIds: ClickIdContext\n session: SessionContext\n identity: IdentityContext\n system: SystemContext\n}\n\n// ── Detection ────────────────────────────────────────────\n\ninterface RawBrowser {\n device: DeviceContext\n browser: BrowserContext\n os: OsContext\n locale: LocaleContext\n}\n\nlet cached: RawBrowser | null = null\n\nfunction extractVersion(ua: string, regex: RegExp): string {\n return ua.match(regex)?.[1] ?? '0'\n}\n\n/**\n * Classify the operating system from a user-agent. Pulled out of {@link detect} as a PURE function\n * so it can be replayed over the stored `WebFunnelSession.userAgent` corpus — a browser sniffer\n * that can only be exercised through a live `navigator` is a sniffer nobody ever checks against\n * real traffic.\n *\n * ORDER IS LOAD-BEARING, and it was wrong until 2026-07-31: every iOS user-agent contains the\n * string \"like Mac OS X\", so a `mac` test placed before the iOS one matched FIRST and reported\n * every single iPhone as macOS. Anything branching on `os.name === 'iOS'` — store routing, app\n * hand-off, platform-conditional copy — was therefore dead on the one platform it mattered on.\n * iOS and Android are checked first now, and each remaining test is unambiguous once they are.\n *\n * iPadOS 13+ is the second half of the problem: it ships a DESKTOP user-agent (\"Macintosh; Intel\n * Mac OS X\") byte-identical to a real Mac's, so the only signal left is a touch screen.\n * `maxTouchPoints > 1` is that signal — Macs report 0 (a trackpad is not a touchscreen), iPads\n * report 5. It is a LIVE-ONLY signal: replaying stored user-agents cannot recover it, so an iPad\n * in the corpus is indistinguishable from a Mac and counts as macOS there.\n *\n * The returned names match the renderer's server-side detector (`apps/renderer/lib/routeSignals`),\n * which had the ordering right all along — the two now agree token for token, so a funnel's\n * `context.os.name` and the route that served it can never disagree about the platform.\n *\n * Validated 2026-07-31 by replaying all 144,938 stored `WebFunnelSession.userAgent` rows: it\n * classifies every non-bot session except 6 Chromebooks' worth of nothing, and it moved 124,192\n * sessions (85.7%) out of the macOS bucket they never belonged in.\n */\nexport function osFromUserAgent(ua: string, maxTouchPoints = 0): string {\n const l = ua.toLowerCase()\n if (/iphone|ipad|ipod/.test(l)) return 'iOS'\n if (l.includes('macintosh') && maxTouchPoints > 1) return 'iOS' // iPadOS 13+ desktop mode\n if (l.includes('android')) return 'Android'\n // Facebook's in-app browser sometimes sends a BRACKET-ONLY user-agent — no Mozilla prefix, no\n // platform token, just `[FBAN/FB4A;FBAV/…]`. In-app browsers are 92% of this product's traffic,\n // so the app code is the platform signal when nothing else is present. FB4A = for Android,\n // FBIOS = for iOS.\n if (l.includes('fban/fb4a')) return 'Android'\n if (l.includes('fban/fbios')) return 'iOS'\n if (l.includes('win')) return 'Windows'\n if (l.includes('mac')) return 'macOS'\n if (l.includes('cros')) return 'Chrome OS' // vocabulary matches routeSignals\n if (l.includes('linux')) return 'Linux'\n return 'Unknown'\n}\n\n/**\n * Sniff device/browser/os/locale from the environment, once. SSR-safe: returns\n * neutral defaults when `window` is absent. (Self-contained v2 detector — the v0\n * {@link ./systemVariables} equivalent emits flat store keys; this returns the\n * nested shape.)\n */\nfunction detect(): RawBrowser {\n if (cached) return cached\n\n if (typeof window === 'undefined') {\n cached = {\n device: {\n type: 'desktop', isMobile: false, isTablet: false,\n screenWidth: 0, screenHeight: 0, viewportWidth: 0, viewportHeight: 0,\n colorDepth: 24, pixelRatio: 1,\n },\n browser: {\n name: 'Unknown', version: '0', userAgent: 'unknown',\n language: 'en', cookieEnabled: true, online: true,\n },\n os: { name: 'Unknown', timezone: 'UTC' },\n locale: { locale: 'en', language: 'en', region: '', timeZone: 'UTC' },\n }\n return cached\n }\n\n const ua = navigator.userAgent\n const l = ua.toLowerCase()\n\n let name = 'Unknown'\n let version = '0'\n if (l.includes('firefox')) { name = 'Firefox'; version = extractVersion(ua, /Firefox\\/(\\d+[\\d.]*)/) }\n else if (l.includes('edg')) { name = 'Edge'; version = extractVersion(ua, /Edg\\/(\\d+[\\d.]*)/) }\n else if (l.includes('chrome') && !l.includes('edg')) { name = 'Chrome'; version = extractVersion(ua, /Chrome\\/(\\d+[\\d.]*)/) }\n else if (l.includes('safari') && !l.includes('chrome')) { name = 'Safari'; version = extractVersion(ua, /Version\\/(\\d+[\\d.]*)/) }\n\n const osName = osFromUserAgent(ua, navigator.maxTouchPoints ?? 0)\n\n // `device.type` deliberately does NOT fold in the iPadOS sniff above. It drives LAYOUT, and an\n // iPad asking for the desktop user-agent is asking for the desktop layout — reclassifying it as\n // a tablet would silently reflow live funnels for a fix that was only ever about `os.name`.\n let type: DeviceContext['type'] = 'desktop'\n if (/mobile|android(?!.*tablet)|iphone|ipod/.test(l)) type = 'mobile'\n else if (/tablet|ipad/.test(l)) type = 'tablet'\n\n const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'\n const fullLocale = navigator.language || 'en'\n const [language = 'en', region = ''] = fullLocale.split('-')\n\n cached = {\n device: {\n type, isMobile: type === 'mobile', isTablet: type === 'tablet',\n screenWidth: window.screen?.width || 0,\n screenHeight: window.screen?.height || 0,\n viewportWidth: window.innerWidth || 0,\n viewportHeight: window.innerHeight || 0,\n colorDepth: window.screen?.colorDepth || 24,\n pixelRatio: window.devicePixelRatio || 1,\n },\n browser: {\n name, version, userAgent: ua,\n language: fullLocale,\n cookieEnabled: navigator.cookieEnabled ?? true,\n online: navigator.onLine ?? true,\n },\n os: { name: osName, timezone: timeZone },\n locale: { locale: fullLocale, language, region, timeZone },\n }\n return cached\n}\n\n/** Collect `utm_*` params (and any extras) from the URL. SSR-safe. */\nfunction collectUtm(): UtmContext {\n if (typeof window === 'undefined') return {}\n const out: UtmContext = {}\n const params = new URLSearchParams(window.location.search)\n params.forEach((value, key) => {\n if (key.startsWith('utm_')) out[key.slice(4)] = value\n })\n return out\n}\n\n/** Known ad-network click-id params. Any present in the URL is captured. */\nconst CLICK_ID_PARAMS = [\n 'fbclid', 'gclid', 'gbraid', 'wbraid', 'msclkid', 'ttclid',\n 'twclid', 'sccid', 'li_fat_id', 'epik', 'rdt_cid', 'dclid', 'irclickid',\n]\n\n/** Collect ad-network click-ids from the entry URL. SSR-safe. */\nfunction collectClickIds(): ClickIdContext {\n if (typeof window === 'undefined') return {}\n const out: ClickIdContext = {}\n const params = new URLSearchParams(window.location.search)\n for (const key of CLICK_ID_PARAMS) {\n const v = params.get(key)\n if (v) out[key] = v\n }\n return out\n}\n\n/** Read a cookie value by name. SSR-safe AND sandbox-safe: in an opaque-origin sandboxed\n * iframe (e.g. the editor preview, which deliberately has no allow-same-origin) the native\n * `document.cookie` GETTER throws a SecurityError — degrade to \"no cookie\", never crash. */\nfunction readCookie(name: string): string | undefined {\n if (typeof document === 'undefined') return undefined\n try {\n const m = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'))\n return m ? decodeURIComponent(m[1]) : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Assemble the full {@link Acquisition} snapshot from the context + `document`\n * (cookies, referrer, path) — captured once on entry, forwarded to the tracker for\n * first-class persistence (session + first-touch Customer) + CAPI.\n */\nexport function buildAcquisition(context: FunnelContext): Acquisition {\n return {\n utm: context.utm,\n clickIds: context.clickIds,\n cookies: { fbp: readCookie('_fbp'), fbc: readCookie('_fbc') },\n referrer: context.session.referrer,\n landingPath: context.session.landingPath,\n }\n}\n\nexport interface BuildContextOptions {\n funnelId?: string\n campaignId?: string\n mode?: 'test' | 'live'\n /** Stable build-time clock (avoids `Date.now()` churn in renders/tests). */\n now?: number\n sessionId?: string | null\n /** Known customer id — the preferred stable bucketing seed (phase-4 §4.2). */\n customerId?: string | null\n /** Signed anonymous visitor id — the fallback bucketing seed. */\n visitorId?: string | null\n /** Overrides for any slice — used by the server to hydrate `utm`/`session`. */\n overrides?: Partial<FunnelContext>\n}\n\n/**\n * Build the read-only {@link FunnelContext} once, at mount. `page` starts at the\n * first page and is replaced per navigation when assembling a snapshot.\n */\nexport function buildContext(opts: BuildContextOptions = {}): FunnelContext {\n const raw = detect()\n const now = opts.now ?? 0\n const referrer = typeof document !== 'undefined' ? document.referrer : ''\n // Captured NOW (build time), not in an effect — see SessionContext.landingPath.\n const landingPath = typeof window !== 'undefined' ? window.location.pathname : ''\n\n const base: FunnelContext = {\n device: raw.device,\n browser: raw.browser,\n os: raw.os,\n locale: raw.locale,\n utm: collectUtm(),\n clickIds: collectClickIds(),\n page: { key: '', slug: '', index: 0, total: 0, progressPercentage: 0, startedAt: now },\n session: { id: opts.sessionId ?? null, startedAt: now, referrer, landingPath },\n identity: { customerId: opts.customerId ?? null, visitorId: opts.visitorId ?? null },\n system: {\n funnelId: opts.funnelId ?? '',\n campaignId: opts.campaignId ?? '',\n mode: opts.mode ?? 'live',\n now,\n },\n }\n\n if (!opts.overrides) return base\n return {\n ...base,\n ...opts.overrides,\n device: { ...base.device, ...opts.overrides.device },\n browser: { ...base.browser, ...opts.overrides.browser },\n os: { ...base.os, ...opts.overrides.os },\n locale: { ...base.locale, ...opts.overrides.locale },\n utm: { ...base.utm, ...opts.overrides.utm },\n clickIds: { ...base.clickIds, ...opts.overrides.clickIds },\n page: { ...base.page, ...opts.overrides.page },\n session: { ...base.session, ...opts.overrides.session },\n identity: { ...base.identity, ...opts.overrides.identity },\n system: { ...base.system, ...opts.overrides.system },\n }\n}\n\n/** Internal: reset the detection cache (tests only). */\nexport function __resetContextCache(): void {\n cached = null\n}\n","/**\n * v2 tracking seam — the funnel runtime emits a **fixed event taxonomy**, but\n * never talks to the network itself. It calls a {@link Tracker} the platform/CLI\n * injects via {@link FunnelProvider}. The real implementation is the existing\n * {@link ./tracker}.`FunnelTracker` (session id, ad attribution, debounced\n * persistence, CAPI fan-out); tests and local dev use {@link createConsoleTracker}.\n *\n * The taxonomy is preserved verbatim from v0 so analytics keep working:\n * funnel.start · page.view · page.exit · user.registered · experiment.exposure ·\n * checkout.start · checkout.payment_added · checkout.failed · purchase.complete\n * plus one v2 addition: checkout.already_purchased (a charge refused because the buyer\n * already owns the product — a flow outcome, never a money one).\n *\n * Where each fires (all from the SDK runtime):\n * - `funnel.start` / `page.view` / `page.exit` / `experiment.exposure` — navigation\n * ({@link ../flow/flow}.`FunnelView`); `page.exit` carries duration + active (visible) time.\n * - `user.registered` — `identify()`, the first time `user.email` is written.\n * - `checkout.*` / `purchase.complete` — the commerce primitives ({@link ../commerce/checkout}).\n * `checkout.payment_added` is reported by an inline driver via `onPaymentAdded` (optional).\n *\n * A `responses.set(...)` does **not** emit a discrete event — values are batched into\n * `userData` and persisted (debounced). Only the events above fire.\n */\n\nimport {\n createContext,\n createElement,\n useCallback,\n useContext,\n type ReactNode,\n} from 'react'\nimport type { Acquisition } from '../state/context'\n\n// ── Event taxonomy (typed, preserved from v0) ────────────\n\nexport interface FunnelEventDataMap {\n 'funnel.start': Record<string, never>\n 'page.view': { pageId: string; pageKey?: string; pageName?: string; isInitial?: boolean; eventId?: string }\n 'page.exit': { pageId: string; durationMs: number; activeMs: number }\n 'user.registered': { email: string; eventId?: string }\n // The commerce primitives enrich the pre-charge steps with the money facts +\n // product identity the pixel loaders need (Meta content_ids/value, TikTok\n // contents, GA4 items). `productId` is the CHARGE/SKU identity (the resolved\n // product's `catalogKey`, falling back to the slot); `amount` is the catalog list\n // price in major units; `eventId` is client-minted (pre-charge, no server id) so a\n // future InitiateCheckout/AddPaymentInfo server CAPI can dedup. All optional so a\n // product-less/uncataloged attempt still type-checks.\n 'checkout.start': { productId?: string; priceId?: string; productName?: string; surface?: string; amount?: number; currency?: string; eventId?: string }\n 'checkout.payment_added': { productId?: string; amount?: number; currency?: string; eventId?: string }\n 'checkout.failed': { category: string; declineCode?: string; productId?: string; intent?: string }\n // The charge was REFUSED because the buyer already owns the product (the platform's\n // double-charge guard). Not a failure and not a sale: it fires INSTEAD of\n // `checkout.failed` (nothing failed) and never alongside `purchase.complete` (no money\n // moved — the original purchase already emitted that event and its pixel, and re-emitting\n // would double-count revenue and post a duplicate conversion). Tracked but never fanned out\n // to ad pixels, so it is countable in analytics without touching revenue.\n 'checkout.already_purchased': { productId?: string; declineCode?: string; intent?: string }\n 'purchase.complete': { amount?: number; currency?: string; email?: string; eventId?: string; productId?: string }\n // Fired from the SDK at settle for a SUBSCRIPTION charge (browser Subscribe),\n // carrying the SAME server-minted `eventId` as the purchase.complete for that\n // settle so it dedups against the server-CAPI Subscribe (which maps\n // subscription.created→Subscribe with that id). Server stays the source of truth\n // (`EVENT_CATALOG.sources: ['backend']`); the SDK mirrors it to fire the pixel.\n 'subscription.created': { amount?: number; currency?: string; productId?: string; eventId?: string }\n 'experiment.exposure': { experimentId: string; variant: string; version?: number }\n}\n\n/**\n * Build the `experiment.exposure` payload — ONE constructor for both exposure\n * emitters (the PAGE path in flow.tsx and the FUNNEL path in platformTracker),\n * so the wire shape can't drift between them. `version` is the platform record\n * version results key on; omitted (not `undefined`) when the record has none.\n */\nexport function exposurePayload(\n experimentId: string,\n variant: string,\n version?: number,\n): FunnelEventDataMap['experiment.exposure'] {\n return { experimentId, variant, ...(version !== undefined ? { version } : {}) }\n}\n\n/**\n * A unique id for an analytics event, used as the **dedup key** between the\n * browser pixel (`fbq(..., { eventID })`) and the server CAPI call. Browser-\n * originated events (page.view, registration) mint one with this; **purchase /\n * subscription events carry the id the *server* minted** (the charge is the source\n * of truth) — see `CheckoutResult.eventId`.\n */\nlet _eventIdCounter = 0\nexport function newEventId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID()\n return `af_${Date.now().toString(36)}_${(_eventIdCounter++).toString(36)}`\n}\n\nexport type KnownFunnelEvent = keyof FunnelEventDataMap\n\n/**\n * The surface the runtime needs from a tracker. A subset of `FunnelTracker`, so\n * the real one satisfies it directly; the console tracker is a trivial stub.\n */\nexport interface Tracker {\n /**\n * The funnel session id this tracker has resolved, or `null` before the first event response\n * mints one. Optional: a custom tracker need not have a session at all, and every reader must\n * cope with `null` (which simply means \"not yet\").\n */\n getSessionId?(): string | null\n /** Emit a known event (typed) or any custom event name. */\n track<E extends KnownFunnelEvent>(event: E, data?: FunnelEventDataMap[E], userData?: Record<string, unknown>): void\n track(event: string, data?: Record<string, unknown>, userData?: Record<string, unknown>): void\n /**\n * Identify by email — fires `user.registered`.\n *\n * NOT idempotent, and never was: every implementation emits on every call (the platform tracker\n * enqueues, the bus wrapper also emits to pixels). This doc used to claim otherwise, which is\n * exactly the sort of thing a welcome-email journey gets built on top of — corrected 2026-07-29.\n * The once-guard lives in `funnel.completeUserRegistration` (state/namespaces.ts) for the page\n * life, and in the server's event route for the durable case. A caller reaching for `identify`\n * directly owns that question itself.\n *\n * The optional `eventId` is the browser↔CAPI dedup key for the registration event.\n */\n identify(email: string, eventId?: string): void\n /** Push the latest variable snapshot for batched/debounced persistence. */\n setVariables?(variables: Record<string, unknown>): void\n /**\n * The acquisition snapshot (utm + click-ids + `_fbp`/`_fbc` + referrer), pushed\n * once on entry. The platform persists it first-class — per-visit on the session +\n * **first-touch (write-once) on the Customer** — and feeds it to CAPI. Optional;\n * the console/test trackers ignore it.\n */\n setAcquisition?(acquisition: Acquisition): void\n}\n\n/** A no-op-ish tracker that logs to the console — for tests, preview, local dev. */\nexport function createConsoleTracker(opts: { silent?: boolean } = {}): Tracker {\n const log = (label: string, ...args: unknown[]) => {\n if (!opts.silent) console.info(`[appfunnel] ${label}`, ...args)\n }\n return {\n track: (event: string, data?: unknown) => log(`track ${event}`, data ?? {}),\n identify: (email: string, eventId?: string) => log('identify', email, eventId),\n setVariables: (vars) => log('vars', vars),\n setAcquisition: (acq) => log('acquisition', acq),\n }\n}\n\n// ── React wiring ─────────────────────────────────────────\n\nconst TrackerContext = createContext<Tracker | null>(null)\n\nexport function TrackerProvider({\n tracker,\n children,\n}: {\n tracker: Tracker\n children: ReactNode\n}): ReactNode {\n return createElement(TrackerContext.Provider, { value: tracker }, children)\n}\n\n/** Internal: the raw tracker, or a silent console fallback if none provided. */\nexport function useTrackerRef(): Tracker {\n return useContext(TrackerContext) ?? FALLBACK\n}\n\nconst FALLBACK = createConsoleTracker({ silent: true })\n\n/**\n * `const { track } = useTracker()` — emit a custom event. Auto events\n * (page.view, identify, purchase, …) fire on their own; this is the escape\n * hatch for funnel-specific events (`track('quiz_skipped', { step: 3 })`).\n */\nexport function useTracker(): { track: Tracker['track'] } {\n const tracker = useTrackerRef()\n const track = useCallback(\n (event: string, data?: Record<string, unknown>, userData?: Record<string, unknown>) =>\n tracker.track(event, data as never, userData),\n [tracker],\n )\n return { track }\n}\n","/**\n * The **`window.appfunnel` event bus** — the client-side integration surface\n * (port of v0 `admin/lib/funnel/utils/appfunnelRuntime.ts`).\n *\n * Every taxonomy event the runtime emits is mirrored here, so on-page pixels and\n * custom scripts integrate by **subscribing** — `window.appfunnel.on('purchase.complete', …)`\n * — instead of the funnel hand-injecting pixel config per page. The pre-built pixel\n * loaders (Meta/TikTok/GTM/Clarity) are just subscribers; CAPI stays the server-side\n * default (this is the *client* sink of the same events). See doc 08 §3.\n *\n * Two deliberate properties vs. v0:\n * - **Replay history** (`events`): async pixels load *after* `funnel.start`/`page.view`\n * fire, so a late subscriber would miss them. The bus keeps a bounded history a\n * subscriber can replay (the GTM `dataLayer` trick) — no lost events.\n * - **Subscribe + read + drive.** The window surface exposes `on`/`off`/`events` + read\n * getters, and — resolving the deferred bus-control-scope decision (doc 08 §3/§4) —\n * **flow control**: `goTo`/`goNext`/`goPrevious` + a `navigation()` snapshot, so a host\n * page (the live editor, or an author's own external nav UI) can drive the funnel. It\n * still has **no `emit`** (third-party code can't forge taxonomy events) and no\n * `setVariable` (state stays funnel-owned). Flow control is a no-op (warns once) until a\n * `<FunnelView>` mounts and registers itself via {@link FunnelBus.registerNavigation}.\n */\n\nimport { newEventId, type Tracker } from './tracking'\nimport type { NavSnapshot } from '../protocol'\n\n// The flow snapshot is a WIRE type — it lives in the shared protocol (one source of truth for the\n// bus, the EmbedBridge, and the host client). Re-exported here so existing `../tracking/bus` importers\n// keep resolving it.\nexport type { NavSnapshot } from '../protocol'\n\n/** Read accessors the bus exposes — wired to the funnel's store + context. */\nexport interface BusAccessors {\n\tgetVariable: (key: string) => unknown\n\tgetVariables: () => Record<string, unknown>\n\tgetCurrentPageId: () => string | null\n\tgetCustomerId: () => string | null\n\tgetVisitorId: () => string | null\n}\n\nexport interface BusEvent {\n\tevent: string\n\tdata: unknown\n\t/** Epoch ms the event was emitted (for ordering / replay). */\n\tts: number\n}\n\ntype Listener = (data: unknown) => void\n\n/** The flow-control seam a mounted `<FunnelView>` registers into the bus (SDK-internal). */\nexport interface NavigationControl {\n\t/** Jump to a page key. Returns `false` if the key isn't a real page (no navigation happened). */\n\tgoTo(pageKey: string): boolean\n\tgoNext(): void\n\tgoPrevious(): void\n\tsnapshot(): NavSnapshot | null\n}\n\n/**\n * The public `window.appfunnel` surface — subscribe + read + drive the flow. It never\n * exposes `emit` (no forged events) or `setVariable` (state stays funnel-owned).\n */\nexport interface AppfunnelBusApi extends BusAccessors {\n\t/** Subscribe to an event (or `'*'` for all). Returns an unsubscribe fn. */\n\ton(event: string, cb: Listener): () => void\n\toff(event: string, cb: Listener): void\n\t/** Bounded replay history — read past events, then `on()` for future ones. */\n\treadonly events: BusEvent[]\n\t/** Jump the flow to a page key. Returns `false` for an unknown key (or before the flow mounts). */\n\tgoTo(pageKey: string): boolean\n\t/** Advance via the current page's `next` predicate (else the linear next). */\n\tgoNext(): void\n\t/** Step back to the previous page in flow history. */\n\tgoPrevious(): void\n\t/** The current flow snapshot, or `null` before a `<FunnelView>` mounts. */\n\tnavigation(): NavSnapshot | null\n}\n\nconst MAX_HISTORY = 250\n\n/**\n * The internal bus: the public {@link AppfunnelBusApi} plus `emit` (SDK-only) and\n * `now` injection. The SDK holds this; only {@link AppfunnelBusApi} reaches `window`.\n */\nexport interface FunnelBus extends AppfunnelBusApi {\n\temit(event: string, data?: unknown): void\n\t/** SDK-only: a mounted `<FunnelView>` registers its flow control; returns an unregister fn. */\n\tregisterNavigation(nav: NavigationControl): () => void\n}\n\n/** Create a bus over the given read accessors. `now` is injectable for tests. */\nexport function createBus(\n\taccessors: BusAccessors,\n\tnow: () => number = () => Date.now()\n): FunnelBus {\n\tconst listeners = new Map<string, Set<Listener>>()\n\tconst events: BusEvent[] = []\n\n\tconst on: AppfunnelBusApi['on'] = (event, cb) => {\n\t\tlet set = listeners.get(event)\n\t\tif (!set) listeners.set(event, (set = new Set()))\n\t\tset.add(cb)\n\t\treturn () => off(event, cb)\n\t}\n\tconst off: AppfunnelBusApi['off'] = (event, cb) => {\n\t\tlisteners.get(event)?.delete(cb)\n\t}\n\n\tconst emit = (event: string, data?: unknown) => {\n\t\tevents.push({ event, data, ts: now() })\n\t\tif (events.length > MAX_HISTORY) events.shift()\n\t\t// Exact-event listeners, then wildcard. A throwing subscriber never breaks the rest.\n\t\tfor (const cb of listeners.get(event) ?? []) {\n\t\t\ttry {\n\t\t\t\tcb(data)\n\t\t\t} catch {\n\t\t\t\t/* a pixel error must not break the funnel */\n\t\t\t}\n\t\t}\n\t\tfor (const cb of listeners.get('*') ?? []) {\n\t\t\ttry {\n\t\t\t\tcb({ event, data })\n\t\t\t} catch {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t}\n\t}\n\n\t// Flow control delegates to the <FunnelView> that registered itself. Calls before mount\n\t// (or after unmount) are ignored, warning ONCE so a mis-timed host script is debuggable\n\t// without spamming the console on every retry.\n\tlet nav: NavigationControl | null = null\n\tlet warnedNoNav = false\n\tconst currentNav = (): NavigationControl | null => {\n\t\tif (!nav && !warnedNoNav) {\n\t\t\twarnedNoNav = true\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.warn(\n\t\t\t\t'[appfunnel] window.appfunnel navigation called before the funnel flow mounted — ignored'\n\t\t\t)\n\t\t}\n\t\treturn nav\n\t}\n\tconst registerNavigation = (n: NavigationControl) => {\n\t\tnav = n\n\t\twarnedNoNav = false\n\t\treturn () => {\n\t\t\tif (nav === n) nav = null\n\t\t}\n\t}\n\tconst goTo = (pageKey: string): boolean =>\n\t\tcurrentNav()?.goTo(pageKey) ?? false\n\tconst goNext = () => currentNav()?.goNext()\n\tconst goPrevious = () => currentNav()?.goPrevious()\n\tconst navigation = () => nav?.snapshot() ?? null\n\n\treturn {\n\t\ton,\n\t\toff,\n\t\tevents,\n\t\temit,\n\t\tregisterNavigation,\n\t\tgoTo,\n\t\tgoNext,\n\t\tgoPrevious,\n\t\tnavigation,\n\t\t...accessors,\n\t}\n}\n\n/**\n * Wrap a {@link Tracker} so every emitted taxonomy event is mirrored to the bus\n * (the client sink). `identify()` also surfaces a `user.registered` to the bus, so\n * pixels see registration. The server sink (the inner tracker → CAPI) is untouched.\n */\nexport function withBus(tracker: Tracker, bus: FunnelBus): Tracker {\n\treturn {\n\t\t// A transparent decorator has to forward the READ side too. This is the only tracker the\n\t\t// React tree ever sees (`FunnelProvider` provides the wrapped one), so dropping this getter\n\t\t// left every context-side reader — the deep-link hand-off among them — seeing \"no session\"\n\t\t// for the whole visit and silently falling back to the mount-time snapshot, which is null\n\t\t// until the first event response lands.\n\t\tgetSessionId: tracker.getSessionId\n\t\t\t? () => tracker.getSessionId!()\n\t\t\t: undefined,\n\t\t// Spread preserves the original call arity (don't append an undefined userData).\n\t\ttrack: ((...args: [string, unknown?, Record<string, unknown>?]) => {\n\t\t\t;(tracker.track as (...a: unknown[]) => void)(...args)\n\t\t\tbus.emit(args[0], args[1])\n\t\t}) as Tracker['track'],\n\t\tidentify: (email: string, eventId?: string) => {\n\t\t\t// One id shared by the server (inner.identify → CAPI) and the bus (pixel) so\n\t\t\t// CompleteRegistration dedupes across browser + server.\n\t\t\tconst id = eventId ?? newEventId()\n\t\t\ttracker.identify(email, id)\n\t\t\tbus.emit('user.registered', { email, eventId: id })\n\t\t},\n\t\tsetVariables: tracker.setVariables\n\t\t\t? (v) => tracker.setVariables!(v)\n\t\t\t: undefined,\n\t\t// Acquisition is persistence (session + first-touch Customer), not a bus event.\n\t\tsetAcquisition: tracker.setAcquisition\n\t\t\t? (a) => tracker.setAcquisition!(a)\n\t\t\t: undefined,\n\t}\n}\n\ndeclare global {\n\tinterface Window {\n\t\tappfunnel?: AppfunnelBusApi\n\t}\n}\n\n/**\n * Attach the bus's public surface to `window.appfunnel` (client-side only).\n * Returns a detach fn for unmount. No-op under SSR.\n */\nexport function attachBus(bus: FunnelBus): () => void {\n\tif (typeof window === 'undefined') return () => {}\n\tconst {\n\t\ton,\n\t\toff,\n\t\tgetVariable,\n\t\tgetVariables,\n\t\tgetCurrentPageId,\n\t\tgetCustomerId,\n\t\tgetVisitorId,\n\t\tgoTo,\n\t\tgoNext,\n\t\tgoPrevious,\n\t\tnavigation,\n\t} = bus\n\tconst api: AppfunnelBusApi = {\n\t\ton,\n\t\toff,\n\t\tgetVariable,\n\t\tgetVariables,\n\t\tgetCurrentPageId,\n\t\tgetCustomerId,\n\t\tgetVisitorId,\n\t\t// Flow control (bound closures over the bus's live nav registration).\n\t\tgoTo,\n\t\tgoNext,\n\t\tgoPrevious,\n\t\tnavigation,\n\t\tget events() {\n\t\t\treturn bus.events\n\t\t},\n\t}\n\twindow.appfunnel = api\n\treturn () => {\n\t\tif (window.appfunnel === api) delete window.appfunnel\n\t}\n}\n","/**\n * v2 localization — translated **text** (prices already localize via `Intl` in\n * {@link ./catalog}). Per doc 05: locales live in the funnel source — supported\n * locales + default + fallback are funnel config ({@link FunnelLocales}), and\n * each locale is a flat `key → string` **catalog** (`messages/en.json`, …),\n * versioned + published with the funnel. The dashboard's manual translation\n * table edits exactly these catalogs.\n *\n * Lookup walks a **fallback chain** (active → fallback → default) so a missing\n * string never blanks — it falls through, and only as a last resort returns the\n * key (flagged in dev). Interpolation is simple `{{var}}`; plurals use the\n * built-in `Intl.PluralRules`; numbers/dates/percent use `Intl`. No ICU, no rich\n * markup (markup stays in TSX).\n */\n\nimport {\n createContext,\n createElement,\n useContext,\n useEffect,\n useMemo,\n useState,\n type ReactNode,\n} from 'react'\nimport type { FunnelLocales } from '../flow/spine'\nimport { isRtl, resolveLocale, type Direction } from './locale'\n\n// Pure locale resolution lives in ./locale (React-free, shared with the\n// server/tooling entry); re-exported here so existing imports keep working.\nexport { isRtl, resolveLocale } from './locale'\nexport type { Direction } from './locale'\n\n/** locale → (message key → string). The shape of `messages/<locale>.json`. */\nexport type MessageCatalog = Record<string, Record<string, string>>\n\nexport type PluralCategory = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other'\n\n/** Replace `{{name}}` placeholders; leaves unknown ones intact. */\nfunction interpolate(str: string, params?: Record<string, string | number>): string {\n if (!params) return str\n return str.replace(/\\{\\{(\\w+)\\}\\}/g, (_, k: string) => (k in params ? String(params[k]) : `{{${k}}}`))\n}\n\n/** Walk the fallback chain for a key; undefined if absent everywhere. */\nfunction lookup(catalog: MessageCatalog, chain: string[], key: string): string | undefined {\n for (const loc of chain) {\n const v = catalog[loc]?.[key]\n if (v !== undefined) return v\n }\n return undefined\n}\n\nfunction devWarn(message: string): void {\n const env = (globalThis as { process?: { env?: { NODE_ENV?: string } } }).process?.env?.NODE_ENV\n if (env === 'production') return\n try {\n console.warn(message)\n } catch {\n /* no-op */\n }\n}\n\n// ── Public types ─────────────────────────────────────────\n\nexport interface TFunction {\n /** Translate a key, with optional `{{var}}` params. Missing → fallback → key. */\n (key: string, params?: Record<string, string | number>): string\n /** Locale-correct plural: `t.plural(n, { one: '# day', other: '# days' })` (`#` → n). */\n plural: (\n n: number,\n forms: Partial<Record<PluralCategory, string>>,\n params?: Record<string, string | number>,\n ) => string\n}\n\nexport interface Formatters {\n number: (n: number, opts?: Intl.NumberFormatOptions) => string\n date: (d: Date | number, opts?: Intl.DateTimeFormatOptions) => string\n percent: (n: number, opts?: Intl.NumberFormatOptions) => string\n}\n\nexport interface Translation {\n t: TFunction\n fmt: Formatters\n /** The active (resolved) locale. */\n locale: string\n /** Switch locale at runtime (preview / language picker). */\n setLocale: (locale: string) => void\n /** Text direction for the active locale. */\n dir: Direction\n /** The funnel's supported locales. */\n locales: string[]\n}\n\n// ── React wiring ─────────────────────────────────────────\n\ninterface LocaleContextValue {\n locale: string\n setLocale: (locale: string) => void\n config?: FunnelLocales\n catalog: MessageCatalog\n}\n\nconst LocaleContext = createContext<LocaleContextValue | null>(null)\n\nexport interface LocaleProviderProps {\n config?: FunnelLocales\n catalog?: MessageCatalog\n /** Device/browser locale (from computed context) — the resolution input. */\n detected: string\n /** Explicit override (URL/param/geo), highest priority. */\n override?: string\n children: ReactNode\n}\n\n/** Resolves + holds the active locale and the message catalog. */\nexport function LocaleProvider({\n config,\n catalog = {},\n detected,\n override,\n children,\n}: LocaleProviderProps): ReactNode {\n const [locale, setLocale] = useState(() => resolveLocale(config, detected, override))\n // Re-resolve when the inputs change (SSR-hydrated override arriving late, a\n // preview switching `locale`, config swap). A runtime `setLocale` (language\n // picker) survives re-renders — this only fires when a *prop* changes; React\n // bails out when the re-resolved locale is unchanged.\n useEffect(() => {\n setLocale(resolveLocale(config, detected, override))\n }, [config, detected, override])\n const value = useMemo<LocaleContextValue>(\n () => ({ locale, setLocale, config, catalog }),\n [locale, config, catalog],\n )\n return createElement(LocaleContext.Provider, { value }, children)\n}\n\n/** The active (resolved) funnel locale, or `'en'` if no provider — for display\n * formatting (e.g. {@link ./catalog} prices) without building the full handle. */\nexport function useActiveLocale(): string {\n return useContext(LocaleContext)?.locale ?? 'en'\n}\n\n/**\n * `const { t, fmt, locale, dir } = useTranslation()` — translated text +\n * locale-aware `Intl` formatters for the active funnel locale.\n */\nexport function useTranslation(): Translation {\n const ctx = useContext(LocaleContext)\n if (!ctx) throw new Error('useTranslation must be used inside <FunnelProvider>')\n const { locale, setLocale, config, catalog } = ctx\n\n const chain = useMemo(() => {\n const def = config?.default\n const fb = config?.fallback\n return Array.from(new Set([locale, fb, def].filter(Boolean) as string[]))\n }, [locale, config])\n\n const t = useMemo<TFunction>(() => {\n const fn = ((key: string, params?: Record<string, string | number>) => {\n const raw = lookup(catalog, chain, key)\n if (raw === undefined) {\n devWarn(`[appfunnel] missing translation: \"${key}\" (${locale})`)\n return key\n }\n return interpolate(raw, params)\n }) as TFunction\n fn.plural = (n, forms, params) => {\n let rule: PluralCategory\n try {\n rule = new Intl.PluralRules(locale).select(n) as PluralCategory\n } catch {\n rule = 'other'\n }\n const form = forms[rule] ?? forms.other ?? ''\n return interpolate(form.replace(/#/g, String(n)), params)\n }\n return fn\n }, [catalog, chain, locale])\n\n // Like formatMoney: an invalid locale/options must degrade to a plain\n // rendering, never throw mid-render.\n const fmt = useMemo<Formatters>(\n () => ({\n number: (n, opts) => {\n try {\n return new Intl.NumberFormat(locale, opts).format(n)\n } catch {\n return String(n)\n }\n },\n date: (d, opts) => {\n try {\n return new Intl.DateTimeFormat(locale, opts).format(d)\n } catch {\n return String(d instanceof Date ? d.toISOString() : d)\n }\n },\n percent: (n, opts) => {\n try {\n return new Intl.NumberFormat(locale, { style: 'percent', ...opts }).format(n)\n } catch {\n return `${(n * 100).toFixed(0)}%`\n }\n },\n }),\n [locale],\n )\n\n return {\n t,\n fmt,\n locale,\n setLocale,\n dir: isRtl(locale) ? 'rtl' : 'ltr',\n locales: config?.supported ?? [locale],\n }\n}\n","/**\n * v2 `offerings` — the **read-only** offering catalog.\n *\n * **Appfunnel does not manage currency.** Multi-currency is entirely the payment\n * provider's job: the provider (or its preview API) resolves the visitor's price,\n * and we receive a single resolved `{ amount, currency }` per offering. No FX, no\n * currency selection, no conversion on our side. (FX appears only for frozen-USD\n * *reporting*, never display — phase-3 §3.6b.) A provider that doesn't localize\n * simply gives one currency.\n *\n * Our only job is **display**: pick the offering by logical id and **format** its\n * amount. Formatting happens at read time in the funnel's **active locale** (so\n * switching language reformats `kr 79,00` ⇄ `$9.99`), while the **currency** is\n * whatever the provider resolved. Currency selection is the platform's; the\n * authoring funnel only ever names an offering id.\n *\n * The math itself (resolve/format/exponents) is pure and lives in {@link ./money}\n * so the server/tooling entry can use it without React — this module re-exports\n * it and adds the React wiring (provider + hooks).\n */\n\nimport {\n\tcreateContext,\n\tcreateElement,\n\tuseContext,\n\tuseMemo,\n\ttype ReactNode,\n} from 'react'\nimport { useActiveLocale } from '../i18n/translation'\nimport {\n\tformatOffering,\n\tformatSampleOffering,\n\ttype Offering,\n\ttype ResolvedOffering,\n\ttype SampleOffering,\n} from './money'\n\nexport {\n\tresolveOffering,\n\tbuildCatalog,\n\tformatMoney,\n\tformatOffering,\n\tformatSampleOffering,\n\tcurrencyExponent,\n} from './money'\nexport type {\n\tOffering,\n\tResolvedOffering,\n\tOfferingInput,\n\tSampleOffering,\n\tMoney,\n\tInterval,\n} from './money'\n\n// ── React wiring ─────────────────────────────────────────\n\nconst CatalogContext = createContext<Map<string, ResolvedOffering> | null>(null)\n\n/**\n * The funnel's per-slot SAMPLE pricing (`defineFunnel({ sampleOfferings })`) — flat\n * `slot → {@link SampleOffering}`. Separate from the resolved {@link CatalogContext}\n * on purpose: samples are DISPLAY-only placeholders for unassigned slots and must\n * never enter the real catalog `useCatalog` exposes (the checkout driver + tracking\n * enrich off that map — a sample has no `catalogKey` to charge). `useOffering`\n * consults it only as the fallback when the real catalog has no entry for a slot.\n */\nconst SampleContext = createContext<Record<string, SampleOffering> | null>(null)\n\nexport function CatalogProvider({\n\tcatalog,\n\tsamples,\n\tchildren,\n}: {\n\tcatalog: Map<string, ResolvedOffering>\n\t/** Per-slot sample pricing from `defineFunnel({ sampleOfferings })` — the `useOffering` fallback. */\n\tsamples?: Record<string, SampleOffering>\n\tchildren: ReactNode\n}): ReactNode {\n\treturn createElement(\n\t\tCatalogContext.Provider,\n\t\t{ value: catalog },\n\t\tcreateElement(SampleContext.Provider, { value: samples ?? null }, children)\n\t)\n}\n\n/**\n * The raw slot → {@link ResolvedOffering} catalog map (keyed by the page-facing SLOT\n * id; each entry carries its `catalogKey` CHARGE identity + price + period). Internal\n * to the package — `useOffering`/`useOfferings` format it for display, while\n * `commerce/checkout` reads it to enrich the client tracking events (money facts +\n * the charge identity the pixel loaders forward). Not re-exported from the public\n * entry (see `commerce/index.ts`).\n */\nexport function useCatalog(): Map<string, ResolvedOffering> {\n\treturn useContext(CatalogContext) ?? EMPTY\n}\nconst EMPTY = new Map<string, ResolvedOffering>()\n\n/** The funnel's per-slot sample pricing (internal — the `useOffering` fallback source). */\nfunction useSampleOfferings(): Record<string, SampleOffering> {\n\treturn useContext(SampleContext) ?? EMPTY_SAMPLES\n}\nconst EMPTY_SAMPLES: Record<string, SampleOffering> = {}\n\n/**\n * `useOffering('monthly')` — one offering for a slot, formatted in the active locale.\n *\n * Resolution precedence:\n * 1. the slot's real, assigned+resolved offering (a provider-resolved price) →\n * the {@link Offering} (no `sample` flag);\n * 2. else the funnel's {@link SampleOffering} for that slot (declared in\n * `defineFunnel({ sampleOfferings })`) → the SAME {@link Offering} shape flagged\n * `sample: true`, so a page renders identically while the slot is unassigned;\n * 3. else `undefined` (unknown/unassigned slot with no sample).\n *\n * A sample only ever surfaces for an UNASSIGNED slot, which the LIVE-publish gate\n * blocks from promotion — so samples appear only in editor/preview + `appfunnel\n * dev`, never to a paying visitor. `<Checkout>`/`<UpsellButton>` refuse to charge a\n * `sample` offering (the server refuses an unassigned slot regardless).\n */\nexport function useOffering(id: string | undefined): Offering | undefined {\n\tconst catalog = useCatalog()\n\tconst samples = useSampleOfferings()\n\tconst locale = useActiveLocale()\n\tconst resolved = id ? catalog.get(id) : undefined\n\t// Sample is the FALLBACK only — a resolved real offering always wins.\n\tconst sample = !resolved && id ? samples[id] : undefined\n\treturn useMemo(() => {\n\t\tif (resolved) return formatOffering(resolved, locale)\n\t\tif (sample && id) return formatSampleOffering(id, sample, locale)\n\t\treturn undefined\n\t}, [resolved, sample, id, locale])\n}\n\n/** `useOfferings()` — every offering, formatted in the active locale, in order. */\nexport function useOfferings(): Offering[] {\n\tconst catalog = useCatalog()\n\tconst locale = useActiveLocale()\n\treturn useMemo(\n\t\t() => Array.from(catalog.values()).map((r) => formatOffering(r, locale)),\n\t\t[catalog, locale]\n\t)\n}\n","/**\n * Imperative, promise-based modal registry — our trimmed adaptation of\n * eBay's `@ebay/nice-modal-react` (MIT). The model: a module-level registry +\n * a reducer-backed store, so any code can `showModal(MyModal)` from anywhere\n * (no prop-drilling, no rendering the modal where you trigger it) and get back a\n * **promise** that resolves when the modal calls `resolve()` — perfect for\n * confirm/upsell/detail flows.\n *\n * Every modal is keyed by a **stable id**, which also makes it natural to bind\n * analytics later (open/close per id, like pages).\n *\n * Pair it with the controlled chrome in {@link ./overlay}: a `defineModal`\n * component renders a `<Sheet open={m.visible} onClose={m.hide}>`/`<Modal>`.\n * The runtime ({@link ./namespaces}.FunnelProvider) mounts {@link ModalRoot} for\n * you, so there's no provider to wire.\n *\n * Trimmed vs upstream: dropped the antd/mui/bootstrap binding adapters and the\n * standalone `<Provider>` (folded into the funnel runtime).\n */\n\nimport {\n\tcreateContext,\n\tcreateElement,\n\tuseCallback,\n\tuseContext,\n\tuseEffect,\n\tuseMemo,\n\tuseReducer,\n\ttype ComponentType,\n\ttype Dispatch,\n\ttype ReactNode,\n} from 'react'\n\n// ── State ────────────────────────────────────────────────\n\nexport interface ModalState {\n\tid: string\n\targs?: Record<string, unknown>\n\tvisible?: boolean\n\tdelayVisible?: boolean\n\tkeepMounted?: boolean\n}\nexport interface ModalStore {\n\t[id: string]: ModalState\n}\ninterface ModalAction {\n\ttype: 'show' | 'hide' | 'remove' | 'set-flags' | 'reset'\n\tpayload: {\n\t\t/** Absent for `reset`, which clears every modal at once. */\n\t\tmodalId?: string\n\t\targs?: Record<string, unknown>\n\t\tflags?: Record<string, unknown>\n\t}\n}\ninterface ModalCallbacks {\n\t[id: string]: {\n\t\tresolve: (v: unknown) => void\n\t\treject: (v: unknown) => void\n\t\tpromise: Promise<unknown>\n\t}\n}\n\n/** The handle `useModal()` returns to control one modal. */\nexport interface ModalHandler<Props = Record<string, unknown>> {\n\tid: string\n\targs?: Record<string, unknown>\n\tvisible: boolean\n\tkeepMounted: boolean\n\tshow: (args?: Props) => Promise<unknown>\n\thide: () => Promise<unknown>\n\tremove: () => void\n\t/** Resolve the promise returned by `show()` (e.g. a confirm result). */\n\tresolve: (value?: unknown) => void\n\t/** Reject the promise returned by `show()`. */\n\treject: (value?: unknown) => void\n\t/** Resolve the promise returned by `hide()` (after a close transition). */\n\tresolveHide: (value?: unknown) => void\n}\n\n// ── Registry + dispatch ──────────────────────────────────\n\nconst symModalId = Symbol('AppfunnelModalId')\nconst initialState: ModalStore = {}\nconst ModalStateContext = createContext<ModalStore>(initialState)\nconst ModalIdContext = createContext<string | null>(null)\n/** The provider-scoped dispatch — components/hooks always read this, never the module fallback. */\nconst ModalDispatchContext = createContext<Dispatch<ModalAction> | null>(null)\n\nconst REGISTRY: {\n\t[id: string]: { comp: ComponentType<any>; props?: Record<string, unknown> }\n} = {}\nconst ALREADY_MOUNTED: Record<string, boolean> = {}\nconst modalCallbacks: ModalCallbacks = {}\nconst hideCallbacks: ModalCallbacks = {}\n\nlet uid = 0\nconst getUid = () => `_af_modal_${uid++}`\n\n/**\n * Module-level **fallback** dispatch for the imperative API (`showModal` called\n * from plain code with no React context). Runtimes register on a stack in a\n * mount *effect* — never during render, so concurrent SSR renders can't race on\n * it, and a server render (where effects don't run) never touches module state.\n * The imperative API binds to the most recently mounted runtime; inside React,\n * hooks use the provider-scoped {@link ModalDispatchContext} instead.\n */\nconst runtimeStack: Dispatch<ModalAction>[] = []\n\nconst dispatch: Dispatch<ModalAction> = (action) => {\n\tconst top = runtimeStack[runtimeStack.length - 1]\n\tif (!top) {\n\t\tthrow new Error(\n\t\t\t'No modal dispatch — render inside <FunnelProvider> (which mounts the modal runtime).'\n\t\t)\n\t}\n\ttop(action)\n}\n\nexport const modalReducer = (\n\tstate: ModalStore = initialState,\n\taction: ModalAction\n): ModalStore => {\n\tconst { args, flags } = action.payload\n\t// Only `reset` omits it; every other branch below is keyed on a specific modal.\n\tconst modalId = action.payload.modalId as string\n\tswitch (action.type) {\n\t\tcase 'reset':\n\t\t\treturn initialState\n\t\tcase 'show':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\t[modalId]: {\n\t\t\t\t\t...state[modalId],\n\t\t\t\t\tid: modalId,\n\t\t\t\t\targs,\n\t\t\t\t\t// Mount first, then flip visible on the next effect → enter transition.\n\t\t\t\t\tvisible: !!ALREADY_MOUNTED[modalId],\n\t\t\t\t\tdelayVisible: !ALREADY_MOUNTED[modalId],\n\t\t\t\t},\n\t\t\t}\n\t\tcase 'hide':\n\t\t\treturn state[modalId]\n\t\t\t\t? { ...state, [modalId]: { ...state[modalId], visible: false } }\n\t\t\t\t: state\n\t\tcase 'remove': {\n\t\t\tconst next = { ...state }\n\t\t\tdelete next[modalId]\n\t\t\treturn next\n\t\t}\n\t\tcase 'set-flags':\n\t\t\treturn { ...state, [modalId]: { ...state[modalId], ...flags } }\n\t\tdefault:\n\t\t\treturn state\n\t}\n}\n\nfunction idOf(modal: string | ComponentType<any>): string {\n\tif (typeof modal === 'string') return modal\n\tconst m = modal as ComponentType<any> & { [symModalId]?: string }\n\tif (!m[symModalId]) m[symModalId] = getUid()\n\treturn m[symModalId] as string\n}\n\n// ── Imperative API (callable from anywhere) ──────────────\n\n/** Register a component as an id-keyed modal so the placeholder can render it. */\nexport function registerModal(\n\tid: string,\n\tcomp: ComponentType<any>,\n\tprops?: Record<string, unknown>\n): void {\n\tif (!REGISTRY[id]) REGISTRY[id] = { comp, props }\n\telse REGISTRY[id].props = props\n}\n\nexport function unregisterModal(id: string): void {\n\tdelete REGISTRY[id]\n}\n\nfunction showModalVia<T = unknown>(\n\td: Dispatch<ModalAction>,\n\tmodal: string | ComponentType<any>,\n\targs?: Record<string, unknown>\n): Promise<T> {\n\tconst id = idOf(modal)\n\tif (typeof modal !== 'string' && !REGISTRY[id]) registerModal(id, modal)\n\td({ type: 'show', payload: { modalId: id, args } })\n\tif (!modalCallbacks[id]) {\n\t\tlet res!: (v: unknown) => void\n\t\tlet rej!: (v: unknown) => void\n\t\tconst promise = new Promise<unknown>((resolve, reject) => {\n\t\t\tres = resolve\n\t\t\trej = reject\n\t\t})\n\t\tmodalCallbacks[id] = { resolve: res, reject: rej, promise }\n\t}\n\treturn modalCallbacks[id].promise as Promise<T>\n}\n\n/** Show a modal (by component or id). Returns a promise resolved by `resolve()`. */\nexport function showModal<T = unknown>(\n\tmodal: string | ComponentType<any>,\n\targs?: Record<string, unknown>\n): Promise<T> {\n\treturn showModalVia(dispatch, modal, args)\n}\n\nfunction hideModalVia<T = unknown>(\n\td: Dispatch<ModalAction>,\n\tmodal: string | ComponentType<any>\n): Promise<T> {\n\tconst id = idOf(modal)\n\td({ type: 'hide', payload: { modalId: id } })\n\tdelete modalCallbacks[id]\n\tif (!hideCallbacks[id]) {\n\t\tlet res!: (v: unknown) => void\n\t\tlet rej!: (v: unknown) => void\n\t\tconst promise = new Promise<unknown>((resolve, reject) => {\n\t\t\tres = resolve\n\t\t\trej = reject\n\t\t})\n\t\thideCallbacks[id] = { resolve: res, reject: rej, promise }\n\t}\n\treturn hideCallbacks[id].promise as Promise<T>\n}\n\n/** Hide a modal. Returns a promise resolved by `resolveHide()` (post-transition). */\nexport function hideModal<T = unknown>(\n\tmodal: string | ComponentType<any>\n): Promise<T> {\n\treturn hideModalVia(dispatch, modal)\n}\n\nfunction removeModalVia(\n\td: Dispatch<ModalAction>,\n\tmodal: string | ComponentType<any>\n): void {\n\tconst id = idOf(modal)\n\td({ type: 'remove', payload: { modalId: id } })\n\tdelete modalCallbacks[id]\n\tdelete hideCallbacks[id]\n}\n\n/** Remove a modal from the tree (frees its state; better than just hiding). */\nexport function removeModal(modal: string | ComponentType<any>): void {\n\tremoveModalVia(dispatch, modal)\n}\n\n/**\n * Close every open modal at once and settle anything awaiting them.\n *\n * The registry is mounted ABOVE the flow (`FunnelProvider` renders `ModalRoot`, `FunnelView` lives\n * inside it), so a modal a page opened outlives that page — it would otherwise sit on top of the next\n * screen. `FunnelView` calls this on every page change; authors rarely need it directly.\n *\n * Pending `showModal()` promises resolve with `undefined` rather than hanging forever, so `await\n * showModal(...)` in a page handler unblocks and can tell \"dismissed\" from a real result. No-ops when\n * no runtime is mounted (SSR, or a tree rendered without `FunnelProvider`).\n */\nexport function dismissAllModals(): void {\n\tconst top = runtimeStack[runtimeStack.length - 1]\n\tif (!top) return\n\ttop({ type: 'reset', payload: {} })\n\tfor (const id of Object.keys(modalCallbacks)) {\n\t\tmodalCallbacks[id].resolve(undefined)\n\t\tdelete modalCallbacks[id]\n\t}\n\tfor (const id of Object.keys(hideCallbacks)) {\n\t\thideCallbacks[id].resolve(undefined)\n\t\tdelete hideCallbacks[id]\n\t}\n}\n\nfunction setFlags(\n\td: Dispatch<ModalAction>,\n\tid: string,\n\tflags: Record<string, unknown>\n): void {\n\td({ type: 'set-flags', payload: { modalId: id, flags } })\n}\n\n// ── Hook ─────────────────────────────────────────────────\n\nexport function useModal(): ModalHandler\nexport function useModal(\n\tmodal: string,\n\targs?: Record<string, unknown>\n): ModalHandler\nexport function useModal<P extends object>(\n\tmodal: ComponentType<P>,\n\targs?: Partial<P>\n): ModalHandler<P>\nexport function useModal(\n\tmodal?: string | ComponentType<any>,\n\targs?: Record<string, unknown>\n): ModalHandler {\n\tconst modals = useContext(ModalStateContext)\n\tconst contextId = useContext(ModalIdContext)\n\t// Prefer the provider-scoped dispatch; the module fallback covers hook usage\n\t// outside <ModalRuntime> (which itself throws a descriptive error).\n\tconst d = useContext(ModalDispatchContext) ?? dispatch\n\tconst isComponent = !!modal && typeof modal !== 'string'\n\tconst id = modal ? idOf(modal) : contextId\n\tif (!id)\n\t\tthrow new Error(\n\t\t\t'useModal: no modal id (call inside a defineModal component, or pass an id/component).'\n\t\t)\n\n\tuseEffect(() => {\n\t\tif (isComponent && !REGISTRY[id])\n\t\t\tregisterModal(id, modal as ComponentType<any>, args)\n\t}, [isComponent, id, modal, args])\n\n\tconst info = modals[id]\n\tconst show = useCallback(\n\t\t(a?: Record<string, unknown>) => showModalVia(d, id, a),\n\t\t[d, id]\n\t)\n\tconst hide = useCallback(() => hideModalVia(d, id), [d, id])\n\tconst remove = useCallback(() => removeModalVia(d, id), [d, id])\n\tconst resolve = useCallback(\n\t\t(v?: unknown) => {\n\t\t\tmodalCallbacks[id]?.resolve(v)\n\t\t\tdelete modalCallbacks[id]\n\t\t},\n\t\t[id]\n\t)\n\tconst reject = useCallback(\n\t\t(v?: unknown) => {\n\t\t\tmodalCallbacks[id]?.reject(v)\n\t\t\tdelete modalCallbacks[id]\n\t\t},\n\t\t[id]\n\t)\n\tconst resolveHide = useCallback(\n\t\t(v?: unknown) => {\n\t\t\thideCallbacks[id]?.resolve(v)\n\t\t\tdelete hideCallbacks[id]\n\t\t},\n\t\t[id]\n\t)\n\n\treturn useMemo(\n\t\t() => ({\n\t\t\tid,\n\t\t\targs: info?.args,\n\t\t\tvisible: !!info?.visible,\n\t\t\tkeepMounted: !!info?.keepMounted,\n\t\t\tshow,\n\t\t\thide,\n\t\t\tremove,\n\t\t\tresolve,\n\t\t\treject,\n\t\t\tresolveHide,\n\t\t}),\n\t\t[\n\t\t\tid,\n\t\t\tinfo?.args,\n\t\t\tinfo?.visible,\n\t\t\tinfo?.keepMounted,\n\t\t\tshow,\n\t\t\thide,\n\t\t\tremove,\n\t\t\tresolve,\n\t\t\treject,\n\t\t\tresolveHide,\n\t\t]\n\t)\n}\n\n// ── defineModal (HOC) ────────────────────────────────────\n\nexport interface ModalHocProps {\n\tid: string\n\tdefaultVisible?: boolean\n\tkeepMounted?: boolean\n}\n\n/**\n * Wrap a component into an id-keyed modal. Inside it, `useModal()` (no args)\n * gives the handle. Render a controlled `<Sheet>`/`<Modal>` with\n * `open={m.visible} onClose={m.hide}`.\n */\nexport function defineModal<P extends object>(\n\tComp: ComponentType<P>\n): ComponentType<P & ModalHocProps> {\n\treturn function Wrapped({\n\t\tid,\n\t\tdefaultVisible,\n\t\tkeepMounted,\n\t\t...props\n\t}: P & ModalHocProps): ReactNode {\n\t\tconst { args, show } = useModal(id)\n\t\tconst modals = useContext(ModalStateContext)\n\t\tconst d = useContext(ModalDispatchContext) ?? dispatch\n\t\tconst shouldMount = !!modals[id]\n\n\t\tuseEffect(() => {\n\t\t\tif (defaultVisible) show()\n\t\t\tALREADY_MOUNTED[id] = true\n\t\t\treturn () => {\n\t\t\t\tdelete ALREADY_MOUNTED[id]\n\t\t\t}\n\t\t}, [id, show, defaultVisible])\n\n\t\tuseEffect(() => {\n\t\t\tif (keepMounted) setFlags(d, id, { keepMounted: true })\n\t\t}, [d, id, keepMounted])\n\n\t\tconst delayVisible = modals[id]?.delayVisible\n\t\tuseEffect(() => {\n\t\t\tif (delayVisible) show(args)\n\t\t}, [delayVisible, args, show])\n\n\t\tif (!shouldMount) return null\n\t\treturn createElement(\n\t\t\tModalIdContext.Provider,\n\t\t\t{ value: id },\n\t\t\tcreateElement(Comp, { ...(props as P), ...args })\n\t\t)\n\t}\n}\n\n// ── Runtime (mounted by FunnelProvider) ──────────────────\n\n/** Renders every visible registered modal. Mounted once by the funnel runtime. */\nexport function ModalRoot(): ReactNode {\n\tconst modals = useContext(ModalStateContext)\n\tconst toRender = Object.keys(modals)\n\t\t.filter((id) => REGISTRY[id])\n\t\t.map((id) => ({ id, ...REGISTRY[id] }))\n\treturn createElement(\n\t\t'div',\n\t\t{ 'data-appfunnel-modal-root': '' },\n\t\t...toRender.map((t) =>\n\t\t\tcreateElement(t.comp, { key: t.id, id: t.id, ...t.props })\n\t\t)\n\t)\n}\n\n/**\n * Provides the modal store + dispatch (context-scoped) + renders {@link ModalRoot}.\n * Wrapped around the funnel tree by `FunnelProvider`.\n *\n * The module-level fallback dispatch (for the imperative `showModal()` API) is\n * bound in a mount **effect** — never during render — so SSR and concurrent\n * renders are safe. With multiple simultaneous providers the imperative API\n * binds to the **most recently mounted** one (a dev warning fires); hooks inside\n * each tree always use their own provider's dispatch via context.\n */\nexport function ModalRuntime({ children }: { children: ReactNode }): ReactNode {\n\tconst [state, localDispatch] = useReducer(modalReducer, initialState)\n\tuseEffect(() => {\n\t\truntimeStack.push(localDispatch)\n\t\tif (runtimeStack.length > 1) {\n\t\t\ttry {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[appfunnel] ${runtimeStack.length} modal runtimes are mounted — the imperative showModal()/hideModal() API binds to the most recent one. Use the useModal() hook inside each tree instead.`\n\t\t\t\t)\n\t\t\t} catch {\n\t\t\t\t/* no-op */\n\t\t\t}\n\t\t}\n\t\treturn () => {\n\t\t\tconst i = runtimeStack.indexOf(localDispatch)\n\t\t\tif (i !== -1) runtimeStack.splice(i, 1)\n\t\t}\n\t}, [])\n\treturn createElement(\n\t\tModalDispatchContext.Provider,\n\t\t{ value: localDispatch },\n\t\tcreateElement(\n\t\t\tModalStateContext.Provider,\n\t\t\t{ value: state },\n\t\t\tchildren,\n\t\t\tcreateElement(ModalRoot, null)\n\t\t)\n\t)\n}\n","\"use client\";\nimport { createContext } from 'react';\n\nconst LayoutGroupContext = createContext({});\n\nexport { LayoutGroupContext };\n//# sourceMappingURL=LayoutGroupContext.mjs.map\n","\"use client\"\n\nimport { useRef } from \"react\"\n\ntype Init<T> = () => T\n\n/**\n * Creates a constant value over the lifecycle of a component.\n *\n * Even if `useMemo` is provided an empty array as its final argument, it doesn't offer\n * a guarantee that it won't re-run for performance reasons later on. By using `useConstant`\n * you can ensure that initialisers don't execute twice or more.\n */\nexport function useConstant<T>(init: Init<T>) {\n const ref = useRef<T | null>(null)\n\n if (ref.current === null) {\n ref.current = init()\n }\n\n return ref.current\n}\n","export const isBrowser = typeof window !== \"undefined\"\n","\"use client\"\n\nimport { useEffect, useLayoutEffect } from \"react\"\nimport { isBrowser } from \"./is-browser\"\n\nexport const useIsomorphicLayoutEffect = isBrowser ? useLayoutEffect : useEffect\n","\"use client\"\n\nimport { createContext } from \"react\"\nimport type { PresenceContextProps } from \"motion-dom\"\n\nexport type { PresenceContextProps }\n\n/**\n * @public\n */\nexport const PresenceContext =\n /* @__PURE__ */ createContext<PresenceContextProps | null>(null)\n","export function addUniqueItem<T>(arr: T[], item: T) {\n if (arr.indexOf(item) === -1) arr.push(item)\n}\n\nexport function removeItem<T>(arr: T[], item: T) {\n const index = arr.indexOf(item)\n if (index > -1) arr.splice(index, 1)\n}\n\n// Adapted from array-move\nexport function moveItem<T>([...arr]: T[], fromIndex: number, toIndex: number) {\n const startIndex = fromIndex < 0 ? arr.length + fromIndex : fromIndex\n\n if (startIndex >= 0 && startIndex < arr.length) {\n const endIndex = toIndex < 0 ? arr.length + toIndex : toIndex\n\n const [item] = arr.splice(fromIndex, 1)\n arr.splice(endIndex, 0, item)\n }\n\n return arr\n}\n","export const clamp = (min: number, max: number, v: number) => {\n if (v > max) return max\n if (v < min) return min\n return v\n}\n","export function formatErrorMessage(message: string, errorCode?: string) {\n return errorCode\n ? `${message}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${errorCode}`\n : message\n}\n","import { formatErrorMessage } from \"./format-error-message\"\n\nexport type DevMessage = (\n check: boolean,\n message: string,\n errorCode?: string\n) => void\n\nlet warning: DevMessage = () => {}\nlet invariant: DevMessage = () => {}\n\nif (\n typeof process !== \"undefined\" &&\n process.env?.NODE_ENV !== \"production\"\n) {\n warning = (check, message, errorCode) => {\n if (!check && typeof console !== \"undefined\") {\n console.warn(formatErrorMessage(message, errorCode))\n }\n }\n\n invariant = (check, message, errorCode) => {\n if (!check) {\n throw new Error(formatErrorMessage(message, errorCode))\n }\n }\n}\n\nexport { invariant, warning }\n","export const MotionGlobalConfig: {\n skipAnimations?: boolean\n instantAnimations?: boolean\n useManualTiming?: boolean\n WillChange?: any\n mix?: <T>(a: T, b: T) => (p: number) => T\n} = {}\n","/**\n * Check if value is a numerical string, ie a string that is purely a number eg \"100\" or \"-100.1\"\n */\nexport const isNumericalString = (v: string) => /^-?(?:\\d+(?:\\.\\d+)?|\\.\\d+)$/u.test(v)\n","export const isObject = (value: unknown): value is object =>\n typeof value === \"object\" && value !== null\n","/**\n * Check if the value is a zero value string like \"0px\" or \"0%\"\n */\nexport const isZeroValueString = (v: string) => /^0[^.\\s]+$/u.test(v)\n","/*#__NO_SIDE_EFFECTS__*/\nexport function memo<T extends any>(callback: () => T) {\n let result: T | undefined\n\n return () => {\n if (result === undefined) result = callback()\n return result\n }\n}\n","/*#__NO_SIDE_EFFECTS__*/\nexport const noop = <T>(any: T): T => any\n","/**\n * Pipe\n * Compose other transformers to run linearily\n * pipe(min(20), max(40))\n * @param {...functions} transformers\n * @return {function}\n */\nexport const pipe = (...transformers: Function[]) =>\n transformers.reduce((a, b) => (v: any) => b(a(v)))\n","/*\n Progress within given range\n\n Given a lower limit and an upper limit, we return the progress\n (expressed as a number 0-1) represented by the given value, and\n limit that progress to within 0-1.\n*/\n/*#__NO_SIDE_EFFECTS__*/\nexport const progress = (from: number, to: number, value: number) => {\n const range = to - from\n return range ? (value - from) / range : 1\n}\n","import { addUniqueItem, removeItem } from \"./array\"\n\ntype GenericHandler = (...args: any) => void\n\nexport class SubscriptionManager<Handler extends GenericHandler> {\n private subscriptions: Handler[] = []\n\n add(handler: Handler): VoidFunction {\n addUniqueItem(this.subscriptions, handler)\n return () => removeItem(this.subscriptions, handler)\n }\n\n notify(\n a?: Parameters<Handler>[0],\n b?: Parameters<Handler>[1],\n c?: Parameters<Handler>[2]\n ) {\n const numSubscriptions = this.subscriptions.length\n\n if (!numSubscriptions) return\n\n if (numSubscriptions === 1) {\n /**\n * If there's only a single handler we can just call it without invoking a loop.\n */\n this.subscriptions[0](a, b, c)\n } else {\n for (let i = 0; i < numSubscriptions; i++) {\n /**\n * Check whether the handler exists before firing as it's possible\n * the subscriptions were modified during this loop running.\n */\n const handler = this.subscriptions[i]\n handler && handler(a, b, c)\n }\n }\n }\n\n getSize() {\n return this.subscriptions.length\n }\n\n clear() {\n this.subscriptions.length = 0\n }\n}\n","/**\n * Converts seconds to milliseconds\n *\n * @param seconds - Time in seconds.\n * @return milliseconds - Converted time in milliseconds.\n */\n\n/*#__NO_SIDE_EFFECTS__*/\nexport const secondsToMilliseconds = (seconds: number) => seconds * 1000\n\n/*#__NO_SIDE_EFFECTS__*/\nexport const millisecondsToSeconds = (milliseconds: number) =>\n milliseconds / 1000\n","/*\n Convert velocity into velocity per second\n*/\n/*#__NO_SIDE_EFFECTS__*/\nexport const velocityPerSecond = (velocity: number, frameDuration: number) =>\n frameDuration ? velocity * (1000 / frameDuration) : 0\n","import { formatErrorMessage } from \"./format-error-message\"\n\nconst warned = new Set<string>()\n\nexport function hasWarned(message: string) {\n return warned.has(message)\n}\n\nexport function warnOnce(\n condition: boolean,\n message: string,\n errorCode?: string\n) {\n if (condition || warned.has(message)) return\n\n console.warn(formatErrorMessage(message, errorCode))\n warned.add(message)\n}\n","/*\n Bezier function generator\n This has been modified from Gaëtan Renaudeau's BezierEasing\n https://github.com/gre/bezier-easing/blob/master/src/index.js\n https://github.com/gre/bezier-easing/blob/master/LICENSE\n \n I've removed the newtonRaphsonIterate algo because in benchmarking it\n wasn't noticeably faster than binarySubdivision, indeed removing it\n usually improved times, depending on the curve.\n I also removed the lookup table, as for the added bundle size and loop we're\n only cutting ~4 or so subdivision iterations. I bumped the max iterations up\n to 12 to compensate and this still tended to be faster for no perceivable\n loss in accuracy.\n Usage\n const easeOut = cubicBezier(.17,.67,.83,.67);\n const x = easeOut(0.5); // returns 0.627...\n*/\n\nimport { noop } from \"../noop\"\n\n// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.\nconst calcBezier = (t: number, a1: number, a2: number) =>\n (((1.0 - 3.0 * a2 + 3.0 * a1) * t + (3.0 * a2 - 6.0 * a1)) * t + 3.0 * a1) *\n t\n\nconst subdivisionPrecision = 0.0000001\nconst subdivisionMaxIterations = 12\n\nfunction binarySubdivide(\n x: number,\n lowerBound: number,\n upperBound: number,\n mX1: number,\n mX2: number\n) {\n let currentX: number\n let currentT: number\n let i: number = 0\n\n do {\n currentT = lowerBound + (upperBound - lowerBound) / 2.0\n currentX = calcBezier(currentT, mX1, mX2) - x\n if (currentX > 0.0) {\n upperBound = currentT\n } else {\n lowerBound = currentT\n }\n } while (\n Math.abs(currentX) > subdivisionPrecision &&\n ++i < subdivisionMaxIterations\n )\n\n return currentT\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nexport function cubicBezier(\n mX1: number,\n mY1: number,\n mX2: number,\n mY2: number\n) {\n // If this is a linear gradient, return linear easing\n if (mX1 === mY1 && mX2 === mY2) return noop\n\n const getTForX = (aX: number) => binarySubdivide(aX, 0, 1, mX1, mX2)\n\n // If animation is at start/end, return t without easing\n return (t: number) =>\n t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2)\n}\n","// Accepts an easing function and returns a new one that outputs mirrored values for\n\nimport { EasingModifier } from \"../types\"\n\n// the second half of the animation. Turns easeIn into easeInOut.\n/*#__NO_SIDE_EFFECTS__*/\nexport const mirrorEasing: EasingModifier = (easing) => (p) =>\n p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2\n","// Accepts an easing function and returns a new one that outputs reversed values.\n\nimport { EasingModifier } from \"../types\"\n\n// Turns easeIn into easeOut.\n/*#__NO_SIDE_EFFECTS__*/\nexport const reverseEasing: EasingModifier = (easing) => (p) =>\n 1 - easing(1 - p)\n","import { cubicBezier } from \"./cubic-bezier\"\nimport { mirrorEasing } from \"./modifiers/mirror\"\nimport { reverseEasing } from \"./modifiers/reverse\"\n\nexport const backOut = /*@__PURE__*/ cubicBezier(0.33, 1.53, 0.69, 0.99)\nexport const backIn = /*@__PURE__*/ reverseEasing(backOut)\nexport const backInOut = /*@__PURE__*/ mirrorEasing(backIn)\n","import { backIn } from \"./back\"\n\nexport const anticipate = (p: number) =>\n p >= 1\n ? 1\n : (p *= 2) < 1\n ? 0.5 * backIn(p)\n : 0.5 * (2 - Math.pow(2, -10 * (p - 1)))\n","import { mirrorEasing } from \"./modifiers/mirror\"\nimport { reverseEasing } from \"./modifiers/reverse\"\nimport { EasingFunction } from \"./types\"\n\nexport const circIn: EasingFunction = (p) => 1 - Math.sin(Math.acos(p))\nexport const circOut = reverseEasing(circIn)\nexport const circInOut = mirrorEasing(circIn)\n","import { cubicBezier } from \"./cubic-bezier\"\n\nexport const easeIn = /*@__PURE__*/ cubicBezier(0.42, 0, 1, 1)\nexport const easeOut = /*@__PURE__*/ cubicBezier(0, 0, 0.58, 1)\nexport const easeInOut = /*@__PURE__*/ cubicBezier(0.42, 0, 0.58, 1)\n","import { Easing } from \"../types\"\n\n/*#__NO_SIDE_EFFECTS__*/\nexport const isEasingArray = (ease: any): ease is Easing[] => {\n return Array.isArray(ease) && typeof ease[0] !== \"number\"\n}\n","import { BezierDefinition, Easing } from \"../types\"\n\n/*#__NO_SIDE_EFFECTS__*/\nexport const isBezierDefinition = (\n easing: Easing | Easing[]\n): easing is BezierDefinition =>\n Array.isArray(easing) && typeof easing[0] === \"number\"\n","import { invariant } from \"../../errors\"\nimport { noop } from \"../../noop\"\nimport { anticipate } from \"../anticipate\"\nimport { backIn, backInOut, backOut } from \"../back\"\nimport { circIn, circInOut, circOut } from \"../circ\"\nimport { cubicBezier } from \"../cubic-bezier\"\nimport { easeIn, easeInOut, easeOut } from \"../ease\"\nimport { Easing, EasingFunction } from \"../types\"\nimport { isBezierDefinition } from \"./is-bezier-definition\"\n\nconst easingLookup = {\n linear: noop,\n easeIn,\n easeInOut,\n easeOut,\n circIn,\n circInOut,\n circOut,\n backIn,\n backInOut,\n backOut,\n anticipate,\n}\n\nconst isValidEasing = (easing: Easing): easing is keyof typeof easingLookup => {\n return typeof easing === \"string\"\n}\n\nexport const easingDefinitionToFunction = (\n definition: Easing\n): EasingFunction => {\n if (isBezierDefinition(definition)) {\n // If cubic bezier definition, create bezier curve\n invariant(\n definition.length === 4,\n `Cubic bezier arrays must contain four numerical values.`,\n \"cubic-bezier-length\"\n )\n\n const [x1, y1, x2, y2] = definition\n return cubicBezier(x1, y1, x2, y2)\n } else if (isValidEasing(definition)) {\n // Else lookup from table\n invariant(\n easingLookup[definition] !== undefined,\n `Invalid easing type '${definition}'`,\n \"invalid-easing-type\"\n )\n return easingLookup[definition]\n }\n\n return definition\n}\n","import { StepId } from \"./types\"\n\nexport const stepsOrder: StepId[] = [\n \"setup\", // Compute\n \"read\", // Read\n \"resolveKeyframes\", // Write/Read/Write/Read\n \"preUpdate\", // Compute\n \"update\", // Compute\n \"preRender\", // Compute\n \"render\", // Write\n \"postRender\", // Compute\n] as const\n\nexport type StepNames = (typeof stepsOrder)[number]\n","import { FrameData, Process, Step } from \"./types\"\n\nexport function createRenderStep(runNextFrame: () => void): Step {\n /**\n * We create and reuse two queues, one to queue jobs for the current frame\n * and one for the next. We reuse to avoid triggering GC after x frames.\n */\n let thisFrame = new Set<Process>()\n let nextFrame = new Set<Process>()\n\n /**\n * Track whether we're currently processing jobs in this step. This way\n * we can decide whether to schedule new jobs for this frame or next.\n */\n let isProcessing = false\n\n let flushNextFrame = false\n\n /**\n * A set of processes which were marked keepAlive when scheduled.\n */\n const toKeepAlive = new WeakSet<Process>()\n\n let latestFrameData: FrameData = {\n delta: 0.0,\n timestamp: 0.0,\n isProcessing: false,\n }\n\n function triggerCallback(callback: Process) {\n if (toKeepAlive.has(callback)) {\n step.schedule(callback)\n runNextFrame()\n }\n\n callback(latestFrameData)\n }\n\n const step: Step = {\n /**\n * Schedule a process to run on the next frame.\n */\n schedule: (callback, keepAlive = false, immediate = false) => {\n const addToCurrentFrame = immediate && isProcessing\n const queue = addToCurrentFrame ? thisFrame : nextFrame\n\n if (keepAlive) toKeepAlive.add(callback)\n\n queue.add(callback)\n\n return callback\n },\n\n /**\n * Cancel the provided callback from running on the next frame.\n */\n cancel: (callback) => {\n nextFrame.delete(callback)\n toKeepAlive.delete(callback)\n },\n\n /**\n * Execute all schedule callbacks.\n */\n process: (frameData) => {\n latestFrameData = frameData\n\n /**\n * If we're already processing we've probably been triggered by a flushSync\n * inside an existing process. Instead of executing, mark flushNextFrame\n * as true and ensure we flush the following frame at the end of this one.\n */\n if (isProcessing) {\n flushNextFrame = true\n return\n }\n\n isProcessing = true\n\n // Swap this frame and the next to avoid GC\n const prevFrame = thisFrame\n thisFrame = nextFrame\n nextFrame = prevFrame\n\n // Execute this frame\n thisFrame.forEach(triggerCallback)\n\n // Clear the frame so no callbacks remain. This is to avoid\n // memory leaks should this render step not run for a while.\n thisFrame.clear()\n\n isProcessing = false\n\n if (flushNextFrame) {\n flushNextFrame = false\n step.process(frameData)\n }\n },\n }\n\n return step\n}\n","import { MotionGlobalConfig } from \"motion-utils\"\nimport { stepsOrder } from \"./order\"\nimport { createRenderStep } from \"./render-step\"\nimport { Batcher, FrameData, Process, Steps } from \"./types\"\n\nconst maxElapsed = 40\n\nexport function createRenderBatcher(\n scheduleNextBatch: (callback: Function) => void,\n allowKeepAlive: boolean\n) {\n let runNextFrame = false\n let useDefaultElapsed = true\n\n const state: FrameData = {\n delta: 0.0,\n timestamp: 0.0,\n isProcessing: false,\n }\n\n const flagRunNextFrame = () => (runNextFrame = true)\n\n const steps = stepsOrder.reduce((acc, key) => {\n acc[key] = createRenderStep(flagRunNextFrame)\n return acc\n }, {} as Steps)\n\n const {\n setup,\n read,\n resolveKeyframes,\n preUpdate,\n update,\n preRender,\n render,\n postRender,\n } = steps\n\n const processBatch = () => {\n const useManualTiming = MotionGlobalConfig.useManualTiming\n const timestamp = useManualTiming\n ? state.timestamp\n : performance.now()\n runNextFrame = false\n\n if (!useManualTiming) {\n state.delta = useDefaultElapsed\n ? 1000 / 60\n : Math.max(Math.min(timestamp - state.timestamp, maxElapsed), 1)\n }\n\n state.timestamp = timestamp\n state.isProcessing = true\n\n // Unrolled render loop for better per-frame performance\n setup.process(state)\n read.process(state)\n resolveKeyframes.process(state)\n preUpdate.process(state)\n update.process(state)\n preRender.process(state)\n render.process(state)\n postRender.process(state)\n\n state.isProcessing = false\n\n if (runNextFrame && allowKeepAlive) {\n useDefaultElapsed = false\n scheduleNextBatch(processBatch)\n }\n }\n\n const wake = () => {\n runNextFrame = true\n useDefaultElapsed = true\n\n if (!state.isProcessing) {\n scheduleNextBatch(processBatch)\n }\n }\n\n const schedule = stepsOrder.reduce((acc, key) => {\n const step = steps[key]\n acc[key] = (process: Process, keepAlive = false, immediate = false) => {\n if (!runNextFrame) wake()\n\n return step.schedule(process, keepAlive, immediate)\n }\n return acc\n }, {} as Batcher)\n\n const cancel = (process: Process) => {\n for (let i = 0; i < stepsOrder.length; i++) {\n steps[stepsOrder[i]].cancel(process)\n }\n }\n\n return { schedule, cancel, state, steps }\n}\n","import { noop } from \"motion-utils\"\nimport { createRenderBatcher } from \"./batcher\"\n\nexport const {\n schedule: frame,\n cancel: cancelFrame,\n state: frameData,\n steps: frameSteps,\n} = /* @__PURE__ */ createRenderBatcher(\n typeof requestAnimationFrame !== \"undefined\" ? requestAnimationFrame : noop,\n true\n)\n","import { MotionGlobalConfig } from \"motion-utils\"\nimport { frameData } from \"./frame\"\n\nlet now: number | undefined\n\nfunction clearTime() {\n now = undefined\n}\n\n/**\n * An eventloop-synchronous alternative to performance.now().\n *\n * Ensures that time measurements remain consistent within a synchronous context.\n * Usually calling performance.now() twice within the same synchronous context\n * will return different values which isn't useful for animations when we're usually\n * trying to sync animations to the same frame.\n */\nexport const time = {\n now: (): number => {\n if (now === undefined) {\n time.set(\n frameData.isProcessing || MotionGlobalConfig.useManualTiming\n ? frameData.timestamp\n : performance.now()\n )\n }\n\n return now!\n },\n set: (newTime: number) => {\n now = newTime\n queueMicrotask(clearTime)\n },\n}\n","import { AnyResolvedKeyframe } from \"../types\"\n\nexport type CSSVariableName = `--${string}`\n\nexport type CSSVariableToken = `var(${CSSVariableName})`\n\nconst checkStringStartsWith =\n <T extends string>(token: string) =>\n (key?: AnyResolvedKeyframe | null): key is T =>\n typeof key === \"string\" && key.startsWith(token)\n\nexport const isCSSVariableName =\n /*@__PURE__*/ checkStringStartsWith<CSSVariableName>(\"--\")\n\nconst startsAsVariableToken =\n /*@__PURE__*/ checkStringStartsWith<CSSVariableToken>(\"var(--\")\nexport const isCSSVariableToken = (\n value?: string\n): value is CSSVariableToken => {\n const startsWithToken = startsAsVariableToken(value)\n\n if (!startsWithToken) return false\n\n // Ensure any comments are stripped from the value as this can harm performance of the regex.\n return singleCssVariableRegex.test(value.split(\"/*\")[0].trim())\n}\n\nconst singleCssVariableRegex =\n /var\\(--(?:[\\w-]+\\s*|[\\w-]+\\s*,(?:\\s*[^)(\\s]|\\s*\\((?:[^)(]|\\([^)(]*\\))*\\))+\\s*)\\)$/iu\n\n/**\n * Check if a value contains a CSS variable anywhere (e.g. inside calc()).\n * Unlike isCSSVariableToken which checks if the value IS a var() token,\n * this checks if the value CONTAINS var() somewhere in the string.\n */\nexport function containsCSSVariable(\n value?: AnyResolvedKeyframe | null\n): boolean {\n if (typeof value !== \"string\") return false\n // Strip comments to avoid false positives\n return value.split(\"/*\")[0].includes(\"var(--\")\n}\n","import { clamp } from \"motion-utils\"\n\nexport const number = {\n test: (v: number) => typeof v === \"number\",\n parse: parseFloat,\n transform: (v: number) => v,\n}\n\nexport const alpha = {\n ...number,\n transform: (v: number) => clamp(0, 1, v),\n}\n\nexport const scale = {\n ...number,\n default: 1,\n}\n","// If this number is a decimal, make it just five decimal places\n// to avoid exponents\nexport const sanitize = (v: number) => Math.round(v * 100000) / 100000\n","export const floatRegex = /-?(?:\\d+(?:\\.\\d+)?|\\.\\d+)/gu\n","export function isNullish(v: any): v is null | undefined {\n return v == null\n}\n","export const singleColorRegex =\n /^(?:#[\\da-f]{3,8}|(?:rgb|hsl)a?\\((?:-?[\\d.]+%?[,\\s]+){2}-?[\\d.]+%?\\s*(?:[,/]\\s*)?(?:\\b\\d+(?:\\.\\d+)?|\\.\\d+)?%?\\))$/iu\n","import { Color, HSLA, RGBA } from \"../types\"\nimport { floatRegex } from \"../utils/float-regex\"\nimport { isNullish } from \"../utils/is-nullish\"\nimport { singleColorRegex } from \"../utils/single-color-regex\"\n\n/**\n * Returns true if the provided string is a color, ie rgba(0,0,0,0) or #000,\n * but false if a number or multiple colors\n */\nexport const isColorString = (type: string, testProp?: string) => (v: any) => {\n return Boolean(\n (typeof v === \"string\" &&\n singleColorRegex.test(v) &&\n v.startsWith(type)) ||\n (testProp &&\n !isNullish(v) &&\n Object.prototype.hasOwnProperty.call(v, testProp))\n )\n}\n\nexport const splitColor =\n <V extends RGBA | HSLA>(aName: string, bName: string, cName: string) =>\n (v: string | Color): V => {\n if (typeof v !== \"string\") return v as any\n\n const [a, b, c, alpha] = v.match(floatRegex) as any\n\n return {\n [aName]: parseFloat(a),\n [bName]: parseFloat(b),\n [cName]: parseFloat(c),\n alpha: alpha !== undefined ? parseFloat(alpha) : 1,\n } as V\n }\n","import { clamp } from \"motion-utils\"\nimport { alpha as alphaType, number } from \"../numbers\"\nimport { RGBA } from \"../types\"\nimport { sanitize } from \"../utils/sanitize\"\nimport { isColorString, splitColor } from \"./utils\"\n\nconst clampRgbUnit = (v: number) => clamp(0, 255, v)\nexport const rgbUnit = {\n ...number,\n transform: (v: number) => Math.round(clampRgbUnit(v)),\n}\n\nexport const rgba = {\n test: /*@__PURE__*/ isColorString(\"rgb\", \"red\"),\n parse: /*@__PURE__*/ splitColor<RGBA>(\"red\", \"green\", \"blue\"),\n transform: ({ red, green, blue, alpha = 1 }: RGBA) =>\n \"rgba(\" +\n rgbUnit.transform(red) +\n \", \" +\n rgbUnit.transform(green) +\n \", \" +\n rgbUnit.transform(blue) +\n \", \" +\n sanitize(alphaType.transform(alpha)) +\n \")\",\n}\n","import { RGBA } from \"../types\"\nimport { rgba } from \"./rgba\"\nimport { isColorString } from \"./utils\"\n\nfunction parseHex(v: string): RGBA {\n let r = \"\"\n let g = \"\"\n let b = \"\"\n let a = \"\"\n\n // If we have 6 characters, ie #FF0000\n if (v.length > 5) {\n r = v.substring(1, 3)\n g = v.substring(3, 5)\n b = v.substring(5, 7)\n a = v.substring(7, 9)\n\n // Or we have 3 characters, ie #F00\n } else {\n r = v.substring(1, 2)\n g = v.substring(2, 3)\n b = v.substring(3, 4)\n a = v.substring(4, 5)\n r += r\n g += g\n b += b\n a += a\n }\n\n return {\n red: parseInt(r, 16),\n green: parseInt(g, 16),\n blue: parseInt(b, 16),\n alpha: a ? parseInt(a, 16) / 255 : 1,\n }\n}\n\nexport const hex = {\n test: /*@__PURE__*/ isColorString(\"#\"),\n parse: parseHex,\n transform: rgba.transform,\n}\n","import { AnyResolvedKeyframe } from \"../../../animation/types\"\n\n/*#__NO_SIDE_EFFECTS__*/\nconst createUnitType = (unit: string) => ({\n test: (v: AnyResolvedKeyframe) =>\n typeof v === \"string\" && v.endsWith(unit) && v.split(\" \").length === 1,\n parse: parseFloat,\n transform: (v: number | string) => `${v}${unit}`,\n})\n\nexport const degrees = /*@__PURE__*/ createUnitType(\"deg\")\nexport const percent = /*@__PURE__*/ createUnitType(\"%\")\nexport const px = /*@__PURE__*/ createUnitType(\"px\")\nexport const vh = /*@__PURE__*/ createUnitType(\"vh\")\nexport const vw = /*@__PURE__*/ createUnitType(\"vw\")\n\nexport const progressPercentage = /*@__PURE__*/ (() => ({\n ...percent,\n parse: (v: string) => percent.parse(v) / 100,\n transform: (v: number) => percent.transform(v * 100),\n}))()\n","import { alpha as alphaType } from \"../numbers\"\nimport { percent } from \"../numbers/units\"\nimport { HSLA } from \"../types\"\nimport { sanitize } from \"../utils/sanitize\"\nimport { isColorString, splitColor } from \"./utils\"\n\nexport const hsla = {\n test: /*@__PURE__*/ isColorString(\"hsl\", \"hue\"),\n parse: /*@__PURE__*/ splitColor<HSLA>(\"hue\", \"saturation\", \"lightness\"),\n transform: ({ hue, saturation, lightness, alpha = 1 }: HSLA) => {\n return (\n \"hsla(\" +\n Math.round(hue) +\n \", \" +\n percent.transform(sanitize(saturation)) +\n \", \" +\n percent.transform(sanitize(lightness)) +\n \", \" +\n sanitize(alphaType.transform(alpha)) +\n \")\"\n )\n },\n}\n","import { HSLA, RGBA } from \"../types\"\nimport { hex } from \"./hex\"\nimport { hsla } from \"./hsla\"\nimport { rgba } from \"./rgba\"\n\nexport const color = {\n test: (v: any) => rgba.test(v) || hex.test(v) || hsla.test(v),\n parse: (v: any): RGBA | HSLA => {\n if (rgba.test(v)) {\n return rgba.parse(v)\n } else if (hsla.test(v)) {\n return hsla.parse(v)\n } else {\n return hex.parse(v)\n }\n },\n transform: (v: HSLA | RGBA | string) => {\n return typeof v === \"string\"\n ? v\n : v.hasOwnProperty(\"red\")\n ? rgba.transform(v as RGBA)\n : hsla.transform(v as HSLA)\n },\n getAnimatableNone: (v: string) => {\n const parsed = color.parse(v)\n parsed.alpha = 0\n return color.transform(parsed)\n },\n}\n","export const colorRegex =\n /(?:#[\\da-f]{3,8}|(?:rgb|hsl)a?\\((?:-?[\\d.]+%?[,\\s]+){2}-?[\\d.]+%?\\s*(?:[,/]\\s*)?(?:\\b\\d+(?:\\.\\d+)?|\\.\\d+)?%?\\))/giu\n","import { AnyResolvedKeyframe } from \"../../../animation/types\"\nimport { CSSVariableToken } from \"../../../animation/utils/is-css-variable\"\nimport { color } from \"../color\"\nimport { Color } from \"../types\"\nimport { colorRegex } from \"../utils/color-regex\"\nimport { floatRegex } from \"../utils/float-regex\"\nimport { sanitize } from \"../utils/sanitize\"\n\nfunction test(v: any) {\n return (\n isNaN(v) &&\n typeof v === \"string\" &&\n (v.match(floatRegex)?.length || 0) +\n (v.match(colorRegex)?.length || 0) >\n 0\n )\n}\n\nconst NUMBER_TOKEN = \"number\"\nconst COLOR_TOKEN = \"color\"\nconst VAR_TOKEN = \"var\"\nconst VAR_FUNCTION_TOKEN = \"var(\"\nconst SPLIT_TOKEN = \"${}\"\n\nexport type ComplexValues = Array<\n CSSVariableToken | AnyResolvedKeyframe | Color\n>\n\nexport interface ValueIndexes {\n color: number[]\n number: number[]\n var: number[]\n}\n\nexport interface ComplexValueInfo {\n values: ComplexValues\n split: string[]\n indexes: ValueIndexes\n types: Array<keyof ValueIndexes>\n}\n\n// this regex consists of the `singleCssVariableRegex|rgbHSLValueRegex|digitRegex`\nconst complexRegex =\n /var\\s*\\(\\s*--(?:[\\w-]+\\s*|[\\w-]+\\s*,(?:\\s*[^)(\\s]|\\s*\\((?:[^)(]|\\([^)(]*\\))*\\))+\\s*)\\)|#[\\da-f]{3,8}|(?:rgb|hsl)a?\\((?:-?[\\d.]+%?[,\\s]+){2}-?[\\d.]+%?\\s*(?:[,/]\\s*)?(?:\\b\\d+(?:\\.\\d+)?|\\.\\d+)?%?\\)|-?(?:\\d+(?:\\.\\d+)?|\\.\\d+)/giu\n\nexport function analyseComplexValue(\n value: AnyResolvedKeyframe\n): ComplexValueInfo {\n const originalValue = value.toString()\n\n const values: ComplexValues = []\n const indexes: ValueIndexes = {\n color: [],\n number: [],\n var: [],\n }\n const types: Array<keyof ValueIndexes> = []\n\n let i = 0\n const tokenised = originalValue.replace(complexRegex, (parsedValue) => {\n if (color.test(parsedValue)) {\n indexes.color.push(i)\n types.push(COLOR_TOKEN)\n values.push(color.parse(parsedValue))\n } else if (parsedValue.startsWith(VAR_FUNCTION_TOKEN)) {\n indexes.var.push(i)\n types.push(VAR_TOKEN)\n values.push(parsedValue)\n } else {\n indexes.number.push(i)\n types.push(NUMBER_TOKEN)\n values.push(parseFloat(parsedValue))\n }\n ++i\n return SPLIT_TOKEN\n })\n const split = tokenised.split(SPLIT_TOKEN)\n\n return { values, split, indexes, types }\n}\n\nfunction parseComplexValue(v: AnyResolvedKeyframe) {\n return analyseComplexValue(v).values\n}\n\nfunction buildTransformer({ split, types }: ComplexValueInfo) {\n const numSections = split.length\n return (v: Array<CSSVariableToken | Color | number | string>) => {\n let output = \"\"\n for (let i = 0; i < numSections; i++) {\n output += split[i]\n if (v[i] !== undefined) {\n const type = types[i]\n if (type === NUMBER_TOKEN) {\n output += sanitize(v[i] as number)\n } else if (type === COLOR_TOKEN) {\n output += color.transform(v[i] as Color)\n } else {\n output += v[i]\n }\n }\n }\n\n return output\n }\n}\n\nfunction createTransformer(source: AnyResolvedKeyframe) {\n return buildTransformer(analyseComplexValue(source))\n}\n\nconst convertNumbersToZero = (v: number | string) =>\n typeof v === \"number\" ? 0 : color.test(v) ? color.getAnimatableNone(v) : v\n\n/**\n * Convert a parsed value to its zero equivalent, but preserve numbers\n * that act as divisors in CSS calc() expressions.\n *\n * analyseComplexValue extracts numbers from CSS strings and puts the\n * surrounding text into a `split` template array. For example:\n * \"calc(var(--gap) / 5)\" → values: [var(--gap), 5]\n * split: [\"calc(\", \" / \", \")\"]\n *\n * When building a zero-equivalent for animation, naively zeroing all\n * numbers turns the divisor into 0 → \"calc(var(--gap) / 0)\" → NaN.\n * We detect this by checking whether the text preceding a number\n * (split[i]) ends with \"/\" — the CSS calc division operator.\n */\nconst convertToZero = (\n value: ComplexValues[number],\n splitBefore: string\n): ComplexValues[number] => {\n if (typeof value === \"number\") {\n return splitBefore?.trim().endsWith(\"/\") ? value : 0\n }\n return convertNumbersToZero(value as string)\n}\n\nfunction getAnimatableNone(v: AnyResolvedKeyframe) {\n const info = analyseComplexValue(v)\n const transformer = buildTransformer(info)\n return transformer(\n info.values.map((value, i) => convertToZero(value, info.split[i]))\n )\n}\n\nexport const complex = {\n test,\n parse: parseComplexValue,\n createTransformer,\n getAnimatableNone,\n}\n","import { HSLA, RGBA } from \"../types\"\n\n// Adapted from https://gist.github.com/mjackson/5311256\nfunction hueToRgb(p: number, q: number, t: number) {\n if (t < 0) t += 1\n if (t > 1) t -= 1\n if (t < 1 / 6) return p + (q - p) * 6 * t\n if (t < 1 / 2) return q\n if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6\n return p\n}\n\nexport function hslaToRgba({ hue, saturation, lightness, alpha }: HSLA): RGBA {\n hue /= 360\n saturation /= 100\n lightness /= 100\n\n let red = 0\n let green = 0\n let blue = 0\n\n if (!saturation) {\n red = green = blue = lightness\n } else {\n const q =\n lightness < 0.5\n ? lightness * (1 + saturation)\n : lightness + saturation - lightness * saturation\n const p = 2 * lightness - q\n\n red = hueToRgb(p, q, hue + 1 / 3)\n green = hueToRgb(p, q, hue)\n blue = hueToRgb(p, q, hue - 1 / 3)\n }\n\n return {\n red: Math.round(red * 255),\n green: Math.round(green * 255),\n blue: Math.round(blue * 255),\n alpha,\n }\n}\n","export function mixImmediate<T>(a: T, b: T) {\n return (p: number) => (p > 0 ? b : a)\n}\n","/*\n Value in range from progress\n\n Given a lower limit and an upper limit, we return the value within\n that range as expressed by progress (usually a number from 0 to 1)\n\n So progress = 0.5 would change\n\n from -------- to\n\n to\n\n from ---- to\n\n E.g. from = 10, to = 20, progress = 0.5 => 15\n\n @param [number]: Lower limit of range\n @param [number]: Upper limit of range\n @param [number]: The progress between lower and upper limits expressed 0-1\n @return [number]: Value as calculated from progress within range (not limited within range)\n*/\nexport const mixNumber = (from: number, to: number, progress: number) => {\n return from + (to - from) * progress\n}\n","import { warning } from \"motion-utils\"\nimport { hex } from \"../../value/types/color/hex\"\nimport { hsla } from \"../../value/types/color/hsla\"\nimport { hslaToRgba } from \"../../value/types/color/hsla-to-rgba\"\nimport { rgba } from \"../../value/types/color/rgba\"\nimport { Color, HSLA, RGBA } from \"../../value/types/types\"\nimport { mixImmediate } from \"./immediate\"\nimport { mixNumber } from \"./number\"\n\n// Linear color space blending\n// Explained https://www.youtube.com/watch?v=LKnqECcg6Gw\n// Demonstrated http://codepen.io/osublake/pen/xGVVaN\nexport const mixLinearColor = (from: number, to: number, v: number) => {\n const fromExpo = from * from\n const expo = v * (to * to - fromExpo) + fromExpo\n return expo < 0 ? 0 : Math.sqrt(expo)\n}\n\nconst colorTypes = [hex, rgba, hsla]\nconst getColorType = (v: Color | string) =>\n colorTypes.find((type) => type.test(v))\n\nfunction asRGBA(color: Color | string) {\n const type = getColorType(color)\n\n warning(\n Boolean(type),\n `'${color}' is not an animatable color. Use the equivalent color code instead.`,\n \"color-not-animatable\"\n )\n\n if (!Boolean(type)) return false\n\n let model = type!.parse(color)\n\n if (type === hsla) {\n // TODO Remove this cast - needed since Motion's stricter typing\n model = hslaToRgba(model as HSLA)\n }\n\n return model as RGBA\n}\n\nexport const mixColor = (from: Color | string, to: Color | string) => {\n const fromRGBA = asRGBA(from)\n const toRGBA = asRGBA(to)\n\n if (!fromRGBA || !toRGBA) {\n return mixImmediate(from, to)\n }\n\n const blended = { ...fromRGBA }\n\n return (v: number) => {\n blended.red = mixLinearColor(fromRGBA.red, toRGBA.red, v)\n blended.green = mixLinearColor(fromRGBA.green, toRGBA.green, v)\n blended.blue = mixLinearColor(fromRGBA.blue, toRGBA.blue, v)\n blended.alpha = mixNumber(fromRGBA.alpha, toRGBA.alpha, v)\n return rgba.transform!(blended)\n }\n}\n","export const invisibleValues = new Set([\"none\", \"hidden\"])\n\n/**\n * Returns a function that, when provided a progress value between 0 and 1,\n * will return the \"none\" or \"hidden\" string only when the progress is that of\n * the origin or target.\n */\nexport function mixVisibility(origin: string, target: string) {\n if (invisibleValues.has(origin)) {\n return (p: number) => (p <= 0 ? origin : target)\n } else {\n return (p: number) => (p >= 1 ? target : origin)\n }\n}\n","import { pipe, warning } from \"motion-utils\"\nimport { AnyResolvedKeyframe } from \"../../animation/types\"\nimport { isCSSVariableToken } from \"../../animation/utils/is-css-variable\"\nimport { color } from \"../../value/types/color\"\nimport {\n analyseComplexValue,\n complex,\n ComplexValueInfo,\n ComplexValues,\n} from \"../../value/types/complex\"\nimport { HSLA, RGBA } from \"../../value/types/types\"\nimport { mixColor } from \"./color\"\nimport { mixImmediate } from \"./immediate\"\nimport { mixNumber as mixNumberImmediate } from \"./number\"\nimport { invisibleValues, mixVisibility } from \"./visibility\"\n\ntype MixableArray = Array<number | RGBA | HSLA | string>\ninterface MixableObject {\n [key: string]: AnyResolvedKeyframe | RGBA | HSLA\n}\n\nfunction mixNumber(a: number, b: number) {\n return (p: number) => mixNumberImmediate(a, b, p)\n}\n\nexport function getMixer<T>(a: T) {\n if (typeof a === \"number\") {\n return mixNumber\n } else if (typeof a === \"string\") {\n return isCSSVariableToken(a)\n ? mixImmediate\n : color.test(a)\n ? mixColor\n : mixComplex\n } else if (Array.isArray(a)) {\n return mixArray\n } else if (typeof a === \"object\") {\n return color.test(a) ? mixColor : mixObject\n }\n\n return mixImmediate\n}\n\nexport function mixArray(a: MixableArray, b: MixableArray) {\n const output = [...a]\n const numValues = output.length\n\n const blendValue = a.map((v, i) => getMixer(v)(v as any, b[i] as any))\n\n return (p: number) => {\n for (let i = 0; i < numValues; i++) {\n output[i] = blendValue[i](p) as any\n }\n return output\n }\n}\n\nexport function mixObject(a: MixableObject, b: MixableObject) {\n const output = { ...a, ...b }\n const blendValue: { [key: string]: (v: number) => any } = {}\n\n for (const key in output) {\n if (a[key] !== undefined && b[key] !== undefined) {\n blendValue[key] = getMixer(a[key])(\n a[key] as any,\n b[key] as any\n ) as any\n }\n }\n\n return (v: number) => {\n for (const key in blendValue) {\n output[key] = blendValue[key](v)\n }\n return output\n }\n}\n\nfunction matchOrder(\n origin: ComplexValueInfo,\n target: ComplexValueInfo\n): ComplexValues {\n const orderedOrigin: ComplexValues = []\n\n const pointers = { color: 0, var: 0, number: 0 }\n\n for (let i = 0; i < target.values.length; i++) {\n const type = target.types[i]\n const originIndex = origin.indexes[type][pointers[type]]\n const originValue = origin.values[originIndex] ?? 0\n\n orderedOrigin[i] = originValue\n\n pointers[type]++\n }\n\n return orderedOrigin\n}\n\nexport const mixComplex = (\n origin: AnyResolvedKeyframe,\n target: AnyResolvedKeyframe\n) => {\n const template = complex.createTransformer(target)\n const originStats = analyseComplexValue(origin)\n const targetStats = analyseComplexValue(target)\n const canInterpolate =\n originStats.indexes.var.length === targetStats.indexes.var.length &&\n originStats.indexes.color.length === targetStats.indexes.color.length &&\n originStats.indexes.number.length >= targetStats.indexes.number.length\n\n if (canInterpolate) {\n if (\n (invisibleValues.has(origin as string) &&\n !targetStats.values.length) ||\n (invisibleValues.has(target as string) &&\n !originStats.values.length)\n ) {\n return mixVisibility(origin as string, target as string)\n }\n\n return pipe(\n mixArray(matchOrder(originStats, targetStats), targetStats.values),\n template\n )\n } else {\n warning(\n true,\n `Complex values '${origin}' and '${target}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,\n \"complex-values-different\"\n )\n\n return mixImmediate(origin, target)\n }\n}\n","import { getMixer } from \"./complex\"\nimport { mixNumber as mixNumberImmediate } from \"./number\"\nimport { Mixer } from \"./types\"\n\nexport function mix<T>(from: T, to: T): Mixer<T>\nexport function mix(from: number, to: number, p: number): number\nexport function mix<T>(from: T, to: T, p?: T): Mixer<T> | number {\n if (\n typeof from === \"number\" &&\n typeof to === \"number\" &&\n typeof p === \"number\"\n ) {\n return mixNumberImmediate(from, to, p)\n }\n\n const mixer = getMixer(from)\n return mixer(from as any, to as any) as Mixer<T>\n}\n","import { cancelFrame, frame, frameData } from \"../../frameloop\"\nimport { time } from \"../../frameloop/sync-time\"\nimport { FrameData } from \"../../frameloop/types\"\nimport { Driver } from \"./types\"\n\nexport const frameloopDriver: Driver = (update) => {\n const passTimestamp = ({ timestamp }: FrameData) => update(timestamp)\n\n return {\n start: (keepAlive = true) => frame.update(passTimestamp, keepAlive),\n stop: () => cancelFrame(passTimestamp),\n /**\n * If we're processing this frame we can use the\n * framelocked timestamp to keep things in sync.\n */\n now: () => (frameData.isProcessing ? frameData.timestamp : time.now()),\n }\n}\n","import { EasingFunction } from \"motion-utils\"\n\nexport const generateLinearEasing = (\n easing: EasingFunction,\n duration: number, // as milliseconds\n resolution: number = 10 // as milliseconds\n): string => {\n let points = \"\"\n const numPoints = Math.max(Math.round(duration / resolution), 2)\n\n for (let i = 0; i < numPoints; i++) {\n points += Math.round(easing(i / (numPoints - 1)) * 10000) / 10000 + \", \"\n }\n\n return `linear(${points.substring(0, points.length - 2)})`\n}\n","import { KeyframeGenerator } from \"../../types\"\n\n/**\n * Implement a practical max duration for keyframe generation\n * to prevent infinite loops\n */\nexport const maxGeneratorDuration = 20_000\nexport function calcGeneratorDuration(\n generator: KeyframeGenerator<unknown>\n): number {\n let duration = 0\n const timeStep = 50\n let state = generator.next(duration)\n while (!state.done && duration < maxGeneratorDuration) {\n duration += timeStep\n state = generator.next(duration)\n }\n\n return duration >= maxGeneratorDuration ? Infinity : duration\n}\n","import { millisecondsToSeconds } from \"motion-utils\"\nimport { GeneratorFactory, Transition } from \"../../types\"\nimport { calcGeneratorDuration, maxGeneratorDuration } from \"./calc-duration\"\n\n/**\n * Create a progress => progress easing function from a generator.\n */\nexport function createGeneratorEasing(\n options: Transition,\n scale = 100,\n createGenerator: GeneratorFactory\n) {\n const generator = createGenerator({ ...options, keyframes: [0, scale] })\n const duration = Math.min(\n calcGeneratorDuration(generator),\n maxGeneratorDuration\n )\n\n return {\n type: \"keyframes\",\n ease: (progress: number) => {\n return generator.next(duration * progress).value / scale\n },\n duration: millisecondsToSeconds(duration),\n }\n}\n","import {\n clamp,\n millisecondsToSeconds,\n secondsToMilliseconds,\n warning,\n} from \"motion-utils\"\nimport {\n AnimationState,\n KeyframeGenerator,\n SpringOptions,\n Transition,\n ValueAnimationOptions,\n} from \"../types\"\nimport { generateLinearEasing } from \"../waapi/utils/linear\"\nimport {\n calcGeneratorDuration,\n maxGeneratorDuration,\n} from \"./utils/calc-duration\"\nimport { createGeneratorEasing } from \"./utils/create-generator-easing\"\n\nconst springDefaults = {\n // Default spring physics\n stiffness: 100,\n damping: 10,\n mass: 1.0,\n velocity: 0.0,\n\n // Default duration/bounce-based options\n duration: 800, // in ms\n bounce: 0.3,\n visualDuration: 0.3, // in seconds\n\n // Rest thresholds\n restSpeed: {\n granular: 0.01,\n default: 2,\n },\n restDelta: {\n granular: 0.005,\n default: 0.5,\n },\n\n // Limits\n minDuration: 0.01, // in seconds\n maxDuration: 10.0, // in seconds\n minDamping: 0.05,\n maxDamping: 1,\n}\n\nfunction calcAngularFreq(undampedFreq: number, dampingRatio: number) {\n return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio)\n}\n\nconst rootIterations = 12\nfunction approximateRoot(\n envelope: (num: number) => number,\n derivative: (num: number) => number,\n initialGuess: number\n): number {\n let result = initialGuess\n for (let i = 1; i < rootIterations; i++) {\n result = result - envelope(result) / derivative(result)\n }\n return result\n}\n\n/**\n * This is ported from the Framer implementation of duration-based spring resolution.\n */\nconst safeMin = 0.001\n\nfunction findSpring({\n duration = springDefaults.duration,\n bounce = springDefaults.bounce,\n velocity = springDefaults.velocity,\n mass = springDefaults.mass,\n}: SpringOptions) {\n let envelope: (num: number) => number\n let derivative: (num: number) => number\n\n warning(\n duration <= secondsToMilliseconds(springDefaults.maxDuration),\n \"Spring duration must be 10 seconds or less\",\n \"spring-duration-limit\"\n )\n\n let dampingRatio = 1 - bounce\n\n /**\n * Restrict dampingRatio and duration to within acceptable ranges.\n */\n dampingRatio = clamp(\n springDefaults.minDamping,\n springDefaults.maxDamping,\n dampingRatio\n )\n duration = clamp(\n springDefaults.minDuration,\n springDefaults.maxDuration,\n millisecondsToSeconds(duration)\n )\n\n if (dampingRatio < 1) {\n /**\n * Underdamped spring\n */\n envelope = (undampedFreq) => {\n const exponentialDecay = undampedFreq * dampingRatio\n const delta = exponentialDecay * duration\n const a = exponentialDecay - velocity\n const b = calcAngularFreq(undampedFreq, dampingRatio)\n const c = Math.exp(-delta)\n return safeMin - (a / b) * c\n }\n\n derivative = (undampedFreq) => {\n const exponentialDecay = undampedFreq * dampingRatio\n const delta = exponentialDecay * duration\n const d = delta * velocity + velocity\n const e =\n Math.pow(dampingRatio, 2) * Math.pow(undampedFreq, 2) * duration\n const f = Math.exp(-delta)\n const g = calcAngularFreq(Math.pow(undampedFreq, 2), dampingRatio)\n const factor = -envelope(undampedFreq) + safeMin > 0 ? -1 : 1\n return (factor * ((d - e) * f)) / g\n }\n } else {\n /**\n * Critically-damped spring\n */\n envelope = (undampedFreq) => {\n const a = Math.exp(-undampedFreq * duration)\n const b = (undampedFreq - velocity) * duration + 1\n return -safeMin + a * b\n }\n\n derivative = (undampedFreq) => {\n const a = Math.exp(-undampedFreq * duration)\n const b = (velocity - undampedFreq) * (duration * duration)\n return a * b\n }\n }\n\n const initialGuess = 5 / duration\n const undampedFreq = approximateRoot(envelope, derivative, initialGuess)\n\n duration = secondsToMilliseconds(duration)\n if (isNaN(undampedFreq)) {\n return {\n stiffness: springDefaults.stiffness,\n damping: springDefaults.damping,\n duration,\n }\n } else {\n const stiffness = Math.pow(undampedFreq, 2) * mass\n return {\n stiffness,\n damping: dampingRatio * 2 * Math.sqrt(mass * stiffness),\n duration,\n }\n }\n}\n\nconst durationKeys = [\"duration\", \"bounce\"]\nconst physicsKeys = [\"stiffness\", \"damping\", \"mass\"]\n\nfunction isSpringType(options: SpringOptions, keys: string[]) {\n return keys.some((key) => (options as any)[key] !== undefined)\n}\n\nfunction getSpringOptions(options: SpringOptions) {\n let springOptions = {\n velocity: springDefaults.velocity,\n stiffness: springDefaults.stiffness,\n damping: springDefaults.damping,\n mass: springDefaults.mass,\n isResolvedFromDuration: false,\n ...options,\n }\n // stiffness/damping/mass overrides duration/bounce\n if (\n !isSpringType(options, physicsKeys) &&\n isSpringType(options, durationKeys)\n ) {\n // Time-defined springs should ignore inherited velocity.\n // Velocity from interrupted animations can cause findSpring()\n // to compute wildly different spring parameters, leading to\n // massive oscillation on small-range animations.\n springOptions.velocity = 0\n\n if (options.visualDuration) {\n const visualDuration = options.visualDuration\n const root = (2 * Math.PI) / (visualDuration * 1.2)\n const stiffness = root * root\n const damping =\n 2 *\n clamp(0.05, 1, 1 - (options.bounce || 0)) *\n Math.sqrt(stiffness)\n\n springOptions = {\n ...springOptions,\n mass: springDefaults.mass,\n stiffness,\n damping,\n }\n } else {\n const derived = findSpring({ ...options, velocity: 0 })\n\n springOptions = {\n ...springOptions,\n ...derived,\n mass: springDefaults.mass,\n }\n springOptions.isResolvedFromDuration = true\n }\n }\n\n return springOptions\n}\n\nfunction spring(\n optionsOrVisualDuration:\n | ValueAnimationOptions<number>\n | number = springDefaults.visualDuration,\n bounce = springDefaults.bounce\n): KeyframeGenerator<number> {\n const options =\n typeof optionsOrVisualDuration !== \"object\"\n ? ({\n visualDuration: optionsOrVisualDuration,\n keyframes: [0, 1],\n bounce,\n } as ValueAnimationOptions<number>)\n : optionsOrVisualDuration\n\n let { restSpeed, restDelta } = options\n\n const origin = options.keyframes[0]\n const target = options.keyframes[options.keyframes.length - 1]\n\n /**\n * This is the Iterator-spec return value. We ensure it's mutable rather than using a generator\n * to reduce GC during animation.\n */\n const state: AnimationState<number> = { done: false, value: origin }\n\n const {\n stiffness,\n damping,\n mass,\n duration,\n velocity,\n isResolvedFromDuration,\n } = getSpringOptions({\n ...options,\n velocity: -millisecondsToSeconds(options.velocity || 0),\n })\n\n const initialVelocity = velocity || 0.0\n const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass))\n\n const initialDelta = target - origin\n const undampedAngularFreq = millisecondsToSeconds(\n Math.sqrt(stiffness / mass)\n )\n\n /**\n * If we're working on a granular scale, use smaller defaults for determining\n * when the spring is finished.\n *\n * These defaults have been selected emprically based on what strikes a good\n * ratio between feeling good and finishing as soon as changes are imperceptible.\n */\n const isGranularScale = Math.abs(initialDelta) < 5\n restSpeed ||= isGranularScale\n ? springDefaults.restSpeed.granular\n : springDefaults.restSpeed.default\n restDelta ||= isGranularScale\n ? springDefaults.restDelta.granular\n : springDefaults.restDelta.default\n\n let resolveSpring: (v: number) => number\n let resolveVelocity: (t: number) => number\n\n // Underdamped coefficients, hoisted for use in the inlined next() hot path\n let angularFreq: number\n let A: number\n let sinCoeff: number\n let cosCoeff: number\n\n if (dampingRatio < 1) {\n angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio)\n\n A =\n (initialVelocity +\n dampingRatio * undampedAngularFreq * initialDelta) /\n angularFreq\n\n // Underdamped spring\n resolveSpring = (t: number) => {\n const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t)\n\n return (\n target -\n envelope *\n (A * Math.sin(angularFreq * t) +\n initialDelta * Math.cos(angularFreq * t))\n )\n }\n\n // Analytical derivative of underdamped spring (px/ms)\n sinCoeff =\n dampingRatio * undampedAngularFreq * A + initialDelta * angularFreq\n cosCoeff =\n dampingRatio * undampedAngularFreq * initialDelta - A * angularFreq\n resolveVelocity = (t: number) => {\n const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t)\n return envelope *\n (sinCoeff * Math.sin(angularFreq * t) +\n cosCoeff * Math.cos(angularFreq * t))\n }\n } else if (dampingRatio === 1) {\n // Critically damped spring\n resolveSpring = (t: number) =>\n target -\n Math.exp(-undampedAngularFreq * t) *\n (initialDelta +\n (initialVelocity + undampedAngularFreq * initialDelta) * t)\n\n // Analytical derivative of critically damped spring (px/ms)\n const C = initialVelocity + undampedAngularFreq * initialDelta\n resolveVelocity = (t: number) =>\n Math.exp(-undampedAngularFreq * t) *\n (undampedAngularFreq * C * t - initialVelocity)\n } else {\n // Overdamped spring\n const dampedAngularFreq =\n undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1)\n\n resolveSpring = (t: number) => {\n const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t)\n\n // When performing sinh or cosh values can hit Infinity so we cap them here\n const freqForT = Math.min(dampedAngularFreq * t, 300)\n\n return (\n target -\n (envelope *\n ((initialVelocity +\n dampingRatio * undampedAngularFreq * initialDelta) *\n Math.sinh(freqForT) +\n dampedAngularFreq *\n initialDelta *\n Math.cosh(freqForT))) /\n dampedAngularFreq\n )\n }\n\n // Analytical derivative of overdamped spring (px/ms)\n const P =\n (initialVelocity +\n dampingRatio * undampedAngularFreq * initialDelta) /\n dampedAngularFreq\n const sinhCoeff =\n dampingRatio * undampedAngularFreq * P - initialDelta * dampedAngularFreq\n const coshCoeff =\n dampingRatio * undampedAngularFreq * initialDelta - P * dampedAngularFreq\n resolveVelocity = (t: number) => {\n const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t)\n const freqForT = Math.min(dampedAngularFreq * t, 300)\n return envelope *\n (sinhCoeff * Math.sinh(freqForT) +\n coshCoeff * Math.cosh(freqForT))\n }\n }\n\n const generator = {\n calculatedDuration: isResolvedFromDuration ? duration || null : null,\n velocity: (t: number) => secondsToMilliseconds(resolveVelocity(t)),\n next: (t: number) => {\n /**\n * For underdamped physics springs we need both position and\n * velocity each tick. Compute shared trig values once to avoid\n * duplicate Math.exp/sin/cos calls on the hot path.\n */\n if (!isResolvedFromDuration && dampingRatio < 1) {\n const envelope = Math.exp(\n -dampingRatio * undampedAngularFreq * t\n )\n const sin = Math.sin(angularFreq * t)\n const cos = Math.cos(angularFreq * t)\n\n const current =\n target -\n envelope *\n (A * sin + initialDelta * cos)\n const currentVelocity = secondsToMilliseconds(\n envelope *\n (sinCoeff * sin + cosCoeff * cos)\n )\n\n state.done =\n Math.abs(currentVelocity) <= restSpeed! &&\n Math.abs(target - current) <= restDelta!\n state.value = state.done ? target : current\n\n return state\n }\n\n const current = resolveSpring(t)\n\n if (!isResolvedFromDuration) {\n const currentVelocity = secondsToMilliseconds(\n resolveVelocity(t)\n )\n state.done =\n Math.abs(currentVelocity) <= restSpeed! &&\n Math.abs(target - current) <= restDelta!\n } else {\n state.done = t >= duration!\n }\n\n state.value = state.done ? target : current\n\n return state\n },\n toString: () => {\n const calculatedDuration = Math.min(\n calcGeneratorDuration(generator),\n maxGeneratorDuration\n )\n\n const easing = generateLinearEasing(\n (progress: number) =>\n generator.next(calculatedDuration * progress).value,\n calculatedDuration,\n 30\n )\n\n return calculatedDuration + \"ms \" + easing\n },\n toTransition: () => {},\n }\n\n return generator\n}\n\nspring.applyToOptions = (options: Transition) => {\n const generatorOptions = createGeneratorEasing(options as any, 100, spring)\n\n options.ease = generatorOptions.ease\n options.duration = secondsToMilliseconds(generatorOptions.duration)\n options.type = \"keyframes\"\n return options\n}\n\nexport { spring }\n","import { velocityPerSecond } from \"motion-utils\"\n\nconst velocitySampleDuration = 5 // ms\n\nexport function getGeneratorVelocity(\n resolveValue: (v: number) => number,\n t: number,\n current: number\n) {\n const prevT = Math.max(t - velocitySampleDuration, 0)\n return velocityPerSecond(current - resolveValue(prevT), t - prevT)\n}\n","import {\n AnimationState,\n KeyframeGenerator,\n ValueAnimationOptions,\n} from \"../types\"\nimport { spring as createSpring } from \"./spring\"\nimport { getGeneratorVelocity } from \"./utils/velocity\"\n\nexport function inertia({\n keyframes,\n velocity = 0.0,\n power = 0.8,\n timeConstant = 325,\n bounceDamping = 10,\n bounceStiffness = 500,\n modifyTarget,\n min,\n max,\n restDelta = 0.5,\n restSpeed,\n}: ValueAnimationOptions<number>): KeyframeGenerator<number> {\n const origin = keyframes[0]\n\n const state: AnimationState<number> = {\n done: false,\n value: origin,\n }\n\n const isOutOfBounds = (v: number) =>\n (min !== undefined && v < min) || (max !== undefined && v > max)\n\n const nearestBoundary = (v: number) => {\n if (min === undefined) return max\n if (max === undefined) return min\n\n return Math.abs(min - v) < Math.abs(max - v) ? min : max\n }\n\n let amplitude = power * velocity\n const ideal = origin + amplitude\n const target = modifyTarget === undefined ? ideal : modifyTarget(ideal)\n\n /**\n * If the target has changed we need to re-calculate the amplitude, otherwise\n * the animation will start from the wrong position.\n */\n if (target !== ideal) amplitude = target - origin\n\n const calcDelta = (t: number) => -amplitude * Math.exp(-t / timeConstant)\n\n const calcLatest = (t: number) => target + calcDelta(t)\n\n const applyFriction = (t: number) => {\n const delta = calcDelta(t)\n const latest = calcLatest(t)\n state.done = Math.abs(delta) <= restDelta\n state.value = state.done ? target : latest\n }\n\n /**\n * Ideally this would resolve for t in a stateless way, we could\n * do that by always precalculating the animation but as we know\n * this will be done anyway we can assume that spring will\n * be discovered during that.\n */\n let timeReachedBoundary: number | undefined\n let spring: KeyframeGenerator<number> | undefined\n\n const checkCatchBoundary = (t: number) => {\n if (!isOutOfBounds(state.value)) return\n\n timeReachedBoundary = t\n\n spring = createSpring({\n keyframes: [state.value, nearestBoundary(state.value)!],\n velocity: getGeneratorVelocity(calcLatest, t, state.value), // TODO: This should be passing * 1000\n damping: bounceDamping,\n stiffness: bounceStiffness,\n restDelta,\n restSpeed,\n })\n }\n\n checkCatchBoundary(0)\n\n return {\n calculatedDuration: null,\n next: (t: number) => {\n /**\n * We need to resolve the friction to figure out if we need a\n * spring but we don't want to do this twice per frame. So here\n * we flag if we updated for this frame and later if we did\n * we can skip doing it again.\n */\n let hasUpdatedFrame = false\n if (!spring && timeReachedBoundary === undefined) {\n hasUpdatedFrame = true\n applyFriction(t)\n checkCatchBoundary(t)\n }\n\n /**\n * If we have a spring and the provided t is beyond the moment the friction\n * animation crossed the min/max boundary, use the spring.\n */\n if (timeReachedBoundary !== undefined && t >= timeReachedBoundary) {\n return spring!.next(t - timeReachedBoundary)\n } else {\n !hasUpdatedFrame && applyFriction(t)\n return state\n }\n },\n }\n}\n","import {\n clamp,\n EasingFunction,\n invariant,\n MotionGlobalConfig,\n noop,\n pipe,\n progress,\n} from \"motion-utils\"\nimport { mix } from \"./mix\"\nimport { Mixer, MixerFactory } from \"./mix/types\"\n\nexport interface InterpolateOptions<T> {\n clamp?: boolean\n ease?: EasingFunction | EasingFunction[]\n mixer?: MixerFactory<T>\n}\n\nfunction createMixers<T>(\n output: T[],\n ease?: EasingFunction | EasingFunction[],\n customMixer?: MixerFactory<T>\n) {\n const mixers: Array<Mixer<T>> = []\n const mixerFactory: MixerFactory<T> =\n customMixer || MotionGlobalConfig.mix || mix\n const numMixers = output.length - 1\n\n for (let i = 0; i < numMixers; i++) {\n let mixer = mixerFactory(output[i], output[i + 1])\n\n if (ease) {\n const easingFunction = Array.isArray(ease) ? ease[i] || noop : ease\n mixer = pipe(easingFunction, mixer) as Mixer<T>\n }\n\n mixers.push(mixer)\n }\n\n return mixers\n}\n\n/**\n * Create a function that maps from a numerical input array to a generic output array.\n *\n * Accepts:\n * - Numbers\n * - Colors (hex, hsl, hsla, rgb, rgba)\n * - Complex (combinations of one or more numbers or strings)\n *\n * ```jsx\n * const mixColor = interpolate([0, 1], ['#fff', '#000'])\n *\n * mixColor(0.5) // 'rgba(128, 128, 128, 1)'\n * ```\n *\n * TODO Revisit this approach once we've moved to data models for values,\n * probably not needed to pregenerate mixer functions.\n *\n * @public\n */\nexport function interpolate<T>(\n input: number[],\n output: T[],\n { clamp: isClamp = true, ease, mixer }: InterpolateOptions<T> = {}\n): (v: number) => T {\n const inputLength = input.length\n\n invariant(\n inputLength === output.length,\n \"Both input and output ranges must be the same length\",\n \"range-length\"\n )\n\n /**\n * If we're only provided a single input, we can just make a function\n * that returns the output.\n */\n if (inputLength === 1) return () => output[0]\n if (inputLength === 2 && output[0] === output[1]) return () => output[1]\n\n const isZeroDeltaRange = input[0] === input[1]\n\n // If input runs highest -> lowest, reverse both arrays\n if (input[0] > input[inputLength - 1]) {\n input = [...input].reverse()\n output = [...output].reverse()\n }\n\n const mixers = createMixers(output, ease, mixer)\n const numMixers = mixers.length\n\n const interpolator = (v: number): T => {\n if (isZeroDeltaRange && v < input[0]) return output[0]\n\n let i = 0\n\n if (numMixers > 1) {\n for (; i < input.length - 2; i++) {\n if (v < input[i + 1]) break\n }\n }\n\n const progressInRange = progress(input[i], input[i + 1], v)\n\n return mixers[i](progressInRange)\n }\n\n return isClamp\n ? (v: number) =>\n interpolator(clamp(input[0], input[inputLength - 1], v))\n : interpolator\n}\n","import { progress } from \"motion-utils\"\nimport { mixNumber } from \"../../../utils/mix/number\"\n\nexport function fillOffset(offset: number[], remaining: number): void {\n const min = offset[offset.length - 1]\n for (let i = 1; i <= remaining; i++) {\n const offsetProgress = progress(0, remaining, i)\n offset.push(mixNumber(min, 1, offsetProgress))\n }\n}\n","import { fillOffset } from \"./fill\"\n\nexport function defaultOffset(arr: any[]): number[] {\n const offset = [0]\n fillOffset(offset, arr.length - 1)\n return offset\n}\n","export function convertOffsetToTimes(offset: number[], duration: number) {\n return offset.map((o) => o * duration)\n}\n","import {\n easeInOut,\n easingDefinitionToFunction,\n EasingFunction,\n isEasingArray,\n} from \"motion-utils\"\nimport { interpolate } from \"../../utils/interpolate\"\nimport { defaultOffset } from \"../keyframes/offsets/default\"\nimport { convertOffsetToTimes } from \"../keyframes/offsets/time\"\nimport {\n AnimationState,\n AnyResolvedKeyframe,\n KeyframeGenerator,\n ValueAnimationOptions,\n} from \"../types\"\n\nexport function defaultEasing(\n values: any[],\n easing?: EasingFunction\n): EasingFunction[] {\n return values.map(() => easing || easeInOut).splice(0, values.length - 1)\n}\n\nexport function keyframes<T extends AnyResolvedKeyframe>({\n duration = 300,\n keyframes: keyframeValues,\n times,\n ease = \"easeInOut\",\n}: ValueAnimationOptions<T>): KeyframeGenerator<T> {\n /**\n * Easing functions can be externally defined as strings. Here we convert them\n * into actual functions.\n */\n const easingFunctions = isEasingArray(ease)\n ? ease.map(easingDefinitionToFunction)\n : easingDefinitionToFunction(ease)\n\n /**\n * This is the Iterator-spec return value. We ensure it's mutable rather than using a generator\n * to reduce GC during animation.\n */\n const state: AnimationState<T> = {\n done: false,\n value: keyframeValues[0],\n }\n\n /**\n * Create a times array based on the provided 0-1 offsets\n */\n const absoluteTimes = convertOffsetToTimes(\n // Only use the provided offsets if they're the correct length\n // TODO Maybe we should warn here if there's a length mismatch\n times && times.length === keyframeValues.length\n ? times\n : defaultOffset(keyframeValues),\n duration\n )\n\n const mapTimeToKeyframe = interpolate<T>(absoluteTimes, keyframeValues, {\n ease: Array.isArray(easingFunctions)\n ? easingFunctions\n : defaultEasing(keyframeValues, easingFunctions),\n })\n\n return {\n calculatedDuration: duration,\n next: (t: number) => {\n state.value = mapTimeToKeyframe(t)\n state.done = t >= duration\n return state\n },\n }\n}\n","import { AnimationPlaybackOptions } from \"../types\"\n\nconst isNotNull = (value: unknown) => value !== null\n\nexport function getFinalKeyframe<T>(\n keyframes: T[],\n { repeat, repeatType = \"loop\" }: AnimationPlaybackOptions,\n finalKeyframe?: T,\n speed: number = 1\n): T {\n const resolvedKeyframes = keyframes.filter(isNotNull)\n const useFirstKeyframe =\n speed < 0 || (repeat && repeatType !== \"loop\" && repeat % 2 === 1)\n const index = useFirstKeyframe ? 0 : resolvedKeyframes.length - 1\n\n return !index || finalKeyframe === undefined\n ? resolvedKeyframes[index]\n : finalKeyframe\n}\n","import { inertia } from \"../generators/inertia\"\nimport { keyframes } from \"../generators/keyframes\"\nimport { spring } from \"../generators/spring\"\nimport { GeneratorFactory, ValueAnimationTransition } from \"../types\"\n\nconst transitionTypeMap: { [key: string]: GeneratorFactory } = {\n decay: inertia,\n inertia,\n tween: keyframes,\n keyframes: keyframes,\n spring,\n}\n\nexport function replaceTransitionType(transition: ValueAnimationTransition) {\n if (typeof transition.type === \"string\") {\n transition.type = transitionTypeMap[transition.type]\n }\n}\n","export class WithPromise {\n protected _finished: Promise<void>\n\n resolve: VoidFunction\n\n constructor() {\n this.updateFinished()\n }\n\n get finished() {\n return this._finished\n }\n\n protected updateFinished() {\n this._finished = new Promise<void>((resolve) => {\n this.resolve = resolve\n })\n }\n\n protected notifyFinished() {\n this.resolve()\n }\n\n /**\n * Allows the animation to be awaited.\n *\n * @deprecated Use `finished` instead.\n */\n then(onResolve: VoidFunction, onReject?: VoidFunction) {\n return this.finished.then(onResolve, onReject)\n }\n}\n","import {\n clamp,\n invariant,\n millisecondsToSeconds,\n pipe,\n secondsToMilliseconds,\n} from \"motion-utils\"\nimport { time } from \"../frameloop/sync-time\"\nimport { mix } from \"../utils/mix\"\nimport { Mixer } from \"../utils/mix/types\"\nimport { frameloopDriver } from \"./drivers/frame\"\nimport { DriverControls } from \"./drivers/types\"\nimport { inertia } from \"./generators/inertia\"\nimport { keyframes as keyframesGenerator } from \"./generators/keyframes\"\nimport { calcGeneratorDuration } from \"./generators/utils/calc-duration\"\nimport { getGeneratorVelocity } from \"./generators/utils/velocity\"\nimport { getFinalKeyframe } from \"./keyframes/get-final\"\nimport {\n AnimationPlaybackControlsWithThen,\n AnimationState,\n GeneratorFactory,\n KeyframeGenerator,\n TimelineWithFallback,\n ValueAnimationOptions,\n} from \"./types\"\nimport { replaceTransitionType } from \"./utils/replace-transition-type\"\nimport { WithPromise } from \"./utils/WithPromise\"\n\nconst percentToProgress = (percent: number) => percent / 100\n\nexport class JSAnimation<T extends number | string>\n extends WithPromise\n implements AnimationPlaybackControlsWithThen\n{\n state: AnimationPlayState = \"idle\"\n\n startTime: number | null = null\n\n /**\n * The driver that's controlling the animation loop. Normally this is a requestAnimationFrame loop\n * but in tests we can pass in a synchronous loop.\n */\n private driver?: DriverControls\n\n private isStopped = false\n\n private generator: KeyframeGenerator<T>\n\n private calculatedDuration: number\n\n private resolvedDuration: number\n\n private totalDuration: number\n\n private options: ValueAnimationOptions<T>\n\n /**\n * The current time of the animation.\n */\n private currentTime: number = 0\n\n /**\n * The time at which the animation was paused.\n */\n private holdTime: number | null = null\n\n /**\n * Playback speed as a factor. 0 would be stopped, -1 reverse and 2 double speed.\n */\n private playbackSpeed = 1\n\n /*\n * If our generator doesn't support mixing numbers, we need to replace keyframes with\n * [0, 100] and then make a function that maps that to the actual keyframes.\n *\n * 100 is chosen instead of 1 as it works nicer with spring animations.\n */\n private mixKeyframes: Mixer<T> | undefined\n\n private mirroredGenerator: KeyframeGenerator<T> | undefined\n\n /**\n * Reusable state object for the delay phase to avoid\n * allocating a new object every frame.\n */\n private delayState: AnimationState<T> = {\n done: false,\n value: undefined as unknown as T,\n }\n\n constructor(options: ValueAnimationOptions<T>) {\n super()\n\n this.options = options\n this.initAnimation()\n this.play()\n\n if (options.autoplay === false) this.pause()\n }\n\n initAnimation() {\n const { options } = this\n\n replaceTransitionType(options)\n\n const {\n type = keyframesGenerator,\n repeat = 0,\n repeatDelay = 0,\n repeatType,\n velocity = 0,\n } = options\n let { keyframes } = options\n\n const generatorFactory =\n (type as GeneratorFactory) || keyframesGenerator\n\n if (\n process.env.NODE_ENV !== \"production\" &&\n generatorFactory !== keyframesGenerator\n ) {\n invariant(\n keyframes.length <= 2,\n `Only two keyframes currently supported with spring and inertia animations. Trying to animate ${keyframes}`,\n \"spring-two-frames\"\n )\n }\n\n if (\n generatorFactory !== keyframesGenerator &&\n typeof keyframes[0] !== \"number\"\n ) {\n this.mixKeyframes = pipe(\n percentToProgress,\n mix(keyframes[0], keyframes[1])\n ) as (t: number) => T\n\n keyframes = [0 as T, 100 as T]\n }\n\n const generator = generatorFactory({ ...options, keyframes })\n\n /**\n * If we have a mirror repeat type we need to create a second generator that outputs the\n * mirrored (not reversed) animation and later ping pong between the two generators.\n */\n if (repeatType === \"mirror\") {\n this.mirroredGenerator = generatorFactory({\n ...options,\n keyframes: [...keyframes].reverse(),\n velocity: -velocity,\n })\n }\n\n /**\n * If duration is undefined and we have repeat options,\n * we need to calculate a duration from the generator.\n *\n * We set it to the generator itself to cache the duration.\n * Any timeline resolver will need to have already precalculated\n * the duration by this step.\n */\n if (generator.calculatedDuration === null) {\n generator.calculatedDuration = calcGeneratorDuration(generator)\n }\n\n const { calculatedDuration } = generator\n this.calculatedDuration = calculatedDuration\n this.resolvedDuration = calculatedDuration + repeatDelay\n this.totalDuration = this.resolvedDuration * (repeat + 1) - repeatDelay\n this.generator = generator\n }\n\n updateTime(timestamp: number) {\n const animationTime =\n Math.round(timestamp - this.startTime!) * this.playbackSpeed\n\n // Update currentTime\n if (this.holdTime !== null) {\n this.currentTime = this.holdTime\n } else {\n // Rounding the time because floating point arithmetic is not always accurate, e.g. 3000.367 - 1000.367 =\n // 2000.0000000000002. This is a problem when we are comparing the currentTime with the duration, for\n // example.\n this.currentTime = animationTime\n }\n }\n\n tick(timestamp: number, sample = false) {\n const {\n generator,\n totalDuration,\n mixKeyframes,\n mirroredGenerator,\n resolvedDuration,\n calculatedDuration,\n } = this\n\n if (this.startTime === null) return generator.next(0)\n\n const {\n delay = 0,\n keyframes,\n repeat,\n repeatType,\n repeatDelay,\n type,\n onUpdate,\n finalKeyframe,\n } = this.options\n\n /**\n * requestAnimationFrame timestamps can come through as lower than\n * the startTime as set by performance.now(). Here we prevent this,\n * though in the future it could be possible to make setting startTime\n * a pending operation that gets resolved here.\n */\n if (this.speed > 0) {\n this.startTime = Math.min(this.startTime, timestamp)\n } else if (this.speed < 0) {\n this.startTime = Math.min(\n timestamp - totalDuration / this.speed,\n this.startTime\n )\n }\n\n if (sample) {\n this.currentTime = timestamp\n } else {\n this.updateTime(timestamp)\n }\n\n // Rebase on delay\n const timeWithoutDelay =\n this.currentTime - delay * (this.playbackSpeed >= 0 ? 1 : -1)\n const isInDelayPhase =\n this.playbackSpeed >= 0\n ? timeWithoutDelay < 0\n : timeWithoutDelay > totalDuration\n this.currentTime = Math.max(timeWithoutDelay, 0)\n\n // If this animation has finished, set the current time to the total duration.\n if (this.state === \"finished\" && this.holdTime === null) {\n this.currentTime = totalDuration\n }\n\n let elapsed = this.currentTime\n let frameGenerator = generator\n\n if (repeat) {\n /**\n * Get the current progress (0-1) of the animation. If t is >\n * than duration we'll get values like 2.5 (midway through the\n * third iteration)\n */\n const progress =\n Math.min(this.currentTime, totalDuration) / resolvedDuration\n\n /**\n * Get the current iteration (0 indexed). For instance the floor of\n * 2.5 is 2.\n */\n let currentIteration = Math.floor(progress)\n\n /**\n * Get the current progress of the iteration by taking the remainder\n * so 2.5 is 0.5 through iteration 2\n */\n let iterationProgress = progress % 1.0\n\n /**\n * If iteration progress is 1 we count that as the end\n * of the previous iteration.\n */\n if (!iterationProgress && progress >= 1) {\n iterationProgress = 1\n }\n\n iterationProgress === 1 && currentIteration--\n\n currentIteration = Math.min(currentIteration, repeat + 1)\n\n /**\n * Reverse progress if we're not running in \"normal\" direction\n */\n\n const isOddIteration = Boolean(currentIteration % 2)\n if (isOddIteration) {\n if (repeatType === \"reverse\") {\n iterationProgress = 1 - iterationProgress\n if (repeatDelay) {\n iterationProgress -= repeatDelay / resolvedDuration\n }\n } else if (repeatType === \"mirror\") {\n frameGenerator = mirroredGenerator!\n }\n }\n\n elapsed = clamp(0, 1, iterationProgress) * resolvedDuration\n }\n\n /**\n * If we're in negative time, set state as the initial keyframe.\n * This prevents delay: x, duration: 0 animations from finishing\n * instantly.\n */\n let state: AnimationState<T>\n if (isInDelayPhase) {\n this.delayState.value = keyframes[0]\n state = this.delayState\n } else {\n state = frameGenerator.next(elapsed)\n }\n\n if (mixKeyframes && !isInDelayPhase) {\n state.value = mixKeyframes(state.value as number)\n }\n\n let { done } = state\n\n if (!isInDelayPhase && calculatedDuration !== null) {\n done =\n this.playbackSpeed >= 0\n ? this.currentTime >= totalDuration\n : this.currentTime <= 0\n }\n\n const isAnimationFinished =\n this.holdTime === null &&\n (this.state === \"finished\" || (this.state === \"running\" && done))\n\n // TODO: The exception for inertia could be cleaner here\n if (isAnimationFinished && type !== inertia) {\n state.value = getFinalKeyframe(\n keyframes,\n this.options,\n finalKeyframe,\n this.speed\n )\n }\n\n if (onUpdate) {\n onUpdate(state.value)\n }\n\n if (isAnimationFinished) {\n this.finish()\n }\n\n return state\n }\n\n /**\n * Allows the returned animation to be awaited or promise-chained. Currently\n * resolves when the animation finishes at all but in a future update could/should\n * reject if its cancels.\n */\n then(resolve: VoidFunction, reject?: VoidFunction) {\n return this.finished.then(resolve, reject)\n }\n\n get duration() {\n return millisecondsToSeconds(this.calculatedDuration)\n }\n\n get iterationDuration() {\n const { delay = 0 } = this.options || {}\n return this.duration + millisecondsToSeconds(delay)\n }\n\n get time() {\n return millisecondsToSeconds(this.currentTime)\n }\n\n set time(newTime: number) {\n newTime = secondsToMilliseconds(newTime)\n this.currentTime = newTime\n\n if (\n this.startTime === null ||\n this.holdTime !== null ||\n this.playbackSpeed === 0\n ) {\n this.holdTime = newTime\n } else if (this.driver) {\n this.startTime = this.driver.now() - newTime / this.playbackSpeed\n }\n\n if (this.driver) {\n this.driver.start(false)\n } else {\n this.startTime = 0\n this.state = \"paused\"\n this.holdTime = newTime\n this.tick(newTime)\n }\n }\n\n /**\n * Returns the generator's velocity at the current time in units/second.\n * Uses the analytical derivative when available (springs), avoiding\n * the MotionValue's frame-dependent velocity estimation.\n */\n getGeneratorVelocity(): number {\n const t = this.currentTime\n if (t <= 0) return this.options.velocity || 0\n\n if (this.generator.velocity) {\n return this.generator.velocity(t)\n }\n\n // Fallback: finite difference\n const current = this.generator.next(t).value as number\n return getGeneratorVelocity(\n (s) => this.generator.next(s).value as number,\n t,\n current\n )\n }\n\n get speed() {\n return this.playbackSpeed\n }\n\n set speed(newSpeed: number) {\n const hasChanged = this.playbackSpeed !== newSpeed\n\n if (hasChanged && this.driver) {\n this.updateTime(time.now())\n }\n\n this.playbackSpeed = newSpeed\n\n if (hasChanged && this.driver) {\n this.time = millisecondsToSeconds(this.currentTime)\n }\n }\n\n play() {\n if (this.isStopped) return\n\n const { driver = frameloopDriver, startTime } = this.options\n\n if (!this.driver) {\n this.driver = driver((timestamp) => this.tick(timestamp))\n }\n\n this.options.onPlay?.()\n\n const now = this.driver.now()\n\n if (this.state === \"finished\") {\n this.updateFinished()\n this.startTime = now\n } else if (this.holdTime !== null) {\n this.startTime = now - this.holdTime\n } else if (!this.startTime) {\n this.startTime = startTime ?? now\n }\n\n if (this.state === \"finished\" && this.speed < 0) {\n this.startTime += this.calculatedDuration\n }\n\n this.holdTime = null\n\n /**\n * Set playState to running only after we've used it in\n * the previous logic.\n */\n this.state = \"running\"\n\n this.driver.start()\n }\n\n pause() {\n this.state = \"paused\"\n this.updateTime(time.now())\n this.holdTime = this.currentTime\n }\n\n /**\n * This method is bound to the instance to fix a pattern where\n * animation.stop is returned as a reference from a useEffect.\n */\n stop = () => {\n const { motionValue } = this.options\n if (motionValue && motionValue.updatedAt !== time.now()) {\n this.tick(time.now())\n }\n\n this.isStopped = true\n if (this.state === \"idle\") return\n this.teardown()\n this.options.onStop?.()\n }\n\n complete() {\n if (this.state !== \"running\") {\n this.play()\n }\n\n this.state = \"finished\"\n this.holdTime = null\n }\n\n finish() {\n this.notifyFinished()\n this.teardown()\n this.state = \"finished\"\n\n this.options.onComplete?.()\n }\n\n cancel() {\n this.holdTime = null\n this.startTime = 0\n this.tick(0)\n this.teardown()\n this.options.onCancel?.()\n }\n\n private teardown() {\n this.state = \"idle\"\n this.stopDriver()\n this.startTime = this.holdTime = null\n }\n\n private stopDriver() {\n if (!this.driver) return\n this.driver.stop()\n this.driver = undefined\n }\n\n sample(sampleTime: number): AnimationState<T> {\n this.startTime = 0\n return this.tick(sampleTime, true)\n }\n\n attachTimeline(timeline: TimelineWithFallback): VoidFunction {\n if (this.options.allowFlatten) {\n this.options.type = \"keyframes\"\n this.options.ease = \"linear\"\n this.initAnimation()\n }\n\n this.driver?.stop()\n return timeline.observe(this)\n }\n}\n\n// Legacy function support\nexport function animateValue<T extends number | string>(\n options: ValueAnimationOptions<T>\n) {\n return new JSAnimation(options)\n}\n","import { UnresolvedValueKeyframe, ValueKeyframe } from \"../../types\"\n\nexport function fillWildcards(\n keyframes: ValueKeyframe[] | UnresolvedValueKeyframe[]\n) {\n for (let i = 1; i < keyframes.length; i++) {\n keyframes[i] ??= keyframes[i - 1]\n }\n}\n","import { transformPropOrder } from \"../utils/keys-transform\"\n\nconst radToDeg = (rad: number) => (rad * 180) / Math.PI\n\ntype MatrixParser = (values: number[]) => number\n\ntype MatrixParsers = Record<\n (typeof transformPropOrder)[number],\n number | MatrixParser\n>\n\nconst rotate = (v: number[]) => {\n const angle = radToDeg(Math.atan2(v[1], v[0]))\n return rebaseAngle(angle)\n}\n\nconst matrix2dParsers: MatrixParsers = {\n x: 4,\n y: 5,\n translateX: 4,\n translateY: 5,\n scaleX: 0,\n scaleY: 3,\n scale: (v) => (Math.abs(v[0]) + Math.abs(v[3])) / 2,\n rotate,\n rotateZ: rotate,\n skewX: (v) => radToDeg(Math.atan(v[1])),\n skewY: (v) => radToDeg(Math.atan(v[2])),\n skew: (v) => (Math.abs(v[1]) + Math.abs(v[2])) / 2,\n} as const\n\nconst rebaseAngle = (angle: number) => {\n angle = angle % 360\n if (angle < 0) angle += 360\n return angle\n}\n\nconst rotateZ = rotate\n\nconst scaleX = (v: number[]) => Math.sqrt(v[0] * v[0] + v[1] * v[1])\nconst scaleY = (v: number[]) => Math.sqrt(v[4] * v[4] + v[5] * v[5])\n\nconst matrix3dParsers: MatrixParsers = {\n x: 12,\n y: 13,\n z: 14,\n translateX: 12,\n translateY: 13,\n translateZ: 14,\n scaleX,\n scaleY,\n scale: (v) => (scaleX(v) + scaleY(v)) / 2,\n rotateX: (v) => rebaseAngle(radToDeg(Math.atan2(v[6], v[5]))),\n rotateY: (v) => rebaseAngle(radToDeg(Math.atan2(-v[2], v[0]))),\n rotateZ,\n rotate: rotateZ,\n skewX: (v) => radToDeg(Math.atan(v[4])),\n skewY: (v) => radToDeg(Math.atan(v[1])),\n skew: (v) => (Math.abs(v[1]) + Math.abs(v[4])) / 2,\n} as const\n\nexport function defaultTransformValue(name: string): number {\n return name.includes(\"scale\") ? 1 : 0\n}\n\nexport function parseValueFromTransform(\n transform: string | undefined,\n name: string\n): number {\n if (!transform || transform === \"none\") {\n return defaultTransformValue(name)\n }\n\n const matrix3dMatch = transform.match(/^matrix3d\\(([-\\d.e\\s,]+)\\)$/u)\n\n let parsers: MatrixParsers\n let match: RegExpMatchArray | null\n\n if (matrix3dMatch) {\n parsers = matrix3dParsers\n match = matrix3dMatch\n } else {\n const matrix2dMatch = transform.match(/^matrix\\(([-\\d.e\\s,]+)\\)$/u)\n\n parsers = matrix2dParsers\n match = matrix2dMatch\n }\n\n if (!match) {\n return defaultTransformValue(name)\n }\n\n const valueParser = parsers[name]\n const values = match[1].split(\",\").map(convertTransformToNumber)\n\n return typeof valueParser === \"function\"\n ? valueParser(values)\n : values[valueParser]\n}\n\nexport const readTransformValue = (instance: HTMLElement, name: string) => {\n const { transform = \"none\" } = getComputedStyle(instance)\n return parseValueFromTransform(transform, name)\n}\n\nfunction convertTransformToNumber(value: string): number {\n return parseFloat(value.trim())\n}\n","/**\n * Generate a list of every possible transform key.\n */\nexport const transformPropOrder = [\n \"transformPerspective\",\n \"x\",\n \"y\",\n \"z\",\n \"translateX\",\n \"translateY\",\n \"translateZ\",\n \"scale\",\n \"scaleX\",\n \"scaleY\",\n \"rotate\",\n \"rotateX\",\n \"rotateY\",\n \"rotateZ\",\n \"skew\",\n \"skewX\",\n \"skewY\",\n]\n\n/**\n * A quick lookup for transform props.\n *\n * `pathRotation` is a transform for routing purposes (skipped from raw\n * style application, wired to the transform composite, flags transform\n * dirty) but is intentionally NOT in `transformPropOrder` — it is\n * composed onto `rotate` at the build sites, not serialized in its own\n * slot, and must stay out of the order-array consumers (parse-transform,\n * unit-conversion, keys-position).\n */\nexport const transformProps = /*@__PURE__*/ (() =>\n new Set([...transformPropOrder, \"pathRotation\"]))()\n","import type { Box } from \"motion-utils\"\nimport { parseValueFromTransform } from \"../../../render/dom/parse-transform\"\nimport { transformPropOrder } from \"../../../render/utils/keys-transform\"\nimport { MotionValue } from \"../../../value\"\nimport { number } from \"../../../value/types/numbers\"\nimport { px } from \"../../../value/types/numbers/units\"\nimport { ValueType } from \"../../../value/types/types\"\nimport { AnyResolvedKeyframe } from \"../../types\"\nimport { WithRender } from \"../types\"\n\nexport const isNumOrPxType = (v?: ValueType): v is ValueType =>\n v === number || v === px\n\ntype GetActualMeasurementInPixels = (\n bbox: Box,\n computedStyle: Partial<CSSStyleDeclaration>\n) => number\n\nconst transformKeys = new Set([\"x\", \"y\", \"z\"])\nconst nonTranslationalTransformKeys = transformPropOrder.filter(\n (key) => !transformKeys.has(key)\n)\n\ntype RemovedTransforms = [string, AnyResolvedKeyframe][]\nexport function removeNonTranslationalTransform(visualElement: WithRender) {\n const removedTransforms: RemovedTransforms = []\n\n nonTranslationalTransformKeys.forEach((key) => {\n const value: MotionValue<AnyResolvedKeyframe> | undefined =\n visualElement.getValue(key)\n if (value !== undefined) {\n removedTransforms.push([key, value.get()])\n value.set(key.startsWith(\"scale\") ? 1 : 0)\n }\n })\n\n return removedTransforms\n}\n\nexport const positionalValues: { [key: string]: GetActualMeasurementInPixels } =\n {\n // Dimensions\n width: (\n { x },\n { paddingLeft = \"0\", paddingRight = \"0\", boxSizing }\n ) => {\n const width = x.max - x.min\n return boxSizing === \"border-box\"\n ? width\n : width - parseFloat(paddingLeft) - parseFloat(paddingRight)\n },\n height: (\n { y },\n { paddingTop = \"0\", paddingBottom = \"0\", boxSizing }\n ) => {\n const height = y.max - y.min\n return boxSizing === \"border-box\"\n ? height\n : height - parseFloat(paddingTop) - parseFloat(paddingBottom)\n },\n\n top: (_bbox, { top }) => parseFloat(top as string),\n left: (_bbox, { left }) => parseFloat(left as string),\n bottom: ({ y }, { top }) => parseFloat(top as string) + (y.max - y.min),\n right: ({ x }, { left }) =>\n parseFloat(left as string) + (x.max - x.min),\n\n // Transform\n x: (_bbox, { transform }) => parseValueFromTransform(transform, \"x\"),\n y: (_bbox, { transform }) => parseValueFromTransform(transform, \"y\"),\n }\n\n// Alias translate longform names\npositionalValues.translateX = positionalValues.x\npositionalValues.translateY = positionalValues.y\n","import { frame } from \"../../frameloop\"\nimport { MotionValue } from \"../../value\"\nimport { AnyResolvedKeyframe } from \"../types\"\nimport { WithRender } from \"./types\"\nimport { fillWildcards } from \"./utils/fill-wildcards\"\nimport { removeNonTranslationalTransform } from \"./utils/unit-conversion\"\n\nexport type UnresolvedKeyframes<T extends AnyResolvedKeyframe> = Array<T | null>\n\nexport type ResolvedKeyframes<T extends AnyResolvedKeyframe> = Array<T>\n\nconst toResolve = new Set<KeyframeResolver>()\nlet isScheduled = false\nlet anyNeedsMeasurement = false\nlet isForced = false\n\nfunction measureAllKeyframes() {\n if (anyNeedsMeasurement) {\n const resolversToMeasure = Array.from(toResolve).filter(\n (resolver: KeyframeResolver) => resolver.needsMeasurement\n )\n const elementsToMeasure = new Set(\n resolversToMeasure.map((resolver) => resolver.element)\n )\n const transformsToRestore = new Map<\n WithRender,\n [string, AnyResolvedKeyframe][]\n >()\n\n /**\n * Write pass\n * If we're measuring elements we want to remove bounding box-changing transforms.\n */\n elementsToMeasure.forEach((element: WithRender) => {\n const removedTransforms = removeNonTranslationalTransform(\n element as any\n )\n\n if (!removedTransforms.length) return\n\n transformsToRestore.set(element, removedTransforms)\n\n element.render()\n })\n\n // Read\n resolversToMeasure.forEach((resolver) => resolver.measureInitialState())\n\n // Write\n elementsToMeasure.forEach((element: WithRender) => {\n element.render()\n\n const restore = transformsToRestore.get(element)\n if (restore) {\n restore.forEach(([key, value]) => {\n element.getValue(key)?.set(value)\n })\n }\n })\n\n // Read\n resolversToMeasure.forEach((resolver) => resolver.measureEndState())\n\n // Write\n resolversToMeasure.forEach((resolver) => {\n if (resolver.suspendedScrollY !== undefined) {\n window.scrollTo(0, resolver.suspendedScrollY)\n }\n })\n }\n\n anyNeedsMeasurement = false\n isScheduled = false\n\n toResolve.forEach((resolver) => resolver.complete(isForced))\n toResolve.clear()\n}\n\nfunction readAllKeyframes() {\n toResolve.forEach((resolver) => {\n resolver.readKeyframes()\n\n if (resolver.needsMeasurement) {\n anyNeedsMeasurement = true\n }\n })\n}\n\nexport function flushKeyframeResolvers() {\n isForced = true\n readAllKeyframes()\n measureAllKeyframes()\n isForced = false\n}\n\nexport type OnKeyframesResolved<T extends AnyResolvedKeyframe> = (\n resolvedKeyframes: ResolvedKeyframes<T>,\n finalKeyframe: T,\n forced: boolean\n) => void\n\nexport class KeyframeResolver<T extends AnyResolvedKeyframe = any> {\n name?: string\n element?: WithRender\n finalKeyframe?: T\n suspendedScrollY?: number\n\n protected unresolvedKeyframes: UnresolvedKeyframes<AnyResolvedKeyframe>\n\n private motionValue?: MotionValue<T>\n private onComplete: OnKeyframesResolved<T>\n\n state: \"pending\" | \"scheduled\" | \"complete\" = \"pending\"\n\n /**\n * Track whether this resolver is async. If it is, it'll be added to the\n * resolver queue and flushed in the next frame. Resolvers that aren't going\n * to trigger read/write thrashing don't need to be async.\n */\n private isAsync = false\n\n /**\n * Track whether this resolver needs to perform a measurement\n * to resolve its keyframes.\n */\n needsMeasurement = false\n\n constructor(\n unresolvedKeyframes: UnresolvedKeyframes<AnyResolvedKeyframe>,\n onComplete: OnKeyframesResolved<T>,\n name?: string,\n motionValue?: MotionValue<T>,\n element?: WithRender,\n isAsync = false\n ) {\n this.unresolvedKeyframes = [...unresolvedKeyframes]\n this.onComplete = onComplete\n this.name = name\n this.motionValue = motionValue\n this.element = element\n this.isAsync = isAsync\n }\n\n scheduleResolve() {\n this.state = \"scheduled\"\n\n if (this.isAsync) {\n toResolve.add(this)\n\n if (!isScheduled) {\n isScheduled = true\n frame.read(readAllKeyframes)\n frame.resolveKeyframes(measureAllKeyframes)\n }\n } else {\n this.readKeyframes()\n this.complete()\n }\n }\n\n readKeyframes() {\n const { unresolvedKeyframes, name, element, motionValue } = this\n\n // If initial keyframe is null we need to read it from the DOM\n if (unresolvedKeyframes[0] === null) {\n const currentValue = motionValue?.get()\n\n // TODO: This doesn't work if the final keyframe is a wildcard\n const finalKeyframe =\n unresolvedKeyframes[unresolvedKeyframes.length - 1]\n\n if (currentValue !== undefined) {\n unresolvedKeyframes[0] = currentValue\n } else if (element && name) {\n const valueAsRead = element.readValue(name, finalKeyframe)\n\n if (valueAsRead !== undefined && valueAsRead !== null) {\n unresolvedKeyframes[0] = valueAsRead\n }\n }\n\n if (unresolvedKeyframes[0] === undefined) {\n unresolvedKeyframes[0] = finalKeyframe\n }\n\n if (motionValue && currentValue === undefined) {\n motionValue.set(unresolvedKeyframes[0] as T)\n }\n }\n\n fillWildcards(unresolvedKeyframes)\n }\n\n setFinalKeyframe() {}\n measureInitialState() {}\n renderEndStyles() {}\n measureEndState() {}\n\n complete(isForcedComplete = false) {\n this.state = \"complete\"\n\n this.onComplete(\n this.unresolvedKeyframes as ResolvedKeyframes<T>,\n this.finalKeyframe as T,\n isForcedComplete\n )\n\n toResolve.delete(this)\n }\n\n cancel() {\n if (this.state === \"scheduled\") {\n toResolve.delete(this)\n this.state = \"pending\"\n }\n }\n\n resume() {\n if (this.state === \"pending\") this.scheduleResolve()\n }\n}\n","export const isCSSVar = (name: string) => name.startsWith(\"--\")\n","import { AnyResolvedKeyframe } from \"../../animation/types\"\nimport { isCSSVar } from \"./is-css-var\"\n\nexport function setStyle(\n element: HTMLElement | SVGElement,\n name: string,\n value: AnyResolvedKeyframe\n) {\n isCSSVar(name)\n ? element.style.setProperty(name, value as string)\n : (element.style[name as any] = value as string)\n}\n","/**\n * Add the ability for test suites to manually set support flags\n * to better test more environments.\n */\nexport const supportsFlags: Record<string, boolean | undefined> = {}\n","import { memo } from \"motion-utils\"\nimport { supportsFlags } from \"./flags\"\n\nexport function memoSupports<T extends any>(\n callback: () => T,\n supportsFlag: keyof typeof supportsFlags\n) {\n const memoized = memo(callback)\n return () => supportsFlags[supportsFlag] ?? memoized()\n}\n","import { ProgressTimeline } from \"../..\"\nimport { memoSupports } from \"./memo\"\n\ndeclare global {\n interface Window {\n ScrollTimeline: ScrollTimeline\n ViewTimeline: ViewTimeline\n }\n}\n\ndeclare class ScrollTimeline implements ProgressTimeline {\n constructor(options: ScrollOptions)\n\n currentTime: null | { value: number }\n\n cancel?: VoidFunction\n}\n\ndeclare class ViewTimeline implements ProgressTimeline {\n constructor(options: { subject: Element; axis?: string })\n\n currentTime: null | { value: number }\n\n cancel?: VoidFunction\n}\n\nexport const supportsScrollTimeline = /* @__PURE__ */ memoSupports(\n () => window.ScrollTimeline !== undefined,\n \"scrollTimeline\"\n)\n\nexport const supportsViewTimeline = /* @__PURE__ */ memoSupports(\n () => window.ViewTimeline !== undefined,\n \"viewTimeline\"\n)\n","import { memoSupports } from \"./memo\"\n\nexport const supportsLinearEasing = /*@__PURE__*/ memoSupports(() => {\n try {\n document\n .createElement(\"div\")\n .animate({ opacity: 0 }, { easing: \"linear(0, 1)\" })\n } catch (e) {\n return false\n }\n return true\n}, \"linearEasing\")\n","import { BezierDefinition } from \"motion-utils\"\n\nexport const cubicBezierAsString = ([a, b, c, d]: BezierDefinition) =>\n `cubic-bezier(${a}, ${b}, ${c}, ${d})`\n","import { cubicBezierAsString } from \"./cubic-bezier\"\n\nexport const supportedWaapiEasing = {\n linear: \"linear\",\n ease: \"ease\",\n easeIn: \"ease-in\",\n easeOut: \"ease-out\",\n easeInOut: \"ease-in-out\",\n circIn: /*@__PURE__*/ cubicBezierAsString([0, 0.65, 0.55, 1]),\n circOut: /*@__PURE__*/ cubicBezierAsString([0.55, 0, 1, 0.45]),\n backIn: /*@__PURE__*/ cubicBezierAsString([0.31, 0.01, 0.66, -0.59]),\n backOut: /*@__PURE__*/ cubicBezierAsString([0.33, 1.53, 0.69, 0.99]),\n}\n","import { Easing, isBezierDefinition } from \"motion-utils\"\nimport { supportsLinearEasing } from \"../../../utils/supports/linear-easing\"\nimport { generateLinearEasing } from \"../utils/linear\"\nimport { cubicBezierAsString } from \"./cubic-bezier\"\nimport { supportedWaapiEasing } from \"./supported\"\n\nexport function mapEasingToNativeEasing(\n easing: Easing | Easing[] | undefined,\n duration: number\n): undefined | string | string[] {\n if (!easing) {\n return undefined\n } else if (typeof easing === \"function\") {\n return supportsLinearEasing()\n ? generateLinearEasing(easing, duration)\n : \"ease-out\"\n } else if (isBezierDefinition(easing)) {\n return cubicBezierAsString(easing)\n } else if (Array.isArray(easing)) {\n return easing.map(\n (segmentEasing) =>\n (mapEasingToNativeEasing(segmentEasing, duration) as string) ||\n supportedWaapiEasing.easeOut\n )\n } else {\n return supportedWaapiEasing[easing as keyof typeof supportedWaapiEasing]\n }\n}\n","import { ValueKeyframesDefinition, ValueTransition } from \"../types\"\nimport { mapEasingToNativeEasing } from \"./easing/map-easing\"\n\nexport function startWaapiAnimation(\n element: Element,\n valueName: string,\n keyframes: ValueKeyframesDefinition,\n {\n delay = 0,\n duration = 300,\n repeat = 0,\n repeatType = \"loop\",\n ease = \"easeOut\",\n times,\n }: ValueTransition = {},\n pseudoElement: string | undefined = undefined\n) {\n const keyframeOptions: PropertyIndexedKeyframes = {\n [valueName]: keyframes as string[],\n }\n if (times) keyframeOptions.offset = times\n\n const easing = mapEasingToNativeEasing(ease, duration)\n\n /**\n * If this is an easing array, apply to keyframes, not animation as a whole\n */\n if (Array.isArray(easing)) keyframeOptions.easing = easing\n\n const options: KeyframeAnimationOptions = {\n delay,\n duration,\n easing: !Array.isArray(easing) ? easing : \"linear\",\n fill: \"both\",\n iterations: repeat + 1,\n direction: repeatType === \"reverse\" ? \"alternate\" : \"normal\",\n }\n\n if (pseudoElement) options.pseudoElement = pseudoElement\n\n return element.animate(keyframeOptions, options)\n}\n","import { AnimationGeneratorType, GeneratorFactory } from \"../../types\"\n\nexport function isGenerator(\n type?: AnimationGeneratorType\n): type is GeneratorFactory {\n return typeof type === \"function\" && \"applyToOptions\" in type\n}\n","import { ValueTransition } from \"../../../animation/types\"\nimport { supportsLinearEasing } from \"../../../utils/supports/linear-easing\"\nimport { isGenerator } from \"../../generators/utils/is-generator\"\n\nexport function applyGeneratorOptions({\n type,\n ...options\n}: ValueTransition): ValueTransition {\n if (isGenerator(type) && supportsLinearEasing()) {\n return type.applyToOptions!(options)\n } else {\n options.duration ??= 300\n options.ease ??= \"easeOut\"\n }\n\n return options\n}\n","import {\n invariant,\n millisecondsToSeconds,\n noop,\n secondsToMilliseconds,\n} from \"motion-utils\"\nimport { setStyle } from \"../render/dom/style-set\"\nimport { supportsScrollTimeline } from \"../utils/supports/scroll-timeline\"\nimport { getFinalKeyframe } from \"./keyframes/get-final\"\nimport {\n AnimationPlaybackControlsWithThen,\n AnyResolvedKeyframe,\n DOMValueAnimationOptions,\n TimelineWithFallback,\n} from \"./types\"\nimport { WithPromise } from \"./utils/WithPromise\"\nimport { startWaapiAnimation } from \"./waapi/start-waapi-animation\"\nimport { applyGeneratorOptions } from \"./waapi/utils/apply-generator\"\n\nexport interface NativeAnimationOptions<V extends AnyResolvedKeyframe = number>\n extends DOMValueAnimationOptions<V> {\n pseudoElement?: string\n startTime?: number\n}\n\n/**\n * NativeAnimation implements AnimationPlaybackControls for the browser's Web Animations API.\n */\nexport class NativeAnimation<T extends AnyResolvedKeyframe>\n extends WithPromise\n implements AnimationPlaybackControlsWithThen\n{\n /**\n * The interfaced Web Animation API animation\n */\n protected animation: Animation\n\n protected finishedTime: number | null = null\n\n protected options: NativeAnimationOptions\n\n private allowFlatten: boolean\n\n private isStopped = false\n\n private isPseudoElement: boolean\n\n /**\n * Tracks a manually-set start time that takes precedence over WAAPI's\n * dynamic startTime. This is cleared when play() or time setter is called,\n * allowing WAAPI to take over timing.\n */\n protected manualStartTime: number | null = null\n\n constructor(options?: NativeAnimationOptions) {\n super()\n\n if (!options) return\n\n const {\n element,\n name,\n keyframes,\n pseudoElement,\n allowFlatten = false,\n finalKeyframe,\n onComplete,\n } = options as any\n\n this.isPseudoElement = Boolean(pseudoElement)\n\n this.allowFlatten = allowFlatten\n this.options = options\n\n invariant(\n typeof options.type !== \"string\",\n `Mini animate() doesn't support \"type\" as a string.`,\n \"mini-spring\"\n )\n\n const transition = applyGeneratorOptions(options)\n\n this.animation = startWaapiAnimation(\n element,\n name,\n keyframes,\n transition,\n pseudoElement\n )\n\n if (transition.autoplay === false) {\n this.animation.pause()\n }\n\n this.animation.onfinish = () => {\n this.finishedTime = this.time\n\n if (!pseudoElement) {\n const keyframe = getFinalKeyframe(\n keyframes as any,\n this.options as any,\n finalKeyframe,\n this.speed\n )\n if (this.updateMotionValue) {\n this.updateMotionValue(keyframe)\n }\n\n /**\n * If we can, we want to commit the final style as set by the user,\n * rather than the computed keyframe value supplied by the animation.\n * We always do this, even when a motion value is present, to prevent\n * a visual flash in Firefox where the WAAPI animation's fill is removed\n * during cancel() before the scheduled render can apply the correct value.\n */\n setStyle(element, name, keyframe)\n\n this.animation.cancel()\n }\n\n onComplete?.()\n this.notifyFinished()\n }\n }\n\n updateMotionValue?(value?: T): void\n\n play() {\n if (this.isStopped) return\n\n this.manualStartTime = null\n this.animation.play()\n\n if (this.state === \"finished\") {\n this.updateFinished()\n }\n }\n\n pause() {\n this.animation.pause()\n }\n\n complete() {\n this.animation.finish?.()\n }\n\n cancel() {\n try {\n this.animation.cancel()\n } catch (e) {}\n }\n\n stop() {\n if (this.isStopped) return\n this.isStopped = true\n const { state } = this\n\n if (state === \"idle\" || state === \"finished\") {\n return\n }\n\n if (this.updateMotionValue) {\n this.updateMotionValue()\n } else {\n this.commitStyles()\n }\n\n if (!this.isPseudoElement) this.cancel()\n }\n\n /**\n * WAAPI doesn't natively have any interruption capabilities.\n *\n * In this method, we commit styles back to the DOM before cancelling\n * the animation.\n *\n * This is designed to be overridden by NativeAnimationExtended, which\n * will create a renderless JS animation and sample it twice to calculate\n * its current value, \"previous\" value, and therefore allow\n * Motion to also correctly calculate velocity for any subsequent animation\n * while deferring the commit until the next animation frame.\n */\n protected commitStyles() {\n const element = this.options?.element\n if (!this.isPseudoElement && element?.isConnected) {\n this.animation.commitStyles?.()\n }\n }\n\n get duration() {\n const duration =\n this.animation.effect?.getComputedTiming?.().duration || 0\n\n return millisecondsToSeconds(Number(duration))\n }\n\n get iterationDuration() {\n const { delay = 0 } = this.options || {}\n return this.duration + millisecondsToSeconds(delay)\n }\n\n get time() {\n return millisecondsToSeconds(Number(this.animation.currentTime) || 0)\n }\n\n set time(newTime: number) {\n const wasFinished = this.finishedTime !== null\n this.manualStartTime = null\n this.finishedTime = null\n this.animation.currentTime = secondsToMilliseconds(newTime)\n\n if (wasFinished) {\n this.animation.pause()\n }\n }\n\n /**\n * The playback speed of the animation.\n * 1 = normal speed, 2 = double speed, 0.5 = half speed.\n */\n get speed() {\n return this.animation.playbackRate\n }\n\n set speed(newSpeed: number) {\n // Allow backwards playback after finishing\n if (newSpeed < 0) this.finishedTime = null\n\n this.animation.playbackRate = newSpeed\n }\n\n get state() {\n return this.finishedTime !== null\n ? \"finished\"\n : this.animation.playState\n }\n\n get startTime() {\n return this.manualStartTime ?? Number(this.animation.startTime)\n }\n\n set startTime(newStartTime: number) {\n this.manualStartTime = this.animation.startTime = newStartTime\n }\n\n /**\n * Attaches a timeline to the animation, for instance the `ScrollTimeline`.\n */\n attachTimeline({\n timeline,\n rangeStart,\n rangeEnd,\n observe,\n }: TimelineWithFallback): VoidFunction {\n if (this.allowFlatten) {\n this.animation.effect?.updateTiming({ easing: \"linear\" })\n }\n\n this.animation.onfinish = null\n\n if (timeline && supportsScrollTimeline()) {\n this.animation.timeline = timeline as any\n\n if (rangeStart) (this.animation as any).rangeStart = rangeStart\n if (rangeEnd) (this.animation as any).rangeEnd = rangeEnd\n\n return noop<void>\n } else {\n return observe(this)\n }\n }\n}\n","import { anticipate, backInOut, circInOut } from \"motion-utils\"\nimport { ValueAnimationTransition } from \"../../types\"\n\nconst unsupportedEasingFunctions = {\n anticipate,\n backInOut,\n circInOut,\n}\n\nfunction isUnsupportedEase(\n key: string\n): key is keyof typeof unsupportedEasingFunctions {\n return key in unsupportedEasingFunctions\n}\n\nexport function replaceStringEasing(transition: ValueAnimationTransition) {\n if (\n typeof transition.ease === \"string\" &&\n isUnsupportedEase(transition.ease)\n ) {\n transition.ease = unsupportedEasingFunctions[transition.ease]\n }\n}\n","import { clamp } from \"motion-utils\"\nimport { time } from \"../frameloop/sync-time\"\nimport { setStyle } from \"../render/dom/style-set\"\nimport { JSAnimation } from \"./JSAnimation\"\nimport { NativeAnimation, NativeAnimationOptions } from \"./NativeAnimation\"\nimport { AnyResolvedKeyframe, ValueAnimationOptions } from \"./types\"\nimport { replaceTransitionType } from \"./utils/replace-transition-type\"\nimport { replaceStringEasing } from \"./waapi/utils/unsupported-easing\"\n\nexport type NativeAnimationOptionsExtended<T extends AnyResolvedKeyframe> =\n NativeAnimationOptions & ValueAnimationOptions<T> & NativeAnimationOptions\n\n/**\n * 10ms is chosen here as it strikes a balance between smooth\n * results (more than one keyframe per frame at 60fps) and\n * keyframe quantity.\n */\nconst sampleDelta = 10 //ms\n\nexport class NativeAnimationExtended<\n T extends AnyResolvedKeyframe\n> extends NativeAnimation<T> {\n options: NativeAnimationOptionsExtended<T>\n\n constructor(options: NativeAnimationOptionsExtended<T>) {\n /**\n * The base NativeAnimation function only supports a subset\n * of Motion easings, and WAAPI also only supports some\n * easing functions via string/cubic-bezier definitions.\n *\n * This function replaces those unsupported easing functions\n * with a JS easing function. This will later get compiled\n * to a linear() easing function.\n */\n replaceStringEasing(options)\n\n /**\n * Ensure we replace the transition type with a generator function\n * before passing to WAAPI.\n *\n * TODO: Does this have a better home? It could be shared with\n * JSAnimation.\n */\n replaceTransitionType(options)\n\n super(options)\n\n /**\n * Only set startTime when the animation should autoplay.\n * Setting startTime on a paused WAAPI animation unpauses it\n * (per the WAAPI spec), which breaks autoplay: false.\n */\n if (options.startTime !== undefined && options.autoplay !== false) {\n this.startTime = options.startTime\n }\n\n this.options = options\n }\n\n /**\n * WAAPI doesn't natively have any interruption capabilities.\n *\n * Rather than read committed styles back out of the DOM, we can\n * create a renderless JS animation and sample it twice to calculate\n * its current value, \"previous\" value, and therefore allow\n * Motion to calculate velocity for any subsequent animation.\n */\n updateMotionValue(value?: T) {\n const { motionValue, onUpdate, onComplete, element, ...options } =\n this.options\n\n if (!motionValue) return\n\n if (value !== undefined) {\n motionValue.set(value)\n return\n }\n\n const sampleAnimation = new JSAnimation({\n ...options,\n autoplay: false,\n })\n\n /**\n * Use wall-clock elapsed time for sampling.\n * Under CPU load, WAAPI's currentTime may not reflect actual\n * elapsed time, causing incorrect sampling and visual jumps.\n */\n const sampleTime = Math.max(sampleDelta, time.now() - this.startTime)\n const delta = clamp(0, sampleDelta, sampleTime - sampleDelta)\n const current = sampleAnimation.sample(sampleTime).value\n\n /**\n * Write the estimated value to inline style so it persists\n * after cancel(), covering the async gap before the next\n * animation starts.\n */\n const { name } = this.options\n if (element && name) setStyle(element, name, current)\n\n motionValue.setWithVelocity(\n sampleAnimation.sample(Math.max(0, sampleTime - delta)).value,\n current,\n delta\n )\n\n sampleAnimation.stop()\n }\n}\n","import { complex } from \"../../value/types/complex\"\nimport { ValueKeyframesDefinition } from \"../types\"\n\n/**\n * Check if a value is animatable. Examples:\n *\n * ✅: 100, \"100px\", \"#fff\"\n * ❌: \"block\", \"url(2.jpg)\"\n * @param value\n *\n * @internal\n */\nexport const isAnimatable = (\n value: ValueKeyframesDefinition,\n name?: string\n) => {\n // If the list of keys that might be non-animatable grows, replace with Set\n if (name === \"zIndex\") return false\n\n // If it's a number or a keyframes array, we can animate it. We might at some point\n // need to do a deep isAnimatable check of keyframes, or let Popmotion handle this,\n // but for now lets leave it like this for performance reasons\n if (typeof value === \"number\" || Array.isArray(value)) return true\n\n if (\n typeof value === \"string\" && // It's animatable if we have a string\n (complex.test(value) || value === \"0\") && // And it contains numbers and/or colors\n !value.startsWith(\"url(\") // Unless it starts with \"url(\"\n ) {\n return true\n }\n\n return false\n}\n","import { warning } from \"motion-utils\"\nimport { isGenerator } from \"../generators/utils/is-generator\"\nimport { ResolvedKeyframes } from \"../keyframes/KeyframesResolver\"\nimport { AnimationGeneratorType } from \"../types\"\nimport { isAnimatable } from \"./is-animatable\"\n\nfunction hasKeyframesChanged(keyframes: ResolvedKeyframes<any>) {\n const current = keyframes[0]\n if (keyframes.length === 1) return true\n for (let i = 0; i < keyframes.length; i++) {\n if (keyframes[i] !== current) return true\n }\n}\n\nexport function canAnimate(\n keyframes: ResolvedKeyframes<any>,\n name?: string,\n type?: AnimationGeneratorType,\n velocity?: number\n) {\n /**\n * Check if we're able to animate between the start and end keyframes,\n * and throw a warning if we're attempting to animate between one that's\n * animatable and another that isn't.\n */\n const originKeyframe = keyframes[0]\n if (originKeyframe === null) {\n return false\n }\n\n /**\n * These aren't traditionally animatable but we do support them.\n * In future we could look into making this more generic or replacing\n * this function with mix() === mixImmediate\n */\n if (name === \"display\" || name === \"visibility\") return true\n\n const targetKeyframe = keyframes[keyframes.length - 1]\n const isOriginAnimatable = isAnimatable(originKeyframe, name)\n const isTargetAnimatable = isAnimatable(targetKeyframe, name)\n\n warning(\n isOriginAnimatable === isTargetAnimatable,\n `You are trying to animate ${name} from \"${originKeyframe}\" to \"${targetKeyframe}\". \"${\n isOriginAnimatable ? targetKeyframe : originKeyframe\n }\" is not an animatable value.`,\n \"value-not-animatable\"\n )\n\n // Always skip if any of these are true\n if (!isOriginAnimatable || !isTargetAnimatable) {\n return false\n }\n\n return (\n hasKeyframesChanged(keyframes) ||\n ((type === \"spring\" || isGenerator(type)) && velocity)\n )\n}\n","import { ValueAnimationOptions } from \"../types\"\n\nexport function makeAnimationInstant(\n options: Partial<{\n duration: ValueAnimationOptions[\"duration\"]\n type: ValueAnimationOptions[\"type\"]\n }>\n): void {\n options.duration = 0\n options.type = \"keyframes\"\n}\n","/**\n * A list of values that can be hardware-accelerated.\n */\nexport const acceleratedValues = new Set<string>([\n \"opacity\",\n \"clipPath\",\n \"filter\",\n \"transform\",\n // TODO: Can be accelerated but currently disabled until https://issues.chromium.org/issues/41491098 is resolved\n // or until we implement support for linear() easing.\n // \"background-color\"\n])\n","const browserColorFunctions =\n /^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\\(/\n\nexport function hasBrowserOnlyColors(keyframes: any[]): boolean {\n for (let i = 0; i < keyframes.length; i++) {\n if (\n typeof keyframes[i] === \"string\" &&\n browserColorFunctions.test(keyframes[i])\n ) {\n return true\n }\n }\n return false\n}\n","import { memo } from \"motion-utils\"\nimport {\n AnyResolvedKeyframe,\n ValueAnimationOptionsWithRenderContext,\n} from \"../../types\"\nimport { acceleratedValues } from \"../utils/accelerated-values\"\nimport { hasBrowserOnlyColors } from \"../utils/is-browser-color\"\n\nconst colorProperties = new Set([\n \"color\",\n \"backgroundColor\",\n \"outlineColor\",\n \"fill\",\n \"stroke\",\n \"borderColor\",\n \"borderTopColor\",\n \"borderRightColor\",\n \"borderBottomColor\",\n \"borderLeftColor\",\n])\n\nconst supportsWaapi = /*@__PURE__*/ memo(() =>\n Object.hasOwnProperty.call(Element.prototype, \"animate\")\n)\n\nexport function supportsBrowserAnimation<T extends AnyResolvedKeyframe>(\n options: ValueAnimationOptionsWithRenderContext<T>\n) {\n const {\n motionValue,\n name,\n repeatDelay,\n repeatType,\n damping,\n type,\n keyframes,\n } = options\n\n const subject = motionValue?.owner?.current\n\n /**\n * We use this check instead of isHTMLElement() because we explicitly\n * **don't** want elements in different timing contexts (i.e. popups)\n * to be accelerated, as it's not possible to sync these animations\n * properly with those driven from the main window frameloop.\n */\n if (!(subject instanceof HTMLElement)) {\n return false\n }\n\n const { onUpdate, transformTemplate } = motionValue!.owner!.getProps()\n\n return (\n supportsWaapi() &&\n name &&\n /**\n * Force WAAPI for color properties with browser-only color formats\n * (oklch, oklab, lab, lch, etc.) that the JS animation path can't parse.\n */\n (acceleratedValues.has(name) ||\n (colorProperties.has(name) &&\n hasBrowserOnlyColors(keyframes))) &&\n (name !== \"transform\" || !transformTemplate) &&\n /**\n * If we're outputting values to onUpdate then we can't use WAAPI as there's\n * no way to read the value from WAAPI every frame.\n */\n !onUpdate &&\n !repeatDelay &&\n repeatType !== \"mirror\" &&\n damping !== 0 &&\n type !== \"inertia\"\n )\n}\n","import { MotionGlobalConfig, noop } from \"motion-utils\"\nimport { time } from \"../frameloop/sync-time\"\nimport { JSAnimation } from \"./JSAnimation\"\nimport { getFinalKeyframe } from \"./keyframes/get-final\"\nimport {\n KeyframeResolver as DefaultKeyframeResolver,\n flushKeyframeResolvers,\n ResolvedKeyframes,\n} from \"./keyframes/KeyframesResolver\"\nimport { NativeAnimationExtended } from \"./NativeAnimationExtended\"\nimport {\n AnimationPlaybackControls,\n AnyResolvedKeyframe,\n TimelineWithFallback,\n ValueAnimationOptions,\n} from \"./types\"\nimport { canAnimate } from \"./utils/can-animate\"\nimport { makeAnimationInstant } from \"./utils/make-animation-instant\"\nimport { WithPromise } from \"./utils/WithPromise\"\nimport { supportsBrowserAnimation } from \"./waapi/supports/waapi\"\n\n/**\n * Maximum time allowed between an animation being created and it being\n * resolved for us to use the latter as the start time.\n *\n * This is to ensure that while we prefer to \"start\" an animation as soon\n * as it's triggered, we also want to avoid a visual jump if there's a big delay\n * between these two moments.\n */\nconst MAX_RESOLVE_DELAY = 40\n\ntype OptionsWithoutKeyframes<T extends AnyResolvedKeyframe> = Omit<\n ValueAnimationOptions<T>,\n \"keyframes\"\n>\n\nexport class AsyncMotionValueAnimation<T extends AnyResolvedKeyframe>\n extends WithPromise\n implements AnimationPlaybackControls\n{\n private createdAt: number\n\n private resolvedAt: number | undefined\n\n private _animation: AnimationPlaybackControls | undefined\n\n private pendingTimeline: TimelineWithFallback | undefined\n\n private keyframeResolver: DefaultKeyframeResolver | undefined\n\n private stopTimeline: VoidFunction | undefined\n\n constructor({\n autoplay = true,\n delay = 0,\n type = \"keyframes\",\n repeat = 0,\n repeatDelay = 0,\n repeatType = \"loop\",\n keyframes,\n name,\n motionValue,\n element,\n ...options\n }: ValueAnimationOptions<T>) {\n super()\n\n this.createdAt = time.now()\n\n const optionsWithDefaults: OptionsWithoutKeyframes<T> = {\n autoplay,\n delay,\n type,\n repeat,\n repeatDelay,\n repeatType,\n name,\n motionValue,\n element,\n ...options,\n }\n\n const KeyframeResolver =\n element?.KeyframeResolver || DefaultKeyframeResolver\n\n this.keyframeResolver = new KeyframeResolver(\n keyframes,\n (\n resolvedKeyframes: ResolvedKeyframes<T>,\n finalKeyframe: T,\n forced: boolean\n ) =>\n this.onKeyframesResolved(\n resolvedKeyframes,\n finalKeyframe,\n optionsWithDefaults,\n !forced\n ),\n name,\n motionValue,\n element\n )\n this.keyframeResolver?.scheduleResolve()\n }\n\n onKeyframesResolved(\n keyframes: ResolvedKeyframes<T>,\n finalKeyframe: T,\n options: OptionsWithoutKeyframes<T>,\n sync: boolean\n ) {\n this.keyframeResolver = undefined\n\n const { name, type, velocity, delay, isHandoff, onUpdate } = options\n this.resolvedAt = time.now()\n\n /**\n * If we can't animate this value with the resolved keyframes\n * then we should complete it immediately.\n */\n let canAnimateValue = true\n if (!canAnimate(keyframes, name, type, velocity)) {\n canAnimateValue = false\n\n if (MotionGlobalConfig.instantAnimations || !delay) {\n onUpdate?.(getFinalKeyframe(keyframes, options, finalKeyframe))\n }\n\n keyframes[0] = keyframes[keyframes.length - 1]\n\n makeAnimationInstant(options)\n options.repeat = 0\n }\n\n /**\n * Resolve startTime for the animation.\n *\n * This method uses the createdAt and resolvedAt to calculate the\n * animation startTime. *Ideally*, we would use the createdAt time as t=0\n * as the following frame would then be the first frame of the animation in\n * progress, which would feel snappier.\n *\n * However, if there's a delay (main thread work) between the creation of\n * the animation and the first committed frame, we prefer to use resolvedAt\n * to avoid a sudden jump into the animation.\n */\n const startTime = sync\n ? !this.resolvedAt\n ? this.createdAt\n : this.resolvedAt - this.createdAt > MAX_RESOLVE_DELAY\n ? this.resolvedAt\n : this.createdAt\n : undefined\n\n const resolvedOptions = {\n startTime,\n finalKeyframe,\n ...options,\n keyframes,\n }\n\n /**\n * Animate via WAAPI if possible. If this is a handoff animation, the optimised animation will be running via\n * WAAPI. Therefore, this animation must be JS to ensure it runs \"under\" the\n * optimised animation.\n *\n * Also skip WAAPI when keyframes aren't animatable, as the resolved\n * values may not be valid CSS and would trigger browser warnings.\n */\n const useWaapi =\n canAnimateValue &&\n !isHandoff &&\n supportsBrowserAnimation(resolvedOptions)\n const element = resolvedOptions.motionValue?.owner?.current\n\n let animation: AnimationPlaybackControls\n if (useWaapi) {\n try {\n animation = new NativeAnimationExtended({\n ...resolvedOptions,\n element,\n } as any)\n } catch {\n animation = new JSAnimation(resolvedOptions)\n }\n } else {\n animation = new JSAnimation(resolvedOptions)\n }\n\n animation.finished.then(() => {\n this.notifyFinished()\n }).catch(noop)\n\n if (this.pendingTimeline) {\n this.stopTimeline = animation.attachTimeline(this.pendingTimeline)\n this.pendingTimeline = undefined\n }\n\n this._animation = animation\n }\n\n get finished() {\n if (!this._animation) {\n return this._finished\n } else {\n return this.animation.finished\n }\n }\n\n then(onResolve: VoidFunction, _onReject?: VoidFunction) {\n return this.finished.finally(onResolve).then(() => {})\n }\n\n get animation(): AnimationPlaybackControls {\n if (!this._animation) {\n this.keyframeResolver?.resume()\n flushKeyframeResolvers()\n }\n\n return this._animation!\n }\n\n get duration() {\n return this.animation.duration\n }\n\n get iterationDuration() {\n return this.animation.iterationDuration\n }\n\n get time() {\n return this.animation.time\n }\n\n set time(newTime: number) {\n this.animation.time = newTime\n }\n\n get speed() {\n return this.animation.speed\n }\n\n get state() {\n return this.animation.state\n }\n\n set speed(newSpeed: number) {\n this.animation.speed = newSpeed\n }\n\n get startTime() {\n return this.animation.startTime\n }\n\n attachTimeline(timeline: TimelineWithFallback) {\n if (this._animation) {\n this.stopTimeline = this.animation.attachTimeline(timeline)\n } else {\n this.pendingTimeline = timeline\n }\n\n return () => this.stop()\n }\n\n play() {\n this.animation.play()\n }\n\n pause() {\n this.animation.pause()\n }\n\n complete() {\n this.animation.complete()\n }\n\n cancel() {\n if (this._animation) {\n this.animation.cancel()\n }\n\n this.keyframeResolver?.cancel()\n }\n\n /**\n * Bound to support return animation.stop pattern\n */\n stop = () => {\n if (this._animation) {\n this._animation.stop()\n this.stopTimeline?.()\n }\n\n this.keyframeResolver?.cancel()\n }\n}\n","import type { DynamicOption } from \"../types\"\nimport type { VisualElement } from \"../../render/VisualElement\"\n\nexport function calcChildStagger(\n children: Set<VisualElement>,\n child: VisualElement,\n delayChildren?: number | DynamicOption<number>,\n staggerChildren: number = 0,\n staggerDirection: number = 1\n): number {\n const index = Array.from(children)\n .sort((a, b) => a.sortNodePosition(b))\n .indexOf(child)\n const numChildren = children.size\n const maxStaggerDuration = (numChildren - 1) * staggerChildren\n const delayIsFunction = typeof delayChildren === \"function\"\n\n return delayIsFunction\n ? delayChildren(index, numChildren)\n : staggerDirection === 1\n ? index * staggerChildren\n : maxStaggerDuration - index * staggerChildren\n}\n","import {\n EasingFunction,\n SubscriptionManager,\n velocityPerSecond,\n warnOnce,\n} from \"motion-utils\"\nimport {\n AnimationPlaybackControlsWithThen,\n AnyResolvedKeyframe,\n TransformProperties,\n} from \"../animation/types\"\nimport { frame } from \"../frameloop\"\nimport { time } from \"../frameloop/sync-time\"\n\n/**\n * @public\n */\nexport type Subscriber<T> = (v: T) => void\n\n/**\n * @public\n */\nexport type PassiveEffect<T> = (v: T, safeSetter: (v: T) => void) => void\n\nexport type StartAnimation = (\n complete: () => void\n) => AnimationPlaybackControlsWithThen | undefined\n\nexport interface MotionValueEventCallbacks<V> {\n animationStart: () => void\n animationComplete: () => void\n animationCancel: () => void\n change: (latestValue: V) => void\n destroy: () => void\n}\n\n/**\n * Maximum time between the value of two frames, beyond which we\n * assume the velocity has since been 0.\n */\nconst MAX_VELOCITY_DELTA = 30\n\nconst isFloat = (value: any): value is string => {\n return !isNaN(parseFloat(value))\n}\n\ninterface ResolvedValues {\n [key: string]: AnyResolvedKeyframe\n}\n\nexport interface Owner {\n current: HTMLElement | unknown\n getProps: () => {\n onUpdate?: (latest: ResolvedValues) => void\n transformTemplate?: (\n transform: TransformProperties,\n generatedTransform: string\n ) => string\n }\n}\n\nexport interface AccelerateConfig {\n factory: (animation: AnimationPlaybackControlsWithThen) => VoidFunction\n times: number[]\n keyframes: any[]\n ease?: EasingFunction | EasingFunction[]\n duration: number\n isTransformed?: boolean\n}\n\nexport interface MotionValueOptions {\n owner?: Owner\n}\n\nexport const collectMotionValues: { current: MotionValue[] | undefined } = {\n current: undefined,\n}\n\n/**\n * `MotionValue` is used to track the state and velocity of motion values.\n *\n * @public\n */\nexport class MotionValue<V = any> {\n /**\n * If a MotionValue has an owner, it was created internally within Motion\n * and therefore has no external listeners. It is therefore safe to animate via WAAPI.\n */\n owner?: Owner\n\n /**\n * The current state of the `MotionValue`.\n */\n private current: V | undefined\n\n /**\n * The previous state of the `MotionValue`.\n */\n private prev: V | undefined\n\n /**\n * The previous state of the `MotionValue` at the end of the previous frame.\n */\n private prevFrameValue: V | undefined\n\n /**\n * The last time the `MotionValue` was updated.\n */\n updatedAt: number\n\n /**\n * The time `prevFrameValue` was updated.\n */\n prevUpdatedAt: number | undefined\n\n /**\n * Add a passive effect to this `MotionValue`.\n *\n * A passive effect intercepts calls to `set`. For instance, `useSpring` adds\n * a passive effect that attaches a `spring` to the latest\n * set value. Hypothetically there could be a `useSmooth` that attaches an input smoothing effect.\n *\n * @internal\n */\n private passiveEffect?: PassiveEffect<V>\n private stopPassiveEffect?: VoidFunction\n\n /**\n * Whether the passive effect is active.\n */\n isEffectActive?: boolean\n\n /**\n * A reference to the currently-controlling animation.\n */\n animation?: AnimationPlaybackControlsWithThen\n\n /**\n * Tracks whether this value can output a velocity. Currently this is only true\n * if the value is numerical, but we might be able to widen the scope here and support\n * other value types.\n *\n * @internal\n */\n private canTrackVelocity: boolean | null = null\n\n /**\n * A list of MotionValues whose values are computed from this one.\n * This is a rough start to a proper signal-like dirtying system.\n */\n private dependents: Set<MotionValue> | undefined\n\n /**\n * Tracks whether this value should be removed\n */\n liveStyle?: boolean\n\n /**\n * Scroll timeline acceleration metadata. When set, VisualElement\n * can create a native WAAPI animation attached to a scroll timeline\n * instead of driving updates through JS.\n */\n accelerate?: AccelerateConfig\n\n /**\n * @param init - The initiating value\n * @param config - Optional configuration options\n *\n * - `transformer`: A function to transform incoming values with.\n */\n constructor(init: V, options: MotionValueOptions = {}) {\n this.setCurrent(init)\n this.owner = options.owner\n }\n\n setCurrent(current: V) {\n this.current = current\n this.updatedAt = time.now()\n\n if (this.canTrackVelocity === null && current !== undefined) {\n this.canTrackVelocity = isFloat(this.current)\n }\n }\n\n setPrevFrameValue(prevFrameValue: V | undefined = this.current) {\n this.prevFrameValue = prevFrameValue\n this.prevUpdatedAt = this.updatedAt\n }\n\n /**\n * Adds a function that will be notified when the `MotionValue` is updated.\n *\n * It returns a function that, when called, will cancel the subscription.\n *\n * When calling `onChange` inside a React component, it should be wrapped with the\n * `useEffect` hook. As it returns an unsubscribe function, this should be returned\n * from the `useEffect` function to ensure you don't add duplicate subscribers..\n *\n * ```jsx\n * export const MyComponent = () => {\n * const x = useMotionValue(0)\n * const y = useMotionValue(0)\n * const opacity = useMotionValue(1)\n *\n * useEffect(() => {\n * function updateOpacity() {\n * const maxXY = Math.max(x.get(), y.get())\n * const newOpacity = transform(maxXY, [0, 100], [1, 0])\n * opacity.set(newOpacity)\n * }\n *\n * const unsubscribeX = x.on(\"change\", updateOpacity)\n * const unsubscribeY = y.on(\"change\", updateOpacity)\n *\n * return () => {\n * unsubscribeX()\n * unsubscribeY()\n * }\n * }, [])\n *\n * return <motion.div style={{ x }} />\n * }\n * ```\n *\n * @param subscriber - A function that receives the latest value.\n * @returns A function that, when called, will cancel this subscription.\n *\n * @deprecated\n */\n onChange(subscription: Subscriber<V>): () => void {\n if (process.env.NODE_ENV !== \"production\") {\n warnOnce(\n false,\n `value.onChange(callback) is deprecated. Switch to value.on(\"change\", callback).`\n )\n }\n return this.on(\"change\", subscription)\n }\n\n /**\n * An object containing a SubscriptionManager for each active event.\n */\n private events: {\n [key: string]: SubscriptionManager<any>\n } = {}\n\n on<EventName extends keyof MotionValueEventCallbacks<V>>(\n eventName: EventName,\n callback: MotionValueEventCallbacks<V>[EventName]\n ) {\n if (!this.events[eventName]) {\n this.events[eventName] = new SubscriptionManager()\n }\n\n const unsubscribe = this.events[eventName].add(callback)\n\n if (eventName === \"change\") {\n return () => {\n unsubscribe()\n\n /**\n * If we have no more change listeners by the start\n * of the next frame, stop active animations.\n */\n frame.read(() => {\n if (!this.events.change.getSize()) {\n this.stop()\n }\n })\n }\n }\n\n return unsubscribe\n }\n\n clearListeners() {\n for (const eventManagers in this.events) {\n this.events[eventManagers].clear()\n }\n }\n\n /**\n * Attaches a passive effect to the `MotionValue`.\n */\n attach(passiveEffect: PassiveEffect<V>, stopPassiveEffect: VoidFunction) {\n this.passiveEffect = passiveEffect\n this.stopPassiveEffect = stopPassiveEffect\n }\n\n /**\n * Sets the state of the `MotionValue`.\n *\n * @remarks\n *\n * ```jsx\n * const x = useMotionValue(0)\n * x.set(10)\n * ```\n *\n * @param latest - Latest value to set.\n * @param render - Whether to notify render subscribers. Defaults to `true`\n *\n * @public\n */\n set(v: V) {\n if (!this.passiveEffect) {\n this.updateAndNotify(v)\n } else {\n this.passiveEffect(v, this.updateAndNotify)\n }\n }\n\n setWithVelocity(prev: V, current: V, delta: number) {\n this.set(current)\n this.prev = undefined\n this.prevFrameValue = prev\n this.prevUpdatedAt = this.updatedAt - delta\n }\n\n /**\n * Set the state of the `MotionValue`, stopping any active animations,\n * effects, and resets velocity to `0`.\n */\n jump(v: V, endAnimation = true) {\n this.updateAndNotify(v)\n this.prev = v\n this.prevUpdatedAt = this.prevFrameValue = undefined\n endAnimation && this.stop()\n if (this.stopPassiveEffect) this.stopPassiveEffect()\n }\n\n dirty() {\n this.events.change?.notify(this.current)\n }\n\n addDependent(dependent: MotionValue) {\n if (!this.dependents) {\n this.dependents = new Set()\n }\n this.dependents.add(dependent)\n }\n\n removeDependent(dependent: MotionValue) {\n if (this.dependents) {\n this.dependents.delete(dependent)\n }\n }\n\n updateAndNotify = (v: V) => {\n const currentTime = time.now()\n\n /**\n * If we're updating the value during another frame or eventloop\n * than the previous frame, then the we set the previous frame value\n * to current.\n */\n if (this.updatedAt !== currentTime) {\n this.setPrevFrameValue()\n }\n\n this.prev = this.current\n\n this.setCurrent(v)\n\n // Update update subscribers\n if (this.current !== this.prev) {\n this.events.change?.notify(this.current)\n\n if (this.dependents) {\n for (const dependent of this.dependents) {\n dependent.dirty()\n }\n }\n }\n }\n\n /**\n * Returns the latest state of `MotionValue`\n *\n * @returns - The latest state of `MotionValue`\n *\n * @public\n */\n get() {\n if (collectMotionValues.current) {\n collectMotionValues.current.push(this)\n }\n\n return this.current!\n }\n\n /**\n * @public\n */\n getPrevious() {\n return this.prev\n }\n\n /**\n * Returns the latest velocity of `MotionValue`\n *\n * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical.\n *\n * @public\n */\n getVelocity() {\n const currentTime = time.now()\n\n if (\n !this.canTrackVelocity ||\n this.prevFrameValue === undefined ||\n currentTime - this.updatedAt > MAX_VELOCITY_DELTA\n ) {\n return 0\n }\n\n const delta = Math.min(\n this.updatedAt - this.prevUpdatedAt!,\n MAX_VELOCITY_DELTA\n )\n\n // Casts because of parseFloat's poor typing\n return velocityPerSecond(\n parseFloat(this.current as any) -\n parseFloat(this.prevFrameValue as any),\n delta\n )\n }\n\n hasAnimated = false\n\n /**\n * Registers a new animation to control this `MotionValue`. Only one\n * animation can drive a `MotionValue` at one time.\n *\n * ```jsx\n * value.start()\n * ```\n *\n * @param animation - A function that starts the provided animation\n */\n start(startAnimation: StartAnimation) {\n this.stop()\n\n return new Promise<void>((resolve) => {\n this.hasAnimated = true\n this.animation = startAnimation(resolve)\n\n if (this.events.animationStart) {\n this.events.animationStart.notify()\n }\n }).then(() => {\n if (this.events.animationComplete) {\n this.events.animationComplete.notify()\n }\n this.clearAnimation()\n })\n }\n\n /**\n * Stop the currently active animation.\n *\n * @public\n */\n stop() {\n if (this.animation) {\n this.animation.stop()\n if (this.events.animationCancel) {\n this.events.animationCancel.notify()\n }\n }\n this.clearAnimation()\n }\n\n /**\n * Returns `true` if this value is currently animating.\n *\n * @public\n */\n isAnimating() {\n return !!this.animation\n }\n\n private clearAnimation() {\n delete this.animation\n }\n\n /**\n * Destroy and clean up subscribers to this `MotionValue`.\n *\n * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically\n * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually\n * created a `MotionValue` via the `motionValue` function.\n *\n * @public\n */\n destroy() {\n this.dependents?.clear()\n this.events.destroy?.notify()\n this.clearListeners()\n this.stop()\n\n if (this.stopPassiveEffect) {\n this.stopPassiveEffect()\n }\n }\n}\n\nexport function motionValue<V>(init: V, options?: MotionValueOptions) {\n return new MotionValue<V>(init, options)\n}\n","/**\n * If `transition` has `inherit: true`, shallow-merge it with\n * `parentTransition` (child keys win) and strip the `inherit` key.\n * Otherwise return `transition` unchanged.\n */\nexport function resolveTransition(\n transition: any,\n parentTransition?: any\n) {\n if (transition?.inherit && parentTransition) {\n const { inherit: _, ...rest } = transition\n return { ...parentTransition, ...rest }\n }\n\n return transition\n}\n","import { resolveTransition } from \"./resolve-transition\"\n\nexport function getValueTransition(transition: any, key: string) {\n const valueTransition =\n transition?.[key as keyof typeof transition] ??\n transition?.[\"default\"] ??\n transition\n\n if (valueTransition !== transition) {\n return resolveTransition(valueTransition, transition)\n }\n\n return valueTransition\n}\n","import { transformProps } from \"../../render/utils/keys-transform\"\nimport type { ValueAnimationOptions } from \"../types\"\n\nconst underDampedSpring: Partial<ValueAnimationOptions> = {\n type: \"spring\",\n stiffness: 500,\n damping: 25,\n restSpeed: 10,\n}\n\nconst criticallyDampedSpring = (\n target: unknown\n): Partial<ValueAnimationOptions> => ({\n type: \"spring\",\n stiffness: 550,\n damping: target === 0 ? 2 * Math.sqrt(550) : 30,\n restSpeed: 10,\n})\n\nconst keyframesTransition: Partial<ValueAnimationOptions> = {\n type: \"keyframes\",\n duration: 0.8,\n}\n\n/**\n * Default easing curve is a slightly shallower version of\n * the default browser easing curve.\n */\nconst ease: Partial<ValueAnimationOptions> = {\n type: \"keyframes\",\n ease: [0.25, 0.1, 0.35, 1],\n duration: 0.3,\n}\n\nexport const getDefaultTransition = (\n valueKey: string,\n { keyframes }: ValueAnimationOptions\n): Partial<ValueAnimationOptions> => {\n if (keyframes.length > 2) {\n return keyframesTransition\n } else if (transformProps.has(valueKey)) {\n return valueKey.startsWith(\"scale\")\n ? criticallyDampedSpring(keyframes[1])\n : underDampedSpring\n }\n\n return ease\n}\n","import type { AnyResolvedKeyframe } from \"../types\"\nimport type { Transition } from \"../types\"\n\nconst orchestrationKeys = new Set([\n \"when\",\n \"delay\",\n \"delayChildren\",\n \"staggerChildren\",\n \"staggerDirection\",\n \"repeat\",\n \"repeatType\",\n \"repeatDelay\",\n \"from\",\n \"elapsed\",\n])\n\n/**\n * Decide whether a transition is defined on a given Transition.\n * This filters out orchestration options and returns true\n * if any options are left.\n */\nexport function isTransitionDefined(\n transition: Transition & { elapsed?: number; from?: AnyResolvedKeyframe }\n) {\n for (const key in transition) {\n if (!orchestrationKeys.has(key)) return true\n }\n return false\n}\n","import { MotionGlobalConfig, secondsToMilliseconds } from \"motion-utils\"\nimport { AsyncMotionValueAnimation } from \"../AsyncMotionValueAnimation\"\nimport { JSAnimation } from \"../JSAnimation\"\nimport type {\n AnyResolvedKeyframe,\n ValueAnimationOptions,\n ValueTransition,\n} from \"../types\"\nimport type { UnresolvedKeyframes } from \"../keyframes/KeyframesResolver\"\nimport { getValueTransition } from \"../utils/get-value-transition\"\nimport { makeAnimationInstant } from \"../utils/make-animation-instant\"\nimport { getDefaultTransition } from \"../utils/default-transitions\"\nimport { getFinalKeyframe } from \"../keyframes/get-final\"\nimport { isTransitionDefined } from \"../utils/is-transition-defined\"\nimport { frame } from \"../../frameloop\"\nimport type { MotionValue, StartAnimation } from \"../../value\"\nimport type { VisualElement } from \"../../render/VisualElement\"\n\nexport const animateMotionValue =\n <V extends AnyResolvedKeyframe>(\n name: string,\n value: MotionValue<V>,\n target: V | UnresolvedKeyframes<V>,\n transition: ValueTransition & { elapsed?: number } = {},\n element?: VisualElement<any>,\n isHandoff?: boolean\n ): StartAnimation =>\n (onComplete) => {\n const valueTransition = getValueTransition(transition, name) || {}\n\n /**\n * Most transition values are currently completely overwritten by value-specific\n * transitions. In the future it'd be nicer to blend these transitions. But for now\n * delay actually does inherit from the root transition if not value-specific.\n */\n const delay = valueTransition.delay || transition.delay || 0\n\n /**\n * Elapsed isn't a public transition option but can be passed through from\n * optimized appear effects in milliseconds.\n */\n let { elapsed = 0 } = transition\n elapsed = elapsed - secondsToMilliseconds(delay)\n\n const options: ValueAnimationOptions = {\n keyframes: Array.isArray(target) ? target : [null, target],\n ease: \"easeOut\",\n velocity: value.getVelocity(),\n ...valueTransition,\n delay: -elapsed,\n onUpdate: (v) => {\n value.set(v)\n valueTransition.onUpdate && valueTransition.onUpdate(v)\n },\n onComplete: () => {\n onComplete()\n valueTransition.onComplete && valueTransition.onComplete()\n },\n name,\n motionValue: value,\n element: isHandoff ? undefined : element,\n }\n\n /**\n * If there's no transition defined for this value, we can generate\n * unique transition settings for this value.\n */\n if (!isTransitionDefined(valueTransition)) {\n Object.assign(options, getDefaultTransition(name, options))\n }\n\n /**\n * Both WAAPI and our internal animation functions use durations\n * as defined by milliseconds, while our external API defines them\n * as seconds.\n */\n options.duration &&= secondsToMilliseconds(options.duration)\n options.repeatDelay &&= secondsToMilliseconds(options.repeatDelay)\n\n /**\n * Support deprecated way to set initial value. Prefer keyframe syntax.\n */\n if (options.from !== undefined) {\n options.keyframes[0] = options.from as any\n }\n\n let shouldSkip = false\n\n if (\n (options as any).type === false ||\n (options.duration === 0 && !options.repeatDelay)\n ) {\n makeAnimationInstant(options)\n\n if (options.delay === 0) {\n shouldSkip = true\n }\n }\n\n if (\n MotionGlobalConfig.instantAnimations ||\n MotionGlobalConfig.skipAnimations ||\n element?.shouldSkipAnimations ||\n valueTransition.skipAnimations\n ) {\n shouldSkip = true\n makeAnimationInstant(options)\n options.delay = 0\n }\n\n /**\n * If the transition type or easing has been explicitly set by the user\n * then we don't want to allow flattening the animation.\n */\n options.allowFlatten = !valueTransition.type && !valueTransition.ease\n\n /**\n * If we can or must skip creating the animation, and apply only\n * the final keyframe, do so. We also check once keyframes are resolved but\n * this early check prevents the need to create an animation at all.\n */\n if (shouldSkip && !isHandoff && value.get() !== undefined) {\n const finalKeyframe = getFinalKeyframe<V>(\n options.keyframes as V[],\n valueTransition\n )\n\n if (finalKeyframe !== undefined) {\n frame.update(() => {\n options.onUpdate!(finalKeyframe)\n options.onComplete!()\n })\n\n return\n }\n }\n\n return valueTransition.isSync\n ? new JSAnimation(options)\n : new AsyncMotionValueAnimation(options)\n }\n","import { invariant, isNumericalString } from \"motion-utils\"\nimport { AnyResolvedKeyframe } from \"../types\"\nimport { CSSVariableToken, isCSSVariableToken } from \"./is-css-variable\"\n\n/**\n * Parse Framer's special CSS variable format into a CSS token and a fallback.\n *\n * ```\n * `var(--foo, #fff)` => [`--foo`, '#fff']\n * ```\n *\n * @param current\n */\n\nconst splitCSSVariableRegex =\n // eslint-disable-next-line redos-detector/no-unsafe-regex -- false positive, as it can match a lot of words\n /^var\\(--(?:([\\w-]+)|([\\w-]+), ?([a-zA-Z\\d ()%#.,-]+))\\)/u\nexport function parseCSSVariable(current: string) {\n const match = splitCSSVariableRegex.exec(current)\n if (!match) return [,]\n\n const [, token1, token2, fallback] = match\n return [`--${token1 ?? token2}`, fallback]\n}\n\nconst maxDepth = 4\nexport function getVariableValue(\n current: CSSVariableToken,\n element: Element,\n depth = 1\n): AnyResolvedKeyframe | undefined {\n invariant(\n depth <= maxDepth,\n `Max CSS variable fallback depth detected in property \"${current}\". This may indicate a circular fallback dependency.`,\n \"max-css-var-depth\"\n )\n\n const [token, fallback] = parseCSSVariable(current)\n\n // No CSS variable detected\n if (!token) return\n\n // Attempt to read this CSS variable off the element\n const resolved = window.getComputedStyle(element).getPropertyValue(token)\n\n if (resolved) {\n const trimmed = resolved.trim()\n return isNumericalString(trimmed) ? parseFloat(trimmed) : trimmed\n }\n\n return isCSSVariableToken(fallback)\n ? getVariableValue(fallback, element, depth + 1)\n : fallback\n}\n","import type {\n AnimationDefinition,\n MotionNodeOptions,\n TargetAndTransition,\n TargetResolver,\n} from \"../../node/types\"\nimport type { ResolvedValues } from \"../types\"\n\nfunction getValueState(visualElement?: any): [ResolvedValues, ResolvedValues] {\n const state: [ResolvedValues, ResolvedValues] = [{}, {}]\n\n visualElement?.values.forEach((value: any, key: string) => {\n state[0][key] = value.get()\n state[1][key] = value.getVelocity()\n })\n\n return state\n}\n\nexport function resolveVariantFromProps(\n props: MotionNodeOptions,\n definition: TargetAndTransition | TargetResolver,\n custom?: any,\n visualElement?: any\n): TargetAndTransition\nexport function resolveVariantFromProps(\n props: MotionNodeOptions,\n definition?: AnimationDefinition,\n custom?: any,\n visualElement?: any\n): undefined | TargetAndTransition\nexport function resolveVariantFromProps(\n props: MotionNodeOptions,\n definition?: AnimationDefinition,\n custom?: any,\n visualElement?: any\n) {\n /**\n * If the variant definition is a function, resolve.\n */\n if (typeof definition === \"function\") {\n const [current, velocity] = getValueState(visualElement)\n definition = definition(\n custom !== undefined ? custom : props.custom,\n current,\n velocity\n )\n }\n\n /**\n * If the variant definition is a variant label, or\n * the function returned a variant label, resolve.\n */\n if (typeof definition === \"string\") {\n definition = props.variants && props.variants[definition]\n }\n\n /**\n * At this point we've resolved both functions and variant labels,\n * but the resolved variant label might itself have been a function.\n * If so, resolve. This can only have returned a valid target object.\n */\n if (typeof definition === \"function\") {\n const [current, velocity] = getValueState(visualElement)\n definition = definition(\n custom !== undefined ? custom : props.custom,\n current,\n velocity\n )\n }\n\n return definition\n}\n","import type {\n AnimationDefinition,\n TargetAndTransition,\n TargetResolver,\n} from \"../../node/types\"\nimport { resolveVariantFromProps } from \"./resolve-variants\"\n\n/**\n * Resolves a variant if it's a variant resolver.\n * Uses `any` type for visualElement to avoid circular dependencies.\n */\nexport function resolveVariant(\n visualElement: any,\n definition?: TargetAndTransition | TargetResolver,\n custom?: any\n): TargetAndTransition\nexport function resolveVariant(\n visualElement: any,\n definition?: AnimationDefinition,\n custom?: any\n): TargetAndTransition | undefined\nexport function resolveVariant(\n visualElement: any,\n definition?: AnimationDefinition,\n custom?: any\n) {\n const props = visualElement.getProps()\n return resolveVariantFromProps(\n props,\n definition,\n custom !== undefined ? custom : props.custom,\n visualElement\n )\n}\n","import { transformPropOrder } from \"./keys-transform\"\n\nexport const positionalKeys = new Set([\n \"width\",\n \"height\",\n \"top\",\n \"left\",\n \"right\",\n \"bottom\",\n ...transformPropOrder,\n])\n","import type { UnresolvedValueKeyframe, ValueKeyframesDefinition } from \"../../animation/types\"\n\nexport const isKeyframesTarget = (\n v: ValueKeyframesDefinition\n): v is UnresolvedValueKeyframe[] => {\n return Array.isArray(v)\n}\n","import { motionValue } from \"../../value\"\nimport { resolveVariant } from \"./resolve-dynamic-variants\"\nimport { isKeyframesTarget } from \"./is-keyframes-target\"\nimport type { AnimationDefinition } from \"../../node/types\"\nimport type {\n AnyResolvedKeyframe,\n UnresolvedValueKeyframe,\n ValueKeyframesDefinition,\n} from \"../../animation/types\"\nimport type { VisualElement } from \"../VisualElement\"\n\n/**\n * Set VisualElement's MotionValue, creating a new MotionValue for it if\n * it doesn't exist.\n */\nfunction setMotionValue(\n visualElement: VisualElement,\n key: string,\n value: AnyResolvedKeyframe\n) {\n if (visualElement.hasValue(key)) {\n visualElement.getValue(key)!.set(value)\n } else {\n visualElement.addValue(key, motionValue(value))\n }\n}\n\nfunction resolveFinalValueInKeyframes(\n v: ValueKeyframesDefinition\n): UnresolvedValueKeyframe {\n // TODO maybe throw if v.length - 1 is placeholder token?\n return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v\n}\n\nexport function setTarget(\n visualElement: VisualElement,\n definition: AnimationDefinition\n) {\n const resolved = resolveVariant(visualElement, definition)\n let { transitionEnd = {}, transition = {}, ...target } = resolved || {}\n\n target = { ...target, ...transitionEnd }\n\n for (const key in target) {\n const value = resolveFinalValueInKeyframes(\n target[key as keyof typeof target] as any\n )\n setMotionValue(visualElement, key, value as AnyResolvedKeyframe)\n }\n}\n","import type { MotionValue } from \"..\"\n\nexport const isMotionValue = (value: any): value is MotionValue =>\n Boolean(value && value.getVelocity)\n","import { isMotionValue } from \"../utils/is-motion-value\"\nimport type { WillChange } from \"./types\"\n\nexport function isWillChangeMotionValue(value: any): value is WillChange {\n return Boolean(isMotionValue(value) && (value as WillChange).add)\n}\n","import { MotionGlobalConfig } from \"motion-utils\"\nimport type { VisualElement } from \"../../render/VisualElement\"\nimport { isWillChangeMotionValue } from \"./is\"\n\nexport function addValueToWillChange(\n visualElement: VisualElement,\n key: string\n) {\n const willChange = visualElement.getValue(\"willChange\")\n\n /**\n * It could be that a user has set willChange to a regular MotionValue,\n * in which case we can't add the value to it.\n */\n if (isWillChangeMotionValue(willChange)) {\n return willChange.add(key)\n } else if (!willChange && MotionGlobalConfig.WillChange) {\n const newWillChange = new MotionGlobalConfig.WillChange(\"auto\")\n\n visualElement.addValue(\"willChange\", newWillChange)\n newWillChange.add(key)\n }\n}\n","export function camelToDash(str: string): string {\n return str.replace(/([A-Z])/g, (match) => `-${match.toLowerCase()}`)\n}\n","import { camelToDash } from \"../../render/dom/utils/camel-to-dash\"\n\nexport const optimizedAppearDataId = \"framerAppearId\"\n\nexport const optimizedAppearDataAttribute =\n \"data-\" + camelToDash(optimizedAppearDataId) as \"data-framer-appear-id\"\n","import { optimizedAppearDataAttribute } from \"./data-id\"\nimport type { WithAppearProps } from \"./types\"\n\nexport function getOptimisedAppearId(\n visualElement: WithAppearProps\n): string | undefined {\n return visualElement.props[optimizedAppearDataAttribute]\n}\n","import { frame } from \"../../frameloop\"\nimport { getValueTransition } from \"../utils/get-value-transition\"\nimport { resolveTransition } from \"../utils/resolve-transition\"\nimport { positionalKeys } from \"../../render/utils/keys-position\"\nimport { setTarget } from \"../../render/utils/setters\"\nimport { addValueToWillChange } from \"../../value/will-change/add-will-change\"\nimport { getOptimisedAppearId } from \"../optimized-appear/get-appear-id\"\nimport { animateMotionValue } from \"./motion-value\"\nimport type { MotionPath } from \"../types\"\nimport type { VisualElementAnimationOptions } from \"./types\"\nimport type { AnimationPlaybackControlsWithThen } from \"../types\"\nimport type { TargetAndTransition } from \"../../node/types\"\nimport type { AnimationTypeState } from \"../../render/utils/animation-state\"\nimport type { VisualElement } from \"../../render/VisualElement\"\n\n/**\n * Decide whether we should block this animation. Previously, we achieved this\n * just by checking whether the key was listed in protectedKeys, but this\n * posed problems if an animation was triggered by afterChildren and protectedKeys\n * had been set to true in the meantime.\n */\nfunction shouldBlockAnimation(\n { protectedKeys, needsAnimating }: AnimationTypeState,\n key: string\n) {\n const shouldBlock =\n protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true\n\n needsAnimating[key] = false\n return shouldBlock\n}\n\nexport function animateTarget(\n visualElement: VisualElement,\n targetAndTransition: TargetAndTransition,\n { delay = 0, transitionOverride, type }: VisualElementAnimationOptions = {}\n): AnimationPlaybackControlsWithThen[] {\n let {\n transition,\n transitionEnd,\n ...target\n } = targetAndTransition\n\n const defaultTransition = visualElement.getDefaultTransition()\n transition = transition\n ? resolveTransition(transition, defaultTransition)\n : defaultTransition\n\n const reduceMotion = (transition as { reduceMotion?: boolean })?.reduceMotion\n const skipAnimations = transition?.skipAnimations\n\n if (transitionOverride) transition = transitionOverride\n\n const animations: AnimationPlaybackControlsWithThen[] = []\n\n const animationTypeState =\n type &&\n visualElement.animationState &&\n visualElement.animationState.getState()[type]\n\n const path = (transition as { path?: MotionPath } | undefined)?.path\n if (path) {\n // path mutates `target` to claim x/y; loop below skips them.\n path.animateVisualElement(\n visualElement,\n target,\n transition,\n delay,\n animations\n )\n }\n\n for (const key in target) {\n const value = visualElement.getValue(\n key,\n visualElement.latestValues[key] ?? null\n )\n const valueTarget = target[key as keyof typeof target]\n\n if (\n valueTarget === undefined ||\n (animationTypeState &&\n shouldBlockAnimation(animationTypeState, key))\n ) {\n continue\n }\n\n const valueTransition = {\n delay,\n ...getValueTransition(transition || {}, key),\n }\n\n if (skipAnimations) valueTransition.skipAnimations = true\n\n /**\n * If the value is already at the defined target, skip the animation.\n * We still re-assert the value via frame.update to take precedence\n * over any stale transitionEnd callbacks from previous animations.\n */\n const currentValue = value.get()\n if (\n currentValue !== undefined &&\n !value.isAnimating() &&\n !Array.isArray(valueTarget) &&\n valueTarget === currentValue &&\n !valueTransition.velocity\n ) {\n frame.update(() => value.set(valueTarget as any))\n continue\n }\n\n /**\n * If this is the first time a value is being animated, check\n * to see if we're handling off from an existing animation.\n */\n let isHandoff = false\n if (window.MotionHandoffAnimation) {\n const appearId = getOptimisedAppearId(visualElement)\n\n if (appearId) {\n const startTime = window.MotionHandoffAnimation(\n appearId,\n key,\n frame\n )\n\n if (startTime !== null) {\n valueTransition.startTime = startTime\n isHandoff = true\n }\n }\n }\n\n addValueToWillChange(visualElement, key)\n\n const shouldReduceMotion =\n reduceMotion ?? visualElement.shouldReduceMotion\n\n value.start(\n animateMotionValue(\n key,\n value,\n valueTarget,\n shouldReduceMotion && positionalKeys.has(key)\n ? { type: false }\n : valueTransition,\n visualElement,\n isHandoff\n )\n )\n\n const animation = value.animation\n\n if (animation) {\n animations.push(animation)\n }\n }\n\n if (transitionEnd) {\n const applyTransitionEnd = () =>\n frame.update(() => {\n transitionEnd && setTarget(visualElement, transitionEnd)\n })\n\n if (animations.length) {\n Promise.all(animations).then(applyTransitionEnd)\n } else {\n applyTransitionEnd()\n }\n }\n\n return animations\n}\n","import { resolveVariant } from \"../../render/utils/resolve-dynamic-variants\"\nimport { calcChildStagger } from \"../utils/calc-child-stagger\"\nimport type { VisualElementAnimationOptions } from \"./types\"\nimport { animateTarget } from \"./visual-element-target\"\nimport type { DynamicOption } from \"../types\"\nimport type { VisualElement } from \"../../render/VisualElement\"\n\nexport function animateVariant(\n visualElement: VisualElement,\n variant: string,\n options: VisualElementAnimationOptions = {}\n): Promise<any> {\n const resolved = resolveVariant(\n visualElement,\n variant,\n options.type === \"exit\"\n ? visualElement.presenceContext?.custom\n : undefined\n )\n\n let { transition = visualElement.getDefaultTransition() || {} } =\n resolved || {}\n\n if (options.transitionOverride) {\n transition = options.transitionOverride\n }\n\n /**\n * If we have a variant, create a callback that runs it as an animation.\n * Otherwise, we resolve a Promise immediately for a composable no-op.\n */\n const getAnimation: () => Promise<any> = resolved\n ? () => Promise.all(animateTarget(visualElement, resolved, options))\n : () => Promise.resolve()\n\n /**\n * If we have children, create a callback that runs all their animations.\n * Otherwise, we resolve a Promise immediately for a composable no-op.\n */\n const getChildAnimations =\n visualElement.variantChildren && visualElement.variantChildren.size\n ? (forwardDelay = 0) => {\n const {\n delayChildren = 0,\n staggerChildren,\n staggerDirection,\n } = transition\n\n return animateChildren(\n visualElement,\n variant,\n forwardDelay,\n delayChildren,\n staggerChildren,\n staggerDirection,\n options\n )\n }\n : () => Promise.resolve()\n\n /**\n * If the transition explicitly defines a \"when\" option, we need to resolve either\n * this animation or all children animations before playing the other.\n */\n const { when } = transition\n if (when) {\n const [first, last] =\n when === \"beforeChildren\"\n ? [getAnimation, getChildAnimations]\n : [getChildAnimations, getAnimation]\n\n return first().then(() => last())\n } else {\n return Promise.all([getAnimation(), getChildAnimations(options.delay)])\n }\n}\n\nfunction animateChildren(\n visualElement: VisualElement,\n variant: string,\n delay: number = 0,\n delayChildren: number | DynamicOption<number> = 0,\n staggerChildren = 0,\n staggerDirection = 1,\n options: VisualElementAnimationOptions\n) {\n const animations: Promise<any>[] = []\n\n for (const child of visualElement.variantChildren!) {\n child.notify(\"AnimationStart\", variant)\n animations.push(\n animateVariant(child, variant, {\n ...options,\n delay:\n delay +\n (typeof delayChildren === \"function\" ? 0 : delayChildren) +\n calcChildStagger(\n visualElement.variantChildren!,\n child,\n delayChildren,\n staggerChildren,\n staggerDirection\n ),\n }).then(() => child.notify(\"AnimationComplete\", variant))\n )\n }\n\n return Promise.all(animations)\n}\n","import { resolveVariant } from \"../../render/utils/resolve-dynamic-variants\"\nimport type { AnimationDefinition } from \"../../node/types\"\nimport type { VisualElement } from \"../../render/VisualElement\"\nimport type { VisualElementAnimationOptions } from \"./types\"\nimport { animateTarget } from \"./visual-element-target\"\nimport { animateVariant } from \"./visual-element-variant\"\n\nexport function animateVisualElement(\n visualElement: VisualElement,\n definition: AnimationDefinition,\n options: VisualElementAnimationOptions = {}\n) {\n visualElement.notify(\"AnimationStart\", definition)\n let animation: Promise<any>\n\n if (Array.isArray(definition)) {\n const animations = definition.map((variant) =>\n animateVariant(visualElement, variant, options)\n )\n animation = Promise.all(animations)\n } else if (typeof definition === \"string\") {\n animation = animateVariant(visualElement, definition, options)\n } else {\n const resolvedDefinition =\n typeof definition === \"function\"\n ? resolveVariant(visualElement, definition, options.custom)\n : definition\n\n animation = Promise.all(\n animateTarget(visualElement, resolvedDefinition, options)\n )\n }\n\n return animation.then(() => {\n visualElement.notify(\"AnimationComplete\", definition)\n })\n}\n","import { ValueType } from \"./types\"\n\n/**\n * ValueType for \"auto\"\n */\nexport const auto: ValueType = {\n test: (v: any) => v === \"auto\",\n parse: (v) => v,\n}\n","import { ValueType } from \"./types\"\n\n/**\n * Tests a provided value against a ValueType\n */\nexport const testValueType = (v: any) => (type: ValueType) => type.test(v)\n","import { auto } from \"./auto\"\nimport { number } from \"./numbers\"\nimport { degrees, percent, px, vh, vw } from \"./numbers/units\"\nimport { testValueType } from \"./test\"\n\n/**\n * A list of value types commonly used for dimensions\n */\nexport const dimensionValueTypes = [number, px, percent, degrees, vw, vh, auto]\n\n/**\n * Tests a dimensional value against the list of dimension ValueTypes\n */\nexport const findDimensionValueType = (v: any) =>\n dimensionValueTypes.find(testValueType(v))\n","import { isZeroValueString } from \"motion-utils\"\nimport { AnyResolvedKeyframe } from \"../../types\"\n\nexport function isNone(value: AnyResolvedKeyframe | null) {\n if (typeof value === \"number\") {\n return value === 0\n } else if (value !== null) {\n return value === \"none\" || value === \"0\" || isZeroValueString(value)\n } else {\n return true\n }\n}\n","import { complex } from \".\"\nimport { floatRegex } from \"../utils/float-regex\"\n\n/**\n * Properties that should default to 1 or 100%\n */\nconst maxDefaults = new Set([\"brightness\", \"contrast\", \"saturate\", \"opacity\"])\n\nfunction applyDefaultFilter(v: string) {\n const [name, value] = v.slice(0, -1).split(\"(\")\n\n if (name === \"drop-shadow\") return v\n\n const [number] = value.match(floatRegex) || []\n if (!number) return v\n\n const unit = value.replace(number, \"\")\n let defaultValue = maxDefaults.has(name) ? 1 : 0\n if (number !== value) defaultValue *= 100\n\n return name + \"(\" + defaultValue + unit + \")\"\n}\n\nconst functionRegex = /\\b([a-z-]*)\\(.*?\\)/gu\n\nexport const filter = {\n ...complex,\n getAnimatableNone: (v: string) => {\n const functions = v.match(functionRegex)\n return functions ? functions.map(applyDefaultFilter).join(\" \") : v\n },\n}\n","import { complex } from \".\"\nimport { AnyResolvedKeyframe } from \"../../../animation/types\"\n\nexport const mask = {\n ...complex,\n getAnimatableNone: (v: AnyResolvedKeyframe) => {\n const parsed = complex.parse(v)\n const transformer = complex.createTransformer(v)\n return transformer(\n parsed.map((v) =>\n typeof v === \"number\" ? 0 : typeof v === \"object\" ? { ...v, alpha: 1 } : v\n )\n )\n },\n}\n","import { number } from \"./numbers\"\n\nexport const int = {\n ...number,\n transform: Math.round,\n}\n","import { alpha, scale } from \"../numbers\"\nimport { degrees, progressPercentage, px } from \"../numbers/units\"\nimport { ValueTypeMap } from \"./types\"\n\nexport const transformValueTypes: ValueTypeMap = {\n rotate: degrees,\n /**\n * Internal channel for `transition.path` orientToPath. Composed onto\n * `rotate` at the transform-build sites so the user's `rotate` is\n * never read or overwritten. Not part of `transformPropOrder`.\n */\n pathRotation: degrees,\n rotateX: degrees,\n rotateY: degrees,\n rotateZ: degrees,\n scale,\n scaleX: scale,\n scaleY: scale,\n scaleZ: scale,\n skew: degrees,\n skewX: degrees,\n skewY: degrees,\n distance: px,\n translateX: px,\n translateY: px,\n translateZ: px,\n x: px,\n y: px,\n z: px,\n perspective: px,\n transformPerspective: px,\n opacity: alpha,\n originX: progressPercentage,\n originY: progressPercentage,\n originZ: px,\n}\n","import { int } from \"../int\"\nimport { alpha } from \"../numbers\"\nimport { px } from \"../numbers/units\"\nimport { transformValueTypes } from \"./transform\"\nimport { ValueTypeMap } from \"./types\"\n\nexport const numberValueTypes: ValueTypeMap = {\n // Border props\n borderWidth: px,\n borderTopWidth: px,\n borderRightWidth: px,\n borderBottomWidth: px,\n borderLeftWidth: px,\n borderRadius: px,\n borderTopLeftRadius: px,\n borderTopRightRadius: px,\n borderBottomRightRadius: px,\n borderBottomLeftRadius: px,\n\n // Positioning props\n width: px,\n maxWidth: px,\n height: px,\n maxHeight: px,\n top: px,\n right: px,\n bottom: px,\n left: px,\n inset: px,\n insetBlock: px,\n insetBlockStart: px,\n insetBlockEnd: px,\n insetInline: px,\n insetInlineStart: px,\n insetInlineEnd: px,\n\n // Spacing props\n padding: px,\n paddingTop: px,\n paddingRight: px,\n paddingBottom: px,\n paddingLeft: px,\n paddingBlock: px,\n paddingBlockStart: px,\n paddingBlockEnd: px,\n paddingInline: px,\n paddingInlineStart: px,\n paddingInlineEnd: px,\n margin: px,\n marginTop: px,\n marginRight: px,\n marginBottom: px,\n marginLeft: px,\n marginBlock: px,\n marginBlockStart: px,\n marginBlockEnd: px,\n marginInline: px,\n marginInlineStart: px,\n marginInlineEnd: px,\n\n // Typography\n fontSize: px,\n\n // Misc\n backgroundPositionX: px,\n backgroundPositionY: px,\n\n ...transformValueTypes,\n zIndex: int,\n\n // SVG\n fillOpacity: alpha,\n strokeOpacity: alpha,\n numOctaves: int,\n}\n","import { color } from \"../color\"\nimport { filter } from \"../complex/filter\"\nimport { mask } from \"../complex/mask\"\nimport { numberValueTypes } from \"./number\"\nimport { ValueTypeMap } from \"./types\"\n\n/**\n * A map of default value types for common values\n */\nexport const defaultValueTypes: ValueTypeMap = {\n ...numberValueTypes,\n\n // Color props\n color,\n backgroundColor: color,\n outlineColor: color,\n fill: color,\n stroke: color,\n\n // Border props\n borderColor: color,\n borderTopColor: color,\n borderRightColor: color,\n borderBottomColor: color,\n borderLeftColor: color,\n filter,\n WebkitFilter: filter,\n mask,\n WebkitMask: mask,\n}\n\n/**\n * Gets the default ValueType for the provided value key\n */\nexport const getDefaultValueType = (key: string) => defaultValueTypes[key]\n","import { complex } from \"../complex\"\nimport { filter } from \"../complex/filter\"\nimport { mask } from \"../complex/mask\"\nimport { getDefaultValueType } from \"../maps/defaults\"\n\nconst customTypes = /*@__PURE__*/ new Set([filter, mask])\n\nexport function getAnimatableNone(key: string, value: string) {\n let defaultValueType = getDefaultValueType(key)\n if (!customTypes.has(defaultValueType as any)) defaultValueType = complex\n // If value is not recognised as animatable, ie \"none\", create an animatable version origin based on the target\n return defaultValueType.getAnimatableNone\n ? defaultValueType.getAnimatableNone(value)\n : undefined\n}\n","import { analyseComplexValue } from \"../../../value/types/complex\"\nimport { getAnimatableNone } from \"../../../value/types/utils/animatable-none\"\nimport { AnyResolvedKeyframe } from \"../../types\"\nimport { UnresolvedKeyframes } from \"../KeyframesResolver\"\n\n/**\n * If we encounter keyframes like \"none\" or \"0\" and we also have keyframes like\n * \"#fff\" or \"200px 200px\" we want to find a keyframe to serve as a template for\n * the \"none\" keyframes. In this case \"#fff\" or \"200px 200px\" - then these get turned into\n * zero equivalents, i.e. \"#fff0\" or \"0px 0px\".\n */\nconst invalidTemplates = new Set([\"auto\", \"none\", \"0\"])\n\nexport function makeNoneKeyframesAnimatable(\n unresolvedKeyframes: UnresolvedKeyframes<AnyResolvedKeyframe>,\n noneKeyframeIndexes: number[],\n name?: string\n) {\n let i = 0\n let animatableTemplate: string | undefined = undefined\n while (i < unresolvedKeyframes.length && !animatableTemplate) {\n const keyframe = unresolvedKeyframes[i]\n if (\n typeof keyframe === \"string\" &&\n !invalidTemplates.has(keyframe) &&\n analyseComplexValue(keyframe).values.length\n ) {\n animatableTemplate = unresolvedKeyframes[i] as string\n }\n i++\n }\n\n if (animatableTemplate && name) {\n for (const noneIndex of noneKeyframeIndexes) {\n unresolvedKeyframes[noneIndex] = getAnimatableNone(\n name,\n animatableTemplate\n )\n }\n }\n}\n","import { positionalKeys } from \"../../render/utils/keys-position\"\nimport { MotionValue } from \"../../value\"\nimport { findDimensionValueType } from \"../../value/types/dimensions\"\nimport { AnyResolvedKeyframe } from \"../types\"\nimport { getVariableValue } from \"../utils/css-variables-conversion\"\nimport {\n containsCSSVariable,\n isCSSVariableToken,\n} from \"../utils/is-css-variable\"\nimport {\n KeyframeResolver,\n OnKeyframesResolved,\n UnresolvedKeyframes,\n} from \"./KeyframesResolver\"\nimport { WithRender } from \"./types\"\nimport { isNone } from \"./utils/is-none\"\nimport { makeNoneKeyframesAnimatable } from \"./utils/make-none-animatable\"\nimport { isNumOrPxType, positionalValues } from \"./utils/unit-conversion\"\n\nexport class DOMKeyframesResolver<\n T extends AnyResolvedKeyframe\n> extends KeyframeResolver<T> {\n name: string\n element?: WithRender\n\n private removedTransforms?: [string, AnyResolvedKeyframe][]\n private measuredOrigin?: AnyResolvedKeyframe\n\n constructor(\n unresolvedKeyframes: UnresolvedKeyframes<AnyResolvedKeyframe>,\n onComplete: OnKeyframesResolved<T>,\n name?: string,\n motionValue?: MotionValue<T>,\n element?: WithRender\n ) {\n super(unresolvedKeyframes, onComplete, name, motionValue, element, true)\n }\n\n readKeyframes() {\n const { unresolvedKeyframes, element, name } = this\n\n if (!element || !element.current) return\n\n super.readKeyframes()\n\n /**\n * If any keyframe is a CSS variable, we need to find its value by sampling the element\n */\n for (let i = 0; i < unresolvedKeyframes.length; i++) {\n let keyframe = unresolvedKeyframes[i]\n\n if (typeof keyframe === \"string\") {\n keyframe = keyframe.trim()\n\n if (isCSSVariableToken(keyframe)) {\n const resolved = getVariableValue(keyframe, element.current)\n\n if (resolved !== undefined) {\n unresolvedKeyframes[i] = resolved as T\n }\n\n if (i === unresolvedKeyframes.length - 1) {\n this.finalKeyframe = keyframe as T\n }\n }\n }\n }\n\n /**\n * Resolve \"none\" values. We do this potentially twice - once before and once after measuring keyframes.\n * This could be seen as inefficient but it's a trade-off to avoid measurements in more situations, which\n * have a far bigger performance impact.\n */\n this.resolveNoneKeyframes()\n\n /**\n * Check to see if unit type has changed. If so schedule jobs that will\n * temporarily set styles to the destination keyframes.\n * Skip if we have more than two keyframes or this isn't a positional value.\n * TODO: We can throw if there are multiple keyframes and the value type changes.\n */\n if (!positionalKeys.has(name) || unresolvedKeyframes.length !== 2) {\n return\n }\n\n const [origin, target] = unresolvedKeyframes\n const originType = findDimensionValueType(origin)\n const targetType = findDimensionValueType(target)\n\n /**\n * If one keyframe contains embedded CSS variables (e.g. in calc()) and the other\n * doesn't, we need to measure to convert to pixels. This handles GitHub issue #3410.\n */\n const originHasVar = containsCSSVariable(origin)\n const targetHasVar = containsCSSVariable(target)\n\n if (originHasVar !== targetHasVar && positionalValues[name]) {\n this.needsMeasurement = true\n return\n }\n\n /**\n * Either we don't recognise these value types or we can animate between them.\n */\n if (originType === targetType) return\n\n /**\n * If both values are numbers or pixels, we can animate between them by\n * converting them to numbers.\n */\n if (isNumOrPxType(originType) && isNumOrPxType(targetType)) {\n for (let i = 0; i < unresolvedKeyframes.length; i++) {\n const value = unresolvedKeyframes[i]\n if (typeof value === \"string\") {\n unresolvedKeyframes[i] = parseFloat(value as string)\n }\n }\n } else if (positionalValues[name]) {\n /**\n * Else, the only way to resolve this is by measuring the element.\n */\n this.needsMeasurement = true\n }\n }\n\n resolveNoneKeyframes() {\n const { unresolvedKeyframes, name } = this\n\n const noneKeyframeIndexes: number[] = []\n for (let i = 0; i < unresolvedKeyframes.length; i++) {\n if (\n unresolvedKeyframes[i] === null ||\n isNone(unresolvedKeyframes[i])\n ) {\n noneKeyframeIndexes.push(i)\n }\n }\n\n if (noneKeyframeIndexes.length) {\n makeNoneKeyframesAnimatable(\n unresolvedKeyframes,\n noneKeyframeIndexes,\n name\n )\n }\n }\n\n measureInitialState() {\n const { element, unresolvedKeyframes, name } = this\n\n if (!element || !element.current) return\n\n if (name === \"height\") {\n this.suspendedScrollY = window.pageYOffset\n }\n\n this.measuredOrigin = positionalValues[name](\n element.measureViewportBox(),\n window.getComputedStyle(element.current)\n )\n\n unresolvedKeyframes[0] = this.measuredOrigin\n\n // Set final key frame to measure after next render\n const measureKeyframe =\n unresolvedKeyframes[unresolvedKeyframes.length - 1]\n\n if (measureKeyframe !== undefined) {\n element.getValue(name, measureKeyframe).jump(measureKeyframe, false)\n }\n }\n\n measureEndState() {\n const { element, name, unresolvedKeyframes } = this\n\n if (!element || !element.current) return\n\n const value = element.getValue(name)\n value && value.jump(this.measuredOrigin, false)\n\n const finalKeyframeIndex = unresolvedKeyframes.length - 1\n const finalKeyframe = unresolvedKeyframes[finalKeyframeIndex]\n\n unresolvedKeyframes[finalKeyframeIndex] = positionalValues[name](\n element.measureViewportBox(),\n window.getComputedStyle(element.current)\n ) as any\n\n if (finalKeyframe !== null && this.finalKeyframe === undefined) {\n this.finalKeyframe = finalKeyframe as T\n }\n\n // If we removed transform values, reapply them before the next render\n if (this.removedTransforms?.length) {\n this.removedTransforms.forEach(\n ([unsetTransformName, unsetTransformValue]) => {\n element\n .getValue(unsetTransformName)!\n .set(unsetTransformValue)\n }\n )\n }\n\n this.resolveNoneKeyframes()\n }\n}\n","/**\n * The four corner-radius longhands. Shared so the projection mixer, scale\n * corrector, WAAPI px-value set and view-transition crop pass don't each carry\n * their own copy. Order is irrelevant - every consumer mixes/corrects/animates\n * each corner independently.\n */\nexport const cornerRadiusProps = [\n \"borderTopLeftRadius\",\n \"borderTopRightRadius\",\n \"borderBottomRightRadius\",\n \"borderBottomLeftRadius\",\n] as const\n","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","import { ValueType } from \"../types\"\n\n/**\n * Provided a value and a ValueType, returns the value as that value type.\n */\nexport const getValueAsType = (value: any, type?: ValueType) => {\n return type && typeof value === \"number\"\n ? (type as any).transform(value)\n : value\n}\n","import { isObject } from \"motion-utils\"\n\n/**\n * Checks if an element is an HTML element in a way\n * that works across iframes\n */\nexport function isHTMLElement(element: unknown): element is HTMLElement {\n return (\n isObject(element) &&\n \"offsetHeight\" in element &&\n !(\"ownerSVGElement\" in element)\n )\n}\n","import { createRenderBatcher } from \"./batcher\"\n\nexport const { schedule: microtask, cancel: cancelMicrotask } =\n /* @__PURE__ */ createRenderBatcher(queueMicrotask, false)\n","export const isDragging = {\n x: false,\n y: false,\n}\n\nexport function isDragActive() {\n return isDragging.x || isDragging.y\n}\n","import {\n ElementOrSelector,\n resolveElements,\n} from \"../../utils/resolve-elements\"\nimport { EventOptions } from \"../types\"\n\nexport function setupGesture(\n elementOrSelector: ElementOrSelector,\n options: EventOptions\n): [Element[], AddEventListenerOptions, VoidFunction] {\n const elements = resolveElements(elementOrSelector)\n\n const gestureAbortController = new AbortController()\n\n const eventOptions = {\n passive: true,\n ...options,\n signal: gestureAbortController.signal,\n }\n\n const cancel = () => gestureAbortController.abort()\n\n return [elements, eventOptions, cancel]\n}\n","import { ElementOrSelector } from \"../utils/resolve-elements\"\nimport { isDragActive } from \"./drag/state/is-active\"\nimport { EventOptions } from \"./types\"\nimport { setupGesture } from \"./utils/setup\"\n\n/**\n * A function to be called when a hover gesture starts.\n *\n * This function can optionally return a function that will be called\n * when the hover gesture ends.\n *\n * @public\n */\nexport type OnHoverStartEvent = (\n element: Element,\n event: PointerEvent\n) => void | OnHoverEndEvent\n\n/**\n * A function to be called when a hover gesture ends.\n *\n * @public\n */\nexport type OnHoverEndEvent = (event: PointerEvent) => void\n\nfunction isValidHover(event: PointerEvent) {\n return !(event.pointerType === \"touch\" || isDragActive())\n}\n\n/**\n * Create a hover gesture. hover() is different to .addEventListener(\"pointerenter\")\n * in that it has an easier syntax, filters out polyfilled touch events, interoperates\n * with drag gestures, and automatically removes the \"pointerennd\" event listener when the hover ends.\n *\n * @public\n */\nexport function hover(\n elementOrSelector: ElementOrSelector,\n onHoverStart: OnHoverStartEvent,\n options: EventOptions = {}\n): VoidFunction {\n const [elements, eventOptions, cancel] = setupGesture(\n elementOrSelector,\n options\n )\n\n elements.forEach((element) => {\n let isPressed = false\n let deferredHoverEnd = false\n let hoverEndCallback: OnHoverEndEvent | undefined\n\n const removePointerLeave = () => {\n element.removeEventListener(\n \"pointerleave\",\n onPointerLeave as EventListener\n )\n }\n\n const endHover = (event: PointerEvent) => {\n if (hoverEndCallback) {\n hoverEndCallback(event)\n hoverEndCallback = undefined\n }\n removePointerLeave()\n }\n\n const onPointerUp = (event: Event) => {\n isPressed = false\n window.removeEventListener(\n \"pointerup\",\n onPointerUp as EventListener\n )\n window.removeEventListener(\n \"pointercancel\",\n onPointerUp as EventListener\n )\n\n if (deferredHoverEnd) {\n deferredHoverEnd = false\n endHover(event as PointerEvent)\n }\n }\n\n const onPointerDown = () => {\n isPressed = true\n window.addEventListener(\n \"pointerup\",\n onPointerUp as EventListener,\n eventOptions\n )\n window.addEventListener(\n \"pointercancel\",\n onPointerUp as EventListener,\n eventOptions\n )\n }\n\n const onPointerLeave = (leaveEvent: PointerEvent) => {\n if (leaveEvent.pointerType === \"touch\") return\n\n if (isPressed) {\n deferredHoverEnd = true\n return\n }\n\n endHover(leaveEvent)\n }\n\n const onPointerEnter = (enterEvent: PointerEvent) => {\n if (!isValidHover(enterEvent)) return\n\n deferredHoverEnd = false\n\n const onHoverEnd = onHoverStart(\n element as Element,\n enterEvent\n )\n\n if (typeof onHoverEnd !== \"function\") return\n\n hoverEndCallback = onHoverEnd\n\n element.addEventListener(\n \"pointerleave\",\n onPointerLeave as EventListener,\n eventOptions\n )\n }\n\n element.addEventListener(\n \"pointerenter\",\n onPointerEnter as EventListener,\n eventOptions\n )\n element.addEventListener(\n \"pointerdown\",\n onPointerDown as EventListener,\n eventOptions\n )\n })\n\n return cancel\n}\n","/**\n * Recursively traverse up the tree to check whether the provided child node\n * is the parent or a descendant of it.\n *\n * @param parent - Element to find\n * @param child - Element to test against parent\n */\nexport const isNodeOrChild = (\n parent: Element | null,\n child?: Element | null\n): boolean => {\n if (!child) {\n return false\n } else if (parent === child) {\n return true\n } else {\n return isNodeOrChild(parent, child.parentElement)\n }\n}\n","export const isPrimaryPointer = (event: PointerEvent) => {\n if (event.pointerType === \"mouse\") {\n return typeof event.button !== \"number\" || event.button <= 0\n } else {\n /**\n * isPrimary is true for all mice buttons, whereas every touch point\n * is regarded as its own input. So subsequent concurrent touch points\n * will be false.\n *\n * Specifically match against false here as incomplete versions of\n * PointerEvents in very old browser might have it set as undefined.\n */\n return event.isPrimary !== false\n }\n}\n","const keyboardAccessibleElements = new Set([\n \"BUTTON\",\n \"INPUT\",\n \"SELECT\",\n \"TEXTAREA\",\n \"A\",\n])\n\n/**\n * Checks if an element is natively keyboard accessible (focusable).\n * Used by the press gesture to determine if we need to add tabIndex.\n */\nexport function isElementKeyboardAccessible(element: Element) {\n return (\n keyboardAccessibleElements.has(element.tagName) ||\n (element as HTMLElement).isContentEditable === true\n )\n}\n\nconst textInputElements = new Set([\"INPUT\", \"SELECT\", \"TEXTAREA\"])\n\n/**\n * Checks if an element has text selection or direct interaction behavior\n * that should block drag gestures from starting.\n *\n * This specifically targets form controls where the user might want to select\n * text or interact with the control (e.g., sliders, dropdowns).\n *\n * Buttons and links are NOT included because they don't have click-and-move\n * actions of their own - they only respond to click events, so dragging\n * should still work when initiated from these elements.\n */\nexport function isElementTextInput(element: Element) {\n return (\n textInputElements.has(element.tagName) ||\n (element as HTMLElement).isContentEditable === true\n )\n}\n","export const isPressing = new WeakSet<EventTarget>()\n","import { isPressing } from \"./state\"\n\n/**\n * Filter out events that are not \"Enter\" keys.\n */\nfunction filterEvents(callback: (event: KeyboardEvent) => void) {\n return (event: KeyboardEvent) => {\n if (event.key !== \"Enter\") return\n callback(event)\n }\n}\n\nfunction firePointerEvent(target: EventTarget, type: \"down\" | \"up\" | \"cancel\") {\n target.dispatchEvent(\n new PointerEvent(\"pointer\" + type, { isPrimary: true, bubbles: true })\n )\n}\n\nexport const enableKeyboardPress = (\n focusEvent: FocusEvent,\n eventOptions: AddEventListenerOptions\n) => {\n const element = focusEvent.currentTarget as HTMLElement\n if (!element) return\n\n const handleKeydown = filterEvents(() => {\n if (isPressing.has(element)) return\n\n firePointerEvent(element, \"down\")\n\n const handleKeyup = filterEvents(() => {\n firePointerEvent(element, \"up\")\n })\n\n const handleBlur = () => firePointerEvent(element, \"cancel\")\n\n element.addEventListener(\"keyup\", handleKeyup, eventOptions)\n element.addEventListener(\"blur\", handleBlur, eventOptions)\n })\n\n element.addEventListener(\"keydown\", handleKeydown, eventOptions)\n\n /**\n * Add an event listener that fires on blur to remove the keydown events.\n */\n element.addEventListener(\n \"blur\",\n () => element.removeEventListener(\"keydown\", handleKeydown),\n eventOptions\n )\n}\n","import { isHTMLElement } from \"../../utils/is-html-element\"\nimport { ElementOrSelector } from \"../../utils/resolve-elements\"\nimport { isDragActive } from \"../drag/state/is-active\"\nimport { EventOptions } from \"../types\"\nimport { isNodeOrChild } from \"../utils/is-node-or-child\"\nimport { isPrimaryPointer } from \"../utils/is-primary-pointer\"\nimport { setupGesture } from \"../utils/setup\"\nimport { OnPressStartEvent } from \"./types\"\nimport { isElementKeyboardAccessible } from \"./utils/is-keyboard-accessible\"\nimport { enableKeyboardPress } from \"./utils/keyboard\"\nimport { isPressing } from \"./utils/state\"\n\n/**\n * Filter out events that are not primary pointer events, or are triggering\n * while a Motion gesture is active.\n */\nfunction isValidPressEvent(event: PointerEvent) {\n return isPrimaryPointer(event) && !isDragActive()\n}\n\nconst claimedPointerDownEvents = new WeakSet<Event>()\n\nexport interface PointerEventOptions extends EventOptions {\n useGlobalTarget?: boolean\n stopPropagation?: boolean\n}\n\n/**\n * Create a press gesture.\n *\n * Press is different to `\"pointerdown\"`, `\"pointerup\"` in that it\n * automatically filters out secondary pointer events like right\n * click and multitouch.\n *\n * It also adds accessibility support for keyboards, where\n * an element with a press gesture will receive focus and\n * trigger on Enter `\"keydown\"` and `\"keyup\"` events.\n *\n * This is different to a browser's `\"click\"` event, which does\n * respond to keyboards but only for the `\"click\"` itself, rather\n * than the press start and end/cancel. The element also needs\n * to be focusable for this to work, whereas a press gesture will\n * make an element focusable by default.\n *\n * @public\n */\nexport function press(\n targetOrSelector: ElementOrSelector,\n onPressStart: OnPressStartEvent,\n options: PointerEventOptions = {}\n): VoidFunction {\n const [targets, eventOptions, cancelEvents] = setupGesture(\n targetOrSelector,\n options\n )\n\n const startPress = (startEvent: PointerEvent) => {\n const target = startEvent.currentTarget as Element\n\n if (!isValidPressEvent(startEvent)) return\n if (claimedPointerDownEvents.has(startEvent)) return\n\n isPressing.add(target)\n\n if (options.stopPropagation) {\n claimedPointerDownEvents.add(startEvent)\n }\n\n const onPressEnd = onPressStart(target, startEvent)\n\n /**\n * End listeners run in the capture phase so a descendant calling\n * stopPropagation() in its own pointerup handler can't prevent the\n * press gesture from ending. This also keeps the gesture-end\n * ordering consistent with the drag gesture. See #2794.\n */\n const endEventOptions = { ...eventOptions, capture: true }\n\n const onPointerEnd = (endEvent: PointerEvent, success: boolean) => {\n window.removeEventListener(\n \"pointerup\",\n onPointerUp,\n endEventOptions\n )\n window.removeEventListener(\n \"pointercancel\",\n onPointerCancel,\n endEventOptions\n )\n\n if (isPressing.has(target)) {\n isPressing.delete(target)\n }\n\n if (!isValidPressEvent(endEvent)) {\n return\n }\n\n if (typeof onPressEnd === \"function\") {\n onPressEnd(endEvent, { success })\n }\n }\n\n const onPointerUp = (upEvent: PointerEvent) => {\n onPointerEnd(\n upEvent,\n (target as any) === window ||\n (target as any) === document ||\n options.useGlobalTarget ||\n isNodeOrChild(target, upEvent.target as Element)\n )\n }\n\n const onPointerCancel = (cancelEvent: PointerEvent) => {\n onPointerEnd(cancelEvent, false)\n }\n\n window.addEventListener(\"pointerup\", onPointerUp, endEventOptions)\n window.addEventListener(\n \"pointercancel\",\n onPointerCancel,\n endEventOptions\n )\n }\n\n targets.forEach((target: EventTarget) => {\n const pointerDownTarget = options.useGlobalTarget ? window : target\n pointerDownTarget.addEventListener(\n \"pointerdown\",\n startPress as EventListener,\n eventOptions\n )\n\n if (isHTMLElement(target)) {\n target.addEventListener(\"focus\", (event) =>\n enableKeyboardPress(event as FocusEvent, eventOptions)\n )\n\n if (\n !isElementKeyboardAccessible(target) &&\n !target.hasAttribute(\"tabindex\")\n ) {\n target.tabIndex = 0\n }\n }\n })\n\n return cancelEvents\n}\n","import { color } from \"../color\"\nimport { complex } from \"../complex\"\nimport { dimensionValueTypes } from \"../dimensions\"\nimport { testValueType } from \"../test\"\n\n/**\n * A list of all ValueTypes\n */\nconst valueTypes = [...dimensionValueTypes, color, complex]\n\n/**\n * Tests a value against the list of ValueTypes\n */\nexport const findValueType = (v: any) => valueTypes.find(testValueType(v))\n","import { Axis, AxisDelta, Box, Delta } from \"motion-utils\"\n\nexport const createAxisDelta = (): AxisDelta => ({\n translate: 0,\n scale: 1,\n origin: 0,\n originPoint: 0,\n})\n\nexport const createDelta = (): Delta => ({\n x: createAxisDelta(),\n y: createAxisDelta(),\n})\n\nexport const createAxis = (): Axis => ({ min: 0, max: 0 })\n\nexport const createBox = (): Box => ({\n x: createAxis(),\n y: createAxis(),\n})\n","import type { VisualElement } from \"./VisualElement\"\n\nexport const visualElementStore = new WeakMap<any, VisualElement>()\n","import type { LegacyAnimationControls } from \"../../node/types\"\n\nexport function isAnimationControls(v?: unknown): v is LegacyAnimationControls {\n return (\n v !== null &&\n typeof v === \"object\" &&\n typeof (v as LegacyAnimationControls).start === \"function\"\n )\n}\n","/**\n * Decides if the supplied variable is variant label\n */\nexport function isVariantLabel(v: unknown): v is string | string[] {\n return typeof v === \"string\" || Array.isArray(v)\n}\n","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","import type { MotionNodeOptions } from \"../../node/types\"\nimport { isAnimationControls } from \"./is-animation-controls\"\nimport { isVariantLabel } from \"./is-variant-label\"\nimport { variantProps } from \"./variant-props\"\n\nexport function isControllingVariants(props: MotionNodeOptions) {\n return (\n isAnimationControls(props.animate) ||\n variantProps.some((name) =>\n isVariantLabel(props[name as keyof typeof props])\n )\n )\n}\n\nexport function isVariantNode(props: MotionNodeOptions) {\n return Boolean(isControllingVariants(props) || props.variants)\n}\n","import { motionValue } from \"../../value\"\nimport { isMotionValue } from \"../../value/utils/is-motion-value\"\n\ntype MotionStyleLike = Record<string, any>\n\n/**\n * Updates motion values from props changes.\n * Uses `any` type for element to avoid circular dependencies with VisualElement.\n */\nexport function updateMotionValuesFromProps(\n element: any,\n next: MotionStyleLike,\n prev: MotionStyleLike\n) {\n for (const key in next) {\n const nextValue = next[key]\n const prevValue = prev[key]\n\n if (isMotionValue(nextValue)) {\n /**\n * If this is a motion value found in props or style, we want to add it\n * to our visual element's motion value map.\n */\n element.addValue(key, nextValue)\n } else if (isMotionValue(prevValue)) {\n /**\n * If we're swapping from a motion value to a static value,\n * create a new motion value from that\n */\n element.addValue(key, motionValue(nextValue, { owner: element }))\n } else if (prevValue !== nextValue) {\n /**\n * If this is a flat value that has changed, update the motion value\n * or create one if it doesn't exist. We only want to do this if we're\n * not handling the value with our animation state.\n */\n if (element.hasValue(key)) {\n const existingValue = element.getValue(key)!\n\n if (existingValue.liveStyle === true) {\n existingValue.jump(nextValue)\n } else if (!existingValue.hasAnimated) {\n existingValue.set(nextValue)\n }\n } else {\n const latestValue = element.getStaticValue(key)\n element.addValue(\n key,\n motionValue(\n latestValue !== undefined ? latestValue : nextValue,\n { owner: element }\n )\n )\n }\n }\n }\n\n // Handle removed values\n for (const key in prev) {\n if (next[key] === undefined) element.removeValue(key)\n }\n\n return next\n}\n","interface ReducedMotionState {\n current: boolean | null\n}\n\n// Does this device prefer reduced motion? Returns `null` server-side.\nexport const prefersReducedMotion: ReducedMotionState = { current: null }\n\nexport const hasReducedMotionListener = { current: false }\n","import { hasReducedMotionListener, prefersReducedMotion } from \"./state\"\n\nconst isBrowser = typeof window !== \"undefined\"\n\nexport function initPrefersReducedMotion() {\n hasReducedMotionListener.current = true\n if (!isBrowser) return\n\n if (window.matchMedia) {\n const motionMediaQuery = window.matchMedia(\"(prefers-reduced-motion)\")\n\n const setReducedMotionPreferences = () =>\n (prefersReducedMotion.current = motionMediaQuery.matches)\n\n motionMediaQuery.addEventListener(\"change\", setReducedMotionPreferences)\n\n setReducedMotionPreferences()\n } else {\n prefersReducedMotion.current = false\n }\n}\n\nexport { prefersReducedMotion, hasReducedMotionListener }\n","import {\n Box,\n isNumericalString,\n isZeroValueString,\n secondsToMilliseconds,\n SubscriptionManager,\n warnOnce,\n} from \"motion-utils\"\nimport { KeyframeResolver } from \"../animation/keyframes/KeyframesResolver\"\nimport { NativeAnimation } from \"../animation/NativeAnimation\"\nimport type { AnyResolvedKeyframe } from \"../animation/types\"\nimport { acceleratedValues } from \"../animation/waapi/utils/accelerated-values\"\nimport { cancelFrame, frame } from \"../frameloop\"\nimport { microtask } from \"../frameloop/microtask\"\nimport { time } from \"../frameloop/sync-time\"\nimport type { MotionNodeOptions } from \"../node/types\"\nimport { createBox } from \"../projection/geometry/models\"\nimport { motionValue, MotionValue } from \"../value\"\nimport { complex } from \"../value/types/complex\"\nimport { getAnimatableNone } from \"../value/types/utils/animatable-none\"\nimport { findValueType } from \"../value/types/utils/find\"\nimport { isMotionValue } from \"../value/utils/is-motion-value\"\nimport { Feature } from \"./Feature\"\nimport { visualElementStore } from \"./store\"\nimport {\n FeatureDefinitions,\n MotionConfigContextProps,\n PresenceContextProps,\n ReducedMotionConfig,\n ResolvedValues,\n VisualElementEventCallbacks,\n VisualElementOptions,\n} from \"./types\"\nimport { AnimationState } from \"./utils/animation-state\"\nimport {\n isControllingVariants as checkIsControllingVariants,\n isVariantNode as checkIsVariantNode,\n} from \"./utils/is-controlling-variants\"\nimport { transformProps } from \"./utils/keys-transform\"\nimport { updateMotionValuesFromProps } from \"./utils/motion-values\"\nimport {\n hasReducedMotionListener,\n initPrefersReducedMotion,\n prefersReducedMotion,\n} from \"./utils/reduced-motion\"\nimport { resolveVariantFromProps } from \"./utils/resolve-variants\"\n\nconst propEventHandlers = [\n \"AnimationStart\",\n \"AnimationComplete\",\n \"Update\",\n \"BeforeLayoutMeasure\",\n \"LayoutMeasure\",\n \"LayoutAnimationStart\",\n \"LayoutAnimationComplete\",\n] as const\n\n/**\n * Static feature definitions - can be injected by framework layer\n */\nlet featureDefinitions: Partial<FeatureDefinitions> = {}\n\n/**\n * Set feature definitions for all VisualElements.\n * This should be called by the framework layer (e.g., framer-motion) during initialization.\n */\nexport function setFeatureDefinitions(\n definitions: Partial<FeatureDefinitions>\n) {\n featureDefinitions = definitions\n}\n\n/**\n * Get the current feature definitions\n */\nexport function getFeatureDefinitions(): Partial<FeatureDefinitions> {\n return featureDefinitions\n}\n\n/**\n * Motion style type - a subset of CSS properties that can contain motion values\n */\nexport type MotionStyle = {\n [K: string]: AnyResolvedKeyframe | MotionValue | undefined\n}\n\n/**\n * A VisualElement is an imperative abstraction around UI elements such as\n * HTMLElement, SVGElement, Three.Object3D etc.\n */\nexport abstract class VisualElement<\n Instance = unknown,\n RenderState = unknown,\n Options extends {} = {}\n> {\n /**\n * VisualElements are arranged in trees mirroring that of the React tree.\n * Each type of VisualElement has a unique name, to detect when we're crossing\n * type boundaries within that tree.\n */\n abstract type: string\n\n /**\n * An `Array.sort` compatible function that will compare two Instances and\n * compare their respective positions within the tree.\n */\n abstract sortInstanceNodePosition(a: Instance, b: Instance): number\n\n /**\n * Measure the viewport-relative bounding box of the Instance.\n */\n abstract measureInstanceViewportBox(\n instance: Instance,\n props: MotionNodeOptions & Partial<MotionConfigContextProps>\n ): Box\n\n /**\n * When a value has been removed from all animation props we need to\n * pick a target to animate back to. For instance, for HTMLElements\n * we can look in the style prop.\n */\n abstract getBaseTargetFromProps(\n props: MotionNodeOptions,\n key: string\n ): AnyResolvedKeyframe | undefined | MotionValue\n\n /**\n * When we first animate to a value we need to animate it *from* a value.\n * Often this have been specified via the initial prop but it might be\n * that the value needs to be read from the Instance.\n */\n abstract readValueFromInstance(\n instance: Instance,\n key: string,\n options: Options\n ): AnyResolvedKeyframe | null | undefined\n\n /**\n * When a value has been removed from the VisualElement we use this to remove\n * it from the inherting class' unique render state.\n */\n abstract removeValueFromRenderState(\n key: string,\n renderState: RenderState\n ): void\n\n /**\n * Run before a React or VisualElement render, builds the latest motion\n * values into an Instance-specific format. For example, HTMLVisualElement\n * will use this step to build `style` and `var` values.\n */\n abstract build(\n renderState: RenderState,\n latestValues: ResolvedValues,\n props: MotionNodeOptions\n ): void\n\n /**\n * Apply the built values to the Instance. For example, HTMLElements will have\n * styles applied via `setProperty` and the style attribute, whereas SVGElements\n * will have values applied to attributes.\n */\n abstract renderInstance(\n instance: Instance,\n renderState: RenderState,\n styleProp?: MotionStyle,\n projection?: any\n ): void\n\n /**\n * This method is called when a transform property is bound to a motion value.\n * It's currently used to measure SVG elements when a new transform property is bound.\n */\n onBindTransform?(): void\n\n /**\n * If the component child is provided as a motion value, handle subscriptions\n * with the renderer-specific VisualElement.\n */\n handleChildMotionValue?(): void\n\n /**\n * This method takes React props and returns found MotionValues. For example, HTML\n * MotionValues will be found within the style prop, whereas for Three.js within attribute arrays.\n *\n * This isn't an abstract method as it needs calling in the constructor, but it is\n * intended to be one.\n */\n scrapeMotionValuesFromProps(\n _props: MotionNodeOptions,\n _prevProps: MotionNodeOptions,\n _visualElement: VisualElement\n ): {\n [key: string]: MotionValue | AnyResolvedKeyframe\n } {\n return {}\n }\n\n /**\n * A reference to the current underlying Instance, e.g. a HTMLElement\n * or Three.Mesh etc.\n */\n current: Instance | null = null\n\n /**\n * A reference to the parent VisualElement (if exists).\n */\n parent: VisualElement | undefined\n\n /**\n * A set containing references to this VisualElement's children.\n */\n children = new Set<VisualElement>()\n\n /**\n * A set containing the latest children of this VisualElement. This is flushed\n * at the start of every commit. We use it to calculate the stagger delay\n * for newly-added children.\n */\n enteringChildren?: Set<VisualElement>\n\n /**\n * The depth of this VisualElement within the overall VisualElement tree.\n */\n depth: number\n\n /**\n * The current render state of this VisualElement. Defined by inherting VisualElements.\n */\n renderState: RenderState\n\n /**\n * An object containing the latest static values for each of this VisualElement's\n * MotionValues.\n */\n latestValues: ResolvedValues\n\n /**\n * Determine what role this visual element should take in the variant tree.\n */\n isVariantNode: boolean = false\n isControllingVariants: boolean = false\n\n /**\n * If this component is part of the variant tree, it should track\n * any children that are also part of the tree. This is essentially\n * a shadow tree to simplify logic around how to stagger over children.\n */\n variantChildren?: Set<VisualElement>\n\n /**\n * Decides whether this VisualElement should animate in reduced motion\n * mode.\n *\n * TODO: This is currently set on every individual VisualElement but feels\n * like it could be set globally.\n */\n shouldReduceMotion: boolean | null = null\n\n /**\n * Decides whether animations should be skipped for this VisualElement.\n * Useful for E2E tests and visual regression testing.\n */\n shouldSkipAnimations: boolean = false\n\n /**\n * Normally, if a component is controlled by a parent's variants, it can\n * rely on that ancestor to trigger animations further down the tree.\n * However, if a component is created after its parent is mounted, the parent\n * won't trigger that mount animation so the child needs to.\n *\n * TODO: This might be better replaced with a method isParentMounted\n */\n manuallyAnimateOnMount: boolean\n\n /**\n * This can be set by AnimatePresence to force components that mount\n * at the same time as it to mount as if they have initial={false} set.\n */\n blockInitialAnimation: boolean\n\n /**\n * A reference to this VisualElement's projection node, used in layout animations.\n */\n projection?: any\n\n /**\n * A map of all motion values attached to this visual element. Motion\n * values are source of truth for any given animated value. A motion\n * value might be provided externally by the component via props.\n */\n values = new Map<string, MotionValue>()\n\n /**\n * The AnimationState, this is hydrated by the animation Feature.\n */\n animationState?: AnimationState\n\n KeyframeResolver = KeyframeResolver\n\n /**\n * The options used to create this VisualElement. The Options type is defined\n * by the inheriting VisualElement and is passed straight through to the render functions.\n */\n readonly options: Options\n\n /**\n * A reference to the latest props provided to the VisualElement's host React component.\n */\n props: MotionNodeOptions\n prevProps?: MotionNodeOptions\n\n presenceContext: PresenceContextProps | null\n prevPresenceContext?: PresenceContextProps | null\n\n /**\n * Cleanup functions for active features (hover/tap/exit etc)\n */\n private features: {\n [K in keyof FeatureDefinitions]?: Feature<Instance>\n } = {}\n\n /**\n * A map of every subscription that binds the provided or generated\n * motion values onChange listeners to this visual element.\n */\n private valueSubscriptions = new Map<string, VoidFunction>()\n\n /**\n * A reference to the ReducedMotionConfig passed to the VisualElement's host React component.\n */\n private reducedMotionConfig: ReducedMotionConfig | undefined\n\n /**\n * A reference to the skipAnimations config passed to the VisualElement's host React component.\n */\n private skipAnimationsConfig: boolean | undefined\n\n /**\n * On mount, this will be hydrated with a callback to disconnect\n * this visual element from its parent on unmount.\n */\n private removeFromVariantTree: undefined | VoidFunction\n\n /**\n * A reference to the previously-provided motion values as returned\n * from scrapeMotionValuesFromProps. We use the keys in here to determine\n * if any motion values need to be removed after props are updated.\n */\n private prevMotionValues: MotionStyle = {}\n\n /**\n * When values are removed from all animation props we need to search\n * for a fallback value to animate to. These values are tracked in baseTarget.\n */\n private baseTarget: ResolvedValues\n\n /**\n * Create an object of the values we initially animated from (if initial prop present).\n */\n private initialValues: ResolvedValues\n\n /**\n * Track whether this element has been mounted before, to detect\n * remounts after Suspense unmount/remount cycles.\n */\n private hasBeenMounted = false\n\n /**\n * An object containing a SubscriptionManager for each active event.\n */\n private events: {\n [key: string]: SubscriptionManager<any>\n } = {}\n\n /**\n * An object containing an unsubscribe function for each prop event subscription.\n * For example, every \"Update\" event can have multiple subscribers via\n * VisualElement.on(), but only one of those can be defined via the onUpdate prop.\n */\n private propEventSubscriptions: {\n [key: string]: VoidFunction\n } = {}\n\n constructor(\n {\n parent,\n props,\n presenceContext,\n reducedMotionConfig,\n skipAnimations,\n blockInitialAnimation,\n visualState,\n }: VisualElementOptions<Instance, RenderState>,\n options: Options = {} as any\n ) {\n const { latestValues, renderState } = visualState\n this.latestValues = latestValues\n this.baseTarget = { ...latestValues }\n this.initialValues = props.initial ? { ...latestValues } : {}\n this.renderState = renderState\n this.parent = parent\n this.props = props\n this.presenceContext = presenceContext\n this.depth = parent ? parent.depth + 1 : 0\n this.reducedMotionConfig = reducedMotionConfig\n this.skipAnimationsConfig = skipAnimations\n this.options = options\n this.blockInitialAnimation = Boolean(blockInitialAnimation)\n\n this.isControllingVariants = checkIsControllingVariants(props)\n this.isVariantNode = checkIsVariantNode(props)\n if (this.isVariantNode) {\n this.variantChildren = new Set()\n }\n\n this.manuallyAnimateOnMount = Boolean(parent && parent.current)\n\n /**\n * Any motion values that are provided to the element when created\n * aren't yet bound to the element, as this would technically be impure.\n * However, we iterate through the motion values and set them to the\n * initial values for this component.\n *\n * TODO: This is impure and we should look at changing this to run on mount.\n * Doing so will break some tests but this isn't necessarily a breaking change,\n * more a reflection of the test.\n */\n const { willChange, ...initialMotionValues } =\n this.scrapeMotionValuesFromProps(props, {}, this)\n\n for (const key in initialMotionValues) {\n const value = initialMotionValues[key]\n\n if (latestValues[key] !== undefined && isMotionValue(value)) {\n value.set(latestValues[key])\n }\n }\n }\n\n mount(instance: Instance) {\n /**\n * If this element has been mounted before (e.g. after a Suspense\n * unmount/remount), reset motion values to their initial state\n * so animations replay correctly from initial → animate.\n */\n if (this.hasBeenMounted) {\n for (const key in this.initialValues) {\n this.values.get(key)?.jump(this.initialValues[key])\n this.latestValues[key] = this.initialValues[key]\n }\n }\n\n this.current = instance\n\n visualElementStore.set(instance, this)\n\n if (this.projection && !this.projection.instance) {\n this.projection.mount(instance)\n }\n\n if (this.parent && this.isVariantNode && !this.isControllingVariants) {\n this.removeFromVariantTree = this.parent.addVariantChild(this)\n }\n\n this.values.forEach((value, key) => this.bindToMotionValue(key, value))\n\n /**\n * Determine reduced motion preference. Only initialize the matchMedia\n * listener if we actually need the dynamic value (i.e., when config\n * is neither \"never\" nor \"always\").\n */\n if (this.reducedMotionConfig === \"never\") {\n this.shouldReduceMotion = false\n } else if (this.reducedMotionConfig === \"always\") {\n this.shouldReduceMotion = true\n } else {\n if (!hasReducedMotionListener.current) {\n initPrefersReducedMotion()\n }\n this.shouldReduceMotion = prefersReducedMotion.current\n }\n\n if (process.env.NODE_ENV !== \"production\") {\n warnOnce(\n this.shouldReduceMotion !== true,\n \"You have Reduced Motion enabled on your device. Animations may not appear as expected.\",\n \"reduced-motion-disabled\"\n )\n }\n\n /**\n * Set whether animations should be skipped based on the config.\n */\n this.shouldSkipAnimations = this.skipAnimationsConfig ?? false\n\n this.parent?.addChild(this)\n\n this.update(this.props, this.presenceContext)\n\n this.hasBeenMounted = true\n }\n\n unmount() {\n this.projection && this.projection.unmount()\n cancelFrame(this.notifyUpdate)\n cancelFrame(this.render)\n this.valueSubscriptions.forEach((remove) => remove())\n this.valueSubscriptions.clear()\n this.removeFromVariantTree && this.removeFromVariantTree()\n this.parent?.removeChild(this)\n\n for (const key in this.events) {\n this.events[key].clear()\n }\n\n for (const key in this.features) {\n const feature = this.features[key as keyof typeof this.features]\n if (feature) {\n feature.unmount()\n feature.isMounted = false\n }\n }\n this.current = null\n }\n\n addChild(child: VisualElement) {\n this.children.add(child)\n this.enteringChildren ??= new Set()\n this.enteringChildren.add(child)\n }\n\n removeChild(child: VisualElement) {\n this.children.delete(child)\n this.enteringChildren && this.enteringChildren.delete(child)\n }\n\n private bindToMotionValue(key: string, value: MotionValue) {\n if (this.valueSubscriptions.has(key)) {\n this.valueSubscriptions.get(key)!()\n }\n\n if (\n value.accelerate &&\n acceleratedValues.has(key) &&\n this.current instanceof HTMLElement\n ) {\n const { factory, keyframes, times, ease, duration } =\n value.accelerate\n\n const animation = new NativeAnimation({\n element: this.current,\n name: key,\n keyframes,\n times,\n ease,\n duration: secondsToMilliseconds(duration),\n })\n\n const cleanup = factory(animation)\n\n this.valueSubscriptions.set(key, () => {\n cleanup()\n animation.cancel()\n })\n return\n }\n\n const valueIsTransform = transformProps.has(key)\n\n if (valueIsTransform && this.onBindTransform) {\n this.onBindTransform()\n }\n\n const removeOnChange = value.on(\n \"change\",\n (latestValue: AnyResolvedKeyframe) => {\n this.latestValues[key] = latestValue\n\n this.props.onUpdate && frame.preRender(this.notifyUpdate)\n\n if (valueIsTransform && this.projection) {\n this.projection.isTransformDirty = true\n }\n\n this.scheduleRender()\n }\n )\n\n let removeSyncCheck: VoidFunction | void\n if (\n typeof window !== \"undefined\" &&\n (window as any).MotionCheckAppearSync\n ) {\n removeSyncCheck = (window as any).MotionCheckAppearSync(\n this,\n key,\n value\n )\n }\n\n this.valueSubscriptions.set(key, () => {\n removeOnChange()\n if (removeSyncCheck) removeSyncCheck()\n // Defer to MotionValue.on(\"change\") auto-stop so React 19 remounts\n // can resubscribe before the animation is cancelled (#3315).\n })\n }\n\n sortNodePosition(other: VisualElement<Instance>) {\n /**\n * If these nodes aren't even of the same type we can't compare their depth.\n */\n if (\n !this.current ||\n !this.sortInstanceNodePosition ||\n this.type !== other.type\n ) {\n return 0\n }\n\n return this.sortInstanceNodePosition(\n this.current as Instance,\n other.current as Instance\n )\n }\n\n updateFeatures() {\n let key: keyof typeof featureDefinitions = \"animation\"\n\n for (key in featureDefinitions) {\n const featureDefinition = featureDefinitions[key]\n\n if (!featureDefinition) continue\n\n const { isEnabled, Feature: FeatureConstructor } = featureDefinition\n\n /**\n * If this feature is enabled but not active, make a new instance.\n */\n if (\n !this.features[key] &&\n FeatureConstructor &&\n isEnabled(this.props)\n ) {\n this.features[key] = new FeatureConstructor(this) as any\n }\n\n /**\n * If we have a feature, mount or update it.\n */\n if (this.features[key]) {\n const feature = this.features[key]!\n if (feature.isMounted) {\n feature.update()\n } else {\n feature.mount()\n feature.isMounted = true\n }\n }\n }\n }\n\n notifyUpdate = () => this.notify(\"Update\", this.latestValues)\n\n triggerBuild() {\n this.build(this.renderState, this.latestValues, this.props)\n }\n\n render = () => {\n if (!this.current) return\n this.triggerBuild()\n this.renderInstance(\n this.current,\n this.renderState,\n (this.props as any).style,\n this.projection\n )\n }\n\n private renderScheduledAt = 0.0\n scheduleRender = () => {\n const now = time.now()\n if (this.renderScheduledAt < now) {\n this.renderScheduledAt = now\n frame.render(this.render, false, true)\n }\n }\n\n /**\n * Measure the current viewport box with or without transforms.\n * Only measures axis-aligned boxes, rotate and skew must be manually\n * removed with a re-render to work.\n */\n measureViewportBox() {\n return this.current\n ? this.measureInstanceViewportBox(this.current, this.props)\n : createBox()\n }\n\n getStaticValue(key: string) {\n return this.latestValues[key]\n }\n\n setStaticValue(key: string, value: AnyResolvedKeyframe) {\n this.latestValues[key] = value\n }\n\n /**\n * Update the provided props. Ensure any newly-added motion values are\n * added to our map, old ones removed, and listeners updated.\n */\n update(\n props: MotionNodeOptions,\n presenceContext: PresenceContextProps | null\n ) {\n if (props.transformTemplate || this.props.transformTemplate) {\n this.scheduleRender()\n }\n\n this.prevProps = this.props\n this.props = props\n\n this.prevPresenceContext = this.presenceContext\n this.presenceContext = presenceContext\n\n /**\n * Update prop event handlers ie onAnimationStart, onAnimationComplete\n */\n for (let i = 0; i < propEventHandlers.length; i++) {\n const key = propEventHandlers[i]\n if (this.propEventSubscriptions[key]) {\n this.propEventSubscriptions[key]()\n delete this.propEventSubscriptions[key]\n }\n\n const listenerName = (\"on\" + key) as keyof typeof props\n const listener = props[listenerName]\n if (listener) {\n this.propEventSubscriptions[key] = this.on(key as any, listener)\n }\n }\n\n this.prevMotionValues = updateMotionValuesFromProps(\n this,\n this.scrapeMotionValuesFromProps(props, this.prevProps || {}, this),\n this.prevMotionValues\n )\n\n if (this.handleChildMotionValue) {\n this.handleChildMotionValue()\n }\n }\n\n getProps() {\n return this.props\n }\n\n /**\n * Returns the variant definition with a given name.\n */\n getVariant(name: string) {\n return this.props.variants ? this.props.variants[name] : undefined\n }\n\n /**\n * Returns the defined default transition on this component.\n */\n getDefaultTransition() {\n return this.props.transition\n }\n\n getTransformPagePoint() {\n return (this.props as any).transformPagePoint\n }\n\n getClosestVariantNode(): VisualElement | undefined {\n return this.isVariantNode\n ? this\n : this.parent\n ? this.parent.getClosestVariantNode()\n : undefined\n }\n\n /**\n * Add a child visual element to our set of children.\n */\n addVariantChild(child: VisualElement) {\n const closestVariantNode = this.getClosestVariantNode()\n if (closestVariantNode) {\n closestVariantNode.variantChildren &&\n closestVariantNode.variantChildren.add(child)\n return () => closestVariantNode.variantChildren!.delete(child)\n }\n }\n\n /**\n * Add a motion value and bind it to this visual element.\n */\n addValue(key: string, value: MotionValue) {\n // Remove existing value if it exists\n const existingValue = this.values.get(key)\n\n if (value !== existingValue) {\n if (existingValue) this.removeValue(key)\n this.bindToMotionValue(key, value)\n this.values.set(key, value)\n this.latestValues[key] = value.get()\n }\n }\n\n /**\n * Remove a motion value and unbind any active subscriptions.\n */\n removeValue(key: string) {\n this.values.delete(key)\n const unsubscribe = this.valueSubscriptions.get(key)\n if (unsubscribe) {\n unsubscribe()\n this.valueSubscriptions.delete(key)\n }\n delete this.latestValues[key]\n this.removeValueFromRenderState(key, this.renderState)\n }\n\n /**\n * Check whether we have a motion value for this key\n */\n hasValue(key: string) {\n return this.values.has(key)\n }\n\n /**\n * Get a motion value for this key. If called with a default\n * value, we'll create one if none exists.\n */\n getValue(key: string): MotionValue | undefined\n getValue(key: string, defaultValue: AnyResolvedKeyframe | null): MotionValue\n getValue(\n key: string,\n defaultValue?: AnyResolvedKeyframe | null\n ): MotionValue | undefined {\n if (this.props.values && this.props.values[key]) {\n return this.props.values[key]\n }\n\n let value = this.values.get(key)\n\n if (value === undefined && defaultValue !== undefined) {\n value = motionValue(\n defaultValue === null ? undefined : defaultValue,\n { owner: this }\n )\n this.addValue(key, value)\n }\n\n return value\n }\n\n /**\n * If we're trying to animate to a previously unencountered value,\n * we need to check for it in our state and as a last resort read it\n * directly from the instance (which might have performance implications).\n */\n readValue(key: string, target?: AnyResolvedKeyframe | null) {\n let value =\n this.latestValues[key] !== undefined || !this.current\n ? this.latestValues[key]\n : this.getBaseTargetFromProps(this.props, key) ??\n this.readValueFromInstance(this.current, key, this.options)\n\n if (value !== undefined && value !== null) {\n if (\n typeof value === \"string\" &&\n (isNumericalString(value) || isZeroValueString(value))\n ) {\n // If this is a number read as a string, ie \"0\" or \"200\", convert it to a number\n value = parseFloat(value)\n } else if (!findValueType(value) && complex.test(target)) {\n value = getAnimatableNone(key, target as string)\n }\n\n this.setBaseTarget(key, isMotionValue(value) ? value.get() : value)\n }\n\n return isMotionValue(value) ? value.get() : value\n }\n\n /**\n * Set the base target to later animate back to. This is currently\n * only hydrated on creation and when we first read a value.\n */\n setBaseTarget(key: string, value: AnyResolvedKeyframe) {\n this.baseTarget[key] = value\n }\n\n /**\n * Find the base target for a value thats been removed from all animation\n * props.\n */\n getBaseTarget(key: string): ResolvedValues[string] | undefined | null {\n const { initial } = this.props\n\n let valueFromInitial: ResolvedValues[string] | undefined | null\n\n if (typeof initial === \"string\" || typeof initial === \"object\") {\n const variant = resolveVariantFromProps(\n this.props,\n initial as any,\n this.presenceContext?.custom\n )\n if (variant) {\n valueFromInitial = variant[\n key as keyof typeof variant\n ] as string\n }\n }\n\n /**\n * If this value still exists in the current initial variant, read that.\n */\n if (initial && valueFromInitial !== undefined) {\n return valueFromInitial\n }\n\n /**\n * Alternatively, if this VisualElement config has defined a getBaseTarget\n * so we can read the value from an alternative source, try that.\n */\n const target = this.getBaseTargetFromProps(this.props, key)\n if (target !== undefined && !isMotionValue(target)) return target\n\n /**\n * If the value was initially defined on initial, but it doesn't any more,\n * return undefined. Otherwise return the value as initially read from the DOM.\n */\n return this.initialValues[key] !== undefined &&\n valueFromInitial === undefined\n ? undefined\n : this.baseTarget[key]\n }\n\n on<EventName extends keyof VisualElementEventCallbacks>(\n eventName: EventName,\n callback: VisualElementEventCallbacks[EventName]\n ) {\n if (!this.events[eventName]) {\n this.events[eventName] = new SubscriptionManager()\n }\n\n return this.events[eventName].add(callback)\n }\n\n notify<EventName extends keyof VisualElementEventCallbacks>(\n eventName: EventName,\n ...args: any\n ) {\n if (this.events[eventName]) {\n this.events[eventName].notify(...args)\n }\n }\n\n scheduleRenderMicrotask() {\n microtask.render(this.render)\n }\n}\n","import { isMotionValue } from \"../../value/utils/is-motion-value\"\nimport type { MotionValue } from \"../../value\"\nimport type { AnyResolvedKeyframe } from \"../../animation/types\"\nimport { DOMKeyframesResolver } from \"../../animation/keyframes/DOMKeyframesResolver\"\nimport type { MotionNodeOptions } from \"../../node/types\"\nimport type { DOMVisualElementOptions } from \"./types\"\nimport type { HTMLRenderState } from \"../html/types\"\nimport { VisualElement, MotionStyle } from \"../VisualElement\"\n\nexport abstract class DOMVisualElement<\n Instance extends HTMLElement | SVGElement = HTMLElement,\n State extends HTMLRenderState = HTMLRenderState,\n Options extends DOMVisualElementOptions = DOMVisualElementOptions\n> extends VisualElement<Instance, State, Options> {\n sortInstanceNodePosition(a: Instance, b: Instance): number {\n /**\n * compareDocumentPosition returns a bitmask, by using the bitwise &\n * we're returning true if 2 in that bitmask is set to true. 2 is set\n * to true if b preceeds a.\n */\n return a.compareDocumentPosition(b) & 2 ? 1 : -1\n }\n\n getBaseTargetFromProps(\n props: MotionNodeOptions,\n key: string\n ): AnyResolvedKeyframe | MotionValue<any> | undefined {\n const style = (props as MotionNodeOptions & { style?: MotionStyle }).style\n return style ? (style[key] as string) : undefined\n }\n\n removeValueFromRenderState(\n key: string,\n { vars, style }: HTMLRenderState\n ): void {\n delete vars[key]\n delete style[key]\n }\n\n KeyframeResolver = DOMKeyframesResolver\n\n childSubscription?: VoidFunction\n handleChildMotionValue() {\n if (this.childSubscription) {\n this.childSubscription()\n delete this.childSubscription\n }\n\n const { children } = this.props as MotionNodeOptions & { children?: MotionValue | any }\n if (isMotionValue(children)) {\n this.childSubscription = children.on(\"change\", (latest) => {\n if (this.current) {\n this.current.textContent = `${latest}`\n }\n })\n }\n }\n}\n","import type { VisualElement } from \"./VisualElement\"\n\n/**\n * Feature base class for extending VisualElement functionality.\n * Features are plugins that can be mounted/unmounted to add behavior\n * like gestures, animations, or layout tracking.\n */\nexport abstract class Feature<T extends any = any> {\n isMounted = false\n\n node: VisualElement<T>\n\n constructor(node: VisualElement<T>) {\n this.node = node\n }\n\n abstract mount(): void\n\n abstract unmount(): void\n\n update(): void {}\n}\n","import { BoundingBox, Box, TransformPoint } from \"motion-utils\"\n\n/**\n * Bounding boxes tend to be defined as top, left, right, bottom. For various operations\n * it's easier to consider each axis individually. This function returns a bounding box\n * as a map of single-axis min/max values.\n */\nexport function convertBoundingBoxToBox({\n top,\n left,\n right,\n bottom,\n}: BoundingBox): Box {\n return {\n x: { min: left, max: right },\n y: { min: top, max: bottom },\n }\n}\n\nexport function convertBoxToBoundingBox({ x, y }: Box): BoundingBox {\n return { top: y.min, right: x.max, bottom: y.max, left: x.min }\n}\n\n/**\n * Applies a TransformPoint function to a bounding box. TransformPoint is usually a function\n * provided by Framer to allow measured points to be corrected for device scaling. This is used\n * when measuring DOM elements and DOM event points.\n */\nexport function transformBoxPoints(\n point: BoundingBox,\n transformPoint?: TransformPoint\n) {\n if (!transformPoint) return point\n const topLeft = transformPoint({ x: point.left, y: point.top })\n const bottomRight = transformPoint({ x: point.right, y: point.bottom })\n\n return {\n top: topLeft.y,\n left: topLeft.x,\n bottom: bottomRight.y,\n right: bottomRight.x,\n }\n}\n","import { TransformPoint } from \"motion-utils\"\nimport {\n convertBoundingBoxToBox,\n transformBoxPoints,\n} from \"../geometry/conversion\"\nimport { translateAxis } from \"../geometry/delta-apply\"\n\nexport function measureViewportBox(\n instance: HTMLElement,\n transformPoint?: TransformPoint\n) {\n return convertBoundingBoxToBox(\n transformBoxPoints(instance.getBoundingClientRect(), transformPoint)\n )\n}\n\nexport function measurePageBox(\n element: HTMLElement,\n rootProjectionNode: any,\n transformPagePoint?: TransformPoint\n) {\n const viewportBox = measureViewportBox(element, transformPagePoint)\n const { scroll } = rootProjectionNode\n\n if (scroll) {\n translateAxis(viewportBox.x, scroll.offset.x)\n translateAxis(viewportBox.y, scroll.offset.y)\n }\n\n return viewportBox\n}\n","import { getValueAsType } from \"../../../value/types/utils/get-as-type\"\nimport { numberValueTypes } from \"../../../value/types/maps/number\"\nimport { transformPropOrder } from \"../../utils/keys-transform\"\nimport { ResolvedValues } from \"../../types\"\nimport { HTMLRenderState } from \"../types\"\nimport type { MotionNodeOptions } from \"../../../node/types\"\n\nconst translateAlias = {\n x: \"translateX\",\n y: \"translateY\",\n z: \"translateZ\",\n transformPerspective: \"perspective\",\n}\n\nconst numTransforms = transformPropOrder.length\n\n/**\n * Build a CSS transform style from individual x/y/scale etc properties.\n *\n * This outputs with a default order of transforms/scales/rotations, this can be customised by\n * providing a transformTemplate function.\n */\nexport function buildTransform(\n latestValues: ResolvedValues,\n transform: HTMLRenderState[\"transform\"],\n transformTemplate?: MotionNodeOptions[\"transformTemplate\"]\n) {\n // The transform string we're going to build into.\n let transformString = \"\"\n let transformIsDefault = true\n\n /**\n * Loop over all possible transforms in order, adding the ones that\n * are present to the transform string.\n */\n for (let i = 0; i < numTransforms; i++) {\n const key = transformPropOrder[i] as keyof typeof translateAlias\n const value = latestValues[key]\n\n if (value === undefined) continue\n\n let valueIsDefault = true\n if (typeof value === \"number\") {\n valueIsDefault = value === (key.startsWith(\"scale\") ? 1 : 0)\n } else {\n const parsed = parseFloat(value)\n valueIsDefault = key.startsWith(\"scale\") ? parsed === 1 : parsed === 0\n }\n\n if (!valueIsDefault || transformTemplate) {\n const valueAsType = getValueAsType(value, numberValueTypes[key])\n\n if (!valueIsDefault) {\n transformIsDefault = false\n const transformName = translateAlias[key] || key\n transformString += `${transformName}(${valueAsType}) `\n }\n\n if (transformTemplate) {\n transform[key] = valueAsType\n }\n }\n }\n\n // `pathRotation` composes onto `rotate` as a separate additive term so\n // the user's `rotate` is never clobbered. Deliberately not a slot in\n // `transformPropOrder`.\n const pathRotation = latestValues.pathRotation\n if (pathRotation) {\n transformIsDefault = false\n transformString += `rotate(${getValueAsType(\n pathRotation,\n numberValueTypes.pathRotation\n )}) `\n }\n\n transformString = transformString.trim()\n\n // If we have a custom `transform` template, pass our transform values and\n // generated transformString to that before returning\n if (transformTemplate) {\n transformString = transformTemplate(\n transform,\n transformIsDefault ? \"\" : transformString\n )\n } else if (transformIsDefault) {\n transformString = \"none\"\n }\n\n return transformString\n}\n","import { getValueAsType } from \"../../../value/types/utils/get-as-type\"\nimport { numberValueTypes } from \"../../../value/types/maps/number\"\nimport { transformProps } from \"../../utils/keys-transform\"\nimport { isCSSVariableName } from \"../../../animation/utils/is-css-variable\"\nimport { ResolvedValues } from \"../../types\"\nimport { HTMLRenderState } from \"../types\"\nimport { buildTransform } from \"./build-transform\"\nimport type { MotionNodeOptions } from \"../../../node/types\"\n\nexport function buildHTMLStyles(\n state: HTMLRenderState,\n latestValues: ResolvedValues,\n transformTemplate?: MotionNodeOptions[\"transformTemplate\"]\n) {\n const { style, vars, transformOrigin } = state\n\n // Track whether we encounter any transform or transformOrigin values.\n let hasTransform = false\n let hasTransformOrigin = false\n\n /**\n * Loop over all our latest animated values and decide whether to handle them\n * as a style or CSS variable.\n *\n * Transforms and transform origins are kept separately for further processing.\n */\n for (const key in latestValues) {\n const value = latestValues[key]\n\n if (transformProps.has(key)) {\n // If this is a transform, flag to enable further transform processing\n hasTransform = true\n continue\n } else if (isCSSVariableName(key)) {\n vars[key] = value\n continue\n } else {\n // Convert the value to its default value type, ie 0 -> \"0px\"\n const valueAsType = getValueAsType(value, numberValueTypes[key])\n\n if (key.startsWith(\"origin\")) {\n // If this is a transform origin, flag and enable further transform-origin processing\n hasTransformOrigin = true\n transformOrigin[key as keyof typeof transformOrigin] =\n valueAsType\n } else {\n style[key] = valueAsType\n }\n }\n }\n\n if (!latestValues.transform) {\n if (hasTransform || transformTemplate) {\n style.transform = buildTransform(\n latestValues,\n state.transform,\n transformTemplate\n )\n } else if (style.transform) {\n /**\n * If we have previously created a transform but currently don't have any,\n * reset transform style to none.\n */\n style.transform = \"none\"\n }\n }\n\n /**\n * Build a transformOrigin style. Uses the same defaults as the browser for\n * undefined origins.\n */\n if (hasTransformOrigin) {\n const {\n originX = \"50%\",\n originY = \"50%\",\n originZ = 0,\n } = transformOrigin\n style.transformOrigin = `${originX} ${originY} ${originZ}`\n }\n}\n","import type { MotionStyle } from \"../../VisualElement\"\nimport { HTMLRenderState } from \"../types\"\n\nexport function renderHTML(\n element: HTMLElement,\n { style, vars }: HTMLRenderState,\n styleProp?: MotionStyle,\n projection?: any\n) {\n const elementStyle = element.style\n\n let key: string\n for (key in style) {\n // CSSStyleDeclaration has [index: number]: string; in the types, so we use that as key type.\n elementStyle[key as unknown as number] = style[key] as string\n }\n\n // Write projection styles directly to element style\n projection?.applyProjectionStyles(elementStyle, styleProp)\n\n for (key in vars) {\n // Loop over any CSS variables and assign those.\n // They can only be assigned using `setProperty`.\n elementStyle.setProperty(key, vars[key] as string)\n }\n}\n","import { px } from \"../../value/types/numbers/units\"\nimport type { Axis } from \"motion-utils\"\nimport type { ScaleCorrectorDefinition } from \"./types\"\n\nexport function pixelsToPercent(pixels: number, axis: Axis): number {\n if (axis.max === axis.min) return 0\n return (pixels / (axis.max - axis.min)) * 100\n}\n\n/**\n * We always correct borderRadius as a percentage rather than pixels to reduce paints.\n * For example, if you are projecting a box that is 100px wide with a 10px borderRadius\n * into a box that is 200px wide with a 20px borderRadius, that is actually a 10%\n * borderRadius in both states. If we animate between the two in pixels that will trigger\n * a paint each time. If we animate between the two in percentage we'll avoid a paint.\n */\nexport const correctBorderRadius: ScaleCorrectorDefinition = {\n correct: (latest, node) => {\n if (!node.target) return latest\n\n /**\n * If latest is a string, if it's a percentage we can return immediately as it's\n * going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number.\n */\n if (typeof latest === \"string\") {\n if (px.test(latest)) {\n latest = parseFloat(latest)\n } else {\n return latest\n }\n }\n\n /**\n * If latest is a number, it's a pixel value. We use the current viewportBox to calculate that\n * pixel value as a percentage of each axis\n */\n const x = pixelsToPercent(latest, node.target.x)\n const y = pixelsToPercent(latest, node.target.y)\n\n return `${x}% ${y}%`\n },\n}\n","import { complex } from \"../../value/types/complex\"\nimport { mixNumber } from \"../../utils/mix/number\"\nimport type { ScaleCorrectorDefinition } from \"./types\"\n\nexport const correctBoxShadow: ScaleCorrectorDefinition = {\n correct: (latest: string, { treeScale, projectionDelta }) => {\n const original = latest\n const shadow = complex.parse(latest)\n\n // TODO: Doesn't support multiple shadows\n if (shadow.length > 5) return original\n\n const template = complex.createTransformer(latest)\n const offset = typeof shadow[0] !== \"number\" ? 1 : 0\n\n // Calculate the overall context scale\n const xScale = projectionDelta!.x.scale * treeScale!.x\n const yScale = projectionDelta!.y.scale * treeScale!.y\n\n // Scale x/y\n ;(shadow[0 + offset] as number) /= xScale\n ;(shadow[1 + offset] as number) /= yScale\n\n /**\n * Ideally we'd correct x and y scales individually, but because blur and\n * spread apply to both we have to take a scale average and apply that instead.\n * We could potentially improve the outcome of this by incorporating the ratio between\n * the two scales.\n */\n const averageScale = mixNumber(xScale, yScale, 0.5)\n\n // Blur\n if (typeof shadow[2 + offset] === \"number\")\n (shadow[2 + offset] as number) /= averageScale\n\n // Spread\n if (typeof shadow[3 + offset] === \"number\")\n (shadow[3 + offset] as number) /= averageScale\n\n return template(shadow)\n },\n}\n","import { isCSSVariableName } from \"../../animation/utils/is-css-variable\"\nimport { 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 scaleCorrectors: 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\nexport function addScaleCorrector(correctors: ScaleCorrectorMap) {\n for (const key in correctors) {\n scaleCorrectors[key] = correctors[key]\n if (isCSSVariableName(key)) {\n scaleCorrectors[key].isCSSVariable = true\n }\n }\n}\n","import { transformProps } from \"./keys-transform\"\nimport type { MotionNodeOptions } from \"../../node/types\"\nimport {\n scaleCorrectors,\n addScaleCorrector,\n} from \"../../projection/styles/scale-correction\"\n\nexport { scaleCorrectors, addScaleCorrector }\n\nexport function isForcedMotionValue(\n key: string,\n { layout, layoutId }: MotionNodeOptions\n) {\n return (\n transformProps.has(key) ||\n key.startsWith(\"origin\") ||\n ((layout || layoutId !== undefined) &&\n (!!scaleCorrectors[key] || key === \"opacity\"))\n )\n}\n","import { isMotionValue } from \"../../../value/utils/is-motion-value\"\nimport type { MotionNodeOptions } from \"../../../node/types\"\nimport { isForcedMotionValue } from \"../../utils/is-forced-motion-value\"\nimport type { VisualElement } from \"../../VisualElement\"\n\nexport function scrapeMotionValuesFromProps(\n props: MotionNodeOptions,\n prevProps: MotionNodeOptions,\n visualElement?: VisualElement\n) {\n const style = (props as any).style\n const prevStyle = (prevProps as any)?.style\n const newValues: { [key: string]: any } = {}\n\n if (!style) return newValues\n\n for (const key in style) {\n if (\n isMotionValue(style[key]) ||\n (prevStyle && isMotionValue(prevStyle[key])) ||\n isForcedMotionValue(key, props) ||\n visualElement?.getValue(key)?.liveStyle !== undefined\n ) {\n newValues[key] = style[key]\n }\n }\n\n return newValues\n}\n","import type { Box } from \"motion-utils\"\nimport type { AnyResolvedKeyframe } from \"../../animation/types\"\nimport { isCSSVariableName } from \"../../animation/utils/is-css-variable\"\nimport type { MotionNodeOptions } from \"../../node/types\"\nimport { transformProps } from \"../utils/keys-transform\"\nimport {\n defaultTransformValue,\n readTransformValue,\n} from \"../dom/parse-transform\"\nimport { measureViewportBox } from \"../../projection/utils/measure\"\nimport { DOMVisualElement } from \"../dom/DOMVisualElement\"\nimport type { DOMVisualElementOptions } from \"../dom/types\"\nimport type { ResolvedValues, MotionConfigContextProps } from \"../types\"\nimport type { VisualElement } from \"../VisualElement\"\nimport { HTMLRenderState } from \"./types\"\nimport { buildHTMLStyles } from \"./utils/build-styles\"\nimport { renderHTML } from \"./utils/render\"\nimport { scrapeMotionValuesFromProps } from \"./utils/scrape-motion-values\"\n\nexport function getComputedStyle(element: HTMLElement) {\n return window.getComputedStyle(element)\n}\n\nexport class HTMLVisualElement extends DOMVisualElement<\n HTMLElement,\n HTMLRenderState,\n DOMVisualElementOptions\n> {\n type = \"html\"\n\n readValueFromInstance(\n instance: HTMLElement,\n key: string\n ): AnyResolvedKeyframe | null | undefined {\n if (transformProps.has(key)) {\n return this.projection?.isProjecting\n ? defaultTransformValue(key)\n : readTransformValue(instance, key)\n } else {\n const computedStyle = getComputedStyle(instance)\n const value =\n (isCSSVariableName(key)\n ? computedStyle.getPropertyValue(key)\n : computedStyle[key as keyof typeof computedStyle]) || 0\n\n return typeof value === \"string\" ? value.trim() : (value as number)\n }\n }\n\n measureInstanceViewportBox(\n instance: HTMLElement,\n { transformPagePoint }: MotionNodeOptions & Partial<MotionConfigContextProps>\n ): Box {\n return measureViewportBox(instance, transformPagePoint)\n }\n\n build(\n renderState: HTMLRenderState,\n latestValues: ResolvedValues,\n props: MotionNodeOptions\n ) {\n buildHTMLStyles(renderState, latestValues, props.transformTemplate)\n }\n\n scrapeMotionValuesFromProps(\n props: MotionNodeOptions,\n prevProps: MotionNodeOptions,\n visualElement: VisualElement\n ) {\n return scrapeMotionValuesFromProps(props, prevProps, visualElement)\n }\n\n renderInstance = renderHTML\n}\n","import { ResolvedValues } from \"../../types\"\n\nconst dashKeys = {\n offset: \"stroke-dashoffset\",\n array: \"stroke-dasharray\",\n}\n\nconst camelKeys = {\n offset: \"strokeDashoffset\",\n array: \"strokeDasharray\",\n}\n\n/**\n * Build SVG path properties. Uses the path's measured length to convert\n * our custom pathLength, pathSpacing and pathOffset into stroke-dashoffset\n * and stroke-dasharray attributes.\n *\n * This function is mutative to reduce per-frame GC.\n *\n * Note: We use unitless values for stroke-dasharray and stroke-dashoffset\n * because Safari incorrectly scales px values when the page is zoomed.\n */\nexport function buildSVGPath(\n attrs: ResolvedValues,\n length: number,\n spacing = 1,\n offset = 0,\n useDashCase: boolean = true\n): void {\n // Normalise path length by setting SVG attribute pathLength to 1\n attrs.pathLength = 1\n\n // We use dash case when setting attributes directly to the DOM node and camel case\n // when defining props on a React component.\n const keys = useDashCase ? dashKeys : camelKeys\n\n // Build the dash offset (unitless to avoid Safari zoom bug)\n attrs[keys.offset] = `${-offset}`\n\n // Build the dash array (unitless to avoid Safari zoom bug)\n attrs[keys.array] = `${length} ${spacing}`\n}\n","import type { MotionNodeOptions } from \"../../../node/types\"\nimport { buildHTMLStyles } from \"../../html/utils/build-styles\"\nimport { ResolvedValues } from \"../../types\"\nimport { SVGRenderState } from \"../types\"\nimport { buildSVGPath } from \"./path\"\n\n/**\n * CSS Motion Path properties that should remain as CSS styles on SVG elements.\n */\nconst cssMotionPathProperties = [\n \"offsetDistance\",\n \"offsetPath\",\n \"offsetRotate\",\n \"offsetAnchor\",\n]\n\n/**\n * Build SVG visual attributes, like cx and style.transform\n */\nexport function buildSVGAttrs(\n state: SVGRenderState,\n {\n attrX,\n attrY,\n attrScale,\n pathLength,\n pathSpacing = 1,\n pathOffset = 0,\n // This is object creation, which we try to avoid per-frame.\n ...latest\n }: ResolvedValues,\n isSVGTag: boolean,\n transformTemplate?: MotionNodeOptions[\"transformTemplate\"],\n styleProp?: Record<string, any>\n) {\n buildHTMLStyles(state, latest, transformTemplate)\n\n /**\n * For svg tags we just want to make sure viewBox is animatable and treat all the styles\n * as normal HTML tags.\n */\n if (isSVGTag) {\n if (state.style.viewBox) {\n state.attrs.viewBox = state.style.viewBox\n }\n return\n }\n\n state.attrs = state.style\n state.style = {}\n const { attrs, style } = state\n\n /**\n * However, we apply transforms as CSS transforms.\n * So if we detect a transform, transformOrigin we take it from attrs and copy it into style.\n */\n if (attrs.transform) {\n style.transform = attrs.transform\n delete attrs.transform\n }\n if (style.transform || attrs.transformOrigin) {\n style.transformOrigin = attrs.transformOrigin ?? \"50% 50%\"\n delete attrs.transformOrigin\n }\n\n if (style.transform) {\n /**\n * SVG's element transform-origin uses its own median as a reference.\n * Therefore, transformBox becomes a fill-box\n */\n style.transformBox = (styleProp?.transformBox as string) ?? \"fill-box\"\n delete attrs.transformBox\n }\n\n for (const key of cssMotionPathProperties) {\n if (attrs[key] !== undefined) {\n style[key] = attrs[key]\n delete attrs[key]\n }\n }\n\n // Render attrX/attrY/attrScale as attributes\n if (attrX !== undefined) attrs.x = attrX\n if (attrY !== undefined) attrs.y = attrY\n if (attrScale !== undefined) attrs.scale = attrScale\n\n // Build SVG path if one has been defined\n if (pathLength !== undefined) {\n buildSVGPath(\n attrs,\n pathLength as number,\n pathSpacing as number,\n pathOffset as number,\n false\n )\n }\n}\n","/**\n * A set of attribute names that are always read/written as camel case.\n */\nexport const camelCaseAttributes = new Set([\n \"baseFrequency\",\n \"diffuseConstant\",\n \"kernelMatrix\",\n \"kernelUnitLength\",\n \"keySplines\",\n \"keyTimes\",\n \"limitingConeAngle\",\n \"markerHeight\",\n \"markerWidth\",\n \"numOctaves\",\n \"targetX\",\n \"targetY\",\n \"surfaceScale\",\n \"specularConstant\",\n \"specularExponent\",\n \"stdDeviation\",\n \"tableValues\",\n \"viewBox\",\n \"gradientTransform\",\n \"pathLength\",\n \"startOffset\",\n \"textLength\",\n \"lengthAdjust\",\n])\n","export const isSVGTag = (tag: unknown) =>\n typeof tag === \"string\" && tag.toLowerCase() === \"svg\"\n","import type { MotionStyle } from \"../../VisualElement\"\nimport { camelToDash } from \"../../dom/utils/camel-to-dash\"\nimport { renderHTML } from \"../../html/utils/render\"\nimport { SVGRenderState } from \"../types\"\nimport { camelCaseAttributes } from \"./camel-case-attrs\"\n\nexport function renderSVG(\n element: SVGElement,\n renderState: SVGRenderState,\n _styleProp?: MotionStyle,\n projection?: any\n) {\n renderHTML(element as any, renderState, undefined, projection)\n\n for (const key in renderState.attrs) {\n element.setAttribute(\n !camelCaseAttributes.has(key) ? camelToDash(key) : key,\n renderState.attrs[key] as string\n )\n }\n}\n","import { isMotionValue } from \"../../../value/utils/is-motion-value\"\nimport type { MotionNodeOptions } from \"../../../node/types\"\nimport { transformPropOrder } from \"../../utils/keys-transform\"\nimport { scrapeMotionValuesFromProps as scrapeHTMLMotionValuesFromProps } from \"../../html/utils/scrape-motion-values\"\nimport type { VisualElement } from \"../../VisualElement\"\n\nexport function scrapeMotionValuesFromProps(\n props: MotionNodeOptions,\n prevProps: MotionNodeOptions,\n visualElement?: VisualElement\n) {\n const newValues = scrapeHTMLMotionValuesFromProps(\n props,\n prevProps,\n visualElement\n )\n\n for (const key in props) {\n if (\n isMotionValue(props[key as keyof typeof props]) ||\n isMotionValue(prevProps[key as keyof typeof prevProps])\n ) {\n const targetKey =\n transformPropOrder.indexOf(key) !== -1\n ? \"attr\" + key.charAt(0).toUpperCase() + key.substring(1)\n : key\n\n newValues[targetKey] = props[key as keyof typeof props]\n }\n }\n\n return newValues\n}\n","import type { AnyResolvedKeyframe } from \"../../animation/types\"\nimport type { MotionValue } from \"../../value\"\nimport type { MotionNodeOptions } from \"../../node/types\"\nimport { transformProps } from \"../utils/keys-transform\"\nimport { getDefaultValueType } from \"../../value/types/maps/defaults\"\nimport { createBox } from \"../../projection/geometry/models\"\nimport { DOMVisualElement } from \"../dom/DOMVisualElement\"\nimport type { DOMVisualElementOptions } from \"../dom/types\"\nimport { camelToDash } from \"../dom/utils/camel-to-dash\"\nimport type { ResolvedValues } from \"../types\"\nimport type { VisualElement, MotionStyle } from \"../VisualElement\"\nimport { SVGRenderState } from \"./types\"\nimport { buildSVGAttrs } from \"./utils/build-attrs\"\nimport { camelCaseAttributes } from \"./utils/camel-case-attrs\"\nimport { isSVGTag } from \"./utils/is-svg-tag\"\nimport { renderSVG } from \"./utils/render\"\nimport { scrapeMotionValuesFromProps } from \"./utils/scrape-motion-values\"\nexport class SVGVisualElement extends DOMVisualElement<\n SVGElement,\n SVGRenderState,\n DOMVisualElementOptions\n> {\n type = \"svg\"\n\n isSVGTag = false\n\n getBaseTargetFromProps(\n props: MotionNodeOptions,\n key: string\n ): AnyResolvedKeyframe | MotionValue<any> | undefined {\n return props[key as keyof MotionNodeOptions]\n }\n\n readValueFromInstance(instance: SVGElement, key: string) {\n if (transformProps.has(key)) {\n const defaultType = getDefaultValueType(key)\n return defaultType ? defaultType.default || 0 : 0\n }\n key = !camelCaseAttributes.has(key) ? camelToDash(key) : key\n return instance.getAttribute(key)\n }\n\n measureInstanceViewportBox = createBox\n\n scrapeMotionValuesFromProps(\n props: MotionNodeOptions,\n prevProps: MotionNodeOptions,\n visualElement: VisualElement\n ) {\n return scrapeMotionValuesFromProps(props, prevProps, visualElement)\n }\n\n build(\n renderState: SVGRenderState,\n latestValues: ResolvedValues,\n props: MotionNodeOptions\n ) {\n buildSVGAttrs(\n renderState,\n latestValues,\n this.isSVGTag,\n props.transformTemplate,\n (props as any).style\n )\n }\n\n renderInstance(\n instance: SVGElement,\n renderState: SVGRenderState,\n styleProp?: MotionStyle | undefined,\n projection?: any\n ): void {\n renderSVG(instance, renderState, styleProp, projection)\n }\n\n mount(instance: SVGElement) {\n this.isSVGTag = isSVGTag(instance.tagName)\n super.mount(instance)\n }\n}\n","import { isVariantLabel } from \"./is-variant-label\"\nimport { variantProps } from \"./variant-props\"\n\nconst numVariantProps = variantProps.length\n\ntype VariantStateContext = {\n initial?: string | string[]\n animate?: string | string[]\n exit?: string | string[]\n whileHover?: string | string[]\n whileDrag?: string | string[]\n whileFocus?: string | string[]\n whileTap?: string | string[]\n}\n\n/**\n * Get variant context from a visual element's parent chain.\n * Uses `any` type for visualElement to avoid circular dependencies.\n */\nexport function getVariantContext(\n visualElement?: any\n): undefined | VariantStateContext {\n if (!visualElement) return undefined\n\n if (!visualElement.isControllingVariants) {\n const context = visualElement.parent\n ? getVariantContext(visualElement.parent) || {}\n : {}\n if (visualElement.props.initial !== undefined) {\n context.initial = visualElement.props.initial as any\n }\n return context\n }\n\n const context: VariantStateContext = {}\n for (let i = 0; i < numVariantProps; i++) {\n const name = variantProps[i] as keyof typeof context\n const prop = visualElement.props[name]\n\n if (isVariantLabel(prop) || prop === false) {\n ;(context as any)[name] = prop\n }\n }\n\n return context\n}\n","export function shallowCompare(next: any[], prev: any[] | null) {\n if (!Array.isArray(prev)) return false\n\n const prevLength = prev.length\n\n if (prevLength !== next.length) return false\n\n for (let i = 0; i < prevLength; i++) {\n if (prev[i] !== next[i]) return false\n }\n\n return true\n}\n","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 { getVariantContext } from \"./get-variant-context\"\nimport { isAnimationControls } from \"./is-animation-controls\"\nimport { isKeyframesTarget } from \"./is-keyframes-target\"\nimport { isVariantLabel } from \"./is-variant-label\"\nimport { 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\nconst reversePriorityOrder = [...variantPriorityOrder].reverse()\nconst numAnimationTypes = variantPriorityOrder.length\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\nfunction createAnimateFunction(visualElement: any): AnimateFunction {\n return (animations: DefinitionAndOptions[]) => {\n return Promise.all(\n animations.map(({ animation, options }) =>\n animateVisualElement(visualElement, animation, options)\n )\n )\n }\n}\n\nexport function createAnimationState(visualElement: any): AnimationState {\n let animate = createAnimateFunction(visualElement)\n let state = createState()\n let isInitialRender = true\n /**\n * Track whether the animation state has been reset (e.g. via StrictMode\n * double-invocation or Suspense unmount/remount). On the first\n * animateChanges() call after a reset we need to behave like the initial\n * render for variant-inheritance checks, even though isInitialRender is\n * already false.\n */\n let wasReset = false\n\n /**\n * This function will be used to reduce the animation definitions for\n * each active animation type into an object of resolved values for it.\n */\n const buildResolvedTypeValues =\n (type: AnimationType) =>\n (\n acc: { [key: string]: any },\n definition: string | TargetAndTransition | undefined\n ) => {\n const resolved = resolveVariant(\n visualElement,\n definition,\n type === \"exit\"\n ? visualElement.presenceContext?.custom\n : undefined\n )\n\n if (resolved) {\n const { transition, transitionEnd, ...target } = resolved\n acc = { ...acc, ...target, ...transitionEnd }\n }\n\n return acc\n }\n\n /**\n * This just allows us to inject mocked animation functions\n * @internal\n */\n function setAnimateFunction(\n makeAnimator: (visualElement: any) => AnimateFunction\n ) {\n animate = makeAnimator(visualElement)\n }\n\n /**\n * When we receive new props, we need to:\n * 1. Create a list of protected keys for each type. This is a directory of\n * value keys that are currently being \"handled\" by types of a higher priority\n * so that whenever an animation is played of a given type, these values are\n * protected from being animated.\n * 2. Determine if an animation type needs animating.\n * 3. Determine if any values have been removed from a type and figure out\n * what to animate those to.\n */\n function animateChanges(changedActiveType?: AnimationType) {\n const { props } = visualElement\n const context = getVariantContext(visualElement.parent) || {}\n\n /**\n * A list of animations that we'll build into as we iterate through the animation\n * types. This will get executed at the end of the function.\n */\n const animations: DefinitionAndOptions[] = []\n\n /**\n * Keep track of which values have been removed. Then, as we hit lower priority\n * animation types, we can check if they contain removed values and animate to that.\n */\n const removedKeys = new Set<string>()\n\n /**\n * A dictionary of all encountered keys. This is an object to let us build into and\n * copy it without iteration. Each time we hit an animation type we set its protected\n * keys - the keys its not allowed to animate - to the latest version of this object.\n */\n let encounteredKeys: { [key: string]: any } = {}\n\n /**\n * If a variant has been removed at a given index, and this component is controlling\n * variant animations, we want to ensure lower-priority variants are forced to animate.\n */\n let removedVariantIndex = Infinity\n\n /**\n * Iterate through all animation types in reverse priority order. For each, we want to\n * detect which values it's handling and whether or not they've changed (and therefore\n * need to be animated). If any values have been removed, we want to detect those in\n * lower priority props and flag for animation.\n */\n for (let i = 0; i < numAnimationTypes; i++) {\n const type = reversePriorityOrder[i]\n const typeState = state[type]\n const prop =\n props[type] !== undefined\n ? props[type]\n : context[type as keyof typeof context]\n const propIsVariant = isVariantLabel(prop)\n\n /**\n * If this type has *just* changed isActive status, set activeDelta\n * to that status. Otherwise set to null.\n */\n const activeDelta =\n type === changedActiveType ? typeState.isActive : null\n\n if (activeDelta === false) removedVariantIndex = i\n\n /**\n * If this prop is an inherited variant, rather than been set directly on the\n * component itself, we want to make sure we allow the parent to trigger animations.\n *\n * TODO: Can probably change this to a !isControllingVariants check\n */\n let isInherited =\n prop === context[type as keyof typeof context] &&\n prop !== props[type] &&\n propIsVariant\n\n if (\n isInherited &&\n (isInitialRender || wasReset) &&\n visualElement.manuallyAnimateOnMount\n ) {\n isInherited = false\n }\n\n /**\n * Set all encountered keys so far as the protected keys for this type. This will\n * be any key that has been animated or otherwise handled by active, higher-priortiy types.\n */\n typeState.protectedKeys = { ...encounteredKeys }\n\n // Check if we can skip analysing this prop early\n if (\n // If it isn't active and hasn't *just* been set as inactive\n (!typeState.isActive && activeDelta === null) ||\n // If we didn't and don't have any defined prop for this animation type\n (!prop && !typeState.prevProp) ||\n // Or if the prop doesn't define an animation\n isAnimationControls(prop) ||\n typeof prop === \"boolean\"\n ) {\n continue\n }\n\n /**\n * If exit is already active and wasn't just activated, skip\n * re-processing to prevent interrupting running exit animations.\n * Re-resolving exit with a changed custom value can start new\n * value animations that stop the originals, leaving the exit\n * animation promise unresolved and the component stuck in the DOM.\n */\n if (type === \"exit\" && typeState.isActive && activeDelta !== true) {\n if (typeState.prevResolvedValues) {\n encounteredKeys = {\n ...encounteredKeys,\n ...typeState.prevResolvedValues,\n }\n }\n continue\n }\n\n /**\n * As we go look through the values defined on this type, if we detect\n * a changed value or a value that was removed in a higher priority, we set\n * this to true and add this prop to the animation list.\n */\n const variantDidChange = checkVariantsDidChange(\n typeState.prevProp,\n prop\n )\n\n let shouldAnimateType =\n variantDidChange ||\n // If we're making this variant active, we want to always make it active\n (type === changedActiveType &&\n typeState.isActive &&\n !isInherited &&\n propIsVariant) ||\n // If we removed a higher-priority variant (i is in reverse order)\n (i > removedVariantIndex && propIsVariant)\n\n let handledRemovedValues = false\n\n /**\n * As animations can be set as variant lists, variants or target objects, we\n * coerce everything to an array if it isn't one already\n */\n const definitionList = Array.isArray(prop) ? prop : [prop]\n\n /**\n * Build an object of all the resolved values. We'll use this in the subsequent\n * animateChanges calls to determine whether a value has changed.\n */\n let resolvedValues = definitionList.reduce(\n buildResolvedTypeValues(type),\n {}\n )\n\n if (activeDelta === false) resolvedValues = {}\n\n /**\n * Now we need to loop through all the keys in the prev prop and this prop,\n * and decide:\n * 1. If the value has changed, and needs animating\n * 2. If it has been removed, and needs adding to the removedKeys set\n * 3. If it has been removed in a higher priority type and needs animating\n * 4. If it hasn't been removed in a higher priority but hasn't changed, and\n * needs adding to the type's protectedKeys list.\n */\n const { prevResolvedValues = {} } = typeState\n\n const allKeys = {\n ...prevResolvedValues,\n ...resolvedValues,\n }\n const markToAnimate = (key: string) => {\n shouldAnimateType = true\n if (removedKeys.has(key)) {\n handledRemovedValues = true\n removedKeys.delete(key)\n }\n typeState.needsAnimating[key] = true\n\n const motionValue = visualElement.getValue(key)\n if (motionValue) motionValue.liveStyle = false\n }\n\n for (const key in allKeys) {\n const next = resolvedValues[key]\n const prev = prevResolvedValues[key]\n\n // If we've already handled this we can just skip ahead\n if (encounteredKeys.hasOwnProperty(key)) continue\n\n /**\n * If the value has changed, we probably want to animate it.\n */\n let valueHasChanged = false\n if (isKeyframesTarget(next) && isKeyframesTarget(prev)) {\n valueHasChanged =\n !shallowCompare(next, prev) || variantDidChange\n } else {\n valueHasChanged = next !== prev\n }\n\n if (valueHasChanged) {\n if (next !== undefined && next !== null) {\n // If next is defined and doesn't equal prev, it needs animating\n markToAnimate(key)\n } else {\n // If it's undefined, it's been removed.\n removedKeys.add(key)\n }\n } else if (next !== undefined && removedKeys.has(key)) {\n /**\n * If next hasn't changed and it isn't undefined, we want to check if it's\n * been removed by a higher priority\n */\n markToAnimate(key)\n } else {\n /**\n * If it hasn't changed, we add it to the list of protected values\n * to ensure it doesn't get animated.\n */\n typeState.protectedKeys[key] = true\n }\n }\n\n /**\n * Update the typeState so next time animateChanges is called we can compare the\n * latest prop and resolvedValues to these.\n */\n typeState.prevProp = prop\n typeState.prevResolvedValues = resolvedValues\n\n if (typeState.isActive) {\n encounteredKeys = { ...encounteredKeys, ...resolvedValues }\n }\n\n if (\n (isInitialRender || wasReset) &&\n visualElement.blockInitialAnimation\n ) {\n shouldAnimateType = false\n }\n\n /**\n * If this is an inherited prop we want to skip this animation\n * unless the inherited variants haven't changed on this render.\n */\n const willAnimateViaParent = isInherited && variantDidChange\n const needsAnimating = !willAnimateViaParent || handledRemovedValues\n if (shouldAnimateType && needsAnimating) {\n animations.push(\n ...definitionList.map((animation) => {\n const options: VisualElementAnimationOptions = { type }\n\n /**\n * If we're performing the initial animation, but we're not\n * rendering at the same time as the variant-controlling parent,\n * we want to use the parent's transition to calculate the stagger.\n */\n if (\n typeof animation === \"string\" &&\n (isInitialRender || wasReset) &&\n !willAnimateViaParent &&\n visualElement.manuallyAnimateOnMount &&\n visualElement.parent\n ) {\n const { parent } = visualElement\n const parentVariant = resolveVariant(\n parent,\n animation\n )\n\n if (parent.enteringChildren && parentVariant) {\n const { delayChildren } =\n parentVariant.transition || {}\n options.delay = calcChildStagger(\n parent.enteringChildren,\n visualElement,\n delayChildren\n )\n }\n }\n\n return {\n animation: animation as AnimationDefinition,\n options,\n }\n })\n )\n }\n }\n\n /**\n * If there are some removed value that haven't been dealt with,\n * we need to create a new animation that falls back either to the value\n * defined in the style prop, or the last read value.\n */\n if (removedKeys.size) {\n const fallbackAnimation: TargetAndTransition = {}\n\n /**\n * If the initial prop contains a transition we can use that, otherwise\n * allow the animation function to use the visual element's default.\n */\n if (typeof props.initial !== \"boolean\") {\n const initialTransition = resolveVariant(\n visualElement,\n Array.isArray(props.initial)\n ? props.initial[0]\n : props.initial\n )\n\n if (initialTransition && initialTransition.transition) {\n fallbackAnimation.transition = initialTransition.transition\n }\n }\n\n removedKeys.forEach((key) => {\n const fallbackTarget = visualElement.getBaseTarget(key)\n\n const motionValue = visualElement.getValue(key)\n if (motionValue) motionValue.liveStyle = true\n\n // @ts-expect-error - @mattgperry to figure if we should do something here\n fallbackAnimation[key] = fallbackTarget ?? null\n })\n\n animations.push({ animation: fallbackAnimation })\n }\n\n let shouldAnimate = Boolean(animations.length)\n\n if (\n isInitialRender &&\n (props.initial === false || props.initial === props.animate) &&\n !visualElement.manuallyAnimateOnMount\n ) {\n shouldAnimate = false\n }\n\n isInitialRender = false\n wasReset = false\n return shouldAnimate ? animate(animations) : Promise.resolve()\n }\n\n /**\n * Change whether a certain animation type is active.\n */\n function setActive(type: AnimationType, isActive: boolean) {\n // If the active state hasn't changed, we can safely do nothing here\n if (state[type].isActive === isActive) return Promise.resolve()\n\n // Propagate active change to children\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 keyof typeof state].protectedKeys = {}\n }\n\n return animations\n }\n\n return {\n animateChanges,\n setActive,\n setAnimateFunction,\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 createTypeState(isActive = false): AnimationTypeState {\n return {\n isActive,\n protectedKeys: {},\n needsAnimating: {},\n prevResolvedValues: {},\n }\n}\n\nfunction createState() {\n return {\n animate: createTypeState(true),\n whileInView: createTypeState(),\n whileHover: createTypeState(),\n whileTap: createTypeState(),\n whileDrag: createTypeState(),\n whileFocus: createTypeState(),\n exit: createTypeState(),\n }\n}\n","export function addDomEvent(\n target: EventTarget,\n eventName: string,\n handler: EventListener,\n options: AddEventListenerOptions = { passive: true }\n) {\n target.addEventListener(eventName, handler, options)\n\n return () => target.removeEventListener(eventName, handler, options)\n}\n","import type { AnyResolvedKeyframe } from \"../../animation/types\"\nimport { isMotionValue } from \"./is-motion-value\"\nimport type { MotionValue } from \"../index\"\n\n/**\n * If the provided value is a MotionValue, this returns the actual value, otherwise just the value itself\n */\nexport function resolveMotionValue(\n value?: AnyResolvedKeyframe | MotionValue\n): AnyResolvedKeyframe {\n return isMotionValue(value) ? value.get() : value\n}\n","\"use client\"\n\nimport type { Transition } from \"motion-dom\"\nimport { TransformPoint } from \"motion-utils\"\nimport { createContext } from \"react\"\n\nexport type ReducedMotionConfig = \"always\" | \"never\" | \"user\"\n\n/**\n * @public\n */\nexport interface MotionConfigContext {\n /**\n * Internal, exported only for usage in Framer\n */\n transformPagePoint: TransformPoint\n\n /**\n * Internal. Determines whether this is a static context ie the Framer canvas. If so,\n * it'll disable all dynamic functionality.\n */\n isStatic: boolean\n\n /**\n * Defines a new default transition for the entire tree.\n *\n * @public\n */\n transition?: Transition\n\n /**\n * If true, will respect the device prefersReducedMotion setting by switching\n * transform animations off.\n *\n * @public\n */\n reducedMotion?: ReducedMotionConfig\n\n /**\n * A custom `nonce` attribute used when wanting to enforce a Content Security Policy (CSP).\n * For more details see:\n * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src#unsafe_inline_styles\n *\n * @public\n */\n nonce?: string\n\n /**\n * If true, all animations will be skipped and values will be set instantly.\n * Useful for E2E tests and visual regression testing.\n *\n * @public\n */\n skipAnimations?: boolean\n\n}\n\n/**\n * @public\n */\nexport const MotionConfigContext = createContext<MotionConfigContext>({\n transformPagePoint: (p) => p,\n isStatic: false,\n reducedMotion: \"never\",\n})\n","\"use client\"\n\nimport { createContext } from \"react\"\nimport { CreateVisualElement } from \"../render/types\"\n\nexport interface LazyContextProps {\n renderer?: CreateVisualElement\n strict: boolean\n}\n\nexport const LazyContext = createContext<LazyContextProps>({ strict: false })\n","import { getFeatureDefinitions, setFeatureDefinitions } from \"motion-dom\"\nimport { MotionProps } from \"../types\"\nimport { FeatureDefinitions } from \"./types\"\n\nconst featureProps = {\n animation: [\n \"animate\",\n \"variants\",\n \"whileHover\",\n \"whileTap\",\n \"exit\",\n \"whileInView\",\n \"whileFocus\",\n \"whileDrag\",\n ],\n exit: [\"exit\"],\n drag: [\"drag\", \"dragControls\"],\n focus: [\"whileFocus\"],\n hover: [\"whileHover\", \"onHoverStart\", \"onHoverEnd\"],\n tap: [\"whileTap\", \"onTap\", \"onTapStart\", \"onTapCancel\"],\n pan: [\"onPan\", \"onPanStart\", \"onPanSessionStart\", \"onPanEnd\"],\n inView: [\"whileInView\", \"onViewportEnter\", \"onViewportLeave\"],\n layout: [\"layout\", \"layoutId\"],\n}\n\nlet isInitialized = false\n\n/**\n * Initialize feature definitions with isEnabled checks.\n * This must be called before any motion components are rendered.\n */\nexport function initFeatureDefinitions() {\n if (isInitialized) return\n\n const initialFeatureDefinitions: Partial<FeatureDefinitions> = {}\n\n for (const key in featureProps) {\n initialFeatureDefinitions[\n key as keyof typeof initialFeatureDefinitions\n ] = {\n isEnabled: (props: MotionProps) =>\n featureProps[key as keyof typeof featureProps].some(\n (name: string) => !!props[name as keyof typeof props]\n ),\n }\n }\n\n setFeatureDefinitions(initialFeatureDefinitions)\n isInitialized = true\n}\n\n/**\n * Get the current feature definitions, initializing if needed.\n */\nexport function getInitializedFeatureDefinitions(): Partial<FeatureDefinitions> {\n initFeatureDefinitions()\n return getFeatureDefinitions()\n}\n","import { setFeatureDefinitions } from \"motion-dom\"\nimport { getInitializedFeatureDefinitions } from \"./definitions\"\nimport { FeaturePackages } from \"./types\"\n\nexport function loadFeatures(features: FeaturePackages) {\n const featureDefinitions = getInitializedFeatureDefinitions()\n\n for (const key in features) {\n featureDefinitions[key as keyof typeof featureDefinitions] = {\n ...featureDefinitions[key as keyof typeof featureDefinitions],\n ...features[key as keyof typeof features],\n } as any\n }\n\n setFeatureDefinitions(featureDefinitions)\n}\n","\"use client\"\n\nimport { useEffect, useRef, useState } from \"react\"\nimport { LazyContext } from \"../../context/LazyContext\"\nimport { loadFeatures } from \"../../motion/features/load-features\"\nimport { FeatureBundle, LazyFeatureBundle } from \"../../motion/features/types\"\nimport { CreateVisualElement } from \"../../render/types\"\nimport { LazyProps } from \"./types\"\n\n/**\n * Used in conjunction with the `m` component to reduce bundle size.\n *\n * `m` is a version of the `motion` component that only loads functionality\n * critical for the initial render.\n *\n * `LazyMotion` can then be used to either synchronously or asynchronously\n * load animation and gesture support.\n *\n * ```jsx\n * // Synchronous loading\n * import { LazyMotion, m, domAnimation } from \"framer-motion\"\n *\n * function App() {\n * return (\n * <LazyMotion features={domAnimation}>\n * <m.div animate={{ scale: 2 }} />\n * </LazyMotion>\n * )\n * }\n *\n * // Asynchronous loading\n * import { LazyMotion, m } from \"framer-motion\"\n *\n * function App() {\n * return (\n * <LazyMotion features={() => import('./path/to/domAnimation')}>\n * <m.div animate={{ scale: 2 }} />\n * </LazyMotion>\n * )\n * }\n * ```\n *\n * @public\n */\nexport function LazyMotion({ children, features, strict = false }: LazyProps) {\n const [, setIsLoaded] = useState(!isLazyBundle(features))\n const loadedRenderer = useRef<undefined | CreateVisualElement>(undefined)\n\n /**\n * If this is a synchronous load, load features immediately\n */\n if (!isLazyBundle(features)) {\n const { renderer, ...loadedFeatures } = features\n loadedRenderer.current = renderer\n loadFeatures(loadedFeatures)\n }\n\n useEffect(() => {\n if (isLazyBundle(features)) {\n features().then(({ renderer, ...loadedFeatures }) => {\n loadFeatures(loadedFeatures)\n loadedRenderer.current = renderer\n setIsLoaded(true)\n })\n }\n }, [])\n\n return (\n <LazyContext.Provider\n value={{ renderer: loadedRenderer.current, strict }}\n >\n {children}\n </LazyContext.Provider>\n )\n}\n\nfunction isLazyBundle(\n features: FeatureBundle | LazyFeatureBundle\n): features is LazyFeatureBundle {\n return typeof features === \"function\"\n}\n","import { MotionProps } from \"../types\"\n\n/**\n * A list of all valid MotionProps.\n *\n * @privateRemarks\n * This doesn't throw if a `MotionProp` name is missing - it should.\n */\nconst validMotionProps = new Set<keyof MotionProps>([\n \"animate\",\n \"exit\",\n \"variants\",\n \"initial\",\n \"style\",\n \"values\",\n \"variants\",\n \"transition\",\n \"transformTemplate\",\n \"custom\",\n \"inherit\",\n \"onBeforeLayoutMeasure\",\n \"onAnimationStart\",\n \"onAnimationComplete\",\n \"onUpdate\",\n \"onDragStart\",\n \"onDrag\",\n \"onDragEnd\",\n \"onMeasureDragConstraints\",\n \"onDirectionLock\",\n \"onDragTransitionEnd\",\n \"_dragX\",\n \"_dragY\",\n \"onHoverStart\",\n \"onHoverEnd\",\n \"onViewportEnter\",\n \"onViewportLeave\",\n \"globalTapTarget\",\n \"propagate\",\n \"ignoreStrict\",\n \"viewport\",\n])\n\n/**\n * Check whether a prop name is a valid `MotionProp` key.\n *\n * @param key - Name of the property to check\n * @returns `true` is key is a valid `MotionProp`.\n *\n * @public\n */\nexport function isValidMotionProp(key: string) {\n return (\n key.startsWith(\"while\") ||\n (key.startsWith(\"drag\") && key !== \"draggable\") ||\n key.startsWith(\"layout\") ||\n key.startsWith(\"onTap\") ||\n key.startsWith(\"onPan\") ||\n key.startsWith(\"onLayout\") ||\n validMotionProps.has(key as keyof MotionProps)\n )\n}\n","import { isMotionValue } from \"motion-dom\"\nimport type { MotionProps } from \"../../../motion/types\"\nimport { isValidMotionProp } from \"../../../motion/utils/valid-prop\"\n\nlet shouldForward = (key: string) => !isValidMotionProp(key)\n\nexport type IsValidProp = (key: string) => boolean\n\nexport function loadExternalIsValidProp(isValidProp?: IsValidProp) {\n if (typeof isValidProp !== \"function\") return\n\n // Explicitly filter our events\n shouldForward = (key: string) =>\n key.startsWith(\"on\") ? !isValidMotionProp(key) : isValidProp(key)\n}\n\n/**\n * Emotion and Styled Components both allow users to pass through arbitrary props to their components\n * to dynamically generate CSS. They both use the `@emotion/is-prop-valid` package to determine which\n * of these should be passed to the underlying DOM node.\n *\n * However, when styling a Motion component `styled(motion.div)`, both packages pass through *all* props\n * as it's seen as an arbitrary component rather than a DOM node. Motion only allows arbitrary props\n * passed through the `custom` prop so it doesn't *need* the payload or computational overhead of\n * `@emotion/is-prop-valid`, however to fix this problem we need to use it.\n *\n * By making it an optionalDependency we can offer this functionality only in the situations where it's\n * actually required.\n */\ntry {\n /**\n * We attempt to import this package but require won't be defined in esm environments, in that case\n * isPropValid will have to be provided via `MotionContext`. In a 6.0.0 this should probably be removed\n * in favour of explicit injection.\n *\n * String concatenation prevents bundlers like webpack (e.g. Storybook)\n * from statically resolving this optional dependency at build time.\n */\n const emotionPkg = \"@emotion/is-prop-\" + \"valid\"\n loadExternalIsValidProp(require(emotionPkg).default)\n} catch {\n // We don't need to actually do anything here - the fallback is the existing `isPropValid`.\n}\n\nexport function filterProps(\n props: MotionProps,\n isDom: boolean,\n forwardMotionProps: boolean\n) {\n const filteredProps: MotionProps = {}\n\n for (const key in props) {\n /**\n * values is considered a valid prop by Emotion, so if it's present\n * this will be rendered out to the DOM unless explicitly filtered.\n *\n * We check the type as it could be used with the `feColorMatrix`\n * element, which we support.\n */\n if (key === \"values\" && typeof props.values === \"object\") continue\n\n if (isMotionValue(props[key as keyof typeof props])) continue\n\n if (\n shouldForward(key) ||\n (forwardMotionProps === true && isValidMotionProp(key)) ||\n (!isDom && !isValidMotionProp(key)) ||\n // If trying to use native HTML drag events, forward drag listeners\n (props[\"draggable\" as keyof MotionProps] &&\n key.startsWith(\"onDrag\"))\n ) {\n filteredProps[key as keyof MotionProps] =\n props[key as keyof MotionProps]\n }\n }\n\n return filteredProps\n}\n","\"use client\"\n\nimport type { VisualElement } from \"motion-dom\"\nimport { createContext } from \"react\"\n\nexport interface MotionContextProps<Instance = unknown> {\n visualElement?: VisualElement<Instance>\n initial?: false | string | string[]\n animate?: string | string[]\n}\n\nexport const MotionContext = /* @__PURE__ */ createContext<MotionContextProps>(\n {}\n)\n","import { isControllingVariants, isVariantLabel } from \"motion-dom\"\nimport type { MotionContextProps } from \".\"\nimport { MotionProps } from \"../../motion/types\"\n\nexport function getCurrentTreeVariants(\n props: MotionProps,\n context: MotionContextProps\n): MotionContextProps {\n if (isControllingVariants(props)) {\n const { initial, animate } = props\n return {\n initial:\n initial === false || isVariantLabel(initial)\n ? (initial as any)\n : undefined,\n animate: isVariantLabel(animate) ? animate : undefined,\n }\n }\n return props.inherit !== false ? context : {}\n}\n","\"use client\"\n\nimport { useContext, useMemo } from \"react\"\nimport { MotionContext, type MotionContextProps } from \".\"\nimport { MotionProps } from \"../../motion/types\"\nimport { getCurrentTreeVariants } from \"./utils\"\n\nexport function useCreateMotionContext<Instance>(\n props: MotionProps\n): MotionContextProps<Instance> {\n const { initial, animate } = getCurrentTreeVariants(\n props,\n useContext(MotionContext)\n )\n\n return useMemo(\n () => ({ initial, animate }),\n [variantLabelsAsDependency(initial), variantLabelsAsDependency(animate)]\n )\n}\n\nfunction variantLabelsAsDependency(\n prop: undefined | string | string[] | boolean\n) {\n return Array.isArray(prop) ? prop.join(\" \") : prop\n}\n","import { HTMLRenderState } from \"../types\"\n\nexport const createHtmlRenderState = (): HTMLRenderState => ({\n style: {},\n transform: {},\n transformOrigin: {},\n vars: {},\n})\n","\"use client\"\n\nimport { AnyResolvedKeyframe, buildHTMLStyles, isForcedMotionValue, isMotionValue, MotionValue } from \"motion-dom\"\nimport { HTMLProps, useMemo } from \"react\"\nimport { MotionProps } from \"../../motion/types\"\nimport { ResolvedValues } from \"../types\"\nimport { createHtmlRenderState } from \"./utils/create-render-state\"\n\nexport function copyRawValuesOnly(\n target: ResolvedValues,\n source: { [key: string]: AnyResolvedKeyframe | MotionValue },\n props: MotionProps\n) {\n for (const key in source) {\n if (!isMotionValue(source[key]) && !isForcedMotionValue(key, props)) {\n target[key] = source[key] as AnyResolvedKeyframe\n }\n }\n}\n\nfunction useInitialMotionValues(\n { transformTemplate }: MotionProps,\n visualState: ResolvedValues\n) {\n return useMemo(() => {\n const state = createHtmlRenderState()\n\n buildHTMLStyles(state, visualState, transformTemplate)\n\n return Object.assign({}, state.vars, state.style)\n }, [visualState])\n}\n\nfunction useStyle(\n props: MotionProps,\n visualState: ResolvedValues\n): ResolvedValues {\n const styleProp = props.style || {}\n const style = {}\n\n /**\n * Copy non-Motion Values straight into style\n */\n copyRawValuesOnly(style, styleProp as any, props)\n\n Object.assign(style, useInitialMotionValues(props, visualState))\n\n return style\n}\n\nexport function useHTMLProps(\n props: MotionProps & HTMLProps<HTMLElement>,\n visualState: ResolvedValues\n) {\n // The `any` isn't ideal but it is the type of createElement props argument\n const htmlProps: any = {}\n const style = useStyle(props, visualState)\n\n if (props.drag && props.dragListener !== false) {\n // Disable the ghost element when a user drags\n htmlProps.draggable = false\n\n // Disable text selection\n style.userSelect =\n style.WebkitUserSelect =\n style.WebkitTouchCallout =\n \"none\"\n\n // Disable scrolling on the draggable direction\n style.touchAction =\n props.drag === true\n ? \"none\"\n : `pan-${props.drag === \"x\" ? \"y\" : \"x\"}`\n }\n\n if (\n props.tabIndex === undefined &&\n (props.onTap || props.onTapStart || props.whileTap)\n ) {\n htmlProps.tabIndex = 0\n }\n\n htmlProps.style = style\n\n return htmlProps\n}\n","import { createHtmlRenderState } from \"../../html/utils/create-render-state\"\nimport { SVGRenderState } from \"../types\"\n\nexport const createSvgRenderState = (): SVGRenderState => ({\n ...createHtmlRenderState(),\n attrs: {},\n})\n","\"use client\"\n\nimport { buildSVGAttrs, isSVGTag } from \"motion-dom\"\nimport { useMemo } from \"react\"\nimport { MotionProps } from \"../../motion/types\"\nimport { copyRawValuesOnly } from \"../html/use-props\"\nimport { ResolvedValues } from \"../types\"\nimport { createSvgRenderState } from \"./utils/create-render-state\"\n\nexport function useSVGProps(\n props: MotionProps,\n visualState: ResolvedValues,\n _isStatic: boolean,\n Component: string | React.ComponentType<React.PropsWithChildren<unknown>>\n) {\n const visualProps = useMemo(() => {\n const state = createSvgRenderState()\n\n buildSVGAttrs(\n state,\n visualState,\n isSVGTag(Component),\n props.transformTemplate,\n props.style\n )\n\n return {\n ...state.attrs,\n style: { ...state.style },\n }\n }, [visualState])\n\n if (props.style) {\n const rawStyles = {}\n copyRawValuesOnly(rawStyles, props.style as any, props)\n visualProps.style = { ...rawStyles, ...visualProps.style }\n }\n\n return visualProps\n}\n","/**\n * We keep these listed separately as we use the lowercase tag names as part\n * of the runtime bundle to detect SVG components\n */\nexport const lowercaseSVGElements = [\n \"animate\",\n \"circle\",\n \"defs\",\n \"desc\",\n \"ellipse\",\n \"g\",\n \"image\",\n \"line\",\n \"filter\",\n \"marker\",\n \"mask\",\n \"metadata\",\n \"path\",\n \"pattern\",\n \"polygon\",\n \"polyline\",\n \"rect\",\n \"stop\",\n \"switch\",\n \"symbol\",\n \"svg\",\n \"text\",\n \"tspan\",\n \"use\",\n \"view\",\n]\n","import * as React from \"react\"\nimport { lowercaseSVGElements } from \"../../svg/lowercase-elements\"\n\nexport function isSVGComponent(Component: string | React.ComponentType<any>) {\n if (\n /**\n * If it's not a string, it's a custom React component. Currently we only support\n * HTML custom React components.\n */\n typeof Component !== \"string\" ||\n /**\n * If it contains a dash, the element is a custom HTML webcomponent.\n */\n Component.includes(\"-\")\n ) {\n return false\n } else if (\n /**\n * If it's in our list of lowercase SVG tags, it's an SVG component\n */\n lowercaseSVGElements.indexOf(Component) > -1 ||\n /**\n * If it contains a capital letter, it's an SVG component\n */\n /[A-Z]/u.test(Component)\n ) {\n return true\n }\n\n return false\n}\n","\"use client\"\n\nimport { isMotionValue } from \"motion-dom\"\nimport { Fragment, createElement, useMemo } from \"react\"\nimport { MotionProps } from \"../../motion/types\"\nimport { VisualState } from \"../../motion/utils/use-visual-state\"\nimport { HTMLRenderState } from \"../html/types\"\nimport { useHTMLProps } from \"../html/use-props\"\nimport { SVGRenderState } from \"../svg/types\"\nimport { useSVGProps } from \"../svg/use-props\"\nimport { DOMMotionComponents } from \"./types\"\nimport { filterProps } from \"./utils/filter-props\"\nimport { isSVGComponent } from \"./utils/is-svg-component\"\n\nexport function useRender<\n Props = {},\n TagName extends keyof DOMMotionComponents | string = \"div\"\n>(\n Component: TagName | string | React.ComponentType<Props>,\n props: MotionProps,\n ref: React.Ref<HTMLElement | SVGElement>,\n {\n latestValues,\n }: VisualState<HTMLElement | SVGElement, HTMLRenderState | SVGRenderState>,\n isStatic: boolean,\n forwardMotionProps: boolean = false,\n isSVG?: boolean\n) {\n const useVisualProps =\n (isSVG ?? isSVGComponent(Component)) ? useSVGProps : useHTMLProps\n\n const visualProps = useVisualProps(\n props as any,\n latestValues,\n isStatic,\n Component as any\n )\n const filteredProps = filterProps(\n props,\n typeof Component === \"string\",\n forwardMotionProps\n )\n const elementProps =\n Component !== Fragment ? { ...filteredProps, ...visualProps, ref } : {}\n\n /**\n * If component has been handed a motion value as its child,\n * memoise its initial value and render that. Subsequent updates\n * will be handled by the onChange handler\n */\n const { children } = props\n const renderedChildren = useMemo(\n () => (isMotionValue(children) ? children.get() : children),\n [children]\n )\n\n return createElement<any>(Component, {\n ...elementProps,\n children: renderedChildren,\n })\n}\n","\"use client\"\n\nimport {\n AnyResolvedKeyframe,\n isAnimationControls,\n isControllingVariants as checkIsControllingVariants,\n isVariantNode as checkIsVariantNode,\n ResolvedValues,\n resolveVariantFromProps,\n} from \"motion-dom\"\nimport { useContext } from \"react\"\nimport { MotionContext, MotionContextProps } from \"../../context/MotionContext\"\nimport {\n PresenceContext,\n type PresenceContextProps,\n} from \"../../context/PresenceContext\"\nimport { ScrapeMotionValuesFromProps } from \"../../render/types\"\nimport { useConstant } from \"../../utils/use-constant\"\nimport { resolveMotionValue } from \"motion-dom\"\nimport { MotionProps } from \"../types\"\n\nexport interface VisualState<Instance, RenderState> {\n renderState: RenderState\n latestValues: ResolvedValues\n onMount?: (instance: Instance) => void\n}\n\nexport type UseVisualState<Instance, RenderState> = (\n props: MotionProps,\n isStatic: boolean\n) => VisualState<Instance, RenderState>\n\nexport interface UseVisualStateConfig<RenderState> {\n scrapeMotionValuesFromProps: ScrapeMotionValuesFromProps\n createRenderState: () => RenderState\n}\n\nfunction makeState<I, RS>(\n {\n scrapeMotionValuesFromProps,\n createRenderState,\n }: UseVisualStateConfig<RS>,\n props: MotionProps,\n context: MotionContextProps,\n presenceContext: PresenceContextProps | null\n) {\n const state: VisualState<I, RS> = {\n latestValues: makeLatestValues(\n props,\n context,\n presenceContext,\n scrapeMotionValuesFromProps\n ),\n renderState: createRenderState(),\n }\n\n return state\n}\n\nfunction makeLatestValues(\n props: MotionProps,\n context: MotionContextProps,\n presenceContext: PresenceContextProps | null,\n scrapeMotionValues: ScrapeMotionValuesFromProps\n) {\n const values: ResolvedValues = {}\n\n const motionValues = scrapeMotionValues(props, {})\n for (const key in motionValues) {\n values[key] = resolveMotionValue(motionValues[key])\n }\n\n let { initial, animate } = props\n const isControllingVariants = checkIsControllingVariants(props)\n const isVariantNode = checkIsVariantNode(props)\n\n if (\n context &&\n isVariantNode &&\n !isControllingVariants &&\n props.inherit !== false\n ) {\n if (initial === undefined) initial = context.initial\n if (animate === undefined) animate = context.animate\n }\n\n let isInitialAnimationBlocked = presenceContext\n ? presenceContext.initial === false\n : false\n isInitialAnimationBlocked = isInitialAnimationBlocked || initial === false\n\n const variantToSet = isInitialAnimationBlocked ? animate : initial\n\n if (\n variantToSet &&\n typeof variantToSet !== \"boolean\" &&\n !isAnimationControls(variantToSet)\n ) {\n const list = Array.isArray(variantToSet) ? variantToSet : [variantToSet]\n for (let i = 0; i < list.length; i++) {\n const resolved = resolveVariantFromProps(props, list[i] as any)\n if (resolved) {\n const { transitionEnd, transition, ...target } = resolved\n for (const key in target) {\n let valueTarget = target[key as keyof typeof target]\n\n if (Array.isArray(valueTarget)) {\n /**\n * Take final keyframe if the initial animation is blocked because\n * we want to initialise at the end of that blocked animation.\n */\n const index = isInitialAnimationBlocked\n ? valueTarget.length - 1\n : 0\n valueTarget = valueTarget[index] as any\n }\n\n if (valueTarget !== null) {\n values[key] = valueTarget as AnyResolvedKeyframe\n }\n }\n for (const key in transitionEnd) {\n values[key] = transitionEnd[\n key as keyof typeof transitionEnd\n ] as AnyResolvedKeyframe\n }\n }\n }\n }\n\n return values\n}\n\nexport const makeUseVisualState =\n <I, RS>(config: UseVisualStateConfig<RS>): UseVisualState<I, RS> =>\n (props: MotionProps, isStatic: boolean): VisualState<I, RS> => {\n const context = useContext(MotionContext)\n const presenceContext = useContext(PresenceContext)\n const make = () => makeState(config, props, context, presenceContext)\n\n return isStatic ? make() : useConstant(make)\n }\n","\"use client\"\n\nimport { scrapeHTMLMotionValuesFromProps } from \"motion-dom\"\nimport { makeUseVisualState } from \"../../motion/utils/use-visual-state\"\nimport { createHtmlRenderState } from \"./utils/create-render-state\"\n\nexport const useHTMLVisualState = /*@__PURE__*/ makeUseVisualState({\n scrapeMotionValuesFromProps: scrapeHTMLMotionValuesFromProps,\n createRenderState: createHtmlRenderState,\n})\n","\"use client\"\n\nimport { scrapeSVGMotionValuesFromProps } from \"motion-dom\"\nimport { makeUseVisualState } from \"../../motion/utils/use-visual-state\"\nimport { createSvgRenderState } from \"./utils/create-render-state\"\n\nexport const useSVGVisualState = /*@__PURE__*/ makeUseVisualState({\n scrapeMotionValuesFromProps: scrapeSVGMotionValuesFromProps,\n createRenderState: createSvgRenderState,\n})\n","export const motionComponentSymbol = Symbol.for(\"motionComponentSymbol\")\n","\"use client\"\n\nimport type { VisualElement } from \"motion-dom\"\nimport * as React from \"react\"\nimport { useCallback, useInsertionEffect, useRef } from \"react\"\nimport { VisualState } from \"./use-visual-state\"\n\n/**\n * Creates a ref function that, when called, hydrates the provided\n * external ref and VisualElement.\n */\nexport function useMotionRef<Instance, RenderState>(\n visualState: VisualState<Instance, RenderState>,\n visualElement?: VisualElement<Instance> | null,\n externalRef?: React.Ref<Instance>\n): React.Ref<Instance> {\n /**\n * Store externalRef in a ref to avoid including it in the useCallback\n * dependency array. Including externalRef in dependencies causes issues\n * with libraries like Radix UI that create new callback refs on each render\n * when using asChild - this would cause the callback to be recreated,\n * triggering element remounts and breaking AnimatePresence exit animations.\n */\n const externalRefContainer = useRef(externalRef)\n useInsertionEffect(() => {\n externalRefContainer.current = externalRef\n })\n\n // Store cleanup function returned by callback refs (React 19 feature)\n const refCleanup = useRef<(() => void) | null>(null)\n\n return useCallback(\n (instance: Instance) => {\n if (instance) {\n visualState.onMount?.(instance)\n }\n\n if (visualElement) {\n instance ? visualElement.mount(instance) : visualElement.unmount()\n }\n\n const ref = externalRefContainer.current\n if (typeof ref === \"function\") {\n if (instance) {\n const cleanup = ref(instance)\n if (typeof cleanup === \"function\") {\n refCleanup.current = cleanup\n }\n } else if (refCleanup.current) {\n refCleanup.current()\n refCleanup.current = null\n } else {\n ref(instance)\n }\n } else if (ref) {\n ;(ref as React.MutableRefObject<Instance>).current = instance\n }\n },\n [visualElement]\n )\n}\n","import { MutableRefObject } from \"./safe-react-types\"\n\nexport function isRefObject<E = any>(ref: any): ref is MutableRefObject<E> {\n return (\n ref &&\n typeof ref === \"object\" &&\n Object.prototype.hasOwnProperty.call(ref, \"current\")\n )\n}\n","\"use client\"\n\nimport {\n optimizedAppearDataAttribute,\n type HTMLRenderState,\n type SVGRenderState,\n type VisualElement,\n} from \"motion-dom\"\nimport * as React from \"react\"\nimport { useContext, useEffect, useInsertionEffect, useRef } from \"react\"\nimport { LazyContext } from \"../../context/LazyContext\"\nimport { MotionConfigContext } from \"../../context/MotionConfigContext\"\nimport { MotionContext } from \"../../context/MotionContext\"\nimport { PresenceContext } from \"../../context/PresenceContext\"\nimport {\n InitialPromotionConfig,\n SwitchLayoutGroupContext,\n} from \"../../context/SwitchLayoutGroupContext\"\nimport { MotionProps } from \"../../motion/types\"\nimport type { IProjectionNode } from \"motion-dom\"\nimport { DOMMotionComponents } from \"../../render/dom/types\"\nimport { CreateVisualElement } from \"../../render/types\"\nimport { isRefObject } from \"../../utils/is-ref-object\"\nimport { useIsomorphicLayoutEffect } from \"../../utils/use-isomorphic-effect\"\nimport { VisualState } from \"./use-visual-state\"\n\nexport function useVisualElement<\n Props,\n TagName extends keyof DOMMotionComponents | string\n>(\n Component: TagName | string | React.ComponentType<Props>,\n visualState:\n | VisualState<SVGElement, SVGRenderState>\n | VisualState<HTMLElement, HTMLRenderState>,\n props: MotionProps & Partial<MotionConfigContext>,\n createVisualElement?: CreateVisualElement<Props, TagName>,\n ProjectionNodeConstructor?: any,\n isSVG?: boolean\n): VisualElement<HTMLElement | SVGElement> | undefined {\n const { visualElement: parent } = useContext(MotionContext)\n const lazyContext = useContext(LazyContext)\n const presenceContext = useContext(PresenceContext)\n const motionConfig = useContext(MotionConfigContext)\n const reducedMotionConfig = motionConfig.reducedMotion\n const skipAnimations = motionConfig.skipAnimations\n\n const visualElementRef = useRef<VisualElement<\n HTMLElement | SVGElement\n > | null>(null)\n\n /**\n * Track whether the component has been through React's commit phase.\n * Used to detect when LazyMotion features load after the component has mounted.\n */\n const hasMountedOnce = useRef(false)\n\n /**\n * If we haven't preloaded a renderer, check to see if we have one lazy-loaded\n */\n createVisualElement =\n createVisualElement ||\n (lazyContext.renderer as CreateVisualElement<Props, TagName>)\n\n if (!visualElementRef.current && createVisualElement) {\n visualElementRef.current = createVisualElement(Component, {\n visualState,\n parent,\n props,\n presenceContext,\n blockInitialAnimation: presenceContext\n ? presenceContext.initial === false\n : false,\n reducedMotionConfig,\n skipAnimations,\n isSVG,\n })\n\n /**\n * If the component has already mounted before features loaded (e.g. via\n * LazyMotion with async feature loading), we need to force the initial\n * animation to run. Otherwise state changes that occurred before features\n * loaded will be lost and the element will snap to its final state.\n */\n if (hasMountedOnce.current && visualElementRef.current) {\n visualElementRef.current.manuallyAnimateOnMount = true\n }\n }\n\n const visualElement = visualElementRef.current\n\n /**\n * Load Motion gesture and animation features. These are rendered as renderless\n * components so each feature can optionally make use of React lifecycle methods.\n */\n const initialLayoutGroupConfig = useContext(SwitchLayoutGroupContext)\n\n if (\n visualElement &&\n !visualElement.projection &&\n ProjectionNodeConstructor &&\n (visualElement.type === \"html\" || visualElement.type === \"svg\")\n ) {\n createProjectionNode(\n visualElementRef.current!,\n props,\n ProjectionNodeConstructor,\n initialLayoutGroupConfig\n )\n }\n\n const isMounted = useRef(false)\n useInsertionEffect(() => {\n /**\n * Check the component has already mounted before calling\n * `update` unnecessarily. This ensures we skip the initial update.\n */\n if (visualElement && isMounted.current) {\n visualElement.update(props, presenceContext)\n }\n })\n\n /**\n * Cache this value as we want to know whether HandoffAppearAnimations\n * was present on initial render - it will be deleted after this.\n */\n const optimisedAppearId =\n props[optimizedAppearDataAttribute as keyof typeof props]\n const wantsHandoff = useRef(\n Boolean(optimisedAppearId) &&\n typeof window !== \"undefined\" &&\n !window.MotionHandoffIsComplete?.(optimisedAppearId) &&\n window.MotionHasOptimisedAnimation?.(optimisedAppearId)\n )\n\n useIsomorphicLayoutEffect(() => {\n /**\n * Track that this component has mounted. This is used to detect when\n * LazyMotion features load after the component has already committed.\n */\n hasMountedOnce.current = true\n\n if (!visualElement) return\n\n isMounted.current = true\n window.MotionIsMounted = true\n\n visualElement.updateFeatures()\n visualElement.scheduleRenderMicrotask()\n\n /**\n * Ideally this function would always run in a useEffect.\n *\n * However, if we have optimised appear animations to handoff from,\n * it needs to happen synchronously to ensure there's no flash of\n * incorrect styles in the event of a hydration error.\n *\n * So if we detect a situtation where optimised appear animations\n * are running, we use useLayoutEffect to trigger animations.\n */\n if (wantsHandoff.current && visualElement.animationState) {\n visualElement.animationState.animateChanges()\n }\n })\n\n useEffect(() => {\n if (!visualElement) return\n\n if (!wantsHandoff.current && visualElement.animationState) {\n visualElement.animationState.animateChanges()\n }\n\n if (wantsHandoff.current) {\n // This ensures all future calls to animateChanges() in this component will run in useEffect\n queueMicrotask(() => {\n window.MotionHandoffMarkAsComplete?.(optimisedAppearId)\n })\n\n wantsHandoff.current = false\n }\n\n /**\n * Now we've finished triggering animations for this element we\n * can wipe the enteringChildren set for the next render.\n */\n visualElement.enteringChildren = undefined\n })\n\n return visualElement!\n}\n\nfunction createProjectionNode(\n visualElement: VisualElement<any>,\n props: MotionProps,\n ProjectionNodeConstructor: any,\n initialPromotionConfig?: InitialPromotionConfig\n) {\n const {\n layoutId,\n layout,\n drag,\n dragConstraints,\n layoutScroll,\n layoutRoot,\n layoutAnchor,\n layoutCrossfade,\n } = props\n\n visualElement.projection = new ProjectionNodeConstructor(\n visualElement.latestValues,\n props[\"data-framer-portal-id\"]\n ? undefined\n : getClosestProjectingNode(visualElement.parent)\n ) as IProjectionNode\n\n visualElement.projection.setOptions({\n layoutId,\n layout,\n alwaysMeasureLayout:\n Boolean(drag) || (dragConstraints && isRefObject(dragConstraints)),\n visualElement,\n /**\n * TODO: Update options in an effect. This could be tricky as it'll be too late\n * to update by the time layout animations run.\n * We also need to fix this safeToRemove by linking it up to the one returned by usePresence,\n * ensuring it gets called if there's no potential layout animations.\n *\n */\n animationType: typeof layout === \"string\" ? layout : \"both\",\n initialPromotionConfig,\n crossfade: layoutCrossfade,\n layoutScroll,\n layoutRoot,\n layoutAnchor,\n })\n}\n\nfunction getClosestProjectingNode(\n visualElement?: VisualElement<\n unknown,\n unknown,\n { allowProjection?: boolean }\n >\n): IProjectionNode | undefined {\n if (!visualElement) return undefined\n\n return visualElement.options.allowProjection !== false\n ? visualElement.projection\n : getClosestProjectingNode(visualElement.parent)\n}\n","\"use client\"\n\nimport { invariant, warning } from \"motion-utils\"\nimport * as React from \"react\"\nimport { forwardRef, useContext } from \"react\"\nimport { LayoutGroupContext } from \"../context/LayoutGroupContext\"\nimport { LazyContext } from \"../context/LazyContext\"\nimport { MotionConfigContext } from \"../context/MotionConfigContext\"\nimport { MotionContext } from \"../context/MotionContext\"\nimport { useCreateMotionContext } from \"../context/MotionContext/create\"\nimport { DOMMotionComponents } from \"../render/dom/types\"\nimport { useRender } from \"../render/dom/use-render\"\nimport { isSVGComponent } from \"../render/dom/utils/is-svg-component\"\nimport { HTMLRenderState } from \"../render/html/types\"\nimport { useHTMLVisualState } from \"../render/html/use-html-visual-state\"\nimport { SVGRenderState } from \"../render/svg/types\"\nimport { useSVGVisualState } from \"../render/svg/use-svg-visual-state\"\nimport { CreateVisualElement } from \"../render/types\"\nimport { getInitializedFeatureDefinitions } from \"./features/definitions\"\nimport { loadFeatures } from \"./features/load-features\"\nimport { FeatureBundle, FeaturePackages } from \"./features/types\"\nimport { MotionProps } from \"./types\"\nimport { motionComponentSymbol } from \"./utils/symbol\"\nimport { useMotionRef } from \"./utils/use-motion-ref\"\nimport { useVisualElement } from \"./utils/use-visual-element\"\n\nexport interface MotionComponentConfig<\n TagName extends keyof DOMMotionComponents | string = \"div\"\n> {\n preloadedFeatures?: FeatureBundle\n createVisualElement?: CreateVisualElement\n Component: TagName | React.ComponentType<React.PropsWithChildren<unknown>>\n forwardMotionProps?: boolean\n}\n\nexport type MotionComponentProps<Props> = {\n [K in Exclude<keyof Props, keyof MotionProps>]?: Props[K]\n} & MotionProps\n\nexport type MotionComponent<T, P> = T extends keyof DOMMotionComponents\n ? DOMMotionComponents[T]\n : React.ComponentType<\n Omit<MotionComponentProps<P>, \"children\"> & {\n children?: \"children\" extends keyof P\n ? P[\"children\"] | MotionComponentProps<P>[\"children\"]\n : MotionComponentProps<P>[\"children\"]\n }\n >\n\nexport interface MotionComponentOptions {\n forwardMotionProps?: boolean\n /**\n * Specify whether the component renders an HTML or SVG element.\n * This is useful when wrapping custom SVG components that need\n * SVG-specific attribute handling (like viewBox animation).\n * By default, Motion auto-detects based on the component name,\n * but custom React components are always treated as HTML.\n */\n type?: \"html\" | \"svg\"\n}\n\n/**\n * Create a `motion` component.\n *\n * This function accepts a Component argument, which can be either a string (ie \"div\"\n * for `motion.div`), or an actual React component.\n *\n * Alongside this is a config option which provides a way of rendering the provided\n * component \"offline\", or outside the React render cycle.\n */\nexport function createMotionComponent<\n Props,\n TagName extends keyof DOMMotionComponents | string = \"div\"\n>(\n Component: TagName | string | React.ComponentType<Props>,\n { forwardMotionProps = false, type }: MotionComponentOptions = {},\n preloadedFeatures?: FeaturePackages,\n createVisualElement?: CreateVisualElement<Props, TagName>\n) {\n preloadedFeatures && loadFeatures(preloadedFeatures)\n\n /**\n * Determine whether to use SVG or HTML rendering based on:\n * 1. Explicit `type` option (highest priority)\n * 2. Auto-detection via `isSVGComponent`\n */\n const isSVG = type ? type === \"svg\" : isSVGComponent(Component)\n const useVisualState = isSVG ? useSVGVisualState : useHTMLVisualState\n\n function MotionDOMComponent(\n props: MotionComponentProps<Props>,\n externalRef?: React.Ref<HTMLElement | SVGElement>\n ) {\n /**\n * If we need to measure the element we load this functionality in a\n * separate class component in order to gain access to getSnapshotBeforeUpdate.\n */\n let MeasureLayout: undefined | React.ComponentType<MotionProps>\n\n const configAndProps = {\n ...useContext(MotionConfigContext),\n ...props,\n layoutId: useLayoutId(props),\n }\n\n const { isStatic } = configAndProps\n\n const context = useCreateMotionContext<HTMLElement | SVGElement>(props)\n\n const visualState = useVisualState(props, isStatic)\n\n if (!isStatic && typeof window !== \"undefined\") {\n useStrictMode(configAndProps, preloadedFeatures)\n\n const layoutProjection = getProjectionFunctionality(configAndProps)\n MeasureLayout = layoutProjection.MeasureLayout\n\n /**\n * Create a VisualElement for this component. A VisualElement provides a common\n * interface to renderer-specific APIs (ie DOM/Three.js etc) as well as\n * providing a way of rendering to these APIs outside of the React render loop\n * for more performant animations and interactions\n */\n context.visualElement = useVisualElement(\n Component,\n visualState,\n configAndProps,\n createVisualElement,\n layoutProjection.ProjectionNode,\n isSVG\n )\n }\n\n /**\n * The mount order and hierarchy is specific to ensure our element ref\n * is hydrated by the time features fire their effects.\n */\n return (\n <MotionContext.Provider value={context}>\n {MeasureLayout && context.visualElement ? (\n <MeasureLayout\n visualElement={context.visualElement}\n {...configAndProps}\n />\n ) : null}\n {useRender<Props, TagName>(\n Component,\n props,\n useMotionRef<\n HTMLElement | SVGElement,\n HTMLRenderState | SVGRenderState\n >(visualState, context.visualElement, externalRef),\n visualState,\n isStatic,\n forwardMotionProps,\n isSVG\n )}\n </MotionContext.Provider>\n )\n }\n\n MotionDOMComponent.displayName = `motion.${\n typeof Component === \"string\"\n ? Component\n : `create(${Component.displayName ?? Component.name ?? \"\"})`\n }`\n\n const ForwardRefMotionComponent = forwardRef(MotionDOMComponent as any)\n ;(ForwardRefMotionComponent as any)[motionComponentSymbol] = Component\n\n return ForwardRefMotionComponent as MotionComponent<TagName, Props>\n}\n\nfunction useLayoutId({ layoutId }: MotionProps) {\n const layoutGroupId = useContext(LayoutGroupContext).id\n return layoutGroupId && layoutId !== undefined\n ? layoutGroupId + \"-\" + layoutId\n : layoutId\n}\n\nfunction useStrictMode(\n configAndProps: MotionProps,\n preloadedFeatures?: FeaturePackages\n) {\n const isStrict = useContext(LazyContext).strict\n\n /**\n * If we're in development mode, check to make sure we're not rendering a motion component\n * as a child of LazyMotion, as this will break the file-size benefits of using it.\n */\n if (\n process.env.NODE_ENV !== \"production\" &&\n preloadedFeatures &&\n isStrict\n ) {\n const strictMessage =\n \"You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.\"\n configAndProps.ignoreStrict\n ? warning(false, strictMessage, \"lazy-strict-mode\")\n : invariant(false, strictMessage, \"lazy-strict-mode\")\n }\n}\n\nfunction getProjectionFunctionality(props: MotionProps) {\n const featureDefinitions = getInitializedFeatureDefinitions()\n const { drag, layout } = featureDefinitions\n\n if (!drag && !layout) return {}\n\n const combined = { ...drag, ...layout }\n\n return {\n MeasureLayout:\n drag?.isEnabled(props) || layout?.isEnabled(props)\n ? combined.MeasureLayout\n : undefined,\n ProjectionNode: combined.ProjectionNode,\n }\n}\n","import { warnOnce } from \"motion-utils\"\nimport { createMotionComponent, MotionComponentOptions } from \"../../motion\"\nimport { FeaturePackages } from \"../../motion/features/types\"\nimport { MotionProps } from \"../../motion/types\"\nimport { DOMMotionComponents } from \"../dom/types\"\nimport { CreateVisualElement } from \"../types\"\n\n/**\n * I'd rather the return type of `custom` to be implicit but this throws\n * incorrect relative paths in the exported types and API Extractor throws\n * a wobbly.\n */\ntype ComponentProps<Props> = React.PropsWithoutRef<Props & MotionProps> &\n React.RefAttributes<SVGElement | HTMLElement>\nexport type CustomDomComponent<Props> = React.ComponentType<\n ComponentProps<Props>\n>\n\ntype MotionProxy = typeof createMotionComponent &\n DOMMotionComponents & { create: typeof createMotionComponent }\n\nexport function createMotionProxy(\n preloadedFeatures?: FeaturePackages,\n createVisualElement?: CreateVisualElement<any, any>\n): MotionProxy {\n if (typeof Proxy === \"undefined\") {\n return createMotionComponent as MotionProxy\n }\n\n /**\n * A cache of generated `motion` components, e.g `motion.div`, `motion.input` etc.\n * Rather than generating them anew every render.\n */\n const componentCache = new Map<string, any>()\n\n const factory = (Component: string, options?: MotionComponentOptions) => {\n return createMotionComponent(\n Component,\n options,\n preloadedFeatures,\n createVisualElement\n )\n }\n\n /**\n * Support for deprecated`motion(Component)` pattern\n */\n const deprecatedFactoryFunction = (\n Component: string,\n options?: MotionComponentOptions\n ) => {\n if (process.env.NODE_ENV !== \"production\") {\n warnOnce(\n false,\n \"motion() is deprecated. Use motion.create() instead.\"\n )\n }\n return factory(Component, options)\n }\n\n return new Proxy(deprecatedFactoryFunction, {\n /**\n * Called when `motion` is referenced with a prop: `motion.div`, `motion.input` etc.\n * The prop name is passed through as `key` and we can use that to generate a `motion`\n * DOM component with that name.\n */\n get: (_target, key: string) => {\n if (key === \"create\") return factory\n\n /**\n * If this element doesn't exist in the component cache, create it and cache.\n */\n if (!componentCache.has(key)) {\n componentCache.set(\n key,\n createMotionComponent(\n key,\n undefined,\n preloadedFeatures,\n createVisualElement\n )\n )\n }\n\n return componentCache.get(key)!\n },\n }) as MotionProxy\n}\n","import { createMotionProxy } from \"../create-proxy\"\n\nexport const m = /*@__PURE__*/ createMotionProxy()\n","import { HTMLVisualElement, SVGVisualElement } from \"motion-dom\"\nimport { ComponentType, Fragment } from \"react\"\nimport { CreateVisualElement, VisualElementOptions } from \"../types\"\nimport { isSVGComponent } from \"./utils/is-svg-component\"\n\nexport const createDomVisualElement: CreateVisualElement = (\n Component: string | ComponentType<React.PropsWithChildren<unknown>>,\n options: VisualElementOptions<HTMLElement | SVGElement>\n) => {\n /**\n * Use explicit isSVG override if provided, otherwise auto-detect\n */\n const isSVG = options.isSVG ?? isSVGComponent(Component)\n\n return isSVG\n ? new SVGVisualElement(options)\n : new HTMLVisualElement(options, {\n allowProjection: Component !== Fragment,\n })\n}\n","import {\n createAnimationState,\n Feature,\n isAnimationControls,\n type VisualElement,\n} from \"motion-dom\"\n\nexport class AnimationFeature extends Feature<unknown> {\n unmountControls?: () => void\n\n /**\n * We dynamically generate the AnimationState manager as it contains a reference\n * to the underlying animation library. We only want to load that if we load this,\n * so people can optionally code split it out using the `m` component.\n */\n constructor(node: VisualElement) {\n super(node)\n node.animationState ||= createAnimationState(node)\n }\n\n updateAnimationControlsSubscription() {\n const { animate } = this.node.getProps()\n if (isAnimationControls(animate)) {\n this.unmountControls = animate.subscribe(this.node)\n }\n }\n\n /**\n * Subscribe any provided AnimationControls to the component's VisualElement\n */\n mount() {\n this.updateAnimationControlsSubscription()\n }\n\n update() {\n const { animate } = this.node.getProps()\n const { animate: prevAnimate } = this.node.prevProps || {}\n if (animate !== prevAnimate) {\n this.updateAnimationControlsSubscription()\n }\n }\n\n unmount() {\n this.node.animationState!.reset()\n this.unmountControls?.()\n }\n}\n","import { Feature, resolveVariant } from \"motion-dom\"\n\nlet id = 0\n\nexport class ExitAnimationFeature extends Feature<unknown> {\n private id: number = id++\n private isExitComplete = false\n\n update() {\n if (!this.node.presenceContext) return\n\n const { isPresent, onExitComplete } = this.node.presenceContext\n const { isPresent: prevIsPresent } = this.node.prevPresenceContext || {}\n\n if (!this.node.animationState || isPresent === prevIsPresent) {\n return\n }\n\n if (isPresent && prevIsPresent === false) {\n /**\n * When re-entering, if the exit animation already completed\n * (element is at rest), reset to initial values so the enter\n * animation replays from the correct position.\n */\n if (this.isExitComplete) {\n const { initial, custom } = this.node.getProps()\n\n if (\n typeof initial === \"string\" ||\n (typeof initial === \"object\" &&\n initial !== null &&\n !Array.isArray(initial))\n ) {\n const resolved = resolveVariant(\n this.node,\n initial,\n custom\n )\n if (resolved) {\n const { transition, transitionEnd, ...target } =\n resolved\n for (const key in target) {\n this.node\n .getValue(key)\n ?.jump(\n target[\n key as keyof typeof target\n ] as any\n )\n }\n }\n }\n\n this.node.animationState.reset()\n this.node.animationState.animateChanges()\n } else {\n this.node.animationState.setActive(\"exit\", false)\n }\n\n this.isExitComplete = false\n return\n }\n\n const exitAnimation = this.node.animationState.setActive(\n \"exit\",\n !isPresent\n )\n\n if (onExitComplete && !isPresent) {\n exitAnimation.then(() => {\n this.isExitComplete = true\n onExitComplete(this.id)\n })\n }\n }\n\n mount() {\n const { register, onExitComplete } = this.node.presenceContext || {}\n\n if (onExitComplete) {\n onExitComplete(this.id)\n }\n\n if (register) {\n this.unmount = register(this.id)\n }\n }\n\n unmount() {}\n}\n","import { AnimationFeature } from \"./animation\"\nimport { ExitAnimationFeature } from \"./animation/exit\"\nimport { FeaturePackages } from \"./types\"\n\nexport const animations: FeaturePackages = {\n animation: {\n Feature: AnimationFeature,\n },\n exit: {\n Feature: ExitAnimationFeature,\n },\n}\n","import { EventInfo, isPrimaryPointer } from \"motion-dom\"\n\nexport type EventListenerWithPointInfo = (\n e: PointerEvent,\n info: EventInfo\n) => void\n\nexport function extractEventInfo(event: PointerEvent): EventInfo {\n return {\n point: {\n x: event.pageX,\n y: event.pageY,\n },\n }\n}\n\nexport const addPointerInfo =\n (handler: EventListenerWithPointInfo): EventListener =>\n (event: PointerEvent) =>\n isPrimaryPointer(event) && handler(event, extractEventInfo(event))\n","import { Feature, frame, hover, type VisualElement } from \"motion-dom\"\nimport { extractEventInfo } from \"../events/event-info\"\n\nfunction handleHoverEvent(\n node: VisualElement<Element>,\n event: PointerEvent,\n lifecycle: \"Start\" | \"End\"\n) {\n const { props } = node\n\n if (node.animationState && props.whileHover) {\n node.animationState.setActive(\"whileHover\", lifecycle === \"Start\")\n }\n\n const eventName = (\"onHover\" + lifecycle) as \"onHoverStart\" | \"onHoverEnd\"\n const callback = props[eventName]\n if (callback) {\n frame.postRender(() => callback(event, extractEventInfo(event)))\n }\n}\n\nexport class HoverGesture extends Feature<Element> {\n mount() {\n const { current } = this.node\n if (!current) return\n\n this.unmount = hover(current, (_element, startEvent) => {\n handleHoverEvent(this.node, startEvent, \"Start\")\n\n return (endEvent) => handleHoverEvent(this.node, endEvent, \"End\")\n })\n }\n\n unmount() {}\n}\n","import { Feature, addDomEvent } from \"motion-dom\"\nimport { pipe } from \"motion-utils\"\n\nexport class FocusGesture extends Feature<Element> {\n private isActive = false\n\n onFocus() {\n let isFocusVisible = false\n\n /**\n * If this element doesn't match focus-visible then don't\n * apply whileHover. But, if matches throws that focus-visible\n * is not a valid selector then in that browser outline styles will be applied\n * to the element by default and we want to match that behaviour with whileFocus.\n */\n try {\n isFocusVisible = this.node.current!.matches(\":focus-visible\")\n } catch (e) {\n isFocusVisible = true\n }\n\n if (!isFocusVisible || !this.node.animationState) return\n\n this.node.animationState.setActive(\"whileFocus\", true)\n this.isActive = true\n }\n\n onBlur() {\n if (!this.isActive || !this.node.animationState) return\n this.node.animationState.setActive(\"whileFocus\", false)\n this.isActive = false\n }\n\n mount() {\n this.unmount = pipe(\n addDomEvent(this.node.current!, \"focus\", () => this.onFocus()),\n addDomEvent(this.node.current!, \"blur\", () => this.onBlur())\n ) as VoidFunction\n }\n\n unmount() {}\n}\n","import { Feature, frame, press, type VisualElement } from \"motion-dom\"\nimport { extractEventInfo } from \"../events/event-info\"\n\nfunction handlePressEvent(\n node: VisualElement<Element>,\n event: PointerEvent,\n lifecycle: \"Start\" | \"End\" | \"Cancel\"\n) {\n const { props } = node\n\n if (node.current instanceof HTMLButtonElement && node.current.disabled) {\n return\n }\n\n if (node.animationState && props.whileTap) {\n node.animationState.setActive(\"whileTap\", lifecycle === \"Start\")\n }\n\n const eventName = (\"onTap\" + (lifecycle === \"End\" ? \"\" : lifecycle)) as\n | \"onTapStart\"\n | \"onTap\"\n | \"onTapCancel\"\n\n const callback = props[eventName]\n if (callback) {\n frame.postRender(() => callback(event, extractEventInfo(event)))\n }\n}\n\nexport class PressGesture extends Feature<Element> {\n mount() {\n const { current } = this.node\n if (!current) return\n\n const { globalTapTarget, propagate } = this.node.props\n\n this.unmount = press(\n current,\n (_element, startEvent) => {\n handlePressEvent(this.node, startEvent, \"Start\")\n\n return (endEvent, { success }) =>\n handlePressEvent(\n this.node,\n endEvent,\n success ? \"End\" : \"Cancel\"\n )\n },\n {\n useGlobalTarget: globalTapTarget,\n stopPropagation: propagate?.tap === false,\n }\n )\n }\n\n unmount() {}\n}\n","type IntersectionHandler = (entry: IntersectionObserverEntry) => void\n\ninterface ElementIntersectionObservers {\n [key: string]: IntersectionObserver\n}\n\n/**\n * Map an IntersectionHandler callback to an element. We only ever make one handler for one\n * element, so even though these handlers might all be triggered by different\n * observers, we can keep them in the same map.\n */\nconst observerCallbacks = new WeakMap<Element, IntersectionHandler>()\n\n/**\n * Multiple observers can be created for multiple element/document roots. Each with\n * different settings. So here we store dictionaries of observers to each root,\n * using serialised settings (threshold/margin) as lookup keys.\n */\nconst observers = new WeakMap<\n Element | Document,\n ElementIntersectionObservers\n>()\n\nconst fireObserverCallback = (entry: IntersectionObserverEntry) => {\n const callback = observerCallbacks.get(entry.target)\n callback && callback(entry)\n}\n\nconst fireAllObserverCallbacks: IntersectionObserverCallback = (entries) => {\n entries.forEach(fireObserverCallback)\n}\n\nfunction initIntersectionObserver({\n root,\n ...options\n}: IntersectionObserverInit): IntersectionObserver {\n const lookupRoot = root || document\n\n /**\n * If we don't have an observer lookup map for this root, create one.\n */\n if (!observers.has(lookupRoot)) {\n observers.set(lookupRoot, {})\n }\n const rootObservers = observers.get(lookupRoot)!\n\n const key = JSON.stringify(options)\n\n /**\n * If we don't have an observer for this combination of root and settings,\n * create one.\n */\n if (!rootObservers[key]) {\n rootObservers[key] = new IntersectionObserver(\n fireAllObserverCallbacks,\n { root, ...options }\n )\n }\n\n return rootObservers[key]\n}\n\nexport function observeIntersection(\n element: Element,\n options: IntersectionObserverInit,\n callback: IntersectionHandler\n) {\n const rootInteresectionObserver = initIntersectionObserver(options)\n\n observerCallbacks.set(element, callback)\n rootInteresectionObserver.observe(element)\n\n return () => {\n observerCallbacks.delete(element)\n rootInteresectionObserver.unobserve(element)\n }\n}\n","import { Feature } from \"motion-dom\"\nimport { MotionProps } from \"../../types\"\nimport { observeIntersection } from \"./observers\"\n\nconst thresholdNames = {\n some: 0,\n all: 1,\n}\n\nexport class InViewFeature extends Feature<Element> {\n private hasEnteredView = false\n\n private isInView = false\n\n private stopObserver?: () => void\n\n private startObserver() {\n this.stopObserver?.()\n\n const { viewport = {} } = this.node.getProps()\n const { root, margin: rootMargin, amount = \"some\", once } = viewport\n\n const options = {\n root: root ? root.current : undefined,\n rootMargin,\n threshold:\n typeof amount === \"number\" ? amount : thresholdNames[amount],\n }\n\n const onIntersectionUpdate = (entry: IntersectionObserverEntry) => {\n const { isIntersecting } = entry\n\n /**\n * If there's been no change in the viewport state, early return.\n */\n if (this.isInView === isIntersecting) return\n\n this.isInView = isIntersecting\n\n /**\n * Handle hasEnteredView. If this is only meant to run once, and\n * element isn't visible, early return. Otherwise set hasEnteredView to true.\n */\n if (once && !isIntersecting && this.hasEnteredView) {\n return\n } else if (isIntersecting) {\n this.hasEnteredView = true\n }\n\n if (this.node.animationState) {\n this.node.animationState.setActive(\n \"whileInView\",\n isIntersecting\n )\n }\n\n /**\n * Use the latest committed props rather than the ones in scope\n * when this observer is created\n */\n const { onViewportEnter, onViewportLeave } = this.node.getProps()\n const callback = isIntersecting ? onViewportEnter : onViewportLeave\n callback && callback(entry)\n }\n\n this.stopObserver = observeIntersection(\n this.node.current!,\n options,\n onIntersectionUpdate\n )\n }\n\n mount() {\n this.startObserver()\n }\n\n update() {\n if (typeof IntersectionObserver === \"undefined\") return\n\n const { props, prevProps } = this.node\n const hasOptionsChanged = [\"amount\", \"margin\", \"root\"].some(\n hasViewportOptionChanged(props, prevProps)\n )\n\n if (hasOptionsChanged) {\n this.startObserver()\n }\n }\n\n unmount() {\n this.stopObserver?.()\n this.hasEnteredView = false\n this.isInView = false\n }\n}\n\nfunction hasViewportOptionChanged(\n { viewport = {} }: MotionProps,\n { viewport: prevViewport = {} }: MotionProps = {}\n) {\n return (name: keyof typeof viewport) =>\n viewport[name] !== prevViewport[name]\n}\n","import { HoverGesture } from \"../../gestures/hover\"\nimport { FocusGesture } from \"../../gestures/focus\"\nimport { PressGesture } from \"../../gestures/press\"\nimport { InViewFeature } from \"./viewport\"\nimport { FeaturePackages } from \"./types\"\n\nexport const gestureAnimations: FeaturePackages = {\n inView: {\n Feature: InViewFeature,\n },\n tap: {\n Feature: PressGesture,\n },\n focus: {\n Feature: FocusGesture,\n },\n hover: {\n Feature: HoverGesture,\n },\n}\n","\"use client\"\n\nimport { animations } from \"../../motion/features/animations\"\nimport { gestureAnimations } from \"../../motion/features/gestures\"\nimport { FeatureBundle } from \"../../motion/features/types\"\nimport { createDomVisualElement } from \"./create-visual-element\"\n\n/**\n * @public\n */\nexport const domAnimation: FeatureBundle = {\n renderer: createDomVisualElement,\n ...animations,\n ...gestureAnimations,\n}\n","\"use client\"\n\nimport {\n hasReducedMotionListener,\n initPrefersReducedMotion,\n prefersReducedMotion,\n} from \"motion-dom\"\nimport { warnOnce } from \"motion-utils\"\nimport { useState } from \"react\"\n\n/**\n * A hook that returns `true` if we should be using reduced motion based on the current device's Reduced Motion setting.\n *\n * This can be used to implement changes to your UI based on Reduced Motion. For instance, replacing motion-sickness inducing\n * `x`/`y` animations with `opacity`, disabling the autoplay of background videos, or turning off parallax motion.\n *\n * It will actively respond to changes and re-render your components with the latest setting.\n *\n * ```jsx\n * export function Sidebar({ isOpen }) {\n * const shouldReduceMotion = useReducedMotion()\n * const closedX = shouldReduceMotion ? 0 : \"-100%\"\n *\n * return (\n * <motion.div animate={{\n * opacity: isOpen ? 1 : 0,\n * x: isOpen ? 0 : closedX\n * }} />\n * )\n * }\n * ```\n *\n * @return boolean\n *\n * @public\n */\nexport function useReducedMotion() {\n /**\n * Lazy initialisation of prefersReducedMotion\n */\n !hasReducedMotionListener.current && initPrefersReducedMotion()\n\n const [shouldReduceMotion] = useState(prefersReducedMotion.current)\n\n if (process.env.NODE_ENV !== \"production\") {\n warnOnce(\n shouldReduceMotion !== true,\n \"You have Reduced Motion enabled on your device. Animations may not appear as expected.\",\n \"reduced-motion-disabled\"\n )\n }\n\n /**\n * TODO See if people miss automatically updating shouldReduceMotion setting\n */\n\n return shouldReduceMotion\n}\n","/**\n * Raw, **controlled** overlay chrome — `<Sheet>` (a drawer, or a floating card) and\n * `<Modal>` (a centered dialog). Headless and styleable (className/portal/dismiss), the\n * same two-tier contract as `<Choice>`: thin wrappers you restyle or eject.\n *\n * These are the presentation layer. For *imperative*, promise-based modals\n * triggered from anywhere, wrap one in `defineModal` and `showModal(...)`\n * (see {@link ./modals}) — that registry drives these controlled primitives.\n * They're also used directly (no registry) where local state is simpler, e.g.\n * the checkout `sheet` surface.\n *\n * Still deliberately minimal: portal to `document.body`, lock body scroll while open,\n * dismiss on Escape / backdrop, **no focus-trap dependency**. Focus-trap stays out because\n * the overlay's only real inhabitant is a payment surface whose fields live in a\n * cross-origin provider iframe — a JS trap cannot see focus inside that iframe, so it would\n * either fight the provider for focus or have to whitelist it into meaninglessness. The\n * `role=\"dialog\"` + `aria-modal` pair already tells assistive tech to scope to the overlay.\n *\n * What DID change: there is now an animation engine, and only for the `floating` sheet\n * variant — the ENTRY, a spring rather than a hand-picked duration (see\n * {@link OVERLAY_SPRING}), plus the backdrop's fade. That is the whole of it.\n *\n * There is deliberately **no height animation**. An earlier revision measured the sheet's\n * natural height and sprang the frame to it, on the theory that Stripe's iframe growing\n * (Link loading, an OTP step swapping in) would otherwise snap. The reference sheet was then\n * measured directly and does nothing of the kind: it *reserves* a fixed height\n * ({@link floatingGeometry}) so the card renders at full size while still blank, holding its\n * shape until the provider paints into it. Reserving beats animating — there is no reflow to\n * smooth over in the first place, and no measure→animate loop to keep honest. BOTH modes\n * reserve: the phone against the viewport, the desktop against a cap\n * ({@link FLOATING_DESKTOP_HEIGHT}), because a centered card cannot take the viewport's whole\n * height without becoming a column.\n *\n * The one thing the card DOES read at runtime is whether it has scrolled to the end — a\n * reserved height means content routinely overflows it, and a hard-cut edge gives the buyer no\n * hint there is more below. {@link useScrollFade} publishes that as a single custom property\n * and the fade elements are pure CSS off it; see {@link OVERLAY_FADE}.\n *\n * The engine is `framer-motion`'s size-optimised path only — `LazyMotion` + the `m`\n * component + the `domAnimation` feature bundle, in `strict` mode so a future edit that\n * reaches for the full `motion` component fails loudly instead of silently shipping layout\n * projection, drag and every gesture to every funnel. The `edge` sheets and `<Modal>` render\n * plain, unanimated `div`s exactly as before — no motion component, no `LazyMotion`, byte-\n * identical DOM.\n */\n\nimport {\n createElement,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n type CSSProperties,\n type ReactNode,\n} from 'react'\nimport { createPortal } from 'react-dom'\nimport { LazyMotion, domAnimation, m, useReducedMotion } from 'framer-motion'\nimport { useModal } from './registry'\n\nexport type SheetSide = 'bottom' | 'top' | 'left' | 'right'\n\n/**\n * How a `<Sheet>` presents itself.\n * - `edge` (default) — the classic drawer, flush against the `side` edge. Every existing\n * consumer is this, unchanged in DOM, geometry and (lack of) motion.\n * - `floating` — a rounded card inset {@link FLOATING_INSET} from the viewport, presented two\n * ways by width (see {@link floatingGeometry}): bottom-anchored on a phone, centered at\n * {@link FLOATING_WIDTH} on a desktop. Both RESERVE their height. Springs in. `side` does\n * not apply.\n */\nexport type SheetVariant = 'edge' | 'floating'\n\n/**\n * `<Sheet>`/`<Modal>` bind themselves to the surrounding {@link defineModal} via\n * its context — so inside a modal you write just `<Sheet>…</Sheet>`, with no\n * open/onClose plumbing. They are therefore **only valid inside a `defineModal`**\n * (rendered through `showModal`); used anywhere else `useModal()` throws, which\n * is the correct signal. For an overlay driven by local state, wrap it in a\n * `defineModal` and `showModal` it — that's the one overlay path.\n */\nfunction useModalControl(): { open: boolean; onClose: () => void } {\n const m = useModal()\n return {\n open: m.visible,\n onClose: () => {\n m.hide()\n m.resolveHide()\n if (!m.keepMounted) m.remove()\n },\n }\n}\n\ninterface OverlayCommon {\n className?: string\n backdropClassName?: string\n dismissOnBackdrop?: boolean\n ariaLabel?: string\n children: ReactNode\n}\n\n/** Flexbox placement of the panel within the viewport. */\ntype Container = Pick<CSSProperties, 'flexDirection' | 'justifyContent' | 'alignItems'>\n\ninterface ShellProps {\n open: boolean\n onClose: () => void\n className?: string\n backdropClassName?: string\n dismissOnBackdrop?: boolean\n ariaLabel?: string\n container: Container\n /** Panel layout (size + corners per variant). */\n panel: CSSProperties\n /** Backdrop fill — the floating card sits on a lighter scrim than the edge drawers. */\n backdrop: string\n /** The panel's own inner gutter in px, republished as `--af-overlay-gutter` (see {@link overlayVars}). */\n gutter: number\n /**\n * `floating` wraps the panel in an animated frame and springs in; `edge` renders the\n * panel bare and unanimated (byte-identical to the pre-motion shell).\n */\n variant: SheetVariant\n children: ReactNode\n}\n\n// ── Geometry ────────────────────────────────────────────────\n//\n// Every number below is a real measurement off the reference sheet, or a deliberate,\n// commented deviation from it. The reference presents the floating sheet TWO ways and swaps\n// between them on width, which the SDK cannot express in CSS: it ships no stylesheet, and an\n// inline style has no media query. So the swap is a JS read of the viewport width\n// ({@link floatingMode}) — see {@link useFloatingMode} for how it stays correct across resize\n// and rotation. Everything WITHIN a mode is still plain CSS, so nothing re-renders while the\n// buyer scrolls, types or the provider iframe grows.\n\n/** The floating card's width on desktop, where it is a fixed-width centered card. */\nconst FLOATING_WIDTH = 440\n/** Inset between the viewport edge and the card, on all four sides, in both modes. */\nconst FLOATING_INSET = 6\n/** The card's own gutter. Symmetric (the reference is `24px 0`) — see {@link FLOATING_CARD}. */\nconst FLOATING_GUTTER = 20\n/** The card's corner radius, in both modes. */\nconst FLOATING_RADIUS = 44\n/**\n * How much of the page the mobile sheet leaves visible above itself — measured at 44px, and\n * the whole reason the mobile sheet reads as a sheet OVER the funnel rather than a takeover.\n */\nconst FLOATING_REVEAL = 44\n/**\n * Below this viewport width the sheet is bottom-anchored; at or above it the sheet is a\n * centered card. The reference is still in mobile presentation at 500px and in desktop\n * presentation at 1920px; the exact switch is not observable from those two points, so this is\n * the conventional small/medium boundary.\n */\nconst FLOATING_BREAKPOINT = 640\n/**\n * The desktop card's RESERVED height — the ceiling in `min(100dvh − inset, cap)`.\n *\n * Desktop reserves for the same reason mobile does: the card must not resize when Stripe's\n * iframe finishes loading. But desktop is CENTERED, so it cannot simply take the viewport the\n * way the bottom-anchored phone sheet does — an unbounded `100dvh − 12` is a 440×1288 column on\n * a 1440p monitor (a 1:2.9 rectangle), which reads as a sidebar, not a dialog. Hence a cap.\n *\n * 720 is the smallest round number that satisfies all three constraints:\n * - **It clears the content.** The reference's desktop card measured 680px of natural content\n * at a 958px-tall viewport, ours 711px. A cap BELOW those would make the reserve a\n * regression — it would introduce a scrollbar where the old content-height card had none.\n * 720 clears our own measurement with a few px of slack. (A ~900px PaymentElement still\n * scrolls, which is expected and is what the sticky dock exists for.)\n * - **It is a defensible rectangle.** At {@link FLOATING_WIDTH} = 440 the golden-ratio height\n * is 712px; 720 is that rounded up onto the 8px grid, so the card reads as a proportioned\n * dialog at any viewport tall enough to show it whole.\n * - **It stays a dialog on a big monitor.** 720 is ~75% of the reference's 958px viewport,\n * ~77% of a 1080p one, and ~55% of a 1440p one — always inset, never a full-height column.\n * Below 732px of viewport the `100dvh` leg binds first and the card simply fills what's there,\n * exactly as it did before.\n */\nconst FLOATING_DESKTOP_HEIGHT = 720\n/** The edge drawers' and the dialog's inner gutters — the `padding` in the layouts below. */\nconst EDGE_GUTTER = 16\nconst MODAL_GUTTER = 24\n\n/**\n * The sheet's surface colour and inner gutter, republished as CSS custom properties on the\n * panel so code that renders INTO the sheet can match it without importing this module.\n *\n * The one consumer is the Stripe driver's sticky submit dock (`SHEET_SUBMIT_DOCK` in\n * ../drivers/stripe.tsx), which needs both: the gutter, to lay its fill across the sheet's\n * bottom spacing while keeping the button a gutter above the card's edge, and the surface\n * colour, to paint the gap above the button so scrolling card fields can't show through it.\n * Both are read with fallbacks (`0px` / `transparent`) that reproduce exactly the pre-dock-fill\n * behaviour, so a host that doesn't publish them is unaffected.\n *\n * A funnel that repaints the panel (which takes `!important`, since the background below is\n * an inline style) should set `--af-overlay-surface` to the same colour in the same rule.\n *\n * There is a THIRD property on the floating card, `--af-overlay-fade` (0 or 1), and it is\n * deliberately NOT here: it is written imperatively by {@link useScrollFade} rather than\n * through React's style prop, because it changes as the buyer scrolls and re-rendering the\n * overlay for that would be absurd. Every reader spells it `var(--af-overlay-fade, 0)`, so\n * before the first measurement — and in any host that never publishes it — the fade is simply\n * off, which is the pre-fade behaviour exactly.\n */\nconst OVERLAY_SURFACE = '#fff'\ntype OverlayVars = { '--af-overlay-surface': string; '--af-overlay-gutter': string }\nconst overlayVars = (gutter: number): OverlayVars => ({\n '--af-overlay-surface': OVERLAY_SURFACE,\n '--af-overlay-gutter': `${gutter}px`,\n})\n\n/**\n * Which of the two floating presentations a viewport gets. Pure, and exported for the tests:\n * this is the only place the breakpoint is decided.\n */\nexport type FloatingMode = 'mobile' | 'desktop'\nexport const floatingMode = (viewportWidth: number): FloatingMode =>\n viewportWidth >= FLOATING_BREAKPOINT ? 'desktop' : 'mobile'\n\n/**\n * The frame — the outer box: it owns the {@link FLOATING_INSET} gutter, the entry spring, and\n * (on mobile) the reserved height. Deliberately **not** the scroll container; the card below\n * is, and the sticky submit dock resolves against the card, so nothing here may grow an\n * `overflow`.\n *\n * A flex column with `boxSizing: border-box`, so the card (a flex item whose `overflow: auto`\n * zeroes its automatic minimum size) shrinks to the frame's content box and scrolls the\n * remainder, and every height below is a border-box number that includes the inset.\n */\nconst FLOATING_FRAME: CSSProperties = {\n position: 'relative',\n display: 'flex',\n flexDirection: 'column',\n boxSizing: 'border-box',\n padding: FLOATING_INSET,\n}\n\n/**\n * The visible card, and THE SCROLLPORT — `overflow: auto` here is load-bearing well beyond\n * its own layout: the checkout sheet docks its submit button with `position: sticky` against\n * exactly this box (see SHEET_SUBMIT_DOCK in ../drivers/stripe.tsx), because a ~900px Stripe\n * PaymentElement would otherwise leave \"Pay now\" a screenful below the fold. Moving the\n * scroll to an inner wrapper, or clipping it on an ancestor, silently un-sticks that button —\n * sticky fails quietly, with no error anywhere.\n *\n * `boxSizing: border-box` is required, not cosmetic: the mobile height below is the card's\n * BORDER box (667px at a 723px viewport, i.e. the frame's 679px minus its 12px of inset), and\n * the card carries 20px of its own padding. Left to a host page that resets to `content-box`\n * the card would render 40px too tall and overflow its frame.\n *\n * Deviation from the reference, on purpose: the reference card is `padding: 24px 0` with\n * `align-items: center`, which works because ITS children carry their own horizontal gutter.\n * Ours are funnel-authored and provider-rendered, so the card owns a symmetric\n * {@link FLOATING_GUTTER} instead and lays out as a plain block. That gutter also keeps\n * content clear of the 44px corner curve (at 20px down from the edge the curve has only\n * eaten ~7px), so nothing clips.\n */\nconst FLOATING_CARD: CSSProperties = {\n display: 'block',\n boxSizing: 'border-box',\n padding: FLOATING_GUTTER,\n borderRadius: FLOATING_RADIUS,\n boxShadow: '0 10px 15px -3px rgba(0,0,0,.1), 0 4px 6px -4px rgba(0,0,0,.1)',\n overflow: 'auto',\n overscrollBehavior: 'contain',\n WebkitOverflowScrolling: 'touch',\n // The card scrolls but never SHOWS a bar. A gutter-wide track down the inside of a 44px-radius\n // floating card reads as a rendering fault rather than an affordance, and the \"more below\" job it\n // would do is already done — properly, and in the card's own colours — by the fade at the bottom\n // edge (`--af-overlay-fade`). Standard property first; WebKit before Safari 18.2 needs the\n // pseudo-element, which inline styles can't express — see CARD_SCROLLBAR_CSS.\n scrollbarWidth: 'none',\n msOverflowStyle: 'none',\n}\n\n/**\n * The `::-webkit-scrollbar` half of hiding the bar, for WebKit builds predating `scrollbar-width`\n * (Safari < 18.2). Scoped to the floating CARD alone, deliberately: `data-appfunnel-overlay-panel`\n * is also worn by `edge` sheets and by every registry <Modal>, and those have no bottom fade to\n * replace the bar with — hiding it there would remove the only hint their content scrolls.\n */\nconst CARD_SCROLLBAR_CSS = '[data-appfunnel-overlay-card]::-webkit-scrollbar{width:0;height:0;display:none}'\nconst CARD_STYLE_ID = 'af-overlay-card-scrollbar'\n\n/** Inject the WebKit rule once per document. No-op on the server and on every call after the first. */\nfunction ensureCardScrollbarStyles(): void {\n if (typeof document === 'undefined' || document.getElementById(CARD_STYLE_ID)) return\n const style = document.createElement('style')\n style.id = CARD_STYLE_ID\n style.textContent = CARD_SCROLLBAR_CSS\n document.head.appendChild(style)\n}\n\n/** `100vh`/`100dvh` minus an inset, as a bare math expression — `min()`'s arguments are\n * calc-expressions already, so a `calc()` around them THERE would only be noise. */\nconst viewport = (unit: 'vh' | 'dvh', subtract: number) =>\n subtract ? `100${unit} - ${subtract}px` : `100${unit}`\n\n/**\n * `height` gets `vh` and `max-height` gets `dvh`, and the pair is not redundant.\n *\n * The reference sets both to the same `vh` figure, which is right on a desktop where they are\n * equal. On a phone `100vh` is the LARGE viewport — it counts the retracted URL bar — so a\n * card sized only in `vh` puts its own sticky Pay button underneath the browser chrome. `dvh`\n * is the visible one and tracks the chrome as it retracts. Writing the reference's number as\n * the `height` and the dynamic one as the `max-height` gives: identical geometry to the\n * measurement wherever the two units agree (every desktop, and the emulated viewports the\n * spec was measured at), the visible viewport wherever they don't, and — because a browser too\n * old for `dvh` simply drops the `max-height` declaration — the reference's literal `vh`\n * behaviour as the floor. One expression, no feature detection.\n */\nconst vh = (subtract: number) => (subtract ? `calc(${viewport('vh', subtract)})` : '100vh')\nconst dvh = (subtract: number) => (subtract ? `calc(${viewport('dvh', subtract)})` : '100dvh')\n\n/**\n * The same pair, CAPPED — the desktop card's reserved height (see {@link FLOATING_DESKTOP_HEIGHT}).\n * `min()` predates `dvh` in every engine that ships it, so the only browser that drops these is\n * one too old for either, and it drops them to `height: auto` — the content-height card this\n * replaced. Degradation, not breakage.\n */\nconst cappedVh = (subtract: number, cap: number) => `min(${viewport('vh', subtract)}, ${cap}px)`\nconst cappedDvh = (subtract: number, cap: number) => `min(${viewport('dvh', subtract)}, ${cap}px)`\n\n/**\n * The measured geometry, per mode. Taken off the reference at 500×723 and 1920×958; the\n * expressions below reproduce those numbers exactly at those viewports.\n *\n * MOBILE — bottom-anchored, and height-RESERVED rather than height-animated:\n * frame width 100% height 100vh − 44 (679 @ 723)\n * card width 100% height 100vh − 56 (667 @ 723, = frame minus its 12px of inset)\n * so the sheet keeps a 6px gutter left, right and below, and leaves {@link FLOATING_REVEAL}\n * of the funnel visible above itself. The card is full-size from the first frame, which is\n * the point: it holds its shape while still blank instead of snapping open when Stripe paints.\n *\n * DESKTOP — centered, and height-RESERVED too, but against a ceiling rather than the viewport\n * (see {@link FLOATING_DESKTOP_HEIGHT} for the 720):\n * frame width 440 height min(100vh, 732)\n * card width 428 height min(100vh − 12, 720)\n * The two expressions differ by the frame's 12px of inset, exactly as on mobile, so the 6px\n * gutter holds whichever leg of the `min()` binds. The reference's content-height card is what\n * this replaces: the owner does not want the card resizing when Stripe's iframe finishes\n * loading, and reserving is the only way to hold a shape you cannot yet measure.\n */\nexport function floatingGeometry(mode: FloatingMode): {\n container: Container\n frame: CSSProperties\n card: CSSProperties\n} {\n if (mode === 'mobile') {\n return {\n // `row` + `flex-end` = horizontally centered (moot at width 100%) and pinned to the\n // bottom edge, the cross axis. The reference wrapper is `center` / `flex-end`.\n container: { flexDirection: 'row', justifyContent: 'center', alignItems: 'flex-end' },\n frame: {\n ...FLOATING_FRAME,\n width: '100%',\n maxWidth: 'none',\n height: vh(FLOATING_REVEAL),\n // The dynamic twin of the height, NOT a bare `100dvh`: frame and card have to shrink\n // by the same amount when the two units disagree, or the 6px bottom gutter opens up\n // into a 44px one.\n maxHeight: dvh(FLOATING_REVEAL),\n },\n card: {\n ...FLOATING_CARD,\n height: vh(FLOATING_REVEAL + FLOATING_INSET * 2),\n maxHeight: dvh(FLOATING_REVEAL + FLOATING_INSET * 2),\n },\n }\n }\n return {\n container: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center' },\n frame: {\n ...FLOATING_FRAME,\n width: FLOATING_WIDTH,\n maxWidth: FLOATING_WIDTH,\n height: cappedVh(0, FLOATING_DESKTOP_HEIGHT + FLOATING_INSET * 2),\n // The dynamic twin, for the same reason as mobile's: frame and card must shrink by the\n // same amount when the two units disagree, or the 6px gutter opens up.\n maxHeight: cappedDvh(0, FLOATING_DESKTOP_HEIGHT + FLOATING_INSET * 2),\n },\n card: {\n ...FLOATING_CARD,\n height: cappedVh(FLOATING_INSET * 2, FLOATING_DESKTOP_HEIGHT),\n maxHeight: cappedDvh(FLOATING_INSET * 2, FLOATING_DESKTOP_HEIGHT),\n },\n }\n}\n\n// ── The scroll fade ─────────────────────────────────────────\n//\n// A reserved height means the card overflows routinely — a ~900px PaymentElement in a 720px\n// card — and a hard-cut bottom edge gives the buyer no hint that anything is below it. The\n// affordance is a gradient fading the content into the card's own surface, shown ONLY while\n// there is more to scroll.\n//\n// A gradient, not `backdrop-filter: blur()`. Blur is a per-frame compositor pass over a\n// scrolling region, it is still `-webkit-` prefixed on Safari and disabled outright behind\n// some privacy settings and in software rendering, and over a flat opaque surface the two are\n// visually indistinguishable anyway — a blur of white IS white. It would cost real frames\n// during exactly the scroll it decorates and buy nothing.\n//\n// WHERE the fade lives is the interesting part, because the bottom of the scrollport is\n// usually already occupied by the checkout driver's sticky submit dock, and a fade pinned to\n// the card's bottom edge would sit UNDER it, invisible. The rule that resolves it:\n//\n// the fade belongs at the seam between scrolling content and whatever is pinned below it,\n// and it is owned by whatever OWNS that seam.\n//\n// The sheet owns the default seam — the card's bottom edge — and paints {@link OVERLAY_FADE}\n// there. Any sticky footer that COVERS that seam has moved it to its own top edge, and only\n// that footer knows where its top edge is, so it paints its own (`SHEET_SUBMIT_FADE` in\n// ../drivers/stripe.tsx). The sheet never asks whether a dock exists: its fade is simply\n// covered by the dock's opaque, `z-index: 1` fill when there is one, so exactly one fade is\n// ever visible. The two can never disagree about WHEN to show, because both are pure CSS off\n// the single `--af-overlay-fade` flag this module publishes.\n\n/** How much content the fade covers, in px. Mirrored (deliberately, not imported — the driver\n * is a separate entry and must not pull this module's framer-motion into its chunk) by\n * `SHEET_SUBMIT_FADE` in ../drivers/stripe.tsx. */\nconst FLOATING_FADE = 32\n\n/**\n * The sheet's own fade: the last child of the card, pinned to the card's bottom EDGE.\n *\n * - `sticky` + a negative `bottom` of one gutter — the same trick, and for the same reason, as\n * the submit dock: content scrolls THROUGH a scroll container's padding box, so a fade that\n * stopped at the content box would leave the last gutter of content un-faded. It therefore\n * spans `FLOATING_FADE` of content PLUS the gutter, and ends flush with the card's edge\n * (where the card's `overflow: auto` clips it to the 44px corner curve for free).\n * - a negative `marginTop` of its own height, NOT the dock's negative `marginBottom`. The\n * difference matters: a last child hanging BELOW the parent's content box adds its height to\n * `scrollHeight`, which would leave permanently-unscrollable slack at the end and pin the\n * fade on forever. Pulling it UP instead lands its bottom edge exactly on the content's, so\n * the flow height, the scroll height and therefore {@link scrollFadeVisible} are all\n * untouched by the fade's presence. It overlays the tail of the content, which is the job.\n * - `pointerEvents: none` — it lies over the content, and must never eat a click or a wheel.\n * - `opacity: var(--af-overlay-fade, 0)` — the flag, defaulting to invisible.\n *\n * The gradient interpolates the surface colour to the `transparent` keyword. Every current\n * engine interpolates in premultiplied alpha, so white→transparent stays white and never bands\n * through grey the way the pre-2017 unpremultiplied behaviour did.\n *\n * `data-appfunnel-overlay-fade` is the seam: `display: none` on it removes the affordance,\n * and a funnel with a non-flat surface can restyle the `background-image` outright.\n *\n * Exported for the same reason `SHEET_SUBMIT_DOCK` is: `var()`/`calc()` values are resolved by\n * the BROWSER and the DOM emulator the tests run in drops them from the CSSOM, so the geometry\n * is asserted against this object rather than a style attribute missing half of it.\n */\nexport const OVERLAY_FADE: CSSProperties = {\n position: 'sticky',\n bottom: 'calc(-1 * var(--af-overlay-gutter, 0px))',\n height: `calc(${FLOATING_FADE}px + var(--af-overlay-gutter, 0px))`,\n marginTop: `calc(-${FLOATING_FADE}px - var(--af-overlay-gutter, 0px))`,\n pointerEvents: 'none',\n opacity: 'var(--af-overlay-fade, 0)',\n // Not an entry animation and not vestibular motion — a cross-fade so the affordance doesn't\n // pop in and out on the last pixel of a flick scroll.\n transition: 'opacity 150ms linear',\n backgroundImage: 'linear-gradient(to top, var(--af-overlay-surface, transparent), transparent)',\n}\n\n/**\n * Is there more content below the fold? Pure, and exported for the tests — the threshold is\n * the whole behavioural contract (on mid-scroll, OFF at the end, and never on at all when the\n * content fits), and it is the one thing here that is not CSS.\n *\n * The 1px tolerance is not slop: `scrollHeight` and `clientHeight` are integers while\n * `scrollTop` is fractional on a zoomed or fractionally-scaled display, so an exactly\n * scrolled-to-the-end card reports a remainder of up to ~0.99px. Without the tolerance the\n * fade would linger at the very bottom on exactly the displays that are hardest to test on.\n */\nexport const SCROLL_FADE_EPSILON = 1\nexport const scrollFadeVisible = (scrollTop: number, scrollHeight: number, clientHeight: number): boolean =>\n scrollHeight - clientHeight - scrollTop > SCROLL_FADE_EPSILON\n\n/**\n * Per-side EDGE geometry. The `maxHeight` + `overflow: auto` pair makes the PANEL the scroll\n * container, for the same sticky-dock reason spelled out on {@link FLOATING_CARD}.\n *\n * `flexDirection` is explicit on every row, and that is a BUG FIX: the shell sets\n * `display: flex` on the viewport-filling container, and flex defaults to `row`. So\n * `justifyContent: 'flex-end'` — written for `side=\"bottom\"` — was resolving on the\n * HORIZONTAL axis and rendering a right-anchored panel, and `side=\"top\"` a left-anchored one.\n * `left`/`right` only ever looked correct because they carry an explicit `width`/`height`,\n * and `row` happened to be the axis they wanted. Naming the axis per side fixes bottom/top\n * and is a no-op for left/right (and for `<Modal>`, which centers on both axes either way).\n */\nconst SHEET_LAYOUT: Record<SheetSide, { container: Container; panel: CSSProperties }> = {\n bottom: { container: { flexDirection: 'column', justifyContent: 'flex-end', alignItems: 'stretch' }, panel: { borderTopLeftRadius: 16, borderTopRightRadius: 16, padding: 16, maxHeight: '90vh', overflow: 'auto' } },\n top: { container: { flexDirection: 'column', justifyContent: 'flex-start', alignItems: 'stretch' }, panel: { borderBottomLeftRadius: 16, borderBottomRightRadius: 16, padding: 16, maxHeight: '90vh', overflow: 'auto' } },\n left: { container: { flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'stretch' }, panel: { height: '100%', width: 'min(420px, 90vw)', padding: 16, overflow: 'auto' } },\n right: { container: { flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'stretch' }, panel: { height: '100%', width: 'min(420px, 90vw)', padding: 16, overflow: 'auto' } },\n}\n\n/**\n * The floating variant has no static container: its placement is per-mode and the shell\n * supplies it from {@link floatingGeometry} once it knows the viewport.\n */\nconst FLOATING_CONTAINER: Container = {}\n\n// ── Motion ──────────────────────────────────────────────────\n\n/**\n * The one spring — the entry offset, and nothing else (the sheet's height is reserved by\n * layout, never animated; see the module header).\n *\n * Solved, not guessed: the reference sheet's computed transition is `0.58913s`, which is a\n * spring-solver-derived duration rather than a hand-authored one. `stiffness: 100,\n * damping: 18, mass: 1` is the (ζ = 0.9) spring whose settle time under framer-motion's own\n * generator is **589ms** for the 32px entry offset — the same motion, from a real solver\n * instead of a transcribed number. ζ = 0.9 puts the overshoot at ~0.15% (0.05px on the\n * entry), so it reads as \"rises and settles\", not as a bounce.\n */\nexport const OVERLAY_SPRING = { type: 'spring', stiffness: 100, damping: 18, mass: 1 } as const\n\n/** How far the card starts below its resting position. */\nexport const ENTRY_OFFSET = 32\n\n/** The backdrop's own fade — the reference runs it as a flat `opacity 0.5s`, in parallel. */\nconst BACKDROP_FADE = { duration: 0.5, ease: 'easeOut' } as const\n\n/**\n * A layout effect on the client, a plain effect where there is no DOM. The branch is decided\n * once at module scope on `typeof window`, so the hook order never varies within a runtime,\n * and React never warns about a layout effect on the server.\n */\nconst useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect\n\n/**\n * Which floating presentation to render, kept in sync with the viewport.\n *\n * The width is read in an EFFECT, never during render: the module is imported into SSR builds\n * (see state/ssr.node.test.tsx) and must not touch `window` while rendering. It is a *layout*\n * effect on the client, which runs after the portal commits but before the browser paints, so\n * the pre-measurement default below is never actually seen — no flash, no mid-entry re-layout.\n *\n * `resize` covers the desktop case and, on a phone, also fires for the software keyboard and\n * for URL-bar chrome; `orientationchange` covers the rotations some older mobile browsers\n * report without a `resize`. Both re-derive the same pure {@link floatingMode}, and setting\n * the identical mode again is a React bail-out, so a stream of resize events over a drag\n * re-renders at most twice: once entering desktop, once leaving it.\n */\nfunction useFloatingMode(active: boolean): FloatingMode {\n // Mobile-first: this is the value a runtime with no `window` would keep, and it is the\n // safer of the two if a browser somehow paints before the layout effect (a full-width,\n // bottom-anchored card is legible at any width; a 440px card at 320px is not).\n const [mode, setMode] = useState<FloatingMode>('mobile')\n\n useIsomorphicLayoutEffect(() => {\n if (!active || typeof window === 'undefined') return\n const sync = () => setMode(floatingMode(window.innerWidth))\n sync()\n window.addEventListener('resize', sync)\n window.addEventListener('orientationchange', sync)\n return () => {\n window.removeEventListener('resize', sync)\n window.removeEventListener('orientationchange', sync)\n }\n }, [active])\n\n return mode\n}\n\n/**\n * Keeps `--af-overlay-fade` on the card in sync with \"is there more content below?\".\n *\n * Written to the DOM node directly, never through React state: this flips on a scroll and the\n * overlay hosts a provider iframe — re-rendering the tree for a cosmetic flag would be paid\n * for by every consumer of it. One `setProperty` call invalidates the two fade elements' paint\n * and nothing else, and the value is inherited, so neither fade needs to be reachable from here.\n *\n * COST, which is the point of the shape below:\n * - the `scroll` listener is `passive` (never blocks the compositor) and does one integer\n * compare — if a measurement is already queued it returns immediately. So the actual work is\n * at most ONCE PER ANIMATION FRAME however fast the buyer flicks, and it is three layout\n * reads on one element plus, only when the answer CHANGED, a style write.\n * - `ResizeObserver` covers the reason this can't be scroll-only: Stripe's PaymentElement\n * grows after load (Link's \"save my information\" block expanding, an OTP step swapping in),\n * which changes `scrollHeight` without any scroll event at all. It watches the card (the\n * viewport side of the sum) and the card's direct children (the content side — growth\n * anywhere inside the provider's tree propagates up to them, since they are in normal flow).\n * - `MutationObserver` on `childList` alone re-subscribes if the card's direct children are\n * swapped. Insurance: in practice they are stable for the sheet's lifetime, so it never\n * fires, and watching one level of childList costs nothing when nothing changes.\n * Both observers and the listener are torn down on unmount, and a queued frame is cancelled.\n *\n * Guarded on `typeof` rather than assumed: this module is imported into SSR builds, and the\n * fade degrades to permanently-off (its `var()` fallback) wherever the observers are missing.\n */\nfunction useScrollFade(active: boolean): { current: HTMLDivElement | null } {\n const ref = useRef<HTMLDivElement | null>(null)\n\n useIsomorphicLayoutEffect(() => {\n const el = ref.current\n if (!active || !el || typeof window === 'undefined') return\n\n let queued = 0\n const measure = () => {\n queued = 0\n const visible = scrollFadeVisible(el.scrollTop, el.scrollHeight, el.clientHeight)\n el.style.setProperty('--af-overlay-fade', visible ? '1' : '0')\n }\n const schedule = () => {\n if (!queued) queued = window.requestAnimationFrame(measure)\n }\n\n measure()\n el.addEventListener('scroll', schedule, { passive: true })\n\n let ro: ResizeObserver | null = null\n let mo: MutationObserver | null = null\n if (typeof ResizeObserver !== 'undefined') {\n const observer = new ResizeObserver(schedule)\n ro = observer\n const watch = () => {\n observer.observe(el)\n for (const child of Array.from(el.children)) observer.observe(child)\n }\n watch()\n if (typeof MutationObserver !== 'undefined') {\n mo = new MutationObserver(() => {\n watch()\n schedule()\n })\n mo.observe(el, { childList: true })\n }\n }\n\n return () => {\n if (queued) window.cancelAnimationFrame(queued)\n el.removeEventListener('scroll', schedule)\n ro?.disconnect()\n mo?.disconnect()\n }\n }, [active])\n\n return ref\n}\n\n/** Shared overlay shell: portal, backdrop, scroll-lock, Escape — variant-agnostic. */\nfunction OverlayShell({\n open,\n onClose,\n className,\n backdropClassName,\n dismissOnBackdrop = true,\n ariaLabel,\n container,\n panel,\n backdrop,\n gutter,\n variant,\n children,\n}: ShellProps): ReactNode {\n const floating = variant === 'floating'\n const mode = useFloatingMode(floating && open)\n // Floating only — `edge` and <Modal> keep the untouched panel below, ref and all.\n const cardRef = useScrollFade(floating && open)\n // `null` on the server and on the very first client render; the overlay only ever mounts\n // from a client interaction, so it never participates in hydration either way.\n const reduced = useReducedMotion()\n\n useEffect(() => {\n if (!open || typeof document === 'undefined') return\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') onClose()\n }\n const prev = document.body.style.overflow\n document.body.style.overflow = 'hidden'\n document.addEventListener('keydown', onKey)\n return () => {\n document.body.style.overflow = prev\n document.removeEventListener('keydown', onKey)\n }\n }, [open, onClose])\n\n if (!open || typeof document === 'undefined') return null\n\n const backdropProps = {\n 'data-appfunnel-overlay-backdrop': '',\n className: backdropClassName,\n onClick: dismissOnBackdrop ? onClose : undefined,\n style: { position: 'absolute' as const, inset: 0, background: backdrop },\n }\n\n const panelStyle: CSSProperties = {\n position: 'relative',\n background: OVERLAY_SURFACE,\n // Custom properties aren't in React's CSSProperties; the cast is the only way to set one\n // inline, and is exactly what React itself supports at runtime.\n ...(overlayVars(gutter) as unknown as CSSProperties),\n ...panel,\n }\n\n // EDGE (and <Modal>): the pre-motion tree, unchanged — plain divs, no animation, no\n // LazyMotion provider, no extra wrapper between the container and the panel.\n if (!floating) {\n return createPortal(\n createElement(\n 'div',\n {\n role: 'dialog',\n 'aria-modal': true,\n 'aria-label': ariaLabel,\n 'data-appfunnel-overlay': '',\n style: { position: 'fixed', inset: 0, zIndex: 1000, display: 'flex', ...container },\n },\n createElement('div', backdropProps),\n createElement('div', { 'data-appfunnel-overlay-panel': '', className, style: panelStyle }, children),\n ),\n document.body,\n )\n }\n\n // FLOATING: the backdrop fades and the frame springs up — transform and opacity only, which\n // is the whole animation. The card inside it is an ordinary div: it is the scrollport, and\n // must be neither transformed nor animated.\n // (`frameProps` is hoisted out of the call so the `data-*` seam isn't excess-property-checked\n // against framer's motion props — it is a real DOM attribute, forwarded verbatim.)\n const geometry = floatingGeometry(mode)\n ensureCardScrollbarStyles()\n const frameProps = {\n 'data-appfunnel-overlay-frame': '',\n style: geometry.frame,\n initial: reduced ? false : { opacity: 0, y: ENTRY_OFFSET },\n animate: { opacity: 1, y: 0 },\n transition: reduced ? { duration: 0 } : OVERLAY_SPRING,\n }\n const overlay = createElement(\n 'div',\n {\n role: 'dialog',\n 'aria-modal': true,\n 'aria-label': ariaLabel,\n 'data-appfunnel-overlay': '',\n // The floating variant places itself: `container` from the caller carries the shared\n // bits, `geometry.container` the per-mode anchoring.\n style: { position: 'fixed', inset: 0, zIndex: 1000, display: 'flex', ...container, ...geometry.container },\n },\n createElement(m.div, {\n ...backdropProps,\n initial: reduced ? false : { opacity: 0 },\n animate: { opacity: 1 },\n transition: BACKDROP_FADE,\n }),\n createElement(\n m.div,\n frameProps,\n createElement(\n 'div',\n {\n 'data-appfunnel-overlay-panel': '',\n // The card-only seam CARD_SCROLLBAR_CSS hooks; see the note there for why it isn't the\n // panel attribute above.\n 'data-appfunnel-overlay-card': '',\n className,\n ref: cardRef,\n style: { ...panelStyle, ...geometry.card },\n },\n children,\n // Last child by construction — see OVERLAY_FADE. It takes no room in the flow, so the\n // funnel's own children still lay out (and still ARE) the card's content exactly as\n // before; the tail of them is simply overlaid while there is more to scroll.\n createElement('div', { 'data-appfunnel-overlay-fade': '', 'aria-hidden': true, style: OVERLAY_FADE }),\n ),\n ),\n )\n\n return createPortal(\n createElement(LazyMotion, { features: domAnimation, strict: true }, overlay),\n document.body,\n )\n}\n\nexport type SheetProps = OverlayCommon & {\n /** Edge the drawer slides from (default `bottom`). Ignored when `variant=\"floating\"`. */\n side?: SheetSide\n /** Presentation style (default `edge`) — see {@link SheetVariant}. */\n variant?: SheetVariant\n}\n\n/**\n * A drawer, or (with `variant=\"floating\"`) a centered card. Inside a `defineModal` it\n * auto-binds — `<Sheet>…`; outside one, control it with `open`/`onClose`.\n */\nexport function Sheet(props: SheetProps): ReactNode {\n const control = useModalControl()\n const variant = props.variant ?? 'edge'\n const layout = SHEET_LAYOUT[props.side ?? 'bottom']\n return createElement(OverlayShell, {\n ...control,\n className: props.className,\n backdropClassName: props.backdropClassName,\n dismissOnBackdrop: props.dismissOnBackdrop,\n ariaLabel: props.ariaLabel,\n variant,\n container: variant === 'floating' ? FLOATING_CONTAINER : layout.container,\n panel: variant === 'floating' ? {} : layout.panel,\n // The floating card sits on the reference's lighter scrim; the edge drawers keep theirs.\n backdrop: variant === 'floating' ? 'rgba(0,0,0,0.45)' : 'rgba(0,0,0,0.5)',\n gutter: variant === 'floating' ? FLOATING_GUTTER : EDGE_GUTTER,\n children: props.children,\n })\n}\n\nexport type ModalProps = OverlayCommon\n\n/** A centered dialog. Auto-binds to its `defineModal` — `<Modal>…`. */\nexport function Modal(props: ModalProps): ReactNode {\n const control = useModalControl()\n return createElement(OverlayShell, {\n ...control,\n className: props.className,\n backdropClassName: props.backdropClassName,\n dismissOnBackdrop: props.dismissOnBackdrop,\n ariaLabel: props.ariaLabel,\n variant: 'edge',\n container: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center' },\n panel: { borderRadius: 16, padding: 24, width: 'min(480px, 92vw)', maxHeight: '90vh', overflow: 'auto' },\n backdrop: 'rgba(0,0,0,0.5)',\n gutter: MODAL_GUTTER,\n children: props.children,\n })\n}\n","/**\n * v2 commerce primitives — three components, and the question each one answers is its NAME.\n *\n * ```tsx\n * <Checkout offering=\"plan\" /> // payment renders HERE\n * <CheckoutButton offering=\"plan\">Get my plan</CheckoutButton> // …and this opens it elsewhere\n * <UpsellButton offering=\"addon\">Add it</UpsellButton> // one tap; opens only to recover\n * ```\n *\n * - `<Checkout>` — the **purchase** primitive, rendered where you put it. Takes no children,\n * because there is no trigger: the payment IS what it renders.\n * - `<CheckoutButton>` — the same purchase, opened from a button. Takes `opens` (our sheet, the\n * provider's popup, or a full-page redirect) and children/`asChild` for the button itself.\n * - `<UpsellButton>` — the **upsell** primitive. Off-session charge to the saved method, one tap,\n * no card re-entry; it only opens anything when that charge fails and it recovers on-session.\n * - `useCheckout()` — the headless hook under all three, always available for a fully-custom CTA.\n *\n * Both Checkout components take `payment` — {@link PaymentMode}, WHAT the buyer sees — defaulting to\n * `'auto'`, the best complete payment UI this provider can render here. Position in the JSX carries\n * WHERE, which is what makes `children`/`asChild` structurally meaningful: they exist on the\n * components that have a button and are a compile error on the one that doesn't.\n *\n * `surface` — one word answering both questions — is still accepted on `<Checkout>`; see\n * {@link CheckoutLegacyProps}.\n *\n * The SDK never talks to a provider. It owns the state machine + the analytics\n * (`checkout.start` / `purchase.complete`) + post-charge navigation, and\n * delegates the actual charge/render to an injected {@link CheckoutDriver}\n * (the real one is platform-side; tests use {@link createMockDriver}).\n *\n * Which offering is charged is the author's bound variable, captured at render\n * (inline surfaces) or at `open()` time (trigger surfaces).\n */\n\nimport {\n\tcreateContext,\n\tcreateElement,\n\tisValidElement,\n\tcloneElement,\n\tuseCallback,\n\tuseContext,\n\tuseEffect,\n\tuseRef,\n\tuseState,\n\ttype ComponentType,\n\ttype ReactElement,\n\ttype ReactNode,\n} from 'react'\nimport type { Appearance as StripeAppearance } from '@stripe/stripe-js'\nimport type { CheckoutSettings as PaddleCheckoutSettings } from '@paddle/paddle-js'\nimport { useTrackerRef, newEventId } from '../tracking/tracking'\nimport { useCatalog, useOffering, type Interval } from './catalog'\nimport { useNavigation } from '../flow/flow'\nimport { useFunnel } from '../state/namespaces'\nimport { Sheet } from '../modals/sheet'\nimport { defineModal, useModal, showModal } from '../modals/registry'\nimport {\n\tcheckoutError,\n\tisInlineSurface,\n\tprofileFor,\n\tresolvePayment,\n\tresolveSurface,\n\tvalidateCheckout,\n\tPAYMENT_RENDERINGS,\n\ttype CheckoutError,\n\ttype CheckoutErrorCategory,\n\ttype CheckoutIntent,\n\ttype CheckoutProvider,\n\ttype CheckoutSurface,\n\ttype DeviceClass,\n\ttype HostedPaymentMode,\n\ttype OpensIn,\n\ttype PaymentMode,\n\ttype PaymentRendering,\n\ttype UpsellKind,\n} from './capabilities'\n\n// ── Capability matrix (pure — lives in ./capabilities, ships via the manifest\n// entry so the API/editor/AI run the SAME checks; re-exported here so every\n// existing import keeps working) ───────────────────────\nexport {\n\tINLINE_SURFACES,\n\tMANAGED_PROFILES,\n\tPAYMENT_RENDERINGS,\n\tPROVIDER_HOSTED_SURFACES,\n\tPROVIDER_PROFILES,\n\tcheckoutError,\n\tisCompleteSurface,\n\tisInlineSurface,\n\tisMerchantOfRecord,\n\tisOrchestrator,\n\tisProviderHostedSurface,\n\tisRenderableSurface,\n\tprofileFor,\n\trenderableSurfaces,\n\tresolvePayment,\n\tresolveSurface,\n\tsupportsManaged,\n\tsurfacesFor,\n\ttrialShapesFor,\n\tvalidateCheckout,\n\tvalidateTrial,\n\tvalidateTrialSurface,\n\tvalidateUpsell,\n} from './capabilities'\nexport type {\n\tCheckoutError,\n\tCheckoutErrorCategory,\n\tCheckoutIntent,\n\tCheckoutProvider,\n\tCheckoutSurface,\n\tDeviceClass,\n\tHostedPaymentMode,\n\tOffSessionReliability,\n\tOpensIn,\n\tPaymentMode,\n\tPaymentRendering,\n\tProviderProfile,\n\tProviderVariant,\n\tSurfaceCapability,\n\tSurfacePreference,\n\tTrialShape,\n\tUpsellKind,\n\tValidationResult,\n} from './capabilities'\n\n/**\n * The one place the runtime asks the matrix \"can this checkout exist?\" — the author-time\n * (surface × variant) gate, evaluated in the browser instead of on the wire. Returns the matrix's\n * reason when the pair can't be produced, `undefined` when it can.\n *\n * Deliberately INERT without a variant: a plain pinned surface is validated at publish and must\n * keep reaching the driver exactly as it did before managed existed. What this catches is the one\n * mistake only authoring can make — under `managed` Stripe collects the card in its own frame, so\n * pinning `element` or `express` beside it (each one a Stripe Elements component we would mount in\n * the page ourselves) asks for a checkout that cannot exist. `sheet` is NOT one of them and is not\n * refused: it is the funnel's own overlay hosting whatever the driver renders, which under managed\n * is Stripe's embedded checkout. The server refuses the impossible pairs too, but only after a\n * round-trip and as a generic rejection; the matrix's reason names BOTH halves so the author knows\n * which one to give up.\n */\nfunction refuseSurface(\n\tprovider: CheckoutProvider,\n\tsurface: CheckoutSurface,\n\tmanaged?: boolean\n): string | undefined {\n\tif (!managed) return undefined\n\tconst check = validateCheckout(provider, surface, { managed })\n\treturn check.ok\n\t\t? undefined\n\t\t: (check.reason ??\n\t\t\t\t`'${surface}' isn't available on ${provider} managed payments`)\n}\n\n// ── Driver seam ──────────────────────────────────────────\n\nexport type CheckoutStatus =\n\t| 'idle'\n\t| 'loading'\n\t| 'requires_action'\n\t| 'success'\n\t| 'error'\n\nexport interface CheckoutRequest {\n\t/** The offering SLOT the page named (`<Checkout offering=\"primary\">`) — the display/analytics identity. Kept as the wire field `product` at the provider boundary. */\n\tproduct: string\n\t/** The catalog charge KEY charged — the CHARGE identity, resolved from `product` by {@link driverWithCatalog}. */\n\tcatalogKey?: string\n\tintent: CheckoutIntent\n\t/**\n\t * WHERE the attempt is presented — the CONTAINER. This is the field that crosses the wire\n\t * (`CheckoutSessionRequest.surface` in ./checkout-api) and the one the server validates and\n\t * answers with a payment step. Absent = off-session: no UI at all (the one-tap upsell).\n\t */\n\tsurface?: CheckoutSurface\n\t/**\n\t * WHAT the provider was asked to render inside that container — the author's word, kept whole.\n\t *\n\t * Absent on nearly every attempt, because the two questions usually have one answer:\n\t * `<Checkout payment=\"card\">` mounts an inline card form in the page, and the page IS the\n\t * container. They come apart in exactly one place — an on-session RECOVERY, which has no page\n\t * slot to mount into and is therefore re-hosted in the SDK's sheet. There the container is\n\t * `sheet` while the author asked for, say, a wallet quick-button. Until this field existed the\n\t * container simply OVERWROTE the author's word on the way to the driver, and a\n\t * `recover={{ payment: 'express' }}` got a card form — silently, because a card form is a\n\t * perfectly good checkout and nothing on the wire disagreed.\n\t *\n\t * CLIENT-SIDE ONLY, and that is not a shortcut: the server is asked for a payment STEP, and\n\t * `express` and `element` are the same step (`client_confirm` — one intent, one clientSecret).\n\t * The difference is purely which of the provider's components the driver mounts against it, so\n\t * it is the driver's question and never the server's. `postSession` builds its body field by\n\t * field and doesn't read this, so the wire is byte-identical to before.\n\t *\n\t * Drivers read it as `req.rendering ?? req.surface`; a driver that ignores it entirely keeps\n\t * behaving exactly as it did.\n\t */\n\trendering?: CheckoutSurface\n\t/**\n\t * For `upsell` intent — which kind of off-session charge. Filled in from the offering by\n\t * {@link driverWithCatalog} when the author didn't say (see {@link upsellKindFor}); absent\n\t * only when the slot doesn't resolve, and the server then applies its own default.\n\t */\n\tkind?: UpsellKind\n\t/**\n\t * Run this attempt through the provider's MANAGED (provider-as-Merchant-of-Record) mode —\n\t * Stripe Managed Payments, the only variant today. Author-set per checkout (see\n\t * {@link UseCheckoutOptions.managed}); drivers forward it verbatim to the wire's\n\t * `CheckoutSessionRequest.managed`, where the SERVER re-validates it against the\n\t * mode-resolved store's eligibility. Absent/false = ordinary provider checkout.\n\t */\n\tmanaged?: boolean\n\t/**\n\t * Buyer email at attempt time, read from the funnel's `user.email` namespace value\n\t * (injected by `FunnelProvider` via {@link driverWithEmail} — no author wiring).\n\t * Drivers forward it into the wire `CheckoutSessionRequest.email` (Stripe Customer\n\t * creation / receipts / Paddle prefill).\n\t */\n\temail?: string\n\t/**\n\t * How the PROVIDER should paint its own fields — see {@link CheckoutAppearance}. Display-only:\n\t * `postSession` builds its wire body field by field, so this never leaves the browser.\n\t */\n\tappearance?: CheckoutAppearance\n\t/**\n\t * How the provider LISTS the payment methods — see {@link CheckoutMethods}. Display-only, same\n\t * as `appearance`: it never leaves the browser.\n\t */\n\tmethods?: CheckoutMethods\n\t/**\n\t * Classes for the buttons the SDK renders itself — see {@link CheckoutClassNames}. Display-only.\n\t */\n\tclassNames?: CheckoutClassNames\n}\n\n/**\n * Classes for the buttons the SDK renders ITSELF — the pay button, and \"Pay another way\".\n *\n * Both ship styled: a funnel that sets nothing gets buttons that already look deliberate, rather\n * than raw browser chrome the author has to discover and fix. Pass a class here and the SDK drops\n * its own styling for that button entirely, so Tailwind (or anything else) owns it outright with no\n * inline styles to out-specify and no `!important`.\n *\n * ```tsx\n * <Checkout\n * offering=\"plan\"\n * classNames={{\n * submit: 'w-full rounded-xl bg-emerald-600 py-4 text-lg font-bold text-white',\n * payAnotherWay: 'mt-3 w-full rounded-xl bg-neutral-100 py-3 font-semibold',\n * }}\n * />\n * ```\n *\n * The provider's own fields are a different question — they render inside its frame, where no class\n * of yours reaches. Theme those with {@link CheckoutAppearance}.\n */\n/**\n * DEFAULT BUTTON STYLING — the SDK's buttons must never render as raw browser chrome.\n *\n * `Pay now` and `Pay another way` are ours, not the provider's, so nothing paints them unless we\n * do. Shipping them bare made every funnel hand-write attribute-selector CSS before its checkout\n * stopped looking broken: a tax on the common case, and easy to forget entirely.\n *\n * Every rule is wrapped in `:where()`, which contributes ZERO specificity. That is the whole\n * mechanism, and it is why these are a stylesheet rather than inline styles:\n *\n * - inline styles would beat every stylesheet, beginning with the `[data-checkout-submit]` rules\n * real funnels already ship — the SDK would have silently repainted their CTA;\n * - a plain `[data-checkout-submit]` rule of ours would tie those funnels on specificity and be\n * settled by injection order, which is not a contract anyone can rely on.\n *\n * At zero specificity ANY author rule wins outright — one Tailwind class, an attribute selector, a\n * `className` through {@link CheckoutClassNames} — with no `!important` and no ordering games. The\n * default is what you get when you have said nothing at all.\n *\n * THE DEFAULT HAS TO BE GOOD, not merely present. Anything a funnel would have to restyle to look\n * finished is work every other funnel inherits too, so the pay button ships at the size, weight and\n * radius a paywall CTA actually wants, in near-black — which sits correctly on any palette rather\n * than merely avoiding offence. No variables to learn and nothing to configure: a funnel that says\n * nothing gets a checkout that already looks deliberate.\n */\nconst CHECKOUT_BUTTON_CSS = `\n:where([data-checkout-submit],[data-checkout-another-way],[data-mock-surface]){\ndisplay:block;width:100%;box-sizing:border-box;border:0;cursor:pointer;font:inherit;\nline-height:1.25;text-align:center;-webkit-appearance:none;appearance:none;\ntransition:transform .15s ease,opacity .2s ease,background-color .2s ease}\n:where([data-checkout-submit],[data-mock-surface]){\nmargin-top:16px;padding:16px 20px;border-radius:12px;font-size:17px;font-weight:700;\nletter-spacing:-.01em;color:#fff;\nbackground:#111827}\n:where([data-checkout-another-way]){\nmargin-top:10px;padding:13px 20px;border-radius:12px;font-size:15px;font-weight:600;\nbackground:transparent;color:#6b7280}\n:where([data-checkout-another-way]:hover){background:rgba(0,0,0,.04);color:inherit}\n:where([data-checkout-submit]:active,[data-checkout-another-way]:active,[data-mock-surface]:active){transform:scale(.98)}\n:where([data-checkout-submit]:disabled,[data-mock-surface]:disabled){opacity:.55;cursor:default;transform:none}\n:where([data-checkout-submit]:focus-visible,[data-checkout-another-way]:focus-visible,[data-mock-surface]:focus-visible){\noutline:2px solid currentColor;outline-offset:2px}\n@keyframes af-checkout-spin{to{transform:rotate(360deg)}}\n:where([data-checkout-spinner]){\ndisplay:inline-block;vertical-align:-.125em;width:1.15em;height:1.15em;\nanimation:af-checkout-spin .7s linear infinite}\n@media (prefers-reduced-motion:reduce){\n:where([data-checkout-spinner]){animation-duration:2.4s}}\n`\nconst CHECKOUT_BUTTON_STYLE_ID = 'af-checkout-button-defaults'\n\n/**\n * The busy indicator the SDK shows while a charge is in flight — a circular track with a moving arc,\n * drawn in `currentColor` so it takes the button's own text colour wherever it lands.\n *\n * SVG rather than a bordered div: a border-spinner inherits the button's box sizing and breaks the\n * moment someone restyles the button, and it can't be recoloured by text colour alone. Marked\n * `aria-hidden` because the state is already carried by the button's `disabled` — a screen reader\n * announcing a decorative circle adds nothing.\n */\nexport function CheckoutSpinner(): ReactNode {\n\t// SELF-SUFFICIENT. Every visible property of this element — its 1.15em box, `inline-block`, and\n\t// the rotation itself — lives in CHECKOUT_BUTTON_CSS, so rendering the SVG without that\n\t// stylesheet paints nothing that reads as a spinner. Until 2026-07-29 the only production\n\t// injector was `ConfirmForm` (drivers/stripe.tsx), i.e. the Stripe Elements CARD FORM, and the\n\t// two places the spinner actually appears need no card form at all: an off-session\n\t// `<UpsellButton>` mounts no surface, and a managed checkout paints Stripe's own iframe. So on\n\t// ThriftAI's \"Add to my program\" the busy state was correct and simply invisible — the buyer\n\t// tapped, nothing moved, and they tapped again. Injecting here means the spinner carries its own\n\t// styling wherever it is used, including from a funnel's render prop.\n\t//\n\t// Idempotent and SSR-safe (ensureCheckoutButtonStyles no-ops without a document and after the\n\t// first call), and called during render exactly as ConfirmForm has always called it.\n\tensureCheckoutButtonStyles()\n\treturn createElement(\n\t\t'svg',\n\t\t{ 'data-checkout-spinner': '', viewBox: '0 0 24 24', fill: 'none', 'aria-hidden': true, focusable: 'false' },\n\t\tcreateElement('circle', {\n\t\t\tcx: 12, cy: 12, r: 9, stroke: 'currentColor', strokeWidth: 3, opacity: 0.25,\n\t\t}),\n\t\tcreateElement('path', {\n\t\t\td: 'M21 12a9 9 0 0 0-9-9', stroke: 'currentColor', strokeWidth: 3, strokeLinecap: 'round',\n\t\t}),\n\t)\n}\n\n/** Inject the defaults once per document. No-op on the server and after the first call. */\nexport function ensureCheckoutButtonStyles(): void {\n if (typeof document === 'undefined' || document.getElementById(CHECKOUT_BUTTON_STYLE_ID)) return\n const style = document.createElement('style')\n style.id = CHECKOUT_BUTTON_STYLE_ID\n style.textContent = CHECKOUT_BUTTON_CSS\n // FIRST in <head>, so that even an author rule of equal specificity (another `:where()`, say)\n // still wins on order. Nothing here should ever outrank the funnel's own stylesheet.\n document.head.prepend(style)\n}\n\nexport interface CheckoutClassNames {\n\t/** The pay button (`[data-checkout-submit]`). */\n\tsubmit?: string\n\t/** The \"Pay another way\" control under a wallet button (`[data-checkout-another-way]`). */\n\tpayAnotherWay?: string\n}\n\n/**\n * Theming for the payment fields the PROVIDER renders.\n *\n * Those fields live in a cross-origin iframe, so no amount of CSS in the funnel reaches them — the\n * provider has to be told how to paint them. (The funnel's own submit button is ordinary DOM and\n * needs none of this; style it with the `[data-checkout-submit]` attribute.)\n *\n * DELIBERATELY NOT NORMALIZED. Providers share almost nothing here: Stripe Elements takes ~100\n * design tokens plus per-selector rules, Paddle takes a light/dark flag and puts everything else in\n * its dashboard, Whop exposes four tokens, SolidGate takes per-element CSS and no tokens at all. The\n * true intersection is roughly `{ theme }`, so a common shape would be either useless or a lie about\n * what actually applies. Instead each provider gets its OWN key, typed straight from that provider's\n * package — nothing here to keep in sync as they evolve, and no silent dropping of a token the\n * provider never supported.\n *\n * ```tsx\n * <Checkout offering=\"plan\" payment=\"card\" appearance={{\n * stripe: { variables: { colorPrimary: '#2cad39', fontFamily: 'Inter, sans-serif' } },\n * }} />\n * ```\n *\n * Only the surfaces the SDK mounts itself can be themed this way — `element`, `express`, and the\n * `sheet` that hosts them. `embedded` is the provider's own hosted page (Stripe serves it from\n * `js.stripe.com`), which takes its styling from that provider's dashboard instead.\n */\nexport interface CheckoutAppearance {\n\t/** Stripe's Appearance API, verbatim — `theme`, `variables`, `rules`, `labels`, `inputs`. */\n\tstripe?: StripeAppearance\n\t/**\n\t * Paddle's presentational checkout settings. Narrowed from their `CheckoutSettings` to the\n\t * fields an author can safely own: the rest is plumbing the driver sets for correctness —\n\t * `displayMode`/`frameTarget` wire the frame up, and `variant` is how the express surface is\n\t * selected, so overriding any of them would break the surface rather than restyle it.\n\t * Paddle's real branding lives in its dashboard; `theme` is the only client-side colour knob.\n\t */\n\tpaddle?: Pick<PaddleCheckoutSettings, 'theme' | 'frameStyle' | 'frameInitialHeight'>\n}\n\n/**\n * How the list of payment methods is PRESENTED, in the surfaces the SDK mounts itself.\n *\n * Normalized, unlike {@link CheckoutAppearance} — and the difference is real rather than an\n * inconsistency. Appearance is a token bag whose true cross-provider intersection is roughly empty,\n * so a shared shape there would be a lie. \"Stack the methods and start them collapsed\" is one idea\n * with one meaning, so it gets one spelling.\n *\n * The DEFAULT is `{ layout: 'accordion', collapsed: true }`: the buyer sees the methods they can pay\n * with — wallets included — and picks one before any field appears, instead of landing on an open\n * card form with the wallet they'd have preferred hidden below it.\n *\n * ```tsx\n * <Checkout offering=\"plan\" /> // accordion, collapsed\n * <Checkout offering=\"plan\" methods={{ collapsed: false }} /> // first method open\n * <Checkout offering=\"plan\" methods={{ layout: 'tabs' }} /> // methods across the top\n * <Checkout offering=\"plan\" methods={{ order: ['apple_pay', 'card'] }} /> // lead with Apple Pay\n * ```\n *\n * **Only applies where the SDK mounts the method list** — `payment=\"card\"`, and the `payment=\"auto\"`\n * fallback when no wallet is enrolled, on Stripe. It is IGNORED, never an error, when the provider\n * owns the whole UI: `payment=\"full\"`, anything under `managed`, and Paddle, which has no equivalent\n * setting. Wallets also have to be able to appear at all before ordering them means anything — that\n * needs the domain registered with Stripe as a payment method domain.\n */\nexport interface CheckoutMethods {\n\t/** `'accordion'` (default) stacks the methods as rows; `'tabs'` runs them across the top. */\n\tlayout?: 'accordion' | 'tabs'\n\t/** Start with every method closed, so the buyer chooses before any fields render. Default `true`. */\n\tcollapsed?: boolean\n\t/**\n\t * Force the LEADING methods, e.g. `['apple_pay', 'google_pay', 'card']`; the provider orders\n\t * whatever isn't named. Left alone, Stripe orders by what it expects this buyer to convert on.\n\t */\n\torder?: string[]\n\t/**\n\t * Offer \"Pay another way\" beneath the wallet button. Default `true`.\n\t *\n\t * `false` makes a wallet-led checkout wallet-ONLY: a buyer with Apple Pay enrolled sees that\n\t * button and nothing else, with no card form to drop into. It does NOT strand the walletless —\n\t * when no wallet is enrolled there is no wallet button to stand alone, and the card form is\n\t * shown as it always is. The choice is only about buyers who HAVE a wallet.\n\t *\n\t * Worth being deliberate about: a buyer whose enrolled card fails inside the wallet sheet has\n\t * nowhere else to go on this screen. Leave it on unless the funnel is deliberately wallet-only.\n\t */\n\tpayAnotherWay?: boolean\n}\n\nexport interface CheckoutResult {\n\tok: boolean\n\terror?: CheckoutError\n\t/** Charged amount in minor units (for the purchase event). */\n\tamountMinor?: number\n\tcurrency?: string\n\t/**\n\t * The **server-minted** dedup id for the purchase event — the platform creates it\n\t * when the charge settles and fires CAPI with it; the SDK emits `purchase.complete`\n\t * with the same id so the browser pixel dedupes against the server. (Server is the\n\t * source of truth for payment events; the SDK doesn't mint these.)\n\t */\n\teventId?: string\n}\n\nexport interface CheckoutCallbacks {\n\tonSuccess: (result: CheckoutResult) => void\n\tonError: (error: CheckoutError) => void\n\t/**\n\t * The buyer SUBMITTED an inline surface (Stripe confirm click / wallet\n\t * authorization; Paddle inline checkout opening). This is when `checkout.start`\n\t * fires and the status machine enters `loading` for inline attempts — trigger\n\t * surfaces fire it at click time instead. It also marks fresh user intent, so\n\t * the once-per-chain recovery guard resets. Optional: drivers that can't\n\t * observe submit simply never call it, and the SHEET host deliberately doesn't\n\t * forward it (the sheet's own open already began the attempt — re-firing would\n\t * double-count starts and un-arm the recovery guard mid-chain).\n\t */\n\tonStart?: () => void\n\t/**\n\t * The inline surface reports a valid payment method was entered (e.g. Stripe's\n\t * Payment Element became `complete`), before the charge. Drives the\n\t * `checkout.payment_added` analytics step; optional — drivers that can't observe\n\t * it (or off-session charges) simply never call it.\n\t */\n\tonPaymentAdded?: () => void\n}\n\n/**\n * What a driver factory (`stripeCheckoutDriver` et al. from the\n * `@appfunnel-dev/sdk/driver-*` entries) receives to construct a\n * {@link CheckoutDriver}. Derived by `createFunnelTree` from the SAME\n * renderer-injected mount data the platform tracker uses (tracking config +\n * identity), so checkout wire calls land on the exact campaign/funnel/session\n * the analytics do — there is no second config channel to drift.\n *\n * Serializable on purpose, and factories must be **construction-safe on the\n * server too**: a factory only closes over this ctx (no provider SDK, no\n * `window`) — all provider work belongs in effects/event handlers, so SSR can\n * render the driver's stable inline placeholder and hydration matches.\n */\nexport interface CheckoutDriverContext {\n\t/** Public API origin, e.g. `https://api.appfunnel.net` (no trailing slash). */\n\tapiBase: string\n\t/**\n\t * Campaign DB id (the checkout route key, same as the ingestion route key). ABSENT on the\n\t * build-preview surface, which is served by build id and belongs to no campaign — `preview`\n\t * below carries that surface's routing + credential instead. Exactly one of the two is set.\n\t */\n\tcampaignId?: string | null\n\t/**\n\t * Build-preview checkout (authors QA-ing an unpublished build). Present → the driver targets\n\t * the campaign-less preview endpoint and authenticates with the build's preview token — the\n\t * SAME token the renderer already required to serve the page, simply forwarded. Only ever\n\t * valid with `mode: 'test'`; the server rejects anything else.\n\t */\n\tpreview?: {\n\t\t/** The build being previewed — what the token is signed over. */\n\t\tbuildId: string\n\t\t/** HMAC preview token (`?t=` on the preview URL). */\n\t\ttoken: string\n\t} | null\n\t/** WebFunnel DB id (NOT the funnel.ts config id). */\n\tfunnelId: string\n\t/** Render-time mode — the server resolves the product binding + store credentials by it. */\n\tmode: 'test' | 'live'\n\t/** Funnel session id when one exists (analytics + customer continuity). */\n\tsessionId?: string | null\n\t/** Signed-cookie-verified bare visitor id, when known. */\n\tvisitorId?: string | null\n}\n\n/**\n * The provider seam. The platform injects the real one (Stripe/Paddle/Whop/…);\n * tests use {@link createMockDriver}.\n *\n * Most providers ship their **own React SDK** (`@stripe/react-stripe-js`,\n * `@paddle/paddle-js`, Primer's React components, …). A driver's `renderInline`\n * returns exactly that: the provider's React element mounted in our chrome (inline,\n * or inside the `<Sheet>`). Those provider SDKs live in the **driver/platform**\n * package, not our core funnel SDK — which is why the driver is injected: the core\n * stays lean and provider-agnostic, and you only pull the SDK for the provider you use.\n */\nexport interface CheckoutDriver {\n\tprovider: CheckoutProvider\n\t/** Trigger a charge (trigger surfaces + programmatic). Resolves when settled. */\n\tstart(req: CheckoutRequest): Promise<CheckoutResult>\n\t/** Render an inline surface (e.g. the provider's React payment element); report via callbacks. */\n\trenderInline?(req: CheckoutRequest, cb: CheckoutCallbacks): ReactNode\n\t/**\n\t * Verify an EXISTING attempt with the server (`POST /complete`, bounded re-poll on\n\t * `pending`) — the redirect-return resume leg: hosted-checkout success URLs carry\n\t * `?af_checkout={correlationId}` back into the funnel, and {@link CheckoutResume}\n\t * hands the id here so the settlement (server-verified) resolves into the normal\n\t * success/failure paths. Never charges; only verifies.\n\t */\n\tresume?(correlationId: string): Promise<CheckoutResult>\n}\n\nexport interface MockDriverOptions {\n\t/** The result a successful charge resolves with. */\n\tresult?: CheckoutResult\n\t/** Make **off-session** charges (no surface) fail — to exercise the upsell's on-session recovery. */\n\tfailOffSession?: CheckoutError | boolean\n}\n\n/** A console/no-op driver — tests, preview, local dev. Succeeds unless configured to fail. */\nexport function createMockDriver(\n\tprovider: CheckoutProvider = 'stripe',\n\toptions: MockDriverOptions = {}\n): CheckoutDriver {\n\tconst success: CheckoutResult = options.result ?? {\n\t\tok: true,\n\t\tamountMinor: 0,\n\t\tcurrency: 'USD',\n\t}\n\tconst offError: CheckoutError =\n\t\ttypeof options.failOffSession === 'object'\n\t\t\t? options.failOffSession\n\t\t\t: checkoutError(\n\t\t\t\t\t'authentication_required',\n\t\t\t\t\t'off-session charge declined (mock)'\n\t\t\t\t)\n\treturn {\n\t\tprovider,\n\t\tstart: (req) => {\n\t\t\tif (options.failOffSession && !req.surface)\n\t\t\t\treturn Promise.resolve({ ok: false, error: offError })\n\t\t\treturn Promise.resolve(success)\n\t\t},\n\t\trenderInline: (req, cb) => {\n\t\t\t// The placeholder is a real button on screen in `appfunnel dev`, so it gets the same\n\t\t\t// default paint as the drivers' own — a dev preview shouldn't be the one place the\n\t\t\t// checkout looks unfinished.\n\t\t\tensureCheckoutButtonStyles()\n\t\t\treturn createElement(\n\t\t\t\t'button',\n\t\t\t\t{\n\t\t\t\t\ttype: 'button',\n\t\t\t\t\t'data-mock-surface': req.surface,\n\t\t\t\t\t// The container and the RENDERING are separate answers (see\n\t\t\t\t\t// CheckoutRequest.rendering) — a driver that collapsed them would silently\n\t\t\t\t\t// render the wrong thing, so the mock reports both and tests can tell.\n\t\t\t\t\t'data-mock-rendering': req.rendering ?? req.surface,\n\t\t\t\t\tonClick: () => {\n\t\t\t\t\t\tcb.onStart?.() // user submit — mirrors the real drivers (checkout.start for inline)\n\t\t\t\t\t\tif (success.ok) cb.onSuccess(success)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tcb.onError(\n\t\t\t\t\t\t\t\tsuccess.error ??\n\t\t\t\t\t\t\t\t\tcheckoutError(\n\t\t\t\t\t\t\t\t\t\t'processing_error',\n\t\t\t\t\t\t\t\t\t\t'failed (mock)'\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t`Pay (mock ${req.surface})`\n\t\t\t)\n\t\t},\n\t\tresume: () => Promise.resolve(success),\n\t}\n}\n\n/**\n * Wrap a driver so every attempt carries the buyer email the funnel has collected\n * (`user.email`), read at ATTEMPT time — `start()` for trigger surfaces, the\n * `renderInline` request for mounted surfaces. Applied by `FunnelProvider` around\n * the injected driver, so `useCheckout`, `<Checkout>` inline branches and the\n * checkout sheet all forward it without wiring; drivers pass it into the wire's\n * `CheckoutSessionRequest.email`. An explicit `req.email` always wins.\n */\nexport function driverWithEmail(\n\tdriver: CheckoutDriver,\n\tgetEmail: () => string | undefined\n): CheckoutDriver {\n\tconst enrich = (req: CheckoutRequest): CheckoutRequest =>\n\t\treq.email !== undefined ? req : { ...req, email: getEmail() }\n\treturn {\n\t\t...driver,\n\t\tstart: (req) => driver.start(enrich(req)),\n\t\trenderInline: driver.renderInline\n\t\t\t? (req, cb) => driver.renderInline!(enrich(req), cb)\n\t\t\t: undefined,\n\t}\n}\n\n/**\n * The off-session charge {@link UpsellKind} an offering is sold as, read off the OFFERING.\n *\n * `kind` describes the money, and the money is a property of the catalog entry rather than of the\n * page selling it: a one-time offering can only ever be charged as `'one-time'`, and a recurring\n * one is by default a second, stacked `'subscription'`. The server validates the word it is handed\n * against the catalog's own `Offering.kind` and rejects a mismatch (*\"a 'one-time' upsell must\n * reference a ONE_TIME product\"*), so an author restating it could only ever be redundant — or\n * wrong. That leaves exactly one word worth writing: `kind=\"upgrade\"`, \"change the plan on the\n * subscription they already have\", which nothing about the offering can tell us. An explicit\n * `kind` always wins over this default.\n *\n * STRUCTURAL by construction: it reads `interval`, never the `period`/`periodly` display strings\n * (which are copy — `month × 3` reads `quarter`, and localisation may rewrite either).\n *\n * An offering that hasn't resolved (unknown slot, or one still showing SAMPLE pricing) yields\n * `undefined`: the wire field stays absent and the server applies its own default, exactly as\n * before. A sample never reaches a charge anyway — `<Checkout>`/`<UpsellButton>` simulate it.\n */\nexport function upsellKindFor(offering?: {\n\tinterval?: Interval\n}): UpsellKind | undefined {\n\tif (!offering?.interval) return undefined\n\treturn offering.interval === 'one_time' ? 'one-time' : 'subscription'\n}\n\n/**\n * Resolve the offering SLOT (`req.product`, e.g. `'primary'`) to the CATALOG FACTS about it on\n * every attempt, from the funnel's resolved catalog map:\n * - its assigned catalog KEY (`req.catalogKey`, e.g. `'pro-monthly'`) — the charge identity;\n * - for an upsell, the {@link UpsellKind} that offering is charged as (see {@link upsellKindFor}).\n *\n * Applied by `FunnelProvider` around the driver so `<Checkout offering=\"primary\">` puts the slot on\n * the wire while the driver charges the real catalog key — the driver never learns what a slot is,\n * and page code can only name a slot the funnel declares (the server can't be handed an arbitrary\n * catalog key). An explicit `req.catalogKey`/`req.kind` always wins.\n *\n * Here rather than in the components because it is the ATTEMPT that needs the answer, not the\n * mount: `<Checkout>` freezes its presentation at mount (a re-decided surface would orphan an\n * attempt in flight), and a value frozen alongside it would be read before this map could be\n * consulted for the product the click actually names. Every path — `driver.start`, the inline\n * mount, the sheet — arrives here, so there is one place the facts get filled in.\n */\nexport function driverWithCatalog(\n\tdriver: CheckoutDriver,\n\tcatalog: ReadonlyMap<string, { catalogKey: string; interval?: Interval }>\n): CheckoutDriver {\n\tconst enrich = (req: CheckoutRequest): CheckoutRequest => {\n\t\tconst resolved = catalog.get(req.product)\n\t\treturn {\n\t\t\t...req,\n\t\t\tcatalogKey: req.catalogKey ?? resolved?.catalogKey,\n\t\t\t// Only an upsell has a kind to fill: it is the off-session charge shape, and the\n\t\t\t// server reads the field for no other intent.\n\t\t\tkind:\n\t\t\t\treq.intent === 'upsell'\n\t\t\t\t\t? (req.kind ?? upsellKindFor(resolved))\n\t\t\t\t\t: req.kind,\n\t\t}\n\t}\n\treturn {\n\t\t...driver,\n\t\tstart: (req) => driver.start(enrich(req)),\n\t\trenderInline: driver.renderInline\n\t\t\t? (req, cb) => driver.renderInline!(enrich(req), cb)\n\t\t\t: undefined,\n\t}\n}\n\nconst DriverContext = createContext<CheckoutDriver | null>(null)\n\nexport function CheckoutDriverProvider({\n\tdriver,\n\tchildren,\n}: {\n\tdriver: CheckoutDriver\n\tchildren: ReactNode\n}): ReactNode {\n\treturn createElement(DriverContext.Provider, { value: driver }, children)\n}\n\nfunction useDriver(): CheckoutDriver {\n\treturn useContext(DriverContext) ?? FALLBACK_DRIVER\n}\nconst FALLBACK_DRIVER = createMockDriver()\n\n// ── Failure routing (the recovery \"magic\") ───────────────\n\n/** One declarative recovery route for a failure category. */\nexport type FailureRoute =\n\t| { go: string } // navigate the flow to a page key (e.g. a real-card recapture page)\n\t| { modal: string | ComponentType<any> } // show a registry modal — it receives {@link FailureModalProps}\n\t| { fallback: CheckoutSurface } // re-collect a card ON-SESSION on this surface and retry (once)\n\t| ((error: CheckoutError) => void) // full control\n\n/**\n * What a `{ modal }` failure route hands the modal — the error AND the actions,\n * because registry modals mount outside the flow's nav context and a recovery\n * modal that can't act is just an error toast. Type your modal with this:\n *\n * ```tsx\n * const Declined = defineModal<FailureModalProps>(({ error, go, retry }) => (\n * <Sheet>\n * <p>{error.category === 'prepaid_card' ? 'Prepaid cards can't start a trial.' : 'Payment didn't go through.'}</p>\n * <button onClick={() => retry('sheet')}>Try another card</button>\n * <button onClick={() => go('downsell')}>See the lite plan</button>\n * </Sheet>\n * ))\n * ```\n *\n * A modal can also host a whole `<Checkout offering=\"…\" payment=\"card\" />` for\n * an inline downsell — the driver context is app-level, so checkout works inside\n * modals as-is.\n */\nexport interface FailureModalProps {\n\terror: CheckoutError\n\t/** The product whose charge failed (absent only for product-less failures). */\n\tproduct?: string\n\t/** Navigate the flow to a page key (modals can't call useNavigation themselves). */\n\tgo: (pageKey: string) => void\n\t/**\n\t * Re-attempt the SAME product. `retry()` re-runs an upsell off-session; for a\n\t * purchase (which needs UI to re-collect) it opens the payment sheet.\n\t * `retry('sheet')` re-collects on the SDK sheet; an inline surface\n\t * (`element`/`express`/`embedded`) is COERCED to the sheet when the provider\n\t * supports it — a retry has no page slot to mount into, so the sheet hosts the\n\t * element. On sheet-less MoR providers (Paddle) inline retries run through the\n\t * driver, whose provider checkout opens its own overlay. `retry('popup')` /\n\t * `retry('redirect')` hand off to the provider. A failed retry routes through\n\t * `onFailed` again (the modal reopens) — the loop is user-driven, never\n\t * automatic. Hide the modal first (`useModal().hide()`) when retrying into a\n\t * surface that opens its own overlay.\n\t */\n\tretry: (surface?: CheckoutSurface) => void\n}\n\n/**\n * Declarative failure recovery — route each failure **category** to what happens\n * next, instead of hand-wiring `onError`:\n *\n * ```tsx\n * <Checkout offering=\"monthly\" payment=\"card\" onFailed={{\n * prepaid_card: { go: 'real-card' },\n * insufficient_funds: { modal: DownsellModal },\n * default: { modal: TryAgainModal },\n * }} />\n * ```\n *\n * Resolution: exact category → `default` → nothing (the error state + `checkout.\n * failed` event stand, as today). Four built-in judgments:\n * - `canceled` only routes when mapped EXPLICITLY — a deliberately dismissed\n * sheet/popup is not a failure to recover from, so `default` never catches it;\n * - `already_purchased` likewise: unmapped, the buyer owns it and the flow ADVANCES\n * as a success would, no purchase event ({@link CheckoutErrorCategory});\n * - a `{ fallback }` recovery runs at most once per attempt chain (its own\n * failure routes through the non-fallback routes), so declines can't loop;\n * - a `{ fallback }` reached through `default` is skipped for a NON-retryable error\n * — a card form can't fix a rejection. Mapped to the CATEGORY it always runs.\n *\n * `checkout.failed` fires with category + declineCode on every failure regardless\n * of routing — recovery pages are measurable, and being ordinary flow pages they\n * are A/B-able with page experiments like anything else.\n */\nexport type OnFailedMap = Partial<\n\tRecord<CheckoutErrorCategory | 'default', FailureRoute>\n>\n\n// ── The headless hook ────────────────────────────────────\n\nexport interface UseCheckoutOptions {\n\t/**\n\t * Classes for the buttons the SDK renders ITSELF — see {@link CheckoutClassNames}. Lives here\n\t * rather than on the components so it reaches the one place an author cannot otherwise style:\n\t * the recovery sheet `<UpsellButton>` opens, which has no page slot and takes no `className`.\n\t */\n\tclassNames?: CheckoutClassNames\n\tintent?: CheckoutIntent\n\t/**\n\t * For `upsell` intent — which kind of off-session charge.\n\t *\n\t * **Rarely worth writing.** It defaults to what the OFFERING is: a one-time offering charges\n\t * `'one-time'`, a recurring one charges a second, stacked `'subscription'` (see\n\t * {@link upsellKindFor}). The one word the offering can't tell us is `'upgrade'` — change the\n\t * plan on the subscription the buyer already has, rather than adding another beside it — and on\n\t * Paddle, which can't stack a second subscription at all, that is the only way to upsell one.\n\t */\n\tkind?: UpsellKind\n\t/**\n\t * Run this checkout through the provider's MANAGED mode — today, **Stripe Managed Payments**,\n\t * with Stripe as Merchant of Record for the charge (it owns tax, fraud and disputes).\n\t *\n\t * Per CHECKOUT on purpose: both shapes are legitimate on the same store, so the funnel picks\n\t * charge by charge — a managed upsell trades the one-tap off-session charge for MoR coverage, a\n\t * non-managed one keeps the one tap.\n\t *\n\t * Managed narrows what else is legal, because Stripe collects the card in its own frame: the\n\t * two surfaces that mount a Stripe Elements component in our page (`element`, `express`) are\n\t * gone, leaving `embedded`, `redirect` and `sheet` — the last of those being our overlay\n\t * hosting Stripe's embedded checkout, presentation rather than payment, which is why it\n\t * survives. So `surface=\"auto\"` resolves against the MANAGED profile (→ `embedded`, on both\n\t * device classes), and a pinned Elements surface is refused here rather than on the wire (see\n\t * {@link refuseSurface}).\n\t *\n\t * Selection is only half the gate: eligibility is per Stripe ACCOUNT, established at Stripe's\n\t * managed onboarding, so the SERVER re-validates this against the store and rejects the attempt\n\t * if that store isn't onboarded. The claim never enables it. Absent/false = ordinary provider\n\t * checkout, unchanged in every respect.\n\t */\n\tmanaged?: boolean\n\t/** Advance to the next page after a successful charge (default: true). */\n\tadvanceOnSuccess?: boolean\n\tonSuccess?: (result: CheckoutResult) => void\n\tonError?: (error: CheckoutError) => void\n\t/** Declarative failure recovery — see {@link OnFailedMap}. Runs AFTER `onError`. */\n\tonFailed?: OnFailedMap\n\t/**\n\t * Try this surface ON-SESSION once on any first failure, before `onFailed`\n\t * routing: the off-session (or first) charge fails, the surface re-collects a\n\t * card, the retry's failure then goes through `onFailed`. Never re-triggered\n\t * by its own failure; never triggered by a failure the platform marked\n\t * NON-retryable (`CheckoutError.retryable`), which covers a user-`canceled`\n\t * checkout, a product the buyer already owns, and every refusal a fresh card\n\t * cannot change.\n\t *\n\t * KEEPS taking a surface word, unlike `<UpsellButton recover>` — the two answer different questions.\n\t * `<UpsellButton>` is one intent (\"charge off-session, and rescue it if that fails\"), and for that\n\t * intent the container was never the author's to pick, which is why naming it was boilerplate\n\t * in all 18 authored call sites. The hook is intent-agnostic and serves `<Checkout>` too, where\n\t * there is nothing to default to (the paywall's own surface IS the payment UI, so auto-opening\n\t * a second one on a decline would be a behaviour change to every purchase), and where a\n\t * container can genuinely be the point: `popup`/`redirect` hand the recovery to the provider's\n\t * own UI. It is also the word `{ fallback }` routes and `retry(surface)` speak, so this stays\n\t * the low-level knob and `recover` is the sugar that resolves into it.\n\t */\n\trecoverySurface?: CheckoutSurface\n}\n\nexport interface CheckoutHandle {\n\t/** Start the charge for a product; resolves with the result (no surface = off-session). */\n\topen: (\n\t\tproduct: string,\n\t\tsurface?: CheckoutSurface\n\t) => Promise<CheckoutResult>\n\tstatus: CheckoutStatus\n\t/** The last failure, structured so you can route/recover by `category`. */\n\terror: CheckoutError | null\n\tisLoading: boolean\n\treset: () => void\n\t/** Build the callbacks an inline surface reports through (used by `<Checkout>`). */\n\tcallbacksFor: (\n\t\tproduct?: string,\n\t\tsurface?: CheckoutSurface\n\t) => CheckoutCallbacks & { onStart: () => void }\n}\n\n/**\n * The headless checkout hook. Owns the state machine + analytics + post-charge\n * navigation; delegates the charge to the injected {@link CheckoutDriver}.\n */\nexport function useCheckout(opts: UseCheckoutOptions = {}): CheckoutHandle {\n\tconst driver = useDriver()\n\tconst tracker = useTrackerRef()\n\tconst catalog = useCatalog()\n\tconst nav = useNavigation()\n\tconst funnel = useFunnel()\n\tconst [status, setStatus] = useState<CheckoutStatus>('idle')\n\tconst [error, setError] = useState<CheckoutError | null>(null)\n\n\tconst intent = opts.intent ?? 'purchase'\n\tconst kind = opts.kind\n\tconst managed = opts.managed\n\tconst advance = opts.advanceOnSuccess ?? true\n\n\t// Resolve the product a checkout is for (by SLOT) → the fields the client events\n\t// carry so the renderer's pixel loaders can forward network-required data:\n\t// - `productId` — the CHARGE/SKU identity (Meta content_ids / TikTok contents /\n\t// GA4 items). It's the resolved product's `catalogKey` (what the charge + the\n\t// server CAPI key on), falling back to the raw slot when a slot isn't remapped\n\t// (`catalogKey` defaults to the slot id). Same identity on every event below.\n\t// - `amount`/`currency` — the catalog LIST price (pre-charge events have no\n\t// settled amount yet); minor→major mirrors purchase.complete's `/100`.\n\t// - `isSubscription` — a recurring INTERVAL marks a subscription (the structural fact;\n\t// `period` is display copy a translation could rewrite); with no catalog entry the\n\t// off-session upsell `kind` decides. Drives the browser Subscribe.\n\tconst productFacts = useCallback(\n\t\t(product?: string) => {\n\t\t\tconst resolved = product ? catalog.get(product) : undefined\n\t\t\treturn {\n\t\t\t\tproductId: resolved?.catalogKey ?? product,\n\t\t\t\tamount: resolved ? resolved.priceMinor / 100 : undefined,\n\t\t\t\tcurrency: resolved?.currency,\n\t\t\t\tisSubscription: resolved\n\t\t\t\t\t? resolved.interval !== 'one_time'\n\t\t\t\t\t: kind === 'subscription' || kind === 'upgrade',\n\t\t\t}\n\t\t},\n\t\t[catalog, kind]\n\t)\n\n\t// True while an on-session recovery attempt (recoverySurface / a `{ fallback }`\n\t// route) is in flight — its own failure must not start ANOTHER re-collect, so\n\t// declines can't loop. Cleared on every fresh user-initiated attempt.\n\tconst recovering = useRef(false)\n\t// fail → startRecovery → (sheet/attempt) → fail is mutually recursive; refs give\n\t// the cycle stable identities so the returned handle doesn't churn per render.\n\tconst failRef = useRef<(err: CheckoutError, product?: string) => void>(\n\t\t() => {}\n\t)\n\tconst attemptRef = useRef<\n\t\t(product: string, surface?: CheckoutSurface) => Promise<CheckoutResult>\n\t>(async () => ({ ok: false }))\n\n\tconst succeed = useCallback(\n\t\t(result: CheckoutResult, product?: string) => {\n\t\t\tsetStatus('success')\n\t\t\t// PURCHASE STATE, written by the SDK on every settled charge — inline surfaces AND the\n\t\t\t// redirect-return leg, where the page that owned the `onSuccess` handler is long gone.\n\t\t\t// Post-purchase pages (upsells, the download/finish page) gate on `data.purchased`, and\n\t\t\t// their guard is now evaluated SERVER-side on every deep-link/refresh — so a buyer whose\n\t\t\t// purchase was only ever recorded by a page-local handler would be bounced back to the\n\t\t\t// start of the funnel on the first reload, with the thing they paid for out of reach.\n\t\t\t// Persistence rides the normal write path (debounced snapshot + exit flush).\n\t\t\tfunnel.data.set({ purchased: true })\n\t\t\tconst { productId, isSubscription } = productFacts(product)\n\t\t\tconst amount =\n\t\t\t\tresult.amountMinor != null\n\t\t\t\t\t? result.amountMinor / 100\n\t\t\t\t\t: undefined\n\t\t\ttracker.track('purchase.complete', {\n\t\t\t\tamount,\n\t\t\t\tcurrency: result.currency,\n\t\t\t\tproductId,\n\t\t\t\teventId: result.eventId, // server-minted (browser↔CAPI dedup); undefined if none\n\t\t\t})\n\t\t\t// Restore the browser Subscribe: a settled SUBSCRIPTION ALSO fires\n\t\t\t// subscription.created, reusing the SAME server-minted eventId as the\n\t\t\t// purchase.complete above so the browser Subscribe dedups into the ONE\n\t\t\t// conversion the server-CAPI Subscribe already reported (it maps\n\t\t\t// subscription.created→Subscribe with that id). Do NOT mint a fresh id here.\n\t\t\t// Purchase AND Subscribe both firing for a subscription is correct — Meta\n\t\t\t// treats them as distinct standard events (v1 parity), not a double Purchase.\n\t\t\t// A one-time charge never emits it.\n\t\t\tif (isSubscription) {\n\t\t\t\ttracker.track('subscription.created', {\n\t\t\t\t\tamount,\n\t\t\t\t\tcurrency: result.currency,\n\t\t\t\t\tproductId,\n\t\t\t\t\teventId: result.eventId,\n\t\t\t\t})\n\t\t\t}\n\t\t\topts.onSuccess?.(result)\n\t\t\tif (advance) nav.next()\n\t\t},\n\t\t[tracker, nav, advance, opts, productFacts, funnel]\n\t)\n\tconst succeedRef = useRef(succeed)\n\tsucceedRef.current = succeed\n\n\t/**\n\t * The buyer ALREADY OWNS this product (`already_purchased` — the platform's double-charge\n\t * guard refused the charge). Advance the flow exactly where a success would, WITHOUT\n\t * inventing a purchase.\n\t *\n\t * The two halves are deliberately separated, because they are separate outcomes:\n\t * - NAVIGATION happens in full — `advanceOnSuccess` is honoured, `onSuccess` runs (that is\n\t * where funnels put their post-purchase routing and their \"mark it bought\" state), and\n\t * `data.purchased` is set. That flag is ownership, not revenue, and it is true: they\n\t * bought it. Leaving it false would let the server-side post-purchase guard bounce the\n\t * buyer off the very page we just advanced them to.\n\t * - MONEY does not happen at all — no `purchase.complete`, no `subscription.created`, no\n\t * settlement. THIS attempt moved no money; the original purchase already emitted those\n\t * events with the server-minted dedup id and posted the conversion to every pixel.\n\t * Re-emitting would double-count revenue in analytics and report a second conversion to\n\t * Meta/TikTok for one sale. `checkout.already_purchased` is what fires instead: tracked,\n\t * never fanned out to integrations (see ../tracking/catalog).\n\t *\n\t * `onSuccess` receives a bare `{ ok: true }` — no `amountMinor`, no `currency`, no\n\t * `eventId`, because no charge produced any of them. A handler that only routes or flips\n\t * page state (what templates do) is unaffected; one that reports money has nothing to\n\t * report, which is the honest answer.\n\t */\n\tconst alreadyOwned = useCallback(\n\t\t(err: CheckoutError, product?: string) => {\n\t\t\tsetStatus('success')\n\t\t\tsetError(null)\n\t\t\tfunnel.data.set({ purchased: true })\n\t\t\tconst { productId } = productFacts(product)\n\t\t\ttracker.track('checkout.already_purchased', {\n\t\t\t\tproductId,\n\t\t\t\tdeclineCode: err.declineCode,\n\t\t\t\tintent,\n\t\t\t})\n\t\t\topts.onSuccess?.({ ok: true })\n\t\t\tif (advance) nav.next()\n\t\t},\n\t\t[tracker, nav, advance, opts, productFacts, funnel, intent]\n\t)\n\tconst alreadyOwnedRef = useRef(alreadyOwned)\n\talreadyOwnedRef.current = alreadyOwned\n\n\tconst begin = useCallback(\n\t\t(product?: string, surface?: CheckoutSurface) => {\n\t\t\tsetStatus('loading')\n\t\t\tsetError(null)\n\t\t\tconst { productId, amount, currency } = productFacts(product)\n\t\t\t// Client-minted eventId (pre-charge — no server id yet); lets a future\n\t\t\t// InitiateCheckout server CAPI dedup against this pixel fire.\n\t\t\ttracker.track('checkout.start', {\n\t\t\t\tproductId,\n\t\t\t\tamount,\n\t\t\t\tcurrency,\n\t\t\t\tsurface,\n\t\t\t\teventId: newEventId(),\n\t\t\t})\n\t\t},\n\t\t[tracker, productFacts]\n\t)\n\n\tconst paymentAdded = useCallback(\n\t\t(product?: string) => {\n\t\t\tconst { productId, amount, currency } = productFacts(product)\n\t\t\t// Distinct client eventId per AddPaymentInfo (its own Meta standard event).\n\t\t\ttracker.track('checkout.payment_added', {\n\t\t\t\tproductId,\n\t\t\t\tamount,\n\t\t\t\tcurrency,\n\t\t\t\teventId: newEventId(),\n\t\t\t})\n\t\t},\n\t\t[tracker, productFacts]\n\t)\n\n\t// Open the on-session recovery surface for a product. A recovery has no page slot\n\t// to mount UI into, so surfaces that need one route through our sheet: `sheet`\n\t// itself, and inline surfaces WHEN the provider supports the sheet (Stripe et al.\n\t// — an element/express recovery is the same client_confirm hosted in the sheet).\n\t// Everything else (popup/redirect, and inline on sheet-less MoR providers like\n\t// Paddle, whose provider_checkout opens its OWN overlay) runs through the driver.\n\t// Asked of the VARIANT's profile, not the base one: which surfaces exist is exactly\n\t// the question a variant answers differently, and a variant with no sheet must fall\n\t// through to the driver rather than open a container it doesn't have. (Stripe\n\t// managed HAS one — it hosts Stripe's embedded checkout — so this reads `true` there\n\t// and the recovery stays in the funnel.)\n\tconst hostInSheet = (surface: CheckoutSurface): boolean =>\n\t\tsurface === 'sheet' ||\n\t\t(isInlineSurface(surface) &&\n\t\t\t!!profileFor(driver.provider, { managed })?.surfaces.sheet)\n\tconst startRecovery = (product: string, rendering: CheckoutSurface) => {\n\t\trecovering.current = true\n\t\t// ONE authored word, TWO questions: where do we present this, and what does the provider\n\t\t// render in there. `hostInSheet` answers the first — a recovery has no page slot, so an\n\t\t// inline one is re-hosted in our sheet — and the author's word answers the second, whole.\n\t\t// Both travel to the driver; only the CONTAINER crosses the wire. (This used to be one\n\t\t// value, and the container overwrote it: see {@link CheckoutRequest.rendering}.)\n\t\tconst container = hostInSheet(rendering) ? 'sheet' : rendering\n\t\t// The recovery is authored too (`recoverySurface` / `<UpsellButton recover>` / `retry(surface)`),\n\t\t// so it can be as impossible under a variant as the paywall's own — refuse it instead of\n\t\t// opening a checkout the server is bound to reject, or (worse) one that quietly renders\n\t\t// something else. BOTH halves are asked, because they can fail for different reasons and\n\t\t// the author needs the one that names their mistake:\n\t\t// - the CONTAINER, which is what the server will be handed. Under managed the sheet is\n\t\t// LEGAL: it is our overlay, not a card form of ours, and it hosts whatever the driver\n\t\t// renders — Stripe's own embedded checkout — so a managed upsell recovers in place\n\t\t// rather than through `redirect`, which navigates the buyer out of the funnel.\n\t\t// - the RENDERING, which is what the driver will mount. Under managed `element`/`express`\n\t\t// each NAME a Stripe Elements component we would confirm ourselves, and moving one into\n\t\t// our sheet doesn't make it legal — the container changed, the card form didn't (see\n\t\t// MANAGED_PROFILES). Asking only about the container would coerce that pin to `sheet`,\n\t\t// pass, and hand the buyer Stripe's frame instead of what the page asked for.\n\t\t// Neither check fires without a variant (refuseSurface is inert there), so a plain pinned\n\t\t// recovery reaches the driver exactly as it always has.\n\t\t//\n\t\t// Marking the chain as recovering FIRST is what keeps this from re-entering itself through\n\t\t// `failRef` (which only starts a recovery while the guard is down).\n\t\tconst rejection =\n\t\t\trefuseSurface(driver.provider, rendering, managed) ??\n\t\t\trefuseSurface(driver.provider, container, managed)\n\t\tif (rejection) {\n\t\t\tfailRef.current(\n\t\t\t\tcheckoutError('processing_error', rejection, { retryable: false }),\n\t\t\t\tproduct\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\tif (container === 'sheet') {\n\t\t\tbegin(product, 'sheet')\n\t\t\tvoid showModal(CheckoutSheet, {\n\t\t\t\tproduct,\n\t\t\t\tsurface: 'sheet',\n\t\t\t\trendering,\n\t\t\t\tintent,\n\t\t\t\tkind,\n\t\t\t\tmanaged,\n\t\t\t\tclassNames: opts.classNames,\n\t\t\t\tonSuccess: (r: CheckoutResult) =>\n\t\t\t\t\tsucceedRef.current(r, product),\n\t\t\t\tonError: (e: CheckoutError) => failRef.current(e, product),\n\t\t\t\tonPaymentAdded: () => paymentAdded(product),\n\t\t\t})\n\t\t} else {\n\t\t\t// popup/redirect, and inline surfaces on a sheet-less provider (Paddle) whose own\n\t\t\t// checkout opens its overlay: the container IS the rendering, so there is nothing to\n\t\t\t// carry separately.\n\t\t\tvoid attemptRef.current(product, rendering)\n\t\t}\n\t}\n\n\tfailRef.current = (err: CheckoutError, product?: string) => {\n\t\t// ALREADY OWNED — the one outcome that arrives on the failure path but isn't one.\n\t\t// The buyer has the product, so unless the author claimed the category explicitly\n\t\t// (their mapping wins, exactly as it does for `canceled`), the flow ADVANCES and no\n\t\t// purchase is fabricated — see {@link alreadyOwned}. It never reaches the error state,\n\t\t// `onError`, or the recovery machinery: there is nothing to recover from.\n\t\tconst owned = err.category === 'already_purchased'\n\t\tif (owned && !opts.onFailed?.already_purchased) {\n\t\t\talreadyOwnedRef.current(err, product)\n\t\t\treturn\n\t\t}\n\t\t// 3DS/SCA that an off-session charge can't satisfy → flag for recovery.\n\t\tsetStatus(\n\t\t\towned\n\t\t\t\t? 'success'\n\t\t\t\t: err.category === 'authentication_required'\n\t\t\t\t\t? 'requires_action'\n\t\t\t\t\t: 'error'\n\t\t)\n\t\tsetError(owned ? null : err)\n\t\tif (owned) {\n\t\t\t// The honest event either way: an explicit route changes where the buyer goes, not\n\t\t\t// what happened. `checkout.failed` would book a failure that never occurred, and a\n\t\t\t// purchase event would book revenue twice.\n\t\t\ttracker.track('checkout.already_purchased', {\n\t\t\t\tproductId: productFacts(product).productId,\n\t\t\t\tdeclineCode: err.declineCode,\n\t\t\t\tintent,\n\t\t\t})\n\t\t} else {\n\t\t\ttracker.track('checkout.failed', {\n\t\t\t\tcategory: err.category,\n\t\t\t\tdeclineCode: err.declineCode,\n\t\t\t\t// RESOLVED via productFacts, like every sibling emitter — this was the ONE that\n\t\t\t\t// passed the raw slot ('upsell-sell-through') while `checkout.start` and the branch\n\t\t\t\t// directly above passed the catalog key ('STR_59.95_Monthly_29.95Month_Trial_AF').\n\t\t\t\t// Two vocabularies for one field means no funnel report can join a start to its\n\t\t\t\t// failure, which is the entire question you ask this event (2026-07-29).\n\t\t\t\tproductId: productFacts(product).productId,\n\t\t\t\tintent,\n\t\t\t})\n\t\t\topts.onError?.(err)\n\t\t}\n\n\t\t// A deliberately dismissed checkout routes only when 'canceled' is mapped\n\t\t// EXPLICITLY — recovery machinery must not chase a user who closed the sheet.\n\t\tif (err.category === 'canceled' && !opts.onFailed?.canceled) return\n\t\t// First failure + a recovery surface → re-collect on-session, ONCE; the\n\t\t// retry's failure falls through to onFailed below.\n\t\t//\n\t\t// `retryable` is the gate (it is literally this question: \"may re-attempting, e.g. an\n\t\t// on-session re-collection, succeed?\"). A refusal the platform marked non-retryable —\n\t\t// a validator rejection, a charge-shape error, a subscription that can't be upgraded,\n\t\t// an issuer that said do-not-retry — must not open a card form that is bound to fail\n\t\t// again; the failure routes through `onFailed` instead. `canceled` is non-retryable by\n\t\t// construction, so its exclusion here is now implied rather than special-cased.\n\t\tif (product && !recovering.current && opts.recoverySurface && err.retryable) {\n\t\t\tstartRecovery(product, opts.recoverySurface)\n\t\t\treturn\n\t\t}\n\t\tlet route =\n\t\t\topts.onFailed?.[err.category] ??\n\t\t\t(err.category === 'canceled' ? undefined : opts.onFailed?.default)\n\t\t// The same judgment for the `{ fallback }` ROUTE, which is the same re-collection by\n\t\t// another name: a fallback reached through `default` (category-agnostic — the author\n\t\t// never said \"re-collect for THIS\") is dropped for a non-retryable error. A fallback\n\t\t// mapped to the exact category is authored intent and always runs, which is how e.g.\n\t\t// Paddle's do-not-retry decline can still be given a card form deliberately.\n\t\tif (\n\t\t\troute &&\n\t\t\ttypeof route === 'object' &&\n\t\t\t'fallback' in route &&\n\t\t\t!err.retryable &&\n\t\t\t!opts.onFailed?.[err.category]\n\t\t) {\n\t\t\troute = undefined\n\t\t}\n\t\t// The documented `{ fallback }` fall-through: a fallback runs at most once per\n\t\t// attempt chain, so once a recovery is in flight the RECOVERY's own failure\n\t\t// resolves the DEFAULT route instead — unless the default is itself a fallback\n\t\t// (or was the resolved route), in which case the error state stands.\n\t\tif (\n\t\t\troute &&\n\t\t\ttypeof route === 'object' &&\n\t\t\t'fallback' in route &&\n\t\t\trecovering.current\n\t\t) {\n\t\t\tconst dflt = opts.onFailed?.default\n\t\t\troute =\n\t\t\t\tdflt &&\n\t\t\t\tdflt !== route &&\n\t\t\t\t!(typeof dflt === 'object' && 'fallback' in dflt)\n\t\t\t\t\t? dflt\n\t\t\t\t\t: undefined\n\t\t}\n\t\tif (!route) return\n\t\tif (typeof route === 'function') route(err)\n\t\telse if ('go' in route) nav.go(route.go)\n\t\telse if ('modal' in route) {\n\t\t\t// Hand the modal the ACTIONS, not just the error (FailureModalProps) — the\n\t\t\t// registry host mounts outside the nav context, so these closures are the\n\t\t\t// modal's only way to move the flow or re-charge.\n\t\t\tconst props: FailureModalProps = {\n\t\t\t\terror: err,\n\t\t\t\tproduct,\n\t\t\t\tgo: (pageKey: string) => nav.go(pageKey),\n\t\t\t\tretry: (surface?: CheckoutSurface) => {\n\t\t\t\t\tif (!product) return\n\t\t\t\t\trecovering.current = true // a retry's failure routes again; it never auto-recovers on top\n\t\t\t\t\tif (!surface) {\n\t\t\t\t\t\t// Bare retry: an upsell re-runs off-session; a purchase needs UI to\n\t\t\t\t\t\t// re-collect a card — the sheet where the provider supports it, else\n\t\t\t\t\t\t// the provider's own overlay (popup).\n\t\t\t\t\t\tif (intent === 'upsell')\n\t\t\t\t\t\t\tvoid attemptRef.current(product)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tstartRecovery(\n\t\t\t\t\t\t\t\tproduct,\n\t\t\t\t\t\t\t\tprofileFor(driver.provider, { managed })\n\t\t\t\t\t\t\t\t\t?.surfaces.sheet\n\t\t\t\t\t\t\t\t\t? 'sheet'\n\t\t\t\t\t\t\t\t\t: 'popup'\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t// startRecovery routes it: surfaces needing a MOUNTED UI go through the\n\t\t\t\t\t// SAME CheckoutSheet machinery the recovery path uses — driver.start\n\t\t\t\t\t// cannot mount React UI, so routing them there would dead-end and mint\n\t\t\t\t\t// orphan attempts. popup/redirect (and Paddle's own-overlay inline) are\n\t\t\t\t\t// driver-run hand-offs.\n\t\t\t\t\tstartRecovery(product, surface)\n\t\t\t\t},\n\t\t\t}\n\t\t\tvoid showModal(\n\t\t\t\troute.modal,\n\t\t\t\tprops as unknown as Record<string, unknown>\n\t\t\t)\n\t\t} else if ('fallback' in route) {\n\t\t\tif (product && !recovering.current)\n\t\t\t\tstartRecovery(product, route.fallback)\n\t\t}\n\t}\n\n\tattemptRef.current = async (\n\t\tproduct: string,\n\t\tsurface?: CheckoutSurface\n\t): Promise<CheckoutResult> => {\n\t\t// An impossible (surface × variant) pair never reaches the wire — the round-trip would\n\t\t// only come back as a generic rejection (see refuseSurface). Off-session attempts have no\n\t\t// surface to check.\n\t\tconst rejection = surface\n\t\t\t? refuseSurface(driver.provider, surface, managed)\n\t\t\t: undefined\n\t\tif (rejection) {\n\t\t\tconst err = checkoutError('processing_error', rejection, {\n\t\t\t\tretryable: false,\n\t\t\t})\n\t\t\tfailRef.current(err, product)\n\t\t\treturn { ok: false, error: err }\n\t\t}\n\t\tbegin(product, surface)\n\t\ttry {\n\t\t\tconst result = await driver.start({\n\t\t\t\tproduct,\n\t\t\t\tintent,\n\t\t\t\tsurface,\n\t\t\t\tkind,\n\t\t\t\tmanaged,\n\t\t\t})\n\t\t\tif (result.ok) succeedRef.current(result, product)\n\t\t\telse\n\t\t\t\tfailRef.current(\n\t\t\t\t\tresult.error ?? checkoutError('unknown', 'Checkout failed'),\n\t\t\t\t\tproduct\n\t\t\t\t)\n\t\t\treturn result\n\t\t} catch (e) {\n\t\t\tconst err = checkoutError(\n\t\t\t\t'processing_error',\n\t\t\t\te instanceof Error ? e.message : 'Checkout failed'\n\t\t\t)\n\t\t\tfailRef.current(err, product)\n\t\t\treturn { ok: false, error: err }\n\t\t}\n\t}\n\n\tconst open = useCallback(\n\t\tasync (\n\t\t\tproduct: string,\n\t\t\tsurface?: CheckoutSurface\n\t\t): Promise<CheckoutResult> => {\n\t\t\trecovering.current = false // fresh user-initiated attempt chain\n\t\t\treturn attemptRef.current(product, surface)\n\t\t},\n\t\t[]\n\t)\n\n\tconst callbacksFor = useCallback(\n\t\t(product?: string, surface?: CheckoutSurface) => ({\n\t\t\tonStart: () => {\n\t\t\t\trecovering.current = false // fresh user-initiated attempt chain\n\t\t\t\tbegin(product, surface)\n\t\t\t},\n\t\t\tonSuccess: (result: CheckoutResult) =>\n\t\t\t\tsucceedRef.current(result, product),\n\t\t\tonError: (err: CheckoutError) => failRef.current(err, product),\n\t\t\tonPaymentAdded: () => paymentAdded(product),\n\t\t}),\n\t\t[begin, paymentAdded]\n\t)\n\n\tconst reset = useCallback(() => {\n\t\trecovering.current = false\n\t\tsetStatus('idle')\n\t\tsetError(null)\n\t}, [])\n\n\treturn {\n\t\topen,\n\t\tstatus,\n\t\terror,\n\t\tisLoading: status === 'loading',\n\t\treset,\n\t\tcallbacksFor,\n\t}\n}\n\n// ── The components ───────────────────────────────────────\n\n/** Everything every checkout component takes, whatever it renders and wherever it renders it. */\nexport interface CheckoutCommonProps\n\textends Omit<UseCheckoutOptions, 'managed'> {\n\t/** Logical offering slot (the author's bound selection). */\n\toffering: string\n\tclassName?: string\n\t/**\n\t * How the provider paints its own card fields ({@link CheckoutAppearance}) — needed because those\n\t * fields render in a cross-origin iframe the funnel's CSS can't reach.\n\t */\n\tappearance?: CheckoutAppearance\n\t/** How the provider lists the payment methods ({@link CheckoutMethods}) — accordion + collapsed\n\t * by default. Ignored on surfaces where the provider owns the whole UI. */\n\tmethods?: CheckoutMethods\n}\n\n/**\n * The `managed` × `payment` constraint, as a type rather than a runtime rejection.\n *\n * Under Stripe **Managed Payments** the provider collects the card in its own frame — custom payment\n * forms are unsupported — so the two modes that mount Elements components of ours (`'card'`,\n * `'wallets'`) cannot exist there. That has always been true; what changed is WHEN you find out.\n * Before, `<Checkout payment=\"card\" managed>` compiled, failed publish validation if the scanner\n * caught it, and otherwise reached the browser to be refused on mount (see `refuseSurface`). Now the\n * pair doesn't type-check, and the author reads the constraint in their editor.\n *\n * Three members rather than two because `managed` is often a variable (a funnel A/B-ing MoR against\n * its own Stripe account writes `managed={testing.managed}`): a non-literal boolean lands on the\n * second member and gets the CONSERVATIVE narrowing, which is the only safe answer when the value\n * isn't known until runtime.\n */\nexport type PaymentAxis =\n\t| {\n\t\t\t/** See {@link UseCheckoutOptions.managed}. */\n\t\t\tmanaged?: false | undefined\n\t\t\t/** WHAT the buyer sees — {@link PaymentMode}. Default `'auto'`. */\n\t\t\tpayment?: PaymentMode\n\t }\n\t| {\n\t\t\tmanaged: boolean\n\t\t\t/** Narrowed by `managed`: the provider collects the card, so no card fields of ours. */\n\t\t\tpayment?: HostedPaymentMode\n\t }\n\n/**\n * The `opens` × `payment` constraint. `'popup'` and `'redirect'` are the provider's own overlay and\n * the provider's own page — whole checkouts they paint themselves — so there is nothing of ours\n * inside to configure and `payment` narrows the same way `managed` narrows it. `'sheet'` is OUR\n * overlay hosting whatever the provider renders, so every mode stays available there.\n */\nexport type OpensAxis =\n\t| {\n\t\t\t/** WHERE the payment is presented — {@link OpensIn}. Default `'sheet'`. */\n\t\t\topens?: 'sheet' | undefined\n\t }\n\t| {\n\t\t\topens: Exclude<OpensIn, 'sheet'>\n\t\t\t/** Narrowed by `opens`: the provider is painting the whole thing. */\n\t\t\tpayment?: HostedPaymentMode\n\t }\n\n/**\n * The button's own content, and the `asChild` contract made structural.\n *\n * `asChild` clones YOUR element and puts the click handler on it, so \"your element\" has to be\n * exactly one element — not a string, not a fragment, not two of them. Written as a union, that is\n * what the type says, and `<CheckoutButton asChild>Buy now</CheckoutButton>` stops compiling instead\n * of rendering an un-clickable string.\n */\n/**\n * What the trigger tells you about the attempt it is running, handed to a render-prop child.\n *\n * `loading` is the charge actually being in flight — the window where a second tap would be a\n * second attempt. `disabled` is what the SDK would put on its own button, and today they are the\n * same fact; they are two names because \"is something happening\" and \"should this be pressable\"\n * stop agreeing the moment anything else can disable a trigger.\n */\nexport interface TriggerState {\n\t/** An attempt is in flight — show a spinner, swap the label, whatever the funnel wants. */\n\tloading: boolean\n\t/** What the SDK would set on its own button. Spread it onto yours. */\n\tdisabled: boolean\n\t/**\n\t * The SDK's circular busy indicator while `loading`, and `null` otherwise — so a custom trigger\n\t * gets the same spinner the default button draws without every funnel hand-rolling one. Render it\n\t * beside your label, or instead of it.\n\t */\n\tspinner: ReactNode\n}\n\nexport type TriggerAxis =\n\t| {\n\t\t\t/** Clone your own element instead of rendering the default button. */\n\t\t\tasChild?: false | undefined\n\t\t\t/**\n\t\t\t * Button label (default: `Continue`), or a FUNCTION taking {@link TriggerState} and\n\t\t\t * returning your own element — the way to render a loading state without `asChild`\n\t\t\t * needing to guess one:\n\t\t\t *\n\t\t\t * ```tsx\n\t\t\t * <UpsellButton offering=\"addon\">\n\t\t\t * {({ loading, disabled }) => (\n\t\t\t * <button disabled={disabled}>{loading ? 'Adding…' : 'Add to my program'}</button>\n\t\t\t * )}\n\t\t\t * </UpsellButton>\n\t\t\t * ```\n\t\t\t */\n\t\t\tchildren?: ReactNode | ((state: TriggerState) => ReactElement)\n\t }\n\t| {\n\t\t\tasChild: true\n\t\t\t/**\n\t\t\t * YOUR trigger element — exactly one, and it receives the click handler. A function is\n\t\t\t * accepted here too, and gets {@link TriggerState}; `asChild` and a render prop mean the\n\t\t\t * same thing, so writing both is allowed rather than an error.\n\t\t\t */\n\t\t\tchildren: ReactElement | ((state: TriggerState) => ReactElement)\n\t }\n\n/**\n * `<Checkout>`: the payment renders HERE, so there is no trigger and no children.\n *\n * `children?: never` is the point of the split. `<Checkout payment=\"card\" asChild><button/></Checkout>`\n * used to compile and silently drop the button — the inline branch never read either prop — which is\n * the class of mistake a conditional API produces and a structural one cannot.\n */\nexport type CheckoutInlineProps = PaymentAxis & {\n\tsurface?: never\n\t/** There is no \"elsewhere\" to open — that's `<CheckoutButton>`. */\n\topens?: never\n\tasChild?: never\n\t/** `<Checkout>` renders the payment itself. For a button, use `<CheckoutButton>`. */\n\tchildren?: never\n}\n\n/** Props for {@link Checkout} — the payment, rendered where the tag sits. */\nexport type CheckoutProps = CheckoutCommonProps & CheckoutInlineProps\n\n/** Props for {@link CheckoutButton} — a purchase the buyer opens from a button. */\nexport type CheckoutButtonProps = CheckoutCommonProps &\n\tPaymentAxis &\n\tOpensAxis &\n\tTriggerAxis\n\n/**\n * The `sheet` surface as a registry modal: our {@link Sheet} hosts the driver's\n * element. It resolves outcomes by invoking the callbacks passed via `showModal`\n * args — closures created in the `<Checkout>` trigger (which lives inside\n * `<FunnelView>`, so they carry navigation).\n *\n * EVERY exit resolves exactly once: success/failure through the driver callbacks,\n * and a dismissal (backdrop/Escape unmounts the modal) as `canceled` — otherwise\n * the attempt's status would sit in `loading` forever, permanently disabling the\n * trigger. `canceled` then follows the built-in judgment: status → `error`,\n * `checkout.failed` fires, but `onFailed` routes it only when mapped explicitly.\n * `onStart` is deliberately NOT forwarded to the hosted element — the sheet's\n * open already began the attempt (see {@link CheckoutCallbacks.onStart}).\n */\nconst CheckoutSheet = defineModal<{\n\tproduct: string\n\tsurface: CheckoutSurface\n\t/**\n\t * What the driver should render INSIDE the sheet, when that isn't simply \"whatever the sheet\n\t * normally hosts\". Set by the recovery path, whose author named a payment UI\n\t * (`recover={{ payment: 'express' }}`) that the sheet then hosts on their behalf — the sheet is\n\t * the container, never the answer to what gets rendered. Absent (a plain\n\t * `<CheckoutButton opens=\"sheet\">`) = the driver's default for the sheet, exactly as before.\n\t */\n\trendering?: CheckoutSurface\n\tintent: CheckoutIntent\n\t/** Only ever the AUTHOR's word; an unstated kind is filled from the offering at the driver\n\t * seam ({@link driverWithCatalog}), which the sheet's request passes through like any other. */\n\tkind?: UpsellKind\n\t/** The provider variant the attempt runs as — carried so the hosted surface opens the same\n\t * (managed or not) session the trigger would have. */\n\tmanaged?: boolean\n\t/** Forwarded to the hosted inline surface so the sheet themes like the page would. */\n\tappearance?: CheckoutAppearance\n\t/** Forwarded for the same reason as `appearance`: the sheet lists methods like the page would. */\n\tmethods?: CheckoutMethods\n\t/** Forwarded so a sheet-hosted button is painted exactly like the page's would be. */\n\tclassNames?: CheckoutClassNames\n\tonSuccess: (result: CheckoutResult) => void\n\tonError: (error: CheckoutError) => void\n\tonPaymentAdded?: () => void\n}>(({ product, surface, rendering, intent, kind, managed, appearance, methods, classNames, onSuccess, onError, onPaymentAdded }) => {\n\tconst driver = useDriver()\n\tconst modal = useModal()\n\t// True once ANY outcome was reported — the unmount cleanup below only converts a\n\t// silent dismissal into `canceled`, never doubles a real outcome.\n\tconst resolved = useRef(false)\n\tconst onErrorRef = useRef(onError)\n\tonErrorRef.current = onError\n\tconst hostable = !!driver.renderInline\n\tuseEffect(() => {\n\t\tif (!hostable) {\n\t\t\t// Defensive: a driver with no inline surface cannot host the sheet — resolve\n\t\t\t// the attempt instead of leaving the trigger stuck in `loading`.\n\t\t\tresolved.current = true\n\t\t\tonErrorRef.current(\n\t\t\t\tcheckoutError(\n\t\t\t\t\t'processing_error',\n\t\t\t\t\t'This checkout driver has no inline surface to host in the sheet'\n\t\t\t\t)\n\t\t\t)\n\t\t\tvoid modal.hide()\n\t\t\tmodal.remove()\n\t\t\treturn\n\t\t}\n\t\treturn () => {\n\t\t\t// Backdrop/Escape dismissal removes the modal (unmount) without an outcome.\n\t\t\tif (!resolved.current) {\n\t\t\t\tonErrorRef.current(\n\t\t\t\t\tcheckoutError(\n\t\t\t\t\t\t'canceled',\n\t\t\t\t\t\t'Checkout was dismissed before completing'\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\t// Mount-scoped by design: resolution is tracked through refs.\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [])\n\tif (!driver.renderInline) return null\n\t// Outcomes REMOVE the modal (not just hide it): the next show mounts fresh, so\n\t// the resolution ref can never leak a previous attempt's state into a new one.\n\tconst close = () => {\n\t\tresolved.current = true\n\t\tvoid modal.hide()\n\t\tmodal.remove()\n\t}\n\treturn createElement(Sheet, {\n\t\t// The payment sheet is the FLOATING presentation — an inset card that springs in on\n\t\t// transform/opacity only. Its HEIGHT is never animated: on mobile the card RESERVES a\n\t\t// fixed height so it holds its shape while the provider's iframe is still blank, rather\n\t\t// than growing as Link loads, expands and swaps to an OTP step. See `SheetVariant` in\n\t\t// ../modals/sheet.tsx for why this is a Sheet variant rather than a `<Modal>`: the sticky\n\t\t// submit dock's whole contract is \"the SHEET's panel is the scrollport\", and it stays one\n\t\t// file away from it.\n\t\tvariant: 'floating',\n\t\tchildren: driver.renderInline(\n\t\t\t{ product, intent, surface, rendering, kind, managed, appearance, methods, classNames },\n\t\t\t{\n\t\t\t\tonSuccess: (r) => {\n\t\t\t\t\tclose()\n\t\t\t\t\tonSuccess(r)\n\t\t\t\t},\n\t\t\t\tonError: (e) => {\n\t\t\t\t\tclose()\n\t\t\t\t\tonError(e)\n\t\t\t\t},\n\t\t\t\tonPaymentAdded,\n\t\t\t}\n\t\t),\n\t})\n})\n\n/** Render the default trigger button, or clone the author's `asChild` element. */\n/**\n * Host elements that actually have a `disabled` attribute. Forwarding it to a `<div>` or an `<a>`\n * would be an invalid DOM attribute (and a React warning), so those are left alone — a funnel that\n * triggers from a div can read `disabled` off the render prop and do whatever is right for it.\n * A COMPONENT (function/class) is always forwarded to: it can accept the prop and decide.\n */\nconst DISABLEABLE = new Set(['button', 'input', 'select', 'textarea', 'fieldset', 'optgroup', 'option'])\n\nfunction trigger(\n\tonClick: () => void,\n\t{\n\t\tasChild,\n\t\tchildren,\n\t\tclassName,\n\t\tdisabled,\n\t}: {\n\t\tasChild?: boolean\n\t\tchildren?: ReactNode | ((state: TriggerState) => ReactElement)\n\t\tclassName?: string\n\t\tdisabled?: boolean\n\t}\n): ReactNode {\n\tconst busy = !!disabled\n\t// A render prop is `asChild` that can SEE the attempt: same clone, same click handler, but the\n\t// funnel gets to draw a spinner or swap the label. `asChild` alone can't — which is why a custom\n\t// trigger silently had no loading state, and why this exists.\n\tconst spinner = busy ? createElement(CheckoutSpinner) : null\n\tconst resolved =\n\t\ttypeof children === 'function' ? children({ loading: busy, disabled: busy, spinner }) : children\n\n\tif ((asChild || typeof children === 'function') && isValidElement(resolved)) {\n\t\tconst child = resolved as ReactElement<{ onClick?: () => void; disabled?: boolean }>\n\t\t// The child's OWN `disabled` wins: it said something explicit, and an attempt being in flight\n\t\t// is not a reason to overrule it. Absent, it inherits ours — the bug this fixes was cloning\n\t\t// only `onClick`, so every `asChild` trigger stayed pressable through its own charge.\n\t\tconst forwards = typeof child.type !== 'string' || DISABLEABLE.has(child.type)\n\t\treturn cloneElement(child, {\n\t\t\tonClick,\n\t\t\t...(forwards && child.props.disabled === undefined ? { disabled: busy } : {}),\n\t\t})\n\t}\n\t// The SDK's own button says it is working without the funnel asking. The spinner sits BESIDE the\n\t// label rather than replacing it: the label is what tells the buyer which purchase is running,\n\t// and swapping it out mid-charge is the moment they most want that confirmed. The default button\n\t// is full-width, so nothing shifts.\n\tconst label = (resolved as ReactNode) ?? 'Continue'\n\treturn createElement(\n\t\t'button',\n\t\t{ type: 'button', className, disabled, onClick },\n\t\tbusy\n\t\t\t? createElement(\n\t\t\t\t\t'span',\n\t\t\t\t\t{ style: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: '.5em' } },\n\t\t\t\t\tspinner,\n\t\t\t\t\tlabel,\n\t\t\t\t)\n\t\t\t: label\n\t)\n}\n\n/**\n * Detect the buyer's device CLASS for `surface=\"auto\"` resolution — a tiny, deterministic,\n * SSR-safe heuristic (kept local so the checkout chunk doesn't pull the funnel-context module\n * graph). Wallet-first is a phone affordance, so we only need a binary mobile/desktop split:\n * - a mobile-phone UA (the same discriminator {@link ../state/context} uses) → `mobile`;\n * - else a coarse-pointer + narrow-viewport touch device (a phone with an ambiguous UA) → `mobile`;\n * - everything else (desktop, tablets) → `desktop` (the inline card field / embedded frame).\n * SSR (`window` absent) returns `desktop`, matching the neutral default in state/context.ts.\n */\nexport function detectDeviceClass(): DeviceClass {\n\tif (typeof window === 'undefined') return 'desktop'\n\tconst ua = navigator.userAgent?.toLowerCase() ?? ''\n\tif (/mobile|android(?!.*tablet)|iphone|ipod/.test(ua)) return 'mobile'\n\ttry {\n\t\tif (window.matchMedia?.('(pointer: coarse)').matches && window.innerWidth > 0 && window.innerWidth < 768) {\n\t\t\treturn 'mobile'\n\t\t}\n\t} catch {\n\t\t// A locked-down frame can throw on matchMedia — treat as desktop.\n\t}\n\treturn 'desktop'\n}\n\n/**\n * SAMPLE-pricing behaviour: an unassigned offering slot resolves (via `useOffering`) to a DISPLAY-only\n * {@link Offering} flagged `sample: true` — placeholder pricing with no catalog charge key. A sample can\n * ONLY occur in a preview/unpublished funnel (the LIVE-publish gate blocks promotion while any slot is\n * unassigned), so it never reaches a paying visitor. Rather than dead-ending the preview with a disabled\n * button, `<Checkout>`/`<UpsellButton>` treat a sample click as a SIMULATED success: they run the normal success\n * path (fire `onSuccess` + auto-advance) without ever touching a provider/charge, so the whole funnel stays\n * walkable end-to-end in preview with no template-side preview code. The server remains the authority — it\n * refuses an unassigned slot — so this is a preview affordance only. `notePreviewCheckout` logs a dev note.\n */\nfunction notePreviewCheckout(\n\tkind: 'Checkout' | 'CheckoutButton' | 'UpsellButton',\n\tslot: string\n): void {\n\tif (\n\t\t(globalThis as { process?: { env?: { NODE_ENV?: string } } }).process?.env\n\t\t\t?.NODE_ENV !== 'production'\n\t) {\n\t\tconsole.info(\n\t\t\t`[appfunnel] <${kind} offering=\"${slot}\"> resolved to SAMPLE pricing (no assigned offering) — this is a preview, so the action simulates a successful purchase and advances the flow (no real charge) to keep the funnel walkable. Assign a real offering to \"${slot}\" to enable live checkout.`\n\t\t)\n\t}\n}\n\n/**\n * WHERE an attempt is presented and WHAT the provider renders inside it — the pair the two author\n * axes resolve to, and the pair {@link CheckoutRequest} carries as `surface` + `rendering`.\n */\ninterface Presentation {\n\t/** The CONTAINER — the one word that crosses the wire (`CheckoutRequest.surface`). */\n\tcontainer: CheckoutSurface\n\t/**\n\t * WHAT the provider renders in there, when that is a separate answer. Absent = the container IS\n\t * the answer, which is the case everywhere except our own overlay: a page-mounted checkout\n\t * renders in the page, and a provider-hosted popup/redirect renders its own everything.\n\t */\n\trendering?: CheckoutSurface\n}\n\n/**\n * Map the author's two axes onto the wire's one word. THE seam between the new API and the unchanged\n * checkout protocol: `payment` picks the rendering ({@link resolvePayment}), `opens` picks the\n * container, and the server keeps being handed exactly the {@link CheckoutSurface} vocabulary it has\n * always validated — `postSession` builds its body field by field and learns nothing new.\n *\n * Three shapes, and `rendering` is absent in two of them because there is nothing separate to say:\n * - no `opens` (`<Checkout>`) — the PAGE is the container, so container = rendering by construction;\n * - `opens: 'popup' | 'redirect'` — the provider paints the whole thing, container included;\n * - `opens: 'sheet'` — our overlay hosting the provider's rendering. The one place the two answers\n * genuinely differ, and what {@link CheckoutRequest.rendering} exists for.\n */\nfunction resolvePresentation(\n\tprovider: CheckoutProvider,\n\topts: { payment?: PaymentMode; opens?: OpensIn; managed?: boolean }\n): Presentation {\n\tconst { payment = 'auto', opens, managed } = opts\n\tif (opens === 'popup' || opens === 'redirect') return { container: opens }\n\tconst rendering = resolvePayment(provider, payment, detectDeviceClass(), {\n\t\tmanaged,\n\t})\n\treturn opens === 'sheet'\n\t\t? { container: 'sheet', rendering }\n\t\t: { container: rendering }\n}\n\n/** What {@link Checkout} and {@link CheckoutButton} share — everything but how they resolve. */\ninterface CheckoutImplProps extends UseCheckoutOptions {\n\toffering: string\n\t/**\n\t * Resolve this checkout's {@link Presentation}. Called EXACTLY once, in the mount-time freeze\n\t * below — the two components differ only in what they pass here.\n\t */\n\tresolve: (provider: CheckoutProvider) => Presentation\n\t/** The author-facing component name, for the preview note. */\n\tas: 'Checkout' | 'CheckoutButton'\n\tasChild?: boolean\n\tchildren?: ReactNode\n\tclassName?: string\n\tappearance?: CheckoutAppearance\n\tmethods?: CheckoutMethods\n\tclassNames?: CheckoutClassNames\n}\n\n/**\n * The purchase machinery both checkout components run on. Three presentation modes by the RESOLVED\n * container:\n * - **inline** (`express`/`element`/`embedded`) — the driver renders the provider UI in place\n * (keyed by product so a selection change remounts it);\n * - **SDK sheet** (`sheet`) — a trigger opens the Appfunnel-owned {@link Sheet} and the driver\n * renders the provider element inside it;\n * - **provider-hosted** (`popup`/`redirect`) — a trigger hands off to the provider's own overlay/page.\n */\nfunction CheckoutImpl({\n\toffering,\n\tresolve,\n\tas,\n\tasChild,\n\tchildren,\n\tclassName,\n\tappearance,\n\tmethods,\n\tclassNames,\n\t...options\n}: CheckoutImplProps): ReactNode {\n\t// `offering` is the author-facing prop; internally it flows as the checkout SLOT\n\t// (`req.product` on the wire — the provider boundary keeps the `product` field).\n\tconst product = offering\n\tconst driver = useDriver()\n\tconst managed = options.managed\n\t// Resolve the presentation ONCE per mount, against the provider + detected device class (and the\n\t// provider VARIANT, so `'auto'` picks from what THIS checkout can render — under `managed` both\n\t// device classes land on `embedded`, which also makes the SSR/hydration answers agree by\n\t// construction since the device class stops mattering).\n\t//\n\t// FROZEN via the initializer, and BOTH halves are frozen together on purpose: recomputing either\n\t// one remounts the driver, and a remounted driver mints a SECOND correlationId — orphaning the\n\t// attempt already in flight against the first. The container and the rendering are one decision\n\t// about one attempt, so they are one piece of state.\n\tconst [presentation] = useState<Presentation>(() => resolve(driver.provider))\n\tconst surface = presentation.container\n\tconst rendering = presentation.rendering\n\tconst checkout = useCheckout(options)\n\tconst intent = options.intent ?? 'purchase'\n\t// SAMPLE (preview) behaviour: an unassigned slot resolves to sample (placeholder) pricing, which only\n\t// happens in a preview funnel. Instead of starting a real charge we simulate success — run the normal\n\t// success path (onSuccess + auto-advance), no provider — so the preview is walkable (see\n\t// notePreviewCheckout). The server still refuses an unassigned slot; this is a preview affordance only.\n\tconst isSample = useOffering(offering)?.sample === true\n\tconst previewAdvance = () => {\n\t\tnotePreviewCheckout(as, product)\n\t\tcheckout.callbacksFor(product, surface).onSuccess({ ok: true })\n\t}\n\n\t// An authoring mistake the runtime can answer without asking anyone (see refuseSurface):\n\t// `managed` beside a surface managed doesn't have. Reported ONCE on mount through the normal\n\t// failure path — status → `error`, `checkout.failed` fires, `onFailed` routes — because that\n\t// is how every other checkout outcome reaches the author, and nothing chargeable is rendered\n\t// below: mounting the provider element (or a trigger for it) would open an attempt the server\n\t// is bound to reject. Callbacks ride a ref so the mount-scoped effect stays mount-scoped.\n\tconst rejection = refuseSurface(driver.provider, surface, managed)\n\tconst callbacksRef = useRef(checkout.callbacksFor)\n\tcallbacksRef.current = checkout.callbacksFor\n\tuseEffect(() => {\n\t\tif (!rejection) return\n\t\tcallbacksRef\n\t\t\t.current(product, surface)\n\t\t\t.onError(checkoutError('processing_error', rejection, { retryable: false }))\n\t\t// Mount-scoped by design: the pair is an authoring fact and `surface` is frozen, so it\n\t\t// cannot become true (or stop being true) later in this mount.\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [])\n\tif (rejection) return null\n\n\t// Inline: driver renders the mounted UI; keyed by product so changing the\n\t// selected plan cleanly remounts the surface. A SAMPLE slot has no charge key,\n\t// so instead of mounting the provider element we render a trigger that advances\n\t// the preview (never a live payment surface for placeholder pricing).\n\tif (isInlineSurface(surface)) {\n\t\tif (isSample) return trigger(previewAdvance, { asChild, children, className })\n\t\treturn driver.renderInline\n\t\t\t? createElement(\n\t\t\t\t\t'div',\n\t\t\t\t\t{ key: product, className },\n\t\t\t\t\tdriver.renderInline(\n\t\t\t\t\t\t{ product, intent, surface, rendering, managed, appearance, methods, classNames },\n\t\t\t\t\t\tcheckout.callbacksFor(product, surface)\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t: null\n\t}\n\n\t// SDK sheet: open our overlay (a registry modal) hosting the driver's element.\n\tif (surface === 'sheet') {\n\t\tconst cb = checkout.callbacksFor(product, surface)\n\t\tconst open = () => {\n\t\t\tif (isSample) return previewAdvance()\n\t\t\tcb.onStart()\n\t\t\tshowModal(CheckoutSheet, {\n\t\t\t\tproduct,\n\t\t\t\tsurface,\n\t\t\t\t// What the sheet HOSTS, when the author said (`payment`). Absent for a legacy\n\t\t\t\t// `surface=\"sheet\"`, which never named one — the driver's own default stands, exactly\n\t\t\t\t// as it did before there was a second word to carry.\n\t\t\t\trendering,\n\t\t\t\tintent,\n\t\t\t\tappearance,\n\t\t\t\tmethods,\n\t\t\t\tclassNames,\n\t\t\t\tkind: options.kind,\n\t\t\t\tmanaged,\n\t\t\t\tonSuccess: cb.onSuccess,\n\t\t\t\tonError: cb.onError,\n\t\t\t\tonPaymentAdded: cb.onPaymentAdded,\n\t\t\t})\n\t\t}\n\t\treturn trigger(open, {\n\t\t\tasChild,\n\t\t\tchildren,\n\t\t\tclassName,\n\t\t\tdisabled: checkout.isLoading,\n\t\t})\n\t}\n\n\t// Provider-hosted (popup/redirect): trigger hands off to the provider.\n\treturn trigger(\n\t\t() => {\n\t\t\tif (isSample) return previewAdvance()\n\t\t\tvoid checkout.open(product, surface)\n\t\t},\n\t\t{\n\t\t\tasChild,\n\t\t\tchildren,\n\t\t\tclassName,\n\t\t\tdisabled: checkout.isLoading,\n\t\t}\n\t)\n}\n\n/**\n * **The purchase, rendered right here.** The provider's payment UI mounts where you put this tag —\n * no button, no overlay, nothing to tap first.\n *\n * ```tsx\n * <Checkout offering=\"plan\" /> // the best complete payment UI for this provider\n * <Checkout offering=\"plan\" payment=\"card\" /> // a card form\n * <Checkout offering=\"plan\" payment=\"full\" /> // the provider's whole checkout, in the page\n * ```\n *\n * `payment` ({@link PaymentMode}) is the only decision, it defaults to `'auto'`, and `'auto'` always\n * resolves to a COMPLETE way to pay — a buyer who reaches this can always finish, whatever wallets\n * they do or don't have. To open the payment from a button instead, reach for {@link CheckoutButton};\n * that is the whole difference between the two, and it's carried by which tag you write rather than\n * by a prop.\n *\n * @param props {@link CheckoutProps} — or the deprecated `surface` shape, unchanged.\n */\nexport function Checkout(props: CheckoutProps): ReactNode {\n\t// The prop UNION is an authoring contract; inside, one widened view of it. Which shape was\n\t// written is decided exactly once, in `resolve` below, by whether `surface` is present.\n\tconst {\n\t\toffering,\n\t\tpayment,\n\t\tclassName,\n\t\tappearance,\n\t\tmethods,\n\t\tclassNames,\n\t\t...options\n\t} = props as CheckoutCommonProps & {\n\t\tpayment?: PaymentMode\n\t\tmanaged?: boolean\n\t}\n\tconst managed = options.managed\n\treturn createElement(CheckoutImpl, {\n\t\t...options,\n\t\toffering,\n\t\tclassName,\n\t\tappearance,\n\t\tmethods,\n\t\tclassNames,\n\t\tas: 'Checkout',\n\t\t// The axes resolve, and the result is always an INLINE rendering: `<Checkout>` is the payment\n\t\t// itself, so there is no container question for it to answer. A payment that opens somewhere\n\t\t// is `<CheckoutButton>`.\n\t\tresolve: (provider: CheckoutProvider) => resolvePresentation(provider, { payment, managed }),\n\t})\n}\n\n/**\n * **The purchase, opened from a button.** Same charge, same `payment` axis; this one waits for a tap\n * and then presents the payment somewhere else.\n *\n * ```tsx\n * <CheckoutButton offering=\"plan\">Get my plan</CheckoutButton> // our sheet\n * <CheckoutButton offering=\"plan\" opens=\"redirect\">Continue</CheckoutButton> // the provider's page\n * <CheckoutButton offering=\"plan\" asChild><MyButton /></CheckoutButton> // your own trigger\n * ```\n *\n * `opens` ({@link OpensIn}) defaults to `'sheet'` — the funnel's own overlay, hosting whatever the\n * provider renders, buyer never leaves the page. `'redirect'` is the one to reach for inside the iOS\n * in-app browsers Meta and TikTok open, where overlays can fail silently.\n *\n * `asChild` clones YOUR element and gives it the click handler; the type requires exactly one\n * element child when you use it.\n */\nexport function CheckoutButton(props: CheckoutButtonProps): ReactNode {\n\tconst {\n\t\toffering,\n\t\tpayment,\n\t\topens,\n\t\tasChild,\n\t\tchildren,\n\t\tclassName,\n\t\tappearance,\n\t\tmethods,\n\t\tclassNames,\n\t\t...options\n\t} = props as CheckoutCommonProps & {\n\t\tpayment?: PaymentMode\n\t\topens?: OpensIn\n\t\tasChild?: boolean\n\t\tchildren?: ReactNode\n\t\tmanaged?: boolean\n\t}\n\tconst managed = options.managed\n\treturn createElement(CheckoutImpl, {\n\t\t...options,\n\t\toffering,\n\t\tclassName,\n\t\tappearance,\n\t\tmethods,\n\t\tclassNames,\n\t\tasChild,\n\t\tchildren,\n\t\tas: 'CheckoutButton',\n\t\tresolve: (provider: CheckoutProvider) =>\n\t\t\tresolvePresentation(provider, {\n\t\t\t\tpayment,\n\t\t\t\topens: opens ?? 'sheet',\n\t\t\t\tmanaged,\n\t\t\t}),\n\t})\n}\n\n/** Recovery, described by what it should ask the buyer for — see {@link UpsellButtonProps.recover}. */\nexport interface UpsellRecovery {\n\t/**\n\t * Which payment UI the provider renders in the recovery sheet. Omit for the provider's own\n\t * default there (Stripe: the card form; Stripe managed: its embedded checkout) — which is\n\t * what every authored upsell in every template has ever wanted.\n\t */\n\tpayment?: PaymentRendering\n}\n\n/**\n * The container a recovery runs in when the author didn't name one — and they never can, so this\n * is every recovery's container. OURS wherever the (provider × variant) has a sheet, because the\n * whole point of recovering is to keep the buyer on the page they are already on, mid-sequence.\n *\n * A provider with no sheet of ours (Paddle: merchant-of-record, card entry only ever happens in\n * its frame) has no such option, so the recovery falls to that provider's best renderable surface\n * — its own overlay/frame, opened by the driver. Resolved through the same `'auto'` machinery\n * `<Checkout>` uses, so \"best\" means one thing in the SDK rather than two.\n */\nfunction defaultRecoveryContainer(\n\tprovider: CheckoutProvider,\n\tmanaged?: boolean\n): CheckoutSurface {\n\tif (profileFor(provider, { managed }).surfaces.sheet) return 'sheet'\n\treturn resolveSurface(provider, 'auto', detectDeviceClass(), { managed })\n}\n\n/** What {@link UpsellButton} takes beyond the shared axes (`managed` comes in via {@link PaymentAxis}). */\nexport interface UpsellCommonProps\n\textends Omit<UseCheckoutOptions, 'intent' | 'managed'> {\n\toffering: string\n\t/**\n\t * What happens when the one-tap off-session charge fails: **recover on-session**, in the\n\t * funnel, once. ON BY DEFAULT — every authored `<UpsellButton>` in every template asked for it, so\n\t * asking was boilerplate rather than a decision. `recover={false}` opts out and leaves the\n\t * failure to `onError` / the `checkout.failed` event.\n\t *\n\t * It names no surface, because a recovery has no surface to name. The buyer is mid-sequence\n\t * with no page slot to mount a payment UI into, so the SDK's own sheet hosts it — the container\n\t * is always ours (where the provider allows one at all: see {@link defaultRecoveryContainer}).\n\t * All that is left to choose is what the provider renders inside, and only when the default\n\t * isn't wanted — which is what the `payment` prop is for: `payment=\"wallets\"` re-collects with a\n\t * wallet quick-button instead of a card form. (`opens` is the one exception to \"no container to\n\t * name\": it hands the recovery to the provider's own overlay or page instead of our sheet.)\n\t *\n\t * Under `managed` this isn't a decline path at all — it IS the checkout. Stripe Managed\n\t * Payments has no one tap (the charge has to ride a Checkout Session, which an off-session\n\t * PaymentIntent isn't), so the surfaceless attempt is refused and the recovery is what sells:\n\t * our sheet, hosting Stripe's embedded checkout, on the page the buyer was already on. Being\n\t * the default, that now needs nothing authored.\n\t *\n\t * Only opens for a RETRYABLE failure ({@link CheckoutError.retryable}), so a refusal a new\n\t * card can't change never asks for one. The case that matters here is the repeat tap:\n\t * `already_purchased` means the buyer owns the upsell, and the flow advances instead — no\n\t * card form, no second charge, no second conversion.\n\t */\n\trecover?: boolean | UpsellRecovery\n\tclassName?: string\n}\n\n/**\n * Props for {@link UpsellButton}. `payment` and `opens` describe the RECOVERY — the only thing an\n * upsell ever presents — and are narrowed by `managed`/`opens` exactly as they are on the checkout\n * components.\n */\nexport type UpsellButtonProps = UpsellCommonProps &\n\tPaymentAxis &\n\tOpensAxis &\n\tTriggerAxis\n\n/**\n * Resolve the recovery to the ONE surface word the hook's machinery takes ({@link\n * UseCheckoutOptions.recoverySurface}), of which everything below is a more legible spelling.\n *\n * The hook then splits it back into a container and a rendering (`startRecovery` → `hostInSheet`):\n * an INLINE word means \"the provider renders this, in our sheet\", and `popup`/`redirect` mean \"hand\n * the whole thing to the provider\". So `opens` maps to the container words and `payment` maps to the\n * rendering words, and the single knob underneath keeps carrying both.\n *\n * Precedence, most explicit first — every branch documents a spelling that already existed, so an\n * upsell written before any of this resolves to exactly what it used to:\n */\nfunction resolveRecovery(\n\tprovider: CheckoutProvider,\n\topts: {\n\t\trecover?: boolean | UpsellRecovery\n\t\tpayment?: PaymentMode\n\t\topens?: OpensIn\n\t\trecoverySurface?: CheckoutSurface\n\t\tmanaged?: boolean\n\t}\n): CheckoutSurface | undefined {\n\tconst { recover, payment, opens, recoverySurface, managed } = opts\n\t// No recovery at all: the failure is the author's to handle (onError / checkout.failed).\n\tif (recover === false) return undefined\n\t// A provider hand-off — the one container an upsell CAN name, because it isn't ours. This is the\n\t// iOS in-app-browser escape hatch, and it is why `opens` outranks everything below it.\n\tif (opens === 'popup' || opens === 'redirect') return opens\n\t// `recover={{ payment }}` — the nested spelling, for an author who is already describing the\n\t// recovery as an object rather than reaching for the flat prop.\n\tif (recover && recover !== true && recover.payment) return recover.payment\n\t// The payment axis proper. `'auto'` deliberately does NOT resolve here: on a recovery it means\n\t// \"whatever the provider puts in our sheet\", which is the sheet's own default and is complete by\n\t// construction — resolving it to a concrete rendering would silently change what every existing\n\t// upsell shows, to no benefit.\n\tif (payment && payment !== 'auto') return PAYMENT_RENDERINGS[payment]\n\t// The one raw surface word left: `recoverySurface`, which the headless hook takes directly.\n\tif (recover === undefined && !opens && recoverySurface) return recoverySurface\n\t// The default: recover, in our sheet, with whatever the provider renders there.\n\treturn defaultRecoveryContainer(provider, managed)\n}\n\n/**\n * **The upsell.** One tap charges the card the buyer already gave you — off-session, no surface, no\n * card re-entry. Nothing opens unless that charge fails.\n *\n * ```tsx\n * <UpsellButton offering=\"addon\">Add it</UpsellButton>\n * <UpsellButton offering=\"addon\" payment=\"wallets\">Add it</UpsellButton> // recover with a wallet\n * <UpsellButton offering=\"addon\" recover={false}>Add it</UpsellButton> // don't recover at all\n * ```\n *\n * When it fails it RECOVERS on-session by default ({@link UpsellCommonProps.recover}): the SDK's\n * sheet re-collects and charges again, once, and the retry's own failure routes through `onFailed`\n * (e.g. prepaid_card → a recapture page) instead of dead-ending. `payment` and `opens` describe THAT\n * — there is nothing else for them to describe, since the one-tap charge shows no UI at all.\n *\n * `managed` ({@link UseCheckoutOptions.managed}) applies here as anywhere else — this is the checkout\n * that decides, so the two upsell shapes can coexist in one funnel: a MANAGED upsell buys\n * Merchant-of-Record coverage, while the default non-managed one keeps the one tap.\n */\nexport function UpsellButton(props: UpsellButtonProps): ReactNode {\n\tconst {\n\t\toffering,\n\t\trecover,\n\t\tpayment,\n\t\topens,\n\t\tasChild,\n\t\tchildren,\n\t\tclassName,\n\t\t...options\n\t} = props as UpsellCommonProps & {\n\t\tpayment?: PaymentMode\n\t\topens?: OpensIn\n\t\tasChild?: boolean\n\t\tchildren?: ReactNode\n\t\tmanaged?: boolean\n\t}\n\t// Author-facing prop → internal checkout SLOT (wire keeps `product`).\n\tconst product = offering\n\tconst driver = useDriver()\n\t// Frozen per mount for the same reason `<Checkout>`'s presentation is: the default reads the\n\t// device class, and a recovery that changed shape between the failure and the sheet would open a\n\t// container the failure wasn't validated against.\n\tconst [recoverySurface] = useState<CheckoutSurface | undefined>(() =>\n\t\tresolveRecovery(driver.provider, {\n\t\t\trecover,\n\t\t\tpayment,\n\t\t\topens,\n\t\t\trecoverySurface: options.recoverySurface,\n\t\t\tmanaged: options.managed,\n\t\t})\n\t)\n\tconst checkout = useCheckout({ ...options, intent: 'upsell', recoverySurface })\n\t// SAMPLE (preview): an unassigned slot resolves to placeholder pricing (preview only). Simulate the\n\t// off-session charge succeeding — run the success path (onSuccess + auto-advance) — so the post-purchase\n\t// upsell sequence is walkable in preview without any template-side preview code (see notePreviewCheckout).\n\tconst isSample = useOffering(offering)?.sample === true\n\n\treturn trigger(\n\t\t() => {\n\t\t\tif (isSample) {\n\t\t\t\tnotePreviewCheckout('UpsellButton', product)\n\t\t\t\tcheckout.callbacksFor(product).onSuccess({ ok: true })\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvoid checkout.open(product) /* off-session (no surface) */\n\t\t},\n\t\t{\n\t\t\tasChild,\n\t\t\tchildren: children ?? 'Add to my plan',\n\t\t\tclassName,\n\t\t\tdisabled: checkout.isLoading,\n\t\t}\n\t)\n}\n\n// ── Redirect-return resume (hosted checkout success URLs) ────────────────────\n\n/** correlationIds this page load already resumed — the leg runs once per attempt\n * even if the component remounts (StrictMode, page-experiment remounts). */\nconst consumedResumes = new Set<string>()\n\n/**\n * The dangling settle leg of the `redirect` surface. The server appends\n * `af_checkout={correlationId}` to hosted-checkout success URLs; when the buyer\n * lands back in the funnel this component detects the param, has the server\n * VERIFY the attempt (`driver.resume` → `POST /complete`, bounded re-poll while\n * `pending`), and resolves it into the normal machinery:\n *\n * - `settled` → `purchase.complete` fires with the settlement's server-minted\n * `eventId` (pixel↔CAPI dedup), the flow advances, and the param is stripped\n * (`history.replaceState`) so a reload can't re-run the leg;\n * - `failed` → the normal failure path (`checkout.failed` + status `error`;\n * any `onFailed` maps passed as props apply — product-less, so only\n * `go`/handler routes can act).\n *\n * SSR-safe (effect-only) and runs once per correlationId per page load. Mounted\n * automatically by `createFunnelTree` inside the nav context; needs a driver\n * with `resume` (both platform drivers ship it; the mock resolves its result).\n */\nexport function CheckoutResume(options: UseCheckoutOptions = {}): ReactNode {\n\tconst driver = useDriver()\n\tconst checkout = useCheckout(options)\n\tconst callbacksRef = useRef(checkout.callbacksFor)\n\tcallbacksRef.current = checkout.callbacksFor\n\n\tuseEffect(() => {\n\t\tif (typeof window === 'undefined' || !driver.resume) return\n\t\tconst url = new URL(window.location.href)\n\t\tconst correlationId = url.searchParams.get('af_checkout')\n\t\tif (!correlationId || consumedResumes.has(correlationId)) return\n\t\tconsumedResumes.add(correlationId)\n\t\tvoid driver.resume(correlationId).then((result) => {\n\t\t\t// Not a new attempt — no onStart/`checkout.start`; the charge already ran.\n\t\t\tconst cb = callbacksRef.current()\n\t\t\tif (result.ok) {\n\t\t\t\t// Re-read the URL HERE rather than reusing the one captured at mount: the path is\n\t\t\t\t// live now (the SDK rewrites it to `<basePath>/<slug>` on every page change), and the\n\t\t\t\t// verify round-trip above is long enough for a loader page to have auto-advanced.\n\t\t\t\t// Writing the mount-time URL back would drag the address bar to a page the visitor\n\t\t\t\t// already left — and a reload would then send a paying buyer back to the paywall.\n\t\t\t\tconst current = new URL(window.location.href)\n\t\t\t\tcurrent.searchParams.delete('af_checkout')\n\t\t\t\twindow.history.replaceState(\n\t\t\t\t\twindow.history.state,\n\t\t\t\t\t'',\n\t\t\t\t\tcurrent.toString()\n\t\t\t\t)\n\t\t\t\tcb.onSuccess(result)\n\t\t\t} else {\n\t\t\t\tcb.onError(\n\t\t\t\t\tresult.error ??\n\t\t\t\t\t\tcheckoutError(\n\t\t\t\t\t\t\t'unknown',\n\t\t\t\t\t\t\t'The checkout could not be verified'\n\t\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\t\t// Mount-scoped by design (the URL param is a page-load fact).\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [])\n\n\treturn null\n}\n","'use client';\nfunction __insertCSS(code) {\n if (!code || typeof document == 'undefined') return\n let head = document.head || document.getElementsByTagName('head')[0]\n let style = document.createElement('style')\n style.type = 'text/css'\n head.appendChild(style)\n ;style.styleSheet ? (style.styleSheet.cssText = code) : style.appendChild(document.createTextNode(code))\n}\n\nimport React from 'react';\nimport ReactDOM from 'react-dom';\n\nconst getAsset = (type)=>{\n switch(type){\n case 'success':\n return SuccessIcon;\n case 'info':\n return InfoIcon;\n case 'warning':\n return WarningIcon;\n case 'error':\n return ErrorIcon;\n default:\n return null;\n }\n};\nconst bars = Array(12).fill(0);\nconst Loader = ({ visible, className })=>{\n return /*#__PURE__*/ React.createElement(\"div\", {\n className: [\n 'sonner-loading-wrapper',\n className\n ].filter(Boolean).join(' '),\n \"data-visible\": visible\n }, /*#__PURE__*/ React.createElement(\"div\", {\n className: \"sonner-spinner\"\n }, bars.map((_, i)=>/*#__PURE__*/ React.createElement(\"div\", {\n className: \"sonner-loading-bar\",\n key: `spinner-bar-${i}`\n }))));\n};\nconst SuccessIcon = /*#__PURE__*/ React.createElement(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n viewBox: \"0 0 20 20\",\n fill: \"currentColor\",\n height: \"20\",\n width: \"20\"\n}, /*#__PURE__*/ React.createElement(\"path\", {\n fillRule: \"evenodd\",\n d: \"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z\",\n clipRule: \"evenodd\"\n}));\nconst WarningIcon = /*#__PURE__*/ React.createElement(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n viewBox: \"0 0 24 24\",\n fill: \"currentColor\",\n height: \"20\",\n width: \"20\"\n}, /*#__PURE__*/ React.createElement(\"path\", {\n fillRule: \"evenodd\",\n d: \"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z\",\n clipRule: \"evenodd\"\n}));\nconst InfoIcon = /*#__PURE__*/ React.createElement(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n viewBox: \"0 0 20 20\",\n fill: \"currentColor\",\n height: \"20\",\n width: \"20\"\n}, /*#__PURE__*/ React.createElement(\"path\", {\n fillRule: \"evenodd\",\n d: \"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z\",\n clipRule: \"evenodd\"\n}));\nconst ErrorIcon = /*#__PURE__*/ React.createElement(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n viewBox: \"0 0 20 20\",\n fill: \"currentColor\",\n height: \"20\",\n width: \"20\"\n}, /*#__PURE__*/ React.createElement(\"path\", {\n fillRule: \"evenodd\",\n d: \"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z\",\n clipRule: \"evenodd\"\n}));\nconst CloseIcon = /*#__PURE__*/ React.createElement(\"svg\", {\n xmlns: \"http://www.w3.org/2000/svg\",\n width: \"12\",\n height: \"12\",\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n stroke: \"currentColor\",\n strokeWidth: \"1.5\",\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\"\n}, /*#__PURE__*/ React.createElement(\"line\", {\n x1: \"18\",\n y1: \"6\",\n x2: \"6\",\n y2: \"18\"\n}), /*#__PURE__*/ React.createElement(\"line\", {\n x1: \"6\",\n y1: \"6\",\n x2: \"18\",\n y2: \"18\"\n}));\n\nconst useIsDocumentHidden = ()=>{\n const [isDocumentHidden, setIsDocumentHidden] = React.useState(document.hidden);\n React.useEffect(()=>{\n const callback = ()=>{\n setIsDocumentHidden(document.hidden);\n };\n document.addEventListener('visibilitychange', callback);\n return ()=>window.removeEventListener('visibilitychange', callback);\n }, []);\n return isDocumentHidden;\n};\n\nlet toastsCounter = 1;\nclass Observer {\n constructor(){\n // We use arrow functions to maintain the correct `this` reference\n this.subscribe = (subscriber)=>{\n this.subscribers.push(subscriber);\n return ()=>{\n const index = this.subscribers.indexOf(subscriber);\n this.subscribers.splice(index, 1);\n };\n };\n this.publish = (data)=>{\n this.subscribers.forEach((subscriber)=>subscriber(data));\n };\n this.addToast = (data)=>{\n this.publish(data);\n this.toasts = [\n ...this.toasts,\n data\n ];\n };\n this.create = (data)=>{\n var _data_id;\n const { message, ...rest } = data;\n const id = typeof (data == null ? void 0 : data.id) === 'number' || ((_data_id = data.id) == null ? void 0 : _data_id.length) > 0 ? data.id : toastsCounter++;\n const alreadyExists = this.toasts.find((toast)=>{\n return toast.id === id;\n });\n const dismissible = data.dismissible === undefined ? true : data.dismissible;\n if (this.dismissedToasts.has(id)) {\n this.dismissedToasts.delete(id);\n }\n if (alreadyExists) {\n this.toasts = this.toasts.map((toast)=>{\n if (toast.id === id) {\n this.publish({\n ...toast,\n ...data,\n id,\n title: message\n });\n return {\n ...toast,\n ...data,\n id,\n dismissible,\n title: message\n };\n }\n return toast;\n });\n } else {\n this.addToast({\n title: message,\n ...rest,\n dismissible,\n id\n });\n }\n return id;\n };\n this.dismiss = (id)=>{\n if (id) {\n this.dismissedToasts.add(id);\n requestAnimationFrame(()=>this.subscribers.forEach((subscriber)=>subscriber({\n id,\n dismiss: true\n })));\n } else {\n this.toasts.forEach((toast)=>{\n this.subscribers.forEach((subscriber)=>subscriber({\n id: toast.id,\n dismiss: true\n }));\n });\n }\n return id;\n };\n this.message = (message, data)=>{\n return this.create({\n ...data,\n message\n });\n };\n this.error = (message, data)=>{\n return this.create({\n ...data,\n message,\n type: 'error'\n });\n };\n this.success = (message, data)=>{\n return this.create({\n ...data,\n type: 'success',\n message\n });\n };\n this.info = (message, data)=>{\n return this.create({\n ...data,\n type: 'info',\n message\n });\n };\n this.warning = (message, data)=>{\n return this.create({\n ...data,\n type: 'warning',\n message\n });\n };\n this.loading = (message, data)=>{\n return this.create({\n ...data,\n type: 'loading',\n message\n });\n };\n this.promise = (promise, data)=>{\n if (!data) {\n // Nothing to show\n return;\n }\n let id = undefined;\n if (data.loading !== undefined) {\n id = this.create({\n ...data,\n promise,\n type: 'loading',\n message: data.loading,\n description: typeof data.description !== 'function' ? data.description : undefined\n });\n }\n const p = Promise.resolve(promise instanceof Function ? promise() : promise);\n let shouldDismiss = id !== undefined;\n let result;\n const originalPromise = p.then(async (response)=>{\n result = [\n 'resolve',\n response\n ];\n const isReactElementResponse = React.isValidElement(response);\n if (isReactElementResponse) {\n shouldDismiss = false;\n this.create({\n id,\n type: 'default',\n message: response\n });\n } else if (isHttpResponse(response) && !response.ok) {\n shouldDismiss = false;\n const promiseData = typeof data.error === 'function' ? await data.error(`HTTP error! status: ${response.status}`) : data.error;\n const description = typeof data.description === 'function' ? await data.description(`HTTP error! status: ${response.status}`) : data.description;\n const isExtendedResult = typeof promiseData === 'object' && !React.isValidElement(promiseData);\n const toastSettings = isExtendedResult ? promiseData : {\n message: promiseData\n };\n this.create({\n id,\n type: 'error',\n description,\n ...toastSettings\n });\n } else if (response instanceof Error) {\n shouldDismiss = false;\n const promiseData = typeof data.error === 'function' ? await data.error(response) : data.error;\n const description = typeof data.description === 'function' ? await data.description(response) : data.description;\n const isExtendedResult = typeof promiseData === 'object' && !React.isValidElement(promiseData);\n const toastSettings = isExtendedResult ? promiseData : {\n message: promiseData\n };\n this.create({\n id,\n type: 'error',\n description,\n ...toastSettings\n });\n } else if (data.success !== undefined) {\n shouldDismiss = false;\n const promiseData = typeof data.success === 'function' ? await data.success(response) : data.success;\n const description = typeof data.description === 'function' ? await data.description(response) : data.description;\n const isExtendedResult = typeof promiseData === 'object' && !React.isValidElement(promiseData);\n const toastSettings = isExtendedResult ? promiseData : {\n message: promiseData\n };\n this.create({\n id,\n type: 'success',\n description,\n ...toastSettings\n });\n }\n }).catch(async (error)=>{\n result = [\n 'reject',\n error\n ];\n if (data.error !== undefined) {\n shouldDismiss = false;\n const promiseData = typeof data.error === 'function' ? await data.error(error) : data.error;\n const description = typeof data.description === 'function' ? await data.description(error) : data.description;\n const isExtendedResult = typeof promiseData === 'object' && !React.isValidElement(promiseData);\n const toastSettings = isExtendedResult ? promiseData : {\n message: promiseData\n };\n this.create({\n id,\n type: 'error',\n description,\n ...toastSettings\n });\n }\n }).finally(()=>{\n if (shouldDismiss) {\n // Toast is still in load state (and will be indefinitely — dismiss it)\n this.dismiss(id);\n id = undefined;\n }\n data.finally == null ? void 0 : data.finally.call(data);\n });\n const unwrap = ()=>new Promise((resolve, reject)=>originalPromise.then(()=>result[0] === 'reject' ? reject(result[1]) : resolve(result[1])).catch(reject));\n if (typeof id !== 'string' && typeof id !== 'number') {\n // cannot Object.assign on undefined\n return {\n unwrap\n };\n } else {\n return Object.assign(id, {\n unwrap\n });\n }\n };\n this.custom = (jsx, data)=>{\n const id = (data == null ? void 0 : data.id) || toastsCounter++;\n this.create({\n jsx: jsx(id),\n id,\n ...data\n });\n return id;\n };\n this.getActiveToasts = ()=>{\n return this.toasts.filter((toast)=>!this.dismissedToasts.has(toast.id));\n };\n this.subscribers = [];\n this.toasts = [];\n this.dismissedToasts = new Set();\n }\n}\nconst ToastState = new Observer();\n// bind this to the toast function\nconst toastFunction = (message, data)=>{\n const id = (data == null ? void 0 : data.id) || toastsCounter++;\n ToastState.addToast({\n title: message,\n ...data,\n id\n });\n return id;\n};\nconst isHttpResponse = (data)=>{\n return data && typeof data === 'object' && 'ok' in data && typeof data.ok === 'boolean' && 'status' in data && typeof data.status === 'number';\n};\nconst basicToast = toastFunction;\nconst getHistory = ()=>ToastState.toasts;\nconst getToasts = ()=>ToastState.getActiveToasts();\n// We use `Object.assign` to maintain the correct types as we would lose them otherwise\nconst toast = Object.assign(basicToast, {\n success: ToastState.success,\n info: ToastState.info,\n warning: ToastState.warning,\n error: ToastState.error,\n custom: ToastState.custom,\n message: ToastState.message,\n promise: ToastState.promise,\n dismiss: ToastState.dismiss,\n loading: ToastState.loading\n}, {\n getHistory,\n getToasts\n});\n\n__insertCSS(\"[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}\");\n\nfunction isAction(action) {\n return action.label !== undefined;\n}\n\n// Visible toasts amount\nconst VISIBLE_TOASTS_AMOUNT = 3;\n// Viewport padding\nconst VIEWPORT_OFFSET = '24px';\n// Mobile viewport padding\nconst MOBILE_VIEWPORT_OFFSET = '16px';\n// Default lifetime of a toasts (in ms)\nconst TOAST_LIFETIME = 4000;\n// Default toast width\nconst TOAST_WIDTH = 356;\n// Default gap between toasts\nconst GAP = 14;\n// Threshold to dismiss a toast\nconst SWIPE_THRESHOLD = 45;\n// Equal to exit animation duration\nconst TIME_BEFORE_UNMOUNT = 200;\nfunction cn(...classes) {\n return classes.filter(Boolean).join(' ');\n}\nfunction getDefaultSwipeDirections(position) {\n const [y, x] = position.split('-');\n const directions = [];\n if (y) {\n directions.push(y);\n }\n if (x) {\n directions.push(x);\n }\n return directions;\n}\nconst Toast = (props)=>{\n var _toast_classNames, _toast_classNames1, _toast_classNames2, _toast_classNames3, _toast_classNames4, _toast_classNames5, _toast_classNames6, _toast_classNames7, _toast_classNames8;\n const { invert: ToasterInvert, toast, unstyled, interacting, setHeights, visibleToasts, heights, index, toasts, expanded, removeToast, defaultRichColors, closeButton: closeButtonFromToaster, style, cancelButtonStyle, actionButtonStyle, className = '', descriptionClassName = '', duration: durationFromToaster, position, gap, expandByDefault, classNames, icons, closeButtonAriaLabel = 'Close toast' } = props;\n const [swipeDirection, setSwipeDirection] = React.useState(null);\n const [swipeOutDirection, setSwipeOutDirection] = React.useState(null);\n const [mounted, setMounted] = React.useState(false);\n const [removed, setRemoved] = React.useState(false);\n const [swiping, setSwiping] = React.useState(false);\n const [swipeOut, setSwipeOut] = React.useState(false);\n const [isSwiped, setIsSwiped] = React.useState(false);\n const [offsetBeforeRemove, setOffsetBeforeRemove] = React.useState(0);\n const [initialHeight, setInitialHeight] = React.useState(0);\n const remainingTime = React.useRef(toast.duration || durationFromToaster || TOAST_LIFETIME);\n const dragStartTime = React.useRef(null);\n const toastRef = React.useRef(null);\n const isFront = index === 0;\n const isVisible = index + 1 <= visibleToasts;\n const toastType = toast.type;\n const dismissible = toast.dismissible !== false;\n const toastClassname = toast.className || '';\n const toastDescriptionClassname = toast.descriptionClassName || '';\n // Height index is used to calculate the offset as it gets updated before the toast array, which means we can calculate the new layout faster.\n const heightIndex = React.useMemo(()=>heights.findIndex((height)=>height.toastId === toast.id) || 0, [\n heights,\n toast.id\n ]);\n const closeButton = React.useMemo(()=>{\n var _toast_closeButton;\n return (_toast_closeButton = toast.closeButton) != null ? _toast_closeButton : closeButtonFromToaster;\n }, [\n toast.closeButton,\n closeButtonFromToaster\n ]);\n const duration = React.useMemo(()=>toast.duration || durationFromToaster || TOAST_LIFETIME, [\n toast.duration,\n durationFromToaster\n ]);\n const closeTimerStartTimeRef = React.useRef(0);\n const offset = React.useRef(0);\n const lastCloseTimerStartTimeRef = React.useRef(0);\n const pointerStartRef = React.useRef(null);\n const [y, x] = position.split('-');\n const toastsHeightBefore = React.useMemo(()=>{\n return heights.reduce((prev, curr, reducerIndex)=>{\n // Calculate offset up until current toast\n if (reducerIndex >= heightIndex) {\n return prev;\n }\n return prev + curr.height;\n }, 0);\n }, [\n heights,\n heightIndex\n ]);\n const isDocumentHidden = useIsDocumentHidden();\n const invert = toast.invert || ToasterInvert;\n const disabled = toastType === 'loading';\n offset.current = React.useMemo(()=>heightIndex * gap + toastsHeightBefore, [\n heightIndex,\n toastsHeightBefore\n ]);\n React.useEffect(()=>{\n remainingTime.current = duration;\n }, [\n duration\n ]);\n React.useEffect(()=>{\n // Trigger enter animation without using CSS animation\n setMounted(true);\n }, []);\n React.useEffect(()=>{\n const toastNode = toastRef.current;\n if (toastNode) {\n const height = toastNode.getBoundingClientRect().height;\n // Add toast height to heights array after the toast is mounted\n setInitialHeight(height);\n setHeights((h)=>[\n {\n toastId: toast.id,\n height,\n position: toast.position\n },\n ...h\n ]);\n return ()=>setHeights((h)=>h.filter((height)=>height.toastId !== toast.id));\n }\n }, [\n setHeights,\n toast.id\n ]);\n React.useLayoutEffect(()=>{\n // Keep height up to date with the content in case it updates\n if (!mounted) return;\n const toastNode = toastRef.current;\n const originalHeight = toastNode.style.height;\n toastNode.style.height = 'auto';\n const newHeight = toastNode.getBoundingClientRect().height;\n toastNode.style.height = originalHeight;\n setInitialHeight(newHeight);\n setHeights((heights)=>{\n const alreadyExists = heights.find((height)=>height.toastId === toast.id);\n if (!alreadyExists) {\n return [\n {\n toastId: toast.id,\n height: newHeight,\n position: toast.position\n },\n ...heights\n ];\n } else {\n return heights.map((height)=>height.toastId === toast.id ? {\n ...height,\n height: newHeight\n } : height);\n }\n });\n }, [\n mounted,\n toast.title,\n toast.description,\n setHeights,\n toast.id,\n toast.jsx,\n toast.action,\n toast.cancel\n ]);\n const deleteToast = React.useCallback(()=>{\n // Save the offset for the exit swipe animation\n setRemoved(true);\n setOffsetBeforeRemove(offset.current);\n setHeights((h)=>h.filter((height)=>height.toastId !== toast.id));\n setTimeout(()=>{\n removeToast(toast);\n }, TIME_BEFORE_UNMOUNT);\n }, [\n toast,\n removeToast,\n setHeights,\n offset\n ]);\n React.useEffect(()=>{\n if (toast.promise && toastType === 'loading' || toast.duration === Infinity || toast.type === 'loading') return;\n let timeoutId;\n // Pause the timer on each hover\n const pauseTimer = ()=>{\n if (lastCloseTimerStartTimeRef.current < closeTimerStartTimeRef.current) {\n // Get the elapsed time since the timer started\n const elapsedTime = new Date().getTime() - closeTimerStartTimeRef.current;\n remainingTime.current = remainingTime.current - elapsedTime;\n }\n lastCloseTimerStartTimeRef.current = new Date().getTime();\n };\n const startTimer = ()=>{\n // setTimeout(, Infinity) behaves as if the delay is 0.\n // As a result, the toast would be closed immediately, giving the appearance that it was never rendered.\n // See: https://github.com/denysdovhan/wtfjs?tab=readme-ov-file#an-infinite-timeout\n if (remainingTime.current === Infinity) return;\n closeTimerStartTimeRef.current = new Date().getTime();\n // Let the toast know it has started\n timeoutId = setTimeout(()=>{\n toast.onAutoClose == null ? void 0 : toast.onAutoClose.call(toast, toast);\n deleteToast();\n }, remainingTime.current);\n };\n if (expanded || interacting || isDocumentHidden) {\n pauseTimer();\n } else {\n startTimer();\n }\n return ()=>clearTimeout(timeoutId);\n }, [\n expanded,\n interacting,\n toast,\n toastType,\n isDocumentHidden,\n deleteToast\n ]);\n React.useEffect(()=>{\n if (toast.delete) {\n deleteToast();\n toast.onDismiss == null ? void 0 : toast.onDismiss.call(toast, toast);\n }\n }, [\n deleteToast,\n toast.delete\n ]);\n function getLoadingIcon() {\n var _toast_classNames;\n if (icons == null ? void 0 : icons.loading) {\n var _toast_classNames1;\n return /*#__PURE__*/ React.createElement(\"div\", {\n className: cn(classNames == null ? void 0 : classNames.loader, toast == null ? void 0 : (_toast_classNames1 = toast.classNames) == null ? void 0 : _toast_classNames1.loader, 'sonner-loader'),\n \"data-visible\": toastType === 'loading'\n }, icons.loading);\n }\n return /*#__PURE__*/ React.createElement(Loader, {\n className: cn(classNames == null ? void 0 : classNames.loader, toast == null ? void 0 : (_toast_classNames = toast.classNames) == null ? void 0 : _toast_classNames.loader),\n visible: toastType === 'loading'\n });\n }\n const icon = toast.icon || (icons == null ? void 0 : icons[toastType]) || getAsset(toastType);\n var _toast_richColors, _icons_close;\n return /*#__PURE__*/ React.createElement(\"li\", {\n tabIndex: 0,\n ref: toastRef,\n className: cn(className, toastClassname, classNames == null ? void 0 : classNames.toast, toast == null ? void 0 : (_toast_classNames = toast.classNames) == null ? void 0 : _toast_classNames.toast, classNames == null ? void 0 : classNames.default, classNames == null ? void 0 : classNames[toastType], toast == null ? void 0 : (_toast_classNames1 = toast.classNames) == null ? void 0 : _toast_classNames1[toastType]),\n \"data-sonner-toast\": \"\",\n \"data-rich-colors\": (_toast_richColors = toast.richColors) != null ? _toast_richColors : defaultRichColors,\n \"data-styled\": !Boolean(toast.jsx || toast.unstyled || unstyled),\n \"data-mounted\": mounted,\n \"data-promise\": Boolean(toast.promise),\n \"data-swiped\": isSwiped,\n \"data-removed\": removed,\n \"data-visible\": isVisible,\n \"data-y-position\": y,\n \"data-x-position\": x,\n \"data-index\": index,\n \"data-front\": isFront,\n \"data-swiping\": swiping,\n \"data-dismissible\": dismissible,\n \"data-type\": toastType,\n \"data-invert\": invert,\n \"data-swipe-out\": swipeOut,\n \"data-swipe-direction\": swipeOutDirection,\n \"data-expanded\": Boolean(expanded || expandByDefault && mounted),\n \"data-testid\": toast.testId,\n style: {\n '--index': index,\n '--toasts-before': index,\n '--z-index': toasts.length - index,\n '--offset': `${removed ? offsetBeforeRemove : offset.current}px`,\n '--initial-height': expandByDefault ? 'auto' : `${initialHeight}px`,\n ...style,\n ...toast.style\n },\n onDragEnd: ()=>{\n setSwiping(false);\n setSwipeDirection(null);\n pointerStartRef.current = null;\n },\n onPointerDown: (event)=>{\n if (event.button === 2) return; // Return early on right click\n if (disabled || !dismissible) return;\n dragStartTime.current = new Date();\n setOffsetBeforeRemove(offset.current);\n // Ensure we maintain correct pointer capture even when going outside of the toast (e.g. when swiping)\n event.target.setPointerCapture(event.pointerId);\n if (event.target.tagName === 'BUTTON') return;\n setSwiping(true);\n pointerStartRef.current = {\n x: event.clientX,\n y: event.clientY\n };\n },\n onPointerUp: ()=>{\n var _toastRef_current, _toastRef_current1, _dragStartTime_current;\n if (swipeOut || !dismissible) return;\n pointerStartRef.current = null;\n const swipeAmountX = Number(((_toastRef_current = toastRef.current) == null ? void 0 : _toastRef_current.style.getPropertyValue('--swipe-amount-x').replace('px', '')) || 0);\n const swipeAmountY = Number(((_toastRef_current1 = toastRef.current) == null ? void 0 : _toastRef_current1.style.getPropertyValue('--swipe-amount-y').replace('px', '')) || 0);\n const timeTaken = new Date().getTime() - ((_dragStartTime_current = dragStartTime.current) == null ? void 0 : _dragStartTime_current.getTime());\n const swipeAmount = swipeDirection === 'x' ? swipeAmountX : swipeAmountY;\n const velocity = Math.abs(swipeAmount) / timeTaken;\n if (Math.abs(swipeAmount) >= SWIPE_THRESHOLD || velocity > 0.11) {\n setOffsetBeforeRemove(offset.current);\n toast.onDismiss == null ? void 0 : toast.onDismiss.call(toast, toast);\n if (swipeDirection === 'x') {\n setSwipeOutDirection(swipeAmountX > 0 ? 'right' : 'left');\n } else {\n setSwipeOutDirection(swipeAmountY > 0 ? 'down' : 'up');\n }\n deleteToast();\n setSwipeOut(true);\n return;\n } else {\n var _toastRef_current2, _toastRef_current3;\n (_toastRef_current2 = toastRef.current) == null ? void 0 : _toastRef_current2.style.setProperty('--swipe-amount-x', `0px`);\n (_toastRef_current3 = toastRef.current) == null ? void 0 : _toastRef_current3.style.setProperty('--swipe-amount-y', `0px`);\n }\n setIsSwiped(false);\n setSwiping(false);\n setSwipeDirection(null);\n },\n onPointerMove: (event)=>{\n var _window_getSelection, // Apply transform using both x and y values\n _toastRef_current, _toastRef_current1;\n if (!pointerStartRef.current || !dismissible) return;\n const isHighlighted = ((_window_getSelection = window.getSelection()) == null ? void 0 : _window_getSelection.toString().length) > 0;\n if (isHighlighted) return;\n const yDelta = event.clientY - pointerStartRef.current.y;\n const xDelta = event.clientX - pointerStartRef.current.x;\n var _props_swipeDirections;\n const swipeDirections = (_props_swipeDirections = props.swipeDirections) != null ? _props_swipeDirections : getDefaultSwipeDirections(position);\n // Determine swipe direction if not already locked\n if (!swipeDirection && (Math.abs(xDelta) > 1 || Math.abs(yDelta) > 1)) {\n setSwipeDirection(Math.abs(xDelta) > Math.abs(yDelta) ? 'x' : 'y');\n }\n let swipeAmount = {\n x: 0,\n y: 0\n };\n const getDampening = (delta)=>{\n const factor = Math.abs(delta) / 20;\n return 1 / (1.5 + factor);\n };\n // Only apply swipe in the locked direction\n if (swipeDirection === 'y') {\n // Handle vertical swipes\n if (swipeDirections.includes('top') || swipeDirections.includes('bottom')) {\n if (swipeDirections.includes('top') && yDelta < 0 || swipeDirections.includes('bottom') && yDelta > 0) {\n swipeAmount.y = yDelta;\n } else {\n // Smoothly transition to dampened movement\n const dampenedDelta = yDelta * getDampening(yDelta);\n // Ensure we don't jump when transitioning to dampened movement\n swipeAmount.y = Math.abs(dampenedDelta) < Math.abs(yDelta) ? dampenedDelta : yDelta;\n }\n }\n } else if (swipeDirection === 'x') {\n // Handle horizontal swipes\n if (swipeDirections.includes('left') || swipeDirections.includes('right')) {\n if (swipeDirections.includes('left') && xDelta < 0 || swipeDirections.includes('right') && xDelta > 0) {\n swipeAmount.x = xDelta;\n } else {\n // Smoothly transition to dampened movement\n const dampenedDelta = xDelta * getDampening(xDelta);\n // Ensure we don't jump when transitioning to dampened movement\n swipeAmount.x = Math.abs(dampenedDelta) < Math.abs(xDelta) ? dampenedDelta : xDelta;\n }\n }\n }\n if (Math.abs(swipeAmount.x) > 0 || Math.abs(swipeAmount.y) > 0) {\n setIsSwiped(true);\n }\n (_toastRef_current = toastRef.current) == null ? void 0 : _toastRef_current.style.setProperty('--swipe-amount-x', `${swipeAmount.x}px`);\n (_toastRef_current1 = toastRef.current) == null ? void 0 : _toastRef_current1.style.setProperty('--swipe-amount-y', `${swipeAmount.y}px`);\n }\n }, closeButton && !toast.jsx && toastType !== 'loading' ? /*#__PURE__*/ React.createElement(\"button\", {\n \"aria-label\": closeButtonAriaLabel,\n \"data-disabled\": disabled,\n \"data-close-button\": true,\n onClick: disabled || !dismissible ? ()=>{} : ()=>{\n deleteToast();\n toast.onDismiss == null ? void 0 : toast.onDismiss.call(toast, toast);\n },\n className: cn(classNames == null ? void 0 : classNames.closeButton, toast == null ? void 0 : (_toast_classNames2 = toast.classNames) == null ? void 0 : _toast_classNames2.closeButton)\n }, (_icons_close = icons == null ? void 0 : icons.close) != null ? _icons_close : CloseIcon) : null, (toastType || toast.icon || toast.promise) && toast.icon !== null && ((icons == null ? void 0 : icons[toastType]) !== null || toast.icon) ? /*#__PURE__*/ React.createElement(\"div\", {\n \"data-icon\": \"\",\n className: cn(classNames == null ? void 0 : classNames.icon, toast == null ? void 0 : (_toast_classNames3 = toast.classNames) == null ? void 0 : _toast_classNames3.icon)\n }, toast.promise || toast.type === 'loading' && !toast.icon ? toast.icon || getLoadingIcon() : null, toast.type !== 'loading' ? icon : null) : null, /*#__PURE__*/ React.createElement(\"div\", {\n \"data-content\": \"\",\n className: cn(classNames == null ? void 0 : classNames.content, toast == null ? void 0 : (_toast_classNames4 = toast.classNames) == null ? void 0 : _toast_classNames4.content)\n }, /*#__PURE__*/ React.createElement(\"div\", {\n \"data-title\": \"\",\n className: cn(classNames == null ? void 0 : classNames.title, toast == null ? void 0 : (_toast_classNames5 = toast.classNames) == null ? void 0 : _toast_classNames5.title)\n }, toast.jsx ? toast.jsx : typeof toast.title === 'function' ? toast.title() : toast.title), toast.description ? /*#__PURE__*/ React.createElement(\"div\", {\n \"data-description\": \"\",\n className: cn(descriptionClassName, toastDescriptionClassname, classNames == null ? void 0 : classNames.description, toast == null ? void 0 : (_toast_classNames6 = toast.classNames) == null ? void 0 : _toast_classNames6.description)\n }, typeof toast.description === 'function' ? toast.description() : toast.description) : null), /*#__PURE__*/ React.isValidElement(toast.cancel) ? toast.cancel : toast.cancel && isAction(toast.cancel) ? /*#__PURE__*/ React.createElement(\"button\", {\n \"data-button\": true,\n \"data-cancel\": true,\n style: toast.cancelButtonStyle || cancelButtonStyle,\n onClick: (event)=>{\n // We need to check twice because typescript\n if (!isAction(toast.cancel)) return;\n if (!dismissible) return;\n toast.cancel.onClick == null ? void 0 : toast.cancel.onClick.call(toast.cancel, event);\n deleteToast();\n },\n className: cn(classNames == null ? void 0 : classNames.cancelButton, toast == null ? void 0 : (_toast_classNames7 = toast.classNames) == null ? void 0 : _toast_classNames7.cancelButton)\n }, toast.cancel.label) : null, /*#__PURE__*/ React.isValidElement(toast.action) ? toast.action : toast.action && isAction(toast.action) ? /*#__PURE__*/ React.createElement(\"button\", {\n \"data-button\": true,\n \"data-action\": true,\n style: toast.actionButtonStyle || actionButtonStyle,\n onClick: (event)=>{\n // We need to check twice because typescript\n if (!isAction(toast.action)) return;\n toast.action.onClick == null ? void 0 : toast.action.onClick.call(toast.action, event);\n if (event.defaultPrevented) return;\n deleteToast();\n },\n className: cn(classNames == null ? void 0 : classNames.actionButton, toast == null ? void 0 : (_toast_classNames8 = toast.classNames) == null ? void 0 : _toast_classNames8.actionButton)\n }, toast.action.label) : null);\n};\nfunction getDocumentDirection() {\n if (typeof window === 'undefined') return 'ltr';\n if (typeof document === 'undefined') return 'ltr'; // For Fresh purpose\n const dirAttribute = document.documentElement.getAttribute('dir');\n if (dirAttribute === 'auto' || !dirAttribute) {\n return window.getComputedStyle(document.documentElement).direction;\n }\n return dirAttribute;\n}\nfunction assignOffset(defaultOffset, mobileOffset) {\n const styles = {};\n [\n defaultOffset,\n mobileOffset\n ].forEach((offset, index)=>{\n const isMobile = index === 1;\n const prefix = isMobile ? '--mobile-offset' : '--offset';\n const defaultValue = isMobile ? MOBILE_VIEWPORT_OFFSET : VIEWPORT_OFFSET;\n function assignAll(offset) {\n [\n 'top',\n 'right',\n 'bottom',\n 'left'\n ].forEach((key)=>{\n styles[`${prefix}-${key}`] = typeof offset === 'number' ? `${offset}px` : offset;\n });\n }\n if (typeof offset === 'number' || typeof offset === 'string') {\n assignAll(offset);\n } else if (typeof offset === 'object') {\n [\n 'top',\n 'right',\n 'bottom',\n 'left'\n ].forEach((key)=>{\n if (offset[key] === undefined) {\n styles[`${prefix}-${key}`] = defaultValue;\n } else {\n styles[`${prefix}-${key}`] = typeof offset[key] === 'number' ? `${offset[key]}px` : offset[key];\n }\n });\n } else {\n assignAll(defaultValue);\n }\n });\n return styles;\n}\nfunction useSonner() {\n const [activeToasts, setActiveToasts] = React.useState([]);\n React.useEffect(()=>{\n return ToastState.subscribe((toast)=>{\n if (toast.dismiss) {\n setTimeout(()=>{\n ReactDOM.flushSync(()=>{\n setActiveToasts((toasts)=>toasts.filter((t)=>t.id !== toast.id));\n });\n });\n return;\n }\n // Prevent batching, temp solution.\n setTimeout(()=>{\n ReactDOM.flushSync(()=>{\n setActiveToasts((toasts)=>{\n const indexOfExistingToast = toasts.findIndex((t)=>t.id === toast.id);\n // Update the toast if it already exists\n if (indexOfExistingToast !== -1) {\n return [\n ...toasts.slice(0, indexOfExistingToast),\n {\n ...toasts[indexOfExistingToast],\n ...toast\n },\n ...toasts.slice(indexOfExistingToast + 1)\n ];\n }\n return [\n toast,\n ...toasts\n ];\n });\n });\n });\n });\n }, []);\n return {\n toasts: activeToasts\n };\n}\nconst Toaster = /*#__PURE__*/ React.forwardRef(function Toaster(props, ref) {\n const { id, invert, position = 'bottom-right', hotkey = [\n 'altKey',\n 'KeyT'\n ], expand, closeButton, className, offset, mobileOffset, theme = 'light', richColors, duration, style, visibleToasts = VISIBLE_TOASTS_AMOUNT, toastOptions, dir = getDocumentDirection(), gap = GAP, icons, containerAriaLabel = 'Notifications' } = props;\n const [toasts, setToasts] = React.useState([]);\n const filteredToasts = React.useMemo(()=>{\n if (id) {\n return toasts.filter((toast)=>toast.toasterId === id);\n }\n return toasts.filter((toast)=>!toast.toasterId);\n }, [\n toasts,\n id\n ]);\n const possiblePositions = React.useMemo(()=>{\n return Array.from(new Set([\n position\n ].concat(filteredToasts.filter((toast)=>toast.position).map((toast)=>toast.position))));\n }, [\n filteredToasts,\n position\n ]);\n const [heights, setHeights] = React.useState([]);\n const [expanded, setExpanded] = React.useState(false);\n const [interacting, setInteracting] = React.useState(false);\n const [actualTheme, setActualTheme] = React.useState(theme !== 'system' ? theme : typeof window !== 'undefined' ? window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' : 'light');\n const listRef = React.useRef(null);\n const hotkeyLabel = hotkey.join('+').replace(/Key/g, '').replace(/Digit/g, '');\n const lastFocusedElementRef = React.useRef(null);\n const isFocusWithinRef = React.useRef(false);\n const removeToast = React.useCallback((toastToRemove)=>{\n setToasts((toasts)=>{\n var _toasts_find;\n if (!((_toasts_find = toasts.find((toast)=>toast.id === toastToRemove.id)) == null ? void 0 : _toasts_find.delete)) {\n ToastState.dismiss(toastToRemove.id);\n }\n return toasts.filter(({ id })=>id !== toastToRemove.id);\n });\n }, []);\n React.useEffect(()=>{\n return ToastState.subscribe((toast)=>{\n if (toast.dismiss) {\n // Prevent batching of other state updates\n requestAnimationFrame(()=>{\n setToasts((toasts)=>toasts.map((t)=>t.id === toast.id ? {\n ...t,\n delete: true\n } : t));\n });\n return;\n }\n // Prevent batching, temp solution.\n setTimeout(()=>{\n ReactDOM.flushSync(()=>{\n setToasts((toasts)=>{\n const indexOfExistingToast = toasts.findIndex((t)=>t.id === toast.id);\n // Update the toast if it already exists\n if (indexOfExistingToast !== -1) {\n return [\n ...toasts.slice(0, indexOfExistingToast),\n {\n ...toasts[indexOfExistingToast],\n ...toast\n },\n ...toasts.slice(indexOfExistingToast + 1)\n ];\n }\n return [\n toast,\n ...toasts\n ];\n });\n });\n });\n });\n }, [\n toasts\n ]);\n React.useEffect(()=>{\n if (theme !== 'system') {\n setActualTheme(theme);\n return;\n }\n if (theme === 'system') {\n // check if current preference is dark\n if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {\n // it's currently dark\n setActualTheme('dark');\n } else {\n // it's not dark\n setActualTheme('light');\n }\n }\n if (typeof window === 'undefined') return;\n const darkMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');\n try {\n // Chrome & Firefox\n darkMediaQuery.addEventListener('change', ({ matches })=>{\n if (matches) {\n setActualTheme('dark');\n } else {\n setActualTheme('light');\n }\n });\n } catch (error) {\n // Safari < 14\n darkMediaQuery.addListener(({ matches })=>{\n try {\n if (matches) {\n setActualTheme('dark');\n } else {\n setActualTheme('light');\n }\n } catch (e) {\n console.error(e);\n }\n });\n }\n }, [\n theme\n ]);\n React.useEffect(()=>{\n // Ensure expanded is always false when no toasts are present / only one left\n if (toasts.length <= 1) {\n setExpanded(false);\n }\n }, [\n toasts\n ]);\n React.useEffect(()=>{\n const handleKeyDown = (event)=>{\n var _listRef_current;\n const isHotkeyPressed = hotkey.every((key)=>event[key] || event.code === key);\n if (isHotkeyPressed) {\n var _listRef_current1;\n setExpanded(true);\n (_listRef_current1 = listRef.current) == null ? void 0 : _listRef_current1.focus();\n }\n if (event.code === 'Escape' && (document.activeElement === listRef.current || ((_listRef_current = listRef.current) == null ? void 0 : _listRef_current.contains(document.activeElement)))) {\n setExpanded(false);\n }\n };\n document.addEventListener('keydown', handleKeyDown);\n return ()=>document.removeEventListener('keydown', handleKeyDown);\n }, [\n hotkey\n ]);\n React.useEffect(()=>{\n if (listRef.current) {\n return ()=>{\n if (lastFocusedElementRef.current) {\n lastFocusedElementRef.current.focus({\n preventScroll: true\n });\n lastFocusedElementRef.current = null;\n isFocusWithinRef.current = false;\n }\n };\n }\n }, [\n listRef.current\n ]);\n return(// Remove item from normal navigation flow, only available via hotkey\n /*#__PURE__*/ React.createElement(\"section\", {\n ref: ref,\n \"aria-label\": `${containerAriaLabel} ${hotkeyLabel}`,\n tabIndex: -1,\n \"aria-live\": \"polite\",\n \"aria-relevant\": \"additions text\",\n \"aria-atomic\": \"false\",\n suppressHydrationWarning: true\n }, possiblePositions.map((position, index)=>{\n var _heights_;\n const [y, x] = position.split('-');\n if (!filteredToasts.length) return null;\n return /*#__PURE__*/ React.createElement(\"ol\", {\n key: position,\n dir: dir === 'auto' ? getDocumentDirection() : dir,\n tabIndex: -1,\n ref: listRef,\n className: className,\n \"data-sonner-toaster\": true,\n \"data-sonner-theme\": actualTheme,\n \"data-y-position\": y,\n \"data-x-position\": x,\n style: {\n '--front-toast-height': `${((_heights_ = heights[0]) == null ? void 0 : _heights_.height) || 0}px`,\n '--width': `${TOAST_WIDTH}px`,\n '--gap': `${gap}px`,\n ...style,\n ...assignOffset(offset, mobileOffset)\n },\n onBlur: (event)=>{\n if (isFocusWithinRef.current && !event.currentTarget.contains(event.relatedTarget)) {\n isFocusWithinRef.current = false;\n if (lastFocusedElementRef.current) {\n lastFocusedElementRef.current.focus({\n preventScroll: true\n });\n lastFocusedElementRef.current = null;\n }\n }\n },\n onFocus: (event)=>{\n const isNotDismissible = event.target instanceof HTMLElement && event.target.dataset.dismissible === 'false';\n if (isNotDismissible) return;\n if (!isFocusWithinRef.current) {\n isFocusWithinRef.current = true;\n lastFocusedElementRef.current = event.relatedTarget;\n }\n },\n onMouseEnter: ()=>setExpanded(true),\n onMouseMove: ()=>setExpanded(true),\n onMouseLeave: ()=>{\n // Avoid setting expanded to false when interacting with a toast, e.g. swiping\n if (!interacting) {\n setExpanded(false);\n }\n },\n onDragEnd: ()=>setExpanded(false),\n onPointerDown: (event)=>{\n const isNotDismissible = event.target instanceof HTMLElement && event.target.dataset.dismissible === 'false';\n if (isNotDismissible) return;\n setInteracting(true);\n },\n onPointerUp: ()=>setInteracting(false)\n }, filteredToasts.filter((toast)=>!toast.position && index === 0 || toast.position === position).map((toast, index)=>{\n var _toastOptions_duration, _toastOptions_closeButton;\n return /*#__PURE__*/ React.createElement(Toast, {\n key: toast.id,\n icons: icons,\n index: index,\n toast: toast,\n defaultRichColors: richColors,\n duration: (_toastOptions_duration = toastOptions == null ? void 0 : toastOptions.duration) != null ? _toastOptions_duration : duration,\n className: toastOptions == null ? void 0 : toastOptions.className,\n descriptionClassName: toastOptions == null ? void 0 : toastOptions.descriptionClassName,\n invert: invert,\n visibleToasts: visibleToasts,\n closeButton: (_toastOptions_closeButton = toastOptions == null ? void 0 : toastOptions.closeButton) != null ? _toastOptions_closeButton : closeButton,\n interacting: interacting,\n position: position,\n style: toastOptions == null ? void 0 : toastOptions.style,\n unstyled: toastOptions == null ? void 0 : toastOptions.unstyled,\n classNames: toastOptions == null ? void 0 : toastOptions.classNames,\n cancelButtonStyle: toastOptions == null ? void 0 : toastOptions.cancelButtonStyle,\n actionButtonStyle: toastOptions == null ? void 0 : toastOptions.actionButtonStyle,\n closeButtonAriaLabel: toastOptions == null ? void 0 : toastOptions.closeButtonAriaLabel,\n removeToast: removeToast,\n toasts: filteredToasts.filter((t)=>t.position == toast.position),\n heights: heights.filter((h)=>h.position == toast.position),\n setHeights: setHeights,\n expandByDefault: expand,\n gap: gap,\n expanded: expanded,\n swipeDirections: props.swipeDirections\n });\n }));\n })));\n});\n\nexport { Toaster, toast, useSonner };\n","/**\n * Toast — a thin convenience over {@link https://sonner.emilkowal.ski | sonner}.\n *\n * Authors call `toast.success(...)` / `toast.error(...)` anywhere in their funnel.\n * `FunnelProvider` auto-mounts {@link FunnelToaster} (opt out with `toaster={false}`),\n * so toasts work with no setup; render it yourself if you want a custom location.\n *\n * **Dependency policy:** sonner is a direct dependency, imported statically (it's a small\n * lib that ships with every funnel — no lazy chunk, no forwarding proxy). `toaster={false}`\n * still renders no toaster markup; a funnel that never toasts just never calls `toast`.\n */\n\nimport { createElement, type ReactNode } from 'react'\nimport { Toaster, type ToasterProps } from 'sonner'\n\nexport type { ToasterProps }\n\n// sonner's imperative `toast` (`toast('hi')`, `toast.success(...)`, `toast.dismiss()`, …),\n// re-exported DIRECTLY. A re-export keeps the emitted .d.ts nameable — annotating an inferred\n// `const toast = sonnerToast` would drag in sonner's un-exported internal types (TS4023).\nexport { toast } from 'sonner'\n\n/**\n * Sonner's `<Toaster>` with funnel defaults (top-center); pass any `ToasterProps` to override.\n * SSR-safe — sonner renders an empty container server-side and hydrates cleanly on the client.\n */\nexport function FunnelToaster(props: ToasterProps = {}): ReactNode {\n return createElement(Toaster, { position: 'top-center', ...props })\n}\n\n/** Internal: resolve the `FunnelProvider` `toaster` prop to an element (or null). */\nexport function renderToaster(toaster: boolean | ToasterProps): ReactNode {\n if (toaster === false) return null\n return <FunnelToaster {...(toaster === true ? {} : toaster)} />\n}\n","/**\n * Canonical email-shape check, shared by the SDK (checkout email enrichment,\n * `completeUserRegistration`) and mirrored from the server's validation. This is a\n * cheap syntactic guard — \"looks like an address\", not deliverability — so a\n * half-typed value can't be treated as a real identity.\n *\n * The pattern (`/^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/`) is the single source of truth for\n * \"valid enough to identify/charge\": exactly one `@`, a dot-separated domain, and a\n * TLD of at least two chars. Keep it identical to the server-side check.\n */\nexport function isValidEmail(value: unknown): value is string {\n\treturn typeof value === 'string' && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/.test(value.trim())\n}\n","import {\n\tcreateContext,\n\tcreateElement,\n\tFragment,\n\tuseCallback,\n\tuseContext,\n\tuseEffect,\n\tuseMemo,\n\tuseState,\n\tuseSyncExternalStore,\n\ttype ReactNode,\n} from 'react'\nimport type { VariableStore } from './variableStore'\nimport {\n\tcreateFunnelStore,\n\tNAMESPACE_PREFIX,\n\ttype WritableNamespace,\n} from './store'\nimport { buildAcquisition, buildContext, type FunnelContext } from './context'\nimport {\n\tTrackerProvider,\n\tcreateConsoleTracker,\n\ttype Tracker,\n} from '../tracking/tracking'\nimport { attachBus, createBus, withBus, type FunnelBus } from '../tracking/bus'\nimport {\n\tCatalogProvider,\n\tbuildCatalog,\n\ttype ResolvedOffering,\n\ttype OfferingInput,\n} from '../commerce/catalog'\nimport {\n\tCheckoutDriverProvider,\n\tcreateMockDriver,\n\tdriverWithEmail,\n\tdriverWithCatalog,\n\ttype CheckoutDriver,\n} from '../commerce/checkout'\nimport { ModalRuntime } from '../modals/registry'\nimport { LocaleProvider, type MessageCatalog } from '../i18n/translation'\nimport { renderToaster, type ToasterProps } from '../toast/toast'\nimport type { FunnelDefinition, FunnelSnapshot } from '../flow/spine'\nimport type { RuntimeExperiment } from '../flow/experiments'\nimport type { VariableValue } from '../types'\nimport { isValidEmail } from '../util/email'\n\n/**\n * v2 namespace layer over the flat {@link VariableStore}.\n *\n * **The public surface is hooks, not a god object.** Reactive reads use\n * `useState`-shaped tuple hooks (`const [goal, setGoal] = useResponse('goal')`);\n * read-only computed values use `useDevice()`/`useLocale()`/`usePage()`/`useUtm()`.\n * `useFunnel()` returns an **imperative, non-subscribing** handle for use in\n * handlers/effects only — it is not the documented primary API and carries no\n * `sdk` branding.\n *\n * Three writable namespaces (`user`/`responses`/`data`) + the read-only\n * `context`. Entitlements are **not** here — they're the separate app/IdentitySDK.\n *\n * All writes route through {@link Namespace.set}, so persistence fires from one\n * place (the \"magic behind set()\", doc 07 §Layer 1). Writes are pure state now —\n * writing `user.email` no longer identifies. Identity is an explicit, one-shot step\n * (`useFunnel().completeUserRegistration()`), so a half-typed email can't leak a\n * partial `user.registered`.\n */\n\n// ── Writable namespace view ──────────────────────────────\n\n/** A typed view over one writable namespace's slice of the store. */\nexport class Namespace<\n\tT extends Record<string, VariableValue> = Record<string, VariableValue>,\n> {\n\tprivate readonly dot: string\n\n\tconstructor(\n\t\tprivate readonly store: VariableStore,\n\t\treadonly name: WritableNamespace,\n\t\t/** Side-effect run after every write (persistence). */\n\t\tprivate readonly onWrite: (\n\t\t\tns: WritableNamespace,\n\t\t\tvalues: Partial<T>\n\t\t) => void\n\t) {\n\t\tthis.dot = `${NAMESPACE_PREFIX[name]}.`\n\t}\n\n\t/** Fully-qualified store key for a namespace-relative key. */\n\tstoreKey(key: string): string {\n\t\treturn this.dot + key\n\t}\n\n\t/** The store-key prefix this namespace reads/writes (e.g. `user.`). */\n\tget prefix(): string {\n\t\treturn this.dot\n\t}\n\n\t/** Read the whole namespace as a flat object (prefix stripped). */\n\tgetAll(): T {\n\t\tconst out: Record<string, VariableValue> = {}\n\t\tconst all = this.store.getState()\n\t\tfor (const key in all) {\n\t\t\tif (key.startsWith(this.dot))\n\t\t\t\tout[key.slice(this.dot.length)] = all[key]\n\t\t}\n\t\treturn out as T\n\t}\n\n\t/** Read one key, or the whole namespace when called with no argument. */\n\tget<K extends keyof T & string>(key: K): T[K]\n\tget(): T\n\tget(key?: string): VariableValue | T {\n\t\treturn key === undefined\n\t\t\t? this.getAll()\n\t\t\t: this.store.get(this.storeKey(key))\n\t}\n\n\t/** Write one or more keys from a plain object (batched + side-effected). */\n\tset(values: Partial<T>): void {\n\t\tconst updates: Record<string, VariableValue> = {}\n\t\tfor (const key in values) {\n\t\t\tupdates[this.storeKey(key)] = values[key] as VariableValue\n\t\t}\n\t\tthis.store.setMany(updates)\n\t\tthis.onWrite(this.name, values)\n\t}\n}\n\n// ── The imperative handle ────────────────────────────────\n\n/**\n * The imperative funnel handle (`useFunnel()`). Non-reactive — for event\n * handlers and effects. Reactive render reads go through the hooks instead.\n */\nexport interface Funnel {\n\tuser: Namespace\n\tresponses: Namespace\n\tdata: Namespace\n\t/** Read-only computed namespace. `page` reflects the latest navigation. */\n\treadonly context: FunnelContext\n\t/** Live page-level experiment records (platform/DB-sourced); the runtime buckets visitors into them. */\n\treadonly experiments: RuntimeExperiment[]\n\t/** Emit a custom analytics event. */\n\ttrack: Tracker['track']\n\t/**\n\t * Complete user registration — the **explicit** identity step. Optionally writes\n\t * `email` first (`completeUserRegistration('a@b.com')`), then, if the effective\n\t * `user.email` is a valid address, identifies the visitor: fires `user.registered`\n\t * → sets the customer's email + forwards to marketing integrations (Customer.io).\n\t *\n\t * Call this on an **intentional submit** (a Continue/Sign-up click), never on\n\t * keystroke — writing email is now a plain attribute write with no identify. A\n\t * missing/invalid email is a no-op. Returns whether identity actually fired.\n\t *\n\t * IDENTIFIES ONCE PER ADDRESS. Calling it again with the same email writes the attribute but\n\t * does not re-fire `user.registered`, and returns `false` — so a resubmit, a back-nav onto the\n\t * email page, or a double-clicked Continue can't send a welcome email twice. Correcting a\n\t * typo'd address DOES identify again: that is a different inbox, not a repeat.\n\t */\n\tcompleteUserRegistration(email?: string): boolean\n\t/** A point-in-time snapshot for predicates (routing/conditions). */\n\tsnapshot(): FunnelSnapshot\n}\n\n/** Build the imperative handle over a store + context + tracker. */\nexport function createFunnel(\n\tstore: VariableStore,\n\tcontext: FunnelContext,\n\ttracker: Tracker,\n\texperiments: RuntimeExperiment[] = []\n): Funnel {\n\t// One write path → one place for the \"magic behind set()\". Writes are pure state:\n\t// identity is NOT wired here (see completeUserRegistration) so a per-keystroke email\n\t// write can't fire a partial `user.registered`.\n\tconst onWrite = (\n\t\t_ns: WritableNamespace,\n\t\t_values: Record<string, VariableValue>\n\t) => {\n\t\t// Push the writable snapshot for debounced persistence.\n\t\ttracker.setVariables?.(store.getState())\n\t}\n\n\tconst user = new Namespace(store, 'user', onWrite)\n\tconst responses = new Namespace(store, 'responses', onWrite)\n\tconst data = new Namespace(store, 'data', onWrite)\n\n\t// The address we have already identified, so a repeat submit doesn't re-fire `user.registered`.\n\t// Scoped to this funnel instance ON PURPOSE — it is the browser-side half of an emit-once pair,\n\t// and its job is the one thing the server cannot do: stop the BUS emit, which drives the\n\t// browser pixel's CompleteRegistration. The server owns the durable half (a reload builds a new\n\t// funnel and clears this, so `event.ts` gates the integration emit on the customer not already\n\t// being identified). Keyed by email rather than a boolean so a genuine correction — typo'd\n\t// address, then the real one — still identifies, which is a different person's inbox.\n\tlet identifiedEmail: string | null = null\n\n\treturn {\n\t\tuser,\n\t\tresponses,\n\t\tdata,\n\t\tcontext,\n\t\texperiments,\n\t\ttrack: (\n\t\t\tevent: string,\n\t\t\teventData?: never,\n\t\t\tuserData?: Record<string, unknown>\n\t\t) => tracker.track(event, eventData, userData),\n\t\tcompleteUserRegistration: (email?: string): boolean => {\n\t\t\tif (email !== undefined) user.set({ email })\n\t\t\tconst e = email ?? user.get('email')\n\t\t\tif (!isValidEmail(e)) return false\n\t\t\t// Already identified THIS address — the write above still stands, but identity has\n\t\t\t// fired and must not fire twice (see `identifiedEmail`). Reports false: nothing new\n\t\t\t// happened, which is what the return value means.\n\t\t\tif (identifiedEmail === e) return false\n\t\t\tidentifiedEmail = e as string\n\t\t\ttracker.identify(e)\n\t\t\treturn true\n\t\t},\n\t\tsnapshot: () => ({\n\t\t\tuser: user.getAll(),\n\t\t\tresponses: responses.getAll(),\n\t\t\tdata: data.getAll(),\n\t\t\tcontext,\n\t\t}),\n\t}\n}\n\n// ── React wiring ─────────────────────────────────────────\n\ninterface FunnelContextValue {\n\tfunnel: Funnel\n\tstore: VariableStore\n\tcontext: FunnelContext\n\tcatalog: Map<string, ResolvedOffering>\n\tdriver: CheckoutDriver\n\t/** Tracker composed with the client bus sink (every track() also hits window.appfunnel). */\n\ttracker: Tracker\n\t/** The window.appfunnel event bus (client-side integration surface). */\n\tbus: FunnelBus\n}\n\nconst FunnelCtx = createContext<FunnelContextValue | null>(null)\n\nexport interface FunnelProviderProps {\n\t/** Mount from a funnel definition (the normal case). */\n\tconfig?: FunnelDefinition\n\t/** Server / session-restored values overriding declared defaults. */\n\tsessionValues?: Record<string, VariableValue>\n\t/**\n\t * FLASH-FREE HYDRATION (SSR-isolation Option B): when true, the store is seeded with\n\t * DEFAULTS only for the initial (hydration) render — matching the build-time-prerendered\n\t * DEFAULT-state markup — and `sessionValues` are applied as a POST-hydration state update in\n\t * a mount effect (`store.setMany`), so a returning visitor's saved answers pop into\n\t * already-visible controls without an empty-shell flash or a hydration mismatch. Off (the\n\t * default) preserves the original behavior: `sessionValues` seed the store at construction\n\t * (used by SSR itself and by non-prerendered mounts). The client entry sets this to true. */\n\tdeferSessionValues?: boolean\n\t/** The platform tracker; defaults to a silent console tracker (tests/dev). */\n\ttracker?: Tracker\n\t/** Computed-context seed (funnel id, test/live mode, server-hydrated utm/session). */\n\tcontext?: Parameters<typeof buildContext>[0]\n\t/** Offerings with their provider-resolved price (`{ amount, currency }`). */\n\tofferings?: OfferingInput[]\n\t/** Live page-level experiment records, platform/DB-sourced (not authored in funnel code). */\n\texperiments?: RuntimeExperiment[]\n\t/** The platform checkout driver; defaults to a mock that resolves successfully. */\n\tcheckout?: CheckoutDriver\n\t/** Message catalogs per locale (`messages/<locale>.json`) for translation. */\n\tmessages?: MessageCatalog\n\t/** Explicit locale override (URL/param/geo); wins over the detected device locale. */\n\tlocale?: string\n\t/** Auto-mount the toast `<Toaster>` (default true). Pass props to customize, or `false` to opt out. */\n\ttoaster?: boolean | ToasterProps\n\t/** Advanced / testing: supply a pre-built store instead of a `config`. */\n\tstore?: VariableStore\n\tchildren: ReactNode\n}\n\n/**\n * Mounts a funnel: builds the writable {@link VariableStore} + the read-only\n * {@link FunnelContext} (once) and provides the runtime to the tree via hooks.\n */\nexport function FunnelProvider({\n\tconfig,\n\tsessionValues,\n\tdeferSessionValues = false,\n\ttracker,\n\tcontext: contextOpts,\n\tofferings,\n\texperiments,\n\tcheckout,\n\tmessages,\n\tlocale: localeOverride,\n\ttoaster = true,\n\tstore,\n\tchildren,\n}: FunnelProviderProps): ReactNode {\n\tconst resolvedTracker = tracker ?? FALLBACK_TRACKER\n\tconst [value] = useState<FunnelContextValue>(() => {\n\t\tconst s =\n\t\t\tstore ??\n\t\t\tcreateFunnelStore(\n\t\t\t\t{ responses: config?.responses, data: config?.data },\n\t\t\t\t// FLASH-FREE HYDRATION: with deferSessionValues the initial render is seeded with\n\t\t\t\t// DEFAULTS ONLY, so the client's first render is byte-identical to the build-time\n\t\t\t\t// DEFAULT-state prerender it hydrates against (clean match). The visitor's saved\n\t\t\t\t// answers arrive as a post-hydration setMany below. Without the flag, sessionValues\n\t\t\t\t// seed the store at construction (SSR + non-prerendered paths).\n\t\t\t\tdeferSessionValues ? undefined : sessionValues\n\t\t\t)\n\t\tconst ctx = buildContext({\n\t\t\tfunnelId: config?.id,\n\t\t\t...contextOpts,\n\t\t})\n\t\t// The client event bus (window.appfunnel), composed into the tracker so every\n\t\t// taxonomy event mirrors to it for on-page pixels. Read getters wire to store + context.\n\t\tconst bus = createBus({\n\t\t\tgetVariable: (key) => s.get(key),\n\t\t\tgetVariables: () => s.getState(),\n\t\t\tgetCurrentPageId: () => ctx.page.key || null,\n\t\t\tgetCustomerId: () => ctx.identity.customerId,\n\t\t\tgetVisitorId: () => ctx.identity.visitorId,\n\t\t})\n\t\tconst busTracker = withBus(resolvedTracker, bus)\n\t\t// Every checkout attempt carries the buyer email the funnel collected — read\n\t\t// from the store at ATTEMPT time (`user.email`), loose-validated so a half-typed\n\t\t// value can't fail the wire's email validation (the server treats absent email\n\t\t// as an anonymous customer; a webhook/identify backfills it later).\n\t\tconst emailForCheckout = (): string | undefined => {\n\t\t\tconst value = s.get('user.email')\n\t\t\treturn isValidEmail(value) ? value : undefined\n\t\t}\n\t\tconst catalog = buildCatalog(offerings ?? [])\n\t\treturn {\n\t\t\tfunnel: createFunnel(s, ctx, busTracker, experiments ?? []),\n\t\t\tstore: s,\n\t\t\tcontext: ctx,\n\t\t\tcatalog,\n\t\t\t// Slot → catalog-key resolution wraps the email-enriching driver, so the wire charges the real\n\t\t\t// catalog key while pages + analytics keep the durable SLOT identity (req.product).\n\t\t\tdriver: driverWithCatalog(\n\t\t\t\tdriverWithEmail(\n\t\t\t\t\tcheckout ?? createMockDriver(),\n\t\t\t\t\temailForCheckout\n\t\t\t\t),\n\t\t\t\tcatalog\n\t\t\t),\n\t\t\ttracker: busTracker,\n\t\t\tbus,\n\t\t}\n\t})\n\t// Expose the bus on window.appfunnel for the funnel's lifetime (client-side only).\n\tuseEffect(() => attachBus(value.bus), [value.bus])\n\t// FLASH-FREE HYDRATION: apply the visitor's saved answers as a POST-hydration state update.\n\t// The initial render used DEFAULTS (matching the prerendered default-state markup → clean\n\t// hydration), so `sessionValues` land here as an ordinary store write: the values pop into\n\t// already-visible controls (no empty flash, no mismatch). Runs once, after the first commit\n\t// (i.e. after hydrateRoot has reconciled) — a single setMany, batched by the store. No-op\n\t// when there are no deferred values or the flag is off.\n\tuseEffect(() => {\n\t\tif (!deferSessionValues || !sessionValues) return\n\t\tconst updates: Record<string, VariableValue> = {}\n\t\tfor (const [key, v] of Object.entries(sessionValues))\n\t\t\tif (v !== undefined) updates[key] = v\n\t\tif (Object.keys(updates).length > 0) value.store.setMany(updates)\n\t\t// Apply-once on mount; sessionValues is a per-request server snapshot (stable identity).\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [])\n\t// Forward the acquisition snapshot once on entry → the platform persists it\n\t// first-class (session + first-touch Customer) + feeds CAPI.\n\tuseEffect(() => {\n\t\tvalue.tracker.setAcquisition?.(buildAcquisition(value.context))\n\t}, [value])\n\tconst tree = createElement(TrackerProvider, {\n\t\ttracker: value.tracker,\n\t\tchildren: createElement(CheckoutDriverProvider, {\n\t\t\tdriver: value.driver,\n\t\t\tchildren: createElement(CatalogProvider, {\n\t\t\t\tcatalog: value.catalog,\n\t\t\t\t// Per-slot sample pricing (display-only fallback for unassigned slots).\n\t\t\t\tsamples: config?.sampleOfferings,\n\t\t\t\tchildren: createElement(FunnelCtx.Provider, {\n\t\t\t\t\tvalue,\n\t\t\t\t\tchildren: createElement(LocaleProvider, {\n\t\t\t\t\t\tconfig: config?.locales,\n\t\t\t\t\t\tcatalog: messages,\n\t\t\t\t\t\tdetected: value.context.locale.locale,\n\t\t\t\t\t\toverride: localeOverride,\n\t\t\t\t\t\tchildren: createElement(ModalRuntime, { children }),\n\t\t\t\t\t}),\n\t\t\t\t}),\n\t\t\t}),\n\t\t}),\n\t})\n\treturn createElement(Fragment, null, tree, renderToaster(toaster))\n}\n\nconst FALLBACK_TRACKER = createConsoleTracker({ silent: true })\n\nfunction useFunnelCtx(): FunnelContextValue {\n\tconst ctx = useContext(FunnelCtx)\n\tif (!ctx) {\n\t\tthrow new Error(\n\t\t\t'useFunnel/useResponse/… must be used inside <FunnelProvider>'\n\t\t)\n\t}\n\treturn ctx\n}\n\n/**\n * The imperative handle. Does **not** subscribe — use it in event handlers and\n * effects (`useFunnel().responses.set({...})`). For reactive reads use the hooks.\n */\nexport function useFunnel(): Funnel {\n\treturn useFunnelCtx().funnel\n}\n\n/** Internal: the raw {@link VariableStore} (for reactive condition/field hooks). */\nexport function useFunnelStore(): VariableStore {\n\treturn useFunnelCtx().store\n}\n\n/**\n * @internal SDK-only: the event bus for the mounted funnel. Non-throwing (returns null\n * outside a provider) so a standalone `<FunnelView>` in a test doesn't crash. Deliberately\n * absent from the `state` barrel — the public surface is `window.appfunnel` (read + flow\n * control via {@link AppfunnelBusApi}), never the internal `FunnelBus` (which holds `emit`).\n */\nexport function useBusInternal(): FunnelBus | null {\n\treturn useContext(FunnelCtx)?.bus ?? null\n}\n\n// ── Reactive field hooks ─────────────────────────────────\n\n/** Subscribe to a single flat store key; returns its reactive value. */\nfunction useStoreKey(store: VariableStore, key: string): VariableValue {\n\tconst subscribe = useCallback(\n\t\t(cb: () => void) => store.subscribe(cb, { keys: [key] }),\n\t\t[store, key]\n\t)\n\tconst getSnapshot = useCallback(() => store.get(key), [store, key])\n\t// Snapshot is the primitive value → stable by value, no caching needed.\n\treturn useSyncExternalStore(subscribe, getSnapshot, getSnapshot)\n}\n\n/** Build a `useState`-shaped tuple hook bound to one writable namespace. */\nfunction makeFieldHook(ns: WritableNamespace) {\n\treturn function useNamespaceField(\n\t\tkey: string\n\t): [VariableValue, (value: VariableValue) => void] {\n\t\tconst { funnel, store } = useFunnelCtx()\n\t\tconst value = useStoreKey(store, `${NAMESPACE_PREFIX[ns]}.${key}`)\n\t\tconst set = useCallback(\n\t\t\t(v: VariableValue) => funnel[ns].set({ [key]: v }),\n\t\t\t[funnel, key]\n\t\t)\n\t\treturn [value, set]\n\t}\n}\n\n/**\n * `const [goal, setGoal] = useResponse('goal')` — one funnel answer,\n * `useState`-shaped and per-key reactive. Writing persists + (later) feeds\n * analytics aggregation.\n */\nexport const useResponse = makeFieldHook('responses')\n\n/**\n * `const [height, setHeight] = useUserAttribute('height')` — any field on the\n * user. The platform routes known fields → typed column, custom → attribute;\n * the author doesn't specify which. `email` is a plain attribute like any other —\n * writing it does NOT identify; complete identity explicitly on submit with\n * `useFunnel().completeUserRegistration()`.\n */\nexport const useUserAttribute = makeFieldHook('user')\n\n/**\n * `const [score, setScore] = useData('score')` — working/scratch state. Persisted\n * (survives reload/return) but kept out of `responses` aggregation.\n */\nexport const useData = makeFieldHook('data')\n\n/**\n * `const [consent, setConsent] = useMarketingConsent()` — the visitor's marketing\n * opt-in as a plain boolean. Writing `true` records the answer AND fires the\n * platform `marketing.consent_given` event, which sets the customer's consent\n * flag and forwards `marketing_consent: true` to marketing integrations\n * (Customer.io). Writing `false` records the answer only — consent is one-way;\n * there is no un-consent event today. Prefer this over `useResponse('marketingConsent')`,\n * which records the variable but never drives the consent pipeline.\n */\nexport function useMarketingConsent(): [boolean, (granted: boolean) => void] {\n\tconst { funnel, store } = useFunnelCtx()\n\tconst value = useStoreKey(store, `${NAMESPACE_PREFIX.responses}.marketingConsent`)\n\tconst set = useCallback(\n\t\t(granted: boolean) => {\n\t\t\tfunnel.responses.set({ marketingConsent: granted })\n\t\t\tif (granted) funnel.track('marketing.consent_given')\n\t\t},\n\t\t[funnel]\n\t)\n\treturn [Boolean(value), set]\n}\n\n/**\n * The headless field hook — `useField('responses.goal')` — the building block\n * the styleable components (`<Choice>`) wrap. Takes a namespaced path and\n * returns `{ value, set }`. Accepts only writable namespaces.\n */\nexport function useField(path: string): {\n\tvalue: VariableValue\n\tset: (value: VariableValue) => void\n} {\n\tconst dot = path.indexOf('.')\n\tconst ns = path.slice(0, dot) as WritableNamespace\n\tconst key = path.slice(dot + 1)\n\tconst { funnel, store } = useFunnelCtx()\n\tif (!(ns in NAMESPACE_PREFIX)) {\n\t\tthrow new Error(\n\t\t\t`useField: \"${path}\" is not a writable namespace (user/responses/data)`\n\t\t)\n\t}\n\tconst value = useStoreKey(store, `${NAMESPACE_PREFIX[ns]}.${key}`)\n\tconst set = useCallback(\n\t\t(v: VariableValue) => funnel[ns].set({ [key]: v }),\n\t\t[funnel, ns, key]\n\t)\n\treturn { value, set }\n}\n\n// ── Read-only context hooks ──────────────────────────────\n\n/** The whole read-only computed namespace (non-reactive except `page`). */\nfunction useContextObject(): FunnelContext {\n\treturn useFunnelCtx().context\n}\n\n/** `useDevice()` — viewport, device type, pixel ratio (read-only). */\nexport function useDevice(): FunnelContext['device'] {\n\treturn useContextObject().device\n}\n\n/** `useLocale()` — resolved locale/language/region/timezone (read-only). */\nexport function useLocale(): FunnelContext['locale'] {\n\treturn useContextObject().locale\n}\n\n/** `useUtm()` — the 5 utm params captured on entry (read-only). */\nexport function useUtm(): FunnelContext['utm'] {\n\treturn useContextObject().utm\n}\n\n/** `useClickIds()` — per-network ad click-ids captured on entry (read-only). */\nexport function useClickIds(): FunnelContext['clickIds'] {\n\treturn useContextObject().clickIds\n}\n\n/** `useSystem()` — funnel id, test/live mode, build clock (read-only). */\nexport function useSystem(): FunnelContext['system'] {\n\treturn useContextObject().system\n}\n\n/** Read a dotted path out of context, e.g. `useContextValue('device.isMobile')`. */\nexport function useContextValue(path: string): unknown {\n\tconst ctx = useContextObject()\n\treturn useMemo(\n\t\t() =>\n\t\t\tpath\n\t\t\t\t.split('.')\n\t\t\t\t.reduce<unknown>(\n\t\t\t\t\t(acc, k) => (acc as Record<string, unknown>)?.[k],\n\t\t\t\t\tctx\n\t\t\t\t),\n\t\t[ctx, path]\n\t)\n}\n","import * as React from 'react'\nimport {\n createContext,\n createElement,\n Fragment,\n lazy,\n Suspense,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useTransition,\n type ComponentType,\n type ReactNode,\n} from 'react'\nimport { useFunnel, useBusInternal } from '../state/namespaces'\nimport { dismissAllModals } from '../modals/registry'\nimport { exposurePayload, newEventId, useTrackerRef, type Tracker } from '../tracking/tracking'\nimport type { NavigationControl } from '../tracking/bus'\nimport { AF_PROTOCOL, type Capabilities } from '../protocol'\nimport { captureScreenshot } from './screenshot'\nimport { entryGuard, evaluateGate, expectedPathLength, groupProgress, nextPage, outgoingKeys, tracePath, type FlowPage, type GroupProgress, type PageMeta } from './spine'\nimport { bucketingSeed, resolveExperiments } from './experiments'\nimport type { PageContext } from '../state/context'\n\n/** What a page's `load` resolves to — a component, or a module default-exporting one. */\nexport type PageModule = ComponentType | { default: ComponentType }\n\n/**\n * React `<Activity>` — stable since React 19.2. Falls back to the `unstable_Activity`\n * alias on the pre-19.2 versions that only exposed it under that name; `undefined` on\n * older React, where hidden pre-mounting (see {@link FunnelView}'s automatic image\n * preloading) is simply skipped and everything else works unchanged. Feature-detected\n * off the namespace so a missing named export can never break the bundle.\n */\nconst Activity = ((React as Record<string, unknown>).Activity ??\n (React as Record<string, unknown>).unstable_Activity) as\n | ComponentType<{ mode: 'visible' | 'hidden'; children?: ReactNode }>\n | undefined\n\n/**\n * How many next-candidate pages to pre-mount hidden at once — bounds the speculative\n * render/fetch cost when a page branches to many targets (only the first N in\n * route/linear order are warmed).\n */\nconst HIDDEN_CANDIDATE_CAP = 2\n\n/**\n * A page wired into the runtime. Provide **either** an eager `Component` (small\n * funnels, tests) **or** a lazy `load` (code-split: the renderer hands a dynamic\n * `import()` so a big funnel ships one chunk per page, not the whole funnel).\n */\nexport interface RuntimePage {\n key: string\n meta?: PageMeta\n /** Eager component. Provide this or `load`. */\n Component?: ComponentType\n /** Lazy loader for a code-split chunk. Provide this or `Component`. */\n load?: () => Promise<PageModule>\n}\n\nexport interface NavigationState {\n /** The current page's read-only context (key, index, total, progress). */\n page: PageContext\n /** Advance via the current page's `next` predicate, else the linear next. */\n next: () => void\n /** Go to the previous page in history. */\n back: () => void\n /** Jump to a specific page key. */\n go: (key: string) => void\n /** Warm a page's code-split chunk ahead of navigation (e.g. on link hover). No-op for eager pages. */\n prefetch: (key: string) => void\n /**\n * The page keys the visitor could go to next, already resolved to the chunk that\n * would render (experiment variant applied). The **renderer** maps these to chunk\n * URLs and emits `<link rel=\"modulepreload\">` (the browser-native, non-executing,\n * SSR-able prefetch — see v0 `HeadlessFunnelRenderer`). The SDK's `load()`-based\n * `prefetch` is the fallback for mounts without a modulepreload manager.\n */\n nextCandidates: string[]\n canGoBack: boolean\n /**\n * True while a navigation's target page chunk is still resolving (a cold,\n * un-prefetched lazy chunk). The current page stays on screen during this window\n * (no Suspense-fallback flicker); read this to show a subtle \"working\" affordance\n * so a tapped button doesn't feel dead. Usually false/instant when the next chunk\n * was prefetched.\n */\n isNavigating: boolean\n}\n\nconst NavContext = createContext<NavigationState | null>(null)\n\n/** The visitor-routed grouped-progress structure for the current position (see {@link useGroupProgress}). */\nconst GroupProgressContext = createContext<GroupProgress | null>(null)\n\n/** experiment id → the variant this visitor is bucketed into, for the live render. */\nconst ExperimentContext = createContext<Record<string, string>>({})\n\n/**\n * `const variant = useExperiment('welcome-headline')` — the variant key this\n * visitor is assigned in an experiment (`undefined` if not in one). Page-variant\n * swapping is automatic; this is for branching *within* a page or custom logging.\n */\nexport function useExperiment(id: string): string | undefined {\n return useContext(ExperimentContext)[id]\n}\n\n/**\n * Compute the read-only page context for a position in the flow. `total` is the\n * **expected** path length for the visitor's current answers (see\n * {@link expectedPathLength}) — not the raw file count — so progress reaches 100%\n * on whichever branch the funnel actually takes. Clamped so a visitor who jumped\n * past the traced path can't read above 100%.\n */\nfunction pageContextFor(\n currentKey: string,\n slug: string,\n group: string | undefined,\n index: number,\n total: number,\n startedAt: number,\n): PageContext {\n const denom = Math.max(total, index + 1)\n return {\n key: currentKey,\n slug,\n group,\n index,\n total: denom,\n progressPercentage: denom > 0 ? Math.min(100, Math.round(((index + 1) / denom) * 100)) : 0,\n startedAt,\n }\n}\n\n/** Page-timing clock (effects only, never render). */\nconst now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now())\n\n/**\n * `page.exit` timing — wall-clock duration on a page, minus time the tab was\n * hidden (active engagement). Emits for the page being LEFT on each page change;\n * the final page's exit fires on unmount.\n */\nfunction usePageExitTimer(tracker: Tracker, currentKey: string | undefined): void {\n const timer = useRef<{ key: string; enteredAt: number; hidden: number; hiddenSince: number | null } | null>(null)\n const emitExit = useCallback(() => {\n const t = timer.current\n if (!t) return\n const at = now()\n const hidden = t.hidden + (t.hiddenSince != null ? at - t.hiddenSince : 0)\n const durationMs = Math.round(at - t.enteredAt)\n tracker.track('page.exit', { pageId: t.key, durationMs, activeMs: Math.max(0, Math.round(durationMs - hidden)) })\n }, [tracker])\n\n // Track tab visibility so `activeMs` excludes backgrounded time.\n useEffect(() => {\n if (typeof document === 'undefined') return\n const onVis = () => {\n const t = timer.current\n if (!t) return\n if (document.visibilityState === 'hidden') t.hiddenSince = now()\n else if (t.hiddenSince != null) {\n t.hidden += now() - t.hiddenSince\n t.hiddenSince = null\n }\n }\n document.addEventListener('visibilitychange', onVis)\n return () => document.removeEventListener('visibilitychange', onVis)\n }, [])\n\n // On each page change emit page.exit for the page being left, then start the\n // new page's timer.\n useEffect(() => {\n if (!currentKey) return\n if (timer.current && timer.current.key !== currentKey) emitExit()\n const hidden = typeof document !== 'undefined' && document.visibilityState === 'hidden'\n timer.current = { key: currentKey, enteredAt: now(), hidden: 0, hiddenSince: hidden ? now() : null }\n }, [currentKey, emitExit])\n\n useEffect(() => () => emitExit(), [emitExit])\n}\n\n/**\n * Renders the funnel: shows the current page and drives navigation. `next()`\n * resolves the current page's `next` predicate against the live snapshot\n * (writable namespaces + read-only `context`), falling back to the linear next\n * page in file order (see {@link nextPage}).\n *\n * Auto-emits `funnel.start` on mount and `page.view` on each page change, and\n * keeps `context.page` in sync so predicates and `usePage()` see the live page.\n *\n * Pass a `layout` (a `{ children }` component) for **persistent chrome** — a\n * header, progress bar, background — rendered *inside* the nav context but\n * *outside* the page swap, so it mounts once and never remounts on navigation\n * (and can read `usePage`/`useNavigation`).\n *\n * Must live inside `<FunnelProvider>`.\n */\nexport function FunnelView({\n pages,\n initialKey,\n trustInitialKey = false,\n layout,\n fallback,\n prefetch: prefetchMode = 'auto',\n onNavigate,\n}: {\n pages: RuntimePage[]\n initialKey?: string\n /**\n * FLASH-FREE HYDRATION (SSR-isolation Option B, FIX 1): honor `initialKey` VERBATIM as the entry\n * page, WITHOUT re-evaluating its entry `guard` on the client. The SERVER already resolved the\n * true entry — either by evaluating a declarative guard to pick the prerendered target-vs-bounce,\n * or by running the real guard inside the fallback SSR render — and threaded the resolved key\n * here. With `deferSessionValues` on, the client's initial snapshot is EMPTY (saved answers arrive\n * post-hydration), so re-running the guard here would wrongly bounce a qualified visitor and\n * mismatch the server markup. Set by the client entry (via createFunnelTree) alongside\n * `deferSessionValues`; the guard still protects in-funnel navigation and non-deferred mounts.\n */\n trustInitialKey?: boolean\n layout?: ComponentType<{ children: ReactNode }>\n /** Shown in the page area while a lazy page's chunk loads (the layout persists around it). */\n fallback?: ReactNode\n /**\n * `'auto'` (default): the SDK warms next-likely chunks by calling `load()`.\n * `'off'`: the **renderer** owns prefetch (via `<link rel=\"modulepreload\">` over\n * `useNavigation().nextCandidates`) — avoids the redundant `load()` execution.\n */\n prefetch?: 'auto' | 'off'\n /**\n * Fires on every page change (incl. the initial page) with the current page key,\n * slug, and whether it is the flow's START page. `createFunnelTree` wires this to\n * the URL-path sync (`history.replaceState`, v0-style — funnel back is in-memory,\n * not browser history) whenever the renderer injected a `basePath`. Fires for the\n * *resolved* page, so if an entry `guard` bounced a deep-link to the start, the\n * URL gets corrected.\n */\n onNavigate?: (key: string, slug: string, isStart: boolean) => void\n}): ReactNode {\n const funnel = useFunnel()\n const tracker = useTrackerRef()\n\n // Resolve each page to a renderable component: eager `Component` as-is, or a\n // stable `React.lazy` over `load` (memoized so the lazy element identity is\n // stable across renders → no remount). `loaders` keeps the raw `load` fns for\n // prefetch (dynamic import dedupes, so calling them early just warms the chunk).\n const components = useMemo(() => {\n const map = new Map<string, ComponentType>()\n for (const p of pages) {\n if (p.Component) map.set(p.key, p.Component)\n else if (p.load) {\n const load = p.load\n map.set(p.key, lazy(() => Promise.resolve(load()).then((m) =>\n typeof m === 'function' ? { default: m } : m,\n )))\n }\n }\n return map\n }, [pages])\n const loaders = useMemo(\n () => new Map(pages.filter((p) => p.load).map((p) => [p.key, p.load!])),\n [pages],\n )\n\n // Resolve page-level experiments once for this visitor: which variant of each\n // slot to show, and which variant pages drop out of the linear flow. The seed is\n // PINNED to the first non-null value for this mount (a ref, not the live context) so a\n // mid-session identify() that later populates context.identity can never flip an\n // in-progress visitor's variant — the comment's promise is now enforced, not incidental.\n const seedRef = useRef<string | null>(null)\n if (seedRef.current === null) seedRef.current = bucketingSeed(funnel.context)\n const seed = seedRef.current\n const experiments = useMemo(\n () => resolveExperiments(pages, funnel.experiments, seed),\n [pages, funnel.experiments, seed],\n )\n // The two key remaps every navigation touch point needs: a routing TARGET\n // collapses to its slot (variant keys never stand alone in the flow); a slot\n // resolves to the chunk its assigned variant renders.\n const toSlot = useCallback((k: string) => experiments.slotOf[k] ?? k, [experiments])\n const toRenderKey = useCallback((k: string) => experiments.render[k] ?? k, [experiments])\n const pageByKey = useMemo(() => new Map(pages.map((p) => [p.key, p])), [pages])\n // The effective flow: anchors + standalone pages, in order (losers removed).\n const flowPages = useMemo<RuntimePage[]>(\n () => experiments.activeKeys.map((k) => pageByKey.get(k)).filter((p): p is RuntimePage => p !== undefined),\n [experiments, pageByKey],\n )\n\n // The flow as plain {key, meta} for routing + path-length tracing.\n //\n // OPTIONAL per-variant routing (default off): when a NON-CONTROL variant is the\n // one served for a slot AND that variant page declares its OWN `next` routes,\n // those routes govern routing FOR THIS VISITOR — otherwise the slot's routing is\n // inherited unchanged (today's behavior, a pure superset). The slot stays the\n // flow ANCHOR: assignment, exposure, the page `type`/`guard`, and the path-length\n // start-anchor all still read the slot's own meta; only the NEXT-page lookup\n // consults the served variant's routes. Because every downstream reader\n // (`nextPage`, `outgoingKeys`/prefetch, `expectedPathLength`) resolves `meta.next`\n // off THIS array, folding the served variant's `next` in here makes routing,\n // prefetch, and progress all reflect the branch the served variant actually takes,\n // while the control's path is untouched.\n const flow = useMemo<FlowPage[]>(\n () =>\n flowPages.map((p) => {\n const servedVariant = experiments.render[p.key]\n const variantNext = servedVariant ? pageByKey.get(servedVariant)?.meta?.next : undefined\n return variantNext\n ? { key: p.key, meta: { ...(p.meta ?? {}), next: variantNext } }\n : { key: p.key, meta: p.meta }\n }),\n [flowPages, experiments, pageByKey],\n )\n\n // Resolve the starting page. A deep-link / reload `initialKey` is honored only if\n // the page's entry `guard` passes against the (restored) snapshot — else fall\n // back to the start page. (In-funnel navigation never hits this; routing gated it.)\n //\n // `initialKey` may be a page KEY *or* a page SLUG: the URL is slug space (`/<campaign>/<slug>`),\n // and the renderer threads the URL segment through as-is for builds whose artifact index predates\n // the slug map. Key first (a slot key from a variant target), then slug — so a funnel whose slugs\n // differ from its keys still deep-links / reloads onto the right page instead of silently\n // restarting at page one.\n const [history, setHistory] = useState<string[]>(() => {\n const start = flowPages[0]?.key\n if (!initialKey || initialKey === start) return start ? [start] : []\n const target = toSlot(initialKey)\n const page =\n flowPages.find((p) => p.key === target) ??\n flowPages.find((p) => (p.meta?.slug ?? p.key) === initialKey)\n const key = page?.key\n // FLASH-FREE HYDRATION (Option B, FIX 1): when the SERVER already resolved the entry\n // (`trustInitialKey`, set alongside deferSessionValues), honor `initialKey` verbatim — the\n // client's deferred snapshot is empty here, so re-running the guard would wrongly bounce a\n // qualified visitor and mismatch the server markup. The server-resolved key IS the decision.\n if (trustInitialKey) return key ? [key] : start ? [start] : []\n // Effective guard = the page-type default (paywall/upsell need email) AND any\n // explicit meta.guard.\n const guard = entryGuard(page?.meta)\n const ok = key && (!guard || evaluateGate(guard, funnel.snapshot()))\n const first = ok ? key : start\n return first ? [first] : []\n })\n const currentKey = history[history.length - 1]\n const index = history.length - 1\n const startKey = history[0]\n\n // RESUME PATH RECONSTRUCTION — give a reloaded/deep-linked visitor their history back.\n //\n // The seed above deliberately puts exactly ONE entry in `history`, and that has to stay:\n // it is what makes the first client render match the prerendered markup (see FIX 1). But\n // one entry also means a reload onto page 20 of 25 reads as page ONE of the six that are\n // left — `index` 0, `startKey` = the resumed page (so `total` covers only the remainder),\n // `canGoBack` false. The progress bar snaps back to the first notch and Back vanishes.\n // This is not preview-only: the LIVE campaign route injects `basePath`, so the URL sync\n // has always made a refresh land here.\n //\n // THE REPAIR: once the visitor's saved answers are in the store, trace the flow from the\n // funnel's start page to the page they resumed on ({@link tracePath}) and seed `history`\n // with that whole path. `index`, `total`, `startKey` and `canGoBack` are ALL derived from\n // `history` further down, so every one of them corrects itself the moment it is right —\n // none of them is patched individually.\n //\n // WHY IT MUST BE POST-HYDRATION: with `deferSessionValues` the first client render is\n // seeded with DEFAULTS (byte-identical to the default-state prerender it hydrates\n // against) and the visitor's real answers arrive afterwards as a single `store.setMany`\n // from FunnelProvider. React runs CHILD effects before PARENT ones, so in our own mount\n // effect that setMany has NOT happened yet — tracing there would follow the DEFAULT\n // branches and reconstruct somebody else's path. A microtask queued from the mount effect\n // resolves after the entire passive-effect flush of that commit, i.e. after the provider's\n // setMany, so the trace sees the answers the visitor actually gave. (A non-deferred mount\n // already has its values; the extra tick costs it nothing, and one code path serves both.)\n //\n // WHY IT IS INVISIBLE: the traced path ENDS on the resumed page, so it only PREPENDS —\n // `currentKey` is byte-for-byte unchanged. Everything keyed on `currentKey` therefore does\n // not refire: `page.view` (deliberately no longer keyed on `index` — see below), the\n // `onNavigate` URL sync, the scroll-reset/modal teardown, `experiment.exposure`, and the\n // bus `navigation` emit. No duplicate view event, no spurious address-bar rewrite, no jump\n // to the top of the page. (The pushed `navigation` event keeps the pre-repair numbers until\n // the next real page change; imperative reads — `bus.navigation()`, `nav.snapshot()` — go\n // through `navRef`, which is assigned during render, so they are always current.)\n //\n // WHAT IT ACCEPTS: Back walks the PREDICTED path for the restored answers. A visitor who\n // backtracked mid-funnel gets the route their final answers select, not their literal click\n // history — the click history died with the page.\n //\n // RUNS ONCE, and only when there is something to reconstruct. No `initialKey`, an\n // `initialKey` that already resolved to the start page, a visitor who has since navigated\n // (their history is real), or a target the trace cannot reach under the restored answers —\n // each leaves today's single-entry history exactly as it is rather than inventing a path.\n // Client-only (effects never run during SSR), so it cannot cause a hydration mismatch.\n const reconstructed = useRef(false)\n useEffect(() => {\n if (reconstructed.current || typeof window === 'undefined' || !initialKey) return\n reconstructed.current = true\n queueMicrotask(() => {\n setHistory((h) => {\n if (h.length !== 1) return h // already reconstructed, or the visitor moved\n const start = flowPages[0]?.key\n if (!start || start === h[0]) return h // nothing behind the start page\n return tracePath(flow, start, h[0], funnel.snapshot()) ?? h\n })\n })\n // Mount-only by design: a one-shot repair of the ENTRY history. Re-running it after the\n // visitor navigates would overwrite a real history with a predicted one.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n // Expected path length for the visitor's current answers — re-traced per\n // navigation so progress reaches 100% on whichever branch the funnel takes.\n const total = useMemo(\n () => expectedPathLength(flow, startKey, funnel.snapshot()),\n // currentKey in deps: re-trace as each step's answers settle the branch.\n [flow, startKey, currentKey, funnel],\n )\n\n // Keep the read-only context's `page` slice current so predicates + usePage see it.\n const slug = pageByKey.get(currentKey)?.meta?.slug ?? currentKey\n const group = pageByKey.get(currentKey)?.meta?.group\n const page = useMemo(\n () => pageContextFor(currentKey, slug, group, index, total, funnel.context.system.now),\n [currentKey, slug, group, index, total, funnel.context.system.now],\n )\n\n // The visitor-routed grouped-progress structure (branch-aware, mirrors `total`'s\n // routed-path walk) — surfaced via useGroupProgress() for a grouped <ProgressBar>.\n const groups = useMemo(\n () => groupProgress(flow, startKey, currentKey, funnel.snapshot()),\n // currentKey in deps: re-trace as each step's answers settle the branch.\n [flow, startKey, currentKey, funnel],\n )\n // Keep the imperative handle's `context.page` in sync for snapshot()/predicates\n // and the window.appfunnel bus. Synced in a COMMIT effect, not during render —\n // mutating a shared object mid-render is unsafe under SSR/concurrent rendering\n // (two in-flight renders would race on it). Everything render-facing reads\n // `page` from the NavContext value below (React state), so this only serves\n // event-handler/effect readers, which always run after the commit.\n useEffect(() => {\n funnel.context.page = page\n }, [funnel, page])\n\n // funnel.start once, on mount.\n const started = useRef(false)\n useEffect(() => {\n if (started.current) return\n started.current = true\n tracker.track('funnel.start', {})\n }, [tracker])\n\n // page.view on every page change — keyed on the PAGE, not on the position. `index` is read\n // through a ref (assigned during render, so the effect reads the committed value) rather\n // than depended on: the resume path reconstruction above rewrites `history` UNDER the same\n // current page, which moves `index` without the visitor going anywhere. Keeping `index` in\n // the dep array would fire a second, duplicate `page.view` for the page they are already on.\n const indexRef = useRef(index)\n indexRef.current = index\n useEffect(() => {\n if (!currentKey) return\n tracker.track('page.view', { pageId: currentKey, pageKey: currentKey, isInitial: indexRef.current === 0, eventId: newEventId() })\n }, [tracker, currentKey])\n\n // Announce the live page (key + slug + whether it's the flow start) so the URL path can be synced.\n useEffect(() => {\n if (currentKey && onNavigate)\n onNavigate(currentKey, slug, currentKey === flowPages[0]?.key)\n }, [onNavigate, currentKey, slug, flowPages])\n\n // LEAVE NOTHING BEHIND ON A PAGE CHANGE. Navigation is a React state swap, not a document\n // navigation, so two things the browser would normally do for us don't happen:\n //\n // 1. SCROLL POSITION carries over — leaving the bottom of a long page (a paywall) drops the\n // visitor into the middle of the next one.\n // 2. OPEN MODALS survive. The registry mounts them above the flow (FunnelProvider renders\n // ModalRoot; FunnelView lives inside it), so a modal a page opened outlives that page and\n // lands on top of the next screen. dismissAllModals() also settles anything still awaiting\n // `showModal()`, so a page handler can't be left hanging on a promise that never resolves.\n //\n // Both are skipped on the first commit: the entry page may legitimately be restored or\n // deep-linked to an anchor, and nothing can be open yet.\n const navigated = useRef(false)\n useEffect(() => {\n if (!currentKey || typeof window === 'undefined') return\n if (!navigated.current) {\n navigated.current = true\n return\n }\n // `instant` — a smooth animation across a tall page reads as a glitch, and would still\n // be travelling when the next page's own scroll behaviour (an anchor, a sticky CTA) runs.\n window.scrollTo({ top: 0, left: 0, behavior: 'instant' as ScrollBehavior })\n dismissAllModals()\n }, [currentKey])\n\n // experiment.exposure the first time the visitor lands on an experiment slot.\n const exposed = useRef<Set<string>>(new Set())\n useEffect(() => {\n const expId = experiments.experimentOf[currentKey]\n if (!expId || exposed.current.has(expId)) return\n exposed.current.add(expId)\n tracker.track('experiment.exposure', exposurePayload(expId, experiments.assignments[expId], experiments.versionOf[expId]))\n }, [tracker, currentKey, experiments])\n\n usePageExitTimer(tracker, currentKey)\n\n // Navigation swaps a code-split page (a lazy chunk). Wrap the history update in a\n // transition so React keeps the CURRENT page on screen until the next page's chunk\n // is ready, instead of flashing the Suspense `fallback` (the inter-page flicker).\n // `isNavigating` is true while a cold chunk resolves → show a \"working\" affordance\n // so the button doesn't feel dead. Prefetch makes this window usually invisible.\n const [isNavigating, startNav] = useTransition()\n const next = useCallback(() => {\n // Route over the effective flow (slots). The routing edges come from the slot's\n // `meta.next` — OR, when this visitor is served a variant that declares its own\n // `next`, from that variant's routes (folded into `flow` above). Remap any target\n // that points at a collapsed variant key to its slot.\n const target = nextPage(flow, currentKey, funnel.snapshot())\n const resolved = target ? toSlot(target) : target\n if (resolved) startNav(() => setHistory((h) => [...h, resolved]))\n }, [flow, currentKey, funnel, toSlot])\n\n const back = useCallback(\n () => startNav(() => setHistory((h) => (h.length > 1 ? h.slice(0, -1) : h))),\n [],\n )\n const go = useCallback(\n (key: string) => startNav(() => setHistory((h) => [...h, toSlot(key)])),\n [toSlot],\n )\n\n // Resolved candidate components, keyed by render-key — captured when a lazy chunk\n // finishes loading so it can be pre-mounted hidden WITHOUT re-invoking its loader.\n // (Rendering the React.lazy wrapper for a not-yet-rendered candidate would call\n // load() a SECOND time; storing the resolved component pre-mounts it directly, so a\n // chunk's loader runs once.) Eager `Component` pages are always resident and need no\n // entry here.\n const [loadedComps, setLoadedComps] = useState<ReadonlyMap<string, ComponentType>>(() => new Map())\n\n // Warm a slot's code-split chunk (the variant that would actually render). Loading\n // the chunk readies the code so it renders instantly on navigation AND can be\n // pre-mounted hidden (for automatic image preloading — see below); on resolve we\n // capture the component so it can join the hidden pre-mount. Idempotent per render-key.\n const prefetched = useRef<Set<string>>(new Set())\n const prefetch = useCallback(\n (key: string) => {\n const target = toRenderKey(key)\n const load = loaders.get(target)\n if (!load || prefetched.current.has(target)) return\n prefetched.current.add(target)\n load()\n .then((m) => {\n const Comp = typeof m === 'function' ? m : m.default // unwrap a { default } module\n setLoadedComps((prev) => (prev.has(target) ? prev : new Map(prev).set(target, Comp)))\n })\n .catch(() => prefetched.current.delete(target)) // let a failed load retry later\n },\n [loaders, toRenderKey],\n )\n\n // The next-likely pages, resolved to the chunk that would actually render\n // (experiment variant applied) — the renderer modulepreloads these.\n const nextCandidates = useMemo(\n () => [...new Set(outgoingKeys(flow, currentKey).map(toRenderKey))],\n [flow, currentKey, toRenderKey],\n )\n\n // 'auto' mode: the SDK owns chunk warming — load() the next candidates, both to\n // render instantly on navigation AND to make them pre-mountable hidden (below).\n useEffect(() => {\n if (prefetchMode !== 'auto') return\n for (const key of nextCandidates) prefetch(key)\n }, [prefetchMode, nextCandidates, prefetch])\n\n // 'off' mode: the RENDERER owns chunk FETCHING (it modulepreloads all chunks), but a\n // React.lazy page still has to EXECUTE before it can render — and hidden pre-mounting\n // (below) needs the component in hand. So the SDK still load()s the candidates here:\n // the dynamic import dedupes against the renderer's modulepreload (already fetched —\n // this only executes it, near-free), leaving the renderer's all-chunk strategy intact\n // while readying the candidates for the hidden pre-mount.\n useEffect(() => {\n if (prefetchMode !== 'off') return\n for (const key of nextCandidates) prefetch(key)\n }, [prefetchMode, nextCandidates, prefetch])\n\n // Gate for AUTOMATIC image preloading via hidden pre-mount (below). Stays FALSE on\n // the server and through the first client render so the hydration pass matches the\n // SSR markup exactly (no speculative hidden pages in the server output); it flips\n // true in a mount effect, adding the hidden pre-mounts on the next commit. Also\n // honors Data Saver — a visitor on a metered/constrained connection opts out of\n // speculative fetching entirely (one readable check, no config surface).\n const [preMountReady, setPreMountReady] = useState(false)\n useEffect(() => {\n const saveData =\n typeof navigator !== 'undefined' &&\n (navigator as { connection?: { saveData?: boolean } }).connection?.saveData === true\n if (!saveData) setPreMountReady(true)\n }, [])\n\n const value: NavigationState = {\n page,\n next,\n back,\n go,\n prefetch,\n nextCandidates,\n canGoBack: history.length > 1,\n isNavigating,\n }\n\n // Bridge the flow to window.appfunnel + the cross-origin EmbedBridge. `navRef` holds the LATEST value,\n // assigned during render so imperative reads (snapshot(), the nav.* methods) are never a page behind\n // — the previous commit-effect assignment ran AFTER the page.view effect, so snapshots lagged by one.\n const bus = useBusInternal()\n const navRef = useRef(value)\n navRef.current = value\n useEffect(() => {\n if (!bus) return\n const control: NavigationControl = {\n goTo: (key) => {\n // Only navigate to a real page key; report validity so the bridge can reject unknown keys.\n if (!components.has(toRenderKey(key))) return false\n navRef.current.go(key)\n return true\n },\n goNext: () => navRef.current.next(),\n goPrevious: () => navRef.current.back(),\n snapshot: () => {\n const v = navRef.current\n return {\n key: v.page.key,\n index: v.page.index,\n total: v.page.total,\n progressPercentage: v.page.progressPercentage,\n canGoBack: v.canGoBack,\n nextCandidates: v.nextCandidates,\n }\n },\n }\n return bus.registerNavigation(control)\n }, [bus])\n // Emit the FRESH flow snapshot on every page change (incl. the initial page). Keyed on the committed\n // `currentKey` and read from navRef (set above during render), so observers — EmbedBridge and any\n // window.appfunnel `on('navigation')` subscriber — get the page the visitor is actually on, not the\n // previous one. This is the observe channel; it does not depend on registration timing.\n useEffect(() => {\n const v = navRef.current\n bus?.emit('navigation', {\n key: v.page.key,\n index: v.page.index,\n total: v.page.total,\n progressPercentage: v.page.progressPercentage,\n canGoBack: v.canGoBack,\n nextCandidates: v.nextCandidates,\n })\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [bus, currentKey])\n // Render the assigned variant's component at the current slot (the anchor key\n // stays the flow position; only the component swaps). Lazy pages suspend, so the\n // page area shows `fallback` while the chunk loads — inside the layout, so the\n // persistent chrome stays put.\n const renderKey = toRenderKey(currentKey)\n const Current = components.get(renderKey)\n const pageEl = createElement(Suspense, { fallback: fallback ?? null }, Current ? createElement(Current) : null)\n // The layout wraps the page inside NavContext → it persists across navigation\n // (same element type, only the page child swaps) and can use nav/funnel hooks.\n const visible = layout ? createElement(layout, null, pageEl) : pageEl\n\n // AUTOMATIC IMAGE PRELOADING. Pre-mount the next-candidate pages HIDDEN (React\n // `<Activity mode=\"hidden\">`): the browser commits their DOM — including `<img>` —\n // and fetches those images (browsers fetch `<img src>` regardless of `display`), so\n // the imagery is already resident when the visitor navigates. No pop-in, and no code\n // declares anything — it happens purely from the flow graph. Crucially, a HIDDEN\n // Activity DEFERS its subtree's effects, so a pre-mounted page runs NO\n // timers/analytics/tracking (nothing in a `useEffect`) until it is actually shown;\n // and page guards live in the navigation logic, not in render, so rendering a guarded\n // page hidden triggers no redirect. The hidden pages sit OUTSIDE the layout (no\n // duplicate chrome) but INSIDE the nav/funnel providers below, so their snapshot\n // reads resolve. We only pre-mount candidates whose component is in hand — an eager\n // `Component`, or a lazy chunk already executed (`loadedKeys`); an un-loaded lazy\n // chunk is warmed by the `prefetch` effect above and joins once ready. Capped, never\n // includes the current page, and no-ops without `Activity` (older React) or before\n // the client is ready (SSR/hydration/Data-Saver — see `preMountReady`). As\n // `nextCandidates` changes across navigation, the keyed Activity children swap and the\n // stale hidden mounts unmount.\n const hiddenKeys =\n preMountReady && Activity\n ? nextCandidates\n .filter((k) => k !== renderKey && (pageByKey.get(k)?.Component !== undefined || loadedComps.has(k)))\n .slice(0, HIDDEN_CANDIDATE_CAP)\n : []\n const hiddenEls = hiddenKeys.map((k) => {\n // The already-resolved component (eager, or a loaded lazy chunk) — rendered\n // directly so no loader re-runs and nothing suspends inside the hidden subtree.\n const C = pageByKey.get(k)?.Component ?? loadedComps.get(k)\n return C ? createElement(Activity!, { key: k, mode: 'hidden' }, createElement(C)) : null\n })\n const content = hiddenEls.length > 0 ? createElement(Fragment, null, visible, ...hiddenEls) : visible\n\n return createElement(\n ExperimentContext.Provider,\n { value: experiments.assignments },\n createElement(\n NavContext.Provider,\n { value },\n createElement(GroupProgressContext.Provider, { value: groups }, content),\n ),\n )\n}\n\n/** `const { next, back, go, page } = useNavigation()`. */\nexport function useNavigation(): NavigationState {\n const ctx = useContext(NavContext)\n if (!ctx) throw new Error('useNavigation must be used inside <FunnelView>')\n return ctx\n}\n\n/** What the funnel side of the Embed API advertises in its `hello` and answers. */\nconst EMBED_CAPABILITIES: Capabilities = {\n methods: ['nav.snapshot', 'nav.goTo', 'nav.goNext', 'nav.goPrevious', 'screenshot'],\n events: ['navigation'],\n}\n\n/**\n * The funnel side of the **Funnel Embed API**. Mounted by `createFunnelTree` ONLY when\n * `MountOpts.embed` is set — the live preview + the sealed `/preview/<buildId>` build, never a prod\n * funnel (so an embedder can't drive it or read its state). Runs inside `<FunnelView>`'s nav context.\n *\n * It is the funnel's flow bus (`window.appfunnel`) PROJECTED over postMessage: it announces a `hello`\n * with its capabilities, pushes a `navigation` event on every page change, and answers `request`\n * methods (nav.* + screenshot) with correlated `response`s — one dispatcher over the shared registry,\n * not a second nav reader. SSR-safe (effect-only, renders null) and inert when not framed.\n */\nexport function EmbedBridge(): ReactNode {\n const bus = useBusInternal()\n useEffect(() => {\n if (!bus || typeof window === 'undefined' || window.parent === window) return\n const parent = window.parent\n let disposed = false\n\n // Opaque-origin sandbox → target '*'; the preview-host relays only to the trusted dashboard origin.\n const send = (msg: Record<string, unknown>) => {\n try { parent.postMessage({ af: AF_PROTOCOL, source: 'af-preview', ...msg }, '*') } catch { /* ignore */ }\n }\n const hello = () => send({ kind: 'hello', role: 'funnel', protocol: AF_PROTOCOL, capabilities: EMBED_CAPABILITIES })\n const sendSnapshot = () => { const s = bus.navigation(); if (s) send({ kind: 'event', event: 'navigation', data: s }) }\n\n async function invoke(method: string, params: Record<string, unknown> | undefined): Promise<unknown> {\n switch (method) {\n case 'nav.snapshot': return bus!.navigation()\n case 'nav.goTo': {\n const key = params?.key\n // Reject unknown keys (goTo returns false) rather than pushing a blank page into history.\n if (typeof key !== 'string' || !bus!.goTo(key)) throw { code: 'bad_params', message: `unknown page key: ${String(key)}` }\n return undefined // the resulting position arrives as a `navigation` event (nav is async)\n }\n case 'nav.goNext': bus!.goNext(); return undefined\n case 'nav.goPrevious': bus!.goPrevious(); return undefined\n case 'screenshot': return await captureScreenshot(params ?? {})\n default: throw { code: 'unknown_method', message: `unknown method: ${method}` }\n }\n }\n\n async function onMsg(e: MessageEvent) {\n if (e.source !== parent) return // only the trusted host/parent frame may drive us\n const d = e.data\n if (!d || typeof d !== 'object' || d.af !== AF_PROTOCOL || d.source !== 'af-host') return\n if (d.kind === 'hello') { hello(); sendSnapshot(); return } // host (re)connected → re-announce + current snapshot\n if (d.kind !== 'request' || typeof d.id !== 'string') return\n try {\n const result = await invoke(d.method, d.params)\n if (!disposed) send({ kind: 'response', id: d.id, ok: true, result })\n } catch (err) {\n const e2 = err as { code?: string; message?: string }\n const error = e2 && typeof e2.code === 'string'\n ? { code: e2.code, message: String(e2.message ?? e2.code) }\n : { code: 'failed', message: String(e2?.message ?? err) }\n if (!disposed) send({ kind: 'response', id: d.id, ok: false, error })\n }\n }\n\n window.addEventListener('message', onMsg)\n // The observe channel: FunnelView emits a fresh 'navigation' bus event on every page change (incl.\n // the initial page); we forward it verbatim. We subscribe here — a descendant of FunnelView, so this\n // runs BEFORE FunnelView's emit effect — so the initial navigation is never missed.\n const offNav = bus.on('navigation', (data) => { if (!disposed) send({ kind: 'event', event: 'navigation', data }) })\n hello()\n sendSnapshot() // covers a host that connected before we mounted (nav may already be registered)\n\n return () => { disposed = true; offNav(); window.removeEventListener('message', onMsg) }\n }, [bus])\n\n return null\n}\n\n/** `usePage()` — the current page's read-only context, reactive to navigation. */\nexport function usePage(): PageContext {\n return useNavigation().page\n}\n\n/**\n * `useGroupProgress()` — the visitor-routed, branch-aware grouped-progress structure\n * for a grouped `<ProgressBar>`: ordered {@link PageGroup} segments (from `meta.group`),\n * the `activeIndex` of the current group (`-1` when the current page is ungrouped), and\n * the active group's within-group `activeFraction` (0–1). Counts only the pages THIS\n * visitor will actually visit given their answers (see {@link groupProgress}). A funnel\n * with no `group` keys yields `{ groups: [], activeIndex: -1, activeFraction: 0 }`.\n * Must be used inside `<FunnelView>`.\n *\n * Each segment's `key` is the **slug identifier** from {@link PageMeta.group}, NOT a\n * display string — resolve it to a label in your funnel code, e.g.\n * `const GROUP_LABELS = { profile: 'My Profile' }; GROUP_LABELS[group.key]` or\n * `t(`groups.${group.key}`)`. This keeps grouping stable across copy and locale changes.\n */\nexport function useGroupProgress(): GroupProgress {\n const ctx = useContext(GroupProgressContext)\n if (!ctx) throw new Error('useGroupProgress must be used inside <FunnelView>')\n return ctx\n}\n"]}
|