sme-pos-package 1.0.2 → 1.0.4

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/components/button.tsx"],"sourcesContent":["export * from \"./components\";\n","import { useState } from \"react\";\n\ninterface ButtonProps {\n label: string;\n onClick: () => void;\n}\nconst ExampleButton: React.FC<ButtonProps> = ({ label, onClick }) => {\n const [clicked, setClicked] = useState(false);\n const handleClick = () => {\n setClicked(true);\n onClick();\n };\n return (\n <button className=\"custom\" onClick={handleClick}>\n {clicked ? \"Clicked!\" : label}\n </button>\n );\n};\nexport default ExampleButton;\n"],"mappings":"4ZAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,GCAA,IAAAI,EAAyB,iBAarBC,EAAA,6BAPEC,EAAuC,CAAC,CAAE,MAAAC,EAAO,QAAAC,CAAQ,IAAM,CACnE,GAAM,CAACC,EAASC,CAAU,KAAI,YAAS,EAAK,EAK5C,SACE,OAAC,UAAO,UAAU,SAAS,QALT,IAAM,CACxBA,EAAW,EAAI,EACfF,EAAQ,CACV,EAGK,SAAAC,EAAU,WAAaF,EAC1B,CAEJ,EACOI,EAAQL","names":["index_exports","__export","button_default","__toCommonJS","import_react","import_jsx_runtime","ExampleButton","label","onClick","clicked","setClicked","button_default"]}
1
+ {"version":3,"sources":["../node_modules/void-elements/index.js","../src/index.ts","../src/assets/icons/common.tsx","../src/assets/icons/emenu-icon.tsx","../src/components/emenu/menu-link.tsx","../../node_modules/qrcode.react/lib/esm/index.js","../node_modules/react-i18next/dist/es/Trans.js","../node_modules/react-i18next/dist/es/TransWithoutContext.js","../node_modules/react-i18next/dist/es/utils.js","../node_modules/react-i18next/dist/es/unescape.js","../node_modules/react-i18next/dist/es/defaults.js","../node_modules/react-i18next/dist/es/i18nInstance.js","../node_modules/react-i18next/dist/es/context.js","../node_modules/react-i18next/dist/es/useTranslation.js","../node_modules/react-i18next/dist/es/withTranslation.js","../node_modules/react-i18next/dist/es/I18nextProvider.js","../node_modules/react-i18next/dist/es/withSSR.js","../node_modules/react-i18next/dist/es/useSSR.js","../node_modules/clsx/dist/clsx.mjs","../src/utils/functions.ts","../node_modules/framer-motion/dist/es/components/AnimatePresence/index.mjs","../node_modules/framer-motion/dist/es/context/LayoutGroupContext.mjs","../node_modules/framer-motion/dist/es/utils/use-constant.mjs","../node_modules/framer-motion/dist/es/utils/use-isomorphic-effect.mjs","../node_modules/framer-motion/dist/es/utils/is-browser.mjs","../node_modules/framer-motion/dist/es/components/AnimatePresence/PresenceChild.mjs","../node_modules/framer-motion/dist/es/context/PresenceContext.mjs","../node_modules/framer-motion/dist/es/components/AnimatePresence/PopChild.mjs","../node_modules/motion-utils/dist/es/array.mjs","../node_modules/motion-utils/dist/es/clamp.mjs","../node_modules/motion-utils/dist/es/format-error-message.mjs","../node_modules/motion-utils/dist/es/errors.mjs","../node_modules/motion-utils/dist/es/global-config.mjs","../node_modules/motion-utils/dist/es/is-numerical-string.mjs","../node_modules/motion-utils/dist/es/is-object.mjs","../node_modules/motion-utils/dist/es/is-zero-value-string.mjs","../node_modules/motion-utils/dist/es/memo.mjs","../node_modules/motion-utils/dist/es/noop.mjs","../node_modules/motion-utils/dist/es/pipe.mjs","../node_modules/motion-utils/dist/es/progress.mjs","../node_modules/motion-utils/dist/es/subscription-manager.mjs","../node_modules/motion-utils/dist/es/time-conversion.mjs","../node_modules/motion-utils/dist/es/velocity-per-second.mjs","../node_modules/motion-utils/dist/es/warn-once.mjs","../node_modules/motion-utils/dist/es/easing/cubic-bezier.mjs","../node_modules/motion-utils/dist/es/easing/modifiers/mirror.mjs","../node_modules/motion-utils/dist/es/easing/modifiers/reverse.mjs","../node_modules/motion-utils/dist/es/easing/back.mjs","../node_modules/motion-utils/dist/es/easing/anticipate.mjs","../node_modules/motion-utils/dist/es/easing/circ.mjs","../node_modules/motion-utils/dist/es/easing/ease.mjs","../node_modules/motion-utils/dist/es/easing/utils/is-easing-array.mjs","../node_modules/motion-utils/dist/es/easing/utils/is-bezier-definition.mjs","../node_modules/motion-utils/dist/es/easing/utils/map.mjs","../node_modules/motion-dom/dist/es/frameloop/order.mjs","../node_modules/motion-dom/dist/es/stats/buffer.mjs","../node_modules/motion-dom/dist/es/frameloop/render-step.mjs","../node_modules/motion-dom/dist/es/frameloop/batcher.mjs","../node_modules/motion-dom/dist/es/frameloop/frame.mjs","../node_modules/motion-dom/dist/es/frameloop/sync-time.mjs","../node_modules/motion-dom/dist/es/stats/animation-count.mjs","../node_modules/motion-dom/dist/es/animation/utils/is-css-variable.mjs","../node_modules/motion-dom/dist/es/value/types/numbers/index.mjs","../node_modules/motion-dom/dist/es/value/types/utils/sanitize.mjs","../node_modules/motion-dom/dist/es/value/types/utils/float-regex.mjs","../node_modules/motion-dom/dist/es/value/types/utils/is-nullish.mjs","../node_modules/motion-dom/dist/es/value/types/utils/single-color-regex.mjs","../node_modules/motion-dom/dist/es/value/types/color/utils.mjs","../node_modules/motion-dom/dist/es/value/types/color/rgba.mjs","../node_modules/motion-dom/dist/es/value/types/color/hex.mjs","../node_modules/motion-dom/dist/es/value/types/numbers/units.mjs","../node_modules/motion-dom/dist/es/value/types/color/hsla.mjs","../node_modules/motion-dom/dist/es/value/types/color/index.mjs","../node_modules/motion-dom/dist/es/value/types/utils/color-regex.mjs","../node_modules/motion-dom/dist/es/value/types/complex/index.mjs","../node_modules/motion-dom/dist/es/value/types/color/hsla-to-rgba.mjs","../node_modules/motion-dom/dist/es/utils/mix/immediate.mjs","../node_modules/motion-dom/dist/es/utils/mix/number.mjs","../node_modules/motion-dom/dist/es/utils/mix/color.mjs","../node_modules/motion-dom/dist/es/utils/mix/visibility.mjs","../node_modules/motion-dom/dist/es/utils/mix/complex.mjs","../node_modules/motion-dom/dist/es/utils/mix/index.mjs","../node_modules/motion-dom/dist/es/animation/drivers/frame.mjs","../node_modules/motion-dom/dist/es/animation/waapi/utils/linear.mjs","../node_modules/motion-dom/dist/es/animation/generators/utils/calc-duration.mjs","../node_modules/motion-dom/dist/es/animation/generators/utils/create-generator-easing.mjs","../node_modules/motion-dom/dist/es/animation/generators/utils/velocity.mjs","../node_modules/motion-dom/dist/es/animation/generators/spring/defaults.mjs","../node_modules/motion-dom/dist/es/animation/generators/spring/find.mjs","../node_modules/motion-dom/dist/es/animation/generators/spring/index.mjs","../node_modules/motion-dom/dist/es/animation/generators/inertia.mjs","../node_modules/motion-dom/dist/es/utils/interpolate.mjs","../node_modules/motion-dom/dist/es/animation/keyframes/offsets/fill.mjs","../node_modules/motion-dom/dist/es/animation/keyframes/offsets/default.mjs","../node_modules/motion-dom/dist/es/animation/keyframes/offsets/time.mjs","../node_modules/motion-dom/dist/es/animation/generators/keyframes.mjs","../node_modules/motion-dom/dist/es/animation/keyframes/get-final.mjs","../node_modules/motion-dom/dist/es/animation/utils/replace-transition-type.mjs","../node_modules/motion-dom/dist/es/animation/utils/WithPromise.mjs","../node_modules/motion-dom/dist/es/animation/JSAnimation.mjs","../node_modules/motion-dom/dist/es/animation/keyframes/utils/fill-wildcards.mjs","../node_modules/motion-dom/dist/es/render/dom/parse-transform.mjs","../node_modules/motion-dom/dist/es/render/utils/keys-transform.mjs","../node_modules/motion-dom/dist/es/animation/keyframes/utils/unit-conversion.mjs","../node_modules/motion-dom/dist/es/animation/keyframes/KeyframesResolver.mjs","../node_modules/motion-dom/dist/es/render/dom/is-css-var.mjs","../node_modules/motion-dom/dist/es/render/dom/style-set.mjs","../node_modules/motion-dom/dist/es/utils/supports/scroll-timeline.mjs","../node_modules/motion-dom/dist/es/utils/supports/flags.mjs","../node_modules/motion-dom/dist/es/utils/supports/memo.mjs","../node_modules/motion-dom/dist/es/utils/supports/linear-easing.mjs","../node_modules/motion-dom/dist/es/animation/waapi/easing/cubic-bezier.mjs","../node_modules/motion-dom/dist/es/animation/waapi/easing/supported.mjs","../node_modules/motion-dom/dist/es/animation/waapi/easing/map-easing.mjs","../node_modules/motion-dom/dist/es/animation/waapi/start-waapi-animation.mjs","../node_modules/motion-dom/dist/es/animation/generators/utils/is-generator.mjs","../node_modules/motion-dom/dist/es/animation/waapi/utils/apply-generator.mjs","../node_modules/motion-dom/dist/es/animation/NativeAnimation.mjs","../node_modules/motion-dom/dist/es/animation/waapi/utils/unsupported-easing.mjs","../node_modules/motion-dom/dist/es/animation/NativeAnimationExtended.mjs","../node_modules/motion-dom/dist/es/animation/utils/is-animatable.mjs","../node_modules/motion-dom/dist/es/animation/utils/can-animate.mjs","../node_modules/motion-dom/dist/es/animation/utils/make-animation-instant.mjs","../node_modules/motion-dom/dist/es/animation/waapi/supports/waapi.mjs","../node_modules/motion-dom/dist/es/animation/AsyncMotionValueAnimation.mjs","../node_modules/motion-dom/dist/es/animation/utils/css-variables-conversion.mjs","../node_modules/motion-dom/dist/es/animation/utils/get-value-transition.mjs","../node_modules/motion-dom/dist/es/render/utils/keys-position.mjs","../node_modules/motion-dom/dist/es/value/types/auto.mjs","../node_modules/motion-dom/dist/es/value/types/test.mjs","../node_modules/motion-dom/dist/es/value/types/dimensions.mjs","../node_modules/motion-dom/dist/es/animation/keyframes/utils/is-none.mjs","../node_modules/motion-dom/dist/es/value/types/complex/filter.mjs","../node_modules/motion-dom/dist/es/value/types/int.mjs","../node_modules/motion-dom/dist/es/value/types/maps/transform.mjs","../node_modules/motion-dom/dist/es/value/types/maps/number.mjs","../node_modules/motion-dom/dist/es/value/types/maps/defaults.mjs","../node_modules/motion-dom/dist/es/value/types/utils/animatable-none.mjs","../node_modules/motion-dom/dist/es/animation/keyframes/utils/make-none-animatable.mjs","../node_modules/motion-dom/dist/es/animation/keyframes/DOMKeyframesResolver.mjs","../node_modules/motion-dom/dist/es/utils/resolve-elements.mjs","../node_modules/motion-dom/dist/es/value/types/utils/get-as-type.mjs","../node_modules/motion-dom/dist/es/utils/is-html-element.mjs","../node_modules/motion-dom/dist/es/value/index.mjs","../node_modules/motion-dom/dist/es/frameloop/microtask.mjs","../node_modules/motion-dom/dist/es/gestures/drag/state/is-active.mjs","../node_modules/motion-dom/dist/es/gestures/drag/state/set-active.mjs","../node_modules/motion-dom/dist/es/gestures/utils/setup.mjs","../node_modules/motion-dom/dist/es/gestures/hover.mjs","../node_modules/motion-dom/dist/es/gestures/utils/is-node-or-child.mjs","../node_modules/motion-dom/dist/es/gestures/utils/is-primary-pointer.mjs","../node_modules/motion-dom/dist/es/gestures/press/utils/is-keyboard-accessible.mjs","../node_modules/motion-dom/dist/es/gestures/press/utils/state.mjs","../node_modules/motion-dom/dist/es/gestures/press/utils/keyboard.mjs","../node_modules/motion-dom/dist/es/gestures/press/index.mjs","../node_modules/motion-dom/dist/es/utils/is-svg-element.mjs","../node_modules/motion-dom/dist/es/utils/is-svg-svg-element.mjs","../node_modules/motion-dom/dist/es/value/utils/is-motion-value.mjs","../node_modules/motion-dom/dist/es/value/types/utils/find.mjs","../node_modules/framer-motion/dist/es/context/MotionConfigContext.mjs","../node_modules/framer-motion/dist/es/utils/use-composed-ref.mjs","../node_modules/framer-motion/dist/es/components/AnimatePresence/use-presence.mjs","../node_modules/framer-motion/dist/es/components/AnimatePresence/utils.mjs","../node_modules/framer-motion/dist/es/context/LazyContext.mjs","../node_modules/framer-motion/dist/es/motion/features/definitions.mjs","../node_modules/framer-motion/dist/es/motion/features/load-features.mjs","../node_modules/framer-motion/dist/es/motion/utils/valid-prop.mjs","../node_modules/framer-motion/dist/es/render/dom/utils/filter-props.mjs","../node_modules/framer-motion/dist/es/motion/index.mjs","../node_modules/framer-motion/dist/es/context/MotionContext/index.mjs","../node_modules/framer-motion/dist/es/context/MotionContext/create.mjs","../node_modules/framer-motion/dist/es/animation/utils/is-animation-controls.mjs","../node_modules/framer-motion/dist/es/render/utils/is-variant-label.mjs","../node_modules/framer-motion/dist/es/render/utils/variant-props.mjs","../node_modules/framer-motion/dist/es/render/utils/is-controlling-variants.mjs","../node_modules/framer-motion/dist/es/context/MotionContext/utils.mjs","../node_modules/framer-motion/dist/es/render/dom/use-render.mjs","../node_modules/framer-motion/dist/es/render/html/use-props.mjs","../node_modules/framer-motion/dist/es/projection/styles/scale-border-radius.mjs","../node_modules/framer-motion/dist/es/projection/styles/scale-box-shadow.mjs","../node_modules/framer-motion/dist/es/projection/styles/scale-correction.mjs","../node_modules/framer-motion/dist/es/motion/utils/is-forced-motion-value.mjs","../node_modules/framer-motion/dist/es/render/html/utils/build-transform.mjs","../node_modules/framer-motion/dist/es/render/html/utils/build-styles.mjs","../node_modules/framer-motion/dist/es/render/html/utils/create-render-state.mjs","../node_modules/framer-motion/dist/es/render/svg/use-props.mjs","../node_modules/framer-motion/dist/es/render/svg/utils/path.mjs","../node_modules/framer-motion/dist/es/render/svg/utils/build-attrs.mjs","../node_modules/framer-motion/dist/es/render/svg/utils/create-render-state.mjs","../node_modules/framer-motion/dist/es/render/svg/utils/is-svg-tag.mjs","../node_modules/framer-motion/dist/es/render/svg/lowercase-elements.mjs","../node_modules/framer-motion/dist/es/render/dom/utils/is-svg-component.mjs","../node_modules/framer-motion/dist/es/motion/utils/use-visual-state.mjs","../node_modules/framer-motion/dist/es/render/utils/resolve-variants.mjs","../node_modules/framer-motion/dist/es/value/utils/resolve-motion-value.mjs","../node_modules/framer-motion/dist/es/render/html/utils/scrape-motion-values.mjs","../node_modules/framer-motion/dist/es/render/html/use-html-visual-state.mjs","../node_modules/framer-motion/dist/es/render/svg/utils/scrape-motion-values.mjs","../node_modules/framer-motion/dist/es/render/svg/use-svg-visual-state.mjs","../node_modules/framer-motion/dist/es/motion/utils/symbol.mjs","../node_modules/framer-motion/dist/es/motion/utils/use-motion-ref.mjs","../node_modules/framer-motion/dist/es/utils/is-ref-object.mjs","../node_modules/framer-motion/dist/es/motion/utils/use-visual-element.mjs","../node_modules/framer-motion/dist/es/render/dom/utils/camel-to-dash.mjs","../node_modules/framer-motion/dist/es/animation/optimized-appear/data-id.mjs","../node_modules/framer-motion/dist/es/context/SwitchLayoutGroupContext.mjs","../node_modules/framer-motion/dist/es/render/components/create-proxy.mjs","../node_modules/framer-motion/dist/es/render/dom/create-visual-element.mjs","../node_modules/framer-motion/dist/es/projection/geometry/conversion.mjs","../node_modules/framer-motion/dist/es/projection/utils/has-transform.mjs","../node_modules/framer-motion/dist/es/projection/geometry/delta-apply.mjs","../node_modules/framer-motion/dist/es/projection/utils/measure.mjs","../node_modules/framer-motion/dist/es/projection/geometry/models.mjs","../node_modules/framer-motion/dist/es/utils/reduced-motion/state.mjs","../node_modules/framer-motion/dist/es/utils/reduced-motion/index.mjs","../node_modules/framer-motion/dist/es/render/store.mjs","../node_modules/framer-motion/dist/es/render/utils/motion-values.mjs","../node_modules/framer-motion/dist/es/render/VisualElement.mjs","../node_modules/framer-motion/dist/es/render/dom/DOMVisualElement.mjs","../node_modules/framer-motion/dist/es/render/html/utils/render.mjs","../node_modules/framer-motion/dist/es/render/html/HTMLVisualElement.mjs","../node_modules/framer-motion/dist/es/render/svg/utils/camel-case-attrs.mjs","../node_modules/framer-motion/dist/es/render/svg/utils/render.mjs","../node_modules/framer-motion/dist/es/render/svg/SVGVisualElement.mjs","../node_modules/framer-motion/dist/es/render/utils/resolve-dynamic-variants.mjs","../node_modules/framer-motion/dist/es/animation/utils/is-keyframes-target.mjs","../node_modules/framer-motion/dist/es/render/utils/setters.mjs","../node_modules/framer-motion/dist/es/value/use-will-change/is.mjs","../node_modules/framer-motion/dist/es/value/use-will-change/add-will-change.mjs","../node_modules/framer-motion/dist/es/animation/optimized-appear/get-appear-id.mjs","../node_modules/framer-motion/dist/es/animation/animators/waapi/utils/get-final-keyframe.mjs","../node_modules/framer-motion/dist/es/animation/utils/default-transitions.mjs","../node_modules/framer-motion/dist/es/animation/utils/is-transition-defined.mjs","../node_modules/framer-motion/dist/es/animation/interfaces/motion-value.mjs","../node_modules/framer-motion/dist/es/animation/interfaces/visual-element-target.mjs","../node_modules/framer-motion/dist/es/animation/utils/calc-child-stagger.mjs","../node_modules/framer-motion/dist/es/animation/interfaces/visual-element-variant.mjs","../node_modules/framer-motion/dist/es/animation/interfaces/visual-element.mjs","../node_modules/framer-motion/dist/es/utils/shallow-compare.mjs","../node_modules/framer-motion/dist/es/render/utils/get-variant-context.mjs","../node_modules/framer-motion/dist/es/render/utils/animation-state.mjs","../node_modules/framer-motion/dist/es/motion/features/Feature.mjs","../node_modules/framer-motion/dist/es/motion/features/animation/index.mjs","../node_modules/framer-motion/dist/es/motion/features/animation/exit.mjs","../node_modules/framer-motion/dist/es/motion/features/animations.mjs","../node_modules/framer-motion/dist/es/events/add-dom-event.mjs","../node_modules/framer-motion/dist/es/events/event-info.mjs","../node_modules/framer-motion/dist/es/events/add-pointer-event.mjs","../node_modules/framer-motion/dist/es/projection/geometry/delta-calc.mjs","../node_modules/framer-motion/dist/es/projection/utils/each-axis.mjs","../node_modules/framer-motion/dist/es/utils/get-context-window.mjs","../node_modules/framer-motion/dist/es/utils/distance.mjs","../node_modules/framer-motion/dist/es/gestures/pan/PanSession.mjs","../node_modules/framer-motion/dist/es/gestures/drag/utils/constraints.mjs","../node_modules/framer-motion/dist/es/gestures/drag/VisualElementDragControls.mjs","../node_modules/framer-motion/dist/es/gestures/drag/index.mjs","../node_modules/framer-motion/dist/es/gestures/pan/index.mjs","../node_modules/framer-motion/dist/es/motion/features/layout/MeasureLayout.mjs","../node_modules/framer-motion/dist/es/projection/node/state.mjs","../node_modules/framer-motion/dist/es/animation/animate/single-value.mjs","../node_modules/framer-motion/dist/es/render/utils/compare-by-depth.mjs","../node_modules/framer-motion/dist/es/render/utils/flat-tree.mjs","../node_modules/framer-motion/dist/es/utils/delay.mjs","../node_modules/framer-motion/dist/es/projection/animation/mix-values.mjs","../node_modules/framer-motion/dist/es/projection/geometry/copy.mjs","../node_modules/framer-motion/dist/es/projection/geometry/delta-remove.mjs","../node_modules/framer-motion/dist/es/projection/geometry/utils.mjs","../node_modules/framer-motion/dist/es/projection/shared/stack.mjs","../node_modules/framer-motion/dist/es/projection/styles/transform.mjs","../node_modules/framer-motion/dist/es/projection/node/create-projection-node.mjs","../node_modules/framer-motion/dist/es/projection/node/DocumentProjectionNode.mjs","../node_modules/framer-motion/dist/es/projection/node/HTMLProjectionNode.mjs","../node_modules/framer-motion/dist/es/motion/features/drag.mjs","../node_modules/framer-motion/dist/es/gestures/hover.mjs","../node_modules/framer-motion/dist/es/gestures/focus.mjs","../node_modules/framer-motion/dist/es/gestures/press.mjs","../node_modules/framer-motion/dist/es/motion/features/viewport/observers.mjs","../node_modules/framer-motion/dist/es/motion/features/viewport/index.mjs","../node_modules/framer-motion/dist/es/motion/features/gestures.mjs","../node_modules/framer-motion/dist/es/motion/features/layout.mjs","../node_modules/framer-motion/dist/es/render/components/motion/feature-bundle.mjs","../node_modules/framer-motion/dist/es/render/components/motion/proxy.mjs","../src/components/common/modal/modal-header.tsx","../src/components/common/modal/modal-wrapper.tsx","../src/components/common/modal/modal-zoom.tsx","../src/provider/app-provider.tsx","../src/assets/icons/customer-view-icon.tsx","../src/components/common/button-action.tsx","../src/components/kitchen-management/kitchen-status.tsx","../src/components/kanban-template/kitchen-template.tsx","../../node_modules/@remix-run/router/history.ts","../../node_modules/@remix-run/router/utils.ts","../../node_modules/@remix-run/router/router.ts","../../node_modules/react-router/lib/context.ts","../../node_modules/react-router/lib/hooks.tsx","../../node_modules/react-router/lib/deprecations.ts","../../node_modules/react-router/lib/components.tsx","../../node_modules/react-router/index.ts","../../node_modules/react-router-dom/dom.ts","../../node_modules/react-router-dom/index.tsx","../src/assets/icons/order-icon.tsx","../src/assets/icons/breadcrumbs-icon.tsx","../src/components/order-management/order-actions.tsx","../src/components/order-management/order-status.tsx","../src/components/kanban-template/pos-order-template.tsx","../src/assets/icons/kanban-icon.tsx","../src/constants/query.constant.ts","../src/provider/use-session-provider.ts","../node_modules/i18next/dist/esm/i18next.js","../src/components/session-management/open-shift/index.tsx","../../node_modules/react-hook-form/src/utils/isCheckBoxInput.ts","../../node_modules/react-hook-form/src/utils/isDateObject.ts","../../node_modules/react-hook-form/src/utils/isNullOrUndefined.ts","../../node_modules/react-hook-form/src/utils/isObject.ts","../../node_modules/react-hook-form/src/logic/getEventValue.ts","../../node_modules/react-hook-form/src/logic/getNodeParentName.ts","../../node_modules/react-hook-form/src/logic/isNameInFieldArray.ts","../../node_modules/react-hook-form/src/utils/isPlainObject.ts","../../node_modules/react-hook-form/src/utils/isWeb.ts","../../node_modules/react-hook-form/src/utils/cloneObject.ts","../../node_modules/react-hook-form/src/utils/isKey.ts","../../node_modules/react-hook-form/src/utils/isUndefined.ts","../../node_modules/react-hook-form/src/utils/compact.ts","../../node_modules/react-hook-form/src/utils/stringToPath.ts","../../node_modules/react-hook-form/src/utils/get.ts","../../node_modules/react-hook-form/src/utils/isBoolean.ts","../../node_modules/react-hook-form/src/utils/set.ts","../../node_modules/react-hook-form/src/constants.ts","../../node_modules/react-hook-form/src/useFormContext.tsx","../../node_modules/react-hook-form/src/logic/getProxyFormState.ts","../../node_modules/react-hook-form/src/useIsomorphicLayoutEffect.ts","../../node_modules/react-hook-form/src/useFormState.ts","../../node_modules/react-hook-form/src/utils/isString.ts","../../node_modules/react-hook-form/src/logic/generateWatchOutput.ts","../../node_modules/react-hook-form/src/utils/isPrimitive.ts","../../node_modules/react-hook-form/src/utils/deepEqual.ts","../../node_modules/react-hook-form/src/useWatch.ts","../../node_modules/react-hook-form/src/useController.ts","../../node_modules/react-hook-form/src/controller.tsx","../../node_modules/react-hook-form/src/utils/flatten.ts","../../node_modules/react-hook-form/src/form.tsx","../../node_modules/react-hook-form/src/logic/appendErrors.ts","../../node_modules/react-hook-form/src/utils/convertToArrayPayload.ts","../../node_modules/react-hook-form/src/utils/createSubject.ts","../../node_modules/react-hook-form/src/utils/extractFormValues.ts","../../node_modules/react-hook-form/src/utils/isEmptyObject.ts","../../node_modules/react-hook-form/src/utils/isFileInput.ts","../../node_modules/react-hook-form/src/utils/isFunction.ts","../../node_modules/react-hook-form/src/utils/isHTMLElement.ts","../../node_modules/react-hook-form/src/utils/isMultipleSelect.ts","../../node_modules/react-hook-form/src/utils/isRadioInput.ts","../../node_modules/react-hook-form/src/utils/isRadioOrCheckbox.ts","../../node_modules/react-hook-form/src/utils/live.ts","../../node_modules/react-hook-form/src/utils/unset.ts","../../node_modules/react-hook-form/src/utils/objectHasFunction.ts","../../node_modules/react-hook-form/src/logic/getDirtyFields.ts","../../node_modules/react-hook-form/src/logic/getCheckboxValue.ts","../../node_modules/react-hook-form/src/logic/getFieldValueAs.ts","../../node_modules/react-hook-form/src/logic/getRadioValue.ts","../../node_modules/react-hook-form/src/logic/getFieldValue.ts","../../node_modules/react-hook-form/src/logic/getResolverOptions.ts","../../node_modules/react-hook-form/src/utils/isRegex.ts","../../node_modules/react-hook-form/src/logic/getRuleValue.ts","../../node_modules/react-hook-form/src/logic/getValidationModes.ts","../../node_modules/react-hook-form/src/logic/hasPromiseValidation.ts","../../node_modules/react-hook-form/src/logic/hasValidation.ts","../../node_modules/react-hook-form/src/logic/isWatched.ts","../../node_modules/react-hook-form/src/logic/iterateFieldsByAction.ts","../../node_modules/react-hook-form/src/logic/schemaErrorLookup.ts","../../node_modules/react-hook-form/src/logic/shouldRenderFormState.ts","../../node_modules/react-hook-form/src/logic/shouldSubscribeByName.ts","../../node_modules/react-hook-form/src/logic/skipValidation.ts","../../node_modules/react-hook-form/src/logic/unsetEmptyArray.ts","../../node_modules/react-hook-form/src/logic/updateFieldArrayRootError.ts","../../node_modules/react-hook-form/src/logic/getValidateError.ts","../../node_modules/react-hook-form/src/logic/getValueAndMessage.ts","../../node_modules/react-hook-form/src/logic/validateField.ts","../../node_modules/react-hook-form/src/logic/createFormControl.ts","../../node_modules/react-hook-form/src/logic/generateId.ts","../../node_modules/react-hook-form/src/logic/getFocusFieldName.ts","../../node_modules/react-hook-form/src/utils/append.ts","../../node_modules/react-hook-form/src/utils/fillEmptyArray.ts","../../node_modules/react-hook-form/src/utils/insert.ts","../../node_modules/react-hook-form/src/utils/move.ts","../../node_modules/react-hook-form/src/utils/prepend.ts","../../node_modules/react-hook-form/src/utils/remove.ts","../../node_modules/react-hook-form/src/utils/swap.ts","../../node_modules/react-hook-form/src/utils/update.ts","../../node_modules/react-hook-form/src/useFieldArray.ts","../../node_modules/react-hook-form/src/useForm.ts","../../node_modules/react-hook-form/src/watch.tsx","../node_modules/shared/src/utils.ts","../node_modules/lucide-react/src/defaultAttributes.ts","../node_modules/lucide-react/src/Icon.ts","../node_modules/lucide-react/src/createLucideIcon.ts","../node_modules/lucide-react/src/icons/plus.ts","../src/components/kanban-template/pos-template.tsx"],"sourcesContent":["/**\n * This file automatically generated from `pre-publish.js`.\n * Do not manually edit.\n */\n\nmodule.exports = {\n \"area\": true,\n \"base\": true,\n \"br\": true,\n \"col\": true,\n \"embed\": true,\n \"hr\": true,\n \"img\": true,\n \"input\": true,\n \"link\": true,\n \"meta\": true,\n \"param\": true,\n \"source\": true,\n \"track\": true,\n \"wbr\": true\n};\n","export * from \"./components\";\nimport \"./index.css\";\n","export const IcBack = () => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 20 20\"\n fill=\"none\"\n >\n <path\n d=\"M9.20437 9.99956L12.9169 13.7121L11.8564 14.7726L7.08337 9.99956L11.8564 5.22656L12.9169 6.28706L9.20437 9.99956Z\"\n fill=\"currentColor\"\n />\n </svg>\n);\n\nexport const IcClose = ({ className = \"\" }: { className?: string }) => {\n return (\n <svg\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n className={className}\n >\n <path\n d=\"M12.0001 10.7275L16.4551 6.27246L17.7277 7.54506L13.2727 12.0001L17.7277 16.4551L16.4551 17.7277L12.0001 13.2727L7.54506 17.7277L6.27246 16.4551L10.7275 12.0001L6.27246 7.54506L7.54506 6.27246L12.0001 10.7275Z\"\n fill=\"currentColor\"\n />\n </svg>\n );\n};\n\nexport const IcMore = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"4\"\n height=\"18\"\n viewBox=\"0 0 4 18\"\n fill=\"none\"\n >\n <path\n d=\"M1.99922 0.900391C1.00922 0.900391 0.199219 1.71039 0.199219 2.70039C0.199219 3.69039 1.00922 4.50039 1.99922 4.50039C2.98922 4.50039 3.79922 3.69039 3.79922 2.70039C3.79922 1.71039 2.98922 0.900391 1.99922 0.900391ZM1.99922 13.5004C1.00922 13.5004 0.199219 14.3104 0.199219 15.3004C0.199219 16.2904 1.00922 17.1004 1.99922 17.1004C2.98922 17.1004 3.79922 16.2904 3.79922 15.3004C3.79922 14.3104 2.98922 13.5004 1.99922 13.5004ZM1.99922 7.20039C1.00922 7.20039 0.199219 8.01039 0.199219 9.00039C0.199219 9.99039 1.00922 10.8004 1.99922 10.8004C2.98922 10.8004 3.79922 9.99039 3.79922 9.00039C3.79922 8.01039 2.98922 7.20039 1.99922 7.20039Z\"\n fill=\"currentColor\"\n />\n </svg>\n );\n};\n\nexport const IcPencil = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"12\"\n height=\"12\"\n viewBox=\"0 0 12 12\"\n fill=\"none\"\n >\n <path\n d=\"M1.79961 10.1997H2.64801L8.23641 4.61126L7.38801 3.76286L1.79961 9.35126V10.1997ZM11.3996 11.3997H0.599609V8.85386L8.66061 0.792859C8.77313 0.680377 8.92571 0.617188 9.08481 0.617188C9.24391 0.617188 9.39649 0.680377 9.50901 0.792859L11.2064 2.49026C11.3189 2.60278 11.3821 2.75536 11.3821 2.91446C11.3821 3.07356 11.3189 3.22614 11.2064 3.33866L4.34541 10.1997H11.3996V11.3997ZM8.23641 2.91446L9.08481 3.76286L9.93321 2.91446L9.08481 2.06606L8.23641 2.91446Z\"\n fill=\"#060606\"\n />\n </svg>\n );\n};\n\nexport const IcPlus = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"17\"\n height=\"16\"\n viewBox=\"0 0 17 16\"\n fill=\"none\"\n >\n <path\n d=\"M8.59985 4.2998V7.89941H12.2004V8.09961H8.59985V11.7002H8.39966V8.09961H4.80005V7.89941H8.39966V4.2998H8.59985Z\"\n fill=\"currentColor\"\n stroke=\"currentColor\"\n />\n </svg>\n );\n};\n\nexport const IcSubtract = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 20 20\"\n fill=\"none\"\n >\n <path d=\"M4.75 9.25H15.25V10.75H4.75V9.25Z\" fill=\"#BDBDBD\" />\n </svg>\n );\n};\n\nexport const IcTrash = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 20 20\"\n fill=\"none\"\n >\n <path\n d=\"M13.75 5.5H17.5V7H16V16.75C16 16.9489 15.921 17.1397 15.7803 17.2803C15.6397 17.421 15.4489 17.5 15.25 17.5H4.75C4.55109 17.5 4.36032 17.421 4.21967 17.2803C4.07902 17.1397 4 16.9489 4 16.75V7H2.5V5.5H6.25V3.25C6.25 3.05109 6.32902 2.86032 6.46967 2.71967C6.61032 2.57902 6.80109 2.5 7 2.5H13C13.1989 2.5 13.3897 2.57902 13.5303 2.71967C13.671 2.86032 13.75 3.05109 13.75 3.25V5.5ZM14.5 7H5.5V16H14.5V7ZM7.75 9.25H9.25V13.75H7.75V9.25ZM10.75 9.25H12.25V13.75H10.75V9.25ZM7.75 4V5.5H12.25V4H7.75Z\"\n fill=\"currentColor\"\n />\n </svg>\n );\n};\n\nexport const IcBuilding = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"20\"\n viewBox=\"0 0 24 20\"\n fill=\"none\"\n >\n <path\n d=\"M21.4502 17.3503H23.5502V19.4503H0.450195V17.3503H2.5502V1.60029C2.5502 1.32182 2.66082 1.05474 2.85773 0.857831C3.05465 0.660918 3.32172 0.550293 3.6002 0.550293H14.1002C14.3787 0.550293 14.6457 0.660918 14.8427 0.857831C15.0396 1.05474 15.1502 1.32182 15.1502 1.60029V17.3503H19.3502V8.95029H17.2502V6.85029H20.4002C20.6787 6.85029 20.9457 6.96092 21.1427 7.15783C21.3396 7.35474 21.4502 7.62182 21.4502 7.90029V17.3503ZM4.6502 2.65029V17.3503H13.0502V2.65029H4.6502ZM6.7502 8.95029H10.9502V11.0503H6.7502V8.95029ZM6.7502 4.75029H10.9502V6.85029H6.7502V4.75029Z\"\n fill=\"currentColor\"\n />\n </svg>\n );\n};\n\nexport const FileListFillIcon = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"12\"\n height=\"12\"\n viewBox=\"0 0 12 12\"\n fill=\"none\"\n >\n <path\n d=\"M10.7996 12H1.19961C1.04048 12 0.887867 11.9368 0.775345 11.8243C0.662823 11.7117 0.599609 11.5591 0.599609 11.4V0.6C0.599609 0.44087 0.662823 0.288258 0.775345 0.175736C0.887867 0.0632141 1.04048 0 1.19961 0H10.7996C10.9587 0 11.1114 0.0632141 11.2239 0.175736C11.3364 0.288258 11.3996 0.44087 11.3996 0.6V11.4C11.3996 11.5591 11.3364 11.7117 11.2239 11.8243C11.1114 11.9368 10.9587 12 10.7996 12ZM3.59961 3V4.2H8.39961V3H3.59961ZM3.59961 5.4V6.6H8.39961V5.4H3.59961ZM3.59961 7.8V9H8.39961V7.8H3.59961Z\"\n fill=\"#363793\"\n />\n </svg>\n );\n};\n\nexport const CheckBoxStick = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"18\"\n height=\"18\"\n viewBox=\"0 0 18 18\"\n fill=\"none\"\n >\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M4.00033 0.666016C2.15938 0.666016 0.666992 2.1584 0.666992 3.99935V13.9993C0.666992 15.8403 2.15938 17.3327 4.00033 17.3327H14.0003C15.8413 17.3327 17.3337 15.8403 17.3337 13.9993V3.99935C17.3337 2.1584 15.8413 0.666016 14.0003 0.666016H4.00033ZM12.9841 6.2002C12.7402 5.95597 12.3446 5.95538 12.1003 6.19922L7.8171 10.4746L5.90108 8.55762C5.657 8.31354 5.26039 8.31354 5.01632 8.55762C4.77242 8.80155 4.77271 9.1973 5.01632 9.44141L7.37472 11.7998C7.6186 12.0437 8.01435 12.0444 8.2585 11.8008L12.9831 7.08398C13.2274 6.84012 13.228 6.44449 12.9841 6.2002Z\"\n fill=\"#35ADE9\"\n />\n </svg>\n );\n};\n\nexport const IcNotification = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"15\"\n height=\"16\"\n viewBox=\"0 0 15 16\"\n fill=\"none\"\n >\n <path\n d=\"M9.25 14.75V15.25H5.75V14.75H9.25ZM7.5 0.5C8.95869 0.5 10.3572 1.07988 11.3887 2.11133C12.4201 3.14278 13 4.54131 13 6V11.75H14.5V12.25H0.5V11.75H2V6C2 4.54131 2.57988 3.14278 3.61133 2.11133C4.64278 1.07988 6.04131 0.5 7.5 0.5ZM7.5 1C6.17392 1 4.90253 1.52716 3.96484 2.46484C3.02716 3.40253 2.5 4.67392 2.5 6V11.75H12.5V6C12.5 4.67392 11.9728 3.40253 11.0352 2.46484C10.0975 1.52716 8.82608 1 7.5 1Z\"\n fill=\"#060606\"\n stroke=\"currentColor\"\n />\n </svg>\n );\n};\n\nexport const IcCopy = () => {\n return (\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M7.39992 15.1663H4.59992C1.99325 15.1663 0.833252 14.0063 0.833252 11.3997V8.59967C0.833252 5.99301 1.99325 4.83301 4.59992 4.83301H7.39992C10.0066 4.83301 11.1666 5.99301 11.1666 8.59967V11.3997C11.1666 14.0063 10.0066 15.1663 7.39992 15.1663ZM4.59992 5.83301C2.53325 5.83301 1.83325 6.53301 1.83325 8.59967V11.3997C1.83325 13.4663 2.53325 14.1663 4.59992 14.1663H7.39992C9.46659 14.1663 10.1666 13.4663 10.1666 11.3997V8.59967C10.1666 6.53301 9.46659 5.83301 7.39992 5.83301H4.59992Z\"\n fill=\"#1F1F1F\"\n />\n <path\n d=\"M11.3999 11.1663H10.6666C10.3933 11.1663 10.1666 10.9397 10.1666 10.6663V8.59967C10.1666 6.53301 9.46659 5.83301 7.39992 5.83301H5.33325C5.05992 5.83301 4.83325 5.60634 4.83325 5.33301V4.59967C4.83325 1.99301 5.99325 0.833008 8.59992 0.833008H11.3999C14.0066 0.833008 15.1666 1.99301 15.1666 4.59967V7.39967C15.1666 10.0063 14.0066 11.1663 11.3999 11.1663ZM11.1666 10.1663H11.3999C13.4666 10.1663 14.1666 9.46634 14.1666 7.39967V4.59967C14.1666 2.53301 13.4666 1.83301 11.3999 1.83301H8.59992C6.53325 1.83301 5.83325 2.53301 5.83325 4.59967V4.83301H7.39992C10.0066 4.83301 11.1666 5.99301 11.1666 8.59967V10.1663Z\"\n fill=\"#1F1F1F\"\n />\n </svg>\n );\n};\n\nexport const IcThreeDots = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 20 20\"\n fill=\"none\"\n >\n <path\n d=\"M10 3.25C9.175 3.25 8.5 3.925 8.5 4.75C8.5 5.575 9.175 6.25 10 6.25C10.825 6.25 11.5 5.575 11.5 4.75C11.5 3.925 10.825 3.25 10 3.25ZM10 13.75C9.175 13.75 8.5 14.425 8.5 15.25C8.5 16.075 9.175 16.75 10 16.75C10.825 16.75 11.5 16.075 11.5 15.25C11.5 14.425 10.825 13.75 10 13.75ZM10 8.5C9.175 8.5 8.5 9.175 8.5 10C8.5 10.825 9.175 11.5 10 11.5C10.825 11.5 11.5 10.825 11.5 10C11.5 9.175 10.825 8.5 10 8.5Z\"\n fill=\"#060606\"\n />\n </svg>\n );\n};\n\nexport const IcDot = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"3\"\n height=\"3\"\n viewBox=\"0 0 3 3\"\n fill=\"none\"\n >\n <circle cx=\"1.5\" cy=\"1.5\" r=\"1.5\" fill=\"#060606\" />\n </svg>\n );\n};\n\nexport const IcCheckFill = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n >\n <path\n d=\"M6.79985 9.90252L12.315 4.38672L13.164 5.23512L6.79985 11.5993L2.98145 7.78092L3.82985 6.93252L6.79985 9.90252Z\"\n fill=\"#060606\"\n />\n </svg>\n );\n};\n\nexport const IcCloseCircleFill = () => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"15\"\n height=\"15\"\n viewBox=\"0 0 15 15\"\n fill=\"none\"\n >\n <path\n d=\"M7.5 15C3.35775 15 0 11.6423 0 7.5C0 3.35775 3.35775 0 7.5 0C11.6423 0 15 3.35775 15 7.5C15 11.6423 11.6423 15 7.5 15ZM7.5 6.4395L5.379 4.31775L4.31775 5.379L6.4395 7.5L4.31775 9.621L5.379 10.6823L7.5 8.5605L9.621 10.6823L10.6823 9.621L8.5605 7.5L10.6823 5.379L9.621 4.31775L7.5 6.4395Z\"\n fill=\"#FB2B3D\"\n />\n </svg>\n);\n","export const IcQR = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 20 20\"\n fill=\"none\"\n >\n <path\n d=\"M13 13.75V13H10.75V10.75H13V12.25H14.5V13.75H13.75V15.25H12.25V16.75H10.75V14.5H12.25V13.75H13ZM16.75 16.75H13.75V15.25H15.25V13.75H16.75V16.75ZM3.25 3.25H9.25V9.25H3.25V3.25ZM4.75 4.75V7.75H7.75V4.75H4.75ZM10.75 3.25H16.75V9.25H10.75V3.25ZM12.25 4.75V7.75H15.25V4.75H12.25ZM3.25 10.75H9.25V16.75H3.25V10.75ZM4.75 12.25V15.25H7.75V12.25H4.75ZM14.5 10.75H16.75V12.25H14.5V10.75ZM5.5 5.5H7V7H5.5V5.5ZM5.5 13H7V14.5H5.5V13ZM13 5.5H14.5V7H13V5.5Z\"\n fill=\"#060606\"\n />\n </svg>\n );\n};\n\nexport const IcCheck = ({ className }: { className?: string }) => {\n return (\n <svg\n stroke=\"currentColor\"\n fill=\"currentColor\"\n strokeWidth=\"0\"\n viewBox=\"0 0 512 512\"\n height=\"1em\"\n width=\"1em\"\n xmlns=\"http://www.w3.org/2000/svg\"\n className={`${className}`}\n >\n <path\n fill=\"none\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth=\"32\"\n d=\"M416 128 192 384l-96-96\"\n ></path>\n </svg>\n );\n};\n","import { IcCopy } from \"@assets/icons/common\";\nimport { IcCheck, IcQR } from \"@assets/icons/emenu-icon\";\nimport { copyLinkButtonController } from \"@fctc/widget-logic/widget\";\nimport { QRCodeSVG } from \"qrcode.react\";\nimport { useState } from \"react\";\nimport { useTranslation } from \"react-i18next\";\nimport ModalZoom from \"../common/modal/modal-zoom\";\nimport { usePosAppProvider } from \"@provider/app-provider\";\n\nconst EMenuLink = (props: any) => {\n const { formValues, pos_slug_key, value } = props;\n const { t } = useTranslation();\n const { user } = usePosAppProvider();\n const [isOpenQr, setIsOpenQr] = useState(false);\n const dataUser = user?.userProfile?.data;\n\n const eMenuLink = `${value}/${dataUser?.short_name}/${formValues?.[pos_slug_key]}`;\n\n const { handleCopyToClipboard, isCopied } = copyLinkButtonController({\n value: eMenuLink,\n defaultValue: eMenuLink,\n });\n\n return (\n <div className=\"flex items-center justify-center gap-2\">\n <div className=\"border border-stroke-disabled rounded-lg flex max-w-[400px]\">\n <span className=\"p-[10px] border-r border-stroke-disabled text-sm font-medium text-tertiary truncate line-clamp-1 \">\n {eMenuLink}\n </span>\n <button\n className=\"cursor-pointer p-[12px]\"\n type=\"button\"\n onClick={() => handleCopyToClipboard(eMenuLink as string)}\n >\n {isCopied ? <IcCheck /> : <IcCopy />}\n </button>\n </div>\n <button\n type=\"button\"\n onClick={() => setIsOpenQr(!isOpenQr)}\n className=\"p-[10px] border border-stroke-disabled rounded-xl\"\n >\n <IcQR />\n </button>\n <ModalZoom\n isOpen={isOpenQr}\n onClose={() => setIsOpenQr(!isOpenQr)}\n title={t(\"qr_e_menu\")}\n className=\"\"\n >\n {eMenuLink && (\n <div className=\"flex flex-col items-center gap-6\">\n <QRCodeSVG\n value={eMenuLink}\n size={220}\n bgColor={\"#ffffff\"}\n fgColor={\"#000000\"}\n level={\"L\"}\n />\n </div>\n )}\n </ModalZoom>\n </div>\n );\n};\n\nexport default EMenuLink;\n","var __defProp = Object.defineProperty;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __objRest = (source, exclude) => {\n var target = {};\n for (var prop in source)\n if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)\n target[prop] = source[prop];\n if (source != null && __getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(source)) {\n if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))\n target[prop] = source[prop];\n }\n return target;\n};\n\n// src/index.tsx\nimport React from \"react\";\n\n// src/third-party/qrcodegen/index.ts\n/**\n * @license QR Code generator library (TypeScript)\n * Copyright (c) Project Nayuki.\n * SPDX-License-Identifier: MIT\n */\nvar qrcodegen;\n((qrcodegen2) => {\n const _QrCode = class _QrCode {\n /*-- Constructor (low level) and fields --*/\n // Creates a new QR Code with the given version number,\n // error correction level, data codeword bytes, and mask number.\n // This is a low-level API that most users should not use directly.\n // A mid-level API is the encodeSegments() function.\n constructor(version, errorCorrectionLevel, dataCodewords, msk) {\n this.version = version;\n this.errorCorrectionLevel = errorCorrectionLevel;\n // The modules of this QR Code (false = light, true = dark).\n // Immutable after constructor finishes. Accessed through getModule().\n this.modules = [];\n // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.\n this.isFunction = [];\n if (version < _QrCode.MIN_VERSION || version > _QrCode.MAX_VERSION)\n throw new RangeError(\"Version value out of range\");\n if (msk < -1 || msk > 7)\n throw new RangeError(\"Mask value out of range\");\n this.size = version * 4 + 17;\n let row = [];\n for (let i = 0; i < this.size; i++)\n row.push(false);\n for (let i = 0; i < this.size; i++) {\n this.modules.push(row.slice());\n this.isFunction.push(row.slice());\n }\n this.drawFunctionPatterns();\n const allCodewords = this.addEccAndInterleave(dataCodewords);\n this.drawCodewords(allCodewords);\n if (msk == -1) {\n let minPenalty = 1e9;\n for (let i = 0; i < 8; i++) {\n this.applyMask(i);\n this.drawFormatBits(i);\n const penalty = this.getPenaltyScore();\n if (penalty < minPenalty) {\n msk = i;\n minPenalty = penalty;\n }\n this.applyMask(i);\n }\n }\n assert(0 <= msk && msk <= 7);\n this.mask = msk;\n this.applyMask(msk);\n this.drawFormatBits(msk);\n this.isFunction = [];\n }\n /*-- Static factory functions (high level) --*/\n // Returns a QR Code representing the given Unicode text string at the given error correction level.\n // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer\n // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible\n // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the\n // ecl argument if it can be done without increasing the version.\n static encodeText(text, ecl) {\n const segs = qrcodegen2.QrSegment.makeSegments(text);\n return _QrCode.encodeSegments(segs, ecl);\n }\n // Returns a QR Code representing the given binary data at the given error correction level.\n // This function always encodes using the binary segment mode, not any text mode. The maximum number of\n // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.\n // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.\n static encodeBinary(data, ecl) {\n const seg = qrcodegen2.QrSegment.makeBytes(data);\n return _QrCode.encodeSegments([seg], ecl);\n }\n /*-- Static factory functions (mid level) --*/\n // Returns a QR Code representing the given segments with the given encoding parameters.\n // The smallest possible QR Code version within the given range is automatically\n // chosen for the output. Iff boostEcl is true, then the ECC level of the result\n // may be higher than the ecl argument if it can be done without increasing the\n // version. The mask number is either between 0 to 7 (inclusive) to force that\n // mask, or -1 to automatically choose an appropriate mask (which may be slow).\n // This function allows the user to create a custom sequence of segments that switches\n // between modes (such as alphanumeric and byte) to encode text in less space.\n // This is a mid-level API; the high-level API is encodeText() and encodeBinary().\n static encodeSegments(segs, ecl, minVersion = 1, maxVersion = 40, mask = -1, boostEcl = true) {\n if (!(_QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= _QrCode.MAX_VERSION) || mask < -1 || mask > 7)\n throw new RangeError(\"Invalid value\");\n let version;\n let dataUsedBits;\n for (version = minVersion; ; version++) {\n const dataCapacityBits2 = _QrCode.getNumDataCodewords(version, ecl) * 8;\n const usedBits = QrSegment.getTotalBits(segs, version);\n if (usedBits <= dataCapacityBits2) {\n dataUsedBits = usedBits;\n break;\n }\n if (version >= maxVersion)\n throw new RangeError(\"Data too long\");\n }\n for (const newEcl of [_QrCode.Ecc.MEDIUM, _QrCode.Ecc.QUARTILE, _QrCode.Ecc.HIGH]) {\n if (boostEcl && dataUsedBits <= _QrCode.getNumDataCodewords(version, newEcl) * 8)\n ecl = newEcl;\n }\n let bb = [];\n for (const seg of segs) {\n appendBits(seg.mode.modeBits, 4, bb);\n appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);\n for (const b of seg.getData())\n bb.push(b);\n }\n assert(bb.length == dataUsedBits);\n const dataCapacityBits = _QrCode.getNumDataCodewords(version, ecl) * 8;\n assert(bb.length <= dataCapacityBits);\n appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);\n appendBits(0, (8 - bb.length % 8) % 8, bb);\n assert(bb.length % 8 == 0);\n for (let padByte = 236; bb.length < dataCapacityBits; padByte ^= 236 ^ 17)\n appendBits(padByte, 8, bb);\n let dataCodewords = [];\n while (dataCodewords.length * 8 < bb.length)\n dataCodewords.push(0);\n bb.forEach((b, i) => dataCodewords[i >>> 3] |= b << 7 - (i & 7));\n return new _QrCode(version, ecl, dataCodewords, mask);\n }\n /*-- Accessor methods --*/\n // Returns the color of the module (pixel) at the given coordinates, which is false\n // for light or true for dark. The top left corner has the coordinates (x=0, y=0).\n // If the given coordinates are out of bounds, then false (light) is returned.\n getModule(x, y) {\n return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];\n }\n // Modified to expose modules for easy access\n getModules() {\n return this.modules;\n }\n /*-- Private helper methods for constructor: Drawing function modules --*/\n // Reads this object's version field, and draws and marks all function modules.\n drawFunctionPatterns() {\n for (let i = 0; i < this.size; i++) {\n this.setFunctionModule(6, i, i % 2 == 0);\n this.setFunctionModule(i, 6, i % 2 == 0);\n }\n this.drawFinderPattern(3, 3);\n this.drawFinderPattern(this.size - 4, 3);\n this.drawFinderPattern(3, this.size - 4);\n const alignPatPos = this.getAlignmentPatternPositions();\n const numAlign = alignPatPos.length;\n for (let i = 0; i < numAlign; i++) {\n for (let j = 0; j < numAlign; j++) {\n if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0))\n this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);\n }\n }\n this.drawFormatBits(0);\n this.drawVersion();\n }\n // Draws two copies of the format bits (with its own error correction code)\n // based on the given mask and this object's error correction level field.\n drawFormatBits(mask) {\n const data = this.errorCorrectionLevel.formatBits << 3 | mask;\n let rem = data;\n for (let i = 0; i < 10; i++)\n rem = rem << 1 ^ (rem >>> 9) * 1335;\n const bits = (data << 10 | rem) ^ 21522;\n assert(bits >>> 15 == 0);\n for (let i = 0; i <= 5; i++)\n this.setFunctionModule(8, i, getBit(bits, i));\n this.setFunctionModule(8, 7, getBit(bits, 6));\n this.setFunctionModule(8, 8, getBit(bits, 7));\n this.setFunctionModule(7, 8, getBit(bits, 8));\n for (let i = 9; i < 15; i++)\n this.setFunctionModule(14 - i, 8, getBit(bits, i));\n for (let i = 0; i < 8; i++)\n this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));\n for (let i = 8; i < 15; i++)\n this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));\n this.setFunctionModule(8, this.size - 8, true);\n }\n // Draws two copies of the version bits (with its own error correction code),\n // based on this object's version field, iff 7 <= version <= 40.\n drawVersion() {\n if (this.version < 7)\n return;\n let rem = this.version;\n for (let i = 0; i < 12; i++)\n rem = rem << 1 ^ (rem >>> 11) * 7973;\n const bits = this.version << 12 | rem;\n assert(bits >>> 18 == 0);\n for (let i = 0; i < 18; i++) {\n const color = getBit(bits, i);\n const a = this.size - 11 + i % 3;\n const b = Math.floor(i / 3);\n this.setFunctionModule(a, b, color);\n this.setFunctionModule(b, a, color);\n }\n }\n // Draws a 9*9 finder pattern including the border separator,\n // with the center module at (x, y). Modules can be out of bounds.\n drawFinderPattern(x, y) {\n for (let dy = -4; dy <= 4; dy++) {\n for (let dx = -4; dx <= 4; dx++) {\n const dist = Math.max(Math.abs(dx), Math.abs(dy));\n const xx = x + dx;\n const yy = y + dy;\n if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)\n this.setFunctionModule(xx, yy, dist != 2 && dist != 4);\n }\n }\n }\n // Draws a 5*5 alignment pattern, with the center module\n // at (x, y). All modules must be in bounds.\n drawAlignmentPattern(x, y) {\n for (let dy = -2; dy <= 2; dy++) {\n for (let dx = -2; dx <= 2; dx++)\n this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);\n }\n }\n // Sets the color of a module and marks it as a function module.\n // Only used by the constructor. Coordinates must be in bounds.\n setFunctionModule(x, y, isDark) {\n this.modules[y][x] = isDark;\n this.isFunction[y][x] = true;\n }\n /*-- Private helper methods for constructor: Codewords and masking --*/\n // Returns a new byte string representing the given data with the appropriate error correction\n // codewords appended to it, based on this object's version and error correction level.\n addEccAndInterleave(data) {\n const ver = this.version;\n const ecl = this.errorCorrectionLevel;\n if (data.length != _QrCode.getNumDataCodewords(ver, ecl))\n throw new RangeError(\"Invalid argument\");\n const numBlocks = _QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];\n const blockEccLen = _QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver];\n const rawCodewords = Math.floor(_QrCode.getNumRawDataModules(ver) / 8);\n const numShortBlocks = numBlocks - rawCodewords % numBlocks;\n const shortBlockLen = Math.floor(rawCodewords / numBlocks);\n let blocks = [];\n const rsDiv = _QrCode.reedSolomonComputeDivisor(blockEccLen);\n for (let i = 0, k = 0; i < numBlocks; i++) {\n let dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));\n k += dat.length;\n const ecc = _QrCode.reedSolomonComputeRemainder(dat, rsDiv);\n if (i < numShortBlocks)\n dat.push(0);\n blocks.push(dat.concat(ecc));\n }\n let result = [];\n for (let i = 0; i < blocks[0].length; i++) {\n blocks.forEach((block, j) => {\n if (i != shortBlockLen - blockEccLen || j >= numShortBlocks)\n result.push(block[i]);\n });\n }\n assert(result.length == rawCodewords);\n return result;\n }\n // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire\n // data area of this QR Code. Function modules need to be marked off before this is called.\n drawCodewords(data) {\n if (data.length != Math.floor(_QrCode.getNumRawDataModules(this.version) / 8))\n throw new RangeError(\"Invalid argument\");\n let i = 0;\n for (let right = this.size - 1; right >= 1; right -= 2) {\n if (right == 6)\n right = 5;\n for (let vert = 0; vert < this.size; vert++) {\n for (let j = 0; j < 2; j++) {\n const x = right - j;\n const upward = (right + 1 & 2) == 0;\n const y = upward ? this.size - 1 - vert : vert;\n if (!this.isFunction[y][x] && i < data.length * 8) {\n this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));\n i++;\n }\n }\n }\n }\n assert(i == data.length * 8);\n }\n // XORs the codeword modules in this QR Code with the given mask pattern.\n // The function modules must be marked and the codeword bits must be drawn\n // before masking. Due to the arithmetic of XOR, calling applyMask() with\n // the same mask value a second time will undo the mask. A final well-formed\n // QR Code needs exactly one (not zero, two, etc.) mask applied.\n applyMask(mask) {\n if (mask < 0 || mask > 7)\n throw new RangeError(\"Mask value out of range\");\n for (let y = 0; y < this.size; y++) {\n for (let x = 0; x < this.size; x++) {\n let invert;\n switch (mask) {\n case 0:\n invert = (x + y) % 2 == 0;\n break;\n case 1:\n invert = y % 2 == 0;\n break;\n case 2:\n invert = x % 3 == 0;\n break;\n case 3:\n invert = (x + y) % 3 == 0;\n break;\n case 4:\n invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;\n break;\n case 5:\n invert = x * y % 2 + x * y % 3 == 0;\n break;\n case 6:\n invert = (x * y % 2 + x * y % 3) % 2 == 0;\n break;\n case 7:\n invert = ((x + y) % 2 + x * y % 3) % 2 == 0;\n break;\n default:\n throw new Error(\"Unreachable\");\n }\n if (!this.isFunction[y][x] && invert)\n this.modules[y][x] = !this.modules[y][x];\n }\n }\n }\n // Calculates and returns the penalty score based on state of this QR Code's current modules.\n // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.\n getPenaltyScore() {\n let result = 0;\n for (let y = 0; y < this.size; y++) {\n let runColor = false;\n let runX = 0;\n let runHistory = [0, 0, 0, 0, 0, 0, 0];\n for (let x = 0; x < this.size; x++) {\n if (this.modules[y][x] == runColor) {\n runX++;\n if (runX == 5)\n result += _QrCode.PENALTY_N1;\n else if (runX > 5)\n result++;\n } else {\n this.finderPenaltyAddHistory(runX, runHistory);\n if (!runColor)\n result += this.finderPenaltyCountPatterns(runHistory) * _QrCode.PENALTY_N3;\n runColor = this.modules[y][x];\n runX = 1;\n }\n }\n result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * _QrCode.PENALTY_N3;\n }\n for (let x = 0; x < this.size; x++) {\n let runColor = false;\n let runY = 0;\n let runHistory = [0, 0, 0, 0, 0, 0, 0];\n for (let y = 0; y < this.size; y++) {\n if (this.modules[y][x] == runColor) {\n runY++;\n if (runY == 5)\n result += _QrCode.PENALTY_N1;\n else if (runY > 5)\n result++;\n } else {\n this.finderPenaltyAddHistory(runY, runHistory);\n if (!runColor)\n result += this.finderPenaltyCountPatterns(runHistory) * _QrCode.PENALTY_N3;\n runColor = this.modules[y][x];\n runY = 1;\n }\n }\n result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * _QrCode.PENALTY_N3;\n }\n for (let y = 0; y < this.size - 1; y++) {\n for (let x = 0; x < this.size - 1; x++) {\n const color = this.modules[y][x];\n if (color == this.modules[y][x + 1] && color == this.modules[y + 1][x] && color == this.modules[y + 1][x + 1])\n result += _QrCode.PENALTY_N2;\n }\n }\n let dark = 0;\n for (const row of this.modules)\n dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark);\n const total = this.size * this.size;\n const k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;\n assert(0 <= k && k <= 9);\n result += k * _QrCode.PENALTY_N4;\n assert(0 <= result && result <= 2568888);\n return result;\n }\n /*-- Private helper functions --*/\n // Returns an ascending list of positions of alignment patterns for this version number.\n // Each position is in the range [0,177), and are used on both the x and y axes.\n // This could be implemented as lookup table of 40 variable-length lists of integers.\n getAlignmentPatternPositions() {\n if (this.version == 1)\n return [];\n else {\n const numAlign = Math.floor(this.version / 7) + 2;\n const step = this.version == 32 ? 26 : Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;\n let result = [6];\n for (let pos = this.size - 7; result.length < numAlign; pos -= step)\n result.splice(1, 0, pos);\n return result;\n }\n }\n // Returns the number of data bits that can be stored in a QR Code of the given version number, after\n // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.\n // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.\n static getNumRawDataModules(ver) {\n if (ver < _QrCode.MIN_VERSION || ver > _QrCode.MAX_VERSION)\n throw new RangeError(\"Version number out of range\");\n let result = (16 * ver + 128) * ver + 64;\n if (ver >= 2) {\n const numAlign = Math.floor(ver / 7) + 2;\n result -= (25 * numAlign - 10) * numAlign - 55;\n if (ver >= 7)\n result -= 36;\n }\n assert(208 <= result && result <= 29648);\n return result;\n }\n // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any\n // QR Code of the given version number and error correction level, with remainder bits discarded.\n // This stateless pure function could be implemented as a (40*4)-cell lookup table.\n static getNumDataCodewords(ver, ecl) {\n return Math.floor(_QrCode.getNumRawDataModules(ver) / 8) - _QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] * _QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];\n }\n // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be\n // implemented as a lookup table over all possible parameter values, instead of as an algorithm.\n static reedSolomonComputeDivisor(degree) {\n if (degree < 1 || degree > 255)\n throw new RangeError(\"Degree out of range\");\n let result = [];\n for (let i = 0; i < degree - 1; i++)\n result.push(0);\n result.push(1);\n let root = 1;\n for (let i = 0; i < degree; i++) {\n for (let j = 0; j < result.length; j++) {\n result[j] = _QrCode.reedSolomonMultiply(result[j], root);\n if (j + 1 < result.length)\n result[j] ^= result[j + 1];\n }\n root = _QrCode.reedSolomonMultiply(root, 2);\n }\n return result;\n }\n // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.\n static reedSolomonComputeRemainder(data, divisor) {\n let result = divisor.map((_) => 0);\n for (const b of data) {\n const factor = b ^ result.shift();\n result.push(0);\n divisor.forEach((coef, i) => result[i] ^= _QrCode.reedSolomonMultiply(coef, factor));\n }\n return result;\n }\n // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result\n // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.\n static reedSolomonMultiply(x, y) {\n if (x >>> 8 != 0 || y >>> 8 != 0)\n throw new RangeError(\"Byte out of range\");\n let z = 0;\n for (let i = 7; i >= 0; i--) {\n z = z << 1 ^ (z >>> 7) * 285;\n z ^= (y >>> i & 1) * x;\n }\n assert(z >>> 8 == 0);\n return z;\n }\n // Can only be called immediately after a light run is added, and\n // returns either 0, 1, or 2. A helper function for getPenaltyScore().\n finderPenaltyCountPatterns(runHistory) {\n const n = runHistory[1];\n assert(n <= this.size * 3);\n const core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n;\n return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0);\n }\n // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().\n finderPenaltyTerminateAndCount(currentRunColor, currentRunLength, runHistory) {\n if (currentRunColor) {\n this.finderPenaltyAddHistory(currentRunLength, runHistory);\n currentRunLength = 0;\n }\n currentRunLength += this.size;\n this.finderPenaltyAddHistory(currentRunLength, runHistory);\n return this.finderPenaltyCountPatterns(runHistory);\n }\n // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().\n finderPenaltyAddHistory(currentRunLength, runHistory) {\n if (runHistory[0] == 0)\n currentRunLength += this.size;\n runHistory.pop();\n runHistory.unshift(currentRunLength);\n }\n };\n /*-- Constants and tables --*/\n // The minimum version number supported in the QR Code Model 2 standard.\n _QrCode.MIN_VERSION = 1;\n // The maximum version number supported in the QR Code Model 2 standard.\n _QrCode.MAX_VERSION = 40;\n // For use in getPenaltyScore(), when evaluating which mask is best.\n _QrCode.PENALTY_N1 = 3;\n _QrCode.PENALTY_N2 = 3;\n _QrCode.PENALTY_N3 = 40;\n _QrCode.PENALTY_N4 = 10;\n _QrCode.ECC_CODEWORDS_PER_BLOCK = [\n // Version: (note that index 0 is for padding, and is set to an illegal value)\n //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level\n [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],\n // Low\n [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28],\n // Medium\n [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],\n // Quartile\n [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30]\n // High\n ];\n _QrCode.NUM_ERROR_CORRECTION_BLOCKS = [\n // Version: (note that index 0 is for padding, and is set to an illegal value)\n //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level\n [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25],\n // Low\n [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49],\n // Medium\n [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68],\n // Quartile\n [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81]\n // High\n ];\n let QrCode = _QrCode;\n qrcodegen2.QrCode = _QrCode;\n function appendBits(val, len, bb) {\n if (len < 0 || len > 31 || val >>> len != 0)\n throw new RangeError(\"Value out of range\");\n for (let i = len - 1; i >= 0; i--)\n bb.push(val >>> i & 1);\n }\n function getBit(x, i) {\n return (x >>> i & 1) != 0;\n }\n function assert(cond) {\n if (!cond)\n throw new Error(\"Assertion error\");\n }\n const _QrSegment = class _QrSegment {\n /*-- Constructor (low level) and fields --*/\n // Creates a new QR Code segment with the given attributes and data.\n // The character count (numChars) must agree with the mode and the bit buffer length,\n // but the constraint isn't checked. The given bit buffer is cloned and stored.\n constructor(mode, numChars, bitData) {\n this.mode = mode;\n this.numChars = numChars;\n this.bitData = bitData;\n if (numChars < 0)\n throw new RangeError(\"Invalid argument\");\n this.bitData = bitData.slice();\n }\n /*-- Static factory functions (mid level) --*/\n // Returns a segment representing the given binary data encoded in\n // byte mode. All input byte arrays are acceptable. Any text string\n // can be converted to UTF-8 bytes and encoded as a byte mode segment.\n static makeBytes(data) {\n let bb = [];\n for (const b of data)\n appendBits(b, 8, bb);\n return new _QrSegment(_QrSegment.Mode.BYTE, data.length, bb);\n }\n // Returns a segment representing the given string of decimal digits encoded in numeric mode.\n static makeNumeric(digits) {\n if (!_QrSegment.isNumeric(digits))\n throw new RangeError(\"String contains non-numeric characters\");\n let bb = [];\n for (let i = 0; i < digits.length; ) {\n const n = Math.min(digits.length - i, 3);\n appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);\n i += n;\n }\n return new _QrSegment(_QrSegment.Mode.NUMERIC, digits.length, bb);\n }\n // Returns a segment representing the given text string encoded in alphanumeric mode.\n // The characters allowed are: 0 to 9, A to Z (uppercase only), space,\n // dollar, percent, asterisk, plus, hyphen, period, slash, colon.\n static makeAlphanumeric(text) {\n if (!_QrSegment.isAlphanumeric(text))\n throw new RangeError(\"String contains unencodable characters in alphanumeric mode\");\n let bb = [];\n let i;\n for (i = 0; i + 2 <= text.length; i += 2) {\n let temp = _QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;\n temp += _QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));\n appendBits(temp, 11, bb);\n }\n if (i < text.length)\n appendBits(_QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);\n return new _QrSegment(_QrSegment.Mode.ALPHANUMERIC, text.length, bb);\n }\n // Returns a new mutable list of zero or more segments to represent the given Unicode text string.\n // The result may use various segment modes and switch modes to optimize the length of the bit stream.\n static makeSegments(text) {\n if (text == \"\")\n return [];\n else if (_QrSegment.isNumeric(text))\n return [_QrSegment.makeNumeric(text)];\n else if (_QrSegment.isAlphanumeric(text))\n return [_QrSegment.makeAlphanumeric(text)];\n else\n return [_QrSegment.makeBytes(_QrSegment.toUtf8ByteArray(text))];\n }\n // Returns a segment representing an Extended Channel Interpretation\n // (ECI) designator with the given assignment value.\n static makeEci(assignVal) {\n let bb = [];\n if (assignVal < 0)\n throw new RangeError(\"ECI assignment value out of range\");\n else if (assignVal < 1 << 7)\n appendBits(assignVal, 8, bb);\n else if (assignVal < 1 << 14) {\n appendBits(2, 2, bb);\n appendBits(assignVal, 14, bb);\n } else if (assignVal < 1e6) {\n appendBits(6, 3, bb);\n appendBits(assignVal, 21, bb);\n } else\n throw new RangeError(\"ECI assignment value out of range\");\n return new _QrSegment(_QrSegment.Mode.ECI, 0, bb);\n }\n // Tests whether the given string can be encoded as a segment in numeric mode.\n // A string is encodable iff each character is in the range 0 to 9.\n static isNumeric(text) {\n return _QrSegment.NUMERIC_REGEX.test(text);\n }\n // Tests whether the given string can be encoded as a segment in alphanumeric mode.\n // A string is encodable iff each character is in the following set: 0 to 9, A to Z\n // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.\n static isAlphanumeric(text) {\n return _QrSegment.ALPHANUMERIC_REGEX.test(text);\n }\n /*-- Methods --*/\n // Returns a new copy of the data bits of this segment.\n getData() {\n return this.bitData.slice();\n }\n // (Package-private) Calculates and returns the number of bits needed to encode the given segments at\n // the given version. The result is infinity if a segment has too many characters to fit its length field.\n static getTotalBits(segs, version) {\n let result = 0;\n for (const seg of segs) {\n const ccbits = seg.mode.numCharCountBits(version);\n if (seg.numChars >= 1 << ccbits)\n return Infinity;\n result += 4 + ccbits + seg.bitData.length;\n }\n return result;\n }\n // Returns a new array of bytes representing the given string encoded in UTF-8.\n static toUtf8ByteArray(str) {\n str = encodeURI(str);\n let result = [];\n for (let i = 0; i < str.length; i++) {\n if (str.charAt(i) != \"%\")\n result.push(str.charCodeAt(i));\n else {\n result.push(parseInt(str.substring(i + 1, i + 3), 16));\n i += 2;\n }\n }\n return result;\n }\n };\n /*-- Constants --*/\n // Describes precisely all strings that are encodable in numeric mode.\n _QrSegment.NUMERIC_REGEX = /^[0-9]*$/;\n // Describes precisely all strings that are encodable in alphanumeric mode.\n _QrSegment.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\\/:-]*$/;\n // The set of all legal characters in alphanumeric mode,\n // where each character value maps to the index in the string.\n _QrSegment.ALPHANUMERIC_CHARSET = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:\";\n let QrSegment = _QrSegment;\n qrcodegen2.QrSegment = _QrSegment;\n})(qrcodegen || (qrcodegen = {}));\n((qrcodegen2) => {\n let QrCode;\n ((QrCode2) => {\n const _Ecc = class _Ecc {\n // The QR Code can tolerate about 30% erroneous codewords\n /*-- Constructor and fields --*/\n constructor(ordinal, formatBits) {\n this.ordinal = ordinal;\n this.formatBits = formatBits;\n }\n };\n /*-- Constants --*/\n _Ecc.LOW = new _Ecc(0, 1);\n // The QR Code can tolerate about 7% erroneous codewords\n _Ecc.MEDIUM = new _Ecc(1, 0);\n // The QR Code can tolerate about 15% erroneous codewords\n _Ecc.QUARTILE = new _Ecc(2, 3);\n // The QR Code can tolerate about 25% erroneous codewords\n _Ecc.HIGH = new _Ecc(3, 2);\n let Ecc = _Ecc;\n QrCode2.Ecc = _Ecc;\n })(QrCode = qrcodegen2.QrCode || (qrcodegen2.QrCode = {}));\n})(qrcodegen || (qrcodegen = {}));\n((qrcodegen2) => {\n let QrSegment;\n ((QrSegment2) => {\n const _Mode = class _Mode {\n /*-- Constructor and fields --*/\n constructor(modeBits, numBitsCharCount) {\n this.modeBits = modeBits;\n this.numBitsCharCount = numBitsCharCount;\n }\n /*-- Method --*/\n // (Package-private) Returns the bit width of the character count field for a segment in\n // this mode in a QR Code at the given version number. The result is in the range [0, 16].\n numCharCountBits(ver) {\n return this.numBitsCharCount[Math.floor((ver + 7) / 17)];\n }\n };\n /*-- Constants --*/\n _Mode.NUMERIC = new _Mode(1, [10, 12, 14]);\n _Mode.ALPHANUMERIC = new _Mode(2, [9, 11, 13]);\n _Mode.BYTE = new _Mode(4, [8, 16, 16]);\n _Mode.KANJI = new _Mode(8, [8, 10, 12]);\n _Mode.ECI = new _Mode(7, [0, 0, 0]);\n let Mode = _Mode;\n QrSegment2.Mode = _Mode;\n })(QrSegment = qrcodegen2.QrSegment || (qrcodegen2.QrSegment = {}));\n})(qrcodegen || (qrcodegen = {}));\nvar qrcodegen_default = qrcodegen;\n\n// src/index.tsx\n/**\n * @license qrcode.react\n * Copyright (c) Paul O'Shannessy\n * SPDX-License-Identifier: ISC\n */\nvar ERROR_LEVEL_MAP = {\n L: qrcodegen_default.QrCode.Ecc.LOW,\n M: qrcodegen_default.QrCode.Ecc.MEDIUM,\n Q: qrcodegen_default.QrCode.Ecc.QUARTILE,\n H: qrcodegen_default.QrCode.Ecc.HIGH\n};\nvar DEFAULT_SIZE = 128;\nvar DEFAULT_LEVEL = \"L\";\nvar DEFAULT_BGCOLOR = \"#FFFFFF\";\nvar DEFAULT_FGCOLOR = \"#000000\";\nvar DEFAULT_INCLUDEMARGIN = false;\nvar DEFAULT_MINVERSION = 1;\nvar SPEC_MARGIN_SIZE = 4;\nvar DEFAULT_MARGIN_SIZE = 0;\nvar DEFAULT_IMG_SCALE = 0.1;\nfunction generatePath(modules, margin = 0) {\n const ops = [];\n modules.forEach(function(row, y) {\n let start = null;\n row.forEach(function(cell, x) {\n if (!cell && start !== null) {\n ops.push(\n `M${start + margin} ${y + margin}h${x - start}v1H${start + margin}z`\n );\n start = null;\n return;\n }\n if (x === row.length - 1) {\n if (!cell) {\n return;\n }\n if (start === null) {\n ops.push(`M${x + margin},${y + margin} h1v1H${x + margin}z`);\n } else {\n ops.push(\n `M${start + margin},${y + margin} h${x + 1 - start}v1H${start + margin}z`\n );\n }\n return;\n }\n if (cell && start === null) {\n start = x;\n }\n });\n });\n return ops.join(\"\");\n}\nfunction excavateModules(modules, excavation) {\n return modules.slice().map((row, y) => {\n if (y < excavation.y || y >= excavation.y + excavation.h) {\n return row;\n }\n return row.map((cell, x) => {\n if (x < excavation.x || x >= excavation.x + excavation.w) {\n return cell;\n }\n return false;\n });\n });\n}\nfunction getImageSettings(cells, size, margin, imageSettings) {\n if (imageSettings == null) {\n return null;\n }\n const numCells = cells.length + margin * 2;\n const defaultSize = Math.floor(size * DEFAULT_IMG_SCALE);\n const scale = numCells / size;\n const w = (imageSettings.width || defaultSize) * scale;\n const h = (imageSettings.height || defaultSize) * scale;\n const x = imageSettings.x == null ? cells.length / 2 - w / 2 : imageSettings.x * scale;\n const y = imageSettings.y == null ? cells.length / 2 - h / 2 : imageSettings.y * scale;\n const opacity = imageSettings.opacity == null ? 1 : imageSettings.opacity;\n let excavation = null;\n if (imageSettings.excavate) {\n let floorX = Math.floor(x);\n let floorY = Math.floor(y);\n let ceilW = Math.ceil(w + x - floorX);\n let ceilH = Math.ceil(h + y - floorY);\n excavation = { x: floorX, y: floorY, w: ceilW, h: ceilH };\n }\n const crossOrigin = imageSettings.crossOrigin;\n return { x, y, h, w, excavation, opacity, crossOrigin };\n}\nfunction getMarginSize(includeMargin, marginSize) {\n if (marginSize != null) {\n return Math.max(Math.floor(marginSize), 0);\n }\n return includeMargin ? SPEC_MARGIN_SIZE : DEFAULT_MARGIN_SIZE;\n}\nfunction useQRCode({\n value,\n level,\n minVersion,\n includeMargin,\n marginSize,\n imageSettings,\n size,\n boostLevel\n}) {\n let qrcode = React.useMemo(() => {\n const values = Array.isArray(value) ? value : [value];\n const segments = values.reduce((accum, v) => {\n accum.push(...qrcodegen_default.QrSegment.makeSegments(v));\n return accum;\n }, []);\n return qrcodegen_default.QrCode.encodeSegments(\n segments,\n ERROR_LEVEL_MAP[level],\n minVersion,\n void 0,\n void 0,\n boostLevel\n );\n }, [value, level, minVersion, boostLevel]);\n const { cells, margin, numCells, calculatedImageSettings } = React.useMemo(() => {\n let cells2 = qrcode.getModules();\n const margin2 = getMarginSize(includeMargin, marginSize);\n const numCells2 = cells2.length + margin2 * 2;\n const calculatedImageSettings2 = getImageSettings(\n cells2,\n size,\n margin2,\n imageSettings\n );\n return {\n cells: cells2,\n margin: margin2,\n numCells: numCells2,\n calculatedImageSettings: calculatedImageSettings2\n };\n }, [qrcode, size, imageSettings, includeMargin, marginSize]);\n return {\n qrcode,\n margin,\n cells,\n numCells,\n calculatedImageSettings\n };\n}\nvar SUPPORTS_PATH2D = function() {\n try {\n new Path2D().addPath(new Path2D());\n } catch (e) {\n return false;\n }\n return true;\n}();\nvar QRCodeCanvas = React.forwardRef(\n function QRCodeCanvas2(props, forwardedRef) {\n const _a = props, {\n value,\n size = DEFAULT_SIZE,\n level = DEFAULT_LEVEL,\n bgColor = DEFAULT_BGCOLOR,\n fgColor = DEFAULT_FGCOLOR,\n includeMargin = DEFAULT_INCLUDEMARGIN,\n minVersion = DEFAULT_MINVERSION,\n boostLevel,\n marginSize,\n imageSettings\n } = _a, extraProps = __objRest(_a, [\n \"value\",\n \"size\",\n \"level\",\n \"bgColor\",\n \"fgColor\",\n \"includeMargin\",\n \"minVersion\",\n \"boostLevel\",\n \"marginSize\",\n \"imageSettings\"\n ]);\n const _b = extraProps, { style } = _b, otherProps = __objRest(_b, [\"style\"]);\n const imgSrc = imageSettings == null ? void 0 : imageSettings.src;\n const _canvas = React.useRef(null);\n const _image = React.useRef(null);\n const setCanvasRef = React.useCallback(\n (node) => {\n _canvas.current = node;\n if (typeof forwardedRef === \"function\") {\n forwardedRef(node);\n } else if (forwardedRef) {\n forwardedRef.current = node;\n }\n },\n [forwardedRef]\n );\n const [isImgLoaded, setIsImageLoaded] = React.useState(false);\n const { margin, cells, numCells, calculatedImageSettings } = useQRCode({\n value,\n level,\n minVersion,\n boostLevel,\n includeMargin,\n marginSize,\n imageSettings,\n size\n });\n React.useEffect(() => {\n if (_canvas.current != null) {\n const canvas = _canvas.current;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) {\n return;\n }\n let cellsToDraw = cells;\n const image = _image.current;\n const haveImageToRender = calculatedImageSettings != null && image !== null && image.complete && image.naturalHeight !== 0 && image.naturalWidth !== 0;\n if (haveImageToRender) {\n if (calculatedImageSettings.excavation != null) {\n cellsToDraw = excavateModules(\n cells,\n calculatedImageSettings.excavation\n );\n }\n }\n const pixelRatio = window.devicePixelRatio || 1;\n canvas.height = canvas.width = size * pixelRatio;\n const scale = size / numCells * pixelRatio;\n ctx.scale(scale, scale);\n ctx.fillStyle = bgColor;\n ctx.fillRect(0, 0, numCells, numCells);\n ctx.fillStyle = fgColor;\n if (SUPPORTS_PATH2D) {\n ctx.fill(new Path2D(generatePath(cellsToDraw, margin)));\n } else {\n cells.forEach(function(row, rdx) {\n row.forEach(function(cell, cdx) {\n if (cell) {\n ctx.fillRect(cdx + margin, rdx + margin, 1, 1);\n }\n });\n });\n }\n if (calculatedImageSettings) {\n ctx.globalAlpha = calculatedImageSettings.opacity;\n }\n if (haveImageToRender) {\n ctx.drawImage(\n image,\n calculatedImageSettings.x + margin,\n calculatedImageSettings.y + margin,\n calculatedImageSettings.w,\n calculatedImageSettings.h\n );\n }\n }\n });\n React.useEffect(() => {\n setIsImageLoaded(false);\n }, [imgSrc]);\n const canvasStyle = __spreadValues({ height: size, width: size }, style);\n let img = null;\n if (imgSrc != null) {\n img = /* @__PURE__ */ React.createElement(\n \"img\",\n {\n src: imgSrc,\n key: imgSrc,\n style: { display: \"none\" },\n onLoad: () => {\n setIsImageLoaded(true);\n },\n ref: _image,\n crossOrigin: calculatedImageSettings == null ? void 0 : calculatedImageSettings.crossOrigin\n }\n );\n }\n return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(\n \"canvas\",\n __spreadValues({\n style: canvasStyle,\n height: size,\n width: size,\n ref: setCanvasRef,\n role: \"img\"\n }, otherProps)\n ), img);\n }\n);\nQRCodeCanvas.displayName = \"QRCodeCanvas\";\nvar QRCodeSVG = React.forwardRef(\n function QRCodeSVG2(props, forwardedRef) {\n const _a = props, {\n value,\n size = DEFAULT_SIZE,\n level = DEFAULT_LEVEL,\n bgColor = DEFAULT_BGCOLOR,\n fgColor = DEFAULT_FGCOLOR,\n includeMargin = DEFAULT_INCLUDEMARGIN,\n minVersion = DEFAULT_MINVERSION,\n boostLevel,\n title,\n marginSize,\n imageSettings\n } = _a, otherProps = __objRest(_a, [\n \"value\",\n \"size\",\n \"level\",\n \"bgColor\",\n \"fgColor\",\n \"includeMargin\",\n \"minVersion\",\n \"boostLevel\",\n \"title\",\n \"marginSize\",\n \"imageSettings\"\n ]);\n const { margin, cells, numCells, calculatedImageSettings } = useQRCode({\n value,\n level,\n minVersion,\n boostLevel,\n includeMargin,\n marginSize,\n imageSettings,\n size\n });\n let cellsToDraw = cells;\n let image = null;\n if (imageSettings != null && calculatedImageSettings != null) {\n if (calculatedImageSettings.excavation != null) {\n cellsToDraw = excavateModules(\n cells,\n calculatedImageSettings.excavation\n );\n }\n image = /* @__PURE__ */ React.createElement(\n \"image\",\n {\n href: imageSettings.src,\n height: calculatedImageSettings.h,\n width: calculatedImageSettings.w,\n x: calculatedImageSettings.x + margin,\n y: calculatedImageSettings.y + margin,\n preserveAspectRatio: \"none\",\n opacity: calculatedImageSettings.opacity,\n crossOrigin: calculatedImageSettings.crossOrigin\n }\n );\n }\n const fgPath = generatePath(cellsToDraw, margin);\n return /* @__PURE__ */ React.createElement(\n \"svg\",\n __spreadValues({\n height: size,\n width: size,\n viewBox: `0 0 ${numCells} ${numCells}`,\n ref: forwardedRef,\n role: \"img\"\n }, otherProps),\n !!title && /* @__PURE__ */ React.createElement(\"title\", null, title),\n /* @__PURE__ */ React.createElement(\n \"path\",\n {\n fill: bgColor,\n d: `M0,0 h${numCells}v${numCells}H0z`,\n shapeRendering: \"crispEdges\"\n }\n ),\n /* @__PURE__ */ React.createElement(\"path\", { fill: fgColor, d: fgPath, shapeRendering: \"crispEdges\" }),\n image\n );\n }\n);\nQRCodeSVG.displayName = \"QRCodeSVG\";\nexport {\n QRCodeCanvas,\n QRCodeSVG\n};\n","import { useContext } from 'react';\nimport { nodesToString, Trans as TransWithoutContext } from './TransWithoutContext.js';\nimport { getI18n, I18nContext } from './context.js';\nexport { nodesToString };\nexport function Trans({\n children,\n count,\n parent,\n i18nKey,\n context,\n tOptions = {},\n values,\n defaults,\n components,\n ns,\n i18n: i18nFromProps,\n t: tFromProps,\n shouldUnescape,\n ...additionalProps\n}) {\n const {\n i18n: i18nFromContext,\n defaultNS: defaultNSFromContext\n } = useContext(I18nContext) || {};\n const i18n = i18nFromProps || i18nFromContext || getI18n();\n const t = tFromProps || i18n?.t.bind(i18n);\n return TransWithoutContext({\n children,\n count,\n parent,\n i18nKey,\n context,\n tOptions,\n values,\n defaults,\n components,\n ns: ns || t?.ns || defaultNSFromContext || i18n?.options?.defaultNS,\n i18n,\n t: tFromProps,\n shouldUnescape,\n ...additionalProps\n });\n}","import { Fragment, isValidElement, cloneElement, createElement, Children } from 'react';\nimport HTML from 'html-parse-stringify';\nimport { isObject, isString, warn, warnOnce } from './utils.js';\nimport { getDefaults } from './defaults.js';\nimport { getI18n } from './i18nInstance.js';\nconst hasChildren = (node, checkLength) => {\n if (!node) return false;\n const base = node.props?.children ?? node.children;\n if (checkLength) return base.length > 0;\n return !!base;\n};\nconst getChildren = node => {\n if (!node) return [];\n const children = node.props?.children ?? node.children;\n return node.props?.i18nIsDynamicList ? getAsArray(children) : children;\n};\nconst hasValidReactChildren = children => Array.isArray(children) && children.every(isValidElement);\nconst getAsArray = data => Array.isArray(data) ? data : [data];\nconst mergeProps = (source, target) => {\n const newTarget = {\n ...target\n };\n newTarget.props = Object.assign(source.props, target.props);\n return newTarget;\n};\nexport const nodesToString = (children, i18nOptions, i18n, i18nKey) => {\n if (!children) return '';\n let stringNode = '';\n const childrenArray = getAsArray(children);\n const keepArray = i18nOptions?.transSupportBasicHtmlNodes ? i18nOptions.transKeepBasicHtmlNodesFor ?? [] : [];\n childrenArray.forEach((child, childIndex) => {\n if (isString(child)) {\n stringNode += `${child}`;\n return;\n }\n if (isValidElement(child)) {\n const {\n props,\n type\n } = child;\n const childPropsCount = Object.keys(props).length;\n const shouldKeepChild = keepArray.indexOf(type) > -1;\n const childChildren = props.children;\n if (!childChildren && shouldKeepChild && !childPropsCount) {\n stringNode += `<${type}/>`;\n return;\n }\n if (!childChildren && (!shouldKeepChild || childPropsCount) || props.i18nIsDynamicList) {\n stringNode += `<${childIndex}></${childIndex}>`;\n return;\n }\n if (shouldKeepChild && childPropsCount === 1 && isString(childChildren)) {\n stringNode += `<${type}>${childChildren}</${type}>`;\n return;\n }\n const content = nodesToString(childChildren, i18nOptions, i18n, i18nKey);\n stringNode += `<${childIndex}>${content}</${childIndex}>`;\n return;\n }\n if (child === null) {\n warn(i18n, 'TRANS_NULL_VALUE', `Passed in a null value as child`, {\n i18nKey\n });\n return;\n }\n if (isObject(child)) {\n const {\n format,\n ...clone\n } = child;\n const keys = Object.keys(clone);\n if (keys.length === 1) {\n const value = format ? `${keys[0]}, ${format}` : keys[0];\n stringNode += `{{${value}}}`;\n return;\n }\n warn(i18n, 'TRANS_INVALID_OBJ', `Invalid child - Object should only have keys {{ value, format }} (format is optional).`, {\n i18nKey,\n child\n });\n return;\n }\n warn(i18n, 'TRANS_INVALID_VAR', `Passed in a variable like {number} - pass variables for interpolation as full objects like {{number}}.`, {\n i18nKey,\n child\n });\n });\n return stringNode;\n};\nconst renderNodes = (children, knownComponentsMap, targetString, i18n, i18nOptions, combinedTOpts, shouldUnescape) => {\n if (targetString === '') return [];\n const keepArray = i18nOptions.transKeepBasicHtmlNodesFor || [];\n const emptyChildrenButNeedsHandling = targetString && new RegExp(keepArray.map(keep => `<${keep}`).join('|')).test(targetString);\n if (!children && !knownComponentsMap && !emptyChildrenButNeedsHandling && !shouldUnescape) return [targetString];\n const data = knownComponentsMap ?? {};\n const getData = childs => {\n const childrenArray = getAsArray(childs);\n childrenArray.forEach(child => {\n if (isString(child)) return;\n if (hasChildren(child)) getData(getChildren(child));else if (isObject(child) && !isValidElement(child)) Object.assign(data, child);\n });\n };\n getData(children);\n const ast = HTML.parse(`<0>${targetString}</0>`);\n const opts = {\n ...data,\n ...combinedTOpts\n };\n const renderInner = (child, node, rootReactNode) => {\n const childs = getChildren(child);\n const mappedChildren = mapAST(childs, node.children, rootReactNode);\n return hasValidReactChildren(childs) && mappedChildren.length === 0 || child.props?.i18nIsDynamicList ? childs : mappedChildren;\n };\n const pushTranslatedJSX = (child, inner, mem, i, isVoid) => {\n if (child.dummy) {\n child.children = inner;\n mem.push(cloneElement(child, {\n key: i\n }, isVoid ? undefined : inner));\n } else {\n mem.push(...Children.map([child], c => {\n const props = {\n ...c.props\n };\n delete props.i18nIsDynamicList;\n return createElement(c.type, {\n ...props,\n key: i,\n ref: c.props.ref ?? c.ref\n }, isVoid ? null : inner);\n }));\n }\n };\n const mapAST = (reactNode, astNode, rootReactNode) => {\n const reactNodes = getAsArray(reactNode);\n const astNodes = getAsArray(astNode);\n return astNodes.reduce((mem, node, i) => {\n const translationContent = node.children?.[0]?.content && i18n.services.interpolator.interpolate(node.children[0].content, opts, i18n.language);\n if (node.type === 'tag') {\n let tmp = reactNodes[parseInt(node.name, 10)];\n if (!tmp && knownComponentsMap) tmp = knownComponentsMap[node.name];\n if (rootReactNode.length === 1 && !tmp) tmp = rootReactNode[0][node.name];\n if (!tmp) tmp = {};\n const child = Object.keys(node.attrs).length !== 0 ? mergeProps({\n props: node.attrs\n }, tmp) : tmp;\n const isElement = isValidElement(child);\n const isValidTranslationWithChildren = isElement && hasChildren(node, true) && !node.voidElement;\n const isEmptyTransWithHTML = emptyChildrenButNeedsHandling && isObject(child) && child.dummy && !isElement;\n const isKnownComponent = isObject(knownComponentsMap) && Object.hasOwnProperty.call(knownComponentsMap, node.name);\n if (isString(child)) {\n const value = i18n.services.interpolator.interpolate(child, opts, i18n.language);\n mem.push(value);\n } else if (hasChildren(child) || isValidTranslationWithChildren) {\n const inner = renderInner(child, node, rootReactNode);\n pushTranslatedJSX(child, inner, mem, i);\n } else if (isEmptyTransWithHTML) {\n const inner = mapAST(reactNodes, node.children, rootReactNode);\n pushTranslatedJSX(child, inner, mem, i);\n } else if (Number.isNaN(parseFloat(node.name))) {\n if (isKnownComponent) {\n const inner = renderInner(child, node, rootReactNode);\n pushTranslatedJSX(child, inner, mem, i, node.voidElement);\n } else if (i18nOptions.transSupportBasicHtmlNodes && keepArray.indexOf(node.name) > -1) {\n if (node.voidElement) {\n mem.push(createElement(node.name, {\n key: `${node.name}-${i}`\n }));\n } else {\n const inner = mapAST(reactNodes, node.children, rootReactNode);\n mem.push(createElement(node.name, {\n key: `${node.name}-${i}`\n }, inner));\n }\n } else if (node.voidElement) {\n mem.push(`<${node.name} />`);\n } else {\n const inner = mapAST(reactNodes, node.children, rootReactNode);\n mem.push(`<${node.name}>${inner}</${node.name}>`);\n }\n } else if (isObject(child) && !isElement) {\n const content = node.children[0] ? translationContent : null;\n if (content) mem.push(content);\n } else {\n pushTranslatedJSX(child, translationContent, mem, i, node.children.length !== 1 || !translationContent);\n }\n } else if (node.type === 'text') {\n const wrapTextNodes = i18nOptions.transWrapTextNodes;\n const content = shouldUnescape ? i18nOptions.unescape(i18n.services.interpolator.interpolate(node.content, opts, i18n.language)) : i18n.services.interpolator.interpolate(node.content, opts, i18n.language);\n if (wrapTextNodes) {\n mem.push(createElement(wrapTextNodes, {\n key: `${node.name}-${i}`\n }, content));\n } else {\n mem.push(content);\n }\n }\n return mem;\n }, []);\n };\n const result = mapAST([{\n dummy: true,\n children: children || []\n }], ast, getAsArray(children || []));\n return getChildren(result[0]);\n};\nconst fixComponentProps = (component, index, translation) => {\n const componentKey = component.key || index;\n const comp = cloneElement(component, {\n key: componentKey\n });\n if (!comp.props || !comp.props.children || translation.indexOf(`${index}/>`) < 0 && translation.indexOf(`${index} />`) < 0) {\n return comp;\n }\n function Componentized() {\n return createElement(Fragment, null, comp);\n }\n return createElement(Componentized, {\n key: componentKey\n });\n};\nconst generateArrayComponents = (components, translation) => components.map((c, index) => fixComponentProps(c, index, translation));\nconst generateObjectComponents = (components, translation) => {\n const componentMap = {};\n Object.keys(components).forEach(c => {\n Object.assign(componentMap, {\n [c]: fixComponentProps(components[c], c, translation)\n });\n });\n return componentMap;\n};\nconst generateComponents = (components, translation, i18n, i18nKey) => {\n if (!components) return null;\n if (Array.isArray(components)) {\n return generateArrayComponents(components, translation);\n }\n if (isObject(components)) {\n return generateObjectComponents(components, translation);\n }\n warnOnce(i18n, 'TRANS_INVALID_COMPONENTS', `<Trans /> \"components\" prop expects an object or array`, {\n i18nKey\n });\n return null;\n};\nconst isComponentsMap = object => {\n if (!isObject(object)) return false;\n if (Array.isArray(object)) return false;\n return Object.keys(object).reduce((acc, key) => acc && Number.isNaN(Number.parseFloat(key)), true);\n};\nexport function Trans({\n children,\n count,\n parent,\n i18nKey,\n context,\n tOptions = {},\n values,\n defaults,\n components,\n ns,\n i18n: i18nFromProps,\n t: tFromProps,\n shouldUnescape,\n ...additionalProps\n}) {\n const i18n = i18nFromProps || getI18n();\n if (!i18n) {\n warnOnce(i18n, 'NO_I18NEXT_INSTANCE', `Trans: You need to pass in an i18next instance using i18nextReactModule`, {\n i18nKey\n });\n return children;\n }\n const t = tFromProps || i18n.t.bind(i18n) || (k => k);\n const reactI18nextOptions = {\n ...getDefaults(),\n ...i18n.options?.react\n };\n let namespaces = ns || t.ns || i18n.options?.defaultNS;\n namespaces = isString(namespaces) ? [namespaces] : namespaces || ['translation'];\n const nodeAsString = nodesToString(children, reactI18nextOptions, i18n, i18nKey);\n const defaultValue = defaults || nodeAsString || reactI18nextOptions.transEmptyNodeValue || i18nKey;\n const {\n hashTransKey\n } = reactI18nextOptions;\n const key = i18nKey || (hashTransKey ? hashTransKey(nodeAsString || defaultValue) : nodeAsString || defaultValue);\n if (i18n.options?.interpolation?.defaultVariables) {\n values = values && Object.keys(values).length > 0 ? {\n ...values,\n ...i18n.options.interpolation.defaultVariables\n } : {\n ...i18n.options.interpolation.defaultVariables\n };\n }\n const interpolationOverride = values || count !== undefined && !i18n.options?.interpolation?.alwaysFormat || !children ? tOptions.interpolation : {\n interpolation: {\n ...tOptions.interpolation,\n prefix: '#$?',\n suffix: '?$#'\n }\n };\n const combinedTOpts = {\n ...tOptions,\n context: context || tOptions.context,\n count,\n ...values,\n ...interpolationOverride,\n defaultValue,\n ns: namespaces\n };\n const translation = key ? t(key, combinedTOpts) : defaultValue;\n const generatedComponents = generateComponents(components, translation, i18n, i18nKey);\n let indexedChildren = generatedComponents || children;\n let componentsMap = null;\n if (isComponentsMap(generatedComponents)) {\n componentsMap = generatedComponents;\n indexedChildren = children;\n }\n const content = renderNodes(indexedChildren, componentsMap, translation, i18n, reactI18nextOptions, combinedTOpts, shouldUnescape);\n const useAsParent = parent ?? reactI18nextOptions.defaultTransParent;\n return useAsParent ? createElement(useAsParent, additionalProps, content) : content;\n}","export const warn = (i18n, code, msg, rest) => {\n const args = [msg, {\n code,\n ...(rest || {})\n }];\n if (i18n?.services?.logger?.forward) {\n return i18n.services.logger.forward(args, 'warn', 'react-i18next::', true);\n }\n if (isString(args[0])) args[0] = `react-i18next:: ${args[0]}`;\n if (i18n?.services?.logger?.warn) {\n i18n.services.logger.warn(...args);\n } else if (console?.warn) {\n console.warn(...args);\n }\n};\nconst alreadyWarned = {};\nexport const warnOnce = (i18n, code, msg, rest) => {\n if (isString(msg) && alreadyWarned[msg]) return;\n if (isString(msg)) alreadyWarned[msg] = new Date();\n warn(i18n, code, msg, rest);\n};\nconst loadedClb = (i18n, cb) => () => {\n if (i18n.isInitialized) {\n cb();\n } else {\n const initialized = () => {\n setTimeout(() => {\n i18n.off('initialized', initialized);\n }, 0);\n cb();\n };\n i18n.on('initialized', initialized);\n }\n};\nexport const loadNamespaces = (i18n, ns, cb) => {\n i18n.loadNamespaces(ns, loadedClb(i18n, cb));\n};\nexport const loadLanguages = (i18n, lng, ns, cb) => {\n if (isString(ns)) ns = [ns];\n if (i18n.options.preload && i18n.options.preload.indexOf(lng) > -1) return loadNamespaces(i18n, ns, cb);\n ns.forEach(n => {\n if (i18n.options.ns.indexOf(n) < 0) i18n.options.ns.push(n);\n });\n i18n.loadLanguages(lng, loadedClb(i18n, cb));\n};\nexport const hasLoadedNamespace = (ns, i18n, options = {}) => {\n if (!i18n.languages || !i18n.languages.length) {\n warnOnce(i18n, 'NO_LANGUAGES', 'i18n.languages were undefined or empty', {\n languages: i18n.languages\n });\n return true;\n }\n return i18n.hasLoadedNamespace(ns, {\n lng: options.lng,\n precheck: (i18nInstance, loadNotPending) => {\n if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false;\n }\n });\n};\nexport const getDisplayName = Component => Component.displayName || Component.name || (isString(Component) && Component.length > 0 ? Component : 'Unknown');\nexport const isString = obj => typeof obj === 'string';\nexport const isObject = obj => typeof obj === 'object' && obj !== null;","const matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;\nconst htmlEntities = {\n '&amp;': '&',\n '&#38;': '&',\n '&lt;': '<',\n '&#60;': '<',\n '&gt;': '>',\n '&#62;': '>',\n '&apos;': \"'\",\n '&#39;': \"'\",\n '&quot;': '\"',\n '&#34;': '\"',\n '&nbsp;': ' ',\n '&#160;': ' ',\n '&copy;': '©',\n '&#169;': '©',\n '&reg;': '®',\n '&#174;': '®',\n '&hellip;': '…',\n '&#8230;': '…',\n '&#x2F;': '/',\n '&#47;': '/'\n};\nconst unescapeHtmlEntity = m => htmlEntities[m];\nexport const unescape = text => text.replace(matchHtmlEntity, unescapeHtmlEntity);","import { unescape } from './unescape.js';\nlet defaultOptions = {\n bindI18n: 'languageChanged',\n bindI18nStore: '',\n transEmptyNodeValue: '',\n transSupportBasicHtmlNodes: true,\n transWrapTextNodes: '',\n transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],\n useSuspense: true,\n unescape\n};\nexport const setDefaults = (options = {}) => {\n defaultOptions = {\n ...defaultOptions,\n ...options\n };\n};\nexport const getDefaults = () => defaultOptions;","let i18nInstance;\nexport const setI18n = instance => {\n i18nInstance = instance;\n};\nexport const getI18n = () => i18nInstance;","import { createContext } from 'react';\nimport { getDefaults, setDefaults } from './defaults.js';\nimport { getI18n, setI18n } from './i18nInstance.js';\nimport { initReactI18next } from './initReactI18next.js';\nexport { getDefaults, setDefaults, getI18n, setI18n, initReactI18next };\nexport const I18nContext = createContext();\nexport class ReportNamespaces {\n constructor() {\n this.usedNamespaces = {};\n }\n addUsedNamespaces(namespaces) {\n namespaces.forEach(ns => {\n if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true;\n });\n }\n getUsedNamespaces() {\n return Object.keys(this.usedNamespaces);\n }\n}\nexport const composeInitialProps = ForComponent => async ctx => {\n const componentsInitialProps = (await ForComponent.getInitialProps?.(ctx)) ?? {};\n const i18nInitialProps = getInitialProps();\n return {\n ...componentsInitialProps,\n ...i18nInitialProps\n };\n};\nexport const getInitialProps = () => {\n const i18n = getI18n();\n const namespaces = i18n.reportNamespaces?.getUsedNamespaces() ?? [];\n const ret = {};\n const initialI18nStore = {};\n i18n.languages.forEach(l => {\n initialI18nStore[l] = {};\n namespaces.forEach(ns => {\n initialI18nStore[l][ns] = i18n.getResourceBundle(l, ns) || {};\n });\n });\n ret.initialI18nStore = initialI18nStore;\n ret.initialLanguage = i18n.language;\n return ret;\n};","import { useState, useEffect, useContext, useRef, useCallback } from 'react';\nimport { getI18n, getDefaults, ReportNamespaces, I18nContext } from './context.js';\nimport { warnOnce, loadNamespaces, loadLanguages, hasLoadedNamespace, isString, isObject } from './utils.js';\nconst usePrevious = (value, ignore) => {\n const ref = useRef();\n useEffect(() => {\n ref.current = ignore ? ref.current : value;\n }, [value, ignore]);\n return ref.current;\n};\nconst alwaysNewT = (i18n, language, namespace, keyPrefix) => i18n.getFixedT(language, namespace, keyPrefix);\nconst useMemoizedT = (i18n, language, namespace, keyPrefix) => useCallback(alwaysNewT(i18n, language, namespace, keyPrefix), [i18n, language, namespace, keyPrefix]);\nexport const useTranslation = (ns, props = {}) => {\n const {\n i18n: i18nFromProps\n } = props;\n const {\n i18n: i18nFromContext,\n defaultNS: defaultNSFromContext\n } = useContext(I18nContext) || {};\n const i18n = i18nFromProps || i18nFromContext || getI18n();\n if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();\n if (!i18n) {\n warnOnce(i18n, 'NO_I18NEXT_INSTANCE', 'useTranslation: You will need to pass in an i18next instance by using initReactI18next');\n const notReadyT = (k, optsOrDefaultValue) => {\n if (isString(optsOrDefaultValue)) return optsOrDefaultValue;\n if (isObject(optsOrDefaultValue) && isString(optsOrDefaultValue.defaultValue)) return optsOrDefaultValue.defaultValue;\n return Array.isArray(k) ? k[k.length - 1] : k;\n };\n const retNotReady = [notReadyT, {}, false];\n retNotReady.t = notReadyT;\n retNotReady.i18n = {};\n retNotReady.ready = false;\n return retNotReady;\n }\n if (i18n.options.react?.wait) warnOnce(i18n, 'DEPRECATED_OPTION', 'useTranslation: It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.');\n const i18nOptions = {\n ...getDefaults(),\n ...i18n.options.react,\n ...props\n };\n const {\n useSuspense,\n keyPrefix\n } = i18nOptions;\n let namespaces = ns || defaultNSFromContext || i18n.options?.defaultNS;\n namespaces = isString(namespaces) ? [namespaces] : namespaces || ['translation'];\n i18n.reportNamespaces.addUsedNamespaces?.(namespaces);\n const ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(n => hasLoadedNamespace(n, i18n, i18nOptions));\n const memoGetT = useMemoizedT(i18n, props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);\n const getT = () => memoGetT;\n const getNewT = () => alwaysNewT(i18n, props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);\n const [t, setT] = useState(getT);\n let joinedNS = namespaces.join();\n if (props.lng) joinedNS = `${props.lng}${joinedNS}`;\n const previousJoinedNS = usePrevious(joinedNS);\n const isMounted = useRef(true);\n useEffect(() => {\n const {\n bindI18n,\n bindI18nStore\n } = i18nOptions;\n isMounted.current = true;\n if (!ready && !useSuspense) {\n if (props.lng) {\n loadLanguages(i18n, props.lng, namespaces, () => {\n if (isMounted.current) setT(getNewT);\n });\n } else {\n loadNamespaces(i18n, namespaces, () => {\n if (isMounted.current) setT(getNewT);\n });\n }\n }\n if (ready && previousJoinedNS && previousJoinedNS !== joinedNS && isMounted.current) {\n setT(getNewT);\n }\n const boundReset = () => {\n if (isMounted.current) setT(getNewT);\n };\n if (bindI18n) i18n?.on(bindI18n, boundReset);\n if (bindI18nStore) i18n?.store.on(bindI18nStore, boundReset);\n return () => {\n isMounted.current = false;\n if (i18n && bindI18n) bindI18n?.split(' ').forEach(e => i18n.off(e, boundReset));\n if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(e => i18n.store.off(e, boundReset));\n };\n }, [i18n, joinedNS]);\n useEffect(() => {\n if (isMounted.current && ready) {\n setT(getT);\n }\n }, [i18n, keyPrefix, ready]);\n const ret = [t, i18n, ready];\n ret.t = t;\n ret.i18n = i18n;\n ret.ready = ready;\n if (ready) return ret;\n if (!ready && !useSuspense) return ret;\n throw new Promise(resolve => {\n if (props.lng) {\n loadLanguages(i18n, props.lng, namespaces, () => resolve());\n } else {\n loadNamespaces(i18n, namespaces, () => resolve());\n }\n });\n};","import { createElement, forwardRef as forwardRefReact } from 'react';\nimport { useTranslation } from './useTranslation.js';\nimport { getDisplayName } from './utils.js';\nexport const withTranslation = (ns, options = {}) => function Extend(WrappedComponent) {\n function I18nextWithTranslation({\n forwardedRef,\n ...rest\n }) {\n const [t, i18n, ready] = useTranslation(ns, {\n ...rest,\n keyPrefix: options.keyPrefix\n });\n const passDownProps = {\n ...rest,\n t,\n i18n,\n tReady: ready\n };\n if (options.withRef && forwardedRef) {\n passDownProps.ref = forwardedRef;\n } else if (!options.withRef && forwardedRef) {\n passDownProps.forwardedRef = forwardedRef;\n }\n return createElement(WrappedComponent, passDownProps);\n }\n I18nextWithTranslation.displayName = `withI18nextTranslation(${getDisplayName(WrappedComponent)})`;\n I18nextWithTranslation.WrappedComponent = WrappedComponent;\n const forwardRef = (props, ref) => createElement(I18nextWithTranslation, Object.assign({}, props, {\n forwardedRef: ref\n }));\n return options.withRef ? forwardRefReact(forwardRef) : I18nextWithTranslation;\n};","import { createElement, useMemo } from 'react';\nimport { I18nContext } from './context.js';\nexport function I18nextProvider({\n i18n,\n defaultNS,\n children\n}) {\n const value = useMemo(() => ({\n i18n,\n defaultNS\n }), [i18n, defaultNS]);\n return createElement(I18nContext.Provider, {\n value\n }, children);\n}","import { createElement } from 'react';\nimport { useSSR } from './useSSR.js';\nimport { composeInitialProps } from './context.js';\nimport { getDisplayName } from './utils.js';\nexport const withSSR = () => function Extend(WrappedComponent) {\n function I18nextWithSSR({\n initialI18nStore,\n initialLanguage,\n ...rest\n }) {\n useSSR(initialI18nStore, initialLanguage);\n return createElement(WrappedComponent, {\n ...rest\n });\n }\n I18nextWithSSR.getInitialProps = composeInitialProps(WrappedComponent);\n I18nextWithSSR.displayName = `withI18nextSSR(${getDisplayName(WrappedComponent)})`;\n I18nextWithSSR.WrappedComponent = WrappedComponent;\n return I18nextWithSSR;\n};","import { useContext } from 'react';\nimport { getI18n, I18nContext } from './context.js';\nexport const useSSR = (initialI18nStore, initialLanguage, props = {}) => {\n const {\n i18n: i18nFromProps\n } = props;\n const {\n i18n: i18nFromContext\n } = useContext(I18nContext) || {};\n const i18n = i18nFromProps || i18nFromContext || getI18n();\n if (i18n.options?.isClone) return;\n if (initialI18nStore && !i18n.initializedStoreOnce) {\n i18n.services.resourceStore.data = initialI18nStore;\n i18n.options.ns = Object.values(initialI18nStore).reduce((mem, lngResources) => {\n Object.keys(lngResources).forEach(ns => {\n if (mem.indexOf(ns) < 0) mem.push(ns);\n });\n return mem;\n }, i18n.options.ns);\n i18n.initializedStoreOnce = true;\n i18n.isInitialized = true;\n }\n if (initialLanguage && !i18n.initializedLanguageOnce) {\n i18n.changeLanguage(initialLanguage);\n i18n.initializedLanguageOnce = true;\n }\n};","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=\" \"),n+=f)}else for(f in e)e[f]&&(n&&(n+=\" \"),n+=f);return n}export function clsx(){for(var e,t,f=0,n=\"\",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=\" \"),n+=t);return n}export default clsx;","import { TProduct } from \"@type/product/product\";\nimport { clsx } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: any[]) {\n return twMerge(clsx(inputs));\n}\n\nexport const generateRandomText = (length: number) => {\n const chars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n let result = \"\";\n for (let i = 0; i < length; i++) {\n result += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n return result;\n};\n\nexport const isObjectEmpty = (obj: object): boolean => {\n return Object.keys(obj).length === 0;\n};\n\nexport function arraysEqual(a: any[], b: any[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((val, i) => val === b[i]);\n}\n\nexport const formatCurrency = (value: string | number) => {\n if (!value) return \"\";\n return new Intl.NumberFormat(\"en-US\").format(Number(value));\n};\n\nexport const getTimeNow = () => {\n const now = new Date();\n const formatted = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(\n 2,\n \"0\"\n )}-${String(now.getDate()).padStart(2, \"0\")} ${String(\n now.getHours()\n ).padStart(2, \"0\")}:${String(now.getMinutes()).padStart(2, \"0\")}:${String(\n now.getSeconds()\n ).padStart(2, \"0\")}`;\n\n return formatted;\n};\n\nexport const parseStringToObject = (str: string) => {\n try {\n // First parse once — this removes outer quotes if needed\n const firstParse = JSON.parse(str);\n\n // If the result is still a string (double-encoded), parse again\n if (typeof firstParse === \"string\") {\n return JSON.parse(firstParse);\n }\n\n // Otherwise, it's already an object\n return firstParse;\n } catch (error) {\n console.error(\"❌ Failed to parse JSON:\", error);\n return null;\n }\n};\n\nexport function cleanObject<T extends Record<string, any>>(obj: T): Partial<T> {\n const result: Partial<T> = {};\n for (const [k, v] of Object.entries(obj)) {\n if (v != null) {\n result[k as keyof T] = v;\n }\n }\n return result;\n}\n\nexport function filterObject(obj: Record<string, any>) {\n return Object.fromEntries(\n Object.entries(obj).filter(([_, value]) => {\n if (value === \"\" || value === null || value === undefined) return false;\n if (value === 0 || value === false) return false;\n if (typeof value === \"number\" && Number.isNaN(value)) return false;\n return true;\n })\n );\n}\n\nexport function normalizeObject(obj: Record<string, any> | null) {\n if (!obj) return null;\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => {\n if (value === false) return [key, \"\"];\n if (typeof value === \"string\") return [key, value.trim()];\n return [key, value];\n })\n );\n}\n\nexport const makeTaxIds = (taxIds: number[]) => {\n if (!taxIds || taxIds.length === 0) return [];\n\n if (taxIds.length === 1) {\n const id = taxIds[0];\n return [4, id, { id }];\n }\n\n return taxIds.map((id) => [4, id, { id }]);\n};\n\nexport function generatePosReference({\n posId,\n loginNum,\n orderLength,\n}: {\n posId: number | string;\n loginNum: number | string;\n orderLength: number | string;\n}) {\n return (\n \"Order \" +\n posId.toString().padStart(5, \"0\") +\n \"-\" +\n loginNum.toString().padStart(3, \"0\") +\n \"-\" +\n orderLength.toString().padStart(4, \"0\")\n );\n}\n\nexport const getKey = (prodct: TProduct) => {\n const attributeIds = prodct?.attributeValueIds?.join(\".\") ?? [];\n return `${prodct?.id}${attributeIds.length > 0 ? \"-\" : \"\"}${attributeIds}`;\n};\n\nexport const getProductIdFromKey = (key?: string) => {\n return key?.includes(\"-\") ? key?.split?.(\"-\")?.[0] : key;\n};\n\n//format date\n\nexport const getDate = (date: Date | string) => {\n const value = new Date(date);\n const day = value?.getDate().toString().padStart(2, \"0\");\n const month = (value?.getMonth() + 1).toString().padStart(2, \"0\");\n const year = value?.getFullYear();\n\n return {\n day,\n month,\n year,\n };\n};\n\nexport const hh_mm = (date: Date | string) => {\n const value = new Date(date);\n const hours = value?.getHours().toString().padStart(2, \"0\");\n const minutes = value?.getMinutes().toString().padStart(2, \"0\");\n\n return `${hours}:${minutes}`;\n};\n\nexport const dd_mm_yyyy = (date: Date | string) => {\n const value = new Date(date);\n const day = value?.getDate().toString().padStart(2, \"0\");\n const month = (value?.getMonth() + 1).toString().padStart(2, \"0\");\n const year = value?.getFullYear();\n\n return `${day}/${month}/${year}`;\n};\n\nexport const hh_mm_dd_mm_yyyy = (date: Date | string) => {\n return `${hh_mm(date)} ${dd_mm_yyyy(date)}`;\n};\n\nexport function add7Hours(str: string | Date) {\n const d = new Date(str);\n return new Date(d.getTime() + 7 * 3600 * 1000);\n}\n\n// format currency\nexport const unFormatCurrency = (value: string) => {\n return value.replace(/\\,/g, \"\");\n};\n\nexport function ceilDecimal(value: number, decimals: number = 0): number {\n const factor = Math.pow(10, decimals);\n return Math.ceil(value * factor) / factor;\n}\n\nexport function ceilToThousands(value: number): number {\n return Math.ceil(value / 1000) * 1000;\n}\n\nexport const formatVND = (amount: number) => {\n return Math.ceil(amount).toLocaleString(\"en-US\");\n};\n\nexport const formatOrderPrice = (price: number) =>\n price.toLocaleString(\"vi-VN\", { maximumFractionDigits: 0 });\n\nexport const randomNumber = () => {\n return (Date.now() + Math.floor(Math.random() * 1000)).toString();\n};\n\nexport const onFindTable = ({\n order,\n tables,\n floors,\n}: {\n order: any;\n tables: any;\n floors: any;\n}) => {\n if (!tables || !floors || !tables.length || !floors.length)\n return \"Chưa xác định\";\n\n const tableMatched = tables?.find(\n (table: any) => table.id === order?.table_id\n );\n const floorMatched = floors?.find(\n (floor: any) => floor.id === tableMatched?.floor_id\n );\n\n const floor = floorMatched?.name;\n const table = tableMatched?.table_number;\n\n if ((order?.table_id && !tableMatched) || (!order?.table_id && floorMatched))\n return \"Chưa xác định\";\n\n const label = floor || table ? `${floor} - Bàn ${table}` : \"Mang đi\";\n\n return label;\n};\n\ntype ApiOrder = {\n id: number;\n pos_reference: string;\n amount_total: number;\n date_order: string | Date;\n state: string;\n table_id: string | number | boolean;\n lines: number[];\n};\n\nexport const imageToHex = (\n imageUrl: string\n): Promise<{ width: number; height: number; hexString: string }> => {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.crossOrigin = \"anonymous\";\n img.src = imageUrl;\n\n img.onload = () => {\n const width = img.width;\n const height = img.height;\n const canvas = document.createElement(\"canvas\");\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return reject(\"Cannot get canvas context\");\n\n ctx.drawImage(img, 0, 0, width, height);\n const imageData = ctx.getImageData(0, 0, width, height);\n const pixels = imageData.data;\n\n let hexString = \"\";\n\n for (let y = 0; y < height; y++) {\n let byte = 0;\n let bitCount = 0;\n\n for (let x = 0; x < width; x++) {\n const idx = (y * width + x) * 4;\n const r = pixels[idx];\n const g = pixels[idx + 1];\n const b = pixels[idx + 2];\n\n const gray = 0.299 * r + 0.587 * g + 0.114 * b;\n const bw = gray < 128 ? 1 : 0;\n\n byte = (byte << 1) | bw;\n bitCount++;\n\n if (bitCount === 8) {\n hexString += byte.toString(16).padStart(2, \"0\");\n byte = 0;\n bitCount = 0;\n }\n }\n\n if (bitCount > 0) {\n byte = byte << (8 - bitCount);\n hexString += byte.toString(16).padStart(2, \"0\");\n }\n }\n\n resolve({ width, height, hexString });\n };\n\n img.onerror = reject;\n });\n};\n","\"use client\";\nimport { jsx, Fragment } from 'react/jsx-runtime';\nimport { useMemo, useRef, useState, useContext } from 'react';\nimport { LayoutGroupContext } from '../../context/LayoutGroupContext.mjs';\nimport { useConstant } from '../../utils/use-constant.mjs';\nimport { useIsomorphicLayoutEffect } from '../../utils/use-isomorphic-effect.mjs';\nimport { PresenceChild } from './PresenceChild.mjs';\nimport { usePresence } from './use-presence.mjs';\nimport { onlyElements, getChildKey } from './utils.mjs';\n\n/**\n * `AnimatePresence` enables the animation of components that have been removed from the tree.\n *\n * When adding/removing more than a single child, every child **must** be given a unique `key` prop.\n *\n * Any `motion` components that have an `exit` property defined will animate out when removed from\n * the tree.\n *\n * ```jsx\n * import { motion, AnimatePresence } from 'framer-motion'\n *\n * export const Items = ({ items }) => (\n * <AnimatePresence>\n * {items.map(item => (\n * <motion.div\n * key={item.id}\n * initial={{ opacity: 0 }}\n * animate={{ opacity: 1 }}\n * exit={{ opacity: 0 }}\n * />\n * ))}\n * </AnimatePresence>\n * )\n * ```\n *\n * You can sequence exit animations throughout a tree using variants.\n *\n * If a child contains multiple `motion` components with `exit` props, it will only unmount the child\n * once all `motion` components have finished animating out. Likewise, any components using\n * `usePresence` all need to call `safeToRemove`.\n *\n * @public\n */\nconst AnimatePresence = ({ children, custom, initial = true, onExitComplete, presenceAffectsLayout = true, mode = \"sync\", propagate = false, anchorX = \"left\", root }) => {\n const [isParentPresent, safeToRemove] = usePresence(propagate);\n /**\n * Filter any children that aren't ReactElements. We can only track components\n * between renders with a props.key.\n */\n const presentChildren = useMemo(() => onlyElements(children), [children]);\n /**\n * Track the keys of the currently rendered children. This is used to\n * determine which children are exiting.\n */\n const presentKeys = propagate && !isParentPresent ? [] : presentChildren.map(getChildKey);\n /**\n * If `initial={false}` we only want to pass this to components in the first render.\n */\n const isInitialRender = useRef(true);\n /**\n * A ref containing the currently present children. When all exit animations\n * are complete, we use this to re-render the component with the latest children\n * *committed* rather than the latest children *rendered*.\n */\n const pendingPresentChildren = useRef(presentChildren);\n /**\n * Track which exiting children have finished animating out.\n */\n const exitComplete = useConstant(() => new Map());\n /**\n * Save children to render as React state. To ensure this component is concurrent-safe,\n * we check for exiting children via an effect.\n */\n const [diffedChildren, setDiffedChildren] = useState(presentChildren);\n const [renderedChildren, setRenderedChildren] = useState(presentChildren);\n useIsomorphicLayoutEffect(() => {\n isInitialRender.current = false;\n pendingPresentChildren.current = presentChildren;\n /**\n * Update complete status of exiting children.\n */\n for (let i = 0; i < renderedChildren.length; i++) {\n const key = getChildKey(renderedChildren[i]);\n if (!presentKeys.includes(key)) {\n if (exitComplete.get(key) !== true) {\n exitComplete.set(key, false);\n }\n }\n else {\n exitComplete.delete(key);\n }\n }\n }, [renderedChildren, presentKeys.length, presentKeys.join(\"-\")]);\n const exitingChildren = [];\n if (presentChildren !== diffedChildren) {\n let nextChildren = [...presentChildren];\n /**\n * Loop through all the currently rendered components and decide which\n * are exiting.\n */\n for (let i = 0; i < renderedChildren.length; i++) {\n const child = renderedChildren[i];\n const key = getChildKey(child);\n if (!presentKeys.includes(key)) {\n nextChildren.splice(i, 0, child);\n exitingChildren.push(child);\n }\n }\n /**\n * If we're in \"wait\" mode, and we have exiting children, we want to\n * only render these until they've all exited.\n */\n if (mode === \"wait\" && exitingChildren.length) {\n nextChildren = exitingChildren;\n }\n setRenderedChildren(onlyElements(nextChildren));\n setDiffedChildren(presentChildren);\n /**\n * Early return to ensure once we've set state with the latest diffed\n * children, we can immediately re-render.\n */\n return null;\n }\n if (process.env.NODE_ENV !== \"production\" &&\n mode === \"wait\" &&\n renderedChildren.length > 1) {\n console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to \"wait\". This will lead to odd visual behaviour.`);\n }\n /**\n * If we've been provided a forceRender function by the LayoutGroupContext,\n * we can use it to force a re-render amongst all surrounding components once\n * all components have finished animating out.\n */\n const { forceRender } = useContext(LayoutGroupContext);\n return (jsx(Fragment, { children: renderedChildren.map((child) => {\n const key = getChildKey(child);\n const isPresent = propagate && !isParentPresent\n ? false\n : presentChildren === renderedChildren ||\n presentKeys.includes(key);\n const onExit = () => {\n if (exitComplete.has(key)) {\n exitComplete.set(key, true);\n }\n else {\n return;\n }\n let isEveryExitComplete = true;\n exitComplete.forEach((isExitComplete) => {\n if (!isExitComplete)\n isEveryExitComplete = false;\n });\n if (isEveryExitComplete) {\n forceRender?.();\n setRenderedChildren(pendingPresentChildren.current);\n propagate && safeToRemove?.();\n onExitComplete && onExitComplete();\n }\n };\n return (jsx(PresenceChild, { isPresent: isPresent, initial: !isInitialRender.current || initial\n ? undefined\n : false, custom: custom, presenceAffectsLayout: presenceAffectsLayout, mode: mode, root: root, onExitComplete: isPresent ? undefined : onExit, anchorX: anchorX, children: child }, key));\n }) }));\n};\n\nexport { AnimatePresence };\n","\"use client\";\nimport { createContext } from 'react';\n\nconst LayoutGroupContext = createContext({});\n\nexport { LayoutGroupContext };\n","\"use client\";\nimport { useRef } from 'react';\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 */\nfunction useConstant(init) {\n const ref = useRef(null);\n if (ref.current === null) {\n ref.current = init();\n }\n return ref.current;\n}\n\nexport { useConstant };\n","\"use client\";\nimport { useLayoutEffect, useEffect } from 'react';\nimport { isBrowser } from './is-browser.mjs';\n\nconst useIsomorphicLayoutEffect = isBrowser ? useLayoutEffect : useEffect;\n\nexport { useIsomorphicLayoutEffect };\n","const isBrowser = typeof window !== \"undefined\";\n\nexport { isBrowser };\n","\"use client\";\nimport { jsx } from 'react/jsx-runtime';\nimport * as React from 'react';\nimport { useId, useMemo } from 'react';\nimport { PresenceContext } from '../../context/PresenceContext.mjs';\nimport { useConstant } from '../../utils/use-constant.mjs';\nimport { PopChild } from './PopChild.mjs';\n\nconst PresenceChild = ({ children, initial, isPresent, onExitComplete, custom, presenceAffectsLayout, mode, anchorX, root }) => {\n const presenceChildren = useConstant(newChildrenMap);\n const id = useId();\n let isReusedContext = true;\n let context = useMemo(() => {\n isReusedContext = false;\n return {\n id,\n initial,\n isPresent,\n custom,\n onExitComplete: (childId) => {\n presenceChildren.set(childId, true);\n for (const isComplete of presenceChildren.values()) {\n if (!isComplete)\n return; // can stop searching when any is incomplete\n }\n onExitComplete && onExitComplete();\n },\n register: (childId) => {\n presenceChildren.set(childId, false);\n return () => presenceChildren.delete(childId);\n },\n };\n }, [isPresent, presenceChildren, onExitComplete]);\n /**\n * If the presence of a child affects the layout of the components around it,\n * we want to make a new context value to ensure they get re-rendered\n * so they can detect that layout change.\n */\n if (presenceAffectsLayout && isReusedContext) {\n context = { ...context };\n }\n useMemo(() => {\n presenceChildren.forEach((_, key) => presenceChildren.set(key, false));\n }, [isPresent]);\n /**\n * If there's no `motion` components to fire exit animations, we want to remove this\n * component immediately.\n */\n React.useEffect(() => {\n !isPresent &&\n !presenceChildren.size &&\n onExitComplete &&\n onExitComplete();\n }, [isPresent]);\n if (mode === \"popLayout\") {\n children = (jsx(PopChild, { isPresent: isPresent, anchorX: anchorX, root: root, children: children }));\n }\n return (jsx(PresenceContext.Provider, { value: context, children: children }));\n};\nfunction newChildrenMap() {\n return new Map();\n}\n\nexport { PresenceChild };\n","\"use client\";\nimport { createContext } from 'react';\n\n/**\n * @public\n */\nconst PresenceContext = \n/* @__PURE__ */ createContext(null);\n\nexport { PresenceContext };\n","\"use client\";\nimport { jsx } from 'react/jsx-runtime';\nimport { isHTMLElement } from 'motion-dom';\nimport * as React from 'react';\nimport { useId, useRef, useContext, useInsertionEffect } from 'react';\nimport { MotionConfigContext } from '../../context/MotionConfigContext.mjs';\nimport { useComposedRefs } from '../../utils/use-composed-ref.mjs';\n\n/**\n * Measurement functionality has to be within a separate component\n * to leverage snapshot lifecycle.\n */\nclass PopChildMeasure extends React.Component {\n getSnapshotBeforeUpdate(prevProps) {\n const element = this.props.childRef.current;\n if (element && prevProps.isPresent && !this.props.isPresent) {\n const parent = element.offsetParent;\n const parentWidth = isHTMLElement(parent)\n ? parent.offsetWidth || 0\n : 0;\n const size = this.props.sizeRef.current;\n size.height = element.offsetHeight || 0;\n size.width = element.offsetWidth || 0;\n size.top = element.offsetTop;\n size.left = element.offsetLeft;\n size.right = parentWidth - size.width - size.left;\n }\n return null;\n }\n /**\n * Required with getSnapshotBeforeUpdate to stop React complaining.\n */\n componentDidUpdate() { }\n render() {\n return this.props.children;\n }\n}\nfunction PopChild({ children, isPresent, anchorX, root }) {\n const id = useId();\n const ref = useRef(null);\n const size = useRef({\n width: 0,\n height: 0,\n top: 0,\n left: 0,\n right: 0,\n });\n const { nonce } = useContext(MotionConfigContext);\n const composedRef = useComposedRefs(ref, children?.ref);\n /**\n * We create and inject a style block so we can apply this explicit\n * sizing in a non-destructive manner by just deleting the style block.\n *\n * We can't apply size via render as the measurement happens\n * in getSnapshotBeforeUpdate (post-render), likewise if we apply the\n * styles directly on the DOM node, we might be overwriting\n * styles set via the style prop.\n */\n useInsertionEffect(() => {\n const { width, height, top, left, right } = size.current;\n if (isPresent || !ref.current || !width || !height)\n return;\n const x = anchorX === \"left\" ? `left: ${left}` : `right: ${right}`;\n ref.current.dataset.motionPopId = id;\n const style = document.createElement(\"style\");\n if (nonce)\n style.nonce = nonce;\n const parent = root ?? document.head;\n parent.appendChild(style);\n if (style.sheet) {\n style.sheet.insertRule(`\n [data-motion-pop-id=\"${id}\"] {\n position: absolute !important;\n width: ${width}px !important;\n height: ${height}px !important;\n ${x}px !important;\n top: ${top}px !important;\n }\n `);\n }\n return () => {\n if (parent.contains(style)) {\n parent.removeChild(style);\n }\n };\n }, [isPresent]);\n return (jsx(PopChildMeasure, { isPresent: isPresent, childRef: ref, sizeRef: size, children: React.cloneElement(children, { ref: composedRef }) }));\n}\n\nexport { PopChild };\n","function addUniqueItem(arr, item) {\n if (arr.indexOf(item) === -1)\n arr.push(item);\n}\nfunction removeItem(arr, item) {\n const index = arr.indexOf(item);\n if (index > -1)\n arr.splice(index, 1);\n}\n// Adapted from array-move\nfunction moveItem([...arr], fromIndex, toIndex) {\n const startIndex = fromIndex < 0 ? arr.length + fromIndex : fromIndex;\n if (startIndex >= 0 && startIndex < arr.length) {\n const endIndex = toIndex < 0 ? arr.length + toIndex : toIndex;\n const [item] = arr.splice(fromIndex, 1);\n arr.splice(endIndex, 0, item);\n }\n return arr;\n}\n\nexport { addUniqueItem, moveItem, removeItem };\n","const clamp = (min, max, v) => {\n if (v > max)\n return max;\n if (v < min)\n return min;\n return v;\n};\n\nexport { clamp };\n","function formatErrorMessage(message, errorCode) {\n return errorCode\n ? `${message}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${errorCode}`\n : message;\n}\n\nexport { formatErrorMessage };\n","import { formatErrorMessage } from './format-error-message.mjs';\n\nlet warning = () => { };\nlet invariant = () => { };\nif (process.env.NODE_ENV !== \"production\") {\n warning = (check, message, errorCode) => {\n if (!check && typeof console !== \"undefined\") {\n console.warn(formatErrorMessage(message, errorCode));\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","const MotionGlobalConfig = {};\n\nexport { MotionGlobalConfig };\n","/**\n * Check if value is a numerical string, ie a string that is purely a number eg \"100\" or \"-100.1\"\n */\nconst isNumericalString = (v) => /^-?(?:\\d+(?:\\.\\d+)?|\\.\\d+)$/u.test(v);\n\nexport { isNumericalString };\n","function isObject(value) {\n return typeof value === \"object\" && value !== null;\n}\n\nexport { isObject };\n","/**\n * Check if the value is a zero value string like \"0px\" or \"0%\"\n */\nconst isZeroValueString = (v) => /^0[^.\\s]+$/u.test(v);\n\nexport { isZeroValueString };\n","/*#__NO_SIDE_EFFECTS__*/\nfunction memo(callback) {\n let result;\n return () => {\n if (result === undefined)\n result = callback();\n return result;\n };\n}\n\nexport { memo };\n","/*#__NO_SIDE_EFFECTS__*/\nconst noop = (any) => any;\n\nexport { noop };\n","/**\n * Pipe\n * Compose other transformers to run linearily\n * pipe(min(20), max(40))\n * @param {...functions} transformers\n * @return {function}\n */\nconst combineFunctions = (a, b) => (v) => b(a(v));\nconst pipe = (...transformers) => transformers.reduce(combineFunctions);\n\nexport { pipe };\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 @param [number]: Lower limit\n @param [number]: Upper limit\n @param [number]: Value to find progress within given range\n @return [number]: Progress of value within range as expressed 0-1\n*/\n/*#__NO_SIDE_EFFECTS__*/\nconst progress = (from, to, value) => {\n const toFromDifference = to - from;\n return toFromDifference === 0 ? 1 : (value - from) / toFromDifference;\n};\n\nexport { progress };\n","import { addUniqueItem, removeItem } from './array.mjs';\n\nclass SubscriptionManager {\n constructor() {\n this.subscriptions = [];\n }\n add(handler) {\n addUniqueItem(this.subscriptions, handler);\n return () => removeItem(this.subscriptions, handler);\n }\n notify(a, b, c) {\n const numSubscriptions = this.subscriptions.length;\n if (!numSubscriptions)\n return;\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 }\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 getSize() {\n return this.subscriptions.length;\n }\n clear() {\n this.subscriptions.length = 0;\n }\n}\n\nexport { SubscriptionManager };\n","/**\n * Converts seconds to milliseconds\n *\n * @param seconds - Time in seconds.\n * @return milliseconds - Converted time in milliseconds.\n */\n/*#__NO_SIDE_EFFECTS__*/\nconst secondsToMilliseconds = (seconds) => seconds * 1000;\n/*#__NO_SIDE_EFFECTS__*/\nconst millisecondsToSeconds = (milliseconds) => milliseconds / 1000;\n\nexport { millisecondsToSeconds, secondsToMilliseconds };\n","/*\n Convert velocity into velocity per second\n\n @param [number]: Unit per frame\n @param [number]: Frame duration in ms\n*/\nfunction velocityPerSecond(velocity, frameDuration) {\n return frameDuration ? velocity * (1000 / frameDuration) : 0;\n}\n\nexport { velocityPerSecond };\n","import { formatErrorMessage } from './format-error-message.mjs';\n\nconst warned = new Set();\nfunction hasWarned(message) {\n return warned.has(message);\n}\nfunction warnOnce(condition, message, errorCode) {\n if (condition || warned.has(message))\n return;\n console.warn(formatErrorMessage(message, errorCode));\n warned.add(message);\n}\n\nexport { hasWarned, warnOnce };\n","import { noop } from '../noop.mjs';\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// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.\nconst calcBezier = (t, a1, a2) => (((1.0 - 3.0 * a2 + 3.0 * a1) * t + (3.0 * a2 - 6.0 * a1)) * t + 3.0 * a1) *\n t;\nconst subdivisionPrecision = 0.0000001;\nconst subdivisionMaxIterations = 12;\nfunction binarySubdivide(x, lowerBound, upperBound, mX1, mX2) {\n let currentX;\n let currentT;\n let i = 0;\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 }\n else {\n lowerBound = currentT;\n }\n } while (Math.abs(currentX) > subdivisionPrecision &&\n ++i < subdivisionMaxIterations);\n return currentT;\n}\nfunction cubicBezier(mX1, mY1, mX2, mY2) {\n // If this is a linear gradient, return linear easing\n if (mX1 === mY1 && mX2 === mY2)\n return noop;\n const getTForX = (aX) => binarySubdivide(aX, 0, 1, mX1, mX2);\n // If animation is at start/end, return t without easing\n return (t) => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2);\n}\n\nexport { cubicBezier };\n","// Accepts an easing function and returns a new one that outputs mirrored values for\n// the second half of the animation. Turns easeIn into easeInOut.\nconst mirrorEasing = (easing) => (p) => p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2;\n\nexport { mirrorEasing };\n","// Accepts an easing function and returns a new one that outputs reversed values.\n// Turns easeIn into easeOut.\nconst reverseEasing = (easing) => (p) => 1 - easing(1 - p);\n\nexport { reverseEasing };\n","import { cubicBezier } from './cubic-bezier.mjs';\nimport { mirrorEasing } from './modifiers/mirror.mjs';\nimport { reverseEasing } from './modifiers/reverse.mjs';\n\nconst backOut = /*@__PURE__*/ cubicBezier(0.33, 1.53, 0.69, 0.99);\nconst backIn = /*@__PURE__*/ reverseEasing(backOut);\nconst backInOut = /*@__PURE__*/ mirrorEasing(backIn);\n\nexport { backIn, backInOut, backOut };\n","import { backIn } from './back.mjs';\n\nconst anticipate = (p) => (p *= 2) < 1 ? 0.5 * backIn(p) : 0.5 * (2 - Math.pow(2, -10 * (p - 1)));\n\nexport { anticipate };\n","import { mirrorEasing } from './modifiers/mirror.mjs';\nimport { reverseEasing } from './modifiers/reverse.mjs';\n\nconst circIn = (p) => 1 - Math.sin(Math.acos(p));\nconst circOut = reverseEasing(circIn);\nconst circInOut = mirrorEasing(circIn);\n\nexport { circIn, circInOut, circOut };\n","import { cubicBezier } from './cubic-bezier.mjs';\n\nconst easeIn = /*@__PURE__*/ cubicBezier(0.42, 0, 1, 1);\nconst easeOut = /*@__PURE__*/ cubicBezier(0, 0, 0.58, 1);\nconst easeInOut = /*@__PURE__*/ cubicBezier(0.42, 0, 0.58, 1);\n\nexport { easeIn, easeInOut, easeOut };\n","const isEasingArray = (ease) => {\n return Array.isArray(ease) && typeof ease[0] !== \"number\";\n};\n\nexport { isEasingArray };\n","const isBezierDefinition = (easing) => Array.isArray(easing) && typeof easing[0] === \"number\";\n\nexport { isBezierDefinition };\n","import { invariant } from '../../errors.mjs';\nimport { noop } from '../../noop.mjs';\nimport { anticipate } from '../anticipate.mjs';\nimport { backIn, backInOut, backOut } from '../back.mjs';\nimport { circIn, circInOut, circOut } from '../circ.mjs';\nimport { cubicBezier } from '../cubic-bezier.mjs';\nimport { easeIn, easeInOut, easeOut } from '../ease.mjs';\nimport { isBezierDefinition } from './is-bezier-definition.mjs';\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};\nconst isValidEasing = (easing) => {\n return typeof easing === \"string\";\n};\nconst easingDefinitionToFunction = (definition) => {\n if (isBezierDefinition(definition)) {\n // If cubic bezier definition, create bezier curve\n invariant(definition.length === 4, `Cubic bezier arrays must contain four numerical values.`, \"cubic-bezier-length\");\n const [x1, y1, x2, y2] = definition;\n return cubicBezier(x1, y1, x2, y2);\n }\n else if (isValidEasing(definition)) {\n // Else lookup from table\n invariant(easingLookup[definition] !== undefined, `Invalid easing type '${definition}'`, \"invalid-easing-type\");\n return easingLookup[definition];\n }\n return definition;\n};\n\nexport { easingDefinitionToFunction };\n","const stepsOrder = [\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];\n\nexport { stepsOrder };\n","const statsBuffer = {\n value: null,\n addProjectionMetrics: null,\n};\n\nexport { statsBuffer };\n","import { statsBuffer } from '../stats/buffer.mjs';\n\nfunction createRenderStep(runNextFrame, stepName) {\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();\n let nextFrame = new Set();\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 let flushNextFrame = false;\n /**\n * A set of processes which were marked keepAlive when scheduled.\n */\n const toKeepAlive = new WeakSet();\n let latestFrameData = {\n delta: 0.0,\n timestamp: 0.0,\n isProcessing: false,\n };\n let numCalls = 0;\n function triggerCallback(callback) {\n if (toKeepAlive.has(callback)) {\n step.schedule(callback);\n runNextFrame();\n }\n numCalls++;\n callback(latestFrameData);\n }\n const 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 if (keepAlive)\n toKeepAlive.add(callback);\n if (!queue.has(callback))\n queue.add(callback);\n return callback;\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 * Execute all schedule callbacks.\n */\n process: (frameData) => {\n latestFrameData = frameData;\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 isProcessing = true;\n [thisFrame, nextFrame] = [nextFrame, thisFrame];\n // Execute this frame\n thisFrame.forEach(triggerCallback);\n /**\n * If we're recording stats then\n */\n if (stepName && statsBuffer.value) {\n statsBuffer.value.frameloop[stepName].push(numCalls);\n }\n numCalls = 0;\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 isProcessing = false;\n if (flushNextFrame) {\n flushNextFrame = false;\n step.process(frameData);\n }\n },\n };\n return step;\n}\n\nexport { createRenderStep };\n","import { MotionGlobalConfig } from 'motion-utils';\nimport { stepsOrder } from './order.mjs';\nimport { createRenderStep } from './render-step.mjs';\n\nconst maxElapsed = 40;\nfunction createRenderBatcher(scheduleNextBatch, allowKeepAlive) {\n let runNextFrame = false;\n let useDefaultElapsed = true;\n const state = {\n delta: 0.0,\n timestamp: 0.0,\n isProcessing: false,\n };\n const flagRunNextFrame = () => (runNextFrame = true);\n const steps = stepsOrder.reduce((acc, key) => {\n acc[key] = createRenderStep(flagRunNextFrame, allowKeepAlive ? key : undefined);\n return acc;\n }, {});\n const { setup, read, resolveKeyframes, preUpdate, update, preRender, render, postRender, } = steps;\n const processBatch = () => {\n const timestamp = MotionGlobalConfig.useManualTiming\n ? state.timestamp\n : performance.now();\n runNextFrame = false;\n if (!MotionGlobalConfig.useManualTiming) {\n state.delta = useDefaultElapsed\n ? 1000 / 60\n : Math.max(Math.min(timestamp - state.timestamp, maxElapsed), 1);\n }\n state.timestamp = timestamp;\n state.isProcessing = true;\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 state.isProcessing = false;\n if (runNextFrame && allowKeepAlive) {\n useDefaultElapsed = false;\n scheduleNextBatch(processBatch);\n }\n };\n const wake = () => {\n runNextFrame = true;\n useDefaultElapsed = true;\n if (!state.isProcessing) {\n scheduleNextBatch(processBatch);\n }\n };\n const schedule = stepsOrder.reduce((acc, key) => {\n const step = steps[key];\n acc[key] = (process, keepAlive = false, immediate = false) => {\n if (!runNextFrame)\n wake();\n return step.schedule(process, keepAlive, immediate);\n };\n return acc;\n }, {});\n const cancel = (process) => {\n for (let i = 0; i < stepsOrder.length; i++) {\n steps[stepsOrder[i]].cancel(process);\n }\n };\n return { schedule, cancel, state, steps };\n}\n\nexport { createRenderBatcher };\n","import { noop } from 'motion-utils';\nimport { createRenderBatcher } from './batcher.mjs';\n\nconst { schedule: frame, cancel: cancelFrame, state: frameData, steps: frameSteps, } = /* @__PURE__ */ createRenderBatcher(typeof requestAnimationFrame !== \"undefined\" ? requestAnimationFrame : noop, true);\n\nexport { cancelFrame, frame, frameData, frameSteps };\n","import { MotionGlobalConfig } from 'motion-utils';\nimport { frameData } from './frame.mjs';\n\nlet now;\nfunction clearTime() {\n now = undefined;\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 */\nconst time = {\n now: () => {\n if (now === undefined) {\n time.set(frameData.isProcessing || MotionGlobalConfig.useManualTiming\n ? frameData.timestamp\n : performance.now());\n }\n return now;\n },\n set: (newTime) => {\n now = newTime;\n queueMicrotask(clearTime);\n },\n};\n\nexport { time };\n","const activeAnimations = {\n layout: 0,\n mainThread: 0,\n waapi: 0,\n};\n\nexport { activeAnimations };\n","const checkStringStartsWith = (token) => (key) => typeof key === \"string\" && key.startsWith(token);\nconst isCSSVariableName = \n/*@__PURE__*/ checkStringStartsWith(\"--\");\nconst startsAsVariableToken = \n/*@__PURE__*/ checkStringStartsWith(\"var(--\");\nconst isCSSVariableToken = (value) => {\n const startsWithToken = startsAsVariableToken(value);\n if (!startsWithToken)\n return false;\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};\nconst singleCssVariableRegex = /var\\(--(?:[\\w-]+\\s*|[\\w-]+\\s*,(?:\\s*[^)(\\s]|\\s*\\((?:[^)(]|\\([^)(]*\\))*\\))+\\s*)\\)$/iu;\n\nexport { isCSSVariableName, isCSSVariableToken };\n","import { clamp } from 'motion-utils';\n\nconst number = {\n test: (v) => typeof v === \"number\",\n parse: parseFloat,\n transform: (v) => v,\n};\nconst alpha = {\n ...number,\n transform: (v) => clamp(0, 1, v),\n};\nconst scale = {\n ...number,\n default: 1,\n};\n\nexport { alpha, number, scale };\n","// If this number is a decimal, make it just five decimal places\n// to avoid exponents\nconst sanitize = (v) => Math.round(v * 100000) / 100000;\n\nexport { sanitize };\n","const floatRegex = /-?(?:\\d+(?:\\.\\d+)?|\\.\\d+)/gu;\n\nexport { floatRegex };\n","function isNullish(v) {\n return v == null;\n}\n\nexport { isNullish };\n","const singleColorRegex = /^(?:#[\\da-f]{3,8}|(?:rgb|hsl)a?\\((?:-?[\\d.]+%?[,\\s]+){2}-?[\\d.]+%?\\s*(?:[,/]\\s*)?(?:\\b\\d+(?:\\.\\d+)?|\\.\\d+)?%?\\))$/iu;\n\nexport { singleColorRegex };\n","import { floatRegex } from '../utils/float-regex.mjs';\nimport { isNullish } from '../utils/is-nullish.mjs';\nimport { singleColorRegex } from '../utils/single-color-regex.mjs';\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 */\nconst isColorString = (type, testProp) => (v) => {\n return Boolean((typeof v === \"string\" &&\n singleColorRegex.test(v) &&\n v.startsWith(type)) ||\n (testProp &&\n !isNullish(v) &&\n Object.prototype.hasOwnProperty.call(v, testProp)));\n};\nconst splitColor = (aName, bName, cName) => (v) => {\n if (typeof v !== \"string\")\n return v;\n const [a, b, c, alpha] = v.match(floatRegex);\n return {\n [aName]: parseFloat(a),\n [bName]: parseFloat(b),\n [cName]: parseFloat(c),\n alpha: alpha !== undefined ? parseFloat(alpha) : 1,\n };\n};\n\nexport { isColorString, splitColor };\n","import { clamp } from 'motion-utils';\nimport { number, alpha } from '../numbers/index.mjs';\nimport { sanitize } from '../utils/sanitize.mjs';\nimport { isColorString, splitColor } from './utils.mjs';\n\nconst clampRgbUnit = (v) => clamp(0, 255, v);\nconst rgbUnit = {\n ...number,\n transform: (v) => Math.round(clampRgbUnit(v)),\n};\nconst rgba = {\n test: /*@__PURE__*/ isColorString(\"rgb\", \"red\"),\n parse: /*@__PURE__*/ splitColor(\"red\", \"green\", \"blue\"),\n transform: ({ red, green, blue, alpha: alpha$1 = 1 }) => \"rgba(\" +\n rgbUnit.transform(red) +\n \", \" +\n rgbUnit.transform(green) +\n \", \" +\n rgbUnit.transform(blue) +\n \", \" +\n sanitize(alpha.transform(alpha$1)) +\n \")\",\n};\n\nexport { rgbUnit, rgba };\n","import { rgba } from './rgba.mjs';\nimport { isColorString } from './utils.mjs';\n\nfunction parseHex(v) {\n let r = \"\";\n let g = \"\";\n let b = \"\";\n let a = \"\";\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 // Or we have 3 characters, ie #F00\n }\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 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}\nconst hex = {\n test: /*@__PURE__*/ isColorString(\"#\"),\n parse: parseHex,\n transform: rgba.transform,\n};\n\nexport { hex };\n","/*#__NO_SIDE_EFFECTS__*/\nconst createUnitType = (unit) => ({\n test: (v) => typeof v === \"string\" && v.endsWith(unit) && v.split(\" \").length === 1,\n parse: parseFloat,\n transform: (v) => `${v}${unit}`,\n});\nconst degrees = /*@__PURE__*/ createUnitType(\"deg\");\nconst percent = /*@__PURE__*/ createUnitType(\"%\");\nconst px = /*@__PURE__*/ createUnitType(\"px\");\nconst vh = /*@__PURE__*/ createUnitType(\"vh\");\nconst vw = /*@__PURE__*/ createUnitType(\"vw\");\nconst progressPercentage = /*@__PURE__*/ (() => ({\n ...percent,\n parse: (v) => percent.parse(v) / 100,\n transform: (v) => percent.transform(v * 100),\n}))();\n\nexport { degrees, percent, progressPercentage, px, vh, vw };\n","import { alpha } from '../numbers/index.mjs';\nimport { percent } from '../numbers/units.mjs';\nimport { sanitize } from '../utils/sanitize.mjs';\nimport { isColorString, splitColor } from './utils.mjs';\n\nconst hsla = {\n test: /*@__PURE__*/ isColorString(\"hsl\", \"hue\"),\n parse: /*@__PURE__*/ splitColor(\"hue\", \"saturation\", \"lightness\"),\n transform: ({ hue, saturation, lightness, alpha: alpha$1 = 1 }) => {\n return (\"hsla(\" +\n Math.round(hue) +\n \", \" +\n percent.transform(sanitize(saturation)) +\n \", \" +\n percent.transform(sanitize(lightness)) +\n \", \" +\n sanitize(alpha.transform(alpha$1)) +\n \")\");\n },\n};\n\nexport { hsla };\n","import { hex } from './hex.mjs';\nimport { hsla } from './hsla.mjs';\nimport { rgba } from './rgba.mjs';\n\nconst color = {\n test: (v) => rgba.test(v) || hex.test(v) || hsla.test(v),\n parse: (v) => {\n if (rgba.test(v)) {\n return rgba.parse(v);\n }\n else if (hsla.test(v)) {\n return hsla.parse(v);\n }\n else {\n return hex.parse(v);\n }\n },\n transform: (v) => {\n return typeof v === \"string\"\n ? v\n : v.hasOwnProperty(\"red\")\n ? rgba.transform(v)\n : hsla.transform(v);\n },\n getAnimatableNone: (v) => {\n const parsed = color.parse(v);\n parsed.alpha = 0;\n return color.transform(parsed);\n },\n};\n\nexport { color };\n","const colorRegex = /(?:#[\\da-f]{3,8}|(?:rgb|hsl)a?\\((?:-?[\\d.]+%?[,\\s]+){2}-?[\\d.]+%?\\s*(?:[,/]\\s*)?(?:\\b\\d+(?:\\.\\d+)?|\\.\\d+)?%?\\))/giu;\n\nexport { colorRegex };\n","import { color } from '../color/index.mjs';\nimport { colorRegex } from '../utils/color-regex.mjs';\nimport { floatRegex } from '../utils/float-regex.mjs';\nimport { sanitize } from '../utils/sanitize.mjs';\n\nfunction test(v) {\n return (isNaN(v) &&\n typeof v === \"string\" &&\n (v.match(floatRegex)?.length || 0) +\n (v.match(colorRegex)?.length || 0) >\n 0);\n}\nconst NUMBER_TOKEN = \"number\";\nconst COLOR_TOKEN = \"color\";\nconst VAR_TOKEN = \"var\";\nconst VAR_FUNCTION_TOKEN = \"var(\";\nconst SPLIT_TOKEN = \"${}\";\n// this regex consists of the `singleCssVariableRegex|rgbHSLValueRegex|digitRegex`\nconst complexRegex = /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;\nfunction analyseComplexValue(value) {\n const originalValue = value.toString();\n const values = [];\n const indexes = {\n color: [],\n number: [],\n var: [],\n };\n const types = [];\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 }\n else if (parsedValue.startsWith(VAR_FUNCTION_TOKEN)) {\n indexes.var.push(i);\n types.push(VAR_TOKEN);\n values.push(parsedValue);\n }\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 return { values, split, indexes, types };\n}\nfunction parseComplexValue(v) {\n return analyseComplexValue(v).values;\n}\nfunction createTransformer(source) {\n const { split, types } = analyseComplexValue(source);\n const numSections = split.length;\n return (v) => {\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]);\n }\n else if (type === COLOR_TOKEN) {\n output += color.transform(v[i]);\n }\n else {\n output += v[i];\n }\n }\n }\n return output;\n };\n}\nconst convertNumbersToZero = (v) => typeof v === \"number\" ? 0 : color.test(v) ? color.getAnimatableNone(v) : v;\nfunction getAnimatableNone(v) {\n const parsed = parseComplexValue(v);\n const transformer = createTransformer(v);\n return transformer(parsed.map(convertNumbersToZero));\n}\nconst complex = {\n test,\n parse: parseComplexValue,\n createTransformer,\n getAnimatableNone,\n};\n\nexport { analyseComplexValue, complex };\n","// Adapted from https://gist.github.com/mjackson/5311256\nfunction hueToRgb(p, q, t) {\n if (t < 0)\n t += 1;\n if (t > 1)\n t -= 1;\n if (t < 1 / 6)\n return p + (q - p) * 6 * t;\n if (t < 1 / 2)\n return q;\n if (t < 2 / 3)\n return p + (q - p) * (2 / 3 - t) * 6;\n return p;\n}\nfunction hslaToRgba({ hue, saturation, lightness, alpha }) {\n hue /= 360;\n saturation /= 100;\n lightness /= 100;\n let red = 0;\n let green = 0;\n let blue = 0;\n if (!saturation) {\n red = green = blue = lightness;\n }\n else {\n const q = lightness < 0.5\n ? lightness * (1 + saturation)\n : lightness + saturation - lightness * saturation;\n const p = 2 * lightness - q;\n red = hueToRgb(p, q, hue + 1 / 3);\n green = hueToRgb(p, q, hue);\n blue = hueToRgb(p, q, hue - 1 / 3);\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\nexport { hslaToRgba };\n","function mixImmediate(a, b) {\n return (p) => (p > 0 ? b : a);\n}\n\nexport { mixImmediate };\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*/\nconst mixNumber = (from, to, progress) => {\n return from + (to - from) * progress;\n};\n\nexport { mixNumber };\n","import { warning } from 'motion-utils';\nimport { hex } from '../../value/types/color/hex.mjs';\nimport { hsla } from '../../value/types/color/hsla.mjs';\nimport { hslaToRgba } from '../../value/types/color/hsla-to-rgba.mjs';\nimport { rgba } from '../../value/types/color/rgba.mjs';\nimport { mixImmediate } from './immediate.mjs';\nimport { mixNumber } from './number.mjs';\n\n// Linear color space blending\n// Explained https://www.youtube.com/watch?v=LKnqECcg6Gw\n// Demonstrated http://codepen.io/osublake/pen/xGVVaN\nconst mixLinearColor = (from, to, v) => {\n const fromExpo = from * from;\n const expo = v * (to * to - fromExpo) + fromExpo;\n return expo < 0 ? 0 : Math.sqrt(expo);\n};\nconst colorTypes = [hex, rgba, hsla];\nconst getColorType = (v) => colorTypes.find((type) => type.test(v));\nfunction asRGBA(color) {\n const type = getColorType(color);\n warning(Boolean(type), `'${color}' is not an animatable color. Use the equivalent color code instead.`, \"color-not-animatable\");\n if (!Boolean(type))\n return false;\n let model = type.parse(color);\n if (type === hsla) {\n // TODO Remove this cast - needed since Motion's stricter typing\n model = hslaToRgba(model);\n }\n return model;\n}\nconst mixColor = (from, to) => {\n const fromRGBA = asRGBA(from);\n const toRGBA = asRGBA(to);\n if (!fromRGBA || !toRGBA) {\n return mixImmediate(from, to);\n }\n const blended = { ...fromRGBA };\n return (v) => {\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\nexport { mixColor, mixLinearColor };\n","const invisibleValues = new Set([\"none\", \"hidden\"]);\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 */\nfunction mixVisibility(origin, target) {\n if (invisibleValues.has(origin)) {\n return (p) => (p <= 0 ? origin : target);\n }\n else {\n return (p) => (p >= 1 ? target : origin);\n }\n}\n\nexport { invisibleValues, mixVisibility };\n","import { pipe, warning } from 'motion-utils';\nimport { isCSSVariableToken } from '../../animation/utils/is-css-variable.mjs';\nimport { color } from '../../value/types/color/index.mjs';\nimport { complex, analyseComplexValue } from '../../value/types/complex/index.mjs';\nimport { mixColor } from './color.mjs';\nimport { mixImmediate } from './immediate.mjs';\nimport { mixNumber as mixNumber$1 } from './number.mjs';\nimport { invisibleValues, mixVisibility } from './visibility.mjs';\n\nfunction mixNumber(a, b) {\n return (p) => mixNumber$1(a, b, p);\n}\nfunction getMixer(a) {\n if (typeof a === \"number\") {\n return mixNumber;\n }\n else if (typeof a === \"string\") {\n return isCSSVariableToken(a)\n ? mixImmediate\n : color.test(a)\n ? mixColor\n : mixComplex;\n }\n else if (Array.isArray(a)) {\n return mixArray;\n }\n else if (typeof a === \"object\") {\n return color.test(a) ? mixColor : mixObject;\n }\n return mixImmediate;\n}\nfunction mixArray(a, b) {\n const output = [...a];\n const numValues = output.length;\n const blendValue = a.map((v, i) => getMixer(v)(v, b[i]));\n return (p) => {\n for (let i = 0; i < numValues; i++) {\n output[i] = blendValue[i](p);\n }\n return output;\n };\n}\nfunction mixObject(a, b) {\n const output = { ...a, ...b };\n const blendValue = {};\n for (const key in output) {\n if (a[key] !== undefined && b[key] !== undefined) {\n blendValue[key] = getMixer(a[key])(a[key], b[key]);\n }\n }\n return (v) => {\n for (const key in blendValue) {\n output[key] = blendValue[key](v);\n }\n return output;\n };\n}\nfunction matchOrder(origin, target) {\n const orderedOrigin = [];\n const pointers = { color: 0, var: 0, number: 0 };\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 orderedOrigin[i] = originValue;\n pointers[type]++;\n }\n return orderedOrigin;\n}\nconst mixComplex = (origin, target) => {\n const template = complex.createTransformer(target);\n const originStats = analyseComplexValue(origin);\n const targetStats = analyseComplexValue(target);\n const canInterpolate = 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 if (canInterpolate) {\n if ((invisibleValues.has(origin) &&\n !targetStats.values.length) ||\n (invisibleValues.has(target) &&\n !originStats.values.length)) {\n return mixVisibility(origin, target);\n }\n return pipe(mixArray(matchOrder(originStats, targetStats), targetStats.values), template);\n }\n else {\n warning(true, `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.`, \"complex-values-different\");\n return mixImmediate(origin, target);\n }\n};\n\nexport { getMixer, mixArray, mixComplex, mixObject };\n","import { getMixer } from './complex.mjs';\nimport { mixNumber } from './number.mjs';\n\nfunction mix(from, to, p) {\n if (typeof from === \"number\" &&\n typeof to === \"number\" &&\n typeof p === \"number\") {\n return mixNumber(from, to, p);\n }\n const mixer = getMixer(from);\n return mixer(from, to);\n}\n\nexport { mix };\n","import { time } from '../../frameloop/sync-time.mjs';\nimport { frame, cancelFrame, frameData } from '../../frameloop/frame.mjs';\n\nconst frameloopDriver = (update) => {\n const passTimestamp = ({ timestamp }) => update(timestamp);\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\nexport { frameloopDriver };\n","const generateLinearEasing = (easing, duration, // as milliseconds\nresolution = 10 // as milliseconds\n) => {\n let points = \"\";\n const numPoints = Math.max(Math.round(duration / resolution), 2);\n for (let i = 0; i < numPoints; i++) {\n points += Math.round(easing(i / (numPoints - 1)) * 10000) / 10000 + \", \";\n }\n return `linear(${points.substring(0, points.length - 2)})`;\n};\n\nexport { generateLinearEasing };\n","/**\n * Implement a practical max duration for keyframe generation\n * to prevent infinite loops\n */\nconst maxGeneratorDuration = 20000;\nfunction calcGeneratorDuration(generator) {\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 return duration >= maxGeneratorDuration ? Infinity : duration;\n}\n\nexport { calcGeneratorDuration, maxGeneratorDuration };\n","import { millisecondsToSeconds } from 'motion-utils';\nimport { calcGeneratorDuration, maxGeneratorDuration } from './calc-duration.mjs';\n\n/**\n * Create a progress => progress easing function from a generator.\n */\nfunction createGeneratorEasing(options, scale = 100, createGenerator) {\n const generator = createGenerator({ ...options, keyframes: [0, scale] });\n const duration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration);\n return {\n type: \"keyframes\",\n ease: (progress) => {\n return generator.next(duration * progress).value / scale;\n },\n duration: millisecondsToSeconds(duration),\n };\n}\n\nexport { createGeneratorEasing };\n","import { velocityPerSecond } from 'motion-utils';\n\nconst velocitySampleDuration = 5; // ms\nfunction calcGeneratorVelocity(resolveValue, t, current) {\n const prevT = Math.max(t - velocitySampleDuration, 0);\n return velocityPerSecond(current - resolveValue(prevT), t - prevT);\n}\n\nexport { calcGeneratorVelocity };\n","const springDefaults = {\n // Default spring physics\n stiffness: 100,\n damping: 10,\n mass: 1.0,\n velocity: 0.0,\n // Default duration/bounce-based options\n duration: 800, // in ms\n bounce: 0.3,\n visualDuration: 0.3, // in seconds\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 // Limits\n minDuration: 0.01, // in seconds\n maxDuration: 10.0, // in seconds\n minDamping: 0.05,\n maxDamping: 1,\n};\n\nexport { springDefaults };\n","import { warning, secondsToMilliseconds, clamp, millisecondsToSeconds } from 'motion-utils';\nimport { springDefaults } from './defaults.mjs';\n\nconst safeMin = 0.001;\nfunction findSpring({ duration = springDefaults.duration, bounce = springDefaults.bounce, velocity = springDefaults.velocity, mass = springDefaults.mass, }) {\n let envelope;\n let derivative;\n warning(duration <= secondsToMilliseconds(springDefaults.maxDuration), \"Spring duration must be 10 seconds or less\", \"spring-duration-limit\");\n let dampingRatio = 1 - bounce;\n /**\n * Restrict dampingRatio and duration to within acceptable ranges.\n */\n dampingRatio = clamp(springDefaults.minDamping, springDefaults.maxDamping, dampingRatio);\n duration = clamp(springDefaults.minDuration, springDefaults.maxDuration, millisecondsToSeconds(duration));\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 derivative = (undampedFreq) => {\n const exponentialDecay = undampedFreq * dampingRatio;\n const delta = exponentialDecay * duration;\n const d = delta * velocity + velocity;\n const e = 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 }\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 derivative = (undampedFreq) => {\n const a = Math.exp(-undampedFreq * duration);\n const b = (velocity - undampedFreq) * (duration * duration);\n return a * b;\n };\n }\n const initialGuess = 5 / duration;\n const undampedFreq = approximateRoot(envelope, derivative, initialGuess);\n duration = secondsToMilliseconds(duration);\n if (isNaN(undampedFreq)) {\n return {\n stiffness: springDefaults.stiffness,\n damping: springDefaults.damping,\n duration,\n };\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}\nconst rootIterations = 12;\nfunction approximateRoot(envelope, derivative, initialGuess) {\n let result = initialGuess;\n for (let i = 1; i < rootIterations; i++) {\n result = result - envelope(result) / derivative(result);\n }\n return result;\n}\nfunction calcAngularFreq(undampedFreq, dampingRatio) {\n return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio);\n}\n\nexport { calcAngularFreq, findSpring };\n","import { millisecondsToSeconds, secondsToMilliseconds, clamp } from 'motion-utils';\nimport { generateLinearEasing } from '../../waapi/utils/linear.mjs';\nimport { calcGeneratorDuration, maxGeneratorDuration } from '../utils/calc-duration.mjs';\nimport { createGeneratorEasing } from '../utils/create-generator-easing.mjs';\nimport { calcGeneratorVelocity } from '../utils/velocity.mjs';\nimport { springDefaults } from './defaults.mjs';\nimport { findSpring, calcAngularFreq } from './find.mjs';\n\nconst durationKeys = [\"duration\", \"bounce\"];\nconst physicsKeys = [\"stiffness\", \"damping\", \"mass\"];\nfunction isSpringType(options, keys) {\n return keys.some((key) => options[key] !== undefined);\n}\nfunction getSpringOptions(options) {\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 (!isSpringType(options, physicsKeys) &&\n isSpringType(options, durationKeys)) {\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 = 2 *\n clamp(0.05, 1, 1 - (options.bounce || 0)) *\n Math.sqrt(stiffness);\n springOptions = {\n ...springOptions,\n mass: springDefaults.mass,\n stiffness,\n damping,\n };\n }\n else {\n const derived = findSpring(options);\n springOptions = {\n ...springOptions,\n ...derived,\n mass: springDefaults.mass,\n };\n springOptions.isResolvedFromDuration = true;\n }\n }\n return springOptions;\n}\nfunction spring(optionsOrVisualDuration = springDefaults.visualDuration, bounce = springDefaults.bounce) {\n const options = typeof optionsOrVisualDuration !== \"object\"\n ? {\n visualDuration: optionsOrVisualDuration,\n keyframes: [0, 1],\n bounce,\n }\n : optionsOrVisualDuration;\n let { restSpeed, restDelta } = options;\n const origin = options.keyframes[0];\n const target = options.keyframes[options.keyframes.length - 1];\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 = { done: false, value: origin };\n const { stiffness, damping, mass, duration, velocity, isResolvedFromDuration, } = getSpringOptions({\n ...options,\n velocity: -millisecondsToSeconds(options.velocity || 0),\n });\n const initialVelocity = velocity || 0.0;\n const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass));\n const initialDelta = target - origin;\n const undampedAngularFreq = millisecondsToSeconds(Math.sqrt(stiffness / mass));\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 || (restSpeed = isGranularScale\n ? springDefaults.restSpeed.granular\n : springDefaults.restSpeed.default);\n restDelta || (restDelta = isGranularScale\n ? springDefaults.restDelta.granular\n : springDefaults.restDelta.default);\n let resolveSpring;\n if (dampingRatio < 1) {\n const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio);\n // Underdamped spring\n resolveSpring = (t) => {\n const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);\n return (target -\n envelope *\n (((initialVelocity +\n dampingRatio * undampedAngularFreq * initialDelta) /\n angularFreq) *\n Math.sin(angularFreq * t) +\n initialDelta * Math.cos(angularFreq * t)));\n };\n }\n else if (dampingRatio === 1) {\n // Critically damped spring\n resolveSpring = (t) => target -\n Math.exp(-undampedAngularFreq * t) *\n (initialDelta +\n (initialVelocity + undampedAngularFreq * initialDelta) * t);\n }\n else {\n // Overdamped spring\n const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1);\n resolveSpring = (t) => {\n const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);\n // When performing sinh or cosh values can hit Infinity so we cap them here\n const freqForT = Math.min(dampedAngularFreq * t, 300);\n return (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 const generator = {\n calculatedDuration: isResolvedFromDuration ? duration || null : null,\n next: (t) => {\n const current = resolveSpring(t);\n if (!isResolvedFromDuration) {\n let currentVelocity = t === 0 ? initialVelocity : 0.0;\n /**\n * We only need to calculate velocity for under-damped springs\n * as over- and critically-damped springs can't overshoot, so\n * checking only for displacement is enough.\n */\n if (dampingRatio < 1) {\n currentVelocity =\n t === 0\n ? secondsToMilliseconds(initialVelocity)\n : calcGeneratorVelocity(resolveSpring, t, current);\n }\n const isBelowVelocityThreshold = Math.abs(currentVelocity) <= restSpeed;\n const isBelowDisplacementThreshold = Math.abs(target - current) <= restDelta;\n state.done =\n isBelowVelocityThreshold && isBelowDisplacementThreshold;\n }\n else {\n state.done = t >= duration;\n }\n state.value = state.done ? target : current;\n return state;\n },\n toString: () => {\n const calculatedDuration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration);\n const easing = generateLinearEasing((progress) => generator.next(calculatedDuration * progress).value, calculatedDuration, 30);\n return calculatedDuration + \"ms \" + easing;\n },\n toTransition: () => { },\n };\n return generator;\n}\nspring.applyToOptions = (options) => {\n const generatorOptions = createGeneratorEasing(options, 100, spring);\n options.ease = generatorOptions.ease;\n options.duration = secondsToMilliseconds(generatorOptions.duration);\n options.type = \"keyframes\";\n return options;\n};\n\nexport { spring };\n","import { spring } from './spring/index.mjs';\nimport { calcGeneratorVelocity } from './utils/velocity.mjs';\n\nfunction inertia({ keyframes, velocity = 0.0, power = 0.8, timeConstant = 325, bounceDamping = 10, bounceStiffness = 500, modifyTarget, min, max, restDelta = 0.5, restSpeed, }) {\n const origin = keyframes[0];\n const state = {\n done: false,\n value: origin,\n };\n const isOutOfBounds = (v) => (min !== undefined && v < min) || (max !== undefined && v > max);\n const nearestBoundary = (v) => {\n if (min === undefined)\n return max;\n if (max === undefined)\n return min;\n return Math.abs(min - v) < Math.abs(max - v) ? min : max;\n };\n let amplitude = power * velocity;\n const ideal = origin + amplitude;\n const target = modifyTarget === undefined ? ideal : modifyTarget(ideal);\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)\n amplitude = target - origin;\n const calcDelta = (t) => -amplitude * Math.exp(-t / timeConstant);\n const calcLatest = (t) => target + calcDelta(t);\n const applyFriction = (t) => {\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 * 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;\n let spring$1;\n const checkCatchBoundary = (t) => {\n if (!isOutOfBounds(state.value))\n return;\n timeReachedBoundary = t;\n spring$1 = spring({\n keyframes: [state.value, nearestBoundary(state.value)],\n velocity: calcGeneratorVelocity(calcLatest, t, state.value), // TODO: This should be passing * 1000\n damping: bounceDamping,\n stiffness: bounceStiffness,\n restDelta,\n restSpeed,\n });\n };\n checkCatchBoundary(0);\n return {\n calculatedDuration: null,\n next: (t) => {\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$1 && timeReachedBoundary === undefined) {\n hasUpdatedFrame = true;\n applyFriction(t);\n checkCatchBoundary(t);\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$1.next(t - timeReachedBoundary);\n }\n else {\n !hasUpdatedFrame && applyFriction(t);\n return state;\n }\n },\n };\n}\n\nexport { inertia };\n","import { invariant, clamp, MotionGlobalConfig, noop, pipe, progress } from 'motion-utils';\nimport { mix } from './mix/index.mjs';\n\nfunction createMixers(output, ease, customMixer) {\n const mixers = [];\n const mixerFactory = customMixer || MotionGlobalConfig.mix || mix;\n const numMixers = output.length - 1;\n for (let i = 0; i < numMixers; i++) {\n let mixer = mixerFactory(output[i], output[i + 1]);\n if (ease) {\n const easingFunction = Array.isArray(ease) ? ease[i] || noop : ease;\n mixer = pipe(easingFunction, mixer);\n }\n mixers.push(mixer);\n }\n return mixers;\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 */\nfunction interpolate(input, output, { clamp: isClamp = true, ease, mixer } = {}) {\n const inputLength = input.length;\n invariant(inputLength === output.length, \"Both input and output ranges must be the same length\", \"range-length\");\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)\n return () => output[0];\n if (inputLength === 2 && output[0] === output[1])\n return () => output[1];\n const isZeroDeltaRange = input[0] === input[1];\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 const mixers = createMixers(output, ease, mixer);\n const numMixers = mixers.length;\n const interpolator = (v) => {\n if (isZeroDeltaRange && v < input[0])\n return output[0];\n let i = 0;\n if (numMixers > 1) {\n for (; i < input.length - 2; i++) {\n if (v < input[i + 1])\n break;\n }\n }\n const progressInRange = progress(input[i], input[i + 1], v);\n return mixers[i](progressInRange);\n };\n return isClamp\n ? (v) => interpolator(clamp(input[0], input[inputLength - 1], v))\n : interpolator;\n}\n\nexport { interpolate };\n","import { progress } from 'motion-utils';\nimport { mixNumber } from '../../../utils/mix/number.mjs';\n\nfunction fillOffset(offset, remaining) {\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\nexport { fillOffset };\n","import { fillOffset } from './fill.mjs';\n\nfunction defaultOffset(arr) {\n const offset = [0];\n fillOffset(offset, arr.length - 1);\n return offset;\n}\n\nexport { defaultOffset };\n","function convertOffsetToTimes(offset, duration) {\n return offset.map((o) => o * duration);\n}\n\nexport { convertOffsetToTimes };\n","import { easeInOut, isEasingArray, easingDefinitionToFunction } from 'motion-utils';\nimport { interpolate } from '../../utils/interpolate.mjs';\nimport { defaultOffset } from '../keyframes/offsets/default.mjs';\nimport { convertOffsetToTimes } from '../keyframes/offsets/time.mjs';\n\nfunction defaultEasing(values, easing) {\n return values.map(() => easing || easeInOut).splice(0, values.length - 1);\n}\nfunction keyframes({ duration = 300, keyframes: keyframeValues, times, ease = \"easeInOut\", }) {\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 * 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 = {\n done: false,\n value: keyframeValues[0],\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), duration);\n const mapTimeToKeyframe = interpolate(absoluteTimes, keyframeValues, {\n ease: Array.isArray(easingFunctions)\n ? easingFunctions\n : defaultEasing(keyframeValues, easingFunctions),\n });\n return {\n calculatedDuration: duration,\n next: (t) => {\n state.value = mapTimeToKeyframe(t);\n state.done = t >= duration;\n return state;\n },\n };\n}\n\nexport { defaultEasing, keyframes };\n","const isNotNull = (value) => value !== null;\nfunction getFinalKeyframe(keyframes, { repeat, repeatType = \"loop\" }, finalKeyframe, speed = 1) {\n const resolvedKeyframes = keyframes.filter(isNotNull);\n const useFirstKeyframe = speed < 0 || (repeat && repeatType !== \"loop\" && repeat % 2 === 1);\n const index = useFirstKeyframe ? 0 : resolvedKeyframes.length - 1;\n return !index || finalKeyframe === undefined\n ? resolvedKeyframes[index]\n : finalKeyframe;\n}\n\nexport { getFinalKeyframe };\n","import { inertia } from '../generators/inertia.mjs';\nimport { keyframes } from '../generators/keyframes.mjs';\nimport { spring } from '../generators/spring/index.mjs';\n\nconst transitionTypeMap = {\n decay: inertia,\n inertia,\n tween: keyframes,\n keyframes: keyframes,\n spring,\n};\nfunction replaceTransitionType(transition) {\n if (typeof transition.type === \"string\") {\n transition.type = transitionTypeMap[transition.type];\n }\n}\n\nexport { replaceTransitionType };\n","class WithPromise {\n constructor() {\n this.updateFinished();\n }\n get finished() {\n return this._finished;\n }\n updateFinished() {\n this._finished = new Promise((resolve) => {\n this.resolve = resolve;\n });\n }\n notifyFinished() {\n this.resolve();\n }\n /**\n * Allows the animation to be awaited.\n *\n * @deprecated Use `finished` instead.\n */\n then(onResolve, onReject) {\n return this.finished.then(onResolve, onReject);\n }\n}\n\nexport { WithPromise };\n","import { invariant, pipe, clamp, millisecondsToSeconds, secondsToMilliseconds } from 'motion-utils';\nimport { time } from '../frameloop/sync-time.mjs';\nimport { activeAnimations } from '../stats/animation-count.mjs';\nimport { mix } from '../utils/mix/index.mjs';\nimport { frameloopDriver } from './drivers/frame.mjs';\nimport { inertia } from './generators/inertia.mjs';\nimport { keyframes } from './generators/keyframes.mjs';\nimport { calcGeneratorDuration } from './generators/utils/calc-duration.mjs';\nimport { getFinalKeyframe } from './keyframes/get-final.mjs';\nimport { replaceTransitionType } from './utils/replace-transition-type.mjs';\nimport { WithPromise } from './utils/WithPromise.mjs';\n\nconst percentToProgress = (percent) => percent / 100;\nclass JSAnimation extends WithPromise {\n constructor(options) {\n super();\n this.state = \"idle\";\n this.startTime = null;\n this.isStopped = false;\n /**\n * The current time of the animation.\n */\n this.currentTime = 0;\n /**\n * The time at which the animation was paused.\n */\n this.holdTime = null;\n /**\n * Playback speed as a factor. 0 would be stopped, -1 reverse and 2 double speed.\n */\n this.playbackSpeed = 1;\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 this.stop = () => {\n const { motionValue } = this.options;\n if (motionValue && motionValue.updatedAt !== time.now()) {\n this.tick(time.now());\n }\n this.isStopped = true;\n if (this.state === \"idle\")\n return;\n this.teardown();\n this.options.onStop?.();\n };\n activeAnimations.mainThread++;\n this.options = options;\n this.initAnimation();\n this.play();\n if (options.autoplay === false)\n this.pause();\n }\n initAnimation() {\n const { options } = this;\n replaceTransitionType(options);\n const { type = keyframes, repeat = 0, repeatDelay = 0, repeatType, velocity = 0, } = options;\n let { keyframes: keyframes$1 } = options;\n const generatorFactory = type || keyframes;\n if (process.env.NODE_ENV !== \"production\" &&\n generatorFactory !== keyframes) {\n invariant(keyframes$1.length <= 2, `Only two keyframes currently supported with spring and inertia animations. Trying to animate ${keyframes$1}`, \"spring-two-frames\");\n }\n if (generatorFactory !== keyframes &&\n typeof keyframes$1[0] !== \"number\") {\n this.mixKeyframes = pipe(percentToProgress, mix(keyframes$1[0], keyframes$1[1]));\n keyframes$1 = [0, 100];\n }\n const generator = generatorFactory({ ...options, keyframes: keyframes$1 });\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$1].reverse(),\n velocity: -velocity,\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 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 updateTime(timestamp) {\n const animationTime = Math.round(timestamp - this.startTime) * this.playbackSpeed;\n // Update currentTime\n if (this.holdTime !== null) {\n this.currentTime = this.holdTime;\n }\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 tick(timestamp, sample = false) {\n const { generator, totalDuration, mixKeyframes, mirroredGenerator, resolvedDuration, calculatedDuration, } = this;\n if (this.startTime === null)\n return generator.next(0);\n const { delay = 0, keyframes, repeat, repeatType, repeatDelay, type, onUpdate, finalKeyframe, } = this.options;\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 }\n else if (this.speed < 0) {\n this.startTime = Math.min(timestamp - totalDuration / this.speed, this.startTime);\n }\n if (sample) {\n this.currentTime = timestamp;\n }\n else {\n this.updateTime(timestamp);\n }\n // Rebase on delay\n const timeWithoutDelay = this.currentTime - delay * (this.playbackSpeed >= 0 ? 1 : -1);\n const isInDelayPhase = this.playbackSpeed >= 0\n ? timeWithoutDelay < 0\n : timeWithoutDelay > totalDuration;\n this.currentTime = Math.max(timeWithoutDelay, 0);\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 let elapsed = this.currentTime;\n let frameGenerator = generator;\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 = Math.min(this.currentTime, totalDuration) / resolvedDuration;\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 * 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 * 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 iterationProgress === 1 && currentIteration--;\n currentIteration = Math.min(currentIteration, repeat + 1);\n /**\n * Reverse progress if we're not running in \"normal\" direction\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 }\n else if (repeatType === \"mirror\") {\n frameGenerator = mirroredGenerator;\n }\n }\n elapsed = clamp(0, 1, iterationProgress) * resolvedDuration;\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 const state = isInDelayPhase\n ? { done: false, value: keyframes[0] }\n : frameGenerator.next(elapsed);\n if (mixKeyframes) {\n state.value = mixKeyframes(state.value);\n }\n let { done } = state;\n if (!isInDelayPhase && calculatedDuration !== null) {\n done =\n this.playbackSpeed >= 0\n ? this.currentTime >= totalDuration\n : this.currentTime <= 0;\n }\n const isAnimationFinished = this.holdTime === null &&\n (this.state === \"finished\" || (this.state === \"running\" && done));\n // TODO: The exception for inertia could be cleaner here\n if (isAnimationFinished && type !== inertia) {\n state.value = getFinalKeyframe(keyframes, this.options, finalKeyframe, this.speed);\n }\n if (onUpdate) {\n onUpdate(state.value);\n }\n if (isAnimationFinished) {\n this.finish();\n }\n return state;\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, reject) {\n return this.finished.then(resolve, reject);\n }\n get duration() {\n return millisecondsToSeconds(this.calculatedDuration);\n }\n get iterationDuration() {\n const { delay = 0 } = this.options || {};\n return this.duration + millisecondsToSeconds(delay);\n }\n get time() {\n return millisecondsToSeconds(this.currentTime);\n }\n set time(newTime) {\n newTime = secondsToMilliseconds(newTime);\n this.currentTime = newTime;\n if (this.startTime === null ||\n this.holdTime !== null ||\n this.playbackSpeed === 0) {\n this.holdTime = newTime;\n }\n else if (this.driver) {\n this.startTime = this.driver.now() - newTime / this.playbackSpeed;\n }\n this.driver?.start(false);\n }\n get speed() {\n return this.playbackSpeed;\n }\n set speed(newSpeed) {\n this.updateTime(time.now());\n const hasChanged = this.playbackSpeed !== newSpeed;\n this.playbackSpeed = newSpeed;\n if (hasChanged) {\n this.time = millisecondsToSeconds(this.currentTime);\n }\n }\n play() {\n if (this.isStopped)\n return;\n const { driver = frameloopDriver, startTime } = this.options;\n if (!this.driver) {\n this.driver = driver((timestamp) => this.tick(timestamp));\n }\n this.options.onPlay?.();\n const now = this.driver.now();\n if (this.state === \"finished\") {\n this.updateFinished();\n this.startTime = now;\n }\n else if (this.holdTime !== null) {\n this.startTime = now - this.holdTime;\n }\n else if (!this.startTime) {\n this.startTime = startTime ?? now;\n }\n if (this.state === \"finished\" && this.speed < 0) {\n this.startTime += this.calculatedDuration;\n }\n this.holdTime = null;\n /**\n * Set playState to running only after we've used it in\n * the previous logic.\n */\n this.state = \"running\";\n this.driver.start();\n }\n pause() {\n this.state = \"paused\";\n this.updateTime(time.now());\n this.holdTime = this.currentTime;\n }\n complete() {\n if (this.state !== \"running\") {\n this.play();\n }\n this.state = \"finished\";\n this.holdTime = null;\n }\n finish() {\n this.notifyFinished();\n this.teardown();\n this.state = \"finished\";\n this.options.onComplete?.();\n }\n cancel() {\n this.holdTime = null;\n this.startTime = 0;\n this.tick(0);\n this.teardown();\n this.options.onCancel?.();\n }\n teardown() {\n this.state = \"idle\";\n this.stopDriver();\n this.startTime = this.holdTime = null;\n activeAnimations.mainThread--;\n }\n stopDriver() {\n if (!this.driver)\n return;\n this.driver.stop();\n this.driver = undefined;\n }\n sample(sampleTime) {\n this.startTime = 0;\n return this.tick(sampleTime, true);\n }\n attachTimeline(timeline) {\n if (this.options.allowFlatten) {\n this.options.type = \"keyframes\";\n this.options.ease = \"linear\";\n this.initAnimation();\n }\n this.driver?.stop();\n return timeline.observe(this);\n }\n}\n// Legacy function support\nfunction animateValue(options) {\n return new JSAnimation(options);\n}\n\nexport { JSAnimation, animateValue };\n","function fillWildcards(keyframes) {\n for (let i = 1; i < keyframes.length; i++) {\n keyframes[i] ?? (keyframes[i] = keyframes[i - 1]);\n }\n}\n\nexport { fillWildcards };\n","const radToDeg = (rad) => (rad * 180) / Math.PI;\nconst rotate = (v) => {\n const angle = radToDeg(Math.atan2(v[1], v[0]));\n return rebaseAngle(angle);\n};\nconst matrix2dParsers = {\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};\nconst rebaseAngle = (angle) => {\n angle = angle % 360;\n if (angle < 0)\n angle += 360;\n return angle;\n};\nconst rotateZ = rotate;\nconst scaleX = (v) => Math.sqrt(v[0] * v[0] + v[1] * v[1]);\nconst scaleY = (v) => Math.sqrt(v[4] * v[4] + v[5] * v[5]);\nconst matrix3dParsers = {\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};\nfunction defaultTransformValue(name) {\n return name.includes(\"scale\") ? 1 : 0;\n}\nfunction parseValueFromTransform(transform, name) {\n if (!transform || transform === \"none\") {\n return defaultTransformValue(name);\n }\n const matrix3dMatch = transform.match(/^matrix3d\\(([-\\d.e\\s,]+)\\)$/u);\n let parsers;\n let match;\n if (matrix3dMatch) {\n parsers = matrix3dParsers;\n match = matrix3dMatch;\n }\n else {\n const matrix2dMatch = transform.match(/^matrix\\(([-\\d.e\\s,]+)\\)$/u);\n parsers = matrix2dParsers;\n match = matrix2dMatch;\n }\n if (!match) {\n return defaultTransformValue(name);\n }\n const valueParser = parsers[name];\n const values = match[1].split(\",\").map(convertTransformToNumber);\n return typeof valueParser === \"function\"\n ? valueParser(values)\n : values[valueParser];\n}\nconst readTransformValue = (instance, name) => {\n const { transform = \"none\" } = getComputedStyle(instance);\n return parseValueFromTransform(transform, name);\n};\nfunction convertTransformToNumber(value) {\n return parseFloat(value.trim());\n}\n\nexport { defaultTransformValue, parseValueFromTransform, readTransformValue };\n","/**\n * Generate a list of every possible transform key.\n */\nconst 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 * A quick lookup for transform props.\n */\nconst transformProps = /*@__PURE__*/ (() => new Set(transformPropOrder))();\n\nexport { transformPropOrder, transformProps };\n","import { parseValueFromTransform } from '../../../render/dom/parse-transform.mjs';\nimport { transformPropOrder } from '../../../render/utils/keys-transform.mjs';\nimport { number } from '../../../value/types/numbers/index.mjs';\nimport { px } from '../../../value/types/numbers/units.mjs';\n\nconst isNumOrPxType = (v) => v === number || v === px;\nconst transformKeys = new Set([\"x\", \"y\", \"z\"]);\nconst nonTranslationalTransformKeys = transformPropOrder.filter((key) => !transformKeys.has(key));\nfunction removeNonTranslationalTransform(visualElement) {\n const removedTransforms = [];\n nonTranslationalTransformKeys.forEach((key) => {\n const value = visualElement.getValue(key);\n if (value !== undefined) {\n removedTransforms.push([key, value.get()]);\n value.set(key.startsWith(\"scale\") ? 1 : 0);\n }\n });\n return removedTransforms;\n}\nconst positionalValues = {\n // Dimensions\n width: ({ x }, { paddingLeft = \"0\", paddingRight = \"0\" }) => x.max - x.min - parseFloat(paddingLeft) - parseFloat(paddingRight),\n height: ({ y }, { paddingTop = \"0\", paddingBottom = \"0\" }) => y.max - y.min - parseFloat(paddingTop) - parseFloat(paddingBottom),\n top: (_bbox, { top }) => parseFloat(top),\n left: (_bbox, { left }) => parseFloat(left),\n bottom: ({ y }, { top }) => parseFloat(top) + (y.max - y.min),\n right: ({ x }, { left }) => parseFloat(left) + (x.max - x.min),\n // Transform\n x: (_bbox, { transform }) => parseValueFromTransform(transform, \"x\"),\n y: (_bbox, { transform }) => parseValueFromTransform(transform, \"y\"),\n};\n// Alias translate longform names\npositionalValues.translateX = positionalValues.x;\npositionalValues.translateY = positionalValues.y;\n\nexport { isNumOrPxType, positionalValues, removeNonTranslationalTransform };\n","import { fillWildcards } from './utils/fill-wildcards.mjs';\nimport { removeNonTranslationalTransform } from './utils/unit-conversion.mjs';\nimport { frame } from '../../frameloop/frame.mjs';\n\nconst toResolve = new Set();\nlet isScheduled = false;\nlet anyNeedsMeasurement = false;\nlet isForced = false;\nfunction measureAllKeyframes() {\n if (anyNeedsMeasurement) {\n const resolversToMeasure = Array.from(toResolve).filter((resolver) => resolver.needsMeasurement);\n const elementsToMeasure = new Set(resolversToMeasure.map((resolver) => resolver.element));\n const transformsToRestore = new Map();\n /**\n * Write pass\n * If we're measuring elements we want to remove bounding box-changing transforms.\n */\n elementsToMeasure.forEach((element) => {\n const removedTransforms = removeNonTranslationalTransform(element);\n if (!removedTransforms.length)\n return;\n transformsToRestore.set(element, removedTransforms);\n element.render();\n });\n // Read\n resolversToMeasure.forEach((resolver) => resolver.measureInitialState());\n // Write\n elementsToMeasure.forEach((element) => {\n element.render();\n const restore = transformsToRestore.get(element);\n if (restore) {\n restore.forEach(([key, value]) => {\n element.getValue(key)?.set(value);\n });\n }\n });\n // Read\n resolversToMeasure.forEach((resolver) => resolver.measureEndState());\n // Write\n resolversToMeasure.forEach((resolver) => {\n if (resolver.suspendedScrollY !== undefined) {\n window.scrollTo(0, resolver.suspendedScrollY);\n }\n });\n }\n anyNeedsMeasurement = false;\n isScheduled = false;\n toResolve.forEach((resolver) => resolver.complete(isForced));\n toResolve.clear();\n}\nfunction readAllKeyframes() {\n toResolve.forEach((resolver) => {\n resolver.readKeyframes();\n if (resolver.needsMeasurement) {\n anyNeedsMeasurement = true;\n }\n });\n}\nfunction flushKeyframeResolvers() {\n isForced = true;\n readAllKeyframes();\n measureAllKeyframes();\n isForced = false;\n}\nclass KeyframeResolver {\n constructor(unresolvedKeyframes, onComplete, name, motionValue, element, isAsync = false) {\n this.state = \"pending\";\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 this.isAsync = false;\n /**\n * Track whether this resolver needs to perform a measurement\n * to resolve its keyframes.\n */\n this.needsMeasurement = false;\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 scheduleResolve() {\n this.state = \"scheduled\";\n if (this.isAsync) {\n toResolve.add(this);\n if (!isScheduled) {\n isScheduled = true;\n frame.read(readAllKeyframes);\n frame.resolveKeyframes(measureAllKeyframes);\n }\n }\n else {\n this.readKeyframes();\n this.complete();\n }\n }\n readKeyframes() {\n const { unresolvedKeyframes, name, element, motionValue } = this;\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 // TODO: This doesn't work if the final keyframe is a wildcard\n const finalKeyframe = unresolvedKeyframes[unresolvedKeyframes.length - 1];\n if (currentValue !== undefined) {\n unresolvedKeyframes[0] = currentValue;\n }\n else if (element && name) {\n const valueAsRead = element.readValue(name, finalKeyframe);\n if (valueAsRead !== undefined && valueAsRead !== null) {\n unresolvedKeyframes[0] = valueAsRead;\n }\n }\n if (unresolvedKeyframes[0] === undefined) {\n unresolvedKeyframes[0] = finalKeyframe;\n }\n if (motionValue && currentValue === undefined) {\n motionValue.set(unresolvedKeyframes[0]);\n }\n }\n fillWildcards(unresolvedKeyframes);\n }\n setFinalKeyframe() { }\n measureInitialState() { }\n renderEndStyles() { }\n measureEndState() { }\n complete(isForcedComplete = false) {\n this.state = \"complete\";\n this.onComplete(this.unresolvedKeyframes, this.finalKeyframe, isForcedComplete);\n toResolve.delete(this);\n }\n cancel() {\n if (this.state === \"scheduled\") {\n toResolve.delete(this);\n this.state = \"pending\";\n }\n }\n resume() {\n if (this.state === \"pending\")\n this.scheduleResolve();\n }\n}\n\nexport { KeyframeResolver, flushKeyframeResolvers };\n","const isCSSVar = (name) => name.startsWith(\"--\");\n\nexport { isCSSVar };\n","import { isCSSVar } from './is-css-var.mjs';\n\nfunction setStyle(element, name, value) {\n isCSSVar(name)\n ? element.style.setProperty(name, value)\n : (element.style[name] = value);\n}\n\nexport { setStyle };\n","import { memo } from 'motion-utils';\n\nconst supportsScrollTimeline = /* @__PURE__ */ memo(() => window.ScrollTimeline !== undefined);\n\nexport { supportsScrollTimeline };\n","/**\n * Add the ability for test suites to manually set support flags\n * to better test more environments.\n */\nconst supportsFlags = {};\n\nexport { supportsFlags };\n","import { memo } from 'motion-utils';\nimport { supportsFlags } from './flags.mjs';\n\nfunction memoSupports(callback, supportsFlag) {\n const memoized = memo(callback);\n return () => supportsFlags[supportsFlag] ?? memoized();\n}\n\nexport { memoSupports };\n","import { memoSupports } from './memo.mjs';\n\nconst supportsLinearEasing = /*@__PURE__*/ memoSupports(() => {\n try {\n document\n .createElement(\"div\")\n .animate({ opacity: 0 }, { easing: \"linear(0, 1)\" });\n }\n catch (e) {\n return false;\n }\n return true;\n}, \"linearEasing\");\n\nexport { supportsLinearEasing };\n","const cubicBezierAsString = ([a, b, c, d]) => `cubic-bezier(${a}, ${b}, ${c}, ${d})`;\n\nexport { cubicBezierAsString };\n","import { cubicBezierAsString } from './cubic-bezier.mjs';\n\nconst 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\nexport { supportedWaapiEasing };\n","import { isBezierDefinition } from 'motion-utils';\nimport { supportsLinearEasing } from '../../../utils/supports/linear-easing.mjs';\nimport { generateLinearEasing } from '../utils/linear.mjs';\nimport { cubicBezierAsString } from './cubic-bezier.mjs';\nimport { supportedWaapiEasing } from './supported.mjs';\n\nfunction mapEasingToNativeEasing(easing, duration) {\n if (!easing) {\n return undefined;\n }\n else if (typeof easing === \"function\") {\n return supportsLinearEasing()\n ? generateLinearEasing(easing, duration)\n : \"ease-out\";\n }\n else if (isBezierDefinition(easing)) {\n return cubicBezierAsString(easing);\n }\n else if (Array.isArray(easing)) {\n return easing.map((segmentEasing) => mapEasingToNativeEasing(segmentEasing, duration) ||\n supportedWaapiEasing.easeOut);\n }\n else {\n return supportedWaapiEasing[easing];\n }\n}\n\nexport { mapEasingToNativeEasing };\n","import { activeAnimations } from '../../stats/animation-count.mjs';\nimport { statsBuffer } from '../../stats/buffer.mjs';\nimport { mapEasingToNativeEasing } from './easing/map-easing.mjs';\n\nfunction startWaapiAnimation(element, valueName, keyframes, { delay = 0, duration = 300, repeat = 0, repeatType = \"loop\", ease = \"easeOut\", times, } = {}, pseudoElement = undefined) {\n const keyframeOptions = {\n [valueName]: keyframes,\n };\n if (times)\n keyframeOptions.offset = times;\n const easing = mapEasingToNativeEasing(ease, duration);\n /**\n * If this is an easing array, apply to keyframes, not animation as a whole\n */\n if (Array.isArray(easing))\n keyframeOptions.easing = easing;\n if (statsBuffer.value) {\n activeAnimations.waapi++;\n }\n const options = {\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 if (pseudoElement)\n options.pseudoElement = pseudoElement;\n const animation = element.animate(keyframeOptions, options);\n if (statsBuffer.value) {\n animation.finished.finally(() => {\n activeAnimations.waapi--;\n });\n }\n return animation;\n}\n\nexport { startWaapiAnimation };\n","function isGenerator(type) {\n return typeof type === \"function\" && \"applyToOptions\" in type;\n}\n\nexport { isGenerator };\n","import { supportsLinearEasing } from '../../../utils/supports/linear-easing.mjs';\nimport { isGenerator } from '../../generators/utils/is-generator.mjs';\n\nfunction applyGeneratorOptions({ type, ...options }) {\n if (isGenerator(type) && supportsLinearEasing()) {\n return type.applyToOptions(options);\n }\n else {\n options.duration ?? (options.duration = 300);\n options.ease ?? (options.ease = \"easeOut\");\n }\n return options;\n}\n\nexport { applyGeneratorOptions };\n","import { invariant, millisecondsToSeconds, secondsToMilliseconds, noop } from 'motion-utils';\nimport { setStyle } from '../render/dom/style-set.mjs';\nimport { supportsScrollTimeline } from '../utils/supports/scroll-timeline.mjs';\nimport { getFinalKeyframe } from './keyframes/get-final.mjs';\nimport { WithPromise } from './utils/WithPromise.mjs';\nimport { startWaapiAnimation } from './waapi/start-waapi-animation.mjs';\nimport { applyGeneratorOptions } from './waapi/utils/apply-generator.mjs';\n\n/**\n * NativeAnimation implements AnimationPlaybackControls for the browser's Web Animations API.\n */\nclass NativeAnimation extends WithPromise {\n constructor(options) {\n super();\n this.finishedTime = null;\n this.isStopped = false;\n if (!options)\n return;\n const { element, name, keyframes, pseudoElement, allowFlatten = false, finalKeyframe, onComplete, } = options;\n this.isPseudoElement = Boolean(pseudoElement);\n this.allowFlatten = allowFlatten;\n this.options = options;\n invariant(typeof options.type !== \"string\", `Mini animate() doesn't support \"type\" as a string.`, \"mini-spring\");\n const transition = applyGeneratorOptions(options);\n this.animation = startWaapiAnimation(element, name, keyframes, transition, pseudoElement);\n if (transition.autoplay === false) {\n this.animation.pause();\n }\n this.animation.onfinish = () => {\n this.finishedTime = this.time;\n if (!pseudoElement) {\n const keyframe = getFinalKeyframe(keyframes, this.options, finalKeyframe, this.speed);\n if (this.updateMotionValue) {\n this.updateMotionValue(keyframe);\n }\n else {\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 */\n setStyle(element, name, keyframe);\n }\n this.animation.cancel();\n }\n onComplete?.();\n this.notifyFinished();\n };\n }\n play() {\n if (this.isStopped)\n return;\n this.animation.play();\n if (this.state === \"finished\") {\n this.updateFinished();\n }\n }\n pause() {\n this.animation.pause();\n }\n complete() {\n this.animation.finish?.();\n }\n cancel() {\n try {\n this.animation.cancel();\n }\n catch (e) { }\n }\n stop() {\n if (this.isStopped)\n return;\n this.isStopped = true;\n const { state } = this;\n if (state === \"idle\" || state === \"finished\") {\n return;\n }\n if (this.updateMotionValue) {\n this.updateMotionValue();\n }\n else {\n this.commitStyles();\n }\n if (!this.isPseudoElement)\n this.cancel();\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 commitStyles() {\n if (!this.isPseudoElement) {\n this.animation.commitStyles?.();\n }\n }\n get duration() {\n const duration = this.animation.effect?.getComputedTiming?.().duration || 0;\n return millisecondsToSeconds(Number(duration));\n }\n get iterationDuration() {\n const { delay = 0 } = this.options || {};\n return this.duration + millisecondsToSeconds(delay);\n }\n get time() {\n return millisecondsToSeconds(Number(this.animation.currentTime) || 0);\n }\n set time(newTime) {\n this.finishedTime = null;\n this.animation.currentTime = secondsToMilliseconds(newTime);\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 set speed(newSpeed) {\n // Allow backwards playback after finishing\n if (newSpeed < 0)\n this.finishedTime = null;\n this.animation.playbackRate = newSpeed;\n }\n get state() {\n return this.finishedTime !== null\n ? \"finished\"\n : this.animation.playState;\n }\n get startTime() {\n return Number(this.animation.startTime);\n }\n set startTime(newStartTime) {\n this.animation.startTime = newStartTime;\n }\n /**\n * Attaches a timeline to the animation, for instance the `ScrollTimeline`.\n */\n attachTimeline({ timeline, observe }) {\n if (this.allowFlatten) {\n this.animation.effect?.updateTiming({ easing: \"linear\" });\n }\n this.animation.onfinish = null;\n if (timeline && supportsScrollTimeline()) {\n this.animation.timeline = timeline;\n return noop;\n }\n else {\n return observe(this);\n }\n }\n}\n\nexport { NativeAnimation };\n","import { anticipate, backInOut, circInOut } from 'motion-utils';\n\nconst unsupportedEasingFunctions = {\n anticipate,\n backInOut,\n circInOut,\n};\nfunction isUnsupportedEase(key) {\n return key in unsupportedEasingFunctions;\n}\nfunction replaceStringEasing(transition) {\n if (typeof transition.ease === \"string\" &&\n isUnsupportedEase(transition.ease)) {\n transition.ease = unsupportedEasingFunctions[transition.ease];\n }\n}\n\nexport { replaceStringEasing };\n","import { secondsToMilliseconds } from 'motion-utils';\nimport { JSAnimation } from './JSAnimation.mjs';\nimport { NativeAnimation } from './NativeAnimation.mjs';\nimport { replaceTransitionType } from './utils/replace-transition-type.mjs';\nimport { replaceStringEasing } from './waapi/utils/unsupported-easing.mjs';\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\nclass NativeAnimationExtended extends NativeAnimation {\n constructor(options) {\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 * 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 super(options);\n if (options.startTime) {\n this.startTime = options.startTime;\n }\n this.options = options;\n }\n /**\n * WAAPI doesn't natively have any interruption capabilities.\n *\n * Rather than read commited 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) {\n const { motionValue, onUpdate, onComplete, element, ...options } = this.options;\n if (!motionValue)\n return;\n if (value !== undefined) {\n motionValue.set(value);\n return;\n }\n const sampleAnimation = new JSAnimation({\n ...options,\n autoplay: false,\n });\n const sampleTime = secondsToMilliseconds(this.finishedTime ?? this.time);\n motionValue.setWithVelocity(sampleAnimation.sample(sampleTime - sampleDelta).value, sampleAnimation.sample(sampleTime).value, sampleDelta);\n sampleAnimation.stop();\n }\n}\n\nexport { NativeAnimationExtended };\n","import { complex } from '../../value/types/complex/index.mjs';\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 */\nconst isAnimatable = (value, name) => {\n // If the list of keys that might be non-animatable grows, replace with Set\n if (name === \"zIndex\")\n return false;\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))\n return true;\n if (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 return false;\n};\n\nexport { isAnimatable };\n","import { warning } from 'motion-utils';\nimport { isGenerator } from '../generators/utils/is-generator.mjs';\nimport { isAnimatable } from './is-animatable.mjs';\n\nfunction hasKeyframesChanged(keyframes) {\n const current = keyframes[0];\n if (keyframes.length === 1)\n return true;\n for (let i = 0; i < keyframes.length; i++) {\n if (keyframes[i] !== current)\n return true;\n }\n}\nfunction canAnimate(keyframes, name, type, velocity) {\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 * 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\")\n return true;\n const targetKeyframe = keyframes[keyframes.length - 1];\n const isOriginAnimatable = isAnimatable(originKeyframe, name);\n const isTargetAnimatable = isAnimatable(targetKeyframe, name);\n warning(isOriginAnimatable === isTargetAnimatable, `You are trying to animate ${name} from \"${originKeyframe}\" to \"${targetKeyframe}\". \"${isOriginAnimatable ? targetKeyframe : originKeyframe}\" is not an animatable value.`, \"value-not-animatable\");\n // Always skip if any of these are true\n if (!isOriginAnimatable || !isTargetAnimatable) {\n return false;\n }\n return (hasKeyframesChanged(keyframes) ||\n ((type === \"spring\" || isGenerator(type)) && velocity));\n}\n\nexport { canAnimate };\n","function makeAnimationInstant(options) {\n options.duration = 0;\n options.type = \"keyframes\";\n}\n\nexport { makeAnimationInstant };\n","import { memo } from 'motion-utils';\n\n/**\n * A list of values that can be hardware-accelerated.\n */\nconst acceleratedValues = new Set([\n \"opacity\",\n \"clipPath\",\n \"filter\",\n \"transform\",\n // TODO: Could be re-enabled now we have support for linear() easing\n // \"background-color\"\n]);\nconst supportsWaapi = /*@__PURE__*/ memo(() => Object.hasOwnProperty.call(Element.prototype, \"animate\"));\nfunction supportsBrowserAnimation(options) {\n const { motionValue, name, repeatDelay, repeatType, damping, type } = options;\n const subject = motionValue?.owner?.current;\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 const { onUpdate, transformTemplate } = motionValue.owner.getProps();\n return (supportsWaapi() &&\n name &&\n acceleratedValues.has(name) &&\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\nexport { supportsBrowserAnimation };\n","import { MotionGlobalConfig, noop } from 'motion-utils';\nimport { time } from '../frameloop/sync-time.mjs';\nimport { JSAnimation } from './JSAnimation.mjs';\nimport { getFinalKeyframe } from './keyframes/get-final.mjs';\nimport { KeyframeResolver, flushKeyframeResolvers } from './keyframes/KeyframesResolver.mjs';\nimport { NativeAnimationExtended } from './NativeAnimationExtended.mjs';\nimport { canAnimate } from './utils/can-animate.mjs';\nimport { makeAnimationInstant } from './utils/make-animation-instant.mjs';\nimport { WithPromise } from './utils/WithPromise.mjs';\nimport { supportsBrowserAnimation } from './waapi/supports/waapi.mjs';\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;\nclass AsyncMotionValueAnimation extends WithPromise {\n constructor({ autoplay = true, delay = 0, type = \"keyframes\", repeat = 0, repeatDelay = 0, repeatType = \"loop\", keyframes, name, motionValue, element, ...options }) {\n super();\n /**\n * Bound to support return animation.stop pattern\n */\n this.stop = () => {\n if (this._animation) {\n this._animation.stop();\n this.stopTimeline?.();\n }\n this.keyframeResolver?.cancel();\n };\n this.createdAt = time.now();\n const optionsWithDefaults = {\n autoplay,\n delay,\n type,\n repeat,\n repeatDelay,\n repeatType,\n name,\n motionValue,\n element,\n ...options,\n };\n const KeyframeResolver$1 = element?.KeyframeResolver || KeyframeResolver;\n this.keyframeResolver = new KeyframeResolver$1(keyframes, (resolvedKeyframes, finalKeyframe, forced) => this.onKeyframesResolved(resolvedKeyframes, finalKeyframe, optionsWithDefaults, !forced), name, motionValue, element);\n this.keyframeResolver?.scheduleResolve();\n }\n onKeyframesResolved(keyframes, finalKeyframe, options, sync) {\n this.keyframeResolver = undefined;\n const { name, type, velocity, delay, isHandoff, onUpdate } = options;\n this.resolvedAt = time.now();\n /**\n * If we can't animate this value with the resolved keyframes\n * then we should complete it immediately.\n */\n if (!canAnimate(keyframes, name, type, velocity)) {\n if (MotionGlobalConfig.instantAnimations || !delay) {\n onUpdate?.(getFinalKeyframe(keyframes, options, finalKeyframe));\n }\n keyframes[0] = keyframes[keyframes.length - 1];\n makeAnimationInstant(options);\n options.repeat = 0;\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 commited 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 const resolvedOptions = {\n startTime,\n finalKeyframe,\n ...options,\n keyframes,\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 const animation = !isHandoff && supportsBrowserAnimation(resolvedOptions)\n ? new NativeAnimationExtended({\n ...resolvedOptions,\n element: resolvedOptions.motionValue.owner.current,\n })\n : new JSAnimation(resolvedOptions);\n animation.finished.then(() => this.notifyFinished()).catch(noop);\n if (this.pendingTimeline) {\n this.stopTimeline = animation.attachTimeline(this.pendingTimeline);\n this.pendingTimeline = undefined;\n }\n this._animation = animation;\n }\n get finished() {\n if (!this._animation) {\n return this._finished;\n }\n else {\n return this.animation.finished;\n }\n }\n then(onResolve, _onReject) {\n return this.finished.finally(onResolve).then(() => { });\n }\n get animation() {\n if (!this._animation) {\n this.keyframeResolver?.resume();\n flushKeyframeResolvers();\n }\n return this._animation;\n }\n get duration() {\n return this.animation.duration;\n }\n get iterationDuration() {\n return this.animation.iterationDuration;\n }\n get time() {\n return this.animation.time;\n }\n set time(newTime) {\n this.animation.time = newTime;\n }\n get speed() {\n return this.animation.speed;\n }\n get state() {\n return this.animation.state;\n }\n set speed(newSpeed) {\n this.animation.speed = newSpeed;\n }\n get startTime() {\n return this.animation.startTime;\n }\n attachTimeline(timeline) {\n if (this._animation) {\n this.stopTimeline = this.animation.attachTimeline(timeline);\n }\n else {\n this.pendingTimeline = timeline;\n }\n return () => this.stop();\n }\n play() {\n this.animation.play();\n }\n pause() {\n this.animation.pause();\n }\n complete() {\n this.animation.complete();\n }\n cancel() {\n if (this._animation) {\n this.animation.cancel();\n }\n this.keyframeResolver?.cancel();\n }\n}\n\nexport { AsyncMotionValueAnimation };\n","import { invariant, isNumericalString } from 'motion-utils';\nimport { isCSSVariableToken } from './is-css-variable.mjs';\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 */\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;\nfunction parseCSSVariable(current) {\n const match = splitCSSVariableRegex.exec(current);\n if (!match)\n return [,];\n const [, token1, token2, fallback] = match;\n return [`--${token1 ?? token2}`, fallback];\n}\nconst maxDepth = 4;\nfunction getVariableValue(current, element, depth = 1) {\n invariant(depth <= maxDepth, `Max CSS variable fallback depth detected in property \"${current}\". This may indicate a circular fallback dependency.`, \"max-css-var-depth\");\n const [token, fallback] = parseCSSVariable(current);\n // No CSS variable detected\n if (!token)\n return;\n // Attempt to read this CSS variable off the element\n const resolved = window.getComputedStyle(element).getPropertyValue(token);\n if (resolved) {\n const trimmed = resolved.trim();\n return isNumericalString(trimmed) ? parseFloat(trimmed) : trimmed;\n }\n return isCSSVariableToken(fallback)\n ? getVariableValue(fallback, element, depth + 1)\n : fallback;\n}\n\nexport { getVariableValue, parseCSSVariable };\n","function getValueTransition(transition, key) {\n return (transition?.[key] ??\n transition?.[\"default\"] ??\n transition);\n}\n\nexport { getValueTransition };\n","import { transformPropOrder } from './keys-transform.mjs';\n\nconst positionalKeys = new Set([\n \"width\",\n \"height\",\n \"top\",\n \"left\",\n \"right\",\n \"bottom\",\n ...transformPropOrder,\n]);\n\nexport { positionalKeys };\n","/**\n * ValueType for \"auto\"\n */\nconst auto = {\n test: (v) => v === \"auto\",\n parse: (v) => v,\n};\n\nexport { auto };\n","/**\n * Tests a provided value against a ValueType\n */\nconst testValueType = (v) => (type) => type.test(v);\n\nexport { testValueType };\n","import { auto } from './auto.mjs';\nimport { number } from './numbers/index.mjs';\nimport { px, percent, degrees, vw, vh } from './numbers/units.mjs';\nimport { testValueType } from './test.mjs';\n\n/**\n * A list of value types commonly used for dimensions\n */\nconst dimensionValueTypes = [number, px, percent, degrees, vw, vh, auto];\n/**\n * Tests a dimensional value against the list of dimension ValueTypes\n */\nconst findDimensionValueType = (v) => dimensionValueTypes.find(testValueType(v));\n\nexport { dimensionValueTypes, findDimensionValueType };\n","import { isZeroValueString } from 'motion-utils';\n\nfunction isNone(value) {\n if (typeof value === \"number\") {\n return value === 0;\n }\n else if (value !== null) {\n return value === \"none\" || value === \"0\" || isZeroValueString(value);\n }\n else {\n return true;\n }\n}\n\nexport { isNone };\n","import { complex } from './index.mjs';\nimport { floatRegex } from '../utils/float-regex.mjs';\n\n/**\n * Properties that should default to 1 or 100%\n */\nconst maxDefaults = new Set([\"brightness\", \"contrast\", \"saturate\", \"opacity\"]);\nfunction applyDefaultFilter(v) {\n const [name, value] = v.slice(0, -1).split(\"(\");\n if (name === \"drop-shadow\")\n return v;\n const [number] = value.match(floatRegex) || [];\n if (!number)\n return v;\n const unit = value.replace(number, \"\");\n let defaultValue = maxDefaults.has(name) ? 1 : 0;\n if (number !== value)\n defaultValue *= 100;\n return name + \"(\" + defaultValue + unit + \")\";\n}\nconst functionRegex = /\\b([a-z-]*)\\(.*?\\)/gu;\nconst filter = {\n ...complex,\n getAnimatableNone: (v) => {\n const functions = v.match(functionRegex);\n return functions ? functions.map(applyDefaultFilter).join(\" \") : v;\n },\n};\n\nexport { filter };\n","import { number } from './numbers/index.mjs';\n\nconst int = {\n ...number,\n transform: Math.round,\n};\n\nexport { int };\n","import { scale, alpha } from '../numbers/index.mjs';\nimport { degrees, px, progressPercentage } from '../numbers/units.mjs';\n\nconst transformValueTypes = {\n rotate: 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\nexport { transformValueTypes };\n","import { int } from '../int.mjs';\nimport { alpha } from '../numbers/index.mjs';\nimport { px } from '../numbers/units.mjs';\nimport { transformValueTypes } from './transform.mjs';\n\nconst numberValueTypes = {\n // Border props\n borderWidth: px,\n borderTopWidth: px,\n borderRightWidth: px,\n borderBottomWidth: px,\n borderLeftWidth: px,\n borderRadius: px,\n radius: px,\n borderTopLeftRadius: px,\n borderTopRightRadius: px,\n borderBottomRightRadius: px,\n borderBottomLeftRadius: px,\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 // Spacing props\n padding: px,\n paddingTop: px,\n paddingRight: px,\n paddingBottom: px,\n paddingLeft: px,\n margin: px,\n marginTop: px,\n marginRight: px,\n marginBottom: px,\n marginLeft: px,\n // Misc\n backgroundPositionX: px,\n backgroundPositionY: px,\n ...transformValueTypes,\n zIndex: int,\n // SVG\n fillOpacity: alpha,\n strokeOpacity: alpha,\n numOctaves: int,\n};\n\nexport { numberValueTypes };\n","import { color } from '../color/index.mjs';\nimport { filter } from '../complex/filter.mjs';\nimport { numberValueTypes } from './number.mjs';\n\n/**\n * A map of default value types for common values\n */\nconst defaultValueTypes = {\n ...numberValueTypes,\n // Color props\n color,\n backgroundColor: color,\n outlineColor: color,\n fill: color,\n stroke: color,\n // Border props\n borderColor: color,\n borderTopColor: color,\n borderRightColor: color,\n borderBottomColor: color,\n borderLeftColor: color,\n filter,\n WebkitFilter: filter,\n};\n/**\n * Gets the default ValueType for the provided value key\n */\nconst getDefaultValueType = (key) => defaultValueTypes[key];\n\nexport { defaultValueTypes, getDefaultValueType };\n","import { complex } from '../complex/index.mjs';\nimport { filter } from '../complex/filter.mjs';\nimport { getDefaultValueType } from '../maps/defaults.mjs';\n\nfunction getAnimatableNone(key, value) {\n let defaultValueType = getDefaultValueType(key);\n if (defaultValueType !== filter)\n 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\nexport { getAnimatableNone };\n","import { analyseComplexValue } from '../../../value/types/complex/index.mjs';\nimport { getAnimatableNone } from '../../../value/types/utils/animatable-none.mjs';\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\"]);\nfunction makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, name) {\n let i = 0;\n let animatableTemplate = undefined;\n while (i < unresolvedKeyframes.length && !animatableTemplate) {\n const keyframe = unresolvedKeyframes[i];\n if (typeof keyframe === \"string\" &&\n !invalidTemplates.has(keyframe) &&\n analyseComplexValue(keyframe).values.length) {\n animatableTemplate = unresolvedKeyframes[i];\n }\n i++;\n }\n if (animatableTemplate && name) {\n for (const noneIndex of noneKeyframeIndexes) {\n unresolvedKeyframes[noneIndex] = getAnimatableNone(name, animatableTemplate);\n }\n }\n}\n\nexport { makeNoneKeyframesAnimatable };\n","import { positionalKeys } from '../../render/utils/keys-position.mjs';\nimport { findDimensionValueType } from '../../value/types/dimensions.mjs';\nimport { getVariableValue } from '../utils/css-variables-conversion.mjs';\nimport { isCSSVariableToken } from '../utils/is-css-variable.mjs';\nimport { KeyframeResolver } from './KeyframesResolver.mjs';\nimport { isNone } from './utils/is-none.mjs';\nimport { makeNoneKeyframesAnimatable } from './utils/make-none-animatable.mjs';\nimport { isNumOrPxType, positionalValues } from './utils/unit-conversion.mjs';\n\nclass DOMKeyframesResolver extends KeyframeResolver {\n constructor(unresolvedKeyframes, onComplete, name, motionValue, element) {\n super(unresolvedKeyframes, onComplete, name, motionValue, element, true);\n }\n readKeyframes() {\n const { unresolvedKeyframes, element, name } = this;\n if (!element || !element.current)\n return;\n super.readKeyframes();\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 if (typeof keyframe === \"string\") {\n keyframe = keyframe.trim();\n if (isCSSVariableToken(keyframe)) {\n const resolved = getVariableValue(keyframe, element.current);\n if (resolved !== undefined) {\n unresolvedKeyframes[i] = resolved;\n }\n if (i === unresolvedKeyframes.length - 1) {\n this.finalKeyframe = keyframe;\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 * 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 const [origin, target] = unresolvedKeyframes;\n const originType = findDimensionValueType(origin);\n const targetType = findDimensionValueType(target);\n /**\n * Either we don't recognise these value types or we can animate between them.\n */\n if (originType === targetType)\n return;\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);\n }\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 resolveNoneKeyframes() {\n const { unresolvedKeyframes, name } = this;\n const noneKeyframeIndexes = [];\n for (let i = 0; i < unresolvedKeyframes.length; i++) {\n if (unresolvedKeyframes[i] === null ||\n isNone(unresolvedKeyframes[i])) {\n noneKeyframeIndexes.push(i);\n }\n }\n if (noneKeyframeIndexes.length) {\n makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, name);\n }\n }\n measureInitialState() {\n const { element, unresolvedKeyframes, name } = this;\n if (!element || !element.current)\n return;\n if (name === \"height\") {\n this.suspendedScrollY = window.pageYOffset;\n }\n this.measuredOrigin = positionalValues[name](element.measureViewportBox(), window.getComputedStyle(element.current));\n unresolvedKeyframes[0] = this.measuredOrigin;\n // Set final key frame to measure after next render\n const measureKeyframe = unresolvedKeyframes[unresolvedKeyframes.length - 1];\n if (measureKeyframe !== undefined) {\n element.getValue(name, measureKeyframe).jump(measureKeyframe, false);\n }\n }\n measureEndState() {\n const { element, name, unresolvedKeyframes } = this;\n if (!element || !element.current)\n return;\n const value = element.getValue(name);\n value && value.jump(this.measuredOrigin, false);\n const finalKeyframeIndex = unresolvedKeyframes.length - 1;\n const finalKeyframe = unresolvedKeyframes[finalKeyframeIndex];\n unresolvedKeyframes[finalKeyframeIndex] = positionalValues[name](element.measureViewportBox(), window.getComputedStyle(element.current));\n if (finalKeyframe !== null && this.finalKeyframe === undefined) {\n this.finalKeyframe = finalKeyframe;\n }\n // If we removed transform values, reapply them before the next render\n if (this.removedTransforms?.length) {\n this.removedTransforms.forEach(([unsetTransformName, unsetTransformValue]) => {\n element\n .getValue(unsetTransformName)\n .set(unsetTransformValue);\n });\n }\n this.resolveNoneKeyframes();\n }\n}\n\nexport { DOMKeyframesResolver };\n","function resolveElements(elementOrSelector, scope, selectorCache) {\n if (elementOrSelector instanceof EventTarget) {\n return [elementOrSelector];\n }\n else if (typeof elementOrSelector === \"string\") {\n let root = document;\n if (scope) {\n root = scope.current;\n }\n const elements = selectorCache?.[elementOrSelector] ??\n root.querySelectorAll(elementOrSelector);\n return elements ? Array.from(elements) : [];\n }\n return Array.from(elementOrSelector);\n}\n\nexport { resolveElements };\n","/**\n * Provided a value and a ValueType, returns the value as that value type.\n */\nconst getValueAsType = (value, type) => {\n return type && typeof value === \"number\"\n ? type.transform(value)\n : value;\n};\n\nexport { getValueAsType };\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 */\nfunction isHTMLElement(element) {\n return isObject(element) && \"offsetHeight\" in element;\n}\n\nexport { isHTMLElement };\n","import { warnOnce, SubscriptionManager, velocityPerSecond } from 'motion-utils';\nimport { time } from '../frameloop/sync-time.mjs';\nimport { frame } from '../frameloop/frame.mjs';\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;\nconst isFloat = (value) => {\n return !isNaN(parseFloat(value));\n};\nconst collectMotionValues = {\n current: undefined,\n};\n/**\n * `MotionValue` is used to track the state and velocity of motion values.\n *\n * @public\n */\nclass MotionValue {\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, options = {}) {\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 this.canTrackVelocity = null;\n /**\n * An object containing a SubscriptionManager for each active event.\n */\n this.events = {};\n this.updateAndNotify = (v) => {\n const currentTime = time.now();\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 this.prev = this.current;\n this.setCurrent(v);\n // Update update subscribers\n if (this.current !== this.prev) {\n this.events.change?.notify(this.current);\n if (this.dependents) {\n for (const dependent of this.dependents) {\n dependent.dirty();\n }\n }\n }\n };\n this.hasAnimated = false;\n this.setCurrent(init);\n this.owner = options.owner;\n }\n setCurrent(current) {\n this.current = current;\n this.updatedAt = time.now();\n if (this.canTrackVelocity === null && current !== undefined) {\n this.canTrackVelocity = isFloat(this.current);\n }\n }\n setPrevFrameValue(prevFrameValue = this.current) {\n this.prevFrameValue = prevFrameValue;\n this.prevUpdatedAt = this.updatedAt;\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) {\n if (process.env.NODE_ENV !== \"production\") {\n warnOnce(false, `value.onChange(callback) is deprecated. Switch to value.on(\"change\", callback).`);\n }\n return this.on(\"change\", subscription);\n }\n on(eventName, callback) {\n if (!this.events[eventName]) {\n this.events[eventName] = new SubscriptionManager();\n }\n const unsubscribe = this.events[eventName].add(callback);\n if (eventName === \"change\") {\n return () => {\n unsubscribe();\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 return unsubscribe;\n }\n clearListeners() {\n for (const eventManagers in this.events) {\n this.events[eventManagers].clear();\n }\n }\n /**\n * Attaches a passive effect to the `MotionValue`.\n */\n attach(passiveEffect, stopPassiveEffect) {\n this.passiveEffect = passiveEffect;\n this.stopPassiveEffect = stopPassiveEffect;\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) {\n if (!this.passiveEffect) {\n this.updateAndNotify(v);\n }\n else {\n this.passiveEffect(v, this.updateAndNotify);\n }\n }\n setWithVelocity(prev, current, delta) {\n this.set(current);\n this.prev = undefined;\n this.prevFrameValue = prev;\n this.prevUpdatedAt = this.updatedAt - delta;\n }\n /**\n * Set the state of the `MotionValue`, stopping any active animations,\n * effects, and resets velocity to `0`.\n */\n jump(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)\n this.stopPassiveEffect();\n }\n dirty() {\n this.events.change?.notify(this.current);\n }\n addDependent(dependent) {\n if (!this.dependents) {\n this.dependents = new Set();\n }\n this.dependents.add(dependent);\n }\n removeDependent(dependent) {\n if (this.dependents) {\n this.dependents.delete(dependent);\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 return this.current;\n }\n /**\n * @public\n */\n getPrevious() {\n return this.prev;\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 if (!this.canTrackVelocity ||\n this.prevFrameValue === undefined ||\n currentTime - this.updatedAt > MAX_VELOCITY_DELTA) {\n return 0;\n }\n const delta = Math.min(this.updatedAt - this.prevUpdatedAt, MAX_VELOCITY_DELTA);\n // Casts because of parseFloat's poor typing\n return velocityPerSecond(parseFloat(this.current) -\n parseFloat(this.prevFrameValue), delta);\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) {\n this.stop();\n return new Promise((resolve) => {\n this.hasAnimated = true;\n this.animation = startAnimation(resolve);\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 * 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 * Returns `true` if this value is currently animating.\n *\n * @public\n */\n isAnimating() {\n return !!this.animation;\n }\n clearAnimation() {\n delete this.animation;\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 if (this.stopPassiveEffect) {\n this.stopPassiveEffect();\n }\n }\n}\nfunction motionValue(init, options) {\n return new MotionValue(init, options);\n}\n\nexport { MotionValue, collectMotionValues, motionValue };\n","import { createRenderBatcher } from './batcher.mjs';\n\nconst { schedule: microtask, cancel: cancelMicrotask } = \n/* @__PURE__ */ createRenderBatcher(queueMicrotask, false);\n\nexport { cancelMicrotask, microtask };\n","const isDragging = {\n x: false,\n y: false,\n};\nfunction isDragActive() {\n return isDragging.x || isDragging.y;\n}\n\nexport { isDragActive, isDragging };\n","import { isDragging } from './is-active.mjs';\n\nfunction setDragLock(axis) {\n if (axis === \"x\" || axis === \"y\") {\n if (isDragging[axis]) {\n return null;\n }\n else {\n isDragging[axis] = true;\n return () => {\n isDragging[axis] = false;\n };\n }\n }\n else {\n if (isDragging.x || isDragging.y) {\n return null;\n }\n else {\n isDragging.x = isDragging.y = true;\n return () => {\n isDragging.x = isDragging.y = false;\n };\n }\n }\n}\n\nexport { setDragLock };\n","import { resolveElements } from '../../utils/resolve-elements.mjs';\n\nfunction setupGesture(elementOrSelector, options) {\n const elements = resolveElements(elementOrSelector);\n const gestureAbortController = new AbortController();\n const eventOptions = {\n passive: true,\n ...options,\n signal: gestureAbortController.signal,\n };\n const cancel = () => gestureAbortController.abort();\n return [elements, eventOptions, cancel];\n}\n\nexport { setupGesture };\n","import { isDragActive } from './drag/state/is-active.mjs';\nimport { setupGesture } from './utils/setup.mjs';\n\nfunction isValidHover(event) {\n return !(event.pointerType === \"touch\" || isDragActive());\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 */\nfunction hover(elementOrSelector, onHoverStart, options = {}) {\n const [elements, eventOptions, cancel] = setupGesture(elementOrSelector, options);\n const onPointerEnter = (enterEvent) => {\n if (!isValidHover(enterEvent))\n return;\n const { target } = enterEvent;\n const onHoverEnd = onHoverStart(target, enterEvent);\n if (typeof onHoverEnd !== \"function\" || !target)\n return;\n const onPointerLeave = (leaveEvent) => {\n if (!isValidHover(leaveEvent))\n return;\n onHoverEnd(leaveEvent);\n target.removeEventListener(\"pointerleave\", onPointerLeave);\n };\n target.addEventListener(\"pointerleave\", onPointerLeave, eventOptions);\n };\n elements.forEach((element) => {\n element.addEventListener(\"pointerenter\", onPointerEnter, eventOptions);\n });\n return cancel;\n}\n\nexport { hover };\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 */\nconst isNodeOrChild = (parent, child) => {\n if (!child) {\n return false;\n }\n else if (parent === child) {\n return true;\n }\n else {\n return isNodeOrChild(parent, child.parentElement);\n }\n};\n\nexport { isNodeOrChild };\n","const isPrimaryPointer = (event) => {\n if (event.pointerType === \"mouse\") {\n return typeof event.button !== \"number\" || event.button <= 0;\n }\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\nexport { isPrimaryPointer };\n","const focusableElements = new Set([\n \"BUTTON\",\n \"INPUT\",\n \"SELECT\",\n \"TEXTAREA\",\n \"A\",\n]);\nfunction isElementKeyboardAccessible(element) {\n return (focusableElements.has(element.tagName) ||\n element.tabIndex !== -1);\n}\n\nexport { isElementKeyboardAccessible };\n","const isPressing = new WeakSet();\n\nexport { isPressing };\n","import { isPressing } from './state.mjs';\n\n/**\n * Filter out events that are not \"Enter\" keys.\n */\nfunction filterEvents(callback) {\n return (event) => {\n if (event.key !== \"Enter\")\n return;\n callback(event);\n };\n}\nfunction firePointerEvent(target, type) {\n target.dispatchEvent(new PointerEvent(\"pointer\" + type, { isPrimary: true, bubbles: true }));\n}\nconst enableKeyboardPress = (focusEvent, eventOptions) => {\n const element = focusEvent.currentTarget;\n if (!element)\n return;\n const handleKeydown = filterEvents(() => {\n if (isPressing.has(element))\n return;\n firePointerEvent(element, \"down\");\n const handleKeyup = filterEvents(() => {\n firePointerEvent(element, \"up\");\n });\n const handleBlur = () => firePointerEvent(element, \"cancel\");\n element.addEventListener(\"keyup\", handleKeyup, eventOptions);\n element.addEventListener(\"blur\", handleBlur, eventOptions);\n });\n element.addEventListener(\"keydown\", handleKeydown, eventOptions);\n /**\n * Add an event listener that fires on blur to remove the keydown events.\n */\n element.addEventListener(\"blur\", () => element.removeEventListener(\"keydown\", handleKeydown), eventOptions);\n};\n\nexport { enableKeyboardPress };\n","import { isHTMLElement } from '../../utils/is-html-element.mjs';\nimport { isDragActive } from '../drag/state/is-active.mjs';\nimport { isNodeOrChild } from '../utils/is-node-or-child.mjs';\nimport { isPrimaryPointer } from '../utils/is-primary-pointer.mjs';\nimport { setupGesture } from '../utils/setup.mjs';\nimport { isElementKeyboardAccessible } from './utils/is-keyboard-accessible.mjs';\nimport { enableKeyboardPress } from './utils/keyboard.mjs';\nimport { isPressing } from './utils/state.mjs';\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) {\n return isPrimaryPointer(event) && !isDragActive();\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 */\nfunction press(targetOrSelector, onPressStart, options = {}) {\n const [targets, eventOptions, cancelEvents] = setupGesture(targetOrSelector, options);\n const startPress = (startEvent) => {\n const target = startEvent.currentTarget;\n if (!isValidPressEvent(startEvent))\n return;\n isPressing.add(target);\n const onPressEnd = onPressStart(target, startEvent);\n const onPointerEnd = (endEvent, success) => {\n window.removeEventListener(\"pointerup\", onPointerUp);\n window.removeEventListener(\"pointercancel\", onPointerCancel);\n if (isPressing.has(target)) {\n isPressing.delete(target);\n }\n if (!isValidPressEvent(endEvent)) {\n return;\n }\n if (typeof onPressEnd === \"function\") {\n onPressEnd(endEvent, { success });\n }\n };\n const onPointerUp = (upEvent) => {\n onPointerEnd(upEvent, target === window ||\n target === document ||\n options.useGlobalTarget ||\n isNodeOrChild(target, upEvent.target));\n };\n const onPointerCancel = (cancelEvent) => {\n onPointerEnd(cancelEvent, false);\n };\n window.addEventListener(\"pointerup\", onPointerUp, eventOptions);\n window.addEventListener(\"pointercancel\", onPointerCancel, eventOptions);\n };\n targets.forEach((target) => {\n const pointerDownTarget = options.useGlobalTarget ? window : target;\n pointerDownTarget.addEventListener(\"pointerdown\", startPress, eventOptions);\n if (isHTMLElement(target)) {\n target.addEventListener(\"focus\", (event) => enableKeyboardPress(event, eventOptions));\n if (!isElementKeyboardAccessible(target) &&\n !target.hasAttribute(\"tabindex\")) {\n target.tabIndex = 0;\n }\n }\n });\n return cancelEvents;\n}\n\nexport { press };\n","import { isObject } from 'motion-utils';\n\n/**\n * Checks if an element is an SVG element in a way\n * that works across iframes\n */\nfunction isSVGElement(element) {\n return isObject(element) && \"ownerSVGElement\" in element;\n}\n\nexport { isSVGElement };\n","import { isSVGElement } from './is-svg-element.mjs';\n\n/**\n * Checks if an element is specifically an SVGSVGElement (the root SVG element)\n * in a way that works across iframes\n */\nfunction isSVGSVGElement(element) {\n return isSVGElement(element) && element.tagName === \"svg\";\n}\n\nexport { isSVGSVGElement };\n","const isMotionValue = (value) => Boolean(value && value.getVelocity);\n\nexport { isMotionValue };\n","import { color } from '../color/index.mjs';\nimport { complex } from '../complex/index.mjs';\nimport { dimensionValueTypes } from '../dimensions.mjs';\nimport { testValueType } from '../test.mjs';\n\n/**\n * A list of all ValueTypes\n */\nconst valueTypes = [...dimensionValueTypes, color, complex];\n/**\n * Tests a value against the list of ValueTypes\n */\nconst findValueType = (v) => valueTypes.find(testValueType(v));\n\nexport { findValueType };\n","\"use client\";\nimport { createContext } from 'react';\n\n/**\n * @public\n */\nconst MotionConfigContext = createContext({\n transformPagePoint: (p) => p,\n isStatic: false,\n reducedMotion: \"never\",\n});\n\nexport { MotionConfigContext };\n","import * as React from 'react';\n\n/**\n * Taken from https://github.com/radix-ui/primitives/blob/main/packages/react/compose-refs/src/compose-refs.tsx\n */\n/**\n * Set a given ref to a given value\n * This utility takes care of different types of refs: callback refs and RefObject(s)\n */\nfunction setRef(ref, value) {\n if (typeof ref === \"function\") {\n return ref(value);\n }\n else if (ref !== null && ref !== undefined) {\n ref.current = value;\n }\n}\n/**\n * A utility to compose multiple refs together\n * Accepts callback refs and RefObject(s)\n */\nfunction composeRefs(...refs) {\n return (node) => {\n let hasCleanup = false;\n const cleanups = refs.map((ref) => {\n const cleanup = setRef(ref, node);\n if (!hasCleanup && typeof cleanup === \"function\") {\n hasCleanup = true;\n }\n return cleanup;\n });\n // React <19 will log an error to the console if a callback ref returns a\n // value. We don't use ref cleanups internally so this will only happen if a\n // user's ref callback returns a value, which we only expect if they are\n // using the cleanup functionality added in React 19.\n if (hasCleanup) {\n return () => {\n for (let i = 0; i < cleanups.length; i++) {\n const cleanup = cleanups[i];\n if (typeof cleanup === \"function\") {\n cleanup();\n }\n else {\n setRef(refs[i], null);\n }\n }\n };\n }\n };\n}\n/**\n * A custom hook that composes multiple refs\n * Accepts callback refs and RefObject(s)\n */\nfunction useComposedRefs(...refs) {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return React.useCallback(composeRefs(...refs), refs);\n}\n\nexport { useComposedRefs };\n","\"use client\";\nimport { useContext, useId, useEffect, useCallback } from 'react';\nimport { PresenceContext } from '../../context/PresenceContext.mjs';\n\n/**\n * When a component is the child of `AnimatePresence`, it can use `usePresence`\n * to access information about whether it's still present in the React tree.\n *\n * ```jsx\n * import { usePresence } from \"framer-motion\"\n *\n * export const Component = () => {\n * const [isPresent, safeToRemove] = usePresence()\n *\n * useEffect(() => {\n * !isPresent && setTimeout(safeToRemove, 1000)\n * }, [isPresent])\n *\n * return <div />\n * }\n * ```\n *\n * If `isPresent` is `false`, it means that a component has been removed the tree, but\n * `AnimatePresence` won't really remove it until `safeToRemove` has been called.\n *\n * @public\n */\nfunction usePresence(subscribe = true) {\n const context = useContext(PresenceContext);\n if (context === null)\n return [true, null];\n const { isPresent, onExitComplete, register } = context;\n // It's safe to call the following hooks conditionally (after an early return) because the context will always\n // either be null or non-null for the lifespan of the component.\n const id = useId();\n useEffect(() => {\n if (subscribe) {\n return register(id);\n }\n }, [subscribe]);\n const safeToRemove = useCallback(() => subscribe && onExitComplete && onExitComplete(id), [id, onExitComplete, subscribe]);\n return !isPresent && onExitComplete ? [false, safeToRemove] : [true];\n}\n/**\n * Similar to `usePresence`, except `useIsPresent` simply returns whether or not the component is present.\n * There is no `safeToRemove` function.\n *\n * ```jsx\n * import { useIsPresent } from \"framer-motion\"\n *\n * export const Component = () => {\n * const isPresent = useIsPresent()\n *\n * useEffect(() => {\n * !isPresent && console.log(\"I've been removed!\")\n * }, [isPresent])\n *\n * return <div />\n * }\n * ```\n *\n * @public\n */\nfunction useIsPresent() {\n return isPresent(useContext(PresenceContext));\n}\nfunction isPresent(context) {\n return context === null ? true : context.isPresent;\n}\n\nexport { isPresent, useIsPresent, usePresence };\n","import { Children, isValidElement } from 'react';\n\nconst getChildKey = (child) => child.key || \"\";\nfunction onlyElements(children) {\n const filtered = [];\n // We use forEach here instead of map as map mutates the component key by preprending `.$`\n Children.forEach(children, (child) => {\n if (isValidElement(child))\n filtered.push(child);\n });\n return filtered;\n}\n\nexport { getChildKey, onlyElements };\n","\"use client\";\nimport { createContext } from 'react';\n\nconst LazyContext = createContext({ strict: false });\n\nexport { LazyContext };\n","const 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};\nconst featureDefinitions = {};\nfor (const key in featureProps) {\n featureDefinitions[key] = {\n isEnabled: (props) => featureProps[key].some((name) => !!props[name]),\n };\n}\n\nexport { featureDefinitions };\n","import { featureDefinitions } from './definitions.mjs';\n\nfunction loadFeatures(features) {\n for (const key in features) {\n featureDefinitions[key] = {\n ...featureDefinitions[key],\n ...features[key],\n };\n }\n}\n\nexport { loadFeatures };\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([\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 \"ignoreStrict\",\n \"viewport\",\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 */\nfunction isValidMotionProp(key) {\n return (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));\n}\n\nexport { isValidMotionProp };\n","import { isValidMotionProp } from '../../../motion/utils/valid-prop.mjs';\n\nlet shouldForward = (key) => !isValidMotionProp(key);\nfunction loadExternalIsValidProp(isValidProp) {\n if (typeof isValidProp !== \"function\")\n return;\n // Explicitly filter our events\n shouldForward = (key) => key.startsWith(\"on\") ? !isValidMotionProp(key) : isValidProp(key);\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 loadExternalIsValidProp(require(\"@emotion/is-prop-valid\").default);\n}\ncatch {\n // We don't need to actually do anything here - the fallback is the existing `isPropValid`.\n}\nfunction filterProps(props, isDom, forwardMotionProps) {\n const filteredProps = {};\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\")\n continue;\n if (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\"] &&\n key.startsWith(\"onDrag\"))) {\n filteredProps[key] =\n props[key];\n }\n }\n return filteredProps;\n}\n\nexport { filterProps, loadExternalIsValidProp };\n","\"use client\";\nimport { jsxs, jsx } from 'react/jsx-runtime';\nimport { warning, invariant } from 'motion-utils';\nimport { forwardRef, useContext } from 'react';\nimport { LayoutGroupContext } from '../context/LayoutGroupContext.mjs';\nimport { LazyContext } from '../context/LazyContext.mjs';\nimport { MotionConfigContext } from '../context/MotionConfigContext.mjs';\nimport { MotionContext } from '../context/MotionContext/index.mjs';\nimport { useCreateMotionContext } from '../context/MotionContext/create.mjs';\nimport { useRender } from '../render/dom/use-render.mjs';\nimport { isSVGComponent } from '../render/dom/utils/is-svg-component.mjs';\nimport { useHTMLVisualState } from '../render/html/use-html-visual-state.mjs';\nimport { useSVGVisualState } from '../render/svg/use-svg-visual-state.mjs';\nimport { isBrowser } from '../utils/is-browser.mjs';\nimport { featureDefinitions } from './features/definitions.mjs';\nimport { loadFeatures } from './features/load-features.mjs';\nimport { motionComponentSymbol } from './utils/symbol.mjs';\nimport { useMotionRef } from './utils/use-motion-ref.mjs';\nimport { useVisualElement } from './utils/use-visual-element.mjs';\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 */\nfunction createMotionComponent(Component, { forwardMotionProps = false } = {}, preloadedFeatures, createVisualElement) {\n preloadedFeatures && loadFeatures(preloadedFeatures);\n const useVisualState = isSVGComponent(Component)\n ? useSVGVisualState\n : useHTMLVisualState;\n function MotionDOMComponent(props, externalRef) {\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;\n const configAndProps = {\n ...useContext(MotionConfigContext),\n ...props,\n layoutId: useLayoutId(props),\n };\n const { isStatic } = configAndProps;\n const context = useCreateMotionContext(props);\n const visualState = useVisualState(props, isStatic);\n if (!isStatic && isBrowser) {\n useStrictMode(configAndProps, preloadedFeatures);\n const layoutProjection = getProjectionFunctionality(configAndProps);\n MeasureLayout = layoutProjection.MeasureLayout;\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(Component, visualState, configAndProps, createVisualElement, layoutProjection.ProjectionNode);\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 (jsxs(MotionContext.Provider, { value: context, children: [MeasureLayout && context.visualElement ? (jsx(MeasureLayout, { visualElement: context.visualElement, ...configAndProps })) : null, useRender(Component, props, useMotionRef(visualState, context.visualElement, externalRef), visualState, isStatic, forwardMotionProps)] }));\n }\n MotionDOMComponent.displayName = `motion.${typeof Component === \"string\"\n ? Component\n : `create(${Component.displayName ?? Component.name ?? \"\"})`}`;\n const ForwardRefMotionComponent = forwardRef(MotionDOMComponent);\n ForwardRefMotionComponent[motionComponentSymbol] = Component;\n return ForwardRefMotionComponent;\n}\nfunction useLayoutId({ layoutId }) {\n const layoutGroupId = useContext(LayoutGroupContext).id;\n return layoutGroupId && layoutId !== undefined\n ? layoutGroupId + \"-\" + layoutId\n : layoutId;\n}\nfunction useStrictMode(configAndProps, preloadedFeatures) {\n const isStrict = useContext(LazyContext).strict;\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 (process.env.NODE_ENV !== \"production\" &&\n preloadedFeatures &&\n isStrict) {\n const strictMessage = \"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}\nfunction getProjectionFunctionality(props) {\n const { drag, layout } = featureDefinitions;\n if (!drag && !layout)\n return {};\n const combined = { ...drag, ...layout };\n return {\n MeasureLayout: drag?.isEnabled(props) || layout?.isEnabled(props)\n ? combined.MeasureLayout\n : undefined,\n ProjectionNode: combined.ProjectionNode,\n };\n}\n\nexport { createMotionComponent };\n","\"use client\";\nimport { createContext } from 'react';\n\nconst MotionContext = /* @__PURE__ */ createContext({});\n\nexport { MotionContext };\n","\"use client\";\nimport { useContext, useMemo } from 'react';\nimport { MotionContext } from './index.mjs';\nimport { getCurrentTreeVariants } from './utils.mjs';\n\nfunction useCreateMotionContext(props) {\n const { initial, animate } = getCurrentTreeVariants(props, useContext(MotionContext));\n return useMemo(() => ({ initial, animate }), [variantLabelsAsDependency(initial), variantLabelsAsDependency(animate)]);\n}\nfunction variantLabelsAsDependency(prop) {\n return Array.isArray(prop) ? prop.join(\" \") : prop;\n}\n\nexport { useCreateMotionContext };\n","function isAnimationControls(v) {\n return (v !== null &&\n typeof v === \"object\" &&\n typeof v.start === \"function\");\n}\n\nexport { isAnimationControls };\n","/**\n * Decides if the supplied variable is variant label\n */\nfunction isVariantLabel(v) {\n return typeof v === \"string\" || Array.isArray(v);\n}\n\nexport { isVariantLabel };\n","const variantPriorityOrder = [\n \"animate\",\n \"whileInView\",\n \"whileFocus\",\n \"whileHover\",\n \"whileTap\",\n \"whileDrag\",\n \"exit\",\n];\nconst variantProps = [\"initial\", ...variantPriorityOrder];\n\nexport { variantPriorityOrder, variantProps };\n","import { isAnimationControls } from '../../animation/utils/is-animation-controls.mjs';\nimport { isVariantLabel } from './is-variant-label.mjs';\nimport { variantProps } from './variant-props.mjs';\n\nfunction isControllingVariants(props) {\n return (isAnimationControls(props.animate) ||\n variantProps.some((name) => isVariantLabel(props[name])));\n}\nfunction isVariantNode(props) {\n return Boolean(isControllingVariants(props) || props.variants);\n}\n\nexport { isControllingVariants, isVariantNode };\n","import { isControllingVariants } from '../../render/utils/is-controlling-variants.mjs';\nimport { isVariantLabel } from '../../render/utils/is-variant-label.mjs';\n\nfunction getCurrentTreeVariants(props, context) {\n if (isControllingVariants(props)) {\n const { initial, animate } = props;\n return {\n initial: initial === false || isVariantLabel(initial)\n ? initial\n : undefined,\n animate: isVariantLabel(animate) ? animate : undefined,\n };\n }\n return props.inherit !== false ? context : {};\n}\n\nexport { getCurrentTreeVariants };\n","\"use client\";\nimport { isMotionValue } from 'motion-dom';\nimport { Fragment, useMemo, createElement } from 'react';\nimport { useHTMLProps } from '../html/use-props.mjs';\nimport { useSVGProps } from '../svg/use-props.mjs';\nimport { filterProps } from './utils/filter-props.mjs';\nimport { isSVGComponent } from './utils/is-svg-component.mjs';\n\nfunction useRender(Component, props, ref, { latestValues, }, isStatic, forwardMotionProps = false) {\n const useVisualProps = isSVGComponent(Component)\n ? useSVGProps\n : useHTMLProps;\n const visualProps = useVisualProps(props, latestValues, isStatic, Component);\n const filteredProps = filterProps(props, typeof Component === \"string\", forwardMotionProps);\n const elementProps = Component !== Fragment ? { ...filteredProps, ...visualProps, ref } : {};\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(() => (isMotionValue(children) ? children.get() : children), [children]);\n return createElement(Component, {\n ...elementProps,\n children: renderedChildren,\n });\n}\n\nexport { useRender };\n","\"use client\";\nimport { isMotionValue } from 'motion-dom';\nimport { useMemo } from 'react';\nimport { isForcedMotionValue } from '../../motion/utils/is-forced-motion-value.mjs';\nimport { buildHTMLStyles } from './utils/build-styles.mjs';\nimport { createHtmlRenderState } from './utils/create-render-state.mjs';\n\nfunction copyRawValuesOnly(target, source, props) {\n for (const key in source) {\n if (!isMotionValue(source[key]) && !isForcedMotionValue(key, props)) {\n target[key] = source[key];\n }\n }\n}\nfunction useInitialMotionValues({ transformTemplate }, visualState) {\n return useMemo(() => {\n const state = createHtmlRenderState();\n buildHTMLStyles(state, visualState, transformTemplate);\n return Object.assign({}, state.vars, state.style);\n }, [visualState]);\n}\nfunction useStyle(props, visualState) {\n const styleProp = props.style || {};\n const style = {};\n /**\n * Copy non-Motion Values straight into style\n */\n copyRawValuesOnly(style, styleProp, props);\n Object.assign(style, useInitialMotionValues(props, visualState));\n return style;\n}\nfunction useHTMLProps(props, visualState) {\n // The `any` isn't ideal but it is the type of createElement props argument\n const htmlProps = {};\n const style = useStyle(props, visualState);\n if (props.drag && props.dragListener !== false) {\n // Disable the ghost element when a user drags\n htmlProps.draggable = false;\n // Disable text selection\n style.userSelect =\n style.WebkitUserSelect =\n style.WebkitTouchCallout =\n \"none\";\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 if (props.tabIndex === undefined &&\n (props.onTap || props.onTapStart || props.whileTap)) {\n htmlProps.tabIndex = 0;\n }\n htmlProps.style = style;\n return htmlProps;\n}\n\nexport { copyRawValuesOnly, useHTMLProps };\n","import { px } from 'motion-dom';\n\nfunction pixelsToPercent(pixels, axis) {\n if (axis.max === axis.min)\n return 0;\n return (pixels / (axis.max - axis.min)) * 100;\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 */\nconst correctBorderRadius = {\n correct: (latest, node) => {\n if (!node.target)\n return latest;\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 }\n else {\n return latest;\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 return `${x}% ${y}%`;\n },\n};\n\nexport { correctBorderRadius, pixelsToPercent };\n","import { complex, mixNumber } from 'motion-dom';\n\nconst correctBoxShadow = {\n correct: (latest, { treeScale, projectionDelta }) => {\n const original = latest;\n const shadow = complex.parse(latest);\n // TODO: Doesn't support multiple shadows\n if (shadow.length > 5)\n return original;\n const template = complex.createTransformer(latest);\n const offset = typeof shadow[0] !== \"number\" ? 1 : 0;\n // Calculate the overall context scale\n const xScale = projectionDelta.x.scale * treeScale.x;\n const yScale = projectionDelta.y.scale * treeScale.y;\n shadow[0 + offset] /= xScale;\n shadow[1 + offset] /= yScale;\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 // Blur\n if (typeof shadow[2 + offset] === \"number\")\n shadow[2 + offset] /= averageScale;\n // Spread\n if (typeof shadow[3 + offset] === \"number\")\n shadow[3 + offset] /= averageScale;\n return template(shadow);\n },\n};\n\nexport { correctBoxShadow };\n","import { isCSSVariableName } from 'motion-dom';\nimport { correctBorderRadius } from './scale-border-radius.mjs';\nimport { correctBoxShadow } from './scale-box-shadow.mjs';\n\nconst scaleCorrectors = {\n borderRadius: {\n ...correctBorderRadius,\n applyTo: [\n \"borderTopLeftRadius\",\n \"borderTopRightRadius\",\n \"borderBottomLeftRadius\",\n \"borderBottomRightRadius\",\n ],\n },\n borderTopLeftRadius: correctBorderRadius,\n borderTopRightRadius: correctBorderRadius,\n borderBottomLeftRadius: correctBorderRadius,\n borderBottomRightRadius: correctBorderRadius,\n boxShadow: correctBoxShadow,\n};\nfunction addScaleCorrector(correctors) {\n for (const key in correctors) {\n scaleCorrectors[key] = correctors[key];\n if (isCSSVariableName(key)) {\n scaleCorrectors[key].isCSSVariable = true;\n }\n }\n}\n\nexport { addScaleCorrector, scaleCorrectors };\n","import { transformProps } from 'motion-dom';\nimport { scaleCorrectors } from '../../projection/styles/scale-correction.mjs';\n\nfunction isForcedMotionValue(key, { layout, layoutId }) {\n return (transformProps.has(key) ||\n key.startsWith(\"origin\") ||\n ((layout || layoutId !== undefined) &&\n (!!scaleCorrectors[key] || key === \"opacity\")));\n}\n\nexport { isForcedMotionValue };\n","import { transformPropOrder, getValueAsType, numberValueTypes } from 'motion-dom';\n\nconst translateAlias = {\n x: \"translateX\",\n y: \"translateY\",\n z: \"translateZ\",\n transformPerspective: \"perspective\",\n};\nconst numTransforms = transformPropOrder.length;\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 */\nfunction buildTransform(latestValues, transform, transformTemplate) {\n // The transform string we're going to build into.\n let transformString = \"\";\n let transformIsDefault = true;\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];\n const value = latestValues[key];\n if (value === undefined)\n continue;\n let valueIsDefault = true;\n if (typeof value === \"number\") {\n valueIsDefault = value === (key.startsWith(\"scale\") ? 1 : 0);\n }\n else {\n valueIsDefault = parseFloat(value) === 0;\n }\n if (!valueIsDefault || transformTemplate) {\n const valueAsType = getValueAsType(value, numberValueTypes[key]);\n if (!valueIsDefault) {\n transformIsDefault = false;\n const transformName = translateAlias[key] || key;\n transformString += `${transformName}(${valueAsType}) `;\n }\n if (transformTemplate) {\n transform[key] = valueAsType;\n }\n }\n }\n transformString = transformString.trim();\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(transform, transformIsDefault ? \"\" : transformString);\n }\n else if (transformIsDefault) {\n transformString = \"none\";\n }\n return transformString;\n}\n\nexport { buildTransform };\n","import { transformProps, isCSSVariableName, getValueAsType, numberValueTypes } from 'motion-dom';\nimport { buildTransform } from './build-transform.mjs';\n\nfunction buildHTMLStyles(state, latestValues, transformTemplate) {\n const { style, vars, transformOrigin } = state;\n // Track whether we encounter any transform or transformOrigin values.\n let hasTransform = false;\n let hasTransformOrigin = false;\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 if (transformProps.has(key)) {\n // If this is a transform, flag to enable further transform processing\n hasTransform = true;\n continue;\n }\n else if (isCSSVariableName(key)) {\n vars[key] = value;\n continue;\n }\n else {\n // Convert the value to its default value type, ie 0 -> \"0px\"\n const valueAsType = getValueAsType(value, numberValueTypes[key]);\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] =\n valueAsType;\n }\n else {\n style[key] = valueAsType;\n }\n }\n }\n if (!latestValues.transform) {\n if (hasTransform || transformTemplate) {\n style.transform = buildTransform(latestValues, state.transform, 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 * Build a transformOrigin style. Uses the same defaults as the browser for\n * undefined origins.\n */\n if (hasTransformOrigin) {\n const { originX = \"50%\", originY = \"50%\", originZ = 0, } = transformOrigin;\n style.transformOrigin = `${originX} ${originY} ${originZ}`;\n }\n}\n\nexport { buildHTMLStyles };\n","const createHtmlRenderState = () => ({\n style: {},\n transform: {},\n transformOrigin: {},\n vars: {},\n});\n\nexport { createHtmlRenderState };\n","\"use client\";\nimport { useMemo } from 'react';\nimport { copyRawValuesOnly } from '../html/use-props.mjs';\nimport { buildSVGAttrs } from './utils/build-attrs.mjs';\nimport { createSvgRenderState } from './utils/create-render-state.mjs';\nimport { isSVGTag } from './utils/is-svg-tag.mjs';\n\nfunction useSVGProps(props, visualState, _isStatic, Component) {\n const visualProps = useMemo(() => {\n const state = createSvgRenderState();\n buildSVGAttrs(state, visualState, isSVGTag(Component), props.transformTemplate, props.style);\n return {\n ...state.attrs,\n style: { ...state.style },\n };\n }, [visualState]);\n if (props.style) {\n const rawStyles = {};\n copyRawValuesOnly(rawStyles, props.style, props);\n visualProps.style = { ...rawStyles, ...visualProps.style };\n }\n return visualProps;\n}\n\nexport { useSVGProps };\n","import { px } from 'motion-dom';\n\nconst dashKeys = {\n offset: \"stroke-dashoffset\",\n array: \"stroke-dasharray\",\n};\nconst camelKeys = {\n offset: \"strokeDashoffset\",\n array: \"strokeDasharray\",\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 */\nfunction buildSVGPath(attrs, length, spacing = 1, offset = 0, useDashCase = true) {\n // Normalise path length by setting SVG attribute pathLength to 1\n attrs.pathLength = 1;\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 // Build the dash offset\n attrs[keys.offset] = px.transform(-offset);\n // Build the dash array\n const pathLength = px.transform(length);\n const pathSpacing = px.transform(spacing);\n attrs[keys.array] = `${pathLength} ${pathSpacing}`;\n}\n\nexport { buildSVGPath };\n","import { buildHTMLStyles } from '../../html/utils/build-styles.mjs';\nimport { buildSVGPath } from './path.mjs';\n\n/**\n * Build SVG visual attributes, like cx and style.transform\n */\nfunction buildSVGAttrs(state, { attrX, attrY, attrScale, pathLength, pathSpacing = 1, pathOffset = 0, \n// This is object creation, which we try to avoid per-frame.\n...latest }, isSVGTag, transformTemplate, styleProp) {\n buildHTMLStyles(state, latest, transformTemplate);\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 state.attrs = state.style;\n state.style = {};\n const { attrs, style } = state;\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 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 ?? \"fill-box\";\n delete attrs.transformBox;\n }\n // Render attrX/attrY/attrScale as attributes\n if (attrX !== undefined)\n attrs.x = attrX;\n if (attrY !== undefined)\n attrs.y = attrY;\n if (attrScale !== undefined)\n attrs.scale = attrScale;\n // Build SVG path if one has been defined\n if (pathLength !== undefined) {\n buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false);\n }\n}\n\nexport { buildSVGAttrs };\n","import { createHtmlRenderState } from '../../html/utils/create-render-state.mjs';\n\nconst createSvgRenderState = () => ({\n ...createHtmlRenderState(),\n attrs: {},\n});\n\nexport { createSvgRenderState };\n","const isSVGTag = (tag) => typeof tag === \"string\" && tag.toLowerCase() === \"svg\";\n\nexport { isSVGTag };\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 */\nconst 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\nexport { lowercaseSVGElements };\n","import { lowercaseSVGElements } from '../../svg/lowercase-elements.mjs';\n\nfunction isSVGComponent(Component) {\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 return false;\n }\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 return true;\n }\n return false;\n}\n\nexport { isSVGComponent };\n","\"use client\";\nimport { useContext } from 'react';\nimport { isAnimationControls } from '../../animation/utils/is-animation-controls.mjs';\nimport { MotionContext } from '../../context/MotionContext/index.mjs';\nimport { PresenceContext } from '../../context/PresenceContext.mjs';\nimport { isControllingVariants, isVariantNode } from '../../render/utils/is-controlling-variants.mjs';\nimport { resolveVariantFromProps } from '../../render/utils/resolve-variants.mjs';\nimport { useConstant } from '../../utils/use-constant.mjs';\nimport { resolveMotionValue } from '../../value/utils/resolve-motion-value.mjs';\n\nfunction makeState({ scrapeMotionValuesFromProps, createRenderState, }, props, context, presenceContext) {\n const state = {\n latestValues: makeLatestValues(props, context, presenceContext, scrapeMotionValuesFromProps),\n renderState: createRenderState(),\n };\n return state;\n}\nfunction makeLatestValues(props, context, presenceContext, scrapeMotionValues) {\n const values = {};\n const motionValues = scrapeMotionValues(props, {});\n for (const key in motionValues) {\n values[key] = resolveMotionValue(motionValues[key]);\n }\n let { initial, animate } = props;\n const isControllingVariants$1 = isControllingVariants(props);\n const isVariantNode$1 = isVariantNode(props);\n if (context &&\n isVariantNode$1 &&\n !isControllingVariants$1 &&\n props.inherit !== false) {\n if (initial === undefined)\n initial = context.initial;\n if (animate === undefined)\n animate = context.animate;\n }\n let isInitialAnimationBlocked = presenceContext\n ? presenceContext.initial === false\n : false;\n isInitialAnimationBlocked = isInitialAnimationBlocked || initial === false;\n const variantToSet = isInitialAnimationBlocked ? animate : initial;\n if (variantToSet &&\n typeof variantToSet !== \"boolean\" &&\n !isAnimationControls(variantToSet)) {\n const list = Array.isArray(variantToSet) ? variantToSet : [variantToSet];\n for (let i = 0; i < list.length; i++) {\n const resolved = resolveVariantFromProps(props, list[i]);\n if (resolved) {\n const { transitionEnd, transition, ...target } = resolved;\n for (const key in target) {\n let valueTarget = target[key];\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];\n }\n if (valueTarget !== null) {\n values[key] = valueTarget;\n }\n }\n for (const key in transitionEnd) {\n values[key] = transitionEnd[key];\n }\n }\n }\n }\n return values;\n}\nconst makeUseVisualState = (config) => (props, isStatic) => {\n const context = useContext(MotionContext);\n const presenceContext = useContext(PresenceContext);\n const make = () => makeState(config, props, context, presenceContext);\n return isStatic ? make() : useConstant(make);\n};\n\nexport { makeUseVisualState };\n","function getValueState(visualElement) {\n const state = [{}, {}];\n visualElement?.values.forEach((value, key) => {\n state[0][key] = value.get();\n state[1][key] = value.getVelocity();\n });\n return state;\n}\nfunction resolveVariantFromProps(props, definition, custom, visualElement) {\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(custom !== undefined ? custom : props.custom, current, velocity);\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 * 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(custom !== undefined ? custom : props.custom, current, velocity);\n }\n return definition;\n}\n\nexport { resolveVariantFromProps };\n","import { isMotionValue } from 'motion-dom';\n\n/**\n * If the provided value is a MotionValue, this returns the actual value, otherwise just the value itself\n *\n * TODO: Remove and move to library\n */\nfunction resolveMotionValue(value) {\n return isMotionValue(value) ? value.get() : value;\n}\n\nexport { resolveMotionValue };\n","import { isMotionValue } from 'motion-dom';\nimport { isForcedMotionValue } from '../../../motion/utils/is-forced-motion-value.mjs';\n\nfunction scrapeMotionValuesFromProps(props, prevProps, visualElement) {\n const { style } = props;\n const newValues = {};\n for (const key in style) {\n if (isMotionValue(style[key]) ||\n (prevProps.style &&\n isMotionValue(prevProps.style[key])) ||\n isForcedMotionValue(key, props) ||\n visualElement?.getValue(key)?.liveStyle !== undefined) {\n newValues[key] = style[key];\n }\n }\n return newValues;\n}\n\nexport { scrapeMotionValuesFromProps };\n","\"use client\";\nimport { makeUseVisualState } from '../../motion/utils/use-visual-state.mjs';\nimport { createHtmlRenderState } from './utils/create-render-state.mjs';\nimport { scrapeMotionValuesFromProps } from './utils/scrape-motion-values.mjs';\n\nconst useHTMLVisualState = /*@__PURE__*/ makeUseVisualState({\n scrapeMotionValuesFromProps,\n createRenderState: createHtmlRenderState,\n});\n\nexport { useHTMLVisualState };\n","import { isMotionValue, transformPropOrder } from 'motion-dom';\nimport { scrapeMotionValuesFromProps as scrapeMotionValuesFromProps$1 } from '../../html/utils/scrape-motion-values.mjs';\n\nfunction scrapeMotionValuesFromProps(props, prevProps, visualElement) {\n const newValues = scrapeMotionValuesFromProps$1(props, prevProps, visualElement);\n for (const key in props) {\n if (isMotionValue(props[key]) ||\n isMotionValue(prevProps[key])) {\n const targetKey = transformPropOrder.indexOf(key) !== -1\n ? \"attr\" + key.charAt(0).toUpperCase() + key.substring(1)\n : key;\n newValues[targetKey] = props[key];\n }\n }\n return newValues;\n}\n\nexport { scrapeMotionValuesFromProps };\n","\"use client\";\nimport { makeUseVisualState } from '../../motion/utils/use-visual-state.mjs';\nimport { createSvgRenderState } from './utils/create-render-state.mjs';\nimport { scrapeMotionValuesFromProps } from './utils/scrape-motion-values.mjs';\n\nconst useSVGVisualState = /*@__PURE__*/ makeUseVisualState({\n scrapeMotionValuesFromProps: scrapeMotionValuesFromProps,\n createRenderState: createSvgRenderState,\n});\n\nexport { useSVGVisualState };\n","const motionComponentSymbol = Symbol.for(\"motionComponentSymbol\");\n\nexport { motionComponentSymbol };\n","\"use client\";\nimport { useCallback } from 'react';\nimport { isRefObject } from '../../utils/is-ref-object.mjs';\n\n/**\n * Creates a ref function that, when called, hydrates the provided\n * external ref and VisualElement.\n */\nfunction useMotionRef(visualState, visualElement, externalRef) {\n return useCallback((instance) => {\n if (instance) {\n visualState.onMount && visualState.onMount(instance);\n }\n if (visualElement) {\n if (instance) {\n visualElement.mount(instance);\n }\n else {\n visualElement.unmount();\n }\n }\n if (externalRef) {\n if (typeof externalRef === \"function\") {\n externalRef(instance);\n }\n else if (isRefObject(externalRef)) {\n externalRef.current = instance;\n }\n }\n }, \n /**\n * Include externalRef in dependencies to ensure the callback updates\n * when the ref changes, allowing proper ref forwarding.\n */\n [visualElement]);\n}\n\nexport { useMotionRef };\n","function isRefObject(ref) {\n return (ref &&\n typeof ref === \"object\" &&\n Object.prototype.hasOwnProperty.call(ref, \"current\"));\n}\n\nexport { isRefObject };\n","\"use client\";\nimport { useContext, useRef, useInsertionEffect, useEffect } from 'react';\nimport { optimizedAppearDataAttribute } from '../../animation/optimized-appear/data-id.mjs';\nimport { LazyContext } from '../../context/LazyContext.mjs';\nimport { MotionConfigContext } from '../../context/MotionConfigContext.mjs';\nimport { MotionContext } from '../../context/MotionContext/index.mjs';\nimport { PresenceContext } from '../../context/PresenceContext.mjs';\nimport { SwitchLayoutGroupContext } from '../../context/SwitchLayoutGroupContext.mjs';\nimport { isRefObject } from '../../utils/is-ref-object.mjs';\nimport { useIsomorphicLayoutEffect } from '../../utils/use-isomorphic-effect.mjs';\n\nfunction useVisualElement(Component, visualState, props, createVisualElement, ProjectionNodeConstructor) {\n const { visualElement: parent } = useContext(MotionContext);\n const lazyContext = useContext(LazyContext);\n const presenceContext = useContext(PresenceContext);\n const reducedMotionConfig = useContext(MotionConfigContext).reducedMotion;\n const visualElementRef = useRef(null);\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;\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 });\n }\n const visualElement = visualElementRef.current;\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 if (visualElement &&\n !visualElement.projection &&\n ProjectionNodeConstructor &&\n (visualElement.type === \"html\" || visualElement.type === \"svg\")) {\n createProjectionNode(visualElementRef.current, props, ProjectionNodeConstructor, initialLayoutGroupConfig);\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 * 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 = props[optimizedAppearDataAttribute];\n const wantsHandoff = useRef(Boolean(optimisedAppearId) &&\n !window.MotionHandoffIsComplete?.(optimisedAppearId) &&\n window.MotionHasOptimisedAnimation?.(optimisedAppearId));\n useIsomorphicLayoutEffect(() => {\n if (!visualElement)\n return;\n isMounted.current = true;\n window.MotionIsMounted = true;\n visualElement.updateFeatures();\n visualElement.scheduleRenderMicrotask();\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 useEffect(() => {\n if (!visualElement)\n return;\n if (!wantsHandoff.current && visualElement.animationState) {\n visualElement.animationState.animateChanges();\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 wantsHandoff.current = false;\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 return visualElement;\n}\nfunction createProjectionNode(visualElement, props, ProjectionNodeConstructor, initialPromotionConfig) {\n const { layoutId, layout, drag, dragConstraints, layoutScroll, layoutRoot, layoutCrossfade, } = props;\n visualElement.projection = new ProjectionNodeConstructor(visualElement.latestValues, props[\"data-framer-portal-id\"]\n ? undefined\n : getClosestProjectingNode(visualElement.parent));\n visualElement.projection.setOptions({\n layoutId,\n layout,\n alwaysMeasureLayout: 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 });\n}\nfunction getClosestProjectingNode(visualElement) {\n if (!visualElement)\n return undefined;\n return visualElement.options.allowProjection !== false\n ? visualElement.projection\n : getClosestProjectingNode(visualElement.parent);\n}\n\nexport { useVisualElement };\n","/**\n * Convert camelCase to dash-case properties.\n */\nconst camelToDash = (str) => str.replace(/([a-z])([A-Z])/gu, \"$1-$2\").toLowerCase();\n\nexport { camelToDash };\n","import { camelToDash } from '../../render/dom/utils/camel-to-dash.mjs';\n\nconst optimizedAppearDataId = \"framerAppearId\";\nconst optimizedAppearDataAttribute = \"data-\" + camelToDash(optimizedAppearDataId);\n\nexport { optimizedAppearDataAttribute, optimizedAppearDataId };\n","\"use client\";\nimport { createContext } from 'react';\n\n/**\n * Internal, exported only for usage in Framer\n */\nconst SwitchLayoutGroupContext = createContext({});\n\nexport { SwitchLayoutGroupContext };\n","import { warnOnce } from 'motion-utils';\nimport { createMotionComponent } from '../../motion/index.mjs';\n\nfunction createMotionProxy(preloadedFeatures, createVisualElement) {\n if (typeof Proxy === \"undefined\") {\n return createMotionComponent;\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();\n const factory = (Component, options) => {\n return createMotionComponent(Component, options, preloadedFeatures, createVisualElement);\n };\n /**\n * Support for deprecated`motion(Component)` pattern\n */\n const deprecatedFactoryFunction = (Component, options) => {\n if (process.env.NODE_ENV !== \"production\") {\n warnOnce(false, \"motion() is deprecated. Use motion.create() instead.\");\n }\n return factory(Component, options);\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) => {\n if (key === \"create\")\n return factory;\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(key, createMotionComponent(key, undefined, preloadedFeatures, createVisualElement));\n }\n return componentCache.get(key);\n },\n });\n}\n\nexport { createMotionProxy };\n","import { Fragment } from 'react';\nimport { HTMLVisualElement } from '../html/HTMLVisualElement.mjs';\nimport { SVGVisualElement } from '../svg/SVGVisualElement.mjs';\nimport { isSVGComponent } from './utils/is-svg-component.mjs';\n\nconst createDomVisualElement = (Component, options) => {\n return isSVGComponent(Component)\n ? new SVGVisualElement(options)\n : new HTMLVisualElement(options, {\n allowProjection: Component !== Fragment,\n });\n};\n\nexport { createDomVisualElement };\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 */\nfunction convertBoundingBoxToBox({ top, left, right, bottom, }) {\n return {\n x: { min: left, max: right },\n y: { min: top, max: bottom },\n };\n}\nfunction convertBoxToBoundingBox({ x, y }) {\n return { top: y.min, right: x.max, bottom: y.max, left: x.min };\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 */\nfunction transformBoxPoints(point, transformPoint) {\n if (!transformPoint)\n return point;\n const topLeft = transformPoint({ x: point.left, y: point.top });\n const bottomRight = transformPoint({ x: point.right, y: point.bottom });\n return {\n top: topLeft.y,\n left: topLeft.x,\n bottom: bottomRight.y,\n right: bottomRight.x,\n };\n}\n\nexport { convertBoundingBoxToBox, convertBoxToBoundingBox, transformBoxPoints };\n","function isIdentityScale(scale) {\n return scale === undefined || scale === 1;\n}\nfunction hasScale({ scale, scaleX, scaleY }) {\n return (!isIdentityScale(scale) ||\n !isIdentityScale(scaleX) ||\n !isIdentityScale(scaleY));\n}\nfunction hasTransform(values) {\n return (hasScale(values) ||\n has2DTranslate(values) ||\n values.z ||\n values.rotate ||\n values.rotateX ||\n values.rotateY ||\n values.skewX ||\n values.skewY);\n}\nfunction has2DTranslate(values) {\n return is2DTranslate(values.x) || is2DTranslate(values.y);\n}\nfunction is2DTranslate(value) {\n return value && value !== \"0%\";\n}\n\nexport { has2DTranslate, hasScale, hasTransform };\n","import { mixNumber } from 'motion-dom';\nimport { hasTransform } from '../utils/has-transform.mjs';\n\n/**\n * Scales a point based on a factor and an originPoint\n */\nfunction scalePoint(point, scale, originPoint) {\n const distanceFromOrigin = point - originPoint;\n const scaled = scale * distanceFromOrigin;\n return originPoint + scaled;\n}\n/**\n * Applies a translate/scale delta to a point\n */\nfunction applyPointDelta(point, translate, scale, originPoint, boxScale) {\n if (boxScale !== undefined) {\n point = scalePoint(point, boxScale, originPoint);\n }\n return scalePoint(point, scale, originPoint) + translate;\n}\n/**\n * Applies a translate/scale delta to an axis\n */\nfunction applyAxisDelta(axis, translate = 0, scale = 1, originPoint, boxScale) {\n axis.min = applyPointDelta(axis.min, translate, scale, originPoint, boxScale);\n axis.max = applyPointDelta(axis.max, translate, scale, originPoint, boxScale);\n}\n/**\n * Applies a translate/scale delta to a box\n */\nfunction applyBoxDelta(box, { x, y }) {\n applyAxisDelta(box.x, x.translate, x.scale, x.originPoint);\n applyAxisDelta(box.y, y.translate, y.scale, y.originPoint);\n}\nconst TREE_SCALE_SNAP_MIN = 0.999999999999;\nconst TREE_SCALE_SNAP_MAX = 1.0000000000001;\n/**\n * Apply a tree of deltas to a box. We do this to calculate the effect of all the transforms\n * in a tree upon our box before then calculating how to project it into our desired viewport-relative box\n *\n * This is the final nested loop within updateLayoutDelta for future refactoring\n */\nfunction applyTreeDeltas(box, treeScale, treePath, isSharedTransition = false) {\n const treeLength = treePath.length;\n if (!treeLength)\n return;\n // Reset the treeScale\n treeScale.x = treeScale.y = 1;\n let node;\n let delta;\n for (let i = 0; i < treeLength; i++) {\n node = treePath[i];\n delta = node.projectionDelta;\n /**\n * TODO: Prefer to remove this, but currently we have motion components with\n * display: contents in Framer.\n */\n const { visualElement } = node.options;\n if (visualElement &&\n visualElement.props.style &&\n visualElement.props.style.display === \"contents\") {\n continue;\n }\n if (isSharedTransition &&\n node.options.layoutScroll &&\n node.scroll &&\n node !== node.root) {\n transformBox(box, {\n x: -node.scroll.offset.x,\n y: -node.scroll.offset.y,\n });\n }\n if (delta) {\n // Incoporate each ancestor's scale into a culmulative treeScale for this component\n treeScale.x *= delta.x.scale;\n treeScale.y *= delta.y.scale;\n // Apply each ancestor's calculated delta into this component's recorded layout box\n applyBoxDelta(box, delta);\n }\n if (isSharedTransition && hasTransform(node.latestValues)) {\n transformBox(box, node.latestValues);\n }\n }\n /**\n * Snap tree scale back to 1 if it's within a non-perceivable threshold.\n * This will help reduce useless scales getting rendered.\n */\n if (treeScale.x < TREE_SCALE_SNAP_MAX &&\n treeScale.x > TREE_SCALE_SNAP_MIN) {\n treeScale.x = 1.0;\n }\n if (treeScale.y < TREE_SCALE_SNAP_MAX &&\n treeScale.y > TREE_SCALE_SNAP_MIN) {\n treeScale.y = 1.0;\n }\n}\nfunction translateAxis(axis, distance) {\n axis.min = axis.min + distance;\n axis.max = axis.max + distance;\n}\n/**\n * Apply a transform to an axis from the latest resolved motion values.\n * This function basically acts as a bridge between a flat motion value map\n * and applyAxisDelta\n */\nfunction transformAxis(axis, axisTranslate, axisScale, boxScale, axisOrigin = 0.5) {\n const originPoint = mixNumber(axis.min, axis.max, axisOrigin);\n // Apply the axis delta to the final axis\n applyAxisDelta(axis, axisTranslate, axisScale, originPoint, boxScale);\n}\n/**\n * Apply a transform to a box from the latest resolved motion values.\n */\nfunction transformBox(box, transform) {\n transformAxis(box.x, transform.x, transform.scaleX, transform.scale, transform.originX);\n transformAxis(box.y, transform.y, transform.scaleY, transform.scale, transform.originY);\n}\n\nexport { applyAxisDelta, applyBoxDelta, applyPointDelta, applyTreeDeltas, scalePoint, transformAxis, transformBox, translateAxis };\n","import { convertBoundingBoxToBox, transformBoxPoints } from '../geometry/conversion.mjs';\nimport { translateAxis } from '../geometry/delta-apply.mjs';\n\nfunction measureViewportBox(instance, transformPoint) {\n return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint));\n}\nfunction measurePageBox(element, rootProjectionNode, transformPagePoint) {\n const viewportBox = measureViewportBox(element, transformPagePoint);\n const { scroll } = rootProjectionNode;\n if (scroll) {\n translateAxis(viewportBox.x, scroll.offset.x);\n translateAxis(viewportBox.y, scroll.offset.y);\n }\n return viewportBox;\n}\n\nexport { measurePageBox, measureViewportBox };\n","const createAxisDelta = () => ({\n translate: 0,\n scale: 1,\n origin: 0,\n originPoint: 0,\n});\nconst createDelta = () => ({\n x: createAxisDelta(),\n y: createAxisDelta(),\n});\nconst createAxis = () => ({ min: 0, max: 0 });\nconst createBox = () => ({\n x: createAxis(),\n y: createAxis(),\n});\n\nexport { createAxis, createAxisDelta, createBox, createDelta };\n","// Does this device prefer reduced motion? Returns `null` server-side.\nconst prefersReducedMotion = { current: null };\nconst hasReducedMotionListener = { current: false };\n\nexport { hasReducedMotionListener, prefersReducedMotion };\n","import { isBrowser } from '../is-browser.mjs';\nimport { hasReducedMotionListener, prefersReducedMotion } from './state.mjs';\n\nfunction initPrefersReducedMotion() {\n hasReducedMotionListener.current = true;\n if (!isBrowser)\n return;\n if (window.matchMedia) {\n const motionMediaQuery = window.matchMedia(\"(prefers-reduced-motion)\");\n const setReducedMotionPreferences = () => (prefersReducedMotion.current = motionMediaQuery.matches);\n motionMediaQuery.addEventListener(\"change\", setReducedMotionPreferences);\n setReducedMotionPreferences();\n }\n else {\n prefersReducedMotion.current = false;\n }\n}\n\nexport { initPrefersReducedMotion };\n","const visualElementStore = new WeakMap();\n\nexport { visualElementStore };\n","import { isMotionValue, motionValue } from 'motion-dom';\n\nfunction updateMotionValuesFromProps(element, next, prev) {\n for (const key in next) {\n const nextValue = next[key];\n const prevValue = prev[key];\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 }\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 }\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 if (existingValue.liveStyle === true) {\n existingValue.jump(nextValue);\n }\n else if (!existingValue.hasAnimated) {\n existingValue.set(nextValue);\n }\n }\n else {\n const latestValue = element.getStaticValue(key);\n element.addValue(key, motionValue(latestValue !== undefined ? latestValue : nextValue, { owner: element }));\n }\n }\n }\n // Handle removed values\n for (const key in prev) {\n if (next[key] === undefined)\n element.removeValue(key);\n }\n return next;\n}\n\nexport { updateMotionValuesFromProps };\n","import { KeyframeResolver, time, frame, isMotionValue, cancelFrame, transformProps, motionValue, findValueType, complex, getAnimatableNone, microtask } from 'motion-dom';\nimport { warnOnce, isNumericalString, isZeroValueString, SubscriptionManager } from 'motion-utils';\nimport { featureDefinitions } from '../motion/features/definitions.mjs';\nimport { createBox } from '../projection/geometry/models.mjs';\nimport { initPrefersReducedMotion } from '../utils/reduced-motion/index.mjs';\nimport { hasReducedMotionListener, prefersReducedMotion } from '../utils/reduced-motion/state.mjs';\nimport { visualElementStore } from './store.mjs';\nimport { isControllingVariants, isVariantNode } from './utils/is-controlling-variants.mjs';\nimport { updateMotionValuesFromProps } from './utils/motion-values.mjs';\nimport { resolveVariantFromProps } from './utils/resolve-variants.mjs';\n\nconst propEventHandlers = [\n \"AnimationStart\",\n \"AnimationComplete\",\n \"Update\",\n \"BeforeLayoutMeasure\",\n \"LayoutMeasure\",\n \"LayoutAnimationStart\",\n \"LayoutAnimationComplete\",\n];\n/**\n * A VisualElement is an imperative abstraction around UI elements such as\n * HTMLElement, SVGElement, Three.Object3D etc.\n */\nclass VisualElement {\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(_props, _prevProps, _visualElement) {\n return {};\n }\n constructor({ parent, props, presenceContext, reducedMotionConfig, blockInitialAnimation, visualState, }, options = {}) {\n /**\n * A reference to the current underlying Instance, e.g. a HTMLElement\n * or Three.Mesh etc.\n */\n this.current = null;\n /**\n * A set containing references to this VisualElement's children.\n */\n this.children = new Set();\n /**\n * Determine what role this visual element should take in the variant tree.\n */\n this.isVariantNode = false;\n this.isControllingVariants = false;\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 this.shouldReduceMotion = null;\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 this.values = new Map();\n this.KeyframeResolver = KeyframeResolver;\n /**\n * Cleanup functions for active features (hover/tap/exit etc)\n */\n this.features = {};\n /**\n * A map of every subscription that binds the provided or generated\n * motion values onChange listeners to this visual element.\n */\n this.valueSubscriptions = new Map();\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 this.prevMotionValues = {};\n /**\n * An object containing a SubscriptionManager for each active event.\n */\n this.events = {};\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 this.propEventSubscriptions = {};\n this.notifyUpdate = () => this.notify(\"Update\", this.latestValues);\n this.render = () => {\n if (!this.current)\n return;\n this.triggerBuild();\n this.renderInstance(this.current, this.renderState, this.props.style, this.projection);\n };\n this.renderScheduledAt = 0.0;\n this.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 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.options = options;\n this.blockInitialAnimation = Boolean(blockInitialAnimation);\n this.isControllingVariants = isControllingVariants(props);\n this.isVariantNode = isVariantNode(props);\n if (this.isVariantNode) {\n this.variantChildren = new Set();\n }\n this.manuallyAnimateOnMount = Boolean(parent && parent.current);\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 } = this.scrapeMotionValuesFromProps(props, {}, this);\n for (const key in initialMotionValues) {\n const value = initialMotionValues[key];\n if (latestValues[key] !== undefined && isMotionValue(value)) {\n value.set(latestValues[key]);\n }\n }\n }\n mount(instance) {\n this.current = instance;\n visualElementStore.set(instance, this);\n if (this.projection && !this.projection.instance) {\n this.projection.mount(instance);\n }\n if (this.parent && this.isVariantNode && !this.isControllingVariants) {\n this.removeFromVariantTree = this.parent.addVariantChild(this);\n }\n this.values.forEach((value, key) => this.bindToMotionValue(key, value));\n if (!hasReducedMotionListener.current) {\n initPrefersReducedMotion();\n }\n this.shouldReduceMotion =\n this.reducedMotionConfig === \"never\"\n ? false\n : this.reducedMotionConfig === \"always\"\n ? true\n : prefersReducedMotion.current;\n if (process.env.NODE_ENV !== \"production\") {\n warnOnce(this.shouldReduceMotion !== true, \"You have Reduced Motion enabled on your device. Animations may not appear as expected.\", \"reduced-motion-disabled\");\n }\n this.parent?.addChild(this);\n this.update(this.props, this.presenceContext);\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 for (const key in this.events) {\n this.events[key].clear();\n }\n for (const key in this.features) {\n const feature = this.features[key];\n if (feature) {\n feature.unmount();\n feature.isMounted = false;\n }\n }\n this.current = null;\n }\n addChild(child) {\n this.children.add(child);\n this.enteringChildren ?? (this.enteringChildren = new Set());\n this.enteringChildren.add(child);\n }\n removeChild(child) {\n this.children.delete(child);\n this.enteringChildren && this.enteringChildren.delete(child);\n }\n bindToMotionValue(key, value) {\n if (this.valueSubscriptions.has(key)) {\n this.valueSubscriptions.get(key)();\n }\n const valueIsTransform = transformProps.has(key);\n if (valueIsTransform && this.onBindTransform) {\n this.onBindTransform();\n }\n const removeOnChange = value.on(\"change\", (latestValue) => {\n this.latestValues[key] = latestValue;\n this.props.onUpdate && frame.preRender(this.notifyUpdate);\n if (valueIsTransform && this.projection) {\n this.projection.isTransformDirty = true;\n }\n this.scheduleRender();\n });\n let removeSyncCheck;\n if (window.MotionCheckAppearSync) {\n removeSyncCheck = window.MotionCheckAppearSync(this, key, value);\n }\n this.valueSubscriptions.set(key, () => {\n removeOnChange();\n if (removeSyncCheck)\n removeSyncCheck();\n if (value.owner)\n value.stop();\n });\n }\n sortNodePosition(other) {\n /**\n * If these nodes aren't even of the same type we can't compare their depth.\n */\n if (!this.current ||\n !this.sortInstanceNodePosition ||\n this.type !== other.type) {\n return 0;\n }\n return this.sortInstanceNodePosition(this.current, other.current);\n }\n updateFeatures() {\n let key = \"animation\";\n for (key in featureDefinitions) {\n const featureDefinition = featureDefinitions[key];\n if (!featureDefinition)\n continue;\n const { isEnabled, Feature: FeatureConstructor } = featureDefinition;\n /**\n * If this feature is enabled but not active, make a new instance.\n */\n if (!this.features[key] &&\n FeatureConstructor &&\n isEnabled(this.props)) {\n this.features[key] = new FeatureConstructor(this);\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 }\n else {\n feature.mount();\n feature.isMounted = true;\n }\n }\n }\n }\n triggerBuild() {\n this.build(this.renderState, this.latestValues, this.props);\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 getStaticValue(key) {\n return this.latestValues[key];\n }\n setStaticValue(key, value) {\n this.latestValues[key] = value;\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(props, presenceContext) {\n if (props.transformTemplate || this.props.transformTemplate) {\n this.scheduleRender();\n }\n this.prevProps = this.props;\n this.props = props;\n this.prevPresenceContext = this.presenceContext;\n this.presenceContext = presenceContext;\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 const listenerName = (\"on\" + key);\n const listener = props[listenerName];\n if (listener) {\n this.propEventSubscriptions[key] = this.on(key, listener);\n }\n }\n this.prevMotionValues = updateMotionValuesFromProps(this, this.scrapeMotionValuesFromProps(props, this.prevProps, this), this.prevMotionValues);\n if (this.handleChildMotionValue) {\n this.handleChildMotionValue();\n }\n }\n getProps() {\n return this.props;\n }\n /**\n * Returns the variant definition with a given name.\n */\n getVariant(name) {\n return this.props.variants ? this.props.variants[name] : undefined;\n }\n /**\n * Returns the defined default transition on this component.\n */\n getDefaultTransition() {\n return this.props.transition;\n }\n getTransformPagePoint() {\n return this.props.transformPagePoint;\n }\n getClosestVariantNode() {\n return this.isVariantNode\n ? this\n : this.parent\n ? this.parent.getClosestVariantNode()\n : undefined;\n }\n /**\n * Add a child visual element to our set of children.\n */\n addVariantChild(child) {\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 * Add a motion value and bind it to this visual element.\n */\n addValue(key, value) {\n // Remove existing value if it exists\n const existingValue = this.values.get(key);\n if (value !== existingValue) {\n if (existingValue)\n this.removeValue(key);\n this.bindToMotionValue(key, value);\n this.values.set(key, value);\n this.latestValues[key] = value.get();\n }\n }\n /**\n * Remove a motion value and unbind any active subscriptions.\n */\n removeValue(key) {\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 * Check whether we have a motion value for this key\n */\n hasValue(key) {\n return this.values.has(key);\n }\n getValue(key, defaultValue) {\n if (this.props.values && this.props.values[key]) {\n return this.props.values[key];\n }\n let value = this.values.get(key);\n if (value === undefined && defaultValue !== undefined) {\n value = motionValue(defaultValue === null ? undefined : defaultValue, { owner: this });\n this.addValue(key, value);\n }\n return value;\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, target) {\n let value = 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 if (value !== undefined && value !== null) {\n if (typeof value === \"string\" &&\n (isNumericalString(value) || isZeroValueString(value))) {\n // If this is a number read as a string, ie \"0\" or \"200\", convert it to a number\n value = parseFloat(value);\n }\n else if (!findValueType(value) && complex.test(target)) {\n value = getAnimatableNone(key, target);\n }\n this.setBaseTarget(key, isMotionValue(value) ? value.get() : value);\n }\n return isMotionValue(value) ? value.get() : value;\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, value) {\n this.baseTarget[key] = value;\n }\n /**\n * Find the base target for a value thats been removed from all animation\n * props.\n */\n getBaseTarget(key) {\n const { initial } = this.props;\n let valueFromInitial;\n if (typeof initial === \"string\" || typeof initial === \"object\") {\n const variant = resolveVariantFromProps(this.props, initial, this.presenceContext?.custom);\n if (variant) {\n valueFromInitial = variant[key];\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 * 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))\n return target;\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 on(eventName, callback) {\n if (!this.events[eventName]) {\n this.events[eventName] = new SubscriptionManager();\n }\n return this.events[eventName].add(callback);\n }\n notify(eventName, ...args) {\n if (this.events[eventName]) {\n this.events[eventName].notify(...args);\n }\n }\n scheduleRenderMicrotask() {\n microtask.render(this.render);\n }\n}\n\nexport { VisualElement };\n","import { DOMKeyframesResolver, isMotionValue } from 'motion-dom';\nimport { VisualElement } from '../VisualElement.mjs';\n\nclass DOMVisualElement extends VisualElement {\n constructor() {\n super(...arguments);\n this.KeyframeResolver = DOMKeyframesResolver;\n }\n sortInstanceNodePosition(a, b) {\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 getBaseTargetFromProps(props, key) {\n return props.style\n ? props.style[key]\n : undefined;\n }\n removeValueFromRenderState(key, { vars, style }) {\n delete vars[key];\n delete style[key];\n }\n handleChildMotionValue() {\n if (this.childSubscription) {\n this.childSubscription();\n delete this.childSubscription;\n }\n const { children } = this.props;\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\nexport { DOMVisualElement };\n","function renderHTML(element, { style, vars }, styleProp, projection) {\n const elementStyle = element.style;\n let key;\n for (key in style) {\n // CSSStyleDeclaration has [index: number]: string; in the types, so we use that as key type.\n elementStyle[key] = style[key];\n }\n // Write projection styles directly to element style\n projection?.applyProjectionStyles(elementStyle, styleProp);\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]);\n }\n}\n\nexport { renderHTML };\n","import { transformProps, defaultTransformValue, readTransformValue, isCSSVariableName } from 'motion-dom';\nimport { measureViewportBox } from '../../projection/utils/measure.mjs';\nimport { DOMVisualElement } from '../dom/DOMVisualElement.mjs';\nimport { buildHTMLStyles } from './utils/build-styles.mjs';\nimport { renderHTML } from './utils/render.mjs';\nimport { scrapeMotionValuesFromProps } from './utils/scrape-motion-values.mjs';\n\nfunction getComputedStyle(element) {\n return window.getComputedStyle(element);\n}\nclass HTMLVisualElement extends DOMVisualElement {\n constructor() {\n super(...arguments);\n this.type = \"html\";\n this.renderInstance = renderHTML;\n }\n readValueFromInstance(instance, key) {\n if (transformProps.has(key)) {\n return this.projection?.isProjecting\n ? defaultTransformValue(key)\n : readTransformValue(instance, key);\n }\n else {\n const computedStyle = getComputedStyle(instance);\n const value = (isCSSVariableName(key)\n ? computedStyle.getPropertyValue(key)\n : computedStyle[key]) || 0;\n return typeof value === \"string\" ? value.trim() : value;\n }\n }\n measureInstanceViewportBox(instance, { transformPagePoint }) {\n return measureViewportBox(instance, transformPagePoint);\n }\n build(renderState, latestValues, props) {\n buildHTMLStyles(renderState, latestValues, props.transformTemplate);\n }\n scrapeMotionValuesFromProps(props, prevProps, visualElement) {\n return scrapeMotionValuesFromProps(props, prevProps, visualElement);\n }\n}\n\nexport { HTMLVisualElement, getComputedStyle };\n","/**\n * A set of attribute names that are always read/written as camel case.\n */\nconst 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\nexport { camelCaseAttributes };\n","import { camelToDash } from '../../dom/utils/camel-to-dash.mjs';\nimport { renderHTML } from '../../html/utils/render.mjs';\nimport { camelCaseAttributes } from './camel-case-attrs.mjs';\n\nfunction renderSVG(element, renderState, _styleProp, projection) {\n renderHTML(element, renderState, undefined, projection);\n for (const key in renderState.attrs) {\n element.setAttribute(!camelCaseAttributes.has(key) ? camelToDash(key) : key, renderState.attrs[key]);\n }\n}\n\nexport { renderSVG };\n","import { transformProps, getDefaultValueType } from 'motion-dom';\nimport { createBox } from '../../projection/geometry/models.mjs';\nimport { DOMVisualElement } from '../dom/DOMVisualElement.mjs';\nimport { camelToDash } from '../dom/utils/camel-to-dash.mjs';\nimport { buildSVGAttrs } from './utils/build-attrs.mjs';\nimport { camelCaseAttributes } from './utils/camel-case-attrs.mjs';\nimport { isSVGTag } from './utils/is-svg-tag.mjs';\nimport { renderSVG } from './utils/render.mjs';\nimport { scrapeMotionValuesFromProps } from './utils/scrape-motion-values.mjs';\n\nclass SVGVisualElement extends DOMVisualElement {\n constructor() {\n super(...arguments);\n this.type = \"svg\";\n this.isSVGTag = false;\n this.measureInstanceViewportBox = createBox;\n }\n getBaseTargetFromProps(props, key) {\n return props[key];\n }\n readValueFromInstance(instance, key) {\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 scrapeMotionValuesFromProps(props, prevProps, visualElement) {\n return scrapeMotionValuesFromProps(props, prevProps, visualElement);\n }\n build(renderState, latestValues, props) {\n buildSVGAttrs(renderState, latestValues, this.isSVGTag, props.transformTemplate, props.style);\n }\n renderInstance(instance, renderState, styleProp, projection) {\n renderSVG(instance, renderState, styleProp, projection);\n }\n mount(instance) {\n this.isSVGTag = isSVGTag(instance.tagName);\n super.mount(instance);\n }\n}\n\nexport { SVGVisualElement };\n","import { resolveVariantFromProps } from './resolve-variants.mjs';\n\nfunction resolveVariant(visualElement, definition, custom) {\n const props = visualElement.getProps();\n return resolveVariantFromProps(props, definition, custom !== undefined ? custom : props.custom, visualElement);\n}\n\nexport { resolveVariant };\n","const isKeyframesTarget = (v) => {\n return Array.isArray(v);\n};\n\nexport { isKeyframesTarget };\n","import { motionValue } from 'motion-dom';\nimport { isKeyframesTarget } from '../../animation/utils/is-keyframes-target.mjs';\nimport { resolveVariant } from './resolve-dynamic-variants.mjs';\n\n/**\n * Set VisualElement's MotionValue, creating a new MotionValue for it if\n * it doesn't exist.\n */\nfunction setMotionValue(visualElement, key, value) {\n if (visualElement.hasValue(key)) {\n visualElement.getValue(key).set(value);\n }\n else {\n visualElement.addValue(key, motionValue(value));\n }\n}\nfunction resolveFinalValueInKeyframes(v) {\n // TODO maybe throw if v.length - 1 is placeholder token?\n return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v;\n}\nfunction setTarget(visualElement, definition) {\n const resolved = resolveVariant(visualElement, definition);\n let { transitionEnd = {}, transition = {}, ...target } = resolved || {};\n target = { ...target, ...transitionEnd };\n for (const key in target) {\n const value = resolveFinalValueInKeyframes(target[key]);\n setMotionValue(visualElement, key, value);\n }\n}\n\nexport { setTarget };\n","import { isMotionValue } from 'motion-dom';\n\nfunction isWillChangeMotionValue(value) {\n return Boolean(isMotionValue(value) && value.add);\n}\n\nexport { isWillChangeMotionValue };\n","import { MotionGlobalConfig } from 'motion-utils';\nimport { isWillChangeMotionValue } from './is.mjs';\n\nfunction addValueToWillChange(visualElement, key) {\n const willChange = visualElement.getValue(\"willChange\");\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 }\n else if (!willChange && MotionGlobalConfig.WillChange) {\n const newWillChange = new MotionGlobalConfig.WillChange(\"auto\");\n visualElement.addValue(\"willChange\", newWillChange);\n newWillChange.add(key);\n }\n}\n\nexport { addValueToWillChange };\n","import { optimizedAppearDataAttribute } from './data-id.mjs';\n\nfunction getOptimisedAppearId(visualElement) {\n return visualElement.props[optimizedAppearDataAttribute];\n}\n\nexport { getOptimisedAppearId };\n","const isNotNull = (value) => value !== null;\nfunction getFinalKeyframe(keyframes, { repeat, repeatType = \"loop\" }, finalKeyframe) {\n const resolvedKeyframes = keyframes.filter(isNotNull);\n const index = repeat && repeatType !== \"loop\" && repeat % 2 === 1\n ? 0\n : resolvedKeyframes.length - 1;\n return !index || finalKeyframe === undefined\n ? resolvedKeyframes[index]\n : finalKeyframe;\n}\n\nexport { getFinalKeyframe };\n","import { transformProps } from 'motion-dom';\n\nconst underDampedSpring = {\n type: \"spring\",\n stiffness: 500,\n damping: 25,\n restSpeed: 10,\n};\nconst criticallyDampedSpring = (target) => ({\n type: \"spring\",\n stiffness: 550,\n damping: target === 0 ? 2 * Math.sqrt(550) : 30,\n restSpeed: 10,\n});\nconst keyframesTransition = {\n type: \"keyframes\",\n duration: 0.8,\n};\n/**\n * Default easing curve is a slightly shallower version of\n * the default browser easing curve.\n */\nconst ease = {\n type: \"keyframes\",\n ease: [0.25, 0.1, 0.35, 1],\n duration: 0.3,\n};\nconst getDefaultTransition = (valueKey, { keyframes }) => {\n if (keyframes.length > 2) {\n return keyframesTransition;\n }\n else if (transformProps.has(valueKey)) {\n return valueKey.startsWith(\"scale\")\n ? criticallyDampedSpring(keyframes[1])\n : underDampedSpring;\n }\n return ease;\n};\n\nexport { getDefaultTransition };\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 */\nfunction isTransitionDefined({ when, delay: _delay, delayChildren, staggerChildren, staggerDirection, repeat, repeatType, repeatDelay, from, elapsed, ...transition }) {\n return !!Object.keys(transition).length;\n}\n\nexport { isTransitionDefined };\n","import { getValueTransition, makeAnimationInstant, frame, JSAnimation, AsyncMotionValueAnimation } from 'motion-dom';\nimport { secondsToMilliseconds, MotionGlobalConfig } from 'motion-utils';\nimport { getFinalKeyframe } from '../animators/waapi/utils/get-final-keyframe.mjs';\nimport { getDefaultTransition } from '../utils/default-transitions.mjs';\nimport { isTransitionDefined } from '../utils/is-transition-defined.mjs';\n\nconst animateMotionValue = (name, value, target, transition = {}, element, isHandoff) => (onComplete) => {\n const valueTransition = getValueTransition(transition, name) || {};\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 * 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 const options = {\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 * 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 * 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 && (options.duration = secondsToMilliseconds(options.duration));\n options.repeatDelay && (options.repeatDelay = secondsToMilliseconds(options.repeatDelay));\n /**\n * Support deprecated way to set initial value. Prefer keyframe syntax.\n */\n if (options.from !== undefined) {\n options.keyframes[0] = options.from;\n }\n let shouldSkip = false;\n if (options.type === false ||\n (options.duration === 0 && !options.repeatDelay)) {\n makeAnimationInstant(options);\n if (options.delay === 0) {\n shouldSkip = true;\n }\n }\n if (MotionGlobalConfig.instantAnimations ||\n MotionGlobalConfig.skipAnimations) {\n shouldSkip = true;\n makeAnimationInstant(options);\n options.delay = 0;\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 * 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(options.keyframes, valueTransition);\n if (finalKeyframe !== undefined) {\n frame.update(() => {\n options.onUpdate(finalKeyframe);\n options.onComplete();\n });\n return;\n }\n }\n return valueTransition.isSync\n ? new JSAnimation(options)\n : new AsyncMotionValueAnimation(options);\n};\n\nexport { animateMotionValue };\n","import { getValueTransition, frame, positionalKeys } from 'motion-dom';\nimport { setTarget } from '../../render/utils/setters.mjs';\nimport { addValueToWillChange } from '../../value/use-will-change/add-will-change.mjs';\nimport { getOptimisedAppearId } from '../optimized-appear/get-appear-id.mjs';\nimport { animateMotionValue } from './motion-value.mjs';\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({ protectedKeys, needsAnimating }, key) {\n const shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true;\n needsAnimating[key] = false;\n return shouldBlock;\n}\nfunction animateTarget(visualElement, targetAndTransition, { delay = 0, transitionOverride, type } = {}) {\n let { transition = visualElement.getDefaultTransition(), transitionEnd, ...target } = targetAndTransition;\n if (transitionOverride)\n transition = transitionOverride;\n const animations = [];\n const animationTypeState = type &&\n visualElement.animationState &&\n visualElement.animationState.getState()[type];\n for (const key in target) {\n const value = visualElement.getValue(key, visualElement.latestValues[key] ?? null);\n const valueTarget = target[key];\n if (valueTarget === undefined ||\n (animationTypeState &&\n shouldBlockAnimation(animationTypeState, key))) {\n continue;\n }\n const valueTransition = {\n delay,\n ...getValueTransition(transition || {}, key),\n };\n /**\n * If the value is already at the defined target, skip the animation.\n */\n const currentValue = value.get();\n if (currentValue !== undefined &&\n !value.isAnimating &&\n !Array.isArray(valueTarget) &&\n valueTarget === currentValue &&\n !valueTransition.velocity) {\n continue;\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 if (appearId) {\n const startTime = window.MotionHandoffAnimation(appearId, key, frame);\n if (startTime !== null) {\n valueTransition.startTime = startTime;\n isHandoff = true;\n }\n }\n }\n addValueToWillChange(visualElement, key);\n value.start(animateMotionValue(key, value, valueTarget, visualElement.shouldReduceMotion && positionalKeys.has(key)\n ? { type: false }\n : valueTransition, visualElement, isHandoff));\n const animation = value.animation;\n if (animation) {\n animations.push(animation);\n }\n }\n if (transitionEnd) {\n Promise.all(animations).then(() => {\n frame.update(() => {\n transitionEnd && setTarget(visualElement, transitionEnd);\n });\n });\n }\n return animations;\n}\n\nexport { animateTarget };\n","function calcChildStagger(children, child, delayChildren, staggerChildren = 0, staggerDirection = 1) {\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 return delayIsFunction\n ? delayChildren(index, numChildren)\n : staggerDirection === 1\n ? index * staggerChildren\n : maxStaggerDuration - index * staggerChildren;\n}\n\nexport { calcChildStagger };\n","import { resolveVariant } from '../../render/utils/resolve-dynamic-variants.mjs';\nimport { calcChildStagger } from '../utils/calc-child-stagger.mjs';\nimport { animateTarget } from './visual-element-target.mjs';\n\nfunction animateVariant(visualElement, variant, options = {}) {\n const resolved = resolveVariant(visualElement, variant, options.type === \"exit\"\n ? visualElement.presenceContext?.custom\n : undefined);\n let { transition = visualElement.getDefaultTransition() || {} } = resolved || {};\n if (options.transitionOverride) {\n transition = options.transitionOverride;\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 = resolved\n ? () => Promise.all(animateTarget(visualElement, resolved, options))\n : () => Promise.resolve();\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 = visualElement.variantChildren && visualElement.variantChildren.size\n ? (forwardDelay = 0) => {\n const { delayChildren = 0, staggerChildren, staggerDirection, } = transition;\n return animateChildren(visualElement, variant, forwardDelay, delayChildren, staggerChildren, staggerDirection, options);\n }\n : () => Promise.resolve();\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] = when === \"beforeChildren\"\n ? [getAnimation, getChildAnimations]\n : [getChildAnimations, getAnimation];\n return first().then(() => last());\n }\n else {\n return Promise.all([getAnimation(), getChildAnimations(options.delay)]);\n }\n}\nfunction animateChildren(visualElement, variant, delay = 0, delayChildren = 0, staggerChildren = 0, staggerDirection = 1, options) {\n const animations = [];\n for (const child of visualElement.variantChildren) {\n child.notify(\"AnimationStart\", variant);\n animations.push(animateVariant(child, variant, {\n ...options,\n delay: delay +\n (typeof delayChildren === \"function\" ? 0 : delayChildren) +\n calcChildStagger(visualElement.variantChildren, child, delayChildren, staggerChildren, staggerDirection),\n }).then(() => child.notify(\"AnimationComplete\", variant)));\n }\n return Promise.all(animations);\n}\n\nexport { animateVariant };\n","import { resolveVariant } from '../../render/utils/resolve-dynamic-variants.mjs';\nimport { animateTarget } from './visual-element-target.mjs';\nimport { animateVariant } from './visual-element-variant.mjs';\n\nfunction animateVisualElement(visualElement, definition, options = {}) {\n visualElement.notify(\"AnimationStart\", definition);\n let animation;\n if (Array.isArray(definition)) {\n const animations = definition.map((variant) => animateVariant(visualElement, variant, options));\n animation = Promise.all(animations);\n }\n else if (typeof definition === \"string\") {\n animation = animateVariant(visualElement, definition, options);\n }\n else {\n const resolvedDefinition = typeof definition === \"function\"\n ? resolveVariant(visualElement, definition, options.custom)\n : definition;\n animation = Promise.all(animateTarget(visualElement, resolvedDefinition, options));\n }\n return animation.then(() => {\n visualElement.notify(\"AnimationComplete\", definition);\n });\n}\n\nexport { animateVisualElement };\n","function shallowCompare(next, prev) {\n if (!Array.isArray(prev))\n return false;\n const prevLength = prev.length;\n if (prevLength !== next.length)\n return false;\n for (let i = 0; i < prevLength; i++) {\n if (prev[i] !== next[i])\n return false;\n }\n return true;\n}\n\nexport { shallowCompare };\n","import { isVariantLabel } from './is-variant-label.mjs';\nimport { variantProps } from './variant-props.mjs';\n\nconst numVariantProps = variantProps.length;\nfunction getVariantContext(visualElement) {\n if (!visualElement)\n return undefined;\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;\n }\n return context;\n }\n const context = {};\n for (let i = 0; i < numVariantProps; i++) {\n const name = variantProps[i];\n const prop = visualElement.props[name];\n if (isVariantLabel(prop) || prop === false) {\n context[name] = prop;\n }\n }\n return context;\n}\n\nexport { getVariantContext };\n","import { animateVisualElement } from '../../animation/interfaces/visual-element.mjs';\nimport { calcChildStagger } from '../../animation/utils/calc-child-stagger.mjs';\nimport { isAnimationControls } from '../../animation/utils/is-animation-controls.mjs';\nimport { isKeyframesTarget } from '../../animation/utils/is-keyframes-target.mjs';\nimport { shallowCompare } from '../../utils/shallow-compare.mjs';\nimport { getVariantContext } from './get-variant-context.mjs';\nimport { isVariantLabel } from './is-variant-label.mjs';\nimport { resolveVariant } from './resolve-dynamic-variants.mjs';\nimport { variantPriorityOrder } from './variant-props.mjs';\n\nconst reversePriorityOrder = [...variantPriorityOrder].reverse();\nconst numAnimationTypes = variantPriorityOrder.length;\nfunction animateList(visualElement) {\n return (animations) => Promise.all(animations.map(({ animation, options }) => animateVisualElement(visualElement, animation, options)));\n}\nfunction createAnimationState(visualElement) {\n let animate = animateList(visualElement);\n let state = createState();\n let isInitialRender = true;\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 = (type) => (acc, definition) => {\n const resolved = resolveVariant(visualElement, definition, type === \"exit\"\n ? visualElement.presenceContext?.custom\n : undefined);\n if (resolved) {\n const { transition, transitionEnd, ...target } = resolved;\n acc = { ...acc, ...target, ...transitionEnd };\n }\n return acc;\n };\n /**\n * This just allows us to inject mocked animation functions\n * @internal\n */\n function setAnimateFunction(makeAnimator) {\n animate = makeAnimator(visualElement);\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) {\n const { props } = visualElement;\n const context = getVariantContext(visualElement.parent) || {};\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 = [];\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();\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 = {};\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 * 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 = props[type] !== undefined\n ? props[type]\n : context[type];\n const propIsVariant = isVariantLabel(prop);\n /**\n * If this type has *just* changed isActive status, set activeDelta\n * to that status. Otherwise set to null.\n */\n const activeDelta = type === changedActiveType ? typeState.isActive : null;\n if (activeDelta === false)\n removedVariantIndex = i;\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 = prop === context[type] &&\n prop !== props[type] &&\n propIsVariant;\n if (isInherited &&\n isInitialRender &&\n visualElement.manuallyAnimateOnMount) {\n isInherited = false;\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 // 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 continue;\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(typeState.prevProp, prop);\n let shouldAnimateType = 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 let handledRemovedValues = false;\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 * 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(buildResolvedTypeValues(type), {});\n if (activeDelta === false)\n resolvedValues = {};\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 const allKeys = {\n ...prevResolvedValues,\n ...resolvedValues,\n };\n const markToAnimate = (key) => {\n shouldAnimateType = true;\n if (removedKeys.has(key)) {\n handledRemovedValues = true;\n removedKeys.delete(key);\n }\n typeState.needsAnimating[key] = true;\n const motionValue = visualElement.getValue(key);\n if (motionValue)\n motionValue.liveStyle = false;\n };\n for (const key in allKeys) {\n const next = resolvedValues[key];\n const prev = prevResolvedValues[key];\n // If we've already handled this we can just skip ahead\n if (encounteredKeys.hasOwnProperty(key))\n continue;\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 = !shallowCompare(next, prev);\n }\n else {\n valueHasChanged = next !== prev;\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 }\n else {\n // If it's undefined, it's been removed.\n removedKeys.add(key);\n }\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 }\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 * 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 if (typeState.isActive) {\n encounteredKeys = { ...encounteredKeys, ...resolvedValues };\n }\n if (isInitialRender && visualElement.blockInitialAnimation) {\n shouldAnimateType = false;\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(...definitionList.map((animation) => {\n const options = { type };\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 (typeof animation === \"string\" &&\n isInitialRender &&\n !willAnimateViaParent &&\n visualElement.manuallyAnimateOnMount &&\n visualElement.parent) {\n const { parent } = visualElement;\n const parentVariant = resolveVariant(parent, animation);\n if (parent.enteringChildren && parentVariant) {\n const { delayChildren } = parentVariant.transition || {};\n options.delay = calcChildStagger(parent.enteringChildren, visualElement, delayChildren);\n }\n }\n return {\n animation: animation,\n options,\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 = {};\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(visualElement, Array.isArray(props.initial)\n ? props.initial[0]\n : props.initial);\n if (initialTransition && initialTransition.transition) {\n fallbackAnimation.transition = initialTransition.transition;\n }\n }\n removedKeys.forEach((key) => {\n const fallbackTarget = visualElement.getBaseTarget(key);\n const motionValue = visualElement.getValue(key);\n if (motionValue)\n motionValue.liveStyle = true;\n // @ts-expect-error - @mattgperry to figure if we should do something here\n fallbackAnimation[key] = fallbackTarget ?? null;\n });\n animations.push({ animation: fallbackAnimation });\n }\n let shouldAnimate = Boolean(animations.length);\n if (isInitialRender &&\n (props.initial === false || props.initial === props.animate) &&\n !visualElement.manuallyAnimateOnMount) {\n shouldAnimate = false;\n }\n isInitialRender = false;\n return shouldAnimate ? animate(animations) : Promise.resolve();\n }\n /**\n * Change whether a certain animation type is active.\n */\n function setActive(type, isActive) {\n // If the active state hasn't changed, we can safely do nothing here\n if (state[type].isActive === isActive)\n return Promise.resolve();\n // Propagate active change to children\n visualElement.variantChildren?.forEach((child) => child.animationState?.setActive(type, isActive));\n state[type].isActive = isActive;\n const animations = animateChanges(type);\n for (const key in state) {\n state[key].protectedKeys = {};\n }\n return animations;\n }\n return {\n animateChanges,\n setActive,\n setAnimateFunction,\n getState: () => state,\n reset: () => {\n state = createState();\n /**\n * Temporarily disabling resetting this flag as it prevents components\n * with initial={false} from animating after being remounted, for instance\n * as the child of an Activity component.\n */\n // isInitialRender = true\n },\n };\n}\nfunction checkVariantsDidChange(prev, next) {\n if (typeof next === \"string\") {\n return next !== prev;\n }\n else if (Array.isArray(next)) {\n return !shallowCompare(next, prev);\n }\n return false;\n}\nfunction createTypeState(isActive = false) {\n return {\n isActive,\n protectedKeys: {},\n needsAnimating: {},\n prevResolvedValues: {},\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\nexport { checkVariantsDidChange, createAnimationState };\n","class Feature {\n constructor(node) {\n this.isMounted = false;\n this.node = node;\n }\n update() { }\n}\n\nexport { Feature };\n","import { isAnimationControls } from '../../../animation/utils/is-animation-controls.mjs';\nimport { createAnimationState } from '../../../render/utils/animation-state.mjs';\nimport { Feature } from '../Feature.mjs';\n\nclass AnimationFeature extends Feature {\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) {\n super(node);\n node.animationState || (node.animationState = createAnimationState(node));\n }\n updateAnimationControlsSubscription() {\n const { animate } = this.node.getProps();\n if (isAnimationControls(animate)) {\n this.unmountControls = animate.subscribe(this.node);\n }\n }\n /**\n * Subscribe any provided AnimationControls to the component's VisualElement\n */\n mount() {\n this.updateAnimationControlsSubscription();\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 unmount() {\n this.node.animationState.reset();\n this.unmountControls?.();\n }\n}\n\nexport { AnimationFeature };\n","import { Feature } from '../Feature.mjs';\n\nlet id = 0;\nclass ExitAnimationFeature extends Feature {\n constructor() {\n super(...arguments);\n this.id = id++;\n }\n update() {\n if (!this.node.presenceContext)\n return;\n const { isPresent, onExitComplete } = this.node.presenceContext;\n const { isPresent: prevIsPresent } = this.node.prevPresenceContext || {};\n if (!this.node.animationState || isPresent === prevIsPresent) {\n return;\n }\n const exitAnimation = this.node.animationState.setActive(\"exit\", !isPresent);\n if (onExitComplete && !isPresent) {\n exitAnimation.then(() => {\n onExitComplete(this.id);\n });\n }\n }\n mount() {\n const { register, onExitComplete } = this.node.presenceContext || {};\n if (onExitComplete) {\n onExitComplete(this.id);\n }\n if (register) {\n this.unmount = register(this.id);\n }\n }\n unmount() { }\n}\n\nexport { ExitAnimationFeature };\n","import { AnimationFeature } from './animation/index.mjs';\nimport { ExitAnimationFeature } from './animation/exit.mjs';\n\nconst animations = {\n animation: {\n Feature: AnimationFeature,\n },\n exit: {\n Feature: ExitAnimationFeature,\n },\n};\n\nexport { animations };\n","function addDomEvent(target, eventName, handler, options = { passive: true }) {\n target.addEventListener(eventName, handler, options);\n return () => target.removeEventListener(eventName, handler);\n}\n\nexport { addDomEvent };\n","import { isPrimaryPointer } from 'motion-dom';\n\nfunction extractEventInfo(event) {\n return {\n point: {\n x: event.pageX,\n y: event.pageY,\n },\n };\n}\nconst addPointerInfo = (handler) => {\n return (event) => isPrimaryPointer(event) && handler(event, extractEventInfo(event));\n};\n\nexport { addPointerInfo, extractEventInfo };\n","import { addDomEvent } from './add-dom-event.mjs';\nimport { addPointerInfo } from './event-info.mjs';\n\nfunction addPointerEvent(target, eventName, handler, options) {\n return addDomEvent(target, eventName, addPointerInfo(handler), options);\n}\n\nexport { addPointerEvent };\n","import { mixNumber } from 'motion-dom';\n\nconst SCALE_PRECISION = 0.0001;\nconst SCALE_MIN = 1 - SCALE_PRECISION;\nconst SCALE_MAX = 1 + SCALE_PRECISION;\nconst TRANSLATE_PRECISION = 0.01;\nconst TRANSLATE_MIN = 0 - TRANSLATE_PRECISION;\nconst TRANSLATE_MAX = 0 + TRANSLATE_PRECISION;\nfunction calcLength(axis) {\n return axis.max - axis.min;\n}\nfunction isNear(value, target, maxDistance) {\n return Math.abs(value - target) <= maxDistance;\n}\nfunction calcAxisDelta(delta, source, target, origin = 0.5) {\n delta.origin = origin;\n delta.originPoint = mixNumber(source.min, source.max, delta.origin);\n delta.scale = calcLength(target) / calcLength(source);\n delta.translate =\n mixNumber(target.min, target.max, delta.origin) - delta.originPoint;\n if ((delta.scale >= SCALE_MIN && delta.scale <= SCALE_MAX) ||\n isNaN(delta.scale)) {\n delta.scale = 1.0;\n }\n if ((delta.translate >= TRANSLATE_MIN &&\n delta.translate <= TRANSLATE_MAX) ||\n isNaN(delta.translate)) {\n delta.translate = 0.0;\n }\n}\nfunction calcBoxDelta(delta, source, target, origin) {\n calcAxisDelta(delta.x, source.x, target.x, origin ? origin.originX : undefined);\n calcAxisDelta(delta.y, source.y, target.y, origin ? origin.originY : undefined);\n}\nfunction calcRelativeAxis(target, relative, parent) {\n target.min = parent.min + relative.min;\n target.max = target.min + calcLength(relative);\n}\nfunction calcRelativeBox(target, relative, parent) {\n calcRelativeAxis(target.x, relative.x, parent.x);\n calcRelativeAxis(target.y, relative.y, parent.y);\n}\nfunction calcRelativeAxisPosition(target, layout, parent) {\n target.min = layout.min - parent.min;\n target.max = target.min + calcLength(layout);\n}\nfunction calcRelativePosition(target, layout, parent) {\n calcRelativeAxisPosition(target.x, layout.x, parent.x);\n calcRelativeAxisPosition(target.y, layout.y, parent.y);\n}\n\nexport { calcAxisDelta, calcBoxDelta, calcLength, calcRelativeAxis, calcRelativeAxisPosition, calcRelativeBox, calcRelativePosition, isNear };\n","function eachAxis(callback) {\n return [callback(\"x\"), callback(\"y\")];\n}\n\nexport { eachAxis };\n","// Fixes https://github.com/motiondivision/motion/issues/2270\nconst getContextWindow = ({ current }) => {\n return current ? current.ownerDocument.defaultView : null;\n};\n\nexport { getContextWindow };\n","const distance = (a, b) => Math.abs(a - b);\nfunction distance2D(a, b) {\n // Multi-dimensional\n const xDelta = distance(a.x, b.x);\n const yDelta = distance(a.y, b.y);\n return Math.sqrt(xDelta ** 2 + yDelta ** 2);\n}\n\nexport { distance, distance2D };\n","import { frame, isPrimaryPointer, cancelFrame, frameData } from 'motion-dom';\nimport { pipe, secondsToMilliseconds, millisecondsToSeconds } from 'motion-utils';\nimport { addPointerEvent } from '../../events/add-pointer-event.mjs';\nimport { extractEventInfo } from '../../events/event-info.mjs';\nimport { distance2D } from '../../utils/distance.mjs';\n\n/**\n * @internal\n */\nclass PanSession {\n constructor(event, handlers, { transformPagePoint, contextWindow = window, dragSnapToOrigin = false, distanceThreshold = 3, } = {}) {\n /**\n * @internal\n */\n this.startEvent = null;\n /**\n * @internal\n */\n this.lastMoveEvent = null;\n /**\n * @internal\n */\n this.lastMoveEventInfo = null;\n /**\n * @internal\n */\n this.handlers = {};\n /**\n * @internal\n */\n this.contextWindow = window;\n this.updatePoint = () => {\n if (!(this.lastMoveEvent && this.lastMoveEventInfo))\n return;\n const info = getPanInfo(this.lastMoveEventInfo, this.history);\n const isPanStarted = this.startEvent !== null;\n // Only start panning if the offset is larger than 3 pixels. If we make it\n // any larger than this we'll want to reset the pointer history\n // on the first update to avoid visual snapping to the cursor.\n const isDistancePastThreshold = distance2D(info.offset, { x: 0, y: 0 }) >= this.distanceThreshold;\n if (!isPanStarted && !isDistancePastThreshold)\n return;\n const { point } = info;\n const { timestamp } = frameData;\n this.history.push({ ...point, timestamp });\n const { onStart, onMove } = this.handlers;\n if (!isPanStarted) {\n onStart && onStart(this.lastMoveEvent, info);\n this.startEvent = this.lastMoveEvent;\n }\n onMove && onMove(this.lastMoveEvent, info);\n };\n this.handlePointerMove = (event, info) => {\n this.lastMoveEvent = event;\n this.lastMoveEventInfo = transformPoint(info, this.transformPagePoint);\n // Throttle mouse move event to once per frame\n frame.update(this.updatePoint, true);\n };\n this.handlePointerUp = (event, info) => {\n this.end();\n const { onEnd, onSessionEnd, resumeAnimation } = this.handlers;\n if (this.dragSnapToOrigin)\n resumeAnimation && resumeAnimation();\n if (!(this.lastMoveEvent && this.lastMoveEventInfo))\n return;\n const panInfo = getPanInfo(event.type === \"pointercancel\"\n ? this.lastMoveEventInfo\n : transformPoint(info, this.transformPagePoint), this.history);\n if (this.startEvent && onEnd) {\n onEnd(event, panInfo);\n }\n onSessionEnd && onSessionEnd(event, panInfo);\n };\n // If we have more than one touch, don't start detecting this gesture\n if (!isPrimaryPointer(event))\n return;\n this.dragSnapToOrigin = dragSnapToOrigin;\n this.handlers = handlers;\n this.transformPagePoint = transformPagePoint;\n this.distanceThreshold = distanceThreshold;\n this.contextWindow = contextWindow || window;\n const info = extractEventInfo(event);\n const initialInfo = transformPoint(info, this.transformPagePoint);\n const { point } = initialInfo;\n const { timestamp } = frameData;\n this.history = [{ ...point, timestamp }];\n const { onSessionStart } = handlers;\n onSessionStart &&\n onSessionStart(event, getPanInfo(initialInfo, this.history));\n this.removeListeners = pipe(addPointerEvent(this.contextWindow, \"pointermove\", this.handlePointerMove), addPointerEvent(this.contextWindow, \"pointerup\", this.handlePointerUp), addPointerEvent(this.contextWindow, \"pointercancel\", this.handlePointerUp));\n }\n updateHandlers(handlers) {\n this.handlers = handlers;\n }\n end() {\n this.removeListeners && this.removeListeners();\n cancelFrame(this.updatePoint);\n }\n}\nfunction transformPoint(info, transformPagePoint) {\n return transformPagePoint ? { point: transformPagePoint(info.point) } : info;\n}\nfunction subtractPoint(a, b) {\n return { x: a.x - b.x, y: a.y - b.y };\n}\nfunction getPanInfo({ point }, history) {\n return {\n point,\n delta: subtractPoint(point, lastDevicePoint(history)),\n offset: subtractPoint(point, startDevicePoint(history)),\n velocity: getVelocity(history, 0.1),\n };\n}\nfunction startDevicePoint(history) {\n return history[0];\n}\nfunction lastDevicePoint(history) {\n return history[history.length - 1];\n}\nfunction getVelocity(history, timeDelta) {\n if (history.length < 2) {\n return { x: 0, y: 0 };\n }\n let i = history.length - 1;\n let timestampedPoint = null;\n const lastPoint = lastDevicePoint(history);\n while (i >= 0) {\n timestampedPoint = history[i];\n if (lastPoint.timestamp - timestampedPoint.timestamp >\n secondsToMilliseconds(timeDelta)) {\n break;\n }\n i--;\n }\n if (!timestampedPoint) {\n return { x: 0, y: 0 };\n }\n const time = millisecondsToSeconds(lastPoint.timestamp - timestampedPoint.timestamp);\n if (time === 0) {\n return { x: 0, y: 0 };\n }\n const currentVelocity = {\n x: (lastPoint.x - timestampedPoint.x) / time,\n y: (lastPoint.y - timestampedPoint.y) / time,\n };\n if (currentVelocity.x === Infinity) {\n currentVelocity.x = 0;\n }\n if (currentVelocity.y === Infinity) {\n currentVelocity.y = 0;\n }\n return currentVelocity;\n}\n\nexport { PanSession };\n","import { mixNumber } from 'motion-dom';\nimport { progress, clamp } from 'motion-utils';\nimport { calcLength } from '../../../projection/geometry/delta-calc.mjs';\n\n/**\n * Apply constraints to a point. These constraints are both physical along an\n * axis, and an elastic factor that determines how much to constrain the point\n * by if it does lie outside the defined parameters.\n */\nfunction applyConstraints(point, { min, max }, elastic) {\n if (min !== undefined && point < min) {\n // If we have a min point defined, and this is outside of that, constrain\n point = elastic\n ? mixNumber(min, point, elastic.min)\n : Math.max(point, min);\n }\n else if (max !== undefined && point > max) {\n // If we have a max point defined, and this is outside of that, constrain\n point = elastic\n ? mixNumber(max, point, elastic.max)\n : Math.min(point, max);\n }\n return point;\n}\n/**\n * Calculate constraints in terms of the viewport when defined relatively to the\n * measured axis. This is measured from the nearest edge, so a max constraint of 200\n * on an axis with a max value of 300 would return a constraint of 500 - axis length\n */\nfunction calcRelativeAxisConstraints(axis, min, max) {\n return {\n min: min !== undefined ? axis.min + min : undefined,\n max: max !== undefined\n ? axis.max + max - (axis.max - axis.min)\n : undefined,\n };\n}\n/**\n * Calculate constraints in terms of the viewport when\n * defined relatively to the measured bounding box.\n */\nfunction calcRelativeConstraints(layoutBox, { top, left, bottom, right }) {\n return {\n x: calcRelativeAxisConstraints(layoutBox.x, left, right),\n y: calcRelativeAxisConstraints(layoutBox.y, top, bottom),\n };\n}\n/**\n * Calculate viewport constraints when defined as another viewport-relative axis\n */\nfunction calcViewportAxisConstraints(layoutAxis, constraintsAxis) {\n let min = constraintsAxis.min - layoutAxis.min;\n let max = constraintsAxis.max - layoutAxis.max;\n // If the constraints axis is actually smaller than the layout axis then we can\n // flip the constraints\n if (constraintsAxis.max - constraintsAxis.min <\n layoutAxis.max - layoutAxis.min) {\n [min, max] = [max, min];\n }\n return { min, max };\n}\n/**\n * Calculate viewport constraints when defined as another viewport-relative box\n */\nfunction calcViewportConstraints(layoutBox, constraintsBox) {\n return {\n x: calcViewportAxisConstraints(layoutBox.x, constraintsBox.x),\n y: calcViewportAxisConstraints(layoutBox.y, constraintsBox.y),\n };\n}\n/**\n * Calculate a transform origin relative to the source axis, between 0-1, that results\n * in an asthetically pleasing scale/transform needed to project from source to target.\n */\nfunction calcOrigin(source, target) {\n let origin = 0.5;\n const sourceLength = calcLength(source);\n const targetLength = calcLength(target);\n if (targetLength > sourceLength) {\n origin = progress(target.min, target.max - sourceLength, source.min);\n }\n else if (sourceLength > targetLength) {\n origin = progress(source.min, source.max - targetLength, target.min);\n }\n return clamp(0, 1, origin);\n}\n/**\n * Rebase the calculated viewport constraints relative to the layout.min point.\n */\nfunction rebaseAxisConstraints(layout, constraints) {\n const relativeConstraints = {};\n if (constraints.min !== undefined) {\n relativeConstraints.min = constraints.min - layout.min;\n }\n if (constraints.max !== undefined) {\n relativeConstraints.max = constraints.max - layout.min;\n }\n return relativeConstraints;\n}\nconst defaultElastic = 0.35;\n/**\n * Accepts a dragElastic prop and returns resolved elastic values for each axis.\n */\nfunction resolveDragElastic(dragElastic = defaultElastic) {\n if (dragElastic === false) {\n dragElastic = 0;\n }\n else if (dragElastic === true) {\n dragElastic = defaultElastic;\n }\n return {\n x: resolveAxisElastic(dragElastic, \"left\", \"right\"),\n y: resolveAxisElastic(dragElastic, \"top\", \"bottom\"),\n };\n}\nfunction resolveAxisElastic(dragElastic, minLabel, maxLabel) {\n return {\n min: resolvePointElastic(dragElastic, minLabel),\n max: resolvePointElastic(dragElastic, maxLabel),\n };\n}\nfunction resolvePointElastic(dragElastic, label) {\n return typeof dragElastic === \"number\"\n ? dragElastic\n : dragElastic[label] || 0;\n}\n\nexport { applyConstraints, calcOrigin, calcRelativeAxisConstraints, calcRelativeConstraints, calcViewportAxisConstraints, calcViewportConstraints, defaultElastic, rebaseAxisConstraints, resolveAxisElastic, resolveDragElastic, resolvePointElastic };\n","import { frame, mixNumber, setDragLock, percent } from 'motion-dom';\nimport { invariant } from 'motion-utils';\nimport { animateMotionValue } from '../../animation/interfaces/motion-value.mjs';\nimport { addDomEvent } from '../../events/add-dom-event.mjs';\nimport { addPointerEvent } from '../../events/add-pointer-event.mjs';\nimport { extractEventInfo } from '../../events/event-info.mjs';\nimport { convertBoxToBoundingBox, convertBoundingBoxToBox } from '../../projection/geometry/conversion.mjs';\nimport { calcLength } from '../../projection/geometry/delta-calc.mjs';\nimport { createBox } from '../../projection/geometry/models.mjs';\nimport { eachAxis } from '../../projection/utils/each-axis.mjs';\nimport { measurePageBox } from '../../projection/utils/measure.mjs';\nimport { getContextWindow } from '../../utils/get-context-window.mjs';\nimport { isRefObject } from '../../utils/is-ref-object.mjs';\nimport { addValueToWillChange } from '../../value/use-will-change/add-will-change.mjs';\nimport { PanSession } from '../pan/PanSession.mjs';\nimport { applyConstraints, calcRelativeConstraints, resolveDragElastic, rebaseAxisConstraints, calcViewportConstraints, calcOrigin, defaultElastic } from './utils/constraints.mjs';\n\nconst elementDragControls = new WeakMap();\nclass VisualElementDragControls {\n constructor(visualElement) {\n this.openDragLock = null;\n this.isDragging = false;\n this.currentDirection = null;\n this.originPoint = { x: 0, y: 0 };\n /**\n * The permitted boundaries of travel, in pixels.\n */\n this.constraints = false;\n this.hasMutatedConstraints = false;\n /**\n * The per-axis resolved elastic values.\n */\n this.elastic = createBox();\n /**\n * The latest pointer event. Used as fallback when the `cancel` and `stop` functions are called without arguments.\n */\n this.latestPointerEvent = null;\n /**\n * The latest pan info. Used as fallback when the `cancel` and `stop` functions are called without arguments.\n */\n this.latestPanInfo = null;\n this.visualElement = visualElement;\n }\n start(originEvent, { snapToCursor = false, distanceThreshold } = {}) {\n /**\n * Don't start dragging if this component is exiting\n */\n const { presenceContext } = this.visualElement;\n if (presenceContext && presenceContext.isPresent === false)\n return;\n const onSessionStart = (event) => {\n const { dragSnapToOrigin } = this.getProps();\n // Stop or pause any animations on both axis values immediately. This allows the user to throw and catch\n // the component.\n dragSnapToOrigin ? this.pauseAnimation() : this.stopAnimation();\n if (snapToCursor) {\n this.snapToCursor(extractEventInfo(event).point);\n }\n };\n const onStart = (event, info) => {\n // Attempt to grab the global drag gesture lock - maybe make this part of PanSession\n const { drag, dragPropagation, onDragStart } = this.getProps();\n if (drag && !dragPropagation) {\n if (this.openDragLock)\n this.openDragLock();\n this.openDragLock = setDragLock(drag);\n // If we don 't have the lock, don't start dragging\n if (!this.openDragLock)\n return;\n }\n this.latestPointerEvent = event;\n this.latestPanInfo = info;\n this.isDragging = true;\n this.currentDirection = null;\n this.resolveConstraints();\n if (this.visualElement.projection) {\n this.visualElement.projection.isAnimationBlocked = true;\n this.visualElement.projection.target = undefined;\n }\n /**\n * Record gesture origin\n */\n eachAxis((axis) => {\n let current = this.getAxisMotionValue(axis).get() || 0;\n /**\n * If the MotionValue is a percentage value convert to px\n */\n if (percent.test(current)) {\n const { projection } = this.visualElement;\n if (projection && projection.layout) {\n const measuredAxis = projection.layout.layoutBox[axis];\n if (measuredAxis) {\n const length = calcLength(measuredAxis);\n current = length * (parseFloat(current) / 100);\n }\n }\n }\n this.originPoint[axis] = current;\n });\n // Fire onDragStart event\n if (onDragStart) {\n frame.postRender(() => onDragStart(event, info));\n }\n addValueToWillChange(this.visualElement, \"transform\");\n const { animationState } = this.visualElement;\n animationState && animationState.setActive(\"whileDrag\", true);\n };\n const onMove = (event, info) => {\n this.latestPointerEvent = event;\n this.latestPanInfo = info;\n const { dragPropagation, dragDirectionLock, onDirectionLock, onDrag, } = this.getProps();\n // If we didn't successfully receive the gesture lock, early return.\n if (!dragPropagation && !this.openDragLock)\n return;\n const { offset } = info;\n // Attempt to detect drag direction if directionLock is true\n if (dragDirectionLock && this.currentDirection === null) {\n this.currentDirection = getCurrentDirection(offset);\n // If we've successfully set a direction, notify listener\n if (this.currentDirection !== null) {\n onDirectionLock && onDirectionLock(this.currentDirection);\n }\n return;\n }\n // Update each point with the latest position\n this.updateAxis(\"x\", info.point, offset);\n this.updateAxis(\"y\", info.point, offset);\n /**\n * Ideally we would leave the renderer to fire naturally at the end of\n * this frame but if the element is about to change layout as the result\n * of a re-render we want to ensure the browser can read the latest\n * bounding box to ensure the pointer and element don't fall out of sync.\n */\n this.visualElement.render();\n /**\n * This must fire after the render call as it might trigger a state\n * change which itself might trigger a layout update.\n */\n onDrag && onDrag(event, info);\n };\n const onSessionEnd = (event, info) => {\n this.latestPointerEvent = event;\n this.latestPanInfo = info;\n this.stop(event, info);\n this.latestPointerEvent = null;\n this.latestPanInfo = null;\n };\n const resumeAnimation = () => eachAxis((axis) => this.getAnimationState(axis) === \"paused\" &&\n this.getAxisMotionValue(axis).animation?.play());\n const { dragSnapToOrigin } = this.getProps();\n this.panSession = new PanSession(originEvent, {\n onSessionStart,\n onStart,\n onMove,\n onSessionEnd,\n resumeAnimation,\n }, {\n transformPagePoint: this.visualElement.getTransformPagePoint(),\n dragSnapToOrigin,\n distanceThreshold,\n contextWindow: getContextWindow(this.visualElement),\n });\n }\n /**\n * @internal\n */\n stop(event, panInfo) {\n const finalEvent = event || this.latestPointerEvent;\n const finalPanInfo = panInfo || this.latestPanInfo;\n const isDragging = this.isDragging;\n this.cancel();\n if (!isDragging || !finalPanInfo || !finalEvent)\n return;\n const { velocity } = finalPanInfo;\n this.startAnimation(velocity);\n const { onDragEnd } = this.getProps();\n if (onDragEnd) {\n frame.postRender(() => onDragEnd(finalEvent, finalPanInfo));\n }\n }\n /**\n * @internal\n */\n cancel() {\n this.isDragging = false;\n const { projection, animationState } = this.visualElement;\n if (projection) {\n projection.isAnimationBlocked = false;\n }\n this.panSession && this.panSession.end();\n this.panSession = undefined;\n const { dragPropagation } = this.getProps();\n if (!dragPropagation && this.openDragLock) {\n this.openDragLock();\n this.openDragLock = null;\n }\n animationState && animationState.setActive(\"whileDrag\", false);\n }\n updateAxis(axis, _point, offset) {\n const { drag } = this.getProps();\n // If we're not dragging this axis, do an early return.\n if (!offset || !shouldDrag(axis, drag, this.currentDirection))\n return;\n const axisValue = this.getAxisMotionValue(axis);\n let next = this.originPoint[axis] + offset[axis];\n // Apply constraints\n if (this.constraints && this.constraints[axis]) {\n next = applyConstraints(next, this.constraints[axis], this.elastic[axis]);\n }\n axisValue.set(next);\n }\n resolveConstraints() {\n const { dragConstraints, dragElastic } = this.getProps();\n const layout = this.visualElement.projection &&\n !this.visualElement.projection.layout\n ? this.visualElement.projection.measure(false)\n : this.visualElement.projection?.layout;\n const prevConstraints = this.constraints;\n if (dragConstraints && isRefObject(dragConstraints)) {\n if (!this.constraints) {\n this.constraints = this.resolveRefConstraints();\n }\n }\n else {\n if (dragConstraints && layout) {\n this.constraints = calcRelativeConstraints(layout.layoutBox, dragConstraints);\n }\n else {\n this.constraints = false;\n }\n }\n this.elastic = resolveDragElastic(dragElastic);\n /**\n * If we're outputting to external MotionValues, we want to rebase the measured constraints\n * from viewport-relative to component-relative.\n */\n if (prevConstraints !== this.constraints &&\n layout &&\n this.constraints &&\n !this.hasMutatedConstraints) {\n eachAxis((axis) => {\n if (this.constraints !== false &&\n this.getAxisMotionValue(axis)) {\n this.constraints[axis] = rebaseAxisConstraints(layout.layoutBox[axis], this.constraints[axis]);\n }\n });\n }\n }\n resolveRefConstraints() {\n const { dragConstraints: constraints, onMeasureDragConstraints } = this.getProps();\n if (!constraints || !isRefObject(constraints))\n return false;\n const constraintsElement = constraints.current;\n invariant(constraintsElement !== null, \"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.\", \"drag-constraints-ref\");\n const { projection } = this.visualElement;\n // TODO\n if (!projection || !projection.layout)\n return false;\n const constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint());\n let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, constraintsBox);\n /**\n * If there's an onMeasureDragConstraints listener we call it and\n * if different constraints are returned, set constraints to that\n */\n if (onMeasureDragConstraints) {\n const userConstraints = onMeasureDragConstraints(convertBoxToBoundingBox(measuredConstraints));\n this.hasMutatedConstraints = !!userConstraints;\n if (userConstraints) {\n measuredConstraints = convertBoundingBoxToBox(userConstraints);\n }\n }\n return measuredConstraints;\n }\n startAnimation(velocity) {\n const { drag, dragMomentum, dragElastic, dragTransition, dragSnapToOrigin, onDragTransitionEnd, } = this.getProps();\n const constraints = this.constraints || {};\n const momentumAnimations = eachAxis((axis) => {\n if (!shouldDrag(axis, drag, this.currentDirection)) {\n return;\n }\n let transition = (constraints && constraints[axis]) || {};\n if (dragSnapToOrigin)\n transition = { min: 0, max: 0 };\n /**\n * Overdamp the boundary spring if `dragElastic` is disabled. There's still a frame\n * of spring animations so we should look into adding a disable spring option to `inertia`.\n * We could do something here where we affect the `bounceStiffness` and `bounceDamping`\n * using the value of `dragElastic`.\n */\n const bounceStiffness = dragElastic ? 200 : 1000000;\n const bounceDamping = dragElastic ? 40 : 10000000;\n const inertia = {\n type: \"inertia\",\n velocity: dragMomentum ? velocity[axis] : 0,\n bounceStiffness,\n bounceDamping,\n timeConstant: 750,\n restDelta: 1,\n restSpeed: 10,\n ...dragTransition,\n ...transition,\n };\n // If we're not animating on an externally-provided `MotionValue` we can use the\n // component's animation controls which will handle interactions with whileHover (etc),\n // otherwise we just have to animate the `MotionValue` itself.\n return this.startAxisValueAnimation(axis, inertia);\n });\n // Run all animations and then resolve the new drag constraints.\n return Promise.all(momentumAnimations).then(onDragTransitionEnd);\n }\n startAxisValueAnimation(axis, transition) {\n const axisValue = this.getAxisMotionValue(axis);\n addValueToWillChange(this.visualElement, axis);\n return axisValue.start(animateMotionValue(axis, axisValue, 0, transition, this.visualElement, false));\n }\n stopAnimation() {\n eachAxis((axis) => this.getAxisMotionValue(axis).stop());\n }\n pauseAnimation() {\n eachAxis((axis) => this.getAxisMotionValue(axis).animation?.pause());\n }\n getAnimationState(axis) {\n return this.getAxisMotionValue(axis).animation?.state;\n }\n /**\n * Drag works differently depending on which props are provided.\n *\n * - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values.\n * - Otherwise, we apply the delta to the x/y motion values.\n */\n getAxisMotionValue(axis) {\n const dragKey = `_drag${axis.toUpperCase()}`;\n const props = this.visualElement.getProps();\n const externalMotionValue = props[dragKey];\n return externalMotionValue\n ? externalMotionValue\n : this.visualElement.getValue(axis, (props.initial\n ? props.initial[axis]\n : undefined) || 0);\n }\n snapToCursor(point) {\n eachAxis((axis) => {\n const { drag } = this.getProps();\n // If we're not dragging this axis, do an early return.\n if (!shouldDrag(axis, drag, this.currentDirection))\n return;\n const { projection } = this.visualElement;\n const axisValue = this.getAxisMotionValue(axis);\n if (projection && projection.layout) {\n const { min, max } = projection.layout.layoutBox[axis];\n axisValue.set(point[axis] - mixNumber(min, max, 0.5));\n }\n });\n }\n /**\n * When the viewport resizes we want to check if the measured constraints\n * have changed and, if so, reposition the element within those new constraints\n * relative to where it was before the resize.\n */\n scalePositionWithinConstraints() {\n if (!this.visualElement.current)\n return;\n const { drag, dragConstraints } = this.getProps();\n const { projection } = this.visualElement;\n if (!isRefObject(dragConstraints) || !projection || !this.constraints)\n return;\n /**\n * Stop current animations as there can be visual glitching if we try to do\n * this mid-animation\n */\n this.stopAnimation();\n /**\n * Record the relative position of the dragged element relative to the\n * constraints box and save as a progress value.\n */\n const boxProgress = { x: 0, y: 0 };\n eachAxis((axis) => {\n const axisValue = this.getAxisMotionValue(axis);\n if (axisValue && this.constraints !== false) {\n const latest = axisValue.get();\n boxProgress[axis] = calcOrigin({ min: latest, max: latest }, this.constraints[axis]);\n }\n });\n /**\n * Update the layout of this element and resolve the latest drag constraints\n */\n const { transformTemplate } = this.visualElement.getProps();\n this.visualElement.current.style.transform = transformTemplate\n ? transformTemplate({}, \"\")\n : \"none\";\n projection.root && projection.root.updateScroll();\n projection.updateLayout();\n this.resolveConstraints();\n /**\n * For each axis, calculate the current progress of the layout axis\n * within the new constraints.\n */\n eachAxis((axis) => {\n if (!shouldDrag(axis, drag, null))\n return;\n /**\n * Calculate a new transform based on the previous box progress\n */\n const axisValue = this.getAxisMotionValue(axis);\n const { min, max } = this.constraints[axis];\n axisValue.set(mixNumber(min, max, boxProgress[axis]));\n });\n }\n addListeners() {\n if (!this.visualElement.current)\n return;\n elementDragControls.set(this.visualElement, this);\n const element = this.visualElement.current;\n /**\n * Attach a pointerdown event listener on this DOM element to initiate drag tracking.\n */\n const stopPointerListener = addPointerEvent(element, \"pointerdown\", (event) => {\n const { drag, dragListener = true } = this.getProps();\n drag && dragListener && this.start(event);\n });\n const measureDragConstraints = () => {\n const { dragConstraints } = this.getProps();\n if (isRefObject(dragConstraints) && dragConstraints.current) {\n this.constraints = this.resolveRefConstraints();\n }\n };\n const { projection } = this.visualElement;\n const stopMeasureLayoutListener = projection.addEventListener(\"measure\", measureDragConstraints);\n if (projection && !projection.layout) {\n projection.root && projection.root.updateScroll();\n projection.updateLayout();\n }\n frame.read(measureDragConstraints);\n /**\n * Attach a window resize listener to scale the draggable target within its defined\n * constraints as the window resizes.\n */\n const stopResizeListener = addDomEvent(window, \"resize\", () => this.scalePositionWithinConstraints());\n /**\n * If the element's layout changes, calculate the delta and apply that to\n * the drag gesture's origin point.\n */\n const stopLayoutUpdateListener = projection.addEventListener(\"didUpdate\", (({ delta, hasLayoutChanged }) => {\n if (this.isDragging && hasLayoutChanged) {\n eachAxis((axis) => {\n const motionValue = this.getAxisMotionValue(axis);\n if (!motionValue)\n return;\n this.originPoint[axis] += delta[axis].translate;\n motionValue.set(motionValue.get() + delta[axis].translate);\n });\n this.visualElement.render();\n }\n }));\n return () => {\n stopResizeListener();\n stopPointerListener();\n stopMeasureLayoutListener();\n stopLayoutUpdateListener && stopLayoutUpdateListener();\n };\n }\n getProps() {\n const props = this.visualElement.getProps();\n const { drag = false, dragDirectionLock = false, dragPropagation = false, dragConstraints = false, dragElastic = defaultElastic, dragMomentum = true, } = props;\n return {\n ...props,\n drag,\n dragDirectionLock,\n dragPropagation,\n dragConstraints,\n dragElastic,\n dragMomentum,\n };\n }\n}\nfunction shouldDrag(direction, drag, currentDirection) {\n return ((drag === true || drag === direction) &&\n (currentDirection === null || currentDirection === direction));\n}\n/**\n * Based on an x/y offset determine the current drag direction. If both axis' offsets are lower\n * than the provided threshold, return `null`.\n *\n * @param offset - The x/y offset from origin.\n * @param lockThreshold - (Optional) - the minimum absolute offset before we can determine a drag direction.\n */\nfunction getCurrentDirection(offset, lockThreshold = 10) {\n let direction = null;\n if (Math.abs(offset.y) > lockThreshold) {\n direction = \"y\";\n }\n else if (Math.abs(offset.x) > lockThreshold) {\n direction = \"x\";\n }\n return direction;\n}\n\nexport { VisualElementDragControls, elementDragControls };\n","import { Feature } from '../../motion/features/Feature.mjs';\nimport { noop } from 'motion-utils';\nimport { VisualElementDragControls } from './VisualElementDragControls.mjs';\n\nclass DragGesture extends Feature {\n constructor(node) {\n super(node);\n this.removeGroupControls = noop;\n this.removeListeners = noop;\n this.controls = new VisualElementDragControls(node);\n }\n mount() {\n // If we've been provided a DragControls for manual control over the drag gesture,\n // subscribe this component to it on mount.\n const { dragControls } = this.node.getProps();\n if (dragControls) {\n this.removeGroupControls = dragControls.subscribe(this.controls);\n }\n this.removeListeners = this.controls.addListeners() || noop;\n }\n unmount() {\n this.removeGroupControls();\n this.removeListeners();\n }\n}\n\nexport { DragGesture };\n","import { frame } from 'motion-dom';\nimport { noop } from 'motion-utils';\nimport { addPointerEvent } from '../../events/add-pointer-event.mjs';\nimport { Feature } from '../../motion/features/Feature.mjs';\nimport { getContextWindow } from '../../utils/get-context-window.mjs';\nimport { PanSession } from './PanSession.mjs';\n\nconst asyncHandler = (handler) => (event, info) => {\n if (handler) {\n frame.postRender(() => handler(event, info));\n }\n};\nclass PanGesture extends Feature {\n constructor() {\n super(...arguments);\n this.removePointerDownListener = noop;\n }\n onPointerDown(pointerDownEvent) {\n this.session = new PanSession(pointerDownEvent, this.createPanHandlers(), {\n transformPagePoint: this.node.getTransformPagePoint(),\n contextWindow: getContextWindow(this.node),\n });\n }\n createPanHandlers() {\n const { onPanSessionStart, onPanStart, onPan, onPanEnd } = this.node.getProps();\n return {\n onSessionStart: asyncHandler(onPanSessionStart),\n onStart: asyncHandler(onPanStart),\n onMove: onPan,\n onEnd: (event, info) => {\n delete this.session;\n if (onPanEnd) {\n frame.postRender(() => onPanEnd(event, info));\n }\n },\n };\n }\n mount() {\n this.removePointerDownListener = addPointerEvent(this.node.current, \"pointerdown\", (event) => this.onPointerDown(event));\n }\n update() {\n this.session && this.session.updateHandlers(this.createPanHandlers());\n }\n unmount() {\n this.removePointerDownListener();\n this.session && this.session.end();\n }\n}\n\nexport { PanGesture };\n","\"use client\";\nimport { jsx } from 'react/jsx-runtime';\nimport { frame, microtask } from 'motion-dom';\nimport { useContext, Component } from 'react';\nimport { usePresence } from '../../../components/AnimatePresence/use-presence.mjs';\nimport { LayoutGroupContext } from '../../../context/LayoutGroupContext.mjs';\nimport { SwitchLayoutGroupContext } from '../../../context/SwitchLayoutGroupContext.mjs';\nimport { globalProjectionState } from '../../../projection/node/state.mjs';\n\n/**\n * Track whether we've taken any snapshots yet. If not,\n * we can safely skip notification of didUpdate.\n *\n * Difficult to capture in a test but to prevent flickering\n * we must set this to true either on update or unmount.\n * Running `next-env/layout-id` in Safari will show this behaviour if broken.\n */\nlet hasTakenAnySnapshot = false;\nclass MeasureLayoutWithContext extends Component {\n /**\n * This only mounts projection nodes for components that\n * need measuring, we might want to do it for all components\n * in order to incorporate transforms\n */\n componentDidMount() {\n const { visualElement, layoutGroup, switchLayoutGroup, layoutId } = this.props;\n const { projection } = visualElement;\n if (projection) {\n if (layoutGroup.group)\n layoutGroup.group.add(projection);\n if (switchLayoutGroup && switchLayoutGroup.register && layoutId) {\n switchLayoutGroup.register(projection);\n }\n if (hasTakenAnySnapshot) {\n projection.root.didUpdate();\n }\n projection.addEventListener(\"animationComplete\", () => {\n this.safeToRemove();\n });\n projection.setOptions({\n ...projection.options,\n onExitComplete: () => this.safeToRemove(),\n });\n }\n globalProjectionState.hasEverUpdated = true;\n }\n getSnapshotBeforeUpdate(prevProps) {\n const { layoutDependency, visualElement, drag, isPresent } = this.props;\n const { projection } = visualElement;\n if (!projection)\n return null;\n /**\n * TODO: We use this data in relegate to determine whether to\n * promote a previous element. There's no guarantee its presence data\n * will have updated by this point - if a bug like this arises it will\n * have to be that we markForRelegation and then find a new lead some other way,\n * perhaps in didUpdate\n */\n projection.isPresent = isPresent;\n hasTakenAnySnapshot = true;\n if (drag ||\n prevProps.layoutDependency !== layoutDependency ||\n layoutDependency === undefined ||\n prevProps.isPresent !== isPresent) {\n projection.willUpdate();\n }\n else {\n this.safeToRemove();\n }\n if (prevProps.isPresent !== isPresent) {\n if (isPresent) {\n projection.promote();\n }\n else if (!projection.relegate()) {\n /**\n * If there's another stack member taking over from this one,\n * it's in charge of the exit animation and therefore should\n * be in charge of the safe to remove. Otherwise we call it here.\n */\n frame.postRender(() => {\n const stack = projection.getStack();\n if (!stack || !stack.members.length) {\n this.safeToRemove();\n }\n });\n }\n }\n return null;\n }\n componentDidUpdate() {\n const { projection } = this.props.visualElement;\n if (projection) {\n projection.root.didUpdate();\n microtask.postRender(() => {\n if (!projection.currentAnimation && projection.isLead()) {\n this.safeToRemove();\n }\n });\n }\n }\n componentWillUnmount() {\n const { visualElement, layoutGroup, switchLayoutGroup: promoteContext, } = this.props;\n const { projection } = visualElement;\n hasTakenAnySnapshot = true;\n if (projection) {\n projection.scheduleCheckAfterUnmount();\n if (layoutGroup && layoutGroup.group)\n layoutGroup.group.remove(projection);\n if (promoteContext && promoteContext.deregister)\n promoteContext.deregister(projection);\n }\n }\n safeToRemove() {\n const { safeToRemove } = this.props;\n safeToRemove && safeToRemove();\n }\n render() {\n return null;\n }\n}\nfunction MeasureLayout(props) {\n const [isPresent, safeToRemove] = usePresence();\n const layoutGroup = useContext(LayoutGroupContext);\n return (jsx(MeasureLayoutWithContext, { ...props, layoutGroup: layoutGroup, switchLayoutGroup: useContext(SwitchLayoutGroupContext), isPresent: isPresent, safeToRemove: safeToRemove }));\n}\n\nexport { MeasureLayout };\n","/**\n * This should only ever be modified on the client otherwise it'll\n * persist through server requests. If we need instanced states we\n * could lazy-init via root.\n */\nconst globalProjectionState = {\n /**\n * Global flag as to whether the tree has animated since the last time\n * we resized the window\n */\n hasAnimatedSinceResize: true,\n /**\n * We set this to true once, on the first update. Any nodes added to the tree beyond that\n * update will be given a `data-projection-id` attribute.\n */\n hasEverUpdated: false,\n};\n\nexport { globalProjectionState };\n","import { isMotionValue, motionValue } from 'motion-dom';\nimport { animateMotionValue } from '../interfaces/motion-value.mjs';\n\nfunction animateSingleValue(value, keyframes, options) {\n const motionValue$1 = isMotionValue(value) ? value : motionValue(value);\n motionValue$1.start(animateMotionValue(\"\", motionValue$1, keyframes, options));\n return motionValue$1.animation;\n}\n\nexport { animateSingleValue };\n","const compareByDepth = (a, b) => a.depth - b.depth;\n\nexport { compareByDepth };\n","import { addUniqueItem, removeItem } from 'motion-utils';\nimport { compareByDepth } from './compare-by-depth.mjs';\n\nclass FlatTree {\n constructor() {\n this.children = [];\n this.isDirty = false;\n }\n add(child) {\n addUniqueItem(this.children, child);\n this.isDirty = true;\n }\n remove(child) {\n removeItem(this.children, child);\n this.isDirty = true;\n }\n forEach(callback) {\n this.isDirty && this.children.sort(compareByDepth);\n this.isDirty = false;\n this.children.forEach(callback);\n }\n}\n\nexport { FlatTree };\n","import { time, frame, cancelFrame } from 'motion-dom';\nimport { secondsToMilliseconds } from 'motion-utils';\n\n/**\n * Timeout defined in ms\n */\nfunction delay(callback, timeout) {\n const start = time.now();\n const checkElapsed = ({ timestamp }) => {\n const elapsed = timestamp - start;\n if (elapsed >= timeout) {\n cancelFrame(checkElapsed);\n callback(elapsed - timeout);\n }\n };\n frame.setup(checkElapsed, true);\n return () => cancelFrame(checkElapsed);\n}\nfunction delayInSeconds(callback, timeout) {\n return delay(callback, secondsToMilliseconds(timeout));\n}\n\nexport { delay, delayInSeconds };\n","import { mixNumber, percent, px } from 'motion-dom';\nimport { progress, circOut, noop } from 'motion-utils';\n\nconst borders = [\"TopLeft\", \"TopRight\", \"BottomLeft\", \"BottomRight\"];\nconst numBorders = borders.length;\nconst asNumber = (value) => typeof value === \"string\" ? parseFloat(value) : value;\nconst isPx = (value) => typeof value === \"number\" || px.test(value);\nfunction mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) {\n if (shouldCrossfadeOpacity) {\n target.opacity = mixNumber(0, lead.opacity ?? 1, easeCrossfadeIn(progress));\n target.opacityExit = mixNumber(follow.opacity ?? 1, 0, easeCrossfadeOut(progress));\n }\n else if (isOnlyMember) {\n target.opacity = mixNumber(follow.opacity ?? 1, lead.opacity ?? 1, progress);\n }\n /**\n * Mix border radius\n */\n for (let i = 0; i < numBorders; i++) {\n const borderLabel = `border${borders[i]}Radius`;\n let followRadius = getRadius(follow, borderLabel);\n let leadRadius = getRadius(lead, borderLabel);\n if (followRadius === undefined && leadRadius === undefined)\n continue;\n followRadius || (followRadius = 0);\n leadRadius || (leadRadius = 0);\n const canMix = followRadius === 0 ||\n leadRadius === 0 ||\n isPx(followRadius) === isPx(leadRadius);\n if (canMix) {\n target[borderLabel] = Math.max(mixNumber(asNumber(followRadius), asNumber(leadRadius), progress), 0);\n if (percent.test(leadRadius) || percent.test(followRadius)) {\n target[borderLabel] += \"%\";\n }\n }\n else {\n target[borderLabel] = leadRadius;\n }\n }\n /**\n * Mix rotation\n */\n if (follow.rotate || lead.rotate) {\n target.rotate = mixNumber(follow.rotate || 0, lead.rotate || 0, progress);\n }\n}\nfunction getRadius(values, radiusName) {\n return values[radiusName] !== undefined\n ? values[radiusName]\n : values.borderRadius;\n}\n// /**\n// * We only want to mix the background color if there's a follow element\n// * that we're not crossfading opacity between. For instance with switch\n// * AnimateSharedLayout animations, this helps the illusion of a continuous\n// * element being animated but also cuts down on the number of paints triggered\n// * for elements where opacity is doing that work for us.\n// */\n// if (\n// !hasFollowElement &&\n// latestLeadValues.backgroundColor &&\n// latestFollowValues.backgroundColor\n// ) {\n// /**\n// * This isn't ideal performance-wise as mixColor is creating a new function every frame.\n// * We could probably create a mixer that runs at the start of the animation but\n// * the idea behind the crossfader is that it runs dynamically between two potentially\n// * changing targets (ie opacity or borderRadius may be animating independently via variants)\n// */\n// leadState.backgroundColor = followState.backgroundColor = mixColor(\n// latestFollowValues.backgroundColor as string,\n// latestLeadValues.backgroundColor as string\n// )(p)\n// }\nconst easeCrossfadeIn = /*@__PURE__*/ compress(0, 0.5, circOut);\nconst easeCrossfadeOut = /*@__PURE__*/ compress(0.5, 0.95, noop);\nfunction compress(min, max, easing) {\n return (p) => {\n // Could replace ifs with clamp\n if (p < min)\n return 0;\n if (p > max)\n return 1;\n return easing(progress(min, max, p));\n };\n}\n\nexport { mixValues };\n","/**\n * Reset an axis to the provided origin box.\n *\n * This is a mutative operation.\n */\nfunction copyAxisInto(axis, originAxis) {\n axis.min = originAxis.min;\n axis.max = originAxis.max;\n}\n/**\n * Reset a box to the provided origin box.\n *\n * This is a mutative operation.\n */\nfunction copyBoxInto(box, originBox) {\n copyAxisInto(box.x, originBox.x);\n copyAxisInto(box.y, originBox.y);\n}\n/**\n * Reset a delta to the provided origin box.\n *\n * This is a mutative operation.\n */\nfunction copyAxisDeltaInto(delta, originDelta) {\n delta.translate = originDelta.translate;\n delta.scale = originDelta.scale;\n delta.originPoint = originDelta.originPoint;\n delta.origin = originDelta.origin;\n}\n\nexport { copyAxisDeltaInto, copyAxisInto, copyBoxInto };\n","import { percent, mixNumber } from 'motion-dom';\nimport { scalePoint } from './delta-apply.mjs';\n\n/**\n * Remove a delta from a point. This is essentially the steps of applyPointDelta in reverse\n */\nfunction removePointDelta(point, translate, scale, originPoint, boxScale) {\n point -= translate;\n point = scalePoint(point, 1 / scale, originPoint);\n if (boxScale !== undefined) {\n point = scalePoint(point, 1 / boxScale, originPoint);\n }\n return point;\n}\n/**\n * Remove a delta from an axis. This is essentially the steps of applyAxisDelta in reverse\n */\nfunction removeAxisDelta(axis, translate = 0, scale = 1, origin = 0.5, boxScale, originAxis = axis, sourceAxis = axis) {\n if (percent.test(translate)) {\n translate = parseFloat(translate);\n const relativeProgress = mixNumber(sourceAxis.min, sourceAxis.max, translate / 100);\n translate = relativeProgress - sourceAxis.min;\n }\n if (typeof translate !== \"number\")\n return;\n let originPoint = mixNumber(originAxis.min, originAxis.max, origin);\n if (axis === originAxis)\n originPoint -= translate;\n axis.min = removePointDelta(axis.min, translate, scale, originPoint, boxScale);\n axis.max = removePointDelta(axis.max, translate, scale, originPoint, boxScale);\n}\n/**\n * Remove a transforms from an axis. This is essentially the steps of applyAxisTransforms in reverse\n * and acts as a bridge between motion values and removeAxisDelta\n */\nfunction removeAxisTransforms(axis, transforms, [key, scaleKey, originKey], origin, sourceAxis) {\n removeAxisDelta(axis, transforms[key], transforms[scaleKey], transforms[originKey], transforms.scale, origin, sourceAxis);\n}\n/**\n * The names of the motion values we want to apply as translation, scale and origin.\n */\nconst xKeys = [\"x\", \"scaleX\", \"originX\"];\nconst yKeys = [\"y\", \"scaleY\", \"originY\"];\n/**\n * Remove a transforms from an box. This is essentially the steps of applyAxisBox in reverse\n * and acts as a bridge between motion values and removeAxisDelta\n */\nfunction removeBoxTransforms(box, transforms, originBox, sourceBox) {\n removeAxisTransforms(box.x, transforms, xKeys, originBox ? originBox.x : undefined, sourceBox ? sourceBox.x : undefined);\n removeAxisTransforms(box.y, transforms, yKeys, originBox ? originBox.y : undefined, sourceBox ? sourceBox.y : undefined);\n}\n\nexport { removeAxisDelta, removeAxisTransforms, removeBoxTransforms, removePointDelta };\n","import { calcLength } from './delta-calc.mjs';\n\nfunction isAxisDeltaZero(delta) {\n return delta.translate === 0 && delta.scale === 1;\n}\nfunction isDeltaZero(delta) {\n return isAxisDeltaZero(delta.x) && isAxisDeltaZero(delta.y);\n}\nfunction axisEquals(a, b) {\n return a.min === b.min && a.max === b.max;\n}\nfunction boxEquals(a, b) {\n return axisEquals(a.x, b.x) && axisEquals(a.y, b.y);\n}\nfunction axisEqualsRounded(a, b) {\n return (Math.round(a.min) === Math.round(b.min) &&\n Math.round(a.max) === Math.round(b.max));\n}\nfunction boxEqualsRounded(a, b) {\n return axisEqualsRounded(a.x, b.x) && axisEqualsRounded(a.y, b.y);\n}\nfunction aspectRatio(box) {\n return calcLength(box.x) / calcLength(box.y);\n}\nfunction axisDeltaEquals(a, b) {\n return (a.translate === b.translate &&\n a.scale === b.scale &&\n a.originPoint === b.originPoint);\n}\n\nexport { aspectRatio, axisDeltaEquals, axisEquals, axisEqualsRounded, boxEquals, boxEqualsRounded, isDeltaZero };\n","import { addUniqueItem, removeItem } from 'motion-utils';\n\nclass NodeStack {\n constructor() {\n this.members = [];\n }\n add(node) {\n addUniqueItem(this.members, node);\n node.scheduleRender();\n }\n remove(node) {\n removeItem(this.members, node);\n if (node === this.prevLead) {\n this.prevLead = undefined;\n }\n if (node === this.lead) {\n const prevLead = this.members[this.members.length - 1];\n if (prevLead) {\n this.promote(prevLead);\n }\n }\n }\n relegate(node) {\n const indexOfNode = this.members.findIndex((member) => node === member);\n if (indexOfNode === 0)\n return false;\n /**\n * Find the next projection node that is present\n */\n let prevLead;\n for (let i = indexOfNode; i >= 0; i--) {\n const member = this.members[i];\n if (member.isPresent !== false) {\n prevLead = member;\n break;\n }\n }\n if (prevLead) {\n this.promote(prevLead);\n return true;\n }\n else {\n return false;\n }\n }\n promote(node, preserveFollowOpacity) {\n const prevLead = this.lead;\n if (node === prevLead)\n return;\n this.prevLead = prevLead;\n this.lead = node;\n node.show();\n if (prevLead) {\n prevLead.instance && prevLead.scheduleRender();\n node.scheduleRender();\n node.resumeFrom = prevLead;\n if (preserveFollowOpacity) {\n node.resumeFrom.preserveOpacity = true;\n }\n if (prevLead.snapshot) {\n node.snapshot = prevLead.snapshot;\n node.snapshot.latestValues =\n prevLead.animationValues || prevLead.latestValues;\n }\n if (node.root && node.root.isUpdating) {\n node.isLayoutDirty = true;\n }\n const { crossfade } = node.options;\n if (crossfade === false) {\n prevLead.hide();\n }\n /**\n * TODO:\n * - Test border radius when previous node was deleted\n * - boxShadow mixing\n * - Shared between element A in scrolled container and element B (scroll stays the same or changes)\n * - Shared between element A in transformed container and element B (transform stays the same or changes)\n * - Shared between element A in scrolled page and element B (scroll stays the same or changes)\n * ---\n * - Crossfade opacity of root nodes\n * - layoutId changes after animation\n * - layoutId changes mid animation\n */\n }\n }\n exitAnimationComplete() {\n this.members.forEach((node) => {\n const { options, resumingFrom } = node;\n options.onExitComplete && options.onExitComplete();\n if (resumingFrom) {\n resumingFrom.options.onExitComplete &&\n resumingFrom.options.onExitComplete();\n }\n });\n }\n scheduleRender() {\n this.members.forEach((node) => {\n node.instance && node.scheduleRender(false);\n });\n }\n /**\n * Clear any leads that have been removed this render to prevent them from being\n * used in future animations and to prevent memory leaks\n */\n removeLeadSnapshot() {\n if (this.lead && this.lead.snapshot) {\n this.lead.snapshot = undefined;\n }\n }\n}\n\nexport { NodeStack };\n","function buildProjectionTransform(delta, treeScale, latestTransform) {\n let transform = \"\";\n /**\n * The translations we use to calculate are always relative to the viewport coordinate space.\n * But when we apply scales, we also scale the coordinate space of an element and its children.\n * For instance if we have a treeScale (the culmination of all parent scales) of 0.5 and we need\n * to move an element 100 pixels, we actually need to move it 200 in within that scaled space.\n */\n const xTranslate = delta.x.translate / treeScale.x;\n const yTranslate = delta.y.translate / treeScale.y;\n const zTranslate = latestTransform?.z || 0;\n if (xTranslate || yTranslate || zTranslate) {\n transform = `translate3d(${xTranslate}px, ${yTranslate}px, ${zTranslate}px) `;\n }\n /**\n * Apply scale correction for the tree transform.\n * This will apply scale to the screen-orientated axes.\n */\n if (treeScale.x !== 1 || treeScale.y !== 1) {\n transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `;\n }\n if (latestTransform) {\n const { transformPerspective, rotate, rotateX, rotateY, skewX, skewY } = latestTransform;\n if (transformPerspective)\n transform = `perspective(${transformPerspective}px) ${transform}`;\n if (rotate)\n transform += `rotate(${rotate}deg) `;\n if (rotateX)\n transform += `rotateX(${rotateX}deg) `;\n if (rotateY)\n transform += `rotateY(${rotateY}deg) `;\n if (skewX)\n transform += `skewX(${skewX}deg) `;\n if (skewY)\n transform += `skewY(${skewY}deg) `;\n }\n /**\n * Apply scale to match the size of the element to the size we want it.\n * This will apply scale to the element-orientated axes.\n */\n const elementScaleX = delta.x.scale * treeScale.x;\n const elementScaleY = delta.y.scale * treeScale.y;\n if (elementScaleX !== 1 || elementScaleY !== 1) {\n transform += `scale(${elementScaleX}, ${elementScaleY})`;\n }\n return transform || \"none\";\n}\n\nexport { buildProjectionTransform };\n","import { statsBuffer, isSVGElement, isSVGSVGElement, frame, getValueTransition, cancelFrame, time, frameData, frameSteps, microtask, activeAnimations, motionValue, mixNumber } from 'motion-dom';\nimport { SubscriptionManager, clamp, noop } from 'motion-utils';\nimport { animateSingleValue } from '../../animation/animate/single-value.mjs';\nimport { getOptimisedAppearId } from '../../animation/optimized-appear/get-appear-id.mjs';\nimport { FlatTree } from '../../render/utils/flat-tree.mjs';\nimport { delay } from '../../utils/delay.mjs';\nimport { resolveMotionValue } from '../../value/utils/resolve-motion-value.mjs';\nimport { mixValues } from '../animation/mix-values.mjs';\nimport { copyBoxInto, copyAxisDeltaInto } from '../geometry/copy.mjs';\nimport { translateAxis, transformBox, applyBoxDelta, applyTreeDeltas } from '../geometry/delta-apply.mjs';\nimport { calcLength, calcRelativeBox, calcRelativePosition, calcBoxDelta, isNear } from '../geometry/delta-calc.mjs';\nimport { removeBoxTransforms } from '../geometry/delta-remove.mjs';\nimport { createBox, createDelta } from '../geometry/models.mjs';\nimport { boxEqualsRounded, isDeltaZero, axisDeltaEquals, aspectRatio, boxEquals } from '../geometry/utils.mjs';\nimport { NodeStack } from '../shared/stack.mjs';\nimport { scaleCorrectors } from '../styles/scale-correction.mjs';\nimport { buildProjectionTransform } from '../styles/transform.mjs';\nimport { eachAxis } from '../utils/each-axis.mjs';\nimport { hasTransform, hasScale, has2DTranslate } from '../utils/has-transform.mjs';\nimport { globalProjectionState } from './state.mjs';\n\nconst metrics = {\n nodes: 0,\n calculatedTargetDeltas: 0,\n calculatedProjections: 0,\n};\nconst transformAxes = [\"\", \"X\", \"Y\", \"Z\"];\n/**\n * We use 1000 as the animation target as 0-1000 maps better to pixels than 0-1\n * which has a noticeable difference in spring animations\n */\nconst animationTarget = 1000;\nlet id = 0;\nfunction resetDistortingTransform(key, visualElement, values, sharedAnimationValues) {\n const { latestValues } = visualElement;\n // Record the distorting transform and then temporarily set it to 0\n if (latestValues[key]) {\n values[key] = latestValues[key];\n visualElement.setStaticValue(key, 0);\n if (sharedAnimationValues) {\n sharedAnimationValues[key] = 0;\n }\n }\n}\nfunction cancelTreeOptimisedTransformAnimations(projectionNode) {\n projectionNode.hasCheckedOptimisedAppear = true;\n if (projectionNode.root === projectionNode)\n return;\n const { visualElement } = projectionNode.options;\n if (!visualElement)\n return;\n const appearId = getOptimisedAppearId(visualElement);\n if (window.MotionHasOptimisedAnimation(appearId, \"transform\")) {\n const { layout, layoutId } = projectionNode.options;\n window.MotionCancelOptimisedAnimation(appearId, \"transform\", frame, !(layout || layoutId));\n }\n const { parent } = projectionNode;\n if (parent && !parent.hasCheckedOptimisedAppear) {\n cancelTreeOptimisedTransformAnimations(parent);\n }\n}\nfunction createProjectionNode({ attachResizeListener, defaultParent, measureScroll, checkIsScrollRoot, resetTransform, }) {\n return class ProjectionNode {\n constructor(latestValues = {}, parent = defaultParent?.()) {\n /**\n * A unique ID generated for every projection node.\n */\n this.id = id++;\n /**\n * An id that represents a unique session instigated by startUpdate.\n */\n this.animationId = 0;\n this.animationCommitId = 0;\n /**\n * A Set containing all this component's children. This is used to iterate\n * through the children.\n *\n * TODO: This could be faster to iterate as a flat array stored on the root node.\n */\n this.children = new Set();\n /**\n * Options for the node. We use this to configure what kind of layout animations\n * we should perform (if any).\n */\n this.options = {};\n /**\n * We use this to detect when its safe to shut down part of a projection tree.\n * We have to keep projecting children for scale correction and relative projection\n * until all their parents stop performing layout animations.\n */\n this.isTreeAnimating = false;\n this.isAnimationBlocked = false;\n /**\n * Flag to true if we think this layout has been changed. We can't always know this,\n * currently we set it to true every time a component renders, or if it has a layoutDependency\n * if that has changed between renders. Additionally, components can be grouped by LayoutGroup\n * and if one node is dirtied, they all are.\n */\n this.isLayoutDirty = false;\n /**\n * Flag to true if we think the projection calculations for this node needs\n * recalculating as a result of an updated transform or layout animation.\n */\n this.isProjectionDirty = false;\n /**\n * Flag to true if the layout *or* transform has changed. This then gets propagated\n * throughout the projection tree, forcing any element below to recalculate on the next frame.\n */\n this.isSharedProjectionDirty = false;\n /**\n * Flag transform dirty. This gets propagated throughout the whole tree but is only\n * respected by shared nodes.\n */\n this.isTransformDirty = false;\n /**\n * Block layout updates for instant layout transitions throughout the tree.\n */\n this.updateManuallyBlocked = false;\n this.updateBlockedByResize = false;\n /**\n * Set to true between the start of the first `willUpdate` call and the end of the `didUpdate`\n * call.\n */\n this.isUpdating = false;\n /**\n * If this is an SVG element we currently disable projection transforms\n */\n this.isSVG = false;\n /**\n * Flag to true (during promotion) if a node doing an instant layout transition needs to reset\n * its projection styles.\n */\n this.needsReset = false;\n /**\n * Flags whether this node should have its transform reset prior to measuring.\n */\n this.shouldResetTransform = false;\n /**\n * Store whether this node has been checked for optimised appear animations. As\n * effects fire bottom-up, and we want to look up the tree for appear animations,\n * this makes sure we only check each path once, stopping at nodes that\n * have already been checked.\n */\n this.hasCheckedOptimisedAppear = false;\n /**\n * An object representing the calculated contextual/accumulated/tree scale.\n * This will be used to scale calculcated projection transforms, as these are\n * calculated in screen-space but need to be scaled for elements to layoutly\n * make it to their calculated destinations.\n *\n * TODO: Lazy-init\n */\n this.treeScale = { x: 1, y: 1 };\n /**\n *\n */\n this.eventHandlers = new Map();\n this.hasTreeAnimated = false;\n this.layoutVersion = 0;\n // Note: Currently only running on root node\n this.updateScheduled = false;\n this.scheduleUpdate = () => this.update();\n this.projectionUpdateScheduled = false;\n this.checkUpdateFailed = () => {\n if (this.isUpdating) {\n this.isUpdating = false;\n this.clearAllSnapshots();\n }\n };\n /**\n * This is a multi-step process as shared nodes might be of different depths. Nodes\n * are sorted by depth order, so we need to resolve the entire tree before moving to\n * the next step.\n */\n this.updateProjection = () => {\n this.projectionUpdateScheduled = false;\n /**\n * Reset debug counts. Manually resetting rather than creating a new\n * object each frame.\n */\n if (statsBuffer.value) {\n metrics.nodes =\n metrics.calculatedTargetDeltas =\n metrics.calculatedProjections =\n 0;\n }\n this.nodes.forEach(propagateDirtyNodes);\n this.nodes.forEach(resolveTargetDelta);\n this.nodes.forEach(calcProjection);\n this.nodes.forEach(cleanDirtyNodes);\n if (statsBuffer.addProjectionMetrics) {\n statsBuffer.addProjectionMetrics(metrics);\n }\n };\n /**\n * Frame calculations\n */\n this.resolvedRelativeTargetAt = 0.0;\n this.linkedParentVersion = 0;\n this.hasProjected = false;\n this.isVisible = true;\n this.animationProgress = 0;\n /**\n * Shared layout\n */\n // TODO Only running on root node\n this.sharedNodes = new Map();\n this.latestValues = latestValues;\n this.root = parent ? parent.root || parent : this;\n this.path = parent ? [...parent.path, parent] : [];\n this.parent = parent;\n this.depth = parent ? parent.depth + 1 : 0;\n for (let i = 0; i < this.path.length; i++) {\n this.path[i].shouldResetTransform = true;\n }\n if (this.root === this)\n this.nodes = new FlatTree();\n }\n addEventListener(name, handler) {\n if (!this.eventHandlers.has(name)) {\n this.eventHandlers.set(name, new SubscriptionManager());\n }\n return this.eventHandlers.get(name).add(handler);\n }\n notifyListeners(name, ...args) {\n const subscriptionManager = this.eventHandlers.get(name);\n subscriptionManager && subscriptionManager.notify(...args);\n }\n hasListeners(name) {\n return this.eventHandlers.has(name);\n }\n /**\n * Lifecycles\n */\n mount(instance) {\n if (this.instance)\n return;\n this.isSVG = isSVGElement(instance) && !isSVGSVGElement(instance);\n this.instance = instance;\n const { layoutId, layout, visualElement } = this.options;\n if (visualElement && !visualElement.current) {\n visualElement.mount(instance);\n }\n this.root.nodes.add(this);\n this.parent && this.parent.children.add(this);\n if (this.root.hasTreeAnimated && (layout || layoutId)) {\n this.isLayoutDirty = true;\n }\n if (attachResizeListener) {\n let cancelDelay;\n let innerWidth = 0;\n const resizeUnblockUpdate = () => (this.root.updateBlockedByResize = false);\n // Set initial innerWidth in a frame.read callback to batch the read\n frame.read(() => {\n innerWidth = window.innerWidth;\n });\n attachResizeListener(instance, () => {\n const newInnerWidth = window.innerWidth;\n if (newInnerWidth === innerWidth)\n return;\n innerWidth = newInnerWidth;\n this.root.updateBlockedByResize = true;\n cancelDelay && cancelDelay();\n cancelDelay = delay(resizeUnblockUpdate, 250);\n if (globalProjectionState.hasAnimatedSinceResize) {\n globalProjectionState.hasAnimatedSinceResize = false;\n this.nodes.forEach(finishAnimation);\n }\n });\n }\n if (layoutId) {\n this.root.registerSharedNode(layoutId, this);\n }\n // Only register the handler if it requires layout animation\n if (this.options.animate !== false &&\n visualElement &&\n (layoutId || layout)) {\n this.addEventListener(\"didUpdate\", ({ delta, hasLayoutChanged, hasRelativeLayoutChanged, layout: newLayout, }) => {\n if (this.isTreeAnimationBlocked()) {\n this.target = undefined;\n this.relativeTarget = undefined;\n return;\n }\n // TODO: Check here if an animation exists\n const layoutTransition = this.options.transition ||\n visualElement.getDefaultTransition() ||\n defaultLayoutTransition;\n const { onLayoutAnimationStart, onLayoutAnimationComplete, } = visualElement.getProps();\n /**\n * The target layout of the element might stay the same,\n * but its position relative to its parent has changed.\n */\n const hasTargetChanged = !this.targetLayout ||\n !boxEqualsRounded(this.targetLayout, newLayout);\n /*\n * Note: Disabled to fix relative animations always triggering new\n * layout animations. If this causes further issues, we can try\n * a different approach to detecting relative target changes.\n */\n // || hasRelativeLayoutChanged\n /**\n * If the layout hasn't seemed to have changed, it might be that the\n * element is visually in the same place in the document but its position\n * relative to its parent has indeed changed. So here we check for that.\n */\n const hasOnlyRelativeTargetChanged = !hasLayoutChanged && hasRelativeLayoutChanged;\n if (this.options.layoutRoot ||\n this.resumeFrom ||\n hasOnlyRelativeTargetChanged ||\n (hasLayoutChanged &&\n (hasTargetChanged || !this.currentAnimation))) {\n if (this.resumeFrom) {\n this.resumingFrom = this.resumeFrom;\n this.resumingFrom.resumingFrom = undefined;\n }\n const animationOptions = {\n ...getValueTransition(layoutTransition, \"layout\"),\n onPlay: onLayoutAnimationStart,\n onComplete: onLayoutAnimationComplete,\n };\n if (visualElement.shouldReduceMotion ||\n this.options.layoutRoot) {\n animationOptions.delay = 0;\n animationOptions.type = false;\n }\n this.startAnimation(animationOptions);\n /**\n * Set animation origin after starting animation to avoid layout jump\n * caused by stopping previous layout animation\n */\n this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged);\n }\n else {\n /**\n * If the layout hasn't changed and we have an animation that hasn't started yet,\n * finish it immediately. Otherwise it will be animating from a location\n * that was probably never commited to screen and look like a jumpy box.\n */\n if (!hasLayoutChanged) {\n finishAnimation(this);\n }\n if (this.isLead() && this.options.onExitComplete) {\n this.options.onExitComplete();\n }\n }\n this.targetLayout = newLayout;\n });\n }\n }\n unmount() {\n this.options.layoutId && this.willUpdate();\n this.root.nodes.remove(this);\n const stack = this.getStack();\n stack && stack.remove(this);\n this.parent && this.parent.children.delete(this);\n this.instance = undefined;\n this.eventHandlers.clear();\n cancelFrame(this.updateProjection);\n }\n // only on the root\n blockUpdate() {\n this.updateManuallyBlocked = true;\n }\n unblockUpdate() {\n this.updateManuallyBlocked = false;\n }\n isUpdateBlocked() {\n return this.updateManuallyBlocked || this.updateBlockedByResize;\n }\n isTreeAnimationBlocked() {\n return (this.isAnimationBlocked ||\n (this.parent && this.parent.isTreeAnimationBlocked()) ||\n false);\n }\n // Note: currently only running on root node\n startUpdate() {\n if (this.isUpdateBlocked())\n return;\n this.isUpdating = true;\n this.nodes && this.nodes.forEach(resetSkewAndRotation);\n this.animationId++;\n }\n getTransformTemplate() {\n const { visualElement } = this.options;\n return visualElement && visualElement.getProps().transformTemplate;\n }\n willUpdate(shouldNotifyListeners = true) {\n this.root.hasTreeAnimated = true;\n if (this.root.isUpdateBlocked()) {\n this.options.onExitComplete && this.options.onExitComplete();\n return;\n }\n /**\n * If we're running optimised appear animations then these must be\n * cancelled before measuring the DOM. This is so we can measure\n * the true layout of the element rather than the WAAPI animation\n * which will be unaffected by the resetSkewAndRotate step.\n *\n * Note: This is a DOM write. Worst case scenario is this is sandwiched\n * between other snapshot reads which will cause unnecessary style recalculations.\n * This has to happen here though, as we don't yet know which nodes will need\n * snapshots in startUpdate(), but we only want to cancel optimised animations\n * if a layout animation measurement is actually going to be affected by them.\n */\n if (window.MotionCancelOptimisedAnimation &&\n !this.hasCheckedOptimisedAppear) {\n cancelTreeOptimisedTransformAnimations(this);\n }\n !this.root.isUpdating && this.root.startUpdate();\n if (this.isLayoutDirty)\n return;\n this.isLayoutDirty = true;\n for (let i = 0; i < this.path.length; i++) {\n const node = this.path[i];\n node.shouldResetTransform = true;\n node.updateScroll(\"snapshot\");\n if (node.options.layoutRoot) {\n node.willUpdate(false);\n }\n }\n const { layoutId, layout } = this.options;\n if (layoutId === undefined && !layout)\n return;\n const transformTemplate = this.getTransformTemplate();\n this.prevTransformTemplateValue = transformTemplate\n ? transformTemplate(this.latestValues, \"\")\n : undefined;\n this.updateSnapshot();\n shouldNotifyListeners && this.notifyListeners(\"willUpdate\");\n }\n update() {\n this.updateScheduled = false;\n const updateWasBlocked = this.isUpdateBlocked();\n // When doing an instant transition, we skip the layout update,\n // but should still clean up the measurements so that the next\n // snapshot could be taken correctly.\n if (updateWasBlocked) {\n this.unblockUpdate();\n this.clearAllSnapshots();\n this.nodes.forEach(clearMeasurements);\n return;\n }\n /**\n * If this is a repeat of didUpdate then ignore the animation.\n */\n if (this.animationId <= this.animationCommitId) {\n this.nodes.forEach(clearIsLayoutDirty);\n return;\n }\n this.animationCommitId = this.animationId;\n if (!this.isUpdating) {\n this.nodes.forEach(clearIsLayoutDirty);\n }\n else {\n this.isUpdating = false;\n /**\n * Write\n */\n this.nodes.forEach(resetTransformStyle);\n /**\n * Read ==================\n */\n // Update layout measurements of updated children\n this.nodes.forEach(updateLayout);\n /**\n * Write\n */\n // Notify listeners that the layout is updated\n this.nodes.forEach(notifyLayoutUpdate);\n }\n this.clearAllSnapshots();\n /**\n * Manually flush any pending updates. Ideally\n * we could leave this to the following requestAnimationFrame but this seems\n * to leave a flash of incorrectly styled content.\n */\n const now = time.now();\n frameData.delta = clamp(0, 1000 / 60, now - frameData.timestamp);\n frameData.timestamp = now;\n frameData.isProcessing = true;\n frameSteps.update.process(frameData);\n frameSteps.preRender.process(frameData);\n frameSteps.render.process(frameData);\n frameData.isProcessing = false;\n }\n didUpdate() {\n if (!this.updateScheduled) {\n this.updateScheduled = true;\n microtask.read(this.scheduleUpdate);\n }\n }\n clearAllSnapshots() {\n this.nodes.forEach(clearSnapshot);\n this.sharedNodes.forEach(removeLeadSnapshots);\n }\n scheduleUpdateProjection() {\n if (!this.projectionUpdateScheduled) {\n this.projectionUpdateScheduled = true;\n frame.preRender(this.updateProjection, false, true);\n }\n }\n scheduleCheckAfterUnmount() {\n /**\n * If the unmounting node is in a layoutGroup and did trigger a willUpdate,\n * we manually call didUpdate to give a chance to the siblings to animate.\n * Otherwise, cleanup all snapshots to prevents future nodes from reusing them.\n */\n frame.postRender(() => {\n if (this.isLayoutDirty) {\n this.root.didUpdate();\n }\n else {\n this.root.checkUpdateFailed();\n }\n });\n }\n /**\n * Update measurements\n */\n updateSnapshot() {\n if (this.snapshot || !this.instance)\n return;\n this.snapshot = this.measure();\n if (this.snapshot &&\n !calcLength(this.snapshot.measuredBox.x) &&\n !calcLength(this.snapshot.measuredBox.y)) {\n this.snapshot = undefined;\n }\n }\n updateLayout() {\n if (!this.instance)\n return;\n this.updateScroll();\n if (!(this.options.alwaysMeasureLayout && this.isLead()) &&\n !this.isLayoutDirty) {\n return;\n }\n /**\n * When a node is mounted, it simply resumes from the prevLead's\n * snapshot instead of taking a new one, but the ancestors scroll\n * might have updated while the prevLead is unmounted. We need to\n * update the scroll again to make sure the layout we measure is\n * up to date.\n */\n if (this.resumeFrom && !this.resumeFrom.instance) {\n for (let i = 0; i < this.path.length; i++) {\n const node = this.path[i];\n node.updateScroll();\n }\n }\n const prevLayout = this.layout;\n this.layout = this.measure(false);\n this.layoutVersion++;\n this.layoutCorrected = createBox();\n this.isLayoutDirty = false;\n this.projectionDelta = undefined;\n this.notifyListeners(\"measure\", this.layout.layoutBox);\n const { visualElement } = this.options;\n visualElement &&\n visualElement.notify(\"LayoutMeasure\", this.layout.layoutBox, prevLayout ? prevLayout.layoutBox : undefined);\n }\n updateScroll(phase = \"measure\") {\n let needsMeasurement = Boolean(this.options.layoutScroll && this.instance);\n if (this.scroll &&\n this.scroll.animationId === this.root.animationId &&\n this.scroll.phase === phase) {\n needsMeasurement = false;\n }\n if (needsMeasurement && this.instance) {\n const isRoot = checkIsScrollRoot(this.instance);\n this.scroll = {\n animationId: this.root.animationId,\n phase,\n isRoot,\n offset: measureScroll(this.instance),\n wasRoot: this.scroll ? this.scroll.isRoot : isRoot,\n };\n }\n }\n resetTransform() {\n if (!resetTransform)\n return;\n const isResetRequested = this.isLayoutDirty ||\n this.shouldResetTransform ||\n this.options.alwaysMeasureLayout;\n const hasProjection = this.projectionDelta && !isDeltaZero(this.projectionDelta);\n const transformTemplate = this.getTransformTemplate();\n const transformTemplateValue = transformTemplate\n ? transformTemplate(this.latestValues, \"\")\n : undefined;\n const transformTemplateHasChanged = transformTemplateValue !== this.prevTransformTemplateValue;\n if (isResetRequested &&\n this.instance &&\n (hasProjection ||\n hasTransform(this.latestValues) ||\n transformTemplateHasChanged)) {\n resetTransform(this.instance, transformTemplateValue);\n this.shouldResetTransform = false;\n this.scheduleRender();\n }\n }\n measure(removeTransform = true) {\n const pageBox = this.measurePageBox();\n let layoutBox = this.removeElementScroll(pageBox);\n /**\n * Measurements taken during the pre-render stage\n * still have transforms applied so we remove them\n * via calculation.\n */\n if (removeTransform) {\n layoutBox = this.removeTransform(layoutBox);\n }\n roundBox(layoutBox);\n return {\n animationId: this.root.animationId,\n measuredBox: pageBox,\n layoutBox,\n latestValues: {},\n source: this.id,\n };\n }\n measurePageBox() {\n const { visualElement } = this.options;\n if (!visualElement)\n return createBox();\n const box = visualElement.measureViewportBox();\n const wasInScrollRoot = this.scroll?.wasRoot || this.path.some(checkNodeWasScrollRoot);\n if (!wasInScrollRoot) {\n // Remove viewport scroll to give page-relative coordinates\n const { scroll } = this.root;\n if (scroll) {\n translateAxis(box.x, scroll.offset.x);\n translateAxis(box.y, scroll.offset.y);\n }\n }\n return box;\n }\n removeElementScroll(box) {\n const boxWithoutScroll = createBox();\n copyBoxInto(boxWithoutScroll, box);\n if (this.scroll?.wasRoot) {\n return boxWithoutScroll;\n }\n /**\n * Performance TODO: Keep a cumulative scroll offset down the tree\n * rather than loop back up the path.\n */\n for (let i = 0; i < this.path.length; i++) {\n const node = this.path[i];\n const { scroll, options } = node;\n if (node !== this.root && scroll && options.layoutScroll) {\n /**\n * If this is a new scroll root, we want to remove all previous scrolls\n * from the viewport box.\n */\n if (scroll.wasRoot) {\n copyBoxInto(boxWithoutScroll, box);\n }\n translateAxis(boxWithoutScroll.x, scroll.offset.x);\n translateAxis(boxWithoutScroll.y, scroll.offset.y);\n }\n }\n return boxWithoutScroll;\n }\n applyTransform(box, transformOnly = false) {\n const withTransforms = createBox();\n copyBoxInto(withTransforms, box);\n for (let i = 0; i < this.path.length; i++) {\n const node = this.path[i];\n if (!transformOnly &&\n node.options.layoutScroll &&\n node.scroll &&\n node !== node.root) {\n transformBox(withTransforms, {\n x: -node.scroll.offset.x,\n y: -node.scroll.offset.y,\n });\n }\n if (!hasTransform(node.latestValues))\n continue;\n transformBox(withTransforms, node.latestValues);\n }\n if (hasTransform(this.latestValues)) {\n transformBox(withTransforms, this.latestValues);\n }\n return withTransforms;\n }\n removeTransform(box) {\n const boxWithoutTransform = createBox();\n copyBoxInto(boxWithoutTransform, box);\n for (let i = 0; i < this.path.length; i++) {\n const node = this.path[i];\n if (!node.instance)\n continue;\n if (!hasTransform(node.latestValues))\n continue;\n hasScale(node.latestValues) && node.updateSnapshot();\n const sourceBox = createBox();\n const nodeBox = node.measurePageBox();\n copyBoxInto(sourceBox, nodeBox);\n removeBoxTransforms(boxWithoutTransform, node.latestValues, node.snapshot ? node.snapshot.layoutBox : undefined, sourceBox);\n }\n if (hasTransform(this.latestValues)) {\n removeBoxTransforms(boxWithoutTransform, this.latestValues);\n }\n return boxWithoutTransform;\n }\n setTargetDelta(delta) {\n this.targetDelta = delta;\n this.root.scheduleUpdateProjection();\n this.isProjectionDirty = true;\n }\n setOptions(options) {\n this.options = {\n ...this.options,\n ...options,\n crossfade: options.crossfade !== undefined ? options.crossfade : true,\n };\n }\n clearMeasurements() {\n this.scroll = undefined;\n this.layout = undefined;\n this.snapshot = undefined;\n this.prevTransformTemplateValue = undefined;\n this.targetDelta = undefined;\n this.target = undefined;\n this.isLayoutDirty = false;\n }\n forceRelativeParentToResolveTarget() {\n if (!this.relativeParent)\n return;\n /**\n * If the parent target isn't up-to-date, force it to update.\n * This is an unfortunate de-optimisation as it means any updating relative\n * projection will cause all the relative parents to recalculate back\n * up the tree.\n */\n if (this.relativeParent.resolvedRelativeTargetAt !==\n frameData.timestamp) {\n this.relativeParent.resolveTargetDelta(true);\n }\n }\n resolveTargetDelta(forceRecalculation = false) {\n /**\n * Once the dirty status of nodes has been spread through the tree, we also\n * need to check if we have a shared node of a different depth that has itself\n * been dirtied.\n */\n const lead = this.getLead();\n this.isProjectionDirty || (this.isProjectionDirty = lead.isProjectionDirty);\n this.isTransformDirty || (this.isTransformDirty = lead.isTransformDirty);\n this.isSharedProjectionDirty || (this.isSharedProjectionDirty = lead.isSharedProjectionDirty);\n const isShared = Boolean(this.resumingFrom) || this !== lead;\n /**\n * We don't use transform for this step of processing so we don't\n * need to check whether any nodes have changed transform.\n */\n const canSkip = !(forceRecalculation ||\n (isShared && this.isSharedProjectionDirty) ||\n this.isProjectionDirty ||\n this.parent?.isProjectionDirty ||\n this.attemptToResolveRelativeTarget ||\n this.root.updateBlockedByResize);\n if (canSkip)\n return;\n const { layout, layoutId } = this.options;\n /**\n * If we have no layout, we can't perform projection, so early return\n */\n if (!this.layout || !(layout || layoutId))\n return;\n this.resolvedRelativeTargetAt = frameData.timestamp;\n const relativeParent = this.getClosestProjectingParent();\n if (relativeParent &&\n this.linkedParentVersion !== relativeParent.layoutVersion &&\n !relativeParent.options.layoutRoot) {\n this.removeRelativeTarget();\n }\n /**\n * If we don't have a targetDelta but do have a layout, we can attempt to resolve\n * a relativeParent. This will allow a component to perform scale correction\n * even if no animation has started.\n */\n if (!this.targetDelta && !this.relativeTarget) {\n if (relativeParent && relativeParent.layout) {\n this.createRelativeTarget(relativeParent, this.layout.layoutBox, relativeParent.layout.layoutBox);\n }\n else {\n this.removeRelativeTarget();\n }\n }\n /**\n * If we have no relative target or no target delta our target isn't valid\n * for this frame.\n */\n if (!this.relativeTarget && !this.targetDelta)\n return;\n /**\n * Lazy-init target data structure\n */\n if (!this.target) {\n this.target = createBox();\n this.targetWithTransforms = createBox();\n }\n /**\n * If we've got a relative box for this component, resolve it into a target relative to the parent.\n */\n if (this.relativeTarget &&\n this.relativeTargetOrigin &&\n this.relativeParent &&\n this.relativeParent.target) {\n this.forceRelativeParentToResolveTarget();\n calcRelativeBox(this.target, this.relativeTarget, this.relativeParent.target);\n /**\n * If we've only got a targetDelta, resolve it into a target\n */\n }\n else if (this.targetDelta) {\n if (Boolean(this.resumingFrom)) {\n // TODO: This is creating a new object every frame\n this.target = this.applyTransform(this.layout.layoutBox);\n }\n else {\n copyBoxInto(this.target, this.layout.layoutBox);\n }\n applyBoxDelta(this.target, this.targetDelta);\n }\n else {\n /**\n * If no target, use own layout as target\n */\n copyBoxInto(this.target, this.layout.layoutBox);\n }\n /**\n * If we've been told to attempt to resolve a relative target, do so.\n */\n if (this.attemptToResolveRelativeTarget) {\n this.attemptToResolveRelativeTarget = false;\n if (relativeParent &&\n Boolean(relativeParent.resumingFrom) ===\n Boolean(this.resumingFrom) &&\n !relativeParent.options.layoutScroll &&\n relativeParent.target &&\n this.animationProgress !== 1) {\n this.createRelativeTarget(relativeParent, this.target, relativeParent.target);\n }\n else {\n this.relativeParent = this.relativeTarget = undefined;\n }\n }\n /**\n * Increase debug counter for resolved target deltas\n */\n if (statsBuffer.value) {\n metrics.calculatedTargetDeltas++;\n }\n }\n getClosestProjectingParent() {\n if (!this.parent ||\n hasScale(this.parent.latestValues) ||\n has2DTranslate(this.parent.latestValues)) {\n return undefined;\n }\n if (this.parent.isProjecting()) {\n return this.parent;\n }\n else {\n return this.parent.getClosestProjectingParent();\n }\n }\n isProjecting() {\n return Boolean((this.relativeTarget ||\n this.targetDelta ||\n this.options.layoutRoot) &&\n this.layout);\n }\n createRelativeTarget(relativeParent, layout, parentLayout) {\n this.relativeParent = relativeParent;\n this.linkedParentVersion = relativeParent.layoutVersion;\n this.forceRelativeParentToResolveTarget();\n this.relativeTarget = createBox();\n this.relativeTargetOrigin = createBox();\n calcRelativePosition(this.relativeTargetOrigin, layout, parentLayout);\n copyBoxInto(this.relativeTarget, this.relativeTargetOrigin);\n }\n removeRelativeTarget() {\n this.relativeParent = this.relativeTarget = undefined;\n }\n calcProjection() {\n const lead = this.getLead();\n const isShared = Boolean(this.resumingFrom) || this !== lead;\n let canSkip = true;\n /**\n * If this is a normal layout animation and neither this node nor its nearest projecting\n * is dirty then we can't skip.\n */\n if (this.isProjectionDirty || this.parent?.isProjectionDirty) {\n canSkip = false;\n }\n /**\n * If this is a shared layout animation and this node's shared projection is dirty then\n * we can't skip.\n */\n if (isShared &&\n (this.isSharedProjectionDirty || this.isTransformDirty)) {\n canSkip = false;\n }\n /**\n * If we have resolved the target this frame we must recalculate the\n * projection to ensure it visually represents the internal calculations.\n */\n if (this.resolvedRelativeTargetAt === frameData.timestamp) {\n canSkip = false;\n }\n if (canSkip)\n return;\n const { layout, layoutId } = this.options;\n /**\n * If this section of the tree isn't animating we can\n * delete our target sources for the following frame.\n */\n this.isTreeAnimating = Boolean((this.parent && this.parent.isTreeAnimating) ||\n this.currentAnimation ||\n this.pendingAnimation);\n if (!this.isTreeAnimating) {\n this.targetDelta = this.relativeTarget = undefined;\n }\n if (!this.layout || !(layout || layoutId))\n return;\n /**\n * Reset the corrected box with the latest values from box, as we're then going\n * to perform mutative operations on it.\n */\n copyBoxInto(this.layoutCorrected, this.layout.layoutBox);\n /**\n * Record previous tree scales before updating.\n */\n const prevTreeScaleX = this.treeScale.x;\n const prevTreeScaleY = this.treeScale.y;\n /**\n * Apply all the parent deltas to this box to produce the corrected box. This\n * is the layout box, as it will appear on screen as a result of the transforms of its parents.\n */\n applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, isShared);\n /**\n * If this layer needs to perform scale correction but doesn't have a target,\n * use the layout as the target.\n */\n if (lead.layout &&\n !lead.target &&\n (this.treeScale.x !== 1 || this.treeScale.y !== 1)) {\n lead.target = lead.layout.layoutBox;\n lead.targetWithTransforms = createBox();\n }\n const { target } = lead;\n if (!target) {\n /**\n * If we don't have a target to project into, but we were previously\n * projecting, we want to remove the stored transform and schedule\n * a render to ensure the elements reflect the removed transform.\n */\n if (this.prevProjectionDelta) {\n this.createProjectionDeltas();\n this.scheduleRender();\n }\n return;\n }\n if (!this.projectionDelta || !this.prevProjectionDelta) {\n this.createProjectionDeltas();\n }\n else {\n copyAxisDeltaInto(this.prevProjectionDelta.x, this.projectionDelta.x);\n copyAxisDeltaInto(this.prevProjectionDelta.y, this.projectionDelta.y);\n }\n /**\n * Update the delta between the corrected box and the target box before user-set transforms were applied.\n * This will allow us to calculate the corrected borderRadius and boxShadow to compensate\n * for our layout reprojection, but still allow them to be scaled correctly by the user.\n * It might be that to simplify this we may want to accept that user-set scale is also corrected\n * and we wouldn't have to keep and calc both deltas, OR we could support a user setting\n * to allow people to choose whether these styles are corrected based on just the\n * layout reprojection or the final bounding box.\n */\n calcBoxDelta(this.projectionDelta, this.layoutCorrected, target, this.latestValues);\n if (this.treeScale.x !== prevTreeScaleX ||\n this.treeScale.y !== prevTreeScaleY ||\n !axisDeltaEquals(this.projectionDelta.x, this.prevProjectionDelta.x) ||\n !axisDeltaEquals(this.projectionDelta.y, this.prevProjectionDelta.y)) {\n this.hasProjected = true;\n this.scheduleRender();\n this.notifyListeners(\"projectionUpdate\", target);\n }\n /**\n * Increase debug counter for recalculated projections\n */\n if (statsBuffer.value) {\n metrics.calculatedProjections++;\n }\n }\n hide() {\n this.isVisible = false;\n // TODO: Schedule render\n }\n show() {\n this.isVisible = true;\n // TODO: Schedule render\n }\n scheduleRender(notifyAll = true) {\n this.options.visualElement?.scheduleRender();\n if (notifyAll) {\n const stack = this.getStack();\n stack && stack.scheduleRender();\n }\n if (this.resumingFrom && !this.resumingFrom.instance) {\n this.resumingFrom = undefined;\n }\n }\n createProjectionDeltas() {\n this.prevProjectionDelta = createDelta();\n this.projectionDelta = createDelta();\n this.projectionDeltaWithTransform = createDelta();\n }\n setAnimationOrigin(delta, hasOnlyRelativeTargetChanged = false) {\n const snapshot = this.snapshot;\n const snapshotLatestValues = snapshot ? snapshot.latestValues : {};\n const mixedValues = { ...this.latestValues };\n const targetDelta = createDelta();\n if (!this.relativeParent ||\n !this.relativeParent.options.layoutRoot) {\n this.relativeTarget = this.relativeTargetOrigin = undefined;\n }\n this.attemptToResolveRelativeTarget = !hasOnlyRelativeTargetChanged;\n const relativeLayout = createBox();\n const snapshotSource = snapshot ? snapshot.source : undefined;\n const layoutSource = this.layout ? this.layout.source : undefined;\n const isSharedLayoutAnimation = snapshotSource !== layoutSource;\n const stack = this.getStack();\n const isOnlyMember = !stack || stack.members.length <= 1;\n const shouldCrossfadeOpacity = Boolean(isSharedLayoutAnimation &&\n !isOnlyMember &&\n this.options.crossfade === true &&\n !this.path.some(hasOpacityCrossfade));\n this.animationProgress = 0;\n let prevRelativeTarget;\n this.mixTargetDelta = (latest) => {\n const progress = latest / 1000;\n mixAxisDelta(targetDelta.x, delta.x, progress);\n mixAxisDelta(targetDelta.y, delta.y, progress);\n this.setTargetDelta(targetDelta);\n if (this.relativeTarget &&\n this.relativeTargetOrigin &&\n this.layout &&\n this.relativeParent &&\n this.relativeParent.layout) {\n calcRelativePosition(relativeLayout, this.layout.layoutBox, this.relativeParent.layout.layoutBox);\n mixBox(this.relativeTarget, this.relativeTargetOrigin, relativeLayout, progress);\n /**\n * If this is an unchanged relative target we can consider the\n * projection not dirty.\n */\n if (prevRelativeTarget &&\n boxEquals(this.relativeTarget, prevRelativeTarget)) {\n this.isProjectionDirty = false;\n }\n if (!prevRelativeTarget)\n prevRelativeTarget = createBox();\n copyBoxInto(prevRelativeTarget, this.relativeTarget);\n }\n if (isSharedLayoutAnimation) {\n this.animationValues = mixedValues;\n mixValues(mixedValues, snapshotLatestValues, this.latestValues, progress, shouldCrossfadeOpacity, isOnlyMember);\n }\n this.root.scheduleUpdateProjection();\n this.scheduleRender();\n this.animationProgress = progress;\n };\n this.mixTargetDelta(this.options.layoutRoot ? 1000 : 0);\n }\n startAnimation(options) {\n this.notifyListeners(\"animationStart\");\n this.currentAnimation?.stop();\n this.resumingFrom?.currentAnimation?.stop();\n if (this.pendingAnimation) {\n cancelFrame(this.pendingAnimation);\n this.pendingAnimation = undefined;\n }\n /**\n * Start the animation in the next frame to have a frame with progress 0,\n * where the target is the same as when the animation started, so we can\n * calculate the relative positions correctly for instant transitions.\n */\n this.pendingAnimation = frame.update(() => {\n globalProjectionState.hasAnimatedSinceResize = true;\n activeAnimations.layout++;\n this.motionValue || (this.motionValue = motionValue(0));\n this.currentAnimation = animateSingleValue(this.motionValue, [0, 1000], {\n ...options,\n velocity: 0,\n isSync: true,\n onUpdate: (latest) => {\n this.mixTargetDelta(latest);\n options.onUpdate && options.onUpdate(latest);\n },\n onStop: () => {\n activeAnimations.layout--;\n },\n onComplete: () => {\n activeAnimations.layout--;\n options.onComplete && options.onComplete();\n this.completeAnimation();\n },\n });\n if (this.resumingFrom) {\n this.resumingFrom.currentAnimation = this.currentAnimation;\n }\n this.pendingAnimation = undefined;\n });\n }\n completeAnimation() {\n if (this.resumingFrom) {\n this.resumingFrom.currentAnimation = undefined;\n this.resumingFrom.preserveOpacity = undefined;\n }\n const stack = this.getStack();\n stack && stack.exitAnimationComplete();\n this.resumingFrom =\n this.currentAnimation =\n this.animationValues =\n undefined;\n this.notifyListeners(\"animationComplete\");\n }\n finishAnimation() {\n if (this.currentAnimation) {\n this.mixTargetDelta && this.mixTargetDelta(animationTarget);\n this.currentAnimation.stop();\n }\n this.completeAnimation();\n }\n applyTransformsToTarget() {\n const lead = this.getLead();\n let { targetWithTransforms, target, layout, latestValues } = lead;\n if (!targetWithTransforms || !target || !layout)\n return;\n /**\n * If we're only animating position, and this element isn't the lead element,\n * then instead of projecting into the lead box we instead want to calculate\n * a new target that aligns the two boxes but maintains the layout shape.\n */\n if (this !== lead &&\n this.layout &&\n layout &&\n shouldAnimatePositionOnly(this.options.animationType, this.layout.layoutBox, layout.layoutBox)) {\n target = this.target || createBox();\n const xLength = calcLength(this.layout.layoutBox.x);\n target.x.min = lead.target.x.min;\n target.x.max = target.x.min + xLength;\n const yLength = calcLength(this.layout.layoutBox.y);\n target.y.min = lead.target.y.min;\n target.y.max = target.y.min + yLength;\n }\n copyBoxInto(targetWithTransforms, target);\n /**\n * Apply the latest user-set transforms to the targetBox to produce the targetBoxFinal.\n * This is the final box that we will then project into by calculating a transform delta and\n * applying it to the corrected box.\n */\n transformBox(targetWithTransforms, latestValues);\n /**\n * Update the delta between the corrected box and the final target box, after\n * user-set transforms are applied to it. This will be used by the renderer to\n * create a transform style that will reproject the element from its layout layout\n * into the desired bounding box.\n */\n calcBoxDelta(this.projectionDeltaWithTransform, this.layoutCorrected, targetWithTransforms, latestValues);\n }\n registerSharedNode(layoutId, node) {\n if (!this.sharedNodes.has(layoutId)) {\n this.sharedNodes.set(layoutId, new NodeStack());\n }\n const stack = this.sharedNodes.get(layoutId);\n stack.add(node);\n const config = node.options.initialPromotionConfig;\n node.promote({\n transition: config ? config.transition : undefined,\n preserveFollowOpacity: config && config.shouldPreserveFollowOpacity\n ? config.shouldPreserveFollowOpacity(node)\n : undefined,\n });\n }\n isLead() {\n const stack = this.getStack();\n return stack ? stack.lead === this : true;\n }\n getLead() {\n const { layoutId } = this.options;\n return layoutId ? this.getStack()?.lead || this : this;\n }\n getPrevLead() {\n const { layoutId } = this.options;\n return layoutId ? this.getStack()?.prevLead : undefined;\n }\n getStack() {\n const { layoutId } = this.options;\n if (layoutId)\n return this.root.sharedNodes.get(layoutId);\n }\n promote({ needsReset, transition, preserveFollowOpacity, } = {}) {\n const stack = this.getStack();\n if (stack)\n stack.promote(this, preserveFollowOpacity);\n if (needsReset) {\n this.projectionDelta = undefined;\n this.needsReset = true;\n }\n if (transition)\n this.setOptions({ transition });\n }\n relegate() {\n const stack = this.getStack();\n if (stack) {\n return stack.relegate(this);\n }\n else {\n return false;\n }\n }\n resetSkewAndRotation() {\n const { visualElement } = this.options;\n if (!visualElement)\n return;\n // If there's no detected skew or rotation values, we can early return without a forced render.\n let hasDistortingTransform = false;\n /**\n * An unrolled check for rotation values. Most elements don't have any rotation and\n * skipping the nested loop and new object creation is 50% faster.\n */\n const { latestValues } = visualElement;\n if (latestValues.z ||\n latestValues.rotate ||\n latestValues.rotateX ||\n latestValues.rotateY ||\n latestValues.rotateZ ||\n latestValues.skewX ||\n latestValues.skewY) {\n hasDistortingTransform = true;\n }\n // If there's no distorting values, we don't need to do any more.\n if (!hasDistortingTransform)\n return;\n const resetValues = {};\n if (latestValues.z) {\n resetDistortingTransform(\"z\", visualElement, resetValues, this.animationValues);\n }\n // Check the skew and rotate value of all axes and reset to 0\n for (let i = 0; i < transformAxes.length; i++) {\n resetDistortingTransform(`rotate${transformAxes[i]}`, visualElement, resetValues, this.animationValues);\n resetDistortingTransform(`skew${transformAxes[i]}`, visualElement, resetValues, this.animationValues);\n }\n // Force a render of this element to apply the transform with all skews and rotations\n // set to 0.\n visualElement.render();\n // Put back all the values we reset\n for (const key in resetValues) {\n visualElement.setStaticValue(key, resetValues[key]);\n if (this.animationValues) {\n this.animationValues[key] = resetValues[key];\n }\n }\n // Schedule a render for the next frame. This ensures we won't visually\n // see the element with the reset rotate value applied.\n visualElement.scheduleRender();\n }\n applyProjectionStyles(targetStyle, // CSSStyleDeclaration - doesn't allow numbers to be assigned to properties\n styleProp) {\n if (!this.instance || this.isSVG)\n return;\n if (!this.isVisible) {\n targetStyle.visibility = \"hidden\";\n return;\n }\n const transformTemplate = this.getTransformTemplate();\n if (this.needsReset) {\n this.needsReset = false;\n targetStyle.visibility = \"\";\n targetStyle.opacity = \"\";\n targetStyle.pointerEvents =\n resolveMotionValue(styleProp?.pointerEvents) || \"\";\n targetStyle.transform = transformTemplate\n ? transformTemplate(this.latestValues, \"\")\n : \"none\";\n return;\n }\n const lead = this.getLead();\n if (!this.projectionDelta || !this.layout || !lead.target) {\n if (this.options.layoutId) {\n targetStyle.opacity =\n this.latestValues.opacity !== undefined\n ? this.latestValues.opacity\n : 1;\n targetStyle.pointerEvents =\n resolveMotionValue(styleProp?.pointerEvents) || \"\";\n }\n if (this.hasProjected && !hasTransform(this.latestValues)) {\n targetStyle.transform = transformTemplate\n ? transformTemplate({}, \"\")\n : \"none\";\n this.hasProjected = false;\n }\n return;\n }\n targetStyle.visibility = \"\";\n const valuesToRender = lead.animationValues || lead.latestValues;\n this.applyTransformsToTarget();\n let transform = buildProjectionTransform(this.projectionDeltaWithTransform, this.treeScale, valuesToRender);\n if (transformTemplate) {\n transform = transformTemplate(valuesToRender, transform);\n }\n targetStyle.transform = transform;\n const { x, y } = this.projectionDelta;\n targetStyle.transformOrigin = `${x.origin * 100}% ${y.origin * 100}% 0`;\n if (lead.animationValues) {\n /**\n * If the lead component is animating, assign this either the entering/leaving\n * opacity\n */\n targetStyle.opacity =\n lead === this\n ? valuesToRender.opacity ??\n this.latestValues.opacity ??\n 1\n : this.preserveOpacity\n ? this.latestValues.opacity\n : valuesToRender.opacityExit;\n }\n else {\n /**\n * Or we're not animating at all, set the lead component to its layout\n * opacity and other components to hidden.\n */\n targetStyle.opacity =\n lead === this\n ? valuesToRender.opacity !== undefined\n ? valuesToRender.opacity\n : \"\"\n : valuesToRender.opacityExit !== undefined\n ? valuesToRender.opacityExit\n : 0;\n }\n /**\n * Apply scale correction\n */\n for (const key in scaleCorrectors) {\n if (valuesToRender[key] === undefined)\n continue;\n const { correct, applyTo, isCSSVariable } = scaleCorrectors[key];\n /**\n * Only apply scale correction to the value if we have an\n * active projection transform. Otherwise these values become\n * vulnerable to distortion if the element changes size without\n * a corresponding layout animation.\n */\n const corrected = transform === \"none\"\n ? valuesToRender[key]\n : correct(valuesToRender[key], lead);\n if (applyTo) {\n const num = applyTo.length;\n for (let i = 0; i < num; i++) {\n targetStyle[applyTo[i]] = corrected;\n }\n }\n else {\n // If this is a CSS variable, set it directly on the instance.\n // Replacing this function from creating styles to setting them\n // would be a good place to remove per frame object creation\n if (isCSSVariable) {\n this.options.visualElement.renderState.vars[key] = corrected;\n }\n else {\n targetStyle[key] = corrected;\n }\n }\n }\n /**\n * Disable pointer events on follow components. This is to ensure\n * that if a follow component covers a lead component it doesn't block\n * pointer events on the lead.\n */\n if (this.options.layoutId) {\n targetStyle.pointerEvents =\n lead === this\n ? resolveMotionValue(styleProp?.pointerEvents) || \"\"\n : \"none\";\n }\n }\n clearSnapshot() {\n this.resumeFrom = this.snapshot = undefined;\n }\n // Only run on root\n resetTree() {\n this.root.nodes.forEach((node) => node.currentAnimation?.stop());\n this.root.nodes.forEach(clearMeasurements);\n this.root.sharedNodes.clear();\n }\n };\n}\nfunction updateLayout(node) {\n node.updateLayout();\n}\nfunction notifyLayoutUpdate(node) {\n const snapshot = node.resumeFrom?.snapshot || node.snapshot;\n if (node.isLead() &&\n node.layout &&\n snapshot &&\n node.hasListeners(\"didUpdate\")) {\n const { layoutBox: layout, measuredBox: measuredLayout } = node.layout;\n const { animationType } = node.options;\n const isShared = snapshot.source !== node.layout.source;\n // TODO Maybe we want to also resize the layout snapshot so we don't trigger\n // animations for instance if layout=\"size\" and an element has only changed position\n if (animationType === \"size\") {\n eachAxis((axis) => {\n const axisSnapshot = isShared\n ? snapshot.measuredBox[axis]\n : snapshot.layoutBox[axis];\n const length = calcLength(axisSnapshot);\n axisSnapshot.min = layout[axis].min;\n axisSnapshot.max = axisSnapshot.min + length;\n });\n }\n else if (shouldAnimatePositionOnly(animationType, snapshot.layoutBox, layout)) {\n eachAxis((axis) => {\n const axisSnapshot = isShared\n ? snapshot.measuredBox[axis]\n : snapshot.layoutBox[axis];\n const length = calcLength(layout[axis]);\n axisSnapshot.max = axisSnapshot.min + length;\n /**\n * Ensure relative target gets resized and rerendererd\n */\n if (node.relativeTarget && !node.currentAnimation) {\n node.isProjectionDirty = true;\n node.relativeTarget[axis].max =\n node.relativeTarget[axis].min + length;\n }\n });\n }\n const layoutDelta = createDelta();\n calcBoxDelta(layoutDelta, layout, snapshot.layoutBox);\n const visualDelta = createDelta();\n if (isShared) {\n calcBoxDelta(visualDelta, node.applyTransform(measuredLayout, true), snapshot.measuredBox);\n }\n else {\n calcBoxDelta(visualDelta, layout, snapshot.layoutBox);\n }\n const hasLayoutChanged = !isDeltaZero(layoutDelta);\n let hasRelativeLayoutChanged = false;\n if (!node.resumeFrom) {\n const relativeParent = node.getClosestProjectingParent();\n /**\n * If the relativeParent is itself resuming from a different element then\n * the relative snapshot is not relavent\n */\n if (relativeParent && !relativeParent.resumeFrom) {\n const { snapshot: parentSnapshot, layout: parentLayout } = relativeParent;\n if (parentSnapshot && parentLayout) {\n const relativeSnapshot = createBox();\n calcRelativePosition(relativeSnapshot, snapshot.layoutBox, parentSnapshot.layoutBox);\n const relativeLayout = createBox();\n calcRelativePosition(relativeLayout, layout, parentLayout.layoutBox);\n if (!boxEqualsRounded(relativeSnapshot, relativeLayout)) {\n hasRelativeLayoutChanged = true;\n }\n if (relativeParent.options.layoutRoot) {\n node.relativeTarget = relativeLayout;\n node.relativeTargetOrigin = relativeSnapshot;\n node.relativeParent = relativeParent;\n }\n }\n }\n }\n node.notifyListeners(\"didUpdate\", {\n layout,\n snapshot,\n delta: visualDelta,\n layoutDelta,\n hasLayoutChanged,\n hasRelativeLayoutChanged,\n });\n }\n else if (node.isLead()) {\n const { onExitComplete } = node.options;\n onExitComplete && onExitComplete();\n }\n /**\n * Clearing transition\n * TODO: Investigate why this transition is being passed in as {type: false } from Framer\n * and why we need it at all\n */\n node.options.transition = undefined;\n}\nfunction propagateDirtyNodes(node) {\n /**\n * Increase debug counter for nodes encountered this frame\n */\n if (statsBuffer.value) {\n metrics.nodes++;\n }\n if (!node.parent)\n return;\n /**\n * If this node isn't projecting, propagate isProjectionDirty. It will have\n * no performance impact but it will allow the next child that *is* projecting\n * but *isn't* dirty to just check its parent to see if *any* ancestor needs\n * correcting.\n */\n if (!node.isProjecting()) {\n node.isProjectionDirty = node.parent.isProjectionDirty;\n }\n /**\n * Propagate isSharedProjectionDirty and isTransformDirty\n * throughout the whole tree. A future revision can take another look at\n * this but for safety we still recalcualte shared nodes.\n */\n node.isSharedProjectionDirty || (node.isSharedProjectionDirty = Boolean(node.isProjectionDirty ||\n node.parent.isProjectionDirty ||\n node.parent.isSharedProjectionDirty));\n node.isTransformDirty || (node.isTransformDirty = node.parent.isTransformDirty);\n}\nfunction cleanDirtyNodes(node) {\n node.isProjectionDirty =\n node.isSharedProjectionDirty =\n node.isTransformDirty =\n false;\n}\nfunction clearSnapshot(node) {\n node.clearSnapshot();\n}\nfunction clearMeasurements(node) {\n node.clearMeasurements();\n}\nfunction clearIsLayoutDirty(node) {\n node.isLayoutDirty = false;\n}\nfunction resetTransformStyle(node) {\n const { visualElement } = node.options;\n if (visualElement && visualElement.getProps().onBeforeLayoutMeasure) {\n visualElement.notify(\"BeforeLayoutMeasure\");\n }\n node.resetTransform();\n}\nfunction finishAnimation(node) {\n node.finishAnimation();\n node.targetDelta = node.relativeTarget = node.target = undefined;\n node.isProjectionDirty = true;\n}\nfunction resolveTargetDelta(node) {\n node.resolveTargetDelta();\n}\nfunction calcProjection(node) {\n node.calcProjection();\n}\nfunction resetSkewAndRotation(node) {\n node.resetSkewAndRotation();\n}\nfunction removeLeadSnapshots(stack) {\n stack.removeLeadSnapshot();\n}\nfunction mixAxisDelta(output, delta, p) {\n output.translate = mixNumber(delta.translate, 0, p);\n output.scale = mixNumber(delta.scale, 1, p);\n output.origin = delta.origin;\n output.originPoint = delta.originPoint;\n}\nfunction mixAxis(output, from, to, p) {\n output.min = mixNumber(from.min, to.min, p);\n output.max = mixNumber(from.max, to.max, p);\n}\nfunction mixBox(output, from, to, p) {\n mixAxis(output.x, from.x, to.x, p);\n mixAxis(output.y, from.y, to.y, p);\n}\nfunction hasOpacityCrossfade(node) {\n return (node.animationValues && node.animationValues.opacityExit !== undefined);\n}\nconst defaultLayoutTransition = {\n duration: 0.45,\n ease: [0.4, 0, 0.1, 1],\n};\nconst userAgentContains = (string) => typeof navigator !== \"undefined\" &&\n navigator.userAgent &&\n navigator.userAgent.toLowerCase().includes(string);\n/**\n * Measured bounding boxes must be rounded in Safari and\n * left untouched in Chrome, otherwise non-integer layouts within scaled-up elements\n * can appear to jump.\n */\nconst roundPoint = userAgentContains(\"applewebkit/\") && !userAgentContains(\"chrome/\")\n ? Math.round\n : noop;\nfunction roundAxis(axis) {\n // Round to the nearest .5 pixels to support subpixel layouts\n axis.min = roundPoint(axis.min);\n axis.max = roundPoint(axis.max);\n}\nfunction roundBox(box) {\n roundAxis(box.x);\n roundAxis(box.y);\n}\nfunction shouldAnimatePositionOnly(animationType, snapshot, layout) {\n return (animationType === \"position\" ||\n (animationType === \"preserve-aspect\" &&\n !isNear(aspectRatio(snapshot), aspectRatio(layout), 0.2)));\n}\nfunction checkNodeWasScrollRoot(node) {\n return node !== node.root && node.scroll?.wasRoot;\n}\n\nexport { cleanDirtyNodes, createProjectionNode, mixAxis, mixAxisDelta, mixBox, propagateDirtyNodes };\n","import { addDomEvent } from '../../events/add-dom-event.mjs';\nimport { createProjectionNode } from './create-projection-node.mjs';\n\nconst DocumentProjectionNode = createProjectionNode({\n attachResizeListener: (ref, notify) => addDomEvent(ref, \"resize\", notify),\n measureScroll: () => ({\n x: document.documentElement.scrollLeft || document.body.scrollLeft,\n y: document.documentElement.scrollTop || document.body.scrollTop,\n }),\n checkIsScrollRoot: () => true,\n});\n\nexport { DocumentProjectionNode };\n","import { createProjectionNode } from './create-projection-node.mjs';\nimport { DocumentProjectionNode } from './DocumentProjectionNode.mjs';\n\nconst rootProjectionNode = {\n current: undefined,\n};\nconst HTMLProjectionNode = createProjectionNode({\n measureScroll: (instance) => ({\n x: instance.scrollLeft,\n y: instance.scrollTop,\n }),\n defaultParent: () => {\n if (!rootProjectionNode.current) {\n const documentNode = new DocumentProjectionNode({});\n documentNode.mount(window);\n documentNode.setOptions({ layoutScroll: true });\n rootProjectionNode.current = documentNode;\n }\n return rootProjectionNode.current;\n },\n resetTransform: (instance, value) => {\n instance.style.transform = value !== undefined ? value : \"none\";\n },\n checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === \"fixed\"),\n});\n\nexport { HTMLProjectionNode, rootProjectionNode };\n","import { DragGesture } from '../../gestures/drag/index.mjs';\nimport { PanGesture } from '../../gestures/pan/index.mjs';\nimport { MeasureLayout } from './layout/MeasureLayout.mjs';\nimport { HTMLProjectionNode } from '../../projection/node/HTMLProjectionNode.mjs';\n\nconst drag = {\n pan: {\n Feature: PanGesture,\n },\n drag: {\n Feature: DragGesture,\n ProjectionNode: HTMLProjectionNode,\n MeasureLayout,\n },\n};\n\nexport { drag };\n","import { hover, frame } from 'motion-dom';\nimport { extractEventInfo } from '../events/event-info.mjs';\nimport { Feature } from '../motion/features/Feature.mjs';\n\nfunction handleHoverEvent(node, event, lifecycle) {\n const { props } = node;\n if (node.animationState && props.whileHover) {\n node.animationState.setActive(\"whileHover\", lifecycle === \"Start\");\n }\n const eventName = (\"onHover\" + lifecycle);\n const callback = props[eventName];\n if (callback) {\n frame.postRender(() => callback(event, extractEventInfo(event)));\n }\n}\nclass HoverGesture extends Feature {\n mount() {\n const { current } = this.node;\n if (!current)\n return;\n this.unmount = hover(current, (_element, startEvent) => {\n handleHoverEvent(this.node, startEvent, \"Start\");\n return (endEvent) => handleHoverEvent(this.node, endEvent, \"End\");\n });\n }\n unmount() { }\n}\n\nexport { HoverGesture };\n","import { pipe } from 'motion-utils';\nimport { addDomEvent } from '../events/add-dom-event.mjs';\nimport { Feature } from '../motion/features/Feature.mjs';\n\nclass FocusGesture extends Feature {\n constructor() {\n super(...arguments);\n this.isActive = false;\n }\n onFocus() {\n let isFocusVisible = false;\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 }\n catch (e) {\n isFocusVisible = true;\n }\n if (!isFocusVisible || !this.node.animationState)\n return;\n this.node.animationState.setActive(\"whileFocus\", true);\n this.isActive = true;\n }\n onBlur() {\n if (!this.isActive || !this.node.animationState)\n return;\n this.node.animationState.setActive(\"whileFocus\", false);\n this.isActive = false;\n }\n mount() {\n this.unmount = pipe(addDomEvent(this.node.current, \"focus\", () => this.onFocus()), addDomEvent(this.node.current, \"blur\", () => this.onBlur()));\n }\n unmount() { }\n}\n\nexport { FocusGesture };\n","import { press, frame } from 'motion-dom';\nimport { extractEventInfo } from '../events/event-info.mjs';\nimport { Feature } from '../motion/features/Feature.mjs';\n\nfunction handlePressEvent(node, event, lifecycle) {\n const { props } = node;\n if (node.current instanceof HTMLButtonElement && node.current.disabled) {\n return;\n }\n if (node.animationState && props.whileTap) {\n node.animationState.setActive(\"whileTap\", lifecycle === \"Start\");\n }\n const eventName = (\"onTap\" + (lifecycle === \"End\" ? \"\" : lifecycle));\n const callback = props[eventName];\n if (callback) {\n frame.postRender(() => callback(event, extractEventInfo(event)));\n }\n}\nclass PressGesture extends Feature {\n mount() {\n const { current } = this.node;\n if (!current)\n return;\n this.unmount = press(current, (_element, startEvent) => {\n handlePressEvent(this.node, startEvent, \"Start\");\n return (endEvent, { success }) => handlePressEvent(this.node, endEvent, success ? \"End\" : \"Cancel\");\n }, { useGlobalTarget: this.node.props.globalTapTarget });\n }\n unmount() { }\n}\n\nexport { PressGesture };\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();\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();\nconst fireObserverCallback = (entry) => {\n const callback = observerCallbacks.get(entry.target);\n callback && callback(entry);\n};\nconst fireAllObserverCallbacks = (entries) => {\n entries.forEach(fireObserverCallback);\n};\nfunction initIntersectionObserver({ root, ...options }) {\n const lookupRoot = root || document;\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 const key = JSON.stringify(options);\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(fireAllObserverCallbacks, { root, ...options });\n }\n return rootObservers[key];\n}\nfunction observeIntersection(element, options, callback) {\n const rootInteresectionObserver = initIntersectionObserver(options);\n observerCallbacks.set(element, callback);\n rootInteresectionObserver.observe(element);\n return () => {\n observerCallbacks.delete(element);\n rootInteresectionObserver.unobserve(element);\n };\n}\n\nexport { observeIntersection };\n","import { Feature } from '../Feature.mjs';\nimport { observeIntersection } from './observers.mjs';\n\nconst thresholdNames = {\n some: 0,\n all: 1,\n};\nclass InViewFeature extends Feature {\n constructor() {\n super(...arguments);\n this.hasEnteredView = false;\n this.isInView = false;\n }\n startObserver() {\n this.unmount();\n const { viewport = {} } = this.node.getProps();\n const { root, margin: rootMargin, amount = \"some\", once } = viewport;\n const options = {\n root: root ? root.current : undefined,\n rootMargin,\n threshold: typeof amount === \"number\" ? amount : thresholdNames[amount],\n };\n const onIntersectionUpdate = (entry) => {\n const { isIntersecting } = entry;\n /**\n * If there's been no change in the viewport state, early return.\n */\n if (this.isInView === isIntersecting)\n return;\n this.isInView = isIntersecting;\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 }\n else if (isIntersecting) {\n this.hasEnteredView = true;\n }\n if (this.node.animationState) {\n this.node.animationState.setActive(\"whileInView\", isIntersecting);\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 return observeIntersection(this.node.current, options, onIntersectionUpdate);\n }\n mount() {\n this.startObserver();\n }\n update() {\n if (typeof IntersectionObserver === \"undefined\")\n return;\n const { props, prevProps } = this.node;\n const hasOptionsChanged = [\"amount\", \"margin\", \"root\"].some(hasViewportOptionChanged(props, prevProps));\n if (hasOptionsChanged) {\n this.startObserver();\n }\n }\n unmount() { }\n}\nfunction hasViewportOptionChanged({ viewport = {} }, { viewport: prevViewport = {} } = {}) {\n return (name) => viewport[name] !== prevViewport[name];\n}\n\nexport { InViewFeature };\n","import { HoverGesture } from '../../gestures/hover.mjs';\nimport { FocusGesture } from '../../gestures/focus.mjs';\nimport { PressGesture } from '../../gestures/press.mjs';\nimport { InViewFeature } from './viewport/index.mjs';\n\nconst gestureAnimations = {\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\nexport { gestureAnimations };\n","import { HTMLProjectionNode } from '../../projection/node/HTMLProjectionNode.mjs';\nimport { MeasureLayout } from './layout/MeasureLayout.mjs';\n\nconst layout = {\n layout: {\n ProjectionNode: HTMLProjectionNode,\n MeasureLayout,\n },\n};\n\nexport { layout };\n","import { animations } from '../../../motion/features/animations.mjs';\nimport { drag } from '../../../motion/features/drag.mjs';\nimport { gestureAnimations } from '../../../motion/features/gestures.mjs';\nimport { layout } from '../../../motion/features/layout.mjs';\n\nconst featureBundle = {\n ...animations,\n ...gestureAnimations,\n ...drag,\n ...layout,\n};\n\nexport { featureBundle };\n","import { createDomVisualElement } from '../../dom/create-visual-element.mjs';\nimport { createMotionProxy } from '../create-proxy.mjs';\nimport { featureBundle } from './feature-bundle.mjs';\n\nconst motion = /*@__PURE__*/ createMotionProxy(featureBundle, createDomVisualElement);\n\nexport { motion };\n","import { IcClose } from \"@assets/icons/common\";\nimport { cn } from \"@utils/functions\";\n\nconst ModalHeader = ({\n onClose,\n title,\n headerClassName,\n headerAction,\n}: {\n onClose: () => void;\n title?: string;\n headerClassName?: string;\n headerAction?: React.ReactNode;\n}) => {\n return (\n <div\n className={cn(\n \"p-6 py-4 flex items-center justify-between border-b border-stroke-disabled\",\n headerClassName\n )}\n >\n <div className=\"flex items-center gap-2\">\n <p className=\"font-semibold leading-6 text-text-primary tracking-[-0.24px]\">\n {title}\n </p>\n\n {headerAction}\n </div>\n\n <button onClick={onClose}>\n <IcClose />\n </button>\n </div>\n );\n};\n\nexport default ModalHeader;\n","import { useMemo } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { AnimatePresence, motion } from \"motion/react\";\n\nconst ModalWrapper = ({\n isOpen,\n children,\n className,\n id,\n}: {\n isOpen: boolean;\n children: React.ReactNode;\n className?: string;\n id?: string;\n}) => {\n const container = useMemo(() => document.getElementById(id ?? \"root\"), [id]);\n\n return createPortal(\n <AnimatePresence mode=\"wait\">\n {isOpen && (\n <motion.div\n className={`fixed inset-0 z-50 flex items-center justify-center ${\n className ?? \"\"\n }`}\n onTouchStart={(e) => e.stopPropagation()}\n onScroll={(e) => e.stopPropagation()}\n onClick={(e) => e.stopPropagation()}\n onKeyDown={(e) => e.stopPropagation()}\n >\n <div className=\"size-full overflow-hidden sm:w-limitWidth\">\n {children}\n </div>\n </motion.div>\n )}\n </AnimatePresence>,\n container ?? document.body\n );\n};\n\nexport default ModalWrapper;\n\nexport interface ModalProps {\n children?: React.ReactNode;\n isOpen: boolean;\n onClose: () => void;\n className?: string;\n classNameIosPb?: string;\n header?: React.ReactNode;\n footer?: React.ReactNode;\n disableChangeColorTheme?: boolean;\n isHideHeader?: boolean;\n}\n\nexport const ModalTransition = {\n transition: { duration: 0.3 },\n};\n","import { cn } from \"@utils/functions\";\nimport { motion } from \"motion/react\";\nimport ModalHeader from \"./modal-header\";\nimport ModalWrapper from \"./modal-wrapper\";\n\nconst ModalTransition = {\n transition: { duration: 0.3 },\n};\n\nconst ModalZoom = (props: ModalProps) => {\n const {\n isOpen,\n onClose,\n children,\n className,\n title,\n footer,\n modalClassName,\n headerClassName,\n headerAction,\n } = props;\n return (\n <ModalWrapper isOpen={isOpen}>\n <motion.div\n initial={{ opacity: 0 }}\n animate={{ opacity: 1 }}\n exit={{ opacity: 0 }}\n {...ModalTransition}\n className={`flex size-full items-center justify-center bg-overlay pt-safe-area-inset-top`}\n onClick={(e) => {\n onClose();\n e.stopPropagation();\n }}\n >\n <motion.div\n {...ModalTransition}\n onClick={(e) => e.stopPropagation()}\n className={cn(\n \"relative h-fit max-h-[80%] max-w-[80%] bg-white rounded-2xl flex flex-col overflow-hidden\",\n modalClassName\n )}\n >\n {title && (\n <ModalHeader\n onClose={onClose}\n title={title}\n headerClassName={headerClassName}\n headerAction={headerAction}\n />\n )}\n <div className={cn(\"overflow-y-auto p-6 flex-1\", className)}>\n {children}\n </div>\n {footer && <div className=\"sticky bottom-0\">{footer}</div>}\n </motion.div>\n </motion.div>\n </ModalWrapper>\n );\n};\n\nexport default ModalZoom;\n","import {\n useCompany,\n useUser,\n type useCompanyType,\n type useUserType,\n} from \"@fctc/widget-logic/hooks\";\nimport { useEnv } from \"@fctc/widget-logic/provider\";\n\nimport { createContext, useContext, useMemo } from \"react\";\n\ntype PosAppProviderType = {\n user: useUserType;\n company: useCompanyType;\n userProfile: any;\n};\n\nconst PosAppProviderInitialValue: PosAppProviderType = {\n user: {} as useUserType,\n company: {} as useCompanyType,\n userProfile: {},\n};\nconst ReactContext = createContext<PosAppProviderType>(\n PosAppProviderInitialValue\n);\n\nconst PosAppProvider = ({ children }: { children: React.ReactNode }) => {\n const { env } = useEnv();\n const user = useUser({ service: env.default_service });\n const company = useCompany({ service: env.default_service });\n\n const userProfile = useMemo(() => {\n return user?.userProfile?.data;\n }, [user]);\n\n return (\n <ReactContext.Provider\n value={{\n user,\n company,\n userProfile,\n }}\n >\n {children}\n </ReactContext.Provider>\n );\n};\nexport default PosAppProvider;\nexport const usePosAppProvider = () => {\n const context = useContext(ReactContext);\n\n if (!context) {\n return PosAppProviderInitialValue;\n }\n\n return context;\n};\n","export const Line = () => {\n return (\n <svg\n viewBox=\"0 0 305 1\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n className=\"w-full h-px\"\n preserveAspectRatio=\"none\"\n >\n <line\n y1=\"0.5\"\n x2=\"305\"\n y2=\"0.5\"\n stroke=\"#424242\"\n strokeOpacity=\"0.16\"\n strokeDasharray=\"4 4\"\n />\n </svg>\n );\n};\n","import { cn } from \"@utils/functions\";\n\nconst ButtonAction = ({\n id,\n onClick,\n iconSrc,\n children,\n className,\n text,\n disabled,\n type = \"button\",\n textClassName,\n style,\n}: {\n id?: string;\n onClick?: (e?: any) => void;\n iconSrc?: React.ReactNode;\n className?: string;\n disabled?: boolean;\n text?: string;\n children?: React.ReactNode;\n type?: \"button\" | \"submit\" | \"reset\" | undefined;\n textClassName?: string;\n style?: React.CSSProperties;\n}) => {\n return (\n <button\n id={id}\n type={type}\n onClick={onClick}\n disabled={disabled}\n className={cn(\"button\", className)}\n style={style}\n >\n {iconSrc}\n {text && (\n <p className={cn(\"line-clamp-1 font-semibold\", textClassName)}>\n {text}\n </p>\n )}\n {children}\n </button>\n );\n};\n\nexport default ButtonAction;\n","type TStage = {\n alert_timer: number;\n color: string;\n display_name: string;\n id: number;\n name: string;\n sequence: number;\n write_date: string;\n icon_url: string;\n};\n\ntype TProps = {\n stages: TStage[];\n};\n\nconst KitchenStatus = (props: TProps) => {\n if (!props?.stages?.length || props?.stages?.length === 0) return null;\n\n const imgUrl = (iconUrl: string) => {\n const url = `https://sme-api-dev.atomsolution.vn/wesap/${iconUrl}`;\n\n return url;\n };\n\n return (\n <div className=\"grid grid-cols-2 gap-2\">\n {props.stages.map((stage: TStage, index) => {\n return (\n <div\n style={{\n backgroundColor: stage.color + \"33\",\n }}\n key={index}\n className=\"flex flex-col gap-1 p-2 rounded-lg\"\n >\n <div className=\"flex items-center justify-between\">\n {/* <p\n style={{\n color: stage.color,\n }}\n className=\"text-lg font-semibold leading-[26px]\"\n >\n {stage.sequence}\n </p> */}\n\n <img\n src={imgUrl(stage.icon_url)}\n className=\"w-6 aspect-square \"\n />\n </div>\n\n <p\n style={{\n color: stage.color,\n }}\n className=\"text-sm font-medium leading-5 tracking-[-0.2px]\"\n >\n {stage.display_name}\n </p>\n </div>\n );\n })}\n </div>\n );\n};\n\nexport default KitchenStatus;\n\nconst StatusStyle = {};\n","import { Line } from \"@assets/icons/customer-view-icon\";\nimport ButtonAction from \"@components/common/button-action\";\nimport KitchenStatus from \"@components/kitchen-management/kitchen-status\";\nimport { POSPath } from \"@constants/routes.constants\";\nimport { useMemo } from \"react\";\nimport { useTranslation } from \"react-i18next\";\nimport { generatePath, useNavigate } from \"react-router-dom\";\n\ntype TProps = {\n columns: any[];\n row: any;\n onClickRow: any;\n};\n\nconst KitchenTemplate = ({ columns, row, onClickRow }: TProps) => {\n const navigate = useNavigate();\n const kitchenId = useMemo(() => row[\"id\"], [row]);\n const { t } = useTranslation();\n\n const onNavigateToOrderList = () => {\n sessionStorage.setItem(\n \"enter_pincode\",\n window.location.href.split(\"console\")[1]\n );\n localStorage.setItem(\"backUrl\", window.location.href.split(\"console\")[1]);\n navigate(\n `${generatePath(POSPath.ORDERS_KITCHEN_MANAGEMENT, { kitchenId })}?`\n );\n };\n\n return (\n <div\n style={{\n boxShadow: \"0 2px 4px 0 rgba(27, 28, 29, 0.04)\",\n }}\n className=\"p-4 rounded-2xl bg-white flex flex-col gap-4 h-fit border border-stroke-disabled\"\n onClick={() => onClickRow(columns, row)}\n >\n <div className=\"flex flex-col gap-2\">\n <p className=\"font-semibold leading-6 tracking-[-0.24px] text-strong-950\">\n {row[\"name\"]}\n </p>\n <KitchenStatus stages={row[\"stage_ids\"]} />\n </div>\n\n <Line />\n\n <ButtonAction\n onClick={(e) => {\n e.stopPropagation();\n onNavigateToOrderList();\n }}\n className=\"rounded-[6px] bg-primary h-11\"\n text={t(\"detail_button\")}\n />\n </div>\n );\n};\n\nexport default KitchenTemplate;\n","////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location<State = any> extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: State;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial<Path>;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n /**\n * The last action that modified the current location. This will always be\n * Action.Pop when a history instance is first created. This value is mutable.\n */\n readonly action: Action;\n\n /**\n * The current location. This value is mutable.\n */\n readonly location: Location;\n\n /**\n * Returns a valid href for the given `to` value that may be used as\n * the value of an <a href> attribute.\n *\n * @param to - The destination URL\n */\n createHref(to: To): string;\n\n /**\n * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial<Location>;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route (<Route path=\"*\">) since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant<T>(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly<Location> {\n let location: Readonly<Location> = {\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\",\n ...(typeof to === \"string\" ? parsePath(to) : to),\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: (to && (to as Location).key) || key || createKey(),\n };\n return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial<Path>) {\n if (search && search !== \"?\")\n pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\")\n pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial<Path> {\n let parsedPath: Partial<Path> = {};\n\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n window?: Window;\n v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n createHref: (window: Window, to: To) => string,\n validateLocation: ((location: Location, to: To) => void) | null,\n options: UrlHistoryOptions = {}\n): UrlHistory {\n let { window = document.defaultView!, v5Compat = false } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n // Treating this as a full URL will strip any trailing spaces so we need to\n // pre-encode them since they might be part of a matching splat param from\n // an ancestor route\n href = href.replace(/ $/, \"%20\");\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: unknown;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n // We keep the raw Response for redirects so we can return it verbatim\n response: Response;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n type: ResultType.error;\n error: unknown;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `<Form>`,\n * useSubmit(), `<fetcher.Form>`, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude<FormMethod, \"get\">;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude<V7_FormMethod, \"GET\">;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\n };\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs<Context> {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs<Context = any>\n extends DataFunctionArgs<Context> {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs<Context = any>\n extends DataFunctionArgs<Context> {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable<unknown> | null;\n\ntype DataFunctionReturnValue = Promise<DataFunctionValue> | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction<Context = any> = {\n (\n args: LoaderFunctionArgs<Context>,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction<Context = any> {\n (\n args: ActionFunctionArgs<Context>,\n handlerCtx?: unknown\n ): DataFunctionReturnValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n actionStatus?: number;\n actionResult?: any;\n defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\nexport interface DataStrategyMatch\n extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {\n shouldLoad: boolean;\n resolve: (\n handlerOverride?: (\n handler: (ctx?: unknown) => DataFunctionReturnValue\n ) => DataFunctionReturnValue\n ) => Promise<DataStrategyResult>;\n}\n\nexport interface DataStrategyFunctionArgs<Context = any>\n extends DataFunctionArgs<Context> {\n matches: DataStrategyMatch[];\n fetcherKey: string | null;\n}\n\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface DataStrategyResult {\n type: \"data\" | \"error\";\n result: unknown; // data, Error, Response, DeferredData, DataWithResponseInit\n}\n\nexport interface DataStrategyFunction {\n (args: DataStrategyFunctionArgs): Promise<Record<string, DataStrategyResult>>;\n}\n\nexport type AgnosticPatchRoutesOnNavigationFunctionArgs<\n O extends AgnosticRouteObject = AgnosticRouteObject,\n M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = {\n signal: AbortSignal;\n path: string;\n matches: M[];\n fetcherKey: string | undefined;\n patch: (routeId: string | null, children: O[]) => void;\n};\n\nexport type AgnosticPatchRoutesOnNavigationFunction<\n O extends AgnosticRouteObject = AgnosticRouteObject,\n M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = (\n opts: AgnosticPatchRoutesOnNavigationFunctionArgs<O, M>\n) => void | Promise<void>;\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record<string, any>;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set<ImmutableRouteKey>([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne<T, Key = keyof T> = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit<T, K> & Required<Pick<T, K>> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction<R extends AgnosticRouteObject> {\n (): Promise<RequireOne<Omit<R, ImmutableRouteKey>>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n caseSensitive?: boolean;\n path?: string;\n id?: string;\n loader?: LoaderFunction | boolean;\n action?: ActionFunction | boolean;\n hasErrorBoundary?: boolean;\n shouldRevalidate?: ShouldRevalidateFunction;\n handle?: any;\n lazy?: LazyRouteFunction<AgnosticBaseRouteObject>;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record<string, AgnosticDataRouteObject | undefined>;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam<Path extends string> =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam<L> | _PathParam<R>\n : // find params after `:`\n Path extends `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam<Path extends string> =\n // check if path is just a wildcard\n Path extends \"*\" | \"/*\"\n ? \"*\"\n : // look for wildcard at the end of the path\n Path extends `${infer Rest}/*`\n ? \"*\" | _PathParam<Rest>\n : // look for params in the absence of wildcards\n _PathParam<Path>;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise, return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey<Segment extends string> =\n // if you could not find path params, fallback to `string`\n [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params<Key extends string = string> = {\n readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params<ParamKey>;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The route object that was used to match.\n */\n route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {}\n\nfunction isIndexRoute(\n route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n routes: AgnosticRouteObject[],\n mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: string[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, String(index)];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(\n route.index !== true || !route.children,\n `Cannot specify children on an index route`\n );\n invariant(\n !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/v6/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial<Location> | string,\n basename = \"/\"\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n return matchRoutesImpl(routes, locationArg, basename, false);\n}\n\nexport function matchRoutesImpl<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial<Location> | string,\n basename: string,\n allowPartial: boolean\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n let location =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n let pathname = stripBasename(location.pathname || \"/\", basename);\n\n if (pathname == null) {\n return null;\n }\n\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n\n let matches = null;\n for (let i = 0; matches == null && i < branches.length; ++i) {\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n let decoded = decodePath(pathname);\n matches = matchRouteBranch<string, RouteObjectType>(\n branches[i],\n decoded,\n allowPartial\n );\n }\n\n return matches;\n}\n\nexport interface UIMatch<Data = unknown, Handle = unknown> {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: Data;\n handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UIMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle,\n };\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta<RouteObjectType>[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch<RouteObjectType>[] = [],\n parentsMeta: RouteMeta<RouteObjectType>[] = [],\n parentPath = \"\"\n): RouteBranch<RouteObjectType>[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta<RouteObjectType> = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch<RouteObjectType>,\n pathname: string,\n allowPartial = false\n): AgnosticRouteMatch<ParamKey, RouteObjectType>[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch<ParamKey, RouteObjectType>[] = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname =\n matchedPathname === \"/\"\n ? pathname\n : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath(\n { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n remainingPathname\n );\n\n let route = meta.route;\n\n if (\n !match &&\n end &&\n allowPartial &&\n !routesMeta[routesMeta.length - 1].route.index\n ) {\n match = matchPath(\n {\n path: meta.relativePath,\n caseSensitive: meta.caseSensitive,\n end: false,\n },\n remainingPathname\n );\n }\n\n if (!match) {\n return null;\n }\n\n Object.assign(matchedParams, match.params);\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params<ParamKey>,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(\n joinPaths([matchedPathname, match.pathnameBase])\n ),\n route,\n });\n\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n\n return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/v6/utils/generate-path\n */\nexport function generatePath<Path extends string>(\n originalPath: Path,\n params: {\n [key in PathParam<Path>]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam<Path>;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam<Path>];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern<Path extends string = string> {\n /**\n * A string to match against a URL pathname. May contain `:id`-style segments\n * to indicate placeholders for dynamic parameters. May also end with `/*` to\n * indicate matching the rest of the URL pathname.\n */\n path: Path;\n /**\n * Should be `true` if the static portions of the `path` should be matched in\n * the same case.\n */\n caseSensitive?: boolean;\n /**\n * Should be `true` if this pattern should match the entire URL pathname.\n */\n end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch<ParamKey extends string = string> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params<ParamKey>;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The pattern that was used to match.\n */\n pattern: PathPattern;\n}\n\ntype Mutable<T> = {\n -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/v6/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey<Path>,\n Path extends string\n>(\n pattern: PathPattern<Path> | Path,\n pathname: string\n): PathMatch<ParamKey> | null {\n if (typeof pattern === \"string\") {\n pattern = { path: pattern, caseSensitive: false, end: true };\n }\n\n let [matcher, compiledParams] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = compiledParams.reduce<Mutable<Params>>(\n (memo, { paramName, isOptional }, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n }\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, CompiledPathParam[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let params: CompiledPathParam[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(\n /\\/:([\\w-]+)(\\?)?/g,\n (_: string, paramName: string, isOptional) => {\n params.push({ paramName, isOptional: isOptional != null });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n }\n );\n\n if (path.endsWith(\"*\")) {\n params.push({ paramName: \"*\" });\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, params];\n}\n\nexport function decodePath(value: string) {\n try {\n return value\n .split(\"/\")\n .map((v) => decodeURIComponent(v).replace(/\\//g, \"%2F\"))\n .join(\"/\");\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n pathname: string,\n basename: string\n): string | null {\n if (basename === \"/\") return pathname;\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\")\n ? basename.length - 1\n : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n\n return pathname.slice(startIndex) || \"/\";\n}\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\nexport const isAbsoluteUrl = (url: string) => ABSOLUTE_URL_REGEX.test(url);\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/v6/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\",\n } = typeof to === \"string\" ? parsePath(to) : to;\n\n let pathname: string;\n if (toPathname) {\n if (isAbsoluteUrl(toPathname)) {\n pathname = toPathname;\n } else {\n if (toPathname.includes(\"//\")) {\n let oldPathname = toPathname;\n toPathname = toPathname.replace(/\\/\\/+/g, \"/\");\n warning(\n false,\n `Pathnames cannot have embedded double slashes - normalizing ` +\n `${oldPathname} -> ${toPathname}`\n );\n }\n if (toPathname.startsWith(\"/\")) {\n pathname = resolvePathname(toPathname.substring(1), \"/\");\n } else {\n pathname = resolvePathname(toPathname, fromPathname);\n }\n }\n } else {\n pathname = fromPathname;\n }\n\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash),\n };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n\n relativeSegments.forEach((segment) => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n char: string,\n field: string,\n dest: string,\n path: Partial<Path>\n) {\n return (\n `Cannot include a '${char}' character in a manually specified ` +\n `\\`to.${field}\\` field [${JSON.stringify(\n path\n )}]. Please separate it out to the ` +\n `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n `a string in <Link to=\"...\"> and the router will parse it for you.`\n );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * <Route path=\"/\">\n * <Route path=\"accounts\" element={<Link to=\"..\"}>\n * </Route>\n *\n * <Route path=\"/\">\n * <Route path=\"accounts\">\n * <Route element={<AccountsLayout />}> // <-- Does not contribute\n * <Route index element={<Link to=\"..\"} /> // <-- Does not contribute\n * </Route\n * </Route>\n * </Route>\n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n let pathMatches = getPathContributingMatches(matches);\n\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) =>\n idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase\n );\n }\n\n return pathMatches.map((match) => match.pathnameBase);\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial<Path>;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = { ...toArg };\n\n invariant(\n !to.pathname || !to.pathname.includes(\"?\"),\n getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n );\n invariant(\n !to.pathname || !to.pathname.includes(\"#\"),\n getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n );\n invariant(\n !to.search || !to.search.includes(\"#\"),\n getInvalidPathError(\"#\", \"search\", \"hash\", to)\n );\n }\n\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n let from: string;\n\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `<Link to>` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how <a href> works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n !search || search === \"?\"\n ? \"\"\n : search.startsWith(\"?\")\n ? search\n : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = <Data>(\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n *\n * @deprecated The `json` method is deprecated in favor of returning raw objects.\n * This method will be removed in v7.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n\n return new Response(JSON.stringify(data), {\n ...responseInit,\n headers,\n });\n};\n\nexport class DataWithResponseInit<D> {\n type: string = \"DataWithResponseInit\";\n data: D;\n init: ResponseInit | null;\n\n constructor(data: D, init?: ResponseInit) {\n this.data = data;\n this.init = init || null;\n }\n}\n\n/**\n * Create \"responses\" that contain `status`/`headers` without forcing\n * serialization into an actual `Response` - used by Remix single fetch\n */\nexport function data<D>(data: D, init?: number | ResponseInit) {\n return new DataWithResponseInit(\n data,\n typeof init === \"number\" ? { status: init } : init\n );\n}\n\nexport interface TrackedPromise extends Promise<any> {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeysSet: Set<string> = new Set<string>();\n private controller: AbortController;\n private abortPromise: Promise<void>;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record<string, unknown>;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record<string, unknown>, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise<unknown> | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record<string, unknown>,\n init?: number | ResponseInit\n) => DeferredData;\n\n/**\n * @deprecated The `defer` method is deprecated in favor of returning raw\n * objects. This method will be removed in v7.\n */\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n\n/**\n * A redirect response that will perform a `history.replaceState` instead of a\n * `history.pushState` for client-side navigation redirects.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const replace: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Replace\", \"true\");\n return response;\n};\n\nexport type ErrorResponse = {\n status: number;\n statusText: string;\n data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n private error?: Error;\n private internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n DataStrategyMatch,\n AgnosticRouteObject,\n DataResult,\n DataStrategyFunction,\n DataStrategyFunctionArgs,\n DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n DataStrategyResult,\n ImmutableRouteKey,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\n AgnosticPatchRoutesOnNavigationFunction,\n DataWithResponseInit,\n} from \"./utils\";\nimport {\n ErrorResponseImpl,\n ResultType,\n convertRouteMatchToUiMatch,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n getResolveToMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n matchRoutesImpl,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record<string, number>,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise<void>;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher<TData = any>(key: string): Fetcher<TData>;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete the fetcher for a given key\n * @param key\n */\n deleteFetcher(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE DO NOT USE\n *\n * Patch additional children routes into an existing parent route\n * @param routeId The parent route id or a callback function accepting `patch`\n * to perform batch patching\n * @param children The additional children routes\n */\n patchRoutes(routeId: string | null, children: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map<string, AbortController>;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map<string, DeferredData>;\n}\n\n/**\n * State maintained internally by the router. During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\n\n /**\n * The current location reflected by the router\n */\n location: Location;\n\n /**\n * The current set of route matches\n */\n matches: AgnosticDataRouteMatch[];\n\n /**\n * Tracks whether we've completed our initial data load\n */\n initialized: boolean;\n\n /**\n * Current scroll position we should start at for a new view\n * - number -> scroll position to restore to\n * - false -> do not restore scroll at all (used during submissions)\n * - null -> don't have a saved position, scroll to hash or top of page\n */\n restoreScrollPosition: number | false | null;\n\n /**\n * Indicate whether this navigation should skip resetting the scroll position\n * if we are unable to restore the scroll position\n */\n preventScrollReset: boolean;\n\n /**\n * Tracks the state of the current navigation\n */\n navigation: Navigation;\n\n /**\n * Tracks any in-progress revalidations\n */\n revalidation: RevalidationState;\n\n /**\n * Data from the loaders for the current matches\n */\n loaderData: RouteData;\n\n /**\n * Data from the action for the current matches\n */\n actionData: RouteData | null;\n\n /**\n * Errors caught from loaders for the current matches\n */\n errors: RouteData | null;\n\n /**\n * Map of current fetchers\n */\n fetchers: Map<string, Fetcher>;\n\n /**\n * Map of current blockers\n */\n blockers: Map<string, Blocker>;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick<RouterState, \"loaderData\" | \"actionData\" | \"errors\">\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_partialHydration: boolean;\n v7_prependBasename: boolean;\n v7_relativeSplatPath: boolean;\n v7_skipActionErrorRevalidation: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial<FutureConfig>;\n hydrationData?: HydrationState;\n window?: Window;\n dataStrategy?: DataStrategyFunction;\n patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record<string, Headers>;\n actionHeaders: Record<string, Headers>;\n activeDeferreds: Record<string, DeferredData> | null;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n dataStrategy?: DataStrategyFunction;\n }\n ): Promise<StaticHandlerContext | Response>;\n queryRoute(\n request: Request,\n opts?: {\n routeId?: string;\n requestContext?: unknown;\n dataStrategy?: DataStrategyFunction;\n }\n ): Promise<any>;\n}\n\ntype ViewTransitionOpts = {\n currentLocation: Location;\n nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (\n state: RouterState,\n opts: {\n deletedFetchers: string[];\n viewTransitionOpts?: ViewTransitionOpts;\n flushSync: boolean;\n }\n ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates<TData = any> = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n };\n};\n\nexport type Fetcher<TData = any> =\n FetcherStates<TData>[keyof FetcherStates<TData>];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\ntype PendingActionResult = [string, SuccessResult | ErrorResult];\n\ninterface HandleActionResult extends ShortCircuitable {\n /**\n * Route matches which may have been updated from fog of war discovery\n */\n matches?: RouterState[\"matches\"];\n /**\n * Tuple for the returned or thrown value from the current action. The routeId\n * is the action route for success and the bubbled boundary route for errors.\n */\n pendingActionResult?: PendingActionResult;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n /**\n * Route matches which may have been updated from fog of war discovery\n */\n matches?: RouterState[\"matches\"];\n /**\n * loaderData returned from the current set of loaders\n */\n loaderData?: RouterState[\"loaderData\"];\n /**\n * errors thrown from the current set of loaders\n */\n errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set<MutationFormMethod>(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set<FormMethod>(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;\n let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;\n\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n v7_skipActionErrorRevalidation: false,\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set<RouterSubscriber>();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record<string, number> | null = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition: GetScrollPositionFunction | null = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from <ScrollRestoration /> until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialMatchesIsFOW = false;\n let initialErrors: RouteData | null = null;\n\n if (initialMatches == null && !patchRoutesOnNavigationImpl) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and\n // our initial match is a splat route, clear them out so we run through lazy\n // discovery on hydration in case there's a more accurate lazy route match.\n // In SSR apps (with `hydrationData`), we expect that the server will send\n // up the proper matched routes so we don't want to run lazy discovery on\n // initial hydration and want to hydrate into the splat route.\n if (initialMatches && !init.hydrationData) {\n let fogOfWar = checkFogOfWar(\n initialMatches,\n dataRoutes,\n init.history.location.pathname\n );\n if (fogOfWar.active) {\n initialMatches = null;\n }\n }\n\n let initialized: boolean;\n if (!initialMatches) {\n initialized = false;\n initialMatches = [];\n\n // If partial hydration and fog of war is enabled, we will be running\n // `patchRoutesOnNavigation` during hydration so include any partial matches as\n // the initial matches so we can properly render `HydrateFallback`'s\n if (future.v7_partialHydration) {\n let fogOfWar = checkFogOfWar(\n null,\n dataRoutes,\n init.history.location.pathname\n );\n if (fogOfWar.active && fogOfWar.matches) {\n initialMatchesIsFOW = true;\n initialMatches = fogOfWar.matches;\n }\n }\n } else if (initialMatches.some((m) => m.route.lazy)) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!initialMatches.some((m) => m.route.loader)) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n // If errors exist, don't consider routes below the boundary\n if (errors) {\n let idx = initialMatches.findIndex(\n (m) => errors![m.route.id] !== undefined\n );\n initialized = initialMatches\n .slice(0, idx + 1)\n .every((m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors));\n } else {\n initialized = initialMatches.every(\n (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)\n );\n }\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\n }\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions: Map<string, Set<string>> = new Map<\n string,\n Set<string>\n >();\n\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener: (() => void) | null = null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: Set<string> = new Set();\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map<string, AbortController>();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map<string, number>();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set<string>();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map<string, FetchLoadMatch>();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map<string, number>();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set<string>();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map<string, DeferredData>();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map<string, BlockerFunction>();\n\n // Map of pending patchRoutesOnNavigation() promises (keyed by path/matches) so\n // that we only kick them off once for a given combo\n let pendingPatchRoutes = new Map<\n string,\n ReturnType<AgnosticPatchRoutesOnNavigationFunction>\n >();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let unblockBlockerHistoryUpdate: (() => void) | undefined = undefined;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (unblockBlockerHistoryUpdate) {\n unblockBlockerHistoryUpdate();\n unblockBlockerHistoryUpdate = undefined;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n let nextHistoryUpdatePromise = new Promise<void>((resolve) => {\n unblockBlockerHistoryUpdate = resolve;\n });\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked, after the url\n // restoration is also complete. See:\n // https://github.com/remix-run/react-router/issues/11613\n nextHistoryUpdatePromise.then(() => init.history.go(delta));\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () =>\n persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () =>\n routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location, {\n initialHydration: true,\n });\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(\n newState: Partial<RouterState>,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n\n // Remove any lingering deleted fetchers that have already been removed\n // from state.fetchers\n deletedFetchers.forEach((key) => {\n if (!state.fetchers.has(key) && !fetchControllers.has(key)) {\n deletedFetchersKeys.push(key);\n }\n });\n\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach((subscriber) =>\n subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n viewTransitionOpts: opts.viewTransitionOpts,\n flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n } else {\n // We already called deleteFetcher() on these, can remove them from this\n // Set now that we've handed the keys off to the data layer\n deletedFetchersKeys.forEach((key) => deletedFetchers.delete(key));\n }\n }\n\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(\n location: Location,\n newState: Partial<Omit<RouterState, \"action\" | \"location\" | \"navigation\">>,\n { flushSync }: { flushSync?: boolean } = {}\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n // Commit any in-flight routes at the end of the HMR revalidation \"navigation\"\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === HistoryAction.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location,\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set<string>([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n }\n\n updateState(\n {\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n },\n {\n viewTransitionOpts,\n flushSync: flushSync === true,\n }\n );\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n }\n\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(\n to: number | To | null,\n opts?: RouterNavigateOptions\n ): Promise<void> {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n future.v7_relativeSplatPath,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.flushSync) === true;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.viewTransition,\n flushSync,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n {\n overrideNavigation: state.navigation,\n // Proxy through any rending view transition\n enableViewTransition: pendingViewTransitionEnabled === true,\n }\n );\n }\n\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(\n historyAction: HistoryAction,\n location: Location,\n opts?: {\n initialHydration?: boolean;\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponseImpl;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n enableViewTransition?: boolean;\n flushSync?: boolean;\n }\n ): Promise<void> {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches =\n opts?.initialHydration &&\n state.matches &&\n state.matches.length > 0 &&\n !initialMatchesIsFOW\n ? // `matchRoutes()` has already been called if we're in here via `router.initialize()`\n state.matches\n : matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial hydration will always\n // be \"same hash\". For example, on /page#hash and submit a <Form method=\"post\">\n // which will default to a navigation to /page\n if (\n matches &&\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches }, { flushSync });\n return;\n }\n\n let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let { error, notFoundMatches, route } = handleNavigational404(\n location.pathname\n );\n completeNavigation(\n location,\n {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n },\n { flushSync }\n );\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let pendingActionResult: PendingActionResult | undefined;\n\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingActionResult = [\n findNearestBoundary(matches).route.id,\n { type: ResultType.error, error: opts.pendingError },\n ];\n } else if (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\n // Call action if we received an action submission\n let actionResult = await handleAction(\n request,\n location,\n opts.submission,\n matches,\n fogOfWar.active,\n { replace: opts.replace, flushSync }\n );\n\n if (actionResult.shortCircuited) {\n return;\n }\n\n // If we received a 404 from handleAction, it's because we couldn't lazily\n // discover the destination route so we don't want to call loaders\n if (actionResult.pendingActionResult) {\n let [routeId, result] = actionResult.pendingActionResult;\n if (\n isErrorResult(result) &&\n isRouteErrorResponse(result.error) &&\n result.error.status === 404\n ) {\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches: actionResult.matches,\n loaderData: {},\n errors: {\n [routeId]: result.error,\n },\n });\n return;\n }\n }\n\n matches = actionResult.matches || matches;\n pendingActionResult = actionResult.pendingActionResult;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n // No need to do fog of war matching again on loader execution\n fogOfWar.active = false;\n\n // Create a GET request for the loaders\n request = createClientSideRequest(\n init.history,\n request.url,\n request.signal\n );\n }\n\n // Call loaders\n let {\n shortCircuited,\n matches: updatedMatches,\n loaderData,\n errors,\n } = await handleLoaders(\n request,\n location,\n matches,\n fogOfWar.active,\n loadingNavigation,\n opts && opts.submission,\n opts && opts.fetcherSubmission,\n opts && opts.replace,\n opts && opts.initialHydration === true,\n flushSync,\n pendingActionResult\n );\n\n if (shortCircuited) {\n return;\n }\n\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches: updatedMatches || matches,\n ...getActionDataForCommit(pendingActionResult),\n loaderData,\n errors,\n });\n }\n\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(\n request: Request,\n location: Location,\n submission: Submission,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n opts: { replace?: boolean; flushSync?: boolean } = {}\n ): Promise<HandleActionResult> {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n matches,\n location.pathname,\n request.signal\n );\n if (discoverResult.type === \"aborted\") {\n return { shortCircuited: true };\n } else if (discoverResult.type === \"error\") {\n let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n .route.id;\n return {\n matches: discoverResult.partialMatches,\n pendingActionResult: [\n boundaryId,\n {\n type: ResultType.error,\n error: discoverResult.error,\n },\n ],\n };\n } else if (!discoverResult.matches) {\n let { notFoundMatches, error, route } = handleNavigational404(\n location.pathname\n );\n return {\n matches: notFoundMatches,\n pendingActionResult: [\n route.id,\n {\n type: ResultType.error,\n error,\n },\n ],\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n let results = await callDataStrategy(\n \"action\",\n state,\n request,\n [actionMatch],\n matches,\n null\n );\n result = results[actionMatch.route.id];\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n let location = normalizeRedirectLocation(\n result.response.headers.get(\"Location\")!,\n new URL(request.url),\n basename\n );\n replace = location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(request, result, true, {\n submission,\n replace,\n });\n return { shortCircuited: true };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n // By default, all submissions to the current location are REPLACE\n // navigations, but if the action threw an error that'll be rendered in\n // an errorElement, we fall back to PUSH so that the user can use the\n // back button to get back to the pre-submission form location to try\n // again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n matches,\n pendingActionResult: [boundaryMatch.route.id, result],\n };\n }\n\n return {\n matches,\n pendingActionResult: [actionMatch.route.id, result],\n };\n }\n\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: boolean,\n pendingActionResult?: PendingActionResult\n ): Promise<HandleLoadersResult> {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n // If we have partialHydration enabled, then don't update the state for the\n // initial data load since it's not a \"navigation\"\n let shouldUpdateNavigationState =\n !isUninterruptedRevalidation &&\n (!future.v7_partialHydration || !initialHydration);\n\n // When fog of war is enabled, we enter our `loading` state earlier so we\n // can discover new routes during the `loading` state. We skip this if\n // we've already run actions since we would have done our matching already.\n // If the children() function threw then, we want to proceed with the\n // partial matches it discovered.\n if (isFogOfWar) {\n if (shouldUpdateNavigationState) {\n let actionData = getUpdatedActionData(pendingActionResult);\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData !== undefined ? { actionData } : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n let discoverResult = await discoverRoutes(\n matches,\n location.pathname,\n request.signal\n );\n\n if (discoverResult.type === \"aborted\") {\n return { shortCircuited: true };\n } else if (discoverResult.type === \"error\") {\n let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n .route.id;\n return {\n matches: discoverResult.partialMatches,\n loaderData: {},\n errors: {\n [boundaryId]: discoverResult.error,\n },\n };\n } else if (!discoverResult.matches) {\n let { error, notFoundMatches, route } = handleNavigational404(\n location.pathname\n );\n return {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n future.v7_partialHydration && initialHydration === true,\n future.v7_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionResult\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(\n location,\n {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors:\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? { [pendingActionResult[0]]: pendingActionResult[1].error }\n : null,\n ...getActionDataForCommit(pendingActionResult),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n },\n { flushSync }\n );\n return { shortCircuited: true };\n }\n\n if (shouldUpdateNavigationState) {\n let updates: Partial<RouterState> = {};\n if (!isFogOfWar) {\n // Only update navigation/actionNData if we didn't already do it above\n updates.navigation = loadingNavigation;\n let actionData = getUpdatedActionData(pendingActionResult);\n if (actionData !== undefined) {\n updates.actionData = actionData;\n }\n }\n if (revalidatingFetchers.length > 0) {\n updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n }\n updateState(updates, { flushSync });\n }\n\n revalidatingFetchers.forEach((rf) => {\n abortFetcher(rf.key);\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(loaderResults);\n if (redirect) {\n await startRedirectNavigation(request, redirect.result, true, {\n replace,\n });\n return { shortCircuited: true };\n }\n\n redirect = findRedirect(fetcherResults);\n if (redirect) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n fetchRedirectIds.add(redirect.key);\n await startRedirectNavigation(request, redirect.result, true, {\n replace,\n });\n return { shortCircuited: true };\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n loaderResults,\n pendingActionResult,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n // Preserve SSR errors during partial hydration\n if (future.v7_partialHydration && initialHydration && state.errors) {\n errors = { ...state.errors, ...errors };\n }\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n matches,\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n function getUpdatedActionData(\n pendingActionResult: PendingActionResult | undefined\n ): Record<string, RouteData> | null | undefined {\n if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n // This is cast to `any` currently because `RouteData`uses any and it\n // would be a breaking change to use any.\n // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n return {\n [pendingActionResult[0]]: pendingActionResult[1].data as any,\n };\n } else if (state.actionData) {\n if (Object.keys(state.actionData).length === 0) {\n return null;\n } else {\n return state.actionData;\n }\n }\n }\n\n function getUpdatedRevalidatingFetchers(\n revalidatingFetchers: RevalidatingFetcher[]\n ) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n return new Map(state.fetchers);\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n abortFetcher(key);\n\n let flushSync = (opts && opts.flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n future.v7_relativeSplatPath,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath }),\n { flushSync }\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n let preventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n fogOfWar.active,\n flushSync,\n preventScrollReset,\n submission\n );\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n fogOfWar.active,\n flushSync,\n preventScrollReset,\n submission\n );\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n flushSync: boolean,\n preventScrollReset: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n function detectAndHandle405Error(m: AgnosticDataRouteMatch) {\n if (!m.route.action && !m.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error, { flushSync });\n return true;\n }\n return false;\n }\n\n if (!isFogOfWar && detectAndHandle405Error(match)) {\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync,\n });\n\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n requestMatches,\n new URL(fetchRequest.url).pathname,\n fetchRequest.signal,\n key\n );\n\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n setFetcherError(key, routeId, discoverResult.error, { flushSync });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: path }),\n { flushSync }\n );\n return;\n } else {\n requestMatches = discoverResult.matches;\n match = getTargetMatch(requestMatches, path);\n\n if (detectAndHandle405Error(match)) {\n return;\n }\n }\n }\n\n // Call the action for the fetcher\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResults = await callDataStrategy(\n \"action\",\n state,\n fetchRequest,\n [match],\n requestMatches,\n key\n );\n let actionResult = actionResults[match.route.id];\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // Let SuccessResult's fall through for revalidation\n } else {\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(fetchRequest, actionResult, false, {\n fetcherSubmission: submission,\n preventScrollReset,\n });\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n }\n\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n false,\n future.v7_skipActionErrorRevalidation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n [match.route.id, actionResult]\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n abortFetcher(staleKey);\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(loaderResults);\n if (redirect) {\n return startRedirectNavigation(\n revalidationRequest,\n redirect.result,\n false,\n { preventScrollReset }\n );\n }\n\n redirect = findRedirect(fetcherResults);\n if (redirect) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n fetchRedirectIds.add(redirect.key);\n return startRedirectNavigation(\n revalidationRequest,\n redirect.result,\n false,\n { preventScrollReset }\n );\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n\n abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n fetchers: new Map(state.fetchers),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n isFogOfWar: boolean,\n flushSync: boolean,\n preventScrollReset: boolean,\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(\n key,\n getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\n ),\n { flushSync }\n );\n\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(\n matches,\n new URL(fetchRequest.url).pathname,\n fetchRequest.signal,\n key\n );\n\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n setFetcherError(key, routeId, discoverResult.error, { flushSync });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: path }),\n { flushSync }\n );\n return;\n } else {\n matches = discoverResult.matches;\n match = getTargetMatch(matches, path);\n }\n }\n\n // Call the loader for this fetcher route match\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let results = await callDataStrategy(\n \"loader\",\n state,\n fetchRequest,\n [match],\n matches,\n key\n );\n let result = results[match.route.id];\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n // We don't want errors bubbling up or redirects followed for unmounted\n // fetchers, so short circuit here if it was removed from the UI\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(fetchRequest, result, false, {\n preventScrollReset,\n });\n return;\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n request: Request,\n redirect: RedirectResult,\n isNavigation: boolean,\n {\n submission,\n fetcherSubmission,\n preventScrollReset,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n preventScrollReset?: boolean;\n replace?: boolean;\n } = {}\n ) {\n if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n isRevalidationRequired = true;\n }\n\n let location = redirect.response.headers.get(\"Location\");\n invariant(location, \"Expected a Location header on the redirect Response\");\n location = normalizeRedirectLocation(\n location,\n new URL(request.url),\n basename\n );\n let redirectLocation = createLocation(state.location, location, {\n _isRedirect: true,\n });\n\n if (isBrowser) {\n let isDocumentReload = false;\n\n if (redirect.response.headers.has(\"X-Remix-Reload-Document\")) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(location)) {\n const url = init.history.createURL(location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(location);\n } else {\n routerWindow.location.assign(location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true || redirect.response.headers.has(\"X-Remix-Replace\")\n ? HistoryAction.Replace\n : HistoryAction.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType } = state.navigation;\n if (\n !submission &&\n !fetcherSubmission &&\n formMethod &&\n formAction &&\n formEncType\n ) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (\n redirectPreserveMethodStatusCodes.has(redirect.response.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: location,\n },\n // Preserve these flags across redirects\n preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n enableViewTransition: isNavigation\n ? pendingViewTransitionEnabled\n : undefined,\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n submission\n );\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve these flags across redirects\n preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n enableViewTransition: isNavigation\n ? pendingViewTransitionEnabled\n : undefined,\n });\n }\n }\n\n // Utility wrapper for calling dataStrategy client-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(\n type: \"loader\" | \"action\",\n state: RouterState,\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n fetcherKey: string | null\n ): Promise<Record<string, DataResult>> {\n let results: Record<string, DataStrategyResult>;\n let dataResults: Record<string, DataResult> = {};\n try {\n results = await callDataStrategyImpl(\n dataStrategyImpl,\n type,\n state,\n request,\n matchesToLoad,\n matches,\n fetcherKey,\n manifest,\n mapRouteProperties\n );\n } catch (e) {\n // If the outer dataStrategy method throws, just return the error for all\n // matches - and it'll naturally bubble to the root\n matchesToLoad.forEach((m) => {\n dataResults[m.route.id] = {\n type: ResultType.error,\n error: e,\n };\n });\n return dataResults;\n }\n\n for (let [routeId, result] of Object.entries(results)) {\n if (isRedirectDataStrategyResultResult(result)) {\n let response = result.result as Response;\n dataResults[routeId] = {\n type: ResultType.redirect,\n response: normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n routeId,\n matches,\n basename,\n future.v7_relativeSplatPath\n ),\n };\n } else {\n dataResults[routeId] = await convertDataStrategyResultToDataResult(\n result\n );\n }\n }\n\n return dataResults;\n }\n\n async function callLoadersAndMaybeResolveData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n let currentMatches = state.matches;\n\n // Kick off loaders and fetchers in parallel\n let loaderResultsPromise = callDataStrategy(\n \"loader\",\n state,\n request,\n matchesToLoad,\n matches,\n null\n );\n\n let fetcherResultsPromise = Promise.all(\n fetchersToLoad.map(async (f) => {\n if (f.matches && f.match && f.controller) {\n let results = await callDataStrategy(\n \"loader\",\n state,\n createClientSideRequest(init.history, f.path, f.controller.signal),\n [f.match],\n f.matches,\n f.key\n );\n let result = results[f.match.route.id];\n // Fetcher results are keyed by fetcher key from here on out, not routeId\n return { [f.key]: result };\n } else {\n return Promise.resolve({\n [f.key]: {\n type: ResultType.error,\n error: getInternalRouterError(404, {\n pathname: f.path,\n }),\n } as ErrorResult,\n });\n }\n })\n );\n\n let loaderResults = await loaderResultsPromise;\n let fetcherResults = (await fetcherResultsPromise).reduce(\n (acc, r) => Object.assign(acc, r),\n {}\n );\n\n await Promise.all([\n resolveNavigationDeferredResults(\n matches,\n loaderResults,\n request.signal,\n currentMatches,\n state.loaderData\n ),\n resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad),\n ]);\n\n return {\n loaderResults,\n fetcherResults,\n };\n }\n\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n\n // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.add(key);\n }\n abortFetcher(key);\n });\n }\n\n function updateFetcherState(\n key: string,\n fetcher: Fetcher,\n opts: { flushSync?: boolean } = {}\n ) {\n state.fetchers.set(key, fetcher);\n updateState(\n { fetchers: new Map(state.fetchers) },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function setFetcherError(\n key: string,\n routeId: string,\n error: any,\n opts: { flushSync?: boolean } = {}\n ) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState(\n {\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function getFetcher<TData = any>(key: string): Fetcher<TData> {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n function deleteFetcher(key: string): void {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n\n // If we opted into the flag we can clear this now since we're calling\n // deleteFetcher() at the end of updateState() and we've already handed the\n // deleted fetcher keys off to the data layer.\n // If not, we're eagerly calling deleteFetcher() and we need to keep this\n // Set populated until the next updateState call, and we'll clear\n // `deletedFetchers` then\n if (future.v7_fetcherPersist) {\n deletedFetchers.delete(key);\n }\n\n cancelledFetcherLoads.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n if (!future.v7_fetcherPersist) {\n deleteFetcher(key);\n }\n } else {\n activeFetchers.set(key, count);\n }\n\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n if (controller) {\n controller.abort();\n fetchControllers.delete(key);\n }\n }\n\n function markFetchersDone(keys: string[]) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function handleNavigational404(pathname: string) {\n let error = getInternalRouterError(404, { pathname });\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let { matches, route } = getShortCircuitMatches(routesToUse);\n\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n\n return { notFoundMatches: matches, route, error };\n }\n\n function cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the <ScrollRestoration> component\n function enableScrollRestoration(\n positions: Record<string, number>,\n getPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || null;\n\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered <ScrollRestoration/>\n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({ restoreScrollPosition: y });\n }\n }\n\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n\n function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function checkFogOfWar(\n matches: AgnosticDataRouteMatch[] | null,\n routesToUse: AgnosticDataRouteObject[],\n pathname: string\n ): { active: boolean; matches: AgnosticDataRouteMatch[] | null } {\n if (patchRoutesOnNavigationImpl) {\n if (!matches) {\n let fogMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n routesToUse,\n pathname,\n basename,\n true\n );\n\n return { active: true, matches: fogMatches || [] };\n } else {\n if (Object.keys(matches[0].params).length > 0) {\n // If we matched a dynamic param or a splat, it might only be because\n // we haven't yet discovered other routes that would match with a\n // higher score. Call patchRoutesOnNavigation just to be sure\n let partialMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n routesToUse,\n pathname,\n basename,\n true\n );\n return { active: true, matches: partialMatches };\n }\n }\n }\n\n return { active: false, matches: null };\n }\n\n type DiscoverRoutesSuccessResult = {\n type: \"success\";\n matches: AgnosticDataRouteMatch[] | null;\n };\n type DiscoverRoutesErrorResult = {\n type: \"error\";\n error: any;\n partialMatches: AgnosticDataRouteMatch[];\n };\n type DiscoverRoutesAbortedResult = { type: \"aborted\" };\n type DiscoverRoutesResult =\n | DiscoverRoutesSuccessResult\n | DiscoverRoutesErrorResult\n | DiscoverRoutesAbortedResult;\n\n async function discoverRoutes(\n matches: AgnosticDataRouteMatch[],\n pathname: string,\n signal: AbortSignal,\n fetcherKey?: string\n ): Promise<DiscoverRoutesResult> {\n if (!patchRoutesOnNavigationImpl) {\n return { type: \"success\", matches };\n }\n\n let partialMatches: AgnosticDataRouteMatch[] | null = matches;\n while (true) {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let localManifest = manifest;\n try {\n await patchRoutesOnNavigationImpl({\n signal,\n path: pathname,\n matches: partialMatches,\n fetcherKey,\n patch: (routeId, children) => {\n if (signal.aborted) return;\n patchRoutesImpl(\n routeId,\n children,\n routesToUse,\n localManifest,\n mapRouteProperties\n );\n },\n });\n } catch (e) {\n return { type: \"error\", error: e, partialMatches };\n } finally {\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity so when we `updateState` at the end of\n // this navigation/fetch `router.routes` will be a new identity and\n // trigger a re-run of memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR && !signal.aborted) {\n dataRoutes = [...dataRoutes];\n }\n }\n\n if (signal.aborted) {\n return { type: \"aborted\" };\n }\n\n let newMatches = matchRoutes(routesToUse, pathname, basename);\n if (newMatches) {\n return { type: \"success\", matches: newMatches };\n }\n\n let newPartialMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n routesToUse,\n pathname,\n basename,\n true\n );\n\n // Avoid loops if the second pass results in the same partial matches\n if (\n !newPartialMatches ||\n (partialMatches.length === newPartialMatches.length &&\n partialMatches.every(\n (m, i) => m.route.id === newPartialMatches![i].route.id\n ))\n ) {\n return { type: \"success\", matches: null };\n }\n\n partialMatches = newPartialMatches;\n }\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n function patchRoutes(\n routeId: string | null,\n children: AgnosticRouteObject[]\n ): void {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n patchRoutesImpl(\n routeId,\n children,\n routesToUse,\n manifest,\n mapRouteProperties\n );\n\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity and trigger a reflow via `updateState`\n // to re-run memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR) {\n dataRoutes = [...dataRoutes];\n updateState({});\n }\n }\n\n router = {\n get basename() {\n return basename;\n },\n get future() {\n return future;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n patchRoutes,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n v7_relativeSplatPath: boolean;\n v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial<StaticHandlerFutureConfig>;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future: StaticHandlerFutureConfig = {\n v7_relativeSplatPath: false,\n v7_throwAbortReason: false,\n ...(opts ? opts.future : null),\n };\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n *\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent\n * the bubbling of errors which allows single-fetch-type implementations\n * where the client will handle the bubbling and we may need to return data\n * for the handling route\n */\n async function query(\n request: Request,\n {\n requestContext,\n skipLoaderErrorBubbling,\n dataStrategy,\n }: {\n requestContext?: unknown;\n skipLoaderErrorBubbling?: boolean;\n dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise<StaticHandlerContext | Response> {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n dataStrategy || null,\n skipLoaderErrorBubbling === true,\n null\n );\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n *\n * - `opts.routeId` allows you to specify the specific route handler to call.\n * If not provided the handler will determine the proper route by matching\n * against `request.url`\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n dataStrategy,\n }: {\n requestContext?: unknown;\n routeId?: string;\n dataStrategy?: DataStrategyFunction;\n } = {}\n ): Promise<any> {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n dataStrategy || null,\n false,\n match\n );\n\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null\n ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction for a\n // `queryRoute` call, we throw the `DataStrategyResult` to bail out early\n // and then return or throw the raw Response here accordingly\n if (isDataStrategyResult(e) && isResponse(e.result)) {\n if (e.type === ResultType.error) {\n throw e.result;\n }\n return e.result;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n isRouteRequest: boolean\n ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n let results = await callDataStrategy(\n \"action\",\n request,\n [actionMatch],\n matches,\n isRouteRequest,\n requestContext,\n dataStrategy\n );\n result = results[actionMatch.route.id];\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.response.status,\n headers: {\n Location: result.response.headers.get(\"Location\")!,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = skipLoaderErrorBubbling\n ? actionMatch\n : findNearestBoundary(matches, actionMatch.route.id);\n\n let context = await loadRouteData(\n loaderRequest,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n null,\n [boundaryMatch.route.id, result]\n );\n\n // action status codes take precedence over loader status codes\n return {\n ...context,\n statusCode: isRouteErrorResponse(result.error)\n ? result.error.status\n : result.statusCode != null\n ? result.statusCode\n : 500,\n actionData: null,\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n let context = await loadRouteData(\n loaderRequest,\n matches,\n requestContext,\n dataStrategy,\n skipLoaderErrorBubbling,\n null\n );\n\n return {\n ...context,\n actionData: {\n [actionMatch.route.id]: result.data,\n },\n // action status codes take precedence over loader status codes\n ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n actionHeaders: result.headers\n ? { [actionMatch.route.id]: result.headers }\n : {},\n };\n }\n\n async function loadRouteData(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null,\n skipLoaderErrorBubbling: boolean,\n routeMatch: AgnosticDataRouteMatch | null,\n pendingActionResult?: PendingActionResult\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : pendingActionResult && isErrorResult(pendingActionResult[1])\n ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0])\n : matches;\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors:\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? {\n [pendingActionResult[0]]: pendingActionResult[1].error,\n }\n : null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await callDataStrategy(\n \"loader\",\n request,\n matchesToLoad,\n matches,\n isRouteRequest,\n requestContext,\n dataStrategy\n );\n\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map<string, DeferredData>();\n let context = processRouteLoaderData(\n matches,\n results,\n pendingActionResult,\n activeDeferreds,\n skipLoaderErrorBubbling\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set<string>(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\n }\n\n // Utility wrapper for calling dataStrategy server-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(\n type: \"loader\" | \"action\",\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n isRouteRequest: boolean,\n requestContext: unknown,\n dataStrategy: DataStrategyFunction | null\n ): Promise<Record<string, DataResult>> {\n let results = await callDataStrategyImpl(\n dataStrategy || defaultDataStrategy,\n type,\n null,\n request,\n matchesToLoad,\n matches,\n null,\n manifest,\n mapRouteProperties,\n requestContext\n );\n\n let dataResults: Record<string, DataResult> = {};\n await Promise.all(\n matches.map(async (match) => {\n if (!(match.route.id in results)) {\n return;\n }\n let result = results[match.route.id];\n if (isRedirectDataStrategyResultResult(result)) {\n let response = result.result as Response;\n // Throw redirects and let the server handle them with an HTTP redirect\n throw normalizeRelativeRoutingRedirectResponse(\n response,\n request,\n match.route.id,\n matches,\n basename,\n future.v7_relativeSplatPath\n );\n }\n if (isResponse(result.result) && isRouteRequest) {\n // For SSR single-route requests, we want to hand Responses back\n // directly without unwrapping\n throw result;\n }\n\n dataResults[match.route.id] =\n await convertDataStrategyResultToDataResult(result);\n })\n );\n return dataResults;\n }\n\n return {\n dataRoutes,\n query,\n queryRoute,\n };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n routes: AgnosticDataRouteObject[],\n context: StaticHandlerContext,\n error: any\n) {\n let newContext: StaticHandlerContext = {\n ...context,\n statusCode: isRouteErrorResponse(error) ? error.status : 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error,\n },\n };\n return newContext;\n}\n\nfunction throwStaticHandlerAbortedError(\n request: Request,\n isRouteRequest: boolean,\n future: StaticHandlerFutureConfig\n) {\n if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n throw request.signal.reason;\n }\n\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\n}\n\nfunction isSubmissionNavigation(\n opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n v7_relativeSplatPath: boolean,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Account for `?index` params when routing to the current location\n if ((to == null || to === \"\" || to === \".\") && activeRouteMatch) {\n let nakedIndex = hasNakedIndexQuery(path.search);\n if (activeRouteMatch.route.index && !nakedIndex) {\n // Add one when we're targeting an index route\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n } else if (!activeRouteMatch.route.index && nakedIndex) {\n // Remove existing ones when we're not\n let params = new URLSearchParams(path.search);\n let indexValues = params.getAll(\"index\");\n params.delete(\"index\");\n indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n let qs = params.toString();\n path.search = qs ? `?${qs}` : \"\";\n }\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: BaseNavigateOrFetchOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponseImpl;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() as FormMethod);\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes at/below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n matches: AgnosticDataRouteMatch[],\n boundaryId: string,\n includeBoundary = false\n) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n return matches.slice(0, includeBoundary ? index + 1 : index);\n }\n return matches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n initialHydration: boolean,\n skipActionErrorRevalidation: boolean,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: Set<string>,\n deletedFetchers: Set<string>,\n fetchLoadMatches: Map<string, FetchLoadMatch>,\n fetchRedirectIds: Set<string>,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionResult?: PendingActionResult\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingActionResult\n ? isErrorResult(pendingActionResult[1])\n ? pendingActionResult[1].error\n : pendingActionResult[1].data\n : undefined;\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryMatches = matches;\n if (initialHydration && state.errors) {\n // On initial hydration, only consider matches up to _and including_ the boundary.\n // This is inclusive to handle cases where a server loader ran successfully,\n // a child server loader bubbled up to this route, but this route has\n // `clientLoader.hydrate` so we want to still run the `clientLoader` so that\n // we have a complete version of `loaderData`\n boundaryMatches = getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(state.errors)[0],\n true\n );\n } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {\n // If an action threw an error, we call loaders up to, but not including the\n // boundary\n boundaryMatches = getLoaderMatchesUntilBoundary(\n matches,\n pendingActionResult[0]\n );\n }\n\n // Don't revalidate loaders by default after action 4xx/5xx responses\n // when the flag is enabled. They can still opt-into revalidation via\n // `shouldRevalidate` via `actionResult`\n let actionStatus = pendingActionResult\n ? pendingActionResult[1].statusCode\n : undefined;\n let shouldSkipRevalidation =\n skipActionErrorRevalidation && actionStatus && actionStatus >= 400;\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n let { route } = match;\n if (route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n\n if (route.loader == null) {\n return false;\n }\n\n if (initialHydration) {\n return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation\n ? false\n : // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate:\n // - on initial hydration (shouldn't be any fetchers then anyway)\n // - if fetcher won't be present in the subsequent render\n // - no longer matches the URL (v7_fetcherPersist=false)\n // - was unmounted but persisted due to v7_fetcherPersist=true\n if (\n initialHydration ||\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.has(key)\n ) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.has(key)) {\n // Always mark for revalidation if the fetcher was cancelled\n cancelledFetcherLoads.delete(key);\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation\n ? false\n : isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction shouldLoadRouteOnHydration(\n route: AgnosticDataRouteObject,\n loaderData: RouteData | null | undefined,\n errors: RouteData | null | undefined\n) {\n // We dunno if we have a loader - gotta find out!\n if (route.lazy) {\n return true;\n }\n\n // No loader, nothing to initialize\n if (!route.loader) {\n return false;\n }\n\n let hasData = loaderData != null && loaderData[route.id] !== undefined;\n let hasError = errors != null && errors[route.id] !== undefined;\n\n // Don't run if we error'd during SSR\n if (!hasData && hasError) {\n return false;\n }\n\n // Explicitly opting-in to running on hydration\n if (typeof route.loader === \"function\" && route.loader.hydrate === true) {\n return true;\n }\n\n // Otherwise, run if we're not yet initialized with anything\n return !hasData && !hasError;\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: ShouldRevalidateFunctionArgs\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\nfunction patchRoutesImpl(\n routeId: string | null,\n children: AgnosticRouteObject[],\n routesToUse: AgnosticDataRouteObject[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction\n) {\n let childrenToPatch: AgnosticDataRouteObject[];\n if (routeId) {\n let route = manifest[routeId];\n invariant(\n route,\n `No route found to patch children into: routeId = ${routeId}`\n );\n if (!route.children) {\n route.children = [];\n }\n childrenToPatch = route.children;\n } else {\n childrenToPatch = routesToUse;\n }\n\n // Don't patch in routes we already know about so that `patch` is idempotent\n // to simplify user-land code. This is useful because we re-call the\n // `patchRoutesOnNavigation` function for matched routes with params.\n let uniqueChildren = children.filter(\n (newRoute) =>\n !childrenToPatch.some((existingRoute) =>\n isSameRoute(newRoute, existingRoute)\n )\n );\n\n let newRoutes = convertRoutesToDataRoutes(\n uniqueChildren,\n mapRouteProperties,\n [routeId || \"_\", \"patch\", String(childrenToPatch?.length || \"0\")],\n manifest\n );\n\n childrenToPatch.push(...newRoutes);\n}\n\nfunction isSameRoute(\n newRoute: AgnosticRouteObject,\n existingRoute: AgnosticRouteObject\n): boolean {\n // Most optimal check is by id\n if (\n \"id\" in newRoute &&\n \"id\" in existingRoute &&\n newRoute.id === existingRoute.id\n ) {\n return true;\n }\n\n // Second is by pathing differences\n if (\n !(\n newRoute.index === existingRoute.index &&\n newRoute.path === existingRoute.path &&\n newRoute.caseSensitive === existingRoute.caseSensitive\n )\n ) {\n return false;\n }\n\n // Pathless layout routes are trickier since we need to check children.\n // If they have no children then they're the same as far as we can tell\n if (\n (!newRoute.children || newRoute.children.length === 0) &&\n (!existingRoute.children || existingRoute.children.length === 0)\n ) {\n return true;\n }\n\n // Otherwise, we look to see if every child in the new route is already\n // represented in the existing route's children\n return newRoute.children!.every((aChild, i) =>\n existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))\n );\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record<string, any> = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nasync function defaultDataStrategy({\n matches,\n}: DataStrategyFunctionArgs): ReturnType<DataStrategyFunction> {\n let matchesToLoad = matches.filter((m) => m.shouldLoad);\n let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));\n return results.reduce(\n (acc, result, i) =>\n Object.assign(acc, { [matchesToLoad[i].route.id]: result }),\n {}\n );\n}\n\nasync function callDataStrategyImpl(\n dataStrategyImpl: DataStrategyFunction,\n type: \"loader\" | \"action\",\n state: RouterState | null,\n request: Request,\n matchesToLoad: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n fetcherKey: string | null,\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n requestContext?: unknown\n): Promise<Record<string, DataStrategyResult>> {\n let loadRouteDefinitionsPromises = matches.map((m) =>\n m.route.lazy\n ? loadLazyRouteModule(m.route, mapRouteProperties, manifest)\n : undefined\n );\n\n let dsMatches = matches.map((match, i) => {\n let loadRoutePromise = loadRouteDefinitionsPromises[i];\n let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id);\n // `resolve` encapsulates route.lazy(), executing the loader/action,\n // and mapping return values/thrown errors to a `DataStrategyResult`. Users\n // can pass a callback to take fine-grained control over the execution\n // of the loader/action\n let resolve: DataStrategyMatch[\"resolve\"] = async (handlerOverride) => {\n if (\n handlerOverride &&\n request.method === \"GET\" &&\n (match.route.lazy || match.route.loader)\n ) {\n shouldLoad = true;\n }\n return shouldLoad\n ? callLoaderOrAction(\n type,\n request,\n match,\n loadRoutePromise,\n handlerOverride,\n requestContext\n )\n : Promise.resolve({ type: ResultType.data, result: undefined });\n };\n\n return {\n ...match,\n shouldLoad,\n resolve,\n };\n });\n\n // Send all matches here to allow for a middleware-type implementation.\n // handler will be a no-op for unneeded routes and we filter those results\n // back out below.\n let results = await dataStrategyImpl({\n matches: dsMatches,\n request,\n params: matches[0].params,\n fetcherKey,\n context: requestContext,\n });\n\n // Wait for all routes to load here but 'swallow the error since we want\n // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -\n // called from `match.resolve()`\n try {\n await Promise.all(loadRouteDefinitionsPromises);\n } catch (e) {\n // No-op\n }\n\n return results;\n}\n\n// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n loadRoutePromise: Promise<void> | undefined,\n handlerOverride: Parameters<DataStrategyMatch[\"resolve\"]>[0],\n staticContext?: unknown\n): Promise<DataStrategyResult> {\n let result: DataStrategyResult;\n let onReject: (() => void) | undefined;\n\n let runHandler = (\n handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n ): Promise<DataStrategyResult> => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject: () => void;\n // This will never resolve so safe to type it as Promise<DataStrategyResult> to\n // satisfy the function return value\n let abortPromise = new Promise<DataStrategyResult>((_, r) => (reject = r));\n onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n\n let actualHandler = (ctx?: unknown) => {\n if (typeof handler !== \"function\") {\n return Promise.reject(\n new Error(\n `You cannot call the handler for a route which defines a boolean ` +\n `\"${type}\" [routeId: ${match.route.id}]`\n )\n );\n }\n return handler(\n {\n request,\n params: match.params,\n context: staticContext,\n },\n ...(ctx !== undefined ? [ctx] : [])\n );\n };\n\n let handlerPromise: Promise<DataStrategyResult> = (async () => {\n try {\n let val = await (handlerOverride\n ? handlerOverride((ctx: unknown) => actualHandler(ctx))\n : actualHandler());\n return { type: \"data\", result: val };\n } catch (e) {\n return { type: \"error\", result: e };\n }\n })();\n\n return Promise.race([handlerPromise, abortPromise]);\n };\n\n try {\n let handler = match.route[type];\n\n // If we have a route.lazy promise, await that first\n if (loadRoutePromise) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let [value] = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch((e) => {\n handlerError = e;\n }),\n loadRoutePromise,\n ]);\n if (handlerError !== undefined) {\n throw handlerError;\n }\n result = value!;\n } else {\n // Load lazy route module, then run any returned handler\n await loadRoutePromise;\n\n handler = match.route[type];\n if (handler) {\n // Handler still runs even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, result: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result.result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n // We should already be catching and converting normal handler executions to\n // DataStrategyResults and returning them, so anything that throws here is an\n // unexpected error we still need to wrap\n return { type: ResultType.error, result: e };\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n return result;\n}\n\nasync function convertDataStrategyResultToDataResult(\n dataStrategyResult: DataStrategyResult\n): Promise<DataResult> {\n let { result, type } = dataStrategyResult;\n\n if (isResponse(result)) {\n let data: any;\n\n try {\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n if (result.body == null) {\n data = null;\n } else {\n data = await result.json();\n }\n } else {\n data = await result.text();\n }\n } catch (e) {\n return { type: ResultType.error, error: e };\n }\n\n if (type === ResultType.error) {\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(result.status, result.statusText, data),\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n if (type === ResultType.error) {\n if (isDataWithResponseInit(result)) {\n if (result.data instanceof Error) {\n return {\n type: ResultType.error,\n error: result.data,\n statusCode: result.init?.status,\n headers: result.init?.headers\n ? new Headers(result.init.headers)\n : undefined,\n };\n }\n\n // Convert thrown data() to ErrorResponse instances\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(\n result.init?.status || 500,\n undefined,\n result.data\n ),\n statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n headers: result.init?.headers\n ? new Headers(result.init.headers)\n : undefined,\n };\n }\n return {\n type: ResultType.error,\n error: result,\n statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n };\n }\n\n if (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n if (isDataWithResponseInit(result)) {\n return {\n type: ResultType.data,\n data: result.data,\n statusCode: result.init?.status,\n headers: result.init?.headers\n ? new Headers(result.init.headers)\n : undefined,\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(\n response: Response,\n request: Request,\n routeId: string,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n v7_relativeSplatPath: boolean\n) {\n let location = response.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n let trimmedMatches = matches.slice(\n 0,\n matches.findIndex((m) => m.route.id === routeId) + 1\n );\n location = normalizeTo(\n new URL(request.url),\n trimmedMatches,\n basename,\n true,\n location,\n v7_relativeSplatPath\n );\n response.headers.set(\"Location\", location);\n }\n\n return response;\n}\n\nfunction normalizeRedirectLocation(\n location: string,\n currentUrl: URL,\n basename: string\n): string {\n if (ABSOLUTE_URL_REGEX.test(location)) {\n // Strip off the protocol+origin for same-origin + same-basename absolute redirects\n let normalizedLocation = location;\n let url = normalizedLocation.startsWith(\"//\")\n ? new URL(currentUrl.protocol + normalizedLocation)\n : new URL(normalizedLocation);\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n return url.pathname + url.search + url.hash;\n }\n }\n return location;\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n results: Record<string, DataResult>,\n pendingActionResult: PendingActionResult | undefined,\n activeDeferreds: Map<string, DeferredData>,\n skipLoaderErrorBubbling: boolean\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record<string, Headers>;\n} {\n // Fill in loaderData/errors from our loaders\n let loaderData: RouterState[\"loaderData\"] = {};\n let errors: RouterState[\"errors\"] | null = null;\n let statusCode: number | undefined;\n let foundError = false;\n let loaderHeaders: Record<string, Headers> = {};\n let pendingError =\n pendingActionResult && isErrorResult(pendingActionResult[1])\n ? pendingActionResult[1].error\n : undefined;\n\n // Process loader results into state.loaderData/state.errors\n matches.forEach((match) => {\n if (!(match.route.id in results)) {\n return;\n }\n let id = match.route.id;\n let result = results[id];\n invariant(\n !isRedirectResult(result),\n \"Cannot handle redirect results in processLoaderData\"\n );\n if (isErrorResult(result)) {\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError !== undefined) {\n error = pendingError;\n pendingError = undefined;\n }\n\n errors = errors || {};\n\n if (skipLoaderErrorBubbling) {\n errors[id] = error;\n } else {\n // Look upwards from the matched route for the closest ancestor error\n // boundary, defaulting to the root match. Prefer higher error values\n // if lower errors bubble to the same boundary\n let boundaryMatch = findNearestBoundary(matches, id);\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n loaderData[id] = result.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (result.statusCode && result.statusCode !== 200 && !foundError) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n }\n });\n\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here. Also clear out any loaderData for the\n // throwing route\n if (pendingError !== undefined && pendingActionResult) {\n errors = { [pendingActionResult[0]]: pendingError };\n loaderData[pendingActionResult[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n results: Record<string, DataResult>,\n pendingActionResult: PendingActionResult | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: Record<string, DataResult>,\n activeDeferreds: Map<string, DeferredData>\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n results,\n pendingActionResult,\n activeDeferreds,\n false // This method is only called client side so we always want to bubble\n );\n\n // Process results from our revalidating fetchers\n revalidatingFetchers.forEach((rf) => {\n let { key, match, controller } = rf;\n let result = fetcherResults[key];\n invariant(result, \"Did not find corresponding fetcher result\");\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n return;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n });\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\nfunction getActionDataForCommit(\n pendingActionResult: PendingActionResult | undefined\n) {\n if (!pendingActionResult) {\n return {};\n }\n return isErrorResult(pendingActionResult[1])\n ? {\n // Clear out prior actionData on errors\n actionData: {},\n }\n : {\n actionData: {\n [pendingActionResult[0]]: pendingActionResult[1].data,\n },\n };\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n message,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\n message?: string;\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponseImpl(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: Record<string, DataResult>\n): { key: string; result: RedirectResult } | undefined {\n let entries = Object.entries(results);\n for (let i = entries.length - 1; i >= 0; i--) {\n let [key, result] = entries[i];\n if (isRedirectResult(result)) {\n return { key, result };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\n\nfunction isPromise<T = unknown>(val: unknown): val is Promise<T> {\n return typeof val === \"object\" && val != null && \"then\" in val;\n}\n\nfunction isDataStrategyResult(result: unknown): result is DataStrategyResult {\n return (\n result != null &&\n typeof result === \"object\" &&\n \"type\" in result &&\n \"result\" in result &&\n (result.type === ResultType.data || result.type === ResultType.error)\n );\n}\n\nfunction isRedirectDataStrategyResultResult(result: DataStrategyResult) {\n return (\n isResponse(result.result) && redirectStatusCodes.has(result.result.status)\n );\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDataWithResponseInit(\n value: any\n): value is DataWithResponseInit<unknown> {\n return (\n typeof value === \"object\" &&\n value != null &&\n \"type\" in value &&\n \"data\" in value &&\n \"init\" in value &&\n value.type === \"DataWithResponseInit\"\n );\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveNavigationDeferredResults(\n matches: (AgnosticDataRouteMatch | null)[],\n results: Record<string, DataResult>,\n signal: AbortSignal,\n currentMatches: AgnosticDataRouteMatch[],\n currentLoaderData: RouteData\n) {\n let entries = Object.entries(results);\n for (let index = 0; index < entries.length; index++) {\n let [routeId, result] = entries[index];\n let match = matches.find((m) => m?.route.id === routeId);\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && isRevalidatingLoader) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n await resolveDeferredData(result, signal, false).then((result) => {\n if (result) {\n results[routeId] = result;\n }\n });\n }\n }\n}\n\nasync function resolveFetcherDeferredResults(\n matches: (AgnosticDataRouteMatch | null)[],\n results: Record<string, DataResult>,\n revalidatingFetchers: RevalidatingFetcher[]\n) {\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let { key, routeId, controller } = revalidatingFetchers[index];\n let result = results[key];\n let match = matches.find((m) => m?.route.id === routeId);\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n if (isDeferredResult(result)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n invariant(\n controller,\n \"Expected an AbortController for revalidating fetcher deferred result\"\n );\n await resolveDeferredData(result, controller.signal, true).then(\n (result) => {\n if (result) {\n results[key] = result;\n }\n }\n );\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise<SuccessResult | ErrorResult | undefined> {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n _window: Window,\n transitions: Map<string, Set<string>>\n) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(\n TRANSITIONS_STORAGE_KEY\n );\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\n\nfunction persistAppliedTransitions(\n _window: Window,\n transitions: Map<string, Set<string>>\n) {\n if (transitions.size > 0) {\n let json: Record<string, string[]> = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(\n TRANSITIONS_STORAGE_KEY,\n JSON.stringify(json)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save applied view transitions in sessionStorage (${error}).`\n );\n }\n }\n}\n//#endregion\n","import * as React from \"react\";\nimport type {\n AgnosticIndexRouteObject,\n AgnosticNonIndexRouteObject,\n AgnosticRouteMatch,\n History,\n LazyRouteFunction,\n Location,\n Action as NavigationType,\n RelativeRoutingType,\n Router,\n StaticHandlerContext,\n To,\n TrackedPromise,\n} from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticIndexRouteObject[\"path\"];\n id?: AgnosticIndexRouteObject[\"id\"];\n loader?: AgnosticIndexRouteObject[\"loader\"];\n action?: AgnosticIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticIndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport interface NonIndexRouteObject {\n caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticNonIndexRouteObject[\"path\"];\n id?: AgnosticNonIndexRouteObject[\"id\"];\n loader?: AgnosticNonIndexRouteObject[\"loader\"];\n action?: AgnosticNonIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticNonIndexRouteObject[\"handle\"];\n index?: false;\n children?: RouteObject[];\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n children?: DataRouteObject[];\n id: string;\n};\n\nexport interface RouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {}\n\nexport interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}\n\nexport interface DataRouterContextObject\n // Omit `future` since those can be pulled from the `router`\n // `NavigationContext` needs future since it doesn't have a `router` in all cases\n extends Omit<NavigationContextObject, \"future\"> {\n router: Router;\n staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n React.createContext<DataRouterContextObject | null>(null);\nif (__DEV__) {\n DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext<TrackedPromise | null>(null);\nif (__DEV__) {\n AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n flushSync?: boolean;\n viewTransition?: boolean;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `<Router>` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n createHref: History[\"createHref\"];\n // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n encodeLocation?: History[\"encodeLocation\"];\n go: History[\"go\"];\n push(to: To, state?: any, opts?: NavigateOptions): void;\n replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n basename: string;\n navigator: Navigator;\n static: boolean;\n future: {\n v7_relativeSplatPath: boolean;\n };\n}\n\nexport const NavigationContext = React.createContext<NavigationContextObject>(\n null!\n);\n\nif (__DEV__) {\n NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n location: Location;\n navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext<LocationContextObject>(\n null!\n);\n\nif (__DEV__) {\n LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n outlet: React.ReactElement | null;\n matches: RouteMatch[];\n isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext<RouteContextObject>({\n outlet: null,\n matches: [],\n isDataRoute: false,\n});\n\nif (__DEV__) {\n RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext<any>(null);\n\nif (__DEV__) {\n RouteErrorContext.displayName = \"RouteError\";\n}\n","import * as React from \"react\";\nimport type {\n Blocker,\n BlockerFunction,\n Location,\n ParamParseKey,\n Params,\n Path,\n PathMatch,\n PathPattern,\n RelativeRoutingType,\n Router as RemixRouter,\n RevalidationState,\n To,\n UIMatch,\n} from \"@remix-run/router\";\nimport {\n IDLE_BLOCKER,\n Action as NavigationType,\n UNSAFE_convertRouteMatchToUiMatch as convertRouteMatchToUiMatch,\n UNSAFE_decodePath as decodePath,\n UNSAFE_getResolveToMatches as getResolveToMatches,\n UNSAFE_invariant as invariant,\n isRouteErrorResponse,\n joinPaths,\n matchPath,\n matchRoutes,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n DataRouteMatch,\n NavigateOptions,\n RouteContextObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n RouteErrorContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/v6/hooks/use-href\n */\nexport function useHref(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useHref() may be used only in the context of a <Router> component.`\n );\n\n let { basename, navigator } = React.useContext(NavigationContext);\n let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n let joinedPathname = pathname;\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the href. If this is a root navigation, then just use the raw\n // basename which allows the basename to have full control over the presence\n // of a trailing slash on root links\n if (basename !== \"/\") {\n joinedPathname =\n pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n }\n\n return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a `<Router>`.\n *\n * @see https://reactrouter.com/v6/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/v6/hooks/use-location\n */\nexport function useLocation(): Location {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useLocation() may be used only in the context of a <Router> component.`\n );\n\n return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * `<NavLink>`.\n *\n * @see https://reactrouter.com/v6/hooks/use-match\n */\nexport function useMatch<\n ParamKey extends ParamParseKey<Path>,\n Path extends string\n>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useMatch() may be used only in the context of a <Router> component.`\n );\n\n let { pathname } = useLocation();\n return React.useMemo(\n () => matchPath<ParamKey, Path>(pattern, decodePath(pathname)),\n [pathname, pattern]\n );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n (to: To, options?: NavigateOptions): void;\n (delta: number): void;\n}\n\nconst navigateEffectWarning =\n `You should call navigate() in a React.useEffect(), not when ` +\n `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n cb: Parameters<typeof React.useLayoutEffect>[0]\n) {\n let isStatic = React.useContext(NavigationContext).static;\n if (!isStatic) {\n // We should be able to get rid of this once react 18.3 is released\n // See: https://github.com/facebook/react/pull/26395\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(cb);\n }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by `<Link>`s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n let { isDataRoute } = React.useContext(RouteContext);\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useNavigate() may be used only in the context of a <Router> component.`\n );\n\n let dataRouterContext = React.useContext(DataRouterContext);\n let { basename, future, navigator } = React.useContext(NavigationContext);\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n\n let routePathnamesJson = JSON.stringify(\n getResolveToMatches(matches, future.v7_relativeSplatPath)\n );\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our history listener yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n navigator.go(to);\n return;\n }\n\n let path = resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n options.relative === \"path\"\n );\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to handing off to history (but only if we're not in a data router,\n // otherwise it'll prepend the basename inside of the router).\n // If this is a root navigation, then we navigate to the raw basename\n // which allows the basename to have full control over the presence of a\n // trailing slash on root links\n if (dataRouterContext == null && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\"\n ? basename\n : joinPaths([basename, path.pathname]);\n }\n\n (!!options.replace ? navigator.replace : navigator.push)(\n path,\n options.state,\n options\n );\n },\n [\n basename,\n navigator,\n routePathnamesJson,\n locationPathname,\n dataRouterContext,\n ]\n );\n\n return navigate;\n}\n\nconst OutletContext = React.createContext<unknown>(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/v6/hooks/use-outlet-context\n */\nexport function useOutletContext<Context = unknown>(): Context {\n return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `<Outlet>` to render child routes.\n *\n * @see https://reactrouter.com/v6/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n let outlet = React.useContext(RouteContext).outlet;\n if (outlet) {\n return (\n <OutletContext.Provider value={context}>{outlet}</OutletContext.Provider>\n );\n }\n return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/v6/hooks/use-params\n */\nexport function useParams<\n ParamsOrKey extends string | Record<string, string | undefined> = string\n>(): Readonly<\n [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>\n> {\n let { matches } = React.useContext(RouteContext);\n let routeMatch = matches[matches.length - 1];\n return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/v6/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n let { future } = React.useContext(NavigationContext);\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n let routePathnamesJson = JSON.stringify(\n getResolveToMatches(matches, future.v7_relativeSplatPath)\n );\n\n return React.useMemo(\n () =>\n resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n relative === \"path\"\n ),\n [to, routePathnamesJson, locationPathname, relative]\n );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `<Outlet>` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/v6/hooks/use-routes\n */\nexport function useRoutes(\n routes: RouteObject[],\n locationArg?: Partial<Location> | string\n): React.ReactElement | null {\n return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n routes: RouteObject[],\n locationArg?: Partial<Location> | string,\n dataRouterState?: RemixRouter[\"state\"],\n future?: RemixRouter[\"future\"]\n): React.ReactElement | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useRoutes() may be used only in the context of a <Router> component.`\n );\n\n let { navigator } = React.useContext(NavigationContext);\n let { matches: parentMatches } = React.useContext(RouteContext);\n let routeMatch = parentMatches[parentMatches.length - 1];\n let parentParams = routeMatch ? routeMatch.params : {};\n let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n let parentRoute = routeMatch && routeMatch.route;\n\n if (__DEV__) {\n // You won't get a warning about 2 different <Routes> under a <Route>\n // without a trailing *, but this is a best-effort warning anyway since we\n // cannot even give the warning unless they land at the parent route.\n //\n // Example:\n //\n // <Routes>\n // {/* This route path MUST end with /* because otherwise\n // it will never match /blog/post/123 */}\n // <Route path=\"blog\" element={<Blog />} />\n // <Route path=\"blog/feed\" element={<BlogFeed />} />\n // </Routes>\n //\n // function Blog() {\n // return (\n // <Routes>\n // <Route path=\"post/:id\" element={<Post />} />\n // </Routes>\n // );\n // }\n let parentPath = (parentRoute && parentRoute.path) || \"\";\n warningOnce(\n parentPathname,\n !parentRoute || parentPath.endsWith(\"*\"),\n `You rendered descendant <Routes> (or called \\`useRoutes()\\`) at ` +\n `\"${parentPathname}\" (under <Route path=\"${parentPath}\">) but the ` +\n `parent route path has no trailing \"*\". This means if you navigate ` +\n `deeper, the parent won't match anymore and therefore the child ` +\n `routes will never render.\\n\\n` +\n `Please change the parent <Route path=\"${parentPath}\"> to <Route ` +\n `path=\"${parentPath === \"/\" ? \"*\" : `${parentPath}/*`}\">.`\n );\n }\n\n let locationFromContext = useLocation();\n\n let location;\n if (locationArg) {\n let parsedLocationArg =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n invariant(\n parentPathnameBase === \"/\" ||\n parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n `When overriding the location using \\`<Routes location>\\` or \\`useRoutes(routes, location)\\`, ` +\n `the location pathname must begin with the portion of the URL pathname that was ` +\n `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n );\n\n location = parsedLocationArg;\n } else {\n location = locationFromContext;\n }\n\n let pathname = location.pathname || \"/\";\n\n let remainingPathname = pathname;\n if (parentPathnameBase !== \"/\") {\n // Determine the remaining pathname by removing the # of URL segments the\n // parentPathnameBase has, instead of removing based on character count.\n // This is because we can't guarantee that incoming/outgoing encodings/\n // decodings will match exactly.\n // We decode paths before matching on a per-segment basis with\n // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they\n // match what `window.location.pathname` would reflect. Those don't 100%\n // align when it comes to encoded URI characters such as % and &.\n //\n // So we may end up with:\n // pathname: \"/descendant/a%25b/match\"\n // parentPathnameBase: \"/descendant/a%b\"\n //\n // And the direct substring removal approach won't work :/\n let parentSegments = parentPathnameBase.replace(/^\\//, \"\").split(\"/\");\n let segments = pathname.replace(/^\\//, \"\").split(\"/\");\n remainingPathname = \"/\" + segments.slice(parentSegments.length).join(\"/\");\n }\n\n let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n if (__DEV__) {\n warning(\n parentRoute || matches != null,\n `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n );\n\n warning(\n matches == null ||\n matches[matches.length - 1].route.element !== undefined ||\n matches[matches.length - 1].route.Component !== undefined ||\n matches[matches.length - 1].route.lazy !== undefined,\n `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n `does not have an element or Component. This means it will render an <Outlet /> with a ` +\n `null value by default resulting in an \"empty\" page.`\n );\n }\n\n let renderedMatches = _renderMatches(\n matches &&\n matches.map((match) =>\n Object.assign({}, match, {\n params: Object.assign({}, parentParams, match.params),\n pathname: joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathname).pathname\n : match.pathname,\n ]),\n pathnameBase:\n match.pathnameBase === \"/\"\n ? parentPathnameBase\n : joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathnameBase).pathname\n : match.pathnameBase,\n ]),\n })\n ),\n parentMatches,\n dataRouterState,\n future\n );\n\n // When a user passes in a `locationArg`, the associated routes need to\n // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n // to use the scoped location instead of the global location.\n if (locationArg && renderedMatches) {\n return (\n <LocationContext.Provider\n value={{\n location: {\n pathname: \"/\",\n search: \"\",\n hash: \"\",\n state: null,\n key: \"default\",\n ...location,\n },\n navigationType: NavigationType.Pop,\n }}\n >\n {renderedMatches}\n </LocationContext.Provider>\n );\n }\n\n return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n let error = useRouteError();\n let message = isRouteErrorResponse(error)\n ? `${error.status} ${error.statusText}`\n : error instanceof Error\n ? error.message\n : JSON.stringify(error);\n let stack = error instanceof Error ? error.stack : null;\n let lightgrey = \"rgba(200,200,200, 0.5)\";\n let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n let devInfo = null;\n if (__DEV__) {\n console.error(\n \"Error handled by React Router default ErrorBoundary:\",\n error\n );\n\n devInfo = (\n <>\n <p>💿 Hey developer 👋</p>\n <p>\n You can provide a way better UX than this when your app throws errors\n by providing your own <code style={codeStyles}>ErrorBoundary</code> or{\" \"}\n <code style={codeStyles}>errorElement</code> prop on your route.\n </p>\n </>\n );\n }\n\n return (\n <>\n <h2>Unexpected Application Error!</h2>\n <h3 style={{ fontStyle: \"italic\" }}>{message}</h3>\n {stack ? <pre style={preStyles}>{stack}</pre> : null}\n {devInfo}\n </>\n );\n}\n\nconst defaultErrorElement = <DefaultErrorComponent />;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n location: Location;\n revalidation: RevalidationState;\n error: any;\n component: React.ReactNode;\n routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n location: Location;\n revalidation: RevalidationState;\n error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n RenderErrorBoundaryProps,\n RenderErrorBoundaryState\n> {\n constructor(props: RenderErrorBoundaryProps) {\n super(props);\n this.state = {\n location: props.location,\n revalidation: props.revalidation,\n error: props.error,\n };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error: error };\n }\n\n static getDerivedStateFromProps(\n props: RenderErrorBoundaryProps,\n state: RenderErrorBoundaryState\n ) {\n // When we get into an error state, the user will likely click \"back\" to the\n // previous page that didn't have an error. Because this wraps the entire\n // application, that will have no effect--the error page continues to display.\n // This gives us a mechanism to recover from the error when the location changes.\n //\n // Whether we're in an error state or not, we update the location in state\n // so that when we are in an error state, it gets reset when a new location\n // comes in and the user recovers from the error.\n if (\n state.location !== props.location ||\n (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n ) {\n return {\n error: props.error,\n location: props.location,\n revalidation: props.revalidation,\n };\n }\n\n // If we're not changing locations, preserve the location but still surface\n // any new errors that may come through. We retain the existing error, we do\n // this because the error provided from the app state may be cleared without\n // the location changing.\n return {\n error: props.error !== undefined ? props.error : state.error,\n location: state.location,\n revalidation: props.revalidation || state.revalidation,\n };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"React Router caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n return this.state.error !== undefined ? (\n <RouteContext.Provider value={this.props.routeContext}>\n <RouteErrorContext.Provider\n value={this.state.error}\n children={this.props.component}\n />\n </RouteContext.Provider>\n ) : (\n this.props.children\n );\n }\n}\n\ninterface RenderedRouteProps {\n routeContext: RouteContextObject;\n match: RouteMatch<string, RouteObject>;\n children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n let dataRouterContext = React.useContext(DataRouterContext);\n\n // Track how deep we got in our render pass to emulate SSR componentDidCatch\n // in a DataStaticRouter\n if (\n dataRouterContext &&\n dataRouterContext.static &&\n dataRouterContext.staticContext &&\n (match.route.errorElement || match.route.ErrorBoundary)\n ) {\n dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n }\n\n return (\n <RouteContext.Provider value={routeContext}>\n {children}\n </RouteContext.Provider>\n );\n}\n\nexport function _renderMatches(\n matches: RouteMatch[] | null,\n parentMatches: RouteMatch[] = [],\n dataRouterState: RemixRouter[\"state\"] | null = null,\n future: RemixRouter[\"future\"] | null = null\n): React.ReactElement | null {\n if (matches == null) {\n if (!dataRouterState) {\n return null;\n }\n\n if (dataRouterState.errors) {\n // Don't bail if we have data router errors so we can render them in the\n // boundary. Use the pre-matched (or shimmed) matches\n matches = dataRouterState.matches as DataRouteMatch[];\n } else if (\n future?.v7_partialHydration &&\n parentMatches.length === 0 &&\n !dataRouterState.initialized &&\n dataRouterState.matches.length > 0\n ) {\n // Don't bail if we're initializing with partial hydration and we have\n // router matches. That means we're actively running `patchRoutesOnNavigation`\n // so we should render down the partial matches to the appropriate\n // `HydrateFallback`. We only do this if `parentMatches` is empty so it\n // only impacts the root matches for `RouterProvider` and no descendant\n // `<Routes>`\n matches = dataRouterState.matches as DataRouteMatch[];\n } else {\n return null;\n }\n }\n\n let renderedMatches = matches;\n\n // If we have data errors, trim matches to the highest error boundary\n let errors = dataRouterState?.errors;\n if (errors != null) {\n let errorIndex = renderedMatches.findIndex(\n (m) => m.route.id && errors?.[m.route.id] !== undefined\n );\n invariant(\n errorIndex >= 0,\n `Could not find a matching route for errors on route IDs: ${Object.keys(\n errors\n ).join(\",\")}`\n );\n renderedMatches = renderedMatches.slice(\n 0,\n Math.min(renderedMatches.length, errorIndex + 1)\n );\n }\n\n // If we're in a partial hydration mode, detect if we need to render down to\n // a given HydrateFallback while we load the rest of the hydration data\n let renderFallback = false;\n let fallbackIndex = -1;\n if (dataRouterState && future && future.v7_partialHydration) {\n for (let i = 0; i < renderedMatches.length; i++) {\n let match = renderedMatches[i];\n // Track the deepest fallback up until the first route without data\n if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {\n fallbackIndex = i;\n }\n\n if (match.route.id) {\n let { loaderData, errors } = dataRouterState;\n let needsToRunLoader =\n match.route.loader &&\n loaderData[match.route.id] === undefined &&\n (!errors || errors[match.route.id] === undefined);\n if (match.route.lazy || needsToRunLoader) {\n // We found the first route that's not ready to render (waiting on\n // lazy, or has a loader that hasn't run yet). Flag that we need to\n // render a fallback and render up until the appropriate fallback\n renderFallback = true;\n if (fallbackIndex >= 0) {\n renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);\n } else {\n renderedMatches = [renderedMatches[0]];\n }\n break;\n }\n }\n }\n }\n\n return renderedMatches.reduceRight((outlet, match, index) => {\n // Only data routers handle errors/fallbacks\n let error: any;\n let shouldRenderHydrateFallback = false;\n let errorElement: React.ReactNode | null = null;\n let hydrateFallbackElement: React.ReactNode | null = null;\n if (dataRouterState) {\n error = errors && match.route.id ? errors[match.route.id] : undefined;\n errorElement = match.route.errorElement || defaultErrorElement;\n\n if (renderFallback) {\n if (fallbackIndex < 0 && index === 0) {\n warningOnce(\n \"route-fallback\",\n false,\n \"No `HydrateFallback` element provided to render during initial hydration\"\n );\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = null;\n } else if (fallbackIndex === index) {\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = match.route.hydrateFallbackElement || null;\n }\n }\n }\n\n let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n let getChildren = () => {\n let children: React.ReactNode;\n if (error) {\n children = errorElement;\n } else if (shouldRenderHydrateFallback) {\n children = hydrateFallbackElement;\n } else if (match.route.Component) {\n // Note: This is a de-optimized path since React won't re-use the\n // ReactElement since it's identity changes with each new\n // React.createElement call. We keep this so folks can use\n // `<Route Component={...}>` in `<Routes>` but generally `Component`\n // usage is only advised in `RouterProvider` when we can convert it to\n // `element` ahead of time.\n children = <match.route.Component />;\n } else if (match.route.element) {\n children = match.route.element;\n } else {\n children = outlet;\n }\n return (\n <RenderedRoute\n match={match}\n routeContext={{\n outlet,\n matches,\n isDataRoute: dataRouterState != null,\n }}\n children={children}\n />\n );\n };\n // Only wrap in an error boundary within data router usages when we have an\n // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to\n // an ancestor ErrorBoundary/errorElement\n return dataRouterState &&\n (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n <RenderErrorBoundary\n location={dataRouterState.location}\n revalidation={dataRouterState.revalidation}\n component={errorElement}\n error={error}\n children={getChildren()}\n routeContext={{ outlet: null, matches, isDataRoute: true }}\n />\n ) : (\n getChildren()\n );\n }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n UseBlocker = \"useBlocker\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n UseBlocker = \"useBlocker\",\n UseLoaderData = \"useLoaderData\",\n UseActionData = \"useActionData\",\n UseRouteError = \"useRouteError\",\n UseNavigation = \"useNavigation\",\n UseRouteLoaderData = \"useRouteLoaderData\",\n UseMatches = \"useMatches\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n hookName: DataRouterHook | DataRouterStateHook\n) {\n return `${hookName} must be used within a data router. See https://reactrouter.com/v6/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n let ctx = React.useContext(DataRouterContext);\n invariant(ctx, getDataRouterConsoleError(hookName));\n return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n let state = React.useContext(DataRouterStateContext);\n invariant(state, getDataRouterConsoleError(hookName));\n return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n let route = React.useContext(RouteContext);\n invariant(route, getDataRouterConsoleError(hookName));\n return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n let route = useRouteContext(hookName);\n let thisRoute = route.matches[route.matches.length - 1];\n invariant(\n thisRoute.route.id,\n `${hookName} can only be used on routes that contain a unique \"id\"`\n );\n return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n return React.useMemo(\n () => ({\n revalidate: dataRouterContext.router.revalidate,\n state: state.revalidation,\n }),\n [dataRouterContext.router.revalidate, state.revalidation]\n );\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches(): UIMatch[] {\n let { matches, loaderData } = useDataRouterState(\n DataRouterStateHook.UseMatches\n );\n return React.useMemo(\n () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),\n [matches, loaderData]\n );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n if (state.errors && state.errors[routeId] != null) {\n console.error(\n `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n );\n return undefined;\n }\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseActionData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error. This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n let error = React.useContext(RouteErrorContext);\n let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n // If this was a render error, we put it in a RouteError context inside\n // of RenderErrorBoundary\n if (error !== undefined) {\n return error;\n }\n\n // Otherwise look for errors from our data router state\n return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `<Await />` value\n */\nexport function useAsyncValue(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `<Await />` value\n */\nexport function useAsyncError(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation. Mostly used to avoid\n * using half-filled form data. This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n let [blockerKey, setBlockerKey] = React.useState(\"\");\n let blockerFunction = React.useCallback<BlockerFunction>(\n (arg) => {\n if (typeof shouldBlock !== \"function\") {\n return !!shouldBlock;\n }\n if (basename === \"/\") {\n return shouldBlock(arg);\n }\n\n // If they provided us a function and we've got an active basename, strip\n // it from the locations we expose to the user to match the behavior of\n // useLocation\n let { currentLocation, nextLocation, historyAction } = arg;\n return shouldBlock({\n currentLocation: {\n ...currentLocation,\n pathname:\n stripBasename(currentLocation.pathname, basename) ||\n currentLocation.pathname,\n },\n nextLocation: {\n ...nextLocation,\n pathname:\n stripBasename(nextLocation.pathname, basename) ||\n nextLocation.pathname,\n },\n historyAction,\n });\n },\n [basename, shouldBlock]\n );\n\n // This effect is in charge of blocker key assignment and deletion (which is\n // tightly coupled to the key)\n React.useEffect(() => {\n let key = String(++blockerId);\n setBlockerKey(key);\n return () => router.deleteBlocker(key);\n }, [router]);\n\n // This effect handles assigning the blockerFunction. This is to handle\n // unstable blocker function identities, and happens only after the prior\n // effect so we don't get an orphaned blockerFunction in the router with a\n // key of \"\". Until then we just have the IDLE_BLOCKER.\n React.useEffect(() => {\n if (blockerKey !== \"\") {\n router.getBlocker(blockerKey, blockerFunction);\n }\n }, [router, blockerKey, blockerFunction]);\n\n // Prefer the blocker from `state` not `router.state` since DataRouterContext\n // is memoized so this ensures we update on blocker state updates\n return blockerKey && state.blockers.has(blockerKey)\n ? state.blockers.get(blockerKey)!\n : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our router subscriber yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n router.navigate(to);\n } else {\n router.navigate(to, { fromRouteId: id, ...options });\n }\n },\n [router, id]\n );\n\n return navigate;\n}\n\nconst alreadyWarned: Record<string, boolean> = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n if (!cond && !alreadyWarned[key]) {\n alreadyWarned[key] = true;\n warning(false, message);\n }\n}\n","import type { FutureConfig as RouterFutureConfig } from \"@remix-run/router\";\nimport type { FutureConfig as RenderFutureConfig } from \"./components\";\n\nconst alreadyWarned: { [key: string]: boolean } = {};\n\nexport function warnOnce(key: string, message: string): void {\n if (__DEV__ && !alreadyWarned[message]) {\n alreadyWarned[message] = true;\n console.warn(message);\n }\n}\n\nconst logDeprecation = (flag: string, msg: string, link: string) =>\n warnOnce(\n flag,\n `⚠️ React Router Future Flag Warning: ${msg}. ` +\n `You can use the \\`${flag}\\` future flag to opt-in early. ` +\n `For more information, see ${link}.`\n );\n\nexport function logV6DeprecationWarnings(\n renderFuture: Partial<RenderFutureConfig> | undefined,\n routerFuture?: Omit<RouterFutureConfig, \"v7_prependBasename\">\n) {\n if (renderFuture?.v7_startTransition === undefined) {\n logDeprecation(\n \"v7_startTransition\",\n \"React Router will begin wrapping state updates in `React.startTransition` in v7\",\n \"https://reactrouter.com/v6/upgrading/future#v7_starttransition\"\n );\n }\n\n if (\n renderFuture?.v7_relativeSplatPath === undefined &&\n (!routerFuture || routerFuture.v7_relativeSplatPath === undefined)\n ) {\n logDeprecation(\n \"v7_relativeSplatPath\",\n \"Relative route resolution within Splat routes is changing in v7\",\n \"https://reactrouter.com/v6/upgrading/future#v7_relativesplatpath\"\n );\n }\n\n if (routerFuture) {\n if (routerFuture.v7_fetcherPersist === undefined) {\n logDeprecation(\n \"v7_fetcherPersist\",\n \"The persistence behavior of fetchers is changing in v7\",\n \"https://reactrouter.com/v6/upgrading/future#v7_fetcherpersist\"\n );\n }\n\n if (routerFuture.v7_normalizeFormMethod === undefined) {\n logDeprecation(\n \"v7_normalizeFormMethod\",\n \"Casing of `formMethod` fields is being normalized to uppercase in v7\",\n \"https://reactrouter.com/v6/upgrading/future#v7_normalizeformmethod\"\n );\n }\n\n if (routerFuture.v7_partialHydration === undefined) {\n logDeprecation(\n \"v7_partialHydration\",\n \"`RouterProvider` hydration behavior is changing in v7\",\n \"https://reactrouter.com/v6/upgrading/future#v7_partialhydration\"\n );\n }\n\n if (routerFuture.v7_skipActionErrorRevalidation === undefined) {\n logDeprecation(\n \"v7_skipActionErrorRevalidation\",\n \"The revalidation behavior after 4xx/5xx `action` responses is changing in v7\",\n \"https://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation\"\n );\n }\n }\n}\n","import type {\n InitialEntry,\n LazyRouteFunction,\n Location,\n MemoryHistory,\n RelativeRoutingType,\n Router as RemixRouter,\n RouterState,\n RouterSubscriber,\n To,\n TrackedPromise,\n} from \"@remix-run/router\";\nimport {\n AbortedDeferredError,\n Action as NavigationType,\n createMemoryHistory,\n UNSAFE_getResolveToMatches as getResolveToMatches,\n UNSAFE_invariant as invariant,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\nimport * as React from \"react\";\n\nimport type {\n DataRouteObject,\n IndexRouteObject,\n Navigator,\n NonIndexRouteObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n} from \"./context\";\nimport {\n _renderMatches,\n useAsyncValue,\n useInRouterContext,\n useLocation,\n useNavigate,\n useOutlet,\n useRoutes,\n useRoutesImpl,\n} from \"./hooks\";\nimport { logV6DeprecationWarnings } from \"./deprecations\";\n\nexport interface FutureConfig {\n v7_relativeSplatPath: boolean;\n v7_startTransition: boolean;\n}\n\nexport interface RouterProviderProps {\n fallbackElement?: React.ReactNode;\n router: RemixRouter;\n // Only accept future flags relevant to rendering behavior\n // routing flags should be accessed via router.future\n future?: Partial<Pick<FutureConfig, \"v7_startTransition\">>;\n}\n\n/**\n Webpack + React 17 fails to compile on any of the following because webpack\n complains that `startTransition` doesn't exist in `React`:\n * import { startTransition } from \"react\"\n * import * as React from from \"react\";\n \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n * import * as React from from \"react\";\n \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n Moving it to a constant such as the following solves the Webpack/React 17 issue:\n * import * as React from from \"react\";\n const START_TRANSITION = \"startTransition\";\n START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n However, that introduces webpack/terser minification issues in production builds\n in React 18 where minification/obfuscation ends up removing the call of\n React.startTransition entirely from the first half of the ternary. Grabbing\n this exported reference once up front resolves that issue.\n\n See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n fallbackElement,\n router,\n future,\n}: RouterProviderProps): React.ReactElement {\n let [state, setStateImpl] = React.useState(router.state);\n let { v7_startTransition } = future || {};\n\n let setState = React.useCallback<RouterSubscriber>(\n (newState: RouterState) => {\n if (v7_startTransition && startTransitionImpl) {\n startTransitionImpl(() => setStateImpl(newState));\n } else {\n setStateImpl(newState);\n }\n },\n [setStateImpl, v7_startTransition]\n );\n\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n React.useEffect(() => {\n warning(\n fallbackElement == null || !router.future.v7_partialHydration,\n \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n );\n // Only log this once on initial mount\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n let navigator = React.useMemo((): Navigator => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: (n) => router.navigate(n),\n push: (to, state, opts) =>\n router.navigate(to, {\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n replace: (to, state, opts) =>\n router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n };\n }, [router]);\n\n let basename = router.basename || \"/\";\n\n let dataRouterContext = React.useMemo(\n () => ({\n router,\n navigator,\n static: false,\n basename,\n }),\n [router, navigator, basename]\n );\n\n React.useEffect(\n () => logV6DeprecationWarnings(future, router.future),\n [router, future]\n );\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a <script> here\n // containing the hydrated server-side staticContext (from StaticRouterProvider).\n // useId relies on the component tree structure to generate deterministic id's\n // so we need to ensure it remains the same on the client even though\n // we don't need the <script> tag\n return (\n <>\n <DataRouterContext.Provider value={dataRouterContext}>\n <DataRouterStateContext.Provider value={state}>\n <Router\n basename={basename}\n location={state.location}\n navigationType={state.historyAction}\n navigator={navigator}\n future={{\n v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n }}\n >\n {state.initialized || router.future.v7_partialHydration ? (\n <DataRoutes\n routes={router.routes}\n future={router.future}\n state={state}\n />\n ) : (\n fallbackElement\n )}\n </Router>\n </DataRouterStateContext.Provider>\n </DataRouterContext.Provider>\n {null}\n </>\n );\n}\n\nfunction DataRoutes({\n routes,\n future,\n state,\n}: {\n routes: DataRouteObject[];\n future: RemixRouter[\"future\"];\n state: RouterState;\n}): React.ReactElement | null {\n return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface MemoryRouterProps {\n basename?: string;\n children?: React.ReactNode;\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n future?: Partial<FutureConfig>;\n}\n\n/**\n * A `<Router>` that stores all entries in memory.\n *\n * @see https://reactrouter.com/v6/router-components/memory-router\n */\nexport function MemoryRouter({\n basename,\n children,\n initialEntries,\n initialIndex,\n future,\n}: MemoryRouterProps): React.ReactElement {\n let historyRef = React.useRef<MemoryHistory>();\n if (historyRef.current == null) {\n historyRef.current = createMemoryHistory({\n initialEntries,\n initialIndex,\n v5Compat: true,\n });\n }\n\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n future={future}\n />\n );\n}\n\nexport interface NavigateProps {\n to: To;\n replace?: boolean;\n state?: any;\n relative?: RelativeRoutingType;\n}\n\n/**\n * Changes the current location.\n *\n * Note: This API is mostly useful in React.Component subclasses that are not\n * able to use hooks. In functional components, we recommend you use the\n * `useNavigate` hook instead.\n *\n * @see https://reactrouter.com/v6/components/navigate\n */\nexport function Navigate({\n to,\n replace,\n state,\n relative,\n}: NavigateProps): null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of\n // the router loaded. We can help them understand how to avoid that.\n `<Navigate> may be used only in the context of a <Router> component.`\n );\n\n let { future, static: isStatic } = React.useContext(NavigationContext);\n\n warning(\n !isStatic,\n `<Navigate> must not be used on the initial render in a <StaticRouter>. ` +\n `This is a no-op, but you should modify your code so the <Navigate> is ` +\n `only ever rendered in response to some user interaction or state change.`\n );\n\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n let navigate = useNavigate();\n\n // Resolve the path outside of the effect so that when effects run twice in\n // StrictMode they navigate to the same place\n let path = resolveTo(\n to,\n getResolveToMatches(matches, future.v7_relativeSplatPath),\n locationPathname,\n relative === \"path\"\n );\n let jsonPath = JSON.stringify(path);\n\n React.useEffect(\n () => navigate(JSON.parse(jsonPath), { replace, state, relative }),\n [navigate, jsonPath, relative, replace, state]\n );\n\n return null;\n}\n\nexport interface OutletProps {\n context?: unknown;\n}\n\n/**\n * Renders the child route's element, if there is one.\n *\n * @see https://reactrouter.com/v6/components/outlet\n */\nexport function Outlet(props: OutletProps): React.ReactElement | null {\n return useOutlet(props.context);\n}\n\nexport interface PathRouteProps {\n caseSensitive?: NonIndexRouteObject[\"caseSensitive\"];\n path?: NonIndexRouteObject[\"path\"];\n id?: NonIndexRouteObject[\"id\"];\n lazy?: LazyRouteFunction<NonIndexRouteObject>;\n loader?: NonIndexRouteObject[\"loader\"];\n action?: NonIndexRouteObject[\"action\"];\n hasErrorBoundary?: NonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: NonIndexRouteObject[\"shouldRevalidate\"];\n handle?: NonIndexRouteObject[\"handle\"];\n index?: false;\n children?: React.ReactNode;\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n}\n\nexport interface LayoutRouteProps extends PathRouteProps {}\n\nexport interface IndexRouteProps {\n caseSensitive?: IndexRouteObject[\"caseSensitive\"];\n path?: IndexRouteObject[\"path\"];\n id?: IndexRouteObject[\"id\"];\n lazy?: LazyRouteFunction<IndexRouteObject>;\n loader?: IndexRouteObject[\"loader\"];\n action?: IndexRouteObject[\"action\"];\n hasErrorBoundary?: IndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: IndexRouteObject[\"shouldRevalidate\"];\n handle?: IndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n hydrateFallbackElement?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n HydrateFallback?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n}\n\nexport type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;\n\n/**\n * Declares an element that should be rendered at a certain URL path.\n *\n * @see https://reactrouter.com/v6/components/route\n */\nexport function Route(_props: RouteProps): React.ReactElement | null {\n invariant(\n false,\n `A <Route> is only ever to be used as the child of <Routes> element, ` +\n `never rendered directly. Please wrap your <Route> in a <Routes>.`\n );\n}\n\nexport interface RouterProps {\n basename?: string;\n children?: React.ReactNode;\n location: Partial<Location> | string;\n navigationType?: NavigationType;\n navigator: Navigator;\n static?: boolean;\n future?: Partial<Pick<FutureConfig, \"v7_relativeSplatPath\">>;\n}\n\n/**\n * Provides location context for the rest of the app.\n *\n * Note: You usually won't render a `<Router>` directly. Instead, you'll render a\n * router that is more specific to your environment such as a `<BrowserRouter>`\n * in web browsers or a `<StaticRouter>` for server rendering.\n *\n * @see https://reactrouter.com/v6/router-components/router\n */\nexport function Router({\n basename: basenameProp = \"/\",\n children = null,\n location: locationProp,\n navigationType = NavigationType.Pop,\n navigator,\n static: staticProp = false,\n future,\n}: RouterProps): React.ReactElement | null {\n invariant(\n !useInRouterContext(),\n `You cannot render a <Router> inside another <Router>.` +\n ` You should never have more than one in your app.`\n );\n\n // Preserve trailing slashes on basename, so we can let the user control\n // the enforcement of trailing slashes throughout the app\n let basename = basenameProp.replace(/^\\/*/, \"/\");\n let navigationContext = React.useMemo(\n () => ({\n basename,\n navigator,\n static: staticProp,\n future: {\n v7_relativeSplatPath: false,\n ...future,\n },\n }),\n [basename, future, navigator, staticProp]\n );\n\n if (typeof locationProp === \"string\") {\n locationProp = parsePath(locationProp);\n }\n\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n state = null,\n key = \"default\",\n } = locationProp;\n\n let locationContext = React.useMemo(() => {\n let trailingPathname = stripBasename(pathname, basename);\n\n if (trailingPathname == null) {\n return null;\n }\n\n return {\n location: {\n pathname: trailingPathname,\n search,\n hash,\n state,\n key,\n },\n navigationType,\n };\n }, [basename, pathname, search, hash, state, key, navigationType]);\n\n warning(\n locationContext != null,\n `<Router basename=\"${basename}\"> is not able to match the URL ` +\n `\"${pathname}${search}${hash}\" because it does not start with the ` +\n `basename, so the <Router> won't render anything.`\n );\n\n if (locationContext == null) {\n return null;\n }\n\n return (\n <NavigationContext.Provider value={navigationContext}>\n <LocationContext.Provider children={children} value={locationContext} />\n </NavigationContext.Provider>\n );\n}\n\nexport interface RoutesProps {\n children?: React.ReactNode;\n location?: Partial<Location> | string;\n}\n\n/**\n * A container for a nested tree of `<Route>` elements that renders the branch\n * that best matches the current location.\n *\n * @see https://reactrouter.com/v6/components/routes\n */\nexport function Routes({\n children,\n location,\n}: RoutesProps): React.ReactElement | null {\n return useRoutes(createRoutesFromChildren(children), location);\n}\n\nexport interface AwaitResolveRenderFunction {\n (data: Awaited<any>): React.ReactNode;\n}\n\nexport interface AwaitProps {\n children: React.ReactNode | AwaitResolveRenderFunction;\n errorElement?: React.ReactNode;\n resolve: TrackedPromise | any;\n}\n\n/**\n * Component to use for rendering lazily loaded data from returning defer()\n * in a loader function\n */\nexport function Await({ children, errorElement, resolve }: AwaitProps) {\n return (\n <AwaitErrorBoundary resolve={resolve} errorElement={errorElement}>\n <ResolveAwait>{children}</ResolveAwait>\n </AwaitErrorBoundary>\n );\n}\n\ntype AwaitErrorBoundaryProps = React.PropsWithChildren<{\n errorElement?: React.ReactNode;\n resolve: TrackedPromise | any;\n}>;\n\ntype AwaitErrorBoundaryState = {\n error: any;\n};\n\nenum AwaitRenderStatus {\n pending,\n success,\n error,\n}\n\nconst neverSettledPromise = new Promise(() => {});\n\nclass AwaitErrorBoundary extends React.Component<\n AwaitErrorBoundaryProps,\n AwaitErrorBoundaryState\n> {\n constructor(props: AwaitErrorBoundaryProps) {\n super(props);\n this.state = { error: null };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"<Await> caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n let { children, errorElement, resolve } = this.props;\n\n let promise: TrackedPromise | null = null;\n let status: AwaitRenderStatus = AwaitRenderStatus.pending;\n\n if (!(resolve instanceof Promise)) {\n // Didn't get a promise - provide as a resolved promise\n status = AwaitRenderStatus.success;\n promise = Promise.resolve();\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n Object.defineProperty(promise, \"_data\", { get: () => resolve });\n } else if (this.state.error) {\n // Caught a render error, provide it as a rejected promise\n status = AwaitRenderStatus.error;\n let renderError = this.state.error;\n promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n Object.defineProperty(promise, \"_error\", { get: () => renderError });\n } else if ((resolve as TrackedPromise)._tracked) {\n // Already tracked promise - check contents\n promise = resolve;\n status =\n \"_error\" in promise\n ? AwaitRenderStatus.error\n : \"_data\" in promise\n ? AwaitRenderStatus.success\n : AwaitRenderStatus.pending;\n } else {\n // Raw (untracked) promise - track it\n status = AwaitRenderStatus.pending;\n Object.defineProperty(resolve, \"_tracked\", { get: () => true });\n promise = resolve.then(\n (data: any) =>\n Object.defineProperty(resolve, \"_data\", { get: () => data }),\n (error: any) =>\n Object.defineProperty(resolve, \"_error\", { get: () => error })\n );\n }\n\n if (\n status === AwaitRenderStatus.error &&\n promise._error instanceof AbortedDeferredError\n ) {\n // Freeze the UI by throwing a never resolved promise\n throw neverSettledPromise;\n }\n\n if (status === AwaitRenderStatus.error && !errorElement) {\n // No errorElement, throw to the nearest route-level error boundary\n throw promise._error;\n }\n\n if (status === AwaitRenderStatus.error) {\n // Render via our errorElement\n return <AwaitContext.Provider value={promise} children={errorElement} />;\n }\n\n if (status === AwaitRenderStatus.success) {\n // Render children with resolved value\n return <AwaitContext.Provider value={promise} children={children} />;\n }\n\n // Throw to the suspense boundary\n throw promise;\n }\n}\n\n/**\n * @private\n * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`\n */\nfunction ResolveAwait({\n children,\n}: {\n children: React.ReactNode | AwaitResolveRenderFunction;\n}) {\n let data = useAsyncValue();\n let toRender = typeof children === \"function\" ? children(data) : children;\n return <>{toRender}</>;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// UTILS\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Creates a route config from a React \"children\" object, which is usually\n * either a `<Route>` element or an array of them. Used internally by\n * `<Routes>` to create a route config from its children.\n *\n * @see https://reactrouter.com/v6/utils/create-routes-from-children\n */\nexport function createRoutesFromChildren(\n children: React.ReactNode,\n parentPath: number[] = []\n): RouteObject[] {\n let routes: RouteObject[] = [];\n\n React.Children.forEach(children, (element, index) => {\n if (!React.isValidElement(element)) {\n // Ignore non-elements. This allows people to more easily inline\n // conditionals in their route config.\n return;\n }\n\n let treePath = [...parentPath, index];\n\n if (element.type === React.Fragment) {\n // Transparently support React.Fragment and its children.\n routes.push.apply(\n routes,\n createRoutesFromChildren(element.props.children, treePath)\n );\n return;\n }\n\n invariant(\n element.type === Route,\n `[${\n typeof element.type === \"string\" ? element.type : element.type.name\n }] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`\n );\n\n invariant(\n !element.props.index || !element.props.children,\n \"An index route cannot have child routes.\"\n );\n\n let route: RouteObject = {\n id: element.props.id || treePath.join(\"-\"),\n caseSensitive: element.props.caseSensitive,\n element: element.props.element,\n Component: element.props.Component,\n index: element.props.index,\n path: element.props.path,\n loader: element.props.loader,\n action: element.props.action,\n errorElement: element.props.errorElement,\n ErrorBoundary: element.props.ErrorBoundary,\n hasErrorBoundary:\n element.props.ErrorBoundary != null ||\n element.props.errorElement != null,\n shouldRevalidate: element.props.shouldRevalidate,\n handle: element.props.handle,\n lazy: element.props.lazy,\n };\n\n if (element.props.children) {\n route.children = createRoutesFromChildren(\n element.props.children,\n treePath\n );\n }\n\n routes.push(route);\n });\n\n return routes;\n}\n\n/**\n * Renders the result of `matchRoutes()` into a React element.\n */\nexport function renderMatches(\n matches: RouteMatch[] | null\n): React.ReactElement | null {\n return _renderMatches(matches);\n}\n","import * as React from \"react\";\nimport type {\n ActionFunction,\n ActionFunctionArgs,\n AgnosticPatchRoutesOnNavigationFunction,\n AgnosticPatchRoutesOnNavigationFunctionArgs,\n Blocker,\n BlockerFunction,\n DataStrategyFunction,\n DataStrategyFunctionArgs,\n DataStrategyMatch,\n DataStrategyResult,\n ErrorResponse,\n Fetcher,\n HydrationState,\n InitialEntry,\n JsonFunction,\n LazyRouteFunction,\n LoaderFunction,\n LoaderFunctionArgs,\n Location,\n Navigation,\n ParamParseKey,\n Params,\n Path,\n PathMatch,\n PathParam,\n PathPattern,\n RedirectFunction,\n RelativeRoutingType,\n Router as RemixRouter,\n FutureConfig as RouterFutureConfig,\n ShouldRevalidateFunction,\n ShouldRevalidateFunctionArgs,\n To,\n UIMatch,\n} from \"@remix-run/router\";\nimport {\n AbortedDeferredError,\n Action as NavigationType,\n createMemoryHistory,\n createPath,\n createRouter,\n defer,\n generatePath,\n isRouteErrorResponse,\n json,\n matchPath,\n matchRoutes,\n parsePath,\n redirect,\n redirectDocument,\n replace,\n resolvePath,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n AwaitProps,\n FutureConfig,\n IndexRouteProps,\n LayoutRouteProps,\n MemoryRouterProps,\n NavigateProps,\n OutletProps,\n PathRouteProps,\n RouteProps,\n RouterProps,\n RouterProviderProps,\n RoutesProps,\n} from \"./lib/components\";\nimport {\n Await,\n MemoryRouter,\n Navigate,\n Outlet,\n Route,\n Router,\n RouterProvider,\n Routes,\n createRoutesFromChildren,\n renderMatches,\n} from \"./lib/components\";\nimport type {\n DataRouteMatch,\n DataRouteObject,\n IndexRouteObject,\n NavigateOptions,\n Navigator,\n NonIndexRouteObject,\n RouteMatch,\n RouteObject,\n} from \"./lib/context\";\nimport {\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n} from \"./lib/context\";\nimport type { NavigateFunction } from \"./lib/hooks\";\nimport {\n useActionData,\n useAsyncError,\n useAsyncValue,\n useBlocker,\n useHref,\n useInRouterContext,\n useLoaderData,\n useLocation,\n useMatch,\n useMatches,\n useNavigate,\n useNavigation,\n useNavigationType,\n useOutlet,\n useOutletContext,\n useParams,\n useResolvedPath,\n useRevalidator,\n useRouteError,\n useRouteId,\n useRouteLoaderData,\n useRoutes,\n useRoutesImpl,\n} from \"./lib/hooks\";\nimport { logV6DeprecationWarnings } from \"./lib/deprecations\";\n\n// Exported for backwards compatibility, but not being used internally anymore\ntype Hash = string;\ntype Pathname = string;\ntype Search = string;\n\n// Expose react-router public API\nexport type {\n ActionFunction,\n ActionFunctionArgs,\n AwaitProps,\n DataRouteMatch,\n DataRouteObject,\n DataStrategyFunction,\n DataStrategyFunctionArgs,\n DataStrategyMatch,\n DataStrategyResult,\n ErrorResponse,\n Fetcher,\n FutureConfig,\n Hash,\n IndexRouteObject,\n IndexRouteProps,\n JsonFunction,\n LayoutRouteProps,\n LazyRouteFunction,\n LoaderFunction,\n LoaderFunctionArgs,\n Location,\n MemoryRouterProps,\n NavigateFunction,\n NavigateOptions,\n NavigateProps,\n Navigation,\n Navigator,\n NonIndexRouteObject,\n OutletProps,\n ParamParseKey,\n Params,\n Path,\n PathMatch,\n PathParam,\n PathPattern,\n PathRouteProps,\n Pathname,\n RedirectFunction,\n RelativeRoutingType,\n RouteMatch,\n RouteObject,\n RouteProps,\n RouterProps,\n RouterProviderProps,\n RoutesProps,\n Search,\n ShouldRevalidateFunction,\n ShouldRevalidateFunctionArgs,\n To,\n UIMatch,\n Blocker,\n BlockerFunction,\n};\nexport {\n AbortedDeferredError,\n Await,\n MemoryRouter,\n Navigate,\n NavigationType,\n Outlet,\n Route,\n Router,\n RouterProvider,\n Routes,\n createPath,\n createRoutesFromChildren,\n createRoutesFromChildren as createRoutesFromElements,\n defer,\n generatePath,\n isRouteErrorResponse,\n json,\n matchPath,\n matchRoutes,\n parsePath,\n redirect,\n redirectDocument,\n replace,\n renderMatches,\n resolvePath,\n useBlocker,\n useActionData,\n useAsyncError,\n useAsyncValue,\n useHref,\n useInRouterContext,\n useLoaderData,\n useLocation,\n useMatch,\n useMatches,\n useNavigate,\n useNavigation,\n useNavigationType,\n useOutlet,\n useOutletContext,\n useParams,\n useResolvedPath,\n useRevalidator,\n useRouteError,\n useRouteLoaderData,\n useRoutes,\n};\n\nexport type PatchRoutesOnNavigationFunctionArgs =\n AgnosticPatchRoutesOnNavigationFunctionArgs<RouteObject, RouteMatch>;\n\nexport type PatchRoutesOnNavigationFunction =\n AgnosticPatchRoutesOnNavigationFunction<RouteObject, RouteMatch>;\n\nfunction mapRouteProperties(route: RouteObject) {\n let updates: Partial<RouteObject> & { hasErrorBoundary: boolean } = {\n // Note: this check also occurs in createRoutesFromChildren so update\n // there if you change this -- please and thank you!\n hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null,\n };\n\n if (route.Component) {\n if (__DEV__) {\n if (route.element) {\n warning(\n false,\n \"You should not include both `Component` and `element` on your route - \" +\n \"`Component` will be used.\"\n );\n }\n }\n Object.assign(updates, {\n element: React.createElement(route.Component),\n Component: undefined,\n });\n }\n\n if (route.HydrateFallback) {\n if (__DEV__) {\n if (route.hydrateFallbackElement) {\n warning(\n false,\n \"You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - \" +\n \"`HydrateFallback` will be used.\"\n );\n }\n }\n Object.assign(updates, {\n hydrateFallbackElement: React.createElement(route.HydrateFallback),\n HydrateFallback: undefined,\n });\n }\n\n if (route.ErrorBoundary) {\n if (__DEV__) {\n if (route.errorElement) {\n warning(\n false,\n \"You should not include both `ErrorBoundary` and `errorElement` on your route - \" +\n \"`ErrorBoundary` will be used.\"\n );\n }\n }\n Object.assign(updates, {\n errorElement: React.createElement(route.ErrorBoundary),\n ErrorBoundary: undefined,\n });\n }\n\n return updates;\n}\n\nexport function createMemoryRouter(\n routes: RouteObject[],\n opts?: {\n basename?: string;\n future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n hydrationData?: HydrationState;\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n dataStrategy?: DataStrategyFunction;\n patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n }\n): RemixRouter {\n return createRouter({\n basename: opts?.basename,\n future: {\n ...opts?.future,\n v7_prependBasename: true,\n },\n history: createMemoryHistory({\n initialEntries: opts?.initialEntries,\n initialIndex: opts?.initialIndex,\n }),\n hydrationData: opts?.hydrationData,\n routes,\n mapRouteProperties,\n dataStrategy: opts?.dataStrategy,\n patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n }).initialize();\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n DataRouterContext as UNSAFE_DataRouterContext,\n DataRouterStateContext as UNSAFE_DataRouterStateContext,\n LocationContext as UNSAFE_LocationContext,\n NavigationContext as UNSAFE_NavigationContext,\n RouteContext as UNSAFE_RouteContext,\n mapRouteProperties as UNSAFE_mapRouteProperties,\n useRouteId as UNSAFE_useRouteId,\n useRoutesImpl as UNSAFE_useRoutesImpl,\n logV6DeprecationWarnings as UNSAFE_logV6DeprecationWarnings,\n};\n","import type {\n FormEncType,\n HTMLFormMethod,\n RelativeRoutingType,\n} from \"@remix-run/router\";\nimport { stripBasename, UNSAFE_warning as warning } from \"@remix-run/router\";\n\nexport const defaultMethod: HTMLFormMethod = \"get\";\nconst defaultEncType: FormEncType = \"application/x-www-form-urlencoded\";\n\nexport function isHtmlElement(object: any): object is HTMLElement {\n return object != null && typeof object.tagName === \"string\";\n}\n\nexport function isButtonElement(object: any): object is HTMLButtonElement {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"button\";\n}\n\nexport function isFormElement(object: any): object is HTMLFormElement {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"form\";\n}\n\nexport function isInputElement(object: any): object is HTMLInputElement {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"input\";\n}\n\ntype LimitedMouseEvent = Pick<\n MouseEvent,\n \"button\" | \"metaKey\" | \"altKey\" | \"ctrlKey\" | \"shiftKey\"\n>;\n\nfunction isModifiedEvent(event: LimitedMouseEvent) {\n return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);\n}\n\nexport function shouldProcessLinkClick(\n event: LimitedMouseEvent,\n target?: string\n) {\n return (\n event.button === 0 && // Ignore everything but left clicks\n (!target || target === \"_self\") && // Let browser handle \"target=_blank\" etc.\n !isModifiedEvent(event) // Ignore clicks with modifier keys\n );\n}\n\nexport type ParamKeyValuePair = [string, string];\n\nexport type URLSearchParamsInit =\n | string\n | ParamKeyValuePair[]\n | Record<string, string | string[]>\n | URLSearchParams;\n\n/**\n * Creates a URLSearchParams object using the given initializer.\n *\n * This is identical to `new URLSearchParams(init)` except it also\n * supports arrays as values in the object form of the initializer\n * instead of just strings. This is convenient when you need multiple\n * values for a given key, but don't want to use an array initializer.\n *\n * For example, instead of:\n *\n * let searchParams = new URLSearchParams([\n * ['sort', 'name'],\n * ['sort', 'price']\n * ]);\n *\n * you can do:\n *\n * let searchParams = createSearchParams({\n * sort: ['name', 'price']\n * });\n */\nexport function createSearchParams(\n init: URLSearchParamsInit = \"\"\n): URLSearchParams {\n return new URLSearchParams(\n typeof init === \"string\" ||\n Array.isArray(init) ||\n init instanceof URLSearchParams\n ? init\n : Object.keys(init).reduce((memo, key) => {\n let value = init[key];\n return memo.concat(\n Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]\n );\n }, [] as ParamKeyValuePair[])\n );\n}\n\nexport function getSearchParamsForLocation(\n locationSearch: string,\n defaultSearchParams: URLSearchParams | null\n) {\n let searchParams = createSearchParams(locationSearch);\n\n if (defaultSearchParams) {\n // Use `defaultSearchParams.forEach(...)` here instead of iterating of\n // `defaultSearchParams.keys()` to work-around a bug in Firefox related to\n // web extensions. Relevant Bugzilla tickets:\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984\n defaultSearchParams.forEach((_, key) => {\n if (!searchParams.has(key)) {\n defaultSearchParams.getAll(key).forEach((value) => {\n searchParams.append(key, value);\n });\n }\n });\n }\n\n return searchParams;\n}\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\nexport type SubmitTarget =\n | HTMLFormElement\n | HTMLButtonElement\n | HTMLInputElement\n | FormData\n | URLSearchParams\n | JsonValue\n | null;\n\n// One-time check for submitter support\nlet _formDataSupportsSubmitter: boolean | null = null;\n\nfunction isFormDataSubmitterSupported() {\n if (_formDataSupportsSubmitter === null) {\n try {\n new FormData(\n document.createElement(\"form\"),\n // @ts-expect-error if FormData supports the submitter parameter, this will throw\n 0\n );\n _formDataSupportsSubmitter = false;\n } catch (e) {\n _formDataSupportsSubmitter = true;\n }\n }\n return _formDataSupportsSubmitter;\n}\n\n/**\n * Submit options shared by both navigations and fetchers\n */\ninterface SharedSubmitOptions {\n /**\n * The HTTP method used to submit the form. Overrides `<form method>`.\n * Defaults to \"GET\".\n */\n method?: HTMLFormMethod;\n\n /**\n * The action URL path used to submit the form. Overrides `<form action>`.\n * Defaults to the path of the current route.\n */\n action?: string;\n\n /**\n * The encoding used to submit the form. Overrides `<form encType>`.\n * Defaults to \"application/x-www-form-urlencoded\".\n */\n encType?: FormEncType;\n\n /**\n * Determines whether the form action is relative to the route hierarchy or\n * the pathname. Use this if you want to opt out of navigating the route\n * hierarchy and want to instead route based on /-delimited URL segments\n */\n relative?: RelativeRoutingType;\n\n /**\n * In browser-based environments, prevent resetting scroll after this\n * navigation when using the <ScrollRestoration> component\n */\n preventScrollReset?: boolean;\n\n /**\n * Enable flushSync for this submission's state updates\n */\n flushSync?: boolean;\n}\n\n/**\n * Submit options available to fetchers\n */\nexport interface FetcherSubmitOptions extends SharedSubmitOptions {}\n\n/**\n * Submit options available to navigations\n */\nexport interface SubmitOptions extends FetcherSubmitOptions {\n /**\n * Set `true` to replace the current entry in the browser's history stack\n * instead of creating a new one (i.e. stay on \"the same page\"). Defaults\n * to `false`.\n */\n replace?: boolean;\n\n /**\n * State object to add to the history stack entry for this navigation\n */\n state?: any;\n\n /**\n * Indicate a specific fetcherKey to use when using navigate=false\n */\n fetcherKey?: string;\n\n /**\n * navigate=false will use a fetcher instead of a navigation\n */\n navigate?: boolean;\n\n /**\n * Enable view transitions on this submission navigation\n */\n viewTransition?: boolean;\n}\n\nconst supportedFormEncTypes: Set<FormEncType> = new Set([\n \"application/x-www-form-urlencoded\",\n \"multipart/form-data\",\n \"text/plain\",\n]);\n\nfunction getFormEncType(encType: string | null) {\n if (encType != null && !supportedFormEncTypes.has(encType as FormEncType)) {\n warning(\n false,\n `\"${encType}\" is not a valid \\`encType\\` for \\`<Form>\\`/\\`<fetcher.Form>\\` ` +\n `and will default to \"${defaultEncType}\"`\n );\n\n return null;\n }\n return encType;\n}\n\nexport function getFormSubmissionInfo(\n target: SubmitTarget,\n basename: string\n): {\n action: string | null;\n method: string;\n encType: string;\n formData: FormData | undefined;\n body: any;\n} {\n let method: string;\n let action: string | null;\n let encType: string;\n let formData: FormData | undefined;\n let body: any;\n\n if (isFormElement(target)) {\n // When grabbing the action from the element, it will have had the basename\n // prefixed to ensure non-JS scenarios work, so strip it since we'll\n // re-prefix in the router\n let attr = target.getAttribute(\"action\");\n action = attr ? stripBasename(attr, basename) : null;\n method = target.getAttribute(\"method\") || defaultMethod;\n encType = getFormEncType(target.getAttribute(\"enctype\")) || defaultEncType;\n\n formData = new FormData(target);\n } else if (\n isButtonElement(target) ||\n (isInputElement(target) &&\n (target.type === \"submit\" || target.type === \"image\"))\n ) {\n let form = target.form;\n\n if (form == null) {\n throw new Error(\n `Cannot submit a <button> or <input type=\"submit\"> without a <form>`\n );\n }\n\n // <button>/<input type=\"submit\"> may override attributes of <form>\n\n // When grabbing the action from the element, it will have had the basename\n // prefixed to ensure non-JS scenarios work, so strip it since we'll\n // re-prefix in the router\n let attr = target.getAttribute(\"formaction\") || form.getAttribute(\"action\");\n action = attr ? stripBasename(attr, basename) : null;\n\n method =\n target.getAttribute(\"formmethod\") ||\n form.getAttribute(\"method\") ||\n defaultMethod;\n encType =\n getFormEncType(target.getAttribute(\"formenctype\")) ||\n getFormEncType(form.getAttribute(\"enctype\")) ||\n defaultEncType;\n\n // Build a FormData object populated from a form and submitter\n formData = new FormData(form, target);\n\n // If this browser doesn't support the `FormData(el, submitter)` format,\n // then tack on the submitter value at the end. This is a lightweight\n // solution that is not 100% spec compliant. For complete support in older\n // browsers, consider using the `formdata-submitter-polyfill` package\n if (!isFormDataSubmitterSupported()) {\n let { name, type, value } = target;\n if (type === \"image\") {\n let prefix = name ? `${name}.` : \"\";\n formData.append(`${prefix}x`, \"0\");\n formData.append(`${prefix}y`, \"0\");\n } else if (name) {\n formData.append(name, value);\n }\n }\n } else if (isHtmlElement(target)) {\n throw new Error(\n `Cannot submit element that is not <form>, <button>, or ` +\n `<input type=\"submit|image\">`\n );\n } else {\n method = defaultMethod;\n action = null;\n encType = defaultEncType;\n body = target;\n }\n\n // Send body for <Form encType=\"text/plain\" so we encode it into text\n if (formData && encType === \"text/plain\") {\n body = formData;\n formData = undefined;\n }\n\n return { action, method: method.toLowerCase(), encType, formData, body };\n}\n","/**\n * NOTE: If you refactor this to split up the modules into separate files,\n * you'll need to update the rollup config for react-router-dom-v5-compat.\n */\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport type {\n DataRouteObject,\n FutureConfig,\n Location,\n NavigateOptions,\n NavigationType,\n Navigator,\n RelativeRoutingType,\n RouteObject,\n RouterProps,\n RouterProviderProps,\n To,\n DataStrategyFunction,\n PatchRoutesOnNavigationFunction,\n} from \"react-router\";\nimport {\n Router,\n createPath,\n useHref,\n useLocation,\n useMatches,\n useNavigate,\n useNavigation,\n useResolvedPath,\n useBlocker,\n UNSAFE_DataRouterContext as DataRouterContext,\n UNSAFE_DataRouterStateContext as DataRouterStateContext,\n UNSAFE_NavigationContext as NavigationContext,\n UNSAFE_RouteContext as RouteContext,\n UNSAFE_logV6DeprecationWarnings as logV6DeprecationWarnings,\n UNSAFE_mapRouteProperties as mapRouteProperties,\n UNSAFE_useRouteId as useRouteId,\n UNSAFE_useRoutesImpl as useRoutesImpl,\n} from \"react-router\";\nimport type {\n BrowserHistory,\n Fetcher,\n FormEncType,\n FormMethod,\n FutureConfig as RouterFutureConfig,\n GetScrollRestorationKeyFunction,\n HashHistory,\n History,\n HTMLFormMethod,\n HydrationState,\n Router as RemixRouter,\n V7_FormMethod,\n RouterState,\n RouterSubscriber,\n BlockerFunction,\n} from \"@remix-run/router\";\nimport {\n createRouter,\n createBrowserHistory,\n createHashHistory,\n joinPaths,\n stripBasename,\n UNSAFE_ErrorResponseImpl as ErrorResponseImpl,\n UNSAFE_invariant as invariant,\n UNSAFE_warning as warning,\n matchPath,\n IDLE_FETCHER,\n} from \"@remix-run/router\";\n\nimport type {\n SubmitOptions,\n ParamKeyValuePair,\n URLSearchParamsInit,\n SubmitTarget,\n FetcherSubmitOptions,\n} from \"./dom\";\nimport {\n createSearchParams,\n defaultMethod,\n getFormSubmissionInfo,\n getSearchParamsForLocation,\n shouldProcessLinkClick,\n} from \"./dom\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Re-exports\n////////////////////////////////////////////////////////////////////////////////\n\nexport type {\n FormEncType,\n FormMethod,\n GetScrollRestorationKeyFunction,\n ParamKeyValuePair,\n SubmitOptions,\n URLSearchParamsInit,\n V7_FormMethod,\n};\nexport { createSearchParams, ErrorResponseImpl as UNSAFE_ErrorResponseImpl };\n\n// Note: Keep in sync with react-router exports!\nexport type {\n ActionFunction,\n ActionFunctionArgs,\n AwaitProps,\n Blocker,\n BlockerFunction,\n DataRouteMatch,\n DataRouteObject,\n DataStrategyFunction,\n DataStrategyFunctionArgs,\n DataStrategyMatch,\n DataStrategyResult,\n ErrorResponse,\n Fetcher,\n FutureConfig,\n Hash,\n IndexRouteObject,\n IndexRouteProps,\n JsonFunction,\n LazyRouteFunction,\n LayoutRouteProps,\n LoaderFunction,\n LoaderFunctionArgs,\n Location,\n MemoryRouterProps,\n NavigateFunction,\n NavigateOptions,\n NavigateProps,\n Navigation,\n Navigator,\n NonIndexRouteObject,\n OutletProps,\n Params,\n ParamParseKey,\n PatchRoutesOnNavigationFunction,\n PatchRoutesOnNavigationFunctionArgs,\n Path,\n PathMatch,\n Pathname,\n PathParam,\n PathPattern,\n PathRouteProps,\n RedirectFunction,\n RelativeRoutingType,\n RouteMatch,\n RouteObject,\n RouteProps,\n RouterProps,\n RouterProviderProps,\n RoutesProps,\n Search,\n ShouldRevalidateFunction,\n ShouldRevalidateFunctionArgs,\n To,\n UIMatch,\n} from \"react-router\";\nexport {\n AbortedDeferredError,\n Await,\n MemoryRouter,\n Navigate,\n NavigationType,\n Outlet,\n Route,\n Router,\n Routes,\n createMemoryRouter,\n createPath,\n createRoutesFromChildren,\n createRoutesFromElements,\n defer,\n isRouteErrorResponse,\n generatePath,\n json,\n matchPath,\n matchRoutes,\n parsePath,\n redirect,\n redirectDocument,\n replace,\n renderMatches,\n resolvePath,\n useActionData,\n useAsyncError,\n useAsyncValue,\n useBlocker,\n useHref,\n useInRouterContext,\n useLoaderData,\n useLocation,\n useMatch,\n useMatches,\n useNavigate,\n useNavigation,\n useNavigationType,\n useOutlet,\n useOutletContext,\n useParams,\n useResolvedPath,\n useRevalidator,\n useRouteError,\n useRouteLoaderData,\n useRoutes,\n} from \"react-router\";\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n UNSAFE_DataRouterContext,\n UNSAFE_DataRouterStateContext,\n UNSAFE_NavigationContext,\n UNSAFE_LocationContext,\n UNSAFE_RouteContext,\n UNSAFE_useRouteId,\n} from \"react-router\";\n//#endregion\n\ndeclare global {\n var __staticRouterHydrationData: HydrationState | undefined;\n var __reactRouterVersion: string;\n interface Document {\n startViewTransition(cb: () => Promise<void> | void): ViewTransition;\n }\n}\n\n// HEY YOU! DON'T TOUCH THIS VARIABLE!\n//\n// It is replaced with the proper version at build time via a babel plugin in\n// the rollup config.\n//\n// Export a global property onto the window for React Router detection by the\n// Core Web Vitals Technology Report. This way they can configure the `wappalyzer`\n// to detect and properly classify live websites as being built with React Router:\n// https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json\nconst REACT_ROUTER_VERSION = \"0\";\ntry {\n window.__reactRouterVersion = REACT_ROUTER_VERSION;\n} catch (e) {\n // no-op\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Routers\n////////////////////////////////////////////////////////////////////////////////\n\ninterface DOMRouterOpts {\n basename?: string;\n future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n hydrationData?: HydrationState;\n dataStrategy?: DataStrategyFunction;\n patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n window?: Window;\n}\n\nexport function createBrowserRouter(\n routes: RouteObject[],\n opts?: DOMRouterOpts\n): RemixRouter {\n return createRouter({\n basename: opts?.basename,\n future: {\n ...opts?.future,\n v7_prependBasename: true,\n },\n history: createBrowserHistory({ window: opts?.window }),\n hydrationData: opts?.hydrationData || parseHydrationData(),\n routes,\n mapRouteProperties,\n dataStrategy: opts?.dataStrategy,\n patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n window: opts?.window,\n }).initialize();\n}\n\nexport function createHashRouter(\n routes: RouteObject[],\n opts?: DOMRouterOpts\n): RemixRouter {\n return createRouter({\n basename: opts?.basename,\n future: {\n ...opts?.future,\n v7_prependBasename: true,\n },\n history: createHashHistory({ window: opts?.window }),\n hydrationData: opts?.hydrationData || parseHydrationData(),\n routes,\n mapRouteProperties,\n dataStrategy: opts?.dataStrategy,\n patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n window: opts?.window,\n }).initialize();\n}\n\nfunction parseHydrationData(): HydrationState | undefined {\n let state = window?.__staticRouterHydrationData;\n if (state && state.errors) {\n state = {\n ...state,\n errors: deserializeErrors(state.errors),\n };\n }\n return state;\n}\n\nfunction deserializeErrors(\n errors: RemixRouter[\"state\"][\"errors\"]\n): RemixRouter[\"state\"][\"errors\"] {\n if (!errors) return null;\n let entries = Object.entries(errors);\n let serialized: RemixRouter[\"state\"][\"errors\"] = {};\n for (let [key, val] of entries) {\n // Hey you! If you change this, please change the corresponding logic in\n // serializeErrors in react-router-dom/server.tsx :)\n if (val && val.__type === \"RouteErrorResponse\") {\n serialized[key] = new ErrorResponseImpl(\n val.status,\n val.statusText,\n val.data,\n val.internal === true\n );\n } else if (val && val.__type === \"Error\") {\n // Attempt to reconstruct the right type of Error (i.e., ReferenceError)\n if (val.__subType) {\n let ErrorConstructor = window[val.__subType];\n if (typeof ErrorConstructor === \"function\") {\n try {\n // @ts-expect-error\n let error = new ErrorConstructor(val.message);\n // Wipe away the client-side stack trace. Nothing to fill it in with\n // because we don't serialize SSR stack traces for security reasons\n error.stack = \"\";\n serialized[key] = error;\n } catch (e) {\n // no-op - fall through and create a normal Error\n }\n }\n }\n\n if (serialized[key] == null) {\n let error = new Error(val.message);\n // Wipe away the client-side stack trace. Nothing to fill it in with\n // because we don't serialize SSR stack traces for security reasons\n error.stack = \"\";\n serialized[key] = error;\n }\n } else {\n serialized[key] = val;\n }\n }\n return serialized;\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Contexts\n////////////////////////////////////////////////////////////////////////////////\n\ntype ViewTransitionContextObject =\n | {\n isTransitioning: false;\n }\n | {\n isTransitioning: true;\n flushSync: boolean;\n currentLocation: Location;\n nextLocation: Location;\n };\n\nconst ViewTransitionContext = React.createContext<ViewTransitionContextObject>({\n isTransitioning: false,\n});\nif (__DEV__) {\n ViewTransitionContext.displayName = \"ViewTransition\";\n}\n\nexport { ViewTransitionContext as UNSAFE_ViewTransitionContext };\n\n// TODO: (v7) Change the useFetcher data from `any` to `unknown`\ntype FetchersContextObject = Map<string, any>;\n\nconst FetchersContext = React.createContext<FetchersContextObject>(new Map());\nif (__DEV__) {\n FetchersContext.displayName = \"Fetchers\";\n}\n\nexport { FetchersContext as UNSAFE_FetchersContext };\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Components\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n Webpack + React 17 fails to compile on any of the following because webpack\n complains that `startTransition` doesn't exist in `React`:\n * import { startTransition } from \"react\"\n * import * as React from from \"react\";\n \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n * import * as React from from \"react\";\n \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n Moving it to a constant such as the following solves the Webpack/React 17 issue:\n * import * as React from from \"react\";\n const START_TRANSITION = \"startTransition\";\n START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n However, that introduces webpack/terser minification issues in production builds\n in React 18 where minification/obfuscation ends up removing the call of\n React.startTransition entirely from the first half of the ternary. Grabbing\n this exported reference once up front resolves that issue.\n\n See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\nconst FLUSH_SYNC = \"flushSync\";\nconst flushSyncImpl = ReactDOM[FLUSH_SYNC];\nconst USE_ID = \"useId\";\nconst useIdImpl = React[USE_ID];\n\nfunction startTransitionSafe(cb: () => void) {\n if (startTransitionImpl) {\n startTransitionImpl(cb);\n } else {\n cb();\n }\n}\n\nfunction flushSyncSafe(cb: () => void) {\n if (flushSyncImpl) {\n flushSyncImpl(cb);\n } else {\n cb();\n }\n}\n\ninterface ViewTransition {\n finished: Promise<void>;\n ready: Promise<void>;\n updateCallbackDone: Promise<void>;\n skipTransition(): void;\n}\n\nclass Deferred<T> {\n status: \"pending\" | \"resolved\" | \"rejected\" = \"pending\";\n promise: Promise<T>;\n // @ts-expect-error - no initializer\n resolve: (value: T) => void;\n // @ts-expect-error - no initializer\n reject: (reason?: unknown) => void;\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = (value) => {\n if (this.status === \"pending\") {\n this.status = \"resolved\";\n resolve(value);\n }\n };\n this.reject = (reason) => {\n if (this.status === \"pending\") {\n this.status = \"rejected\";\n reject(reason);\n }\n };\n });\n }\n}\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n fallbackElement,\n router,\n future,\n}: RouterProviderProps): React.ReactElement {\n let [state, setStateImpl] = React.useState(router.state);\n let [pendingState, setPendingState] = React.useState<RouterState>();\n let [vtContext, setVtContext] = React.useState<ViewTransitionContextObject>({\n isTransitioning: false,\n });\n let [renderDfd, setRenderDfd] = React.useState<Deferred<void>>();\n let [transition, setTransition] = React.useState<ViewTransition>();\n let [interruption, setInterruption] = React.useState<{\n state: RouterState;\n currentLocation: Location;\n nextLocation: Location;\n }>();\n let fetcherData = React.useRef<Map<string, any>>(new Map());\n let { v7_startTransition } = future || {};\n\n let optInStartTransition = React.useCallback(\n (cb: () => void) => {\n if (v7_startTransition) {\n startTransitionSafe(cb);\n } else {\n cb();\n }\n },\n [v7_startTransition]\n );\n\n let setState = React.useCallback<RouterSubscriber>(\n (\n newState: RouterState,\n {\n deletedFetchers,\n flushSync: flushSync,\n viewTransitionOpts: viewTransitionOpts,\n }\n ) => {\n newState.fetchers.forEach((fetcher, key) => {\n if (fetcher.data !== undefined) {\n fetcherData.current.set(key, fetcher.data);\n }\n });\n deletedFetchers.forEach((key) => fetcherData.current.delete(key));\n\n let isViewTransitionUnavailable =\n router.window == null ||\n router.window.document == null ||\n typeof router.window.document.startViewTransition !== \"function\";\n\n // If this isn't a view transition or it's not available in this browser,\n // just update and be done with it\n if (!viewTransitionOpts || isViewTransitionUnavailable) {\n if (flushSync) {\n flushSyncSafe(() => setStateImpl(newState));\n } else {\n optInStartTransition(() => setStateImpl(newState));\n }\n return;\n }\n\n // flushSync + startViewTransition\n if (flushSync) {\n // Flush through the context to mark DOM elements as transition=ing\n flushSyncSafe(() => {\n // Cancel any pending transitions\n if (transition) {\n renderDfd && renderDfd.resolve();\n transition.skipTransition();\n }\n setVtContext({\n isTransitioning: true,\n flushSync: true,\n currentLocation: viewTransitionOpts.currentLocation,\n nextLocation: viewTransitionOpts.nextLocation,\n });\n });\n\n // Update the DOM\n let t = router.window!.document.startViewTransition(() => {\n flushSyncSafe(() => setStateImpl(newState));\n });\n\n // Clean up after the animation completes\n t.finished.finally(() => {\n flushSyncSafe(() => {\n setRenderDfd(undefined);\n setTransition(undefined);\n setPendingState(undefined);\n setVtContext({ isTransitioning: false });\n });\n });\n\n flushSyncSafe(() => setTransition(t));\n return;\n }\n\n // startTransition + startViewTransition\n if (transition) {\n // Interrupting an in-progress transition, cancel and let everything flush\n // out, and then kick off a new transition from the interruption state\n renderDfd && renderDfd.resolve();\n transition.skipTransition();\n setInterruption({\n state: newState,\n currentLocation: viewTransitionOpts.currentLocation,\n nextLocation: viewTransitionOpts.nextLocation,\n });\n } else {\n // Completed navigation update with opted-in view transitions, let 'er rip\n setPendingState(newState);\n setVtContext({\n isTransitioning: true,\n flushSync: false,\n currentLocation: viewTransitionOpts.currentLocation,\n nextLocation: viewTransitionOpts.nextLocation,\n });\n }\n },\n [router.window, transition, renderDfd, fetcherData, optInStartTransition]\n );\n\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n // When we start a view transition, create a Deferred we can use for the\n // eventual \"completed\" render\n React.useEffect(() => {\n if (vtContext.isTransitioning && !vtContext.flushSync) {\n setRenderDfd(new Deferred<void>());\n }\n }, [vtContext]);\n\n // Once the deferred is created, kick off startViewTransition() to update the\n // DOM and then wait on the Deferred to resolve (indicating the DOM update has\n // happened)\n React.useEffect(() => {\n if (renderDfd && pendingState && router.window) {\n let newState = pendingState;\n let renderPromise = renderDfd.promise;\n let transition = router.window.document.startViewTransition(async () => {\n optInStartTransition(() => setStateImpl(newState));\n await renderPromise;\n });\n transition.finished.finally(() => {\n setRenderDfd(undefined);\n setTransition(undefined);\n setPendingState(undefined);\n setVtContext({ isTransitioning: false });\n });\n setTransition(transition);\n }\n }, [optInStartTransition, pendingState, renderDfd, router.window]);\n\n // When the new location finally renders and is committed to the DOM, this\n // effect will run to resolve the transition\n React.useEffect(() => {\n if (\n renderDfd &&\n pendingState &&\n state.location.key === pendingState.location.key\n ) {\n renderDfd.resolve();\n }\n }, [renderDfd, transition, state.location, pendingState]);\n\n // If we get interrupted with a new navigation during a transition, we skip\n // the active transition, let it cleanup, then kick it off again here\n React.useEffect(() => {\n if (!vtContext.isTransitioning && interruption) {\n setPendingState(interruption.state);\n setVtContext({\n isTransitioning: true,\n flushSync: false,\n currentLocation: interruption.currentLocation,\n nextLocation: interruption.nextLocation,\n });\n setInterruption(undefined);\n }\n }, [vtContext.isTransitioning, interruption]);\n\n React.useEffect(() => {\n warning(\n fallbackElement == null || !router.future.v7_partialHydration,\n \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n );\n // Only log this once on initial mount\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n let navigator = React.useMemo((): Navigator => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: (n) => router.navigate(n),\n push: (to, state, opts) =>\n router.navigate(to, {\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n replace: (to, state, opts) =>\n router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n };\n }, [router]);\n\n let basename = router.basename || \"/\";\n\n let dataRouterContext = React.useMemo(\n () => ({\n router,\n navigator,\n static: false,\n basename,\n }),\n [router, navigator, basename]\n );\n\n let routerFuture = React.useMemo<RouterProps[\"future\"]>(\n () => ({\n v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n }),\n [router.future.v7_relativeSplatPath]\n );\n\n React.useEffect(\n () => logV6DeprecationWarnings(future, router.future),\n [future, router.future]\n );\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a <script> here\n // containing the hydrated server-side staticContext (from StaticRouterProvider).\n // useId relies on the component tree structure to generate deterministic id's\n // so we need to ensure it remains the same on the client even though\n // we don't need the <script> tag\n return (\n <>\n <DataRouterContext.Provider value={dataRouterContext}>\n <DataRouterStateContext.Provider value={state}>\n <FetchersContext.Provider value={fetcherData.current}>\n <ViewTransitionContext.Provider value={vtContext}>\n <Router\n basename={basename}\n location={state.location}\n navigationType={state.historyAction}\n navigator={navigator}\n future={routerFuture}\n >\n {state.initialized || router.future.v7_partialHydration ? (\n <MemoizedDataRoutes\n routes={router.routes}\n future={router.future}\n state={state}\n />\n ) : (\n fallbackElement\n )}\n </Router>\n </ViewTransitionContext.Provider>\n </FetchersContext.Provider>\n </DataRouterStateContext.Provider>\n </DataRouterContext.Provider>\n {null}\n </>\n );\n}\n\n// Memoize to avoid re-renders when updating `ViewTransitionContext`\nconst MemoizedDataRoutes = React.memo(DataRoutes);\n\nfunction DataRoutes({\n routes,\n future,\n state,\n}: {\n routes: DataRouteObject[];\n future: RemixRouter[\"future\"];\n state: RouterState;\n}): React.ReactElement | null {\n return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface BrowserRouterProps {\n basename?: string;\n children?: React.ReactNode;\n future?: Partial<FutureConfig>;\n window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Provides the cleanest URLs.\n */\nexport function BrowserRouter({\n basename,\n children,\n future,\n window,\n}: BrowserRouterProps) {\n let historyRef = React.useRef<BrowserHistory>();\n if (historyRef.current == null) {\n historyRef.current = createBrowserHistory({ window, v5Compat: true });\n }\n\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n future={future}\n />\n );\n}\n\nexport interface HashRouterProps {\n basename?: string;\n children?: React.ReactNode;\n future?: Partial<FutureConfig>;\n window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Stores the location in the hash\n * portion of the URL so it is not sent to the server.\n */\nexport function HashRouter({\n basename,\n children,\n future,\n window,\n}: HashRouterProps) {\n let historyRef = React.useRef<HashHistory>();\n if (historyRef.current == null) {\n historyRef.current = createHashHistory({ window, v5Compat: true });\n }\n\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n future={future}\n />\n );\n}\n\nexport interface HistoryRouterProps {\n basename?: string;\n children?: React.ReactNode;\n future?: FutureConfig;\n history: History;\n}\n\n/**\n * A `<Router>` that accepts a pre-instantiated history object. It's important\n * to note that using your own history object is highly discouraged and may add\n * two versions of the history library to your bundles unless you use the same\n * version of the history library that React Router uses internally.\n */\nfunction HistoryRouter({\n basename,\n children,\n future,\n history,\n}: HistoryRouterProps) {\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n future={future}\n />\n );\n}\n\nif (__DEV__) {\n HistoryRouter.displayName = \"unstable_HistoryRouter\";\n}\n\nexport { HistoryRouter as unstable_HistoryRouter };\n\nexport interface LinkProps\n extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n reloadDocument?: boolean;\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n to: To;\n viewTransition?: boolean;\n}\n\nconst isBrowser =\n typeof window !== \"undefined\" &&\n typeof window.document !== \"undefined\" &&\n typeof window.document.createElement !== \"undefined\";\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\n/**\n * The public API for rendering a history-aware `<a>`.\n */\nexport const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(\n function LinkWithRef(\n {\n onClick,\n relative,\n reloadDocument,\n replace,\n state,\n target,\n to,\n preventScrollReset,\n viewTransition,\n ...rest\n },\n ref\n ) {\n let { basename } = React.useContext(NavigationContext);\n\n // Rendered into <a href> for absolute URLs\n let absoluteHref;\n let isExternal = false;\n\n if (typeof to === \"string\" && ABSOLUTE_URL_REGEX.test(to)) {\n // Render the absolute href server- and client-side\n absoluteHref = to;\n\n // Only check for external origins client-side\n if (isBrowser) {\n try {\n let currentUrl = new URL(window.location.href);\n let targetUrl = to.startsWith(\"//\")\n ? new URL(currentUrl.protocol + to)\n : new URL(to);\n let path = stripBasename(targetUrl.pathname, basename);\n\n if (targetUrl.origin === currentUrl.origin && path != null) {\n // Strip the protocol/origin/basename for same-origin absolute URLs\n to = path + targetUrl.search + targetUrl.hash;\n } else {\n isExternal = true;\n }\n } catch (e) {\n // We can't do external URL detection without a valid URL\n warning(\n false,\n `<Link to=\"${to}\"> contains an invalid URL which will probably break ` +\n `when clicked - please update to a valid URL path.`\n );\n }\n }\n }\n\n // Rendered into <a href> for relative URLs\n let href = useHref(to, { relative });\n\n let internalOnClick = useLinkClickHandler(to, {\n replace,\n state,\n target,\n preventScrollReset,\n relative,\n viewTransition,\n });\n function handleClick(\n event: React.MouseEvent<HTMLAnchorElement, MouseEvent>\n ) {\n if (onClick) onClick(event);\n if (!event.defaultPrevented) {\n internalOnClick(event);\n }\n }\n\n return (\n // eslint-disable-next-line jsx-a11y/anchor-has-content\n <a\n {...rest}\n href={absoluteHref || href}\n onClick={isExternal || reloadDocument ? onClick : handleClick}\n ref={ref}\n target={target}\n />\n );\n }\n);\n\nif (__DEV__) {\n Link.displayName = \"Link\";\n}\n\nexport type NavLinkRenderProps = {\n isActive: boolean;\n isPending: boolean;\n isTransitioning: boolean;\n};\n\nexport interface NavLinkProps\n extends Omit<LinkProps, \"className\" | \"style\" | \"children\"> {\n children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);\n caseSensitive?: boolean;\n className?: string | ((props: NavLinkRenderProps) => string | undefined);\n end?: boolean;\n style?:\n | React.CSSProperties\n | ((props: NavLinkRenderProps) => React.CSSProperties | undefined);\n}\n\n/**\n * A `<Link>` wrapper that knows if it's \"active\" or not.\n */\nexport const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(\n function NavLinkWithRef(\n {\n \"aria-current\": ariaCurrentProp = \"page\",\n caseSensitive = false,\n className: classNameProp = \"\",\n end = false,\n style: styleProp,\n to,\n viewTransition,\n children,\n ...rest\n },\n ref\n ) {\n let path = useResolvedPath(to, { relative: rest.relative });\n let location = useLocation();\n let routerState = React.useContext(DataRouterStateContext);\n let { navigator, basename } = React.useContext(NavigationContext);\n let isTransitioning =\n routerState != null &&\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useViewTransitionState(path) &&\n viewTransition === true;\n\n let toPathname = navigator.encodeLocation\n ? navigator.encodeLocation(path).pathname\n : path.pathname;\n let locationPathname = location.pathname;\n let nextLocationPathname =\n routerState && routerState.navigation && routerState.navigation.location\n ? routerState.navigation.location.pathname\n : null;\n\n if (!caseSensitive) {\n locationPathname = locationPathname.toLowerCase();\n nextLocationPathname = nextLocationPathname\n ? nextLocationPathname.toLowerCase()\n : null;\n toPathname = toPathname.toLowerCase();\n }\n\n if (nextLocationPathname && basename) {\n nextLocationPathname =\n stripBasename(nextLocationPathname, basename) || nextLocationPathname;\n }\n\n // If the `to` has a trailing slash, look at that exact spot. Otherwise,\n // we're looking for a slash _after_ what's in `to`. For example:\n //\n // <NavLink to=\"/users\"> and <NavLink to=\"/users/\">\n // both want to look for a / at index 6 to match URL `/users/matt`\n const endSlashPosition =\n toPathname !== \"/\" && toPathname.endsWith(\"/\")\n ? toPathname.length - 1\n : toPathname.length;\n let isActive =\n locationPathname === toPathname ||\n (!end &&\n locationPathname.startsWith(toPathname) &&\n locationPathname.charAt(endSlashPosition) === \"/\");\n\n let isPending =\n nextLocationPathname != null &&\n (nextLocationPathname === toPathname ||\n (!end &&\n nextLocationPathname.startsWith(toPathname) &&\n nextLocationPathname.charAt(toPathname.length) === \"/\"));\n\n let renderProps = {\n isActive,\n isPending,\n isTransitioning,\n };\n\n let ariaCurrent = isActive ? ariaCurrentProp : undefined;\n\n let className: string | undefined;\n if (typeof classNameProp === \"function\") {\n className = classNameProp(renderProps);\n } else {\n // If the className prop is not a function, we use a default `active`\n // class for <NavLink />s that are active. In v5 `active` was the default\n // value for `activeClassName`, but we are removing that API and can still\n // use the old default behavior for a cleaner upgrade path and keep the\n // simple styling rules working as they currently do.\n className = [\n classNameProp,\n isActive ? \"active\" : null,\n isPending ? \"pending\" : null,\n isTransitioning ? \"transitioning\" : null,\n ]\n .filter(Boolean)\n .join(\" \");\n }\n\n let style =\n typeof styleProp === \"function\" ? styleProp(renderProps) : styleProp;\n\n return (\n <Link\n {...rest}\n aria-current={ariaCurrent}\n className={className}\n ref={ref}\n style={style}\n to={to}\n viewTransition={viewTransition}\n >\n {typeof children === \"function\" ? children(renderProps) : children}\n </Link>\n );\n }\n);\n\nif (__DEV__) {\n NavLink.displayName = \"NavLink\";\n}\n\n/**\n * Form props shared by navigations and fetchers\n */\ninterface SharedFormProps extends React.FormHTMLAttributes<HTMLFormElement> {\n /**\n * The HTTP verb to use when the form is submit. Supports \"get\", \"post\",\n * \"put\", \"delete\", \"patch\".\n */\n method?: HTMLFormMethod;\n\n /**\n * `<form encType>` - enhancing beyond the normal string type and limiting\n * to the built-in browser supported values\n */\n encType?:\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"text/plain\";\n\n /**\n * Normal `<form action>` but supports React Router's relative paths.\n */\n action?: string;\n\n /**\n * Determines whether the form action is relative to the route hierarchy or\n * the pathname. Use this if you want to opt out of navigating the route\n * hierarchy and want to instead route based on /-delimited URL segments\n */\n relative?: RelativeRoutingType;\n\n /**\n * Prevent the scroll position from resetting to the top of the viewport on\n * completion of the navigation when using the <ScrollRestoration> component\n */\n preventScrollReset?: boolean;\n\n /**\n * A function to call when the form is submitted. If you call\n * `event.preventDefault()` then this form will not do anything.\n */\n onSubmit?: React.FormEventHandler<HTMLFormElement>;\n}\n\n/**\n * Form props available to fetchers\n */\nexport interface FetcherFormProps extends SharedFormProps {}\n\n/**\n * Form props available to navigations\n */\nexport interface FormProps extends SharedFormProps {\n /**\n * Indicate a specific fetcherKey to use when using navigate=false\n */\n fetcherKey?: string;\n\n /**\n * navigate=false will use a fetcher instead of a navigation\n */\n navigate?: boolean;\n\n /**\n * Forces a full document navigation instead of a fetch.\n */\n reloadDocument?: boolean;\n\n /**\n * Replaces the current entry in the browser history stack when the form\n * navigates. Use this if you don't want the user to be able to click \"back\"\n * to the page with the form on it.\n */\n replace?: boolean;\n\n /**\n * State object to add to the history stack entry for this navigation\n */\n state?: any;\n\n /**\n * Enable view transitions on this Form navigation\n */\n viewTransition?: boolean;\n}\n\ntype HTMLSubmitEvent = React.BaseSyntheticEvent<\n SubmitEvent,\n Event,\n HTMLFormElement\n>;\n\ntype HTMLFormSubmitter = HTMLButtonElement | HTMLInputElement;\n\n/**\n * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except\n * that the interaction with the server is with `fetch` instead of new document\n * requests, allowing components to add nicer UX to the page as the form is\n * submitted and returns with data.\n */\nexport const Form = React.forwardRef<HTMLFormElement, FormProps>(\n (\n {\n fetcherKey,\n navigate,\n reloadDocument,\n replace,\n state,\n method = defaultMethod,\n action,\n onSubmit,\n relative,\n preventScrollReset,\n viewTransition,\n ...props\n },\n forwardedRef\n ) => {\n let submit = useSubmit();\n let formAction = useFormAction(action, { relative });\n let formMethod: HTMLFormMethod =\n method.toLowerCase() === \"get\" ? \"get\" : \"post\";\n\n let submitHandler: React.FormEventHandler<HTMLFormElement> = (event) => {\n onSubmit && onSubmit(event);\n if (event.defaultPrevented) return;\n event.preventDefault();\n\n let submitter = (event as unknown as HTMLSubmitEvent).nativeEvent\n .submitter as HTMLFormSubmitter | null;\n\n let submitMethod =\n (submitter?.getAttribute(\"formmethod\") as HTMLFormMethod | undefined) ||\n method;\n\n submit(submitter || event.currentTarget, {\n fetcherKey,\n method: submitMethod,\n navigate,\n replace,\n state,\n relative,\n preventScrollReset,\n viewTransition,\n });\n };\n\n return (\n <form\n ref={forwardedRef}\n method={formMethod}\n action={formAction}\n onSubmit={reloadDocument ? onSubmit : submitHandler}\n {...props}\n />\n );\n }\n);\n\nif (__DEV__) {\n Form.displayName = \"Form\";\n}\n\nexport interface ScrollRestorationProps {\n getKey?: GetScrollRestorationKeyFunction;\n storageKey?: string;\n}\n\n/**\n * This component will emulate the browser's scroll restoration on location\n * changes.\n */\nexport function ScrollRestoration({\n getKey,\n storageKey,\n}: ScrollRestorationProps) {\n useScrollRestoration({ getKey, storageKey });\n return null;\n}\n\nif (__DEV__) {\n ScrollRestoration.displayName = \"ScrollRestoration\";\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hooks\n////////////////////////////////////////////////////////////////////////////////\n\nenum DataRouterHook {\n UseScrollRestoration = \"useScrollRestoration\",\n UseSubmit = \"useSubmit\",\n UseSubmitFetcher = \"useSubmitFetcher\",\n UseFetcher = \"useFetcher\",\n useViewTransitionState = \"useViewTransitionState\",\n}\n\nenum DataRouterStateHook {\n UseFetcher = \"useFetcher\",\n UseFetchers = \"useFetchers\",\n UseScrollRestoration = \"useScrollRestoration\",\n}\n\n// Internal hooks\n\nfunction getDataRouterConsoleError(\n hookName: DataRouterHook | DataRouterStateHook\n) {\n return `${hookName} must be used within a data router. See https://reactrouter.com/v6/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n let ctx = React.useContext(DataRouterContext);\n invariant(ctx, getDataRouterConsoleError(hookName));\n return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n let state = React.useContext(DataRouterStateContext);\n invariant(state, getDataRouterConsoleError(hookName));\n return state;\n}\n\n// External hooks\n\n/**\n * Handles the click behavior for router `<Link>` components. This is useful if\n * you need to create custom `<Link>` components with the same click behavior we\n * use in our exported `<Link>`.\n */\nexport function useLinkClickHandler<E extends Element = HTMLAnchorElement>(\n to: To,\n {\n target,\n replace: replaceProp,\n state,\n preventScrollReset,\n relative,\n viewTransition,\n }: {\n target?: React.HTMLAttributeAnchorTarget;\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n viewTransition?: boolean;\n } = {}\n): (event: React.MouseEvent<E, MouseEvent>) => void {\n let navigate = useNavigate();\n let location = useLocation();\n let path = useResolvedPath(to, { relative });\n\n return React.useCallback(\n (event: React.MouseEvent<E, MouseEvent>) => {\n if (shouldProcessLinkClick(event, target)) {\n event.preventDefault();\n\n // If the URL hasn't changed, a regular <a> will do a replace instead of\n // a push, so do the same here unless the replace prop is explicitly set\n let replace =\n replaceProp !== undefined\n ? replaceProp\n : createPath(location) === createPath(path);\n\n navigate(to, {\n replace,\n state,\n preventScrollReset,\n relative,\n viewTransition,\n });\n }\n },\n [\n location,\n navigate,\n path,\n replaceProp,\n state,\n target,\n to,\n preventScrollReset,\n relative,\n viewTransition,\n ]\n );\n}\n\n/**\n * A convenient wrapper for reading and writing search parameters via the\n * URLSearchParams interface.\n */\nexport function useSearchParams(\n defaultInit?: URLSearchParamsInit\n): [URLSearchParams, SetURLSearchParams] {\n warning(\n typeof URLSearchParams !== \"undefined\",\n `You cannot use the \\`useSearchParams\\` hook in a browser that does not ` +\n `support the URLSearchParams API. If you need to support Internet ` +\n `Explorer 11, we recommend you load a polyfill such as ` +\n `https://github.com/ungap/url-search-params.`\n );\n\n let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));\n let hasSetSearchParamsRef = React.useRef(false);\n\n let location = useLocation();\n let searchParams = React.useMemo(\n () =>\n // Only merge in the defaults if we haven't yet called setSearchParams.\n // Once we call that we want those to take precedence, otherwise you can't\n // remove a param with setSearchParams({}) if it has an initial value\n getSearchParamsForLocation(\n location.search,\n hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current\n ),\n [location.search]\n );\n\n let navigate = useNavigate();\n let setSearchParams = React.useCallback<SetURLSearchParams>(\n (nextInit, navigateOptions) => {\n const newSearchParams = createSearchParams(\n typeof nextInit === \"function\" ? nextInit(searchParams) : nextInit\n );\n hasSetSearchParamsRef.current = true;\n navigate(\"?\" + newSearchParams, navigateOptions);\n },\n [navigate, searchParams]\n );\n\n return [searchParams, setSearchParams];\n}\n\nexport type SetURLSearchParams = (\n nextInit?:\n | URLSearchParamsInit\n | ((prev: URLSearchParams) => URLSearchParamsInit),\n navigateOpts?: NavigateOptions\n) => void;\n\n/**\n * Submits a HTML `<form>` to the server without reloading the page.\n */\nexport interface SubmitFunction {\n (\n /**\n * Specifies the `<form>` to be submitted to the server, a specific\n * `<button>` or `<input type=\"submit\">` to use to submit the form, or some\n * arbitrary data to submit.\n *\n * Note: When using a `<button>` its `name` and `value` will also be\n * included in the form data that is submitted.\n */\n target: SubmitTarget,\n\n /**\n * Options that override the `<form>`'s own attributes. Required when\n * submitting arbitrary data without a backing `<form>`.\n */\n options?: SubmitOptions\n ): void;\n}\n\n/**\n * Submits a fetcher `<form>` to the server without reloading the page.\n */\nexport interface FetcherSubmitFunction {\n (\n target: SubmitTarget,\n // Fetchers cannot replace or set state because they are not navigation events\n options?: FetcherSubmitOptions\n ): void;\n}\n\nfunction validateClientSideSubmission() {\n if (typeof document === \"undefined\") {\n throw new Error(\n \"You are calling submit during the server render. \" +\n \"Try calling submit within a `useEffect` or callback instead.\"\n );\n }\n}\n\nlet fetcherId = 0;\nlet getUniqueFetcherId = () => `__${String(++fetcherId)}__`;\n\n/**\n * Returns a function that may be used to programmatically submit a form (or\n * some arbitrary data) to the server.\n */\nexport function useSubmit(): SubmitFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseSubmit);\n let { basename } = React.useContext(NavigationContext);\n let currentRouteId = useRouteId();\n\n return React.useCallback<SubmitFunction>(\n (target, options = {}) => {\n validateClientSideSubmission();\n\n let { action, method, encType, formData, body } = getFormSubmissionInfo(\n target,\n basename\n );\n\n if (options.navigate === false) {\n let key = options.fetcherKey || getUniqueFetcherId();\n router.fetch(key, currentRouteId, options.action || action, {\n preventScrollReset: options.preventScrollReset,\n formData,\n body,\n formMethod: options.method || (method as HTMLFormMethod),\n formEncType: options.encType || (encType as FormEncType),\n flushSync: options.flushSync,\n });\n } else {\n router.navigate(options.action || action, {\n preventScrollReset: options.preventScrollReset,\n formData,\n body,\n formMethod: options.method || (method as HTMLFormMethod),\n formEncType: options.encType || (encType as FormEncType),\n replace: options.replace,\n state: options.state,\n fromRouteId: currentRouteId,\n flushSync: options.flushSync,\n viewTransition: options.viewTransition,\n });\n }\n },\n [router, basename, currentRouteId]\n );\n}\n\n// v7: Eventually we should deprecate this entirely in favor of using the\n// router method directly?\nexport function useFormAction(\n action?: string,\n { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n let { basename } = React.useContext(NavigationContext);\n let routeContext = React.useContext(RouteContext);\n invariant(routeContext, \"useFormAction must be used inside a RouteContext\");\n\n let [match] = routeContext.matches.slice(-1);\n // Shallow clone path so we can modify it below, otherwise we modify the\n // object referenced by useMemo inside useResolvedPath\n let path = { ...useResolvedPath(action ? action : \".\", { relative }) };\n\n // If no action was specified, browsers will persist current search params\n // when determining the path, so match that behavior\n // https://github.com/remix-run/remix/issues/927\n let location = useLocation();\n if (action == null) {\n // Safe to write to this directly here since if action was undefined, we\n // would have called useResolvedPath(\".\") which will never include a search\n path.search = location.search;\n\n // When grabbing search params from the URL, remove any included ?index param\n // since it might not apply to our contextual route. We add it back based\n // on match.route.index below\n let params = new URLSearchParams(path.search);\n let indexValues = params.getAll(\"index\");\n let hasNakedIndexParam = indexValues.some((v) => v === \"\");\n if (hasNakedIndexParam) {\n params.delete(\"index\");\n indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n let qs = params.toString();\n path.search = qs ? `?${qs}` : \"\";\n }\n }\n\n if ((!action || action === \".\") && match.route.index) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the form action. If this is a root navigation, then just use\n // the raw basename which allows the basename to have full control over the\n // presence of a trailing slash on root actions\n if (basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\nexport type FetcherWithComponents<TData> = Fetcher<TData> & {\n Form: React.ForwardRefExoticComponent<\n FetcherFormProps & React.RefAttributes<HTMLFormElement>\n >;\n submit: FetcherSubmitFunction;\n load: (href: string, opts?: { flushSync?: boolean }) => void;\n};\n\n// TODO: (v7) Change the useFetcher generic default from `any` to `unknown`\n\n/**\n * Interacts with route loaders and actions without causing a navigation. Great\n * for any interaction that stays on the same page.\n */\nexport function useFetcher<TData = any>({\n key,\n}: { key?: string } = {}): FetcherWithComponents<TData> {\n let { router } = useDataRouterContext(DataRouterHook.UseFetcher);\n let state = useDataRouterState(DataRouterStateHook.UseFetcher);\n let fetcherData = React.useContext(FetchersContext);\n let route = React.useContext(RouteContext);\n let routeId = route.matches[route.matches.length - 1]?.route.id;\n\n invariant(fetcherData, `useFetcher must be used inside a FetchersContext`);\n invariant(route, `useFetcher must be used inside a RouteContext`);\n invariant(\n routeId != null,\n `useFetcher can only be used on routes that contain a unique \"id\"`\n );\n\n // Fetcher key handling\n // OK to call conditionally to feature detect `useId`\n // eslint-disable-next-line react-hooks/rules-of-hooks\n let defaultKey = useIdImpl ? useIdImpl() : \"\";\n let [fetcherKey, setFetcherKey] = React.useState<string>(key || defaultKey);\n if (key && key !== fetcherKey) {\n setFetcherKey(key);\n } else if (!fetcherKey) {\n // We will only fall through here when `useId` is not available\n setFetcherKey(getUniqueFetcherId());\n }\n\n // Registration/cleanup\n React.useEffect(() => {\n router.getFetcher(fetcherKey);\n return () => {\n // Tell the router we've unmounted - if v7_fetcherPersist is enabled this\n // will not delete immediately but instead queue up a delete after the\n // fetcher returns to an `idle` state\n router.deleteFetcher(fetcherKey);\n };\n }, [router, fetcherKey]);\n\n // Fetcher additions\n let load = React.useCallback(\n (href: string, opts?: { flushSync?: boolean }) => {\n invariant(routeId, \"No routeId available for fetcher.load()\");\n router.fetch(fetcherKey, routeId, href, opts);\n },\n [fetcherKey, routeId, router]\n );\n\n let submitImpl = useSubmit();\n let submit = React.useCallback<FetcherSubmitFunction>(\n (target, opts) => {\n submitImpl(target, {\n ...opts,\n navigate: false,\n fetcherKey,\n });\n },\n [fetcherKey, submitImpl]\n );\n\n let FetcherForm = React.useMemo(() => {\n let FetcherForm = React.forwardRef<HTMLFormElement, FetcherFormProps>(\n (props, ref) => {\n return (\n <Form {...props} navigate={false} fetcherKey={fetcherKey} ref={ref} />\n );\n }\n );\n if (__DEV__) {\n FetcherForm.displayName = \"fetcher.Form\";\n }\n return FetcherForm;\n }, [fetcherKey]);\n\n // Exposed FetcherWithComponents\n let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;\n let data = fetcherData.get(fetcherKey);\n let fetcherWithComponents = React.useMemo(\n () => ({\n Form: FetcherForm,\n submit,\n load,\n ...fetcher,\n data,\n }),\n [FetcherForm, submit, load, fetcher, data]\n );\n\n return fetcherWithComponents;\n}\n\n/**\n * Provides all fetchers currently on the page. Useful for layouts and parent\n * routes that need to provide pending/optimistic UI regarding the fetch.\n */\nexport function useFetchers(): (Fetcher & { key: string })[] {\n let state = useDataRouterState(DataRouterStateHook.UseFetchers);\n return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({\n ...fetcher,\n key,\n }));\n}\n\nconst SCROLL_RESTORATION_STORAGE_KEY = \"react-router-scroll-positions\";\nlet savedScrollPositions: Record<string, number> = {};\n\n/**\n * When rendered inside a RouterProvider, will restore scroll positions on navigations\n */\nfunction useScrollRestoration({\n getKey,\n storageKey,\n}: {\n getKey?: GetScrollRestorationKeyFunction;\n storageKey?: string;\n} = {}) {\n let { router } = useDataRouterContext(DataRouterHook.UseScrollRestoration);\n let { restoreScrollPosition, preventScrollReset } = useDataRouterState(\n DataRouterStateHook.UseScrollRestoration\n );\n let { basename } = React.useContext(NavigationContext);\n let location = useLocation();\n let matches = useMatches();\n let navigation = useNavigation();\n\n // Trigger manual scroll restoration while we're active\n React.useEffect(() => {\n window.history.scrollRestoration = \"manual\";\n return () => {\n window.history.scrollRestoration = \"auto\";\n };\n }, []);\n\n // Save positions on pagehide\n usePageHide(\n React.useCallback(() => {\n if (navigation.state === \"idle\") {\n let key = (getKey ? getKey(location, matches) : null) || location.key;\n savedScrollPositions[key] = window.scrollY;\n }\n try {\n sessionStorage.setItem(\n storageKey || SCROLL_RESTORATION_STORAGE_KEY,\n JSON.stringify(savedScrollPositions)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`\n );\n }\n window.history.scrollRestoration = \"auto\";\n }, [storageKey, getKey, navigation.state, location, matches])\n );\n\n // Read in any saved scroll locations\n if (typeof document !== \"undefined\") {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(() => {\n try {\n let sessionPositions = sessionStorage.getItem(\n storageKey || SCROLL_RESTORATION_STORAGE_KEY\n );\n if (sessionPositions) {\n savedScrollPositions = JSON.parse(sessionPositions);\n }\n } catch (e) {\n // no-op, use default empty object\n }\n }, [storageKey]);\n\n // Enable scroll restoration in the router\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(() => {\n let getKeyWithoutBasename: GetScrollRestorationKeyFunction | undefined =\n getKey && basename !== \"/\"\n ? (location, matches) =>\n getKey(\n // Strip the basename to match useLocation()\n {\n ...location,\n pathname:\n stripBasename(location.pathname, basename) ||\n location.pathname,\n },\n matches\n )\n : getKey;\n let disableScrollRestoration = router?.enableScrollRestoration(\n savedScrollPositions,\n () => window.scrollY,\n getKeyWithoutBasename\n );\n return () => disableScrollRestoration && disableScrollRestoration();\n }, [router, basename, getKey]);\n\n // Restore scrolling when state.restoreScrollPosition changes\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(() => {\n // Explicit false means don't do anything (used for submissions)\n if (restoreScrollPosition === false) {\n return;\n }\n\n // been here before, scroll to it\n if (typeof restoreScrollPosition === \"number\") {\n window.scrollTo(0, restoreScrollPosition);\n return;\n }\n\n // try to scroll to the hash\n if (location.hash) {\n let el = document.getElementById(\n decodeURIComponent(location.hash.slice(1))\n );\n if (el) {\n el.scrollIntoView();\n return;\n }\n }\n\n // Don't reset if this navigation opted out\n if (preventScrollReset === true) {\n return;\n }\n\n // otherwise go to the top on new locations\n window.scrollTo(0, 0);\n }, [location, restoreScrollPosition, preventScrollReset]);\n }\n}\n\nexport { useScrollRestoration as UNSAFE_useScrollRestoration };\n\n/**\n * Setup a callback to be fired on the window's `beforeunload` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nexport function useBeforeUnload(\n callback: (event: BeforeUnloadEvent) => any,\n options?: { capture?: boolean }\n): void {\n let { capture } = options || {};\n React.useEffect(() => {\n let opts = capture != null ? { capture } : undefined;\n window.addEventListener(\"beforeunload\", callback, opts);\n return () => {\n window.removeEventListener(\"beforeunload\", callback, opts);\n };\n }, [callback, capture]);\n}\n\n/**\n * Setup a callback to be fired on the window's `pagehide` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes. This event is better supported than beforeunload across browsers.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nfunction usePageHide(\n callback: (event: PageTransitionEvent) => any,\n options?: { capture?: boolean }\n): void {\n let { capture } = options || {};\n React.useEffect(() => {\n let opts = capture != null ? { capture } : undefined;\n window.addEventListener(\"pagehide\", callback, opts);\n return () => {\n window.removeEventListener(\"pagehide\", callback, opts);\n };\n }, [callback, capture]);\n}\n\n/**\n * Wrapper around useBlocker to show a window.confirm prompt to users instead\n * of building a custom UI with useBlocker.\n *\n * Warning: This has *a lot of rough edges* and behaves very differently (and\n * very incorrectly in some cases) across browsers if user click addition\n * back/forward navigations while the confirm is open. Use at your own risk.\n */\nfunction usePrompt({\n when,\n message,\n}: {\n when: boolean | BlockerFunction;\n message: string;\n}) {\n let blocker = useBlocker(when);\n\n React.useEffect(() => {\n if (blocker.state === \"blocked\") {\n let proceed = window.confirm(message);\n if (proceed) {\n // This timeout is needed to avoid a weird \"race\" on POP navigations\n // between the `window.history` revert navigation and the result of\n // `window.confirm`\n setTimeout(blocker.proceed, 0);\n } else {\n blocker.reset();\n }\n }\n }, [blocker, message]);\n\n React.useEffect(() => {\n if (blocker.state === \"blocked\" && !when) {\n blocker.reset();\n }\n }, [blocker, when]);\n}\n\nexport { usePrompt as unstable_usePrompt };\n\n/**\n * Return a boolean indicating if there is an active view transition to the\n * given href. You can use this value to render CSS classes or viewTransitionName\n * styles onto your elements\n *\n * @param href The destination href\n * @param [opts.relative] Relative routing type (\"route\" | \"path\")\n */\nfunction useViewTransitionState(\n to: To,\n opts: { relative?: RelativeRoutingType } = {}\n) {\n let vtContext = React.useContext(ViewTransitionContext);\n\n invariant(\n vtContext != null,\n \"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. \" +\n \"Did you accidentally import `RouterProvider` from `react-router`?\"\n );\n\n let { basename } = useDataRouterContext(\n DataRouterHook.useViewTransitionState\n );\n let path = useResolvedPath(to, { relative: opts.relative });\n if (!vtContext.isTransitioning) {\n return false;\n }\n\n let currentPath =\n stripBasename(vtContext.currentLocation.pathname, basename) ||\n vtContext.currentLocation.pathname;\n let nextPath =\n stripBasename(vtContext.nextLocation.pathname, basename) ||\n vtContext.nextLocation.pathname;\n\n // Transition is active if we're going to or coming from the indicated\n // destination. This ensures that other PUSH navigations that reverse\n // an indicated transition apply. I.e., on the list view you have:\n //\n // <NavLink to=\"/details/1\" viewTransition>\n //\n // If you click the breadcrumb back to the list view:\n //\n // <NavLink to=\"/list\" viewTransition>\n //\n // We should apply the transition because it's indicated as active going\n // from /list -> /details/1 and therefore should be active on the reverse\n // (even though this isn't strictly a POP reverse)\n return (\n matchPath(path.pathname, nextPath) != null ||\n matchPath(path.pathname, currentPath) != null\n );\n}\n\nexport { useViewTransitionState as useViewTransitionState };\n\n//#endregion\n","export const FileListIcon = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"25\"\n height=\"24\"\n viewBox=\"0 0 25 24\"\n fill=\"none\"\n >\n <path\n d=\"M18.7531 21H6.15312C5.43704 21 4.75028 20.7155 4.24394 20.2092C3.73759 19.7028 3.45313 19.0161 3.45312 18.3V3.9C3.45312 3.66131 3.54795 3.43239 3.71673 3.2636C3.88551 3.09482 4.11443 3 4.35312 3H16.9531C17.1918 3 17.4207 3.09482 17.5895 3.2636C17.7583 3.43239 17.8531 3.66131 17.8531 3.9V14.7H21.4531V18.3C21.4531 19.0161 21.1687 19.7028 20.6623 20.2092C20.156 20.7155 19.4692 21 18.7531 21ZM17.8531 16.5V18.3C17.8531 18.5387 17.9479 18.7676 18.1167 18.9364C18.2855 19.1052 18.5144 19.2 18.7531 19.2C18.9918 19.2 19.2207 19.1052 19.3895 18.9364C19.5583 18.7676 19.6531 18.5387 19.6531 18.3V16.5H17.8531ZM16.0531 19.2V4.8H5.25312V18.3C5.25312 18.5387 5.34795 18.7676 5.51673 18.9364C5.68551 19.1052 5.91443 19.2 6.15312 19.2H16.0531ZM7.05312 7.5H14.2531V9.3H7.05312V7.5ZM7.05312 11.1H14.2531V12.9H7.05312V11.1ZM7.05312 14.7H11.5531V16.5H7.05312V14.7Z\"\n fill=\"#666666\"\n />\n </svg>\n );\n};\n\nexport const IcMenu = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 20 20\"\n fill=\"none\"\n >\n <path\n d=\"M3.24951 4H16.7495V5.5H3.24951V4ZM3.24951 9.25H16.7495V10.75H3.24951V9.25ZM3.24951 14.5H16.7495V16H3.24951V14.5Z\"\n fill=\"#666666\"\n />\n </svg>\n );\n};\n\nexport const QrCodeLine = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 20 20\"\n fill=\"none\"\n >\n <path\n d=\"M13 13.7505V13.0005H10.75V10.7505H13V12.2505H14.5V13.7505H13.75V15.2505H12.25V16.7505H10.75V14.5005H12.25V13.7505H13ZM16.75 16.7505H13.75V15.2505H15.25V13.7505H16.75V16.7505ZM3.25 3.25049H9.25V9.25049H3.25V3.25049ZM4.75 4.75049V7.75049H7.75V4.75049H4.75ZM10.75 3.25049H16.75V9.25049H10.75V3.25049ZM12.25 4.75049V7.75049H15.25V4.75049H12.25ZM3.25 10.7505H9.25V16.7505H3.25V10.7505ZM4.75 12.2505V15.2505H7.75V12.2505H4.75ZM14.5 10.7505H16.75V12.2505H14.5V10.7505ZM5.5 5.50049H7V7.00049H5.5V5.50049ZM5.5 13.0005H7V14.5005H5.5V13.0005ZM13 5.50049H14.5V7.00049H13V5.50049Z\"\n fill=\"currentColor\"\n />\n </svg>\n );\n};\n\nexport const ExternalLinkLine = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n >\n <path\n d=\"M6.79961 4.4001V5.6001H3.79961V12.2001H10.3996V9.2001H11.5996V12.8001C11.5996 12.9592 11.5364 13.1118 11.4239 13.2244C11.3114 13.3369 11.1587 13.4001 10.9996 13.4001H3.19961C3.04048 13.4001 2.88787 13.3369 2.77535 13.2244C2.66282 13.1118 2.59961 12.9592 2.59961 12.8001V5.0001C2.59961 4.84097 2.66282 4.68836 2.77535 4.57583C2.88787 4.46331 3.04048 4.4001 3.19961 4.4001H6.79961ZM13.3996 2.6001V7.4001H12.1996V4.6479L7.52381 9.3243L6.67541 8.4759L11.3506 3.8001H8.59961V2.6001H13.3996Z\"\n fill=\"currentColor\"\n />\n </svg>\n );\n};\n\nexport const IcBarCode = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 20 20\"\n fill=\"none\"\n >\n <path\n d=\"M2.5 4H4V16H2.5V4ZM5.5 4H7V16H5.5V4ZM7.75 4H10V16H7.75V4ZM10.75 4H12.25V16H10.75V4ZM13 4H14.5V16H13V4ZM15.25 4H17.5V16H15.25V4Z\"\n fill=\"#060606\"\n />\n </svg>\n );\n};\n\nexport const IcKitchenOrder = () => {\n return (\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"19\" height=\"15\" viewBox=\"0 0 19 15\" fill=\"none\">\n <path d=\"M11.6667 0H6.66667V1.66667H8.33333V2.54115C4.12223 2.95925 0.833333 6.51225 0.833333 10.8333V11.6667H17.5V10.8333C17.5 6.51225 14.2111 2.95925 10 2.54115V1.66667H11.6667V0ZM9.16667 4.16667C12.5663 4.16667 15.3717 6.71142 15.7818 10H2.55158C2.96166 6.71142 5.76698 4.16667 9.16667 4.16667ZM18.3333 14.1667V12.5H0V14.1667H18.3333Z\" fill=\"#0101FF\"/>\n </svg>\n )\n}","export const IcSearch = (props: React.SVGProps<SVGSVGElement>) => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 20 20\"\n fill=\"none\"\n >\n <path\n d=\"M14.5232 13.4627L17.7355 16.6742L16.6742 17.7355L13.4627 14.5232C12.2678 15.4812 10.7815 16.0022 9.25 16C5.524 16 2.5 12.976 2.5 9.25C2.5 5.524 5.524 2.5 9.25 2.5C12.976 2.5 16 5.524 16 9.25C16.0022 10.7815 15.4812 12.2678 14.5232 13.4627ZM13.0187 12.9062C13.9706 11.9274 14.5021 10.6153 14.5 9.25C14.5 6.349 12.1502 4 9.25 4C6.349 4 4 6.349 4 9.25C4 12.1502 6.349 14.5 9.25 14.5C10.6153 14.5021 11.9274 13.9706 12.9062 13.0187L13.0187 12.9062Z\"\n fill=\"currentColor\"\n />\n </svg>\n )\n}\n\nexport const IcRefresh = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n >\n <path\n d=\"M3.09725 2.32476C4.45817 1.1455 6.19924 0.497495 8 0.500007C12.1423 0.500007 15.5 3.85776 15.5 8.00001C15.5 9.60201 14.9975 11.087 14.1425 12.305L11.75 8.00001H14C14.0001 6.82373 13.6544 5.67336 13.006 4.69195C12.3576 3.71054 11.4349 2.94138 10.3529 2.4801C9.27082 2.01882 8.07704 1.88578 6.91997 2.09752C5.7629 2.30926 4.69359 2.85643 3.845 3.67101L3.09725 2.32476ZM12.9028 13.6753C11.5418 14.8545 9.80076 15.5025 8 15.5C3.85775 15.5 0.5 12.1423 0.5 8.00001C0.5 6.39801 1.0025 4.91301 1.8575 3.69501L4.25 8.00001H2C1.9999 9.17629 2.34556 10.3267 2.994 11.3081C3.64244 12.2895 4.56505 13.0586 5.64712 13.5199C6.72918 13.9812 7.92296 14.1142 9.08003 13.9025C10.2371 13.6908 11.3064 13.1436 12.155 12.329L12.9028 13.6753Z\"\n fill=\"currentColor\"\n />\n </svg>\n )\n}\n\nexport const IcPlus = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"17\"\n height=\"16\"\n viewBox=\"0 0 17 16\"\n fill=\"none\"\n >\n <path\n d=\"M8.59985 4.2998V7.89941H12.2004V8.09961H8.59985V11.7002H8.39966V8.09961H4.80005V7.89941H8.39966V4.2998H8.59985Z\"\n fill=\"currentColor\"\n stroke=\"currentColor\"\n />\n </svg>\n )\n}\n\nexport const IcSubtractLine = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"13\"\n height=\"2\"\n viewBox=\"0 0 13 2\"\n fill=\"none\"\n >\n <path\n d=\"M0.199219 0.0996094H12.7992V1.89961H0.199219V0.0996094Z\"\n fill=\"currentColor\"\n />\n </svg>\n )\n}\n\nexport const IcPrint = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 20 20\"\n fill=\"none\"\n >\n <path\n d=\"M6.25 13.75H13.75V17.5H6.25V13.75ZM15.25 16V12.25H4.75V16H3.25C3.05109 16 2.86032 15.921 2.71967 15.7803C2.57902 15.6397 2.5 15.4489 2.5 15.25V7.75C2.5 7.55109 2.57902 7.36032 2.71967 7.21967C2.86032 7.07902 3.05109 7 3.25 7H16.75C16.9489 7 17.1397 7.07902 17.2803 7.21967C17.421 7.36032 17.5 7.55109 17.5 7.75V15.25C17.5 15.4489 17.421 15.6397 17.2803 15.7803C17.1397 15.921 16.9489 16 16.75 16H15.25ZM4.75 8.5V10H7V8.5H4.75ZM6.25 2.5H13.75C13.9489 2.5 14.1397 2.57902 14.2803 2.71967C14.421 2.86032 14.5 3.05109 14.5 3.25V5.5H5.5V3.25C5.5 3.05109 5.57902 2.86032 5.71967 2.71967C5.86032 2.57902 6.05109 2.5 6.25 2.5Z\"\n fill=\"currentColor\"\n />\n </svg>\n )\n}\n","import { IcPlus } from \"@assets/icons/breadcrumbs-icon\";\nimport ButtonAction from \"@components/common/button-action\";\nimport { useTranslation } from \"react-i18next\";\n\nconst OrderActions = ({\n orderStatus,\n onAddItem,\n onPayment,\n onIssueInvoice,\n onPrintInvoice,\n}: {\n orderStatus: string;\n onAddItem?: () => void;\n onPayment?: () => void;\n onIssueInvoice?: () => void;\n onPrintInvoice?: () => void;\n}) => {\n const { t } = useTranslation();\n\n return (\n <div className=\"flex items-center gap-3 justify-center\">\n <ButtonAction\n className=\"button-secondary\"\n onClick={() => {\n orderStatus === \"draft\"\n ? onAddItem && onAddItem()\n : onIssueInvoice && onIssueInvoice();\n }}\n iconSrc={<IcPlus />}\n text={orderStatus === \"draft\" ? t(\"add_dish\") : t(\"create_invoice\")}\n />\n\n <ButtonAction\n className=\"button-primary\"\n onClick={() => {\n orderStatus === \"draft\"\n ? onPayment && onPayment()\n : onPrintInvoice && onPrintInvoice();\n }}\n text={orderStatus === \"draft\" ? t(\"payment\") : t(\"print_invoice\")}\n />\n </div>\n );\n};\n\nexport default OrderActions;\n","import { ORDER_STATE } from \"@constants/order-state\";\nimport { useTranslation } from \"react-i18next\";\n\nconst STATUS = [\n {\n id: 1,\n value: ORDER_STATE.NEW,\n color: \"#F6B51E\",\n background: \"#FFFAEB\",\n },\n {\n id: 2,\n value: ORDER_STATE.PAID,\n color: \"#1FC163\",\n background: \"#E0FAEB\",\n },\n {\n id: 3,\n value: ORDER_STATE.INVOICED,\n color: \"#35ADE9\",\n background: \"#EBF1FF\",\n },\n {\n id: 4,\n value: ORDER_STATE.CANCEL,\n color: \"#FB2B3D\",\n background: \"#FFEBEC\",\n },\n {\n id: 5,\n value: ORDER_STATE.IN_PAID,\n color: \"#1FC163\",\n background: \"#E0FAEB\",\n },\n];\n\nconst OrderStatus = ({ status }: { status: string }) => {\n const { t } = useTranslation();\n const currentStatus = STATUS.find((item) => {\n return item.value === status;\n });\n return (\n <div\n style={{\n borderColor: currentStatus?.color,\n backgroundColor: currentStatus?.background,\n color: currentStatus?.color,\n }}\n className=\"px-2 py-1 rounded border w-fit\"\n >\n <p className=\"text-xs font-medium leading-4\">\n {t(currentStatus?.value || \"\")}\n </p>\n </div>\n );\n};\n\nexport default OrderStatus;\n","import { Line } from \"@assets/icons/customer-view-icon\";\nimport { FileListIcon } from \"@assets/icons/order-icon\";\nimport OrderActions from \"@components/order-management/order-actions\";\nimport OrderStatus from \"@components/order-management/order-status\";\nimport { dd_mm_yyyy, hh_mm, formatOrderPrice } from \"@utils/functions\";\nimport { useMemo } from \"react\";\n\nconst PosOrderTemplate = ({\n readOnly,\n row,\n handleClick,\n onAddItem,\n onPayment,\n onIssueInvoice,\n onPrintInvoice,\n}: {\n readOnly?: boolean;\n row: any;\n handleClick: () => void;\n onAddItem?: () => void;\n onPayment?: () => void;\n onIssueInvoice?: () => void;\n onPrintInvoice?: () => void;\n}) => {\n const orderDate: Date = useMemo(() => new Date(row[\"date_order\"]), [row]);\n return (\n <div\n onClick={() => handleClick()}\n className=\"p-4 h-fit flex-1 rounded-2xl bg-white flex flex-col gap-3\"\n >\n <div className=\"flex items-center justify-center gap-3\">\n <div className=\"w-14 aspect-square rounded-lg bg-neutral-100-96 flex items-center justify-center\">\n <FileListIcon />\n </div>\n\n <div className=\"flex flex-col flex-1 gap-2 justify-center\">\n <div className=\"flex items-center justify-between\">\n <p className=\"font-bold leading-6 text-text-primary tracking-[-0.16px]\">\n #{row[\"id\"]}\n </p>\n\n <OrderStatus status={row[\"state\"]} />\n </div>\n\n <p className=\"text-sm leading-5 text-text-secondary tracking-[-0.12px]\">\n {dd_mm_yyyy(orderDate)}{\" \"}\n <span className=\"text-text-secondary\">• {hh_mm(orderDate)}</span>\n </p>\n </div>\n </div>\n\n <div className=\"relative\">\n <div className=\"h-4 aspect-square bg-weak-50 rounded-full absolute -left-6 -top-2\" />\n <Line />\n\n <div className=\"h-4 aspect-square bg-weak-50 rounded-full absolute -right-6 -top-2\" />\n </div>\n <div className=\"flex justify-between items-center\">\n <p className=\"text-text-primary text-end font-semibold leading-6 tracking-[-0.24px]\">\n {formatOrderPrice(row[\"amount_total\"])}{\" \"}\n {row[\"currency_id\"]?.display_name}\n </p>\n {!readOnly && (\n <OrderActions\n orderStatus={row[\"state\"]}\n onAddItem={onAddItem}\n onPayment={onPayment}\n onIssueInvoice={onIssueInvoice}\n onPrintInvoice={onPrintInvoice}\n />\n )}\n </div>\n </div>\n );\n};\n\nexport default PosOrderTemplate;\n","export const IcSetting = () => {\n return (\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M0.5 7.99998C0.5 7.35123 0.5825 6.72273 0.737 6.12198C1.15135 6.14377 1.56365 6.05055 1.92833 5.85264C2.29301 5.65472 2.59586 5.35983 2.8034 5.00054C3.01095 4.64126 3.1151 4.23158 3.10436 3.8168C3.09361 3.40202 2.96837 2.99829 2.7425 2.65023C3.64921 1.75816 4.7681 1.11161 5.99375 0.771484C6.18199 1.14159 6.46898 1.45238 6.82294 1.66947C7.1769 1.88655 7.58402 2.00145 7.99925 2.00145C8.41448 2.00145 8.8216 1.88655 9.17556 1.66947C9.52952 1.45238 9.81651 1.14159 10.0048 0.771484C11.2304 1.11161 12.3493 1.75816 13.256 2.65023C13.0299 2.99835 12.9045 3.40224 12.8936 3.81721C12.8828 4.23218 12.987 4.64206 13.1946 5.00149C13.4023 5.36093 13.7054 5.65591 14.0703 5.8538C14.4352 6.05168 14.8477 6.14476 15.2623 6.12273C15.4167 6.72273 15.4993 7.35123 15.4993 7.99998C15.4993 8.64873 15.4167 9.27723 15.2623 9.87799C14.8478 9.85606 14.4354 9.94917 14.0706 10.147C13.7059 10.3449 13.4029 10.6398 13.1953 10.9991C12.9876 11.3584 12.8834 11.7681 12.8941 12.183C12.9048 12.5978 13.0301 13.0016 13.256 13.3497C12.3493 14.2418 11.2304 14.8884 10.0048 15.2285C9.81651 14.8584 9.52952 14.5476 9.17556 14.3305C8.8216 14.1134 8.41448 13.9985 7.99925 13.9985C7.58402 13.9985 7.1769 14.1134 6.82294 14.3305C6.46898 14.5476 6.18199 14.8584 5.99375 15.2285C4.7681 14.8884 3.64921 14.2418 2.7425 13.3497C2.96863 13.0016 3.09405 12.5977 3.10488 12.1828C3.11571 11.7678 3.01152 11.3579 2.80386 10.9985C2.59619 10.639 2.29314 10.3441 1.92823 10.1462C1.56332 9.94829 1.15078 9.85521 0.73625 9.87724C0.5825 9.27798 0.5 8.64948 0.5 7.99998ZM4.103 10.25C4.5755 11.0682 4.7105 12.0095 4.526 12.893C4.832 13.1105 5.1575 13.2987 5.49875 13.4555C6.18625 12.8396 7.07699 12.4993 8 12.5C8.945 12.5 9.8285 12.8532 10.5013 13.4555C10.8425 13.2987 11.168 13.1105 11.474 12.893C11.2846 11.99 11.4352 11.0488 11.897 10.25C12.358 9.45076 13.0978 8.84985 13.9745 8.56248C14.0092 8.18829 14.0092 7.81168 13.9745 7.43748C13.0975 7.15028 12.3574 6.54935 11.8962 5.74998C11.4345 4.95118 11.2838 4.01001 11.4733 3.10698C11.1673 2.88943 10.8417 2.7011 10.5005 2.54448C9.81319 3.16018 8.92276 3.50044 8 3.49998C7.07699 3.50063 6.18625 3.16036 5.49875 2.54448C5.1576 2.7011 4.83192 2.88943 4.526 3.10698C4.71542 4.01001 4.56479 4.95118 4.103 5.74998C3.64203 6.5492 2.90224 7.15012 2.0255 7.43748C1.99081 7.81168 1.99081 8.18829 2.0255 8.56248C2.90252 8.84969 3.6426 9.45062 4.10375 10.25H4.103ZM8 10.25C7.40326 10.25 6.83097 10.0129 6.40901 9.59097C5.98705 9.16902 5.75 8.59672 5.75 7.99998C5.75 7.40325 5.98705 6.83095 6.40901 6.40899C6.83097 5.98704 7.40326 5.74998 8 5.74998C8.59674 5.74998 9.16903 5.98704 9.59099 6.40899C10.0129 6.83095 10.25 7.40325 10.25 7.99998C10.25 8.59672 10.0129 9.16902 9.59099 9.59097C9.16903 10.0129 8.59674 10.25 8 10.25ZM8 8.74998C8.19891 8.74998 8.38968 8.67097 8.53033 8.53031C8.67098 8.38966 8.75 8.1989 8.75 7.99998C8.75 7.80107 8.67098 7.61031 8.53033 7.46965C8.38968 7.329 8.19891 7.24998 8 7.24998C7.80109 7.24998 7.61032 7.329 7.46967 7.46965C7.32902 7.61031 7.25 7.80107 7.25 7.99998C7.25 8.1989 7.32902 8.38966 7.46967 8.53031C7.61032 8.67097 7.80109 8.74998 8 8.74998Z\"\n fill=\"curentColor\"\n />\n </svg>\n );\n};\n","export const QUERY_KEYS = {\n POS_ID: \"pos_id\",\n FLOOR: \"floor\",\n SESSION_ID: \"session-id\",\n ORDER_ID: \"order-id\",\n CATEGORY_ID: \"category-id\",\n OPEN: \"open\",\n CUSTOMER_INFO: \"customer-info\",\n CUSTOMER_ID: \"customer-id\",\n TABLE_ID: \"table-id\",\n KITCHEN_ORDER_STATUS: \"kitchen-order-status\",\n CLOSE_SESSION: \"close-session\",\n SHOW_SCREEN: \"show-screen\",\n};\n","import { useService } from \"@fctc/widget-logic/provider\";\nimport { sessionStorageUtils } from \"@fctc/widget-logic/utils\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { usePosAppProvider } from \"./app-provider\";\n\nconst useSessionProvider = () => {\n const { useCreateSession, useHandleClosingSession, useCreatePosConfig } =\n useService();\n\n const createSessionMutation = useCreateSession().mutateAsync;\n const setOpeningCashBoxMutation = useHandleClosingSession().mutateAsync;\n const createPosConfigMutation = useCreatePosConfig().mutateAsync;\n\n const { user } = usePosAppProvider();\n const dataUser = user?.userProfile?.data;\n const service = sessionStorageUtils.getMenuFocus().service || `wesap`;\n const xNode = dataUser?.x_node || \"\";\n\n const openSession = useMutation({\n mutationFn: async (configId: number) => {\n return await createSessionMutation({\n configId,\n model: \"pos.session\",\n service,\n xNode,\n });\n },\n });\n\n const setOpeningCashBox = useMutation({\n mutationFn: ({\n cashBoxValue,\n sessionId,\n }: {\n cashBoxValue: number;\n sessionId: number;\n }) => {\n return setOpeningCashBoxMutation({\n model: \"pos.session\",\n ids: [Number(sessionId)],\n service,\n xNode,\n method: \"set_opening_control\",\n kwargs: {\n cashbox_value: cashBoxValue,\n notes: \"Opening cashbox\",\n },\n });\n },\n });\n\n const createPosConfig = useMutation({\n mutationFn: async ({\n name,\n modulePosRestaurant,\n }: {\n name: string;\n modulePosRestaurant: string;\n }) => {\n return await createPosConfigMutation({\n model: \"pos.config\",\n name,\n service,\n xNode,\n modulePosRestaurant,\n });\n },\n });\n\n return {\n openSession,\n setOpeningCashBox,\n createPosConfig,\n };\n};\n\nexport default useSessionProvider;\n\nexport type useSessionProviderType = ReturnType<typeof useSessionProvider>;\n","const isString = obj => typeof obj === 'string';\nconst defer = () => {\n let res;\n let rej;\n const promise = new Promise((resolve, reject) => {\n res = resolve;\n rej = reject;\n });\n promise.resolve = res;\n promise.reject = rej;\n return promise;\n};\nconst makeString = object => {\n if (object == null) return '';\n return '' + object;\n};\nconst copy = (a, s, t) => {\n a.forEach(m => {\n if (s[m]) t[m] = s[m];\n });\n};\nconst lastOfPathSeparatorRegExp = /###/g;\nconst cleanKey = key => key && key.indexOf('###') > -1 ? key.replace(lastOfPathSeparatorRegExp, '.') : key;\nconst canNotTraverseDeeper = object => !object || isString(object);\nconst getLastOfPath = (object, path, Empty) => {\n const stack = !isString(path) ? path : path.split('.');\n let stackIndex = 0;\n while (stackIndex < stack.length - 1) {\n if (canNotTraverseDeeper(object)) return {};\n const key = cleanKey(stack[stackIndex]);\n if (!object[key] && Empty) object[key] = new Empty();\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n object = object[key];\n } else {\n object = {};\n }\n ++stackIndex;\n }\n if (canNotTraverseDeeper(object)) return {};\n return {\n obj: object,\n k: cleanKey(stack[stackIndex])\n };\n};\nconst setPath = (object, path, newValue) => {\n const {\n obj,\n k\n } = getLastOfPath(object, path, Object);\n if (obj !== undefined || path.length === 1) {\n obj[k] = newValue;\n return;\n }\n let e = path[path.length - 1];\n let p = path.slice(0, path.length - 1);\n let last = getLastOfPath(object, p, Object);\n while (last.obj === undefined && p.length) {\n e = `${p[p.length - 1]}.${e}`;\n p = p.slice(0, p.length - 1);\n last = getLastOfPath(object, p, Object);\n if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') {\n last.obj = undefined;\n }\n }\n last.obj[`${last.k}.${e}`] = newValue;\n};\nconst pushPath = (object, path, newValue, concat) => {\n const {\n obj,\n k\n } = getLastOfPath(object, path, Object);\n obj[k] = obj[k] || [];\n obj[k].push(newValue);\n};\nconst getPath = (object, path) => {\n const {\n obj,\n k\n } = getLastOfPath(object, path);\n if (!obj) return undefined;\n if (!Object.prototype.hasOwnProperty.call(obj, k)) return undefined;\n return obj[k];\n};\nconst getPathWithDefaults = (data, defaultData, key) => {\n const value = getPath(data, key);\n if (value !== undefined) {\n return value;\n }\n return getPath(defaultData, key);\n};\nconst deepExtend = (target, source, overwrite) => {\n for (const prop in source) {\n if (prop !== '__proto__' && prop !== 'constructor') {\n if (prop in target) {\n if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {\n if (overwrite) target[prop] = source[prop];\n } else {\n deepExtend(target[prop], source[prop], overwrite);\n }\n } else {\n target[prop] = source[prop];\n }\n }\n }\n return target;\n};\nconst regexEscape = str => str.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, '\\\\$&');\nvar _entityMap = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#39;',\n '/': '&#x2F;'\n};\nconst escape = data => {\n if (isString(data)) {\n return data.replace(/[&<>\"'\\/]/g, s => _entityMap[s]);\n }\n return data;\n};\nclass RegExpCache {\n constructor(capacity) {\n this.capacity = capacity;\n this.regExpMap = new Map();\n this.regExpQueue = [];\n }\n getRegExp(pattern) {\n const regExpFromCache = this.regExpMap.get(pattern);\n if (regExpFromCache !== undefined) {\n return regExpFromCache;\n }\n const regExpNew = new RegExp(pattern);\n if (this.regExpQueue.length === this.capacity) {\n this.regExpMap.delete(this.regExpQueue.shift());\n }\n this.regExpMap.set(pattern, regExpNew);\n this.regExpQueue.push(pattern);\n return regExpNew;\n }\n}\nconst chars = [' ', ',', '?', '!', ';'];\nconst looksLikeObjectPathRegExpCache = new RegExpCache(20);\nconst looksLikeObjectPath = (key, nsSeparator, keySeparator) => {\n nsSeparator = nsSeparator || '';\n keySeparator = keySeparator || '';\n const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);\n if (possibleChars.length === 0) return true;\n const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map(c => c === '?' ? '\\\\?' : c).join('|')})`);\n let matched = !r.test(key);\n if (!matched) {\n const ki = key.indexOf(keySeparator);\n if (ki > 0 && !r.test(key.substring(0, ki))) {\n matched = true;\n }\n }\n return matched;\n};\nconst deepFind = (obj, path, keySeparator = '.') => {\n if (!obj) return undefined;\n if (obj[path]) {\n if (!Object.prototype.hasOwnProperty.call(obj, path)) return undefined;\n return obj[path];\n }\n const tokens = path.split(keySeparator);\n let current = obj;\n for (let i = 0; i < tokens.length;) {\n if (!current || typeof current !== 'object') {\n return undefined;\n }\n let next;\n let nextPath = '';\n for (let j = i; j < tokens.length; ++j) {\n if (j !== i) {\n nextPath += keySeparator;\n }\n nextPath += tokens[j];\n next = current[nextPath];\n if (next !== undefined) {\n if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) {\n continue;\n }\n i += j - i + 1;\n break;\n }\n }\n current = next;\n }\n return current;\n};\nconst getCleanedCode = code => code?.replace('_', '-');\n\nconst consoleLogger = {\n type: 'logger',\n log(args) {\n this.output('log', args);\n },\n warn(args) {\n this.output('warn', args);\n },\n error(args) {\n this.output('error', args);\n },\n output(type, args) {\n console?.[type]?.apply?.(console, args);\n }\n};\nclass Logger {\n constructor(concreteLogger, options = {}) {\n this.init(concreteLogger, options);\n }\n init(concreteLogger, options = {}) {\n this.prefix = options.prefix || 'i18next:';\n this.logger = concreteLogger || consoleLogger;\n this.options = options;\n this.debug = options.debug;\n }\n log(...args) {\n return this.forward(args, 'log', '', true);\n }\n warn(...args) {\n return this.forward(args, 'warn', '', true);\n }\n error(...args) {\n return this.forward(args, 'error', '');\n }\n deprecate(...args) {\n return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);\n }\n forward(args, lvl, prefix, debugOnly) {\n if (debugOnly && !this.debug) return null;\n if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;\n return this.logger[lvl](args);\n }\n create(moduleName) {\n return new Logger(this.logger, {\n ...{\n prefix: `${this.prefix}:${moduleName}:`\n },\n ...this.options\n });\n }\n clone(options) {\n options = options || this.options;\n options.prefix = options.prefix || this.prefix;\n return new Logger(this.logger, options);\n }\n}\nvar baseLogger = new Logger();\n\nclass EventEmitter {\n constructor() {\n this.observers = {};\n }\n on(events, listener) {\n events.split(' ').forEach(event => {\n if (!this.observers[event]) this.observers[event] = new Map();\n const numListeners = this.observers[event].get(listener) || 0;\n this.observers[event].set(listener, numListeners + 1);\n });\n return this;\n }\n off(event, listener) {\n if (!this.observers[event]) return;\n if (!listener) {\n delete this.observers[event];\n return;\n }\n this.observers[event].delete(listener);\n }\n emit(event, ...args) {\n if (this.observers[event]) {\n const cloned = Array.from(this.observers[event].entries());\n cloned.forEach(([observer, numTimesAdded]) => {\n for (let i = 0; i < numTimesAdded; i++) {\n observer(...args);\n }\n });\n }\n if (this.observers['*']) {\n const cloned = Array.from(this.observers['*'].entries());\n cloned.forEach(([observer, numTimesAdded]) => {\n for (let i = 0; i < numTimesAdded; i++) {\n observer.apply(observer, [event, ...args]);\n }\n });\n }\n }\n}\n\nclass ResourceStore extends EventEmitter {\n constructor(data, options = {\n ns: ['translation'],\n defaultNS: 'translation'\n }) {\n super();\n this.data = data || {};\n this.options = options;\n if (this.options.keySeparator === undefined) {\n this.options.keySeparator = '.';\n }\n if (this.options.ignoreJSONStructure === undefined) {\n this.options.ignoreJSONStructure = true;\n }\n }\n addNamespaces(ns) {\n if (this.options.ns.indexOf(ns) < 0) {\n this.options.ns.push(ns);\n }\n }\n removeNamespaces(ns) {\n const index = this.options.ns.indexOf(ns);\n if (index > -1) {\n this.options.ns.splice(index, 1);\n }\n }\n getResource(lng, ns, key, options = {}) {\n const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;\n let path;\n if (lng.indexOf('.') > -1) {\n path = lng.split('.');\n } else {\n path = [lng, ns];\n if (key) {\n if (Array.isArray(key)) {\n path.push(...key);\n } else if (isString(key) && keySeparator) {\n path.push(...key.split(keySeparator));\n } else {\n path.push(key);\n }\n }\n }\n const result = getPath(this.data, path);\n if (!result && !ns && !key && lng.indexOf('.') > -1) {\n lng = path[0];\n ns = path[1];\n key = path.slice(2).join('.');\n }\n if (result || !ignoreJSONStructure || !isString(key)) return result;\n return deepFind(this.data?.[lng]?.[ns], key, keySeparator);\n }\n addResource(lng, ns, key, value, options = {\n silent: false\n }) {\n const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n let path = [lng, ns];\n if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);\n if (lng.indexOf('.') > -1) {\n path = lng.split('.');\n value = ns;\n ns = path[1];\n }\n this.addNamespaces(ns);\n setPath(this.data, path, value);\n if (!options.silent) this.emit('added', lng, ns, key, value);\n }\n addResources(lng, ns, resources, options = {\n silent: false\n }) {\n for (const m in resources) {\n if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {\n silent: true\n });\n }\n if (!options.silent) this.emit('added', lng, ns, resources);\n }\n addResourceBundle(lng, ns, resources, deep, overwrite, options = {\n silent: false,\n skipCopy: false\n }) {\n let path = [lng, ns];\n if (lng.indexOf('.') > -1) {\n path = lng.split('.');\n deep = resources;\n resources = ns;\n ns = path[1];\n }\n this.addNamespaces(ns);\n let pack = getPath(this.data, path) || {};\n if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));\n if (deep) {\n deepExtend(pack, resources, overwrite);\n } else {\n pack = {\n ...pack,\n ...resources\n };\n }\n setPath(this.data, path, pack);\n if (!options.silent) this.emit('added', lng, ns, resources);\n }\n removeResourceBundle(lng, ns) {\n if (this.hasResourceBundle(lng, ns)) {\n delete this.data[lng][ns];\n }\n this.removeNamespaces(ns);\n this.emit('removed', lng, ns);\n }\n hasResourceBundle(lng, ns) {\n return this.getResource(lng, ns) !== undefined;\n }\n getResourceBundle(lng, ns) {\n if (!ns) ns = this.options.defaultNS;\n return this.getResource(lng, ns);\n }\n getDataByLanguage(lng) {\n return this.data[lng];\n }\n hasLanguageSomeTranslations(lng) {\n const data = this.getDataByLanguage(lng);\n const n = data && Object.keys(data) || [];\n return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);\n }\n toJSON() {\n return this.data;\n }\n}\n\nvar postProcessor = {\n processors: {},\n addPostProcessor(module) {\n this.processors[module.name] = module;\n },\n handle(processors, value, key, options, translator) {\n processors.forEach(processor => {\n value = this.processors[processor]?.process(value, key, options, translator) ?? value;\n });\n return value;\n }\n};\n\nconst PATH_KEY = Symbol('i18next/PATH_KEY');\nfunction createProxy() {\n const state = [];\n const handler = Object.create(null);\n let proxy;\n handler.get = (target, key) => {\n proxy?.revoke?.();\n if (key === PATH_KEY) return state;\n state.push(key);\n proxy = Proxy.revocable(target, handler);\n return proxy.proxy;\n };\n return Proxy.revocable(Object.create(null), handler).proxy;\n}\nfunction keysFromSelector(selector, opts) {\n const {\n [PATH_KEY]: path\n } = selector(createProxy());\n return path.join(opts?.keySeparator ?? '.');\n}\n\nconst checkedLoadedFor = {};\nconst shouldHandleAsObject = res => !isString(res) && typeof res !== 'boolean' && typeof res !== 'number';\nclass Translator extends EventEmitter {\n constructor(services, options = {}) {\n super();\n copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);\n this.options = options;\n if (this.options.keySeparator === undefined) {\n this.options.keySeparator = '.';\n }\n this.logger = baseLogger.create('translator');\n }\n changeLanguage(lng) {\n if (lng) this.language = lng;\n }\n exists(key, o = {\n interpolation: {}\n }) {\n const opt = {\n ...o\n };\n if (key == null) return false;\n const resolved = this.resolve(key, opt);\n if (resolved?.res === undefined) return false;\n const isObject = shouldHandleAsObject(resolved.res);\n if (opt.returnObjects === false && isObject) {\n return false;\n }\n return true;\n }\n extractFromKey(key, opt) {\n let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;\n if (nsSeparator === undefined) nsSeparator = ':';\n const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;\n let namespaces = opt.ns || this.options.defaultNS || [];\n const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;\n const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);\n if (wouldCheckForNsInKey && !seemsNaturalLanguage) {\n const m = key.match(this.interpolator.nestingRegexp);\n if (m && m.length > 0) {\n return {\n key,\n namespaces: isString(namespaces) ? [namespaces] : namespaces\n };\n }\n const parts = key.split(nsSeparator);\n if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();\n key = parts.join(keySeparator);\n }\n return {\n key,\n namespaces: isString(namespaces) ? [namespaces] : namespaces\n };\n }\n translate(keys, o, lastKey) {\n let opt = typeof o === 'object' ? {\n ...o\n } : o;\n if (typeof opt !== 'object' && this.options.overloadTranslationOptionHandler) {\n opt = this.options.overloadTranslationOptionHandler(arguments);\n }\n if (typeof opt === 'object') opt = {\n ...opt\n };\n if (!opt) opt = {};\n if (keys == null) return '';\n if (typeof keys === 'function') keys = keysFromSelector(keys, {\n ...this.options,\n ...opt\n });\n if (!Array.isArray(keys)) keys = [String(keys)];\n const returnDetails = opt.returnDetails !== undefined ? opt.returnDetails : this.options.returnDetails;\n const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;\n const {\n key,\n namespaces\n } = this.extractFromKey(keys[keys.length - 1], opt);\n const namespace = namespaces[namespaces.length - 1];\n let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;\n if (nsSeparator === undefined) nsSeparator = ':';\n const lng = opt.lng || this.language;\n const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;\n if (lng?.toLowerCase() === 'cimode') {\n if (appendNamespaceToCIMode) {\n if (returnDetails) {\n return {\n res: `${namespace}${nsSeparator}${key}`,\n usedKey: key,\n exactUsedKey: key,\n usedLng: lng,\n usedNS: namespace,\n usedParams: this.getUsedParamsDetails(opt)\n };\n }\n return `${namespace}${nsSeparator}${key}`;\n }\n if (returnDetails) {\n return {\n res: key,\n usedKey: key,\n exactUsedKey: key,\n usedLng: lng,\n usedNS: namespace,\n usedParams: this.getUsedParamsDetails(opt)\n };\n }\n return key;\n }\n const resolved = this.resolve(keys, opt);\n let res = resolved?.res;\n const resUsedKey = resolved?.usedKey || key;\n const resExactUsedKey = resolved?.exactUsedKey || key;\n const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];\n const joinArrays = opt.joinArrays !== undefined ? opt.joinArrays : this.options.joinArrays;\n const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;\n const needsPluralHandling = opt.count !== undefined && !isString(opt.count);\n const hasDefaultValue = Translator.hasDefaultValue(opt);\n const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : '';\n const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {\n ordinal: false\n }) : '';\n const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;\n const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;\n let resForObjHndl = res;\n if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {\n resForObjHndl = defaultValue;\n }\n const handleAsObject = shouldHandleAsObject(resForObjHndl);\n const resType = Object.prototype.toString.apply(resForObjHndl);\n if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {\n if (!opt.returnObjects && !this.options.returnObjects) {\n if (!this.options.returnedObjectHandler) {\n this.logger.warn('accessing an object - but returnObjects options is not enabled!');\n }\n const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {\n ...opt,\n ns: namespaces\n }) : `key '${key} (${this.language})' returned an object instead of string.`;\n if (returnDetails) {\n resolved.res = r;\n resolved.usedParams = this.getUsedParamsDetails(opt);\n return resolved;\n }\n return r;\n }\n if (keySeparator) {\n const resTypeIsArray = Array.isArray(resForObjHndl);\n const copy = resTypeIsArray ? [] : {};\n const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;\n for (const m in resForObjHndl) {\n if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {\n const deepKey = `${newKeyToUse}${keySeparator}${m}`;\n if (hasDefaultValue && !res) {\n copy[m] = this.translate(deepKey, {\n ...opt,\n defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : undefined,\n ...{\n joinArrays: false,\n ns: namespaces\n }\n });\n } else {\n copy[m] = this.translate(deepKey, {\n ...opt,\n ...{\n joinArrays: false,\n ns: namespaces\n }\n });\n }\n if (copy[m] === deepKey) copy[m] = resForObjHndl[m];\n }\n }\n res = copy;\n }\n } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {\n res = res.join(joinArrays);\n if (res) res = this.extendTranslation(res, keys, opt, lastKey);\n } else {\n let usedDefault = false;\n let usedKey = false;\n if (!this.isValidLookup(res) && hasDefaultValue) {\n usedDefault = true;\n res = defaultValue;\n }\n if (!this.isValidLookup(res)) {\n usedKey = true;\n res = key;\n }\n const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;\n const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;\n const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;\n if (usedKey || usedDefault || updateMissing) {\n this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);\n if (keySeparator) {\n const fk = this.resolve(key, {\n ...opt,\n keySeparator: false\n });\n if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.');\n }\n let lngs = [];\n const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);\n if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {\n for (let i = 0; i < fallbackLngs.length; i++) {\n lngs.push(fallbackLngs[i]);\n }\n } else if (this.options.saveMissingTo === 'all') {\n lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);\n } else {\n lngs.push(opt.lng || this.language);\n }\n const send = (l, k, specificDefaultValue) => {\n const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;\n if (this.options.missingKeyHandler) {\n this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);\n } else if (this.backendConnector?.saveMissing) {\n this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);\n }\n this.emit('missingKey', l, namespace, k, res);\n };\n if (this.options.saveMissing) {\n if (this.options.saveMissingPlurals && needsPluralHandling) {\n lngs.forEach(language => {\n const suffixes = this.pluralResolver.getSuffixes(language, opt);\n if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {\n suffixes.push(`${this.options.pluralSeparator}zero`);\n }\n suffixes.forEach(suffix => {\n send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);\n });\n });\n } else {\n send(lngs, key, defaultValue);\n }\n }\n }\n res = this.extendTranslation(res, keys, opt, resolved, lastKey);\n if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {\n res = `${namespace}${nsSeparator}${key}`;\n }\n if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {\n res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : undefined, opt);\n }\n }\n if (returnDetails) {\n resolved.res = res;\n resolved.usedParams = this.getUsedParamsDetails(opt);\n return resolved;\n }\n return res;\n }\n extendTranslation(res, key, opt, resolved, lastKey) {\n if (this.i18nFormat?.parse) {\n res = this.i18nFormat.parse(res, {\n ...this.options.interpolation.defaultVariables,\n ...opt\n }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {\n resolved\n });\n } else if (!opt.skipInterpolation) {\n if (opt.interpolation) this.interpolator.init({\n ...opt,\n ...{\n interpolation: {\n ...this.options.interpolation,\n ...opt.interpolation\n }\n }\n });\n const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== undefined ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);\n let nestBef;\n if (skipOnVariables) {\n const nb = res.match(this.interpolator.nestingRegexp);\n nestBef = nb && nb.length;\n }\n let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;\n if (this.options.interpolation.defaultVariables) data = {\n ...this.options.interpolation.defaultVariables,\n ...data\n };\n res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);\n if (skipOnVariables) {\n const na = res.match(this.interpolator.nestingRegexp);\n const nestAft = na && na.length;\n if (nestBef < nestAft) opt.nest = false;\n }\n if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;\n if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {\n if (lastKey?.[0] === args[0] && !opt.context) {\n this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);\n return null;\n }\n return this.translate(...args, key);\n }, opt);\n if (opt.interpolation) this.interpolator.reset();\n }\n const postProcess = opt.postProcess || this.options.postProcess;\n const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;\n if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {\n res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {\n i18nResolved: {\n ...resolved,\n usedParams: this.getUsedParamsDetails(opt)\n },\n ...opt\n } : opt, this);\n }\n return res;\n }\n resolve(keys, opt = {}) {\n let found;\n let usedKey;\n let exactUsedKey;\n let usedLng;\n let usedNS;\n if (isString(keys)) keys = [keys];\n keys.forEach(k => {\n if (this.isValidLookup(found)) return;\n const extracted = this.extractFromKey(k, opt);\n const key = extracted.key;\n usedKey = key;\n let namespaces = extracted.namespaces;\n if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);\n const needsPluralHandling = opt.count !== undefined && !isString(opt.count);\n const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;\n const needsContextHandling = opt.context !== undefined && (isString(opt.context) || typeof opt.context === 'number') && opt.context !== '';\n const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);\n namespaces.forEach(ns => {\n if (this.isValidLookup(found)) return;\n usedNS = ns;\n if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {\n checkedLoadedFor[`${codes[0]}-${ns}`] = true;\n this.logger.warn(`key \"${usedKey}\" for languages \"${codes.join(', ')}\" won't get resolved as namespace \"${usedNS}\" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');\n }\n codes.forEach(code => {\n if (this.isValidLookup(found)) return;\n usedLng = code;\n const finalKeys = [key];\n if (this.i18nFormat?.addLookupKeys) {\n this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);\n } else {\n let pluralSuffix;\n if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);\n const zeroSuffix = `${this.options.pluralSeparator}zero`;\n const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;\n if (needsPluralHandling) {\n if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {\n finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));\n }\n finalKeys.push(key + pluralSuffix);\n if (needsZeroSuffixLookup) {\n finalKeys.push(key + zeroSuffix);\n }\n }\n if (needsContextHandling) {\n const contextKey = `${key}${this.options.contextSeparator || '_'}${opt.context}`;\n finalKeys.push(contextKey);\n if (needsPluralHandling) {\n if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {\n finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));\n }\n finalKeys.push(contextKey + pluralSuffix);\n if (needsZeroSuffixLookup) {\n finalKeys.push(contextKey + zeroSuffix);\n }\n }\n }\n }\n let possibleKey;\n while (possibleKey = finalKeys.pop()) {\n if (!this.isValidLookup(found)) {\n exactUsedKey = possibleKey;\n found = this.getResource(code, ns, possibleKey, opt);\n }\n }\n });\n });\n });\n return {\n res: found,\n usedKey,\n exactUsedKey,\n usedLng,\n usedNS\n };\n }\n isValidLookup(res) {\n return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');\n }\n getResource(code, ns, key, options = {}) {\n if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);\n return this.resourceStore.getResource(code, ns, key, options);\n }\n getUsedParamsDetails(options = {}) {\n const optionsKeys = ['defaultValue', 'ordinal', 'context', 'replace', 'lng', 'lngs', 'fallbackLng', 'ns', 'keySeparator', 'nsSeparator', 'returnObjects', 'returnDetails', 'joinArrays', 'postProcess', 'interpolation'];\n const useOptionsReplaceForData = options.replace && !isString(options.replace);\n let data = useOptionsReplaceForData ? options.replace : options;\n if (useOptionsReplaceForData && typeof options.count !== 'undefined') {\n data.count = options.count;\n }\n if (this.options.interpolation.defaultVariables) {\n data = {\n ...this.options.interpolation.defaultVariables,\n ...data\n };\n }\n if (!useOptionsReplaceForData) {\n data = {\n ...data\n };\n for (const key of optionsKeys) {\n delete data[key];\n }\n }\n return data;\n }\n static hasDefaultValue(options) {\n const prefix = 'defaultValue';\n for (const option in options) {\n if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {\n return true;\n }\n }\n return false;\n }\n}\n\nclass LanguageUtil {\n constructor(options) {\n this.options = options;\n this.supportedLngs = this.options.supportedLngs || false;\n this.logger = baseLogger.create('languageUtils');\n }\n getScriptPartFromCode(code) {\n code = getCleanedCode(code);\n if (!code || code.indexOf('-') < 0) return null;\n const p = code.split('-');\n if (p.length === 2) return null;\n p.pop();\n if (p[p.length - 1].toLowerCase() === 'x') return null;\n return this.formatLanguageCode(p.join('-'));\n }\n getLanguagePartFromCode(code) {\n code = getCleanedCode(code);\n if (!code || code.indexOf('-') < 0) return code;\n const p = code.split('-');\n return this.formatLanguageCode(p[0]);\n }\n formatLanguageCode(code) {\n if (isString(code) && code.indexOf('-') > -1) {\n let formattedCode;\n try {\n formattedCode = Intl.getCanonicalLocales(code)[0];\n } catch (e) {}\n if (formattedCode && this.options.lowerCaseLng) {\n formattedCode = formattedCode.toLowerCase();\n }\n if (formattedCode) return formattedCode;\n if (this.options.lowerCaseLng) {\n return code.toLowerCase();\n }\n return code;\n }\n return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;\n }\n isSupportedCode(code) {\n if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {\n code = this.getLanguagePartFromCode(code);\n }\n return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;\n }\n getBestMatchFromCodes(codes) {\n if (!codes) return null;\n let found;\n codes.forEach(code => {\n if (found) return;\n const cleanedLng = this.formatLanguageCode(code);\n if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;\n });\n if (!found && this.options.supportedLngs) {\n codes.forEach(code => {\n if (found) return;\n const lngScOnly = this.getScriptPartFromCode(code);\n if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;\n const lngOnly = this.getLanguagePartFromCode(code);\n if (this.isSupportedCode(lngOnly)) return found = lngOnly;\n found = this.options.supportedLngs.find(supportedLng => {\n if (supportedLng === lngOnly) return supportedLng;\n if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;\n if (supportedLng.indexOf('-') > 0 && lngOnly.indexOf('-') < 0 && supportedLng.substring(0, supportedLng.indexOf('-')) === lngOnly) return supportedLng;\n if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;\n });\n });\n }\n if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];\n return found;\n }\n getFallbackCodes(fallbacks, code) {\n if (!fallbacks) return [];\n if (typeof fallbacks === 'function') fallbacks = fallbacks(code);\n if (isString(fallbacks)) fallbacks = [fallbacks];\n if (Array.isArray(fallbacks)) return fallbacks;\n if (!code) return fallbacks.default || [];\n let found = fallbacks[code];\n if (!found) found = fallbacks[this.getScriptPartFromCode(code)];\n if (!found) found = fallbacks[this.formatLanguageCode(code)];\n if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];\n if (!found) found = fallbacks.default;\n return found || [];\n }\n toResolveHierarchy(code, fallbackCode) {\n const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);\n const codes = [];\n const addCode = c => {\n if (!c) return;\n if (this.isSupportedCode(c)) {\n codes.push(c);\n } else {\n this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);\n }\n };\n if (isString(code) && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {\n if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));\n if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));\n if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));\n } else if (isString(code)) {\n addCode(this.formatLanguageCode(code));\n }\n fallbackCodes.forEach(fc => {\n if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));\n });\n return codes;\n }\n}\n\nconst suffixesOrder = {\n zero: 0,\n one: 1,\n two: 2,\n few: 3,\n many: 4,\n other: 5\n};\nconst dummyRule = {\n select: count => count === 1 ? 'one' : 'other',\n resolvedOptions: () => ({\n pluralCategories: ['one', 'other']\n })\n};\nclass PluralResolver {\n constructor(languageUtils, options = {}) {\n this.languageUtils = languageUtils;\n this.options = options;\n this.logger = baseLogger.create('pluralResolver');\n this.pluralRulesCache = {};\n }\n addRule(lng, obj) {\n this.rules[lng] = obj;\n }\n clearCache() {\n this.pluralRulesCache = {};\n }\n getRule(code, options = {}) {\n const cleanedCode = getCleanedCode(code === 'dev' ? 'en' : code);\n const type = options.ordinal ? 'ordinal' : 'cardinal';\n const cacheKey = JSON.stringify({\n cleanedCode,\n type\n });\n if (cacheKey in this.pluralRulesCache) {\n return this.pluralRulesCache[cacheKey];\n }\n let rule;\n try {\n rule = new Intl.PluralRules(cleanedCode, {\n type\n });\n } catch (err) {\n if (!Intl) {\n this.logger.error('No Intl support, please use an Intl polyfill!');\n return dummyRule;\n }\n if (!code.match(/-|_/)) return dummyRule;\n const lngPart = this.languageUtils.getLanguagePartFromCode(code);\n rule = this.getRule(lngPart, options);\n }\n this.pluralRulesCache[cacheKey] = rule;\n return rule;\n }\n needsPlural(code, options = {}) {\n let rule = this.getRule(code, options);\n if (!rule) rule = this.getRule('dev', options);\n return rule?.resolvedOptions().pluralCategories.length > 1;\n }\n getPluralFormsOfKey(code, key, options = {}) {\n return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);\n }\n getSuffixes(code, options = {}) {\n let rule = this.getRule(code, options);\n if (!rule) rule = this.getRule('dev', options);\n if (!rule) return [];\n return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);\n }\n getSuffix(code, count, options = {}) {\n const rule = this.getRule(code, options);\n if (rule) {\n return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;\n }\n this.logger.warn(`no plural rule found for: ${code}`);\n return this.getSuffix('dev', count, options);\n }\n}\n\nconst deepFindWithDefaults = (data, defaultData, key, keySeparator = '.', ignoreJSONStructure = true) => {\n let path = getPathWithDefaults(data, defaultData, key);\n if (!path && ignoreJSONStructure && isString(key)) {\n path = deepFind(data, key, keySeparator);\n if (path === undefined) path = deepFind(defaultData, key, keySeparator);\n }\n return path;\n};\nconst regexSafe = val => val.replace(/\\$/g, '$$$$');\nclass Interpolator {\n constructor(options = {}) {\n this.logger = baseLogger.create('interpolator');\n this.options = options;\n this.format = options?.interpolation?.format || (value => value);\n this.init(options);\n }\n init(options = {}) {\n if (!options.interpolation) options.interpolation = {\n escapeValue: true\n };\n const {\n escape: escape$1,\n escapeValue,\n useRawValueToEscape,\n prefix,\n prefixEscaped,\n suffix,\n suffixEscaped,\n formatSeparator,\n unescapeSuffix,\n unescapePrefix,\n nestingPrefix,\n nestingPrefixEscaped,\n nestingSuffix,\n nestingSuffixEscaped,\n nestingOptionsSeparator,\n maxReplaces,\n alwaysFormat\n } = options.interpolation;\n this.escape = escape$1 !== undefined ? escape$1 : escape;\n this.escapeValue = escapeValue !== undefined ? escapeValue : true;\n this.useRawValueToEscape = useRawValueToEscape !== undefined ? useRawValueToEscape : false;\n this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || '{{';\n this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || '}}';\n this.formatSeparator = formatSeparator || ',';\n this.unescapePrefix = unescapeSuffix ? '' : unescapePrefix || '-';\n this.unescapeSuffix = this.unescapePrefix ? '' : unescapeSuffix || '';\n this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape('$t(');\n this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(')');\n this.nestingOptionsSeparator = nestingOptionsSeparator || ',';\n this.maxReplaces = maxReplaces || 1000;\n this.alwaysFormat = alwaysFormat !== undefined ? alwaysFormat : false;\n this.resetRegExp();\n }\n reset() {\n if (this.options) this.init(this.options);\n }\n resetRegExp() {\n const getOrResetRegExp = (existingRegExp, pattern) => {\n if (existingRegExp?.source === pattern) {\n existingRegExp.lastIndex = 0;\n return existingRegExp;\n }\n return new RegExp(pattern, 'g');\n };\n this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);\n this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);\n this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()\"']+|\"[^\"]*\"|'[^']*'|\\\\((?:[^()]|\"[^\"]*\"|'[^']*')*\\\\))*?)${this.nestingSuffix}`);\n }\n interpolate(str, data, lng, options) {\n let match;\n let value;\n let replaces;\n const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};\n const handleFormat = key => {\n if (key.indexOf(this.formatSeparator) < 0) {\n const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);\n return this.alwaysFormat ? this.format(path, undefined, lng, {\n ...options,\n ...data,\n interpolationkey: key\n }) : path;\n }\n const p = key.split(this.formatSeparator);\n const k = p.shift().trim();\n const f = p.join(this.formatSeparator).trim();\n return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {\n ...options,\n ...data,\n interpolationkey: k\n });\n };\n this.resetRegExp();\n const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;\n const skipOnVariables = options?.interpolation?.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;\n const todos = [{\n regex: this.regexpUnescape,\n safeValue: val => regexSafe(val)\n }, {\n regex: this.regexp,\n safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)\n }];\n todos.forEach(todo => {\n replaces = 0;\n while (match = todo.regex.exec(str)) {\n const matchedVar = match[1].trim();\n value = handleFormat(matchedVar);\n if (value === undefined) {\n if (typeof missingInterpolationHandler === 'function') {\n const temp = missingInterpolationHandler(str, match, options);\n value = isString(temp) ? temp : '';\n } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {\n value = '';\n } else if (skipOnVariables) {\n value = match[0];\n continue;\n } else {\n this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);\n value = '';\n }\n } else if (!isString(value) && !this.useRawValueToEscape) {\n value = makeString(value);\n }\n const safeValue = todo.safeValue(value);\n str = str.replace(match[0], safeValue);\n if (skipOnVariables) {\n todo.regex.lastIndex += value.length;\n todo.regex.lastIndex -= match[0].length;\n } else {\n todo.regex.lastIndex = 0;\n }\n replaces++;\n if (replaces >= this.maxReplaces) {\n break;\n }\n }\n });\n return str;\n }\n nest(str, fc, options = {}) {\n let match;\n let value;\n let clonedOptions;\n const handleHasOptions = (key, inheritedOptions) => {\n const sep = this.nestingOptionsSeparator;\n if (key.indexOf(sep) < 0) return key;\n const c = key.split(new RegExp(`${sep}[ ]*{`));\n let optionsString = `{${c[1]}`;\n key = c[0];\n optionsString = this.interpolate(optionsString, clonedOptions);\n const matchedSingleQuotes = optionsString.match(/'/g);\n const matchedDoubleQuotes = optionsString.match(/\"/g);\n if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {\n optionsString = optionsString.replace(/'/g, '\"');\n }\n try {\n clonedOptions = JSON.parse(optionsString);\n if (inheritedOptions) clonedOptions = {\n ...inheritedOptions,\n ...clonedOptions\n };\n } catch (e) {\n this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);\n return `${key}${sep}${optionsString}`;\n }\n if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;\n return key;\n };\n while (match = this.nestingRegexp.exec(str)) {\n let formatters = [];\n clonedOptions = {\n ...options\n };\n clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;\n clonedOptions.applyPostProcessor = false;\n delete clonedOptions.defaultValue;\n const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf('}') + 1 : match[1].indexOf(this.formatSeparator);\n if (keyEndIndex !== -1) {\n formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map(elem => elem.trim()).filter(Boolean);\n match[1] = match[1].slice(0, keyEndIndex);\n }\n value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);\n if (value && match[0] === str && !isString(value)) return value;\n if (!isString(value)) value = makeString(value);\n if (!value) {\n this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);\n value = '';\n }\n if (formatters.length) {\n value = formatters.reduce((v, f) => this.format(v, f, options.lng, {\n ...options,\n interpolationkey: match[1].trim()\n }), value.trim());\n }\n str = str.replace(match[0], value);\n this.regexp.lastIndex = 0;\n }\n return str;\n }\n}\n\nconst parseFormatStr = formatStr => {\n let formatName = formatStr.toLowerCase().trim();\n const formatOptions = {};\n if (formatStr.indexOf('(') > -1) {\n const p = formatStr.split('(');\n formatName = p[0].toLowerCase().trim();\n const optStr = p[1].substring(0, p[1].length - 1);\n if (formatName === 'currency' && optStr.indexOf(':') < 0) {\n if (!formatOptions.currency) formatOptions.currency = optStr.trim();\n } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {\n if (!formatOptions.range) formatOptions.range = optStr.trim();\n } else {\n const opts = optStr.split(';');\n opts.forEach(opt => {\n if (opt) {\n const [key, ...rest] = opt.split(':');\n const val = rest.join(':').trim().replace(/^'+|'+$/g, '');\n const trimmedKey = key.trim();\n if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;\n if (val === 'false') formatOptions[trimmedKey] = false;\n if (val === 'true') formatOptions[trimmedKey] = true;\n if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);\n }\n });\n }\n }\n return {\n formatName,\n formatOptions\n };\n};\nconst createCachedFormatter = fn => {\n const cache = {};\n return (v, l, o) => {\n let optForCache = o;\n if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {\n optForCache = {\n ...optForCache,\n [o.interpolationkey]: undefined\n };\n }\n const key = l + JSON.stringify(optForCache);\n let frm = cache[key];\n if (!frm) {\n frm = fn(getCleanedCode(l), o);\n cache[key] = frm;\n }\n return frm(v);\n };\n};\nconst createNonCachedFormatter = fn => (v, l, o) => fn(getCleanedCode(l), o)(v);\nclass Formatter {\n constructor(options = {}) {\n this.logger = baseLogger.create('formatter');\n this.options = options;\n this.init(options);\n }\n init(services, options = {\n interpolation: {}\n }) {\n this.formatSeparator = options.interpolation.formatSeparator || ',';\n const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;\n this.formats = {\n number: cf((lng, opt) => {\n const formatter = new Intl.NumberFormat(lng, {\n ...opt\n });\n return val => formatter.format(val);\n }),\n currency: cf((lng, opt) => {\n const formatter = new Intl.NumberFormat(lng, {\n ...opt,\n style: 'currency'\n });\n return val => formatter.format(val);\n }),\n datetime: cf((lng, opt) => {\n const formatter = new Intl.DateTimeFormat(lng, {\n ...opt\n });\n return val => formatter.format(val);\n }),\n relativetime: cf((lng, opt) => {\n const formatter = new Intl.RelativeTimeFormat(lng, {\n ...opt\n });\n return val => formatter.format(val, opt.range || 'day');\n }),\n list: cf((lng, opt) => {\n const formatter = new Intl.ListFormat(lng, {\n ...opt\n });\n return val => formatter.format(val);\n })\n };\n }\n add(name, fc) {\n this.formats[name.toLowerCase().trim()] = fc;\n }\n addCached(name, fc) {\n this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);\n }\n format(value, format, lng, options = {}) {\n const formats = format.split(this.formatSeparator);\n if (formats.length > 1 && formats[0].indexOf('(') > 1 && formats[0].indexOf(')') < 0 && formats.find(f => f.indexOf(')') > -1)) {\n const lastIndex = formats.findIndex(f => f.indexOf(')') > -1);\n formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);\n }\n const result = formats.reduce((mem, f) => {\n const {\n formatName,\n formatOptions\n } = parseFormatStr(f);\n if (this.formats[formatName]) {\n let formatted = mem;\n try {\n const valOptions = options?.formatParams?.[options.interpolationkey] || {};\n const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;\n formatted = this.formats[formatName](mem, l, {\n ...formatOptions,\n ...options,\n ...valOptions\n });\n } catch (error) {\n this.logger.warn(error);\n }\n return formatted;\n } else {\n this.logger.warn(`there was no format function for ${formatName}`);\n }\n return mem;\n }, value);\n return result;\n }\n}\n\nconst removePending = (q, name) => {\n if (q.pending[name] !== undefined) {\n delete q.pending[name];\n q.pendingCount--;\n }\n};\nclass Connector extends EventEmitter {\n constructor(backend, store, services, options = {}) {\n super();\n this.backend = backend;\n this.store = store;\n this.services = services;\n this.languageUtils = services.languageUtils;\n this.options = options;\n this.logger = baseLogger.create('backendConnector');\n this.waitingReads = [];\n this.maxParallelReads = options.maxParallelReads || 10;\n this.readingCalls = 0;\n this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;\n this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;\n this.state = {};\n this.queue = [];\n this.backend?.init?.(services, options.backend, options);\n }\n queueLoad(languages, namespaces, options, callback) {\n const toLoad = {};\n const pending = {};\n const toLoadLanguages = {};\n const toLoadNamespaces = {};\n languages.forEach(lng => {\n let hasAllNamespaces = true;\n namespaces.forEach(ns => {\n const name = `${lng}|${ns}`;\n if (!options.reload && this.store.hasResourceBundle(lng, ns)) {\n this.state[name] = 2;\n } else if (this.state[name] < 0) ; else if (this.state[name] === 1) {\n if (pending[name] === undefined) pending[name] = true;\n } else {\n this.state[name] = 1;\n hasAllNamespaces = false;\n if (pending[name] === undefined) pending[name] = true;\n if (toLoad[name] === undefined) toLoad[name] = true;\n if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;\n }\n });\n if (!hasAllNamespaces) toLoadLanguages[lng] = true;\n });\n if (Object.keys(toLoad).length || Object.keys(pending).length) {\n this.queue.push({\n pending,\n pendingCount: Object.keys(pending).length,\n loaded: {},\n errors: [],\n callback\n });\n }\n return {\n toLoad: Object.keys(toLoad),\n pending: Object.keys(pending),\n toLoadLanguages: Object.keys(toLoadLanguages),\n toLoadNamespaces: Object.keys(toLoadNamespaces)\n };\n }\n loaded(name, err, data) {\n const s = name.split('|');\n const lng = s[0];\n const ns = s[1];\n if (err) this.emit('failedLoading', lng, ns, err);\n if (!err && data) {\n this.store.addResourceBundle(lng, ns, data, undefined, undefined, {\n skipCopy: true\n });\n }\n this.state[name] = err ? -1 : 2;\n if (err && data) this.state[name] = 0;\n const loaded = {};\n this.queue.forEach(q => {\n pushPath(q.loaded, [lng], ns);\n removePending(q, name);\n if (err) q.errors.push(err);\n if (q.pendingCount === 0 && !q.done) {\n Object.keys(q.loaded).forEach(l => {\n if (!loaded[l]) loaded[l] = {};\n const loadedKeys = q.loaded[l];\n if (loadedKeys.length) {\n loadedKeys.forEach(n => {\n if (loaded[l][n] === undefined) loaded[l][n] = true;\n });\n }\n });\n q.done = true;\n if (q.errors.length) {\n q.callback(q.errors);\n } else {\n q.callback();\n }\n }\n });\n this.emit('loaded', loaded);\n this.queue = this.queue.filter(q => !q.done);\n }\n read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {\n if (!lng.length) return callback(null, {});\n if (this.readingCalls >= this.maxParallelReads) {\n this.waitingReads.push({\n lng,\n ns,\n fcName,\n tried,\n wait,\n callback\n });\n return;\n }\n this.readingCalls++;\n const resolver = (err, data) => {\n this.readingCalls--;\n if (this.waitingReads.length > 0) {\n const next = this.waitingReads.shift();\n this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);\n }\n if (err && data && tried < this.maxRetries) {\n setTimeout(() => {\n this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);\n }, wait);\n return;\n }\n callback(err, data);\n };\n const fc = this.backend[fcName].bind(this.backend);\n if (fc.length === 2) {\n try {\n const r = fc(lng, ns);\n if (r && typeof r.then === 'function') {\n r.then(data => resolver(null, data)).catch(resolver);\n } else {\n resolver(null, r);\n }\n } catch (err) {\n resolver(err);\n }\n return;\n }\n return fc(lng, ns, resolver);\n }\n prepareLoading(languages, namespaces, options = {}, callback) {\n if (!this.backend) {\n this.logger.warn('No backend was added via i18next.use. Will not load resources.');\n return callback && callback();\n }\n if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);\n if (isString(namespaces)) namespaces = [namespaces];\n const toLoad = this.queueLoad(languages, namespaces, options, callback);\n if (!toLoad.toLoad.length) {\n if (!toLoad.pending.length) callback();\n return null;\n }\n toLoad.toLoad.forEach(name => {\n this.loadOne(name);\n });\n }\n load(languages, namespaces, callback) {\n this.prepareLoading(languages, namespaces, {}, callback);\n }\n reload(languages, namespaces, callback) {\n this.prepareLoading(languages, namespaces, {\n reload: true\n }, callback);\n }\n loadOne(name, prefix = '') {\n const s = name.split('|');\n const lng = s[0];\n const ns = s[1];\n this.read(lng, ns, 'read', undefined, undefined, (err, data) => {\n if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);\n if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);\n this.loaded(name, err, data);\n });\n }\n saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {\n if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {\n this.logger.warn(`did not save key \"${key}\" as the namespace \"${namespace}\" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');\n return;\n }\n if (key === undefined || key === null || key === '') return;\n if (this.backend?.create) {\n const opts = {\n ...options,\n isUpdate\n };\n const fc = this.backend.create.bind(this.backend);\n if (fc.length < 6) {\n try {\n let r;\n if (fc.length === 5) {\n r = fc(languages, namespace, key, fallbackValue, opts);\n } else {\n r = fc(languages, namespace, key, fallbackValue);\n }\n if (r && typeof r.then === 'function') {\n r.then(data => clb(null, data)).catch(clb);\n } else {\n clb(null, r);\n }\n } catch (err) {\n clb(err);\n }\n } else {\n fc(languages, namespace, key, fallbackValue, clb, opts);\n }\n }\n if (!languages || !languages[0]) return;\n this.store.addResource(languages[0], namespace, key, fallbackValue);\n }\n}\n\nconst get = () => ({\n debug: false,\n initAsync: true,\n ns: ['translation'],\n defaultNS: ['translation'],\n fallbackLng: ['dev'],\n fallbackNS: false,\n supportedLngs: false,\n nonExplicitSupportedLngs: false,\n load: 'all',\n preload: false,\n simplifyPluralSuffix: true,\n keySeparator: '.',\n nsSeparator: ':',\n pluralSeparator: '_',\n contextSeparator: '_',\n partialBundledLanguages: false,\n saveMissing: false,\n updateMissing: false,\n saveMissingTo: 'fallback',\n saveMissingPlurals: true,\n missingKeyHandler: false,\n missingInterpolationHandler: false,\n postProcess: false,\n postProcessPassResolved: false,\n returnNull: false,\n returnEmptyString: true,\n returnObjects: false,\n joinArrays: false,\n returnedObjectHandler: false,\n parseMissingKeyHandler: false,\n appendNamespaceToMissingKey: false,\n appendNamespaceToCIMode: false,\n overloadTranslationOptionHandler: args => {\n let ret = {};\n if (typeof args[1] === 'object') ret = args[1];\n if (isString(args[1])) ret.defaultValue = args[1];\n if (isString(args[2])) ret.tDescription = args[2];\n if (typeof args[2] === 'object' || typeof args[3] === 'object') {\n const options = args[3] || args[2];\n Object.keys(options).forEach(key => {\n ret[key] = options[key];\n });\n }\n return ret;\n },\n interpolation: {\n escapeValue: true,\n format: value => value,\n prefix: '{{',\n suffix: '}}',\n formatSeparator: ',',\n unescapePrefix: '-',\n nestingPrefix: '$t(',\n nestingSuffix: ')',\n nestingOptionsSeparator: ',',\n maxReplaces: 1000,\n skipOnVariables: true\n },\n cacheInBuiltFormats: true\n});\nconst transformOptions = options => {\n if (isString(options.ns)) options.ns = [options.ns];\n if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];\n if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];\n if (options.supportedLngs?.indexOf?.('cimode') < 0) {\n options.supportedLngs = options.supportedLngs.concat(['cimode']);\n }\n if (typeof options.initImmediate === 'boolean') options.initAsync = options.initImmediate;\n return options;\n};\n\nconst noop = () => {};\nconst bindMemberFunctions = inst => {\n const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));\n mems.forEach(mem => {\n if (typeof inst[mem] === 'function') {\n inst[mem] = inst[mem].bind(inst);\n }\n });\n};\nclass I18n extends EventEmitter {\n constructor(options = {}, callback) {\n super();\n this.options = transformOptions(options);\n this.services = {};\n this.logger = baseLogger;\n this.modules = {\n external: []\n };\n bindMemberFunctions(this);\n if (callback && !this.isInitialized && !options.isClone) {\n if (!this.options.initAsync) {\n this.init(options, callback);\n return this;\n }\n setTimeout(() => {\n this.init(options, callback);\n }, 0);\n }\n }\n init(options = {}, callback) {\n this.isInitializing = true;\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n if (options.defaultNS == null && options.ns) {\n if (isString(options.ns)) {\n options.defaultNS = options.ns;\n } else if (options.ns.indexOf('translation') < 0) {\n options.defaultNS = options.ns[0];\n }\n }\n const defOpts = get();\n this.options = {\n ...defOpts,\n ...this.options,\n ...transformOptions(options)\n };\n this.options.interpolation = {\n ...defOpts.interpolation,\n ...this.options.interpolation\n };\n if (options.keySeparator !== undefined) {\n this.options.userDefinedKeySeparator = options.keySeparator;\n }\n if (options.nsSeparator !== undefined) {\n this.options.userDefinedNsSeparator = options.nsSeparator;\n }\n if (typeof this.options.overloadTranslationOptionHandler !== 'function') {\n this.options.overloadTranslationOptionHandler = defOpts.overloadTranslationOptionHandler;\n }\n const createClassOnDemand = ClassOrObject => {\n if (!ClassOrObject) return null;\n if (typeof ClassOrObject === 'function') return new ClassOrObject();\n return ClassOrObject;\n };\n if (!this.options.isClone) {\n if (this.modules.logger) {\n baseLogger.init(createClassOnDemand(this.modules.logger), this.options);\n } else {\n baseLogger.init(null, this.options);\n }\n let formatter;\n if (this.modules.formatter) {\n formatter = this.modules.formatter;\n } else {\n formatter = Formatter;\n }\n const lu = new LanguageUtil(this.options);\n this.store = new ResourceStore(this.options.resources, this.options);\n const s = this.services;\n s.logger = baseLogger;\n s.resourceStore = this.store;\n s.languageUtils = lu;\n s.pluralResolver = new PluralResolver(lu, {\n prepend: this.options.pluralSeparator,\n simplifyPluralSuffix: this.options.simplifyPluralSuffix\n });\n const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format;\n if (usingLegacyFormatFunction) {\n this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);\n }\n if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {\n s.formatter = createClassOnDemand(formatter);\n if (s.formatter.init) s.formatter.init(s, this.options);\n this.options.interpolation.format = s.formatter.format.bind(s.formatter);\n }\n s.interpolator = new Interpolator(this.options);\n s.utils = {\n hasLoadedNamespace: this.hasLoadedNamespace.bind(this)\n };\n s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);\n s.backendConnector.on('*', (event, ...args) => {\n this.emit(event, ...args);\n });\n if (this.modules.languageDetector) {\n s.languageDetector = createClassOnDemand(this.modules.languageDetector);\n if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);\n }\n if (this.modules.i18nFormat) {\n s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);\n if (s.i18nFormat.init) s.i18nFormat.init(this);\n }\n this.translator = new Translator(this.services, this.options);\n this.translator.on('*', (event, ...args) => {\n this.emit(event, ...args);\n });\n this.modules.external.forEach(m => {\n if (m.init) m.init(this);\n });\n }\n this.format = this.options.interpolation.format;\n if (!callback) callback = noop;\n if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {\n const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);\n if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];\n }\n if (!this.services.languageDetector && !this.options.lng) {\n this.logger.warn('init: no languageDetector is used and no lng is defined');\n }\n const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];\n storeApi.forEach(fcName => {\n this[fcName] = (...args) => this.store[fcName](...args);\n });\n const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];\n storeApiChained.forEach(fcName => {\n this[fcName] = (...args) => {\n this.store[fcName](...args);\n return this;\n };\n });\n const deferred = defer();\n const load = () => {\n const finish = (err, t) => {\n this.isInitializing = false;\n if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');\n this.isInitialized = true;\n if (!this.options.isClone) this.logger.log('initialized', this.options);\n this.emit('initialized', this.options);\n deferred.resolve(t);\n callback(err, t);\n };\n if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));\n this.changeLanguage(this.options.lng, finish);\n };\n if (this.options.resources || !this.options.initAsync) {\n load();\n } else {\n setTimeout(load, 0);\n }\n return deferred;\n }\n loadResources(language, callback = noop) {\n let usedCallback = callback;\n const usedLng = isString(language) ? language : this.language;\n if (typeof language === 'function') usedCallback = language;\n if (!this.options.resources || this.options.partialBundledLanguages) {\n if (usedLng?.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();\n const toLoad = [];\n const append = lng => {\n if (!lng) return;\n if (lng === 'cimode') return;\n const lngs = this.services.languageUtils.toResolveHierarchy(lng);\n lngs.forEach(l => {\n if (l === 'cimode') return;\n if (toLoad.indexOf(l) < 0) toLoad.push(l);\n });\n };\n if (!usedLng) {\n const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);\n fallbacks.forEach(l => append(l));\n } else {\n append(usedLng);\n }\n this.options.preload?.forEach?.(l => append(l));\n this.services.backendConnector.load(toLoad, this.options.ns, e => {\n if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);\n usedCallback(e);\n });\n } else {\n usedCallback(null);\n }\n }\n reloadResources(lngs, ns, callback) {\n const deferred = defer();\n if (typeof lngs === 'function') {\n callback = lngs;\n lngs = undefined;\n }\n if (typeof ns === 'function') {\n callback = ns;\n ns = undefined;\n }\n if (!lngs) lngs = this.languages;\n if (!ns) ns = this.options.ns;\n if (!callback) callback = noop;\n this.services.backendConnector.reload(lngs, ns, err => {\n deferred.resolve();\n callback(err);\n });\n return deferred;\n }\n use(module) {\n if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');\n if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');\n if (module.type === 'backend') {\n this.modules.backend = module;\n }\n if (module.type === 'logger' || module.log && module.warn && module.error) {\n this.modules.logger = module;\n }\n if (module.type === 'languageDetector') {\n this.modules.languageDetector = module;\n }\n if (module.type === 'i18nFormat') {\n this.modules.i18nFormat = module;\n }\n if (module.type === 'postProcessor') {\n postProcessor.addPostProcessor(module);\n }\n if (module.type === 'formatter') {\n this.modules.formatter = module;\n }\n if (module.type === '3rdParty') {\n this.modules.external.push(module);\n }\n return this;\n }\n setResolvedLanguage(l) {\n if (!l || !this.languages) return;\n if (['cimode', 'dev'].indexOf(l) > -1) return;\n for (let li = 0; li < this.languages.length; li++) {\n const lngInLngs = this.languages[li];\n if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;\n if (this.store.hasLanguageSomeTranslations(lngInLngs)) {\n this.resolvedLanguage = lngInLngs;\n break;\n }\n }\n if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {\n this.resolvedLanguage = l;\n this.languages.unshift(l);\n }\n }\n changeLanguage(lng, callback) {\n this.isLanguageChangingTo = lng;\n const deferred = defer();\n this.emit('languageChanging', lng);\n const setLngProps = l => {\n this.language = l;\n this.languages = this.services.languageUtils.toResolveHierarchy(l);\n this.resolvedLanguage = undefined;\n this.setResolvedLanguage(l);\n };\n const done = (err, l) => {\n if (l) {\n if (this.isLanguageChangingTo === lng) {\n setLngProps(l);\n this.translator.changeLanguage(l);\n this.isLanguageChangingTo = undefined;\n this.emit('languageChanged', l);\n this.logger.log('languageChanged', l);\n }\n } else {\n this.isLanguageChangingTo = undefined;\n }\n deferred.resolve((...args) => this.t(...args));\n if (callback) callback(err, (...args) => this.t(...args));\n };\n const setLng = lngs => {\n if (!lng && !lngs && this.services.languageDetector) lngs = [];\n const fl = isString(lngs) ? lngs : lngs && lngs[0];\n const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);\n if (l) {\n if (!this.language) {\n setLngProps(l);\n }\n if (!this.translator.language) this.translator.changeLanguage(l);\n this.services.languageDetector?.cacheUserLanguage?.(l);\n }\n this.loadResources(l, err => {\n done(err, l);\n });\n };\n if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {\n setLng(this.services.languageDetector.detect());\n } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {\n if (this.services.languageDetector.detect.length === 0) {\n this.services.languageDetector.detect().then(setLng);\n } else {\n this.services.languageDetector.detect(setLng);\n }\n } else {\n setLng(lng);\n }\n return deferred;\n }\n getFixedT(lng, ns, keyPrefix) {\n const fixedT = (key, opts, ...rest) => {\n let o;\n if (typeof opts !== 'object') {\n o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));\n } else {\n o = {\n ...opts\n };\n }\n o.lng = o.lng || fixedT.lng;\n o.lngs = o.lngs || fixedT.lngs;\n o.ns = o.ns || fixedT.ns;\n if (o.keyPrefix !== '') o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;\n const keySeparator = this.options.keySeparator || '.';\n let resultKey;\n if (o.keyPrefix && Array.isArray(key)) {\n resultKey = key.map(k => {\n if (typeof k === 'function') k = keysFromSelector(k, {\n ...this.options,\n ...opts\n });\n return `${o.keyPrefix}${keySeparator}${k}`;\n });\n } else {\n if (typeof key === 'function') key = keysFromSelector(key, {\n ...this.options,\n ...opts\n });\n resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;\n }\n return this.t(resultKey, o);\n };\n if (isString(lng)) {\n fixedT.lng = lng;\n } else {\n fixedT.lngs = lng;\n }\n fixedT.ns = ns;\n fixedT.keyPrefix = keyPrefix;\n return fixedT;\n }\n t(...args) {\n return this.translator?.translate(...args);\n }\n exists(...args) {\n return this.translator?.exists(...args);\n }\n setDefaultNamespace(ns) {\n this.options.defaultNS = ns;\n }\n hasLoadedNamespace(ns, options = {}) {\n if (!this.isInitialized) {\n this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);\n return false;\n }\n if (!this.languages || !this.languages.length) {\n this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);\n return false;\n }\n const lng = options.lng || this.resolvedLanguage || this.languages[0];\n const fallbackLng = this.options ? this.options.fallbackLng : false;\n const lastLng = this.languages[this.languages.length - 1];\n if (lng.toLowerCase() === 'cimode') return true;\n const loadNotPending = (l, n) => {\n const loadState = this.services.backendConnector.state[`${l}|${n}`];\n return loadState === -1 || loadState === 0 || loadState === 2;\n };\n if (options.precheck) {\n const preResult = options.precheck(this, loadNotPending);\n if (preResult !== undefined) return preResult;\n }\n if (this.hasResourceBundle(lng, ns)) return true;\n if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;\n if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;\n return false;\n }\n loadNamespaces(ns, callback) {\n const deferred = defer();\n if (!this.options.ns) {\n if (callback) callback();\n return Promise.resolve();\n }\n if (isString(ns)) ns = [ns];\n ns.forEach(n => {\n if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);\n });\n this.loadResources(err => {\n deferred.resolve();\n if (callback) callback(err);\n });\n return deferred;\n }\n loadLanguages(lngs, callback) {\n const deferred = defer();\n if (isString(lngs)) lngs = [lngs];\n const preloaded = this.options.preload || [];\n const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));\n if (!newLngs.length) {\n if (callback) callback();\n return Promise.resolve();\n }\n this.options.preload = preloaded.concat(newLngs);\n this.loadResources(err => {\n deferred.resolve();\n if (callback) callback(err);\n });\n return deferred;\n }\n dir(lng) {\n if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);\n if (!lng) return 'rtl';\n try {\n const l = new Intl.Locale(lng);\n if (l && l.getTextInfo) {\n const ti = l.getTextInfo();\n if (ti && ti.direction) return ti.direction;\n }\n } catch (e) {}\n const rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb'];\n const languageUtils = this.services?.languageUtils || new LanguageUtil(get());\n if (lng.toLowerCase().indexOf('-latn') > 1) return 'ltr';\n return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';\n }\n static createInstance(options = {}, callback) {\n const instance = new I18n(options, callback);\n instance.createInstance = I18n.createInstance;\n return instance;\n }\n cloneInstance(options = {}, callback = noop) {\n const forkResourceStore = options.forkResourceStore;\n if (forkResourceStore) delete options.forkResourceStore;\n const mergedOptions = {\n ...this.options,\n ...options,\n ...{\n isClone: true\n }\n };\n const clone = new I18n(mergedOptions);\n if (options.debug !== undefined || options.prefix !== undefined) {\n clone.logger = clone.logger.clone(options);\n }\n const membersToCopy = ['store', 'services', 'language'];\n membersToCopy.forEach(m => {\n clone[m] = this[m];\n });\n clone.services = {\n ...this.services\n };\n clone.services.utils = {\n hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)\n };\n if (forkResourceStore) {\n const clonedData = Object.keys(this.store.data).reduce((prev, l) => {\n prev[l] = {\n ...this.store.data[l]\n };\n prev[l] = Object.keys(prev[l]).reduce((acc, n) => {\n acc[n] = {\n ...prev[l][n]\n };\n return acc;\n }, prev[l]);\n return prev;\n }, {});\n clone.store = new ResourceStore(clonedData, mergedOptions);\n clone.services.resourceStore = clone.store;\n }\n if (options.interpolation) clone.services.interpolator = new Interpolator(mergedOptions);\n clone.translator = new Translator(clone.services, mergedOptions);\n clone.translator.on('*', (event, ...args) => {\n clone.emit(event, ...args);\n });\n clone.init(mergedOptions, callback);\n clone.translator.options = mergedOptions;\n clone.translator.backendConnector.services.utils = {\n hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)\n };\n return clone;\n }\n toJSON() {\n return {\n options: this.options,\n store: this.store,\n language: this.language,\n languages: this.languages,\n resolvedLanguage: this.resolvedLanguage\n };\n }\n}\nconst instance = I18n.createInstance();\n\nconst createInstance = instance.createInstance;\nconst dir = instance.dir;\nconst init = instance.init;\nconst loadResources = instance.loadResources;\nconst reloadResources = instance.reloadResources;\nconst use = instance.use;\nconst changeLanguage = instance.changeLanguage;\nconst getFixedT = instance.getFixedT;\nconst t = instance.t;\nconst exists = instance.exists;\nconst setDefaultNamespace = instance.setDefaultNamespace;\nconst hasLoadedNamespace = instance.hasLoadedNamespace;\nconst loadNamespaces = instance.loadNamespaces;\nconst loadLanguages = instance.loadLanguages;\n\nexport { changeLanguage, createInstance, instance as default, dir, exists, getFixedT, hasLoadedNamespace, init, keysFromSelector as keyFromSelector, loadLanguages, loadNamespaces, loadResources, reloadResources, setDefaultNamespace, t, use };\n","import ButtonAction from \"@components/common/button-action\";\nimport ModalZoom from \"@components/common/modal/modal-zoom\";\nimport { QUERY_KEYS } from \"@constants/query.constant\";\nimport { POSPath } from \"@constants/routes.constants\";\nimport useSessionProvider from \"@provider/use-session-provider\";\nimport { formatCurrency } from \"@utils/functions\";\nimport { t } from \"i18next\";\nimport { useMemo, useState } from \"react\";\nimport { FormProvider } from \"react-hook-form\";\nimport { useNavigate } from \"react-router-dom\";\n\ntype RecordType = Record<string, any>;\n\ntype POSStatus =\n | false\n | \"opened\"\n | \"closed\"\n | \"opening_control\"\n | \"closing_control\";\n\ntype TProps = {\n openModal: boolean;\n setOpenModal: (val: boolean) => void;\n methods: any;\n row: any;\n record: RecordType;\n};\n\nconst OpenSessionModal = (props: TProps) => {\n const { openModal, setOpenModal, methods, row, record } = props;\n const { openSession, setOpeningCashBox } = useSessionProvider();\n const [money, setMoney] = useState(\"\");\n const [loading, setLoading] = useState(false);\n const data = useMemo(() => {\n return {\n current_session_id: record[\"current_session_id\"]?.id ?? \"\",\n record_id: record?.id as number,\n current_session_state: record[\"current_session_state\"] as POSStatus,\n module_pos_restaurant: record[\"module_pos_restaurant\"] as boolean,\n name: record.name as string,\n id: record.id as number,\n cash_control: record.cash_control as boolean,\n };\n }, [record]);\n const onClose = () => props.setOpenModal(false);\n\n const navigate = useNavigate();\n const handleOpeningCashBoxSuccess = (sessionId: number) => {\n onClose();\n if (data.module_pos_restaurant)\n return navigate(\n `${POSPath.TABLES}?${QUERY_KEYS.POS_ID}=${data.id}&${QUERY_KEYS.SESSION_ID}=${sessionId}`\n );\n // return `/${PosPaths.MANAGEMENT_TABLE}?${QUERY_KEYS.POS_ID}=${data.id}&${QUERY_KEYS.SESSION_ID}=${sessionId}`;\n return navigate(\n `${POSPath.MENUS}?${QUERY_KEYS.POS_ID}=${data.id}&${QUERY_KEYS.SESSION_ID}=${sessionId}`\n );\n // else return toast.info(\"Đang phát triển\");\n };\n\n const onSetOpeningCashBox = async (\n cashBoxValue: number,\n sessionId: number\n ) => {\n try {\n await setOpeningCashBox.mutateAsync(\n {\n cashBoxValue,\n sessionId: Number(sessionId),\n },\n {\n onSuccess: () => {\n handleOpeningCashBoxSuccess(sessionId);\n },\n }\n );\n } catch (error) {\n console.error(\"Error setting opening cash box:\", error);\n }\n };\n\n const handleOpenSession = async () => {\n setLoading(true);\n try {\n if (data.current_session_state == \"opening_control\") {\n await onSetOpeningCashBox(\n Number(money),\n Number(data.current_session_id)\n );\n } else {\n const res = await openSession.mutateAsync(Number(data.record_id));\n const sessionIdNew = Object.keys(Object.fromEntries(res as any));\n await onSetOpeningCashBox(Number(money), Number(sessionIdNew[0]));\n }\n } catch (error) {\n console.error(\"Error opening session:\", error);\n } finally {\n setLoading(false);\n }\n };\n const handleAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n const rawValue = e.target.value.replace(/\\,/g, \"\");\n if (!/^\\d*$/.test(rawValue)) return;\n\n setMoney(rawValue);\n };\n return (\n <ModalZoom isOpen={openModal} onClose={onClose} className=\"\">\n <FormProvider {...methods}>\n <div className=\"flex flex-col gap-6 border-b border-[--stroke-default] w-[500px] p-6 bg-white\">\n <div className=\"p-3 flex gap-5 items-center\">\n <img\n src=\"/assets/images/cashier.svg\"\n alt=\"POS Icon\"\n className=\"size-12\"\n />\n <p className=\"text-base text-[#0E121B] font-semibold\">\n {row[\"name\"]}\n </p>\n </div>\n <div className=\"flex flex-col gap-[6px]\">\n <p className=\"text-sm font-medium\">\n {t(\"starting_cash_float\")}{\" \"}\n <span className=\"text-[--color-error]\">*</span>\n </p>\n\n <input\n type=\"text\"\n value={formatCurrency(money)}\n onChange={handleAmountChange}\n onWheel={(e) => e.currentTarget.blur()}\n className=\"border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-gray-400 text-sm\"\n placeholder=\"0\"\n inputMode=\"numeric\"\n />\n </div>\n {/* <div className=\"flex flex-col gap-[6px]\">\n <p className=\"text-sm font-medium\">Lưu ý</p>\n <TextAreaField\n {...{\n defaultValue: \"\",\n string: \"Lưu ý \",\n readOnly: false,\n methods: methods,\n isForm: true,\n placeholder: \"Lưu ý khi mở ca\",\n name: \"note\",\n }}\n />\n </div> */}\n </div>\n <p className=\"p-4 flex justify-end gap-4 mt-auto\">\n <ButtonAction\n onClick={() => setOpenModal(false)}\n className=\"h-[36px] button-secondary\"\n >\n {t(\"cancel_button\")}\n </ButtonAction>\n <ButtonAction\n disabled={!money || loading}\n onClick={handleOpenSession}\n className=\"h-[36px] button-primary\"\n >\n {t(\"open_session\")}\n </ButtonAction>\n </p>\n </FormProvider>\n </ModalZoom>\n );\n};\n\nexport default OpenSessionModal;\n","import type { FieldElement } from '../types';\n\nexport default (element: FieldElement): element is HTMLInputElement =>\n element.type === 'checkbox';\n","export default (value: unknown): value is Date => value instanceof Date;\n","export default (value: unknown): value is null | undefined => value == null;\n","import isDateObject from './isDateObject';\nimport isNullOrUndefined from './isNullOrUndefined';\n\nexport const isObjectType = (value: unknown): value is object =>\n typeof value === 'object';\n\nexport default <T extends object>(value: unknown): value is T =>\n !isNullOrUndefined(value) &&\n !Array.isArray(value) &&\n isObjectType(value) &&\n !isDateObject(value);\n","import isCheckBoxInput from '../utils/isCheckBoxInput';\nimport isObject from '../utils/isObject';\n\ntype Event = { target: any };\n\nexport default (event: unknown) =>\n isObject(event) && (event as Event).target\n ? isCheckBoxInput((event as Event).target)\n ? (event as Event).target.checked\n : (event as Event).target.value\n : event;\n","export default (name: string) =>\n name.substring(0, name.search(/\\.\\d+(\\.|$)/)) || name;\n","import type { InternalFieldName } from '../types';\n\nimport getNodeParentName from './getNodeParentName';\n\nexport default (names: Set<InternalFieldName>, name: InternalFieldName) =>\n names.has(getNodeParentName(name));\n","import isObject from './isObject';\n\nexport default (tempObject: object) => {\n const prototypeCopy =\n tempObject.constructor && tempObject.constructor.prototype;\n\n return (\n isObject(prototypeCopy) && prototypeCopy.hasOwnProperty('isPrototypeOf')\n );\n};\n","export default typeof window !== 'undefined' &&\n typeof window.HTMLElement !== 'undefined' &&\n typeof document !== 'undefined';\n","import isObject from './isObject';\nimport isPlainObject from './isPlainObject';\nimport isWeb from './isWeb';\n\nexport default function cloneObject<T>(data: T): T {\n let copy: any;\n const isArray = Array.isArray(data);\n const isFileListInstance =\n typeof FileList !== 'undefined' ? data instanceof FileList : false;\n\n if (data instanceof Date) {\n copy = new Date(data);\n } else if (\n !(isWeb && (data instanceof Blob || isFileListInstance)) &&\n (isArray || isObject(data))\n ) {\n copy = isArray ? [] : Object.create(Object.getPrototypeOf(data));\n\n if (!isArray && !isPlainObject(data)) {\n copy = data;\n } else {\n for (const key in data) {\n if (data.hasOwnProperty(key)) {\n copy[key] = cloneObject(data[key]);\n }\n }\n }\n } else {\n return data;\n }\n\n return copy;\n}\n","export default (value: string) => /^\\w*$/.test(value);\n","export default (val: unknown): val is undefined => val === undefined;\n","export default <TValue>(value: TValue[]) =>\n Array.isArray(value) ? value.filter(Boolean) : [];\n","import compact from './compact';\n\nexport default (input: string): string[] =>\n compact(input.replace(/[\"|']|\\]/g, '').split(/\\.|\\[/));\n","import isKey from './isKey';\nimport isNullOrUndefined from './isNullOrUndefined';\nimport isObject from './isObject';\nimport isUndefined from './isUndefined';\nimport stringToPath from './stringToPath';\n\nexport default <T>(\n object: T,\n path?: string | null,\n defaultValue?: unknown,\n): any => {\n if (!path || !isObject(object)) {\n return defaultValue;\n }\n\n const result = (isKey(path) ? [path] : stringToPath(path)).reduce(\n (result, key) =>\n isNullOrUndefined(result) ? result : result[key as keyof T & object],\n object,\n );\n\n return isUndefined(result) || result === object\n ? isUndefined(object[path as keyof T])\n ? defaultValue\n : object[path as keyof T]\n : result;\n};\n","export default (value: unknown): value is boolean => typeof value === 'boolean';\n","import type { FieldPath, FieldValues } from '../types';\n\nimport isKey from './isKey';\nimport isObject from './isObject';\nimport stringToPath from './stringToPath';\n\nexport default (\n object: FieldValues,\n path: FieldPath<FieldValues>,\n value?: unknown,\n) => {\n let index = -1;\n const tempPath = isKey(path) ? [path] : stringToPath(path);\n const length = tempPath.length;\n const lastIndex = length - 1;\n\n while (++index < length) {\n const key = tempPath[index];\n let newValue = value;\n\n if (index !== lastIndex) {\n const objValue = object[key];\n newValue =\n isObject(objValue) || Array.isArray(objValue)\n ? objValue\n : !isNaN(+tempPath[index + 1])\n ? []\n : {};\n }\n\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return;\n }\n\n object[key] = newValue;\n object = object[key];\n }\n};\n","export const EVENTS = {\n BLUR: 'blur',\n FOCUS_OUT: 'focusout',\n CHANGE: 'change',\n} as const;\n\nexport const VALIDATION_MODE = {\n onBlur: 'onBlur',\n onChange: 'onChange',\n onSubmit: 'onSubmit',\n onTouched: 'onTouched',\n all: 'all',\n} as const;\n\nexport const INPUT_VALIDATION_RULES = {\n max: 'max',\n min: 'min',\n maxLength: 'maxLength',\n minLength: 'minLength',\n pattern: 'pattern',\n required: 'required',\n validate: 'validate',\n} as const;\n","import React from 'react';\n\nimport type { FieldValues, FormProviderProps, UseFormReturn } from './types';\n\nconst HookFormContext = React.createContext<UseFormReturn | null>(null);\nHookFormContext.displayName = 'HookFormContext';\n\n/**\n * This custom hook allows you to access the form context. useFormContext is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop. To be used with {@link FormProvider}.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)\n *\n * @returns return all useForm methods\n *\n * @example\n * ```tsx\n * function App() {\n * const methods = useForm();\n * const onSubmit = data => console.log(data);\n *\n * return (\n * <FormProvider {...methods} >\n * <form onSubmit={methods.handleSubmit(onSubmit)}>\n * <NestedInput />\n * <input type=\"submit\" />\n * </form>\n * </FormProvider>\n * );\n * }\n *\n * function NestedInput() {\n * const { register } = useFormContext(); // retrieve all hook methods\n * return <input {...register(\"test\")} />;\n * }\n * ```\n */\nexport const useFormContext = <\n TFieldValues extends FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n>(): UseFormReturn<TFieldValues, TContext, TTransformedValues> =>\n React.useContext(HookFormContext) as UseFormReturn<\n TFieldValues,\n TContext,\n TTransformedValues\n >;\n\n/**\n * A provider component that propagates the `useForm` methods to all children components via [React Context](https://react.dev/reference/react/useContext) API. To be used with {@link useFormContext}.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)\n *\n * @param props - all useForm methods\n *\n * @example\n * ```tsx\n * function App() {\n * const methods = useForm();\n * const onSubmit = data => console.log(data);\n *\n * return (\n * <FormProvider {...methods} >\n * <form onSubmit={methods.handleSubmit(onSubmit)}>\n * <NestedInput />\n * <input type=\"submit\" />\n * </form>\n * </FormProvider>\n * );\n * }\n *\n * function NestedInput() {\n * const { register } = useFormContext(); // retrieve all hook methods\n * return <input {...register(\"test\")} />;\n * }\n * ```\n */\nexport const FormProvider = <\n TFieldValues extends FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n>(\n props: FormProviderProps<TFieldValues, TContext, TTransformedValues>,\n) => {\n const { children, ...data } = props;\n return (\n <HookFormContext.Provider value={data as unknown as UseFormReturn}>\n {children}\n </HookFormContext.Provider>\n );\n};\n","import { VALIDATION_MODE } from '../constants';\nimport type { Control, FieldValues, FormState, ReadFormState } from '../types';\n\nexport default <\n TFieldValues extends FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n>(\n formState: FormState<TFieldValues>,\n control: Control<TFieldValues, TContext, TTransformedValues>,\n localProxyFormState?: ReadFormState,\n isRoot = true,\n) => {\n const result = {\n defaultValues: control._defaultValues,\n } as typeof formState;\n\n for (const key in formState) {\n Object.defineProperty(result, key, {\n get: () => {\n const _key = key as keyof FormState<TFieldValues> & keyof ReadFormState;\n\n if (control._proxyFormState[_key] !== VALIDATION_MODE.all) {\n control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;\n }\n\n localProxyFormState && (localProxyFormState[_key] = true);\n return formState[_key];\n },\n });\n }\n\n return result;\n};\n","import React from 'react';\n\nexport const useIsomorphicLayoutEffect =\n typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\n","import React from 'react';\n\nimport getProxyFormState from './logic/getProxyFormState';\nimport type {\n FieldValues,\n UseFormStateProps,\n UseFormStateReturn,\n} from './types';\nimport { useFormContext } from './useFormContext';\nimport { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect';\n\n/**\n * This custom hook allows you to subscribe to each form state, and isolate the re-render at the custom hook level. It has its scope in terms of form state subscription, so it would not affect other useFormState and useForm. Using this hook can reduce the re-render impact on large and complex form application.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useformstate) • [Demo](https://codesandbox.io/s/useformstate-75xly)\n *\n * @param props - include options on specify fields to subscribe. {@link UseFormStateReturn}\n *\n * @example\n * ```tsx\n * function App() {\n * const { register, handleSubmit, control } = useForm({\n * defaultValues: {\n * firstName: \"firstName\"\n * }});\n * const { dirtyFields } = useFormState({\n * control\n * });\n * const onSubmit = (data) => console.log(data);\n *\n * return (\n * <form onSubmit={handleSubmit(onSubmit)}>\n * <input {...register(\"firstName\")} placeholder=\"First Name\" />\n * {dirtyFields.firstName && <p>Field is dirty.</p>}\n * <input type=\"submit\" />\n * </form>\n * );\n * }\n * ```\n */\nexport function useFormState<\n TFieldValues extends FieldValues = FieldValues,\n TTransformedValues = TFieldValues,\n>(\n props?: UseFormStateProps<TFieldValues, TTransformedValues>,\n): UseFormStateReturn<TFieldValues> {\n const methods = useFormContext<TFieldValues, any, TTransformedValues>();\n const { control = methods.control, disabled, name, exact } = props || {};\n const [formState, updateFormState] = React.useState(control._formState);\n const _localProxyFormState = React.useRef({\n isDirty: false,\n isLoading: false,\n dirtyFields: false,\n touchedFields: false,\n validatingFields: false,\n isValidating: false,\n isValid: false,\n errors: false,\n });\n\n useIsomorphicLayoutEffect(\n () =>\n control._subscribe({\n name,\n formState: _localProxyFormState.current,\n exact,\n callback: (formState) => {\n !disabled &&\n updateFormState({\n ...control._formState,\n ...formState,\n });\n },\n }),\n [name, disabled, exact],\n );\n\n React.useEffect(() => {\n _localProxyFormState.current.isValid && control._setValid(true);\n }, [control]);\n\n return React.useMemo(\n () =>\n getProxyFormState(\n formState,\n control,\n _localProxyFormState.current,\n false,\n ),\n [formState, control],\n );\n}\n","export default (value: unknown): value is string => typeof value === 'string';\n","import type { DeepPartial, FieldValues, Names } from '../types';\nimport get from '../utils/get';\nimport isString from '../utils/isString';\n\nexport default <T>(\n names: string | string[] | undefined,\n _names: Names,\n formValues?: FieldValues,\n isGlobal?: boolean,\n defaultValue?: DeepPartial<T> | unknown,\n) => {\n if (isString(names)) {\n isGlobal && _names.watch.add(names);\n return get(formValues, names, defaultValue);\n }\n\n if (Array.isArray(names)) {\n return names.map(\n (fieldName) => (\n isGlobal && _names.watch.add(fieldName),\n get(formValues, fieldName)\n ),\n );\n }\n\n isGlobal && (_names.watchAll = true);\n\n return formValues;\n};\n","import type { Primitive } from '../types';\n\nimport isNullOrUndefined from './isNullOrUndefined';\nimport { isObjectType } from './isObject';\n\nexport default (value: unknown): value is Primitive =>\n isNullOrUndefined(value) || !isObjectType(value);\n","import isObject from '../utils/isObject';\n\nimport isDateObject from './isDateObject';\nimport isPrimitive from './isPrimitive';\n\nexport default function deepEqual(\n object1: any,\n object2: any,\n _internal_visited = new WeakSet(),\n) {\n if (isPrimitive(object1) || isPrimitive(object2)) {\n return Object.is(object1, object2);\n }\n\n if (isDateObject(object1) && isDateObject(object2)) {\n return object1.getTime() === object2.getTime();\n }\n\n const keys1 = Object.keys(object1);\n const keys2 = Object.keys(object2);\n\n if (keys1.length !== keys2.length) {\n return false;\n }\n\n if (_internal_visited.has(object1) || _internal_visited.has(object2)) {\n return true;\n }\n _internal_visited.add(object1);\n _internal_visited.add(object2);\n\n for (const key of keys1) {\n const val1 = object1[key];\n\n if (!keys2.includes(key)) {\n return false;\n }\n\n if (key !== 'ref') {\n const val2 = object2[key];\n\n if (\n (isDateObject(val1) && isDateObject(val2)) ||\n (isObject(val1) && isObject(val2)) ||\n (Array.isArray(val1) && Array.isArray(val2))\n ? !deepEqual(val1, val2, _internal_visited)\n : !Object.is(val1, val2)\n ) {\n return false;\n }\n }\n }\n\n return true;\n}\n","import React from 'react';\n\nimport generateWatchOutput from './logic/generateWatchOutput';\nimport deepEqual from './utils/deepEqual';\nimport type {\n Control,\n DeepPartialSkipArrayKey,\n FieldPath,\n FieldPathValue,\n FieldPathValues,\n FieldValues,\n InternalFieldName,\n UseWatchProps,\n} from './types';\nimport { useFormContext } from './useFormContext';\nimport { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect';\n\n/**\n * Subscribe to the entire form values change and re-render at the hook level.\n *\n * @remarks\n *\n * [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)\n *\n * @param props - defaultValue, disable subscription and match exact name.\n *\n * @example\n * ```tsx\n * const { control } = useForm();\n * const values = useWatch({\n * control,\n * defaultValue: {\n * name: \"data\"\n * },\n * exact: false,\n * })\n * ```\n */\nexport function useWatch<\n TFieldValues extends FieldValues = FieldValues,\n TTransformedValues = TFieldValues,\n>(props: {\n name?: undefined;\n defaultValue?: DeepPartialSkipArrayKey<TFieldValues>;\n control?: Control<TFieldValues, any, TTransformedValues>;\n disabled?: boolean;\n exact?: boolean;\n compute?: undefined;\n}): DeepPartialSkipArrayKey<TFieldValues>;\n/**\n * Custom hook to subscribe to field change and isolate re-rendering at the component level.\n *\n * @remarks\n *\n * [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)\n *\n * @param props - defaultValue, disable subscription and match exact name.\n *\n * @example\n * ```tsx\n * const { control } = useForm();\n * const values = useWatch({\n * control,\n * name: \"fieldA\",\n * defaultValue: \"default value\",\n * exact: false,\n * })\n * ```\n */\nexport function useWatch<\n TFieldValues extends FieldValues = FieldValues,\n TFieldName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n TTransformedValues = TFieldValues,\n>(props: {\n name: TFieldName;\n defaultValue?: FieldPathValue<TFieldValues, TFieldName>;\n control?: Control<TFieldValues, any, TTransformedValues>;\n disabled?: boolean;\n exact?: boolean;\n compute?: undefined;\n}): FieldPathValue<TFieldValues, TFieldName>;\n/**\n * Custom hook to subscribe to field change and compute function to produce state update\n *\n * @remarks\n *\n * [API](https://react-hook-form.com/docs/usewatch)\n *\n * @param props - defaultValue, disable subscription and match exact name.\n *\n * @example\n * ```tsx\n * const { control } = useForm();\n * const values = useWatch({\n * control,\n * compute: (formValues) => formValues.fieldA\n * })\n * ```\n */\nexport function useWatch<\n TFieldValues extends FieldValues = FieldValues,\n TTransformedValues = TFieldValues,\n TComputeValue = unknown,\n>(props: {\n name?: undefined;\n defaultValue?: DeepPartialSkipArrayKey<TFieldValues>;\n control?: Control<TFieldValues, any, TTransformedValues>;\n disabled?: boolean;\n exact?: boolean;\n compute: (formValues: TFieldValues) => TComputeValue;\n}): TComputeValue;\n/**\n * Custom hook to subscribe to field change and compute function to produce state update\n *\n * @remarks\n *\n * [API](https://react-hook-form.com/docs/usewatch)\n *\n * @param props - defaultValue, disable subscription and match exact name.\n *\n * @example\n * ```tsx\n * const { control } = useForm();\n * const values = useWatch({\n * control,\n * name: \"fieldA\",\n * defaultValue: \"default value\",\n * exact: false,\n * compute: (fieldValue) => fieldValue === \"data\" ? fieldValue : null,\n * })\n * ```\n */\nexport function useWatch<\n TFieldValues extends FieldValues = FieldValues,\n TFieldName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n TTransformedValues = TFieldValues,\n TComputeValue = unknown,\n>(props: {\n name: TFieldName;\n defaultValue?: FieldPathValue<TFieldValues, TFieldName>;\n control?: Control<TFieldValues, any, TTransformedValues>;\n disabled?: boolean;\n exact?: boolean;\n compute: (\n fieldValue: FieldPathValue<TFieldValues, TFieldName>,\n ) => TComputeValue;\n}): TComputeValue;\n/**\n * Custom hook to subscribe to field change and isolate re-rendering at the component level.\n *\n * @remarks\n *\n * [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)\n *\n * @param props - defaultValue, disable subscription and match exact name.\n *\n * @example\n * ```tsx\n * const { control } = useForm();\n * const values = useWatch({\n * control,\n * name: [\"fieldA\", \"fieldB\"],\n * defaultValue: {\n * fieldA: \"data\",\n * fieldB: \"data\"\n * },\n * exact: false,\n * })\n * ```\n */\nexport function useWatch<\n TFieldValues extends FieldValues = FieldValues,\n TFieldNames extends\n readonly FieldPath<TFieldValues>[] = readonly FieldPath<TFieldValues>[],\n TTransformedValues = TFieldValues,\n>(props: {\n name: readonly [...TFieldNames];\n defaultValue?: DeepPartialSkipArrayKey<TFieldValues>;\n control?: Control<TFieldValues, any, TTransformedValues>;\n disabled?: boolean;\n exact?: boolean;\n compute?: undefined;\n}): FieldPathValues<TFieldValues, TFieldNames>;\n/**\n * Custom hook to subscribe to field change and compute function to produce state update\n *\n * @remarks\n *\n * [API](https://react-hook-form.com/docs/usewatch)\n *\n * @param props - defaultValue, disable subscription and match exact name.\n *\n * @example\n * ```tsx\n * const { control } = useForm();\n * const values = useWatch({\n * control,\n * name: [\"fieldA\", \"fieldB\"],\n * defaultValue: {\n * fieldA: \"data\",\n * fieldB: 0\n * },\n * compute: ([fieldAValue, fieldBValue]) => fieldB === 2 ? fieldA : null,\n * exact: false,\n * })\n * ```\n */\nexport function useWatch<\n TFieldValues extends FieldValues = FieldValues,\n TFieldNames extends\n readonly FieldPath<TFieldValues>[] = readonly FieldPath<TFieldValues>[],\n TTransformedValues = TFieldValues,\n TComputeValue = unknown,\n>(props: {\n name: readonly [...TFieldNames];\n defaultValue?: DeepPartialSkipArrayKey<TFieldValues>;\n control?: Control<TFieldValues, any, TTransformedValues>;\n disabled?: boolean;\n exact?: boolean;\n compute: (\n fieldValue: FieldPathValues<TFieldValues, TFieldNames>,\n ) => TComputeValue;\n}): TComputeValue;\n/**\n * Custom hook to subscribe to field change and isolate re-rendering at the component level.\n *\n * @remarks\n *\n * [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)\n *\n * @example\n * ```tsx\n * // can skip passing down the control into useWatch if the form is wrapped with the FormProvider\n * const values = useWatch()\n * ```\n */\nexport function useWatch<\n TFieldValues extends FieldValues = FieldValues,\n>(): DeepPartialSkipArrayKey<TFieldValues>;\n/**\n * Custom hook to subscribe to field change and isolate re-rendering at the component level.\n *\n * @remarks\n *\n * [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)\n *\n * @example\n * ```tsx\n * const { control } = useForm();\n * const values = useWatch({\n * name: \"fieldName\"\n * control,\n * })\n * ```\n */\nexport function useWatch<TFieldValues extends FieldValues>(\n props?: UseWatchProps<TFieldValues>,\n) {\n const methods = useFormContext<TFieldValues>();\n const {\n control = methods.control,\n name,\n defaultValue,\n disabled,\n exact,\n compute,\n } = props || {};\n const _defaultValue = React.useRef(defaultValue);\n const _compute = React.useRef(compute);\n const _computeFormValues = React.useRef(undefined);\n\n const _prevControl = React.useRef(control);\n const _prevName = React.useRef(name);\n\n _compute.current = compute;\n\n const [value, updateValue] = React.useState(() => {\n const defaultValue = control._getWatch(\n name as InternalFieldName,\n _defaultValue.current as DeepPartialSkipArrayKey<TFieldValues>,\n );\n\n return _compute.current ? _compute.current(defaultValue) : defaultValue;\n });\n\n const getCurrentOutput = React.useCallback(\n (values?: TFieldValues) => {\n const formValues = generateWatchOutput(\n name as InternalFieldName | InternalFieldName[],\n control._names,\n values || control._formValues,\n false,\n _defaultValue.current,\n );\n\n return _compute.current ? _compute.current(formValues) : formValues;\n },\n [control._formValues, control._names, name],\n );\n\n const refreshValue = React.useCallback(\n (values?: TFieldValues) => {\n if (!disabled) {\n const formValues = generateWatchOutput(\n name as InternalFieldName | InternalFieldName[],\n control._names,\n values || control._formValues,\n false,\n _defaultValue.current,\n );\n\n if (_compute.current) {\n const computedFormValues = _compute.current(formValues);\n\n if (!deepEqual(computedFormValues, _computeFormValues.current)) {\n updateValue(computedFormValues);\n _computeFormValues.current = computedFormValues;\n }\n } else {\n updateValue(formValues);\n }\n }\n },\n [control._formValues, control._names, disabled, name],\n );\n\n useIsomorphicLayoutEffect(() => {\n if (\n _prevControl.current !== control ||\n !deepEqual(_prevName.current, name)\n ) {\n _prevControl.current = control;\n _prevName.current = name;\n refreshValue();\n }\n\n return control._subscribe({\n name,\n formState: {\n values: true,\n },\n exact,\n callback: (formState) => {\n refreshValue(formState.values);\n },\n });\n }, [control, exact, name, refreshValue]);\n\n React.useEffect(() => control._removeUnmounted());\n\n // If name or control changed for this render, synchronously reflect the\n // latest value so callers (like useController) see the correct value\n // immediately on the same render.\n\n // Optimize: Check control reference first before expensive deepEqual\n const controlChanged = _prevControl.current !== control;\n const prevName = _prevName.current;\n\n // Cache the computed output to avoid duplicate calls within the same render\n // We include shouldReturnImmediate in deps to ensure proper recomputation\n const computedOutput = React.useMemo(() => {\n if (disabled) {\n return null;\n }\n\n const nameChanged = !controlChanged && !deepEqual(prevName, name);\n const shouldReturnImmediate = controlChanged || nameChanged;\n\n return shouldReturnImmediate ? getCurrentOutput() : null;\n }, [disabled, controlChanged, name, prevName, getCurrentOutput]);\n\n return computedOutput !== null ? computedOutput : value;\n}\n","import React from 'react';\n\nimport getEventValue from './logic/getEventValue';\nimport isNameInFieldArray from './logic/isNameInFieldArray';\nimport cloneObject from './utils/cloneObject';\nimport get from './utils/get';\nimport isBoolean from './utils/isBoolean';\nimport isUndefined from './utils/isUndefined';\nimport set from './utils/set';\nimport { EVENTS } from './constants';\nimport type {\n ControllerFieldState,\n Field,\n FieldPath,\n FieldPathValue,\n FieldValues,\n InternalFieldName,\n UseControllerProps,\n UseControllerReturn,\n} from './types';\nimport { useFormContext } from './useFormContext';\nimport { useFormState } from './useFormState';\nimport { useWatch } from './useWatch';\n\n/**\n * Custom hook to work with controlled component, this function provide you with both form and field level state. Re-render is isolated at the hook level.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/usecontroller) • [Demo](https://codesandbox.io/s/usecontroller-0o8px)\n *\n * @param props - the path name to the form field value, and validation rules.\n *\n * @returns field properties, field and form state. {@link UseControllerReturn}\n *\n * @example\n * ```tsx\n * function Input(props) {\n * const { field, fieldState, formState } = useController(props);\n * return (\n * <div>\n * <input {...field} placeholder={props.name} />\n * <p>{fieldState.isTouched && \"Touched\"}</p>\n * <p>{formState.isSubmitted ? \"submitted\" : \"\"}</p>\n * </div>\n * );\n * }\n * ```\n */\nexport function useController<\n TFieldValues extends FieldValues = FieldValues,\n TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n TTransformedValues = TFieldValues,\n>(\n props: UseControllerProps<TFieldValues, TName, TTransformedValues>,\n): UseControllerReturn<TFieldValues, TName> {\n const methods = useFormContext<TFieldValues, any, TTransformedValues>();\n const {\n name,\n disabled,\n control = methods.control,\n shouldUnregister,\n defaultValue,\n } = props;\n const isArrayField = isNameInFieldArray(control._names.array, name);\n\n const defaultValueMemo = React.useMemo(\n () =>\n get(\n control._formValues,\n name,\n get(control._defaultValues, name, defaultValue),\n ),\n [control, name, defaultValue],\n );\n\n const value = useWatch({\n control,\n name,\n defaultValue: defaultValueMemo,\n exact: true,\n }) as FieldPathValue<TFieldValues, TName>;\n\n const formState = useFormState({\n control,\n name,\n exact: true,\n });\n\n const _props = React.useRef(props);\n\n const _previousNameRef = React.useRef<string | undefined>(undefined);\n\n const _registerProps = React.useRef(\n control.register(name, {\n ...props.rules,\n value,\n ...(isBoolean(props.disabled) ? { disabled: props.disabled } : {}),\n }),\n );\n\n _props.current = props;\n\n const fieldState = React.useMemo(\n () =>\n Object.defineProperties(\n {},\n {\n invalid: {\n enumerable: true,\n get: () => !!get(formState.errors, name),\n },\n isDirty: {\n enumerable: true,\n get: () => !!get(formState.dirtyFields, name),\n },\n isTouched: {\n enumerable: true,\n get: () => !!get(formState.touchedFields, name),\n },\n isValidating: {\n enumerable: true,\n get: () => !!get(formState.validatingFields, name),\n },\n error: {\n enumerable: true,\n get: () => get(formState.errors, name),\n },\n },\n ) as ControllerFieldState,\n [formState, name],\n );\n\n const onChange = React.useCallback(\n (event: any) =>\n _registerProps.current.onChange({\n target: {\n value: getEventValue(event),\n name: name as InternalFieldName,\n },\n type: EVENTS.CHANGE,\n }),\n [name],\n );\n\n const onBlur = React.useCallback(\n () =>\n _registerProps.current.onBlur({\n target: {\n value: get(control._formValues, name),\n name: name as InternalFieldName,\n },\n type: EVENTS.BLUR,\n }),\n [name, control._formValues],\n );\n\n const ref = React.useCallback(\n (elm: any) => {\n const field = get(control._fields, name);\n\n if (field && elm) {\n field._f.ref = {\n focus: () => elm.focus && elm.focus(),\n select: () => elm.select && elm.select(),\n setCustomValidity: (message: string) =>\n elm.setCustomValidity(message),\n reportValidity: () => elm.reportValidity(),\n };\n }\n },\n [control._fields, name],\n );\n\n const field = React.useMemo(\n () => ({\n name,\n value,\n ...(isBoolean(disabled) || formState.disabled\n ? { disabled: formState.disabled || disabled }\n : {}),\n onChange,\n onBlur,\n ref,\n }),\n [name, disabled, formState.disabled, onChange, onBlur, ref, value],\n );\n\n React.useEffect(() => {\n const _shouldUnregisterField =\n control._options.shouldUnregister || shouldUnregister;\n const previousName = _previousNameRef.current;\n\n if (previousName && previousName !== name && !isArrayField) {\n control.unregister(previousName as FieldPath<TFieldValues>);\n }\n\n control.register(name, {\n ..._props.current.rules,\n ...(isBoolean(_props.current.disabled)\n ? { disabled: _props.current.disabled }\n : {}),\n });\n\n const updateMounted = (name: InternalFieldName, value: boolean) => {\n const field: Field = get(control._fields, name);\n\n if (field && field._f) {\n field._f.mount = value;\n }\n };\n\n updateMounted(name, true);\n\n if (_shouldUnregisterField) {\n const value = cloneObject(\n get(control._options.defaultValues, name, _props.current.defaultValue),\n );\n set(control._defaultValues, name, value);\n if (isUndefined(get(control._formValues, name))) {\n set(control._formValues, name, value);\n }\n }\n\n !isArrayField && control.register(name);\n\n _previousNameRef.current = name;\n\n return () => {\n (\n isArrayField\n ? _shouldUnregisterField && !control._state.action\n : _shouldUnregisterField\n )\n ? control.unregister(name)\n : updateMounted(name, false);\n };\n }, [name, control, isArrayField, shouldUnregister]);\n\n React.useEffect(() => {\n control._setDisabledField({\n disabled,\n name,\n });\n }, [disabled, name, control]);\n\n return React.useMemo(\n () => ({\n field,\n formState,\n fieldState,\n }),\n [field, formState, fieldState],\n );\n}\n","import type { ControllerProps, FieldPath, FieldValues } from './types';\nimport { useController } from './useController';\n\n/**\n * Component based on `useController` hook to work with controlled component.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/usecontroller/controller) • [Demo](https://codesandbox.io/s/react-hook-form-v6-controller-ts-jwyzw) • [Video](https://www.youtube.com/watch?v=N2UNk_UCVyA)\n *\n * @param props - the path name to the form field value, and validation rules.\n *\n * @returns provide field handler functions, field and form state.\n *\n * @example\n * ```tsx\n * function App() {\n * const { control } = useForm<FormValues>({\n * defaultValues: {\n * test: \"\"\n * }\n * });\n *\n * return (\n * <form>\n * <Controller\n * control={control}\n * name=\"test\"\n * render={({ field: { onChange, onBlur, value, ref }, formState, fieldState }) => (\n * <>\n * <input\n * onChange={onChange} // send value to hook form\n * onBlur={onBlur} // notify when input is touched\n * value={value} // return updated value\n * ref={ref} // set ref for focus management\n * />\n * <p>{formState.isSubmitted ? \"submitted\" : \"\"}</p>\n * <p>{fieldState.isTouched ? \"touched\" : \"\"}</p>\n * </>\n * )}\n * />\n * </form>\n * );\n * }\n * ```\n */\nconst Controller = <\n TFieldValues extends FieldValues = FieldValues,\n TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n TTransformedValues = TFieldValues,\n>(\n props: ControllerProps<TFieldValues, TName, TTransformedValues>,\n) =>\n props.render(useController<TFieldValues, TName, TTransformedValues>(props));\n\nexport { Controller };\n","import type { FieldValues } from '../types';\n\nimport { isObjectType } from './isObject';\n\nexport const flatten = (obj: FieldValues) => {\n const output: FieldValues = {};\n\n for (const key of Object.keys(obj)) {\n if (isObjectType(obj[key]) && obj[key] !== null) {\n const nested = flatten(obj[key]);\n\n for (const nestedKey of Object.keys(nested)) {\n output[`${key}.${nestedKey}`] = nested[nestedKey];\n }\n } else {\n output[key] = obj[key];\n }\n }\n\n return output;\n};\n","import React from 'react';\n\nimport { flatten } from './utils/flatten';\nimport type { FieldValues, FormProps } from './types';\nimport { useFormContext } from './useFormContext';\n\nconst POST_REQUEST = 'post';\n\n/**\n * Form component to manage submission.\n *\n * @param props - to setup submission detail. {@link FormProps}\n *\n * @returns form component or headless render prop.\n *\n * @example\n * ```tsx\n * function App() {\n * const { control, formState: { errors } } = useForm();\n *\n * return (\n * <Form action=\"/api\" control={control}>\n * <input {...register(\"name\")} />\n * <p>{errors?.root?.server && 'Server error'}</p>\n * <button>Submit</button>\n * </Form>\n * );\n * }\n * ```\n */\nfunction Form<\n TFieldValues extends FieldValues,\n TTransformedValues = TFieldValues,\n>(props: FormProps<TFieldValues, TTransformedValues>) {\n const methods = useFormContext<TFieldValues, any, TTransformedValues>();\n const [mounted, setMounted] = React.useState(false);\n const {\n control = methods.control,\n onSubmit,\n children,\n action,\n method = POST_REQUEST,\n headers,\n encType,\n onError,\n render,\n onSuccess,\n validateStatus,\n ...rest\n } = props;\n\n const submit = async (event?: React.BaseSyntheticEvent) => {\n let hasError = false;\n let type = '';\n\n await control.handleSubmit(async (data) => {\n const formData = new FormData();\n let formDataJson = '';\n\n try {\n formDataJson = JSON.stringify(data);\n } catch {}\n\n const flattenFormValues = flatten(control._formValues);\n\n for (const key in flattenFormValues) {\n formData.append(key, flattenFormValues[key]);\n }\n\n if (onSubmit) {\n await onSubmit({\n data,\n event,\n method,\n formData,\n formDataJson,\n });\n }\n\n if (action) {\n try {\n const shouldStringifySubmissionData = [\n headers && headers['Content-Type'],\n encType,\n ].some((value) => value && value.includes('json'));\n\n const response = await fetch(String(action), {\n method,\n headers: {\n ...headers,\n ...(encType && encType !== 'multipart/form-data'\n ? { 'Content-Type': encType }\n : {}),\n },\n body: shouldStringifySubmissionData ? formDataJson : formData,\n });\n\n if (\n response &&\n (validateStatus\n ? !validateStatus(response.status)\n : response.status < 200 || response.status >= 300)\n ) {\n hasError = true;\n onError && onError({ response });\n type = String(response.status);\n } else {\n onSuccess && onSuccess({ response });\n }\n } catch (error: unknown) {\n hasError = true;\n onError && onError({ error });\n }\n }\n })(event);\n\n if (hasError && props.control) {\n props.control._subjects.state.next({\n isSubmitSuccessful: false,\n });\n props.control.setError('root.server', {\n type,\n });\n }\n };\n\n React.useEffect(() => {\n setMounted(true);\n }, []);\n\n return render ? (\n <>\n {render({\n submit,\n })}\n </>\n ) : (\n <form\n noValidate={mounted}\n action={action}\n method={method}\n encType={encType}\n onSubmit={submit}\n {...rest}\n >\n {children}\n </form>\n );\n}\n\nexport { Form };\n","import type {\n InternalFieldErrors,\n InternalFieldName,\n ValidateResult,\n} from '../types';\n\nexport default (\n name: InternalFieldName,\n validateAllFieldCriteria: boolean,\n errors: InternalFieldErrors,\n type: string,\n message: ValidateResult,\n) =>\n validateAllFieldCriteria\n ? {\n ...errors[name],\n types: {\n ...(errors[name] && errors[name]!.types ? errors[name]!.types : {}),\n [type]: message || true,\n },\n }\n : {};\n","export default <T>(value: T) => (Array.isArray(value) ? value : [value]);\n","import type { Noop } from '../types';\n\nexport type Observer<T> = {\n next: (value: T) => void;\n};\n\nexport type Subscription = {\n unsubscribe: Noop;\n};\n\nexport type Subject<T> = {\n readonly observers: Observer<T>[];\n subscribe: (value: Observer<T>) => Subscription;\n unsubscribe: Noop;\n} & Observer<T>;\n\nexport default <T>(): Subject<T> => {\n let _observers: Observer<T>[] = [];\n\n const next = (value: T) => {\n for (const observer of _observers) {\n observer.next && observer.next(value);\n }\n };\n\n const subscribe = (observer: Observer<T>): Subscription => {\n _observers.push(observer);\n return {\n unsubscribe: () => {\n _observers = _observers.filter((o) => o !== observer);\n },\n };\n };\n\n const unsubscribe = () => {\n _observers = [];\n };\n\n return {\n get observers() {\n return _observers;\n },\n next,\n subscribe,\n unsubscribe,\n };\n};\n","import isObject from './isObject';\n\nexport default function extractFormValues<\n T extends object,\n K extends Record<string, unknown>,\n>(fieldsState: T, formValues: K) {\n const values: Record<string, unknown> = {};\n\n for (const key in fieldsState) {\n if (fieldsState.hasOwnProperty(key)) {\n const fieldState = fieldsState[key];\n const fieldValue = formValues[key];\n\n if (fieldState && isObject(fieldState) && fieldValue) {\n const nestedFieldsState = extractFormValues(\n fieldState,\n fieldValue as K,\n );\n\n if (isObject(nestedFieldsState)) {\n values[key] = nestedFieldsState;\n }\n } else if (fieldsState[key]) {\n values[key] = fieldValue;\n }\n }\n }\n\n return values;\n}\n","import type { EmptyObject } from '../types';\n\nimport isObject from './isObject';\n\nexport default (value: unknown): value is EmptyObject =>\n isObject(value) && !Object.keys(value).length;\n","import type { FieldElement } from '../types';\n\nexport default (element: FieldElement): element is HTMLInputElement =>\n element.type === 'file';\n","export default (value: unknown): value is Function =>\n typeof value === 'function';\n","import isWeb from './isWeb';\n\nexport default (value: unknown): value is HTMLElement => {\n if (!isWeb) {\n return false;\n }\n\n const owner = value ? ((value as HTMLElement).ownerDocument as Document) : 0;\n return (\n value instanceof\n (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement)\n );\n};\n","import type { FieldElement } from '../types';\n\nexport default (element: FieldElement): element is HTMLSelectElement =>\n element.type === `select-multiple`;\n","import type { FieldElement } from '../types';\n\nexport default (element: FieldElement): element is HTMLInputElement =>\n element.type === 'radio';\n","import type { FieldElement } from '../types';\n\nimport isCheckBoxInput from './isCheckBoxInput';\nimport isRadioInput from './isRadioInput';\n\nexport default (ref: FieldElement): ref is HTMLInputElement =>\n isRadioInput(ref) || isCheckBoxInput(ref);\n","import type { Ref } from '../types';\n\nimport isHTMLElement from './isHTMLElement';\n\nexport default (ref: Ref) => isHTMLElement(ref) && ref.isConnected;\n","import isEmptyObject from './isEmptyObject';\nimport isKey from './isKey';\nimport isObject from './isObject';\nimport isUndefined from './isUndefined';\nimport stringToPath from './stringToPath';\n\nfunction baseGet(object: any, updatePath: (string | number)[]) {\n const length = updatePath.slice(0, -1).length;\n let index = 0;\n\n while (index < length) {\n object = isUndefined(object) ? index++ : object[updatePath[index++]];\n }\n\n return object;\n}\n\nfunction isEmptyArray(obj: unknown[]) {\n for (const key in obj) {\n if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) {\n return false;\n }\n }\n return true;\n}\n\nexport default function unset(object: any, path: string | (string | number)[]) {\n const paths = Array.isArray(path)\n ? path\n : isKey(path)\n ? [path]\n : stringToPath(path);\n\n const childObject = paths.length === 1 ? object : baseGet(object, paths);\n\n const index = paths.length - 1;\n const key = paths[index];\n\n if (childObject) {\n delete childObject[key];\n }\n\n if (\n index !== 0 &&\n ((isObject(childObject) && isEmptyObject(childObject)) ||\n (Array.isArray(childObject) && isEmptyArray(childObject)))\n ) {\n unset(object, paths.slice(0, -1));\n }\n\n return object;\n}\n","import isFunction from './isFunction';\n\nexport default <T>(data: T): boolean => {\n for (const key in data) {\n if (isFunction(data[key])) {\n return true;\n }\n }\n return false;\n};\n","import deepEqual from '../utils/deepEqual';\nimport isNullOrUndefined from '../utils/isNullOrUndefined';\nimport isObject from '../utils/isObject';\nimport isPrimitive from '../utils/isPrimitive';\nimport isUndefined from '../utils/isUndefined';\nimport objectHasFunction from '../utils/objectHasFunction';\n\nfunction isTraversable(value: any): boolean {\n return Array.isArray(value) || (isObject(value) && !objectHasFunction(value));\n}\n\nfunction markFieldsDirty<T>(data: T, fields: Record<string, any> = {}) {\n for (const key in data) {\n const value = data[key];\n\n if (isTraversable(value)) {\n fields[key] = Array.isArray(value) ? [] : {};\n markFieldsDirty(value, fields[key]);\n } else if (!isUndefined(value)) {\n fields[key] = true;\n }\n }\n\n return fields;\n}\n\nexport default function getDirtyFields<T>(\n data: T,\n formValues: T,\n dirtyFieldsFromValues?: Record<\n Extract<keyof T, string>,\n ReturnType<typeof markFieldsDirty> | boolean\n >,\n) {\n if (!dirtyFieldsFromValues) {\n dirtyFieldsFromValues = markFieldsDirty(formValues);\n }\n\n for (const key in data) {\n const value = data[key];\n\n if (isTraversable(value)) {\n if (isUndefined(formValues) || isPrimitive(dirtyFieldsFromValues[key])) {\n dirtyFieldsFromValues[key] = markFieldsDirty(\n value,\n Array.isArray(value) ? [] : {},\n );\n } else {\n getDirtyFields(\n value,\n isNullOrUndefined(formValues) ? {} : formValues[key],\n dirtyFieldsFromValues[key],\n );\n }\n } else {\n const formValue = formValues[key];\n dirtyFieldsFromValues[key] = !deepEqual(value, formValue);\n }\n }\n\n return dirtyFieldsFromValues;\n}\n","import isUndefined from '../utils/isUndefined';\n\ntype CheckboxFieldResult = {\n isValid: boolean;\n value: string | string[] | boolean | undefined;\n};\n\nconst defaultResult: CheckboxFieldResult = {\n value: false,\n isValid: false,\n};\n\nconst validResult = { value: true, isValid: true };\n\nexport default (options?: HTMLInputElement[]): CheckboxFieldResult => {\n if (Array.isArray(options)) {\n if (options.length > 1) {\n const values = options\n .filter((option) => option && option.checked && !option.disabled)\n .map((option) => option.value);\n return { value: values, isValid: !!values.length };\n }\n\n return options[0].checked && !options[0].disabled\n ? // @ts-expect-error expected to work in the browser\n options[0].attributes && !isUndefined(options[0].attributes.value)\n ? isUndefined(options[0].value) || options[0].value === ''\n ? validResult\n : { value: options[0].value, isValid: true }\n : validResult\n : defaultResult;\n }\n\n return defaultResult;\n};\n","import type { Field, NativeFieldValue } from '../types';\nimport isString from '../utils/isString';\nimport isUndefined from '../utils/isUndefined';\n\nexport default <T extends NativeFieldValue>(\n value: T,\n { valueAsNumber, valueAsDate, setValueAs }: Field['_f'],\n) =>\n isUndefined(value)\n ? value\n : valueAsNumber\n ? value === ''\n ? NaN\n : value\n ? +value\n : value\n : valueAsDate && isString(value)\n ? new Date(value)\n : setValueAs\n ? setValueAs(value)\n : value;\n","type RadioFieldResult = {\n isValid: boolean;\n value: number | string | null;\n};\n\nconst defaultReturn: RadioFieldResult = {\n isValid: false,\n value: null,\n};\n\nexport default (options?: HTMLInputElement[]): RadioFieldResult =>\n Array.isArray(options)\n ? options.reduce(\n (previous, option): RadioFieldResult =>\n option && option.checked && !option.disabled\n ? {\n isValid: true,\n value: option.value,\n }\n : previous,\n defaultReturn,\n )\n : defaultReturn;\n","import type { Field } from '../types';\nimport isCheckBox from '../utils/isCheckBoxInput';\nimport isFileInput from '../utils/isFileInput';\nimport isMultipleSelect from '../utils/isMultipleSelect';\nimport isRadioInput from '../utils/isRadioInput';\nimport isUndefined from '../utils/isUndefined';\n\nimport getCheckboxValue from './getCheckboxValue';\nimport getFieldValueAs from './getFieldValueAs';\nimport getRadioValue from './getRadioValue';\n\nexport default function getFieldValue(_f: Field['_f']) {\n const ref = _f.ref;\n\n if (isFileInput(ref)) {\n return ref.files;\n }\n\n if (isRadioInput(ref)) {\n return getRadioValue(_f.refs).value;\n }\n\n if (isMultipleSelect(ref)) {\n return [...ref.selectedOptions].map(({ value }) => value);\n }\n\n if (isCheckBox(ref)) {\n return getCheckboxValue(_f.refs).value;\n }\n\n return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);\n}\n","import type {\n CriteriaMode,\n Field,\n FieldName,\n FieldRefs,\n FieldValues,\n InternalFieldName,\n} from '../types';\nimport { get } from '../utils';\nimport set from '../utils/set';\n\nexport default <TFieldValues extends FieldValues>(\n fieldsNames: Set<InternalFieldName> | InternalFieldName[],\n _fields: FieldRefs,\n criteriaMode?: CriteriaMode,\n shouldUseNativeValidation?: boolean | undefined,\n) => {\n const fields: Record<InternalFieldName, Field['_f']> = {};\n\n for (const name of fieldsNames) {\n const field: Field = get(_fields, name);\n\n field && set(fields, name, field._f);\n }\n\n return {\n criteriaMode,\n names: [...fieldsNames] as FieldName<TFieldValues>[],\n fields,\n shouldUseNativeValidation,\n };\n};\n","export default (value: unknown): value is RegExp => value instanceof RegExp;\n","import type {\n ValidationRule,\n ValidationValue,\n ValidationValueMessage,\n} from '../types';\nimport isObject from '../utils/isObject';\nimport isRegex from '../utils/isRegex';\nimport isUndefined from '../utils/isUndefined';\n\nexport default <T extends ValidationValue>(\n rule?: ValidationRule<T> | ValidationValueMessage<T>,\n) =>\n isUndefined(rule)\n ? rule\n : isRegex(rule)\n ? rule.source\n : isObject(rule)\n ? isRegex(rule.value)\n ? rule.value.source\n : rule.value\n : rule;\n","import { VALIDATION_MODE } from '../constants';\nimport type { Mode, ValidationModeFlags } from '../types';\n\nexport default (mode?: Mode): ValidationModeFlags => ({\n isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,\n isOnBlur: mode === VALIDATION_MODE.onBlur,\n isOnChange: mode === VALIDATION_MODE.onChange,\n isOnAll: mode === VALIDATION_MODE.all,\n isOnTouch: mode === VALIDATION_MODE.onTouched,\n});\n","import type { Field, Validate } from '../types';\nimport isFunction from '../utils/isFunction';\nimport isObject from '../utils/isObject';\n\nconst ASYNC_FUNCTION = 'AsyncFunction';\n\nexport default (fieldReference: Field['_f']) =>\n !!fieldReference &&\n !!fieldReference.validate &&\n !!(\n (isFunction(fieldReference.validate) &&\n fieldReference.validate.constructor.name === ASYNC_FUNCTION) ||\n (isObject(fieldReference.validate) &&\n Object.values(fieldReference.validate).find(\n (validateFunction: Validate<unknown, unknown>) =>\n validateFunction.constructor.name === ASYNC_FUNCTION,\n ))\n );\n","import type { Field } from '../types';\n\nexport default (options: Field['_f']) =>\n options.mount &&\n (options.required ||\n options.min ||\n options.max ||\n options.maxLength ||\n options.minLength ||\n options.pattern ||\n options.validate);\n","import type { InternalFieldName, Names } from '../types';\n\nexport default (\n name: InternalFieldName,\n _names: Names,\n isBlurEvent?: boolean,\n) =>\n !isBlurEvent &&\n (_names.watchAll ||\n _names.watch.has(name) ||\n [..._names.watch].some(\n (watchName) =>\n name.startsWith(watchName) &&\n /^\\.\\w+/.test(name.slice(watchName.length)),\n ));\n","import type { FieldRefs, InternalFieldName, Ref } from '../types';\nimport { get } from '../utils';\nimport isObject from '../utils/isObject';\n\nconst iterateFieldsByAction = (\n fields: FieldRefs,\n action: (ref: Ref, name: string) => 1 | undefined | void,\n fieldsNames?: Set<InternalFieldName> | InternalFieldName[] | 0,\n abortEarly?: boolean,\n) => {\n for (const key of fieldsNames || Object.keys(fields)) {\n const field = get(fields, key);\n\n if (field) {\n const { _f, ...currentField } = field;\n\n if (_f) {\n if (_f.refs && _f.refs[0] && action(_f.refs[0], key) && !abortEarly) {\n return true;\n } else if (_f.ref && action(_f.ref, _f.name) && !abortEarly) {\n return true;\n } else {\n if (iterateFieldsByAction(currentField, action)) {\n break;\n }\n }\n } else if (isObject(currentField)) {\n if (iterateFieldsByAction(currentField as FieldRefs, action)) {\n break;\n }\n }\n }\n }\n return;\n};\nexport default iterateFieldsByAction;\n","import type { FieldError, FieldErrors, FieldValues } from '../types';\nimport get from '../utils/get';\nimport isKey from '../utils/isKey';\n\nexport default function schemaErrorLookup<T extends FieldValues = FieldValues>(\n errors: FieldErrors<T>,\n _fields: FieldValues,\n name: string,\n): {\n error?: FieldError;\n name: string;\n} {\n const error = get(errors, name);\n\n if (error || isKey(name)) {\n return {\n error,\n name,\n };\n }\n\n const names = name.split('.');\n\n while (names.length) {\n const fieldName = names.join('.');\n const field = get(_fields, fieldName);\n const foundError = get(errors, fieldName);\n\n if (field && !Array.isArray(field) && name !== fieldName) {\n return { name };\n }\n\n if (foundError && foundError.type) {\n return {\n name: fieldName,\n error: foundError,\n };\n }\n\n if (foundError && foundError.root && foundError.root.type) {\n return {\n name: `${fieldName}.root`,\n error: foundError.root,\n };\n }\n\n names.pop();\n }\n\n return {\n name,\n };\n}\n","import { VALIDATION_MODE } from '../constants';\nimport type {\n FieldValues,\n FormState,\n InternalFieldName,\n ReadFormState,\n} from '../types';\nimport isEmptyObject from '../utils/isEmptyObject';\n\nexport default <T extends FieldValues, K extends ReadFormState>(\n formStateData: Partial<FormState<T>> & {\n name?: InternalFieldName;\n values?: T;\n },\n _proxyFormState: K,\n updateFormState: (formState: Partial<FormState<T>>) => void,\n isRoot?: boolean,\n) => {\n updateFormState(formStateData);\n const { name, ...formState } = formStateData;\n\n return (\n isEmptyObject(formState) ||\n Object.keys(formState).length >= Object.keys(_proxyFormState).length ||\n Object.keys(formState).find(\n (key) =>\n _proxyFormState[key as keyof ReadFormState] ===\n (!isRoot || VALIDATION_MODE.all),\n )\n );\n};\n","import convertToArrayPayload from '../utils/convertToArrayPayload';\n\nexport default <T extends string | readonly string[] | undefined>(\n name?: T,\n signalName?: string,\n exact?: boolean,\n) =>\n !name ||\n !signalName ||\n name === signalName ||\n convertToArrayPayload(name).some(\n (currentName) =>\n currentName &&\n (exact\n ? currentName === signalName\n : currentName.startsWith(signalName) ||\n signalName.startsWith(currentName)),\n );\n","import type { ValidationModeFlags } from '../types';\n\nexport default (\n isBlurEvent: boolean,\n isTouched: boolean,\n isSubmitted: boolean,\n reValidateMode: {\n isOnBlur: boolean;\n isOnChange: boolean;\n },\n mode: Partial<ValidationModeFlags>,\n) => {\n if (mode.isOnAll) {\n return false;\n } else if (!isSubmitted && mode.isOnTouch) {\n return !(isTouched || isBlurEvent);\n } else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) {\n return !isBlurEvent;\n } else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) {\n return isBlurEvent;\n }\n return true;\n};\n","import compact from '../utils/compact';\nimport get from '../utils/get';\nimport unset from '../utils/unset';\n\nexport default <T>(ref: T, name: string) =>\n !compact(get(ref, name)).length && unset(ref, name);\n","import type {\n FieldError,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n} from '../types';\nimport convertToArrayPayload from '../utils/convertToArrayPayload';\nimport get from '../utils/get';\nimport set from '../utils/set';\n\nexport default <T extends FieldValues = FieldValues>(\n errors: FieldErrors<T>,\n error: Partial<Record<string, FieldError>>,\n name: InternalFieldName,\n): FieldErrors<T> => {\n const fieldArrayErrors = convertToArrayPayload(get(errors, name));\n set(fieldArrayErrors, 'root', error[name]);\n set(errors, name, fieldArrayErrors);\n return errors;\n};\n","import type { FieldError, Ref, ValidateResult } from '../types';\nimport isBoolean from '../utils/isBoolean';\nimport isString from '../utils/isString';\n\nexport default function getValidateError(\n result: ValidateResult,\n ref: Ref,\n type = 'validate',\n): FieldError | void {\n if (\n isString(result) ||\n (Array.isArray(result) && result.every(isString)) ||\n (isBoolean(result) && !result)\n ) {\n return {\n type,\n message: isString(result) ? result : '',\n ref,\n };\n }\n}\n","import type { ValidationRule } from '../types';\nimport isObject from '../utils/isObject';\nimport isRegex from '../utils/isRegex';\n\nexport default (validationData?: ValidationRule) =>\n isObject(validationData) && !isRegex(validationData)\n ? validationData\n : {\n value: validationData,\n message: '',\n };\n","import { INPUT_VALIDATION_RULES } from '../constants';\nimport type {\n Field,\n FieldError,\n FieldValues,\n InternalFieldErrors,\n InternalNameSet,\n MaxType,\n Message,\n MinType,\n NativeFieldValue,\n} from '../types';\nimport get from '../utils/get';\nimport isBoolean from '../utils/isBoolean';\nimport isCheckBoxInput from '../utils/isCheckBoxInput';\nimport isEmptyObject from '../utils/isEmptyObject';\nimport isFileInput from '../utils/isFileInput';\nimport isFunction from '../utils/isFunction';\nimport isHTMLElement from '../utils/isHTMLElement';\nimport isNullOrUndefined from '../utils/isNullOrUndefined';\nimport isObject from '../utils/isObject';\nimport isRadioInput from '../utils/isRadioInput';\nimport isRegex from '../utils/isRegex';\nimport isString from '../utils/isString';\nimport isUndefined from '../utils/isUndefined';\n\nimport appendErrors from './appendErrors';\nimport getCheckboxValue from './getCheckboxValue';\nimport getRadioValue from './getRadioValue';\nimport getValidateError from './getValidateError';\nimport getValueAndMessage from './getValueAndMessage';\n\nexport default async <T extends FieldValues>(\n field: Field,\n disabledFieldNames: InternalNameSet,\n formValues: T,\n validateAllFieldCriteria: boolean,\n shouldUseNativeValidation?: boolean,\n isFieldArray?: boolean,\n): Promise<InternalFieldErrors> => {\n const {\n ref,\n refs,\n required,\n maxLength,\n minLength,\n min,\n max,\n pattern,\n validate,\n name,\n valueAsNumber,\n mount,\n } = field._f;\n const inputValue: NativeFieldValue = get(formValues, name);\n if (!mount || disabledFieldNames.has(name)) {\n return {};\n }\n const inputRef: HTMLInputElement = refs ? refs[0] : (ref as HTMLInputElement);\n const setCustomValidity = (message?: string | boolean) => {\n if (shouldUseNativeValidation && inputRef.reportValidity) {\n inputRef.setCustomValidity(isBoolean(message) ? '' : message || '');\n inputRef.reportValidity();\n }\n };\n const error: InternalFieldErrors = {};\n const isRadio = isRadioInput(ref);\n const isCheckBox = isCheckBoxInput(ref);\n const isRadioOrCheckbox = isRadio || isCheckBox;\n const isEmpty =\n ((valueAsNumber || isFileInput(ref)) &&\n isUndefined(ref.value) &&\n isUndefined(inputValue)) ||\n (isHTMLElement(ref) && ref.value === '') ||\n inputValue === '' ||\n (Array.isArray(inputValue) && !inputValue.length);\n const appendErrorsCurry = appendErrors.bind(\n null,\n name,\n validateAllFieldCriteria,\n error,\n );\n const getMinMaxMessage = (\n exceedMax: boolean,\n maxLengthMessage: Message,\n minLengthMessage: Message,\n maxType: MaxType = INPUT_VALIDATION_RULES.maxLength,\n minType: MinType = INPUT_VALIDATION_RULES.minLength,\n ) => {\n const message = exceedMax ? maxLengthMessage : minLengthMessage;\n error[name] = {\n type: exceedMax ? maxType : minType,\n message,\n ref,\n ...appendErrorsCurry(exceedMax ? maxType : minType, message),\n };\n };\n\n if (\n isFieldArray\n ? !Array.isArray(inputValue) || !inputValue.length\n : required &&\n ((!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue))) ||\n (isBoolean(inputValue) && !inputValue) ||\n (isCheckBox && !getCheckboxValue(refs).isValid) ||\n (isRadio && !getRadioValue(refs).isValid))\n ) {\n const { value, message } = isString(required)\n ? { value: !!required, message: required }\n : getValueAndMessage(required);\n\n if (value) {\n error[name] = {\n type: INPUT_VALIDATION_RULES.required,\n message,\n ref: inputRef,\n ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message),\n };\n if (!validateAllFieldCriteria) {\n setCustomValidity(message);\n return error;\n }\n }\n }\n\n if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {\n let exceedMax;\n let exceedMin;\n const maxOutput = getValueAndMessage(max);\n const minOutput = getValueAndMessage(min);\n\n if (!isNullOrUndefined(inputValue) && !isNaN(inputValue as number)) {\n const valueNumber =\n (ref as HTMLInputElement).valueAsNumber ||\n (inputValue ? +inputValue : inputValue);\n if (!isNullOrUndefined(maxOutput.value)) {\n exceedMax = valueNumber > maxOutput.value;\n }\n if (!isNullOrUndefined(minOutput.value)) {\n exceedMin = valueNumber < minOutput.value;\n }\n } else {\n const valueDate =\n (ref as HTMLInputElement).valueAsDate || new Date(inputValue as string);\n const convertTimeToDate = (time: unknown) =>\n new Date(new Date().toDateString() + ' ' + time);\n const isTime = ref.type == 'time';\n const isWeek = ref.type == 'week';\n\n if (isString(maxOutput.value) && inputValue) {\n exceedMax = isTime\n ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value)\n : isWeek\n ? inputValue > maxOutput.value\n : valueDate > new Date(maxOutput.value);\n }\n\n if (isString(minOutput.value) && inputValue) {\n exceedMin = isTime\n ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value)\n : isWeek\n ? inputValue < minOutput.value\n : valueDate < new Date(minOutput.value);\n }\n }\n\n if (exceedMax || exceedMin) {\n getMinMaxMessage(\n !!exceedMax,\n maxOutput.message,\n minOutput.message,\n INPUT_VALIDATION_RULES.max,\n INPUT_VALIDATION_RULES.min,\n );\n if (!validateAllFieldCriteria) {\n setCustomValidity(error[name]!.message);\n return error;\n }\n }\n }\n\n if (\n (maxLength || minLength) &&\n !isEmpty &&\n (isString(inputValue) || (isFieldArray && Array.isArray(inputValue)))\n ) {\n const maxLengthOutput = getValueAndMessage(maxLength);\n const minLengthOutput = getValueAndMessage(minLength);\n const exceedMax =\n !isNullOrUndefined(maxLengthOutput.value) &&\n inputValue.length > +maxLengthOutput.value;\n const exceedMin =\n !isNullOrUndefined(minLengthOutput.value) &&\n inputValue.length < +minLengthOutput.value;\n\n if (exceedMax || exceedMin) {\n getMinMaxMessage(\n exceedMax,\n maxLengthOutput.message,\n minLengthOutput.message,\n );\n if (!validateAllFieldCriteria) {\n setCustomValidity(error[name]!.message);\n return error;\n }\n }\n }\n\n if (pattern && !isEmpty && isString(inputValue)) {\n const { value: patternValue, message } = getValueAndMessage(pattern);\n\n if (isRegex(patternValue) && !inputValue.match(patternValue)) {\n error[name] = {\n type: INPUT_VALIDATION_RULES.pattern,\n message,\n ref,\n ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message),\n };\n if (!validateAllFieldCriteria) {\n setCustomValidity(message);\n return error;\n }\n }\n }\n\n if (validate) {\n if (isFunction(validate)) {\n const result = await validate(inputValue, formValues);\n const validateError = getValidateError(result, inputRef);\n\n if (validateError) {\n error[name] = {\n ...validateError,\n ...appendErrorsCurry(\n INPUT_VALIDATION_RULES.validate,\n validateError.message,\n ),\n };\n if (!validateAllFieldCriteria) {\n setCustomValidity(validateError.message);\n return error;\n }\n }\n } else if (isObject(validate)) {\n let validationResult = {} as FieldError;\n\n for (const key in validate) {\n if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {\n break;\n }\n\n const validateError = getValidateError(\n await validate[key](inputValue, formValues),\n inputRef,\n key,\n );\n\n if (validateError) {\n validationResult = {\n ...validateError,\n ...appendErrorsCurry(key, validateError.message),\n };\n\n setCustomValidity(validateError.message);\n\n if (validateAllFieldCriteria) {\n error[name] = validationResult;\n }\n }\n }\n\n if (!isEmptyObject(validationResult)) {\n error[name] = {\n ref: inputRef,\n ...validationResult,\n };\n if (!validateAllFieldCriteria) {\n return error;\n }\n }\n }\n }\n\n setCustomValidity(true);\n return error;\n};\n","import { EVENTS, VALIDATION_MODE } from '../constants';\nimport type {\n BatchFieldArrayUpdate,\n ChangeHandler,\n Control,\n DeepPartial,\n DelayCallback,\n EventType,\n Field,\n FieldError,\n FieldErrors,\n FieldNamesMarkedBoolean,\n FieldPath,\n FieldRefs,\n FieldValues,\n FormState,\n FromSubscribe,\n GetIsDirty,\n GetValuesConfig,\n InternalFieldName,\n Names,\n Path,\n ReadFormState,\n Ref,\n SetFieldValue,\n SetValueConfig,\n Subjects,\n UseFormClearErrors,\n UseFormGetFieldState,\n UseFormGetValues,\n UseFormHandleSubmit,\n UseFormProps,\n UseFormRegister,\n UseFormReset,\n UseFormResetField,\n UseFormReturn,\n UseFormSetError,\n UseFormSetFocus,\n UseFormSetValue,\n UseFormSubscribe,\n UseFormTrigger,\n UseFormUnregister,\n UseFormWatch,\n WatchInternal,\n WatchObserver,\n} from '../types';\nimport cloneObject from '../utils/cloneObject';\nimport compact from '../utils/compact';\nimport convertToArrayPayload from '../utils/convertToArrayPayload';\nimport createSubject from '../utils/createSubject';\nimport deepEqual from '../utils/deepEqual';\nimport extractFormValues from '../utils/extractFormValues';\nimport get from '../utils/get';\nimport isBoolean from '../utils/isBoolean';\nimport isCheckBoxInput from '../utils/isCheckBoxInput';\nimport isDateObject from '../utils/isDateObject';\nimport isEmptyObject from '../utils/isEmptyObject';\nimport isFileInput from '../utils/isFileInput';\nimport isFunction from '../utils/isFunction';\nimport isHTMLElement from '../utils/isHTMLElement';\nimport isMultipleSelect from '../utils/isMultipleSelect';\nimport isNullOrUndefined from '../utils/isNullOrUndefined';\nimport isObject from '../utils/isObject';\nimport isRadioOrCheckbox from '../utils/isRadioOrCheckbox';\nimport isString from '../utils/isString';\nimport isUndefined from '../utils/isUndefined';\nimport isWeb from '../utils/isWeb';\nimport live from '../utils/live';\nimport set from '../utils/set';\nimport unset from '../utils/unset';\n\nimport generateWatchOutput from './generateWatchOutput';\nimport getDirtyFields from './getDirtyFields';\nimport getEventValue from './getEventValue';\nimport getFieldValue from './getFieldValue';\nimport getFieldValueAs from './getFieldValueAs';\nimport getResolverOptions from './getResolverOptions';\nimport getRuleValue from './getRuleValue';\nimport getValidationModes from './getValidationModes';\nimport hasPromiseValidation from './hasPromiseValidation';\nimport hasValidation from './hasValidation';\nimport isNameInFieldArray from './isNameInFieldArray';\nimport isWatched from './isWatched';\nimport iterateFieldsByAction from './iterateFieldsByAction';\nimport schemaErrorLookup from './schemaErrorLookup';\nimport shouldRenderFormState from './shouldRenderFormState';\nimport shouldSubscribeByName from './shouldSubscribeByName';\nimport skipValidation from './skipValidation';\nimport unsetEmptyArray from './unsetEmptyArray';\nimport updateFieldArrayRootError from './updateFieldArrayRootError';\nimport validateField from './validateField';\n\nconst defaultOptions = {\n mode: VALIDATION_MODE.onSubmit,\n reValidateMode: VALIDATION_MODE.onChange,\n shouldFocusError: true,\n} as const;\n\nexport function createFormControl<\n TFieldValues extends FieldValues = FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n>(\n props: UseFormProps<TFieldValues, TContext, TTransformedValues> = {},\n): Omit<\n UseFormReturn<TFieldValues, TContext, TTransformedValues>,\n 'formState'\n> & {\n formControl: Omit<\n UseFormReturn<TFieldValues, TContext, TTransformedValues>,\n 'formState'\n >;\n} {\n let _options = {\n ...defaultOptions,\n ...props,\n };\n let _formState: FormState<TFieldValues> = {\n submitCount: 0,\n isDirty: false,\n isReady: false,\n isLoading: isFunction(_options.defaultValues),\n isValidating: false,\n isSubmitted: false,\n isSubmitting: false,\n isSubmitSuccessful: false,\n isValid: false,\n touchedFields: {},\n dirtyFields: {},\n validatingFields: {},\n errors: _options.errors || {},\n disabled: _options.disabled || false,\n };\n let _fields: FieldRefs = {};\n let _defaultValues =\n isObject(_options.defaultValues) || isObject(_options.values)\n ? cloneObject(_options.defaultValues || _options.values) || {}\n : {};\n let _formValues = _options.shouldUnregister\n ? ({} as TFieldValues)\n : (cloneObject(_defaultValues) as TFieldValues);\n let _state = {\n action: false,\n mount: false,\n watch: false,\n };\n let _names: Names = {\n mount: new Set(),\n disabled: new Set(),\n unMount: new Set(),\n array: new Set(),\n watch: new Set(),\n };\n let delayErrorCallback: DelayCallback | null;\n let timer = 0;\n const _proxyFormState: ReadFormState = {\n isDirty: false,\n dirtyFields: false,\n validatingFields: false,\n touchedFields: false,\n isValidating: false,\n isValid: false,\n errors: false,\n };\n let _proxySubscribeFormState = {\n ..._proxyFormState,\n };\n const _subjects: Subjects<TFieldValues> = {\n array: createSubject(),\n state: createSubject(),\n };\n\n const shouldDisplayAllAssociatedErrors =\n _options.criteriaMode === VALIDATION_MODE.all;\n\n const debounce =\n <T extends Function>(callback: T) =>\n (wait: number) => {\n clearTimeout(timer);\n timer = setTimeout(callback, wait);\n };\n\n const _setValid = async (shouldUpdateValid?: boolean) => {\n if (\n !_options.disabled &&\n (_proxyFormState.isValid ||\n _proxySubscribeFormState.isValid ||\n shouldUpdateValid)\n ) {\n const isValid = _options.resolver\n ? isEmptyObject((await _runSchema()).errors)\n : await executeBuiltInValidation(_fields, true);\n\n if (isValid !== _formState.isValid) {\n _subjects.state.next({\n isValid,\n });\n }\n }\n };\n\n const _updateIsValidating = (names?: string[], isValidating?: boolean) => {\n if (\n !_options.disabled &&\n (_proxyFormState.isValidating ||\n _proxyFormState.validatingFields ||\n _proxySubscribeFormState.isValidating ||\n _proxySubscribeFormState.validatingFields)\n ) {\n (names || Array.from(_names.mount)).forEach((name) => {\n if (name) {\n isValidating\n ? set(_formState.validatingFields, name, isValidating)\n : unset(_formState.validatingFields, name);\n }\n });\n\n _subjects.state.next({\n validatingFields: _formState.validatingFields,\n isValidating: !isEmptyObject(_formState.validatingFields),\n });\n }\n };\n\n const _setFieldArray: BatchFieldArrayUpdate = (\n name,\n values = [],\n method,\n args,\n shouldSetValues = true,\n shouldUpdateFieldsAndState = true,\n ) => {\n if (args && method && !_options.disabled) {\n _state.action = true;\n if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {\n const fieldValues = method(get(_fields, name), args.argA, args.argB);\n shouldSetValues && set(_fields, name, fieldValues);\n }\n\n if (\n shouldUpdateFieldsAndState &&\n Array.isArray(get(_formState.errors, name))\n ) {\n const errors = method(\n get(_formState.errors, name),\n args.argA,\n args.argB,\n );\n shouldSetValues && set(_formState.errors, name, errors);\n unsetEmptyArray(_formState.errors, name);\n }\n\n if (\n (_proxyFormState.touchedFields ||\n _proxySubscribeFormState.touchedFields) &&\n shouldUpdateFieldsAndState &&\n Array.isArray(get(_formState.touchedFields, name))\n ) {\n const touchedFields = method(\n get(_formState.touchedFields, name),\n args.argA,\n args.argB,\n );\n shouldSetValues && set(_formState.touchedFields, name, touchedFields);\n }\n\n if (_proxyFormState.dirtyFields || _proxySubscribeFormState.dirtyFields) {\n _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);\n }\n\n _subjects.state.next({\n name,\n isDirty: _getDirty(name, values),\n dirtyFields: _formState.dirtyFields,\n errors: _formState.errors,\n isValid: _formState.isValid,\n });\n } else {\n set(_formValues, name, values);\n }\n };\n\n const updateErrors = (name: InternalFieldName, error: FieldError) => {\n set(_formState.errors, name, error);\n _subjects.state.next({\n errors: _formState.errors,\n });\n };\n\n const _setErrors = (errors: FieldErrors<TFieldValues>) => {\n _formState.errors = errors;\n _subjects.state.next({\n errors: _formState.errors,\n isValid: false,\n });\n };\n\n const updateValidAndValue = (\n name: InternalFieldName,\n shouldSkipSetValueAs: boolean,\n value?: unknown,\n ref?: Ref,\n ) => {\n const field: Field = get(_fields, name);\n\n if (field) {\n const defaultValue = get(\n _formValues,\n name,\n isUndefined(value) ? get(_defaultValues, name) : value,\n );\n\n isUndefined(defaultValue) ||\n (ref && (ref as HTMLInputElement).defaultChecked) ||\n shouldSkipSetValueAs\n ? set(\n _formValues,\n name,\n shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f),\n )\n : setFieldValue(name, defaultValue);\n\n _state.mount && !_state.action && _setValid();\n }\n };\n\n const updateTouchAndDirty = (\n name: InternalFieldName,\n fieldValue: unknown,\n isBlurEvent?: boolean,\n shouldDirty?: boolean,\n shouldRender?: boolean,\n ): Partial<\n Pick<FormState<TFieldValues>, 'dirtyFields' | 'isDirty' | 'touchedFields'>\n > => {\n let shouldUpdateField = false;\n let isPreviousDirty = false;\n const output: Partial<FormState<TFieldValues>> & { name: string } = {\n name,\n };\n\n if (!_options.disabled) {\n if (!isBlurEvent || shouldDirty) {\n if (_proxyFormState.isDirty || _proxySubscribeFormState.isDirty) {\n isPreviousDirty = _formState.isDirty;\n _formState.isDirty = output.isDirty = _getDirty();\n shouldUpdateField = isPreviousDirty !== output.isDirty;\n }\n\n const isCurrentFieldPristine = deepEqual(\n get(_defaultValues, name),\n fieldValue,\n );\n\n isPreviousDirty = !!get(_formState.dirtyFields, name);\n isCurrentFieldPristine\n ? unset(_formState.dirtyFields, name)\n : set(_formState.dirtyFields, name, true);\n output.dirtyFields = _formState.dirtyFields;\n shouldUpdateField =\n shouldUpdateField ||\n ((_proxyFormState.dirtyFields ||\n _proxySubscribeFormState.dirtyFields) &&\n isPreviousDirty !== !isCurrentFieldPristine);\n }\n\n if (isBlurEvent) {\n const isPreviousFieldTouched = get(_formState.touchedFields, name);\n\n if (!isPreviousFieldTouched) {\n set(_formState.touchedFields, name, isBlurEvent);\n output.touchedFields = _formState.touchedFields;\n shouldUpdateField =\n shouldUpdateField ||\n ((_proxyFormState.touchedFields ||\n _proxySubscribeFormState.touchedFields) &&\n isPreviousFieldTouched !== isBlurEvent);\n }\n }\n\n shouldUpdateField && shouldRender && _subjects.state.next(output);\n }\n\n return shouldUpdateField ? output : {};\n };\n\n const shouldRenderByError = (\n name: InternalFieldName,\n isValid?: boolean,\n error?: FieldError,\n fieldState?: {\n dirty?: FieldNamesMarkedBoolean<TFieldValues>;\n isDirty?: boolean;\n touched?: FieldNamesMarkedBoolean<TFieldValues>;\n },\n ) => {\n const previousFieldError = get(_formState.errors, name);\n const shouldUpdateValid =\n (_proxyFormState.isValid || _proxySubscribeFormState.isValid) &&\n isBoolean(isValid) &&\n _formState.isValid !== isValid;\n\n if (_options.delayError && error) {\n delayErrorCallback = debounce(() => updateErrors(name, error));\n delayErrorCallback(_options.delayError);\n } else {\n clearTimeout(timer);\n delayErrorCallback = null;\n error\n ? set(_formState.errors, name, error)\n : unset(_formState.errors, name);\n }\n\n if (\n (error ? !deepEqual(previousFieldError, error) : previousFieldError) ||\n !isEmptyObject(fieldState) ||\n shouldUpdateValid\n ) {\n const updatedFormState = {\n ...fieldState,\n ...(shouldUpdateValid && isBoolean(isValid) ? { isValid } : {}),\n errors: _formState.errors,\n name,\n };\n\n _formState = {\n ..._formState,\n ...updatedFormState,\n };\n\n _subjects.state.next(updatedFormState);\n }\n };\n\n const _runSchema = async (name?: InternalFieldName[]) => {\n _updateIsValidating(name, true);\n const result = await _options.resolver!(\n _formValues as TFieldValues,\n _options.context,\n getResolverOptions(\n name || _names.mount,\n _fields,\n _options.criteriaMode,\n _options.shouldUseNativeValidation,\n ),\n );\n _updateIsValidating(name);\n return result;\n };\n\n const executeSchemaAndUpdateState = async (names?: InternalFieldName[]) => {\n const { errors } = await _runSchema(names);\n\n if (names) {\n for (const name of names) {\n const error = get(errors, name);\n error\n ? set(_formState.errors, name, error)\n : unset(_formState.errors, name);\n }\n } else {\n _formState.errors = errors;\n }\n\n return errors;\n };\n\n const executeBuiltInValidation = async (\n fields: FieldRefs,\n shouldOnlyCheckValid?: boolean,\n context: {\n valid: boolean;\n } = {\n valid: true,\n },\n ) => {\n for (const name in fields) {\n const field = fields[name];\n\n if (field) {\n const { _f, ...fieldValue } = field as Field;\n\n if (_f) {\n const isFieldArrayRoot = _names.array.has(_f.name);\n const isPromiseFunction =\n field._f && hasPromiseValidation((field as Field)._f);\n\n if (isPromiseFunction && _proxyFormState.validatingFields) {\n _updateIsValidating([_f.name], true);\n }\n\n const fieldError = await validateField(\n field as Field,\n _names.disabled,\n _formValues,\n shouldDisplayAllAssociatedErrors,\n _options.shouldUseNativeValidation && !shouldOnlyCheckValid,\n isFieldArrayRoot,\n );\n\n if (isPromiseFunction && _proxyFormState.validatingFields) {\n _updateIsValidating([_f.name]);\n }\n\n if (fieldError[_f.name]) {\n context.valid = false;\n if (shouldOnlyCheckValid) {\n break;\n }\n }\n\n !shouldOnlyCheckValid &&\n (get(fieldError, _f.name)\n ? isFieldArrayRoot\n ? updateFieldArrayRootError(\n _formState.errors,\n fieldError,\n _f.name,\n )\n : set(_formState.errors, _f.name, fieldError[_f.name])\n : unset(_formState.errors, _f.name));\n }\n\n !isEmptyObject(fieldValue) &&\n (await executeBuiltInValidation(\n fieldValue,\n shouldOnlyCheckValid,\n context,\n ));\n }\n }\n\n return context.valid;\n };\n\n const _removeUnmounted = () => {\n for (const name of _names.unMount) {\n const field: Field = get(_fields, name);\n\n field &&\n (field._f.refs\n ? field._f.refs.every((ref) => !live(ref))\n : !live(field._f.ref)) &&\n unregister(name as FieldPath<TFieldValues>);\n }\n\n _names.unMount = new Set();\n };\n\n const _getDirty: GetIsDirty = (name, data) =>\n !_options.disabled &&\n (name && data && set(_formValues, name, data),\n !deepEqual(getValues(), _defaultValues));\n\n const _getWatch: WatchInternal<TFieldValues> = (\n names,\n defaultValue,\n isGlobal,\n ) =>\n generateWatchOutput(\n names,\n _names,\n {\n ...(_state.mount\n ? _formValues\n : isUndefined(defaultValue)\n ? _defaultValues\n : isString(names)\n ? { [names]: defaultValue }\n : defaultValue),\n },\n isGlobal,\n defaultValue,\n );\n\n const _getFieldArray = <TFieldArrayValues>(\n name: InternalFieldName,\n ): Partial<TFieldArrayValues>[] =>\n compact(\n get(\n _state.mount ? _formValues : _defaultValues,\n name,\n _options.shouldUnregister ? get(_defaultValues, name, []) : [],\n ),\n );\n\n const setFieldValue = (\n name: InternalFieldName,\n value: SetFieldValue<TFieldValues>,\n options: SetValueConfig = {},\n ) => {\n const field: Field = get(_fields, name);\n let fieldValue: unknown = value;\n\n if (field) {\n const fieldReference = field._f;\n\n if (fieldReference) {\n !fieldReference.disabled &&\n set(_formValues, name, getFieldValueAs(value, fieldReference));\n\n fieldValue =\n isHTMLElement(fieldReference.ref) && isNullOrUndefined(value)\n ? ''\n : value;\n\n if (isMultipleSelect(fieldReference.ref)) {\n [...fieldReference.ref.options].forEach(\n (optionRef) =>\n (optionRef.selected = (\n fieldValue as InternalFieldName[]\n ).includes(optionRef.value)),\n );\n } else if (fieldReference.refs) {\n if (isCheckBoxInput(fieldReference.ref)) {\n fieldReference.refs.forEach((checkboxRef) => {\n if (!checkboxRef.defaultChecked || !checkboxRef.disabled) {\n if (Array.isArray(fieldValue)) {\n checkboxRef.checked = !!fieldValue.find(\n (data: string) => data === checkboxRef.value,\n );\n } else {\n checkboxRef.checked =\n fieldValue === checkboxRef.value || !!fieldValue;\n }\n }\n });\n } else {\n fieldReference.refs.forEach(\n (radioRef: HTMLInputElement) =>\n (radioRef.checked = radioRef.value === fieldValue),\n );\n }\n } else if (isFileInput(fieldReference.ref)) {\n fieldReference.ref.value = '';\n } else {\n fieldReference.ref.value = fieldValue;\n\n if (!fieldReference.ref.type) {\n _subjects.state.next({\n name,\n values: cloneObject(_formValues),\n });\n }\n }\n }\n }\n\n (options.shouldDirty || options.shouldTouch) &&\n updateTouchAndDirty(\n name,\n fieldValue,\n options.shouldTouch,\n options.shouldDirty,\n true,\n );\n\n options.shouldValidate && trigger(name as Path<TFieldValues>);\n };\n\n const setValues = <\n T extends InternalFieldName,\n K extends SetFieldValue<TFieldValues>,\n U extends SetValueConfig,\n >(\n name: T,\n value: K,\n options: U,\n ) => {\n for (const fieldKey in value) {\n if (!value.hasOwnProperty(fieldKey)) {\n return;\n }\n const fieldValue = value[fieldKey];\n const fieldName = name + '.' + fieldKey;\n const field = get(_fields, fieldName);\n\n (_names.array.has(name) ||\n isObject(fieldValue) ||\n (field && !field._f)) &&\n !isDateObject(fieldValue)\n ? setValues(fieldName, fieldValue, options)\n : setFieldValue(fieldName, fieldValue, options);\n }\n };\n\n const setValue: UseFormSetValue<TFieldValues> = (\n name,\n value,\n options = {},\n ) => {\n const field = get(_fields, name);\n const isFieldArray = _names.array.has(name);\n const cloneValue = cloneObject(value);\n\n set(_formValues, name, cloneValue);\n\n if (isFieldArray) {\n _subjects.array.next({\n name,\n values: cloneObject(_formValues),\n });\n\n if (\n (_proxyFormState.isDirty ||\n _proxyFormState.dirtyFields ||\n _proxySubscribeFormState.isDirty ||\n _proxySubscribeFormState.dirtyFields) &&\n options.shouldDirty\n ) {\n _subjects.state.next({\n name,\n dirtyFields: getDirtyFields(_defaultValues, _formValues),\n isDirty: _getDirty(name, cloneValue),\n });\n }\n } else {\n field && !field._f && !isNullOrUndefined(cloneValue)\n ? setValues(name, cloneValue, options)\n : setFieldValue(name, cloneValue, options);\n }\n\n isWatched(name, _names) && _subjects.state.next({ ..._formState, name });\n _subjects.state.next({\n name: _state.mount ? name : undefined,\n values: cloneObject(_formValues),\n });\n };\n\n const onChange: ChangeHandler = async (event) => {\n _state.mount = true;\n const target = event.target;\n let name: string = target.name;\n let isFieldValueUpdated = true;\n const field: Field = get(_fields, name);\n const _updateIsFieldValueUpdated = (fieldValue: unknown) => {\n isFieldValueUpdated =\n Number.isNaN(fieldValue) ||\n (isDateObject(fieldValue) && isNaN(fieldValue.getTime())) ||\n deepEqual(fieldValue, get(_formValues, name, fieldValue));\n };\n const validationModeBeforeSubmit = getValidationModes(_options.mode);\n const validationModeAfterSubmit = getValidationModes(\n _options.reValidateMode,\n );\n\n if (field) {\n let error;\n let isValid;\n const fieldValue = target.type\n ? getFieldValue(field._f)\n : getEventValue(event);\n const isBlurEvent =\n event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;\n const shouldSkipValidation =\n (!hasValidation(field._f) &&\n !_options.resolver &&\n !get(_formState.errors, name) &&\n !field._f.deps) ||\n skipValidation(\n isBlurEvent,\n get(_formState.touchedFields, name),\n _formState.isSubmitted,\n validationModeAfterSubmit,\n validationModeBeforeSubmit,\n );\n const watched = isWatched(name, _names, isBlurEvent);\n\n set(_formValues, name, fieldValue);\n\n if (isBlurEvent) {\n if (!target || !target.readOnly) {\n field._f.onBlur && field._f.onBlur(event);\n delayErrorCallback && delayErrorCallback(0);\n }\n } else if (field._f.onChange) {\n field._f.onChange(event);\n }\n\n const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent);\n\n const shouldRender = !isEmptyObject(fieldState) || watched;\n\n !isBlurEvent &&\n _subjects.state.next({\n name,\n type: event.type,\n values: cloneObject(_formValues),\n });\n\n if (shouldSkipValidation) {\n if (_proxyFormState.isValid || _proxySubscribeFormState.isValid) {\n if (_options.mode === 'onBlur') {\n if (isBlurEvent) {\n _setValid();\n }\n } else if (!isBlurEvent) {\n _setValid();\n }\n }\n\n return (\n shouldRender &&\n _subjects.state.next({ name, ...(watched ? {} : fieldState) })\n );\n }\n\n !isBlurEvent && watched && _subjects.state.next({ ..._formState });\n\n if (_options.resolver) {\n const { errors } = await _runSchema([name]);\n\n _updateIsFieldValueUpdated(fieldValue);\n\n if (isFieldValueUpdated) {\n const previousErrorLookupResult = schemaErrorLookup(\n _formState.errors,\n _fields,\n name,\n );\n const errorLookupResult = schemaErrorLookup(\n errors,\n _fields,\n previousErrorLookupResult.name || name,\n );\n\n error = errorLookupResult.error;\n name = errorLookupResult.name;\n\n isValid = isEmptyObject(errors);\n }\n } else {\n _updateIsValidating([name], true);\n error = (\n await validateField(\n field,\n _names.disabled,\n _formValues,\n shouldDisplayAllAssociatedErrors,\n _options.shouldUseNativeValidation,\n )\n )[name];\n _updateIsValidating([name]);\n\n _updateIsFieldValueUpdated(fieldValue);\n\n if (isFieldValueUpdated) {\n if (error) {\n isValid = false;\n } else if (\n _proxyFormState.isValid ||\n _proxySubscribeFormState.isValid\n ) {\n isValid = await executeBuiltInValidation(_fields, true);\n }\n }\n }\n\n if (isFieldValueUpdated) {\n field._f.deps &&\n (!Array.isArray(field._f.deps) || field._f.deps.length > 0) &&\n trigger(\n field._f.deps as\n | FieldPath<TFieldValues>\n | FieldPath<TFieldValues>[],\n );\n shouldRenderByError(name, isValid, error, fieldState);\n }\n }\n };\n\n const _focusInput = (ref: Ref, key: string) => {\n if (get(_formState.errors, key) && ref.focus) {\n ref.focus();\n return 1;\n }\n return;\n };\n\n const trigger: UseFormTrigger<TFieldValues> = async (name, options = {}) => {\n let isValid;\n let validationResult;\n const fieldNames = convertToArrayPayload(name) as InternalFieldName[];\n\n if (_options.resolver) {\n const errors = await executeSchemaAndUpdateState(\n isUndefined(name) ? name : fieldNames,\n );\n\n isValid = isEmptyObject(errors);\n validationResult = name\n ? !fieldNames.some((name) => get(errors, name))\n : isValid;\n } else if (name) {\n validationResult = (\n await Promise.all(\n fieldNames.map(async (fieldName) => {\n const field = get(_fields, fieldName);\n return await executeBuiltInValidation(\n field && field._f ? { [fieldName]: field } : field,\n );\n }),\n )\n ).every(Boolean);\n !(!validationResult && !_formState.isValid) && _setValid();\n } else {\n validationResult = isValid = await executeBuiltInValidation(_fields);\n }\n\n _subjects.state.next({\n ...(!isString(name) ||\n ((_proxyFormState.isValid || _proxySubscribeFormState.isValid) &&\n isValid !== _formState.isValid)\n ? {}\n : { name }),\n ...(_options.resolver || !name ? { isValid } : {}),\n errors: _formState.errors,\n });\n\n options.shouldFocus &&\n !validationResult &&\n iterateFieldsByAction(\n _fields,\n _focusInput,\n name ? fieldNames : _names.mount,\n );\n\n return validationResult;\n };\n\n const getValues: UseFormGetValues<TFieldValues> = (\n fieldNames?:\n | FieldPath<TFieldValues>\n | ReadonlyArray<FieldPath<TFieldValues>>,\n config?: GetValuesConfig,\n ) => {\n let values = {\n ...(_state.mount ? _formValues : _defaultValues),\n };\n\n if (config) {\n values = extractFormValues(\n config.dirtyFields ? _formState.dirtyFields : _formState.touchedFields,\n values,\n );\n }\n\n return isUndefined(fieldNames)\n ? values\n : isString(fieldNames)\n ? get(values, fieldNames)\n : fieldNames.map((name) => get(values, name));\n };\n\n const getFieldState: UseFormGetFieldState<TFieldValues> = (\n name,\n formState,\n ) => ({\n invalid: !!get((formState || _formState).errors, name),\n isDirty: !!get((formState || _formState).dirtyFields, name),\n error: get((formState || _formState).errors, name),\n isValidating: !!get(_formState.validatingFields, name),\n isTouched: !!get((formState || _formState).touchedFields, name),\n });\n\n const clearErrors: UseFormClearErrors<TFieldValues> = (name) => {\n name &&\n convertToArrayPayload(name).forEach((inputName) =>\n unset(_formState.errors, inputName),\n );\n\n _subjects.state.next({\n errors: name ? _formState.errors : {},\n });\n };\n\n const setError: UseFormSetError<TFieldValues> = (name, error, options) => {\n const ref = (get(_fields, name, { _f: {} })._f || {}).ref;\n const currentError = get(_formState.errors, name) || {};\n\n // Don't override existing error messages elsewhere in the object tree.\n const { ref: currentRef, message, type, ...restOfErrorTree } = currentError;\n\n set(_formState.errors, name, {\n ...restOfErrorTree,\n ...error,\n ref,\n });\n\n _subjects.state.next({\n name,\n errors: _formState.errors,\n isValid: false,\n });\n\n options && options.shouldFocus && ref && ref.focus && ref.focus();\n };\n\n const watch: UseFormWatch<TFieldValues> = (\n name?:\n | FieldPath<TFieldValues>\n | ReadonlyArray<FieldPath<TFieldValues>>\n | WatchObserver<TFieldValues>,\n defaultValue?: DeepPartial<TFieldValues>,\n ) =>\n isFunction(name)\n ? _subjects.state.subscribe({\n next: (payload) =>\n 'values' in payload &&\n name(\n _getWatch(undefined, defaultValue),\n payload as {\n name?: FieldPath<TFieldValues>;\n type?: EventType;\n value?: unknown;\n },\n ),\n })\n : _getWatch(\n name as InternalFieldName | InternalFieldName[],\n defaultValue,\n true,\n );\n\n const _subscribe: FromSubscribe<TFieldValues> = (props) =>\n _subjects.state.subscribe({\n next: (\n formState: Partial<FormState<TFieldValues>> & {\n name?: InternalFieldName;\n values?: TFieldValues | undefined;\n type?: EventType;\n },\n ) => {\n if (\n shouldSubscribeByName(props.name, formState.name, props.exact) &&\n shouldRenderFormState(\n formState,\n (props.formState as ReadFormState) || _proxyFormState,\n _setFormState,\n props.reRenderRoot,\n )\n ) {\n props.callback({\n values: { ..._formValues } as TFieldValues,\n ..._formState,\n ...formState,\n defaultValues:\n _defaultValues as FormState<TFieldValues>['defaultValues'],\n });\n }\n },\n }).unsubscribe;\n\n const subscribe: UseFormSubscribe<TFieldValues> = (props) => {\n _state.mount = true;\n _proxySubscribeFormState = {\n ..._proxySubscribeFormState,\n ...props.formState,\n };\n return _subscribe({\n ...props,\n formState: _proxySubscribeFormState,\n });\n };\n\n const unregister: UseFormUnregister<TFieldValues> = (name, options = {}) => {\n for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {\n _names.mount.delete(fieldName);\n _names.array.delete(fieldName);\n\n if (!options.keepValue) {\n unset(_fields, fieldName);\n unset(_formValues, fieldName);\n }\n\n !options.keepError && unset(_formState.errors, fieldName);\n !options.keepDirty && unset(_formState.dirtyFields, fieldName);\n !options.keepTouched && unset(_formState.touchedFields, fieldName);\n !options.keepIsValidating &&\n unset(_formState.validatingFields, fieldName);\n !_options.shouldUnregister &&\n !options.keepDefaultValue &&\n unset(_defaultValues, fieldName);\n }\n\n _subjects.state.next({\n values: cloneObject(_formValues),\n });\n\n _subjects.state.next({\n ..._formState,\n ...(!options.keepDirty ? {} : { isDirty: _getDirty() }),\n });\n\n !options.keepIsValid && _setValid();\n };\n\n const _setDisabledField: Control<TFieldValues>['_setDisabledField'] = ({\n disabled,\n name,\n }) => {\n if (\n (isBoolean(disabled) && _state.mount) ||\n !!disabled ||\n _names.disabled.has(name)\n ) {\n disabled ? _names.disabled.add(name) : _names.disabled.delete(name);\n }\n };\n\n const register: UseFormRegister<TFieldValues> = (name, options = {}) => {\n let field = get(_fields, name);\n const disabledIsDefined =\n isBoolean(options.disabled) || isBoolean(_options.disabled);\n\n set(_fields, name, {\n ...(field || {}),\n _f: {\n ...(field && field._f ? field._f : { ref: { name } }),\n name,\n mount: true,\n ...options,\n },\n });\n _names.mount.add(name);\n\n if (field) {\n _setDisabledField({\n disabled: isBoolean(options.disabled)\n ? options.disabled\n : _options.disabled,\n name,\n });\n } else {\n updateValidAndValue(name, true, options.value);\n }\n\n return {\n ...(disabledIsDefined\n ? { disabled: options.disabled || _options.disabled }\n : {}),\n ...(_options.progressive\n ? {\n required: !!options.required,\n min: getRuleValue(options.min),\n max: getRuleValue(options.max),\n minLength: getRuleValue<number>(options.minLength) as number,\n maxLength: getRuleValue(options.maxLength) as number,\n pattern: getRuleValue(options.pattern) as string,\n }\n : {}),\n name,\n onChange,\n onBlur: onChange,\n ref: (ref: HTMLInputElement | null): void => {\n if (ref) {\n register(name, options);\n field = get(_fields, name);\n\n const fieldRef = isUndefined(ref.value)\n ? ref.querySelectorAll\n ? (ref.querySelectorAll('input,select,textarea')[0] as Ref) || ref\n : ref\n : ref;\n const radioOrCheckbox = isRadioOrCheckbox(fieldRef);\n const refs = field._f.refs || [];\n\n if (\n radioOrCheckbox\n ? refs.find((option: Ref) => option === fieldRef)\n : fieldRef === field._f.ref\n ) {\n return;\n }\n\n set(_fields, name, {\n _f: {\n ...field._f,\n ...(radioOrCheckbox\n ? {\n refs: [\n ...refs.filter(live),\n fieldRef,\n ...(Array.isArray(get(_defaultValues, name)) ? [{}] : []),\n ],\n ref: { type: fieldRef.type, name },\n }\n : { ref: fieldRef }),\n },\n });\n\n updateValidAndValue(name, false, undefined, fieldRef);\n } else {\n field = get(_fields, name, {});\n\n if (field._f) {\n field._f.mount = false;\n }\n\n (_options.shouldUnregister || options.shouldUnregister) &&\n !(isNameInFieldArray(_names.array, name) && _state.action) &&\n _names.unMount.add(name);\n }\n },\n };\n };\n\n const _focusError = () =>\n _options.shouldFocusError &&\n iterateFieldsByAction(_fields, _focusInput, _names.mount);\n\n const _disableForm = (disabled?: boolean) => {\n if (isBoolean(disabled)) {\n _subjects.state.next({ disabled });\n iterateFieldsByAction(\n _fields,\n (ref, name) => {\n const currentField: Field = get(_fields, name);\n if (currentField) {\n ref.disabled = currentField._f.disabled || disabled;\n\n if (Array.isArray(currentField._f.refs)) {\n currentField._f.refs.forEach((inputRef) => {\n inputRef.disabled = currentField._f.disabled || disabled;\n });\n }\n }\n },\n 0,\n false,\n );\n }\n };\n\n const handleSubmit: UseFormHandleSubmit<TFieldValues, TTransformedValues> =\n (onValid, onInvalid) => async (e) => {\n let onValidError = undefined;\n if (e) {\n e.preventDefault && e.preventDefault();\n (e as React.BaseSyntheticEvent).persist &&\n (e as React.BaseSyntheticEvent).persist();\n }\n let fieldValues:\n | TFieldValues\n | TTransformedValues\n | Record<string, never> = cloneObject(_formValues);\n\n _subjects.state.next({\n isSubmitting: true,\n });\n\n if (_options.resolver) {\n const { errors, values } = await _runSchema();\n _formState.errors = errors;\n fieldValues = cloneObject(values);\n } else {\n await executeBuiltInValidation(_fields);\n }\n\n if (_names.disabled.size) {\n for (const name of _names.disabled) {\n unset(fieldValues, name);\n }\n }\n\n unset(_formState.errors, 'root');\n\n if (isEmptyObject(_formState.errors)) {\n _subjects.state.next({\n errors: {},\n });\n try {\n await onValid(fieldValues as TTransformedValues, e);\n } catch (error) {\n onValidError = error;\n }\n } else {\n if (onInvalid) {\n await onInvalid({ ..._formState.errors }, e);\n }\n _focusError();\n setTimeout(_focusError);\n }\n\n _subjects.state.next({\n isSubmitted: true,\n isSubmitting: false,\n isSubmitSuccessful: isEmptyObject(_formState.errors) && !onValidError,\n submitCount: _formState.submitCount + 1,\n errors: _formState.errors,\n });\n if (onValidError) {\n throw onValidError;\n }\n };\n\n const resetField: UseFormResetField<TFieldValues> = (name, options = {}) => {\n if (get(_fields, name)) {\n if (isUndefined(options.defaultValue)) {\n setValue(name, cloneObject(get(_defaultValues, name)));\n } else {\n setValue(\n name,\n options.defaultValue as Parameters<typeof setValue<typeof name>>[1],\n );\n set(_defaultValues, name, cloneObject(options.defaultValue));\n }\n\n if (!options.keepTouched) {\n unset(_formState.touchedFields, name);\n }\n\n if (!options.keepDirty) {\n unset(_formState.dirtyFields, name);\n _formState.isDirty = options.defaultValue\n ? _getDirty(name, cloneObject(get(_defaultValues, name)))\n : _getDirty();\n }\n\n if (!options.keepError) {\n unset(_formState.errors, name);\n _proxyFormState.isValid && _setValid();\n }\n\n _subjects.state.next({ ..._formState });\n }\n };\n\n const _reset: UseFormReset<TFieldValues> = (\n formValues,\n keepStateOptions = {},\n ) => {\n const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;\n const cloneUpdatedValues = cloneObject(updatedValues);\n const isEmptyResetValues = isEmptyObject(formValues);\n const values = isEmptyResetValues ? _defaultValues : cloneUpdatedValues;\n\n if (!keepStateOptions.keepDefaultValues) {\n _defaultValues = updatedValues;\n }\n\n if (!keepStateOptions.keepValues) {\n if (keepStateOptions.keepDirtyValues) {\n const fieldsToCheck = new Set([\n ..._names.mount,\n ...Object.keys(getDirtyFields(_defaultValues, _formValues)),\n ]);\n for (const fieldName of Array.from(fieldsToCheck)) {\n get(_formState.dirtyFields, fieldName)\n ? set(values, fieldName, get(_formValues, fieldName))\n : setValue(\n fieldName as FieldPath<TFieldValues>,\n get(values, fieldName),\n );\n }\n } else {\n if (isWeb && isUndefined(formValues)) {\n for (const name of _names.mount) {\n const field = get(_fields, name);\n if (field && field._f) {\n const fieldReference = Array.isArray(field._f.refs)\n ? field._f.refs[0]\n : field._f.ref;\n\n if (isHTMLElement(fieldReference)) {\n const form = fieldReference.closest('form');\n if (form) {\n form.reset();\n break;\n }\n }\n }\n }\n }\n\n if (keepStateOptions.keepFieldsRef) {\n for (const fieldName of _names.mount) {\n setValue(\n fieldName as FieldPath<TFieldValues>,\n get(values, fieldName),\n );\n }\n } else {\n _fields = {};\n }\n }\n\n _formValues = _options.shouldUnregister\n ? keepStateOptions.keepDefaultValues\n ? (cloneObject(_defaultValues) as TFieldValues)\n : ({} as TFieldValues)\n : (cloneObject(values) as TFieldValues);\n\n _subjects.array.next({\n values: { ...values },\n });\n\n _subjects.state.next({\n values: { ...values } as TFieldValues,\n });\n }\n\n _names = {\n mount: keepStateOptions.keepDirtyValues ? _names.mount : new Set(),\n unMount: new Set(),\n array: new Set(),\n disabled: new Set(),\n watch: new Set(),\n watchAll: false,\n focus: '',\n };\n\n _state.mount =\n !_proxyFormState.isValid ||\n !!keepStateOptions.keepIsValid ||\n !!keepStateOptions.keepDirtyValues ||\n (!_options.shouldUnregister && !isEmptyObject(values));\n\n _state.watch = !!_options.shouldUnregister;\n\n _subjects.state.next({\n submitCount: keepStateOptions.keepSubmitCount\n ? _formState.submitCount\n : 0,\n isDirty: isEmptyResetValues\n ? false\n : keepStateOptions.keepDirty\n ? _formState.isDirty\n : !!(\n keepStateOptions.keepDefaultValues &&\n !deepEqual(formValues, _defaultValues)\n ),\n isSubmitted: keepStateOptions.keepIsSubmitted\n ? _formState.isSubmitted\n : false,\n dirtyFields: isEmptyResetValues\n ? {}\n : keepStateOptions.keepDirtyValues\n ? keepStateOptions.keepDefaultValues && _formValues\n ? getDirtyFields(_defaultValues, _formValues)\n : _formState.dirtyFields\n : keepStateOptions.keepDefaultValues && formValues\n ? getDirtyFields(_defaultValues, formValues)\n : keepStateOptions.keepDirty\n ? _formState.dirtyFields\n : {},\n touchedFields: keepStateOptions.keepTouched\n ? _formState.touchedFields\n : {},\n errors: keepStateOptions.keepErrors ? _formState.errors : {},\n isSubmitSuccessful: keepStateOptions.keepIsSubmitSuccessful\n ? _formState.isSubmitSuccessful\n : false,\n isSubmitting: false,\n defaultValues: _defaultValues as FormState<TFieldValues>['defaultValues'],\n });\n };\n\n const reset: UseFormReset<TFieldValues> = (formValues, keepStateOptions) =>\n _reset(\n isFunction(formValues)\n ? (formValues as Function)(_formValues as TFieldValues)\n : formValues,\n keepStateOptions,\n );\n\n const setFocus: UseFormSetFocus<TFieldValues> = (name, options = {}) => {\n const field = get(_fields, name);\n const fieldReference = field && field._f;\n\n if (fieldReference) {\n const fieldRef = fieldReference.refs\n ? fieldReference.refs[0]\n : fieldReference.ref;\n\n if (fieldRef.focus) {\n fieldRef.focus();\n options.shouldSelect &&\n isFunction(fieldRef.select) &&\n fieldRef.select();\n }\n }\n };\n\n const _setFormState = (\n updatedFormState: Partial<FormState<TFieldValues>>,\n ) => {\n _formState = {\n ..._formState,\n ...updatedFormState,\n };\n };\n\n const _resetDefaultValues = () =>\n isFunction(_options.defaultValues) &&\n (_options.defaultValues as Function)().then((values: TFieldValues) => {\n reset(values, _options.resetOptions);\n _subjects.state.next({\n isLoading: false,\n });\n });\n\n const methods = {\n control: {\n register,\n unregister,\n getFieldState,\n handleSubmit,\n setError,\n _subscribe,\n _runSchema,\n _focusError,\n _getWatch,\n _getDirty,\n _setValid,\n _setFieldArray,\n _setDisabledField,\n _setErrors,\n _getFieldArray,\n _reset,\n _resetDefaultValues,\n _removeUnmounted,\n _disableForm,\n _subjects,\n _proxyFormState,\n get _fields() {\n return _fields;\n },\n get _formValues() {\n return _formValues;\n },\n get _state() {\n return _state;\n },\n set _state(value) {\n _state = value;\n },\n get _defaultValues() {\n return _defaultValues;\n },\n get _names() {\n return _names;\n },\n set _names(value) {\n _names = value;\n },\n get _formState() {\n return _formState;\n },\n get _options() {\n return _options;\n },\n set _options(value) {\n _options = {\n ..._options,\n ...value,\n };\n },\n },\n subscribe,\n trigger,\n register,\n handleSubmit,\n watch,\n setValue,\n getValues,\n reset,\n resetField,\n clearErrors,\n unregister,\n setError,\n setFocus,\n getFieldState,\n };\n\n return {\n ...methods,\n formControl: methods,\n };\n}\n","export default () => {\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n return crypto.randomUUID();\n }\n\n const d =\n typeof performance === 'undefined' ? Date.now() : performance.now() * 1000;\n\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16 + d) % 16 | 0;\n\n return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n};\n","import type { FieldArrayMethodProps, InternalFieldName } from '../types';\nimport isUndefined from '../utils/isUndefined';\n\nexport default (\n name: InternalFieldName,\n index: number,\n options: FieldArrayMethodProps = {},\n): string =>\n options.shouldFocus || isUndefined(options.shouldFocus)\n ? options.focusName ||\n `${name}.${isUndefined(options.focusIndex) ? index : options.focusIndex}.`\n : '';\n","import convertToArrayPayload from './convertToArrayPayload';\n\nexport default <T>(data: T[], value: T | T[]): T[] => [\n ...data,\n ...convertToArrayPayload(value),\n];\n","export default <T>(value: T | T[]): undefined[] | undefined =>\n Array.isArray(value) ? value.map(() => undefined) : undefined;\n","import convertToArrayPayload from './convertToArrayPayload';\n\nexport default function insert<T>(data: T[], index: number): (T | undefined)[];\nexport default function insert<T>(\n data: T[],\n index: number,\n value: T | T[],\n): T[];\nexport default function insert<T>(\n data: T[],\n index: number,\n value?: T | T[],\n): (T | undefined)[] {\n return [\n ...data.slice(0, index),\n ...convertToArrayPayload(value),\n ...data.slice(index),\n ];\n}\n","import isUndefined from './isUndefined';\n\nexport default <T>(\n data: (T | undefined)[],\n from: number,\n to: number,\n): (T | undefined)[] => {\n if (!Array.isArray(data)) {\n return [];\n }\n\n if (isUndefined(data[to])) {\n data[to] = undefined;\n }\n data.splice(to, 0, data.splice(from, 1)[0]);\n\n return data;\n};\n","import convertToArrayPayload from './convertToArrayPayload';\n\nexport default <T>(data: T[], value: T | T[]): T[] => [\n ...convertToArrayPayload(value),\n ...convertToArrayPayload(data),\n];\n","import compact from './compact';\nimport convertToArrayPayload from './convertToArrayPayload';\nimport isUndefined from './isUndefined';\n\nfunction removeAtIndexes<T>(data: T[], indexes: number[]): T[] {\n let i = 0;\n const temp = [...data];\n\n for (const index of indexes) {\n temp.splice(index - i, 1);\n i++;\n }\n\n return compact(temp).length ? temp : [];\n}\n\nexport default <T>(data: T[], index?: number | number[]): T[] =>\n isUndefined(index)\n ? []\n : removeAtIndexes(\n data,\n (convertToArrayPayload(index) as number[]).sort((a, b) => a - b),\n );\n","export default <T>(data: T[], indexA: number, indexB: number): void => {\n [data[indexA], data[indexB]] = [data[indexB], data[indexA]];\n};\n","export default <T>(fieldValues: T[], index: number, value: T) => {\n fieldValues[index] = value;\n return fieldValues;\n};\n","import React from 'react';\n\nimport generateId from './logic/generateId';\nimport getFocusFieldName from './logic/getFocusFieldName';\nimport getValidationModes from './logic/getValidationModes';\nimport isWatched from './logic/isWatched';\nimport iterateFieldsByAction from './logic/iterateFieldsByAction';\nimport updateFieldArrayRootError from './logic/updateFieldArrayRootError';\nimport validateField from './logic/validateField';\nimport appendAt from './utils/append';\nimport cloneObject from './utils/cloneObject';\nimport convertToArrayPayload from './utils/convertToArrayPayload';\nimport fillEmptyArray from './utils/fillEmptyArray';\nimport get from './utils/get';\nimport insertAt from './utils/insert';\nimport isEmptyObject from './utils/isEmptyObject';\nimport moveArrayAt from './utils/move';\nimport prependAt from './utils/prepend';\nimport removeArrayAt from './utils/remove';\nimport set from './utils/set';\nimport swapArrayAt from './utils/swap';\nimport unset from './utils/unset';\nimport updateAt from './utils/update';\nimport { VALIDATION_MODE } from './constants';\nimport type {\n Control,\n Field,\n FieldArray,\n FieldArrayMethodProps,\n FieldArrayPath,\n FieldArrayWithId,\n FieldErrors,\n FieldPath,\n FieldValues,\n FormState,\n InternalFieldName,\n RegisterOptions,\n UseFieldArrayProps,\n UseFieldArrayReturn,\n} from './types';\nimport { useFormContext } from './useFormContext';\nimport { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect';\n\n/**\n * A custom hook that exposes convenient methods to perform operations with a list of dynamic inputs that need to be appended, updated, removed etc. • [Demo](https://codesandbox.io/s/react-hook-form-usefieldarray-ssugn) • [Video](https://youtu.be/4MrbfGSFY2A)\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/usefieldarray) • [Demo](https://codesandbox.io/s/react-hook-form-usefieldarray-ssugn)\n *\n * @param props - useFieldArray props\n *\n * @returns methods - functions to manipulate with the Field Arrays (dynamic inputs) {@link UseFieldArrayReturn}\n *\n * @example\n * ```tsx\n * function App() {\n * const { register, control, handleSubmit, reset, trigger, setError } = useForm({\n * defaultValues: {\n * test: []\n * }\n * });\n * const { fields, append } = useFieldArray({\n * control,\n * name: \"test\"\n * });\n *\n * return (\n * <form onSubmit={handleSubmit(data => console.log(data))}>\n * {fields.map((item, index) => (\n * <input key={item.id} {...register(`test.${index}.firstName`)} />\n * ))}\n * <button type=\"button\" onClick={() => append({ firstName: \"bill\" })}>\n * append\n * </button>\n * <input type=\"submit\" />\n * </form>\n * );\n * }\n * ```\n */\nexport function useFieldArray<\n TFieldValues extends FieldValues = FieldValues,\n TFieldArrayName extends\n FieldArrayPath<TFieldValues> = FieldArrayPath<TFieldValues>,\n TKeyName extends string = 'id',\n TTransformedValues = TFieldValues,\n>(\n props: UseFieldArrayProps<\n TFieldValues,\n TFieldArrayName,\n TKeyName,\n TTransformedValues\n >,\n): UseFieldArrayReturn<TFieldValues, TFieldArrayName, TKeyName> {\n const methods = useFormContext();\n const {\n control = methods.control,\n name,\n keyName = 'id',\n shouldUnregister,\n rules,\n } = props;\n const [fields, setFields] = React.useState(control._getFieldArray(name));\n const ids = React.useRef<string[]>(\n control._getFieldArray(name).map(generateId),\n );\n\n const _actioned = React.useRef(false);\n\n control._names.array.add(name);\n\n React.useMemo(\n () =>\n rules &&\n fields.length >= 0 &&\n (control as Control<TFieldValues, any, TTransformedValues>).register(\n name as FieldPath<TFieldValues>,\n rules as RegisterOptions<TFieldValues>,\n ),\n [control, name, fields.length, rules],\n );\n\n useIsomorphicLayoutEffect(\n () =>\n control._subjects.array.subscribe({\n next: ({\n values,\n name: fieldArrayName,\n }: {\n values?: FieldValues;\n name?: InternalFieldName;\n }) => {\n if (fieldArrayName === name || !fieldArrayName) {\n const fieldValues = get(values, name);\n if (Array.isArray(fieldValues)) {\n setFields(fieldValues);\n ids.current = fieldValues.map(generateId);\n }\n }\n },\n }).unsubscribe,\n [control, name],\n );\n\n const updateValues = React.useCallback(\n <\n T extends Partial<\n FieldArrayWithId<TFieldValues, TFieldArrayName, TKeyName>\n >[],\n >(\n updatedFieldArrayValues: T,\n ) => {\n _actioned.current = true;\n control._setFieldArray(name, updatedFieldArrayValues);\n },\n [control, name],\n );\n\n const append = (\n value:\n | Partial<FieldArray<TFieldValues, TFieldArrayName>>\n | Partial<FieldArray<TFieldValues, TFieldArrayName>>[],\n options?: FieldArrayMethodProps,\n ) => {\n const appendValue = convertToArrayPayload(cloneObject(value));\n const updatedFieldArrayValues = appendAt(\n control._getFieldArray(name),\n appendValue,\n );\n control._names.focus = getFocusFieldName(\n name,\n updatedFieldArrayValues.length - 1,\n options,\n );\n ids.current = appendAt(ids.current, appendValue.map(generateId));\n updateValues(updatedFieldArrayValues);\n setFields(updatedFieldArrayValues);\n control._setFieldArray(name, updatedFieldArrayValues, appendAt, {\n argA: fillEmptyArray(value),\n });\n };\n\n const prepend = (\n value:\n | Partial<FieldArray<TFieldValues, TFieldArrayName>>\n | Partial<FieldArray<TFieldValues, TFieldArrayName>>[],\n options?: FieldArrayMethodProps,\n ) => {\n const prependValue = convertToArrayPayload(cloneObject(value));\n const updatedFieldArrayValues = prependAt(\n control._getFieldArray(name),\n prependValue,\n );\n control._names.focus = getFocusFieldName(name, 0, options);\n ids.current = prependAt(ids.current, prependValue.map(generateId));\n updateValues(updatedFieldArrayValues);\n setFields(updatedFieldArrayValues);\n control._setFieldArray(name, updatedFieldArrayValues, prependAt, {\n argA: fillEmptyArray(value),\n });\n };\n\n const remove = (index?: number | number[]) => {\n const updatedFieldArrayValues: Partial<\n FieldArrayWithId<TFieldValues, TFieldArrayName, TKeyName>\n >[] = removeArrayAt(control._getFieldArray(name), index);\n ids.current = removeArrayAt(ids.current, index);\n updateValues(updatedFieldArrayValues);\n setFields(updatedFieldArrayValues);\n !Array.isArray(get(control._fields, name)) &&\n set(control._fields, name, undefined);\n control._setFieldArray(name, updatedFieldArrayValues, removeArrayAt, {\n argA: index,\n });\n };\n\n const insert = (\n index: number,\n value:\n | Partial<FieldArray<TFieldValues, TFieldArrayName>>\n | Partial<FieldArray<TFieldValues, TFieldArrayName>>[],\n options?: FieldArrayMethodProps,\n ) => {\n const insertValue = convertToArrayPayload(cloneObject(value));\n const updatedFieldArrayValues = insertAt(\n control._getFieldArray(name),\n index,\n insertValue,\n );\n control._names.focus = getFocusFieldName(name, index, options);\n ids.current = insertAt(ids.current, index, insertValue.map(generateId));\n updateValues(updatedFieldArrayValues);\n setFields(updatedFieldArrayValues);\n control._setFieldArray(name, updatedFieldArrayValues, insertAt, {\n argA: index,\n argB: fillEmptyArray(value),\n });\n };\n\n const swap = (indexA: number, indexB: number) => {\n const updatedFieldArrayValues = control._getFieldArray(name);\n swapArrayAt(updatedFieldArrayValues, indexA, indexB);\n swapArrayAt(ids.current, indexA, indexB);\n updateValues(updatedFieldArrayValues);\n setFields(updatedFieldArrayValues);\n control._setFieldArray(\n name,\n updatedFieldArrayValues,\n swapArrayAt,\n {\n argA: indexA,\n argB: indexB,\n },\n false,\n );\n };\n\n const move = (from: number, to: number) => {\n const updatedFieldArrayValues = control._getFieldArray(name);\n moveArrayAt(updatedFieldArrayValues, from, to);\n moveArrayAt(ids.current, from, to);\n updateValues(updatedFieldArrayValues);\n setFields(updatedFieldArrayValues);\n control._setFieldArray(\n name,\n updatedFieldArrayValues,\n moveArrayAt,\n {\n argA: from,\n argB: to,\n },\n false,\n );\n };\n\n const update = (\n index: number,\n value: FieldArray<TFieldValues, TFieldArrayName>,\n ) => {\n const updateValue = cloneObject(value);\n const updatedFieldArrayValues = updateAt(\n control._getFieldArray<\n FieldArrayWithId<TFieldValues, TFieldArrayName, TKeyName>\n >(name),\n index,\n updateValue as FieldArrayWithId<TFieldValues, TFieldArrayName, TKeyName>,\n );\n ids.current = [...updatedFieldArrayValues].map((item, i) =>\n !item || i === index ? generateId() : ids.current[i],\n );\n updateValues(updatedFieldArrayValues);\n setFields([...updatedFieldArrayValues]);\n control._setFieldArray(\n name,\n updatedFieldArrayValues,\n updateAt,\n {\n argA: index,\n argB: updateValue,\n },\n true,\n false,\n );\n };\n\n const replace = (\n value:\n | Partial<FieldArray<TFieldValues, TFieldArrayName>>\n | Partial<FieldArray<TFieldValues, TFieldArrayName>>[],\n ) => {\n const updatedFieldArrayValues = convertToArrayPayload(cloneObject(value));\n ids.current = updatedFieldArrayValues.map(generateId);\n updateValues([...updatedFieldArrayValues]);\n setFields([...updatedFieldArrayValues]);\n control._setFieldArray(\n name,\n [...updatedFieldArrayValues],\n <T>(data: T): T => data,\n {},\n true,\n false,\n );\n };\n\n React.useEffect(() => {\n control._state.action = false;\n\n isWatched(name, control._names) &&\n control._subjects.state.next({\n ...control._formState,\n } as FormState<TFieldValues>);\n\n if (\n _actioned.current &&\n (!getValidationModes(control._options.mode).isOnSubmit ||\n control._formState.isSubmitted) &&\n !getValidationModes(control._options.reValidateMode).isOnSubmit\n ) {\n if (control._options.resolver) {\n control._runSchema([name]).then((result) => {\n const error = get(result.errors, name);\n const existingError = get(control._formState.errors, name);\n\n if (\n existingError\n ? (!error && existingError.type) ||\n (error &&\n (existingError.type !== error.type ||\n existingError.message !== error.message))\n : error && error.type\n ) {\n error\n ? set(control._formState.errors, name, error)\n : unset(control._formState.errors, name);\n control._subjects.state.next({\n errors: control._formState.errors as FieldErrors<TFieldValues>,\n });\n }\n });\n } else {\n const field: Field = get(control._fields, name);\n if (\n field &&\n field._f &&\n !(\n getValidationModes(control._options.reValidateMode).isOnSubmit &&\n getValidationModes(control._options.mode).isOnSubmit\n )\n ) {\n validateField(\n field,\n control._names.disabled,\n control._formValues,\n control._options.criteriaMode === VALIDATION_MODE.all,\n control._options.shouldUseNativeValidation,\n true,\n ).then(\n (error) =>\n !isEmptyObject(error) &&\n control._subjects.state.next({\n errors: updateFieldArrayRootError(\n control._formState.errors as FieldErrors<TFieldValues>,\n error,\n name,\n ) as FieldErrors<TFieldValues>,\n }),\n );\n }\n }\n }\n\n control._subjects.state.next({\n name,\n values: cloneObject(control._formValues) as TFieldValues,\n });\n\n control._names.focus &&\n iterateFieldsByAction(control._fields, (ref, key: string) => {\n if (\n control._names.focus &&\n key.startsWith(control._names.focus) &&\n ref.focus\n ) {\n ref.focus();\n return 1;\n }\n return;\n });\n\n control._names.focus = '';\n\n control._setValid();\n _actioned.current = false;\n }, [fields, name, control]);\n\n React.useEffect(() => {\n !get(control._formValues, name) && control._setFieldArray(name);\n\n return () => {\n const updateMounted = (name: InternalFieldName, value: boolean) => {\n const field: Field = get(control._fields, name);\n if (field && field._f) {\n field._f.mount = value;\n }\n };\n\n control._options.shouldUnregister || shouldUnregister\n ? control.unregister(name as FieldPath<TFieldValues>)\n : updateMounted(name, false);\n };\n }, [name, control, keyName, shouldUnregister]);\n\n return {\n swap: React.useCallback(swap, [updateValues, name, control]),\n move: React.useCallback(move, [updateValues, name, control]),\n prepend: React.useCallback(prepend, [updateValues, name, control]),\n append: React.useCallback(append, [updateValues, name, control]),\n remove: React.useCallback(remove, [updateValues, name, control]),\n insert: React.useCallback(insert, [updateValues, name, control]),\n update: React.useCallback(update, [updateValues, name, control]),\n replace: React.useCallback(replace, [updateValues, name, control]),\n fields: React.useMemo(\n () =>\n fields.map((field, index) => ({\n ...field,\n [keyName]: ids.current[index] || generateId(),\n })) as FieldArrayWithId<TFieldValues, TFieldArrayName, TKeyName>[],\n [fields, keyName],\n ),\n };\n}\n","import React from 'react';\n\nimport getProxyFormState from './logic/getProxyFormState';\nimport deepEqual from './utils/deepEqual';\nimport isFunction from './utils/isFunction';\nimport { createFormControl } from './logic';\nimport type {\n FieldValues,\n FormState,\n UseFormProps,\n UseFormReturn,\n} from './types';\nimport { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect';\n\n/**\n * Custom hook to manage the entire form.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform) • [Demo](https://codesandbox.io/s/react-hook-form-get-started-ts-5ksmm) • [Video](https://www.youtube.com/watch?v=RkXv4AXXC_4)\n *\n * @param props - form configuration and validation parameters.\n *\n * @returns methods - individual functions to manage the form state. {@link UseFormReturn}\n *\n * @example\n * ```tsx\n * function App() {\n * const { register, handleSubmit, watch, formState: { errors } } = useForm();\n * const onSubmit = data => console.log(data);\n *\n * console.log(watch(\"example\"));\n *\n * return (\n * <form onSubmit={handleSubmit(onSubmit)}>\n * <input defaultValue=\"test\" {...register(\"example\")} />\n * <input {...register(\"exampleRequired\", { required: true })} />\n * {errors.exampleRequired && <span>This field is required</span>}\n * <button>Submit</button>\n * </form>\n * );\n * }\n * ```\n */\nexport function useForm<\n TFieldValues extends FieldValues = FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n>(\n props: UseFormProps<TFieldValues, TContext, TTransformedValues> = {},\n): UseFormReturn<TFieldValues, TContext, TTransformedValues> {\n const _formControl = React.useRef<\n UseFormReturn<TFieldValues, TContext, TTransformedValues> | undefined\n >(undefined);\n const _values = React.useRef<typeof props.values>(undefined);\n const [formState, updateFormState] = React.useState<FormState<TFieldValues>>({\n isDirty: false,\n isValidating: false,\n isLoading: isFunction(props.defaultValues),\n isSubmitted: false,\n isSubmitting: false,\n isSubmitSuccessful: false,\n isValid: false,\n submitCount: 0,\n dirtyFields: {},\n touchedFields: {},\n validatingFields: {},\n errors: props.errors || {},\n disabled: props.disabled || false,\n isReady: false,\n defaultValues: isFunction(props.defaultValues)\n ? undefined\n : props.defaultValues,\n });\n\n if (!_formControl.current) {\n if (props.formControl) {\n _formControl.current = {\n ...props.formControl,\n formState,\n };\n\n if (props.defaultValues && !isFunction(props.defaultValues)) {\n props.formControl.reset(props.defaultValues, props.resetOptions);\n }\n } else {\n const { formControl, ...rest } = createFormControl(props);\n\n _formControl.current = {\n ...rest,\n formState,\n };\n }\n }\n\n const control = _formControl.current.control;\n control._options = props;\n\n useIsomorphicLayoutEffect(() => {\n const sub = control._subscribe({\n formState: control._proxyFormState,\n callback: () => updateFormState({ ...control._formState }),\n reRenderRoot: true,\n });\n\n updateFormState((data) => ({\n ...data,\n isReady: true,\n }));\n\n control._formState.isReady = true;\n\n return sub;\n }, [control]);\n\n React.useEffect(\n () => control._disableForm(props.disabled),\n [control, props.disabled],\n );\n\n React.useEffect(() => {\n if (props.mode) {\n control._options.mode = props.mode;\n }\n if (props.reValidateMode) {\n control._options.reValidateMode = props.reValidateMode;\n }\n }, [control, props.mode, props.reValidateMode]);\n\n React.useEffect(() => {\n if (props.errors) {\n control._setErrors(props.errors);\n control._focusError();\n }\n }, [control, props.errors]);\n\n React.useEffect(() => {\n props.shouldUnregister &&\n control._subjects.state.next({\n values: control._getWatch(),\n });\n }, [control, props.shouldUnregister]);\n\n React.useEffect(() => {\n if (control._proxyFormState.isDirty) {\n const isDirty = control._getDirty();\n if (isDirty !== formState.isDirty) {\n control._subjects.state.next({\n isDirty,\n });\n }\n }\n }, [control, formState.isDirty]);\n\n React.useEffect(() => {\n if (props.values && !deepEqual(props.values, _values.current)) {\n control._reset(props.values, {\n keepFieldsRef: true,\n ...control._options.resetOptions,\n });\n if (!control._options.resetOptions?.keepIsValid) {\n control._setValid();\n }\n _values.current = props.values;\n updateFormState((state) => ({ ...state }));\n } else {\n control._resetDefaultValues();\n }\n }, [control, props.values]);\n\n React.useEffect(() => {\n if (!control._state.mount) {\n control._setValid();\n control._state.mount = true;\n }\n\n if (control._state.watch) {\n control._state.watch = false;\n control._subjects.state.next({ ...control._formState });\n }\n\n control._removeUnmounted();\n });\n\n _formControl.current.formState = getProxyFormState(formState, control);\n\n return _formControl.current;\n}\n","import { type ReactNode } from 'react';\n\nimport type { Control, FieldPath, FieldPathValue, FieldValues } from './types';\nimport { useWatch } from './useWatch';\n\ntype GetValues<\n TFieldValues extends FieldValues,\n TFieldNames extends readonly FieldPath<TFieldValues>[] = readonly [],\n> = TFieldNames extends readonly [\n infer Name extends FieldPath<TFieldValues>,\n ...infer RestFieldNames,\n]\n ? RestFieldNames extends readonly FieldPath<TFieldValues>[]\n ? readonly [\n FieldPathValue<TFieldValues, Name>,\n ...GetValues<TFieldValues, RestFieldNames>,\n ]\n : never\n : TFieldNames extends readonly [infer Name extends FieldPath<TFieldValues>]\n ? readonly [FieldPathValue<TFieldValues, Name>]\n : TFieldNames extends readonly []\n ? readonly []\n : never;\n\nexport type WatchProps<\n TFieldNames extends readonly FieldPath<TFieldValues>[],\n TFieldValues extends FieldValues = FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n> = {\n control: Control<TFieldValues, TContext, TTransformedValues>;\n names: TFieldNames;\n render: (values: GetValues<TFieldValues, TFieldNames>) => ReactNode;\n};\n\n/**\n * Watch component that subscribes to form field changes and re-renders when watched fields update.\n *\n * @param control - The form control object from useForm\n * @param names - Array of field names to watch for changes\n * @param render - The function that receives watched values and returns ReactNode\n * @returns The result of calling render function with watched values\n *\n * @example\n * The `Watch` component only re-render when the values of `foo`, `bar`, and `baz.qux` change.\n * The types of `foo`, `bar`, and `baz.qux` are precisely inferred.\n *\n * ```tsx\n * const { control } = useForm();\n *\n * <Watch\n * control={control}\n * names={['foo', 'bar', 'baz.qux']}\n * render={([foo, bar, baz_qux]) => <div>{foo}{bar}{baz_qux}</div>}\n * />\n * ```\n */\nexport const Watch = <\n const TFieldNames extends readonly FieldPath<TFieldValues>[],\n TFieldValues extends FieldValues = FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n>({\n control,\n names,\n render,\n}: WatchProps<TFieldNames, TFieldValues, TContext, TTransformedValues>) =>\n render(\n useWatch({ control, name: names }) as GetValues<TFieldValues, TFieldNames>,\n );\n","import { CamelToPascal } from './utility-types';\n\n/**\n * Converts string to kebab case\n *\n * @param {string} string\n * @returns {string} A kebabized string\n */\nexport const toKebabCase = (string: string) =>\n string.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n\n/**\n * Converts string to camel case\n *\n * @param {string} string\n * @returns {string} A camelized string\n */\nexport const toCamelCase = <T extends string>(string: T) =>\n string.replace(/^([A-Z])|[\\s-_]+(\\w)/g, (match, p1, p2) =>\n p2 ? p2.toUpperCase() : p1.toLowerCase(),\n );\n\n/**\n * Converts string to pascal case\n *\n * @param {string} string\n * @returns {string} A pascalized string\n */\nexport const toPascalCase = <T extends string>(string: T): CamelToPascal<T> => {\n const camelCase = toCamelCase(string);\n\n return (camelCase.charAt(0).toUpperCase() + camelCase.slice(1)) as CamelToPascal<T>;\n};\n\n/**\n * Merges classes into a single string\n *\n * @param {array} classes\n * @returns {string} A string of classes\n */\nexport const mergeClasses = <ClassType = string | undefined | null>(...classes: ClassType[]) =>\n classes\n .filter((className, index, array) => {\n return (\n Boolean(className) &&\n (className as string).trim() !== '' &&\n array.indexOf(className) === index\n );\n })\n .join(' ')\n .trim();\n\n/**\n * Is empty string\n *\n * @param {unknown} value\n * @returns {boolean} Whether the value is an empty string\n */\nexport const isEmptyString = (value: unknown): boolean => value === '';\n\n/**\n * Check if a component has an accessibility prop\n *\n * @param {object} props\n * @returns {boolean} Whether the component has an accessibility prop\n */\nexport const hasA11yProp = (props: Record<string, any>) => {\n for (const prop in props) {\n if (prop.startsWith('aria-') || prop === 'role' || prop === 'title') {\n return true;\n }\n }\n};\n","export default {\n xmlns: 'http://www.w3.org/2000/svg',\n width: 24,\n height: 24,\n viewBox: '0 0 24 24',\n fill: 'none',\n stroke: 'currentColor',\n strokeWidth: 2,\n strokeLinecap: 'round',\n strokeLinejoin: 'round',\n};\n","import { createElement, forwardRef } from 'react';\nimport defaultAttributes from './defaultAttributes';\nimport { IconNode, LucideProps } from './types';\nimport { mergeClasses, hasA11yProp } from '@lucide/shared';\n\ninterface IconComponentProps extends LucideProps {\n iconNode: IconNode;\n}\n\n/**\n * Lucide icon component\n *\n * @component Icon\n * @param {object} props\n * @param {string} props.color - The color of the icon\n * @param {number} props.size - The size of the icon\n * @param {number} props.strokeWidth - The stroke width of the icon\n * @param {boolean} props.absoluteStrokeWidth - Whether to use absolute stroke width\n * @param {string} props.className - The class name of the icon\n * @param {IconNode} props.children - The children of the icon\n * @param {IconNode} props.iconNode - The icon node of the icon\n *\n * @returns {ForwardRefExoticComponent} LucideIcon\n */\nconst Icon = forwardRef<SVGSVGElement, IconComponentProps>(\n (\n {\n color = 'currentColor',\n size = 24,\n strokeWidth = 2,\n absoluteStrokeWidth,\n className = '',\n children,\n iconNode,\n ...rest\n },\n ref,\n ) =>\n createElement(\n 'svg',\n {\n ref,\n ...defaultAttributes,\n width: size,\n height: size,\n stroke: color,\n strokeWidth: absoluteStrokeWidth ? (Number(strokeWidth) * 24) / Number(size) : strokeWidth,\n className: mergeClasses('lucide', className),\n ...(!children && !hasA11yProp(rest) && { 'aria-hidden': 'true' }),\n ...rest,\n },\n [\n ...iconNode.map(([tag, attrs]) => createElement(tag, attrs)),\n ...(Array.isArray(children) ? children : [children]),\n ],\n ),\n);\n\nexport default Icon;\n","import { createElement, forwardRef } from 'react';\nimport { mergeClasses, toKebabCase, toPascalCase } from '@lucide/shared';\nimport { IconNode, LucideProps } from './types';\nimport Icon from './Icon';\n\n/**\n * Create a Lucide icon component\n * @param {string} iconName\n * @param {array} iconNode\n * @returns {ForwardRefExoticComponent} LucideIcon\n */\nconst createLucideIcon = (iconName: string, iconNode: IconNode) => {\n const Component = forwardRef<SVGSVGElement, LucideProps>(({ className, ...props }, ref) =>\n createElement(Icon, {\n ref,\n iconNode,\n className: mergeClasses(\n `lucide-${toKebabCase(toPascalCase(iconName))}`,\n `lucide-${iconName}`,\n className,\n ),\n ...props,\n }),\n );\n\n Component.displayName = toPascalCase(iconName);\n\n return Component;\n};\n\nexport default createLucideIcon;\n","import createLucideIcon from '../createLucideIcon';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [\n ['path', { d: 'M5 12h14', key: '1ays0h' }],\n ['path', { d: 'M12 5v14', key: 's699le' }],\n];\n\n/**\n * @component @name Plus\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNNSAxMmgxNCIgLz4KICA8cGF0aCBkPSJNMTIgNXYxNCIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/plus\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst Plus = createLucideIcon('plus', __iconNode);\n\nexport default Plus;\n","import { Line } from \"@assets/icons/customer-view-icon\";\nimport { IcSetting } from \"@assets/icons/kanban-icon\";\nimport OpenSessionModal from \"@components/session-management/open-shift\";\nimport { QUERY_KEYS } from \"@constants/query.constant\";\nimport { POSPath } from \"@constants/routes.constants\";\nimport { dd_mm_yyyy, hh_mm } from \"@utils/functions\";\nimport { t } from \"i18next\";\nimport { Plus } from \"lucide-react\";\nimport { useMemo, useState } from \"react\";\nimport { useForm } from \"react-hook-form\";\nimport { createSearchParams, useNavigate } from \"react-router-dom\";\n\nconst PosTemplate = ({\n row,\n columns,\n onClickRow,\n settings_act_id,\n res_model,\n}: {\n row: any;\n columns: any;\n onClickRow: any;\n settings_act_id?: number;\n res_model?: string;\n}) => {\n const opened =\n row[\"pos_session_state\"] === \"opened\" ||\n row[\"pos_session_state\"] === \"closing_control\";\n const navigate = useNavigate();\n const [openModal, setOpenModal] = useState(false);\n const methods = useForm({\n mode: \"onBlur\",\n });\n const date: Date = useMemo(\n () => new Date(row[\"last_session_closing_date\"]),\n [row]\n );\n\n const navigateToPosManagement = () => {\n const isModePosRestaurant = row[\"module_pos_restaurant\"];\n const sessionId = row[\"current_session_id\"].id;\n const posId = row[\"id\"];\n const query = createSearchParams({\n [QUERY_KEYS.POS_ID]: posId,\n [QUERY_KEYS.SESSION_ID]: sessionId,\n })?.toString();\n sessionStorage.setItem(\n \"enter_pincode\",\n window.location.href.split(\"console\")[1]\n );\n localStorage.setItem(\"backUrl\", window.location.href.split(\"console\")[1]);\n navigate(\n `${isModePosRestaurant ? POSPath.TABLES : POSPath.MENUS}?${query}`\n );\n };\n\n const navigateSettingManagement = async (e: any) => {\n e.stopPropagation();\n navigateSettingManagement({\n aid: settings_act_id,\n id: row?.id,\n model: res_model,\n });\n };\n\n return (\n <>\n <div\n className=\"relative w-full p-4 border border-[--stroke-default] bg-white rounded-xl shadow-sm flex flex-col overflow-hidden min-h-[200px]\"\n onClick={() => onClickRow(columns, row)}\n >\n <div className=\"flex items-start justify-between\">\n <div className=\"flex space-x-2\">\n <img\n src=\"/assets/images/cashier.svg\"\n alt=\"POS Icon\"\n className=\"size-12\"\n />\n <p className=\"text-base text-[#0E121B] font-semibold\">\n {row[\"name\"]}\n </p>\n </div>\n <span\n className={`px-3 py-1 rounded-[4px] text-xs font-medium border ${\n opened\n ? \"bg-[#E0FAEB] text-[#12AF53] border-[#1FC163]\"\n : \"bg-[#FFEBEC] text-[#E93544] border-[#FB2B3D]\"\n }`}\n >\n {opened ? t(\"opening\") : t(\"closed\")}\n </span>\n </div>\n\n <div className=\"relative py-4\">\n <Line />\n </div>\n\n <div className=\"text-sm space-y-2 mt-3 flex-grow\">\n {row[\"last_session_closing_date\"] && (\n <div className=\"flex justify-between\">\n <span className=\"text-gray-500\">\n {\" \"}\n {opened ? t(\"opening\") : t(\"closed\")}\n </span>\n <span className=\"font-medium text-[#0E121B]\">\n {hh_mm(date)} • {dd_mm_yyyy(date)}\n </span>\n </div>\n )}\n\n {opened && (\n <div className=\"flex justify-between\">\n <span className=\"text-gray-500\">{t(\"balance\")}</span>\n <span className=\"font-medium text-[#0E121B]\">\n {row[\"last_session_closing_cash\"].toLocaleString(\"vi-VN\")}đ\n </span>\n </div>\n )}\n </div>\n\n <div className=\"flex justify-end mt-auto pt-4 gap-[10px]\">\n <button\n onClick={async (e) => {\n navigateSettingManagement(e);\n }}\n type=\"button\"\n className=\"button-secondary flex gap-2 items-center\"\n >\n <IcSetting />\n <span>{t(\"setting\")}</span>\n </button>\n {opened ? (\n <button\n onClick={(e) => {\n e.stopPropagation();\n navigateToPosManagement();\n }}\n className=\"button-primary\"\n >\n {t(\"continue_selling\")}\n </button>\n ) : (\n <button\n onClick={(e) => {\n e.stopPropagation();\n setOpenModal(true);\n }}\n className=\"button-primary min-w-[150px] flex gap-2 items-center justify-center\"\n >\n <Plus className=\"w-4 h-4\" />\n {t(\"open_session\")}\n </button>\n )}\n </div>\n </div>\n\n {openModal && (\n <OpenSessionModal\n openModal={openModal}\n setOpenModal={setOpenModal}\n methods={methods}\n row={row}\n record={row}\n />\n )}\n </>\n );\n};\n\nexport default PosTemplate;\n"],"mappings":"k2CAAA,IAAAA,GAAAC,GAAA,CAAAC,GAAAC,KAAA,CAKAA,GAAO,QAAU,CACf,KAAQ,GACR,KAAQ,GACR,GAAM,GACN,IAAO,GACP,MAAS,GACT,GAAM,GACN,IAAO,GACP,MAAS,GACT,KAAQ,GACR,KAAQ,GACR,MAAS,GACT,OAAU,GACV,MAAS,GACT,IAAO,EACT,ICpBA,IAAAC,GAAA,GAAAC,GAAAD,GAAA,eAAAE,GAAA,oBAAAC,GAAA,qBAAAC,GAAA,qBAAAC,GAAA,gBAAAC,KAAA,eAAAC,GAAAP,ICQI,IAAAQ,GAAA,6BAOG,IAAMC,GAAU,CAAC,CAAE,UAAAC,EAAY,EAAG,OAErC,QAAC,OACC,MAAM,KACN,OAAO,KACP,QAAQ,YACR,KAAK,OACL,MAAM,6BACN,UAAWA,EAEX,oBAAC,QACC,EAAE,oNACF,KAAK,eACP,EACF,EA8JG,IAAMC,GAAS,OAElB,SAAC,OACC,MAAM,KACN,OAAO,KACP,QAAQ,YACR,KAAK,OACL,MAAM,6BAEN,qBAAC,QACC,EAAE,weACF,KAAK,UACP,KACA,QAAC,QACC,EAAE,wmBACF,KAAK,UACP,GACF,ECnME,IAAAC,GAAA,6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K,UAAU,6BACb,UAAAE,GAAMd,CAAI,EAAE,WAAIe,GAAWf,CAAI,GAClC,GACF,EAGDP,MACC,SAAC,OAAI,UAAU,uBACb,qBAAC,QAAK,UAAU,gBAAiB,SAAAmB,GAAE,SAAS,EAAE,KAC9C,SAAC,QAAK,UAAU,6BACb,UAAAxB,EAAI,0BAA6B,eAAe,OAAO,EAAE,UAC5D,GACF,GAEJ,KAEA,SAAC,OAAI,UAAU,2CACb,sBAAC,UACC,QAAgBsB,GAAMC,GAAA,sBACpBF,EAA0BC,CAAC,CAC7B,GACA,KAAK,SACL,UAAU,2CAEV,qBAACM,GAAA,EAAU,KACX,QAAC,QAAM,SAAAJ,GAAE,SAAS,EAAE,GACtB,EACCnB,KACC,QAAC,UACC,QAAUiB,GAAM,CACdA,EAAE,gBAAgB,EAClBT,EAAwB,CAC1B,EACA,UAAU,iBAET,SAAAW,GAAE,kBAAkB,EACvB,KAEA,SAAC,UACC,QAAUF,GAAM,CACdA,EAAE,gBAAgB,EAClBb,EAAa,EAAI,CACnB,EACA,UAAU,sEAEV,qBAACoB,GAAA,CAAK,UAAU,UAAU,EACzBL,GAAE,cAAc,GACnB,GAEJ,GACF,EAEChB,MACC,QAACsB,GAAA,CACC,UAAWtB,EACX,aAAcC,EACd,QAASC,EACT,IAAKV,EACL,OAAQA,EACV,GAEJ,CAEJ,EAEO+B,GAAQhC","names":["require_void_elements","__commonJSMin","exports","module","index_exports","__export","menu_link_default","kitchen_template_default","open_shift_default","pos_order_template_default","pos_template_default","__toCommonJS","import_jsx_runtime","IcClose","className","IcCopy","import_jsx_runtime","IcQR","IcCheck","className","import_widget","import_react","__defProp","__getOwnPropSymbols","__hasOwnProp","__propIsEnum","__defNormalProp","obj","key","value","__spreadValues","a","b","prop","__objRest","source","exclude","target","qrcodegen","qrcodegen2","_QrCode","version","errorCorrectionLevel","dataCodewords","msk","row","i","allCodewords","minPenalty","penalty","assert","text","ecl","segs","data","seg","minVersion","maxVersion","mask","boostEcl","dataUsedBits","dataCapacityBits2","usedBits","QrSegment","newEcl","bb","appendBits","dataCapacityBits","padByte","x","y","alignPatPos","numAlign","j","rem","bits","getBit","color","dy","dx","dist","xx","yy","isDark","ver","numBlocks","blockEccLen","rawCodewords","numShortBlocks","shortBlockLen","blocks","rsDiv","k","dat","ecc","result","block","right","vert","invert","runColor","runX","runHistory","runY","dark","sum","total","step","pos","degree","root","divisor","_","factor","coef","z","n","core","currentRunColor","currentRunLength","QrCode","val","len","cond","_QrSegment","mode","numChars","bitData","digits","temp","assignVal","ccbits","str","QrCode2","_Ecc","ordinal","formatBits","Ecc","QrSegment2","_Mode","modeBits","numBitsCharCount","Mode","qrcodegen_default","ERROR_LEVEL_MAP","DEFAULT_SIZE","DEFAULT_LEVEL","DEFAULT_BGCOLOR","DEFAULT_FGCOLOR","DEFAULT_INCLUDEMARGIN","DEFAULT_MINVERSION","SPEC_MARGIN_SIZE","DEFAULT_MARGIN_SIZE","DEFAULT_IMG_SCALE","generatePath","modules","margin","ops","start","cell","excavateModules","excavation","getImageSettings","cells","size","imageSettings","numCells","defaultSize","scale","w","h","opacity","floorX","floorY","ceilW","ceilH","crossOrigin","getMarginSize","includeMargin","marginSize","useQRCode","level","boostLevel","qrcode","React","segments","accum","v","calculatedImageSettings","cells2","margin2","numCells2","calculatedImageSettings2","SUPPORTS_PATH2D","QRCodeCanvas","props","forwardedRef","_a","bgColor","fgColor","_b","style","otherProps","imgSrc","_canvas","_image","setCanvasRef","node","isImgLoaded","setIsImageLoaded","canvas","ctx","cellsToDraw","image","haveImageToRender","pixelRatio","rdx","cdx","canvasStyle","img","QRCodeSVG","title","fgPath","import_react","import_react","import_react","warn","i18n","code","msg","rest","_a","_b","_c","_d","args","__spreadValues","isString","alreadyWarned","warnOnce","loadedClb","cb","initialized","loadNamespaces","ns","loadLanguages","lng","n","hasLoadedNamespace","options","i18nInstance","loadNotPending","isString","obj","isObject","matchHtmlEntity","htmlEntities","unescapeHtmlEntity","m","unescape","text","defaultOptions","unescape","getDefaults","defaultOptions","i18nInstance","getI18n","i18nInstance","import_react","I18nContext","ReportNamespaces","namespaces","ns","import_react","usePrevious","value","ignore","ref","alwaysNewT","i18n","language","namespace","keyPrefix","useMemoizedT","useTranslation","ns","props","_a","_b","_c","_d","i18nFromProps","i18nFromContext","defaultNSFromContext","I18nContext","getI18n","ReportNamespaces","warnOnce","notReadyT","k","optsOrDefaultValue","isString","isObject","retNotReady","i18nOptions","__spreadValues","getDefaults","useSuspense","namespaces","ready","n","hasLoadedNamespace","memoGetT","getT","getNewT","t","setT","joinedNS","previousJoinedNS","isMounted","bindI18n","bindI18nStore","loadLanguages","loadNamespaces","boundReset","e","ret","resolve","import_react","import_react","import_react","import_react","r","f","n","clsx","import_tailwind_merge","cn","inputs","clsx","formatCurrency","value","hh_mm","date","value","hours","minutes","dd_mm_yyyy","day","month","year","formatOrderPrice","price","import_jsx_runtime","import_react","import_react","LayoutGroupContext","import_react","useConstant","init","ref","import_react","isBrowser","useIsomorphicLayoutEffect","isBrowser","import_jsx_runtime","React","import_react","import_react","PresenceContext","import_jsx_runtime","addUniqueItem","arr","item","removeItem","index","clamp","min","max","v","formatErrorMessage","message","errorCode","warning","invariant","check","message","errorCode","formatErrorMessage","MotionGlobalConfig","isNumericalString","v","isObject","value","isZeroValueString","v","memo","callback","result","noop","any","combineFunctions","a","b","v","pipe","transformers","progress","from","to","value","toFromDifference","SubscriptionManager","handler","addUniqueItem","removeItem","a","b","c","numSubscriptions","i","secondsToMilliseconds","seconds","millisecondsToSeconds","milliseconds","velocityPerSecond","velocity","frameDuration","warned","warnOnce","condition","message","errorCode","warned","formatErrorMessage","calcBezier","t","a1","a2","subdivisionPrecision","subdivisionMaxIterations","binarySubdivide","x","lowerBound","upperBound","mX1","mX2","currentX","currentT","cubicBezier","mY1","mY2","noop","getTForX","aX","mirrorEasing","easing","p","reverseEasing","easing","p","backOut","cubicBezier","backIn","reverseEasing","backInOut","mirrorEasing","anticipate","p","backIn","circIn","p","circOut","reverseEasing","circInOut","mirrorEasing","easeIn","cubicBezier","easeOut","easeInOut","isEasingArray","ease","isBezierDefinition","easing","easingLookup","noop","easeIn","easeInOut","easeOut","circIn","circInOut","circOut","backIn","backInOut","backOut","anticipate","isValidEasing","easing","easingDefinitionToFunction","definition","isBezierDefinition","invariant","x1","y1","x2","y2","cubicBezier","stepsOrder","statsBuffer","createRenderStep","runNextFrame","stepName","thisFrame","nextFrame","isProcessing","flushNextFrame","toKeepAlive","latestFrameData","numCalls","triggerCallback","callback","step","keepAlive","immediate","queue","frameData","statsBuffer","maxElapsed","createRenderBatcher","scheduleNextBatch","allowKeepAlive","runNextFrame","useDefaultElapsed","state","flagRunNextFrame","steps","stepsOrder","acc","key","createRenderStep","setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender","processBatch","timestamp","MotionGlobalConfig","wake","step","process","keepAlive","immediate","i","frame","cancelFrame","frameData","frameSteps","createRenderBatcher","noop","now","clearTime","time","frameData","MotionGlobalConfig","newTime","activeAnimations","checkStringStartsWith","token","key","isCSSVariableName","startsAsVariableToken","isCSSVariableToken","value","singleCssVariableRegex","number","v","alpha","__spreadProps","__spreadValues","clamp","scale","sanitize","v","floatRegex","isNullish","v","singleColorRegex","isColorString","type","testProp","v","singleColorRegex","isNullish","splitColor","aName","bName","cName","a","b","c","alpha","floatRegex","clampRgbUnit","v","clamp","rgbUnit","__spreadProps","__spreadValues","number","rgba","isColorString","splitColor","red","green","blue","alpha$1","sanitize","alpha","parseHex","v","r","g","b","a","hex","isColorString","rgba","createUnitType","unit","v","degrees","percent","px","vh","vw","progressPercentage","__spreadProps","__spreadValues","hsla","isColorString","splitColor","hue","saturation","lightness","alpha$1","percent","sanitize","alpha","color","v","rgba","hex","hsla","parsed","colorRegex","test","v","_a","_b","floatRegex","colorRegex","NUMBER_TOKEN","COLOR_TOKEN","VAR_TOKEN","VAR_FUNCTION_TOKEN","SPLIT_TOKEN","complexRegex","analyseComplexValue","value","originalValue","values","indexes","types","i","split","parsedValue","color","parseComplexValue","createTransformer","source","numSections","output","type","sanitize","convertNumbersToZero","getAnimatableNone","parsed","complex","hueToRgb","p","q","t","hslaToRgba","hue","saturation","lightness","alpha","red","green","blue","mixImmediate","a","b","p","mixNumber","from","to","progress","mixLinearColor","from","to","v","fromExpo","expo","colorTypes","hex","rgba","hsla","getColorType","type","asRGBA","color","warning","model","hslaToRgba","mixColor","fromRGBA","toRGBA","mixImmediate","blended","__spreadValues","mixNumber","invisibleValues","mixVisibility","origin","target","p","mixNumber","a","b","p","getMixer","isCSSVariableToken","mixImmediate","color","mixColor","mixComplex","mixArray","mixObject","output","numValues","blendValue","v","i","__spreadValues","key","matchOrder","origin","target","_a","orderedOrigin","pointers","type","originIndex","originValue","template","complex","originStats","analyseComplexValue","targetStats","invisibleValues","mixVisibility","pipe","warning","mix","from","to","p","mixNumber","getMixer","frameloopDriver","update","passTimestamp","timestamp","keepAlive","frame","cancelFrame","frameData","time","generateLinearEasing","easing","duration","resolution","points","numPoints","i","calcGeneratorDuration","generator","duration","timeStep","state","createGeneratorEasing","options","scale","createGenerator","generator","__spreadProps","__spreadValues","duration","calcGeneratorDuration","progress","millisecondsToSeconds","velocitySampleDuration","calcGeneratorVelocity","resolveValue","current","prevT","velocityPerSecond","springDefaults","safeMin","findSpring","duration","springDefaults","bounce","velocity","mass","envelope","derivative","warning","secondsToMilliseconds","dampingRatio","clamp","millisecondsToSeconds","undampedFreq","exponentialDecay","delta","a","b","calcAngularFreq","c","d","e","f","initialGuess","approximateRoot","stiffness","rootIterations","result","i","durationKeys","physicsKeys","isSpringType","options","keys","key","getSpringOptions","springOptions","__spreadValues","springDefaults","visualDuration","root","stiffness","damping","clamp","__spreadProps","derived","findSpring","spring","optionsOrVisualDuration","bounce","restSpeed","restDelta","origin","target","state","mass","duration","velocity","isResolvedFromDuration","millisecondsToSeconds","initialVelocity","dampingRatio","initialDelta","undampedAngularFreq","isGranularScale","resolveSpring","angularFreq","calcAngularFreq","t","envelope","dampedAngularFreq","freqForT","generator","current","currentVelocity","secondsToMilliseconds","calcGeneratorVelocity","isBelowVelocityThreshold","isBelowDisplacementThreshold","calculatedDuration","calcGeneratorDuration","easing","generateLinearEasing","progress","generatorOptions","createGeneratorEasing","inertia","keyframes","velocity","power","timeConstant","bounceDamping","bounceStiffness","modifyTarget","min","max","restDelta","restSpeed","origin","state","isOutOfBounds","v","nearestBoundary","amplitude","ideal","target","calcDelta","t","calcLatest","applyFriction","delta","latest","timeReachedBoundary","spring$1","checkCatchBoundary","spring","calcGeneratorVelocity","hasUpdatedFrame","createMixers","output","ease","customMixer","mixers","mixerFactory","MotionGlobalConfig","mix","numMixers","i","mixer","easingFunction","noop","pipe","interpolate","input","isClamp","inputLength","invariant","isZeroDeltaRange","interpolator","v","progressInRange","progress","clamp","fillOffset","offset","remaining","min","i","offsetProgress","progress","mixNumber","defaultOffset","arr","offset","fillOffset","convertOffsetToTimes","offset","duration","o","defaultEasing","values","easing","easeInOut","keyframes","duration","keyframeValues","times","ease","easingFunctions","isEasingArray","easingDefinitionToFunction","state","absoluteTimes","convertOffsetToTimes","defaultOffset","mapTimeToKeyframe","interpolate","t","isNotNull","value","getFinalKeyframe","keyframes","repeat","repeatType","finalKeyframe","speed","resolvedKeyframes","index","transitionTypeMap","inertia","keyframes","spring","replaceTransitionType","transition","WithPromise","resolve","onResolve","onReject","percentToProgress","percent","JSAnimation","WithPromise","options","_a","_b","motionValue","time","activeAnimations","replaceTransitionType","type","keyframes","repeat","repeatDelay","repeatType","velocity","keyframes$1","generatorFactory","invariant","pipe","mix","generator","__spreadProps","__spreadValues","calcGeneratorDuration","calculatedDuration","timestamp","animationTime","sample","totalDuration","mixKeyframes","mirroredGenerator","resolvedDuration","delay","onUpdate","finalKeyframe","timeWithoutDelay","isInDelayPhase","elapsed","frameGenerator","progress","currentIteration","iterationProgress","clamp","state","done","isAnimationFinished","inertia","getFinalKeyframe","resolve","reject","millisecondsToSeconds","newTime","secondsToMilliseconds","newSpeed","hasChanged","driver","frameloopDriver","startTime","now","sampleTime","timeline","fillWildcards","keyframes","_a","i","radToDeg","rad","rotate","v","angle","rebaseAngle","matrix2dParsers","rotateZ","scaleX","scaleY","matrix3dParsers","defaultTransformValue","name","parseValueFromTransform","transform","matrix3dMatch","parsers","match","matrix2dMatch","valueParser","values","convertTransformToNumber","readTransformValue","instance","value","transformPropOrder","transformProps","isNumOrPxType","v","number","px","transformKeys","nonTranslationalTransformKeys","transformPropOrder","key","removeNonTranslationalTransform","visualElement","removedTransforms","value","positionalValues","x","paddingLeft","paddingRight","y","paddingTop","paddingBottom","_bbox","top","left","transform","parseValueFromTransform","toResolve","isScheduled","anyNeedsMeasurement","isForced","measureAllKeyframes","resolversToMeasure","resolver","elementsToMeasure","transformsToRestore","element","removedTransforms","removeNonTranslationalTransform","restore","key","value","_a","readAllKeyframes","flushKeyframeResolvers","KeyframeResolver","unresolvedKeyframes","onComplete","name","motionValue","isAsync","frame","currentValue","finalKeyframe","valueAsRead","fillWildcards","isForcedComplete","isCSSVar","name","setStyle","element","name","value","isCSSVar","supportsScrollTimeline","memo","supportsFlags","memoSupports","callback","supportsFlag","memoized","memo","_a","supportsFlags","supportsLinearEasing","memoSupports","cubicBezierAsString","a","b","c","d","supportedWaapiEasing","cubicBezierAsString","mapEasingToNativeEasing","easing","duration","supportsLinearEasing","generateLinearEasing","isBezierDefinition","cubicBezierAsString","segmentEasing","supportedWaapiEasing","startWaapiAnimation","element","valueName","keyframes","delay","duration","repeat","repeatType","ease","times","pseudoElement","keyframeOptions","easing","mapEasingToNativeEasing","statsBuffer","activeAnimations","options","animation","isGenerator","type","applyGeneratorOptions","_a","_b","type","options","__objRest","isGenerator","supportsLinearEasing","NativeAnimation","WithPromise","options","element","name","keyframes","pseudoElement","allowFlatten","finalKeyframe","onComplete","invariant","transition","applyGeneratorOptions","startWaapiAnimation","keyframe","getFinalKeyframe","setStyle","_a","_b","e","state","duration","millisecondsToSeconds","delay","newTime","secondsToMilliseconds","newSpeed","newStartTime","timeline","observe","supportsScrollTimeline","noop","unsupportedEasingFunctions","anticipate","backInOut","circInOut","isUnsupportedEase","key","replaceStringEasing","transition","sampleDelta","NativeAnimationExtended","NativeAnimation","options","replaceStringEasing","replaceTransitionType","value","_b","_a","motionValue","onUpdate","onComplete","element","__objRest","sampleAnimation","JSAnimation","__spreadProps","__spreadValues","sampleTime","secondsToMilliseconds","isAnimatable","value","name","complex","hasKeyframesChanged","keyframes","current","i","canAnimate","name","type","velocity","originKeyframe","targetKeyframe","isOriginAnimatable","isAnimatable","isTargetAnimatable","warning","isGenerator","makeAnimationInstant","options","acceleratedValues","supportsWaapi","memo","supportsBrowserAnimation","options","_a","motionValue","name","repeatDelay","repeatType","damping","type","onUpdate","transformTemplate","MAX_RESOLVE_DELAY","AsyncMotionValueAnimation","WithPromise","_a","_b","autoplay","delay","type","repeat","repeatDelay","repeatType","keyframes","name","motionValue","element","options","__objRest","time","optionsWithDefaults","__spreadValues","KeyframeResolver$1","KeyframeResolver","resolvedKeyframes","finalKeyframe","forced","sync","velocity","isHandoff","onUpdate","canAnimate","MotionGlobalConfig","getFinalKeyframe","makeAnimationInstant","startTime","resolvedOptions","__spreadProps","animation","supportsBrowserAnimation","NativeAnimationExtended","JSAnimation","noop","onResolve","_onReject","flushKeyframeResolvers","newTime","newSpeed","timeline","splitCSSVariableRegex","parseCSSVariable","current","match","token1","token2","fallback","maxDepth","getVariableValue","element","depth","invariant","token","resolved","trimmed","isNumericalString","isCSSVariableToken","getValueTransition","transition","key","_a","_b","positionalKeys","transformPropOrder","auto","v","testValueType","v","type","dimensionValueTypes","number","px","percent","degrees","vw","vh","auto","findDimensionValueType","v","testValueType","isNone","value","isZeroValueString","maxDefaults","applyDefaultFilter","v","name","value","number","floatRegex","unit","defaultValue","functionRegex","filter","__spreadProps","__spreadValues","complex","functions","int","__spreadProps","__spreadValues","number","transformValueTypes","degrees","scale","px","alpha","progressPercentage","numberValueTypes","__spreadProps","__spreadValues","px","transformValueTypes","int","alpha","defaultValueTypes","__spreadProps","__spreadValues","numberValueTypes","color","filter","getDefaultValueType","key","getAnimatableNone","key","value","defaultValueType","getDefaultValueType","filter","complex","invalidTemplates","makeNoneKeyframesAnimatable","unresolvedKeyframes","noneKeyframeIndexes","name","i","animatableTemplate","keyframe","analyseComplexValue","noneIndex","getAnimatableNone","DOMKeyframesResolver","KeyframeResolver","unresolvedKeyframes","onComplete","name","motionValue","element","i","keyframe","isCSSVariableToken","resolved","getVariableValue","positionalKeys","origin","target","originType","findDimensionValueType","targetType","isNumOrPxType","value","positionalValues","noneKeyframeIndexes","isNone","makeNoneKeyframesAnimatable","measureKeyframe","_a","finalKeyframeIndex","finalKeyframe","unsetTransformName","unsetTransformValue","resolveElements","elementOrSelector","scope","selectorCache","_a","root","elements","getValueAsType","value","type","isHTMLElement","element","isObject","MAX_VELOCITY_DELTA","isFloat","value","collectMotionValues","MotionValue","init","options","v","_a","currentTime","time","dependent","current","prevFrameValue","subscription","warnOnce","eventName","callback","SubscriptionManager","unsubscribe","frame","eventManagers","passiveEffect","stopPassiveEffect","prev","delta","endAnimation","velocityPerSecond","startAnimation","resolve","_b","motionValue","microtask","cancelMicrotask","createRenderBatcher","isDragging","isDragActive","setDragLock","axis","isDragging","setupGesture","elementOrSelector","options","elements","resolveElements","gestureAbortController","eventOptions","__spreadProps","__spreadValues","isValidHover","event","isDragActive","hover","elementOrSelector","onHoverStart","options","elements","eventOptions","cancel","setupGesture","onPointerEnter","enterEvent","target","onHoverEnd","onPointerLeave","leaveEvent","element","isNodeOrChild","parent","child","isPrimaryPointer","event","focusableElements","isElementKeyboardAccessible","element","isPressing","filterEvents","callback","event","firePointerEvent","target","type","enableKeyboardPress","focusEvent","eventOptions","element","handleKeydown","isPressing","handleKeyup","handleBlur","isValidPressEvent","event","isPrimaryPointer","isDragActive","press","targetOrSelector","onPressStart","options","targets","eventOptions","cancelEvents","setupGesture","startPress","startEvent","target","isPressing","onPressEnd","onPointerEnd","endEvent","success","onPointerUp","onPointerCancel","upEvent","isNodeOrChild","cancelEvent","isHTMLElement","enableKeyboardPress","isElementKeyboardAccessible","isSVGElement","element","isObject","isSVGSVGElement","element","isSVGElement","isMotionValue","value","valueTypes","dimensionValueTypes","color","complex","findValueType","v","testValueType","React","import_react","import_react","MotionConfigContext","p","React","setRef","ref","value","composeRefs","refs","node","hasCleanup","cleanups","cleanup","i","useComposedRefs","PopChildMeasure","prevProps","element","parent","parentWidth","isHTMLElement","size","PopChild","children","isPresent","anchorX","root","id","ref","nonce","MotionConfigContext","composedRef","useComposedRefs","width","height","top","left","right","x","style","PresenceChild","children","initial","isPresent","onExitComplete","custom","presenceAffectsLayout","mode","anchorX","root","presenceChildren","useConstant","newChildrenMap","id","isReusedContext","context","childId","isComplete","__spreadValues","_","key","PopChild","PresenceContext","import_react","usePresence","subscribe","context","PresenceContext","isPresent","onExitComplete","register","id","safeToRemove","import_react","getChildKey","child","onlyElements","children","filtered","AnimatePresence","children","custom","initial","onExitComplete","presenceAffectsLayout","mode","propagate","anchorX","root","isParentPresent","safeToRemove","usePresence","presentChildren","onlyElements","presentKeys","getChildKey","isInitialRender","pendingPresentChildren","exitComplete","useConstant","diffedChildren","setDiffedChildren","renderedChildren","setRenderedChildren","useIsomorphicLayoutEffect","i","key","exitingChildren","nextChildren","child","forceRender","LayoutGroupContext","isPresent","onExit","isEveryExitComplete","isExitComplete","PresenceChild","import_react","LazyContext","featureProps","featureDefinitions","key","props","name","loadFeatures","features","key","featureDefinitions","__spreadValues","validMotionProps","isValidMotionProp","key","shouldForward","key","isValidMotionProp","loadExternalIsValidProp","isValidProp","filterProps","props","isDom","forwardMotionProps","filteredProps","import_jsx_runtime","import_react","import_react","MotionContext","import_react","isAnimationControls","v","isVariantLabel","v","variantPriorityOrder","variantProps","isControllingVariants","props","isAnimationControls","variantProps","name","isVariantLabel","isVariantNode","getCurrentTreeVariants","props","context","isControllingVariants","initial","animate","isVariantLabel","useCreateMotionContext","props","initial","animate","getCurrentTreeVariants","MotionContext","variantLabelsAsDependency","prop","import_react","import_react","pixelsToPercent","pixels","axis","correctBorderRadius","latest","node","px","x","y","correctBoxShadow","latest","treeScale","projectionDelta","original","shadow","complex","template","offset","xScale","yScale","averageScale","mixNumber","scaleCorrectors","__spreadProps","__spreadValues","correctBorderRadius","correctBoxShadow","isForcedMotionValue","key","layout","layoutId","transformProps","scaleCorrectors","translateAlias","numTransforms","transformPropOrder","buildTransform","latestValues","transform","transformTemplate","transformString","transformIsDefault","i","key","value","valueIsDefault","valueAsType","getValueAsType","numberValueTypes","transformName","buildHTMLStyles","state","latestValues","transformTemplate","style","vars","transformOrigin","hasTransform","hasTransformOrigin","key","value","transformProps","isCSSVariableName","valueAsType","getValueAsType","numberValueTypes","buildTransform","originX","originY","originZ","createHtmlRenderState","copyRawValuesOnly","target","source","props","key","isMotionValue","isForcedMotionValue","useInitialMotionValues","transformTemplate","visualState","state","createHtmlRenderState","buildHTMLStyles","useStyle","styleProp","style","useHTMLProps","htmlProps","import_react","dashKeys","camelKeys","buildSVGPath","attrs","length","spacing","offset","useDashCase","keys","px","pathLength","pathSpacing","buildSVGAttrs","state","_a","isSVGTag","transformTemplate","styleProp","_b","attrX","attrY","attrScale","pathLength","pathSpacing","pathOffset","latest","__objRest","buildHTMLStyles","attrs","style","buildSVGPath","createSvgRenderState","__spreadProps","__spreadValues","createHtmlRenderState","isSVGTag","tag","useSVGProps","props","visualState","_isStatic","Component","visualProps","state","createSvgRenderState","buildSVGAttrs","isSVGTag","__spreadProps","__spreadValues","rawStyles","copyRawValuesOnly","lowercaseSVGElements","isSVGComponent","Component","lowercaseSVGElements","useRender","Component","props","ref","latestValues","isStatic","forwardMotionProps","visualProps","isSVGComponent","useSVGProps","useHTMLProps","filteredProps","filterProps","elementProps","__spreadProps","__spreadValues","children","renderedChildren","isMotionValue","import_react","getValueState","visualElement","state","value","key","resolveVariantFromProps","props","definition","custom","current","velocity","resolveMotionValue","value","isMotionValue","makeState","scrapeMotionValuesFromProps","createRenderState","props","context","presenceContext","makeLatestValues","scrapeMotionValues","values","motionValues","key","resolveMotionValue","initial","animate","isControllingVariants$1","isControllingVariants","isVariantNode$1","isVariantNode","isInitialAnimationBlocked","variantToSet","isAnimationControls","list","i","resolved","resolveVariantFromProps","_a","transitionEnd","transition","target","__objRest","valueTarget","index","makeUseVisualState","config","isStatic","MotionContext","PresenceContext","make","useConstant","scrapeMotionValuesFromProps","props","prevProps","visualElement","_a","style","newValues","key","isMotionValue","isForcedMotionValue","useHTMLVisualState","makeUseVisualState","scrapeMotionValuesFromProps","createHtmlRenderState","scrapeMotionValuesFromProps","props","prevProps","visualElement","newValues","key","isMotionValue","targetKey","transformPropOrder","useSVGVisualState","makeUseVisualState","scrapeMotionValuesFromProps","createSvgRenderState","motionComponentSymbol","import_react","isRefObject","ref","useMotionRef","visualState","visualElement","externalRef","instance","isRefObject","import_react","camelToDash","str","optimizedAppearDataId","optimizedAppearDataAttribute","camelToDash","import_react","SwitchLayoutGroupContext","useVisualElement","Component","visualState","props","createVisualElement","ProjectionNodeConstructor","_a","_b","parent","MotionContext","lazyContext","LazyContext","presenceContext","PresenceContext","reducedMotionConfig","MotionConfigContext","visualElementRef","visualElement","initialLayoutGroupConfig","SwitchLayoutGroupContext","createProjectionNode","isMounted","optimisedAppearId","optimizedAppearDataAttribute","wantsHandoff","useIsomorphicLayoutEffect","initialPromotionConfig","layoutId","layout","drag","dragConstraints","layoutScroll","layoutRoot","layoutCrossfade","getClosestProjectingNode","isRefObject","createMotionComponent","Component","forwardMotionProps","preloadedFeatures","createVisualElement","_a","_b","loadFeatures","useVisualState","isSVGComponent","useSVGVisualState","useHTMLVisualState","MotionDOMComponent","props","externalRef","MeasureLayout","configAndProps","__spreadProps","__spreadValues","MotionConfigContext","useLayoutId","isStatic","context","useCreateMotionContext","visualState","isBrowser","useStrictMode","layoutProjection","getProjectionFunctionality","useVisualElement","MotionContext","useRender","useMotionRef","ForwardRefMotionComponent","motionComponentSymbol","layoutId","layoutGroupId","LayoutGroupContext","isStrict","LazyContext","strictMessage","warning","invariant","drag","layout","featureDefinitions","combined","createMotionProxy","preloadedFeatures","createVisualElement","createMotionComponent","componentCache","factory","Component","options","deprecatedFactoryFunction","warnOnce","_target","key","import_react","convertBoundingBoxToBox","top","left","right","bottom","convertBoxToBoundingBox","x","y","transformBoxPoints","point","transformPoint","topLeft","bottomRight","isIdentityScale","scale","hasScale","scaleX","scaleY","hasTransform","values","has2DTranslate","is2DTranslate","value","scalePoint","point","scale","originPoint","distanceFromOrigin","scaled","applyPointDelta","translate","boxScale","applyAxisDelta","axis","applyBoxDelta","box","x","y","TREE_SCALE_SNAP_MIN","TREE_SCALE_SNAP_MAX","applyTreeDeltas","treeScale","treePath","isSharedTransition","treeLength","node","delta","visualElement","transformBox","hasTransform","translateAxis","distance","transformAxis","axisTranslate","axisScale","axisOrigin","mixNumber","transform","measureViewportBox","instance","transformPoint","convertBoundingBoxToBox","transformBoxPoints","measurePageBox","element","rootProjectionNode","transformPagePoint","viewportBox","scroll","translateAxis","createAxisDelta","createDelta","createAxis","createBox","prefersReducedMotion","hasReducedMotionListener","initPrefersReducedMotion","hasReducedMotionListener","isBrowser","motionMediaQuery","setReducedMotionPreferences","prefersReducedMotion","visualElementStore","updateMotionValuesFromProps","element","next","prev","key","nextValue","prevValue","isMotionValue","motionValue","existingValue","latestValue","propEventHandlers","VisualElement","_props","_prevProps","_visualElement","parent","props","presenceContext","reducedMotionConfig","blockInitialAnimation","visualState","options","KeyframeResolver","now","time","frame","latestValues","renderState","__spreadValues","isControllingVariants","isVariantNode","_a","willChange","initialMotionValues","__objRest","key","value","isMotionValue","instance","visualElementStore","hasReducedMotionListener","initPrefersReducedMotion","prefersReducedMotion","warnOnce","cancelFrame","remove","feature","child","valueIsTransform","transformProps","removeOnChange","latestValue","removeSyncCheck","other","featureDefinitions","featureDefinition","isEnabled","FeatureConstructor","createBox","i","listenerName","listener","updateMotionValuesFromProps","name","closestVariantNode","existingValue","unsubscribe","defaultValue","motionValue","target","isNumericalString","isZeroValueString","findValueType","complex","getAnimatableNone","initial","valueFromInitial","variant","resolveVariantFromProps","eventName","callback","SubscriptionManager","args","microtask","DOMVisualElement","VisualElement","DOMKeyframesResolver","a","b","props","key","vars","style","children","isMotionValue","latest","renderHTML","element","style","vars","styleProp","projection","elementStyle","key","getComputedStyle","element","HTMLVisualElement","DOMVisualElement","renderHTML","instance","key","_a","transformProps","defaultTransformValue","readTransformValue","computedStyle","value","isCSSVariableName","transformPagePoint","measureViewportBox","renderState","latestValues","props","buildHTMLStyles","prevProps","visualElement","scrapeMotionValuesFromProps","camelCaseAttributes","renderSVG","element","renderState","_styleProp","projection","renderHTML","key","camelCaseAttributes","camelToDash","SVGVisualElement","DOMVisualElement","createBox","props","key","instance","transformProps","defaultType","getDefaultValueType","camelCaseAttributes","camelToDash","prevProps","visualElement","scrapeMotionValuesFromProps","renderState","latestValues","buildSVGAttrs","styleProp","projection","renderSVG","isSVGTag","createDomVisualElement","Component","options","isSVGComponent","SVGVisualElement","HTMLVisualElement","resolveVariant","visualElement","definition","custom","props","resolveVariantFromProps","isKeyframesTarget","v","setMotionValue","visualElement","key","value","motionValue","resolveFinalValueInKeyframes","v","isKeyframesTarget","setTarget","definition","_a","resolveVariant","transitionEnd","transition","target","__objRest","__spreadValues","isWillChangeMotionValue","value","isMotionValue","addValueToWillChange","visualElement","key","willChange","isWillChangeMotionValue","MotionGlobalConfig","newWillChange","getOptimisedAppearId","visualElement","optimizedAppearDataAttribute","isNotNull","value","getFinalKeyframe","keyframes","repeat","repeatType","finalKeyframe","resolvedKeyframes","index","underDampedSpring","criticallyDampedSpring","target","keyframesTransition","ease","getDefaultTransition","valueKey","keyframes","transformProps","isTransitionDefined","_a","_b","when","_delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed","transition","__objRest","animateMotionValue","name","value","target","transition","element","isHandoff","onComplete","valueTransition","getValueTransition","delay","elapsed","secondsToMilliseconds","options","__spreadProps","__spreadValues","v","isTransitionDefined","getDefaultTransition","shouldSkip","makeAnimationInstant","MotionGlobalConfig","finalKeyframe","getFinalKeyframe","frame","JSAnimation","AsyncMotionValueAnimation","shouldBlockAnimation","protectedKeys","needsAnimating","key","shouldBlock","animateTarget","visualElement","targetAndTransition","delay","transitionOverride","type","_b","_a","transition","transitionEnd","target","__objRest","animations","animationTypeState","value","valueTarget","valueTransition","__spreadValues","getValueTransition","currentValue","isHandoff","appearId","getOptimisedAppearId","startTime","frame","addValueToWillChange","animateMotionValue","positionalKeys","animation","setTarget","calcChildStagger","children","child","delayChildren","staggerChildren","staggerDirection","index","a","b","numChildren","maxStaggerDuration","animateVariant","visualElement","variant","options","_a","resolved","resolveVariant","transition","getAnimation","animateTarget","getChildAnimations","forwardDelay","delayChildren","staggerChildren","staggerDirection","animateChildren","when","first","last","delay","animations","child","__spreadProps","__spreadValues","calcChildStagger","animateVisualElement","visualElement","definition","options","animation","animations","variant","animateVariant","resolvedDefinition","resolveVariant","animateTarget","shallowCompare","next","prev","prevLength","i","numVariantProps","variantProps","getVariantContext","visualElement","context","i","name","prop","isVariantLabel","reversePriorityOrder","variantPriorityOrder","numAnimationTypes","animateList","visualElement","animations","animation","options","animateVisualElement","createAnimationState","animate","state","createState","isInitialRender","buildResolvedTypeValues","type","acc","definition","_a","resolved","resolveVariant","_b","transition","transitionEnd","target","__objRest","__spreadValues","setAnimateFunction","makeAnimator","animateChanges","changedActiveType","props","context","getVariantContext","removedKeys","encounteredKeys","removedVariantIndex","i","typeState","prop","propIsVariant","isVariantLabel","activeDelta","isInherited","isAnimationControls","variantDidChange","checkVariantsDidChange","shouldAnimateType","handledRemovedValues","definitionList","resolvedValues","prevResolvedValues","allKeys","markToAnimate","key","motionValue","next","prev","valueHasChanged","isKeyframesTarget","shallowCompare","willAnimateViaParent","parent","parentVariant","delayChildren","calcChildStagger","fallbackAnimation","initialTransition","fallbackTarget","shouldAnimate","setActive","isActive","child","createTypeState","Feature","node","AnimationFeature","Feature","node","createAnimationState","animate","isAnimationControls","prevAnimate","_a","id","ExitAnimationFeature","Feature","isPresent","onExitComplete","prevIsPresent","exitAnimation","register","animations","AnimationFeature","ExitAnimationFeature","addDomEvent","target","eventName","handler","options","extractEventInfo","event","addPointerInfo","handler","isPrimaryPointer","addPointerEvent","target","eventName","handler","options","addDomEvent","addPointerInfo","SCALE_PRECISION","SCALE_MIN","SCALE_MAX","TRANSLATE_PRECISION","TRANSLATE_MIN","TRANSLATE_MAX","calcLength","axis","isNear","value","target","maxDistance","calcAxisDelta","delta","source","origin","mixNumber","calcBoxDelta","calcRelativeAxis","relative","parent","calcRelativeBox","calcRelativeAxisPosition","layout","calcRelativePosition","eachAxis","callback","getContextWindow","current","distance","a","b","distance2D","xDelta","yDelta","__pow","PanSession","event","handlers","transformPagePoint","contextWindow","dragSnapToOrigin","distanceThreshold","info","getPanInfo","isPanStarted","isDistancePastThreshold","distance2D","point","timestamp","frameData","__spreadProps","__spreadValues","onStart","onMove","transformPoint","frame","onEnd","onSessionEnd","resumeAnimation","panInfo","isPrimaryPointer","extractEventInfo","initialInfo","onSessionStart","pipe","addPointerEvent","cancelFrame","subtractPoint","a","b","history","lastDevicePoint","startDevicePoint","getVelocity","timeDelta","i","timestampedPoint","lastPoint","secondsToMilliseconds","time","millisecondsToSeconds","currentVelocity","applyConstraints","point","min","max","elastic","mixNumber","calcRelativeAxisConstraints","axis","calcRelativeConstraints","layoutBox","top","left","bottom","right","calcViewportAxisConstraints","layoutAxis","constraintsAxis","calcViewportConstraints","constraintsBox","calcOrigin","source","target","origin","sourceLength","calcLength","targetLength","progress","clamp","rebaseAxisConstraints","layout","constraints","relativeConstraints","defaultElastic","resolveDragElastic","dragElastic","resolveAxisElastic","minLabel","maxLabel","resolvePointElastic","label","elementDragControls","VisualElementDragControls","visualElement","createBox","originEvent","snapToCursor","distanceThreshold","presenceContext","onSessionStart","event","dragSnapToOrigin","extractEventInfo","onStart","info","drag","dragPropagation","onDragStart","setDragLock","eachAxis","axis","current","percent","projection","measuredAxis","calcLength","frame","addValueToWillChange","animationState","onMove","dragDirectionLock","onDirectionLock","onDrag","offset","getCurrentDirection","onSessionEnd","resumeAnimation","_a","PanSession","getContextWindow","panInfo","finalEvent","finalPanInfo","isDragging","velocity","onDragEnd","_point","shouldDrag","axisValue","next","applyConstraints","dragConstraints","dragElastic","layout","prevConstraints","isRefObject","calcRelativeConstraints","resolveDragElastic","rebaseAxisConstraints","constraints","onMeasureDragConstraints","constraintsElement","invariant","constraintsBox","measurePageBox","measuredConstraints","calcViewportConstraints","userConstraints","convertBoxToBoundingBox","convertBoundingBoxToBox","dragMomentum","dragTransition","onDragTransitionEnd","momentumAnimations","transition","bounceStiffness","bounceDamping","inertia","__spreadValues","animateMotionValue","dragKey","props","externalMotionValue","point","min","max","mixNumber","boxProgress","latest","calcOrigin","transformTemplate","element","stopPointerListener","addPointerEvent","dragListener","measureDragConstraints","stopMeasureLayoutListener","stopResizeListener","addDomEvent","stopLayoutUpdateListener","delta","hasLayoutChanged","motionValue","defaultElastic","__spreadProps","direction","currentDirection","lockThreshold","DragGesture","Feature","node","noop","VisualElementDragControls","dragControls","asyncHandler","handler","event","info","frame","PanGesture","Feature","noop","pointerDownEvent","PanSession","getContextWindow","onPanSessionStart","onPanStart","onPan","onPanEnd","addPointerEvent","import_jsx_runtime","import_react","globalProjectionState","hasTakenAnySnapshot","MeasureLayoutWithContext","visualElement","layoutGroup","switchLayoutGroup","layoutId","projection","__spreadProps","__spreadValues","globalProjectionState","prevProps","layoutDependency","drag","isPresent","frame","stack","microtask","promoteContext","safeToRemove","MeasureLayout","props","usePresence","LayoutGroupContext","SwitchLayoutGroupContext","animateSingleValue","value","keyframes","options","motionValue$1","isMotionValue","motionValue","animateMotionValue","compareByDepth","a","b","FlatTree","child","addUniqueItem","removeItem","callback","compareByDepth","delay","callback","timeout","start","time","checkElapsed","timestamp","elapsed","cancelFrame","frame","borders","numBorders","asNumber","value","isPx","px","mixValues","target","follow","lead","progress","shouldCrossfadeOpacity","isOnlyMember","_a","_b","_c","_d","mixNumber","easeCrossfadeIn","easeCrossfadeOut","i","borderLabel","followRadius","getRadius","leadRadius","percent","values","radiusName","compress","circOut","noop","min","max","easing","p","copyAxisInto","axis","originAxis","copyBoxInto","box","originBox","copyAxisDeltaInto","delta","originDelta","removePointDelta","point","translate","scale","originPoint","boxScale","scalePoint","removeAxisDelta","axis","origin","originAxis","sourceAxis","percent","mixNumber","removeAxisTransforms","transforms","key","scaleKey","originKey","xKeys","yKeys","removeBoxTransforms","box","originBox","sourceBox","isAxisDeltaZero","delta","isDeltaZero","axisEquals","a","b","boxEquals","axisEqualsRounded","boxEqualsRounded","aspectRatio","box","calcLength","axisDeltaEquals","NodeStack","node","addUniqueItem","removeItem","prevLead","indexOfNode","member","i","preserveFollowOpacity","crossfade","options","resumingFrom","buildProjectionTransform","delta","treeScale","latestTransform","transform","xTranslate","yTranslate","zTranslate","transformPerspective","rotate","rotateX","rotateY","skewX","skewY","elementScaleX","elementScaleY","metrics","transformAxes","animationTarget","id","resetDistortingTransform","key","visualElement","values","sharedAnimationValues","latestValues","cancelTreeOptimisedTransformAnimations","projectionNode","appearId","getOptimisedAppearId","layout","layoutId","frame","parent","createProjectionNode","attachResizeListener","defaultParent","measureScroll","checkIsScrollRoot","resetTransform","statsBuffer","propagateDirtyNodes","resolveTargetDelta","calcProjection","cleanDirtyNodes","i","FlatTree","name","handler","SubscriptionManager","args","subscriptionManager","instance","isSVGElement","isSVGSVGElement","cancelDelay","innerWidth","resizeUnblockUpdate","newInnerWidth","delay","globalProjectionState","finishAnimation","delta","hasLayoutChanged","hasRelativeLayoutChanged","newLayout","layoutTransition","defaultLayoutTransition","onLayoutAnimationStart","onLayoutAnimationComplete","hasTargetChanged","boxEqualsRounded","hasOnlyRelativeTargetChanged","animationOptions","__spreadProps","__spreadValues","getValueTransition","stack","cancelFrame","resetSkewAndRotation","shouldNotifyListeners","node","transformTemplate","clearMeasurements","clearIsLayoutDirty","resetTransformStyle","updateLayout","notifyLayoutUpdate","now","time","frameData","clamp","frameSteps","microtask","clearSnapshot","removeLeadSnapshots","calcLength","prevLayout","createBox","phase","needsMeasurement","isRoot","isResetRequested","hasProjection","isDeltaZero","transformTemplateValue","transformTemplateHasChanged","hasTransform","removeTransform","pageBox","layoutBox","roundBox","_a","box","checkNodeWasScrollRoot","scroll","translateAxis","boxWithoutScroll","copyBoxInto","options","transformOnly","withTransforms","transformBox","boxWithoutTransform","hasScale","sourceBox","nodeBox","removeBoxTransforms","forceRecalculation","lead","isShared","relativeParent","calcRelativeBox","applyBoxDelta","has2DTranslate","parentLayout","calcRelativePosition","canSkip","prevTreeScaleX","prevTreeScaleY","applyTreeDeltas","target","copyAxisDeltaInto","calcBoxDelta","axisDeltaEquals","notifyAll","createDelta","snapshot","snapshotLatestValues","mixedValues","targetDelta","relativeLayout","snapshotSource","layoutSource","isSharedLayoutAnimation","isOnlyMember","shouldCrossfadeOpacity","hasOpacityCrossfade","prevRelativeTarget","latest","progress","mixAxisDelta","mixBox","boxEquals","mixValues","_b","_c","activeAnimations","motionValue","animateSingleValue","targetWithTransforms","shouldAnimatePositionOnly","xLength","yLength","NodeStack","config","needsReset","transition","preserveFollowOpacity","hasDistortingTransform","resetValues","targetStyle","styleProp","resolveMotionValue","valuesToRender","transform","buildProjectionTransform","x","y","scaleCorrectors","correct","applyTo","isCSSVariable","corrected","num","measuredLayout","animationType","eachAxis","axis","axisSnapshot","length","layoutDelta","visualDelta","parentSnapshot","relativeSnapshot","onExitComplete","output","p","mixNumber","mixAxis","from","to","userAgentContains","string","roundPoint","noop","roundAxis","isNear","aspectRatio","DocumentProjectionNode","createProjectionNode","ref","notify","addDomEvent","rootProjectionNode","HTMLProjectionNode","createProjectionNode","instance","documentNode","DocumentProjectionNode","value","drag","PanGesture","DragGesture","HTMLProjectionNode","MeasureLayout","handleHoverEvent","node","event","lifecycle","props","eventName","callback","frame","extractEventInfo","HoverGesture","Feature","current","hover","_element","startEvent","endEvent","FocusGesture","Feature","isFocusVisible","e","pipe","addDomEvent","handlePressEvent","node","event","lifecycle","props","eventName","callback","frame","extractEventInfo","PressGesture","Feature","current","press","_element","startEvent","endEvent","success","observerCallbacks","observers","fireObserverCallback","entry","callback","fireAllObserverCallbacks","entries","initIntersectionObserver","_a","_b","root","options","__objRest","lookupRoot","rootObservers","key","__spreadValues","observeIntersection","element","rootInteresectionObserver","thresholdNames","InViewFeature","Feature","viewport","root","rootMargin","amount","once","options","onIntersectionUpdate","entry","isIntersecting","onViewportEnter","onViewportLeave","callback","observeIntersection","props","prevProps","hasViewportOptionChanged","prevViewport","name","gestureAnimations","InViewFeature","PressGesture","FocusGesture","HoverGesture","layout","HTMLProjectionNode","MeasureLayout","featureBundle","__spreadValues","animations","gestureAnimations","drag","layout","motion","createMotionProxy","featureBundle","createDomVisualElement","import_jsx_runtime","ModalHeader","onClose","title","headerClassName","headerAction","cn","IcClose","modal_header_default","import_react","import_react_dom","import_jsx_runtime","ModalWrapper","isOpen","children","className","id","container","AnimatePresence","motion","e","modal_wrapper_default","import_jsx_runtime","ModalTransition","ModalZoom","props","isOpen","onClose","children","className","title","footer","modalClassName","headerClassName","headerAction","modal_wrapper_default","motion","__spreadProps","__spreadValues","e","cn","modal_header_default","modal_zoom_default","import_hooks","import_provider","import_react","import_jsx_runtime","PosAppProviderInitialValue","ReactContext","usePosAppProvider","context","ReactContext","PosAppProviderInitialValue","import_jsx_runtime","EMenuLink","props","_a","formValues","pos_slug_key","value","t","useTranslation","user","usePosAppProvider","isOpenQr","setIsOpenQr","dataUser","eMenuLink","handleCopyToClipboard","isCopied","IcCheck","IcCopy","IcQR","modal_zoom_default","QRCodeSVG","menu_link_default","import_jsx_runtime","Line","import_jsx_runtime","ButtonAction","id","onClick","iconSrc","children","className","text","disabled","type","textClassName","style","cn","button_action_default","import_jsx_runtime","KitchenStatus","props","_a","_b","imgUrl","iconUrl","stage","index","kitchen_status_default","import_react","Action","invariant","value","message","Error","warning","cond","console","warn","e","createPath","_ref","pathname","search","hash","charAt","parsePath","path","parsedPath","hashIndex","indexOf","substr","searchIndex","ResultType","convertRouteMatchToUiMatch","match","loaderData","route","pathname","params","id","data","handle","generatePath","originalPath","params","path","endsWith","warning","replace","prefix","startsWith","stringify","p","String","segments","split","map","segment","index","array","length","star","keyMatch","match","key","optional","param","invariant","filter","join","matchPath","pattern","pathname","caseSensitive","end","matcher","compiledParams","compilePath","matchedPathname","pathnameBase","captureGroups","slice","reduce","memo","_ref","paramName","isOptional","splatValue","value","undefined","regexpSource","_","push","RegExp","stripBasename","pathname","basename","toLowerCase","startsWith","startIndex","endsWith","length","nextChar","charAt","slice","ABSOLUTE_URL_REGEX","isAbsoluteUrl","url","test","resolvePath","to","fromPathname","toPathname","search","hash","parsePath","includes","oldPathname","replace","warning","resolvePathname","substring","normalizeSearch","normalizeHash","relativePath","segments","split","relativeSegments","forEach","segment","pop","push","join","getInvalidPathError","char","field","dest","path","JSON","stringify","getPathContributingMatches","matches","filter","match","index","route","getResolveToMatches","v7_relativeSplatPath","pathMatches","map","idx","pathnameBase","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","_extends","invariant","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","joinPaths","paths","join","replace","normalizeSearch","search","startsWith","normalizeHash","hash","validMutationMethodsArr","validMutationMethods","Set","validRequestMethodsArr","validRequestMethods","DataRouterContext","createContext","process","env","NODE_ENV","displayName","DataRouterStateContext","AwaitContext","NavigationContext","LocationContext","RouteContext","outlet","matches","isDataRoute","RouteErrorContext","useHref","to","_temp","relative","useInRouterContext","invariant","basename","navigator","useContext","hash","pathname","search","useResolvedPath","joinedPathname","joinPaths","createHref","useLocation","location","navigateEffectWarning","useIsomorphicLayoutEffect","cb","useContext","NavigationContext","static","useLayoutEffect","useNavigate","isDataRoute","RouteContext","useNavigateStable","useNavigateUnstable","useInRouterContext","process","env","NODE_ENV","invariant","dataRouterContext","DataRouterContext","basename","future","navigator","matches","pathname","locationPathname","useLocation","routePathnamesJson","JSON","stringify","getResolveToMatches","v7_relativeSplatPath","activeRef","useRef","current","useCallback","to","options","warning","go","path","resolveTo","parse","relative","joinPaths","replace","push","state","useResolvedPath","to","_temp2","relative","future","useContext","NavigationContext","matches","RouteContext","pathname","locationPathname","useLocation","routePathnamesJson","JSON","stringify","getResolveToMatches","v7_relativeSplatPath","useMemo","resolveTo","parse","DataRouterHook","DataRouterStateHook","getDataRouterConsoleError","hookName","useDataRouterContext","ctx","useContext","DataRouterContext","process","env","NODE_ENV","invariant","useDataRouterState","state","DataRouterStateContext","useRouteContext","route","RouteContext","useCurrentRouteId","thisRoute","matches","length","id","useRouteId","UseRouteId","useNavigation","UseNavigation","navigation","useMatches","matches","loaderData","useDataRouterState","DataRouterStateHook","UseMatches","useMemo","map","m","convertRouteMatchToUiMatch","useNavigateStable","router","useDataRouterContext","DataRouterHook","UseNavigateStable","id","useCurrentRouteId","DataRouterStateHook","activeRef","useRef","useIsomorphicLayoutEffect","current","useCallback","to","options","process","env","NODE_ENV","warning","navigateEffectWarning","navigate","_extends","fromRouteId","alreadyWarned","warnOnce","key","message","process","env","NODE_ENV","console","warn","logDeprecation","flag","msg","link","logV6DeprecationWarnings","renderFuture","routerFuture","v7_startTransition","undefined","v7_relativeSplatPath","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_skipActionErrorRevalidation","START_TRANSITION","startTransitionImpl","React","Router","_ref5","basename","basenameProp","children","location","locationProp","navigationType","NavigationType","Pop","navigator","static","staticProp","future","useInRouterContext","process","env","NODE_ENV","invariant","replace","navigationContext","useMemo","_extends","v7_relativeSplatPath","parsePath","pathname","search","hash","state","key","locationContext","trailingPathname","stripBasename","warning","createElement","NavigationContext","Provider","value","LocationContext","neverSettledPromise","Promise","defaultMethod","defaultEncType","isHtmlElement","object","tagName","isButtonElement","toLowerCase","isFormElement","isInputElement","isModifiedEvent","event","metaKey","altKey","ctrlKey","shiftKey","shouldProcessLinkClick","target","button","createSearchParams","init","URLSearchParams","Array","isArray","Object","keys","reduce","memo","key","value","concat","map","v","_formDataSupportsSubmitter","isFormDataSubmitterSupported","FormData","document","createElement","e","supportedFormEncTypes","Set","getFormEncType","encType","has","process","env","NODE_ENV","warning","defaultEncType","getFormSubmissionInfo","target","basename","method","action","formData","body","isFormElement","attr","getAttribute","stripBasename","defaultMethod","isButtonElement","isInputElement","type","form","Error","name","value","prefix","append","isHtmlElement","undefined","toLowerCase","REACT_ROUTER_VERSION","window","__reactRouterVersion","ViewTransitionContext","createContext","isTransitioning","process","env","NODE_ENV","displayName","FetchersContext","Map","START_TRANSITION","startTransitionImpl","React","FLUSH_SYNC","flushSyncImpl","ReactDOM","USE_ID","useIdImpl","HistoryRouter","_ref6","basename","children","future","history","state","setStateImpl","useState","action","location","v7_startTransition","setState","useCallback","newState","startTransitionImpl","React","useLayoutEffect","listen","useEffect","logV6DeprecationWarnings","createElement","Router","navigationType","navigator","process","env","NODE_ENV","displayName","isBrowser","window","document","ABSOLUTE_URL_REGEX","Link","forwardRef","_ref7","ref","onClick","relative","reloadDocument","replace","target","to","preventScrollReset","viewTransition","rest","_objectWithoutPropertiesLoose","_excluded","useContext","NavigationContext","absoluteHref","isExternal","test","currentUrl","URL","href","targetUrl","startsWith","protocol","path","stripBasename","pathname","origin","search","hash","e","warning","useHref","internalOnClick","useLinkClickHandler","handleClick","event","defaultPrevented","_extends","NavLink","_ref8","ariaCurrentProp","caseSensitive","className","classNameProp","end","style","styleProp","_excluded2","useResolvedPath","useLocation","routerState","DataRouterStateContext","isTransitioning","useViewTransitionState","toPathname","encodeLocation","locationPathname","nextLocationPathname","navigation","toLowerCase","endSlashPosition","endsWith","length","isActive","charAt","isPending","renderProps","ariaCurrent","undefined","filter","Boolean","join","Form","_ref9","forwardedRef","fetcherKey","navigate","method","defaultMethod","onSubmit","props","_excluded3","submit","useSubmit","formAction","useFormAction","formMethod","preventDefault","submitter","nativeEvent","submitMethod","getAttribute","currentTarget","ScrollRestoration","_ref10","getKey","storageKey","useScrollRestoration","DataRouterHook","DataRouterStateHook","getDataRouterConsoleError","hookName","useDataRouterContext","ctx","DataRouterContext","invariant","useDataRouterState","_temp","replaceProp","useNavigate","shouldProcessLinkClick","createPath","validateClientSideSubmission","document","Error","fetcherId","getUniqueFetcherId","String","useSubmit","router","useDataRouterContext","DataRouterHook","UseSubmit","basename","useContext","NavigationContext","currentRouteId","useRouteId","useCallback","target","options","action","method","encType","formData","body","getFormSubmissionInfo","navigate","key","fetcherKey","fetch","preventScrollReset","formMethod","formEncType","flushSync","replace","state","fromRouteId","viewTransition","useFormAction","_temp2","relative","routeContext","RouteContext","process","env","NODE_ENV","invariant","match","matches","slice","path","_extends","useResolvedPath","location","useLocation","search","params","URLSearchParams","indexValues","getAll","some","v","delete","filter","forEach","append","qs","toString","route","index","pathname","joinPaths","createPath","SCROLL_RESTORATION_STORAGE_KEY","savedScrollPositions","useScrollRestoration","_temp4","getKey","storageKey","router","useDataRouterContext","DataRouterHook","UseScrollRestoration","restoreScrollPosition","preventScrollReset","useDataRouterState","DataRouterStateHook","basename","useContext","NavigationContext","location","useLocation","matches","useMatches","navigation","useNavigation","useEffect","window","history","scrollRestoration","usePageHide","useCallback","state","key","scrollY","sessionStorage","setItem","JSON","stringify","error","process","env","NODE_ENV","warning","document","useLayoutEffect","sessionPositions","getItem","parse","e","getKeyWithoutBasename","_extends","pathname","stripBasename","disableScrollRestoration","enableScrollRestoration","scrollTo","hash","el","getElementById","decodeURIComponent","slice","scrollIntoView","usePageHide","callback","options","capture","useEffect","opts","undefined","window","addEventListener","removeEventListener","useViewTransitionState","to","opts","vtContext","useContext","ViewTransitionContext","process","env","NODE_ENV","invariant","basename","useDataRouterContext","DataRouterHook","path","useResolvedPath","relative","isTransitioning","currentPath","stripBasename","currentLocation","pathname","nextPath","nextLocation","matchPath","import_jsx_runtime","KitchenTemplate","columns","row","onClickRow","navigate","useNavigate","kitchenId","t","useTranslation","onNavigateToOrderList","generatePath","kitchen_status_default","Line","button_action_default","e","kitchen_template_default","import_jsx_runtime","FileListIcon","import_jsx_runtime","IcPlus","import_jsx_runtime","OrderActions","orderStatus","onAddItem","onPayment","onIssueInvoice","onPrintInvoice","t","useTranslation","button_action_default","IcPlus","order_actions_default","import_jsx_runtime","STATUS","OrderStatus","status","useTranslation","currentStatus","item","order_status_default","import_react","import_jsx_runtime","PosOrderTemplate","readOnly","row","handleClick","onAddItem","onPayment","onIssueInvoice","onPrintInvoice","_a","orderDate","FileListIcon","order_status_default","dd_mm_yyyy","hh_mm","Line","formatOrderPrice","order_actions_default","pos_order_template_default","import_jsx_runtime","IcSetting","QUERY_KEYS","import_provider","import_utils","import_react_query","useSessionProvider","_a","useCreateSession","useHandleClosingSession","useCreatePosConfig","createSessionMutation","setOpeningCashBoxMutation","createPosConfigMutation","user","usePosAppProvider","dataUser","service","xNode","openSession","configId","__async","setOpeningCashBox","cashBoxValue","sessionId","createPosConfig","_0","name","modulePosRestaurant","use_session_provider_default","isString","obj","defer","res","rej","promise","resolve","reject","makeString","object","copy","a","s","t","m","lastOfPathSeparatorRegExp","cleanKey","key","canNotTraverseDeeper","getLastOfPath","path","Empty","stack","stackIndex","setPath","newValue","k","e","p","last","pushPath","concat","getPath","getPathWithDefaults","data","defaultData","value","deepExtend","target","source","overwrite","prop","regexEscape","str","_entityMap","escape","RegExpCache","capacity","pattern","regExpFromCache","regExpNew","chars","looksLikeObjectPathRegExpCache","looksLikeObjectPath","nsSeparator","keySeparator","possibleChars","c","r","matched","ki","deepFind","tokens","current","i","next","nextPath","j","getCleanedCode","code","consoleLogger","args","type","_a","_b","Logger","_Logger","concreteLogger","options","lvl","prefix","debugOnly","moduleName","__spreadValues","baseLogger","EventEmitter","events","listener","event","numListeners","observer","numTimesAdded","ResourceStore","ns","index","lng","ignoreJSONStructure","result","resources","deep","pack","v","postProcessor","module","processors","translator","processor","PATH_KEY","createProxy","state","handler","proxy","keysFromSelector","selector","opts","checkedLoadedFor","shouldHandleAsObject","Translator","_Translator","services","o","opt","resolved","isObject","namespaces","wouldCheckForNsInKey","seemsNaturalLanguage","parts","keys","lastKey","returnDetails","namespace","appendNamespaceToCIMode","resUsedKey","resExactUsedKey","noObject","joinArrays","handleAsObjectInI18nFormat","needsPluralHandling","hasDefaultValue","defaultValueSuffix","defaultValueSuffixOrdinalFallback","needsZeroSuffixLookup","defaultValue","resForObjHndl","handleAsObject","resType","__spreadProps","resTypeIsArray","newKeyToUse","deepKey","usedDefault","usedKey","resForMissing","updateMissing","fk","lngs","fallbackLngs","send","l","specificDefaultValue","defaultForMissing","language","suffixes","suffix","skipOnVariables","nestBef","nb","na","nestAft","postProcess","postProcessorNames","found","exactUsedKey","usedLng","usedNS","extracted","needsContextHandling","codes","finalKeys","pluralSuffix","zeroSuffix","ordinalPrefix","contextKey","possibleKey","optionsKeys","useOptionsReplaceForData","option","LanguageUtil","formattedCode","cleanedLng","lngScOnly","lngOnly","supportedLng","fallbacks","fallbackCode","fallbackCodes","addCode","fc","suffixesOrder","dummyRule","count","PluralResolver","languageUtils","cleanedCode","cacheKey","rule","err","lngPart","pluralCategory1","pluralCategory2","pluralCategory","deepFindWithDefaults","regexSafe","val","Interpolator","escape$1","escapeValue","useRawValueToEscape","prefixEscaped","suffixEscaped","formatSeparator","unescapeSuffix","unescapePrefix","nestingPrefix","nestingPrefixEscaped","nestingSuffix","nestingSuffixEscaped","nestingOptionsSeparator","maxReplaces","alwaysFormat","getOrResetRegExp","existingRegExp","match","replaces","handleFormat","f","missingInterpolationHandler","todo","matchedVar","temp","safeValue","clonedOptions","handleHasOptions","inheritedOptions","sep","optionsString","matchedSingleQuotes","matchedDoubleQuotes","formatters","keyEndIndex","elem","parseFormatStr","formatStr","formatName","formatOptions","optStr","rest","trimmedKey","createCachedFormatter","fn","cache","optForCache","frm","createNonCachedFormatter","Formatter","cf","formatter","name","format","formats","lastIndex","mem","formatted","valOptions","error","removePending","q","Connector","backend","store","languages","callback","toLoad","pending","toLoadLanguages","toLoadNamespaces","hasAllNamespaces","loaded","loadedKeys","n","fcName","tried","wait","resolver","fallbackValue","isUpdate","clb","_c","_d","_e","get","ret","transformOptions","noop","bindMemberFunctions","inst","I18n","_I18n","defOpts","createClassOnDemand","ClassOrObject","lu","deferred","load","finish","usedCallback","append","li","lngInLngs","setLngProps","done","setLng","fl","keyPrefix","fixedT","resultKey","fallbackLng","lastLng","loadNotPending","loadState","preResult","preloaded","newLngs","ti","rtlLngs","instance","forkResourceStore","mergedOptions","clone","clonedData","prev","acc","createInstance","dir","init","loadResources","reloadResources","use","changeLanguage","getFixedT","exists","setDefaultNamespace","hasLoadedNamespace","loadNamespaces","loadLanguages","import_react","isCheckBoxInput","element","isDateObject","value","isNullOrUndefined","isObjectType","isObject","getEventValue","event","getNodeParentName","name","isNameInFieldArray","names","isPlainObject","tempObject","prototypeCopy","isWeb","cloneObject","data","copy","isArray","isFileListInstance","key","isKey","isUndefined","val","compact","stringToPath","input","get","object","path","defaultValue","result","isBoolean","set","index","tempPath","length","lastIndex","newValue","objValue","EVENTS","VALIDATION_MODE","INPUT_VALIDATION_RULES","HookFormContext","React","FormProvider","props","_a","children","data","__objRest","React","HookFormContext","getProxyFormState","formState","control","localProxyFormState","isRoot","result","key","_key","VALIDATION_MODE","useIsomorphicLayoutEffect","isString","value","generateWatchOutput","names","_names","formValues","isGlobal","defaultValue","get","fieldName","isPrimitive","isNullOrUndefined","isObjectType","deepEqual","object1","object2","_internal_visited","isDateObject","keys1","keys2","key","val1","val2","isObject","appendErrors","name","validateAllFieldCriteria","errors","type","message","__spreadProps","__spreadValues","convertToArrayPayload","value","createSubject","_observers","observer","o","extractFormValues","fieldsState","formValues","values","key","fieldState","fieldValue","isObject","nestedFieldsState","isEmptyObject","isFileInput","element","isFunction","isHTMLElement","isWeb","owner","isMultipleSelect","isRadioInput","isRadioOrCheckbox","ref","isCheckBoxInput","live","baseGet","object","updatePath","length","index","isUndefined","isEmptyArray","obj","unset","path","paths","isKey","stringToPath","childObject","objectHasFunction","data","isTraversable","markFieldsDirty","fields","getDirtyFields","dirtyFieldsFromValues","isPrimitive","isNullOrUndefined","formValue","deepEqual","defaultResult","validResult","getCheckboxValue","options","option","getFieldValueAs","valueAsNumber","valueAsDate","setValueAs","isString","defaultReturn","getRadioValue","previous","getFieldValue","_f","isCheckBox","getResolverOptions","fieldsNames","_fields","criteriaMode","shouldUseNativeValidation","field","get","set","isRegex","getRuleValue","rule","getValidationModes","mode","VALIDATION_MODE","ASYNC_FUNCTION","hasPromiseValidation","fieldReference","validateFunction","hasValidation","isWatched","_names","isBlurEvent","watchName","iterateFieldsByAction","action","abortEarly","_a","currentField","__objRest","schemaErrorLookup","error","names","fieldName","foundError","shouldRenderFormState","formStateData","_proxyFormState","updateFormState","isRoot","formState","shouldSubscribeByName","signalName","exact","currentName","skipValidation","isTouched","isSubmitted","reValidateMode","unsetEmptyArray","compact","updateFieldArrayRootError","fieldArrayErrors","getValidateError","result","isBoolean","getValueAndMessage","validationData","validateField","disabledFieldNames","isFieldArray","__async","refs","required","maxLength","minLength","min","max","pattern","validate","mount","inputValue","inputRef","setCustomValidity","isRadio","isEmpty","appendErrorsCurry","getMinMaxMessage","exceedMax","maxLengthMessage","minLengthMessage","maxType","INPUT_VALIDATION_RULES","minType","exceedMin","maxOutput","minOutput","valueNumber","valueDate","convertTimeToDate","time","isTime","isWeek","maxLengthOutput","minLengthOutput","patternValue","validateError","validationResult","defaultOptions","createFormControl","props","_options","_formState","_defaultValues","cloneObject","_formValues","_state","delayErrorCallback","timer","_proxySubscribeFormState","_subjects","shouldDisplayAllAssociatedErrors","debounce","callback","wait","_setValid","shouldUpdateValid","isValid","_runSchema","executeBuiltInValidation","_updateIsValidating","isValidating","_setFieldArray","method","args","shouldSetValues","shouldUpdateFieldsAndState","fieldValues","touchedFields","_getDirty","updateErrors","_setErrors","updateValidAndValue","shouldSkipSetValueAs","defaultValue","setFieldValue","updateTouchAndDirty","shouldDirty","shouldRender","shouldUpdateField","isPreviousDirty","output","isCurrentFieldPristine","isPreviousFieldTouched","shouldRenderByError","previousFieldError","updatedFormState","executeSchemaAndUpdateState","_0","_1","_2","shouldOnlyCheckValid","context","isFieldArrayRoot","isPromiseFunction","fieldError","_removeUnmounted","unregister","getValues","_getWatch","isGlobal","generateWatchOutput","_getFieldArray","optionRef","checkboxRef","radioRef","trigger","setValues","fieldKey","isDateObject","setValue","cloneValue","onChange","event","target","isFieldValueUpdated","_updateIsFieldValueUpdated","validationModeBeforeSubmit","validationModeAfterSubmit","getEventValue","EVENTS","shouldSkipValidation","watched","previousErrorLookupResult","errorLookupResult","_focusInput","fieldNames","config","getFieldState","clearErrors","inputName","setError","currentRef","restOfErrorTree","watch","payload","_subscribe","_setFormState","subscribe","_setDisabledField","disabled","register","disabledIsDefined","fieldRef","radioOrCheckbox","isNameInFieldArray","_focusError","_disableForm","handleSubmit","onValid","onInvalid","e","onValidError","resetField","_reset","keepStateOptions","updatedValues","cloneUpdatedValues","isEmptyResetValues","fieldsToCheck","form","reset","setFocus","methods","useForm","props","_formControl","React","_values","formState","updateFormState","isFunction","__spreadProps","__spreadValues","_a","createFormControl","formControl","rest","__objRest","control","useIsomorphicLayoutEffect","sub","data","isDirty","deepEqual","state","getProxyFormState","import_jsx_runtime","OpenSessionModal","props","openModal","setOpenModal","methods","row","record","openSession","setOpeningCashBox","use_session_provider_default","money","setMoney","loading","setLoading","data","_a","_b","onClose","navigate","useNavigate","handleOpeningCashBoxSuccess","sessionId","QUERY_KEYS","onSetOpeningCashBox","cashBoxValue","__async","error","handleOpenSession","res","sessionIdNew","handleAmountChange","e","rawValue","modal_zoom_default","FormProvider","__spreadProps","__spreadValues","t","formatCurrency","button_action_default","open_shift_default","toKebabCase","string","toCamelCase","match","p1","p2","toPascalCase","camelCase","mergeClasses","classes","className","index","array","hasA11yProp","props","prop","defaultAttributes","Icon","_a","ref","_b","color","size","strokeWidth","absoluteStrokeWidth","className","children","iconNode","rest","__objRest","__spreadValues","__spreadProps","defaultAttributes","mergeClasses","hasA11yProp","tag","attrs","createLucideIcon","iconName","iconNode","Component","_a","ref","_b","className","props","__objRest","Icon","__spreadValues","mergeClasses","toKebabCase","toPascalCase","__iconNode","Plus","createLucideIcon","import_react","import_jsx_runtime","PosTemplate","row","columns","onClickRow","settings_act_id","res_model","opened","navigate","useNavigate","openModal","setOpenModal","methods","useForm","date","navigateToPosManagement","_a","isModePosRestaurant","sessionId","posId","query","createSearchParams","QUERY_KEYS","navigateSettingManagement","e","__async","t","Line","hh_mm","dd_mm_yyyy","IcSetting","Plus","open_shift_default","pos_template_default"]}