{ "version": 3, "sources": ["../../../../../node_modules/.pnpm/scheduler@0.25.0/node_modules/scheduler/cjs/scheduler.production.js", "../../../../../node_modules/.pnpm/scheduler@0.25.0/node_modules/scheduler/index.js", "../../../../../node_modules/.pnpm/react-is@16.13.1/node_modules/react-is/cjs/react-is.production.min.js", "../../../../../node_modules/.pnpm/react-is@16.13.1/node_modules/react-is/index.js", "../../../../../node_modules/.pnpm/hoist-non-react-statics@3.3.2/node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js", "../../../../../node_modules/.pnpm/bson-objectid@2.0.4/node_modules/bson-objectid/objectid.js", "../../../../../node_modules/.pnpm/object-to-formdata@4.5.1/node_modules/object-to-formdata/src/index.js", "../../../../../node_modules/.pnpm/crypt@0.0.2/node_modules/crypt/crypt.js", "../../../../../node_modules/.pnpm/charenc@0.0.2/node_modules/charenc/charenc.js", "../../../../../node_modules/.pnpm/is-buffer@1.1.6/node_modules/is-buffer/index.js", "../../../../../node_modules/.pnpm/md5@2.3.0/node_modules/md5/md5.js", "../../../src/forms/RowLabel/index.tsx", "../../../src/elements/RenderCustomComponent/index.tsx", "../../../src/forms/RowLabel/Context/index.tsx", "../../../src/forms/Form/context.ts", "../../../../../node_modules/.pnpm/use-context-selector@2.0.0_react@19.2.4_scheduler@0.25.0/node_modules/use-context-selector/dist/index.js", "../../../src/fields/Array/index.tsx", "../../../../../node_modules/.pnpm/sonner@1.7.4_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/sonner/src/index.tsx", "../../../../../node_modules/.pnpm/sonner@1.7.4_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/sonner/src/assets.tsx", "../../../../../node_modules/.pnpm/sonner@1.7.4_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/sonner/src/hooks.tsx", "../../../../../node_modules/.pnpm/sonner@1.7.4_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/sonner/src/state.ts", "../../../../../node_modules/.pnpm/sonner@1.7.4_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/sonner/dist/index.mjs.map", "../../../../../node_modules/.pnpm/sonner@1.7.4_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/sonner/src/styles.css", "../../../../../node_modules/.pnpm/sonner@1.7.4_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/sonner/src/types.ts", "../../../src/elements/Banner/index.tsx", "../../../src/elements/Link/index.tsx", "../../../src/providers/RouteTransition/index.tsx", "../../../src/elements/Link/formatUrl.ts", "../../../src/elements/Button/index.tsx", "../../../src/icons/Chevron/index.tsx", "../../../src/icons/Edit/index.tsx", "../../../src/icons/Link/index.tsx", "../../../src/icons/Plus/index.tsx", "../../../src/icons/Swap/index.tsx", "../../../src/elements/Popup/PopupButtonList/index.tsx", "../../../src/elements/Popup/PopupDivider/index.tsx", "../../../src/elements/Popup/PopupGroupLabel/index.tsx", "../../../src/elements/Popup/index.tsx", "../../../src/hooks/useEffectEvent.ts", "../../../src/elements/Popup/PopupTrigger/index.tsx", "../../../src/elements/Tooltip/index.tsx", "../../../src/hooks/useIntersect.ts", "../../../src/elements/ClipboardAction/isClipboardDataValid.ts", "../../../src/elements/ClipboardAction/clipboardUtilities.ts", "../../../src/elements/ClipboardAction/index.tsx", "../../../src/icons/More/index.tsx", "../../../src/elements/ClipboardAction/ClipboardActionLabel.tsx", "../../../src/icons/Copy/index.tsx", "../../../src/elements/ClipboardAction/mergeFormStateFromClipboard.ts", "../../../src/elements/DraggableSortable/DraggableSortableItem/index.tsx", "../../../src/elements/DraggableSortable/useDraggableSortable/index.tsx", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/hooks/useCombinedRefs.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/execution-context/canUseDOM.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/type-guards/isWindow.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/type-guards/isNode.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/execution-context/getWindow.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/type-guards/isDocument.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/type-guards/isHTMLElement.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/type-guards/isSVGElement.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/execution-context/getOwnerDocument.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/hooks/useIsomorphicLayoutEffect.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/hooks/useEvent.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/hooks/useInterval.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/hooks/useLatestValue.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/hooks/useLazyMemo.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/hooks/useNodeRef.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/hooks/usePrevious.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/hooks/useUniqueId.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/adjustment.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/event/hasViewportRelativeCoordinates.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/event/isKeyboardEvent.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/event/isTouchEvent.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/coordinates/getEventCoordinates.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/css.ts", "../../../../../node_modules/.pnpm/@dnd-kit+utilities@3.2.2_react@19.2.4/node_modules/@dnd-kit/utilities/src/focus/findFirstFocusableNode.ts", "../../../../../node_modules/.pnpm/@dnd-kit+sortable@10.0.0_@dnd-kit+core@6.3.1_react-dom@19.2.4_react@19.2.4__react@19.2.4__react@19.2.4/node_modules/@dnd-kit/sortable/src/utilities/arrayMove.ts", "../../../../../node_modules/.pnpm/@dnd-kit+sortable@10.0.0_@dnd-kit+core@6.3.1_react-dom@19.2.4_react@19.2.4__react@19.2.4__react@19.2.4/node_modules/@dnd-kit/sortable/src/utilities/arraySwap.ts", "../../../../../node_modules/.pnpm/@dnd-kit+sortable@10.0.0_@dnd-kit+core@6.3.1_react-dom@19.2.4_react@19.2.4__react@19.2.4__react@19.2.4/node_modules/@dnd-kit/sortable/src/utilities/getSortedRects.ts", "../../../../../node_modules/.pnpm/@dnd-kit+sortable@10.0.0_@dnd-kit+core@6.3.1_react-dom@19.2.4_react@19.2.4__react@19.2.4__react@19.2.4/node_modules/@dnd-kit/sortable/src/utilities/isValidIndex.ts", "../../../../../node_modules/.pnpm/@dnd-kit+sortable@10.0.0_@dnd-kit+core@6.3.1_react-dom@19.2.4_react@19.2.4__react@19.2.4__react@19.2.4/node_modules/@dnd-kit/sortable/src/utilities/itemsEqual.ts", "../../../../../node_modules/.pnpm/@dnd-kit+sortable@10.0.0_@dnd-kit+core@6.3.1_react-dom@19.2.4_react@19.2.4__react@19.2.4__react@19.2.4/node_modules/@dnd-kit/sortable/src/utilities/normalizeDisabled.ts", "../../../../../node_modules/.pnpm/@dnd-kit+sortable@10.0.0_@dnd-kit+core@6.3.1_react-dom@19.2.4_react@19.2.4__react@19.2.4__react@19.2.4/node_modules/@dnd-kit/sortable/src/strategies/horizontalListSorting.ts", "../../../../../node_modules/.pnpm/@dnd-kit+sortable@10.0.0_@dnd-kit+core@6.3.1_react-dom@19.2.4_react@19.2.4__react@19.2.4__react@19.2.4/node_modules/@dnd-kit/sortable/src/strategies/rectSorting.ts", "../../../../../node_modules/.pnpm/@dnd-kit+sortable@10.0.0_@dnd-kit+core@6.3.1_react-dom@19.2.4_react@19.2.4__react@19.2.4__react@19.2.4/node_modules/@dnd-kit/sortable/src/strategies/rectSwapping.ts", "../../../../../node_modules/.pnpm/@dnd-kit+sortable@10.0.0_@dnd-kit+core@6.3.1_react-dom@19.2.4_react@19.2.4__react@19.2.4__react@19.2.4/node_modules/@dnd-kit/sortable/src/strategies/verticalListSorting.ts", "../../../../../node_modules/.pnpm/@dnd-kit+sortable@10.0.0_@dnd-kit+core@6.3.1_react-dom@19.2.4_react@19.2.4__react@19.2.4__react@19.2.4/node_modules/@dnd-kit/sortable/src/components/SortableContext.tsx", "../../../../../node_modules/.pnpm/@dnd-kit+sortable@10.0.0_@dnd-kit+core@6.3.1_react-dom@19.2.4_react@19.2.4__react@19.2.4__react@19.2.4/node_modules/@dnd-kit/sortable/src/hooks/defaults.ts", "../../../../../node_modules/.pnpm/@dnd-kit+sortable@10.0.0_@dnd-kit+core@6.3.1_react-dom@19.2.4_react@19.2.4__react@19.2.4__react@19.2.4/node_modules/@dnd-kit/sortable/src/hooks/utilities/useDerivedTransform.ts", "../../../../../node_modules/.pnpm/@dnd-kit+sortable@10.0.0_@dnd-kit+core@6.3.1_react-dom@19.2.4_react@19.2.4__react@19.2.4__react@19.2.4/node_modules/@dnd-kit/sortable/src/hooks/useSortable.ts", "../../../../../node_modules/.pnpm/@dnd-kit+sortable@10.0.0_@dnd-kit+core@6.3.1_react-dom@19.2.4_react@19.2.4__react@19.2.4__react@19.2.4/node_modules/@dnd-kit/sortable/src/types/type-guard.ts", "../../../../../node_modules/.pnpm/@dnd-kit+sortable@10.0.0_@dnd-kit+core@6.3.1_react-dom@19.2.4_react@19.2.4__react@19.2.4__react@19.2.4/node_modules/@dnd-kit/sortable/src/sensors/keyboard/sortableKeyboardCoordinates.ts", "../../../src/elements/DraggableSortable/index.tsx", "../../../src/elements/ErrorPill/index.tsx", "../../../src/fields/FieldDescription/index.tsx", "../../../src/fields/FieldError/index.tsx", "../../../src/fields/FieldLabel/index.tsx", "../../../src/providers/EditDepth/index.tsx", "../../../src/providers/Locale/index.tsx", "../../../src/utilities/findLocaleFromCode.ts", "../../../../../node_modules/.pnpm/@faceless-ui+modal@3.0.0_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/modal/src/asModal/index.tsx", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/extends.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js", "../../../../../node_modules/.pnpm/dom-helpers@5.2.1/node_modules/dom-helpers/esm/hasClass.js", "../../../../../node_modules/.pnpm/dom-helpers@5.2.1/node_modules/dom-helpers/esm/addClass.js", "../../../../../node_modules/.pnpm/dom-helpers@5.2.1/node_modules/dom-helpers/esm/removeClass.js", "../../../../../node_modules/.pnpm/react-transition-group@4.4.5_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/react-transition-group/esm/CSSTransition.js", "../../../../../node_modules/.pnpm/react-transition-group@4.4.5_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/react-transition-group/esm/Transition.js", "../../../../../node_modules/.pnpm/react-transition-group@4.4.5_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/react-transition-group/esm/config.js", "../../../../../node_modules/.pnpm/react-transition-group@4.4.5_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/react-transition-group/esm/TransitionGroupContext.js", "../../../../../node_modules/.pnpm/react-transition-group@4.4.5_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/react-transition-group/esm/utils/reflow.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js", "../../../../../node_modules/.pnpm/@faceless-ui+modal@3.0.0_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/modal/src/useModal/index.tsx", "../../../../../node_modules/.pnpm/@faceless-ui+modal@3.0.0_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/modal/src/ModalProvider/context.tsx", "../../../../../node_modules/.pnpm/@faceless-ui+modal@3.0.0_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/modal/src/ModalProvider/generateTransitionClasses.ts", "../../../../../node_modules/.pnpm/focus-trap@7.5.4/node_modules/focus-trap/index.js", "../../../../../node_modules/.pnpm/@faceless-ui+modal@3.0.0_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/modal/src/Modal/index.tsx", "../../../../../node_modules/.pnpm/@faceless-ui+modal@3.0.0_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/modal/src/ModalContainer/index.tsx", "../../../../../node_modules/.pnpm/@faceless-ui+modal@3.0.0_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/modal/src/ModalProvider/index.tsx", "../../../../../node_modules/.pnpm/body-scroll-lock@4.0.0-beta.0/node_modules/body-scroll-lock/lib/bodyScrollLock.esm.js", "../../../../../node_modules/.pnpm/@faceless-ui+modal@3.0.0_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/modal/src/ModalProvider/generateCSS.tsx", "../../../../../node_modules/.pnpm/@faceless-ui+modal@3.0.0_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/modal/src/ModalProvider/reducer.ts", "../../../src/providers/Auth/index.tsx", "../../../src/elements/StayLoggedIn/index.tsx", "../../../src/elements/ConfirmationModal/index.tsx", "../../../src/elements/Drawer/index.tsx", "../../../src/elements/Gutter/index.tsx", "../../../src/elements/Drawer/useDrawerSlug.tsx", "../../../src/utilities/api.ts", "../../../src/utilities/generateFieldID.ts", "../../../src/forms/Form/rowHelpers.ts", "../../../src/forms/NullifyField/index.tsx", "../../../src/fields/Checkbox/index.tsx", "../../../src/forms/useField/index.tsx", "../../../src/hooks/useThrottledEffect.ts", "../../../src/providers/DocumentInfo/index.tsx", "../../../src/utilities/formatDocTitle/index.ts", "../../../../../node_modules/.pnpm/@date-fns+tz@1.2.0/node_modules/@date-fns/tz/tzOffset/index.js", "../../../../../node_modules/.pnpm/@date-fns+tz@1.2.0/node_modules/@date-fns/tz/date/mini.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constants.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constructFrom.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/toDate.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/defaultOptions.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfWeek.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfISOWeek.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeekYear.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/getTimezoneOffsetInMilliseconds.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/normalizeDates.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfDay.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarDays.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfISOWeekYear.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/compareAsc.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constructNow.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameDay.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isDate.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isValid.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarMonths.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/getRoundingMethod.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMilliseconds.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfDay.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfMonth.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isLastDayOfMonth.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMonths.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInSeconds.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfYear.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfToday.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDayOfYear.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeek.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeekYear.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfWeekYear.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeek.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/addLeadingZeros.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/format/lightFormatters.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/format/formatters.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/format/longFormatters.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/protectedTokens.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/format.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistance.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceToNow.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/transpose.js", "../../../../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isToday.js", "../../../src/utilities/formatDocTitle/formatDateTitle.ts", "../../../src/utilities/formatDocTitle/formatLexicalDocTitle.ts", "../../../src/utilities/formatDocTitle/formatRelationshipTitle.ts", "../../../src/providers/DocumentTitle/index.tsx", "../../../src/providers/Preferences/index.tsx", "../../../src/utilities/deepMerge.ts", "../../../src/providers/UploadEdits/index.tsx", "../../../src/providers/DocumentInfo/useGetDocPermissions.tsx", "../../../src/utilities/hasSavePermission.ts", "../../../src/utilities/isEditing.ts", "../../../src/providers/Operation/index.tsx", "../../../src/forms/RenderFields/context.ts", "../../../src/forms/withCondition/index.tsx", "../../../src/forms/withCondition/WatchCondition.tsx", "../../../src/fields/mergeFieldStyles.ts", "../../../src/fields/shared/index.tsx", "../../../src/fields/Checkbox/Input.tsx", "../../../src/icons/Check/index.tsx", "../../../src/icons/Line/index.tsx", "../../../src/utilities/scrollToID.ts", "../../../src/fields/Array/ArrayRow.tsx", "../../../src/elements/ArrayAction/index.tsx", "../../../src/elements/Collapsible/index.tsx", "../../../src/icons/DragHandle/index.tsx", "../../../src/elements/AnimateHeight/index.tsx", "../../../src/elements/AnimateHeight/usePatchAnimateHeight.ts", "../../../src/elements/Collapsible/provider.tsx", "../../../src/forms/RenderFields/index.tsx", "../../../src/elements/RenderIfInViewport/index.tsx", "../../../src/forms/RenderFields/RenderField.tsx", "../../../src/fields/Blocks/index.tsx", "../../../src/fields/Blocks/BlockRow.tsx", "../../../src/elements/Pill/index.tsx", "../../../src/hooks/useThrottledValue.ts", "../../../src/fields/Blocks/RowActions.tsx", "../../../src/fields/Blocks/BlocksDrawer/index.tsx", "../../../src/fields/Blocks/BlockSelector/index.tsx", "../../../src/elements/ThumbnailCard/index.tsx", "../../../src/graphics/DefaultBlockImage/index.tsx", "../../../../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/esm-browser/stringify.js", "../../../../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/esm-browser/rng.js", "../../../../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/esm-browser/native.js", "../../../../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/esm-browser/v4.js", "../../../src/fields/Blocks/BlockSelector/BlockSearch/index.tsx", "../../../src/icons/Search/index.tsx", "../../../src/fields/Blocks/SectionTitle/index.tsx", "../../../src/fields/Code/index.tsx", "../../../src/elements/CodeEditor/index.tsx", "../../../src/fields/Collapsible/index.tsx", "../../../src/forms/WatchChildErrors/index.tsx", "../../../src/forms/WatchChildErrors/buildPathSegments.ts", "../../../src/fields/DateTime/index.tsx", "../../../src/elements/DatePicker/index.tsx", "../../../src/elements/TimezonePicker/index.tsx", "../../../src/elements/ReactSelect/index.tsx", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/typeof.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/toPrimitive.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/defineProperty.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/objectSpread2.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/slicedToArray.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js", "../../../../../node_modules/.pnpm/react-select@5.9.0_@types+react@19.2.9_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/react-select/dist/useStateManager-7e1e8489.esm.js", "../../../../../node_modules/.pnpm/react-select@5.9.0_@types+react@19.2.9_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/react-select/dist/react-select.esm.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/classCallCheck.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/createClass.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/inherits.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/createSuper.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/iterableToArray.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js", "../../../../../node_modules/.pnpm/react-select@5.9.0_@types+react@19.2.9_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/react-select/dist/Select-aab027f3.esm.js", "../../../../../node_modules/.pnpm/@emotion+react@11.14.0_@types+react@19.2.9_react@19.2.4/node_modules/@emotion/react/dist/emotion-element-f0de968e.browser.esm.js", "../../../../../node_modules/.pnpm/@emotion+sheet@1.4.0/node_modules/@emotion/sheet/dist/emotion-sheet.esm.js", "../../../../../node_modules/.pnpm/stylis@4.2.0/node_modules/stylis/src/Enum.js", "../../../../../node_modules/.pnpm/stylis@4.2.0/node_modules/stylis/src/Utility.js", "../../../../../node_modules/.pnpm/stylis@4.2.0/node_modules/stylis/src/Tokenizer.js", "../../../../../node_modules/.pnpm/stylis@4.2.0/node_modules/stylis/src/Parser.js", "../../../../../node_modules/.pnpm/stylis@4.2.0/node_modules/stylis/src/Serializer.js", "../../../../../node_modules/.pnpm/stylis@4.2.0/node_modules/stylis/src/Middleware.js", "../../../../../node_modules/.pnpm/@emotion+memoize@0.9.0/node_modules/@emotion/memoize/dist/emotion-memoize.esm.js", "../../../../../node_modules/.pnpm/@emotion+cache@11.14.0/node_modules/@emotion/cache/dist/emotion-cache.browser.esm.js", "../../../../../node_modules/.pnpm/@emotion+utils@1.4.2/node_modules/@emotion/utils/dist/emotion-utils.browser.esm.js", "../../../../../node_modules/.pnpm/@emotion+hash@0.9.2/node_modules/@emotion/hash/dist/emotion-hash.esm.js", "../../../../../node_modules/.pnpm/@emotion+unitless@0.10.0/node_modules/@emotion/unitless/dist/emotion-unitless.esm.js", "../../../../../node_modules/.pnpm/@emotion+serialize@1.3.3/node_modules/@emotion/serialize/dist/emotion-serialize.esm.js", "../../../../../node_modules/.pnpm/@emotion+use-insertion-effect-with-fallbacks@1.2.0_react@19.2.4/node_modules/@emotion/use-insertion-effect-with-fallbacks/dist/emotion-use-insertion-effect-with-fallbacks.browser.esm.js", "../../../../../node_modules/.pnpm/@emotion+react@11.14.0_@types+react@19.2.9_react@19.2.4/node_modules/@emotion/react/dist/emotion-react.browser.esm.js", "../../../../../node_modules/.pnpm/@babel+runtime@7.28.6/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js", "../../../../../node_modules/.pnpm/react-select@5.9.0_@types+react@19.2.9_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/react-select/dist/index-641ee5b8.esm.js", "../../../../../node_modules/.pnpm/use-isomorphic-layout-effect@1.2.1_@types+react@19.2.9_react@19.2.4/node_modules/use-isomorphic-layout-effect/dist/use-isomorphic-layout-effect.browser.esm.js", "../../../../../node_modules/.pnpm/memoize-one@6.0.0/node_modules/memoize-one/dist/memoize-one.esm.js", "../../../../../node_modules/.pnpm/react-select@5.9.0_@types+react@19.2.9_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/react-select/creatable/dist/react-select-creatable.esm.js", "../../../../../node_modules/.pnpm/react-select@5.9.0_@types+react@19.2.9_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/react-select/dist/useCreatable-84008237.esm.js", "../../../src/elements/ReactSelect/ClearIndicator/index.tsx", "../../../src/elements/ReactSelect/Control/index.tsx", "../../../src/elements/ReactSelect/DropdownIndicator/index.tsx", "../../../src/elements/ReactSelect/Input/index.tsx", "../../../src/elements/ReactSelect/MultiValue/index.tsx", "../../../src/elements/ReactSelect/MultiValueLabel/index.tsx", "../../../src/elements/ReactSelect/MultiValueRemove/index.tsx", "../../../src/elements/ReactSelect/SingleValue/index.tsx", "../../../src/elements/ReactSelect/ValueContainer/index.tsx", "../../../src/elements/WhereBuilder/Condition/Select/formatOptions.ts", "../../../src/fields/Email/index.tsx", "../../../src/fields/Group/index.tsx", "../../../src/fields/Row/provider.tsx", "../../../src/fields/Tabs/provider.tsx", "../../../src/fields/Group/provider.tsx", "../../../src/fields/Hidden/index.tsx", "../../../src/fields/Join/index.tsx", "../../../src/elements/RelationshipTable/index.tsx", "../../../src/providers/ListQuery/index.tsx", "../../../src/elements/ListDrawer/Provider.tsx", "../../../src/utilities/parseSearchParams.ts", "../../../src/providers/ListQuery/context.ts", "../../../src/providers/ListQuery/mergeQuery.ts", "../../../src/providers/ListQuery/sanitizeQuery.ts", "../../../src/providers/ServerFunctions/index.tsx", "../../../src/providers/TableColumns/index.tsx", "../../../src/providers/TableColumns/context.ts", "../../../src/elements/ColumnSelector/index.tsx", "../../../src/elements/PillSelector/index.tsx", "../../../src/elements/DocumentDrawer/index.tsx", "../../../src/hooks/useRelatedCollections.ts", "../../../src/elements/DocumentDrawer/DrawerContent.tsx", "../../../src/elements/Loading/index.tsx", "../../../src/elements/LoadingOverlay/index.tsx", "../../../src/hooks/useDelayedRender.ts", "../../../src/elements/LoadingOverlay/reducer.ts", "../../../src/utilities/abortAndIgnore.ts", "../../../src/elements/DocumentDrawer/Provider.tsx", "../../../src/elements/Table/RelationshipProvider/index.tsx", "../../../src/hooks/useDebounce.ts", "../../../src/elements/Table/RelationshipProvider/reducer.ts", "../../../src/elements/RelationshipTable/AddNewButton.tsx", "../../../src/elements/RelationshipTable/cells/DrawerLink/index.tsx", "../../../src/providers/TableColumns/RenderDefaultCell/index.tsx", "../../../src/elements/Table/DefaultCell/index.tsx", "../../../src/utilities/formatAdminURL.ts", "../../../src/utilities/getDisplayedFieldValue.ts", "../../../src/utilities/isValidReactElement.ts", "../../../src/elements/Table/DefaultCell/fields/Code/index.tsx", "../../../src/elements/Table/DefaultCell/fields/Array/index.tsx", "../../../src/elements/Table/DefaultCell/fields/Blocks/index.tsx", "../../../src/elements/Table/DefaultCell/fields/Checkbox/index.tsx", "../../../src/elements/Table/DefaultCell/fields/Date/index.tsx", "../../../src/elements/Table/DefaultCell/fields/File/index.tsx", "../../../src/elements/Thumbnail/index.tsx", "../../../src/graphics/File/index.tsx", "../../../src/elements/Table/DefaultCell/fields/JSON/index.tsx", "../../../src/utilities/stringifyTruncated.ts", "../../../src/elements/Table/DefaultCell/fields/Relationship/index.tsx", "../../../src/utilities/canUseDOM.ts", "../../../src/elements/Table/DefaultCell/fields/Select/index.tsx", "../../../src/elements/Table/DefaultCell/fields/Textarea/index.tsx", "../../../src/elements/Table/DefaultCell/fields/index.tsx", "../../../src/elements/RelationshipTable/Pagination.tsx", "../../../src/elements/Pagination/index.tsx", "../../../src/elements/Pagination/ClickableArrow/index.tsx", "../../../src/elements/Pagination/Page/index.tsx", "../../../src/elements/Pagination/Separator/index.tsx", "../../../src/fields/JSON/index.tsx", "../../../src/fields/Number/index.tsx", "../../../src/fields/Point/index.tsx", "../../../src/fields/RadioGroup/index.tsx", "../../../src/fields/RadioGroup/Radio/index.tsx", "../../../src/fields/Relationship/index.tsx", "../../../src/fields/Relationship/Input.tsx", "../../../src/elements/AddNewRelation/index.tsx", "../../../src/elements/ListDrawer/index.tsx", "../../../src/elements/ListDrawer/DrawerContent.tsx", "../../../src/hooks/useDebouncedCallback.ts", "../../../src/hooks/useQueue.ts", "../../../src/providers/DocumentEvents/index.tsx", "../../../src/utilities/sanitizeFilterOptionsQuery.ts", "../../../src/fields/Relationship/createRelationMap.ts", "../../../src/fields/Relationship/findOptionsByValue.ts", "../../../src/fields/Relationship/optionsReducer.ts", "../../../src/fields/Relationship/select-components/MultiValueLabel/index.tsx", "../../../src/fields/Relationship/select-components/SingleValue/index.tsx", "../../../src/fields/RichText/index.tsx", "../../../src/fields/Row/index.tsx", "../../../src/fields/Select/index.tsx", "../../../src/fields/Select/Input.tsx", "../../../src/fields/Tabs/index.tsx", "../../../src/forms/Form/index.tsx", "../../../src/elements/Toasts/fieldErrors.tsx", "../../../src/hooks/useDebouncedEffect.ts", "../../../src/providers/UploadHandlers/index.tsx", "../../../src/forms/Form/errorMessages.ts", "../../../src/forms/Form/fieldReducer.ts", "../../../src/forms/Form/mergeServerFormState.ts", "../../../src/forms/Form/rows.ts", "../../../src/forms/Form/initContextState.ts", "../../../src/fields/Tabs/Tab/index.tsx", "../../../src/fields/Text/index.tsx", "../../../src/fields/Text/Input.tsx", "../../../src/fields/Textarea/index.tsx", "../../../src/fields/Textarea/Input.tsx", "../../../src/fields/UI/index.tsx", "../../../src/fields/Upload/index.tsx", "../../../src/elements/BulkUpload/index.tsx", "../../../src/providers/UploadControls/index.tsx", "../../../src/elements/BulkUpload/AddFilesView/index.tsx", "../../../src/elements/Dropzone/index.tsx", "../../../src/elements/BulkUpload/Header/index.tsx", "../../../src/elements/BulkUpload/DrawerCloseButton/index.tsx", "../../../src/elements/BulkUpload/AddingFilesView/index.tsx", "../../../src/elements/BulkUpload/ActionsBar/index.tsx", "../../../src/elements/BulkUpload/EditMany/index.tsx", "../../../src/elements/BulkUpload/FormsManager/index.tsx", "../../../src/elements/BulkUpload/FormsManager/createFormData.ts", "../../../src/elements/BulkUpload/FormsManager/reducer.ts", "../../../src/elements/BulkUpload/EditMany/DrawerContent.tsx", "../../../src/elements/FieldSelect/index.tsx", "../../../src/utilities/filterOutUploadFields.ts", "../../../src/elements/FieldSelect/reduceFieldOptions.ts", "../../../src/forms/Form/createNestedClientFieldPath.ts", "../../../src/utilities/combineFieldLabel.tsx", "../../../src/elements/BulkUpload/DiscardWithoutSaving/index.tsx", "../../../src/elements/BulkUpload/EditForm/index.tsx", "../../../src/elements/DocumentFields/index.tsx", "../../../src/elements/TrashBanner/index.tsx", "../../../src/icons/Trash/index.tsx", "../../../src/elements/FolderView/MoveDocToFolder/index.tsx", "../../../src/icons/Folder/index.tsx", "../../../src/elements/FolderView/Drawers/MoveToFolder/index.tsx", "../../../src/providers/Folders/index.tsx", "../../../src/providers/Folders/groupItemIDsByRelation.ts", "../../../src/providers/RouteCache/index.tsx", "../../../src/elements/DrawerActionHeader/index.tsx", "../../../src/forms/Submit/index.tsx", "../../../src/elements/DrawerContentContainer/index.tsx", "../../../src/elements/ListHeader/TitleActions/ListCreateNewDocInFolderButton.tsx", "../../../src/elements/NoListResults/index.tsx", "../../../src/elements/Translation/index.tsx", "../../../src/elements/FolderView/Breadcrumbs/index.tsx", "../../../src/elements/FolderView/ColoredFolderIcon/index.tsx", "../../../src/elements/Upload/index.tsx", "../../../src/elements/EditUpload/index.tsx", "../../../../../node_modules/.pnpm/react-image-crop@10.1.8_react@19.2.4/node_modules/react-image-crop/dist/index.js", "../../../src/elements/FileDetails/index.tsx", "../../../src/elements/FileDetails/DraggableFileDetails/index.tsx", "../../../src/elements/FileDetails/StaticFileDetails/index.tsx", "../../../src/elements/FileDetails/FileMeta/index.tsx", "../../../src/elements/CopyToClipboard/index.tsx", "../../../src/elements/PreviewSizes/index.tsx", "../../../src/elements/BulkUpload/FileSidebar/index.tsx", "../../../../../node_modules/.pnpm/@faceless-ui+window-info@3.0.1_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/window-info/src/index.ts", "../../../../../node_modules/.pnpm/@faceless-ui+window-info@3.0.1_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/window-info/src/useWindowInfo/index.tsx", "../../../../../node_modules/.pnpm/@faceless-ui+window-info@3.0.1_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/window-info/src/WindowInfoProvider/context.tsx", "../../../../../node_modules/.pnpm/@faceless-ui+window-info@3.0.1_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/window-info/src/WindowInfo/index.tsx", "../../../../../node_modules/.pnpm/@faceless-ui+window-info@3.0.1_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/window-info/src/WindowInfoProvider/index.tsx", "../../../../../node_modules/.pnpm/@faceless-ui+window-info@3.0.1_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/window-info/src/withWindowInfo/index.tsx", "../../../src/elements/Thumbnail/createThumbnail.ts", "../../../src/fields/Upload/Input.tsx", "../../../src/utilities/normalizeRelationshipValue.ts", "../../../src/fields/Upload/HasMany/index.tsx", "../../../src/fields/Upload/RelationshipContent/index.tsx", "../../../src/fields/Upload/UploadCard/index.tsx", "../../../src/fields/Upload/HasOne/index.tsx", "../../../src/fields/ConfirmPassword/index.tsx", "../../../src/fields/Password/index.tsx", "../../../src/fields/Password/input.tsx", "../../../src/fields/index.tsx", "../../../src/hooks/useHotkey.ts", "../../../src/hooks/usePayloadAPI.ts", "../../../src/hooks/useResize.ts", "../../../src/hooks/useUseAsTitle.ts", "../../../src/elements/SortHeader/index.tsx", "../../../src/icons/Sort/index.tsx", "../../../src/elements/SortRow/index.tsx", "../../../src/elements/Table/OrderableTable.tsx", "../../../src/elements/Table/OrderableRow.tsx", "../../../src/elements/Table/OrderableRowDragPreview.tsx", "../../../src/elements/QueryPresets/cells/ColumnsCell/index.tsx", "../../../src/elements/QueryPresets/cells/WhereCell/index.tsx", "../../../src/elements/QueryPresets/cells/AccessCell/index.tsx", "../../../src/elements/QueryPresets/cells/GroupByCell/index.tsx", "../../../src/utilities/reduceFieldsToOptions.tsx", "../../../src/elements/WhereBuilder/field-types.tsx", "../../../src/elements/QueryPresets/fields/ColumnsField/index.tsx", "../../../src/elements/QueryPresets/fields/WhereField/index.tsx", "../../../src/elements/QueryPresets/fields/GroupByField/index.tsx", "../../../src/elements/LeaveWithoutSaving/index.tsx", "../../../src/elements/LeaveWithoutSaving/usePreventLeave.tsx", "../../../src/elements/DocumentTakeOver/index.tsx", "../../../src/elements/DocumentLocked/index.tsx", "../../../src/utilities/isClientUserObject.ts", "../../../src/elements/ViewDescription/index.tsx", "../../../src/elements/AppHeader/index.tsx", "../../../src/graphics/Account/index.tsx", "../../../src/graphics/Account/Default/index.tsx", "../../../src/graphics/Account/Gravatar/index.tsx", "../../../src/providers/Actions/index.tsx", "../../../src/elements/Hamburger/index.tsx", "../../../src/icons/CloseMenu/index.tsx", "../../../src/icons/Menu/index.tsx", "../../../src/elements/Localizer/index.tsx", "../../../src/elements/Localizer/LocalizerLabel/index.tsx", "../../../src/elements/Nav/context.tsx", "../../../src/elements/Nav/NavToggler/index.tsx", "../../../src/elements/StepNav/index.tsx", "../../../src/graphics/Icon/index.tsx", "../../../src/elements/StepNav/context.tsx", "../../../src/elements/StepNav/SetStepNav.tsx", "../../../src/elements/Card/index.tsx", "../../../src/elements/CopyLocaleData/index.tsx", "../../../src/elements/DeleteMany/index.tsx", "../../../src/providers/Selection/index.tsx", "../../../src/elements/ListSelection/index.tsx", "../../../src/elements/DocumentControls/index.tsx", "../../../src/providers/LivePreview/context.ts", "../../../src/elements/Autosave/index.tsx", "../../../src/utilities/reduceFieldsToValuesWithValidation.ts", "../../../src/elements/DeleteDocument/index.tsx", "../../../src/elements/DuplicateDocument/index.tsx", "../../../src/utilities/traverseForLocalizedFields.ts", "../../../src/elements/DuplicateDocument/SelectLocalesDrawer/index.tsx", "../../../src/elements/LivePreview/Toggler/index.tsx", "../../../src/icons/Eye/index.tsx", "../../../src/elements/Locked/index.tsx", "../../../src/icons/Lock/index.tsx", "../../../src/elements/PermanentlyDeleteButton/index.tsx", "../../../src/elements/PreviewButton/index.tsx", "../../../src/icons/ExternalLink/index.tsx", "../../../src/elements/PublishButton/index.tsx", "../../../src/elements/PublishButton/ScheduleDrawer/index.tsx", "../../../src/elements/Table/index.tsx", "../../../src/elements/PublishButton/ScheduleDrawer/buildUpcomingColumns.tsx", "../../../src/elements/RestoreButton/index.tsx", "../../../src/elements/SaveButton/index.tsx", "../../../src/elements/SaveDraftButton/index.tsx", "../../../src/elements/Status/index.tsx", "../../../src/elements/UnpublishButton/index.tsx", "../../../src/elements/HTMLDiff/index.tsx", "../../../src/elements/HTMLDiff/diff/index.ts", "../../../src/hooks/useClickOutside.ts", "../../../src/providers/ClickOutside/index.tsx", "../../../src/elements/EditMany/index.tsx", "../../../src/elements/EditMany/DrawerContent.tsx", "../../../src/elements/FullscreenModal/index.tsx", "../../../src/elements/GenerateConfirmation/index.tsx", "../../../src/elements/HydrateAuthProvider/index.tsx", "../../../src/elements/ListControls/index.tsx", "../../../src/icons/Dots/index.tsx", "../../../src/elements/GroupByBuilder/index.tsx", "../../../src/elements/QueryPresets/QueryPresetBar/index.tsx", "../../../src/elements/QueryPresets/QueryPresetToggler/index.tsx", "../../../src/icons/People/index.tsx", "../../../src/elements/SearchFilter/index.tsx", "../../../src/elements/SearchBar/index.tsx", "../../../src/elements/WhereBuilder/index.tsx", "../../../src/elements/WhereBuilder/Condition/index.tsx", "../../../src/elements/WhereBuilder/Condition/DefaultFilter/index.tsx", "../../../src/elements/WhereBuilder/Condition/Date/index.tsx", "../../../src/elements/WhereBuilder/Condition/Number/index.tsx", "../../../src/elements/WhereBuilder/Condition/Relationship/index.tsx", "../../../src/elements/WhereBuilder/Condition/Relationship/optionsReducer.ts", "../../../src/elements/WhereBuilder/Condition/Select/index.tsx", "../../../src/elements/WhereBuilder/Condition/Text/index.tsx", "../../../src/elements/WhereBuilder/Condition/validOperators.ts", "../../../src/elements/ListControls/getTextFieldsToBeSearched.ts", "../../../src/views/List/ListSelection/index.tsx", "../../../src/elements/PublishMany/index.tsx", "../../../src/elements/PublishMany/DrawerContent.tsx", "../../../src/elements/RestoreMany/index.tsx", "../../../src/elements/UnpublishMany/index.tsx", "../../../src/elements/UnpublishMany/DrawerContent.tsx", "../../../src/views/List/ListHeader/index.tsx", "../../../src/elements/CloseModalButton/index.tsx", "../../../src/elements/DefaultListViewTabs/index.tsx", "../../../src/elements/ListHeader/DrawerRelationshipSelect/index.tsx", "../../../src/elements/ListHeader/index.tsx", "../../../src/elements/ListHeader/DrawerTitleActions/ListDrawerCreateNewDocButton.tsx", "../../../src/elements/ListHeader/TitleActions/ListBulkUploadButton.tsx", "../../../src/elements/ListHeader/TitleActions/ListCreateNewDocButton.tsx", "../../../src/elements/ListHeader/TitleActions/ListEmptyTrashButton.tsx", "../../../src/views/List/GroupByHeader/index.tsx", "../../../src/elements/PageControls/index.tsx", "../../../src/elements/PerPage/index.tsx", "../../../src/elements/StickyToolbar/index.tsx", "../../../src/elements/PageControls/GroupByPageControls.tsx", "../../../src/elements/Logout/index.tsx", "../../../src/icons/LogOut/index.tsx", "../../../src/elements/NavGroup/index.tsx", "../../../src/elements/Combobox/index.tsx", "../../../src/elements/FolderView/BrowseByFolderButton/index.tsx", "../../../src/elements/FolderView/FolderTypeField/index.tsx", "../../../src/elements/FolderView/FolderFileTable/index.tsx", "../../../src/icons/Document/index.tsx", "../../../src/elements/FolderView/DraggableTableRow/index.tsx", "../../../src/elements/FolderView/DraggableWithClick/index.tsx", "../../../src/elements/FolderView/SimpleTable/index.tsx", "../../../src/elements/FolderView/ItemCardGrid/index.tsx", "../../../src/elements/FolderView/FolderFileCard/index.tsx", "../../../src/icons/ThreeDots/index.tsx", "../../../src/elements/RenderTitle/index.tsx", "../../../src/elements/IDLabel/index.tsx", "../../../src/utilities/sanitizeID.ts", "../../../src/elements/SortColumn/index.tsx", "../../../src/elements/ItemsDrawer/index.tsx", "../../../src/elements/ItemsDrawer/ItemSearch/index.tsx", "../../../src/fields/Slug/index.tsx", "../../../src/icons/CodeBlock/index.tsx", "../../../src/icons/MinimizeMaximize/index.tsx", "../../../src/icons/Gear/index.tsx", "../../../src/icons/MoveFolder/index.tsx", "../../../src/icons/GridView/index.tsx", "../../../src/icons/ListView/index.tsx", "../../../src/providers/ToastContainer/icons/Error.tsx", "../../../src/providers/ToastContainer/icons/Info.tsx", "../../../src/providers/ToastContainer/icons/Success.tsx", "../../../src/providers/ToastContainer/icons/Warning.tsx", "../../../src/providers/ClientFunction/index.tsx", "../../../src/providers/LivePreview/index.tsx", "../../../src/hooks/usePopupWindow.ts", "../../../src/utilities/formatAbsoluteURL.ts", "../../../src/providers/LivePreview/collisionDetection.ts", "../../../src/providers/LivePreview/sizeReducer.ts", "../../../src/providers/RouteTransition/ProgressBar/index.tsx", "../../../src/providers/EntityVisibility/index.tsx", "../../../src/providers/Params/index.tsx", "../../../src/providers/Root/index.tsx", "../../../../../node_modules/.pnpm/@faceless-ui+scroll-info@2.0.0_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/scroll-info/src/ScrollInfo/index.tsx", "../../../../../node_modules/.pnpm/@faceless-ui+scroll-info@2.0.0_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/scroll-info/src/useScrollInfo/index.tsx", "../../../../../node_modules/.pnpm/@faceless-ui+scroll-info@2.0.0_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/scroll-info/src/ScrollInfoProvider/context.tsx", "../../../../../node_modules/.pnpm/@faceless-ui+scroll-info@2.0.0_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/scroll-info/src/ScrollInfoProvider/index.tsx", "../../../../../node_modules/.pnpm/@faceless-ui+scroll-info@2.0.0_react-dom@19.2.4_react@19.2.4__react@19.2.4/node_modules/@faceless-ui/scroll-info/src/withScrollInfo/index.tsx", "../../../src/elements/CloseModalOnRouteChange/index.tsx", "../../../src/providers/WindowInfo/index.tsx", "../../../src/providers/SearchParams/index.tsx", "../../../src/providers/ToastContainer/index.tsx", "../../../src/elements/EmailAndUsername/index.tsx", "../../../src/elements/SelectAll/index.tsx", "../../../src/elements/SelectRow/index.tsx", "../../../src/elements/SelectMany/index.tsx", "../../../src/views/List/index.tsx", "../../../src/views/CollectionFolder/index.tsx", "../../../src/elements/FolderView/CurrentFolderActions/index.tsx", "../../../src/elements/FolderView/DragOverlaySelection/index.tsx", "../../../src/elements/FolderView/SortByPill/index.tsx", "../../../src/elements/FolderView/ToggleViewButtons/index.tsx", "../../../src/views/CollectionFolder/ListSelection/index.tsx", "../../../src/elements/FolderView/Drawers/EditFolderAction/index.tsx", "../../../src/views/BrowseByFolder/index.tsx", "../../../src/elements/FolderView/FilterFolderTypePill/index.tsx", "../../../src/elements/CheckboxPopup/index.tsx", "../../../src/views/Edit/index.tsx", "../../../src/elements/DocumentDrawer/DrawerHeader/index.tsx", "../../../src/elements/LivePreview/Window/index.tsx", "../../../src/elements/LivePreview/Device/index.tsx", "../../../src/elements/LivePreview/IFrame/index.tsx", "../../../src/elements/LivePreview/Toolbar/index.tsx", "../../../src/elements/LivePreview/Toolbar/Controls/index.tsx", "../../../src/elements/LivePreview/Toolbar/SizeInput/index.tsx", "../../../src/utilities/handleBackToDashboard.tsx", "../../../src/utilities/handleGoBack.tsx", "../../../src/utilities/handleTakeOver.tsx", "../../../src/views/Edit/Auth/index.tsx", "../../../src/views/Edit/Auth/APIKey.tsx", "../../../src/views/Edit/SetDocumentStepNav/index.tsx", "../../../src/views/Edit/SetDocumentTitle/index.tsx", "../../../src/elements/FieldDiffLabel/index.tsx", "../../../src/elements/FieldDiffContainer/index.tsx"], "sourcesContent": ["/**\n * @license React\n * scheduler.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nfunction push(heap, node) {\n var index = heap.length;\n heap.push(node);\n a: for (; 0 < index; ) {\n var parentIndex = (index - 1) >>> 1,\n parent = heap[parentIndex];\n if (0 < compare(parent, node))\n (heap[parentIndex] = node), (heap[index] = parent), (index = parentIndex);\n else break a;\n }\n}\nfunction peek(heap) {\n return 0 === heap.length ? null : heap[0];\n}\nfunction pop(heap) {\n if (0 === heap.length) return null;\n var first = heap[0],\n last = heap.pop();\n if (last !== first) {\n heap[0] = last;\n a: for (\n var index = 0, length = heap.length, halfLength = length >>> 1;\n index < halfLength;\n\n ) {\n var leftIndex = 2 * (index + 1) - 1,\n left = heap[leftIndex],\n rightIndex = leftIndex + 1,\n right = heap[rightIndex];\n if (0 > compare(left, last))\n rightIndex < length && 0 > compare(right, left)\n ? ((heap[index] = right),\n (heap[rightIndex] = last),\n (index = rightIndex))\n : ((heap[index] = left),\n (heap[leftIndex] = last),\n (index = leftIndex));\n else if (rightIndex < length && 0 > compare(right, last))\n (heap[index] = right), (heap[rightIndex] = last), (index = rightIndex);\n else break a;\n }\n }\n return first;\n}\nfunction compare(a, b) {\n var diff = a.sortIndex - b.sortIndex;\n return 0 !== diff ? diff : a.id - b.id;\n}\nexports.unstable_now = void 0;\nif (\"object\" === typeof performance && \"function\" === typeof performance.now) {\n var localPerformance = performance;\n exports.unstable_now = function () {\n return localPerformance.now();\n };\n} else {\n var localDate = Date,\n initialTime = localDate.now();\n exports.unstable_now = function () {\n return localDate.now() - initialTime;\n };\n}\nvar taskQueue = [],\n timerQueue = [],\n taskIdCounter = 1,\n currentTask = null,\n currentPriorityLevel = 3,\n isPerformingWork = !1,\n isHostCallbackScheduled = !1,\n isHostTimeoutScheduled = !1,\n localSetTimeout = \"function\" === typeof setTimeout ? setTimeout : null,\n localClearTimeout = \"function\" === typeof clearTimeout ? clearTimeout : null,\n localSetImmediate = \"undefined\" !== typeof setImmediate ? setImmediate : null;\nfunction advanceTimers(currentTime) {\n for (var timer = peek(timerQueue); null !== timer; ) {\n if (null === timer.callback) pop(timerQueue);\n else if (timer.startTime <= currentTime)\n pop(timerQueue),\n (timer.sortIndex = timer.expirationTime),\n push(taskQueue, timer);\n else break;\n timer = peek(timerQueue);\n }\n}\nfunction handleTimeout(currentTime) {\n isHostTimeoutScheduled = !1;\n advanceTimers(currentTime);\n if (!isHostCallbackScheduled)\n if (null !== peek(taskQueue))\n (isHostCallbackScheduled = !0), requestHostCallback();\n else {\n var firstTimer = peek(timerQueue);\n null !== firstTimer &&\n requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);\n }\n}\nvar isMessageLoopRunning = !1,\n taskTimeoutID = -1,\n frameInterval = 5,\n startTime = -1;\nfunction shouldYieldToHost() {\n return exports.unstable_now() - startTime < frameInterval ? !1 : !0;\n}\nfunction performWorkUntilDeadline() {\n if (isMessageLoopRunning) {\n var currentTime = exports.unstable_now();\n startTime = currentTime;\n var hasMoreWork = !0;\n try {\n a: {\n isHostCallbackScheduled = !1;\n isHostTimeoutScheduled &&\n ((isHostTimeoutScheduled = !1),\n localClearTimeout(taskTimeoutID),\n (taskTimeoutID = -1));\n isPerformingWork = !0;\n var previousPriorityLevel = currentPriorityLevel;\n try {\n b: {\n advanceTimers(currentTime);\n for (\n currentTask = peek(taskQueue);\n null !== currentTask &&\n !(\n currentTask.expirationTime > currentTime && shouldYieldToHost()\n );\n\n ) {\n var callback = currentTask.callback;\n if (\"function\" === typeof callback) {\n currentTask.callback = null;\n currentPriorityLevel = currentTask.priorityLevel;\n var continuationCallback = callback(\n currentTask.expirationTime <= currentTime\n );\n currentTime = exports.unstable_now();\n if (\"function\" === typeof continuationCallback) {\n currentTask.callback = continuationCallback;\n advanceTimers(currentTime);\n hasMoreWork = !0;\n break b;\n }\n currentTask === peek(taskQueue) && pop(taskQueue);\n advanceTimers(currentTime);\n } else pop(taskQueue);\n currentTask = peek(taskQueue);\n }\n if (null !== currentTask) hasMoreWork = !0;\n else {\n var firstTimer = peek(timerQueue);\n null !== firstTimer &&\n requestHostTimeout(\n handleTimeout,\n firstTimer.startTime - currentTime\n );\n hasMoreWork = !1;\n }\n }\n break a;\n } finally {\n (currentTask = null),\n (currentPriorityLevel = previousPriorityLevel),\n (isPerformingWork = !1);\n }\n hasMoreWork = void 0;\n }\n } finally {\n hasMoreWork\n ? schedulePerformWorkUntilDeadline()\n : (isMessageLoopRunning = !1);\n }\n }\n}\nvar schedulePerformWorkUntilDeadline;\nif (\"function\" === typeof localSetImmediate)\n schedulePerformWorkUntilDeadline = function () {\n localSetImmediate(performWorkUntilDeadline);\n };\nelse if (\"undefined\" !== typeof MessageChannel) {\n var channel = new MessageChannel(),\n port = channel.port2;\n channel.port1.onmessage = performWorkUntilDeadline;\n schedulePerformWorkUntilDeadline = function () {\n port.postMessage(null);\n };\n} else\n schedulePerformWorkUntilDeadline = function () {\n localSetTimeout(performWorkUntilDeadline, 0);\n };\nfunction requestHostCallback() {\n isMessageLoopRunning ||\n ((isMessageLoopRunning = !0), schedulePerformWorkUntilDeadline());\n}\nfunction requestHostTimeout(callback, ms) {\n taskTimeoutID = localSetTimeout(function () {\n callback(exports.unstable_now());\n }, ms);\n}\nexports.unstable_IdlePriority = 5;\nexports.unstable_ImmediatePriority = 1;\nexports.unstable_LowPriority = 4;\nexports.unstable_NormalPriority = 3;\nexports.unstable_Profiling = null;\nexports.unstable_UserBlockingPriority = 2;\nexports.unstable_cancelCallback = function (task) {\n task.callback = null;\n};\nexports.unstable_continueExecution = function () {\n isHostCallbackScheduled ||\n isPerformingWork ||\n ((isHostCallbackScheduled = !0), requestHostCallback());\n};\nexports.unstable_forceFrameRate = function (fps) {\n 0 > fps || 125 < fps\n ? console.error(\n \"forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported\"\n )\n : (frameInterval = 0 < fps ? Math.floor(1e3 / fps) : 5);\n};\nexports.unstable_getCurrentPriorityLevel = function () {\n return currentPriorityLevel;\n};\nexports.unstable_getFirstCallbackNode = function () {\n return peek(taskQueue);\n};\nexports.unstable_next = function (eventHandler) {\n switch (currentPriorityLevel) {\n case 1:\n case 2:\n case 3:\n var priorityLevel = 3;\n break;\n default:\n priorityLevel = currentPriorityLevel;\n }\n var previousPriorityLevel = currentPriorityLevel;\n currentPriorityLevel = priorityLevel;\n try {\n return eventHandler();\n } finally {\n currentPriorityLevel = previousPriorityLevel;\n }\n};\nexports.unstable_pauseExecution = function () {};\nexports.unstable_requestPaint = function () {};\nexports.unstable_runWithPriority = function (priorityLevel, eventHandler) {\n switch (priorityLevel) {\n case 1:\n case 2:\n case 3:\n case 4:\n case 5:\n break;\n default:\n priorityLevel = 3;\n }\n var previousPriorityLevel = currentPriorityLevel;\n currentPriorityLevel = priorityLevel;\n try {\n return eventHandler();\n } finally {\n currentPriorityLevel = previousPriorityLevel;\n }\n};\nexports.unstable_scheduleCallback = function (\n priorityLevel,\n callback,\n options\n) {\n var currentTime = exports.unstable_now();\n \"object\" === typeof options && null !== options\n ? ((options = options.delay),\n (options =\n \"number\" === typeof options && 0 < options\n ? currentTime + options\n : currentTime))\n : (options = currentTime);\n switch (priorityLevel) {\n case 1:\n var timeout = -1;\n break;\n case 2:\n timeout = 250;\n break;\n case 5:\n timeout = 1073741823;\n break;\n case 4:\n timeout = 1e4;\n break;\n default:\n timeout = 5e3;\n }\n timeout = options + timeout;\n priorityLevel = {\n id: taskIdCounter++,\n callback: callback,\n priorityLevel: priorityLevel,\n startTime: options,\n expirationTime: timeout,\n sortIndex: -1\n };\n options > currentTime\n ? ((priorityLevel.sortIndex = options),\n push(timerQueue, priorityLevel),\n null === peek(taskQueue) &&\n priorityLevel === peek(timerQueue) &&\n (isHostTimeoutScheduled\n ? (localClearTimeout(taskTimeoutID), (taskTimeoutID = -1))\n : (isHostTimeoutScheduled = !0),\n requestHostTimeout(handleTimeout, options - currentTime)))\n : ((priorityLevel.sortIndex = timeout),\n push(taskQueue, priorityLevel),\n isHostCallbackScheduled ||\n isPerformingWork ||\n ((isHostCallbackScheduled = !0), requestHostCallback()));\n return priorityLevel;\n};\nexports.unstable_shouldYield = shouldYieldToHost;\nexports.unstable_wrapCallback = function (callback) {\n var parentPriorityLevel = currentPriorityLevel;\n return function () {\n var previousPriorityLevel = currentPriorityLevel;\n currentPriorityLevel = parentPriorityLevel;\n try {\n return callback.apply(this, arguments);\n } finally {\n currentPriorityLevel = previousPriorityLevel;\n }\n };\n};\n", "'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n", "/** @license React v16.13.1\n * react-is.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';var b=\"function\"===typeof Symbol&&Symbol.for,c=b?Symbol.for(\"react.element\"):60103,d=b?Symbol.for(\"react.portal\"):60106,e=b?Symbol.for(\"react.fragment\"):60107,f=b?Symbol.for(\"react.strict_mode\"):60108,g=b?Symbol.for(\"react.profiler\"):60114,h=b?Symbol.for(\"react.provider\"):60109,k=b?Symbol.for(\"react.context\"):60110,l=b?Symbol.for(\"react.async_mode\"):60111,m=b?Symbol.for(\"react.concurrent_mode\"):60111,n=b?Symbol.for(\"react.forward_ref\"):60112,p=b?Symbol.for(\"react.suspense\"):60113,q=b?\nSymbol.for(\"react.suspense_list\"):60120,r=b?Symbol.for(\"react.memo\"):60115,t=b?Symbol.for(\"react.lazy\"):60116,v=b?Symbol.for(\"react.block\"):60121,w=b?Symbol.for(\"react.fundamental\"):60117,x=b?Symbol.for(\"react.responder\"):60118,y=b?Symbol.for(\"react.scope\"):60119;\nfunction z(a){if(\"object\"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;\nexports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};\nexports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};\nexports.isValidElementType=function(a){return\"string\"===typeof a||\"function\"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||\"object\"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;\n", "'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-is.production.min.js');\n} else {\n module.exports = require('./cjs/react-is.development.js');\n}\n", "'use strict';\n\nvar reactIs = require('react-is');\n\n/**\n * Copyright 2015, Yahoo! Inc.\n * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.\n */\nvar REACT_STATICS = {\n childContextTypes: true,\n contextType: true,\n contextTypes: true,\n defaultProps: true,\n displayName: true,\n getDefaultProps: true,\n getDerivedStateFromError: true,\n getDerivedStateFromProps: true,\n mixins: true,\n propTypes: true,\n type: true\n};\nvar KNOWN_STATICS = {\n name: true,\n length: true,\n prototype: true,\n caller: true,\n callee: true,\n arguments: true,\n arity: true\n};\nvar FORWARD_REF_STATICS = {\n '$$typeof': true,\n render: true,\n defaultProps: true,\n displayName: true,\n propTypes: true\n};\nvar MEMO_STATICS = {\n '$$typeof': true,\n compare: true,\n defaultProps: true,\n displayName: true,\n propTypes: true,\n type: true\n};\nvar TYPE_STATICS = {};\nTYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;\nTYPE_STATICS[reactIs.Memo] = MEMO_STATICS;\n\nfunction getStatics(component) {\n // React v16.11 and below\n if (reactIs.isMemo(component)) {\n return MEMO_STATICS;\n } // React v16.12 and above\n\n\n return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;\n}\n\nvar defineProperty = Object.defineProperty;\nvar getOwnPropertyNames = Object.getOwnPropertyNames;\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar getPrototypeOf = Object.getPrototypeOf;\nvar objectPrototype = Object.prototype;\nfunction hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {\n if (typeof sourceComponent !== 'string') {\n // don't hoist over string (html) components\n if (objectPrototype) {\n var inheritedComponent = getPrototypeOf(sourceComponent);\n\n if (inheritedComponent && inheritedComponent !== objectPrototype) {\n hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);\n }\n }\n\n var keys = getOwnPropertyNames(sourceComponent);\n\n if (getOwnPropertySymbols) {\n keys = keys.concat(getOwnPropertySymbols(sourceComponent));\n }\n\n var targetStatics = getStatics(targetComponent);\n var sourceStatics = getStatics(sourceComponent);\n\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n\n if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {\n var descriptor = getOwnPropertyDescriptor(sourceComponent, key);\n\n try {\n // Avoid failures from read-only properties\n defineProperty(targetComponent, key, descriptor);\n } catch (e) {}\n }\n }\n }\n\n return targetComponent;\n}\n\nmodule.exports = hoistNonReactStatics;\n", "\nvar MACHINE_ID = Math.floor(Math.random() * 0xFFFFFF);\nvar index = ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10);\nvar pid = (typeof process === 'undefined' || typeof process.pid !== 'number' ? Math.floor(Math.random() * 100000) : process.pid) % 0xFFFF;\n// \n// Attempt to fallback Buffer if _Buffer is undefined (e.g. for Node.js).\n// Worst case fallback to null and handle with null checking before using.\nvar BufferCtr = (() => { try { return _Buffer; }catch(_){ try{ return Buffer; }catch(_){ return null; } } })();\n\n/**\n * Determine if an object is Buffer\n *\n * Author: Feross Aboukhadijeh \n * License: MIT\n *\n */\nvar isBuffer = function (obj) {\n return !!(\n obj != null &&\n obj.constructor &&\n typeof obj.constructor.isBuffer === 'function' &&\n obj.constructor.isBuffer(obj)\n )\n};\n\n// Precomputed hex table enables speedy hex string conversion\nvar hexTable = [];\nfor (var i = 0; i < 256; i++) {\n hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16);\n}\n\n// Regular expression that checks for hex value\nvar checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');\n\n// Lookup tables\nvar decodeLookup = [];\ni = 0;\nwhile (i < 10) decodeLookup[0x30 + i] = i++;\nwhile (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++;\n\n/**\n * Create a new immutable ObjectID instance\n *\n * @class Represents the BSON ObjectID type\n * @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number.\n * @return {Object} instance of ObjectID.\n */\nfunction ObjectID(id) {\n if(!(this instanceof ObjectID)) return new ObjectID(id);\n if(id && ((id instanceof ObjectID) || id._bsontype===\"ObjectID\"))\n return id;\n\n this._bsontype = 'ObjectID';\n\n // The most common usecase (blank id, new objectId instance)\n if (id == null || typeof id === 'number') {\n // Generate a new id\n this.id = this.generate(id);\n // Return the object\n return;\n }\n\n // Check if the passed in id is valid\n var valid = ObjectID.isValid(id);\n\n // Throw an error if it's not a valid setup\n if (!valid && id != null) {\n throw new Error(\n 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'\n );\n } else if (valid && typeof id === 'string' && id.length === 24) {\n return ObjectID.createFromHexString(id);\n } else if (id != null && id.length === 12) {\n // assume 12 byte string\n this.id = id;\n } else if (id != null && typeof id.toHexString === 'function') {\n // Duck-typing to support ObjectId from different npm packages\n return id;\n } else {\n throw new Error(\n 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'\n );\n }\n}\nmodule.exports = ObjectID;\nObjectID.default = ObjectID;\n\n/**\n * Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID.\n *\n * @param {Number} time an integer number representing a number of seconds.\n * @return {ObjectID} return the created ObjectID\n * @api public\n */\nObjectID.createFromTime = function(time){\n time = parseInt(time, 10) % 0xFFFFFFFF;\n return new ObjectID(hex(8,time)+\"0000000000000000\");\n};\n\n/**\n * Creates an ObjectID from a hex string representation of an ObjectID.\n *\n * @param {String} hexString create a ObjectID from a passed in 24 byte hexstring.\n * @return {ObjectID} return the created ObjectID\n * @api public\n */\nObjectID.createFromHexString = function(hexString) {\n // Throw an error if it's not a valid setup\n if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) {\n throw new Error(\n 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'\n );\n }\n\n // Calculate lengths\n var data = '';\n var i = 0;\n\n while (i < 24) {\n data += String.fromCharCode((decodeLookup[hexString.charCodeAt(i++)] << 4) | decodeLookup[hexString.charCodeAt(i++)]);\n }\n\n return new ObjectID(data);\n};\n\n/**\n * Checks if a value is a valid bson ObjectId\n *\n * @param {String} objectid Can be a 24 byte hex string or an instance of ObjectID.\n * @return {Boolean} return true if the value is a valid bson ObjectID, return false otherwise.\n * @api public\n *\n * THE NATIVE DOCUMENTATION ISN'T CLEAR ON THIS GUY!\n * http://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html#objectid-isvalid\n */\nObjectID.isValid = function(id) {\n if (id == null) return false;\n\n if (typeof id === 'number') {\n return true;\n }\n\n if (typeof id === 'string') {\n return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id));\n }\n\n if (id instanceof ObjectID) {\n return true;\n }\n\n // \n if (isBuffer(id)) {\n return ObjectID.isValid(id.toString('hex'));\n }\n\n // Duck-Typing detection of ObjectId like objects\n // \n if (typeof id.toHexString === 'function') {\n if(\n BufferCtr &&\n (id.id instanceof BufferCtr || typeof id.id === 'string')\n ) {\n return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id));\n }\n }\n\n return false;\n};\n\nObjectID.prototype = {\n constructor: ObjectID,\n\n /**\n * Return the ObjectID id as a 24 byte hex string representation\n *\n * @return {String} return the 24 byte hex string representation.\n * @api public\n */\n toHexString: function() {\n if (!this.id || !this.id.length) {\n throw new Error(\n 'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' +\n JSON.stringify(this.id) +\n ']'\n );\n }\n\n if (this.id.length === 24) {\n return this.id;\n }\n\n if (isBuffer(this.id)) {\n return this.id.toString('hex')\n }\n\n var hexString = '';\n for (var i = 0; i < this.id.length; i++) {\n hexString += hexTable[this.id.charCodeAt(i)];\n }\n\n return hexString;\n },\n\n /**\n * Compares the equality of this ObjectID with `otherID`.\n *\n * @param {Object} otherId ObjectID instance to compare against.\n * @return {Boolean} the result of comparing two ObjectID's\n * @api public\n */\n equals: function (otherId){\n if (otherId instanceof ObjectID) {\n return this.toString() === otherId.toString();\n } else if (\n typeof otherId === 'string' &&\n ObjectID.isValid(otherId) &&\n otherId.length === 12 &&\n isBuffer(this.id)\n ) {\n return otherId === this.id.toString('binary');\n } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) {\n return otherId.toLowerCase() === this.toHexString();\n } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) {\n return otherId === this.id;\n } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) {\n return otherId.toHexString() === this.toHexString();\n } else {\n return false;\n }\n },\n\n /**\n * Returns the generation date (accurate up to the second) that this ID was generated.\n *\n * @return {Date} the generation date\n * @api public\n */\n getTimestamp: function(){\n var timestamp = new Date();\n var time;\n if (isBuffer(this.id)) {\n time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24);\n } else {\n time = this.id.charCodeAt(3) | (this.id.charCodeAt(2) << 8) | (this.id.charCodeAt(1) << 16) | (this.id.charCodeAt(0) << 24);\n }\n timestamp.setTime(Math.floor(time) * 1000);\n return timestamp;\n },\n\n /**\n * Generate a 12 byte id buffer used in ObjectID's\n *\n * @method\n * @param {number} [time] optional parameter allowing to pass in a second based timestamp.\n * @return {string} return the 12 byte id buffer string.\n */\n generate: function (time) {\n if ('number' !== typeof time) {\n time = ~~(Date.now() / 1000);\n }\n\n //keep it in the ring!\n time = parseInt(time, 10) % 0xFFFFFFFF;\n\n var inc = next();\n\n return String.fromCharCode(\n ((time >> 24) & 0xFF),\n ((time >> 16) & 0xFF),\n ((time >> 8) & 0xFF),\n (time & 0xFF),\n ((MACHINE_ID >> 16) & 0xFF),\n ((MACHINE_ID >> 8) & 0xFF),\n (MACHINE_ID & 0xFF),\n ((pid >> 8) & 0xFF),\n (pid & 0xFF),\n ((inc >> 16) & 0xFF),\n ((inc >> 8) & 0xFF),\n (inc & 0xFF)\n )\n },\n};\n\nfunction next() {\n return index = (index+1) % 0xFFFFFF;\n}\n\nfunction hex(length, n) {\n n = n.toString(16);\n return (n.length===length)? n : \"00000000\".substring(n.length, length) + n;\n}\n\nfunction buffer(str) {\n var i=0,out=[];\n\n if(str.length===24)\n for(;i<24; out.push(parseInt(str[i]+str[i+1], 16)),i+=2);\n\n else if(str.length===12)\n for(;i<12; out.push(str.charCodeAt(i)),i++);\n\n return out;\n}\n\nvar inspect = (Symbol && Symbol.for && Symbol.for('nodejs.util.inspect.custom')) || 'inspect';\n\n/**\n * Converts to a string representation of this Id.\n *\n * @return {String} return the 24 byte hex string representation.\n * @api private\n */\nObjectID.prototype[inspect] = function() { return \"ObjectID(\"+this+\")\" };\nObjectID.prototype.toJSON = ObjectID.prototype.toHexString;\nObjectID.prototype.toString = ObjectID.prototype.toHexString;\n", "function isUndefined(value) {\n return value === undefined;\n}\n\nfunction isNull(value) {\n return value === null;\n}\n\nfunction isBoolean(value) {\n return typeof value === 'boolean';\n}\n\nfunction isObject(value) {\n return value === Object(value);\n}\n\nfunction isArray(value) {\n return Array.isArray(value);\n}\n\nfunction isDate(value) {\n return value instanceof Date;\n}\n\nfunction isBlob(value, isReactNative) {\n return isReactNative\n ? isObject(value) && !isUndefined(value.uri)\n : isObject(value) &&\n typeof value.size === 'number' &&\n typeof value.type === 'string' &&\n typeof value.slice === 'function';\n}\n\nfunction isFile(value, isReactNative) {\n return (\n isBlob(value, isReactNative) &&\n typeof value.name === 'string' &&\n (isObject(value.lastModifiedDate) || typeof value.lastModified === 'number')\n );\n}\n\nfunction initCfg(value) {\n return isUndefined(value) ? false : value;\n}\n\nfunction serialize(obj, cfg, fd, pre) {\n cfg = cfg || {};\n fd = fd || new FormData();\n\n cfg.indices = initCfg(cfg.indices);\n cfg.nullsAsUndefineds = initCfg(cfg.nullsAsUndefineds);\n cfg.booleansAsIntegers = initCfg(cfg.booleansAsIntegers);\n cfg.allowEmptyArrays = initCfg(cfg.allowEmptyArrays);\n cfg.noAttributesWithArrayNotation = initCfg(\n cfg.noAttributesWithArrayNotation,\n );\n cfg.noFilesWithArrayNotation = initCfg(cfg.noFilesWithArrayNotation);\n cfg.dotsForObjectNotation = initCfg(cfg.dotsForObjectNotation);\n\n const isReactNative = typeof fd.getParts === 'function';\n\n if (isUndefined(obj)) {\n return fd;\n } else if (isNull(obj)) {\n if (!cfg.nullsAsUndefineds) {\n fd.append(pre, '');\n }\n } else if (isBoolean(obj)) {\n if (cfg.booleansAsIntegers) {\n fd.append(pre, obj ? 1 : 0);\n } else {\n fd.append(pre, obj);\n }\n } else if (isArray(obj)) {\n if (obj.length) {\n obj.forEach((value, index) => {\n let key = pre + '[' + (cfg.indices ? index : '') + ']';\n\n if (\n cfg.noAttributesWithArrayNotation ||\n (cfg.noFilesWithArrayNotation && isFile(value, isReactNative))\n ) {\n key = pre;\n }\n\n serialize(value, cfg, fd, key);\n });\n } else if (cfg.allowEmptyArrays) {\n fd.append(cfg.noAttributesWithArrayNotation ? pre : pre + '[]', '');\n }\n } else if (isDate(obj)) {\n fd.append(pre, obj.toISOString());\n } else if (isObject(obj) && !isBlob(obj, isReactNative)) {\n Object.keys(obj).forEach((prop) => {\n const value = obj[prop];\n\n if (isArray(value)) {\n while (prop.length > 2 && prop.lastIndexOf('[]') === prop.length - 2) {\n prop = prop.substring(0, prop.length - 2);\n }\n }\n\n const key = pre\n ? cfg.dotsForObjectNotation\n ? pre + '.' + prop\n : pre + '[' + prop + ']'\n : prop;\n\n serialize(value, cfg, fd, key);\n });\n } else {\n fd.append(pre, obj);\n }\n\n return fd;\n}\n\nmodule.exports = {\n serialize,\n};\n", "(function() {\n var base64map\n = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n\n crypt = {\n // Bit-wise rotation left\n rotl: function(n, b) {\n return (n << b) | (n >>> (32 - b));\n },\n\n // Bit-wise rotation right\n rotr: function(n, b) {\n return (n << (32 - b)) | (n >>> b);\n },\n\n // Swap big-endian to little-endian and vice versa\n endian: function(n) {\n // If number given, swap endian\n if (n.constructor == Number) {\n return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00;\n }\n\n // Else, assume array and swap all items\n for (var i = 0; i < n.length; i++)\n n[i] = crypt.endian(n[i]);\n return n;\n },\n\n // Generate an array of any length of random bytes\n randomBytes: function(n) {\n for (var bytes = []; n > 0; n--)\n bytes.push(Math.floor(Math.random() * 256));\n return bytes;\n },\n\n // Convert a byte array to big-endian 32-bit words\n bytesToWords: function(bytes) {\n for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)\n words[b >>> 5] |= bytes[i] << (24 - b % 32);\n return words;\n },\n\n // Convert big-endian 32-bit words to a byte array\n wordsToBytes: function(words) {\n for (var bytes = [], b = 0; b < words.length * 32; b += 8)\n bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);\n return bytes;\n },\n\n // Convert a byte array to a hex string\n bytesToHex: function(bytes) {\n for (var hex = [], i = 0; i < bytes.length; i++) {\n hex.push((bytes[i] >>> 4).toString(16));\n hex.push((bytes[i] & 0xF).toString(16));\n }\n return hex.join('');\n },\n\n // Convert a hex string to a byte array\n hexToBytes: function(hex) {\n for (var bytes = [], c = 0; c < hex.length; c += 2)\n bytes.push(parseInt(hex.substr(c, 2), 16));\n return bytes;\n },\n\n // Convert a byte array to a base-64 string\n bytesToBase64: function(bytes) {\n for (var base64 = [], i = 0; i < bytes.length; i += 3) {\n var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n for (var j = 0; j < 4; j++)\n if (i * 8 + j * 6 <= bytes.length * 8)\n base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));\n else\n base64.push('=');\n }\n return base64.join('');\n },\n\n // Convert a base-64 string to a byte array\n base64ToBytes: function(base64) {\n // Remove non-base-64 characters\n base64 = base64.replace(/[^A-Z0-9+\\/]/ig, '');\n\n for (var bytes = [], i = 0, imod4 = 0; i < base64.length;\n imod4 = ++i % 4) {\n if (imod4 == 0) continue;\n bytes.push(((base64map.indexOf(base64.charAt(i - 1))\n & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2))\n | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));\n }\n return bytes;\n }\n };\n\n module.exports = crypt;\n})();\n", "var charenc = {\n // UTF-8 encoding\n utf8: {\n // Convert a string to a byte array\n stringToBytes: function(str) {\n return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)));\n },\n\n // Convert a byte array to a string\n bytesToString: function(bytes) {\n return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)));\n }\n },\n\n // Binary encoding\n bin: {\n // Convert a string to a byte array\n stringToBytes: function(str) {\n for (var bytes = [], i = 0; i < str.length; i++)\n bytes.push(str.charCodeAt(i) & 0xFF);\n return bytes;\n },\n\n // Convert a byte array to a string\n bytesToString: function(bytes) {\n for (var str = [], i = 0; i < bytes.length; i++)\n str.push(String.fromCharCode(bytes[i]));\n return str.join('');\n }\n }\n};\n\nmodule.exports = charenc;\n", "/*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nmodule.exports = function (obj) {\n return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)\n}\n\nfunction isBuffer (obj) {\n return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer (obj) {\n return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))\n}\n", "(function(){\r\n var crypt = require('crypt'),\r\n utf8 = require('charenc').utf8,\r\n isBuffer = require('is-buffer'),\r\n bin = require('charenc').bin,\r\n\r\n // The core\r\n md5 = function (message, options) {\r\n // Convert to byte array\r\n if (message.constructor == String)\r\n if (options && options.encoding === 'binary')\r\n message = bin.stringToBytes(message);\r\n else\r\n message = utf8.stringToBytes(message);\r\n else if (isBuffer(message))\r\n message = Array.prototype.slice.call(message, 0);\r\n else if (!Array.isArray(message) && message.constructor !== Uint8Array)\r\n message = message.toString();\r\n // else, assume byte array already\r\n\r\n var m = crypt.bytesToWords(message),\r\n l = message.length * 8,\r\n a = 1732584193,\r\n b = -271733879,\r\n c = -1732584194,\r\n d = 271733878;\r\n\r\n // Swap endian\r\n for (var i = 0; i < m.length; i++) {\r\n m[i] = ((m[i] << 8) | (m[i] >>> 24)) & 0x00FF00FF |\r\n ((m[i] << 24) | (m[i] >>> 8)) & 0xFF00FF00;\r\n }\r\n\r\n // Padding\r\n m[l >>> 5] |= 0x80 << (l % 32);\r\n m[(((l + 64) >>> 9) << 4) + 14] = l;\r\n\r\n // Method shortcuts\r\n var FF = md5._ff,\r\n GG = md5._gg,\r\n HH = md5._hh,\r\n II = md5._ii;\r\n\r\n for (var i = 0; i < m.length; i += 16) {\r\n\r\n var aa = a,\r\n bb = b,\r\n cc = c,\r\n dd = d;\r\n\r\n a = FF(a, b, c, d, m[i+ 0], 7, -680876936);\r\n d = FF(d, a, b, c, m[i+ 1], 12, -389564586);\r\n c = FF(c, d, a, b, m[i+ 2], 17, 606105819);\r\n b = FF(b, c, d, a, m[i+ 3], 22, -1044525330);\r\n a = FF(a, b, c, d, m[i+ 4], 7, -176418897);\r\n d = FF(d, a, b, c, m[i+ 5], 12, 1200080426);\r\n c = FF(c, d, a, b, m[i+ 6], 17, -1473231341);\r\n b = FF(b, c, d, a, m[i+ 7], 22, -45705983);\r\n a = FF(a, b, c, d, m[i+ 8], 7, 1770035416);\r\n d = FF(d, a, b, c, m[i+ 9], 12, -1958414417);\r\n c = FF(c, d, a, b, m[i+10], 17, -42063);\r\n b = FF(b, c, d, a, m[i+11], 22, -1990404162);\r\n a = FF(a, b, c, d, m[i+12], 7, 1804603682);\r\n d = FF(d, a, b, c, m[i+13], 12, -40341101);\r\n c = FF(c, d, a, b, m[i+14], 17, -1502002290);\r\n b = FF(b, c, d, a, m[i+15], 22, 1236535329);\r\n\r\n a = GG(a, b, c, d, m[i+ 1], 5, -165796510);\r\n d = GG(d, a, b, c, m[i+ 6], 9, -1069501632);\r\n c = GG(c, d, a, b, m[i+11], 14, 643717713);\r\n b = GG(b, c, d, a, m[i+ 0], 20, -373897302);\r\n a = GG(a, b, c, d, m[i+ 5], 5, -701558691);\r\n d = GG(d, a, b, c, m[i+10], 9, 38016083);\r\n c = GG(c, d, a, b, m[i+15], 14, -660478335);\r\n b = GG(b, c, d, a, m[i+ 4], 20, -405537848);\r\n a = GG(a, b, c, d, m[i+ 9], 5, 568446438);\r\n d = GG(d, a, b, c, m[i+14], 9, -1019803690);\r\n c = GG(c, d, a, b, m[i+ 3], 14, -187363961);\r\n b = GG(b, c, d, a, m[i+ 8], 20, 1163531501);\r\n a = GG(a, b, c, d, m[i+13], 5, -1444681467);\r\n d = GG(d, a, b, c, m[i+ 2], 9, -51403784);\r\n c = GG(c, d, a, b, m[i+ 7], 14, 1735328473);\r\n b = GG(b, c, d, a, m[i+12], 20, -1926607734);\r\n\r\n a = HH(a, b, c, d, m[i+ 5], 4, -378558);\r\n d = HH(d, a, b, c, m[i+ 8], 11, -2022574463);\r\n c = HH(c, d, a, b, m[i+11], 16, 1839030562);\r\n b = HH(b, c, d, a, m[i+14], 23, -35309556);\r\n a = HH(a, b, c, d, m[i+ 1], 4, -1530992060);\r\n d = HH(d, a, b, c, m[i+ 4], 11, 1272893353);\r\n c = HH(c, d, a, b, m[i+ 7], 16, -155497632);\r\n b = HH(b, c, d, a, m[i+10], 23, -1094730640);\r\n a = HH(a, b, c, d, m[i+13], 4, 681279174);\r\n d = HH(d, a, b, c, m[i+ 0], 11, -358537222);\r\n c = HH(c, d, a, b, m[i+ 3], 16, -722521979);\r\n b = HH(b, c, d, a, m[i+ 6], 23, 76029189);\r\n a = HH(a, b, c, d, m[i+ 9], 4, -640364487);\r\n d = HH(d, a, b, c, m[i+12], 11, -421815835);\r\n c = HH(c, d, a, b, m[i+15], 16, 530742520);\r\n b = HH(b, c, d, a, m[i+ 2], 23, -995338651);\r\n\r\n a = II(a, b, c, d, m[i+ 0], 6, -198630844);\r\n d = II(d, a, b, c, m[i+ 7], 10, 1126891415);\r\n c = II(c, d, a, b, m[i+14], 15, -1416354905);\r\n b = II(b, c, d, a, m[i+ 5], 21, -57434055);\r\n a = II(a, b, c, d, m[i+12], 6, 1700485571);\r\n d = II(d, a, b, c, m[i+ 3], 10, -1894986606);\r\n c = II(c, d, a, b, m[i+10], 15, -1051523);\r\n b = II(b, c, d, a, m[i+ 1], 21, -2054922799);\r\n a = II(a, b, c, d, m[i+ 8], 6, 1873313359);\r\n d = II(d, a, b, c, m[i+15], 10, -30611744);\r\n c = II(c, d, a, b, m[i+ 6], 15, -1560198380);\r\n b = II(b, c, d, a, m[i+13], 21, 1309151649);\r\n a = II(a, b, c, d, m[i+ 4], 6, -145523070);\r\n d = II(d, a, b, c, m[i+11], 10, -1120210379);\r\n c = II(c, d, a, b, m[i+ 2], 15, 718787259);\r\n b = II(b, c, d, a, m[i+ 9], 21, -343485551);\r\n\r\n a = (a + aa) >>> 0;\r\n b = (b + bb) >>> 0;\r\n c = (c + cc) >>> 0;\r\n d = (d + dd) >>> 0;\r\n }\r\n\r\n return crypt.endian([a, b, c, d]);\r\n };\r\n\r\n // Auxiliary functions\r\n md5._ff = function (a, b, c, d, x, s, t) {\r\n var n = a + (b & c | ~b & d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._gg = function (a, b, c, d, x, s, t) {\r\n var n = a + (b & d | c & ~d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._hh = function (a, b, c, d, x, s, t) {\r\n var n = a + (b ^ c ^ d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._ii = function (a, b, c, d, x, s, t) {\r\n var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n\r\n // Package private blocksize\r\n md5._blocksize = 16;\r\n md5._digestsize = 16;\r\n\r\n module.exports = function (message, options) {\r\n if (message === undefined || message === null)\r\n throw new Error('Illegal argument ' + message);\r\n\r\n var digestbytes = crypt.wordsToBytes(md5(message, options));\r\n return options && options.asBytes ? digestbytes :\r\n options && options.asString ? bin.bytesToString(digestbytes) :\r\n crypt.bytesToHex(digestbytes);\r\n };\r\n\r\n})();\r\n", "'use client'\nimport React from 'react'\n\nimport type { RowLabelProps } from './types.js'\n\nimport { RenderCustomComponent } from '../../elements/RenderCustomComponent/index.js'\nimport { RowLabelProvider } from './Context/index.js'\nexport type { RowLabelProps }\n\nconst baseClass = 'row-label'\n\nexport const RowLabel: React.FC = (props) => {\n const { className, CustomComponent, label, path, rowNumber } = props\n\n return (\n \n \n {label}\n \n ) : (\n label\n )\n }\n />\n \n )\n}\n", "type Args = {\n CustomComponent?: React.ReactNode\n Fallback: React.ReactNode\n}\n\n/**\n * Renders a CustomComponent or a Fallback component.\n * Only fallback if the Custom Component is undefined.\n *\n * If the CustomComponent is null, render null.\n *\n * @param {Object} args - Arguments object.\n * @param {React.ReactNode} [args.CustomComponent] - Optional custom component to render.\n * @param {React.ReactNode} args.Fallback - Fallback component to render if CustomComponent is undefined.\n * @returns {React.ReactNode} Rendered component.\n */\nexport function RenderCustomComponent({ CustomComponent, Fallback }: Args): React.ReactNode {\n return CustomComponent !== undefined ? CustomComponent : Fallback\n}\n", "'use client'\n\nimport React from 'react'\n\nimport { useWatchForm } from '../../Form/context.js'\n\ntype RowLabelType = {\n readonly data: T\n readonly path: string\n readonly rowNumber?: number\n}\n\nconst RowLabel = React.createContext({\n data: {},\n path: '',\n rowNumber: undefined,\n})\n\ntype Props = {\n readonly children: React.ReactNode\n} & Omit, 'data'>\n\nexport const RowLabelProvider: React.FC> = ({ children, path, rowNumber }) => {\n const { getDataByPath, getSiblingData } = useWatchForm()\n const collapsibleData = getSiblingData(path)\n const arrayData = getDataByPath(path)\n\n const data = arrayData || collapsibleData\n\n const contextValue = React.useMemo(() => ({ data, path, rowNumber }), [data, path, rowNumber])\n\n return {children}\n}\n\nexport const useRowLabel = () => {\n return React.use(RowLabel) as RowLabelType\n}\n", "'use client'\nimport type { RenderedField } from 'payload'\n\nimport { createContext, use } from 'react'\nimport {\n createContext as createSelectorContext,\n useContextSelector,\n useContext as useFullContext,\n} from 'use-context-selector'\n\nimport type { Context, FormFieldsContext as FormFieldsContextType } from './types.js'\n\nconst FormContext = createContext({} as Context)\nconst DocumentFormContext = createContext({} as Context)\nconst FormWatchContext = createContext({} as Context)\nconst SubmittedContext = createContext(false)\nconst ProcessingContext = createContext(false)\n/**\n * If the form has started processing in the background (e.g.\n * if autosave is running), this will be true.\n */\nconst BackgroundProcessingContext = createContext(false)\nconst ModifiedContext = createContext(false)\nconst InitializingContext = createContext(false)\nconst FormFieldsContext = createSelectorContext([{}, () => null])\n\nexport type RenderedFieldSlots = Map\n\n/**\n * Get the state of the form, can be used to submit & validate the form.\n *\n * @see https://payloadcms.com/docs/admin/react-hooks#useform\n */\nconst useForm = (): Context => use(FormContext)\n/**\n * Get the state of the document-level form. This is useful if you need to access the document-level Form from within a child Form.\n * This is the case withing lexical Blocks, as each lexical blocks renders their own Form.\n */\nconst useDocumentForm = (): Context => use(DocumentFormContext)\n\nconst useWatchForm = (): Context => use(FormWatchContext)\nconst useFormSubmitted = (): boolean => use(SubmittedContext)\nconst useFormProcessing = (): boolean => use(ProcessingContext)\n/**\n * If the form has started processing in the background (e.g.\n * if autosave is running), this will be true.\n */\nconst useFormBackgroundProcessing = (): boolean => use(BackgroundProcessingContext)\nconst useFormModified = (): boolean => use(ModifiedContext)\nconst useFormInitializing = (): boolean => use(InitializingContext)\n\n/**\n * Get and set the value of a form field based on a selector\n *\n * @see https://payloadcms.com/docs/admin/react-hooks#useformfields\n */\nconst useFormFields = (\n selector: (context: FormFieldsContextType) => Value,\n): Value => useContextSelector(FormFieldsContext, selector)\n\n/**\n * Get the state of all form fields.\n *\n * @see https://payloadcms.com/docs/admin/react-hooks#useallformfields\n */\nconst useAllFormFields = (): FormFieldsContextType => useFullContext(FormFieldsContext)\n\nexport {\n BackgroundProcessingContext,\n DocumentFormContext,\n FormContext,\n FormFieldsContext,\n FormWatchContext,\n InitializingContext,\n ModifiedContext,\n ProcessingContext,\n SubmittedContext,\n useAllFormFields,\n useDocumentForm,\n useForm,\n useFormBackgroundProcessing,\n useFormFields,\n useFormInitializing,\n useFormModified,\n useFormProcessing,\n useFormSubmitted,\n useWatchForm,\n}\n", "import { createElement, createContext as createContextOrig, useContext as useContextOrig, useEffect, useLayoutEffect, useReducer, useRef, useState, } from 'react';\nimport { unstable_NormalPriority as NormalPriority, unstable_runWithPriority as runWithPriority, } from 'scheduler';\nconst CONTEXT_VALUE = Symbol();\nconst ORIGINAL_PROVIDER = Symbol();\nconst isSSR = typeof window === 'undefined' ||\n /ServerSideRendering/.test(window.navigator && window.navigator.userAgent);\nconst useIsomorphicLayoutEffect = isSSR ? useEffect : useLayoutEffect;\n// for preact that doesn't have runWithPriority\nconst runWithNormalPriority = runWithPriority\n ? (fn) => {\n try {\n runWithPriority(NormalPriority, fn);\n }\n catch (e) {\n if (e.message === 'Not implemented.') {\n fn();\n }\n else {\n throw e;\n }\n }\n }\n : (fn) => fn();\nconst createProvider = (ProviderOrig) => {\n const ContextProvider = ({ value, children, }) => {\n const valueRef = useRef(value);\n const versionRef = useRef(0);\n const [resolve, setResolve] = useState(null);\n if (resolve) {\n resolve(value);\n setResolve(null);\n }\n const contextValue = useRef();\n if (!contextValue.current) {\n const listeners = new Set();\n const update = (fn, options) => {\n versionRef.current += 1;\n const action = {\n n: versionRef.current,\n };\n if (options === null || options === void 0 ? void 0 : options.suspense) {\n action.n *= -1; // this is intentional to make it temporary version\n action.p = new Promise((r) => {\n setResolve(() => (v) => {\n action.v = v;\n delete action.p;\n r(v);\n });\n });\n }\n listeners.forEach((listener) => listener(action));\n fn();\n };\n contextValue.current = {\n [CONTEXT_VALUE]: {\n /* \"v\"alue */ v: valueRef,\n /* versio\"n\" */ n: versionRef,\n /* \"l\"isteners */ l: listeners,\n /* \"u\"pdate */ u: update,\n },\n };\n }\n useIsomorphicLayoutEffect(() => {\n valueRef.current = value;\n versionRef.current += 1;\n runWithNormalPriority(() => {\n contextValue.current[CONTEXT_VALUE].l.forEach((listener) => {\n listener({ n: versionRef.current, v: value });\n });\n });\n }, [value]);\n return createElement(ProviderOrig, { value: contextValue.current }, children);\n };\n return ContextProvider;\n};\nconst identity = (x) => x;\n/**\n * This creates a special context for `useContextSelector`.\n *\n * @example\n * import { createContext } from 'use-context-selector';\n *\n * const PersonContext = createContext({ firstName: '', familyName: '' });\n */\nexport function createContext(defaultValue) {\n const context = createContextOrig({\n [CONTEXT_VALUE]: {\n /* \"v\"alue */ v: { current: defaultValue },\n /* versio\"n\" */ n: { current: -1 },\n /* \"l\"isteners */ l: new Set(),\n /* \"u\"pdate */ u: (f) => f(),\n },\n });\n context[ORIGINAL_PROVIDER] = context.Provider;\n context.Provider = createProvider(context.Provider);\n delete context.Consumer; // no support for Consumer\n return context;\n}\n/**\n * This hook returns context selected value by selector.\n *\n * It will only accept context created by `createContext`.\n * It will trigger re-render if only the selected value is referentially changed.\n *\n * The selector should return referentially equal result for same input for better performance.\n *\n * @example\n * import { useContextSelector } from 'use-context-selector';\n *\n * const firstName = useContextSelector(PersonContext, (state) => state.firstName);\n */\nexport function useContextSelector(context, selector) {\n const contextValue = useContextOrig(context)[CONTEXT_VALUE];\n if (typeof process === 'object' && process.env.NODE_ENV !== 'production') {\n if (!contextValue) {\n throw new Error('useContextSelector requires special context');\n }\n }\n const { \n /* \"v\"alue */ v: { current: value }, \n /* versio\"n\" */ n: { current: version }, \n /* \"l\"isteners */ l: listeners, } = contextValue;\n const selected = selector(value);\n const [state, dispatch] = useReducer((prev, action) => {\n if (!action) {\n // case for `dispatch()` below\n return [value, selected];\n }\n if ('p' in action) {\n throw action.p;\n }\n if (action.n === version) {\n if (Object.is(prev[1], selected)) {\n return prev; // bail out\n }\n return [value, selected];\n }\n try {\n if ('v' in action) {\n if (Object.is(prev[0], action.v)) {\n return prev; // do not update\n }\n const nextSelected = selector(action.v);\n if (Object.is(prev[1], nextSelected)) {\n return prev; // do not update\n }\n return [action.v, nextSelected];\n }\n }\n catch (_e) {\n // ignored (stale props or some other reason)\n }\n return [...prev]; // schedule update\n }, [value, selected]);\n if (!Object.is(state[1], selected)) {\n // schedule re-render\n // this is safe because it's self contained\n dispatch();\n }\n useIsomorphicLayoutEffect(() => {\n listeners.add(dispatch);\n return () => {\n listeners.delete(dispatch);\n };\n }, [listeners]);\n return state[1];\n}\n/**\n * This hook returns the entire context value.\n * Use this instead of React.useContext for consistent behavior.\n *\n * @example\n * import { useContext } from 'use-context-selector';\n *\n * const person = useContext(PersonContext);\n */\nexport function useContext(context) {\n return useContextSelector(context, identity);\n}\n/**\n * This hook returns an update function to wrap an updating function\n *\n * Use this for a function that will change a value in\n * concurrent rendering in React 18.\n * Otherwise, there's no need to use this hook.\n *\n * @example\n * import { useContextUpdate } from 'use-context-selector';\n *\n * const update = useContextUpdate();\n *\n * // Wrap set state function\n * update(() => setState(...));\n *\n * // Experimental suspense mode\n * update(() => setState(...), { suspense: true });\n */\nexport function useContextUpdate(context) {\n const contextValue = useContextOrig(context)[CONTEXT_VALUE];\n if (typeof process === 'object' && process.env.NODE_ENV !== 'production') {\n if (!contextValue) {\n throw new Error('useContextUpdate requires special context');\n }\n }\n const { u: update } = contextValue;\n return update;\n}\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * This is a Provider component for bridging multiple react roots\n *\n * @example\n * const valueToBridge = useBridgeValue(PersonContext);\n * return (\n * \n * \n * {children}\n * \n * \n * );\n */\nexport const BridgeProvider = ({ context, value, children, }) => {\n const { [ORIGINAL_PROVIDER]: ProviderOrig } = context;\n if (typeof process === 'object' && process.env.NODE_ENV !== 'production') {\n if (!ProviderOrig) {\n throw new Error('BridgeProvider requires special context');\n }\n }\n return createElement(ProviderOrig, { value }, children);\n};\n/**\n * This hook return a value for BridgeProvider\n */\nexport const useBridgeValue = (context) => {\n const bridgeValue = useContextOrig(context);\n if (typeof process === 'object' && process.env.NODE_ENV !== 'production') {\n if (!bridgeValue[CONTEXT_VALUE]) {\n throw new Error('useBridgeValue requires special context');\n }\n }\n return bridgeValue;\n};\n", "'use client'\nimport type {\n ArrayFieldClientComponent,\n ArrayFieldClientProps,\n ArrayField as ArrayFieldType,\n} from 'payload'\n\nimport { getTranslation } from '@payloadcms/translations'\nimport React, { Fragment, useCallback, useId, useMemo } from 'react'\nimport { toast } from 'sonner'\n\nimport type { ClipboardPasteData } from '../../elements/ClipboardAction/types.js'\n\nimport { Banner } from '../../elements/Banner/index.js'\nimport { Button } from '../../elements/Button/index.js'\nimport { clipboardCopy, clipboardPaste } from '../../elements/ClipboardAction/clipboardUtilities.js'\nimport { ClipboardAction } from '../../elements/ClipboardAction/index.js'\nimport {\n mergeFormStateFromClipboard,\n reduceFormStateByPath,\n} from '../../elements/ClipboardAction/mergeFormStateFromClipboard.js'\nimport { DraggableSortableItem } from '../../elements/DraggableSortable/DraggableSortableItem/index.js'\nimport { DraggableSortable } from '../../elements/DraggableSortable/index.js'\nimport { ErrorPill } from '../../elements/ErrorPill/index.js'\nimport { RenderCustomComponent } from '../../elements/RenderCustomComponent/index.js'\nimport { FieldDescription } from '../../fields/FieldDescription/index.js'\nimport { FieldError } from '../../fields/FieldError/index.js'\nimport { FieldLabel } from '../../fields/FieldLabel/index.js'\nimport { useForm, useFormSubmitted } from '../../forms/Form/context.js'\nimport { extractRowsAndCollapsedIDs, toggleAllRows } from '../../forms/Form/rowHelpers.js'\nimport { NullifyLocaleField } from '../../forms/NullifyField/index.js'\nimport { useField } from '../../forms/useField/index.js'\nimport { withCondition } from '../../forms/withCondition/index.js'\nimport { useConfig } from '../../providers/Config/index.js'\nimport { useDocumentInfo } from '../../providers/DocumentInfo/index.js'\nimport { useLocale } from '../../providers/Locale/index.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { scrollToID } from '../../utilities/scrollToID.js'\nimport { mergeFieldStyles } from '../mergeFieldStyles.js'\nimport { fieldBaseClass } from '../shared/index.js'\nimport { ArrayRow } from './ArrayRow.js'\nimport './index.scss'\n\nconst baseClass = 'array-field'\n\nexport const ArrayFieldComponent: ArrayFieldClientComponent = (props) => {\n const {\n field,\n field: {\n name,\n type,\n admin: { className, description, isSortable = true } = {},\n fields,\n label,\n localized,\n maxRows,\n minRows: minRowsProp,\n required,\n },\n forceRender = false,\n path: pathFromProps,\n permissions,\n readOnly,\n schemaPath: schemaPathFromProps,\n validate,\n } = props\n\n const schemaPath = schemaPathFromProps ?? name\n\n const minRows = minRowsProp ?? (required ? 1 : 0)\n\n const { setDocFieldPreferences } = useDocumentInfo()\n const {\n addFieldRow,\n dispatchFields,\n getFields,\n moveFieldRow,\n removeFieldRow,\n replaceState,\n setModified,\n } = useForm()\n const submitted = useFormSubmitted()\n const { code: locale } = useLocale()\n const { i18n, t } = useTranslation()\n\n const {\n config: { localization },\n } = useConfig()\n\n const editingDefaultLocale = (() => {\n if (localization && localization.fallback) {\n const defaultLocale = localization.defaultLocale\n return locale === defaultLocale\n }\n\n return true\n })()\n\n // Handle labeling for Arrays, Global Arrays, and Blocks\n const getLabels = (p: ArrayFieldClientProps): Partial => {\n if ('labels' in p && p?.labels) {\n return p.labels\n }\n\n if ('labels' in p.field && p.field.labels) {\n return { plural: p.field.labels?.plural, singular: p.field.labels?.singular }\n }\n\n if ('label' in p.field && p.field.label) {\n return { plural: undefined, singular: p.field.label }\n }\n\n return { plural: t('general:rows'), singular: t('general:row') }\n }\n\n const labels = getLabels(props)\n\n const memoizedValidate = useCallback(\n (value, options) => {\n // alternative locales can be null\n if (!editingDefaultLocale && value === null) {\n return true\n }\n\n if (typeof validate === 'function') {\n return validate(value, { ...options, maxRows, minRows, required })\n }\n },\n [maxRows, minRows, required, validate, editingDefaultLocale],\n )\n\n const {\n customComponents: { AfterInput, BeforeInput, Description, Error, Label } = {},\n disabled,\n errorPaths,\n path,\n rows = [],\n showError,\n valid,\n value,\n } = useField({\n hasRows: true,\n potentiallyStalePath: pathFromProps,\n validate: memoizedValidate,\n })\n\n const componentId = useId()\n const scrollIdPrefix = useMemo(() => `scroll-${componentId}`, [componentId])\n\n const addRow = useCallback(\n (rowIndex: number) => {\n addFieldRow({\n path,\n rowIndex,\n schemaPath,\n })\n\n setTimeout(() => {\n scrollToID(`${scrollIdPrefix}-row-${rowIndex}`)\n }, 0)\n },\n [addFieldRow, path, schemaPath, scrollIdPrefix],\n )\n\n const duplicateRow = useCallback(\n (rowIndex: number) => {\n dispatchFields({ type: 'DUPLICATE_ROW', path, rowIndex })\n\n setModified(true)\n\n setTimeout(() => {\n scrollToID(`${scrollIdPrefix}-row-${rowIndex}`)\n }, 0)\n },\n [dispatchFields, path, scrollIdPrefix, setModified],\n )\n\n const removeRow = useCallback(\n (rowIndex: number) => {\n removeFieldRow({ path, rowIndex })\n },\n [removeFieldRow, path],\n )\n\n const moveRow = useCallback(\n (moveFromIndex: number, moveToIndex: number) => {\n moveFieldRow({\n moveFromIndex,\n moveToIndex,\n path,\n })\n },\n [path, moveFieldRow],\n )\n\n const toggleCollapseAll = useCallback(\n (collapsed: boolean) => {\n const { collapsedIDs, updatedRows } = toggleAllRows({\n collapsed,\n rows,\n })\n setDocFieldPreferences(path, { collapsed: collapsedIDs })\n dispatchFields({ type: 'SET_ALL_ROWS_COLLAPSED', path, updatedRows })\n },\n [dispatchFields, path, rows, setDocFieldPreferences],\n )\n\n const setCollapse = useCallback(\n (rowID: string, collapsed: boolean) => {\n const { collapsedIDs, updatedRows } = extractRowsAndCollapsedIDs({\n collapsed,\n rowID,\n rows,\n })\n\n dispatchFields({ type: 'SET_ROW_COLLAPSED', path, updatedRows })\n setDocFieldPreferences(path, { collapsed: collapsedIDs })\n },\n [dispatchFields, path, rows, setDocFieldPreferences],\n )\n\n const copyRow = useCallback(\n (rowIndex: number) => {\n const formState = { ...getFields() }\n const clipboardResult = clipboardCopy({\n type,\n fields,\n getDataToCopy: () =>\n reduceFormStateByPath({\n formState,\n path,\n rowIndex,\n }),\n path,\n rowIndex,\n t,\n })\n\n if (typeof clipboardResult === 'string') {\n toast.error(clipboardResult)\n } else {\n toast.success(t('general:copied'))\n }\n },\n [fields, getFields, path, t, type],\n )\n\n const pasteRow = useCallback(\n (rowIndex: number) => {\n const formState = { ...getFields() }\n const pasteArgs = {\n onPaste: (dataFromClipboard: ClipboardPasteData) => {\n const newState = mergeFormStateFromClipboard({\n dataFromClipboard,\n formState,\n path,\n rowIndex,\n })\n replaceState(newState)\n setModified(true)\n },\n path,\n schemaFields: fields,\n t,\n }\n\n const clipboardResult = clipboardPaste(pasteArgs)\n\n if (typeof clipboardResult === 'string') {\n toast.error(clipboardResult)\n }\n },\n [fields, getFields, path, replaceState, setModified, t],\n )\n\n const pasteField = useCallback(\n (dataFromClipboard: ClipboardPasteData) => {\n const formState = { ...getFields() }\n const newState = mergeFormStateFromClipboard({\n dataFromClipboard,\n formState,\n path,\n })\n replaceState(newState)\n setModified(true)\n },\n [getFields, path, replaceState, setModified],\n )\n\n const getDataToCopy = useCallback(\n () =>\n reduceFormStateByPath({\n formState: { ...getFields() },\n path,\n }),\n [getFields, path],\n )\n\n const hasMaxRows = maxRows && rows.length >= maxRows\n\n const fieldErrorCount = errorPaths.length\n const fieldHasErrors = submitted && errorPaths.length > 0\n\n const showRequired = (readOnly || disabled) && rows.length === 0\n const showMinRows = (rows.length && rows.length < minRows) || (required && rows.length === 0)\n\n const styles = useMemo(() => mergeFieldStyles(field), [field])\n\n return (\n \n {showError && (\n }\n />\n )}\n
\n
\n
\n

\n \n }\n />\n

\n {fieldHasErrors && fieldErrorCount > 0 && (\n \n )}\n
\n
    \n {rows?.length > 0 && (\n \n
  • \n toggleCollapseAll(true)}\n type=\"button\"\n >\n {t('fields:collapseAll')}\n \n
  • \n
  • \n toggleCollapseAll(false)}\n type=\"button\"\n >\n {t('fields:showAll')}\n \n
  • \n
    \n )}\n
  • \n 0}\n allowPaste={!readOnly}\n className={`${baseClass}__header-action`}\n disabled={disabled}\n fields={fields}\n getDataToCopy={getDataToCopy}\n onPaste={pasteField}\n path={path}\n type={type}\n />\n
  • \n
\n
\n }\n />\n
\n \n {BeforeInput}\n {(rows?.length > 0 || (!valid && (showRequired || showMinRows))) && (\n row.id)}\n onDragEnd={({ moveFromIndex, moveToIndex }) => moveRow(moveFromIndex, moveToIndex)}\n >\n {rows.map((rowData, i) => {\n const { id: rowID, isLoading } = rowData\n\n const rowPath = `${path}.${i}`\n\n const rowErrorCount = errorPaths?.filter((errorPath) =>\n errorPath.startsWith(rowPath + '.'),\n ).length\n\n return (\n \n {(draggableSortableItemProps) => (\n \n )}\n \n )\n })}\n {!valid && (\n \n {showRequired && (\n \n {t('validation:fieldHasNo', { label: getTranslation(labels.plural, i18n) })}\n \n )}\n {showMinRows && (\n \n {t('validation:requiresAtLeast', {\n count: minRows,\n label:\n getTranslation(minRows > 1 ? labels.plural : labels.singular, i18n) ||\n t(minRows > 1 ? 'general:rows' : 'general:row'),\n })}\n \n )}\n \n )}\n \n )}\n {!hasMaxRows && !readOnly && (\n {\n void addRow(value || 0)\n }}\n >\n {t('fields:addLabel', { label: getTranslation(labels.singular, i18n) })}\n \n )}\n {AfterInput}\n \n )\n}\n\nexport const ArrayField = withCondition(ArrayFieldComponent)\n", "'use client';\n\nimport React, { forwardRef, isValidElement } from 'react';\nimport ReactDOM from 'react-dom';\n\nimport { CloseIcon, getAsset, Loader } from './assets';\nimport { useIsDocumentHidden } from './hooks';\nimport { toast, ToastState } from './state';\nimport './styles.css';\nimport {\n isAction,\n SwipeDirection,\n type ExternalToast,\n type HeightT,\n type ToasterProps,\n type ToastProps,\n type ToastT,\n type ToastToDismiss,\n} from './types';\n\n// Visible toasts amount\nconst VISIBLE_TOASTS_AMOUNT = 3;\n\n// Viewport padding\nconst VIEWPORT_OFFSET = '32px';\n\n// Mobile viewport padding\nconst MOBILE_VIEWPORT_OFFSET = '16px';\n\n// Default lifetime of a toasts (in ms)\nconst TOAST_LIFETIME = 4000;\n\n// Default toast width\nconst TOAST_WIDTH = 356;\n\n// Default gap between toasts\nconst GAP = 14;\n\n// Threshold to dismiss a toast\nconst SWIPE_THRESHOLD = 20;\n\n// Equal to exit animation duration\nconst TIME_BEFORE_UNMOUNT = 200;\n\nfunction cn(...classes: (string | undefined)[]) {\n return classes.filter(Boolean).join(' ');\n}\n\nfunction getDefaultSwipeDirections(position: string): Array {\n const [y, x] = position.split('-');\n const directions: Array = [];\n\n if (y) {\n directions.push(y as SwipeDirection);\n }\n\n if (x) {\n directions.push(x as SwipeDirection);\n }\n\n return directions;\n}\n\nconst Toast = (props: ToastProps) => {\n const {\n invert: ToasterInvert,\n toast,\n unstyled,\n interacting,\n setHeights,\n visibleToasts,\n heights,\n index,\n toasts,\n expanded,\n removeToast,\n defaultRichColors,\n closeButton: closeButtonFromToaster,\n style,\n cancelButtonStyle,\n actionButtonStyle,\n className = '',\n descriptionClassName = '',\n duration: durationFromToaster,\n position,\n gap,\n loadingIcon: loadingIconProp,\n expandByDefault,\n classNames,\n icons,\n closeButtonAriaLabel = 'Close toast',\n pauseWhenPageIsHidden,\n } = props;\n const [swipeDirection, setSwipeDirection] = React.useState<'x' | 'y' | null>(null);\n const [swipeOutDirection, setSwipeOutDirection] = React.useState<'left' | 'right' | 'up' | 'down' | null>(null);\n const [mounted, setMounted] = React.useState(false);\n const [removed, setRemoved] = React.useState(false);\n const [swiping, setSwiping] = React.useState(false);\n const [swipeOut, setSwipeOut] = React.useState(false);\n const [isSwiped, setIsSwiped] = React.useState(false);\n const [offsetBeforeRemove, setOffsetBeforeRemove] = React.useState(0);\n const [initialHeight, setInitialHeight] = React.useState(0);\n const remainingTime = React.useRef(toast.duration || durationFromToaster || TOAST_LIFETIME);\n const dragStartTime = React.useRef(null);\n const toastRef = React.useRef(null);\n const isFront = index === 0;\n const isVisible = index + 1 <= visibleToasts;\n const toastType = toast.type;\n const dismissible = toast.dismissible !== false;\n const toastClassname = toast.className || '';\n const toastDescriptionClassname = toast.descriptionClassName || '';\n // Height index is used to calculate the offset as it gets updated before the toast array, which means we can calculate the new layout faster.\n const heightIndex = React.useMemo(\n () => heights.findIndex((height) => height.toastId === toast.id) || 0,\n [heights, toast.id],\n );\n const closeButton = React.useMemo(\n () => toast.closeButton ?? closeButtonFromToaster,\n [toast.closeButton, closeButtonFromToaster],\n );\n const duration = React.useMemo(\n () => toast.duration || durationFromToaster || TOAST_LIFETIME,\n [toast.duration, durationFromToaster],\n );\n const closeTimerStartTimeRef = React.useRef(0);\n const offset = React.useRef(0);\n const lastCloseTimerStartTimeRef = React.useRef(0);\n const pointerStartRef = React.useRef<{ x: number; y: number } | null>(null);\n const [y, x] = position.split('-');\n const toastsHeightBefore = React.useMemo(() => {\n return heights.reduce((prev, curr, reducerIndex) => {\n // Calculate offset up until current toast\n if (reducerIndex >= heightIndex) {\n return prev;\n }\n\n return prev + curr.height;\n }, 0);\n }, [heights, heightIndex]);\n const isDocumentHidden = useIsDocumentHidden();\n\n const invert = toast.invert || ToasterInvert;\n const disabled = toastType === 'loading';\n\n offset.current = React.useMemo(() => heightIndex * gap + toastsHeightBefore, [heightIndex, toastsHeightBefore]);\n\n React.useEffect(() => {\n remainingTime.current = duration;\n }, [duration]);\n\n React.useEffect(() => {\n // Trigger enter animation without using CSS animation\n setMounted(true);\n }, []);\n\n React.useEffect(() => {\n const toastNode = toastRef.current;\n if (toastNode) {\n const height = toastNode.getBoundingClientRect().height;\n // Add toast height to heights array after the toast is mounted\n setInitialHeight(height);\n setHeights((h) => [{ toastId: toast.id, height, position: toast.position }, ...h]);\n return () => setHeights((h) => h.filter((height) => height.toastId !== toast.id));\n }\n }, [setHeights, toast.id]);\n\n React.useLayoutEffect(() => {\n if (!mounted) return;\n const toastNode = toastRef.current;\n const originalHeight = toastNode.style.height;\n toastNode.style.height = 'auto';\n const newHeight = toastNode.getBoundingClientRect().height;\n toastNode.style.height = originalHeight;\n\n setInitialHeight(newHeight);\n\n setHeights((heights) => {\n const alreadyExists = heights.find((height) => height.toastId === toast.id);\n if (!alreadyExists) {\n return [{ toastId: toast.id, height: newHeight, position: toast.position }, ...heights];\n } else {\n return heights.map((height) => (height.toastId === toast.id ? { ...height, height: newHeight } : height));\n }\n });\n }, [mounted, toast.title, toast.description, setHeights, toast.id]);\n\n const deleteToast = React.useCallback(() => {\n // Save the offset for the exit swipe animation\n setRemoved(true);\n setOffsetBeforeRemove(offset.current);\n setHeights((h) => h.filter((height) => height.toastId !== toast.id));\n\n setTimeout(() => {\n removeToast(toast);\n }, TIME_BEFORE_UNMOUNT);\n }, [toast, removeToast, setHeights, offset]);\n\n React.useEffect(() => {\n if ((toast.promise && toastType === 'loading') || toast.duration === Infinity || toast.type === 'loading') return;\n let timeoutId: NodeJS.Timeout;\n\n // Pause the timer on each hover\n const pauseTimer = () => {\n if (lastCloseTimerStartTimeRef.current < closeTimerStartTimeRef.current) {\n // Get the elapsed time since the timer started\n const elapsedTime = new Date().getTime() - closeTimerStartTimeRef.current;\n\n remainingTime.current = remainingTime.current - elapsedTime;\n }\n\n lastCloseTimerStartTimeRef.current = new Date().getTime();\n };\n\n const startTimer = () => {\n // setTimeout(, Infinity) behaves as if the delay is 0.\n // As a result, the toast would be closed immediately, giving the appearance that it was never rendered.\n // See: https://github.com/denysdovhan/wtfjs?tab=readme-ov-file#an-infinite-timeout\n if (remainingTime.current === Infinity) return;\n\n closeTimerStartTimeRef.current = new Date().getTime();\n\n // Let the toast know it has started\n timeoutId = setTimeout(() => {\n toast.onAutoClose?.(toast);\n deleteToast();\n }, remainingTime.current);\n };\n\n if (expanded || interacting || (pauseWhenPageIsHidden && isDocumentHidden)) {\n pauseTimer();\n } else {\n startTimer();\n }\n\n return () => clearTimeout(timeoutId);\n }, [expanded, interacting, toast, toastType, pauseWhenPageIsHidden, isDocumentHidden, deleteToast]);\n\n React.useEffect(() => {\n if (toast.delete) {\n deleteToast();\n }\n }, [deleteToast, toast.delete]);\n\n function getLoadingIcon() {\n if (icons?.loading) {\n return (\n \n {icons.loading}\n \n );\n }\n\n if (loadingIconProp) {\n return (\n \n {loadingIconProp}\n \n );\n }\n return ;\n }\n\n return (\n {\n setSwiping(false);\n setSwipeDirection(null);\n pointerStartRef.current = null;\n }}\n onPointerDown={(event) => {\n if (disabled || !dismissible) return;\n dragStartTime.current = new Date();\n setOffsetBeforeRemove(offset.current);\n // Ensure we maintain correct pointer capture even when going outside of the toast (e.g. when swiping)\n (event.target as HTMLElement).setPointerCapture(event.pointerId);\n if ((event.target as HTMLElement).tagName === 'BUTTON') return;\n setSwiping(true);\n pointerStartRef.current = { x: event.clientX, y: event.clientY };\n }}\n onPointerUp={() => {\n if (swipeOut || !dismissible) return;\n\n pointerStartRef.current = null;\n const swipeAmountX = Number(\n toastRef.current?.style.getPropertyValue('--swipe-amount-x').replace('px', '') || 0,\n );\n const swipeAmountY = Number(\n toastRef.current?.style.getPropertyValue('--swipe-amount-y').replace('px', '') || 0,\n );\n const timeTaken = new Date().getTime() - dragStartTime.current?.getTime();\n\n const swipeAmount = swipeDirection === 'x' ? swipeAmountX : swipeAmountY;\n const velocity = Math.abs(swipeAmount) / timeTaken;\n\n if (Math.abs(swipeAmount) >= SWIPE_THRESHOLD || velocity > 0.11) {\n setOffsetBeforeRemove(offset.current);\n toast.onDismiss?.(toast);\n\n if (swipeDirection === 'x') {\n setSwipeOutDirection(swipeAmountX > 0 ? 'right' : 'left');\n } else {\n setSwipeOutDirection(swipeAmountY > 0 ? 'down' : 'up');\n }\n\n deleteToast();\n setSwipeOut(true);\n setIsSwiped(false);\n return;\n }\n\n setSwiping(false);\n setSwipeDirection(null);\n }}\n onPointerMove={(event) => {\n if (!pointerStartRef.current || !dismissible) return;\n\n const isHighlighted = window.getSelection()?.toString().length > 0;\n if (isHighlighted) return;\n\n const yDelta = event.clientY - pointerStartRef.current.y;\n const xDelta = event.clientX - pointerStartRef.current.x;\n\n const swipeDirections = props.swipeDirections ?? getDefaultSwipeDirections(position);\n\n // Determine swipe direction if not already locked\n if (!swipeDirection && (Math.abs(xDelta) > 1 || Math.abs(yDelta) > 1)) {\n setSwipeDirection(Math.abs(xDelta) > Math.abs(yDelta) ? 'x' : 'y');\n }\n\n let swipeAmount = { x: 0, y: 0 };\n\n // Only apply swipe in the locked direction\n if (swipeDirection === 'y') {\n // Handle vertical swipes\n if (swipeDirections.includes('top') || swipeDirections.includes('bottom')) {\n if (swipeDirections.includes('top') && yDelta < 0) {\n swipeAmount.y = yDelta;\n } else if (swipeDirections.includes('bottom') && yDelta > 0) {\n swipeAmount.y = yDelta;\n }\n }\n } else if (swipeDirection === 'x') {\n // Handle horizontal swipes\n if (swipeDirections.includes('left') || swipeDirections.includes('right')) {\n if (swipeDirections.includes('left') && xDelta < 0) {\n swipeAmount.x = xDelta;\n } else if (swipeDirections.includes('right') && xDelta > 0) {\n swipeAmount.x = xDelta;\n }\n }\n }\n\n if (Math.abs(swipeAmount.x) > 0 || Math.abs(swipeAmount.y) > 0) {\n setIsSwiped(true);\n }\n\n // Apply transform using both x and y values\n toastRef.current?.style.setProperty('--swipe-amount-x', `${swipeAmount.x}px`);\n toastRef.current?.style.setProperty('--swipe-amount-y', `${swipeAmount.y}px`);\n }}\n >\n {closeButton && !toast.jsx ? (\n {}\n : () => {\n deleteToast();\n toast.onDismiss?.(toast);\n }\n }\n className={cn(classNames?.closeButton, toast?.classNames?.closeButton)}\n >\n {icons?.close ?? CloseIcon}\n \n ) : null}\n {/* TODO: This can be cleaner */}\n {toast.jsx || isValidElement(toast.title) ? (\n toast.jsx ? (\n toast.jsx\n ) : typeof toast.title === 'function' ? (\n toast.title()\n ) : (\n toast.title\n )\n ) : (\n <>\n {toastType || toast.icon || toast.promise ? (\n
\n {toast.promise || (toast.type === 'loading' && !toast.icon) ? toast.icon || getLoadingIcon() : null}\n {toast.type !== 'loading' ? toast.icon || icons?.[toastType] || getAsset(toastType) : null}\n
\n ) : null}\n\n
\n
\n {typeof toast.title === 'function' ? toast.title() : toast.title}\n
\n {toast.description ? (\n \n {typeof toast.description === 'function' ? toast.description() : toast.description}\n
\n ) : null}\n \n {isValidElement(toast.cancel) ? (\n toast.cancel\n ) : toast.cancel && isAction(toast.cancel) ? (\n {\n // We need to check twice because typescript\n if (!isAction(toast.cancel)) return;\n if (!dismissible) return;\n toast.cancel.onClick?.(event);\n deleteToast();\n }}\n className={cn(classNames?.cancelButton, toast?.classNames?.cancelButton)}\n >\n {toast.cancel.label}\n \n ) : null}\n {isValidElement(toast.action) ? (\n toast.action\n ) : toast.action && isAction(toast.action) ? (\n {\n // We need to check twice because typescript\n if (!isAction(toast.action)) return;\n toast.action.onClick?.(event);\n if (event.defaultPrevented) return;\n deleteToast();\n }}\n className={cn(classNames?.actionButton, toast?.classNames?.actionButton)}\n >\n {toast.action.label}\n \n ) : null}\n \n )}\n \n );\n};\n\nfunction getDocumentDirection(): ToasterProps['dir'] {\n if (typeof window === 'undefined') return 'ltr';\n if (typeof document === 'undefined') return 'ltr'; // For Fresh purpose\n\n const dirAttribute = document.documentElement.getAttribute('dir');\n\n if (dirAttribute === 'auto' || !dirAttribute) {\n return window.getComputedStyle(document.documentElement).direction as ToasterProps['dir'];\n }\n\n return dirAttribute as ToasterProps['dir'];\n}\n\nfunction assignOffset(defaultOffset: ToasterProps['offset'], mobileOffset: ToasterProps['mobileOffset']) {\n const styles = {} as React.CSSProperties;\n\n [defaultOffset, mobileOffset].forEach((offset, index) => {\n const isMobile = index === 1;\n const prefix = isMobile ? '--mobile-offset' : '--offset';\n const defaultValue = isMobile ? MOBILE_VIEWPORT_OFFSET : VIEWPORT_OFFSET;\n\n function assignAll(offset: string | number) {\n ['top', 'right', 'bottom', 'left'].forEach((key) => {\n styles[`${prefix}-${key}`] = typeof offset === 'number' ? `${offset}px` : offset;\n });\n }\n\n if (typeof offset === 'number' || typeof offset === 'string') {\n assignAll(offset);\n } else if (typeof offset === 'object') {\n ['top', 'right', 'bottom', 'left'].forEach((key) => {\n if (offset[key] === undefined) {\n styles[`${prefix}-${key}`] = defaultValue;\n } else {\n styles[`${prefix}-${key}`] = typeof offset[key] === 'number' ? `${offset[key]}px` : offset[key];\n }\n });\n } else {\n assignAll(defaultValue);\n }\n });\n\n return styles;\n}\n\nfunction useSonner() {\n const [activeToasts, setActiveToasts] = React.useState([]);\n\n React.useEffect(() => {\n return ToastState.subscribe((toast) => {\n if ((toast as ToastToDismiss).dismiss) {\n setTimeout(() => {\n ReactDOM.flushSync(() => {\n setActiveToasts((toasts) => toasts.filter((t) => t.id !== toast.id));\n });\n });\n return;\n }\n\n // Prevent batching, temp solution.\n setTimeout(() => {\n ReactDOM.flushSync(() => {\n setActiveToasts((toasts) => {\n const indexOfExistingToast = toasts.findIndex((t) => t.id === toast.id);\n\n // Update the toast if it already exists\n if (indexOfExistingToast !== -1) {\n return [\n ...toasts.slice(0, indexOfExistingToast),\n { ...toasts[indexOfExistingToast], ...toast },\n ...toasts.slice(indexOfExistingToast + 1),\n ];\n }\n\n return [toast, ...toasts];\n });\n });\n });\n });\n }, []);\n\n return {\n toasts: activeToasts,\n };\n}\n\nconst Toaster = forwardRef(function Toaster(props, ref) {\n const {\n invert,\n position = 'bottom-right',\n hotkey = ['altKey', 'KeyT'],\n expand,\n closeButton,\n className,\n offset,\n mobileOffset,\n theme = 'light',\n richColors,\n duration,\n style,\n visibleToasts = VISIBLE_TOASTS_AMOUNT,\n toastOptions,\n dir = getDocumentDirection(),\n gap = GAP,\n loadingIcon,\n icons,\n containerAriaLabel = 'Notifications',\n pauseWhenPageIsHidden,\n } = props;\n const [toasts, setToasts] = React.useState([]);\n const possiblePositions = React.useMemo(() => {\n return Array.from(\n new Set([position].concat(toasts.filter((toast) => toast.position).map((toast) => toast.position))),\n );\n }, [toasts, position]);\n const [heights, setHeights] = React.useState([]);\n const [expanded, setExpanded] = React.useState(false);\n const [interacting, setInteracting] = React.useState(false);\n const [actualTheme, setActualTheme] = React.useState(\n theme !== 'system'\n ? theme\n : typeof window !== 'undefined'\n ? window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches\n ? 'dark'\n : 'light'\n : 'light',\n );\n\n const listRef = React.useRef(null);\n const hotkeyLabel = hotkey.join('+').replace(/Key/g, '').replace(/Digit/g, '');\n const lastFocusedElementRef = React.useRef(null);\n const isFocusWithinRef = React.useRef(false);\n\n const removeToast = React.useCallback((toastToRemove: ToastT) => {\n setToasts((toasts) => {\n if (!toasts.find((toast) => toast.id === toastToRemove.id)?.delete) {\n ToastState.dismiss(toastToRemove.id);\n }\n\n return toasts.filter(({ id }) => id !== toastToRemove.id);\n });\n }, []);\n\n React.useEffect(() => {\n return ToastState.subscribe((toast) => {\n if ((toast as ToastToDismiss).dismiss) {\n setToasts((toasts) => toasts.map((t) => (t.id === toast.id ? { ...t, delete: true } : t)));\n return;\n }\n\n // Prevent batching, temp solution.\n setTimeout(() => {\n ReactDOM.flushSync(() => {\n setToasts((toasts) => {\n const indexOfExistingToast = toasts.findIndex((t) => t.id === toast.id);\n\n // Update the toast if it already exists\n if (indexOfExistingToast !== -1) {\n return [\n ...toasts.slice(0, indexOfExistingToast),\n { ...toasts[indexOfExistingToast], ...toast },\n ...toasts.slice(indexOfExistingToast + 1),\n ];\n }\n\n return [toast, ...toasts];\n });\n });\n });\n });\n }, []);\n\n React.useEffect(() => {\n if (theme !== 'system') {\n setActualTheme(theme);\n return;\n }\n\n if (theme === 'system') {\n // check if current preference is dark\n if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {\n // it's currently dark\n setActualTheme('dark');\n } else {\n // it's not dark\n setActualTheme('light');\n }\n }\n\n if (typeof window === 'undefined') return;\n const darkMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');\n\n try {\n // Chrome & Firefox\n darkMediaQuery.addEventListener('change', ({ matches }) => {\n if (matches) {\n setActualTheme('dark');\n } else {\n setActualTheme('light');\n }\n });\n } catch (error) {\n // Safari < 14\n darkMediaQuery.addListener(({ matches }) => {\n try {\n if (matches) {\n setActualTheme('dark');\n } else {\n setActualTheme('light');\n }\n } catch (e) {\n console.error(e);\n }\n });\n }\n }, [theme]);\n\n React.useEffect(() => {\n // Ensure expanded is always false when no toasts are present / only one left\n if (toasts.length <= 1) {\n setExpanded(false);\n }\n }, [toasts]);\n\n React.useEffect(() => {\n const handleKeyDown = (event: KeyboardEvent) => {\n const isHotkeyPressed = hotkey.every((key) => (event as any)[key] || event.code === key);\n\n if (isHotkeyPressed) {\n setExpanded(true);\n listRef.current?.focus();\n }\n\n if (\n event.code === 'Escape' &&\n (document.activeElement === listRef.current || listRef.current?.contains(document.activeElement))\n ) {\n setExpanded(false);\n }\n };\n document.addEventListener('keydown', handleKeyDown);\n\n return () => document.removeEventListener('keydown', handleKeyDown);\n }, [hotkey]);\n\n React.useEffect(() => {\n if (listRef.current) {\n return () => {\n if (lastFocusedElementRef.current) {\n lastFocusedElementRef.current.focus({ preventScroll: true });\n lastFocusedElementRef.current = null;\n isFocusWithinRef.current = false;\n }\n };\n }\n }, [listRef.current]);\n\n return (\n // Remove item from normal navigation flow, only available via hotkey\n \n {possiblePositions.map((position, index) => {\n const [y, x] = position.split('-');\n\n if (!toasts.length) return null;\n\n return (\n 1 && !expand}\n data-x-position={x}\n style={\n {\n '--front-toast-height': `${heights[0]?.height || 0}px`,\n '--width': `${TOAST_WIDTH}px`,\n '--gap': `${gap}px`,\n ...style,\n ...assignOffset(offset, mobileOffset),\n } as React.CSSProperties\n }\n onBlur={(event) => {\n if (isFocusWithinRef.current && !event.currentTarget.contains(event.relatedTarget)) {\n isFocusWithinRef.current = false;\n if (lastFocusedElementRef.current) {\n lastFocusedElementRef.current.focus({ preventScroll: true });\n lastFocusedElementRef.current = null;\n }\n }\n }}\n onFocus={(event) => {\n const isNotDismissible =\n event.target instanceof HTMLElement && event.target.dataset.dismissible === 'false';\n\n if (isNotDismissible) return;\n\n if (!isFocusWithinRef.current) {\n isFocusWithinRef.current = true;\n lastFocusedElementRef.current = event.relatedTarget as HTMLElement;\n }\n }}\n onMouseEnter={() => setExpanded(true)}\n onMouseMove={() => setExpanded(true)}\n onMouseLeave={() => {\n // Avoid setting expanded to false when interacting with a toast, e.g. swiping\n if (!interacting) {\n setExpanded(false);\n }\n }}\n onDragEnd={() => setExpanded(false)}\n onPointerDown={(event) => {\n const isNotDismissible =\n event.target instanceof HTMLElement && event.target.dataset.dismissible === 'false';\n\n if (isNotDismissible) return;\n setInteracting(true);\n }}\n onPointerUp={() => setInteracting(false)}\n >\n {toasts\n .filter((toast) => (!toast.position && index === 0) || toast.position === position)\n .map((toast, index) => (\n t.position == toast.position)}\n heights={heights.filter((h) => h.position == toast.position)}\n setHeights={setHeights}\n expandByDefault={expand}\n gap={gap}\n loadingIcon={loadingIcon}\n expanded={expanded}\n pauseWhenPageIsHidden={pauseWhenPageIsHidden}\n swipeDirections={props.swipeDirections}\n />\n ))}\n \n );\n })}\n \n );\n});\nexport { toast, Toaster, type ExternalToast, type ToastT, type ToasterProps, useSonner };\nexport { type ToastClassnames, type ToastToDismiss, type Action } from './types';\n", "'use client';\nimport React from 'react';\nimport type { ToastTypes } from './types';\n\nexport const getAsset = (type: ToastTypes): JSX.Element | null => {\n switch (type) {\n case 'success':\n return SuccessIcon;\n\n case 'info':\n return InfoIcon;\n\n case 'warning':\n return WarningIcon;\n\n case 'error':\n return ErrorIcon;\n\n default:\n return null;\n }\n};\n\nconst bars = Array(12).fill(0);\n\nexport const Loader = ({ visible, className }: { visible: boolean, className?: string }) => {\n return (\n
\n
\n {bars.map((_, i) => (\n
\n ))}\n
\n
\n );\n};\n\nconst SuccessIcon = (\n \n \n \n);\n\nconst WarningIcon = (\n \n \n \n);\n\nconst InfoIcon = (\n \n \n \n);\n\nconst ErrorIcon = (\n \n \n \n);\n\nexport const CloseIcon = (\n \n \n \n \n);\n", "import React from 'react';\n\nexport const useIsDocumentHidden = () => {\n const [isDocumentHidden, setIsDocumentHidden] = React.useState(document.hidden);\n\n React.useEffect(() => {\n const callback = () => {\n setIsDocumentHidden(document.hidden);\n };\n document.addEventListener('visibilitychange', callback);\n return () => window.removeEventListener('visibilitychange', callback);\n }, []);\n\n return isDocumentHidden;\n};\n", "import type { ExternalToast, PromiseData, PromiseT, ToastT, ToastToDismiss, ToastTypes } from './types';\n\nimport React from 'react';\n\nlet toastsCounter = 1;\n\ntype titleT = (() => React.ReactNode) | React.ReactNode;\n\nclass Observer {\n subscribers: Array<(toast: ExternalToast | ToastToDismiss) => void>;\n toasts: Array;\n dismissedToasts: Set;\n\n constructor() {\n this.subscribers = [];\n this.toasts = [];\n this.dismissedToasts = new Set();\n }\n\n // We use arrow functions to maintain the correct `this` reference\n subscribe = (subscriber: (toast: ToastT | ToastToDismiss) => void) => {\n this.subscribers.push(subscriber);\n\n return () => {\n const index = this.subscribers.indexOf(subscriber);\n this.subscribers.splice(index, 1);\n };\n };\n\n publish = (data: ToastT) => {\n this.subscribers.forEach((subscriber) => subscriber(data));\n };\n\n addToast = (data: ToastT) => {\n this.publish(data);\n this.toasts = [...this.toasts, data];\n };\n\n create = (\n data: ExternalToast & {\n message?: titleT;\n type?: ToastTypes;\n promise?: PromiseT;\n jsx?: React.ReactElement;\n },\n ) => {\n const { message, ...rest } = data;\n const id = typeof data?.id === 'number' || data.id?.length > 0 ? data.id : toastsCounter++;\n const alreadyExists = this.toasts.find((toast) => {\n return toast.id === id;\n });\n const dismissible = data.dismissible === undefined ? true : data.dismissible;\n\n if (this.dismissedToasts.has(id)) {\n this.dismissedToasts.delete(id);\n }\n\n if (alreadyExists) {\n this.toasts = this.toasts.map((toast) => {\n if (toast.id === id) {\n this.publish({ ...toast, ...data, id, title: message });\n return {\n ...toast,\n ...data,\n id,\n dismissible,\n title: message,\n };\n }\n\n return toast;\n });\n } else {\n this.addToast({ title: message, ...rest, dismissible, id });\n }\n\n return id;\n };\n\n dismiss = (id?: number | string) => {\n this.dismissedToasts.add(id);\n\n if (!id) {\n this.toasts.forEach((toast) => {\n this.subscribers.forEach((subscriber) => subscriber({ id: toast.id, dismiss: true }));\n });\n }\n this.subscribers.forEach((subscriber) => subscriber({ id, dismiss: true }));\n return id;\n };\n\n message = (message: titleT | React.ReactNode, data?: ExternalToast) => {\n return this.create({ ...data, message });\n };\n\n error = (message: titleT | React.ReactNode, data?: ExternalToast) => {\n return this.create({ ...data, message, type: 'error' });\n };\n\n success = (message: titleT | React.ReactNode, data?: ExternalToast) => {\n return this.create({ ...data, type: 'success', message });\n };\n\n info = (message: titleT | React.ReactNode, data?: ExternalToast) => {\n return this.create({ ...data, type: 'info', message });\n };\n\n warning = (message: titleT | React.ReactNode, data?: ExternalToast) => {\n return this.create({ ...data, type: 'warning', message });\n };\n\n loading = (message: titleT | React.ReactNode, data?: ExternalToast) => {\n return this.create({ ...data, type: 'loading', message });\n };\n\n promise = (promise: PromiseT, data?: PromiseData) => {\n if (!data) {\n // Nothing to show\n return;\n }\n\n let id: string | number | undefined = undefined;\n if (data.loading !== undefined) {\n id = this.create({\n ...data,\n promise,\n type: 'loading',\n message: data.loading,\n description: typeof data.description !== 'function' ? data.description : undefined,\n });\n }\n\n const p = promise instanceof Promise ? promise : promise();\n\n let shouldDismiss = id !== undefined;\n let result: ['resolve', ToastData] | ['reject', unknown];\n\n const originalPromise = p\n .then(async (response) => {\n result = ['resolve', response];\n const isReactElementResponse = React.isValidElement(response);\n if (isReactElementResponse) {\n shouldDismiss = false;\n this.create({ id, type: 'default', message: response });\n } else if (isHttpResponse(response) && !response.ok) {\n shouldDismiss = false;\n const message =\n typeof data.error === 'function' ? await data.error(`HTTP error! status: ${response.status}`) : data.error;\n const description =\n typeof data.description === 'function'\n ? await data.description(`HTTP error! status: ${response.status}`)\n : data.description;\n this.create({ id, type: 'error', message, description });\n } else if (data.success !== undefined) {\n shouldDismiss = false;\n const message = typeof data.success === 'function' ? await data.success(response) : data.success;\n const description =\n typeof data.description === 'function' ? await data.description(response) : data.description;\n this.create({ id, type: 'success', message, description });\n }\n })\n .catch(async (error) => {\n result = ['reject', error];\n if (data.error !== undefined) {\n shouldDismiss = false;\n const message = typeof data.error === 'function' ? await data.error(error) : data.error;\n const description = typeof data.description === 'function' ? await data.description(error) : data.description;\n this.create({ id, type: 'error', message, description });\n }\n })\n .finally(() => {\n if (shouldDismiss) {\n // Toast is still in load state (and will be indefinitely — dismiss it)\n this.dismiss(id);\n id = undefined;\n }\n\n data.finally?.();\n });\n\n const unwrap = () =>\n new Promise((resolve, reject) =>\n originalPromise.then(() => (result[0] === 'reject' ? reject(result[1]) : resolve(result[1]))).catch(reject),\n );\n\n if (typeof id !== 'string' && typeof id !== 'number') {\n // cannot Object.assign on undefined\n return { unwrap };\n } else {\n return Object.assign(id, { unwrap });\n }\n };\n\n custom = (jsx: (id: number | string) => React.ReactElement, data?: ExternalToast) => {\n const id = data?.id || toastsCounter++;\n this.create({ jsx: jsx(id), id, ...data });\n return id;\n };\n\n getActiveToasts = () => {\n return this.toasts.filter((toast) => !this.dismissedToasts.has(toast.id));\n };\n}\n\nexport const ToastState = new Observer();\n\n// bind this to the toast function\nconst toastFunction = (message: titleT, data?: ExternalToast) => {\n const id = data?.id || toastsCounter++;\n\n ToastState.addToast({\n title: message,\n ...data,\n id,\n });\n return id;\n};\n\nconst isHttpResponse = (data: any): data is Response => {\n return (\n data &&\n typeof data === 'object' &&\n 'ok' in data &&\n typeof data.ok === 'boolean' &&\n 'status' in data &&\n typeof data.status === 'number'\n );\n};\n\nconst basicToast = toastFunction;\n\nconst getHistory = () => ToastState.toasts;\nconst getToasts = () => ToastState.getActiveToasts();\n\n// We use `Object.assign` to maintain the correct types as we would lose them otherwise\nexport const toast = Object.assign(\n basicToast,\n {\n success: ToastState.success,\n info: ToastState.info,\n warning: ToastState.warning,\n error: ToastState.error,\n custom: ToastState.custom,\n message: ToastState.message,\n promise: ToastState.promise,\n dismiss: ToastState.dismiss,\n loading: ToastState.loading,\n },\n { getHistory, getToasts },\n);\n", "\n export default function styleInject(css, { insertAt } = {}) {\n if (!css || typeof document === 'undefined') return\n \n const head = document.head || document.getElementsByTagName('head')[0]\n const style = document.createElement('style')\n style.type = 'text/css'\n \n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild)\n } else {\n head.appendChild(style)\n }\n } else {\n head.appendChild(style)\n }\n \n if (style.styleSheet) {\n style.styleSheet.cssText = css\n } else {\n style.appendChild(document.createTextNode(css))\n }\n }\n ", "import styleInject from '#style-inject';styleInject(\":where(html[dir=\\\"ltr\\\"]),:where([data-sonner-toaster][dir=\\\"ltr\\\"]){--toast-icon-margin-start: -3px;--toast-icon-margin-end: 4px;--toast-svg-margin-start: -1px;--toast-svg-margin-end: 0px;--toast-button-margin-start: auto;--toast-button-margin-end: 0;--toast-close-button-start: 0;--toast-close-button-end: unset;--toast-close-button-transform: translate(-35%, -35%)}:where(html[dir=\\\"rtl\\\"]),:where([data-sonner-toaster][dir=\\\"rtl\\\"]){--toast-icon-margin-start: 4px;--toast-icon-margin-end: -3px;--toast-svg-margin-start: 0px;--toast-svg-margin-end: -1px;--toast-button-margin-start: 0;--toast-button-margin-end: auto;--toast-close-button-start: unset;--toast-close-button-end: 0;--toast-close-button-transform: translate(35%, -35%)}:where([data-sonner-toaster]){position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1: hsl(0, 0%, 99%);--gray2: hsl(0, 0%, 97.3%);--gray3: hsl(0, 0%, 95.1%);--gray4: hsl(0, 0%, 93%);--gray5: hsl(0, 0%, 90.9%);--gray6: hsl(0, 0%, 88.7%);--gray7: hsl(0, 0%, 85.8%);--gray8: hsl(0, 0%, 78%);--gray9: hsl(0, 0%, 56.1%);--gray10: hsl(0, 0%, 52.3%);--gray11: hsl(0, 0%, 43.5%);--gray12: hsl(0, 0%, 9%);--border-radius: 8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:none;z-index:999999999;transition:transform .4s ease}:where([data-sonner-toaster][data-lifted=\\\"true\\\"]){transform:translateY(-10px)}@media (hover: none) and (pointer: coarse){:where([data-sonner-toaster][data-lifted=\\\"true\\\"]){transform:none}}:where([data-sonner-toaster][data-x-position=\\\"right\\\"]){right:var(--offset-right)}:where([data-sonner-toaster][data-x-position=\\\"left\\\"]){left:var(--offset-left)}:where([data-sonner-toaster][data-x-position=\\\"center\\\"]){left:50%;transform:translate(-50%)}:where([data-sonner-toaster][data-y-position=\\\"top\\\"]){top:var(--offset-top)}:where([data-sonner-toaster][data-y-position=\\\"bottom\\\"]){bottom:var(--offset-bottom)}:where([data-sonner-toast]){--y: translateY(100%);--lift-amount: calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);filter:blur(0);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere}:where([data-sonner-toast][data-styled=\\\"true\\\"]){padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}:where([data-sonner-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-y-position=\\\"top\\\"]){top:0;--y: translateY(-100%);--lift: 1;--lift-amount: calc(1 * var(--gap))}:where([data-sonner-toast][data-y-position=\\\"bottom\\\"]){bottom:0;--y: translateY(100%);--lift: -1;--lift-amount: calc(var(--lift) * var(--gap))}:where([data-sonner-toast]) :where([data-description]){font-weight:400;line-height:1.4;color:inherit}:where([data-sonner-toast]) :where([data-title]){font-weight:500;line-height:1.5;color:inherit}:where([data-sonner-toast]) :where([data-icon]){display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}:where([data-sonner-toast][data-promise=\\\"true\\\"]) :where([data-icon])>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}:where([data-sonner-toast]) :where([data-icon])>*{flex-shrink:0}:where([data-sonner-toast]) :where([data-icon]) svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}:where([data-sonner-toast]) :where([data-content]){display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;cursor:pointer;outline:none;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}:where([data-sonner-toast]) :where([data-button]):focus-visible{box-shadow:0 0 0 2px #0006}:where([data-sonner-toast]) :where([data-button]):first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}:where([data-sonner-toast]) :where([data-cancel]){color:var(--normal-text);background:rgba(0,0,0,.08)}:where([data-sonner-toast][data-theme=\\\"dark\\\"]) :where([data-cancel]){background:rgba(255,255,255,.3)}:where([data-sonner-toast]) :where([data-close-button]){position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast] [data-close-button]{background:var(--gray1)}:where([data-sonner-toast]) :where([data-close-button]):focus-visible{box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast]) :where([data-disabled=\\\"true\\\"]){cursor:not-allowed}:where([data-sonner-toast]):hover :where([data-close-button]):hover{background:var(--gray2);border-color:var(--gray5)}:where([data-sonner-toast][data-swiping=\\\"true\\\"]):before{content:\\\"\\\";position:absolute;left:-50%;right:-50%;height:100%;z-index:-1}:where([data-sonner-toast][data-y-position=\\\"top\\\"][data-swiping=\\\"true\\\"]):before{bottom:50%;transform:scaleY(3) translateY(50%)}:where([data-sonner-toast][data-y-position=\\\"bottom\\\"][data-swiping=\\\"true\\\"]):before{top:50%;transform:scaleY(3) translateY(-50%)}:where([data-sonner-toast][data-swiping=\\\"false\\\"][data-removed=\\\"true\\\"]):before{content:\\\"\\\";position:absolute;inset:0;transform:scaleY(2)}:where([data-sonner-toast]):after{content:\\\"\\\";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}:where([data-sonner-toast][data-mounted=\\\"true\\\"]){--y: translateY(0);opacity:1}:where([data-sonner-toast][data-expanded=\\\"false\\\"][data-front=\\\"false\\\"]){--scale: var(--toasts-before) * .05 + 1;--y: translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}:where([data-sonner-toast])>*{transition:opacity .4s}:where([data-sonner-toast][data-expanded=\\\"false\\\"][data-front=\\\"false\\\"][data-styled=\\\"true\\\"])>*{opacity:0}:where([data-sonner-toast][data-visible=\\\"false\\\"]){opacity:0;pointer-events:none}:where([data-sonner-toast][data-mounted=\\\"true\\\"][data-expanded=\\\"true\\\"]){--y: translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}:where([data-sonner-toast][data-removed=\\\"true\\\"][data-front=\\\"true\\\"][data-swipe-out=\\\"false\\\"]){--y: translateY(calc(var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed=\\\"true\\\"][data-front=\\\"false\\\"][data-swipe-out=\\\"false\\\"][data-expanded=\\\"true\\\"]){--y: translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed=\\\"true\\\"][data-front=\\\"false\\\"][data-swipe-out=\\\"false\\\"][data-expanded=\\\"false\\\"]){--y: translateY(40%);opacity:0;transition:transform .5s,opacity .2s}:where([data-sonner-toast][data-removed=\\\"true\\\"][data-front=\\\"false\\\"]):before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y, 0px)) translate(var(--swipe-amount-x, 0px));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width: 600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-theme=light]{--normal-bg: #fff;--normal-border: var(--gray4);--normal-text: var(--gray12);--success-bg: hsl(143, 85%, 96%);--success-border: hsl(145, 92%, 91%);--success-text: hsl(140, 100%, 27%);--info-bg: hsl(208, 100%, 97%);--info-border: hsl(221, 91%, 91%);--info-text: hsl(210, 92%, 45%);--warning-bg: hsl(49, 100%, 97%);--warning-border: hsl(49, 91%, 91%);--warning-text: hsl(31, 92%, 45%);--error-bg: hsl(359, 100%, 97%);--error-border: hsl(359, 100%, 94%);--error-text: hsl(360, 100%, 45%)}[data-sonner-toaster][data-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg: #fff;--normal-border: var(--gray3);--normal-text: var(--gray12)}[data-sonner-toaster][data-theme=dark]{--normal-bg: #000;--normal-bg-hover: hsl(0, 0%, 12%);--normal-border: hsl(0, 0%, 20%);--normal-border-hover: hsl(0, 0%, 25%);--normal-text: var(--gray1);--success-bg: hsl(150, 100%, 6%);--success-border: hsl(147, 100%, 12%);--success-text: hsl(150, 86%, 65%);--info-bg: hsl(215, 100%, 6%);--info-border: hsl(223, 100%, 12%);--info-text: hsl(216, 87%, 65%);--warning-bg: hsl(64, 100%, 6%);--warning-border: hsl(60, 100%, 12%);--warning-text: hsl(46, 87%, 65%);--error-bg: hsl(358, 76%, 10%);--error-border: hsl(357, 89%, 16%);--error-text: hsl(358, 100%, 81%)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success],[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info],[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning],[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error],[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size: 16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:nth-child(1){animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}to{opacity:.15}}@media (prefers-reduced-motion){[data-sonner-toast],[data-sonner-toast]>*,.sonner-loading-bar{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}\\n\")", "import React from 'react';\n\nexport type ToastTypes = 'normal' | 'action' | 'success' | 'info' | 'warning' | 'error' | 'loading' | 'default';\n\nexport type PromiseT = Promise | (() => Promise);\n\nexport type PromiseTResult =\n | string\n | React.ReactNode\n | ((data: Data) => React.ReactNode | string | Promise);\n\nexport type PromiseExternalToast = Omit;\n\nexport type PromiseData = PromiseExternalToast & {\n loading?: string | React.ReactNode;\n success?: PromiseTResult;\n error?: PromiseTResult;\n description?: PromiseTResult;\n finally?: () => void | Promise;\n};\n\nexport interface ToastClassnames {\n toast?: string;\n title?: string;\n description?: string;\n loader?: string;\n closeButton?: string;\n cancelButton?: string;\n actionButton?: string;\n success?: string;\n error?: string;\n info?: string;\n warning?: string;\n loading?: string;\n default?: string;\n content?: string;\n icon?: string;\n}\n\nexport interface ToastIcons {\n success?: React.ReactNode;\n info?: React.ReactNode;\n warning?: React.ReactNode;\n error?: React.ReactNode;\n loading?: React.ReactNode;\n close?: React.ReactNode;\n}\n\nexport interface Action {\n label: React.ReactNode;\n onClick: (event: React.MouseEvent) => void;\n actionButtonStyle?: React.CSSProperties;\n}\n\nexport interface ToastT {\n id: number | string;\n title?: (() => React.ReactNode) | React.ReactNode;\n type?: ToastTypes;\n icon?: React.ReactNode;\n jsx?: React.ReactNode;\n richColors?: boolean;\n invert?: boolean;\n closeButton?: boolean;\n dismissible?: boolean;\n description?: (() => React.ReactNode) | React.ReactNode;\n duration?: number;\n delete?: boolean;\n action?: Action | React.ReactNode;\n cancel?: Action | React.ReactNode;\n onDismiss?: (toast: ToastT) => void;\n onAutoClose?: (toast: ToastT) => void;\n promise?: PromiseT;\n cancelButtonStyle?: React.CSSProperties;\n actionButtonStyle?: React.CSSProperties;\n style?: React.CSSProperties;\n unstyled?: boolean;\n className?: string;\n classNames?: ToastClassnames;\n descriptionClassName?: string;\n position?: Position;\n}\n\nexport function isAction(action: Action | React.ReactNode): action is Action {\n return (action as Action).label !== undefined;\n}\n\nexport type Position = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'top-center' | 'bottom-center';\nexport interface HeightT {\n height: number;\n toastId: number | string;\n position: Position;\n}\n\ninterface ToastOptions {\n className?: string;\n closeButton?: boolean;\n descriptionClassName?: string;\n style?: React.CSSProperties;\n cancelButtonStyle?: React.CSSProperties;\n actionButtonStyle?: React.CSSProperties;\n duration?: number;\n unstyled?: boolean;\n classNames?: ToastClassnames;\n}\n\ntype Offset =\n | {\n top?: string | number;\n right?: string | number;\n bottom?: string | number;\n left?: string | number;\n }\n | string\n | number;\n\nexport interface ToasterProps {\n invert?: boolean;\n theme?: 'light' | 'dark' | 'system';\n position?: Position;\n hotkey?: string[];\n richColors?: boolean;\n expand?: boolean;\n duration?: number;\n gap?: number;\n visibleToasts?: number;\n closeButton?: boolean;\n toastOptions?: ToastOptions;\n className?: string;\n style?: React.CSSProperties;\n offset?: Offset;\n mobileOffset?: Offset;\n dir?: 'rtl' | 'ltr' | 'auto';\n swipeDirections?: SwipeDirection[];\n /**\n * @deprecated Please use the `icons` prop instead:\n * ```jsx\n * }}\n * />\n * ```\n */\n loadingIcon?: React.ReactNode;\n icons?: ToastIcons;\n containerAriaLabel?: string;\n pauseWhenPageIsHidden?: boolean;\n}\n\nexport type SwipeDirection = 'top' | 'right' | 'bottom' | 'left';\n\nexport interface ToastProps {\n toast: ToastT;\n toasts: ToastT[];\n index: number;\n swipeDirections?: SwipeDirection[];\n expanded: boolean;\n invert: boolean;\n heights: HeightT[];\n setHeights: React.Dispatch>;\n removeToast: (toast: ToastT) => void;\n gap?: number;\n position: Position;\n visibleToasts: number;\n expandByDefault: boolean;\n closeButton: boolean;\n interacting: boolean;\n style?: React.CSSProperties;\n cancelButtonStyle?: React.CSSProperties;\n actionButtonStyle?: React.CSSProperties;\n duration?: number;\n className?: string;\n unstyled?: boolean;\n descriptionClassName?: string;\n loadingIcon?: React.ReactNode;\n classNames?: ToastClassnames;\n icons?: ToastIcons;\n closeButtonAriaLabel?: string;\n pauseWhenPageIsHidden: boolean;\n defaultRichColors?: boolean;\n}\n\nexport enum SwipeStateTypes {\n SwipedOut = 'SwipedOut',\n SwipedBack = 'SwipedBack',\n NotSwiped = 'NotSwiped',\n}\n\nexport type Theme = 'light' | 'dark';\n\nexport interface ToastToDismiss {\n id: number | string;\n dismiss: boolean;\n}\n\nexport type ExternalToast = Omit & {\n id?: number | string;\n};\n", "'use client'\nimport type { MouseEvent } from 'react'\n\nimport React from 'react'\n\nimport './index.scss'\nimport { Link } from '../Link/index.js'\n\nconst baseClass = 'banner'\n\ntype onClick = (event: MouseEvent) => void\n\nexport type Props = Readonly<{\n alignIcon?: 'left' | 'right'\n children?: React.ReactNode\n className?: string\n icon?: React.ReactNode\n onClick?: onClick\n to?: string\n type?: 'default' | 'error' | 'info' | 'success'\n}>\n\nexport type RenderedTypeProps = {\n children?: React.ReactNode\n className?: string\n onClick?: onClick\n to: string\n}\n\nexport const Banner: React.FC = ({\n type = 'default',\n alignIcon = 'right',\n children,\n className,\n icon,\n onClick,\n to,\n}) => {\n const classes = [\n baseClass,\n `${baseClass}--type-${type}`,\n className && className,\n to && `${baseClass}--has-link`,\n (to || onClick) && `${baseClass}--has-action`,\n icon && `${baseClass}--has-icon`,\n icon && `${baseClass}--align-icon-${alignIcon}`,\n ]\n .filter(Boolean)\n .join(' ')\n\n let RenderedType: React.ComponentType | React.ElementType = 'div'\n\n if (onClick && !to) {\n RenderedType = 'button'\n }\n if (to) {\n RenderedType = Link\n }\n\n return (\n \n {icon && alignIcon === 'left' && {icon}}\n {children}\n {icon && alignIcon === 'right' && {icon}}\n \n )\n}\n", "'use client'\nimport NextLinkImport from 'next/link.js'\nimport { useRouter } from 'next/navigation.js'\nimport React from 'react'\n\nimport { useRouteTransition } from '../../providers/RouteTransition/index.js'\nimport { formatUrl } from './formatUrl.js'\n\nconst NextLink = 'default' in NextLinkImport ? NextLinkImport.default : NextLinkImport\n\n// Copied from https://github.com/vercel/next.js/blob/canary/packages/next/src/client/link.tsx#L180-L191\nfunction isModifiedEvent(event: React.MouseEvent): boolean {\n const eventTarget = event.currentTarget as HTMLAnchorElement | SVGAElement\n const target = eventTarget.getAttribute('target')\n return (\n (target && target !== '_self') ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey || // triggers resource download\n (event.nativeEvent && event.nativeEvent.which === 2)\n )\n}\n\ntype Props = {\n /**\n * Disable the e.preventDefault() call on click if you want to handle it yourself via onClick\n *\n * @default true\n */\n preventDefault?: boolean\n} & Parameters[0]\n\nexport const Link: React.FC = ({\n children,\n href,\n onClick,\n preventDefault = true,\n ref,\n replace,\n scroll,\n ...rest\n}) => {\n const router = useRouter()\n const { startRouteTransition } = useRouteTransition()\n\n return (\n {\n if (isModifiedEvent(e)) {\n return\n }\n\n if (onClick) {\n onClick(e)\n }\n\n // We need a preventDefault here so that a clicked link doesn't trigger twice,\n // once for default browser navigation and once for startRouteTransition\n if (preventDefault) {\n e.preventDefault()\n }\n\n const url = typeof href === 'string' ? href : formatUrl(href)\n\n const navigate = () => {\n if (replace) {\n void router.replace(url, { scroll })\n } else {\n void router.push(url, { scroll })\n }\n }\n\n // Call startRouteTransition if available, otherwise navigate directly\n startRouteTransition(navigate)\n }}\n ref={ref}\n {...rest}\n >\n {children}\n \n )\n}\n", "'use client'\nimport React, { startTransition, useCallback, useEffect, useOptimistic, useRef } from 'react'\n\n/**\n * Route transitions are useful in showing immediate visual feedback to the user when navigating between pages. This is especially useful on slow networks when navigating to data heavy or process intensive pages.\n * To use route transitions, place the `RouteTransitionProvider` at the root of your application, outside of the `ProgressBar` component.\n * To trigger a route transition, use the `Link` component from `@payloadcms/ui`,\n * or wrap a callback function with the `startRouteTransition` method.\n * To gain access to the `RouteTransitionContext`, call the `useRouteTransition` hook in your component.\n * @returns A context provider with methods and state for transitioning between routes, including `isTransitioning`, `startRouteTransition`, and `transitionProgress`.\n * @example\n * import { RouteTransitionProvider, ProgressBar, Link } from '@payloadcms/ui'\n * const App = () => (\n * \n * \n * Go Somewhere\n * \n * )\n */\nexport const RouteTransitionProvider: React.FC = ({ children }) => {\n const [isTransitioning, setIsTransitioning] = useOptimistic(false)\n const [transitionProgress, setTransitionProgress] = React.useState(0)\n\n const transitionProgressRef = useRef(transitionProgress)\n\n const timerID = useRef(null)\n\n const initiateProgress = useCallback(() => {\n timerID.current = setInterval(() => {\n // randomly update progress using an exponential curve\n // cap the progress to ensure it never fully reaches completion\n // accelerate quickly then decelerate slowly\n const maxProgress = 0.93\n const jumpFactor = 0.2 // lower to reduce jumps in progress\n const growthFactor = 0.75 // adjust to control acceleration\n const slowdownFactor = 0.75 // adjust to control deceleration\n\n const newProgress =\n transitionProgressRef.current +\n (maxProgress - transitionProgressRef.current) *\n Math.random() *\n jumpFactor *\n Math.pow(Math.log(1 + (1 - transitionProgressRef.current) * growthFactor), slowdownFactor)\n\n setTransitionProgress(newProgress)\n transitionProgressRef.current = newProgress\n }, 250) // every n ms, update progress\n }, [])\n\n useEffect(() => {\n setTransitionProgress(0)\n transitionProgressRef.current = 0\n\n if (isTransitioning) {\n initiateProgress()\n } else {\n if (timerID.current) {\n clearInterval(timerID.current)\n }\n }\n }, [isTransitioning, initiateProgress])\n\n const startRouteTransition: StartRouteTransition = useCallback(\n (callback?: () => void) => {\n startTransition(() => {\n setIsTransitioning(true)\n\n if (typeof callback === 'function') {\n callback()\n }\n })\n },\n [setIsTransitioning],\n )\n\n return (\n \n {children}\n \n )\n}\n\ntype RouteTransitionProps = {\n children: React.ReactNode\n}\n\ntype StartRouteTransition = (callback?: () => void) => void\n\ntype RouteTransitionContextValue = {\n isTransitioning: boolean\n startRouteTransition: StartRouteTransition\n transitionProgress: number\n}\n\nconst RouteTransitionContext = React.createContext({\n isTransitioning: false,\n // Default implementation: just call the callback directly (no transition animation)\n startRouteTransition: (callback) => {\n if (typeof callback === 'function') {\n callback()\n }\n },\n transitionProgress: 0,\n})\n\n/**\n * Use this hook to access the `RouteTransitionContext` provided by the `RouteTransitionProvider`.\n * To start a transition, fire the `startRouteTransition` method with a provided callback to run while the transition takes place.\n * @returns The `RouteTransitionContext` needed for transitioning between routes, including `isTransitioning`, `startRouteTransition`, and `transitionProgress`.\n * @example\n * 'use client'\n * import React, { useCallback } from 'react'\n * import { useTransition } from '@payloadcms/ui'\n * import { useRouter } from 'next/navigation'\n *\n * const MyComponent: React.FC = () => {\n * const router = useRouter()\n * const { startRouteTransition } = useRouteTransition()\n *\n * const redirectSomewhere = useCallback(() => {\n * startRouteTransition(() => router.push('/somewhere'))\n * }, [startRouteTransition, router])\n *\n * // ...\n * }\n */\nexport const useRouteTransition = () => React.use(RouteTransitionContext)\n", "// Format function modified from nodejs\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { UrlObject } from 'url'\n\nconst slashedProtocols = /https?|ftp|gopher|file/\n\nfunction stringifyUrlQueryParam(param: unknown): string {\n if (\n typeof param === 'string' ||\n (typeof param === 'number' && !isNaN(param)) ||\n typeof param === 'boolean'\n ) {\n return String(param)\n } else {\n return ''\n }\n}\n\nexport function urlQueryToSearchParams(urlQuery: UrlObject['query']): URLSearchParams {\n const result = new URLSearchParams()\n Object.entries(urlQuery).forEach(([key, value]) => {\n if (Array.isArray(value)) {\n value.forEach((item) => result.append(key, stringifyUrlQueryParam(item)))\n } else {\n result.set(key, stringifyUrlQueryParam(value))\n }\n })\n return result\n}\n\nexport function formatUrl(urlObj: UrlObject) {\n let { auth } = urlObj\n const { hostname } = urlObj\n let protocol = urlObj.protocol || ''\n let pathname = urlObj.pathname || ''\n let hash = urlObj.hash || ''\n let query = urlObj.query || ''\n let host: false | string = false\n\n auth = auth ? encodeURIComponent(auth).replace(/%3A/i, ':') + '@' : ''\n\n if (urlObj.host) {\n host = auth + urlObj.host\n } else if (hostname) {\n host = auth + (~hostname.indexOf(':') ? `[${hostname}]` : hostname)\n if (urlObj.port) {\n host += ':' + urlObj.port\n }\n }\n\n if (query && typeof query === 'object') {\n query = String(urlQueryToSearchParams(query))\n }\n\n let search = urlObj.search || (query && `?${query}`) || ''\n\n if (protocol && !protocol.endsWith(':')) {\n protocol += ':'\n }\n\n if (urlObj.slashes || ((!protocol || slashedProtocols.test(protocol)) && host !== false)) {\n host = '//' + (host || '')\n if (pathname && pathname[0] !== '/') {\n pathname = '/' + pathname\n }\n } else if (!host) {\n host = ''\n }\n\n if (hash && hash[0] !== '#') {\n hash = '#' + hash\n }\n if (search && search[0] !== '?') {\n search = '?' + search\n }\n\n pathname = pathname.replace(/[?#]/g, encodeURIComponent)\n search = search.replace('#', '%23')\n\n return `${protocol}${host}${pathname}${search}${hash}`\n}\n", "'use client'\nimport React, { Fragment, isValidElement } from 'react'\n\nimport type { Props } from './types.js'\n\nimport { ChevronIcon } from '../../icons/Chevron/index.js'\nimport { EditIcon } from '../../icons/Edit/index.js'\nimport { LinkIcon } from '../../icons/Link/index.js'\nimport { PlusIcon } from '../../icons/Plus/index.js'\nimport { SwapIcon } from '../../icons/Swap/index.js'\nimport { XIcon } from '../../icons/X/index.js'\nimport { Link } from '../Link/index.js'\nimport { Popup } from '../Popup/index.js'\nimport './index.scss'\nimport { Tooltip } from '../Tooltip/index.js'\n\nconst icons = {\n chevron: ChevronIcon,\n edit: EditIcon,\n link: LinkIcon,\n plus: PlusIcon,\n swap: SwapIcon,\n x: XIcon,\n}\n\nconst baseClass = 'btn'\n\nexport const ButtonContents = ({ children, icon, showTooltip, tooltip }) => {\n const BuiltInIcon = icons[icon]\n\n return (\n \n {tooltip && (\n \n {tooltip}\n \n )}\n \n {children && {children}}\n {icon && (\n \n {isValidElement(icon) && icon}\n {BuiltInIcon && }\n \n )}\n \n \n )\n}\n\nexport const Button: React.FC = (props) => {\n const {\n id,\n type = 'button',\n 'aria-label': ariaLabel,\n buttonStyle = 'primary',\n children,\n className,\n disabled,\n el = 'button',\n enableSubMenu,\n extraButtonProps = {},\n icon,\n iconPosition = 'right',\n iconStyle = 'without-border',\n margin = true,\n newTab,\n onClick,\n onMouseDown,\n ref,\n round,\n size = 'medium',\n SubMenuPopupContent,\n to,\n tooltip,\n url,\n } = props\n\n const [showTooltip, setShowTooltip] = React.useState(false)\n\n const classes = [\n baseClass,\n className && className,\n icon && `${baseClass}--icon`,\n iconStyle && `${baseClass}--icon-style-${iconStyle}`,\n icon && !children && `${baseClass}--icon-only`,\n size && `${baseClass}--size-${size}`,\n icon && iconPosition && `${baseClass}--icon-position-${iconPosition}`,\n tooltip && `${baseClass}--has-tooltip`,\n !SubMenuPopupContent && `${baseClass}--withoutPopup`,\n !margin && `${baseClass}--no-margin`,\n ]\n .filter(Boolean)\n .join(' ')\n\n function handleClick(event) {\n setShowTooltip(false)\n if (type !== 'submit' && onClick) {\n event.preventDefault()\n }\n if (onClick) {\n onClick(event)\n }\n }\n\n const styleClasses = [\n buttonStyle && `${baseClass}--style-${buttonStyle}`,\n disabled && `${baseClass}--disabled`,\n round && `${baseClass}--round`,\n SubMenuPopupContent ? `${baseClass}--withPopup` : `${baseClass}--withoutPopup`,\n ]\n .filter(Boolean)\n .join(' ')\n\n const buttonProps = {\n id,\n type,\n 'aria-disabled': disabled,\n 'aria-label': ariaLabel,\n className: !SubMenuPopupContent ? [classes, styleClasses].join(' ') : classes,\n disabled,\n onClick: !disabled ? handleClick : undefined,\n onMouseDown: !disabled ? onMouseDown : undefined,\n onPointerEnter: tooltip ? () => setShowTooltip(true) : undefined,\n onPointerLeave: tooltip ? () => setShowTooltip(false) : undefined,\n rel: newTab ? 'noopener noreferrer' : undefined,\n target: newTab ? '_blank' : undefined,\n title: ariaLabel,\n ...extraButtonProps,\n }\n\n let buttonElement\n\n switch (el) {\n case 'anchor':\n buttonElement = (\n }\n >\n \n {children}\n \n \n )\n break\n\n case 'link':\n if (disabled) {\n buttonElement = (\n
\n \n {children}\n \n
\n )\n }\n\n buttonElement = (\n \n \n {children}\n \n \n )\n\n break\n\n default:\n const Tag = el // eslint-disable-line no-case-declarations\n\n buttonElement = (\n \n \n {children}\n \n \n )\n break\n }\n if (SubMenuPopupContent) {\n return (\n
\n {buttonElement}\n }\n buttonSize={size}\n className={disabled && !enableSubMenu ? `${baseClass}--popup-disabled` : ''}\n disabled={disabled && !enableSubMenu}\n horizontalAlign=\"right\"\n id={`${id}-popup`}\n noBackground\n render={({ close }) => SubMenuPopupContent({ close: () => close() })}\n size=\"large\"\n verticalAlign=\"bottom\"\n />\n
\n )\n }\n\n return buttonElement\n}\n", "import React from 'react'\n\nimport './index.scss'\n\nexport const ChevronIcon: React.FC<{\n readonly ariaLabel?: string\n readonly className?: string\n readonly direction?: 'down' | 'left' | 'right' | 'up'\n readonly size?: 'large' | 'small'\n}> = ({ ariaLabel, className, direction, size }) => (\n \n \n \n)\n", "import React from 'react'\n\nimport './index.scss'\n\nexport const EditIcon: React.FC<{ className?: string }> = ({ className }) => (\n \n \n \n)\n", "import React from 'react'\n\nimport './index.scss'\n\nexport const LinkIcon: React.FC = () => (\n \n \n \n)\n", "import React from 'react'\n\nimport './index.scss'\n\nexport const PlusIcon: React.FC = () => (\n \n \n \n)\n", "import React from 'react'\n\nimport './index.scss'\n\nexport const SwapIcon: React.FC = () => (\n \n \n \n)\n", "'use client'\nimport type { LinkProps } from 'next/link.js'\n\nimport * as React from 'react'\n\nimport { Link } from '../../Link/index.js'\nimport './index.scss'\n\nconst baseClass = 'popup-button-list'\n\nexport { PopupListDivider as Divider } from '../PopupDivider/index.js'\nexport { PopupListGroupLabel as GroupLabel } from '../PopupGroupLabel/index.js'\n\nexport const ButtonGroup: React.FC<{\n buttonSize?: 'default' | 'small'\n children: React.ReactNode\n className?: string\n textAlign?: 'center' | 'left' | 'right'\n}> = ({ buttonSize = 'default', children, className, textAlign = 'left' }) => {\n const classes = [\n baseClass,\n className,\n `${baseClass}__text-align--${textAlign}`,\n `${baseClass}__button-size--${buttonSize}`,\n ]\n .filter(Boolean)\n .join(' ')\n return
{children}
\n}\n\ntype MenuButtonProps = {\n active?: boolean\n children: React.ReactNode\n className?: string\n disabled?: boolean\n href?: LinkProps['href']\n id?: string\n onClick?: (e?: React.MouseEvent) => void\n}\n\nexport const Button: React.FC = ({\n id,\n active,\n children,\n className,\n disabled,\n href,\n onClick,\n}) => {\n const classes = [\n `${baseClass}__button`,\n disabled && `${baseClass}__disabled`,\n active && `${baseClass}__button--selected`,\n className,\n ]\n .filter(Boolean)\n .join(' ')\n\n if (!disabled) {\n if (href) {\n return (\n {\n if (onClick) {\n onClick(e)\n }\n }}\n prefetch={false}\n >\n {children}\n \n )\n }\n\n if (onClick) {\n return (\n {\n if (onClick) {\n onClick(e)\n }\n }}\n type=\"button\"\n >\n {children}\n \n )\n }\n }\n\n return (\n
\n {children}\n
\n )\n}\n", "import React from 'react'\n\nimport './index.scss'\n\nconst baseClass = 'popup-divider'\n\nexport const PopupListDivider: React.FC = () => {\n return
\n}\n", "import React from 'react'\n\nimport './index.scss'\n\nconst baseClass = 'popup-list-group-label'\n\nexport const PopupListGroupLabel: React.FC<{\n label: string\n}> = ({ label }) => {\n return

{label}

\n}\n", "'use client'\nimport type { CSSProperties } from 'react'\n\nexport * as PopupList from './PopupButtonList/index.js'\n\nimport React, { useCallback, useEffect, useRef, useState } from 'react'\nimport { createPortal } from 'react-dom'\n\nimport { useEffectEvent } from '../../hooks/useEffectEvent.js'\nimport './index.scss'\nimport { PopupTrigger } from './PopupTrigger/index.js'\n\nconst baseClass = 'popup'\n\n/**\n * Selector for all elements the browser considers tabbable.\n */\nconst TABBABLE_SELECTOR = [\n 'a[href]',\n 'button:not(:disabled)',\n 'input:not(:disabled):not([type=\"hidden\"])',\n 'select:not(:disabled)',\n 'textarea:not(:disabled)',\n '[tabindex]',\n '[contenteditable]:not([contenteditable=\"false\"])',\n 'audio[controls]',\n 'video[controls]',\n 'summary',\n]\n .map((s) => `${s}:not([tabindex=\"-1\"])`)\n .join(', ')\n\nexport type PopupProps = {\n backgroundColor?: CSSProperties['backgroundColor']\n boundingRef?: React.RefObject\n button?: React.ReactNode\n /**\n * The class name to apply to the button that triggers the popup.\n */\n buttonClassName?: string\n buttonSize?: 'large' | 'medium' | 'small' | 'xsmall'\n buttonType?: 'custom' | 'default' | 'none'\n caret?: boolean\n children?: React.ReactNode\n /**\n * The class name to apply to the popup container containing the trigger.\n * This does not wrap the actual popup content, which is rendered in a portal.\n */\n className?: string\n disabled?: boolean\n /**\n * Force control the open state of the popup, regardless of the trigger.\n */\n forceOpen?: boolean\n /**\n * Preferred horizontal alignment of the popup, if there is enough space available.\n *\n * @default 'left'\n */\n horizontalAlign?: 'center' | 'left' | 'right'\n id?: string\n initActive?: boolean\n noBackground?: boolean\n onToggleClose?: () => void\n onToggleOpen?: (active: boolean) => void\n /**\n * Class name to apply to the portal container.\n */\n portalClassName?: string\n render?: (args: { close: () => void }) => React.ReactNode\n showOnHover?: boolean\n /**\n * By default, the scrollbar is hidden. If you want to show it, set this to true.\n * In both cases, the container is still scrollable.\n *\n * @default false\n */\n showScrollbar?: boolean\n size?: 'fit-content' | 'large' | 'medium' | 'small'\n /**\n * Preferred vertical alignment of the popup (position below or above the trigger),\n * if there is enough space available.\n *\n * If the popup is too close to the edge of the viewport, it will flip to the opposite side\n * regardless of the preferred vertical alignment.\n *\n * @default 'bottom'\n */\n verticalAlign?: 'bottom' | 'top'\n}\n\n/**\n * Component that renders a popup, as well as a button that triggers the popup.\n *\n * The popup is rendered in a portal, and is automatically positioned above / below the trigger,\n * depending on the verticalAlign prop and the space available.\n */\nexport const Popup: React.FC = (props) => {\n const {\n id,\n button,\n buttonClassName,\n buttonSize,\n buttonType = 'default',\n caret = true,\n children,\n className,\n disabled,\n forceOpen,\n horizontalAlign = 'left',\n initActive = false,\n noBackground,\n onToggleClose,\n onToggleOpen,\n portalClassName,\n render,\n showOnHover = false,\n showScrollbar = false,\n size = 'medium',\n verticalAlign = 'bottom',\n } = props\n\n const popupRef = useRef(null)\n const triggerRef = useRef(null)\n\n /**\n * Keeps track of whether the popup was opened via keyboard.\n * This is used to determine whether to autofocus the first element in the popup.\n * If the popup was opened via mouse, we do not want to autofocus the first element.\n */\n const openedViaKeyboardRef = useRef(false)\n\n const [mounted, setMounted] = useState(false)\n const [active, setActiveInternal] = useState(initActive)\n const [isOnTop, setIsOnTop] = useState(verticalAlign === 'top')\n\n // Track when component is mounted to avoid SSR/client hydration mismatch\n useEffect(() => {\n setMounted(true)\n }, [])\n\n const setActive = useCallback(\n (isActive: boolean, viaKeyboard = false) => {\n if (isActive) {\n openedViaKeyboardRef.current = viaKeyboard\n onToggleOpen?.(true)\n } else {\n onToggleClose?.()\n }\n setActiveInternal(isActive)\n },\n [onToggleClose, onToggleOpen],\n )\n\n // /////////////////////////////////////\n // Position Calculation\n //\n // Calculates and applies popup position relative to trigger.\n // Always checks viewport bounds (for flipping), but only updates\n // styles if the calculated position differs from current position.\n // /////////////////////////////////////\n\n const updatePosition = useEffectEvent(() => {\n const trigger = triggerRef.current\n const popup = popupRef.current\n if (!trigger || !popup) {\n return\n }\n\n const triggerRect = trigger.getBoundingClientRect()\n const popupRect = popup.getBoundingClientRect()\n\n // Gap between the popup and the trigger/viewport edges (in pixels)\n const offset = 10\n\n // /////////////////////////////////////\n // Vertical Positioning\n // Calculates the `top` position in absolute page coordinates.\n // Uses `verticalAlign` prop as the preferred direction, but flips\n // to the opposite side if there's not enough viewport space.\n // /////////////////////////////////////\n\n let top: number\n let onTop = verticalAlign === 'top'\n\n if (verticalAlign === 'bottom') {\n top = triggerRect.bottom + window.scrollY + offset\n\n if (triggerRect.bottom + popupRect.height + offset > window.innerHeight) {\n top = triggerRect.top + window.scrollY - popupRect.height - offset\n onTop = true\n }\n } else {\n top = triggerRect.top + window.scrollY - popupRect.height - offset\n\n if (triggerRect.top - popupRect.height - offset < 0) {\n top = triggerRect.bottom + window.scrollY + offset\n onTop = false\n }\n }\n\n setIsOnTop(onTop)\n\n // /////////////////////////////////////\n // Horizontal Positioning\n // Calculates the `left` position based on `horizontalAlign` prop:\n // - 'left': aligns popup's left edge with trigger's left edge\n // - 'right': aligns popup's right edge with trigger's right edge\n // - 'center': centers popup horizontally relative to trigger\n // Then clamps to keep the popup within viewport bounds.\n // /////////////////////////////////////\n\n let left =\n horizontalAlign === 'right'\n ? triggerRect.right - popupRect.width\n : horizontalAlign === 'center'\n ? triggerRect.left + triggerRect.width / 2 - popupRect.width / 2\n : triggerRect.left\n\n left = Math.max(offset, Math.min(left, window.innerWidth - popupRect.width - offset))\n\n // /////////////////////////////////////\n // Caret Positioning\n // Positions the caret arrow to point at the trigger's horizontal center.\n // Clamps between 12px from edges to prevent caret from overflowing the popup.\n // /////////////////////////////////////\n\n const triggerCenter = triggerRect.left + triggerRect.width / 2\n const caretLeft = Math.max(12, Math.min(triggerCenter - left, popupRect.width - 12))\n\n // /////////////////////////////////////\n // Apply Styles (only if changed)\n // Compares calculated position with current styles to avoid unnecessary\n // DOM updates during scroll. This prevents visual lag by relying on the absolute\n // positioning where possible (popup slightly lags behind when scrolling really fast),\n // while still allowing position changes when needed (e.g., sticky parent, viewport flip).\n // Values are rounded to match browser's CSS precision and avoid false updates.\n // /////////////////////////////////////\n\n const newTop = `${Math.round(top)}px`\n const newLeft = `${Math.round(left + window.scrollX)}px`\n const newCaretLeft = `${Math.round(caretLeft)}px`\n\n if (popup.style.top !== newTop) {\n popup.style.top = newTop\n }\n if (popup.style.left !== newLeft) {\n popup.style.left = newLeft\n }\n if (popup.style.getPropertyValue('--caret-left') !== newCaretLeft) {\n popup.style.setProperty('--caret-left', newCaretLeft)\n }\n })\n\n // /////////////////////////////////////\n // Click Outside Handler\n // Closes popup when clicking outside both the popup and trigger.\n // /////////////////////////////////////\n\n const handleClickOutside = useEffectEvent((e: MouseEvent) => {\n const isOutsidePopup = !popupRef.current?.contains(e.target as Node)\n const isOutsideTrigger = !triggerRef.current?.contains(e.target as Node)\n\n if (isOutsidePopup && isOutsideTrigger) {\n setActive(false)\n }\n })\n\n // /////////////////////////////////////\n // Keyboard Navigation\n // Handles keyboard interactions when popup is open:\n // - Escape: closes popup and returns focus to trigger\n // - Tab/Shift+Tab: cycles through focusable items with wrapping\n // - ArrowUp/ArrowDown: same as Shift+Tab/Tab for menu-style navigation\n // Focus is managed manually to support elements the browser might skip.\n // /////////////////////////////////////\n\n const handleKeyDown = useEffectEvent((e: KeyboardEvent) => {\n const popup = popupRef.current\n if (!popup || !active) {\n return\n }\n\n if (e.key === 'Escape') {\n e.preventDefault()\n setActive(false)\n triggerRef.current?.querySelector('button, [tabindex=\"0\"]')?.focus()\n return\n }\n\n if (e.key === 'Tab' || e.key === 'ArrowDown' || e.key === 'ArrowUp') {\n const focusable = Array.from(popup.querySelectorAll(TABBABLE_SELECTOR))\n if (focusable.length === 0) {\n return\n }\n\n e.preventDefault()\n\n const currentIndex = focusable.findIndex((el) => el === document.activeElement)\n const goBackward = e.key === 'ArrowUp' || (e.key === 'Tab' && e.shiftKey)\n\n let nextIndex: number\n if (currentIndex === -1) {\n nextIndex = goBackward ? focusable.length - 1 : 0\n } else if (goBackward) {\n nextIndex = currentIndex === 0 ? focusable.length - 1 : currentIndex - 1\n } else {\n nextIndex = currentIndex === focusable.length - 1 ? 0 : currentIndex + 1\n }\n\n focusable[nextIndex].focus()\n }\n })\n\n // /////////////////////////////////////\n // Click Handler for Actionable Elements\n // Closes popup when buttons/links inside are clicked (includes Enter/Space activation).\n // /////////////////////////////////////\n\n const handleActionableClick = useEffectEvent((e: MouseEvent) => {\n const target = e.target as HTMLElement\n\n // Allow opting out with data-popup-prevent-close attribute on element or ancestor\n if (target.closest('[data-popup-prevent-close]')) {\n return\n }\n\n // Check if the clicked element or any ancestor is an actionable element\n const actionable = target.closest('button, a[href], [role=\"button\"], [role=\"menuitem\"]')\n if (actionable && popupRef.current?.contains(actionable)) {\n setActive(false)\n }\n })\n\n // /////////////////////////////////////\n // Effect: Setup/Teardown position and focus management\n // /////////////////////////////////////\n\n useEffect(() => {\n if (!active) {\n return\n }\n\n const popup = popupRef.current\n if (!popup) {\n return\n }\n\n // /////////////////////////////////////\n // Initial Position\n // Calculate and apply popup position immediately on open.\n // /////////////////////////////////////\n\n updatePosition()\n\n // /////////////////////////////////////\n // Focus Management\n // When opened via keyboard, autofocus the first focusable button.\n // When opened via mouse, skip autofocus to avoid unwanted highlights.\n // /////////////////////////////////////\n\n if (openedViaKeyboardRef.current) {\n // Use requestAnimationFrame to ensure DOM is ready.\n requestAnimationFrame(() => {\n const firstFocusable = popup.querySelector(TABBABLE_SELECTOR)\n firstFocusable?.focus()\n })\n }\n\n // /////////////////////////////////////\n // Event Listeners\n // - resize/scroll: recalculate position (only applies styles if changed)\n // - mousedown: detect clicks outside to close\n // - keydown: handle keyboard navigation\n // /////////////////////////////////////\n\n window.addEventListener('resize', updatePosition)\n window.addEventListener('scroll', updatePosition, { capture: true, passive: true })\n document.addEventListener('mousedown', handleClickOutside)\n document.addEventListener('keydown', handleKeyDown)\n popup.addEventListener('click', handleActionableClick)\n\n return () => {\n window.removeEventListener('resize', updatePosition)\n window.removeEventListener('scroll', updatePosition, { capture: true })\n document.removeEventListener('mousedown', handleClickOutside)\n document.removeEventListener('keydown', handleKeyDown)\n popup.removeEventListener('click', handleActionableClick)\n }\n }, [active])\n\n useEffect(() => {\n if (forceOpen !== undefined) {\n setActive(forceOpen)\n }\n }, [forceOpen, setActive])\n\n const Trigger = (\n \n )\n\n return (\n
\n
\n {showOnHover ? (\n setActive(true)}\n onMouseLeave={() => setActive(false)}\n role=\"button\"\n tabIndex={0}\n >\n {Trigger}\n
\n ) : (\n Trigger\n )}\n
\n\n {mounted\n ? // We need to make sure the popup is part of the DOM (although invisible), even if it's not active.\n // This ensures that components within the popup, like modals, do not unmount when the popup closes.\n // Otherwise, modals opened from the popup will close unexpectedly when clicking within the modal, since\n // that closes the popup due to the click outside handler.\n createPortal(\n \n \n {render?.({ close: () => setActive(false) })}\n {children}\n
\n {caret &&
}\n
,\n document.body,\n )\n : null}\n \n )\n}\n", "'use client'\n\n/**\n\nPolyfill taken and modified from https://github.com/bluesky-social/social-app/blob/ce0bf867ff3b50a495d8db242a7f55371bffeadc/src/lib/hooks/useNonReactiveCallback.ts\n\nCopyright 2023–2025 Bluesky PBC\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\nimport React, { useCallback, useInsertionEffect, useRef } from 'react'\n\n// This should be used sparingly. It erases reactivity, i.e. when the inputs\n// change, the function itself will remain the same. This means that if you\n// use this at a higher level of your tree, and then some state you read in it\n// changes, there is no mechanism for anything below in the tree to \"react\"\n// to this change (e.g. by knowing to call your function again).\n//\n// Also, you should avoid calling the returned function during rendering\n// since the values captured by it are going to lag behind.\n\nexport const useEffectEvent =\n 'useEffectEvent' in React && typeof React.useEffectEvent === 'function'\n ? // useEffectEvent is available in Next.js 16 / newer versions of React\n React.useEffectEvent\n : // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n (fn: T): T => {\n // useEffectEvent is not available in older versions of React, so we need to polyfill it\n const ref = useRef(fn)\n useInsertionEffect(() => {\n ref.current = fn\n }, [fn])\n return useCallback((...args: any) => {\n const latestFn = ref.current\n return latestFn(...args)\n }, []) as unknown as T\n }\n", "'use client'\nimport React from 'react'\n\nimport './index.scss'\n\nconst baseClass = 'popup-button'\n\nexport type PopupTriggerProps = {\n active: boolean\n button: React.ReactNode\n buttonType: 'custom' | 'default' | 'none'\n className?: string\n disabled?: boolean\n noBackground?: boolean\n setActive: (active: boolean, viaKeyboard?: boolean) => void\n size?: 'large' | 'medium' | 'small' | 'xsmall'\n}\n\nexport const PopupTrigger: React.FC = (props) => {\n const { active, button, buttonType, className, disabled, noBackground, setActive, size } = props\n\n const classes = [\n baseClass,\n className,\n `${baseClass}--${buttonType}`,\n !noBackground && `${baseClass}--background`,\n size && `${baseClass}--size-${size}`,\n disabled && `${baseClass}--disabled`,\n ]\n .filter(Boolean)\n .join(' ')\n\n const handleClick = () => {\n setActive(!active, false)\n }\n\n const handleKeyDown = (e: React.KeyboardEvent) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault()\n setActive(!active, true)\n }\n }\n\n if (buttonType === 'none') {\n return null\n }\n\n if (buttonType === 'custom') {\n return (\n \n {button}\n \n )\n }\n\n return (\n \n {button}\n \n )\n}\n", "'use client'\nimport React, { useEffect } from 'react'\n\nimport { useIntersect } from '../../hooks/useIntersect.js'\nimport './index.scss'\n\nexport type Props = {\n alignCaret?: 'center' | 'left' | 'right'\n boundingRef?: React.RefObject\n children: React.ReactNode\n className?: string\n delay?: number\n position?: 'bottom' | 'top'\n show?: boolean\n /**\n * If the tooltip position should not change depending on if the toolbar is outside the boundingRef. @default false\n */\n staticPositioning?: boolean\n}\n\nexport const Tooltip: React.FC = (props) => {\n const {\n alignCaret = 'center',\n boundingRef,\n children,\n className,\n delay = 350,\n position: positionFromProps,\n show: showFromProps = true,\n staticPositioning = false,\n } = props\n\n const [show, setShow] = React.useState(showFromProps)\n const [position, setPosition] = React.useState<'bottom' | 'top'>('top')\n\n const getTitleAttribute = (content) => (typeof content === 'string' ? content : '')\n\n const [ref, intersectionEntry] = useIntersect(\n {\n root: boundingRef?.current || null,\n rootMargin: '-145px 0px 0px 100px',\n threshold: 0,\n },\n staticPositioning,\n )\n\n useEffect(() => {\n let timerID: NodeJS.Timeout\n\n // do not use the delay on transition-out\n if (delay && showFromProps) {\n timerID = setTimeout(() => {\n setShow(showFromProps)\n }, delay)\n } else {\n setShow(showFromProps)\n }\n\n return () => {\n if (timerID) {\n clearTimeout(timerID)\n }\n }\n }, [showFromProps, delay])\n\n useEffect(() => {\n if (staticPositioning) {\n return\n }\n setPosition(intersectionEntry?.isIntersecting ? 'top' : 'bottom')\n }, [intersectionEntry, staticPositioning])\n\n // The first aside is always on top. The purpose of that is that it can reliably be used for the interaction observer (as it's not moving around), to calculate the position of the actual tooltip.\n return (\n \n {!staticPositioning && (\n \n
{children}
\n \n )}\n \n
{children}
\n \n
\n )\n}\n", "'use client'\n\nimport type React from 'react'\n\nimport { useEffect, useRef, useState } from 'react'\n\ntype Intersect = [\n setNode: React.Dispatch,\n entry: IntersectionObserverEntry,\n node: HTMLElement,\n]\n\nexport const useIntersect = (\n { root = null, rootMargin = '0px', threshold = 0 } = {},\n disable?: boolean,\n): Intersect => {\n const [entry, updateEntry] = useState()\n const [node, setNode] = useState(null)\n\n const observer = useRef(\n typeof window !== 'undefined' && 'IntersectionObserver' in window && !disable\n ? new window.IntersectionObserver(([ent]) => updateEntry(ent), {\n root,\n rootMargin,\n threshold,\n })\n : null,\n )\n\n useEffect(() => {\n if (disable) {\n return\n }\n const { current: currentObserver } = observer\n currentObserver.disconnect()\n\n if (node) {\n currentObserver.observe(node)\n }\n\n return () => currentObserver.disconnect()\n }, [node, disable])\n\n return [setNode, entry, node]\n}\n", "import type { ClientBlock, ClientField } from 'payload'\n\nimport { fieldAffectsData, fieldHasSubFields } from 'payload/shared'\n\nimport type { ClipboardPasteActionValidateArgs } from './types.js'\n\n/**\n * Validates whether clipboard data is compatible with the target schema.\n * For this to be true, the copied field and the target to be pasted must\n * be structurally equivalent (same schema)\n *\n * @returns True if the clipboard data is valid and can be pasted, false otherwise\n */\nexport function isClipboardDataValid({ data, path, ...args }: ClipboardPasteActionValidateArgs) {\n if (typeof data === 'undefined' || !path || !args.type) {\n return false\n }\n\n if (args.type === 'blocks') {\n return isClipboardBlocksValid({\n blocksFromClipboard: args.blocks,\n blocksFromConfig: args.schemaBlocks,\n })\n } else {\n return isClipboardFieldsValid({\n fieldsFromClipboard: args.fields,\n fieldsFromConfig: args.schemaFields,\n })\n }\n}\n\nfunction isClipboardFieldsValid({\n fieldsFromClipboard,\n fieldsFromConfig,\n}: {\n fieldsFromClipboard: ClientField[]\n fieldsFromConfig?: ClientField[]\n}): boolean {\n if (!fieldsFromConfig || fieldsFromClipboard.length !== fieldsFromConfig?.length) {\n return false\n }\n\n return fieldsFromClipboard.every((clipboardField, i) => {\n const configField = fieldsFromConfig[i]\n\n if (clipboardField.type !== configField.type) {\n return false\n }\n\n const affectsData = fieldAffectsData(clipboardField) && fieldAffectsData(configField)\n if (affectsData && clipboardField.name !== configField.name) {\n return false\n }\n\n const hasNestedFieldsConfig = fieldHasSubFields(configField)\n const hasNestedFieldsClipboard = fieldHasSubFields(clipboardField)\n if (hasNestedFieldsClipboard !== hasNestedFieldsConfig) {\n return false\n }\n\n if (hasNestedFieldsClipboard && hasNestedFieldsConfig) {\n return isClipboardFieldsValid({\n fieldsFromClipboard: clipboardField.fields,\n fieldsFromConfig: configField.fields,\n })\n }\n\n return true\n })\n}\n\nfunction isClipboardBlocksValid({\n blocksFromClipboard,\n blocksFromConfig,\n}: {\n blocksFromClipboard: ClientBlock[]\n blocksFromConfig?: ClientBlock[]\n}) {\n const configBlockMap = new Map(blocksFromConfig?.map((block) => [block.slug, block]))\n\n if (!configBlockMap.size) {\n return false\n }\n\n const checkedSlugs = new Set()\n\n for (const currBlock of blocksFromClipboard) {\n const currSlug = currBlock.slug\n\n if (!checkedSlugs.has(currSlug)) {\n const configBlock = configBlockMap.get(currSlug)\n if (!configBlock) {\n return false\n }\n\n if (\n !isClipboardFieldsValid({\n fieldsFromClipboard: currBlock.fields,\n fieldsFromConfig: configBlock.fields,\n })\n ) {\n return false\n }\n\n checkedSlugs.add(currSlug)\n }\n }\n return true\n}\n", "import type {\n ClipboardCopyActionArgs,\n ClipboardPasteActionArgs,\n ClipboardPasteActionValidateArgs,\n ClipboardPasteData,\n} from './types.js'\n\nimport { isClipboardDataValid } from './isClipboardDataValid.js'\n\nconst localStorageClipboardKey = '_payloadClipboard'\n\n/**\n * @note This function doesn't use the Clipboard API, but localStorage. See rationale in #11513\n */\nexport function clipboardCopy(args: ClipboardCopyActionArgs): string | true {\n const { getDataToCopy, t, ...rest } = args\n\n const dataToWrite = {\n data: getDataToCopy(),\n ...rest,\n }\n\n try {\n localStorage.setItem(localStorageClipboardKey, JSON.stringify(dataToWrite))\n return true\n } catch (_err) {\n return t('error:unableToCopy')\n }\n}\n\n/**\n * @note This function doesn't use the Clipboard API, but localStorage. See rationale in #11513\n */\nexport function clipboardPaste({\n onPaste,\n path: fieldPath,\n t,\n ...args\n}: ClipboardPasteActionArgs): string | true {\n let dataToPaste: ClipboardPasteData\n\n try {\n const jsonFromClipboard = localStorage.getItem(localStorageClipboardKey)\n\n if (!jsonFromClipboard) {\n return t('error:invalidClipboardData')\n }\n\n dataToPaste = JSON.parse(jsonFromClipboard)\n } catch (_err) {\n return t('error:invalidClipboardData')\n }\n\n const dataToValidate = {\n ...dataToPaste,\n ...args,\n fieldPath,\n } as ClipboardPasteActionValidateArgs\n\n if (!isClipboardDataValid(dataToValidate)) {\n return t('error:invalidClipboardData')\n }\n\n onPaste(dataToPaste)\n\n return true\n}\n", "'use client'\n\nimport type { FormStateWithoutComponents } from 'payload'\n\nimport { type FC, useCallback } from 'react'\nimport { toast } from 'sonner'\n\nimport type { ClipboardCopyData, OnPasteFn } from './types.js'\n\nimport { MoreIcon } from '../../icons/More/index.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { Popup, PopupList } from '../Popup/index.js'\nimport { ClipboardActionLabel } from './ClipboardActionLabel.js'\nimport { clipboardCopy, clipboardPaste } from './clipboardUtilities.js'\n\nconst baseClass = 'clipboard-action'\n\ntype Props = {\n allowCopy?: boolean\n allowPaste?: boolean\n className?: string\n copyClassName?: string\n disabled?: boolean\n getDataToCopy: () => FormStateWithoutComponents\n isRow?: boolean\n onPaste: OnPasteFn\n pasteClassName?: string\n} & ClipboardCopyData\n\n/**\n * Menu actions for copying and pasting fields. Currently, this is only used in Arrays and Blocks.\n * @note This component doesn't use the Clipboard API, but localStorage. See rationale in #11513\n */\nexport const ClipboardAction: FC = ({\n allowCopy,\n allowPaste,\n className,\n copyClassName,\n disabled,\n isRow,\n onPaste,\n pasteClassName,\n path,\n ...rest\n}) => {\n const { t } = useTranslation()\n\n const classes = [`${baseClass}__popup`, className].filter(Boolean).join(' ')\n\n const handleCopy = useCallback(() => {\n const clipboardResult = clipboardCopy({\n path,\n t,\n ...rest,\n })\n\n if (typeof clipboardResult === 'string') {\n toast.error(clipboardResult)\n } else {\n toast.success(t('general:copied'))\n }\n }, [t, rest, path])\n\n const handlePaste = useCallback(() => {\n const clipboardResult = clipboardPaste(\n rest.type === 'array'\n ? {\n onPaste,\n path,\n schemaFields: rest.fields,\n t,\n }\n : {\n onPaste,\n path,\n schemaBlocks: rest.blocks,\n t,\n },\n )\n\n if (typeof clipboardResult === 'string') {\n toast.error(clipboardResult)\n }\n }, [onPaste, rest, path, t])\n\n if (!allowPaste && !allowCopy) {\n return null\n }\n\n return (\n }\n className={classes}\n disabled={disabled}\n horizontalAlign=\"center\"\n render={({ close }) => (\n \n {\n void handleCopy()\n close()\n }}\n >\n \n \n {\n void handlePaste()\n close()\n }}\n >\n \n \n \n )}\n size=\"large\"\n verticalAlign=\"bottom\"\n />\n )\n}\n", "import React from 'react'\n\nimport './index.scss'\n\nexport const MoreIcon: React.FC<{ className?: string }> = ({ className }) => (\n \n \n \n \n \n)\n", "'use client'\n\nimport { Fragment } from 'react'\n\nimport { CopyIcon } from '../../icons/Copy/index.js'\nimport { EditIcon } from '../../icons/Edit/index.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\n\nexport const ClipboardActionLabel = ({\n isPaste,\n isRow,\n}: {\n isPaste?: boolean\n isRow?: boolean\n}) => {\n const { t } = useTranslation()\n\n let label = t('general:copyField')\n if (!isRow && isPaste) {\n label = t('general:pasteField')\n } else if (isRow && !isPaste) {\n label = t('general:copyRow')\n } else if (isRow && isPaste) {\n label = t('general:pasteRow')\n }\n\n return (\n \n {isPaste ? : } {label}\n \n )\n}\n", "import React from 'react'\n\nimport './index.scss'\n\nexport const CopyIcon: React.FC = () => (\n // \n // \n // \n // \n \n \n \n)\n", "import type { FieldState, FormState } from 'payload'\n\nimport type { ClipboardPasteData } from './types.js'\n\nexport function reduceFormStateByPath({\n formState,\n path,\n rowIndex,\n}: {\n formState: FormState\n path: string\n rowIndex?: number\n}) {\n const filteredState: Record = {}\n const prefix = typeof rowIndex !== 'number' ? path : `${path}.${rowIndex}`\n\n for (const key in formState) {\n if (!key.startsWith(prefix)) {\n continue\n }\n\n const { customComponents: _, validate: __, ...field } = formState[key]\n\n if (Array.isArray(field.rows)) {\n field.rows = field.rows.map((row) => {\n if (!row || typeof row !== 'object') {\n return row\n }\n const { customComponents: _, ...serializableRow } = row\n return serializableRow\n })\n }\n\n filteredState[key] = field\n }\n\n return filteredState\n}\n\nexport function mergeFormStateFromClipboard({\n dataFromClipboard: clipboardData,\n formState,\n path,\n rowIndex,\n}: {\n dataFromClipboard: ClipboardPasteData\n formState: FormState\n path: string\n rowIndex?: number\n}) {\n const {\n type: typeFromClipboard,\n data: dataFromClipboard,\n path: pathFromClipboard,\n rowIndex: rowIndexFromClipboard,\n } = clipboardData\n\n const copyFromField = typeof rowIndexFromClipboard !== 'number'\n const pasteIntoField = typeof rowIndex !== 'number'\n const fromRowToField = !copyFromField && pasteIntoField\n const isArray = typeFromClipboard === 'array'\n\n let pathToReplace: string\n if (copyFromField && pasteIntoField) {\n pathToReplace = pathFromClipboard\n } else if (copyFromField) {\n pathToReplace = `${pathFromClipboard}.${rowIndex}`\n } else {\n pathToReplace = `${pathFromClipboard}.${rowIndexFromClipboard}`\n }\n\n let targetSegment: string\n if (!pasteIntoField) {\n targetSegment = `${path}.${rowIndex}`\n } else if (fromRowToField) {\n targetSegment = `${path}.0`\n } else {\n targetSegment = path\n }\n\n if (fromRowToField) {\n const lastRenderedPath = `${path}.0`\n const rowIDFromClipboard = dataFromClipboard[`${pathToReplace}.id`].value as string\n const hasRows = formState[path].rows?.length\n\n formState[path].rows = [\n {\n ...(hasRows && isArray ? formState[path].rows[0] : {}),\n id: rowIDFromClipboard,\n isLoading: false,\n lastRenderedPath,\n },\n ]\n formState[path].value = 1\n formState[path].initialValue = 1\n formState[path].disableFormData = true\n\n for (const fieldPath in formState) {\n if (\n fieldPath !== path &&\n !fieldPath.startsWith(lastRenderedPath) &&\n fieldPath.startsWith(path)\n ) {\n delete formState[fieldPath]\n }\n }\n }\n\n for (const clipboardPath in dataFromClipboard) {\n // Pasting a row id, skip overwriting\n if (\n (!pasteIntoField && clipboardPath.endsWith('.id')) ||\n !clipboardPath.startsWith(pathToReplace)\n ) {\n continue\n }\n\n const newPath = clipboardPath.replace(pathToReplace, targetSegment)\n\n const customComponents = isArray ? formState[newPath]?.customComponents : undefined\n const validate = isArray ? formState[newPath]?.validate : undefined\n\n formState[newPath] = {\n customComponents,\n validate,\n ...dataFromClipboard[clipboardPath],\n }\n }\n\n return formState\n}\n", "'use client'\nimport type { UseDraggableArguments } from '@dnd-kit/core'\n\nimport React, { Fragment } from 'react'\n\nimport type { ChildFunction } from './types.js'\n\nimport { useDraggableSortable } from '../useDraggableSortable/index.js'\n\nexport const DraggableSortableItem: React.FC<\n {\n children: ChildFunction\n } & UseDraggableArguments\n> = (props) => {\n const { id, children, disabled } = props\n\n const { attributes, isDragging, listeners, setNodeRef, transform, transition } =\n useDraggableSortable({\n id,\n disabled,\n })\n\n return (\n \n {children({\n attributes: {\n ...attributes,\n style: {\n cursor: isDragging ? 'grabbing' : 'grab',\n },\n },\n isDragging,\n listeners,\n setNodeRef,\n transform,\n transition,\n })}\n \n )\n}\n", "'use client'\nimport type { UseDraggableArguments } from '@dnd-kit/core'\n\nimport { useSortable } from '@dnd-kit/sortable'\n\nimport type { UseDraggableSortableReturn } from './types.js'\n\nexport const useDraggableSortable = (props: UseDraggableArguments): UseDraggableSortableReturn => {\n const { id, disabled } = props\n\n const { attributes, isDragging, listeners, setNodeRef, transform, transition } = useSortable({\n id,\n disabled,\n transition: {\n duration: 250,\n easing: 'cubic-bezier(0, 0.2, 0.2, 1)',\n },\n })\n\n return {\n attributes: {\n ...attributes,\n style: {\n cursor: isDragging ? 'grabbing' : 'grab',\n transition,\n },\n },\n isDragging,\n listeners,\n setNodeRef,\n transform: transform && `translate3d(${transform.x}px, ${transform.y}px, 0)`, // translate3d is faster than translate in most browsers\n transition,\n }\n}\n", "import {useMemo} from 'react';\n\nexport function useCombinedRefs(\n ...refs: ((node: T) => void)[]\n): (node: T) => void {\n return useMemo(\n () => (node: T) => {\n refs.forEach((ref) => ref(node));\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n refs\n );\n}\n", "// https://github.com/facebook/react/blob/master/packages/shared/ExecutionEnvironment.js\nexport const canUseDOM =\n typeof window !== 'undefined' &&\n typeof window.document !== 'undefined' &&\n typeof window.document.createElement !== 'undefined';\n", "export function isWindow(element: Object): element is typeof window {\n const elementString = Object.prototype.toString.call(element);\n return (\n elementString === '[object Window]' ||\n // In Electron context the Window object serializes to [object global]\n elementString === '[object global]'\n );\n}\n", "export function isNode(node: Object): node is Node {\n return 'nodeType' in node;\n}\n", "import {isWindow} from '../type-guards/isWindow';\nimport {isNode} from '../type-guards/isNode';\n\nexport function getWindow(target: Event['target']): typeof window {\n if (!target) {\n return window;\n }\n\n if (isWindow(target)) {\n return target;\n }\n\n if (!isNode(target)) {\n return window;\n }\n\n return target.ownerDocument?.defaultView ?? window;\n}\n", "import {getWindow} from '../execution-context/getWindow';\n\nexport function isDocument(node: Node): node is Document {\n const {Document} = getWindow(node);\n\n return node instanceof Document;\n}\n", "import {getWindow} from '../execution-context/getWindow';\n\nimport {isWindow} from './isWindow';\n\nexport function isHTMLElement(node: Node | Window): node is HTMLElement {\n if (isWindow(node)) {\n return false;\n }\n\n return node instanceof getWindow(node).HTMLElement;\n}\n", "import {getWindow} from '../execution-context/getWindow';\n\nexport function isSVGElement(node: Node): node is SVGElement {\n return node instanceof getWindow(node).SVGElement;\n}\n", "import {\n isWindow,\n isHTMLElement,\n isDocument,\n isNode,\n isSVGElement,\n} from '../type-guards';\n\nexport function getOwnerDocument(target: Event['target']): Document {\n if (!target) {\n return document;\n }\n\n if (isWindow(target)) {\n return target.document;\n }\n\n if (!isNode(target)) {\n return document;\n }\n\n if (isDocument(target)) {\n return target;\n }\n\n if (isHTMLElement(target) || isSVGElement(target)) {\n return target.ownerDocument;\n }\n\n return document;\n}\n", "import {useEffect, useLayoutEffect} from 'react';\n\nimport {canUseDOM} from '../execution-context';\n\n/**\n * A hook that resolves to useEffect on the server and useLayoutEffect on the client\n * @param callback {function} Callback function that is invoked when the dependencies of the hook change\n */\nexport const useIsomorphicLayoutEffect = canUseDOM\n ? useLayoutEffect\n : useEffect;\n", "import {useCallback, useRef} from 'react';\n\nimport {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';\n\nexport function useEvent(handler: T | undefined) {\n const handlerRef = useRef(handler);\n\n useIsomorphicLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n return useCallback(function (...args: any) {\n return handlerRef.current?.(...args);\n }, []);\n}\n", "import {useCallback, useRef} from 'react';\n\nexport function useInterval() {\n const intervalRef = useRef(null);\n\n const set = useCallback((listener: Function, duration: number) => {\n intervalRef.current = setInterval(listener, duration);\n }, []);\n\n const clear = useCallback(() => {\n if (intervalRef.current !== null) {\n clearInterval(intervalRef.current);\n intervalRef.current = null;\n }\n }, []);\n\n return [set, clear] as const;\n}\n", "import {useRef} from 'react';\nimport type {DependencyList} from 'react';\n\nimport {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';\n\nexport function useLatestValue(\n value: T,\n dependencies: DependencyList = [value]\n) {\n const valueRef = useRef(value);\n\n useIsomorphicLayoutEffect(() => {\n if (valueRef.current !== value) {\n valueRef.current = value;\n }\n }, dependencies);\n\n return valueRef;\n}\n", "import {useMemo, useRef} from 'react';\n\nexport function useLazyMemo(\n callback: (prevValue: T | undefined) => T,\n dependencies: any[]\n) {\n const valueRef = useRef();\n\n return useMemo(\n () => {\n const newValue = callback(valueRef.current);\n valueRef.current = newValue;\n\n return newValue;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [...dependencies]\n );\n}\n", "import {useRef, useCallback} from 'react';\n\nimport {useEvent} from './useEvent';\n\nexport function useNodeRef(\n onChange?: (\n newElement: HTMLElement | null,\n previousElement: HTMLElement | null\n ) => void\n) {\n const onChangeHandler = useEvent(onChange);\n const node = useRef(null);\n const setNodeRef = useCallback(\n (element: HTMLElement | null) => {\n if (element !== node.current) {\n onChangeHandler?.(element, node.current);\n }\n\n node.current = element;\n },\n //eslint-disable-next-line\n []\n );\n\n return [node, setNodeRef] as const;\n}\n", "import {useRef, useEffect} from 'react';\n\nexport function usePrevious(value: T) {\n const ref = useRef();\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref.current;\n}\n", "import {useMemo} from 'react';\n\nlet ids: Record = {};\n\nexport function useUniqueId(prefix: string, value?: string) {\n return useMemo(() => {\n if (value) {\n return value;\n }\n\n const id = ids[prefix] == null ? 0 : ids[prefix] + 1;\n ids[prefix] = id;\n\n return `${prefix}-${id}`;\n }, [prefix, value]);\n}\n", "function createAdjustmentFn(modifier: number) {\n return , U extends string>(\n object: T,\n ...adjustments: Partial[]\n ): T => {\n return adjustments.reduce(\n (accumulator, adjustment) => {\n const entries = Object.entries(adjustment) as [U, number][];\n\n for (const [key, valueAdjustment] of entries) {\n const value = accumulator[key];\n\n if (value != null) {\n accumulator[key] = (value + modifier * valueAdjustment) as T[U];\n }\n }\n\n return accumulator;\n },\n {\n ...object,\n }\n );\n };\n}\n\nexport const add = createAdjustmentFn(1);\nexport const subtract = createAdjustmentFn(-1);\n", "export function hasViewportRelativeCoordinates(\n event: Event\n): event is Event & Pick {\n return 'clientX' in event && 'clientY' in event;\n}\n", "import {getWindow} from '../execution-context';\n\nexport function isKeyboardEvent(\n event: Event | undefined | null\n): event is KeyboardEvent {\n if (!event) {\n return false;\n }\n\n const {KeyboardEvent} = getWindow(event.target);\n\n return KeyboardEvent && event instanceof KeyboardEvent;\n}\n", "import {getWindow} from '../execution-context';\n\nexport function isTouchEvent(\n event: Event | undefined | null\n): event is TouchEvent {\n if (!event) {\n return false;\n }\n\n const {TouchEvent} = getWindow(event.target);\n\n return TouchEvent && event instanceof TouchEvent;\n}\n", "import type {Coordinates} from './types';\nimport {isTouchEvent, hasViewportRelativeCoordinates} from '../event';\n\n/**\n * Returns the normalized x and y coordinates for mouse and touch events.\n */\nexport function getEventCoordinates(event: Event): Coordinates | null {\n if (isTouchEvent(event)) {\n if (event.touches && event.touches.length) {\n const {clientX: x, clientY: y} = event.touches[0];\n\n return {\n x,\n y,\n };\n } else if (event.changedTouches && event.changedTouches.length) {\n const {clientX: x, clientY: y} = event.changedTouches[0];\n\n return {\n x,\n y,\n };\n }\n }\n\n if (hasViewportRelativeCoordinates(event)) {\n return {\n x: event.clientX,\n y: event.clientY,\n };\n }\n\n return null;\n}\n", "export type Transform = {\n x: number;\n y: number;\n scaleX: number;\n scaleY: number;\n};\n\nexport interface Transition {\n property: string;\n easing: string;\n duration: number;\n}\n\nexport const CSS = Object.freeze({\n Translate: {\n toString(transform: Transform | null) {\n if (!transform) {\n return;\n }\n\n const {x, y} = transform;\n\n return `translate3d(${x ? Math.round(x) : 0}px, ${\n y ? Math.round(y) : 0\n }px, 0)`;\n },\n },\n Scale: {\n toString(transform: Transform | null) {\n if (!transform) {\n return;\n }\n\n const {scaleX, scaleY} = transform;\n\n return `scaleX(${scaleX}) scaleY(${scaleY})`;\n },\n },\n Transform: {\n toString(transform: Transform | null) {\n if (!transform) {\n return;\n }\n\n return [\n CSS.Translate.toString(transform),\n CSS.Scale.toString(transform),\n ].join(' ');\n },\n },\n Transition: {\n toString({property, duration, easing}: Transition) {\n return `${property} ${duration}ms ${easing}`;\n },\n },\n});\n", "const SELECTOR =\n 'a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]';\n\nexport function findFirstFocusableNode(\n element: HTMLElement\n): HTMLElement | null {\n if (element.matches(SELECTOR)) {\n return element;\n }\n\n return element.querySelector(SELECTOR);\n}\n", "/**\n * Move an array item to a different position. Returns a new array with the item moved to the new position.\n */\nexport function arrayMove(array: T[], from: number, to: number): T[] {\n const newArray = array.slice();\n newArray.splice(\n to < 0 ? newArray.length + to : to,\n 0,\n newArray.splice(from, 1)[0]\n );\n\n return newArray;\n}\n", "/**\n * Swap an array item to a different position. Returns a new array with the item swapped to the new position.\n */\nexport function arraySwap(array: T[], from: number, to: number): T[] {\n const newArray = array.slice();\n\n newArray[from] = array[to];\n newArray[to] = array[from];\n\n return newArray;\n}\n", "import type {\n ClientRect,\n UniqueIdentifier,\n UseDndContextReturnValue,\n} from '@dnd-kit/core';\n\nexport function getSortedRects(\n items: UniqueIdentifier[],\n rects: UseDndContextReturnValue['droppableRects']\n) {\n return items.reduce((accumulator, id, index) => {\n const rect = rects.get(id);\n\n if (rect) {\n accumulator[index] = rect;\n }\n\n return accumulator;\n }, Array(items.length));\n}\n", "export function isValidIndex(index: number | null): index is number {\n return index !== null && index >= 0;\n}\n", "import type {UniqueIdentifier} from '@dnd-kit/core';\n\nexport function itemsEqual(a: UniqueIdentifier[], b: UniqueIdentifier[]) {\n if (a === b) {\n return true;\n }\n\n if (a.length !== b.length) {\n return false;\n }\n\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n\n return true;\n}\n", "import type {Disabled} from '../types';\n\nexport function normalizeDisabled(disabled: boolean | Disabled): Disabled {\n if (typeof disabled === 'boolean') {\n return {\n draggable: disabled,\n droppable: disabled,\n };\n }\n\n return disabled;\n}\n", "import type {ClientRect} from '@dnd-kit/core';\nimport type {SortingStrategy} from '../types';\n\n// To-do: We should be calculating scale transformation\nconst defaultScale = {\n scaleX: 1,\n scaleY: 1,\n};\n\nexport const horizontalListSortingStrategy: SortingStrategy = ({\n rects,\n activeNodeRect: fallbackActiveRect,\n activeIndex,\n overIndex,\n index,\n}) => {\n const activeNodeRect = rects[activeIndex] ?? fallbackActiveRect;\n\n if (!activeNodeRect) {\n return null;\n }\n\n const itemGap = getItemGap(rects, index, activeIndex);\n\n if (index === activeIndex) {\n const newIndexRect = rects[overIndex];\n\n if (!newIndexRect) {\n return null;\n }\n\n return {\n x:\n activeIndex < overIndex\n ? newIndexRect.left +\n newIndexRect.width -\n (activeNodeRect.left + activeNodeRect.width)\n : newIndexRect.left - activeNodeRect.left,\n y: 0,\n ...defaultScale,\n };\n }\n\n if (index > activeIndex && index <= overIndex) {\n return {\n x: -activeNodeRect.width - itemGap,\n y: 0,\n ...defaultScale,\n };\n }\n\n if (index < activeIndex && index >= overIndex) {\n return {\n x: activeNodeRect.width + itemGap,\n y: 0,\n ...defaultScale,\n };\n }\n\n return {\n x: 0,\n y: 0,\n ...defaultScale,\n };\n};\n\nfunction getItemGap(rects: ClientRect[], index: number, activeIndex: number) {\n const currentRect: ClientRect | undefined = rects[index];\n const previousRect: ClientRect | undefined = rects[index - 1];\n const nextRect: ClientRect | undefined = rects[index + 1];\n\n if (!currentRect || (!previousRect && !nextRect)) {\n return 0;\n }\n\n if (activeIndex < index) {\n return previousRect\n ? currentRect.left - (previousRect.left + previousRect.width)\n : nextRect.left - (currentRect.left + currentRect.width);\n }\n\n return nextRect\n ? nextRect.left - (currentRect.left + currentRect.width)\n : currentRect.left - (previousRect.left + previousRect.width);\n}\n", "import {arrayMove} from '../utilities';\nimport type {SortingStrategy} from '../types';\n\nexport const rectSortingStrategy: SortingStrategy = ({\n rects,\n activeIndex,\n overIndex,\n index,\n}) => {\n const newRects = arrayMove(rects, overIndex, activeIndex);\n\n const oldRect = rects[index];\n const newRect = newRects[index];\n\n if (!newRect || !oldRect) {\n return null;\n }\n\n return {\n x: newRect.left - oldRect.left,\n y: newRect.top - oldRect.top,\n scaleX: newRect.width / oldRect.width,\n scaleY: newRect.height / oldRect.height,\n };\n};\n", "import type {SortingStrategy} from '../types';\n\nexport const rectSwappingStrategy: SortingStrategy = ({\n activeIndex,\n index,\n rects,\n overIndex,\n}) => {\n let oldRect;\n let newRect;\n\n if (index === activeIndex) {\n oldRect = rects[index];\n newRect = rects[overIndex];\n }\n\n if (index === overIndex) {\n oldRect = rects[index];\n newRect = rects[activeIndex];\n }\n\n if (!newRect || !oldRect) {\n return null;\n }\n\n return {\n x: newRect.left - oldRect.left,\n y: newRect.top - oldRect.top,\n scaleX: newRect.width / oldRect.width,\n scaleY: newRect.height / oldRect.height,\n };\n};\n", "import type {ClientRect} from '@dnd-kit/core';\nimport type {SortingStrategy} from '../types';\n\n// To-do: We should be calculating scale transformation\nconst defaultScale = {\n scaleX: 1,\n scaleY: 1,\n};\n\nexport const verticalListSortingStrategy: SortingStrategy = ({\n activeIndex,\n activeNodeRect: fallbackActiveRect,\n index,\n rects,\n overIndex,\n}) => {\n const activeNodeRect = rects[activeIndex] ?? fallbackActiveRect;\n\n if (!activeNodeRect) {\n return null;\n }\n\n if (index === activeIndex) {\n const overIndexRect = rects[overIndex];\n\n if (!overIndexRect) {\n return null;\n }\n\n return {\n x: 0,\n y:\n activeIndex < overIndex\n ? overIndexRect.top +\n overIndexRect.height -\n (activeNodeRect.top + activeNodeRect.height)\n : overIndexRect.top - activeNodeRect.top,\n ...defaultScale,\n };\n }\n\n const itemGap = getItemGap(rects, index, activeIndex);\n\n if (index > activeIndex && index <= overIndex) {\n return {\n x: 0,\n y: -activeNodeRect.height - itemGap,\n ...defaultScale,\n };\n }\n\n if (index < activeIndex && index >= overIndex) {\n return {\n x: 0,\n y: activeNodeRect.height + itemGap,\n ...defaultScale,\n };\n }\n\n return {\n x: 0,\n y: 0,\n ...defaultScale,\n };\n};\n\nfunction getItemGap(\n clientRects: ClientRect[],\n index: number,\n activeIndex: number\n) {\n const currentRect: ClientRect | undefined = clientRects[index];\n const previousRect: ClientRect | undefined = clientRects[index - 1];\n const nextRect: ClientRect | undefined = clientRects[index + 1];\n\n if (!currentRect) {\n return 0;\n }\n\n if (activeIndex < index) {\n return previousRect\n ? currentRect.top - (previousRect.top + previousRect.height)\n : nextRect\n ? nextRect.top - (currentRect.top + currentRect.height)\n : 0;\n }\n\n return nextRect\n ? nextRect.top - (currentRect.top + currentRect.height)\n : previousRect\n ? currentRect.top - (previousRect.top + previousRect.height)\n : 0;\n}\n", "import React, {useEffect, useMemo, useRef} from 'react';\nimport {useDndContext, ClientRect, UniqueIdentifier} from '@dnd-kit/core';\nimport {useIsomorphicLayoutEffect, useUniqueId} from '@dnd-kit/utilities';\n\nimport type {Disabled, SortingStrategy} from '../types';\nimport {getSortedRects, itemsEqual, normalizeDisabled} from '../utilities';\nimport {rectSortingStrategy} from '../strategies';\n\nexport interface Props {\n children: React.ReactNode;\n items: (UniqueIdentifier | {id: UniqueIdentifier})[];\n strategy?: SortingStrategy;\n id?: string;\n disabled?: boolean | Disabled;\n}\n\nconst ID_PREFIX = 'Sortable';\n\ninterface ContextDescriptor {\n activeIndex: number;\n containerId: string;\n disabled: Disabled;\n disableTransforms: boolean;\n items: UniqueIdentifier[];\n overIndex: number;\n useDragOverlay: boolean;\n sortedRects: ClientRect[];\n strategy: SortingStrategy;\n}\n\nexport const Context = React.createContext({\n activeIndex: -1,\n containerId: ID_PREFIX,\n disableTransforms: false,\n items: [],\n overIndex: -1,\n useDragOverlay: false,\n sortedRects: [],\n strategy: rectSortingStrategy,\n disabled: {\n draggable: false,\n droppable: false,\n },\n});\n\nexport function SortableContext({\n children,\n id,\n items: userDefinedItems,\n strategy = rectSortingStrategy,\n disabled: disabledProp = false,\n}: Props) {\n const {\n active,\n dragOverlay,\n droppableRects,\n over,\n measureDroppableContainers,\n } = useDndContext();\n const containerId = useUniqueId(ID_PREFIX, id);\n const useDragOverlay = Boolean(dragOverlay.rect !== null);\n const items = useMemo(\n () =>\n userDefinedItems.map((item) =>\n typeof item === 'object' && 'id' in item ? item.id : item\n ),\n [userDefinedItems]\n );\n const isDragging = active != null;\n const activeIndex = active ? items.indexOf(active.id) : -1;\n const overIndex = over ? items.indexOf(over.id) : -1;\n const previousItemsRef = useRef(items);\n const itemsHaveChanged = !itemsEqual(items, previousItemsRef.current);\n const disableTransforms =\n (overIndex !== -1 && activeIndex === -1) || itemsHaveChanged;\n const disabled = normalizeDisabled(disabledProp);\n\n useIsomorphicLayoutEffect(() => {\n if (itemsHaveChanged && isDragging) {\n measureDroppableContainers(items);\n }\n }, [itemsHaveChanged, items, isDragging, measureDroppableContainers]);\n\n useEffect(() => {\n previousItemsRef.current = items;\n }, [items]);\n\n const contextValue = useMemo(\n (): ContextDescriptor => ({\n activeIndex,\n containerId,\n disabled,\n disableTransforms,\n items,\n overIndex,\n useDragOverlay,\n sortedRects: getSortedRects(items, droppableRects),\n strategy,\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n activeIndex,\n containerId,\n disabled.draggable,\n disabled.droppable,\n disableTransforms,\n items,\n overIndex,\n droppableRects,\n useDragOverlay,\n strategy,\n ]\n );\n\n return {children};\n}\n", "import {CSS} from '@dnd-kit/utilities';\n\nimport {arrayMove} from '../utilities';\n\nimport type {\n AnimateLayoutChanges,\n NewIndexGetter,\n SortableTransition,\n} from './types';\n\nexport const defaultNewIndexGetter: NewIndexGetter = ({\n id,\n items,\n activeIndex,\n overIndex,\n}) => arrayMove(items, activeIndex, overIndex).indexOf(id);\n\nexport const defaultAnimateLayoutChanges: AnimateLayoutChanges = ({\n containerId,\n isSorting,\n wasDragging,\n index,\n items,\n newIndex,\n previousItems,\n previousContainerId,\n transition,\n}) => {\n if (!transition || !wasDragging) {\n return false;\n }\n\n if (previousItems !== items && index === newIndex) {\n return false;\n }\n\n if (isSorting) {\n return true;\n }\n\n return newIndex !== index && containerId === previousContainerId;\n};\n\nexport const defaultTransition: SortableTransition = {\n duration: 200,\n easing: 'ease',\n};\n\nexport const transitionProperty = 'transform';\n\nexport const disabledTransition = CSS.Transition.toString({\n property: transitionProperty,\n duration: 0,\n easing: 'linear',\n});\n\nexport const defaultAttributes = {\n roleDescription: 'sortable',\n};\n", "import {useEffect, useRef, useState} from 'react';\nimport {getClientRect, ClientRect} from '@dnd-kit/core';\nimport {Transform, useIsomorphicLayoutEffect} from '@dnd-kit/utilities';\n\ninterface Arguments {\n rect: React.MutableRefObject;\n disabled: boolean;\n index: number;\n node: React.MutableRefObject;\n}\n\n/*\n * When the index of an item changes while sorting,\n * we need to temporarily disable the transforms\n */\nexport function useDerivedTransform({disabled, index, node, rect}: Arguments) {\n const [derivedTransform, setDerivedtransform] = useState(\n null\n );\n const previousIndex = useRef(index);\n\n useIsomorphicLayoutEffect(() => {\n if (!disabled && index !== previousIndex.current && node.current) {\n const initial = rect.current;\n\n if (initial) {\n const current = getClientRect(node.current, {\n ignoreTransform: true,\n });\n\n const delta = {\n x: initial.left - current.left,\n y: initial.top - current.top,\n scaleX: initial.width / current.width,\n scaleY: initial.height / current.height,\n };\n\n if (delta.x || delta.y) {\n setDerivedtransform(delta);\n }\n }\n }\n\n if (index !== previousIndex.current) {\n previousIndex.current = index;\n }\n }, [disabled, index, node, rect]);\n\n useEffect(() => {\n if (derivedTransform) {\n setDerivedtransform(null);\n }\n }, [derivedTransform]);\n\n return derivedTransform;\n}\n", "import {useContext, useEffect, useMemo, useRef} from 'react';\nimport {\n useDraggable,\n useDroppable,\n UseDraggableArguments,\n UseDroppableArguments,\n} from '@dnd-kit/core';\nimport type {Data} from '@dnd-kit/core';\nimport {CSS, isKeyboardEvent, useCombinedRefs} from '@dnd-kit/utilities';\n\nimport {Context} from '../components';\nimport type {Disabled, SortableData, SortingStrategy} from '../types';\nimport {isValidIndex} from '../utilities';\nimport {\n defaultAnimateLayoutChanges,\n defaultAttributes,\n defaultNewIndexGetter,\n defaultTransition,\n disabledTransition,\n transitionProperty,\n} from './defaults';\nimport type {\n AnimateLayoutChanges,\n NewIndexGetter,\n SortableTransition,\n} from './types';\nimport {useDerivedTransform} from './utilities';\n\nexport interface Arguments\n extends Omit,\n Pick {\n animateLayoutChanges?: AnimateLayoutChanges;\n disabled?: boolean | Disabled;\n getNewIndex?: NewIndexGetter;\n strategy?: SortingStrategy;\n transition?: SortableTransition | null;\n}\n\nexport function useSortable({\n animateLayoutChanges = defaultAnimateLayoutChanges,\n attributes: userDefinedAttributes,\n disabled: localDisabled,\n data: customData,\n getNewIndex = defaultNewIndexGetter,\n id,\n strategy: localStrategy,\n resizeObserverConfig,\n transition = defaultTransition,\n}: Arguments) {\n const {\n items,\n containerId,\n activeIndex,\n disabled: globalDisabled,\n disableTransforms,\n sortedRects,\n overIndex,\n useDragOverlay,\n strategy: globalStrategy,\n } = useContext(Context);\n const disabled: Disabled = normalizeLocalDisabled(\n localDisabled,\n globalDisabled\n );\n const index = items.indexOf(id);\n const data = useMemo(\n () => ({sortable: {containerId, index, items}, ...customData}),\n [containerId, customData, index, items]\n );\n const itemsAfterCurrentSortable = useMemo(\n () => items.slice(items.indexOf(id)),\n [items, id]\n );\n const {\n rect,\n node,\n isOver,\n setNodeRef: setDroppableNodeRef,\n } = useDroppable({\n id,\n data,\n disabled: disabled.droppable,\n resizeObserverConfig: {\n updateMeasurementsFor: itemsAfterCurrentSortable,\n ...resizeObserverConfig,\n },\n });\n const {\n active,\n activatorEvent,\n activeNodeRect,\n attributes,\n setNodeRef: setDraggableNodeRef,\n listeners,\n isDragging,\n over,\n setActivatorNodeRef,\n transform,\n } = useDraggable({\n id,\n data,\n attributes: {\n ...defaultAttributes,\n ...userDefinedAttributes,\n },\n disabled: disabled.draggable,\n });\n const setNodeRef = useCombinedRefs(setDroppableNodeRef, setDraggableNodeRef);\n const isSorting = Boolean(active);\n const displaceItem =\n isSorting &&\n !disableTransforms &&\n isValidIndex(activeIndex) &&\n isValidIndex(overIndex);\n const shouldDisplaceDragSource = !useDragOverlay && isDragging;\n const dragSourceDisplacement =\n shouldDisplaceDragSource && displaceItem ? transform : null;\n const strategy = localStrategy ?? globalStrategy;\n const finalTransform = displaceItem\n ? dragSourceDisplacement ??\n strategy({\n rects: sortedRects,\n activeNodeRect,\n activeIndex,\n overIndex,\n index,\n })\n : null;\n const newIndex =\n isValidIndex(activeIndex) && isValidIndex(overIndex)\n ? getNewIndex({id, items, activeIndex, overIndex})\n : index;\n const activeId = active?.id;\n const previous = useRef({\n activeId,\n items,\n newIndex,\n containerId,\n });\n const itemsHaveChanged = items !== previous.current.items;\n const shouldAnimateLayoutChanges = animateLayoutChanges({\n active,\n containerId,\n isDragging,\n isSorting,\n id,\n index,\n items,\n newIndex: previous.current.newIndex,\n previousItems: previous.current.items,\n previousContainerId: previous.current.containerId,\n transition,\n wasDragging: previous.current.activeId != null,\n });\n\n const derivedTransform = useDerivedTransform({\n disabled: !shouldAnimateLayoutChanges,\n index,\n node,\n rect,\n });\n\n useEffect(() => {\n if (isSorting && previous.current.newIndex !== newIndex) {\n previous.current.newIndex = newIndex;\n }\n\n if (containerId !== previous.current.containerId) {\n previous.current.containerId = containerId;\n }\n\n if (items !== previous.current.items) {\n previous.current.items = items;\n }\n }, [isSorting, newIndex, containerId, items]);\n\n useEffect(() => {\n if (activeId === previous.current.activeId) {\n return;\n }\n\n if (activeId != null && previous.current.activeId == null) {\n previous.current.activeId = activeId;\n return;\n }\n\n const timeoutId = setTimeout(() => {\n previous.current.activeId = activeId;\n }, 50);\n\n return () => clearTimeout(timeoutId);\n }, [activeId]);\n\n return {\n active,\n activeIndex,\n attributes,\n data,\n rect,\n index,\n newIndex,\n items,\n isOver,\n isSorting,\n isDragging,\n listeners,\n node,\n overIndex,\n over,\n setNodeRef,\n setActivatorNodeRef,\n setDroppableNodeRef,\n setDraggableNodeRef,\n transform: derivedTransform ?? finalTransform,\n transition: getTransition(),\n };\n\n function getTransition() {\n if (\n // Temporarily disable transitions for a single frame to set up derived transforms\n derivedTransform ||\n // Or to prevent items jumping to back to their \"new\" position when items change\n (itemsHaveChanged && previous.current.newIndex === index)\n ) {\n return disabledTransition;\n }\n\n if (\n (shouldDisplaceDragSource && !isKeyboardEvent(activatorEvent)) ||\n !transition\n ) {\n return undefined;\n }\n\n if (isSorting || shouldAnimateLayoutChanges) {\n return CSS.Transition.toString({\n ...transition,\n property: transitionProperty,\n });\n }\n\n return undefined;\n }\n}\n\nfunction normalizeLocalDisabled(\n localDisabled: Arguments['disabled'],\n globalDisabled: Disabled\n) {\n if (typeof localDisabled === 'boolean') {\n return {\n draggable: localDisabled,\n // Backwards compatibility\n droppable: false,\n };\n }\n\n return {\n draggable: localDisabled?.draggable ?? globalDisabled.draggable,\n droppable: localDisabled?.droppable ?? globalDisabled.droppable,\n };\n}\n", "import type {\n Active,\n Data,\n DroppableContainer,\n DraggableNode,\n Over,\n} from '@dnd-kit/core';\n\nimport type {SortableData} from './data';\n\nexport function hasSortableData<\n T extends Active | Over | DraggableNode | DroppableContainer\n>(\n entry: T | null | undefined\n): entry is T & {data: {current: Data}} {\n if (!entry) {\n return false;\n }\n\n const data = entry.data.current;\n\n if (\n data &&\n 'sortable' in data &&\n typeof data.sortable === 'object' &&\n 'containerId' in data.sortable &&\n 'items' in data.sortable &&\n 'index' in data.sortable\n ) {\n return true;\n }\n\n return false;\n}\n", "import {\n closestCorners,\n getScrollableAncestors,\n getFirstCollision,\n KeyboardCode,\n DroppableContainer,\n KeyboardCoordinateGetter,\n} from '@dnd-kit/core';\nimport {subtract} from '@dnd-kit/utilities';\n\nimport {hasSortableData} from '../../types';\n\nconst directions: string[] = [\n KeyboardCode.Down,\n KeyboardCode.Right,\n KeyboardCode.Up,\n KeyboardCode.Left,\n];\n\nexport const sortableKeyboardCoordinates: KeyboardCoordinateGetter = (\n event,\n {\n context: {\n active,\n collisionRect,\n droppableRects,\n droppableContainers,\n over,\n scrollableAncestors,\n },\n }\n) => {\n if (directions.includes(event.code)) {\n event.preventDefault();\n\n if (!active || !collisionRect) {\n return;\n }\n\n const filteredContainers: DroppableContainer[] = [];\n\n droppableContainers.getEnabled().forEach((entry) => {\n if (!entry || entry?.disabled) {\n return;\n }\n\n const rect = droppableRects.get(entry.id);\n\n if (!rect) {\n return;\n }\n\n switch (event.code) {\n case KeyboardCode.Down:\n if (collisionRect.top < rect.top) {\n filteredContainers.push(entry);\n }\n break;\n case KeyboardCode.Up:\n if (collisionRect.top > rect.top) {\n filteredContainers.push(entry);\n }\n break;\n case KeyboardCode.Left:\n if (collisionRect.left > rect.left) {\n filteredContainers.push(entry);\n }\n break;\n case KeyboardCode.Right:\n if (collisionRect.left < rect.left) {\n filteredContainers.push(entry);\n }\n break;\n }\n });\n\n const collisions = closestCorners({\n active,\n collisionRect: collisionRect,\n droppableRects,\n droppableContainers: filteredContainers,\n pointerCoordinates: null,\n });\n let closestId = getFirstCollision(collisions, 'id');\n\n if (closestId === over?.id && collisions.length > 1) {\n closestId = collisions[1].id;\n }\n\n if (closestId != null) {\n const activeDroppable = droppableContainers.get(active.id);\n const newDroppable = droppableContainers.get(closestId);\n const newRect = newDroppable ? droppableRects.get(newDroppable.id) : null;\n const newNode = newDroppable?.node.current;\n\n if (newNode && newRect && activeDroppable && newDroppable) {\n const newScrollAncestors = getScrollableAncestors(newNode);\n const hasDifferentScrollAncestors = newScrollAncestors.some(\n (element, index) => scrollableAncestors[index] !== element\n );\n const hasSameContainer = isSameContainer(activeDroppable, newDroppable);\n const isAfterActive = isAfter(activeDroppable, newDroppable);\n const offset =\n hasDifferentScrollAncestors || !hasSameContainer\n ? {\n x: 0,\n y: 0,\n }\n : {\n x: isAfterActive ? collisionRect.width - newRect.width : 0,\n y: isAfterActive ? collisionRect.height - newRect.height : 0,\n };\n const rectCoordinates = {\n x: newRect.left,\n y: newRect.top,\n };\n\n const newCoordinates =\n offset.x && offset.y\n ? rectCoordinates\n : subtract(rectCoordinates, offset);\n\n return newCoordinates;\n }\n }\n }\n\n return undefined;\n};\n\nfunction isSameContainer(a: DroppableContainer, b: DroppableContainer) {\n if (!hasSortableData(a) || !hasSortableData(b)) {\n return false;\n }\n\n return (\n a.data.current.sortable.containerId === b.data.current.sortable.containerId\n );\n}\n\nfunction isAfter(a: DroppableContainer, b: DroppableContainer) {\n if (!hasSortableData(a) || !hasSortableData(b)) {\n return false;\n }\n\n if (!isSameContainer(a, b)) {\n return false;\n }\n\n return a.data.current.sortable.index < b.data.current.sortable.index;\n}\n", "'use client'\nimport type { DragEndEvent, DragStartEvent } from '@dnd-kit/core'\n\nimport {\n closestCenter,\n DndContext,\n KeyboardSensor,\n PointerSensor,\n useDroppable,\n useSensor,\n useSensors,\n} from '@dnd-kit/core'\nimport { SortableContext, sortableKeyboardCoordinates } from '@dnd-kit/sortable'\nimport React, { useCallback, useId } from 'react'\n\nimport type { Props } from './types.js'\n\nexport { Props }\n\nexport const DraggableSortable: React.FC = (props) => {\n const { children, className, ids, onDragEnd, onDragStart } = props\n\n const dndContextID = useId()\n const sortableContextID = useId()\n\n const { setNodeRef } = useDroppable({\n id: dndContextID,\n })\n\n const sensors = useSensors(\n useSensor(PointerSensor, {\n activationConstraint: {\n distance: 5,\n },\n }),\n useSensor(KeyboardSensor, {\n coordinateGetter: sortableKeyboardCoordinates,\n }),\n )\n\n const handleDragEnd = useCallback(\n (event: DragEndEvent) => {\n const { active, over } = event\n\n event.activatorEvent.stopPropagation()\n\n if (!active || !over) {\n return\n }\n\n if (typeof onDragEnd === 'function') {\n onDragEnd({\n event,\n moveFromIndex: ids.findIndex((_id) => _id === active.id),\n moveToIndex: ids.findIndex((_id) => _id === over.id),\n })\n }\n },\n [onDragEnd, ids],\n )\n\n const handleDragStart = useCallback(\n (event: DragStartEvent) => {\n const { active } = event\n\n if (!active) {\n return\n }\n\n if (typeof onDragStart === 'function') {\n onDragStart({ id: active.id, event })\n }\n },\n [onDragStart],\n )\n\n return (\n \n \n
\n {children}\n
\n \n \n )\n}\n", "'use client'\nimport type { I18nClient } from '@payloadcms/translations'\n\nimport React from 'react'\n\nimport './index.scss'\n\nconst baseClass = 'error-pill'\n\nexport type ErrorPillProps = {\n className?: string\n count: number\n i18n: I18nClient\n withMessage?: boolean\n}\n\nexport const ErrorPill: React.FC = (props) => {\n const { className, count, i18n, withMessage } = props\n const lessThan3Chars = !withMessage && count < 99\n\n const classes = [baseClass, lessThan3Chars && `${baseClass}--fixed-width`, className && className]\n .filter(Boolean)\n .join(' ')\n\n if (count === 0) {\n return null\n }\n\n return (\n
\n
\n {count}\n {withMessage && ` ${count > 1 ? i18n.t('general:errors') : i18n.t('general:error')}`}\n
\n
\n )\n}\n", "'use client'\nimport type { GenericDescriptionProps } from 'payload'\n\nimport { getTranslation } from '@payloadcms/translations'\nimport React from 'react'\n\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport './index.scss'\n\nconst baseClass = 'field-description'\n\nexport const FieldDescription: React.FC = (props) => {\n const { className, description, marginPlacement, path } = props\n\n const { i18n } = useTranslation()\n\n if (description) {\n return (\n \n {getTranslation(description, i18n)}\n \n )\n }\n\n return null\n}\n", "'use client'\n\nimport type { GenericErrorProps } from 'payload'\n\nimport React from 'react'\n\nimport { Tooltip } from '../../elements/Tooltip/index.js'\nimport { useFormFields, useFormSubmitted } from '../../forms/Form/context.js'\nimport './index.scss'\n\nconst baseClass = 'field-error'\n\nexport const FieldError: React.FC = (props) => {\n const {\n alignCaret = 'right',\n message: messageFromProps,\n path,\n showError: showErrorFromProps,\n } = props\n\n const hasSubmitted = useFormSubmitted()\n const field = useFormFields(([fields]) => (fields && fields?.[path]) || null)\n\n const { errorMessage, valid } = field || {}\n\n const message = messageFromProps || errorMessage\n const showMessage = showErrorFromProps || (hasSubmitted && valid === false)\n\n if (showMessage && message?.length) {\n return (\n \n {message}\n \n )\n }\n\n return null\n}\n", "'use client'\n\nimport type { GenericLabelProps } from 'payload'\n\nimport { getTranslation } from '@payloadcms/translations'\nimport React from 'react'\n\nimport { useForm } from '../../forms/Form/context.js'\nimport { useEditDepth } from '../../providers/EditDepth/index.js'\nimport { useLocale } from '../../providers/Locale/index.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { generateFieldID } from '../../utilities/generateFieldID.js'\nimport './index.scss'\n\nexport const FieldLabel: React.FC = (props) => {\n const {\n as: ElementFromProps = 'label',\n hideLocale = false,\n htmlFor: htmlForFromProps,\n label,\n localized = false,\n path,\n required = false,\n unstyled = false,\n } = props\n\n const { uuid } = useForm()\n const editDepth = useEditDepth()\n\n const htmlFor = htmlForFromProps || generateFieldID(path, editDepth, uuid)\n\n const { i18n } = useTranslation()\n const { code, label: localLabel } = useLocale()\n\n const Element =\n ElementFromProps === 'label' ? (htmlFor ? 'label' : 'span') : ElementFromProps || 'span'\n\n if (label) {\n return (\n \n {getTranslation(label, i18n)}\n {required && !unstyled && *}\n {localized && !hideLocale && (\n \n — {typeof localLabel === 'string' ? localLabel : code}\n \n )}\n \n )\n }\n\n return null\n}\n", "'use client'\nimport React, { createContext, use } from 'react'\n\nexport const EditDepthContext = createContext(0)\n\nexport const EditDepthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {\n const parentDepth = useEditDepth()\n const depth = parentDepth + 1\n\n return {children}\n}\n\nexport const useEditDepth = (): number => use(EditDepthContext)\n", "'use client'\n\nimport type { Locale } from 'payload'\n\nimport { useSearchParams } from 'next/navigation.js'\nimport { formatAdminURL } from 'payload/shared'\nimport React, { createContext, use, useEffect, useRef, useState } from 'react'\n\nimport { findLocaleFromCode } from '../../utilities/findLocaleFromCode.js'\nimport { useAuth } from '../Auth/index.js'\nimport { useConfig } from '../Config/index.js'\n\nconst LocaleContext = createContext({} as Locale)\n\nexport const LocaleLoadingContext = createContext({\n localeIsLoading: false,\n setLocaleIsLoading: (_: boolean) => undefined,\n})\n\nconst fetchPreferences = async | string>(\n key: string,\n baseURL: string,\n): Promise<{ id: string; value: T }> =>\n await fetch(`${baseURL}/payload-preferences/${key}`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n })?.then((res) => res.json() as Promise<{ id: string; value: T }>)\n\nexport const LocaleProvider: React.FC<{ children?: React.ReactNode; locale?: Locale['code'] }> = ({\n children,\n /**\n The `locale` prop originates from the root layout, which does not have access to search params\n This component uses the `useSearchParams` hook to get the locale from the URL as precedence over this prop\n This prop does not update as the user navigates the site, because the root layout does not re-render\n */\n locale: initialLocaleFromPrefs,\n}) => {\n const {\n config: {\n localization = false,\n routes: { api: apiRoute },\n },\n } = useConfig()\n\n const { user } = useAuth()\n\n const defaultLocale = localization ? localization.defaultLocale : 'en'\n\n const localeFromParams = useSearchParams().get('locale')\n\n const [locale, setLocale] = React.useState(() => {\n if (!localization || (localization && !localization.locales.length)) {\n // TODO: return null V4\n return {} as Locale\n }\n\n return (\n findLocaleFromCode(localization, localeFromParams) ||\n findLocaleFromCode(localization, initialLocaleFromPrefs) ||\n findLocaleFromCode(localization, defaultLocale) ||\n findLocaleFromCode(localization, localization.locales[0].code)\n )\n })\n\n const [isLoading, setLocaleIsLoading] = useState(false)\n\n const prevLocale = useRef(locale)\n\n useEffect(() => {\n /**\n * We need to set `isLoading` back to false once the locale is detected to be different\n * This happens when the user clicks an anchor link which appends the `?locale=` query param\n * This triggers a client-side navigation, which re-renders the page with the new locale\n * In Next.js, local state is persisted during this type of navigation because components are not unmounted\n */\n if (locale.code !== prevLocale.current.code) {\n setLocaleIsLoading(false)\n }\n\n prevLocale.current = locale\n }, [locale])\n\n const fetchURL = formatAdminURL({\n apiRoute,\n path: '',\n })\n\n useEffect(() => {\n /**\n * This effect should only run when `localeFromParams` changes, i.e. when the user clicks an anchor link\n * The root layout, which sends the initial locale from prefs, will not re-render as the user navigates the site\n * For this reason, we need to fetch the locale from prefs if the search params clears the `locale` query param\n */\n async function resetLocale() {\n if (localization && user?.id) {\n const localeToUse =\n localeFromParams ||\n (await fetchPreferences('locale', fetchURL)?.then((res) => res.value))\n\n const newLocale =\n findLocaleFromCode(localization, localeToUse) ||\n findLocaleFromCode(localization, defaultLocale) ||\n findLocaleFromCode(localization, localization?.locales?.[0]?.code)\n\n if (newLocale) {\n setLocale(newLocale)\n }\n }\n }\n\n void resetLocale()\n }, [defaultLocale, localization, fetchURL, localeFromParams, user?.id])\n\n return (\n \n \n {children}\n \n \n )\n}\n\nexport const useLocaleLoading = () => use(LocaleLoadingContext)\n\n/**\n * TODO: V4\n * The return type of the `useLocale` hook will change in v4. It will return `null | Locale` instead of `false | {} | Locale`.\n */\nexport const useLocale = (): Locale => use(LocaleContext)\n", "import type { Locale, SanitizedLocalizationConfig } from 'payload'\n/*\n return the Locale for given locale code, else return null\n*/\nexport const findLocaleFromCode = (\n localizationConfig: SanitizedLocalizationConfig,\n locale: string,\n): Locale | null => {\n if (!localizationConfig?.locales || localizationConfig.locales.length === 0) {\n return null\n }\n\n return localizationConfig.locales.find((el) => el?.code === locale)\n}\n", null, "function _extends() {\n return _extends = Object.assign ? Object.assign.bind() : function (n) {\n for (var e = 1; e < arguments.length; e++) {\n var t = arguments[e];\n for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);\n }\n return n;\n }, _extends.apply(null, arguments);\n}\nexport { _extends as default };", "function _objectWithoutPropertiesLoose(r, e) {\n if (null == r) return {};\n var t = {};\n for (var n in r) if ({}.hasOwnProperty.call(r, n)) {\n if (-1 !== e.indexOf(n)) continue;\n t[n] = r[n];\n }\n return t;\n}\nexport { _objectWithoutPropertiesLoose as default };", "function _setPrototypeOf(t, e) {\n return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {\n return t.__proto__ = e, t;\n }, _setPrototypeOf(t, e);\n}\nexport { _setPrototypeOf as default };", "import setPrototypeOf from \"./setPrototypeOf.js\";\nfunction _inheritsLoose(t, o) {\n t.prototype = Object.create(o.prototype), t.prototype.constructor = t, setPrototypeOf(t, o);\n}\nexport { _inheritsLoose as default };", "/**\n * Checks if a given element has a CSS class.\n * \n * @param element the element\n * @param className the CSS class name\n */\nexport default function hasClass(element, className) {\n if (element.classList) return !!className && element.classList.contains(className);\n return (\" \" + (element.className.baseVal || element.className) + \" \").indexOf(\" \" + className + \" \") !== -1;\n}", "import hasClass from './hasClass';\n/**\n * Adds a CSS class to a given element.\n * \n * @param element the element\n * @param className the CSS class name\n */\n\nexport default function addClass(element, className) {\n if (element.classList) element.classList.add(className);else if (!hasClass(element, className)) if (typeof element.className === 'string') element.className = element.className + \" \" + className;else element.setAttribute('class', (element.className && element.className.baseVal || '') + \" \" + className);\n}", "function replaceClassName(origClass, classToRemove) {\n return origClass.replace(new RegExp(\"(^|\\\\s)\" + classToRemove + \"(?:\\\\s|$)\", 'g'), '$1').replace(/\\s+/g, ' ').replace(/^\\s*|\\s*$/g, '');\n}\n/**\n * Removes a CSS class from a given element.\n * \n * @param element the element\n * @param className the CSS class name\n */\n\n\nexport default function removeClass(element, className) {\n if (element.classList) {\n element.classList.remove(className);\n } else if (typeof element.className === 'string') {\n element.className = replaceClassName(element.className, className);\n } else {\n element.setAttribute('class', replaceClassName(element.className && element.className.baseVal || '', className));\n }\n}", "import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _inheritsLoose from \"@babel/runtime/helpers/esm/inheritsLoose\";\nimport PropTypes from 'prop-types';\nimport addOneClass from 'dom-helpers/addClass';\nimport removeOneClass from 'dom-helpers/removeClass';\nimport React from 'react';\nimport Transition from './Transition';\nimport { classNamesShape } from './utils/PropTypes';\nimport { forceReflow } from './utils/reflow';\n\nvar _addClass = function addClass(node, classes) {\n return node && classes && classes.split(' ').forEach(function (c) {\n return addOneClass(node, c);\n });\n};\n\nvar removeClass = function removeClass(node, classes) {\n return node && classes && classes.split(' ').forEach(function (c) {\n return removeOneClass(node, c);\n });\n};\n/**\n * A transition component inspired by the excellent\n * [ng-animate](https://docs.angularjs.org/api/ngAnimate) library, you should\n * use it if you're using CSS transitions or animations. It's built upon the\n * [`Transition`](https://reactcommunity.org/react-transition-group/transition)\n * component, so it inherits all of its props.\n *\n * `CSSTransition` applies a pair of class names during the `appear`, `enter`,\n * and `exit` states of the transition. The first class is applied and then a\n * second `*-active` class in order to activate the CSS transition. After the\n * transition, matching `*-done` class names are applied to persist the\n * transition state.\n *\n * ```jsx\n * function App() {\n * const [inProp, setInProp] = useState(false);\n * return (\n *
\n * \n *
\n * {\"I'll receive my-node-* classes\"}\n *
\n *
\n * \n *
\n * );\n * }\n * ```\n *\n * When the `in` prop is set to `true`, the child component will first receive\n * the class `example-enter`, then the `example-enter-active` will be added in\n * the next tick. `CSSTransition` [forces a\n * reflow](https://github.com/reactjs/react-transition-group/blob/5007303e729a74be66a21c3e2205e4916821524b/src/CSSTransition.js#L208-L215)\n * between before adding the `example-enter-active`. This is an important trick\n * because it allows us to transition between `example-enter` and\n * `example-enter-active` even though they were added immediately one after\n * another. Most notably, this is what makes it possible for us to animate\n * _appearance_.\n *\n * ```css\n * .my-node-enter {\n * opacity: 0;\n * }\n * .my-node-enter-active {\n * opacity: 1;\n * transition: opacity 200ms;\n * }\n * .my-node-exit {\n * opacity: 1;\n * }\n * .my-node-exit-active {\n * opacity: 0;\n * transition: opacity 200ms;\n * }\n * ```\n *\n * `*-active` classes represent which styles you want to animate **to**, so it's\n * important to add `transition` declaration only to them, otherwise transitions\n * might not behave as intended! This might not be obvious when the transitions\n * are symmetrical, i.e. when `*-enter-active` is the same as `*-exit`, like in\n * the example above (minus `transition`), but it becomes apparent in more\n * complex transitions.\n *\n * **Note**: If you're using the\n * [`appear`](http://reactcommunity.org/react-transition-group/transition#Transition-prop-appear)\n * prop, make sure to define styles for `.appear-*` classes as well.\n */\n\n\nvar CSSTransition = /*#__PURE__*/function (_React$Component) {\n _inheritsLoose(CSSTransition, _React$Component);\n\n function CSSTransition() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;\n _this.appliedClasses = {\n appear: {},\n enter: {},\n exit: {}\n };\n\n _this.onEnter = function (maybeNode, maybeAppearing) {\n var _this$resolveArgument = _this.resolveArguments(maybeNode, maybeAppearing),\n node = _this$resolveArgument[0],\n appearing = _this$resolveArgument[1];\n\n _this.removeClasses(node, 'exit');\n\n _this.addClass(node, appearing ? 'appear' : 'enter', 'base');\n\n if (_this.props.onEnter) {\n _this.props.onEnter(maybeNode, maybeAppearing);\n }\n };\n\n _this.onEntering = function (maybeNode, maybeAppearing) {\n var _this$resolveArgument2 = _this.resolveArguments(maybeNode, maybeAppearing),\n node = _this$resolveArgument2[0],\n appearing = _this$resolveArgument2[1];\n\n var type = appearing ? 'appear' : 'enter';\n\n _this.addClass(node, type, 'active');\n\n if (_this.props.onEntering) {\n _this.props.onEntering(maybeNode, maybeAppearing);\n }\n };\n\n _this.onEntered = function (maybeNode, maybeAppearing) {\n var _this$resolveArgument3 = _this.resolveArguments(maybeNode, maybeAppearing),\n node = _this$resolveArgument3[0],\n appearing = _this$resolveArgument3[1];\n\n var type = appearing ? 'appear' : 'enter';\n\n _this.removeClasses(node, type);\n\n _this.addClass(node, type, 'done');\n\n if (_this.props.onEntered) {\n _this.props.onEntered(maybeNode, maybeAppearing);\n }\n };\n\n _this.onExit = function (maybeNode) {\n var _this$resolveArgument4 = _this.resolveArguments(maybeNode),\n node = _this$resolveArgument4[0];\n\n _this.removeClasses(node, 'appear');\n\n _this.removeClasses(node, 'enter');\n\n _this.addClass(node, 'exit', 'base');\n\n if (_this.props.onExit) {\n _this.props.onExit(maybeNode);\n }\n };\n\n _this.onExiting = function (maybeNode) {\n var _this$resolveArgument5 = _this.resolveArguments(maybeNode),\n node = _this$resolveArgument5[0];\n\n _this.addClass(node, 'exit', 'active');\n\n if (_this.props.onExiting) {\n _this.props.onExiting(maybeNode);\n }\n };\n\n _this.onExited = function (maybeNode) {\n var _this$resolveArgument6 = _this.resolveArguments(maybeNode),\n node = _this$resolveArgument6[0];\n\n _this.removeClasses(node, 'exit');\n\n _this.addClass(node, 'exit', 'done');\n\n if (_this.props.onExited) {\n _this.props.onExited(maybeNode);\n }\n };\n\n _this.resolveArguments = function (maybeNode, maybeAppearing) {\n return _this.props.nodeRef ? [_this.props.nodeRef.current, maybeNode] // here `maybeNode` is actually `appearing`\n : [maybeNode, maybeAppearing];\n };\n\n _this.getClassNames = function (type) {\n var classNames = _this.props.classNames;\n var isStringClassNames = typeof classNames === 'string';\n var prefix = isStringClassNames && classNames ? classNames + \"-\" : '';\n var baseClassName = isStringClassNames ? \"\" + prefix + type : classNames[type];\n var activeClassName = isStringClassNames ? baseClassName + \"-active\" : classNames[type + \"Active\"];\n var doneClassName = isStringClassNames ? baseClassName + \"-done\" : classNames[type + \"Done\"];\n return {\n baseClassName: baseClassName,\n activeClassName: activeClassName,\n doneClassName: doneClassName\n };\n };\n\n return _this;\n }\n\n var _proto = CSSTransition.prototype;\n\n _proto.addClass = function addClass(node, type, phase) {\n var className = this.getClassNames(type)[phase + \"ClassName\"];\n\n var _this$getClassNames = this.getClassNames('enter'),\n doneClassName = _this$getClassNames.doneClassName;\n\n if (type === 'appear' && phase === 'done' && doneClassName) {\n className += \" \" + doneClassName;\n } // This is to force a repaint,\n // which is necessary in order to transition styles when adding a class name.\n\n\n if (phase === 'active') {\n if (node) forceReflow(node);\n }\n\n if (className) {\n this.appliedClasses[type][phase] = className;\n\n _addClass(node, className);\n }\n };\n\n _proto.removeClasses = function removeClasses(node, type) {\n var _this$appliedClasses$ = this.appliedClasses[type],\n baseClassName = _this$appliedClasses$.base,\n activeClassName = _this$appliedClasses$.active,\n doneClassName = _this$appliedClasses$.done;\n this.appliedClasses[type] = {};\n\n if (baseClassName) {\n removeClass(node, baseClassName);\n }\n\n if (activeClassName) {\n removeClass(node, activeClassName);\n }\n\n if (doneClassName) {\n removeClass(node, doneClassName);\n }\n };\n\n _proto.render = function render() {\n var _this$props = this.props,\n _ = _this$props.classNames,\n props = _objectWithoutPropertiesLoose(_this$props, [\"classNames\"]);\n\n return /*#__PURE__*/React.createElement(Transition, _extends({}, props, {\n onEnter: this.onEnter,\n onEntered: this.onEntered,\n onEntering: this.onEntering,\n onExit: this.onExit,\n onExiting: this.onExiting,\n onExited: this.onExited\n }));\n };\n\n return CSSTransition;\n}(React.Component);\n\nCSSTransition.defaultProps = {\n classNames: ''\n};\nCSSTransition.propTypes = process.env.NODE_ENV !== \"production\" ? _extends({}, Transition.propTypes, {\n /**\n * The animation classNames applied to the component as it appears, enters,\n * exits or has finished the transition. A single name can be provided, which\n * will be suffixed for each stage, e.g. `classNames=\"fade\"` applies:\n *\n * - `fade-appear`, `fade-appear-active`, `fade-appear-done`\n * - `fade-enter`, `fade-enter-active`, `fade-enter-done`\n * - `fade-exit`, `fade-exit-active`, `fade-exit-done`\n *\n * A few details to note about how these classes are applied:\n *\n * 1. They are _joined_ with the ones that are already defined on the child\n * component, so if you want to add some base styles, you can use\n * `className` without worrying that it will be overridden.\n *\n * 2. If the transition component mounts with `in={false}`, no classes are\n * applied yet. You might be expecting `*-exit-done`, but if you think\n * about it, a component cannot finish exiting if it hasn't entered yet.\n *\n * 2. `fade-appear-done` and `fade-enter-done` will _both_ be applied. This\n * allows you to define different behavior for when appearing is done and\n * when regular entering is done, using selectors like\n * `.fade-enter-done:not(.fade-appear-done)`. For example, you could apply\n * an epic entrance animation when element first appears in the DOM using\n * [Animate.css](https://daneden.github.io/animate.css/). Otherwise you can\n * simply use `fade-enter-done` for defining both cases.\n *\n * Each individual classNames can also be specified independently like:\n *\n * ```js\n * classNames={{\n * appear: 'my-appear',\n * appearActive: 'my-active-appear',\n * appearDone: 'my-done-appear',\n * enter: 'my-enter',\n * enterActive: 'my-active-enter',\n * enterDone: 'my-done-enter',\n * exit: 'my-exit',\n * exitActive: 'my-active-exit',\n * exitDone: 'my-done-exit',\n * }}\n * ```\n *\n * If you want to set these classes using CSS Modules:\n *\n * ```js\n * import styles from './styles.css';\n * ```\n *\n * you might want to use camelCase in your CSS file, that way could simply\n * spread them instead of listing them one by one:\n *\n * ```js\n * classNames={{ ...styles }}\n * ```\n *\n * @type {string | {\n * appear?: string,\n * appearActive?: string,\n * appearDone?: string,\n * enter?: string,\n * enterActive?: string,\n * enterDone?: string,\n * exit?: string,\n * exitActive?: string,\n * exitDone?: string,\n * }}\n */\n classNames: classNamesShape,\n\n /**\n * A `` callback fired immediately after the 'enter' or 'appear' class is\n * applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool)\n */\n onEnter: PropTypes.func,\n\n /**\n * A `` callback fired immediately after the 'enter-active' or\n * 'appear-active' class is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool)\n */\n onEntering: PropTypes.func,\n\n /**\n * A `` callback fired immediately after the 'enter' or\n * 'appear' classes are **removed** and the `done` class is added to the DOM node.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool)\n */\n onEntered: PropTypes.func,\n\n /**\n * A `` callback fired immediately after the 'exit' class is\n * applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed\n *\n * @type Function(node: HtmlElement)\n */\n onExit: PropTypes.func,\n\n /**\n * A `` callback fired immediately after the 'exit-active' is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed\n *\n * @type Function(node: HtmlElement)\n */\n onExiting: PropTypes.func,\n\n /**\n * A `` callback fired immediately after the 'exit' classes\n * are **removed** and the `exit-done` class is added to the DOM node.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed\n *\n * @type Function(node: HtmlElement)\n */\n onExited: PropTypes.func\n}) : {};\nexport default CSSTransition;", "import _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _inheritsLoose from \"@babel/runtime/helpers/esm/inheritsLoose\";\nimport PropTypes from 'prop-types';\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport config from './config';\nimport { timeoutsShape } from './utils/PropTypes';\nimport TransitionGroupContext from './TransitionGroupContext';\nimport { forceReflow } from './utils/reflow';\nexport var UNMOUNTED = 'unmounted';\nexport var EXITED = 'exited';\nexport var ENTERING = 'entering';\nexport var ENTERED = 'entered';\nexport var EXITING = 'exiting';\n/**\n * The Transition component lets you describe a transition from one component\n * state to another _over time_ with a simple declarative API. Most commonly\n * it's used to animate the mounting and unmounting of a component, but can also\n * be used to describe in-place transition states as well.\n *\n * ---\n *\n * **Note**: `Transition` is a platform-agnostic base component. If you're using\n * transitions in CSS, you'll probably want to use\n * [`CSSTransition`](https://reactcommunity.org/react-transition-group/css-transition)\n * instead. It inherits all the features of `Transition`, but contains\n * additional features necessary to play nice with CSS transitions (hence the\n * name of the component).\n *\n * ---\n *\n * By default the `Transition` component does not alter the behavior of the\n * component it renders, it only tracks \"enter\" and \"exit\" states for the\n * components. It's up to you to give meaning and effect to those states. For\n * example we can add styles to a component when it enters or exits:\n *\n * ```jsx\n * import { Transition } from 'react-transition-group';\n *\n * const duration = 300;\n *\n * const defaultStyle = {\n * transition: `opacity ${duration}ms ease-in-out`,\n * opacity: 0,\n * }\n *\n * const transitionStyles = {\n * entering: { opacity: 1 },\n * entered: { opacity: 1 },\n * exiting: { opacity: 0 },\n * exited: { opacity: 0 },\n * };\n *\n * const Fade = ({ in: inProp }) => (\n * \n * {state => (\n *
\n * I'm a fade Transition!\n *
\n * )}\n *
\n * );\n * ```\n *\n * There are 4 main states a Transition can be in:\n * - `'entering'`\n * - `'entered'`\n * - `'exiting'`\n * - `'exited'`\n *\n * Transition state is toggled via the `in` prop. When `true` the component\n * begins the \"Enter\" stage. During this stage, the component will shift from\n * its current transition state, to `'entering'` for the duration of the\n * transition and then to the `'entered'` stage once it's complete. Let's take\n * the following example (we'll use the\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate) hook):\n *\n * ```jsx\n * function App() {\n * const [inProp, setInProp] = useState(false);\n * return (\n *
\n * \n * {state => (\n * // ...\n * )}\n * \n * \n *
\n * );\n * }\n * ```\n *\n * When the button is clicked the component will shift to the `'entering'` state\n * and stay there for 500ms (the value of `timeout`) before it finally switches\n * to `'entered'`.\n *\n * When `in` is `false` the same thing happens except the state moves from\n * `'exiting'` to `'exited'`.\n */\n\nvar Transition = /*#__PURE__*/function (_React$Component) {\n _inheritsLoose(Transition, _React$Component);\n\n function Transition(props, context) {\n var _this;\n\n _this = _React$Component.call(this, props, context) || this;\n var parentGroup = context; // In the context of a TransitionGroup all enters are really appears\n\n var appear = parentGroup && !parentGroup.isMounting ? props.enter : props.appear;\n var initialStatus;\n _this.appearStatus = null;\n\n if (props.in) {\n if (appear) {\n initialStatus = EXITED;\n _this.appearStatus = ENTERING;\n } else {\n initialStatus = ENTERED;\n }\n } else {\n if (props.unmountOnExit || props.mountOnEnter) {\n initialStatus = UNMOUNTED;\n } else {\n initialStatus = EXITED;\n }\n }\n\n _this.state = {\n status: initialStatus\n };\n _this.nextCallback = null;\n return _this;\n }\n\n Transition.getDerivedStateFromProps = function getDerivedStateFromProps(_ref, prevState) {\n var nextIn = _ref.in;\n\n if (nextIn && prevState.status === UNMOUNTED) {\n return {\n status: EXITED\n };\n }\n\n return null;\n } // getSnapshotBeforeUpdate(prevProps) {\n // let nextStatus = null\n // if (prevProps !== this.props) {\n // const { status } = this.state\n // if (this.props.in) {\n // if (status !== ENTERING && status !== ENTERED) {\n // nextStatus = ENTERING\n // }\n // } else {\n // if (status === ENTERING || status === ENTERED) {\n // nextStatus = EXITING\n // }\n // }\n // }\n // return { nextStatus }\n // }\n ;\n\n var _proto = Transition.prototype;\n\n _proto.componentDidMount = function componentDidMount() {\n this.updateStatus(true, this.appearStatus);\n };\n\n _proto.componentDidUpdate = function componentDidUpdate(prevProps) {\n var nextStatus = null;\n\n if (prevProps !== this.props) {\n var status = this.state.status;\n\n if (this.props.in) {\n if (status !== ENTERING && status !== ENTERED) {\n nextStatus = ENTERING;\n }\n } else {\n if (status === ENTERING || status === ENTERED) {\n nextStatus = EXITING;\n }\n }\n }\n\n this.updateStatus(false, nextStatus);\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n this.cancelNextCallback();\n };\n\n _proto.getTimeouts = function getTimeouts() {\n var timeout = this.props.timeout;\n var exit, enter, appear;\n exit = enter = appear = timeout;\n\n if (timeout != null && typeof timeout !== 'number') {\n exit = timeout.exit;\n enter = timeout.enter; // TODO: remove fallback for next major\n\n appear = timeout.appear !== undefined ? timeout.appear : enter;\n }\n\n return {\n exit: exit,\n enter: enter,\n appear: appear\n };\n };\n\n _proto.updateStatus = function updateStatus(mounting, nextStatus) {\n if (mounting === void 0) {\n mounting = false;\n }\n\n if (nextStatus !== null) {\n // nextStatus will always be ENTERING or EXITING.\n this.cancelNextCallback();\n\n if (nextStatus === ENTERING) {\n if (this.props.unmountOnExit || this.props.mountOnEnter) {\n var node = this.props.nodeRef ? this.props.nodeRef.current : ReactDOM.findDOMNode(this); // https://github.com/reactjs/react-transition-group/pull/749\n // With unmountOnExit or mountOnEnter, the enter animation should happen at the transition between `exited` and `entering`.\n // To make the animation happen, we have to separate each rendering and avoid being processed as batched.\n\n if (node) forceReflow(node);\n }\n\n this.performEnter(mounting);\n } else {\n this.performExit();\n }\n } else if (this.props.unmountOnExit && this.state.status === EXITED) {\n this.setState({\n status: UNMOUNTED\n });\n }\n };\n\n _proto.performEnter = function performEnter(mounting) {\n var _this2 = this;\n\n var enter = this.props.enter;\n var appearing = this.context ? this.context.isMounting : mounting;\n\n var _ref2 = this.props.nodeRef ? [appearing] : [ReactDOM.findDOMNode(this), appearing],\n maybeNode = _ref2[0],\n maybeAppearing = _ref2[1];\n\n var timeouts = this.getTimeouts();\n var enterTimeout = appearing ? timeouts.appear : timeouts.enter; // no enter animation skip right to ENTERED\n // if we are mounting and running this it means appear _must_ be set\n\n if (!mounting && !enter || config.disabled) {\n this.safeSetState({\n status: ENTERED\n }, function () {\n _this2.props.onEntered(maybeNode);\n });\n return;\n }\n\n this.props.onEnter(maybeNode, maybeAppearing);\n this.safeSetState({\n status: ENTERING\n }, function () {\n _this2.props.onEntering(maybeNode, maybeAppearing);\n\n _this2.onTransitionEnd(enterTimeout, function () {\n _this2.safeSetState({\n status: ENTERED\n }, function () {\n _this2.props.onEntered(maybeNode, maybeAppearing);\n });\n });\n });\n };\n\n _proto.performExit = function performExit() {\n var _this3 = this;\n\n var exit = this.props.exit;\n var timeouts = this.getTimeouts();\n var maybeNode = this.props.nodeRef ? undefined : ReactDOM.findDOMNode(this); // no exit animation skip right to EXITED\n\n if (!exit || config.disabled) {\n this.safeSetState({\n status: EXITED\n }, function () {\n _this3.props.onExited(maybeNode);\n });\n return;\n }\n\n this.props.onExit(maybeNode);\n this.safeSetState({\n status: EXITING\n }, function () {\n _this3.props.onExiting(maybeNode);\n\n _this3.onTransitionEnd(timeouts.exit, function () {\n _this3.safeSetState({\n status: EXITED\n }, function () {\n _this3.props.onExited(maybeNode);\n });\n });\n });\n };\n\n _proto.cancelNextCallback = function cancelNextCallback() {\n if (this.nextCallback !== null) {\n this.nextCallback.cancel();\n this.nextCallback = null;\n }\n };\n\n _proto.safeSetState = function safeSetState(nextState, callback) {\n // This shouldn't be necessary, but there are weird race conditions with\n // setState callbacks and unmounting in testing, so always make sure that\n // we can cancel any pending setState callbacks after we unmount.\n callback = this.setNextCallback(callback);\n this.setState(nextState, callback);\n };\n\n _proto.setNextCallback = function setNextCallback(callback) {\n var _this4 = this;\n\n var active = true;\n\n this.nextCallback = function (event) {\n if (active) {\n active = false;\n _this4.nextCallback = null;\n callback(event);\n }\n };\n\n this.nextCallback.cancel = function () {\n active = false;\n };\n\n return this.nextCallback;\n };\n\n _proto.onTransitionEnd = function onTransitionEnd(timeout, handler) {\n this.setNextCallback(handler);\n var node = this.props.nodeRef ? this.props.nodeRef.current : ReactDOM.findDOMNode(this);\n var doesNotHaveTimeoutOrListener = timeout == null && !this.props.addEndListener;\n\n if (!node || doesNotHaveTimeoutOrListener) {\n setTimeout(this.nextCallback, 0);\n return;\n }\n\n if (this.props.addEndListener) {\n var _ref3 = this.props.nodeRef ? [this.nextCallback] : [node, this.nextCallback],\n maybeNode = _ref3[0],\n maybeNextCallback = _ref3[1];\n\n this.props.addEndListener(maybeNode, maybeNextCallback);\n }\n\n if (timeout != null) {\n setTimeout(this.nextCallback, timeout);\n }\n };\n\n _proto.render = function render() {\n var status = this.state.status;\n\n if (status === UNMOUNTED) {\n return null;\n }\n\n var _this$props = this.props,\n children = _this$props.children,\n _in = _this$props.in,\n _mountOnEnter = _this$props.mountOnEnter,\n _unmountOnExit = _this$props.unmountOnExit,\n _appear = _this$props.appear,\n _enter = _this$props.enter,\n _exit = _this$props.exit,\n _timeout = _this$props.timeout,\n _addEndListener = _this$props.addEndListener,\n _onEnter = _this$props.onEnter,\n _onEntering = _this$props.onEntering,\n _onEntered = _this$props.onEntered,\n _onExit = _this$props.onExit,\n _onExiting = _this$props.onExiting,\n _onExited = _this$props.onExited,\n _nodeRef = _this$props.nodeRef,\n childProps = _objectWithoutPropertiesLoose(_this$props, [\"children\", \"in\", \"mountOnEnter\", \"unmountOnExit\", \"appear\", \"enter\", \"exit\", \"timeout\", \"addEndListener\", \"onEnter\", \"onEntering\", \"onEntered\", \"onExit\", \"onExiting\", \"onExited\", \"nodeRef\"]);\n\n return (\n /*#__PURE__*/\n // allows for nested Transitions\n React.createElement(TransitionGroupContext.Provider, {\n value: null\n }, typeof children === 'function' ? children(status, childProps) : React.cloneElement(React.Children.only(children), childProps))\n );\n };\n\n return Transition;\n}(React.Component);\n\nTransition.contextType = TransitionGroupContext;\nTransition.propTypes = process.env.NODE_ENV !== \"production\" ? {\n /**\n * A React reference to DOM element that need to transition:\n * https://stackoverflow.com/a/51127130/4671932\n *\n * - When `nodeRef` prop is used, `node` is not passed to callback functions\n * (e.g. `onEnter`) because user already has direct access to the node.\n * - When changing `key` prop of `Transition` in a `TransitionGroup` a new\n * `nodeRef` need to be provided to `Transition` with changed `key` prop\n * (see\n * [test/CSSTransition-test.js](https://github.com/reactjs/react-transition-group/blob/13435f897b3ab71f6e19d724f145596f5910581c/test/CSSTransition-test.js#L362-L437)).\n */\n nodeRef: PropTypes.shape({\n current: typeof Element === 'undefined' ? PropTypes.any : function (propValue, key, componentName, location, propFullName, secret) {\n var value = propValue[key];\n return PropTypes.instanceOf(value && 'ownerDocument' in value ? value.ownerDocument.defaultView.Element : Element)(propValue, key, componentName, location, propFullName, secret);\n }\n }),\n\n /**\n * A `function` child can be used instead of a React element. This function is\n * called with the current transition status (`'entering'`, `'entered'`,\n * `'exiting'`, `'exited'`), which can be used to apply context\n * specific props to a component.\n *\n * ```jsx\n * \n * {state => (\n * \n * )}\n * \n * ```\n */\n children: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.element.isRequired]).isRequired,\n\n /**\n * Show the component; triggers the enter or exit states\n */\n in: PropTypes.bool,\n\n /**\n * By default the child component is mounted immediately along with\n * the parent `Transition` component. If you want to \"lazy mount\" the component on the\n * first `in={true}` you can set `mountOnEnter`. After the first enter transition the component will stay\n * mounted, even on \"exited\", unless you also specify `unmountOnExit`.\n */\n mountOnEnter: PropTypes.bool,\n\n /**\n * By default the child component stays mounted after it reaches the `'exited'` state.\n * Set `unmountOnExit` if you'd prefer to unmount the component after it finishes exiting.\n */\n unmountOnExit: PropTypes.bool,\n\n /**\n * By default the child component does not perform the enter transition when\n * it first mounts, regardless of the value of `in`. If you want this\n * behavior, set both `appear` and `in` to `true`.\n *\n * > **Note**: there are no special appear states like `appearing`/`appeared`, this prop\n * > only adds an additional enter transition. However, in the\n * > `` component that first enter transition does result in\n * > additional `.appear-*` classes, that way you can choose to style it\n * > differently.\n */\n appear: PropTypes.bool,\n\n /**\n * Enable or disable enter transitions.\n */\n enter: PropTypes.bool,\n\n /**\n * Enable or disable exit transitions.\n */\n exit: PropTypes.bool,\n\n /**\n * The duration of the transition, in milliseconds.\n * Required unless `addEndListener` is provided.\n *\n * You may specify a single timeout for all transitions:\n *\n * ```jsx\n * timeout={500}\n * ```\n *\n * or individually:\n *\n * ```jsx\n * timeout={{\n * appear: 500,\n * enter: 300,\n * exit: 500,\n * }}\n * ```\n *\n * - `appear` defaults to the value of `enter`\n * - `enter` defaults to `0`\n * - `exit` defaults to `0`\n *\n * @type {number | { enter?: number, exit?: number, appear?: number }}\n */\n timeout: function timeout(props) {\n var pt = timeoutsShape;\n if (!props.addEndListener) pt = pt.isRequired;\n\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n return pt.apply(void 0, [props].concat(args));\n },\n\n /**\n * Add a custom transition end trigger. Called with the transitioning\n * DOM node and a `done` callback. Allows for more fine grained transition end\n * logic. Timeouts are still used as a fallback if provided.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * ```jsx\n * addEndListener={(node, done) => {\n * // use the css transitionend event to mark the finish of a transition\n * node.addEventListener('transitionend', done, false);\n * }}\n * ```\n */\n addEndListener: PropTypes.func,\n\n /**\n * Callback fired before the \"entering\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool) -> void\n */\n onEnter: PropTypes.func,\n\n /**\n * Callback fired after the \"entering\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool)\n */\n onEntering: PropTypes.func,\n\n /**\n * Callback fired after the \"entered\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool) -> void\n */\n onEntered: PropTypes.func,\n\n /**\n * Callback fired before the \"exiting\" status is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExit: PropTypes.func,\n\n /**\n * Callback fired after the \"exiting\" status is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExiting: PropTypes.func,\n\n /**\n * Callback fired after the \"exited\" status is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExited: PropTypes.func\n} : {}; // Name the function so it is clearer in the documentation\n\nfunction noop() {}\n\nTransition.defaultProps = {\n in: false,\n mountOnEnter: false,\n unmountOnExit: false,\n appear: false,\n enter: true,\n exit: true,\n onEnter: noop,\n onEntering: noop,\n onEntered: noop,\n onExit: noop,\n onExiting: noop,\n onExited: noop\n};\nTransition.UNMOUNTED = UNMOUNTED;\nTransition.EXITED = EXITED;\nTransition.ENTERING = ENTERING;\nTransition.ENTERED = ENTERED;\nTransition.EXITING = EXITING;\nexport default Transition;", "export default {\n disabled: false\n};", "import React from 'react';\nexport default React.createContext(null);", "export var forceReflow = function forceReflow(node) {\n return node.scrollTop;\n};", "function _assertThisInitialized(e) {\n if (void 0 === e) throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n return e;\n}\nexport { _assertThisInitialized as default };", null, null, null, "import {\n tabbable,\n focusable,\n isFocusable,\n isTabbable,\n getTabIndex,\n} from 'tabbable';\n\nconst activeFocusTraps = {\n activateTrap(trapStack, trap) {\n if (trapStack.length > 0) {\n const activeTrap = trapStack[trapStack.length - 1];\n if (activeTrap !== trap) {\n activeTrap.pause();\n }\n }\n\n const trapIndex = trapStack.indexOf(trap);\n if (trapIndex === -1) {\n trapStack.push(trap);\n } else {\n // move this existing trap to the front of the queue\n trapStack.splice(trapIndex, 1);\n trapStack.push(trap);\n }\n },\n\n deactivateTrap(trapStack, trap) {\n const trapIndex = trapStack.indexOf(trap);\n if (trapIndex !== -1) {\n trapStack.splice(trapIndex, 1);\n }\n\n if (trapStack.length > 0) {\n trapStack[trapStack.length - 1].unpause();\n }\n },\n};\n\nconst isSelectableInput = function (node) {\n return (\n node.tagName &&\n node.tagName.toLowerCase() === 'input' &&\n typeof node.select === 'function'\n );\n};\n\nconst isEscapeEvent = function (e) {\n return e?.key === 'Escape' || e?.key === 'Esc' || e?.keyCode === 27;\n};\n\nconst isTabEvent = function (e) {\n return e?.key === 'Tab' || e?.keyCode === 9;\n};\n\n// checks for TAB by default\nconst isKeyForward = function (e) {\n return isTabEvent(e) && !e.shiftKey;\n};\n\n// checks for SHIFT+TAB by default\nconst isKeyBackward = function (e) {\n return isTabEvent(e) && e.shiftKey;\n};\n\nconst delay = function (fn) {\n return setTimeout(fn, 0);\n};\n\n// Array.find/findIndex() are not supported on IE; this replicates enough\n// of Array.findIndex() for our needs\nconst findIndex = function (arr, fn) {\n let idx = -1;\n\n arr.every(function (value, i) {\n if (fn(value)) {\n idx = i;\n return false; // break\n }\n\n return true; // next\n });\n\n return idx;\n};\n\n/**\n * Get an option's value when it could be a plain value, or a handler that provides\n * the value.\n * @param {*} value Option's value to check.\n * @param {...*} [params] Any parameters to pass to the handler, if `value` is a function.\n * @returns {*} The `value`, or the handler's returned value.\n */\nconst valueOrHandler = function (value, ...params) {\n return typeof value === 'function' ? value(...params) : value;\n};\n\nconst getActualTarget = function (event) {\n // NOTE: If the trap is _inside_ a shadow DOM, event.target will always be the\n // shadow host. However, event.target.composedPath() will be an array of\n // nodes \"clicked\" from inner-most (the actual element inside the shadow) to\n // outer-most (the host HTML document). If we have access to composedPath(),\n // then use its first element; otherwise, fall back to event.target (and\n // this only works for an _open_ shadow DOM; otherwise,\n // composedPath()[0] === event.target always).\n return event.target.shadowRoot && typeof event.composedPath === 'function'\n ? event.composedPath()[0]\n : event.target;\n};\n\n// NOTE: this must be _outside_ `createFocusTrap()` to make sure all traps in this\n// current instance use the same stack if `userOptions.trapStack` isn't specified\nconst internalTrapStack = [];\n\nconst createFocusTrap = function (elements, userOptions) {\n // SSR: a live trap shouldn't be created in this type of environment so this\n // should be safe code to execute if the `document` option isn't specified\n const doc = userOptions?.document || document;\n\n const trapStack = userOptions?.trapStack || internalTrapStack;\n\n const config = {\n returnFocusOnDeactivate: true,\n escapeDeactivates: true,\n delayInitialFocus: true,\n isKeyForward,\n isKeyBackward,\n ...userOptions,\n };\n\n const state = {\n // containers given to createFocusTrap()\n // @type {Array}\n containers: [],\n\n // list of objects identifying tabbable nodes in `containers` in the trap\n // NOTE: it's possible that a group has no tabbable nodes if nodes get removed while the trap\n // is active, but the trap should never get to a state where there isn't at least one group\n // with at least one tabbable node in it (that would lead to an error condition that would\n // result in an error being thrown)\n // @type {Array<{\n // container: HTMLElement,\n // tabbableNodes: Array, // empty if none\n // focusableNodes: Array, // empty if none\n // posTabIndexesFound: boolean,\n // firstTabbableNode: HTMLElement|undefined,\n // lastTabbableNode: HTMLElement|undefined,\n // firstDomTabbableNode: HTMLElement|undefined,\n // lastDomTabbableNode: HTMLElement|undefined,\n // nextTabbableNode: (node: HTMLElement, forward: boolean) => HTMLElement|undefined\n // }>}\n containerGroups: [], // same order/length as `containers` list\n\n // references to objects in `containerGroups`, but only those that actually have\n // tabbable nodes in them\n // NOTE: same order as `containers` and `containerGroups`, but __not necessarily__\n // the same length\n tabbableGroups: [],\n\n nodeFocusedBeforeActivation: null,\n mostRecentlyFocusedNode: null,\n active: false,\n paused: false,\n\n // timer ID for when delayInitialFocus is true and initial focus in this trap\n // has been delayed during activation\n delayInitialFocusTimer: undefined,\n\n // the most recent KeyboardEvent for the configured nav key (typically [SHIFT+]TAB), if any\n recentNavEvent: undefined,\n };\n\n let trap; // eslint-disable-line prefer-const -- some private functions reference it, and its methods reference private functions, so we must declare here and define later\n\n /**\n * Gets a configuration option value.\n * @param {Object|undefined} configOverrideOptions If true, and option is defined in this set,\n * value will be taken from this object. Otherwise, value will be taken from base configuration.\n * @param {string} optionName Name of the option whose value is sought.\n * @param {string|undefined} [configOptionName] Name of option to use __instead of__ `optionName`\n * IIF `configOverrideOptions` is not defined. Otherwise, `optionName` is used.\n */\n const getOption = (configOverrideOptions, optionName, configOptionName) => {\n return configOverrideOptions &&\n configOverrideOptions[optionName] !== undefined\n ? configOverrideOptions[optionName]\n : config[configOptionName || optionName];\n };\n\n /**\n * Finds the index of the container that contains the element.\n * @param {HTMLElement} element\n * @param {Event} [event] If available, and `element` isn't directly found in any container,\n * the event's composed path is used to see if includes any known trap containers in the\n * case where the element is inside a Shadow DOM.\n * @returns {number} Index of the container in either `state.containers` or\n * `state.containerGroups` (the order/length of these lists are the same); -1\n * if the element isn't found.\n */\n const findContainerIndex = function (element, event) {\n const composedPath =\n typeof event?.composedPath === 'function'\n ? event.composedPath()\n : undefined;\n // NOTE: search `containerGroups` because it's possible a group contains no tabbable\n // nodes, but still contains focusable nodes (e.g. if they all have `tabindex=-1`)\n // and we still need to find the element in there\n return state.containerGroups.findIndex(\n ({ container, tabbableNodes }) =>\n container.contains(element) ||\n // fall back to explicit tabbable search which will take into consideration any\n // web components if the `tabbableOptions.getShadowRoot` option was used for\n // the trap, enabling shadow DOM support in tabbable (`Node.contains()` doesn't\n // look inside web components even if open)\n composedPath?.includes(container) ||\n tabbableNodes.find((node) => node === element)\n );\n };\n\n /**\n * Gets the node for the given option, which is expected to be an option that\n * can be either a DOM node, a string that is a selector to get a node, `false`\n * (if a node is explicitly NOT given), or a function that returns any of these\n * values.\n * @param {string} optionName\n * @returns {undefined | false | HTMLElement | SVGElement} Returns\n * `undefined` if the option is not specified; `false` if the option\n * resolved to `false` (node explicitly not given); otherwise, the resolved\n * DOM node.\n * @throws {Error} If the option is set, not `false`, and is not, or does not\n * resolve to a node.\n */\n const getNodeForOption = function (optionName, ...params) {\n let optionValue = config[optionName];\n\n if (typeof optionValue === 'function') {\n optionValue = optionValue(...params);\n }\n\n if (optionValue === true) {\n optionValue = undefined; // use default value\n }\n\n if (!optionValue) {\n if (optionValue === undefined || optionValue === false) {\n return optionValue;\n }\n // else, empty string (invalid), null (invalid), 0 (invalid)\n\n throw new Error(\n `\\`${optionName}\\` was specified but was not a node, or did not return a node`\n );\n }\n\n let node = optionValue; // could be HTMLElement, SVGElement, or non-empty string at this point\n\n if (typeof optionValue === 'string') {\n node = doc.querySelector(optionValue); // resolve to node, or null if fails\n if (!node) {\n throw new Error(\n `\\`${optionName}\\` as selector refers to no known node`\n );\n }\n }\n\n return node;\n };\n\n const getInitialFocusNode = function () {\n let node = getNodeForOption('initialFocus');\n\n // false explicitly indicates we want no initialFocus at all\n if (node === false) {\n return false;\n }\n\n if (node === undefined || !isFocusable(node, config.tabbableOptions)) {\n // option not specified nor focusable: use fallback options\n if (findContainerIndex(doc.activeElement) >= 0) {\n node = doc.activeElement;\n } else {\n const firstTabbableGroup = state.tabbableGroups[0];\n const firstTabbableNode =\n firstTabbableGroup && firstTabbableGroup.firstTabbableNode;\n\n // NOTE: `fallbackFocus` option function cannot return `false` (not supported)\n node = firstTabbableNode || getNodeForOption('fallbackFocus');\n }\n }\n\n if (!node) {\n throw new Error(\n 'Your focus-trap needs to have at least one focusable element'\n );\n }\n\n return node;\n };\n\n const updateTabbableNodes = function () {\n state.containerGroups = state.containers.map((container) => {\n const tabbableNodes = tabbable(container, config.tabbableOptions);\n\n // NOTE: if we have tabbable nodes, we must have focusable nodes; focusable nodes\n // are a superset of tabbable nodes since nodes with negative `tabindex` attributes\n // are focusable but not tabbable\n const focusableNodes = focusable(container, config.tabbableOptions);\n\n const firstTabbableNode =\n tabbableNodes.length > 0 ? tabbableNodes[0] : undefined;\n const lastTabbableNode =\n tabbableNodes.length > 0\n ? tabbableNodes[tabbableNodes.length - 1]\n : undefined;\n\n const firstDomTabbableNode = focusableNodes.find((node) =>\n isTabbable(node)\n );\n const lastDomTabbableNode = focusableNodes\n .slice()\n .reverse()\n .find((node) => isTabbable(node));\n\n const posTabIndexesFound = !!tabbableNodes.find(\n (node) => getTabIndex(node) > 0\n );\n\n return {\n container,\n tabbableNodes,\n focusableNodes,\n\n /** True if at least one node with positive `tabindex` was found in this container. */\n posTabIndexesFound,\n\n /** First tabbable node in container, __tabindex__ order; `undefined` if none. */\n firstTabbableNode,\n /** Last tabbable node in container, __tabindex__ order; `undefined` if none. */\n lastTabbableNode,\n\n // NOTE: DOM order is NOT NECESSARILY \"document position\" order, but figuring that out\n // would require more than just https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition\n // because that API doesn't work with Shadow DOM as well as it should (@see\n // https://github.com/whatwg/dom/issues/320) and since this first/last is only needed, so far,\n // to address an edge case related to positive tabindex support, this seems like a much easier,\n // \"close enough most of the time\" alternative for positive tabindexes which should generally\n // be avoided anyway...\n /** First tabbable node in container, __DOM__ order; `undefined` if none. */\n firstDomTabbableNode,\n /** Last tabbable node in container, __DOM__ order; `undefined` if none. */\n lastDomTabbableNode,\n\n /**\n * Finds the __tabbable__ node that follows the given node in the specified direction,\n * in this container, if any.\n * @param {HTMLElement} node\n * @param {boolean} [forward] True if going in forward tab order; false if going\n * in reverse.\n * @returns {HTMLElement|undefined} The next tabbable node, if any.\n */\n nextTabbableNode(node, forward = true) {\n const nodeIdx = tabbableNodes.indexOf(node);\n if (nodeIdx < 0) {\n // either not tabbable nor focusable, or was focused but not tabbable (negative tabindex):\n // since `node` should at least have been focusable, we assume that's the case and mimic\n // what browsers do, which is set focus to the next node in __document position order__,\n // regardless of positive tabindexes, if any -- and for reasons explained in the NOTE\n // above related to `firstDomTabbable` and `lastDomTabbable` properties, we fall back to\n // basic DOM order\n if (forward) {\n return focusableNodes\n .slice(focusableNodes.indexOf(node) + 1)\n .find((el) => isTabbable(el));\n }\n\n return focusableNodes\n .slice(0, focusableNodes.indexOf(node))\n .reverse()\n .find((el) => isTabbable(el));\n }\n\n return tabbableNodes[nodeIdx + (forward ? 1 : -1)];\n },\n };\n });\n\n state.tabbableGroups = state.containerGroups.filter(\n (group) => group.tabbableNodes.length > 0\n );\n\n // throw if no groups have tabbable nodes and we don't have a fallback focus node either\n if (\n state.tabbableGroups.length <= 0 &&\n !getNodeForOption('fallbackFocus') // returning false not supported for this option\n ) {\n throw new Error(\n 'Your focus-trap must have at least one container with at least one tabbable node in it at all times'\n );\n }\n\n // NOTE: Positive tabindexes are only properly supported in single-container traps because\n // doing it across multiple containers where tabindexes could be all over the place\n // would require Tabbable to support multiple containers, would require additional\n // specialized Shadow DOM support, and would require Tabbable's multi-container support\n // to look at those containers in document position order rather than user-provided\n // order (as they are treated in Focus-trap, for legacy reasons). See discussion on\n // https://github.com/focus-trap/focus-trap/issues/375 for more details.\n if (\n state.containerGroups.find((g) => g.posTabIndexesFound) &&\n state.containerGroups.length > 1\n ) {\n throw new Error(\n \"At least one node with a positive tabindex was found in one of your focus-trap's multiple containers. Positive tabindexes are only supported in single-container focus-traps.\"\n );\n }\n };\n\n /**\n * Gets the current activeElement. If it's a web-component and has open shadow-root\n * it will recursively search inside shadow roots for the \"true\" activeElement.\n *\n * @param {Document | ShadowRoot} el\n *\n * @returns {HTMLElement} The element that currently has the focus\n **/\n const getActiveElement = function (el) {\n const activeElement = el.activeElement;\n\n if (!activeElement) {\n return;\n }\n\n if (\n activeElement.shadowRoot &&\n activeElement.shadowRoot.activeElement !== null\n ) {\n return getActiveElement(activeElement.shadowRoot);\n }\n\n return activeElement;\n };\n\n const tryFocus = function (node) {\n if (node === false) {\n return;\n }\n\n if (node === getActiveElement(document)) {\n return;\n }\n\n if (!node || !node.focus) {\n tryFocus(getInitialFocusNode());\n return;\n }\n\n node.focus({ preventScroll: !!config.preventScroll });\n // NOTE: focus() API does not trigger focusIn event so set MRU node manually\n state.mostRecentlyFocusedNode = node;\n\n if (isSelectableInput(node)) {\n node.select();\n }\n };\n\n const getReturnFocusNode = function (previousActiveElement) {\n const node = getNodeForOption('setReturnFocus', previousActiveElement);\n return node ? node : node === false ? false : previousActiveElement;\n };\n\n /**\n * Finds the next node (in either direction) where focus should move according to a\n * keyboard focus-in event.\n * @param {Object} params\n * @param {Node} [params.target] Known target __from which__ to navigate, if any.\n * @param {KeyboardEvent|FocusEvent} [params.event] Event to use if `target` isn't known (event\n * will be used to determine the `target`). Ignored if `target` is specified.\n * @param {boolean} [params.isBackward] True if focus should move backward.\n * @returns {Node|undefined} The next node, or `undefined` if a next node couldn't be\n * determined given the current state of the trap.\n */\n const findNextNavNode = function ({ target, event, isBackward = false }) {\n target = target || getActualTarget(event);\n updateTabbableNodes();\n\n let destinationNode = null;\n\n if (state.tabbableGroups.length > 0) {\n // make sure the target is actually contained in a group\n // NOTE: the target may also be the container itself if it's focusable\n // with tabIndex='-1' and was given initial focus\n const containerIndex = findContainerIndex(target, event);\n const containerGroup =\n containerIndex >= 0 ? state.containerGroups[containerIndex] : undefined;\n\n if (containerIndex < 0) {\n // target not found in any group: quite possible focus has escaped the trap,\n // so bring it back into...\n if (isBackward) {\n // ...the last node in the last group\n destinationNode =\n state.tabbableGroups[state.tabbableGroups.length - 1]\n .lastTabbableNode;\n } else {\n // ...the first node in the first group\n destinationNode = state.tabbableGroups[0].firstTabbableNode;\n }\n } else if (isBackward) {\n // REVERSE\n\n // is the target the first tabbable node in a group?\n let startOfGroupIndex = findIndex(\n state.tabbableGroups,\n ({ firstTabbableNode }) => target === firstTabbableNode\n );\n\n if (\n startOfGroupIndex < 0 &&\n (containerGroup.container === target ||\n (isFocusable(target, config.tabbableOptions) &&\n !isTabbable(target, config.tabbableOptions) &&\n !containerGroup.nextTabbableNode(target, false)))\n ) {\n // an exception case where the target is either the container itself, or\n // a non-tabbable node that was given focus (i.e. tabindex is negative\n // and user clicked on it or node was programmatically given focus)\n // and is not followed by any other tabbable node, in which\n // case, we should handle shift+tab as if focus were on the container's\n // first tabbable node, and go to the last tabbable node of the LAST group\n startOfGroupIndex = containerIndex;\n }\n\n if (startOfGroupIndex >= 0) {\n // YES: then shift+tab should go to the last tabbable node in the\n // previous group (and wrap around to the last tabbable node of\n // the LAST group if it's the first tabbable node of the FIRST group)\n const destinationGroupIndex =\n startOfGroupIndex === 0\n ? state.tabbableGroups.length - 1\n : startOfGroupIndex - 1;\n\n const destinationGroup = state.tabbableGroups[destinationGroupIndex];\n\n destinationNode =\n getTabIndex(target) >= 0\n ? destinationGroup.lastTabbableNode\n : destinationGroup.lastDomTabbableNode;\n } else if (!isTabEvent(event)) {\n // user must have customized the nav keys so we have to move focus manually _within_\n // the active group: do this based on the order determined by tabbable()\n destinationNode = containerGroup.nextTabbableNode(target, false);\n }\n } else {\n // FORWARD\n\n // is the target the last tabbable node in a group?\n let lastOfGroupIndex = findIndex(\n state.tabbableGroups,\n ({ lastTabbableNode }) => target === lastTabbableNode\n );\n\n if (\n lastOfGroupIndex < 0 &&\n (containerGroup.container === target ||\n (isFocusable(target, config.tabbableOptions) &&\n !isTabbable(target, config.tabbableOptions) &&\n !containerGroup.nextTabbableNode(target)))\n ) {\n // an exception case where the target is the container itself, or\n // a non-tabbable node that was given focus (i.e. tabindex is negative\n // and user clicked on it or node was programmatically given focus)\n // and is not followed by any other tabbable node, in which\n // case, we should handle tab as if focus were on the container's\n // last tabbable node, and go to the first tabbable node of the FIRST group\n lastOfGroupIndex = containerIndex;\n }\n\n if (lastOfGroupIndex >= 0) {\n // YES: then tab should go to the first tabbable node in the next\n // group (and wrap around to the first tabbable node of the FIRST\n // group if it's the last tabbable node of the LAST group)\n const destinationGroupIndex =\n lastOfGroupIndex === state.tabbableGroups.length - 1\n ? 0\n : lastOfGroupIndex + 1;\n\n const destinationGroup = state.tabbableGroups[destinationGroupIndex];\n\n destinationNode =\n getTabIndex(target) >= 0\n ? destinationGroup.firstTabbableNode\n : destinationGroup.firstDomTabbableNode;\n } else if (!isTabEvent(event)) {\n // user must have customized the nav keys so we have to move focus manually _within_\n // the active group: do this based on the order determined by tabbable()\n destinationNode = containerGroup.nextTabbableNode(target);\n }\n }\n } else {\n // no groups available\n // NOTE: the fallbackFocus option does not support returning false to opt-out\n destinationNode = getNodeForOption('fallbackFocus');\n }\n\n return destinationNode;\n };\n\n // This needs to be done on mousedown and touchstart instead of click\n // so that it precedes the focus event.\n const checkPointerDown = function (e) {\n const target = getActualTarget(e);\n\n if (findContainerIndex(target, e) >= 0) {\n // allow the click since it ocurred inside the trap\n return;\n }\n\n if (valueOrHandler(config.clickOutsideDeactivates, e)) {\n // immediately deactivate the trap\n trap.deactivate({\n // NOTE: by setting `returnFocus: false`, deactivate() will do nothing,\n // which will result in the outside click setting focus to the node\n // that was clicked (and if not focusable, to \"nothing\"); by setting\n // `returnFocus: true`, we'll attempt to re-focus the node originally-focused\n // on activation (or the configured `setReturnFocus` node), whether the\n // outside click was on a focusable node or not\n returnFocus: config.returnFocusOnDeactivate,\n });\n return;\n }\n\n // This is needed for mobile devices.\n // (If we'll only let `click` events through,\n // then on mobile they will be blocked anyways if `touchstart` is blocked.)\n if (valueOrHandler(config.allowOutsideClick, e)) {\n // allow the click outside the trap to take place\n return;\n }\n\n // otherwise, prevent the click\n e.preventDefault();\n };\n\n // In case focus escapes the trap for some strange reason, pull it back in.\n // NOTE: the focusIn event is NOT cancelable, so if focus escapes, it may cause unexpected\n // scrolling if the node that got focused was out of view; there's nothing we can do to\n // prevent that from happening by the time we discover that focus escaped\n const checkFocusIn = function (event) {\n const target = getActualTarget(event);\n const targetContained = findContainerIndex(target, event) >= 0;\n\n // In Firefox when you Tab out of an iframe the Document is briefly focused.\n if (targetContained || target instanceof Document) {\n if (targetContained) {\n state.mostRecentlyFocusedNode = target;\n }\n } else {\n // escaped! pull it back in to where it just left\n event.stopImmediatePropagation();\n\n // focus will escape if the MRU node had a positive tab index and user tried to nav forward;\n // it will also escape if the MRU node had a 0 tab index and user tried to nav backward\n // toward a node with a positive tab index\n let nextNode; // next node to focus, if we find one\n let navAcrossContainers = true;\n if (state.mostRecentlyFocusedNode) {\n if (getTabIndex(state.mostRecentlyFocusedNode) > 0) {\n // MRU container index must be >=0 otherwise we wouldn't have it as an MRU node...\n const mruContainerIdx = findContainerIndex(\n state.mostRecentlyFocusedNode\n );\n // there MAY not be any tabbable nodes in the container if there are at least 2 containers\n // and the MRU node is focusable but not tabbable (focus-trap requires at least 1 container\n // with at least one tabbable node in order to function, so this could be the other container\n // with nothing tabbable in it)\n const { tabbableNodes } = state.containerGroups[mruContainerIdx];\n if (tabbableNodes.length > 0) {\n // MRU tab index MAY not be found if the MRU node is focusable but not tabbable\n const mruTabIdx = tabbableNodes.findIndex(\n (node) => node === state.mostRecentlyFocusedNode\n );\n if (mruTabIdx >= 0) {\n if (config.isKeyForward(state.recentNavEvent)) {\n if (mruTabIdx + 1 < tabbableNodes.length) {\n nextNode = tabbableNodes[mruTabIdx + 1];\n navAcrossContainers = false;\n }\n // else, don't wrap within the container as focus should move to next/previous\n // container\n } else {\n if (mruTabIdx - 1 >= 0) {\n nextNode = tabbableNodes[mruTabIdx - 1];\n navAcrossContainers = false;\n }\n // else, don't wrap within the container as focus should move to next/previous\n // container\n }\n // else, don't find in container order without considering direction too\n }\n }\n // else, no tabbable nodes in that container (which means we must have at least one other\n // container with at least one tabbable node in it, otherwise focus-trap would've thrown\n // an error the last time updateTabbableNodes() was run): find next node among all known\n // containers\n } else {\n // check to see if there's at least one tabbable node with a positive tab index inside\n // the trap because focus seems to escape when navigating backward from a tabbable node\n // with tabindex=0 when this is the case (instead of wrapping to the tabbable node with\n // the greatest positive tab index like it should)\n if (\n !state.containerGroups.some((g) =>\n g.tabbableNodes.some((n) => getTabIndex(n) > 0)\n )\n ) {\n // no containers with tabbable nodes with positive tab indexes which means the focus\n // escaped for some other reason and we should just execute the fallback to the\n // MRU node or initial focus node, if any\n navAcrossContainers = false;\n }\n }\n } else {\n // no MRU node means we're likely in some initial condition when the trap has just\n // been activated and initial focus hasn't been given yet, in which case we should\n // fall through to trying to focus the initial focus node, which is what should\n // happen below at this point in the logic\n navAcrossContainers = false;\n }\n\n if (navAcrossContainers) {\n nextNode = findNextNavNode({\n // move FROM the MRU node, not event-related node (which will be the node that is\n // outside the trap causing the focus escape we're trying to fix)\n target: state.mostRecentlyFocusedNode,\n isBackward: config.isKeyBackward(state.recentNavEvent),\n });\n }\n\n if (nextNode) {\n tryFocus(nextNode);\n } else {\n tryFocus(state.mostRecentlyFocusedNode || getInitialFocusNode());\n }\n }\n\n state.recentNavEvent = undefined; // clear\n };\n\n // Hijack key nav events on the first and last focusable nodes of the trap,\n // in order to prevent focus from escaping. If it escapes for even a\n // moment it can end up scrolling the page and causing confusion so we\n // kind of need to capture the action at the keydown phase.\n const checkKeyNav = function (event, isBackward = false) {\n state.recentNavEvent = event;\n\n const destinationNode = findNextNavNode({ event, isBackward });\n if (destinationNode) {\n if (isTabEvent(event)) {\n // since tab natively moves focus, we wouldn't have a destination node unless we\n // were on the edge of a container and had to move to the next/previous edge, in\n // which case we want to prevent default to keep the browser from moving focus\n // to where it normally would\n event.preventDefault();\n }\n tryFocus(destinationNode);\n }\n // else, let the browser take care of [shift+]tab and move the focus\n };\n\n const checkKey = function (event) {\n if (\n isEscapeEvent(event) &&\n valueOrHandler(config.escapeDeactivates, event) !== false\n ) {\n event.preventDefault();\n trap.deactivate();\n return;\n }\n\n if (config.isKeyForward(event) || config.isKeyBackward(event)) {\n checkKeyNav(event, config.isKeyBackward(event));\n }\n };\n\n const checkClick = function (e) {\n const target = getActualTarget(e);\n\n if (findContainerIndex(target, e) >= 0) {\n return;\n }\n\n if (valueOrHandler(config.clickOutsideDeactivates, e)) {\n return;\n }\n\n if (valueOrHandler(config.allowOutsideClick, e)) {\n return;\n }\n\n e.preventDefault();\n e.stopImmediatePropagation();\n };\n\n //\n // EVENT LISTENERS\n //\n\n const addListeners = function () {\n if (!state.active) {\n return;\n }\n\n // There can be only one listening focus trap at a time\n activeFocusTraps.activateTrap(trapStack, trap);\n\n // Delay ensures that the focused element doesn't capture the event\n // that caused the focus trap activation.\n state.delayInitialFocusTimer = config.delayInitialFocus\n ? delay(function () {\n tryFocus(getInitialFocusNode());\n })\n : tryFocus(getInitialFocusNode());\n\n doc.addEventListener('focusin', checkFocusIn, true);\n doc.addEventListener('mousedown', checkPointerDown, {\n capture: true,\n passive: false,\n });\n doc.addEventListener('touchstart', checkPointerDown, {\n capture: true,\n passive: false,\n });\n doc.addEventListener('click', checkClick, {\n capture: true,\n passive: false,\n });\n doc.addEventListener('keydown', checkKey, {\n capture: true,\n passive: false,\n });\n\n return trap;\n };\n\n const removeListeners = function () {\n if (!state.active) {\n return;\n }\n\n doc.removeEventListener('focusin', checkFocusIn, true);\n doc.removeEventListener('mousedown', checkPointerDown, true);\n doc.removeEventListener('touchstart', checkPointerDown, true);\n doc.removeEventListener('click', checkClick, true);\n doc.removeEventListener('keydown', checkKey, true);\n\n return trap;\n };\n\n //\n // MUTATION OBSERVER\n //\n\n const checkDomRemoval = function (mutations) {\n const isFocusedNodeRemoved = mutations.some(function (mutation) {\n const removedNodes = Array.from(mutation.removedNodes);\n return removedNodes.some(function (node) {\n return node === state.mostRecentlyFocusedNode;\n });\n });\n\n // If the currently focused is removed then browsers will move focus to the\n // element. If this happens, try to move focus back into the trap.\n if (isFocusedNodeRemoved) {\n tryFocus(getInitialFocusNode());\n }\n };\n\n // Use MutationObserver - if supported - to detect if focused node is removed\n // from the DOM.\n const mutationObserver =\n typeof window !== 'undefined' && 'MutationObserver' in window\n ? new MutationObserver(checkDomRemoval)\n : undefined;\n\n const updateObservedNodes = function () {\n if (!mutationObserver) {\n return;\n }\n\n mutationObserver.disconnect();\n if (state.active && !state.paused) {\n state.containers.map(function (container) {\n mutationObserver.observe(container, {\n subtree: true,\n childList: true,\n });\n });\n }\n };\n\n //\n // TRAP DEFINITION\n //\n\n trap = {\n get active() {\n return state.active;\n },\n\n get paused() {\n return state.paused;\n },\n\n activate(activateOptions) {\n if (state.active) {\n return this;\n }\n\n const onActivate = getOption(activateOptions, 'onActivate');\n const onPostActivate = getOption(activateOptions, 'onPostActivate');\n const checkCanFocusTrap = getOption(activateOptions, 'checkCanFocusTrap');\n\n if (!checkCanFocusTrap) {\n updateTabbableNodes();\n }\n\n state.active = true;\n state.paused = false;\n state.nodeFocusedBeforeActivation = doc.activeElement;\n\n onActivate?.();\n\n const finishActivation = () => {\n if (checkCanFocusTrap) {\n updateTabbableNodes();\n }\n addListeners();\n updateObservedNodes();\n onPostActivate?.();\n };\n\n if (checkCanFocusTrap) {\n checkCanFocusTrap(state.containers.concat()).then(\n finishActivation,\n finishActivation\n );\n return this;\n }\n\n finishActivation();\n return this;\n },\n\n deactivate(deactivateOptions) {\n if (!state.active) {\n return this;\n }\n\n const options = {\n onDeactivate: config.onDeactivate,\n onPostDeactivate: config.onPostDeactivate,\n checkCanReturnFocus: config.checkCanReturnFocus,\n ...deactivateOptions,\n };\n\n clearTimeout(state.delayInitialFocusTimer); // noop if undefined\n state.delayInitialFocusTimer = undefined;\n\n removeListeners();\n state.active = false;\n state.paused = false;\n updateObservedNodes();\n\n activeFocusTraps.deactivateTrap(trapStack, trap);\n\n const onDeactivate = getOption(options, 'onDeactivate');\n const onPostDeactivate = getOption(options, 'onPostDeactivate');\n const checkCanReturnFocus = getOption(options, 'checkCanReturnFocus');\n const returnFocus = getOption(\n options,\n 'returnFocus',\n 'returnFocusOnDeactivate'\n );\n\n onDeactivate?.();\n\n const finishDeactivation = () => {\n delay(() => {\n if (returnFocus) {\n tryFocus(getReturnFocusNode(state.nodeFocusedBeforeActivation));\n }\n onPostDeactivate?.();\n });\n };\n\n if (returnFocus && checkCanReturnFocus) {\n checkCanReturnFocus(\n getReturnFocusNode(state.nodeFocusedBeforeActivation)\n ).then(finishDeactivation, finishDeactivation);\n return this;\n }\n\n finishDeactivation();\n return this;\n },\n\n pause(pauseOptions) {\n if (state.paused || !state.active) {\n return this;\n }\n\n const onPause = getOption(pauseOptions, 'onPause');\n const onPostPause = getOption(pauseOptions, 'onPostPause');\n\n state.paused = true;\n onPause?.();\n\n removeListeners();\n updateObservedNodes();\n\n onPostPause?.();\n return this;\n },\n\n unpause(unpauseOptions) {\n if (!state.paused || !state.active) {\n return this;\n }\n\n const onUnpause = getOption(unpauseOptions, 'onUnpause');\n const onPostUnpause = getOption(unpauseOptions, 'onPostUnpause');\n\n state.paused = false;\n onUnpause?.();\n\n updateTabbableNodes();\n addListeners();\n updateObservedNodes();\n\n onPostUnpause?.();\n return this;\n },\n\n updateContainerElements(containerElements) {\n const elementsAsArray = [].concat(containerElements).filter(Boolean);\n\n state.containers = elementsAsArray.map((element) =>\n typeof element === 'string' ? doc.querySelector(element) : element\n );\n\n if (state.active) {\n updateTabbableNodes();\n }\n\n updateObservedNodes();\n\n return this;\n },\n };\n\n // initialize container elements\n trap.updateContainerElements(elements);\n\n return trap;\n};\n\nexport { createFocusTrap };\n", null, null, null, "function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }\n\n// Older browsers don't support event options, feature detect it.\n\n// Adopted and modified solution from Bohdan Didukh (2017)\n// https://stackoverflow.com/questions/41594997/ios-10-safari-prevent-scrolling-behind-a-fixed-overlay-and-maintain-scroll-posi\n\nvar hasPassiveEvents = false;\nif (typeof window !== 'undefined') {\n var passiveTestOptions = {\n get passive() {\n hasPassiveEvents = true;\n return undefined;\n }\n };\n window.addEventListener('testPassive', null, passiveTestOptions);\n window.removeEventListener('testPassive', null, passiveTestOptions);\n}\n\nvar isIosDevice = typeof window !== 'undefined' && window.navigator && window.navigator.platform && (/iP(ad|hone|od)/.test(window.navigator.platform) || window.navigator.platform === 'MacIntel' && window.navigator.maxTouchPoints > 1);\n\n\nvar locks = [];\nvar documentListenerAdded = false;\nvar initialClientY = -1;\nvar previousBodyOverflowSetting = void 0;\nvar previousBodyPosition = void 0;\nvar previousBodyPaddingRight = void 0;\n\n// returns true if `el` should be allowed to receive touchmove events.\nvar allowTouchMove = function allowTouchMove(el) {\n return locks.some(function (lock) {\n if (lock.options.allowTouchMove && lock.options.allowTouchMove(el)) {\n return true;\n }\n\n return false;\n });\n};\n\nvar preventDefault = function preventDefault(rawEvent) {\n var e = rawEvent || window.event;\n\n // For the case whereby consumers adds a touchmove event listener to document.\n // Recall that we do document.addEventListener('touchmove', preventDefault, { passive: false })\n // in disableBodyScroll - so if we provide this opportunity to allowTouchMove, then\n // the touchmove event on document will break.\n if (allowTouchMove(e.target)) {\n return true;\n }\n\n // Do not prevent if the event has more than one touch (usually meaning this is a multi touch gesture like pinch to zoom).\n if (e.touches.length > 1) return true;\n\n if (e.preventDefault) e.preventDefault();\n\n return false;\n};\n\nvar setOverflowHidden = function setOverflowHidden(options) {\n // If previousBodyPaddingRight is already set, don't set it again.\n if (previousBodyPaddingRight === undefined) {\n var _reserveScrollBarGap = !!options && options.reserveScrollBarGap === true;\n var scrollBarGap = window.innerWidth - document.documentElement.clientWidth;\n\n if (_reserveScrollBarGap && scrollBarGap > 0) {\n var computedBodyPaddingRight = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'), 10);\n previousBodyPaddingRight = document.body.style.paddingRight;\n document.body.style.paddingRight = computedBodyPaddingRight + scrollBarGap + 'px';\n }\n }\n\n // If previousBodyOverflowSetting is already set, don't set it again.\n if (previousBodyOverflowSetting === undefined) {\n previousBodyOverflowSetting = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n }\n};\n\nvar restoreOverflowSetting = function restoreOverflowSetting() {\n if (previousBodyPaddingRight !== undefined) {\n document.body.style.paddingRight = previousBodyPaddingRight;\n\n // Restore previousBodyPaddingRight to undefined so setOverflowHidden knows it\n // can be set again.\n previousBodyPaddingRight = undefined;\n }\n\n if (previousBodyOverflowSetting !== undefined) {\n document.body.style.overflow = previousBodyOverflowSetting;\n\n // Restore previousBodyOverflowSetting to undefined\n // so setOverflowHidden knows it can be set again.\n previousBodyOverflowSetting = undefined;\n }\n};\n\nvar setPositionFixed = function setPositionFixed() {\n return window.requestAnimationFrame(function () {\n // If previousBodyPosition is already set, don't set it again.\n if (previousBodyPosition === undefined) {\n previousBodyPosition = {\n position: document.body.style.position,\n top: document.body.style.top,\n left: document.body.style.left\n };\n\n // Update the dom inside an animation frame \n var _window = window,\n scrollY = _window.scrollY,\n scrollX = _window.scrollX,\n innerHeight = _window.innerHeight;\n\n document.body.style.position = 'fixed';\n document.body.style.top = -scrollY;\n document.body.style.left = -scrollX;\n\n setTimeout(function () {\n return window.requestAnimationFrame(function () {\n // Attempt to check if the bottom bar appeared due to the position change\n var bottomBarHeight = innerHeight - window.innerHeight;\n if (bottomBarHeight && scrollY >= innerHeight) {\n // Move the content further up so that the bottom bar doesn't hide it\n document.body.style.top = -(scrollY + bottomBarHeight);\n }\n });\n }, 300);\n }\n });\n};\n\nvar restorePositionSetting = function restorePositionSetting() {\n if (previousBodyPosition !== undefined) {\n // Convert the position from \"px\" to Int\n var y = -parseInt(document.body.style.top, 10);\n var x = -parseInt(document.body.style.left, 10);\n\n // Restore styles\n document.body.style.position = previousBodyPosition.position;\n document.body.style.top = previousBodyPosition.top;\n document.body.style.left = previousBodyPosition.left;\n\n // Restore scroll\n window.scrollTo(x, y);\n\n previousBodyPosition = undefined;\n }\n};\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Problems_and_solutions\nvar isTargetElementTotallyScrolled = function isTargetElementTotallyScrolled(targetElement) {\n return targetElement ? targetElement.scrollHeight - targetElement.scrollTop <= targetElement.clientHeight : false;\n};\n\nvar handleScroll = function handleScroll(event, targetElement) {\n var clientY = event.targetTouches[0].clientY - initialClientY;\n\n if (allowTouchMove(event.target)) {\n return false;\n }\n\n if (targetElement && targetElement.scrollTop === 0 && clientY > 0) {\n // element is at the top of its scroll.\n return preventDefault(event);\n }\n\n if (isTargetElementTotallyScrolled(targetElement) && clientY < 0) {\n // element is at the bottom of its scroll.\n return preventDefault(event);\n }\n\n event.stopPropagation();\n return true;\n};\n\nexport var disableBodyScroll = function disableBodyScroll(targetElement, options) {\n // targetElement must be provided\n if (!targetElement) {\n // eslint-disable-next-line no-console\n console.error('disableBodyScroll unsuccessful - targetElement must be provided when calling disableBodyScroll on IOS devices.');\n return;\n }\n\n // disableBodyScroll must not have been called on this targetElement before\n if (locks.some(function (lock) {\n return lock.targetElement === targetElement;\n })) {\n return;\n }\n\n var lock = {\n targetElement: targetElement,\n options: options || {}\n };\n\n locks = [].concat(_toConsumableArray(locks), [lock]);\n\n if (isIosDevice) {\n setPositionFixed();\n } else {\n setOverflowHidden(options);\n }\n\n if (isIosDevice) {\n targetElement.ontouchstart = function (event) {\n if (event.targetTouches.length === 1) {\n // detect single touch.\n initialClientY = event.targetTouches[0].clientY;\n }\n };\n targetElement.ontouchmove = function (event) {\n if (event.targetTouches.length === 1) {\n // detect single touch.\n handleScroll(event, targetElement);\n }\n };\n\n if (!documentListenerAdded) {\n document.addEventListener('touchmove', preventDefault, hasPassiveEvents ? { passive: false } : undefined);\n documentListenerAdded = true;\n }\n }\n};\n\nexport var clearAllBodyScrollLocks = function clearAllBodyScrollLocks() {\n if (isIosDevice) {\n // Clear all locks ontouchstart/ontouchmove handlers, and the references.\n locks.forEach(function (lock) {\n lock.targetElement.ontouchstart = null;\n lock.targetElement.ontouchmove = null;\n });\n\n if (documentListenerAdded) {\n document.removeEventListener('touchmove', preventDefault, hasPassiveEvents ? { passive: false } : undefined);\n documentListenerAdded = false;\n }\n\n // Reset initial clientY.\n initialClientY = -1;\n }\n\n if (isIosDevice) {\n restorePositionSetting();\n } else {\n restoreOverflowSetting();\n }\n\n locks = [];\n};\n\nexport var enableBodyScroll = function enableBodyScroll(targetElement) {\n if (!targetElement) {\n // eslint-disable-next-line no-console\n console.error('enableBodyScroll unsuccessful - targetElement must be provided when calling enableBodyScroll on IOS devices.');\n return;\n }\n\n locks = locks.filter(function (lock) {\n return lock.targetElement !== targetElement;\n });\n\n if (isIosDevice) {\n targetElement.ontouchstart = null;\n targetElement.ontouchmove = null;\n\n if (documentListenerAdded && locks.length === 0) {\n document.removeEventListener('touchmove', preventDefault, hasPassiveEvents ? { passive: false } : undefined);\n documentListenerAdded = false;\n }\n }\n\n if (isIosDevice) {\n restorePositionSetting();\n } else {\n restoreOverflowSetting();\n }\n};\n\n", null, null, "'use client'\nimport type { ClientUser, SanitizedPermissions, TypedUser } from 'payload'\n\nimport { useModal } from '@faceless-ui/modal'\nimport { usePathname, useRouter } from 'next/navigation.js'\nimport { formatAdminURL } from 'payload/shared'\nimport * as qs from 'qs-esm'\nimport React, { createContext, use, useCallback, useEffect, useState } from 'react'\nimport { toast } from 'sonner'\n\nimport { stayLoggedInModalSlug } from '../../elements/StayLoggedIn/index.js'\nimport { useEffectEvent } from '../../hooks/useEffectEvent.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { requests } from '../../utilities/api.js'\nimport { useConfig } from '../Config/index.js'\nimport { useRouteTransition } from '../RouteTransition/index.js'\n\nexport type UserWithToken = {\n /** seconds until expiration */\n exp: number\n token: string\n user: T\n}\n\nexport type AuthContext = {\n fetchFullUser: () => Promise\n logOut: () => Promise\n /**\n * These are the permissions for the current user from a global scope.\n *\n * When checking for permissions on document specific level, use the `useDocumentInfo` hook instead.\n *\n * @example\n *\n * ```tsx\n * import { useAuth } from 'payload/ui'\n *\n * const MyComponent: React.FC = () => {\n * const { permissions } = useAuth()\n *\n * if (permissions?.collections?.myCollection?.create) {\n * // user can create documents in 'myCollection'\n * }\n *\n * return null\n * }\n * ```\n *\n * with useDocumentInfo:\n *\n * ```tsx\n * import { useDocumentInfo } from 'payload/ui'\n *\n * const MyComponent: React.FC = () => {\n * const { docPermissions } = useDocumentInfo()\n * if (docPermissions?.create) {\n * // user can create this document\n * }\n * return null\n * } ```\n */\n permissions?: SanitizedPermissions\n refreshCookie: (forceRefresh?: boolean) => void\n refreshCookieAsync: () => Promise\n refreshPermissions: () => Promise\n setPermissions: (permissions: SanitizedPermissions) => void\n setUser: (user: null | UserWithToken) => void\n strategy?: string\n token?: string\n tokenExpirationMs?: number\n user?: null | T\n}\n\nconst Context = createContext({} as AuthContext)\n\nconst maxTimeoutMs = 2147483647\n\ntype Props = {\n children: React.ReactNode\n permissions?: SanitizedPermissions\n user?: ClientUser | null\n}\n\nexport function AuthProvider({\n children,\n permissions: initialPermissions,\n user: initialUser,\n}: Props) {\n const pathname = usePathname()\n const router = useRouter()\n\n const { config } = useConfig()\n\n const {\n admin: {\n autoLogin,\n autoRefresh,\n routes: { inactivity: logoutInactivityRoute },\n user: userSlug,\n },\n routes: { admin: adminRoute, api: apiRoute },\n } = config\n\n const { i18n } = useTranslation()\n const { closeAllModals, openModal } = useModal()\n const { startRouteTransition } = useRouteTransition()\n\n const [user, setUserInMemory] = useState(initialUser)\n const [tokenInMemory, setTokenInMemory] = useState()\n const [tokenExpirationMs, setTokenExpirationMs] = useState()\n const [permissions, setPermissions] = useState(initialPermissions)\n const [forceLogoutBufferMs, setForceLogoutBufferMs] = useState(120_000)\n const [fetchedUserOnMount, setFetchedUserOnMount] = useState(false)\n\n const refreshTokenTimeoutRef = React.useRef>(null)\n const reminderTimeoutRef = React.useRef>(null)\n const forceLogOutTimeoutRef = React.useRef>(null)\n\n const id = user?.id\n\n const redirectToInactivityRoute = useCallback(() => {\n const baseAdminRoute = formatAdminURL({ adminRoute, path: '' })\n startRouteTransition(() =>\n router.replace(\n formatAdminURL({\n adminRoute,\n path: `${logoutInactivityRoute}${window.location.pathname.startsWith(baseAdminRoute) ? `?redirect=${encodeURIComponent(window.location.pathname)}` : ''}`,\n }),\n ),\n )\n\n closeAllModals()\n }, [router, adminRoute, logoutInactivityRoute, closeAllModals, startRouteTransition])\n\n const revokeTokenAndExpire = useCallback(() => {\n setUserInMemory(null)\n setTokenInMemory(undefined)\n setTokenExpirationMs(undefined)\n clearTimeout(refreshTokenTimeoutRef.current)\n }, [])\n\n // Handler for reminder timeout - uses useEffectEvent to capture latest autoRefresh value\n const handleReminderTimeout = useEffectEvent(() => {\n if (autoRefresh) {\n refreshCookieEvent()\n } else {\n openModal(stayLoggedInModalSlug)\n }\n })\n\n const setNewUser = useCallback(\n (userResponse: null | UserWithToken) => {\n clearTimeout(reminderTimeoutRef.current)\n clearTimeout(forceLogOutTimeoutRef.current)\n\n if (userResponse?.user) {\n setUserInMemory(userResponse.user)\n setTokenInMemory(userResponse.token)\n setTokenExpirationMs(userResponse.exp * 1000)\n\n const expiresInMs = Math.max(\n 0,\n Math.min((userResponse.exp ?? 0) * 1000 - Date.now(), maxTimeoutMs),\n )\n\n if (expiresInMs) {\n const nextForceLogoutBufferMs = Math.min(60_000, expiresInMs / 2)\n setForceLogoutBufferMs(nextForceLogoutBufferMs)\n\n reminderTimeoutRef.current = setTimeout(\n handleReminderTimeout,\n Math.max(expiresInMs - nextForceLogoutBufferMs, 0),\n )\n\n forceLogOutTimeoutRef.current = setTimeout(() => {\n revokeTokenAndExpire()\n redirectToInactivityRoute()\n }, expiresInMs)\n }\n } else {\n revokeTokenAndExpire()\n }\n },\n [redirectToInactivityRoute, revokeTokenAndExpire],\n )\n\n const refreshCookie = useCallback(\n (forceRefresh?: boolean) => {\n if (!id) {\n return\n }\n\n const expiresInMs = Math.max(0, (tokenExpirationMs ?? 0) - Date.now())\n\n if (forceRefresh || (tokenExpirationMs && expiresInMs < forceLogoutBufferMs * 2)) {\n clearTimeout(refreshTokenTimeoutRef.current)\n refreshTokenTimeoutRef.current = setTimeout(async () => {\n try {\n const request = await requests.post(\n formatAdminURL({\n apiRoute,\n path: `/${userSlug}/refresh-token?refresh`,\n }),\n {\n headers: {\n 'Accept-Language': i18n.language,\n },\n },\n )\n\n if (request.status === 200) {\n const json: UserWithToken = await request.json()\n setNewUser(json)\n } else {\n setNewUser(null)\n redirectToInactivityRoute()\n }\n } catch (e) {\n toast.error(e.message)\n }\n }, 1000)\n }\n },\n [\n apiRoute,\n i18n.language,\n redirectToInactivityRoute,\n setNewUser,\n tokenExpirationMs,\n userSlug,\n forceLogoutBufferMs,\n id,\n ],\n )\n\n const refreshCookieAsync = useCallback(\n async (skipSetUser?: boolean): Promise => {\n try {\n const request = await requests.post(\n formatAdminURL({\n apiRoute,\n path: `/${userSlug}/refresh-token`,\n }),\n {\n headers: {\n 'Accept-Language': i18n.language,\n },\n },\n )\n\n if (request.status === 200) {\n const json: UserWithToken = await request.json()\n if (!skipSetUser) {\n setNewUser(json)\n }\n return json.user\n }\n\n if (user) {\n setNewUser(null)\n redirectToInactivityRoute()\n }\n } catch (e) {\n toast.error(`Refreshing token failed: ${e.message}`)\n }\n return null\n },\n [apiRoute, i18n.language, redirectToInactivityRoute, setNewUser, userSlug, user],\n )\n\n const logOut = useCallback(async () => {\n try {\n if (user && user.collection) {\n setNewUser(null)\n await requests.post(\n formatAdminURL({\n apiRoute,\n path: `/${user.collection}/logout`,\n }),\n )\n }\n } catch (_) {\n // fail silently and log the user out in state\n }\n\n return true\n }, [apiRoute, setNewUser, user])\n\n const refreshPermissions = useCallback(\n async ({ locale }: { locale?: string } = {}) => {\n const params = qs.stringify(\n {\n locale,\n },\n {\n addQueryPrefix: true,\n },\n )\n\n try {\n const request = await requests.get(\n formatAdminURL({\n apiRoute,\n path: `/access${params}`,\n }),\n {\n headers: {\n 'Accept-Language': i18n.language,\n },\n },\n )\n\n if (request.status === 200) {\n const json: SanitizedPermissions = await request.json()\n setPermissions(json)\n } else {\n throw new Error(`Fetching permissions failed with status code ${request.status}`)\n }\n } catch (e) {\n toast.error(`Refreshing permissions failed: ${e.message}`)\n }\n },\n [apiRoute, i18n],\n )\n\n const fetchFullUser = React.useCallback(async () => {\n try {\n const request = await requests.get(\n formatAdminURL({\n apiRoute,\n path: `/${userSlug}/me`,\n }),\n {\n credentials: 'include',\n headers: {\n 'Accept-Language': i18n.language,\n },\n },\n )\n\n if (request.status === 200) {\n const json: UserWithToken = await request.json()\n setNewUser(json)\n return json?.user || null\n }\n } catch (e) {\n toast.error(`Fetching user failed: ${e.message}`)\n }\n\n return null\n }, [apiRoute, userSlug, i18n.language, setNewUser])\n\n const refreshCookieEvent = useEffectEvent(refreshCookie)\n useEffect(() => {\n // when location changes, refresh cookie\n refreshCookieEvent()\n }, [pathname])\n\n const fetchFullUserEvent = useEffectEvent(fetchFullUser)\n useEffect(() => {\n async function fetchUserOnMount() {\n await fetchFullUserEvent()\n setFetchedUserOnMount(true)\n }\n\n void fetchUserOnMount()\n }, [])\n\n useEffect(() => {\n if (!user && autoLogin && !autoLogin.prefillOnly) {\n void fetchFullUserEvent()\n }\n }, [user, autoLogin])\n\n useEffect(\n () => () => {\n // remove all timeouts on unmount\n clearTimeout(refreshTokenTimeoutRef.current)\n clearTimeout(reminderTimeoutRef.current)\n clearTimeout(forceLogOutTimeoutRef.current)\n },\n [],\n )\n\n if (!user && !fetchedUserOnMount) {\n return null\n }\n\n return (\n \n {children}\n \n )\n}\n\nexport const useAuth = (): AuthContext => use(Context) as AuthContext\n", "'use client'\nimport { useRouter } from 'next/navigation.js'\nimport { formatAdminURL } from 'payload/shared'\nimport React, { useCallback } from 'react'\n\nimport type { OnCancel } from '../ConfirmationModal/index.js'\n\nimport { useAuth } from '../../providers/Auth/index.js'\nimport { useConfig } from '../../providers/Config/index.js'\nimport { useRouteTransition } from '../../providers/RouteTransition/index.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { ConfirmationModal } from '../ConfirmationModal/index.js'\n\nexport const stayLoggedInModalSlug = 'stay-logged-in'\n\nexport const StayLoggedInModal: React.FC = () => {\n const { refreshCookie } = useAuth()\n\n const router = useRouter()\n const { config } = useConfig()\n\n const {\n admin: {\n routes: { logout: logoutRoute },\n },\n routes: { admin: adminRoute },\n } = config\n\n const { t } = useTranslation()\n const { startRouteTransition } = useRouteTransition()\n\n const onConfirm = useCallback(() => {\n return startRouteTransition(() =>\n router.push(\n formatAdminURL({\n adminRoute,\n path: logoutRoute,\n }),\n ),\n )\n }, [router, startRouteTransition, adminRoute, logoutRoute])\n\n const onCancel: OnCancel = useCallback(() => {\n refreshCookie()\n }, [refreshCookie])\n\n return (\n \n )\n}\n", "'use client'\nimport { Modal, useModal } from '@faceless-ui/modal'\nimport React, { useCallback } from 'react'\n\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { Button } from '../Button/index.js'\nimport { drawerZBase, useDrawerDepth } from '../Drawer/index.js'\nimport './index.scss'\n\nconst baseClass = 'confirmation-modal'\n\nexport type OnCancel = () => void\n\nexport type ConfirmationModalProps = {\n body: React.ReactNode\n cancelLabel?: string\n className?: string\n confirmingLabel?: string\n confirmLabel?: string\n heading: React.ReactNode\n modalSlug: string\n onCancel?: OnCancel\n onConfirm: () => Promise | void\n}\n\nexport function ConfirmationModal(props: ConfirmationModalProps) {\n const {\n body,\n cancelLabel,\n className,\n confirmingLabel,\n confirmLabel,\n heading,\n modalSlug,\n onCancel: onCancelFromProps,\n onConfirm: onConfirmFromProps,\n } = props\n\n const editDepth = useDrawerDepth()\n\n const [confirming, setConfirming] = React.useState(false)\n\n const { closeModal, isModalOpen } = useModal()\n const { t } = useTranslation()\n\n const onConfirm = useCallback(async () => {\n if (!confirming) {\n setConfirming(true)\n\n if (typeof onConfirmFromProps === 'function') {\n await onConfirmFromProps()\n }\n\n setConfirming(false)\n closeModal(modalSlug)\n }\n }, [confirming, onConfirmFromProps, closeModal, modalSlug])\n\n const onCancel = useCallback(() => {\n if (!confirming) {\n closeModal(modalSlug)\n\n if (typeof onCancelFromProps === 'function') {\n onCancelFromProps()\n }\n }\n }, [confirming, onCancelFromProps, closeModal, modalSlug])\n\n if (!isModalOpen(modalSlug)) {\n return null\n }\n\n return (\n \n
\n
\n {typeof heading === 'string' ?

{heading}

: heading}\n {typeof body === 'string' ?

{body}

: body}\n
\n
\n \n {cancelLabel || t('general:cancel')}\n \n \n
\n
\n \n )\n}\n", "'use client'\nimport { Modal, useModal } from '@faceless-ui/modal'\nimport React, { createContext, use, useCallback, useLayoutEffect, useState } from 'react'\n\nimport type { Props, TogglerProps } from './types.js'\n\nimport { XIcon } from '../../icons/X/index.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { Gutter } from '../Gutter/index.js'\nimport './index.scss'\n\nconst baseClass = 'drawer'\n\nexport const drawerZBase = 100\n\nexport const formatDrawerSlug = ({ slug, depth }: { depth: number; slug: string }): string =>\n `drawer_${depth}_${slug}`\n\nexport { useDrawerSlug } from './useDrawerSlug.js'\n\nexport const DrawerToggler: React.FC = ({\n slug,\n children,\n className,\n disabled,\n onClick,\n ...rest\n}) => {\n const { openModal } = useModal()\n\n const handleClick = useCallback(\n (e) => {\n openModal(slug)\n if (typeof onClick === 'function') {\n onClick(e)\n }\n },\n [openModal, slug, onClick],\n )\n\n return (\n \n )\n}\n\nexport const Drawer: React.FC = ({\n slug,\n children,\n className,\n gutter = true,\n Header,\n hoverTitle,\n title,\n}) => {\n const { t } = useTranslation()\n const { closeModal, modalState } = useModal()\n const drawerDepth = useDrawerDepth()\n\n const isOpen = !!modalState[slug]?.isOpen\n\n const [animateIn, setAnimateIn] = useState(isOpen)\n\n useLayoutEffect(() => {\n setAnimateIn(isOpen)\n }, [isOpen])\n\n if (isOpen) {\n // IMPORTANT: do not render the drawer until it is explicitly open, this is to avoid large html trees especially when nesting drawers\n return (\n \n 1 && `${baseClass}--nested`,\n ]\n .filter(Boolean)\n .join(' ')}\n // Fixes https://github.com/payloadcms/payload/issues/13778\n closeOnBlur={false}\n slug={slug}\n style={{\n zIndex: drawerZBase + drawerDepth,\n }}\n >\n {(!drawerDepth || drawerDepth === 1) &&
}\n closeModal(slug)}\n type=\"button\"\n />\n \n
\n \n {Header}\n {Header === undefined && (\n
\n

\n {title}\n

\n {/* TODO: the `button` HTML element breaks CSS transitions on the drawer for some reason...\n i.e. changing to a `div` element will fix the animation issue but will break accessibility\n */}\n closeModal(slug)}\n type=\"button\"\n >\n \n \n
\n )}\n {children}\n
\n
\n \n \n )\n }\n\n return null\n}\n\nexport const DrawerDepthContext = createContext(1)\n\nexport const DrawerDepthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {\n const parentDepth = useDrawerDepth()\n const depth = parentDepth + 1\n\n return {children}\n}\n\nexport const useDrawerDepth = (): number => use(DrawerDepthContext)\n", "'use client'\nimport React from 'react'\n\nimport './index.scss'\n\nexport type GutterProps = {\n children: React.ReactNode\n className?: string\n left?: boolean\n negativeLeft?: boolean\n negativeRight?: boolean\n ref?: React.RefObject\n right?: boolean\n}\n\nconst baseClass = 'gutter'\n\nexport const Gutter: React.FC = (props) => {\n const {\n children,\n className,\n left = true,\n negativeLeft = false,\n negativeRight = false,\n ref,\n right = true,\n } = props\n\n const shouldPadLeft = left && !negativeLeft\n const shouldPadRight = right && !negativeRight\n\n return (\n \n {children}\n
\n )\n}\n", "'use client'\nimport { useId } from 'react'\n\nimport { useEditDepth } from '../../providers/EditDepth/index.js'\nimport { formatDrawerSlug } from './index.js'\n\nexport const useDrawerSlug = (slug: string): string => {\n const uuid = useId()\n const editDepth = useEditDepth()\n return formatDrawerSlug({\n slug: `${slug}-${uuid}`,\n depth: editDepth,\n })\n}\n", "import * as qs from 'qs-esm'\n\ntype GetOptions = {\n params?: Record\n} & RequestInit\n\nexport const requests = {\n delete: (url: string, options: RequestInit = { headers: {} }): Promise => {\n const headers = options && options.headers ? { ...options.headers } : {}\n\n const formattedOptions: RequestInit = {\n ...options,\n credentials: 'include',\n headers: {\n ...headers,\n },\n method: 'delete',\n }\n\n return fetch(url, formattedOptions)\n },\n\n get: (url: string, options: GetOptions = { headers: {} }): Promise => {\n let query = ''\n if (options.params) {\n query = qs.stringify(options.params, { addQueryPrefix: true })\n }\n return fetch(`${url}${query}`, {\n credentials: 'include',\n ...options,\n })\n },\n\n patch: (url: string, options: RequestInit = { headers: {} }): Promise => {\n const headers = options && options.headers ? { ...options.headers } : {}\n\n const formattedOptions: RequestInit = {\n ...options,\n credentials: 'include',\n headers: {\n ...headers,\n },\n method: 'PATCH',\n }\n\n return fetch(url, formattedOptions)\n },\n\n post: (url: string, options: RequestInit = { headers: {} }): Promise => {\n const headers = options && options.headers ? { ...options.headers } : {}\n\n const formattedOptions: RequestInit = {\n ...options,\n credentials: 'include',\n headers: {\n ...headers,\n },\n method: 'post',\n }\n\n return fetch(`${url}`, formattedOptions)\n },\n\n put: (url: string, options: RequestInit = { headers: {} }): Promise => {\n const headers = options && options.headers ? { ...options.headers } : {}\n\n const formattedOptions: RequestInit = {\n ...options,\n credentials: 'include',\n headers: {\n ...headers,\n },\n method: 'put',\n }\n\n return fetch(url, formattedOptions)\n },\n}\n", "export const generateFieldID = (path: string, editDepth: number, uuid: string) => {\n if (!path) {\n return undefined\n }\n return `field-${path.replace(/\\./g, '__')}${editDepth > 1 ? `-${editDepth}` : ''}${uuid ? `-${uuid}` : ''}`\n}\n", "'use client'\nimport type { Row } from 'payload'\n\nexport const extractRowsAndCollapsedIDs = ({\n collapsed,\n rowID,\n rows,\n}: {\n collapsed: boolean\n rowID: string\n rows: Row[]\n}): {\n collapsedIDs: string[]\n updatedRows: Row[]\n} => {\n return rows.reduce(\n (acc, row) => {\n if (rowID === row.id) {\n row.collapsed = collapsed\n }\n if (row.collapsed) {\n acc.collapsedIDs.push(row.id)\n }\n acc.updatedRows.push(row)\n return acc\n },\n {\n collapsedIDs: [],\n updatedRows: [],\n },\n )\n}\n\nexport const toggleAllRows = ({\n collapsed,\n rows,\n}): {\n collapsedIDs: string[]\n updatedRows: Row[]\n} => {\n return rows.reduce(\n (acc, row) => {\n row.collapsed = collapsed\n if (collapsed) {\n acc.collapsedIDs.push(row.id)\n }\n acc.updatedRows.push(row)\n return acc\n },\n {\n collapsedIDs: [],\n updatedRows: [],\n },\n )\n}\n", "'use client'\n\nimport * as React from 'react'\n\nimport { Banner } from '../../elements/Banner/index.js'\nimport { CheckboxField } from '../../fields/Checkbox/index.js'\nimport { useConfig } from '../../providers/Config/index.js'\nimport { useLocale } from '../../providers/Locale/index.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { useForm } from '../Form/context.js'\nimport './index.scss'\n\nconst baseClass = 'nullify-locale-field'\n\ntype NullifyLocaleFieldProps = {\n readonly fieldValue?: [] | null | number\n readonly localized: boolean\n readonly path: string\n readonly readOnly?: boolean\n}\n\nexport const NullifyLocaleField: React.FC = ({\n fieldValue,\n localized,\n path,\n readOnly = false,\n}) => {\n const { code: currentLocale } = useLocale()\n const {\n config: { localization },\n } = useConfig()\n const [checked, setChecked] = React.useState(typeof fieldValue !== 'number')\n const { t } = useTranslation()\n const { dispatchFields, setModified } = useForm()\n\n if (!localized || !localization) {\n // hide when field is not localized or localization is not enabled\n return null\n }\n\n if (localization.defaultLocale === currentLocale || !localization.fallback) {\n // if editing default locale or when fallback is disabled\n return null\n }\n\n const onChange = () => {\n const useFallback = !checked\n\n dispatchFields({\n type: 'UPDATE',\n path,\n value: useFallback ? null : fieldValue || 0,\n })\n setModified(true)\n setChecked(useFallback)\n }\n\n if (fieldValue) {\n let hideCheckbox = false\n if (typeof fieldValue === 'number' && fieldValue > 0) {\n hideCheckbox = true\n }\n if (Array.isArray(fieldValue) && fieldValue.length > 0) {\n hideCheckbox = true\n }\n\n if (hideCheckbox) {\n if (checked) {\n setChecked(false)\n } // uncheck when field has value\n return null\n }\n }\n\n return (\n \n {!fieldValue && readOnly ? (\n t('general:fallbackToDefaultLocale')\n ) : (\n \n )}\n \n )\n}\n", "'use client'\nimport type {\n CheckboxFieldClientComponent,\n CheckboxFieldClientProps,\n CheckboxFieldValidation,\n} from 'payload'\n\nimport { rtlLanguages } from '@payloadcms/translations'\nimport React, { useCallback, useMemo } from 'react'\n\nimport type { CheckboxInputProps } from './Input.js'\n\nimport { RenderCustomComponent } from '../../elements/RenderCustomComponent/index.js'\nimport { FieldDescription } from '../../fields/FieldDescription/index.js'\nimport { FieldError } from '../../fields/FieldError/index.js'\nimport { useForm } from '../../forms/Form/context.js'\nimport { useField } from '../../forms/useField/index.js'\nimport { withCondition } from '../../forms/withCondition/index.js'\nimport { useEditDepth } from '../../providers/EditDepth/index.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { generateFieldID } from '../../utilities/generateFieldID.js'\nimport { mergeFieldStyles } from '../mergeFieldStyles.js'\nimport { fieldBaseClass } from '../shared/index.js'\nimport { CheckboxInput } from './Input.js'\nimport './index.scss'\n\nconst baseClass = 'checkbox'\n\nexport { CheckboxFieldClientProps, CheckboxInput, type CheckboxInputProps }\n\nconst CheckboxFieldComponent: CheckboxFieldClientComponent = (props) => {\n const {\n id,\n checked: checkedFromProps,\n disableFormData,\n field,\n field: {\n admin: { className, description } = {} as CheckboxFieldClientProps['field']['admin'],\n label,\n required,\n } = {} as CheckboxFieldClientProps['field'],\n onChange: onChangeFromProps,\n partialChecked,\n path: pathFromProps,\n readOnly,\n validate,\n } = props\n\n const { uuid } = useForm()\n\n const editDepth = useEditDepth()\n\n const {\n i18n: { language },\n } = useTranslation()\n const isRTL = (rtlLanguages as readonly string[]).includes(language)\n\n const memoizedValidate: CheckboxFieldValidation = useCallback(\n (value, options) => {\n if (typeof validate === 'function') {\n return validate(value, { ...options, required })\n }\n },\n [validate, required],\n )\n\n const {\n customComponents: { AfterInput, BeforeInput, Description, Error, Label } = {},\n disabled,\n path,\n setValue,\n showError,\n value,\n } = useField({\n disableFormData,\n potentiallyStalePath: pathFromProps,\n validate: memoizedValidate,\n })\n\n const onToggle = useCallback(() => {\n if (!readOnly) {\n setValue(!value)\n if (typeof onChangeFromProps === 'function') {\n onChangeFromProps(!value)\n }\n }\n }, [onChangeFromProps, readOnly, setValue, value])\n\n const checked = checkedFromProps || Boolean(value)\n\n const fieldID = id || generateFieldID(path, editDepth, uuid)\n\n const styles = useMemo(() => mergeFieldStyles(field), [field])\n\n return (\n \n \n }\n />\n \n }\n />\n \n )\n}\n\nexport const CheckboxField = withCondition(CheckboxFieldComponent)\n", "'use client'\nimport type { PayloadRequest } from 'payload'\n\nimport React, { useCallback, useMemo, useRef } from 'react'\n\nimport type { UPDATE } from '../Form/types.js'\nimport type { FieldType, Options } from './types.js'\n\nexport type { FieldType, Options }\n\nimport { useThrottledEffect } from '../../hooks/useThrottledEffect.js'\nimport { useAuth } from '../../providers/Auth/index.js'\nimport { useConfig } from '../../providers/Config/index.js'\nimport { useDocumentInfo } from '../../providers/DocumentInfo/index.js'\nimport { useOperation } from '../../providers/Operation/index.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport {\n useDocumentForm,\n useForm,\n useFormFields,\n useFormInitializing,\n useFormProcessing,\n useFormSubmitted,\n} from '../Form/context.js'\nimport { useFieldPath } from '../RenderFields/context.js'\n\nconst useFieldInForm = (options?: Options): FieldType => {\n const {\n disableFormData = false,\n hasRows,\n path: pathFromOptions,\n potentiallyStalePath,\n validate,\n } = options || {}\n\n const pathFromContext = useFieldPath()\n\n // This is a workaround for stale props given to server rendered components.\n // See the notes in the `potentiallyStalePath` type definition for more details.\n const path = pathFromOptions || pathFromContext || potentiallyStalePath\n\n const submitted = useFormSubmitted()\n const processing = useFormProcessing()\n const initializing = useFormInitializing()\n const { user } = useAuth()\n const { id, collectionSlug } = useDocumentInfo()\n const operation = useOperation()\n\n const dispatchField = useFormFields(([_, dispatch]) => dispatch)\n const field = useFormFields(([fields]) => (fields && fields?.[path]) || null)\n\n const { t } = useTranslation()\n const { config } = useConfig()\n\n const { getData, getDataByPath, getSiblingData, setModified } = useForm()\n const documentForm = useDocumentForm()\n\n const filterOptions = field?.filterOptions\n const value = field?.value as TValue\n const initialValue = field?.initialValue as TValue\n const valid = typeof field?.valid === 'boolean' ? field.valid : true\n const showError = valid === false && submitted\n\n const prevValid = useRef(valid)\n const prevErrorMessage = useRef(field?.errorMessage)\n\n const pathSegments = path ? path.split('.') : []\n\n // Method to return from `useField`, used to\n // update field values from field component(s)\n const setValue = useCallback(\n (e, disableModifyingForm = false) => {\n // TODO:\n // There are no built-in fields that pass events into `e`.\n // Remove this check in the next major version.\n const isEvent =\n e &&\n typeof e === 'object' &&\n typeof e.preventDefault === 'function' &&\n typeof e.stopPropagation === 'function'\n\n const val = isEvent ? e.target.value : e\n\n dispatchField({\n type: 'UPDATE',\n disableFormData: disableFormData || (hasRows && val > 0),\n path,\n value: val,\n })\n\n if (!disableModifyingForm) {\n setModified(true)\n }\n },\n [setModified, path, dispatchField, disableFormData, hasRows],\n )\n\n // Store result from hook as ref\n // to prevent unnecessary rerenders\n const result: FieldType = useMemo(\n () => ({\n blocksFilterOptions: field?.blocksFilterOptions,\n customComponents: field?.customComponents,\n disabled: processing || initializing,\n errorMessage: field?.errorMessage,\n errorPaths: field?.errorPaths || [],\n filterOptions,\n formInitializing: initializing,\n formProcessing: processing,\n formSubmitted: submitted,\n initialValue,\n path,\n rows: field?.rows,\n selectFilterOptions: field?.selectFilterOptions,\n setValue,\n showError,\n valid: field?.valid,\n value,\n }),\n [\n field,\n processing,\n setValue,\n showError,\n submitted,\n value,\n initialValue,\n path,\n filterOptions,\n initializing,\n ],\n )\n\n // Throttle the validate function\n useThrottledEffect(\n () => {\n const validateField = async () => {\n let valueToValidate = value\n\n if (field?.rows && Array.isArray(field.rows)) {\n valueToValidate = getDataByPath(path)\n }\n\n let errorMessage: string | undefined = prevErrorMessage.current\n let valid: boolean | string = prevValid.current\n\n const data = getData()\n const isValid =\n typeof validate === 'function'\n ? await validate(valueToValidate, {\n id,\n blockData: undefined, // Will be expensive to get - not worth to pass to client-side validation, as this can be obtained by the user using `useFormFields()`\n collectionSlug,\n data: documentForm?.getData ? documentForm.getData() : data,\n event: 'onChange',\n operation,\n path: pathSegments,\n preferences: {} as any,\n req: {\n payload: {\n config,\n },\n t,\n user,\n } as unknown as PayloadRequest,\n siblingData: getSiblingData(path),\n })\n : typeof prevErrorMessage.current === 'string'\n ? prevErrorMessage.current\n : prevValid.current\n\n if (typeof isValid === 'string') {\n valid = false\n errorMessage = isValid\n } else if (typeof isValid === 'boolean') {\n valid = isValid\n errorMessage = undefined\n }\n\n // Only dispatch if the validation result has changed\n // This will prevent unnecessary rerenders\n if (valid !== prevValid.current || errorMessage !== prevErrorMessage.current) {\n prevValid.current = valid\n prevErrorMessage.current = errorMessage\n\n const update: UPDATE = {\n type: 'UPDATE',\n errorMessage,\n path,\n rows: field?.rows,\n valid,\n validate,\n value,\n }\n\n if (disableFormData || (hasRows ? typeof value === 'number' && value > 0 : false)) {\n update.disableFormData = true\n }\n\n if (typeof dispatchField === 'function') {\n dispatchField(update)\n }\n }\n }\n\n void validateField()\n },\n 150,\n [\n value,\n disableFormData,\n dispatchField,\n getData,\n getSiblingData,\n getDataByPath,\n id,\n operation,\n path,\n user,\n validate,\n field?.rows,\n collectionSlug,\n ],\n )\n\n return result\n}\n\n/**\n * Context to allow providing useField value for fields directly, if managed outside the Form\n *\n * @experimental\n */\nexport const FieldContext = React.createContext | undefined>(undefined)\n\n/**\n * Get and set the value of a form field.\n *\n * @see https://payloadcms.com/docs/admin/react-hooks#usefield\n */\nexport const useField = (options?: Options): FieldType => {\n const pathFromContext = useFieldPath()\n\n const fieldContext = React.use(FieldContext) as FieldType | undefined\n\n // Lock the mode on first render so hook order is stable forever. This ensures\n // that hooks are called in the same order each time a component renders => should\n // not break the rule of hooks.\n const hasFieldContext = React.useRef(null)\n if (hasFieldContext.current === null) {\n // Use field context, if a field context exists **and** the path matches. If the path\n // does not match, this could be the field context of a parent field => there likely is\n // a nested
we should use instead => 'form'\n const currentPath = options?.path || pathFromContext || options?.potentiallyStalePath\n\n hasFieldContext.current =\n fieldContext && currentPath && fieldContext.path === currentPath ? true : false\n }\n\n if (hasFieldContext.current === true) {\n if (!fieldContext) {\n // Provider was removed after mount. That violates hook guarantees.\n throw new Error('FieldContext was removed after mount. This breaks hook ordering.')\n }\n return fieldContext\n }\n\n // We intentionally guard this hook call with a mode that is fixed on first render.\n // The order is consistent across renders. Silence the linter’s false positive.\n\n // eslint-disable-next-line react-compiler/react-compiler\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useFieldInForm(options)\n}\n", "'use client'\nimport type React from 'react'\n\nimport { useEffect, useRef } from 'react'\n\ntype useThrottledEffect = (\n callback: React.EffectCallback,\n delay: number,\n deps: React.DependencyList,\n) => void\n\n/**\n * A hook that will throttle the execution of a callback function inside a useEffect.\n * This is useful for things like throttling loading states or other UI updates.\n * @param callback The callback function to be executed.\n * @param delay The delay in milliseconds to throttle the callback.\n * @param deps The dependencies to watch for changes.\n */\nexport const useThrottledEffect: useThrottledEffect = (callback, delay, deps = []) => {\n const lastRan = useRef(Date.now())\n\n useEffect(() => {\n const handler = setTimeout(\n () => {\n if (Date.now() - lastRan.current >= delay) {\n callback()\n lastRan.current = Date.now()\n }\n },\n delay - (Date.now() - lastRan.current),\n )\n\n return () => {\n clearTimeout(handler)\n }\n }, [delay, ...deps])\n}\n", "'use client'\nimport type { ClientUser, DocumentPreferences } from 'payload'\n\nimport { formatAdminURL } from 'payload/shared'\nimport * as qs from 'qs-esm'\nimport React, { createContext, use, useCallback, useEffect, useMemo, useRef, useState } from 'react'\n\nimport type { DocumentInfoContext, DocumentInfoProps } from './types.js'\n\nimport { useControllableState } from '../../hooks/useControllableState.js'\nimport { useAuth } from '../../providers/Auth/index.js'\nimport { requests } from '../../utilities/api.js'\nimport { formatDocTitle } from '../../utilities/formatDocTitle/index.js'\nimport { useConfig } from '../Config/index.js'\nimport { DocumentTitleProvider } from '../DocumentTitle/index.js'\nimport { useLocale, useLocaleLoading } from '../Locale/index.js'\nimport { usePreferences } from '../Preferences/index.js'\nimport { useTranslation } from '../Translation/index.js'\nimport { UploadEditsProvider, useUploadEdits } from '../UploadEdits/index.js'\nimport { useGetDocPermissions } from './useGetDocPermissions.js'\n\nconst Context = createContext({} as DocumentInfoContext)\n\nexport type * from './types.js'\n\nexport const useDocumentInfo = (): DocumentInfoContext => use(Context)\n\nconst DocumentInfo: React.FC<\n {\n readonly children: React.ReactNode\n } & DocumentInfoProps\n> = ({ children, ...props }) => {\n const {\n id,\n collectionSlug,\n currentEditor: currentEditorFromProps,\n docPermissions: docPermissionsFromProps,\n globalSlug,\n hasPublishedDoc: hasPublishedDocFromProps,\n hasPublishPermission: hasPublishPermissionFromProps,\n hasSavePermission: hasSavePermissionFromProps,\n initialData,\n initialState,\n isLocked: isLockedFromProps,\n lastUpdateTime: lastUpdateTimeFromProps,\n mostRecentVersionIsAutosaved: mostRecentVersionIsAutosavedFromProps,\n unpublishedVersionCount: unpublishedVersionCountFromProps,\n versionCount: versionCountFromProps,\n } = props\n\n const [docPermissions, setDocPermissions] = useControllableState(docPermissionsFromProps)\n\n const [hasSavePermission, setHasSavePermission] = useControllableState(hasSavePermissionFromProps)\n\n const [hasPublishPermission, setHasPublishPermission] = useControllableState(\n hasPublishPermissionFromProps,\n )\n\n const { permissions } = useAuth()\n\n const {\n config: {\n admin: { dateFormat },\n collections,\n routes: { api },\n },\n getEntityConfig,\n } = useConfig()\n\n const collectionConfig = getEntityConfig({ collectionSlug })\n const globalConfig = getEntityConfig({ globalSlug })\n\n // Check if the locked-documents collection exists in the config\n const hasLockedDocumentsCollection = collections.some(\n (collection) => collection.slug === 'payload-locked-documents',\n )\n\n const abortControllerRef = useRef(new AbortController())\n const docConfig = collectionConfig || globalConfig\n\n const { i18n } = useTranslation()\n\n const { uploadEdits } = useUploadEdits()\n\n /**\n * @deprecated This state will be removed in v4.\n * This is for performance reasons. Use the `DocumentTitleContext` instead.\n */\n const [title, setDocumentTitle] = useState(() =>\n formatDocTitle({\n collectionConfig,\n data: { ...(initialData || {}), id },\n dateFormat,\n fallback: id?.toString(),\n globalConfig,\n i18n,\n }),\n )\n\n const [mostRecentVersionIsAutosaved, setMostRecentVersionIsAutosaved] = useState(\n mostRecentVersionIsAutosavedFromProps,\n )\n\n const [versionCount, setVersionCount] = useState(versionCountFromProps)\n\n const [hasPublishedDoc, setHasPublishedDoc] = useState(hasPublishedDocFromProps)\n\n const [unpublishedVersionCount, setUnpublishedVersionCount] = useState(\n unpublishedVersionCountFromProps,\n )\n\n const [documentIsLocked, setDocumentIsLocked] = useControllableState(\n isLockedFromProps,\n )\n\n const [currentEditor, setCurrentEditor] = useControllableState(\n currentEditorFromProps,\n )\n const [lastUpdateTime, setLastUpdateTime] = useControllableState(lastUpdateTimeFromProps)\n\n const [data, setData] = useControllableState(initialData)\n\n const [uploadStatus, setUploadStatus] = useControllableState<'failed' | 'idle' | 'uploading'>(\n 'idle',\n )\n\n const documentLockState = useRef<{\n hasShownLockedModal: boolean\n isLocked: boolean\n user: ClientUser | number | string\n } | null>({\n hasShownLockedModal: false,\n isLocked: false,\n user: null,\n })\n\n const updateUploadStatus = useCallback(\n (status: 'failed' | 'idle' | 'uploading') => {\n setUploadStatus(status)\n },\n [setUploadStatus],\n )\n\n const { getPreference, setPreference } = usePreferences()\n const { code: locale } = useLocale()\n const { localeIsLoading } = useLocaleLoading()\n\n const isInitializing = useMemo(\n () => initialState === undefined || initialData === undefined || localeIsLoading,\n [initialData, initialState, localeIsLoading],\n )\n\n const baseAPIPath = formatAdminURL({\n apiRoute: api,\n path: '',\n })\n\n let slug: string\n let pluralType: 'collections' | 'globals'\n let preferencesKey: string\n\n if (globalSlug) {\n slug = globalSlug\n pluralType = 'globals'\n preferencesKey = `global-${slug}`\n }\n\n if (collectionSlug) {\n slug = collectionSlug\n pluralType = 'collections'\n\n if (id) {\n preferencesKey = `collection-${slug}-${id}`\n }\n }\n\n const unlockDocument = useCallback(\n async (docID: number | string, slug: string) => {\n // Check if the locked-documents collection exists before making API calls\n if (!hasLockedDocumentsCollection) {\n return\n }\n\n try {\n const isGlobal = slug === globalSlug\n\n const request = await requests.get(`${baseAPIPath}/payload-locked-documents`, {\n credentials: 'include',\n params: isGlobal\n ? {\n 'where[globalSlug][equals]': slug,\n }\n : {\n 'where[document.relationTo][equals]': slug,\n 'where[document.value][equals]': docID,\n },\n })\n\n const { docs } = await request.json()\n\n if (docs?.length > 0) {\n const lockID = docs[0].id\n await requests.delete(`${baseAPIPath}/payload-locked-documents/${lockID}`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n })\n setDocumentIsLocked(false)\n }\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Failed to unlock the document', error)\n }\n },\n [baseAPIPath, globalSlug, setDocumentIsLocked, hasLockedDocumentsCollection],\n )\n\n const updateDocumentEditor = useCallback(\n async (docID: number | string, slug: string, user: ClientUser | number | string) => {\n // Check if the locked-documents collection exists before making API calls\n if (!hasLockedDocumentsCollection) {\n return\n }\n\n try {\n const isGlobal = slug === globalSlug\n\n // Check if the document is already locked\n const request = await requests.get(`${baseAPIPath}/payload-locked-documents`, {\n credentials: 'include',\n params: isGlobal\n ? {\n 'where[globalSlug][equals]': slug,\n }\n : {\n 'where[document.relationTo][equals]': slug,\n 'where[document.value][equals]': docID,\n },\n })\n\n const { docs } = await request.json()\n\n if (docs?.length > 0) {\n const lockID = docs[0].id\n\n const userData =\n typeof user === 'object'\n ? { relationTo: user.collection, value: user.id }\n : { relationTo: 'users', value: user }\n\n // Send a patch request to update the _lastEdited info\n await requests.patch(`${baseAPIPath}/payload-locked-documents/${lockID}`, {\n body: JSON.stringify({\n user: userData,\n }),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n })\n }\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Failed to update the document editor', error)\n }\n },\n [baseAPIPath, globalSlug, hasLockedDocumentsCollection],\n )\n\n const getDocPermissions = useGetDocPermissions({\n id: id as string,\n api,\n collectionSlug,\n globalSlug,\n i18n,\n locale,\n permissions,\n setDocPermissions,\n setHasPublishPermission,\n setHasSavePermission,\n })\n\n const getDocPreferences = useCallback(() => {\n return getPreference(preferencesKey)\n }, [getPreference, preferencesKey])\n\n const setDocFieldPreferences = useCallback(\n async (path, fieldPreferences) => {\n const allPreferences = await getDocPreferences()\n\n if (preferencesKey) {\n try {\n await setPreference(preferencesKey, {\n ...allPreferences,\n fields: {\n ...(allPreferences?.fields || {}),\n [path]: {\n ...allPreferences?.fields?.[path],\n ...fieldPreferences,\n },\n },\n })\n } catch (e) {\n console.error(e) // eslint-disable-line no-console\n }\n }\n },\n [setPreference, preferencesKey, getDocPreferences],\n )\n\n const incrementVersionCount = useCallback(() => {\n const newCount = versionCount + 1\n if (collectionConfig && collectionConfig.versions) {\n if (collectionConfig.versions.maxPerDoc > 0) {\n setVersionCount(Math.min(newCount, collectionConfig.versions.maxPerDoc))\n } else {\n setVersionCount(newCount)\n }\n } else if (globalConfig && globalConfig.versions) {\n if (globalConfig.versions.max > 0) {\n setVersionCount(Math.min(newCount, globalConfig.versions.max))\n } else {\n setVersionCount(newCount)\n }\n }\n }, [collectionConfig, globalConfig, versionCount])\n\n /**\n * @todo: Remove this in v4\n * Users should use the `DocumentTitleContext` instead.\n */\n useEffect(() => {\n setDocumentTitle(\n formatDocTitle({\n collectionConfig,\n data: { ...data, id },\n dateFormat,\n fallback: id?.toString(),\n globalConfig,\n i18n,\n }),\n )\n }, [collectionConfig, globalConfig, data, dateFormat, i18n, id])\n\n // clean on unmount\n useEffect(() => {\n const re1 = abortControllerRef.current\n\n return () => {\n if (re1) {\n try {\n re1.abort()\n } catch (_err) {\n // swallow error\n }\n }\n }\n }, [])\n\n const action: string = React.useMemo(() => {\n const docPath = `${pluralType === 'globals' ? `/globals` : ''}/${slug}${id ? `/${id}` : ''}`\n\n return `${baseAPIPath}${docPath}${qs.stringify(\n {\n depth: 0,\n 'fallback-locale': 'null',\n locale,\n uploadEdits: uploadEdits || undefined,\n },\n {\n addQueryPrefix: true,\n },\n )}`\n }, [baseAPIPath, locale, pluralType, id, slug, uploadEdits])\n\n const value: DocumentInfoContext = {\n ...props,\n action,\n currentEditor,\n data,\n docConfig,\n docPermissions,\n documentIsLocked,\n documentLockState,\n getDocPermissions,\n getDocPreferences,\n hasPublishedDoc,\n hasPublishPermission,\n hasSavePermission,\n incrementVersionCount,\n initialData,\n initialState,\n isInitializing,\n lastUpdateTime,\n mostRecentVersionIsAutosaved,\n preferencesKey,\n savedDocumentData: data,\n setCurrentEditor,\n setData,\n setDocFieldPreferences,\n setDocumentIsLocked,\n setDocumentTitle,\n setHasPublishedDoc,\n setLastUpdateTime,\n setMostRecentVersionIsAutosaved,\n setUnpublishedVersionCount,\n setUploadStatus: updateUploadStatus,\n title,\n unlockDocument,\n unpublishedVersionCount,\n updateDocumentEditor,\n updateSavedDocumentData: setData,\n uploadStatus,\n versionCount,\n }\n\n return (\n \n {children}\n \n )\n}\n\nexport const DocumentInfoProvider: React.FC<\n {\n readonly children: React.ReactNode\n } & DocumentInfoProps\n> = (props) => {\n return (\n \n \n \n )\n}\n", "import type { I18n } from '@payloadcms/translations'\nimport type {\n ClientCollectionConfig,\n ClientGlobalConfig,\n SanitizedConfig,\n TypeWithID,\n} from 'payload'\n\nimport { getTranslation } from '@payloadcms/translations'\n\nimport { formatDate } from './formatDateTitle.js'\nimport { formatLexicalDocTitle, isSerializedLexicalEditor } from './formatLexicalDocTitle.js'\nimport { formatRelationshipTitle } from './formatRelationshipTitle.js'\n\nexport const formatDocTitle = ({\n collectionConfig,\n data,\n dateFormat: dateFormatFromConfig,\n fallback,\n globalConfig,\n i18n,\n}: {\n collectionConfig?: ClientCollectionConfig\n data: TypeWithID\n dateFormat: SanitizedConfig['admin']['dateFormat']\n fallback?: object | string\n globalConfig?: ClientGlobalConfig\n i18n: I18n\n}): string => {\n let title: string\n\n if (collectionConfig) {\n const useAsTitle = collectionConfig?.admin?.useAsTitle\n\n if (useAsTitle) {\n title = data?.[useAsTitle] as string\n\n if (title) {\n const fieldConfig = collectionConfig.fields.find(\n (f) => 'name' in f && f.name === useAsTitle,\n )\n\n const isDate = fieldConfig?.type === 'date'\n const isRelationship = fieldConfig?.type === 'relationship'\n\n if (isDate) {\n const dateFormat =\n ('date' in fieldConfig.admin && fieldConfig?.admin?.date?.displayFormat) ||\n dateFormatFromConfig\n\n title = formatDate({ date: title, i18n, pattern: dateFormat }) || title\n }\n\n if (isRelationship) {\n const formattedRelationshipTitle = formatRelationshipTitle(data[useAsTitle])\n title = formattedRelationshipTitle\n }\n }\n }\n }\n\n if (globalConfig) {\n title = getTranslation(globalConfig?.label, i18n) || globalConfig?.slug\n }\n\n // richtext lexical case. We convert the first child of root to plain text\n if (title && isSerializedLexicalEditor(title)) {\n title = formatLexicalDocTitle(title.root.children?.[0]?.children || [], '')\n }\n\n if (!title && isSerializedLexicalEditor(fallback)) {\n title = formatLexicalDocTitle(fallback.root.children?.[0]?.children || [], '')\n }\n\n if (!title) {\n title = typeof fallback === 'string' ? fallback : `[${i18n.t('general:untitled')}]`\n }\n\n return title\n}\n", "const offsetFormatCache = {};\nconst offsetCache = {};\n\n/**\n * The function extracts UTC offset in minutes from the given date in specified\n * time zone.\n *\n * Unlike `Date.prototype.getTimezoneOffset`, this function returns the value\n * mirrored to the sign of the offset in the time zone. For Asia/Singapore\n * (UTC+8), `tzOffset` returns 480, while `getTimezoneOffset` returns -480.\n *\n * @param timeZone - Time zone name (IANA or UTC offset)\n * @param date - Date to check the offset for\n *\n * @returns UTC offset in minutes\n */\nexport function tzOffset(timeZone, date) {\n try {\n const format = offsetFormatCache[timeZone] ||= new Intl.DateTimeFormat(\"en-GB\", {\n timeZone,\n hour: \"numeric\",\n timeZoneName: \"longOffset\"\n }).format;\n const offsetStr = format(date).split('GMT')[1] || '';\n if (offsetStr in offsetCache) return offsetCache[offsetStr];\n return calcOffset(offsetStr, offsetStr.split(\":\"));\n } catch {\n // Fallback to manual parsing if the runtime doesn't support \u00B1HH:MM/\u00B1HHMM/\u00B1HH\n // See: https://github.com/nodejs/node/issues/53419\n if (timeZone in offsetCache) return offsetCache[timeZone];\n const captures = timeZone?.match(offsetRe);\n if (captures) return calcOffset(timeZone, captures.slice(1));\n return NaN;\n }\n}\nconst offsetRe = /([+-]\\d\\d):?(\\d\\d)?/;\nfunction calcOffset(cacheStr, values) {\n const hours = +values[0];\n const minutes = +(values[1] || 0);\n return offsetCache[cacheStr] = hours > 0 ? hours * 60 + minutes : hours * 60 - minutes;\n}", "import { tzOffset } from \"../tzOffset/index.js\";\nexport class TZDateMini extends Date {\n //#region static\n\n constructor(...args) {\n super();\n if (args.length > 1 && typeof args[args.length - 1] === \"string\") {\n this.timeZone = args.pop();\n }\n this.internal = new Date();\n if (isNaN(tzOffset(this.timeZone, this))) {\n this.setTime(NaN);\n } else {\n if (!args.length) {\n this.setTime(Date.now());\n } else if (typeof args[0] === \"number\" && (args.length === 1 || args.length === 2 && typeof args[1] !== \"number\")) {\n this.setTime(args[0]);\n } else if (typeof args[0] === \"string\") {\n this.setTime(+new Date(args[0]));\n } else if (args[0] instanceof Date) {\n this.setTime(+args[0]);\n } else {\n this.setTime(+new Date(...args));\n adjustToSystemTZ(this, NaN);\n syncToInternal(this);\n }\n }\n }\n static tz(tz, ...args) {\n return args.length ? new TZDateMini(...args, tz) : new TZDateMini(Date.now(), tz);\n }\n\n //#endregion\n\n //#region time zone\n\n withTimeZone(timeZone) {\n return new TZDateMini(+this, timeZone);\n }\n getTimezoneOffset() {\n return -tzOffset(this.timeZone, this);\n }\n\n //#endregion\n\n //#region time\n\n setTime(time) {\n Date.prototype.setTime.apply(this, arguments);\n syncToInternal(this);\n return +this;\n }\n\n //#endregion\n\n //#region date-fns integration\n\n [Symbol.for(\"constructDateFrom\")](date) {\n return new TZDateMini(+new Date(date), this.timeZone);\n }\n\n //#endregion\n}\n\n// Assign getters and setters\nconst re = /^(get|set)(?!UTC)/;\nObject.getOwnPropertyNames(Date.prototype).forEach(method => {\n if (!re.test(method)) return;\n const utcMethod = method.replace(re, \"$1UTC\");\n // Filter out methods without UTC counterparts\n if (!TZDateMini.prototype[utcMethod]) return;\n if (method.startsWith(\"get\")) {\n // Delegate to internal date's UTC method\n TZDateMini.prototype[method] = function () {\n return this.internal[utcMethod]();\n };\n } else {\n // Assign regular setter\n TZDateMini.prototype[method] = function () {\n Date.prototype[utcMethod].apply(this.internal, arguments);\n syncFromInternal(this);\n return +this;\n };\n\n // Assign UTC setter\n TZDateMini.prototype[utcMethod] = function () {\n Date.prototype[utcMethod].apply(this, arguments);\n syncToInternal(this);\n return +this;\n };\n }\n});\n\n/**\n * Function syncs time to internal date, applying the time zone offset.\n *\n * @param {Date} date - Date to sync\n */\nfunction syncToInternal(date) {\n date.internal.setTime(+date);\n date.internal.setUTCMinutes(date.internal.getUTCMinutes() - date.getTimezoneOffset());\n}\n\n/**\n * Function syncs the internal date UTC values to the date. It allows to get\n * accurate timestamp value.\n *\n * @param {Date} date - The date to sync\n */\nfunction syncFromInternal(date) {\n // First we transpose the internal values\n Date.prototype.setFullYear.call(date, date.internal.getUTCFullYear(), date.internal.getUTCMonth(), date.internal.getUTCDate());\n Date.prototype.setHours.call(date, date.internal.getUTCHours(), date.internal.getUTCMinutes(), date.internal.getUTCSeconds(), date.internal.getUTCMilliseconds());\n\n // Now we have to adjust the date to the system time zone\n adjustToSystemTZ(date);\n}\n\n/**\n * Function adjusts the date to the system time zone. It uses the time zone\n * differences to calculate the offset and adjust the date.\n *\n * @param {Date} date - Date to adjust\n */\nfunction adjustToSystemTZ(date) {\n // Save the time zone offset before all the adjustments\n const offset = tzOffset(date.timeZone, date);\n\n //#region System DST adjustment\n\n // The biggest problem with using the system time zone is that when we create\n // a date from internal values stored in UTC, the system time zone might end\n // up on the DST hour:\n //\n // $ TZ=America/New_York node\n // > new Date(2020, 2, 8, 1).toString()\n // 'Sun Mar 08 2020 01:00:00 GMT-0500 (Eastern Standard Time)'\n // > new Date(2020, 2, 8, 2).toString()\n // 'Sun Mar 08 2020 03:00:00 GMT-0400 (Eastern Daylight Time)'\n // > new Date(2020, 2, 8, 3).toString()\n // 'Sun Mar 08 2020 03:00:00 GMT-0400 (Eastern Daylight Time)'\n // > new Date(2020, 2, 8, 4).toString()\n // 'Sun Mar 08 2020 04:00:00 GMT-0400 (Eastern Daylight Time)'\n //\n // Here we get the same hour for both 2 and 3, because the system time zone\n // has DST beginning at 8 March 2020, 2 a.m. and jumps to 3 a.m. So we have\n // to adjust the internal date to reflect that.\n //\n // However we want to adjust only if that's the DST hour the change happenes,\n // not the hour where DST moves to.\n\n // We calculate the previous hour to see if the time zone offset has changed\n // and we have landed on the DST hour.\n const prevHour = new Date(+date);\n // We use UTC methods here as we don't want to land on the same hour again\n // in case of DST.\n prevHour.setUTCHours(prevHour.getUTCHours() - 1);\n\n // Calculate if we are on the system DST hour.\n const systemOffset = -new Date(+date).getTimezoneOffset();\n const prevHourSystemOffset = -new Date(+prevHour).getTimezoneOffset();\n const systemDSTChange = systemOffset - prevHourSystemOffset;\n // Detect the DST shift. System DST change will occur both on\n const dstShift = Date.prototype.getHours.apply(date) !== date.internal.getUTCHours();\n\n // Move the internal date when we are on the system DST hour.\n if (systemDSTChange && dstShift) date.internal.setUTCMinutes(date.internal.getUTCMinutes() + systemDSTChange);\n\n //#endregion\n\n //#region System diff adjustment\n\n // Now we need to adjust the date, since we just applied internal values.\n // We need to calculate the difference between the system and date time zones\n // and apply it to the date.\n\n const offsetDiff = systemOffset - offset;\n if (offsetDiff) Date.prototype.setUTCMinutes.call(date, Date.prototype.getUTCMinutes.call(date) + offsetDiff);\n\n //#endregion\n\n //#region Post-adjustment DST fix\n\n const postOffset = tzOffset(date.timeZone, date);\n const postSystemOffset = -new Date(+date).getTimezoneOffset();\n const postOffsetDiff = postSystemOffset - postOffset;\n const offsetChanged = postOffset !== offset;\n const postDiff = postOffsetDiff - offsetDiff;\n if (offsetChanged && postDiff) {\n Date.prototype.setUTCMinutes.call(date, Date.prototype.getUTCMinutes.call(date) + postDiff);\n\n // Now we need to check if got offset change during the post-adjustment.\n // If so, we also need both dates to reflect that.\n\n const newOffset = tzOffset(date.timeZone, date);\n const offsetChange = postOffset - newOffset;\n if (offsetChange) {\n date.internal.setUTCMinutes(date.internal.getUTCMinutes() + offsetChange);\n Date.prototype.setUTCMinutes.call(date, Date.prototype.getUTCMinutes.call(date) + offsetChange);\n }\n }\n\n //#endregion\n}", "/**\n * @module constants\n * @summary Useful constants\n * @description\n * Collection of useful date constants.\n *\n * The constants could be imported from `date-fns/constants`:\n *\n * ```ts\n * import { maxTime, minTime } from \"./constants/date-fns/constants\";\n *\n * function isAllowedTime(time) {\n * return time <= maxTime && time >= minTime;\n * }\n * ```\n */\n\n/**\n * @constant\n * @name daysInWeek\n * @summary Days in 1 week.\n */\nexport const daysInWeek = 7;\n\n/**\n * @constant\n * @name daysInYear\n * @summary Days in 1 year.\n *\n * @description\n * How many days in a year.\n *\n * One years equals 365.2425 days according to the formula:\n *\n * > Leap year occurs every 4 years, except for years that are divisible by 100 and not divisible by 400.\n * > 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days\n */\nexport const daysInYear = 365.2425;\n\n/**\n * @constant\n * @name maxTime\n * @summary Maximum allowed time.\n *\n * @example\n * import { maxTime } from \"./constants/date-fns/constants\";\n *\n * const isValid = 8640000000000001 <= maxTime;\n * //=> false\n *\n * new Date(8640000000000001);\n * //=> Invalid Date\n */\nexport const maxTime = Math.pow(10, 8) * 24 * 60 * 60 * 1000;\n\n/**\n * @constant\n * @name minTime\n * @summary Minimum allowed time.\n *\n * @example\n * import { minTime } from \"./constants/date-fns/constants\";\n *\n * const isValid = -8640000000000001 >= minTime;\n * //=> false\n *\n * new Date(-8640000000000001)\n * //=> Invalid Date\n */\nexport const minTime = -maxTime;\n\n/**\n * @constant\n * @name millisecondsInWeek\n * @summary Milliseconds in 1 week.\n */\nexport const millisecondsInWeek = 604800000;\n\n/**\n * @constant\n * @name millisecondsInDay\n * @summary Milliseconds in 1 day.\n */\nexport const millisecondsInDay = 86400000;\n\n/**\n * @constant\n * @name millisecondsInMinute\n * @summary Milliseconds in 1 minute\n */\nexport const millisecondsInMinute = 60000;\n\n/**\n * @constant\n * @name millisecondsInHour\n * @summary Milliseconds in 1 hour\n */\nexport const millisecondsInHour = 3600000;\n\n/**\n * @constant\n * @name millisecondsInSecond\n * @summary Milliseconds in 1 second\n */\nexport const millisecondsInSecond = 1000;\n\n/**\n * @constant\n * @name minutesInYear\n * @summary Minutes in 1 year.\n */\nexport const minutesInYear = 525600;\n\n/**\n * @constant\n * @name minutesInMonth\n * @summary Minutes in 1 month.\n */\nexport const minutesInMonth = 43200;\n\n/**\n * @constant\n * @name minutesInDay\n * @summary Minutes in 1 day.\n */\nexport const minutesInDay = 1440;\n\n/**\n * @constant\n * @name minutesInHour\n * @summary Minutes in 1 hour.\n */\nexport const minutesInHour = 60;\n\n/**\n * @constant\n * @name monthsInQuarter\n * @summary Months in 1 quarter.\n */\nexport const monthsInQuarter = 3;\n\n/**\n * @constant\n * @name monthsInYear\n * @summary Months in 1 year.\n */\nexport const monthsInYear = 12;\n\n/**\n * @constant\n * @name quartersInYear\n * @summary Quarters in 1 year\n */\nexport const quartersInYear = 4;\n\n/**\n * @constant\n * @name secondsInHour\n * @summary Seconds in 1 hour.\n */\nexport const secondsInHour = 3600;\n\n/**\n * @constant\n * @name secondsInMinute\n * @summary Seconds in 1 minute.\n */\nexport const secondsInMinute = 60;\n\n/**\n * @constant\n * @name secondsInDay\n * @summary Seconds in 1 day.\n */\nexport const secondsInDay = secondsInHour * 24;\n\n/**\n * @constant\n * @name secondsInWeek\n * @summary Seconds in 1 week.\n */\nexport const secondsInWeek = secondsInDay * 7;\n\n/**\n * @constant\n * @name secondsInYear\n * @summary Seconds in 1 year.\n */\nexport const secondsInYear = secondsInDay * daysInYear;\n\n/**\n * @constant\n * @name secondsInMonth\n * @summary Seconds in 1 month\n */\nexport const secondsInMonth = secondsInYear / 12;\n\n/**\n * @constant\n * @name secondsInQuarter\n * @summary Seconds in 1 quarter.\n */\nexport const secondsInQuarter = secondsInMonth * 3;\n\n/**\n * @constant\n * @name constructFromSymbol\n * @summary Symbol enabling Date extensions to inherit properties from the reference date.\n *\n * The symbol is used to enable the `constructFrom` function to construct a date\n * using a reference date and a value. It allows to transfer extra properties\n * from the reference date to the new date. It's useful for extensions like\n * [`TZDate`](https://github.com/date-fns/tz) that accept a time zone as\n * a constructor argument.\n */\nexport const constructFromSymbol = Symbol.for(\"constructDateFrom\");\n", "import { constructFromSymbol } from \"./constants.js\";\n\n/**\n * @name constructFrom\n * @category Generic Helpers\n * @summary Constructs a date using the reference date and the value\n *\n * @description\n * The function constructs a new date using the constructor from the reference\n * date and the given value. It helps to build generic functions that accept\n * date extensions.\n *\n * It defaults to `Date` if the passed reference date is a number or a string.\n *\n * Starting from v3.7.0, it allows to construct a date using `[Symbol.for(\"constructDateFrom\")]`\n * enabling to transfer extra properties from the reference date to the new date.\n * It's useful for extensions like [`TZDate`](https://github.com/date-fns/tz)\n * that accept a time zone as a constructor argument.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n *\n * @param date - The reference date to take constructor from\n * @param value - The value to create the date\n *\n * @returns Date initialized using the given date and value\n *\n * @example\n * import { constructFrom } from \"./constructFrom/date-fns\";\n *\n * // A function that clones a date preserving the original type\n * function cloneDate(date: DateType): DateType {\n * return constructFrom(\n * date, // Use constructor from the given date\n * date.getTime() // Use the date value to create a new date\n * );\n * }\n */\nexport function constructFrom(date, value) {\n if (typeof date === \"function\") return date(value);\n\n if (date && typeof date === \"object\" && constructFromSymbol in date)\n return date[constructFromSymbol](value);\n\n if (date instanceof Date) return new date.constructor(value);\n\n return new Date(value);\n}\n\n// Fallback for modularized imports:\nexport default constructFrom;\n", "import { constructFrom } from \"./constructFrom.js\";\n\n/**\n * @name toDate\n * @category Common Helpers\n * @summary Convert the given argument to an instance of Date.\n *\n * @description\n * Convert the given argument to an instance of Date.\n *\n * If the argument is an instance of Date, the function returns its clone.\n *\n * If the argument is a number, it is treated as a timestamp.\n *\n * If the argument is none of the above, the function returns Invalid Date.\n *\n * Starting from v3.7.0, it clones a date using `[Symbol.for(\"constructDateFrom\")]`\n * enabling to transfer extra properties from the reference date to the new date.\n * It's useful for extensions like [`TZDate`](https://github.com/date-fns/tz)\n * that accept a time zone as a constructor argument.\n *\n * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param argument - The value to convert\n *\n * @returns The parsed date in the local time zone\n *\n * @example\n * // Clone the date:\n * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))\n * //=> Tue Feb 11 2014 11:30:30\n *\n * @example\n * // Convert the timestamp to date:\n * const result = toDate(1392098430000)\n * //=> Tue Feb 11 2014 11:30:30\n */\nexport function toDate(argument, context) {\n // [TODO] Get rid of `toDate` or `constructFrom`?\n return constructFrom(context || argument, argument);\n}\n\n// Fallback for modularized imports:\nexport default toDate;\n", "let defaultOptions = {};\n\nexport function getDefaultOptions() {\n return defaultOptions;\n}\n\nexport function setDefaultOptions(newOptions) {\n defaultOptions = newOptions;\n}\n", "import { getDefaultOptions } from \"./_lib/defaultOptions.js\";\nimport { toDate } from \"./toDate.js\";\n\n/**\n * The {@link startOfWeek} function options.\n */\n\n/**\n * @name startOfWeek\n * @category Week Helpers\n * @summary Return the start of a week for the given date.\n *\n * @description\n * Return the start of a week for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a week\n *\n * @example\n * // The start of a week for 2 September 2014 11:55:00:\n * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sun Aug 31 2014 00:00:00\n *\n * @example\n * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00:\n * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })\n * //=> Mon Sep 01 2014 00:00:00\n */\nexport function startOfWeek(date, options) {\n const defaultOptions = getDefaultOptions();\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const _date = toDate(date, options?.in);\n const day = _date.getDay();\n const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;\n\n _date.setDate(_date.getDate() - diff);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n\n// Fallback for modularized imports:\nexport default startOfWeek;\n", "import { startOfWeek } from \"./startOfWeek.js\";\n\n/**\n * The {@link startOfISOWeek} function options.\n */\n\n/**\n * @name startOfISOWeek\n * @category ISO Week Helpers\n * @summary Return the start of an ISO week for the given date.\n *\n * @description\n * Return the start of an ISO week for the given date.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of an ISO week\n *\n * @example\n * // The start of an ISO week for 2 September 2014 11:55:00:\n * const result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Mon Sep 01 2014 00:00:00\n */\nexport function startOfISOWeek(date, options) {\n return startOfWeek(date, { ...options, weekStartsOn: 1 });\n}\n\n// Fallback for modularized imports:\nexport default startOfISOWeek;\n", "import { constructFrom } from \"./constructFrom.js\";\nimport { startOfISOWeek } from \"./startOfISOWeek.js\";\nimport { toDate } from \"./toDate.js\";\n\n/**\n * The {@link getISOWeekYear} function options.\n */\n\n/**\n * @name getISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Get the ISO week-numbering year of the given date.\n *\n * @description\n * Get the ISO week-numbering year of the given date,\n * which always starts 3 days before the year's first Thursday.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The given date\n *\n * @returns The ISO week-numbering year\n *\n * @example\n * // Which ISO-week numbering year is 2 January 2005?\n * const result = getISOWeekYear(new Date(2005, 0, 2))\n * //=> 2004\n */\nexport function getISOWeekYear(date, options) {\n const _date = toDate(date, options?.in);\n const year = _date.getFullYear();\n\n const fourthOfJanuaryOfNextYear = constructFrom(_date, 0);\n fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);\n fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);\n const startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear);\n\n const fourthOfJanuaryOfThisYear = constructFrom(_date, 0);\n fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);\n fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);\n const startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear);\n\n if (_date.getTime() >= startOfNextYear.getTime()) {\n return year + 1;\n } else if (_date.getTime() >= startOfThisYear.getTime()) {\n return year;\n } else {\n return year - 1;\n }\n}\n\n// Fallback for modularized imports:\nexport default getISOWeekYear;\n", "import { toDate } from \"../toDate.js\";\n\n/**\n * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.\n * They usually appear for dates that denote time before the timezones were introduced\n * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891\n * and GMT+01:00:00 after that date)\n *\n * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,\n * which would lead to incorrect calculations.\n *\n * This function returns the timezone offset in milliseconds that takes seconds in account.\n */\nexport function getTimezoneOffsetInMilliseconds(date) {\n const _date = toDate(date);\n const utcDate = new Date(\n Date.UTC(\n _date.getFullYear(),\n _date.getMonth(),\n _date.getDate(),\n _date.getHours(),\n _date.getMinutes(),\n _date.getSeconds(),\n _date.getMilliseconds(),\n ),\n );\n utcDate.setUTCFullYear(_date.getFullYear());\n return +date - +utcDate;\n}\n", "import { constructFrom } from \"../constructFrom.js\";\n\nexport function normalizeDates(context, ...dates) {\n const normalize = constructFrom.bind(\n null,\n context || dates.find((date) => typeof date === \"object\"),\n );\n return dates.map(normalize);\n}\n", "import { toDate } from \"./toDate.js\";\n\n/**\n * The {@link startOfDay} function options.\n */\n\n/**\n * @name startOfDay\n * @category Day Helpers\n * @summary Return the start of a day for the given date.\n *\n * @description\n * Return the start of a day for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The start of a day\n *\n * @example\n * // The start of a day for 2 September 2014 11:55:00:\n * const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 02 2014 00:00:00\n */\nexport function startOfDay(date, options) {\n const _date = toDate(date, options?.in);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n\n// Fallback for modularized imports:\nexport default startOfDay;\n", "import { getTimezoneOffsetInMilliseconds } from \"./_lib/getTimezoneOffsetInMilliseconds.js\";\nimport { normalizeDates } from \"./_lib/normalizeDates.js\";\nimport { millisecondsInDay } from \"./constants.js\";\nimport { startOfDay } from \"./startOfDay.js\";\n\n/**\n * The {@link differenceInCalendarDays} function options.\n */\n\n/**\n * @name differenceInCalendarDays\n * @category Day Helpers\n * @summary Get the number of calendar days between the given dates.\n *\n * @description\n * Get the number of calendar days between the given dates. This means that the times are removed\n * from the dates and then the difference in days is calculated.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - The options object\n *\n * @returns The number of calendar days\n *\n * @example\n * // How many calendar days are between\n * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?\n * const result = differenceInCalendarDays(\n * new Date(2012, 6, 2, 0, 0),\n * new Date(2011, 6, 2, 23, 0)\n * )\n * //=> 366\n * // How many calendar days are between\n * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?\n * const result = differenceInCalendarDays(\n * new Date(2011, 6, 3, 0, 1),\n * new Date(2011, 6, 2, 23, 59)\n * )\n * //=> 1\n */\nexport function differenceInCalendarDays(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = normalizeDates(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const laterStartOfDay = startOfDay(laterDate_);\n const earlierStartOfDay = startOfDay(earlierDate_);\n\n const laterTimestamp =\n +laterStartOfDay - getTimezoneOffsetInMilliseconds(laterStartOfDay);\n const earlierTimestamp =\n +earlierStartOfDay - getTimezoneOffsetInMilliseconds(earlierStartOfDay);\n\n // Round the number of days to the nearest integer because the number of\n // milliseconds in a day is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round((laterTimestamp - earlierTimestamp) / millisecondsInDay);\n}\n\n// Fallback for modularized imports:\nexport default differenceInCalendarDays;\n", "import { constructFrom } from \"./constructFrom.js\";\nimport { getISOWeekYear } from \"./getISOWeekYear.js\";\nimport { startOfISOWeek } from \"./startOfISOWeek.js\";\n\n/**\n * The {@link startOfISOWeekYear} function options.\n */\n\n/**\n * @name startOfISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Return the start of an ISO week-numbering year for the given date.\n *\n * @description\n * Return the start of an ISO week-numbering year,\n * which always starts 3 days before the year's first Thursday.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of an ISO week-numbering year\n *\n * @example\n * // The start of an ISO week-numbering year for 2 July 2005:\n * const result = startOfISOWeekYear(new Date(2005, 6, 2))\n * //=> Mon Jan 03 2005 00:00:00\n */\nexport function startOfISOWeekYear(date, options) {\n const year = getISOWeekYear(date, options);\n const fourthOfJanuary = constructFrom(options?.in || date, 0);\n fourthOfJanuary.setFullYear(year, 0, 4);\n fourthOfJanuary.setHours(0, 0, 0, 0);\n return startOfISOWeek(fourthOfJanuary);\n}\n\n// Fallback for modularized imports:\nexport default startOfISOWeekYear;\n", "import { toDate } from \"./toDate.js\";\n\n/**\n * @name compareAsc\n * @category Common Helpers\n * @summary Compare the two dates and return -1, 0 or 1.\n *\n * @description\n * Compare the two dates and return 1 if the first date is after the second,\n * -1 if the first date is before the second or 0 if dates are equal.\n *\n * @param dateLeft - The first date to compare\n * @param dateRight - The second date to compare\n *\n * @returns The result of the comparison\n *\n * @example\n * // Compare 11 February 1987 and 10 July 1989:\n * const result = compareAsc(new Date(1987, 1, 11), new Date(1989, 6, 10))\n * //=> -1\n *\n * @example\n * // Sort the array of dates:\n * const result = [\n * new Date(1995, 6, 2),\n * new Date(1987, 1, 11),\n * new Date(1989, 6, 10)\n * ].sort(compareAsc)\n * //=> [\n * // Wed Feb 11 1987 00:00:00,\n * // Mon Jul 10 1989 00:00:00,\n * // Sun Jul 02 1995 00:00:00\n * // ]\n */\nexport function compareAsc(dateLeft, dateRight) {\n const diff = +toDate(dateLeft) - +toDate(dateRight);\n\n if (diff < 0) return -1;\n else if (diff > 0) return 1;\n\n // Return 0 if diff is 0; return NaN if diff is NaN\n return diff;\n}\n\n// Fallback for modularized imports:\nexport default compareAsc;\n", "import { constructFrom } from \"./constructFrom.js\";\n\n/**\n * @name constructNow\n * @category Generic Helpers\n * @summary Constructs a new current date using the passed value constructor.\n * @pure false\n *\n * @description\n * The function constructs a new current date using the constructor from\n * the reference date. It helps to build generic functions that accept date\n * extensions and use the current date.\n *\n * It defaults to `Date` if the passed reference date is a number or a string.\n *\n * @param date - The reference date to take constructor from\n *\n * @returns Current date initialized using the given date constructor\n *\n * @example\n * import { constructNow, isSameDay } from 'date-fns'\n *\n * function isToday(\n * date: DateArg,\n * ): boolean {\n * // If we were to use `new Date()` directly, the function would behave\n * // differently in different timezones and return false for the same date.\n * return isSameDay(date, constructNow(date));\n * }\n */\nexport function constructNow(date) {\n return constructFrom(date, Date.now());\n}\n\n// Fallback for modularized imports:\nexport default constructNow;\n", "import { normalizeDates } from \"./_lib/normalizeDates.js\";\nimport { startOfDay } from \"./startOfDay.js\";\n\n/**\n * The {@link isSameDay} function options.\n */\n\n/**\n * @name isSameDay\n * @category Day Helpers\n * @summary Are the given dates in the same day (and year and month)?\n *\n * @description\n * Are the given dates in the same day (and year and month)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same day (and year and month)\n *\n * @example\n * // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day?\n * const result = isSameDay(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 18, 0))\n * //=> true\n *\n * @example\n * // Are 4 September and 4 October in the same day?\n * const result = isSameDay(new Date(2014, 8, 4), new Date(2014, 9, 4))\n * //=> false\n *\n * @example\n * // Are 4 September, 2014 and 4 September, 2015 in the same day?\n * const result = isSameDay(new Date(2014, 8, 4), new Date(2015, 8, 4))\n * //=> false\n */\nexport function isSameDay(laterDate, earlierDate, options) {\n const [dateLeft_, dateRight_] = normalizeDates(\n options?.in,\n laterDate,\n earlierDate,\n );\n return +startOfDay(dateLeft_) === +startOfDay(dateRight_);\n}\n\n// Fallback for modularized imports:\nexport default isSameDay;\n", "/**\n * @name isDate\n * @category Common Helpers\n * @summary Is the given value a date?\n *\n * @description\n * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.\n *\n * @param value - The value to check\n *\n * @returns True if the given value is a date\n *\n * @example\n * // For a valid date:\n * const result = isDate(new Date())\n * //=> true\n *\n * @example\n * // For an invalid date:\n * const result = isDate(new Date(NaN))\n * //=> true\n *\n * @example\n * // For some value:\n * const result = isDate('2014-02-31')\n * //=> false\n *\n * @example\n * // For an object:\n * const result = isDate({})\n * //=> false\n */\nexport function isDate(value) {\n return (\n value instanceof Date ||\n (typeof value === \"object\" &&\n Object.prototype.toString.call(value) === \"[object Date]\")\n );\n}\n\n// Fallback for modularized imports:\nexport default isDate;\n", "import { isDate } from \"./isDate.js\";\nimport { toDate } from \"./toDate.js\";\n\n/**\n * @name isValid\n * @category Common Helpers\n * @summary Is the given date valid?\n *\n * @description\n * Returns false if argument is Invalid Date and true otherwise.\n * Argument is converted to Date using `toDate`. See [toDate](https://date-fns.org/docs/toDate)\n * Invalid Date is a Date, whose time value is NaN.\n *\n * Time value of Date: http://es5.github.io/#x15.9.1.1\n *\n * @param date - The date to check\n *\n * @returns The date is valid\n *\n * @example\n * // For the valid date:\n * const result = isValid(new Date(2014, 1, 31))\n * //=> true\n *\n * @example\n * // For the value, convertible into a date:\n * const result = isValid(1393804800000)\n * //=> true\n *\n * @example\n * // For the invalid date:\n * const result = isValid(new Date(''))\n * //=> false\n */\nexport function isValid(date) {\n return !((!isDate(date) && typeof date !== \"number\") || isNaN(+toDate(date)));\n}\n\n// Fallback for modularized imports:\nexport default isValid;\n", "import { normalizeDates } from \"./_lib/normalizeDates.js\";\n\n/**\n * The {@link differenceInCalendarMonths} function options.\n */\n\n/**\n * @name differenceInCalendarMonths\n * @category Month Helpers\n * @summary Get the number of calendar months between the given dates.\n *\n * @description\n * Get the number of calendar months between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of calendar months\n *\n * @example\n * // How many calendar months are between 31 January 2014 and 1 September 2014?\n * const result = differenceInCalendarMonths(\n * new Date(2014, 8, 1),\n * new Date(2014, 0, 31)\n * )\n * //=> 8\n */\nexport function differenceInCalendarMonths(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = normalizeDates(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const yearsDiff = laterDate_.getFullYear() - earlierDate_.getFullYear();\n const monthsDiff = laterDate_.getMonth() - earlierDate_.getMonth();\n\n return yearsDiff * 12 + monthsDiff;\n}\n\n// Fallback for modularized imports:\nexport default differenceInCalendarMonths;\n", "export function getRoundingMethod(method) {\n return (number) => {\n const round = method ? Math[method] : Math.trunc;\n const result = round(number);\n // Prevent negative zero\n return result === 0 ? 0 : result;\n };\n}\n", "import { toDate } from \"./toDate.js\";\n\n/**\n * @name differenceInMilliseconds\n * @category Millisecond Helpers\n * @summary Get the number of milliseconds between the given dates.\n *\n * @description\n * Get the number of milliseconds between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n *\n * @returns The number of milliseconds\n *\n * @example\n * // How many milliseconds are between\n * // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700?\n * const result = differenceInMilliseconds(\n * new Date(2014, 6, 2, 12, 30, 21, 700),\n * new Date(2014, 6, 2, 12, 30, 20, 600)\n * )\n * //=> 1100\n */\nexport function differenceInMilliseconds(laterDate, earlierDate) {\n return +toDate(laterDate) - +toDate(earlierDate);\n}\n\n// Fallback for modularized imports:\nexport default differenceInMilliseconds;\n", "import { toDate } from \"./toDate.js\";\n\n/**\n * The {@link endOfDay} function options.\n */\n\n/**\n * @name endOfDay\n * @category Day Helpers\n * @summary Return the end of a day for the given date.\n *\n * @description\n * Return the end of a day for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a day\n *\n * @example\n * // The end of a day for 2 September 2014 11:55:00:\n * const result = endOfDay(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 02 2014 23:59:59.999\n */\nexport function endOfDay(date, options) {\n const _date = toDate(date, options?.in);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n\n// Fallback for modularized imports:\nexport default endOfDay;\n", "import { toDate } from \"./toDate.js\";\n\n/**\n * The {@link endOfMonth} function options.\n */\n\n/**\n * @name endOfMonth\n * @category Month Helpers\n * @summary Return the end of a month for the given date.\n *\n * @description\n * Return the end of a month for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a month\n *\n * @example\n * // The end of a month for 2 September 2014 11:55:00:\n * const result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 30 2014 23:59:59.999\n */\nexport function endOfMonth(date, options) {\n const _date = toDate(date, options?.in);\n const month = _date.getMonth();\n _date.setFullYear(_date.getFullYear(), month + 1, 0);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n\n// Fallback for modularized imports:\nexport default endOfMonth;\n", "import { endOfDay } from \"./endOfDay.js\";\nimport { endOfMonth } from \"./endOfMonth.js\";\nimport { toDate } from \"./toDate.js\";\n\n/**\n * @name isLastDayOfMonth\n * @category Month Helpers\n * @summary Is the given date the last day of a month?\n *\n * @description\n * Is the given date the last day of a month?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is the last day of a month\n *\n * @example\n * // Is 28 February 2014 the last day of a month?\n * const result = isLastDayOfMonth(new Date(2014, 1, 28))\n * //=> true\n */\nexport function isLastDayOfMonth(date, options) {\n const _date = toDate(date, options?.in);\n return +endOfDay(_date, options) === +endOfMonth(_date, options);\n}\n\n// Fallback for modularized imports:\nexport default isLastDayOfMonth;\n", "import { normalizeDates } from \"./_lib/normalizeDates.js\";\nimport { compareAsc } from \"./compareAsc.js\";\nimport { differenceInCalendarMonths } from \"./differenceInCalendarMonths.js\";\nimport { isLastDayOfMonth } from \"./isLastDayOfMonth.js\";\n\n/**\n * The {@link differenceInMonths} function options.\n */\n\n/**\n * @name differenceInMonths\n * @category Month Helpers\n * @summary Get the number of full months between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of full months\n *\n * @example\n * // How many full months are between 31 January 2014 and 1 September 2014?\n * const result = differenceInMonths(new Date(2014, 8, 1), new Date(2014, 0, 31))\n * //=> 7\n */\nexport function differenceInMonths(laterDate, earlierDate, options) {\n const [laterDate_, workingLaterDate, earlierDate_] = normalizeDates(\n options?.in,\n laterDate,\n laterDate,\n earlierDate,\n );\n\n const sign = compareAsc(workingLaterDate, earlierDate_);\n const difference = Math.abs(\n differenceInCalendarMonths(workingLaterDate, earlierDate_),\n );\n\n if (difference < 1) return 0;\n\n if (workingLaterDate.getMonth() === 1 && workingLaterDate.getDate() > 27)\n workingLaterDate.setDate(30);\n\n workingLaterDate.setMonth(workingLaterDate.getMonth() - sign * difference);\n\n let isLastMonthNotFull = compareAsc(workingLaterDate, earlierDate_) === -sign;\n\n if (\n isLastDayOfMonth(laterDate_) &&\n difference === 1 &&\n compareAsc(laterDate_, earlierDate_) === 1\n ) {\n isLastMonthNotFull = false;\n }\n\n const result = sign * (difference - +isLastMonthNotFull);\n return result === 0 ? 0 : result;\n}\n\n// Fallback for modularized imports:\nexport default differenceInMonths;\n", "import { getRoundingMethod } from \"./_lib/getRoundingMethod.js\";\nimport { differenceInMilliseconds } from \"./differenceInMilliseconds.js\";\n\n/**\n * The {@link differenceInSeconds} function options.\n */\n\n/**\n * @name differenceInSeconds\n * @category Second Helpers\n * @summary Get the number of seconds between the given dates.\n *\n * @description\n * Get the number of seconds between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options.\n *\n * @returns The number of seconds\n *\n * @example\n * // How many seconds are between\n * // 2 July 2014 12:30:07.999 and 2 July 2014 12:30:20.000?\n * const result = differenceInSeconds(\n * new Date(2014, 6, 2, 12, 30, 20, 0),\n * new Date(2014, 6, 2, 12, 30, 7, 999)\n * )\n * //=> 12\n */\nexport function differenceInSeconds(laterDate, earlierDate, options) {\n const diff = differenceInMilliseconds(laterDate, earlierDate) / 1000;\n return getRoundingMethod(options?.roundingMethod)(diff);\n}\n\n// Fallback for modularized imports:\nexport default differenceInSeconds;\n", "import { toDate } from \"./toDate.js\";\n\n/**\n * The {@link startOfYear} function options.\n */\n\n/**\n * @name startOfYear\n * @category Year Helpers\n * @summary Return the start of a year for the given date.\n *\n * @description\n * Return the start of a year for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The start of a year\n *\n * @example\n * // The start of a year for 2 September 2014 11:55:00:\n * const result = startOfYear(new Date(2014, 8, 2, 11, 55, 00))\n * //=> Wed Jan 01 2014 00:00:00\n */\nexport function startOfYear(date, options) {\n const date_ = toDate(date, options?.in);\n date_.setFullYear(date_.getFullYear(), 0, 1);\n date_.setHours(0, 0, 0, 0);\n return date_;\n}\n\n// Fallback for modularized imports:\nexport default startOfYear;\n", "import { endOfDay } from \"./endOfDay.js\";\n\n/**\n * The {@link endOfToday} function options.\n */\n\n/**\n * @name endOfToday\n * @category Day Helpers\n * @summary Return the end of today.\n * @pure false\n *\n * @description\n * Return the end of today.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param options - The options\n *\n * @returns The end of today\n *\n * @example\n * // If today is 6 October 2014:\n * const result = endOfToday()\n * //=> Mon Oct 6 2014 23:59:59.999\n */\nexport function endOfToday(options) {\n return endOfDay(Date.now(), options);\n}\n\n// Fallback for modularized imports:\nexport default endOfToday;\n", "import { differenceInCalendarDays } from \"./differenceInCalendarDays.js\";\nimport { startOfYear } from \"./startOfYear.js\";\nimport { toDate } from \"./toDate.js\";\n\n/**\n * The {@link getDayOfYear} function options.\n */\n\n/**\n * @name getDayOfYear\n * @category Day Helpers\n * @summary Get the day of the year of the given date.\n *\n * @description\n * Get the day of the year of the given date.\n *\n * @param date - The given date\n * @param options - The options\n *\n * @returns The day of year\n *\n * @example\n * // Which day of the year is 2 July 2014?\n * const result = getDayOfYear(new Date(2014, 6, 2))\n * //=> 183\n */\nexport function getDayOfYear(date, options) {\n const _date = toDate(date, options?.in);\n const diff = differenceInCalendarDays(_date, startOfYear(_date));\n const dayOfYear = diff + 1;\n return dayOfYear;\n}\n\n// Fallback for modularized imports:\nexport default getDayOfYear;\n", "import { millisecondsInWeek } from \"./constants.js\";\nimport { startOfISOWeek } from \"./startOfISOWeek.js\";\nimport { startOfISOWeekYear } from \"./startOfISOWeekYear.js\";\nimport { toDate } from \"./toDate.js\";\n\n/**\n * The {@link getISOWeek} function options.\n */\n\n/**\n * @name getISOWeek\n * @category ISO Week Helpers\n * @summary Get the ISO week of the given date.\n *\n * @description\n * Get the ISO week of the given date.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The given date\n * @param options - The options\n *\n * @returns The ISO week\n *\n * @example\n * // Which week of the ISO-week numbering year is 2 January 2005?\n * const result = getISOWeek(new Date(2005, 0, 2))\n * //=> 53\n */\nexport function getISOWeek(date, options) {\n const _date = toDate(date, options?.in);\n const diff = +startOfISOWeek(_date) - +startOfISOWeekYear(_date);\n\n // Round the number of weeks to the nearest integer because the number of\n // milliseconds in a week is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(diff / millisecondsInWeek) + 1;\n}\n\n// Fallback for modularized imports:\nexport default getISOWeek;\n", "import { getDefaultOptions } from \"./_lib/defaultOptions.js\";\nimport { constructFrom } from \"./constructFrom.js\";\nimport { startOfWeek } from \"./startOfWeek.js\";\nimport { toDate } from \"./toDate.js\";\n\n/**\n * The {@link getWeekYear} function options.\n */\n\n/**\n * @name getWeekYear\n * @category Week-Numbering Year Helpers\n * @summary Get the local week-numbering year of the given date.\n *\n * @description\n * Get the local week-numbering year of the given date.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The local week-numbering year\n *\n * @example\n * // Which week numbering year is 26 December 2004 with the default settings?\n * const result = getWeekYear(new Date(2004, 11, 26))\n * //=> 2005\n *\n * @example\n * // Which week numbering year is 26 December 2004 if week starts on Saturday?\n * const result = getWeekYear(new Date(2004, 11, 26), { weekStartsOn: 6 })\n * //=> 2004\n *\n * @example\n * // Which week numbering year is 26 December 2004 if the first week contains 4 January?\n * const result = getWeekYear(new Date(2004, 11, 26), { firstWeekContainsDate: 4 })\n * //=> 2004\n */\nexport function getWeekYear(date, options) {\n const _date = toDate(date, options?.in);\n const year = _date.getFullYear();\n\n const defaultOptions = getDefaultOptions();\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const firstWeekOfNextYear = constructFrom(options?.in || date, 0);\n firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate);\n firstWeekOfNextYear.setHours(0, 0, 0, 0);\n const startOfNextYear = startOfWeek(firstWeekOfNextYear, options);\n\n const firstWeekOfThisYear = constructFrom(options?.in || date, 0);\n firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate);\n firstWeekOfThisYear.setHours(0, 0, 0, 0);\n const startOfThisYear = startOfWeek(firstWeekOfThisYear, options);\n\n if (+_date >= +startOfNextYear) {\n return year + 1;\n } else if (+_date >= +startOfThisYear) {\n return year;\n } else {\n return year - 1;\n }\n}\n\n// Fallback for modularized imports:\nexport default getWeekYear;\n", "import { getDefaultOptions } from \"./_lib/defaultOptions.js\";\nimport { constructFrom } from \"./constructFrom.js\";\nimport { getWeekYear } from \"./getWeekYear.js\";\nimport { startOfWeek } from \"./startOfWeek.js\";\n\n/**\n * The {@link startOfWeekYear} function options.\n */\n\n/**\n * @name startOfWeekYear\n * @category Week-Numbering Year Helpers\n * @summary Return the start of a local week-numbering year for the given date.\n *\n * @description\n * Return the start of a local week-numbering year.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a week-numbering year\n *\n * @example\n * // The start of an a week-numbering year for 2 July 2005 with default settings:\n * const result = startOfWeekYear(new Date(2005, 6, 2))\n * //=> Sun Dec 26 2004 00:00:00\n *\n * @example\n * // The start of a week-numbering year for 2 July 2005\n * // if Monday is the first day of week\n * // and 4 January is always in the first week of the year:\n * const result = startOfWeekYear(new Date(2005, 6, 2), {\n * weekStartsOn: 1,\n * firstWeekContainsDate: 4\n * })\n * //=> Mon Jan 03 2005 00:00:00\n */\nexport function startOfWeekYear(date, options) {\n const defaultOptions = getDefaultOptions();\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const year = getWeekYear(date, options);\n const firstWeek = constructFrom(options?.in || date, 0);\n firstWeek.setFullYear(year, 0, firstWeekContainsDate);\n firstWeek.setHours(0, 0, 0, 0);\n const _date = startOfWeek(firstWeek, options);\n return _date;\n}\n\n// Fallback for modularized imports:\nexport default startOfWeekYear;\n", "import { millisecondsInWeek } from \"./constants.js\";\nimport { startOfWeek } from \"./startOfWeek.js\";\nimport { startOfWeekYear } from \"./startOfWeekYear.js\";\nimport { toDate } from \"./toDate.js\";\n\n/**\n * The {@link getWeek} function options.\n */\n\n/**\n * @name getWeek\n * @category Week Helpers\n * @summary Get the local week index of the given date.\n *\n * @description\n * Get the local week index of the given date.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The week\n *\n * @example\n * // Which week of the local week numbering year is 2 January 2005 with default options?\n * const result = getWeek(new Date(2005, 0, 2))\n * //=> 2\n *\n * @example\n * // Which week of the local week numbering year is 2 January 2005,\n * // if Monday is the first day of the week,\n * // and the first week of the year always contains 4 January?\n * const result = getWeek(new Date(2005, 0, 2), {\n * weekStartsOn: 1,\n * firstWeekContainsDate: 4\n * })\n * //=> 53\n */\nexport function getWeek(date, options) {\n const _date = toDate(date, options?.in);\n const diff = +startOfWeek(_date, options) - +startOfWeekYear(_date, options);\n\n // Round the number of weeks to the nearest integer because the number of\n // milliseconds in a week is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(diff / millisecondsInWeek) + 1;\n}\n\n// Fallback for modularized imports:\nexport default getWeek;\n", "export function addLeadingZeros(number, targetLength) {\n const sign = number < 0 ? \"-\" : \"\";\n const output = Math.abs(number).toString().padStart(targetLength, \"0\");\n return sign + output;\n}\n", "import { addLeadingZeros } from \"../addLeadingZeros.js\";\n\n/*\n * | | Unit | | Unit |\n * |-----|--------------------------------|-----|--------------------------------|\n * | a | AM, PM | A* | |\n * | d | Day of month | D | |\n * | h | Hour [1-12] | H | Hour [0-23] |\n * | m | Minute | M | Month |\n * | s | Second | S | Fraction of second |\n * | y | Year (abs) | Y | |\n *\n * Letters marked by * are not implemented but reserved by Unicode standard.\n */\n\nexport const lightFormatters = {\n // Year\n y(date, token) {\n // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens\n // | Year | y | yy | yyy | yyyy | yyyyy |\n // |----------|-------|----|-------|-------|-------|\n // | AD 1 | 1 | 01 | 001 | 0001 | 00001 |\n // | AD 12 | 12 | 12 | 012 | 0012 | 00012 |\n // | AD 123 | 123 | 23 | 123 | 0123 | 00123 |\n // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |\n // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |\n\n const signedYear = date.getFullYear();\n // Returns 1 for 1 BC (which is year 0 in JavaScript)\n const year = signedYear > 0 ? signedYear : 1 - signedYear;\n return addLeadingZeros(token === \"yy\" ? year % 100 : year, token.length);\n },\n\n // Month\n M(date, token) {\n const month = date.getMonth();\n return token === \"M\" ? String(month + 1) : addLeadingZeros(month + 1, 2);\n },\n\n // Day of the month\n d(date, token) {\n return addLeadingZeros(date.getDate(), token.length);\n },\n\n // AM or PM\n a(date, token) {\n const dayPeriodEnumValue = date.getHours() / 12 >= 1 ? \"pm\" : \"am\";\n\n switch (token) {\n case \"a\":\n case \"aa\":\n return dayPeriodEnumValue.toUpperCase();\n case \"aaa\":\n return dayPeriodEnumValue;\n case \"aaaaa\":\n return dayPeriodEnumValue[0];\n case \"aaaa\":\n default:\n return dayPeriodEnumValue === \"am\" ? \"a.m.\" : \"p.m.\";\n }\n },\n\n // Hour [1-12]\n h(date, token) {\n return addLeadingZeros(date.getHours() % 12 || 12, token.length);\n },\n\n // Hour [0-23]\n H(date, token) {\n return addLeadingZeros(date.getHours(), token.length);\n },\n\n // Minute\n m(date, token) {\n return addLeadingZeros(date.getMinutes(), token.length);\n },\n\n // Second\n s(date, token) {\n return addLeadingZeros(date.getSeconds(), token.length);\n },\n\n // Fraction of second\n S(date, token) {\n const numberOfDigits = token.length;\n const milliseconds = date.getMilliseconds();\n const fractionalSeconds = Math.trunc(\n milliseconds * Math.pow(10, numberOfDigits - 3),\n );\n return addLeadingZeros(fractionalSeconds, token.length);\n },\n};\n", "import { getDayOfYear } from \"../../getDayOfYear.js\";\nimport { getISOWeek } from \"../../getISOWeek.js\";\nimport { getISOWeekYear } from \"../../getISOWeekYear.js\";\nimport { getWeek } from \"../../getWeek.js\";\nimport { getWeekYear } from \"../../getWeekYear.js\";\n\nimport { addLeadingZeros } from \"../addLeadingZeros.js\";\nimport { lightFormatters } from \"./lightFormatters.js\";\n\nconst dayPeriodEnum = {\n am: \"am\",\n pm: \"pm\",\n midnight: \"midnight\",\n noon: \"noon\",\n morning: \"morning\",\n afternoon: \"afternoon\",\n evening: \"evening\",\n night: \"night\",\n};\n\n/*\n * | | Unit | | Unit |\n * |-----|--------------------------------|-----|--------------------------------|\n * | a | AM, PM | A* | Milliseconds in day |\n * | b | AM, PM, noon, midnight | B | Flexible day period |\n * | c | Stand-alone local day of week | C* | Localized hour w/ day period |\n * | d | Day of month | D | Day of year |\n * | e | Local day of week | E | Day of week |\n * | f | | F* | Day of week in month |\n * | g* | Modified Julian day | G | Era |\n * | h | Hour [1-12] | H | Hour [0-23] |\n * | i! | ISO day of week | I! | ISO week of year |\n * | j* | Localized hour w/ day period | J* | Localized hour w/o day period |\n * | k | Hour [1-24] | K | Hour [0-11] |\n * | l* | (deprecated) | L | Stand-alone month |\n * | m | Minute | M | Month |\n * | n | | N | |\n * | o! | Ordinal number modifier | O | Timezone (GMT) |\n * | p! | Long localized time | P! | Long localized date |\n * | q | Stand-alone quarter | Q | Quarter |\n * | r* | Related Gregorian year | R! | ISO week-numbering year |\n * | s | Second | S | Fraction of second |\n * | t! | Seconds timestamp | T! | Milliseconds timestamp |\n * | u | Extended year | U* | Cyclic year |\n * | v* | Timezone (generic non-locat.) | V* | Timezone (location) |\n * | w | Local week of year | W* | Week of month |\n * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |\n * | y | Year (abs) | Y | Local week-numbering year |\n * | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) |\n *\n * Letters marked by * are not implemented but reserved by Unicode standard.\n *\n * Letters marked by ! are non-standard, but implemented by date-fns:\n * - `o` modifies the previous token to turn it into an ordinal (see `format` docs)\n * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,\n * i.e. 7 for Sunday, 1 for Monday, etc.\n * - `I` is ISO week of year, as opposed to `w` which is local week of year.\n * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.\n * `R` is supposed to be used in conjunction with `I` and `i`\n * for universal ISO week-numbering date, whereas\n * `Y` is supposed to be used in conjunction with `w` and `e`\n * for week-numbering date specific to the locale.\n * - `P` is long localized date format\n * - `p` is long localized time format\n */\n\nexport const formatters = {\n // Era\n G: function (date, token, localize) {\n const era = date.getFullYear() > 0 ? 1 : 0;\n switch (token) {\n // AD, BC\n case \"G\":\n case \"GG\":\n case \"GGG\":\n return localize.era(era, { width: \"abbreviated\" });\n // A, B\n case \"GGGGG\":\n return localize.era(era, { width: \"narrow\" });\n // Anno Domini, Before Christ\n case \"GGGG\":\n default:\n return localize.era(era, { width: \"wide\" });\n }\n },\n\n // Year\n y: function (date, token, localize) {\n // Ordinal number\n if (token === \"yo\") {\n const signedYear = date.getFullYear();\n // Returns 1 for 1 BC (which is year 0 in JavaScript)\n const year = signedYear > 0 ? signedYear : 1 - signedYear;\n return localize.ordinalNumber(year, { unit: \"year\" });\n }\n\n return lightFormatters.y(date, token);\n },\n\n // Local week-numbering year\n Y: function (date, token, localize, options) {\n const signedWeekYear = getWeekYear(date, options);\n // Returns 1 for 1 BC (which is year 0 in JavaScript)\n const weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;\n\n // Two digit year\n if (token === \"YY\") {\n const twoDigitYear = weekYear % 100;\n return addLeadingZeros(twoDigitYear, 2);\n }\n\n // Ordinal number\n if (token === \"Yo\") {\n return localize.ordinalNumber(weekYear, { unit: \"year\" });\n }\n\n // Padding\n return addLeadingZeros(weekYear, token.length);\n },\n\n // ISO week-numbering year\n R: function (date, token) {\n const isoWeekYear = getISOWeekYear(date);\n\n // Padding\n return addLeadingZeros(isoWeekYear, token.length);\n },\n\n // Extended year. This is a single number designating the year of this calendar system.\n // The main difference between `y` and `u` localizers are B.C. years:\n // | Year | `y` | `u` |\n // |------|-----|-----|\n // | AC 1 | 1 | 1 |\n // | BC 1 | 1 | 0 |\n // | BC 2 | 2 | -1 |\n // Also `yy` always returns the last two digits of a year,\n // while `uu` pads single digit years to 2 characters and returns other years unchanged.\n u: function (date, token) {\n const year = date.getFullYear();\n return addLeadingZeros(year, token.length);\n },\n\n // Quarter\n Q: function (date, token, localize) {\n const quarter = Math.ceil((date.getMonth() + 1) / 3);\n switch (token) {\n // 1, 2, 3, 4\n case \"Q\":\n return String(quarter);\n // 01, 02, 03, 04\n case \"QQ\":\n return addLeadingZeros(quarter, 2);\n // 1st, 2nd, 3rd, 4th\n case \"Qo\":\n return localize.ordinalNumber(quarter, { unit: \"quarter\" });\n // Q1, Q2, Q3, Q4\n case \"QQQ\":\n return localize.quarter(quarter, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // 1, 2, 3, 4 (narrow quarter; could be not numerical)\n case \"QQQQQ\":\n return localize.quarter(quarter, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // 1st quarter, 2nd quarter, ...\n case \"QQQQ\":\n default:\n return localize.quarter(quarter, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // Stand-alone quarter\n q: function (date, token, localize) {\n const quarter = Math.ceil((date.getMonth() + 1) / 3);\n switch (token) {\n // 1, 2, 3, 4\n case \"q\":\n return String(quarter);\n // 01, 02, 03, 04\n case \"qq\":\n return addLeadingZeros(quarter, 2);\n // 1st, 2nd, 3rd, 4th\n case \"qo\":\n return localize.ordinalNumber(quarter, { unit: \"quarter\" });\n // Q1, Q2, Q3, Q4\n case \"qqq\":\n return localize.quarter(quarter, {\n width: \"abbreviated\",\n context: \"standalone\",\n });\n // 1, 2, 3, 4 (narrow quarter; could be not numerical)\n case \"qqqqq\":\n return localize.quarter(quarter, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // 1st quarter, 2nd quarter, ...\n case \"qqqq\":\n default:\n return localize.quarter(quarter, {\n width: \"wide\",\n context: \"standalone\",\n });\n }\n },\n\n // Month\n M: function (date, token, localize) {\n const month = date.getMonth();\n switch (token) {\n case \"M\":\n case \"MM\":\n return lightFormatters.M(date, token);\n // 1st, 2nd, ..., 12th\n case \"Mo\":\n return localize.ordinalNumber(month + 1, { unit: \"month\" });\n // Jan, Feb, ..., Dec\n case \"MMM\":\n return localize.month(month, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // J, F, ..., D\n case \"MMMMM\":\n return localize.month(month, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // January, February, ..., December\n case \"MMMM\":\n default:\n return localize.month(month, { width: \"wide\", context: \"formatting\" });\n }\n },\n\n // Stand-alone month\n L: function (date, token, localize) {\n const month = date.getMonth();\n switch (token) {\n // 1, 2, ..., 12\n case \"L\":\n return String(month + 1);\n // 01, 02, ..., 12\n case \"LL\":\n return addLeadingZeros(month + 1, 2);\n // 1st, 2nd, ..., 12th\n case \"Lo\":\n return localize.ordinalNumber(month + 1, { unit: \"month\" });\n // Jan, Feb, ..., Dec\n case \"LLL\":\n return localize.month(month, {\n width: \"abbreviated\",\n context: \"standalone\",\n });\n // J, F, ..., D\n case \"LLLLL\":\n return localize.month(month, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // January, February, ..., December\n case \"LLLL\":\n default:\n return localize.month(month, { width: \"wide\", context: \"standalone\" });\n }\n },\n\n // Local week of year\n w: function (date, token, localize, options) {\n const week = getWeek(date, options);\n\n if (token === \"wo\") {\n return localize.ordinalNumber(week, { unit: \"week\" });\n }\n\n return addLeadingZeros(week, token.length);\n },\n\n // ISO week of year\n I: function (date, token, localize) {\n const isoWeek = getISOWeek(date);\n\n if (token === \"Io\") {\n return localize.ordinalNumber(isoWeek, { unit: \"week\" });\n }\n\n return addLeadingZeros(isoWeek, token.length);\n },\n\n // Day of the month\n d: function (date, token, localize) {\n if (token === \"do\") {\n return localize.ordinalNumber(date.getDate(), { unit: \"date\" });\n }\n\n return lightFormatters.d(date, token);\n },\n\n // Day of year\n D: function (date, token, localize) {\n const dayOfYear = getDayOfYear(date);\n\n if (token === \"Do\") {\n return localize.ordinalNumber(dayOfYear, { unit: \"dayOfYear\" });\n }\n\n return addLeadingZeros(dayOfYear, token.length);\n },\n\n // Day of week\n E: function (date, token, localize) {\n const dayOfWeek = date.getDay();\n switch (token) {\n // Tue\n case \"E\":\n case \"EE\":\n case \"EEE\":\n return localize.day(dayOfWeek, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // T\n case \"EEEEE\":\n return localize.day(dayOfWeek, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"EEEEEE\":\n return localize.day(dayOfWeek, {\n width: \"short\",\n context: \"formatting\",\n });\n // Tuesday\n case \"EEEE\":\n default:\n return localize.day(dayOfWeek, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // Local day of week\n e: function (date, token, localize, options) {\n const dayOfWeek = date.getDay();\n const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;\n switch (token) {\n // Numerical value (Nth day of week with current locale or weekStartsOn)\n case \"e\":\n return String(localDayOfWeek);\n // Padded numerical value\n case \"ee\":\n return addLeadingZeros(localDayOfWeek, 2);\n // 1st, 2nd, ..., 7th\n case \"eo\":\n return localize.ordinalNumber(localDayOfWeek, { unit: \"day\" });\n case \"eee\":\n return localize.day(dayOfWeek, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // T\n case \"eeeee\":\n return localize.day(dayOfWeek, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"eeeeee\":\n return localize.day(dayOfWeek, {\n width: \"short\",\n context: \"formatting\",\n });\n // Tuesday\n case \"eeee\":\n default:\n return localize.day(dayOfWeek, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // Stand-alone local day of week\n c: function (date, token, localize, options) {\n const dayOfWeek = date.getDay();\n const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;\n switch (token) {\n // Numerical value (same as in `e`)\n case \"c\":\n return String(localDayOfWeek);\n // Padded numerical value\n case \"cc\":\n return addLeadingZeros(localDayOfWeek, token.length);\n // 1st, 2nd, ..., 7th\n case \"co\":\n return localize.ordinalNumber(localDayOfWeek, { unit: \"day\" });\n case \"ccc\":\n return localize.day(dayOfWeek, {\n width: \"abbreviated\",\n context: \"standalone\",\n });\n // T\n case \"ccccc\":\n return localize.day(dayOfWeek, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // Tu\n case \"cccccc\":\n return localize.day(dayOfWeek, {\n width: \"short\",\n context: \"standalone\",\n });\n // Tuesday\n case \"cccc\":\n default:\n return localize.day(dayOfWeek, {\n width: \"wide\",\n context: \"standalone\",\n });\n }\n },\n\n // ISO day of week\n i: function (date, token, localize) {\n const dayOfWeek = date.getDay();\n const isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;\n switch (token) {\n // 2\n case \"i\":\n return String(isoDayOfWeek);\n // 02\n case \"ii\":\n return addLeadingZeros(isoDayOfWeek, token.length);\n // 2nd\n case \"io\":\n return localize.ordinalNumber(isoDayOfWeek, { unit: \"day\" });\n // Tue\n case \"iii\":\n return localize.day(dayOfWeek, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // T\n case \"iiiii\":\n return localize.day(dayOfWeek, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"iiiiii\":\n return localize.day(dayOfWeek, {\n width: \"short\",\n context: \"formatting\",\n });\n // Tuesday\n case \"iiii\":\n default:\n return localize.day(dayOfWeek, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // AM or PM\n a: function (date, token, localize) {\n const hours = date.getHours();\n const dayPeriodEnumValue = hours / 12 >= 1 ? \"pm\" : \"am\";\n\n switch (token) {\n case \"a\":\n case \"aa\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n case \"aaa\":\n return localize\n .dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n })\n .toLowerCase();\n case \"aaaaa\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"aaaa\":\n default:\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // AM, PM, midnight, noon\n b: function (date, token, localize) {\n const hours = date.getHours();\n let dayPeriodEnumValue;\n if (hours === 12) {\n dayPeriodEnumValue = dayPeriodEnum.noon;\n } else if (hours === 0) {\n dayPeriodEnumValue = dayPeriodEnum.midnight;\n } else {\n dayPeriodEnumValue = hours / 12 >= 1 ? \"pm\" : \"am\";\n }\n\n switch (token) {\n case \"b\":\n case \"bb\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n case \"bbb\":\n return localize\n .dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n })\n .toLowerCase();\n case \"bbbbb\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"bbbb\":\n default:\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // in the morning, in the afternoon, in the evening, at night\n B: function (date, token, localize) {\n const hours = date.getHours();\n let dayPeriodEnumValue;\n if (hours >= 17) {\n dayPeriodEnumValue = dayPeriodEnum.evening;\n } else if (hours >= 12) {\n dayPeriodEnumValue = dayPeriodEnum.afternoon;\n } else if (hours >= 4) {\n dayPeriodEnumValue = dayPeriodEnum.morning;\n } else {\n dayPeriodEnumValue = dayPeriodEnum.night;\n }\n\n switch (token) {\n case \"B\":\n case \"BB\":\n case \"BBB\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n case \"BBBBB\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"BBBB\":\n default:\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // Hour [1-12]\n h: function (date, token, localize) {\n if (token === \"ho\") {\n let hours = date.getHours() % 12;\n if (hours === 0) hours = 12;\n return localize.ordinalNumber(hours, { unit: \"hour\" });\n }\n\n return lightFormatters.h(date, token);\n },\n\n // Hour [0-23]\n H: function (date, token, localize) {\n if (token === \"Ho\") {\n return localize.ordinalNumber(date.getHours(), { unit: \"hour\" });\n }\n\n return lightFormatters.H(date, token);\n },\n\n // Hour [0-11]\n K: function (date, token, localize) {\n const hours = date.getHours() % 12;\n\n if (token === \"Ko\") {\n return localize.ordinalNumber(hours, { unit: \"hour\" });\n }\n\n return addLeadingZeros(hours, token.length);\n },\n\n // Hour [1-24]\n k: function (date, token, localize) {\n let hours = date.getHours();\n if (hours === 0) hours = 24;\n\n if (token === \"ko\") {\n return localize.ordinalNumber(hours, { unit: \"hour\" });\n }\n\n return addLeadingZeros(hours, token.length);\n },\n\n // Minute\n m: function (date, token, localize) {\n if (token === \"mo\") {\n return localize.ordinalNumber(date.getMinutes(), { unit: \"minute\" });\n }\n\n return lightFormatters.m(date, token);\n },\n\n // Second\n s: function (date, token, localize) {\n if (token === \"so\") {\n return localize.ordinalNumber(date.getSeconds(), { unit: \"second\" });\n }\n\n return lightFormatters.s(date, token);\n },\n\n // Fraction of second\n S: function (date, token) {\n return lightFormatters.S(date, token);\n },\n\n // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)\n X: function (date, token, _localize) {\n const timezoneOffset = date.getTimezoneOffset();\n\n if (timezoneOffset === 0) {\n return \"Z\";\n }\n\n switch (token) {\n // Hours and optional minutes\n case \"X\":\n return formatTimezoneWithOptionalMinutes(timezoneOffset);\n\n // Hours, minutes and optional seconds without `:` delimiter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `XX`\n case \"XXXX\":\n case \"XX\": // Hours and minutes without `:` delimiter\n return formatTimezone(timezoneOffset);\n\n // Hours, minutes and optional seconds with `:` delimiter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `XXX`\n case \"XXXXX\":\n case \"XXX\": // Hours and minutes with `:` delimiter\n default:\n return formatTimezone(timezoneOffset, \":\");\n }\n },\n\n // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)\n x: function (date, token, _localize) {\n const timezoneOffset = date.getTimezoneOffset();\n\n switch (token) {\n // Hours and optional minutes\n case \"x\":\n return formatTimezoneWithOptionalMinutes(timezoneOffset);\n\n // Hours, minutes and optional seconds without `:` delimiter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `xx`\n case \"xxxx\":\n case \"xx\": // Hours and minutes without `:` delimiter\n return formatTimezone(timezoneOffset);\n\n // Hours, minutes and optional seconds with `:` delimiter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `xxx`\n case \"xxxxx\":\n case \"xxx\": // Hours and minutes with `:` delimiter\n default:\n return formatTimezone(timezoneOffset, \":\");\n }\n },\n\n // Timezone (GMT)\n O: function (date, token, _localize) {\n const timezoneOffset = date.getTimezoneOffset();\n\n switch (token) {\n // Short\n case \"O\":\n case \"OO\":\n case \"OOO\":\n return \"GMT\" + formatTimezoneShort(timezoneOffset, \":\");\n // Long\n case \"OOOO\":\n default:\n return \"GMT\" + formatTimezone(timezoneOffset, \":\");\n }\n },\n\n // Timezone (specific non-location)\n z: function (date, token, _localize) {\n const timezoneOffset = date.getTimezoneOffset();\n\n switch (token) {\n // Short\n case \"z\":\n case \"zz\":\n case \"zzz\":\n return \"GMT\" + formatTimezoneShort(timezoneOffset, \":\");\n // Long\n case \"zzzz\":\n default:\n return \"GMT\" + formatTimezone(timezoneOffset, \":\");\n }\n },\n\n // Seconds timestamp\n t: function (date, token, _localize) {\n const timestamp = Math.trunc(+date / 1000);\n return addLeadingZeros(timestamp, token.length);\n },\n\n // Milliseconds timestamp\n T: function (date, token, _localize) {\n return addLeadingZeros(+date, token.length);\n },\n};\n\nfunction formatTimezoneShort(offset, delimiter = \"\") {\n const sign = offset > 0 ? \"-\" : \"+\";\n const absOffset = Math.abs(offset);\n const hours = Math.trunc(absOffset / 60);\n const minutes = absOffset % 60;\n if (minutes === 0) {\n return sign + String(hours);\n }\n return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);\n}\n\nfunction formatTimezoneWithOptionalMinutes(offset, delimiter) {\n if (offset % 60 === 0) {\n const sign = offset > 0 ? \"-\" : \"+\";\n return sign + addLeadingZeros(Math.abs(offset) / 60, 2);\n }\n return formatTimezone(offset, delimiter);\n}\n\nfunction formatTimezone(offset, delimiter = \"\") {\n const sign = offset > 0 ? \"-\" : \"+\";\n const absOffset = Math.abs(offset);\n const hours = addLeadingZeros(Math.trunc(absOffset / 60), 2);\n const minutes = addLeadingZeros(absOffset % 60, 2);\n return sign + hours + delimiter + minutes;\n}\n", "const dateLongFormatter = (pattern, formatLong) => {\n switch (pattern) {\n case \"P\":\n return formatLong.date({ width: \"short\" });\n case \"PP\":\n return formatLong.date({ width: \"medium\" });\n case \"PPP\":\n return formatLong.date({ width: \"long\" });\n case \"PPPP\":\n default:\n return formatLong.date({ width: \"full\" });\n }\n};\n\nconst timeLongFormatter = (pattern, formatLong) => {\n switch (pattern) {\n case \"p\":\n return formatLong.time({ width: \"short\" });\n case \"pp\":\n return formatLong.time({ width: \"medium\" });\n case \"ppp\":\n return formatLong.time({ width: \"long\" });\n case \"pppp\":\n default:\n return formatLong.time({ width: \"full\" });\n }\n};\n\nconst dateTimeLongFormatter = (pattern, formatLong) => {\n const matchResult = pattern.match(/(P+)(p+)?/) || [];\n const datePattern = matchResult[1];\n const timePattern = matchResult[2];\n\n if (!timePattern) {\n return dateLongFormatter(pattern, formatLong);\n }\n\n let dateTimeFormat;\n\n switch (datePattern) {\n case \"P\":\n dateTimeFormat = formatLong.dateTime({ width: \"short\" });\n break;\n case \"PP\":\n dateTimeFormat = formatLong.dateTime({ width: \"medium\" });\n break;\n case \"PPP\":\n dateTimeFormat = formatLong.dateTime({ width: \"long\" });\n break;\n case \"PPPP\":\n default:\n dateTimeFormat = formatLong.dateTime({ width: \"full\" });\n break;\n }\n\n return dateTimeFormat\n .replace(\"{{date}}\", dateLongFormatter(datePattern, formatLong))\n .replace(\"{{time}}\", timeLongFormatter(timePattern, formatLong));\n};\n\nexport const longFormatters = {\n p: timeLongFormatter,\n P: dateTimeLongFormatter,\n};\n", "const dayOfYearTokenRE = /^D+$/;\nconst weekYearTokenRE = /^Y+$/;\n\nconst throwTokens = [\"D\", \"DD\", \"YY\", \"YYYY\"];\n\nexport function isProtectedDayOfYearToken(token) {\n return dayOfYearTokenRE.test(token);\n}\n\nexport function isProtectedWeekYearToken(token) {\n return weekYearTokenRE.test(token);\n}\n\nexport function warnOrThrowProtectedError(token, format, input) {\n const _message = message(token, format, input);\n console.warn(_message);\n if (throwTokens.includes(token)) throw new RangeError(_message);\n}\n\nfunction message(token, format, input) {\n const subject = token[0] === \"Y\" ? \"years\" : \"days of the month\";\n return `Use \\`${token.toLowerCase()}\\` instead of \\`${token}\\` (in \\`${format}\\`) for formatting ${subject} to the input \\`${input}\\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`;\n}\n", "import { defaultLocale } from \"./_lib/defaultLocale.js\";\nimport { getDefaultOptions } from \"./_lib/defaultOptions.js\";\nimport { formatters } from \"./_lib/format/formatters.js\";\nimport { longFormatters } from \"./_lib/format/longFormatters.js\";\nimport {\n isProtectedDayOfYearToken,\n isProtectedWeekYearToken,\n warnOrThrowProtectedError,\n} from \"./_lib/protectedTokens.js\";\nimport { isValid } from \"./isValid.js\";\nimport { toDate } from \"./toDate.js\";\n\n// Rexports of internal for libraries to use.\n// See: https://github.com/date-fns/date-fns/issues/3638#issuecomment-1877082874\nexport { formatters, longFormatters };\n\n// This RegExp consists of three parts separated by `|`:\n// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token\n// (one of the certain letters followed by `o`)\n// - (\\w)\\1* matches any sequences of the same letter\n// - '' matches two quote characters in a row\n// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),\n// except a single quote symbol, which ends the sequence.\n// Two quote characters do not end the sequence.\n// If there is no matching single quote\n// then the sequence will continue until the end of the string.\n// - . matches any single character unmatched by previous parts of the RegExps\nconst formattingTokensRegExp =\n /[yYQqMLwIdDecihHKkms]o|(\\w)\\1*|''|'(''|[^'])+('|$)|./g;\n\n// This RegExp catches symbols escaped by quotes, and also\n// sequences of symbols P, p, and the combinations like `PPPPPPPppppp`\nconst longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;\n\nconst escapedStringRegExp = /^'([^]*?)'?$/;\nconst doubleQuoteRegExp = /''/g;\nconst unescapedLatinCharacterRegExp = /[a-zA-Z]/;\n\nexport { format as formatDate };\n\n/**\n * The {@link format} function options.\n */\n\n/**\n * @name format\n * @alias formatDate\n * @category Common Helpers\n * @summary Format the date.\n *\n * @description\n * Return the formatted date string in the given format. The result may vary by locale.\n *\n * > \u26A0\uFE0F Please note that the `format` tokens differ from Moment.js and other libraries.\n * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * The characters wrapped between two single quotes characters (') are escaped.\n * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.\n * (see the last example)\n *\n * Format of the string is based on Unicode Technical Standard #35:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n * with a few additions (see note 7 below the table).\n *\n * Accepted patterns:\n * | Unit | Pattern | Result examples | Notes |\n * |---------------------------------|---------|-----------------------------------|-------|\n * | Era | G..GGG | AD, BC | |\n * | | GGGG | Anno Domini, Before Christ | 2 |\n * | | GGGGG | A, B | |\n * | Calendar year | y | 44, 1, 1900, 2017 | 5 |\n * | | yo | 44th, 1st, 0th, 17th | 5,7 |\n * | | yy | 44, 01, 00, 17 | 5 |\n * | | yyy | 044, 001, 1900, 2017 | 5 |\n * | | yyyy | 0044, 0001, 1900, 2017 | 5 |\n * | | yyyyy | ... | 3,5 |\n * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |\n * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |\n * | | YY | 44, 01, 00, 17 | 5,8 |\n * | | YYY | 044, 001, 1900, 2017 | 5 |\n * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |\n * | | YYYYY | ... | 3,5 |\n * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |\n * | | RR | -43, 00, 01, 1900, 2017 | 5,7 |\n * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |\n * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |\n * | | RRRRR | ... | 3,5,7 |\n * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |\n * | | uu | -43, 01, 1900, 2017 | 5 |\n * | | uuu | -043, 001, 1900, 2017 | 5 |\n * | | uuuu | -0043, 0001, 1900, 2017 | 5 |\n * | | uuuuu | ... | 3,5 |\n * | Quarter (formatting) | Q | 1, 2, 3, 4 | |\n * | | Qo | 1st, 2nd, 3rd, 4th | 7 |\n * | | QQ | 01, 02, 03, 04 | |\n * | | QQQ | Q1, Q2, Q3, Q4 | |\n * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |\n * | | QQQQQ | 1, 2, 3, 4 | 4 |\n * | Quarter (stand-alone) | q | 1, 2, 3, 4 | |\n * | | qo | 1st, 2nd, 3rd, 4th | 7 |\n * | | qq | 01, 02, 03, 04 | |\n * | | qqq | Q1, Q2, Q3, Q4 | |\n * | | qqqq | 1st quarter, 2nd quarter, ... | 2 |\n * | | qqqqq | 1, 2, 3, 4 | 4 |\n * | Month (formatting) | M | 1, 2, ..., 12 | |\n * | | Mo | 1st, 2nd, ..., 12th | 7 |\n * | | MM | 01, 02, ..., 12 | |\n * | | MMM | Jan, Feb, ..., Dec | |\n * | | MMMM | January, February, ..., December | 2 |\n * | | MMMMM | J, F, ..., D | |\n * | Month (stand-alone) | L | 1, 2, ..., 12 | |\n * | | Lo | 1st, 2nd, ..., 12th | 7 |\n * | | LL | 01, 02, ..., 12 | |\n * | | LLL | Jan, Feb, ..., Dec | |\n * | | LLLL | January, February, ..., December | 2 |\n * | | LLLLL | J, F, ..., D | |\n * | Local week of year | w | 1, 2, ..., 53 | |\n * | | wo | 1st, 2nd, ..., 53th | 7 |\n * | | ww | 01, 02, ..., 53 | |\n * | ISO week of year | I | 1, 2, ..., 53 | 7 |\n * | | Io | 1st, 2nd, ..., 53th | 7 |\n * | | II | 01, 02, ..., 53 | 7 |\n * | Day of month | d | 1, 2, ..., 31 | |\n * | | do | 1st, 2nd, ..., 31st | 7 |\n * | | dd | 01, 02, ..., 31 | |\n * | Day of year | D | 1, 2, ..., 365, 366 | 9 |\n * | | Do | 1st, 2nd, ..., 365th, 366th | 7 |\n * | | DD | 01, 02, ..., 365, 366 | 9 |\n * | | DDD | 001, 002, ..., 365, 366 | |\n * | | DDDD | ... | 3 |\n * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | |\n * | | EEEE | Monday, Tuesday, ..., Sunday | 2 |\n * | | EEEEE | M, T, W, T, F, S, S | |\n * | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |\n * | | io | 1st, 2nd, ..., 7th | 7 |\n * | | ii | 01, 02, ..., 07 | 7 |\n * | | iii | Mon, Tue, Wed, ..., Sun | 7 |\n * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |\n * | | iiiii | M, T, W, T, F, S, S | 7 |\n * | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 |\n * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |\n * | | eo | 2nd, 3rd, ..., 1st | 7 |\n * | | ee | 02, 03, ..., 01 | |\n * | | eee | Mon, Tue, Wed, ..., Sun | |\n * | | eeee | Monday, Tuesday, ..., Sunday | 2 |\n * | | eeeee | M, T, W, T, F, S, S | |\n * | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |\n * | | co | 2nd, 3rd, ..., 1st | 7 |\n * | | cc | 02, 03, ..., 01 | |\n * | | ccc | Mon, Tue, Wed, ..., Sun | |\n * | | cccc | Monday, Tuesday, ..., Sunday | 2 |\n * | | ccccc | M, T, W, T, F, S, S | |\n * | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | AM, PM | a..aa | AM, PM | |\n * | | aaa | am, pm | |\n * | | aaaa | a.m., p.m. | 2 |\n * | | aaaaa | a, p | |\n * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | |\n * | | bbb | am, pm, noon, midnight | |\n * | | bbbb | a.m., p.m., noon, midnight | 2 |\n * | | bbbbb | a, p, n, mi | |\n * | Flexible day period | B..BBB | at night, in the morning, ... | |\n * | | BBBB | at night, in the morning, ... | 2 |\n * | | BBBBB | at night, in the morning, ... | |\n * | Hour [1-12] | h | 1, 2, ..., 11, 12 | |\n * | | ho | 1st, 2nd, ..., 11th, 12th | 7 |\n * | | hh | 01, 02, ..., 11, 12 | |\n * | Hour [0-23] | H | 0, 1, 2, ..., 23 | |\n * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |\n * | | HH | 00, 01, 02, ..., 23 | |\n * | Hour [0-11] | K | 1, 2, ..., 11, 0 | |\n * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |\n * | | KK | 01, 02, ..., 11, 00 | |\n * | Hour [1-24] | k | 24, 1, 2, ..., 23 | |\n * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |\n * | | kk | 24, 01, 02, ..., 23 | |\n * | Minute | m | 0, 1, ..., 59 | |\n * | | mo | 0th, 1st, ..., 59th | 7 |\n * | | mm | 00, 01, ..., 59 | |\n * | Second | s | 0, 1, ..., 59 | |\n * | | so | 0th, 1st, ..., 59th | 7 |\n * | | ss | 00, 01, ..., 59 | |\n * | Fraction of second | S | 0, 1, ..., 9 | |\n * | | SS | 00, 01, ..., 99 | |\n * | | SSS | 000, 001, ..., 999 | |\n * | | SSSS | ... | 3 |\n * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |\n * | | XX | -0800, +0530, Z | |\n * | | XXX | -08:00, +05:30, Z | |\n * | | XXXX | -0800, +0530, Z, +123456 | 2 |\n * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |\n * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |\n * | | xx | -0800, +0530, +0000 | |\n * | | xxx | -08:00, +05:30, +00:00 | 2 |\n * | | xxxx | -0800, +0530, +0000, +123456 | |\n * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |\n * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |\n * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |\n * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |\n * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |\n * | Seconds timestamp | t | 512969520 | 7 |\n * | | tt | ... | 3,7 |\n * | Milliseconds timestamp | T | 512969520900 | 7 |\n * | | TT | ... | 3,7 |\n * | Long localized date | P | 04/29/1453 | 7 |\n * | | PP | Apr 29, 1453 | 7 |\n * | | PPP | April 29th, 1453 | 7 |\n * | | PPPP | Friday, April 29th, 1453 | 2,7 |\n * | Long localized time | p | 12:00 AM | 7 |\n * | | pp | 12:00:00 AM | 7 |\n * | | ppp | 12:00:00 AM GMT+2 | 7 |\n * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |\n * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 |\n * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 |\n * | | PPPppp | April 29th, 1453 at ... | 7 |\n * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 |\n * Notes:\n * 1. \"Formatting\" units (e.g. formatting quarter) in the default en-US locale\n * are the same as \"stand-alone\" units, but are different in some languages.\n * \"Formatting\" units are declined according to the rules of the language\n * in the context of a date. \"Stand-alone\" units are always nominative singular:\n *\n * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`\n *\n * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`\n *\n * 2. Any sequence of the identical letters is a pattern, unless it is escaped by\n * the single quote characters (see below).\n * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)\n * the output will be the same as default pattern for this unit, usually\n * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units\n * are marked with \"2\" in the last column of the table.\n *\n * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`\n *\n * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`\n *\n * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`\n *\n * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`\n *\n * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`\n *\n * 3. Some patterns could be unlimited length (such as `yyyyyyyy`).\n * The output will be padded with zeros to match the length of the pattern.\n *\n * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`\n *\n * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.\n * These tokens represent the shortest form of the quarter.\n *\n * 5. The main difference between `y` and `u` patterns are B.C. years:\n *\n * | Year | `y` | `u` |\n * |------|-----|-----|\n * | AC 1 | 1 | 1 |\n * | BC 1 | 1 | 0 |\n * | BC 2 | 2 | -1 |\n *\n * Also `yy` always returns the last two digits of a year,\n * while `uu` pads single digit years to 2 characters and returns other years unchanged:\n *\n * | Year | `yy` | `uu` |\n * |------|------|------|\n * | 1 | 01 | 01 |\n * | 14 | 14 | 14 |\n * | 376 | 76 | 376 |\n * | 1453 | 53 | 1453 |\n *\n * The same difference is true for local and ISO week-numbering years (`Y` and `R`),\n * except local week-numbering years are dependent on `options.weekStartsOn`\n * and `options.firstWeekContainsDate` (compare [getISOWeekYear](https://date-fns.org/docs/getISOWeekYear)\n * and [getWeekYear](https://date-fns.org/docs/getWeekYear)).\n *\n * 6. Specific non-location timezones are currently unavailable in `date-fns`,\n * so right now these tokens fall back to GMT timezones.\n *\n * 7. These patterns are not in the Unicode Technical Standard #35:\n * - `i`: ISO day of week\n * - `I`: ISO week of year\n * - `R`: ISO week-numbering year\n * - `t`: seconds timestamp\n * - `T`: milliseconds timestamp\n * - `o`: ordinal number modifier\n * - `P`: long localized date\n * - `p`: long localized time\n *\n * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.\n * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.\n * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * @param date - The original date\n * @param format - The string of tokens\n * @param options - An object with options\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n * @throws `options.locale` must contain `localize` property\n * @throws `options.locale` must contain `formatLong` property\n * @throws use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws format string contains an unescaped latin alphabet character\n *\n * @example\n * // Represent 11 February 2014 in middle-endian format:\n * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')\n * //=> '02/11/2014'\n *\n * @example\n * // Represent 2 July 2014 in Esperanto:\n * import { eoLocale } from 'date-fns/locale/eo'\n * const result = format(new Date(2014, 6, 2), \"do 'de' MMMM yyyy\", {\n * locale: eoLocale\n * })\n * //=> '2-a de julio 2014'\n *\n * @example\n * // Escape string by single quote characters:\n * const result = format(new Date(2014, 6, 2, 15), \"h 'o''clock'\")\n * //=> \"3 o'clock\"\n */\nexport function format(date, formatStr, options) {\n const defaultOptions = getDefaultOptions();\n const locale = options?.locale ?? defaultOptions.locale ?? defaultLocale;\n\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const originalDate = toDate(date, options?.in);\n\n if (!isValid(originalDate)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n let parts = formatStr\n .match(longFormattingTokensRegExp)\n .map((substring) => {\n const firstCharacter = substring[0];\n if (firstCharacter === \"p\" || firstCharacter === \"P\") {\n const longFormatter = longFormatters[firstCharacter];\n return longFormatter(substring, locale.formatLong);\n }\n return substring;\n })\n .join(\"\")\n .match(formattingTokensRegExp)\n .map((substring) => {\n // Replace two single quote characters with one single quote character\n if (substring === \"''\") {\n return { isToken: false, value: \"'\" };\n }\n\n const firstCharacter = substring[0];\n if (firstCharacter === \"'\") {\n return { isToken: false, value: cleanEscapedString(substring) };\n }\n\n if (formatters[firstCharacter]) {\n return { isToken: true, value: substring };\n }\n\n if (firstCharacter.match(unescapedLatinCharacterRegExp)) {\n throw new RangeError(\n \"Format string contains an unescaped latin alphabet character `\" +\n firstCharacter +\n \"`\",\n );\n }\n\n return { isToken: false, value: substring };\n });\n\n // invoke localize preprocessor (only for french locales at the moment)\n if (locale.localize.preprocessor) {\n parts = locale.localize.preprocessor(originalDate, parts);\n }\n\n const formatterOptions = {\n firstWeekContainsDate,\n weekStartsOn,\n locale,\n };\n\n return parts\n .map((part) => {\n if (!part.isToken) return part.value;\n\n const token = part.value;\n\n if (\n (!options?.useAdditionalWeekYearTokens &&\n isProtectedWeekYearToken(token)) ||\n (!options?.useAdditionalDayOfYearTokens &&\n isProtectedDayOfYearToken(token))\n ) {\n warnOrThrowProtectedError(token, formatStr, String(date));\n }\n\n const formatter = formatters[token[0]];\n return formatter(originalDate, token, locale.localize, formatterOptions);\n })\n .join(\"\");\n}\n\nfunction cleanEscapedString(input) {\n const matched = input.match(escapedStringRegExp);\n\n if (!matched) {\n return input;\n }\n\n return matched[1].replace(doubleQuoteRegExp, \"'\");\n}\n\n// Fallback for modularized imports:\nexport default format;\n", "import { defaultLocale } from \"./_lib/defaultLocale.js\";\nimport { getDefaultOptions } from \"./_lib/defaultOptions.js\";\nimport { getTimezoneOffsetInMilliseconds } from \"./_lib/getTimezoneOffsetInMilliseconds.js\";\nimport { normalizeDates } from \"./_lib/normalizeDates.js\";\nimport { compareAsc } from \"./compareAsc.js\";\nimport { minutesInDay, minutesInMonth } from \"./constants.js\";\nimport { differenceInMonths } from \"./differenceInMonths.js\";\nimport { differenceInSeconds } from \"./differenceInSeconds.js\";\n\n/**\n * The {@link formatDistance} function options.\n */\n\n/**\n * @name formatDistance\n * @category Common Helpers\n * @summary Return the distance between the given dates in words.\n *\n * @description\n * Return the distance between the given dates in words.\n *\n * | Distance between dates | Result |\n * |-------------------------------------------------------------------|---------------------|\n * | 0 ... 30 secs | less than a minute |\n * | 30 secs ... 1 min 30 secs | 1 minute |\n * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes |\n * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour |\n * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours |\n * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day |\n * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days |\n * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month |\n * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months |\n * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months |\n * | 1 yr ... 1 yr 3 months | about 1 year |\n * | 1 yr 3 months ... 1 yr 9 month s | over 1 year |\n * | 1 yr 9 months ... 2 yrs | almost 2 years |\n * | N yrs ... N yrs 3 months | about N years |\n * | N yrs 3 months ... N yrs 9 months | over N years |\n * | N yrs 9 months ... N+1 yrs | almost N+1 years |\n *\n * With `options.includeSeconds == true`:\n * | Distance between dates | Result |\n * |------------------------|----------------------|\n * | 0 secs ... 5 secs | less than 5 seconds |\n * | 5 secs ... 10 secs | less than 10 seconds |\n * | 10 secs ... 20 secs | less than 20 seconds |\n * | 20 secs ... 40 secs | half a minute |\n * | 40 secs ... 60 secs | less than a minute |\n * | 60 secs ... 90 secs | 1 minute |\n *\n * @param laterDate - The date\n * @param earlierDate - The date to compare with\n * @param options - An object with options\n *\n * @returns The distance in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `baseDate` must not be Invalid Date\n * @throws `options.locale` must contain `formatDistance` property\n *\n * @example\n * // What is the distance between 2 July 2014 and 1 January 2015?\n * const result = formatDistance(new Date(2014, 6, 2), new Date(2015, 0, 1))\n * //=> '6 months'\n *\n * @example\n * // What is the distance between 1 January 2015 00:00:15\n * // and 1 January 2015 00:00:00, including seconds?\n * const result = formatDistance(\n * new Date(2015, 0, 1, 0, 0, 15),\n * new Date(2015, 0, 1, 0, 0, 0),\n * { includeSeconds: true }\n * )\n * //=> 'less than 20 seconds'\n *\n * @example\n * // What is the distance from 1 January 2016\n * // to 1 January 2015, with a suffix?\n * const result = formatDistance(new Date(2015, 0, 1), new Date(2016, 0, 1), {\n * addSuffix: true\n * })\n * //=> 'about 1 year ago'\n *\n * @example\n * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto?\n * import { eoLocale } from 'date-fns/locale/eo'\n * const result = formatDistance(new Date(2016, 7, 1), new Date(2015, 0, 1), {\n * locale: eoLocale\n * })\n * //=> 'pli ol 1 jaro'\n */\nexport function formatDistance(laterDate, earlierDate, options) {\n const defaultOptions = getDefaultOptions();\n const locale = options?.locale ?? defaultOptions.locale ?? defaultLocale;\n const minutesInAlmostTwoDays = 2520;\n\n const comparison = compareAsc(laterDate, earlierDate);\n\n if (isNaN(comparison)) throw new RangeError(\"Invalid time value\");\n\n const localizeOptions = Object.assign({}, options, {\n addSuffix: options?.addSuffix,\n comparison: comparison,\n });\n\n const [laterDate_, earlierDate_] = normalizeDates(\n options?.in,\n ...(comparison > 0 ? [earlierDate, laterDate] : [laterDate, earlierDate]),\n );\n\n const seconds = differenceInSeconds(earlierDate_, laterDate_);\n const offsetInSeconds =\n (getTimezoneOffsetInMilliseconds(earlierDate_) -\n getTimezoneOffsetInMilliseconds(laterDate_)) /\n 1000;\n const minutes = Math.round((seconds - offsetInSeconds) / 60);\n let months;\n\n // 0 up to 2 mins\n if (minutes < 2) {\n if (options?.includeSeconds) {\n if (seconds < 5) {\n return locale.formatDistance(\"lessThanXSeconds\", 5, localizeOptions);\n } else if (seconds < 10) {\n return locale.formatDistance(\"lessThanXSeconds\", 10, localizeOptions);\n } else if (seconds < 20) {\n return locale.formatDistance(\"lessThanXSeconds\", 20, localizeOptions);\n } else if (seconds < 40) {\n return locale.formatDistance(\"halfAMinute\", 0, localizeOptions);\n } else if (seconds < 60) {\n return locale.formatDistance(\"lessThanXMinutes\", 1, localizeOptions);\n } else {\n return locale.formatDistance(\"xMinutes\", 1, localizeOptions);\n }\n } else {\n if (minutes === 0) {\n return locale.formatDistance(\"lessThanXMinutes\", 1, localizeOptions);\n } else {\n return locale.formatDistance(\"xMinutes\", minutes, localizeOptions);\n }\n }\n\n // 2 mins up to 0.75 hrs\n } else if (minutes < 45) {\n return locale.formatDistance(\"xMinutes\", minutes, localizeOptions);\n\n // 0.75 hrs up to 1.5 hrs\n } else if (minutes < 90) {\n return locale.formatDistance(\"aboutXHours\", 1, localizeOptions);\n\n // 1.5 hrs up to 24 hrs\n } else if (minutes < minutesInDay) {\n const hours = Math.round(minutes / 60);\n return locale.formatDistance(\"aboutXHours\", hours, localizeOptions);\n\n // 1 day up to 1.75 days\n } else if (minutes < minutesInAlmostTwoDays) {\n return locale.formatDistance(\"xDays\", 1, localizeOptions);\n\n // 1.75 days up to 30 days\n } else if (minutes < minutesInMonth) {\n const days = Math.round(minutes / minutesInDay);\n return locale.formatDistance(\"xDays\", days, localizeOptions);\n\n // 1 month up to 2 months\n } else if (minutes < minutesInMonth * 2) {\n months = Math.round(minutes / minutesInMonth);\n return locale.formatDistance(\"aboutXMonths\", months, localizeOptions);\n }\n\n months = differenceInMonths(earlierDate_, laterDate_);\n\n // 2 months up to 12 months\n if (months < 12) {\n const nearestMonth = Math.round(minutes / minutesInMonth);\n return locale.formatDistance(\"xMonths\", nearestMonth, localizeOptions);\n\n // 1 year up to max Date\n } else {\n const monthsSinceStartOfYear = months % 12;\n const years = Math.trunc(months / 12);\n\n // N years up to 1 years 3 months\n if (monthsSinceStartOfYear < 3) {\n return locale.formatDistance(\"aboutXYears\", years, localizeOptions);\n\n // N years 3 months up to N years 9 months\n } else if (monthsSinceStartOfYear < 9) {\n return locale.formatDistance(\"overXYears\", years, localizeOptions);\n\n // N years 9 months up to N year 12 months\n } else {\n return locale.formatDistance(\"almostXYears\", years + 1, localizeOptions);\n }\n }\n}\n\n// Fallback for modularized imports:\nexport default formatDistance;\n", "import { constructNow } from \"./constructNow.js\";\n\nimport { formatDistance } from \"./formatDistance.js\";\n\n/**\n * The {@link formatDistanceToNow} function options.\n */\n\n/**\n * @name formatDistanceToNow\n * @category Common Helpers\n * @summary Return the distance between the given date and now in words.\n * @pure false\n *\n * @description\n * Return the distance between the given date and now in words.\n *\n * | Distance to now | Result |\n * |-------------------------------------------------------------------|---------------------|\n * | 0 ... 30 secs | less than a minute |\n * | 30 secs ... 1 min 30 secs | 1 minute |\n * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes |\n * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour |\n * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours |\n * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day |\n * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days |\n * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month |\n * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months |\n * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months |\n * | 1 yr ... 1 yr 3 months | about 1 year |\n * | 1 yr 3 months ... 1 yr 9 month s | over 1 year |\n * | 1 yr 9 months ... 2 yrs | almost 2 years |\n * | N yrs ... N yrs 3 months | about N years |\n * | N yrs 3 months ... N yrs 9 months | over N years |\n * | N yrs 9 months ... N+1 yrs | almost N+1 years |\n *\n * With `options.includeSeconds == true`:\n * | Distance to now | Result |\n * |---------------------|----------------------|\n * | 0 secs ... 5 secs | less than 5 seconds |\n * | 5 secs ... 10 secs | less than 10 seconds |\n * | 10 secs ... 20 secs | less than 20 seconds |\n * | 20 secs ... 40 secs | half a minute |\n * | 40 secs ... 60 secs | less than a minute |\n * | 60 secs ... 90 secs | 1 minute |\n *\n * @param date - The given date\n * @param options - The object with options\n *\n * @returns The distance in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `options.locale` must contain `formatDistance` property\n *\n * @example\n * // If today is 1 January 2015, what is the distance to 2 July 2014?\n * const result = formatDistanceToNow(\n * new Date(2014, 6, 2)\n * )\n * //=> '6 months'\n *\n * @example\n * // If now is 1 January 2015 00:00:00,\n * // what is the distance to 1 January 2015 00:00:15, including seconds?\n * const result = formatDistanceToNow(\n * new Date(2015, 0, 1, 0, 0, 15),\n * {includeSeconds: true}\n * )\n * //=> 'less than 20 seconds'\n *\n * @example\n * // If today is 1 January 2015,\n * // what is the distance to 1 January 2016, with a suffix?\n * const result = formatDistanceToNow(\n * new Date(2016, 0, 1),\n * {addSuffix: true}\n * )\n * //=> 'in about 1 year'\n *\n * @example\n * // If today is 1 January 2015,\n * // what is the distance to 1 August 2016 in Esperanto?\n * const eoLocale = require('date-fns/locale/eo')\n * const result = formatDistanceToNow(\n * new Date(2016, 7, 1),\n * {locale: eoLocale}\n * )\n * //=> 'pli ol 1 jaro'\n */\nexport function formatDistanceToNow(date, options) {\n return formatDistance(date, constructNow(date), options);\n}\n\n// Fallback for modularized imports:\nexport default formatDistanceToNow;\n", "import { constructFrom } from \"./constructFrom.js\";\n\n/**\n * @name transpose\n * @category Generic Helpers\n * @summary Transpose the date to the given constructor.\n *\n * @description\n * The function transposes the date to the given constructor. It helps you\n * to transpose the date in the system time zone to say `UTCDate` or any other\n * date extension.\n *\n * @typeParam InputDate - The input `Date` type derived from the passed argument.\n * @typeParam ResultDate - The result `Date` type derived from the passed constructor.\n *\n * @param date - The date to use values from\n * @param constructor - The date constructor to use\n *\n * @returns Date transposed to the given constructor\n *\n * @example\n * // Create July 10, 2022 00:00 in locale time zone\n * const date = new Date(2022, 6, 10)\n * //=> 'Sun Jul 10 2022 00:00:00 GMT+0800 (Singapore Standard Time)'\n *\n * @example\n * // Transpose the date to July 10, 2022 00:00 in UTC\n * transpose(date, UTCDate)\n * //=> 'Sun Jul 10 2022 00:00:00 GMT+0000 (Coordinated Universal Time)'\n */\nexport function transpose(date, constructor) {\n const date_ = isConstructor(constructor)\n ? new constructor(0)\n : constructFrom(constructor, 0);\n date_.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());\n date_.setHours(\n date.getHours(),\n date.getMinutes(),\n date.getSeconds(),\n date.getMilliseconds(),\n );\n return date_;\n}\n\nfunction isConstructor(constructor) {\n return (\n typeof constructor === \"function\" &&\n constructor.prototype?.constructor === constructor\n );\n}\n\n// Fallback for modularized imports:\nexport default transpose;\n", "import { constructFrom } from \"./constructFrom.js\";\nimport { constructNow } from \"./constructNow.js\";\nimport { isSameDay } from \"./isSameDay.js\";\n\n/**\n * The {@link isToday} function options.\n */\n\n/**\n * @name isToday\n * @category Day Helpers\n * @summary Is the given date today?\n * @pure false\n *\n * @description\n * Is the given date today?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is today\n *\n * @example\n * // If today is 6 October 2014, is 6 October 14:00:00 today?\n * const result = isToday(new Date(2014, 9, 6, 14, 0))\n * //=> true\n */\nexport function isToday(date, options) {\n return isSameDay(\n constructFrom(options?.in || date, date),\n constructNow(options?.in || date),\n );\n}\n\n// Fallback for modularized imports:\nexport default isToday;\n", "import type { I18n, I18nClient } from '@payloadcms/translations'\n\nimport { TZDateMini as TZDate } from '@date-fns/tz/date/mini'\nimport { format, formatDistanceToNow, transpose } from 'date-fns'\n\nexport type FormatDateArgs = {\n date: Date | number | string | undefined\n i18n: I18n | I18nClient\n pattern: string\n timezone?: string\n}\n\nexport const formatDate = ({ date, i18n, pattern, timezone }: FormatDateArgs): string => {\n const theDate = new TZDate(new Date(date))\n\n if (timezone) {\n const DateWithOriginalTz = TZDate.tz(timezone)\n\n const modifiedDate = theDate.withTimeZone(timezone)\n\n // Transpose the date to the selected timezone\n const dateWithTimezone = transpose(modifiedDate, DateWithOriginalTz)\n\n // Transpose the date to the user's timezone - this is necessary because the react-datepicker component insists on displaying the date in the user's timezone\n return i18n.dateFNS\n ? format(dateWithTimezone, pattern, { locale: i18n.dateFNS })\n : `${i18n.t('general:loading')}...`\n }\n\n return i18n.dateFNS\n ? format(theDate, pattern, { locale: i18n.dateFNS })\n : `${i18n.t('general:loading')}...`\n}\n\ntype FormatTimeToNowArgs = {\n date: Date | number | string | undefined\n i18n: I18n | I18nClient\n}\n\nexport const formatTimeToNow = ({ date, i18n }: FormatTimeToNowArgs): string => {\n const theDate = typeof date === 'string' ? new Date(date) : date\n return i18n?.dateFNS\n ? formatDistanceToNow(theDate, { locale: i18n.dateFNS })\n : `${i18n.t('general:loading')}...`\n}\n", "type SerializedLexicalEditor = {\n root: {\n children: Array<{ children?: Array<{ type: string }>; type: string }>\n }\n}\n\nexport function isSerializedLexicalEditor(value: unknown): value is SerializedLexicalEditor {\n return typeof value === 'object' && 'root' in value\n}\n\nexport function formatLexicalDocTitle(\n editorState: Array<{ children?: Array<{ type: string }>; type: string }>,\n textContent: string,\n): string {\n for (const node of editorState) {\n if ('text' in node && node.text) {\n textContent += node.text as string\n } else {\n if (!('children' in node)) {\n textContent += `[${node.type}]`\n }\n }\n if ('children' in node && node.children) {\n textContent += formatLexicalDocTitle(node.children as Array<{ type: string }>, textContent)\n }\n }\n return textContent\n}\n", "export const formatRelationshipTitle = (data): string => {\n if (Array.isArray(data)) {\n return data\n .map((item) => {\n if (typeof item === 'object' && item !== null) {\n return item.id\n }\n return String(item)\n })\n .filter(Boolean)\n .join(', ')\n }\n\n if (typeof data === 'object' && data !== null) {\n return data.id || ''\n }\n\n return String(data)\n}\n", "import type { ClientCollectionConfig, ClientGlobalConfig } from 'payload'\n\nimport { createContext, use, useEffect, useState } from 'react'\n\nimport { formatDocTitle } from '../../utilities/formatDocTitle/index.js'\nimport { useConfig } from '../Config/index.js'\nimport { useDocumentInfo } from '../DocumentInfo/index.js'\nimport { useTranslation } from '../Translation/index.js'\n\ntype IDocumentTitleContext = {\n setDocumentTitle: (title: string) => void\n title: string\n}\n\nconst DocumentTitleContext = createContext({} as IDocumentTitleContext)\n\nexport const useDocumentTitle = (): IDocumentTitleContext => use(DocumentTitleContext)\n\nexport const DocumentTitleProvider: React.FC<{\n children: React.ReactNode\n}> = ({ children }) => {\n const { id, collectionSlug, data, docConfig, globalSlug, initialData } = useDocumentInfo()\n\n const {\n config: {\n admin: { dateFormat },\n },\n } = useConfig()\n\n const { i18n } = useTranslation()\n\n const [title, setDocumentTitle] = useState(() =>\n formatDocTitle({\n collectionConfig: collectionSlug ? (docConfig as ClientCollectionConfig) : undefined,\n data: { ...(initialData || {}), id },\n dateFormat,\n fallback: id?.toString(),\n globalConfig: globalSlug ? (docConfig as ClientGlobalConfig) : undefined,\n i18n,\n }),\n )\n\n useEffect(() => {\n setDocumentTitle(\n formatDocTitle({\n collectionConfig: collectionSlug ? (docConfig as ClientCollectionConfig) : undefined,\n data: { ...data, id },\n dateFormat,\n fallback: id?.toString(),\n globalConfig: globalSlug ? (docConfig as ClientGlobalConfig) : undefined,\n i18n,\n }),\n )\n }, [data, dateFormat, i18n, id, collectionSlug, docConfig, globalSlug])\n\n return {children}\n}\n", "'use client'\nimport { dequal } from 'dequal/lite' // lite: no need for Map and Set support\nimport { formatAdminURL } from 'payload/shared'\nimport React, { createContext, use, useCallback, useEffect, useRef } from 'react'\n\nimport type { Preferences } from '../../forms/Form/types.js'\n\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { requests } from '../../utilities/api.js'\nimport { deepMergeSimple } from '../../utilities/deepMerge.js'\nimport { useAuth } from '../Auth/index.js'\nimport { useConfig } from '../Config/index.js'\n\ntype PreferencesContext = {\n getPreference: (key: string) => Promise\n /**\n * @param key - a string identifier for the property being set\n * @param value - preference data to store\n * @param merge - when true will combine the existing preference object batch the change into one request for objects, default = false\n */\n setPreference: (key: string, value: T, merge?: boolean) => Promise\n}\n\nconst Context = createContext({} as PreferencesContext)\n\nconst requestOptions = (value, language) => ({\n body: JSON.stringify({ value }),\n headers: {\n 'Accept-Language': language,\n 'Content-Type': 'application/json',\n },\n})\n\nexport const PreferencesProvider: React.FC<{ children?: React.ReactNode }> = ({ children }) => {\n const contextRef = useRef({} as PreferencesContext)\n const preferencesRef = useRef({})\n const pendingUpdate = useRef({})\n const { config } = useConfig()\n const { user } = useAuth()\n const { i18n } = useTranslation()\n\n const {\n routes: { api },\n } = config\n\n useEffect(() => {\n if (!user) {\n // clear preferences between users\n preferencesRef.current = {}\n }\n }, [user])\n\n const getPreference = useCallback(\n async (key: string): Promise => {\n const prefs = preferencesRef.current\n\n if (typeof prefs[key] !== 'undefined') {\n return prefs[key]\n }\n\n const promise = new Promise((resolve: (value: T) => void) => {\n void (async () => {\n const request = await requests.get(\n formatAdminURL({\n apiRoute: api,\n path: `/payload-preferences/${key}`,\n }),\n {\n credentials: 'include',\n headers: {\n 'Accept-Language': i18n.language,\n },\n },\n )\n\n let value = null\n\n if (request.status === 200) {\n const preference = await request.json()\n value = preference.value\n }\n\n preferencesRef.current[key] = value\n\n resolve(value)\n })()\n })\n\n prefs[key] = promise\n\n return promise\n },\n [i18n.language, api, preferencesRef],\n )\n\n const setPreference = useCallback(\n async (key: string, value: unknown, merge = false): Promise => {\n if (merge === false) {\n preferencesRef.current[key] = value\n\n await requests.post(\n formatAdminURL({\n apiRoute: api,\n path: `/payload-preferences/${key}`,\n }),\n requestOptions(value, i18n.language),\n )\n\n return\n }\n\n let newValue = value\n const currentPreference = await getPreference(key)\n\n // handle value objects where multiple values can be set under one key\n if (\n typeof value === 'object' &&\n typeof currentPreference === 'object' &&\n typeof newValue === 'object'\n ) {\n // merge the value with any existing preference for the key\n if (currentPreference) {\n newValue = deepMergeSimple(currentPreference, newValue)\n }\n\n if (dequal(newValue, currentPreference)) {\n return\n }\n\n // add the requested changes to a pendingUpdate batch for the key\n pendingUpdate.current[key] = {\n ...pendingUpdate.current[key],\n ...(newValue as Record),\n }\n } else {\n if (newValue === currentPreference) {\n return\n }\n\n pendingUpdate.current[key] = newValue\n }\n\n const updatePreference = async () => {\n // compare the value stored in context before sending to eliminate duplicate requests\n if (dequal(pendingUpdate.current[key], preferencesRef.current[key])) {\n return\n }\n\n // preference set in context here to prevent other updatePreference at the same time\n preferencesRef.current[key] = pendingUpdate.current[key]\n\n await requests.post(\n formatAdminURL({\n apiRoute: api,\n path: `/payload-preferences/${key}`,\n }),\n requestOptions(preferencesRef.current[key], i18n.language),\n )\n\n // reset any changes for this key after sending the request\n delete pendingUpdate.current[key]\n }\n\n // use timeout to allow multiple changes of different values using the same key in one request\n setTimeout(() => {\n void updatePreference()\n })\n },\n [api, getPreference, i18n.language, pendingUpdate],\n )\n\n contextRef.current.getPreference = getPreference\n contextRef.current.setPreference = setPreference\n return {children}\n}\n\nexport const usePreferences = (): PreferencesContext => use(Context)\n", "/**\n * Very simple, but fast deepMerge implementation. Only deepMerges objects, not arrays and clones everything.\n * Do not use this if your object contains any complex objects like React Components, or if you would like to combine Arrays.\n * If you only have simple objects and need a fast deepMerge, this is the function for you.\n *\n * obj2 takes precedence over obj1 - thus if obj2 has a key that obj1 also has, obj2's value will be used.\n *\n * @param obj1 base object\n * @param obj2 object to merge \"into\" obj1\n */\nexport function deepMergeSimple(obj1: object, obj2: object): T {\n const output = { ...obj1 }\n\n for (const key in obj2) {\n if (Object.prototype.hasOwnProperty.call(obj2, key)) {\n if (typeof obj2[key] === 'object' && !Array.isArray(obj2[key]) && obj1[key]) {\n output[key] = deepMergeSimple(obj1[key], obj2[key])\n } else {\n output[key] = obj2[key]\n }\n }\n }\n\n return output as T\n}\n", "'use client'\nimport type { UploadEdits } from 'payload'\n\nimport React from 'react'\n\nexport type UploadEditsProviderProps = {\n children: React.ReactNode\n initialUploadEdits?: UploadEdits\n}\nexport type UploadEditsContext = {\n getUploadEdits: () => UploadEdits\n resetUploadEdits: () => void\n updateUploadEdits: (edits: UploadEdits) => void\n uploadEdits: UploadEdits\n}\n\nconst Context = React.createContext({\n getUploadEdits: () => undefined,\n resetUploadEdits: undefined,\n updateUploadEdits: undefined,\n uploadEdits: undefined,\n})\n\nexport const UploadEditsProvider = ({ children, initialUploadEdits }: UploadEditsProviderProps) => {\n const [uploadEdits, setUploadEdits] = React.useState(initialUploadEdits || {})\n\n const resetUploadEdits = () => {\n setUploadEdits({})\n }\n\n const updateUploadEdits = (edits: UploadEdits) => {\n setUploadEdits((prevEdits) => ({\n ...(prevEdits || {}),\n ...(edits || {}),\n }))\n }\n\n const getUploadEdits = () => uploadEdits\n\n return (\n \n {children}\n \n )\n}\n\nexport const useUploadEdits = (): UploadEditsContext => React.use(Context)\n", "import type { Data, SanitizedDocumentPermissions, SanitizedPermissions } from 'payload'\n\nimport { formatAdminURL } from 'payload/shared'\nimport * as qs from 'qs-esm'\nimport React from 'react'\n\nimport { hasSavePermission as getHasSavePermission } from '../../utilities/hasSavePermission.js'\nimport { isEditing as getIsEditing } from '../../utilities/isEditing.js'\n\nexport type GetDocPermissions = (data?: Data) => Promise\n\nexport const useGetDocPermissions = ({\n id,\n api,\n collectionSlug,\n globalSlug,\n i18n,\n locale,\n permissions,\n setDocPermissions,\n setHasPublishPermission,\n setHasSavePermission,\n}: {\n api: string\n collectionSlug: string\n globalSlug: string\n i18n: any\n id: string\n locale: string\n permissions: SanitizedPermissions\n setDocPermissions: React.Dispatch>\n setHasPublishPermission: React.Dispatch>\n setHasSavePermission: React.Dispatch>\n}): GetDocPermissions =>\n React.useCallback(\n async (data: Data) => {\n const params = {\n locale: locale || undefined,\n }\n\n const idToUse = data?.id || id\n const newIsEditing = getIsEditing({ id: idToUse, collectionSlug, globalSlug })\n\n if (newIsEditing) {\n const docAccessPath: `/${string}` = collectionSlug\n ? `/${collectionSlug}/access/${idToUse}`\n : globalSlug\n ? `/globals/${globalSlug}/access`\n : null\n\n if (docAccessPath) {\n const res = await fetch(\n formatAdminURL({\n apiRoute: api,\n path: `${docAccessPath}${qs.stringify(params, { addQueryPrefix: true })}`,\n }),\n {\n body: JSON.stringify({\n ...(data?.doc || data || {}),\n _status: 'draft',\n }),\n credentials: 'include',\n headers: {\n 'Accept-Language': i18n.language,\n 'Content-Type': 'application/json',\n },\n method: 'post',\n },\n )\n\n const json: SanitizedDocumentPermissions = await res.json()\n\n const publishedAccessJSON = await fetch(\n formatAdminURL({\n apiRoute: api,\n path: `${docAccessPath}${qs.stringify(params, { addQueryPrefix: true })}`,\n }),\n {\n body: JSON.stringify({\n ...(data?.doc || data || {}),\n _status: 'published',\n }),\n credentials: 'include',\n headers: {\n 'Accept-Language': i18n.language,\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n },\n ).then((res) => res.json())\n\n setDocPermissions(json)\n\n setHasSavePermission(\n getHasSavePermission({\n collectionSlug,\n docPermissions: json,\n globalSlug,\n isEditing: newIsEditing,\n }),\n )\n\n setHasPublishPermission(publishedAccessJSON?.update)\n }\n } else {\n // when creating new documents, there is no permissions saved for this document yet\n // use the generic entity permissions instead\n const newDocPermissions = collectionSlug\n ? permissions?.collections?.[collectionSlug]\n : permissions?.globals?.[globalSlug]\n\n setDocPermissions(newDocPermissions)\n\n setHasSavePermission(\n getHasSavePermission({\n collectionSlug,\n docPermissions: newDocPermissions,\n globalSlug,\n isEditing: newIsEditing,\n }),\n )\n }\n },\n [\n locale,\n id,\n collectionSlug,\n globalSlug,\n api,\n i18n.language,\n setDocPermissions,\n setHasSavePermission,\n setHasPublishPermission,\n permissions?.collections,\n permissions?.globals,\n ],\n )\n", "import type {\n SanitizedCollectionPermission,\n SanitizedDocumentPermissions,\n SanitizedGlobalPermission,\n} from 'payload'\n\nexport const hasSavePermission = (args: {\n /*\n * Pass either `collectionSlug` or `globalSlug`\n */\n collectionSlug?: string\n docPermissions: SanitizedDocumentPermissions\n /*\n * Pass either `collectionSlug` or `globalSlug`\n */\n globalSlug?: string\n isEditing: boolean\n}) => {\n const { collectionSlug, docPermissions, globalSlug, isEditing } = args\n\n if (collectionSlug) {\n return Boolean(\n (isEditing && docPermissions?.update) ||\n (!isEditing && (docPermissions as SanitizedCollectionPermission)?.create),\n )\n }\n\n if (globalSlug) {\n return Boolean((docPermissions as SanitizedGlobalPermission)?.update)\n }\n\n return false\n}\n", "export const isEditing = ({\n id,\n collectionSlug,\n globalSlug,\n}: {\n collectionSlug?: string\n globalSlug?: string\n id?: number | string\n}): boolean => Boolean(globalSlug || (collectionSlug && !!id))\n", "'use client'\nimport React, { createContext, use } from 'react'\n\nexport const OperationContext = createContext('' as Operation)\n\nexport const OperationProvider: React.FC<{ children: React.ReactNode; operation: Operation }> = ({\n children,\n operation,\n}) => {children}\n\nexport type Operation = 'create' | 'update'\n\nexport const useOperation = (): Operation | undefined => use(OperationContext)\n", "import React from 'react'\n\n/**\n * All fields are wrapped in a `FieldPathContext` provider by default.\n * The `useFieldPath` hook will return this value if it exists, not the path the field was explicitly given.\n * This means if you render a field directly, you will need to wrap it with a new `FieldPathContext` provider.\n * Otherwise, it will return the parent's path, not the path it was explicitly given.\n * @example\n * ```tsx\n * 'use client'\n * import React from 'react'\n * import { TextField, FieldPathContext } from '@payloadcms/ui'\n * import type { TextFieldClientComponent } from 'payload'\n *\n * export const MyCustomField: TextFieldClientComponent = (props) => {\n * return (\n * \n * \n * \n * )\n * }\n * ```\n *\n * @experimental This is an experimental API and may change at any time. Use at your own risk.\n */\nexport const FieldPathContext = React.createContext(undefined)\n\n/**\n * Gets the current field path from the nearest `FieldPathContext` provider.\n * All fields are wrapped in this context by default.\n *\n * @experimental This is an experimental API and may change at any time. Use at your own risk.\n */\nexport const useFieldPath = () => {\n const context = React.useContext(FieldPathContext)\n\n if (!context) {\n // swallow the error, not all fields are wrapped in a FieldPathContext\n return undefined\n }\n\n return context\n}\n", "'use client'\nimport type { FieldPaths } from 'payload'\nimport type { MarkOptional } from 'ts-essentials'\n\nimport React from 'react'\n\nimport { WatchCondition } from './WatchCondition.js'\n\nexport const withCondition =

>(\n Field: React.ComponentType

,\n): React.FC

=> {\n const CheckForCondition: React.FC

= (props) => {\n const { path } = props\n\n return (\n \n \n \n )\n }\n\n return CheckForCondition\n}\n", "'use client'\n\nimport type React from 'react'\n\nimport { useFormFields } from '../Form/context.js'\n\nexport const WatchCondition: React.FC<{\n children: React.ReactNode\n path: string\n}> = (props) => {\n const { children, path } = props\n\n const field = useFormFields(([fields]) => (fields && fields?.[path]) || null)\n\n const { passesCondition } = field || {}\n\n if (passesCondition === false) {\n return null\n }\n\n return children\n}\n", "import type { ClientField } from 'payload'\n\nexport const mergeFieldStyles = (\n field: ClientField | Omit,\n): React.CSSProperties => ({\n ...(field?.admin?.style || {}),\n ...(field?.admin?.width\n ? {\n '--field-width': field.admin.width,\n }\n : {\n flex: '1 1 auto',\n }),\n // allow flex overrides to still take precedence over the fallback\n ...(field?.admin?.style?.flex\n ? {\n flex: field.admin.style.flex,\n }\n : {}),\n})\n", "'use client'\nimport type { Locale, SanitizedLocalizationConfig } from 'payload'\n\nexport const fieldBaseClass = 'field-type'\n\n/**\n * Determines whether a field should be displayed as right-to-left (RTL) based on its configuration, payload's localization configuration and the adming user's currently enabled locale.\n\n * @returns Whether the field should be displayed as RTL.\n */\nexport function isFieldRTL({\n fieldLocalized,\n fieldRTL,\n locale,\n localizationConfig,\n}: {\n fieldLocalized: boolean\n fieldRTL: boolean\n locale: Locale\n localizationConfig?: SanitizedLocalizationConfig\n}) {\n const hasMultipleLocales =\n locale &&\n localizationConfig &&\n localizationConfig.locales &&\n localizationConfig.locales.length > 1\n\n const isCurrentLocaleDefaultLocale = locale?.code === localizationConfig?.defaultLocale\n\n return (\n (fieldRTL !== false &&\n locale?.rtl === true &&\n (fieldLocalized ||\n (!fieldLocalized && !hasMultipleLocales) || // If there is only one locale which is also rtl, that field is rtl too\n (!fieldLocalized && isCurrentLocaleDefaultLocale))) || // If the current locale is the default locale, but the field is not localized, that field is rtl too\n fieldRTL === true\n ) // If fieldRTL is true. This should be useful for when no localization is set at all in the payload config, but you still want fields to be rtl.\n}\n", "'use client'\nimport type { StaticLabel } from 'payload'\n\nimport React, { useEffect, useId, useState } from 'react'\n\nimport { RenderCustomComponent } from '../../elements/RenderCustomComponent/index.js'\nimport { FieldLabel } from '../../fields/FieldLabel/index.js'\nimport { CheckIcon } from '../../icons/Check/index.js'\nimport { LineIcon } from '../../icons/Line/index.js'\n\nexport type CheckboxInputProps = {\n readonly AfterInput?: React.ReactNode\n readonly BeforeInput?: React.ReactNode\n readonly checked?: boolean\n readonly className?: string\n readonly id?: string\n readonly inputRef?: React.RefObject\n readonly Label?: React.ReactNode\n readonly label?: StaticLabel\n readonly localized?: boolean\n readonly name?: string\n readonly onToggle: (event: React.ChangeEvent) => void\n readonly partialChecked?: boolean\n readonly readOnly?: boolean\n readonly required?: boolean\n}\n\nexport const inputBaseClass = 'checkbox-input'\n\nexport const CheckboxInput: React.FC = ({\n id: idFromProps,\n name,\n AfterInput,\n BeforeInput,\n checked,\n className,\n inputRef,\n Label,\n label,\n localized,\n onToggle,\n partialChecked,\n readOnly: readOnlyFromProps,\n required,\n}) => {\n const [isHydrated, setIsHydrated] = useState(false)\n const fallbackID = useId()\n const id = idFromProps || fallbackID\n\n useEffect(() => {\n setIsHydrated(true)\n }, [])\n\n const readOnly = readOnlyFromProps || !isHydrated\n\n return (\n \n

\n {BeforeInput}\n \n \n {checked && }\n {!checked && partialChecked && }\n \n {AfterInput}\n
\n \n }\n />\n \n )\n}\n", "import React from 'react'\n\nimport './index.scss'\n\nexport const CheckIcon: React.FC = () => (\n \n \n \n)\n", "import React from 'react'\n\nimport './index.scss'\n\nexport const LineIcon: React.FC = () => (\n \n \n \n)\n", "export const scrollToID = (id: string): void => {\n const element = document.getElementById(id)\n\n if (element) {\n const bounds = element.getBoundingClientRect()\n window.scrollBy({\n behavior: 'smooth',\n top: bounds.top - 100,\n })\n }\n}\n", "'use client'\nimport type {\n ArrayField,\n ClientComponentProps,\n ClientField,\n Row,\n SanitizedFieldPermissions,\n} from 'payload'\n\nimport { getTranslation } from '@payloadcms/translations'\nimport React from 'react'\n\nimport type { UseDraggableSortableReturn } from '../../elements/DraggableSortable/useDraggableSortable/types.js'\n\nimport { ArrayAction } from '../../elements/ArrayAction/index.js'\nimport { Collapsible } from '../../elements/Collapsible/index.js'\nimport { ErrorPill } from '../../elements/ErrorPill/index.js'\nimport { ShimmerEffect } from '../../elements/ShimmerEffect/index.js'\nimport { useFormSubmitted } from '../../forms/Form/context.js'\nimport { RenderFields } from '../../forms/RenderFields/index.js'\nimport { RowLabel } from '../../forms/RowLabel/index.js'\nimport { useThrottledValue } from '../../hooks/useThrottledValue.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport './index.scss'\n\nconst baseClass = 'array-field'\n\ntype ArrayRowProps = {\n readonly addRow: (rowIndex: number) => Promise | void\n readonly copyRow: (rowIndex: number) => void\n readonly CustomRowLabel?: React.ReactNode\n readonly duplicateRow: (rowIndex: number) => void\n readonly errorCount: number\n readonly fields: ClientField[]\n readonly hasMaxRows?: boolean\n readonly isLoading?: boolean\n readonly isSortable?: boolean\n readonly labels: Partial\n readonly moveRow: (fromIndex: number, toIndex: number) => void\n readonly parentPath: string\n readonly pasteRow: (rowIndex: number) => void\n readonly path: string\n readonly permissions: SanitizedFieldPermissions\n readonly readOnly?: boolean\n readonly removeRow: (rowIndex: number) => void\n readonly row: Row\n readonly rowCount: number\n readonly rowIndex: number\n readonly schemaPath: string\n readonly scrollIdPrefix: string\n readonly setCollapse: (rowID: string, collapsed: boolean) => void\n} & Pick &\n UseDraggableSortableReturn\n\nexport const ArrayRow: React.FC = ({\n addRow,\n attributes,\n copyRow,\n CustomRowLabel,\n duplicateRow,\n errorCount,\n fields,\n forceRender = false,\n hasMaxRows,\n isDragging,\n isLoading: isLoadingFromProps,\n isSortable,\n labels,\n listeners,\n moveRow,\n parentPath,\n pasteRow,\n path,\n permissions,\n readOnly,\n removeRow,\n row,\n rowCount,\n rowIndex,\n schemaPath,\n scrollIdPrefix,\n setCollapse,\n setNodeRef,\n transform,\n transition,\n}) => {\n const isLoading = useThrottledValue(isLoadingFromProps, 500)\n\n const { i18n } = useTranslation()\n const hasSubmitted = useFormSubmitted()\n\n const fallbackLabel = `${getTranslation(labels.singular, i18n)} ${String(rowIndex + 1).padStart(\n 2,\n '0',\n )}`\n\n const fieldHasErrors = errorCount > 0 && hasSubmitted\n\n const classNames = [\n `${baseClass}__row`,\n fieldHasErrors ? `${baseClass}__row--has-errors` : `${baseClass}__row--no-errors`,\n ]\n .filter(Boolean)\n .join(' ')\n\n return (\n \n \n ) : undefined\n }\n className={classNames}\n collapsibleStyle={fieldHasErrors ? 'error' : 'default'}\n dragHandleProps={\n isSortable\n ? {\n id: row.id,\n attributes,\n listeners,\n }\n : undefined\n }\n header={\n \n {isLoading ? (\n \n ) : (\n \n )}\n {fieldHasErrors && }\n \n }\n isCollapsed={row.collapsed}\n onToggle={(collapsed) => setCollapse(row.id, collapsed)}\n >\n {isLoading ? (\n \n ) : (\n \n )}\n \n \n )\n}\n", "'use client'\nimport React from 'react'\n\nimport { ChevronIcon } from '../../icons/Chevron/index.js'\nimport { CopyIcon } from '../../icons/Copy/index.js'\nimport { MoreIcon } from '../../icons/More/index.js'\nimport { PlusIcon } from '../../icons/Plus/index.js'\nimport { XIcon } from '../../icons/X/index.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { ClipboardActionLabel } from '../ClipboardAction/ClipboardActionLabel.js'\nimport './index.scss'\nimport { Popup, PopupList } from '../Popup/index.js'\n\nconst baseClass = 'array-actions'\n\nexport type Props = {\n addRow: (current: number, blockType?: string) => Promise | void\n copyRow: (index: number) => void\n duplicateRow: (current: number) => void\n hasMaxRows: boolean\n index: number\n isSortable?: boolean\n moveRow: (from: number, to: number) => void\n pasteRow: (index: number) => void\n removeRow: (index: number) => void\n rowCount: number\n}\n\nexport const ArrayAction: React.FC = ({\n addRow,\n copyRow,\n duplicateRow,\n hasMaxRows,\n index,\n isSortable,\n moveRow,\n pasteRow,\n removeRow,\n rowCount,\n}) => {\n const { t } = useTranslation()\n\n return (\n }\n buttonClassName={`${baseClass}__button`}\n className={baseClass}\n horizontalAlign=\"center\"\n render={({ close }) => {\n return (\n \n {isSortable && index !== 0 && (\n {\n moveRow(index, index - 1)\n close()\n }}\n >\n
\n \n
\n {t('general:moveUp')}\n \n )}\n {isSortable && index < rowCount - 1 && (\n {\n moveRow(index, index + 1)\n close()\n }}\n >\n
\n \n
\n {t('general:moveDown')}\n \n )}\n {!hasMaxRows && (\n \n {\n void addRow(index + 1)\n close()\n }}\n >\n \n {t('general:addBelow')}\n \n {\n duplicateRow(index)\n close()\n }}\n >\n \n {t('general:duplicate')}\n \n \n )}\n {\n copyRow(index)\n close()\n }}\n >\n \n \n {\n pasteRow(index)\n close()\n }}\n >\n \n \n {\n removeRow(index)\n close()\n }}\n >\n \n {t('general:remove')}\n \n
\n )\n }}\n size=\"medium\"\n />\n )\n}\n", "'use client'\nimport React, { useState } from 'react'\n\nimport type { DragHandleProps } from '../DraggableSortable/DraggableSortableItem/types.js'\n\nimport { ChevronIcon } from '../../icons/Chevron/index.js'\nimport { DragHandleIcon } from '../../icons/DragHandle/index.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport './index.scss'\nimport { AnimateHeight } from '../AnimateHeight/index.js'\nimport { CollapsibleProvider, useCollapsible } from './provider.js'\n\nconst baseClass = 'collapsible'\n\nexport { CollapsibleProvider, useCollapsible }\n\nexport type CollapsibleProps = {\n actions?: React.ReactNode\n /**\n * Components that will be rendered within the collapsible provider but after the wrapper.\n */\n AfterCollapsible?: React.ReactNode\n children: React.ReactNode\n className?: string\n collapsibleStyle?: 'default' | 'error'\n /**\n * If set to true, clicking on the collapsible header will not toggle the collapsible state.\n * This is useful if the collapsible state is controlled externally (e.g. from a parent component or custom button).\n */\n disableHeaderToggle?: boolean\n /**\n * If set to true, the toggle indicator (chevron) on the right side of the header will be hidden.\n */\n disableToggleIndicator?: boolean\n dragHandleProps?: DragHandleProps\n header?: React.ReactNode\n initCollapsed?: boolean\n isCollapsed?: boolean\n onToggle?: (collapsed: boolean) => Promise | void\n}\n\nexport const Collapsible: React.FC = ({\n actions,\n AfterCollapsible,\n children,\n className,\n collapsibleStyle = 'default',\n disableHeaderToggle = false,\n disableToggleIndicator = false,\n dragHandleProps,\n header,\n initCollapsed,\n isCollapsed: collapsedFromProps,\n onToggle,\n}) => {\n const [collapsedLocal, setCollapsedLocal] = useState(Boolean(initCollapsed))\n const [hoveringToggle, setHoveringToggle] = useState(false)\n const { isWithinCollapsible } = useCollapsible()\n const { t } = useTranslation()\n\n const isCollapsed = typeof collapsedFromProps === 'boolean' ? collapsedFromProps : collapsedLocal\n\n const toggleCollapsible = React.useCallback(() => {\n if (typeof onToggle === 'function') {\n void onToggle(!isCollapsed)\n }\n setCollapsedLocal(!isCollapsed)\n }, [onToggle, isCollapsed])\n\n return (\n \n \n setHoveringToggle(true)}\n onMouseLeave={() => setHoveringToggle(false)}\n >\n {!disableHeaderToggle && (\n \n {t('fields:toggleBlock')}\n \n )}\n\n {dragHandleProps && (\n \n \n \n )}\n {header ? (\n \n {header}\n \n ) : null}\n
\n {actions ?
{actions}
: null}\n {!disableToggleIndicator && (\n
\n \n
\n )}\n
\n \n \n
{children}
\n
\n {AfterCollapsible}\n
\n \n )\n}\n", "import React from 'react'\n\nimport './index.scss'\n\nexport const DragHandleIcon: React.FC<{ className?: string }> = ({ className }) => (\n \n \n \n \n \n \n \n \n)\n", "'use client'\nimport React, { useEffect, useRef } from 'react'\n\nimport { usePatchAnimateHeight } from './usePatchAnimateHeight.js'\nimport './index.scss'\n\nexport const AnimateHeight: React.FC<{\n children: React.ReactNode\n className?: string\n duration?: number\n height?: 'auto' | number\n id?: string\n}> = ({ id, children, className, duration = 300, height }) => {\n const [open, setOpen] = React.useState(() => Boolean(height))\n\n const prevIsOpen = useRef(open)\n\n const [childrenDisplay, setChildrenDisplay] = React.useState(\n () => (open ? '' : 'none'),\n )\n\n const [parentOverflow, setParentOverflow] = React.useState(() =>\n open ? '' : 'hidden',\n )\n\n const [isAnimating, setIsAnimating] = React.useState(false)\n\n const containerRef = useRef(null)\n const contentRef = useRef(null)\n\n useEffect(() => {\n let displayTimer: number\n let overflowTimer: number\n\n const newIsOpen = Boolean(height)\n const hasChanged = prevIsOpen.current !== newIsOpen\n prevIsOpen.current = newIsOpen\n\n if (hasChanged) {\n setIsAnimating(true)\n setParentOverflow('hidden')\n\n if (newIsOpen) {\n setChildrenDisplay('')\n } else {\n // `display: none` once closed\n displayTimer = window.setTimeout(() => {\n setChildrenDisplay('none')\n }, duration)\n }\n\n setOpen(newIsOpen)\n\n // reset overflow once open\n overflowTimer = window.setTimeout(() => {\n setParentOverflow('')\n setIsAnimating(false)\n }, duration)\n }\n\n return () => {\n if (displayTimer) {\n clearTimeout(displayTimer)\n }\n\n if (overflowTimer) {\n clearTimeout(overflowTimer)\n }\n }\n }, [height, duration])\n\n usePatchAnimateHeight({\n containerRef,\n contentRef,\n duration,\n open,\n })\n\n return (\n \n
\n {children}\n
\n \n )\n}\n", "import { useEffect, useMemo, useRef, useState } from 'react'\n\nexport const usePatchAnimateHeight = ({\n containerRef,\n contentRef,\n duration,\n open,\n}: {\n containerRef: React.RefObject\n contentRef: React.RefObject\n duration: number\n open: boolean\n}): { browserSupportsKeywordAnimation: boolean } => {\n const browserSupportsKeywordAnimation = useMemo(\n () =>\n typeof CSS !== 'undefined' && CSS && CSS.supports\n ? CSS.supports('interpolate-size', 'allow-keywords')\n : false,\n [],\n )\n\n const hasInitialized = useRef(false)\n const previousOpenState = useRef(open)\n const [isAnimating, setIsAnimating] = useState(false)\n const resizeObserverRef = useRef(null)\n\n useEffect(() => {\n const container = containerRef.current\n const content = contentRef.current\n\n if (!container || !content || browserSupportsKeywordAnimation) {\n return\n }\n\n const setContainerHeight = (height: string) => {\n container.style.height = height\n }\n\n const handleTransitionEnd = () => {\n if (container) {\n container.style.transition = ''\n container.style.height = open ? 'auto' : '0px'\n setIsAnimating(false)\n }\n }\n\n const animate = () => {\n if (!hasInitialized.current && open) {\n // Skip animation on first render\n setContainerHeight('auto')\n setIsAnimating(false)\n return\n }\n\n hasInitialized.current = true\n\n if (previousOpenState.current !== open) {\n setContainerHeight(open ? '0px' : `${content.scrollHeight}px`)\n }\n\n // Trigger reflow\n container.offsetHeight // eslint-disable-line @typescript-eslint/no-unused-expressions\n\n setIsAnimating(true)\n container.style.transition = `height ${duration}ms ease`\n setContainerHeight(open ? `${content.scrollHeight}px` : '0px')\n\n const onTransitionEnd = () => {\n handleTransitionEnd()\n container.removeEventListener('transitionend', onTransitionEnd)\n }\n\n container.addEventListener('transitionend', onTransitionEnd)\n }\n\n animate()\n previousOpenState.current = open\n\n // Setup ResizeObserver\n resizeObserverRef.current = new ResizeObserver(() => {\n if (isAnimating) {\n container.style.height = open ? `${content.scrollHeight}px` : '0px'\n }\n })\n resizeObserverRef.current.observe(content)\n\n return () => {\n if (container) {\n container.style.transition = ''\n container.style.height = ''\n }\n resizeObserverRef.current?.disconnect()\n }\n }, [open, duration, containerRef, contentRef, browserSupportsKeywordAnimation])\n\n return { browserSupportsKeywordAnimation }\n}\n", "'use client'\nimport React, { createContext, use } from 'react'\n\ntype ContextType = {\n isCollapsed: boolean\n isVisible: boolean\n isWithinCollapsible: boolean\n toggle: () => void\n}\n\nconst Context = createContext({\n isCollapsed: undefined,\n isVisible: undefined,\n isWithinCollapsible: undefined,\n toggle: () => {},\n} as ContextType)\n\nexport const CollapsibleProvider: React.FC<{\n children?: React.ReactNode\n isCollapsed?: boolean\n isWithinCollapsible?: boolean\n toggle: () => void\n}> = ({ children, isCollapsed, isWithinCollapsible = true, toggle }) => {\n const { isCollapsed: parentIsCollapsed, isVisible } = useCollapsible()\n\n const contextValue = React.useMemo((): ContextType => {\n return {\n isCollapsed,\n isVisible: isVisible && !parentIsCollapsed,\n isWithinCollapsible,\n toggle,\n }\n }, [isCollapsed, isWithinCollapsible, toggle, parentIsCollapsed, isVisible])\n\n return {children}\n}\n\nexport const useCollapsible = (): ContextType => use(Context)\n", "'use client'\n\nimport type { SanitizedFieldPermissions } from 'payload'\n\nimport { fieldIsHiddenOrDisabled, getFieldPaths, getFieldPermissions } from 'payload/shared'\nimport React from 'react'\n\nimport type { RenderFieldsProps } from './types.js'\n\nimport { RenderIfInViewport } from '../../elements/RenderIfInViewport/index.js'\nimport { useOperation } from '../../providers/Operation/index.js'\nimport './index.scss'\nimport { FieldPathContext } from './context.js'\nimport { RenderField } from './RenderField.js'\n\nconst baseClass = 'render-fields'\n\nexport { RenderFieldsProps as Props }\n\nexport const RenderFields: React.FC = (props) => {\n const {\n className,\n fields,\n forceRender,\n margins,\n parentIndexPath,\n parentPath,\n parentSchemaPath,\n permissions,\n readOnly: readOnlyFromParent,\n } = props\n\n const operation = useOperation()\n\n if (fields && fields.length > 0) {\n return (\n \n {fields.map((field, i) => {\n // For sidebar fields in the main fields array, `field` will be `null`, and visa versa\n // This is to keep the order of the fields consistent and maintain the correct index paths for the main fields (i)\n if (!field || fieldIsHiddenOrDisabled(field)) {\n return null\n }\n\n const {\n operation: hasOperationPermission,\n permissions: fieldPermissions,\n read: hasReadPermission,\n } = getFieldPermissions({\n field,\n operation,\n parentName: parentPath?.includes('.')\n ? parentPath.split('.')[parentPath.split('.').length - 1]\n : parentPath,\n permissions,\n })\n\n // If the user cannot read the field, then filter it out\n // This is different from `admin.readOnly` which is executed based on `operation`\n if ('name' in field && !hasReadPermission) {\n return null\n }\n\n // `admin.readOnly` displays the value but prevents the field from being edited\n let isReadOnly = readOnlyFromParent || field?.admin?.readOnly\n\n // If parent field is `readOnly: true`, but this field is `readOnly: false`, the field should still be editable\n if (isReadOnly && field.admin?.readOnly === false) {\n isReadOnly = false\n }\n\n // If the user does not have access at the operation level, to begin with, force it to be read-only\n if ('name' in field && !hasOperationPermission) {\n isReadOnly = true\n }\n\n const { indexPath, path, schemaPath } = getFieldPaths({\n field,\n index: i,\n parentIndexPath,\n parentPath,\n parentSchemaPath,\n })\n\n return (\n \n \n \n )\n })}\n \n )\n }\n\n return null\n}\n", "'use client'\nimport type { ClientComponentProps } from 'payload'\n\nimport React from 'react'\n\nimport { useIntersect } from '../../hooks/useIntersect.js'\n\nexport const RenderIfInViewport: React.FC<\n {\n children: React.ReactNode\n className?: string\n } & Pick\n> = ({ children, className, forceRender }) => {\n const [hasRendered, setHasRendered] = React.useState(Boolean(forceRender))\n const [intersectionRef, entry] = useIntersect(\n {\n rootMargin: '1000px',\n },\n Boolean(forceRender),\n )\n\n const isIntersecting = Boolean(entry?.isIntersecting)\n const isAboveViewport = entry?.boundingClientRect?.top < 0\n const shouldRender = forceRender || isIntersecting || isAboveViewport\n\n React.useEffect(() => {\n if (shouldRender && !hasRendered) {\n setHasRendered(true)\n }\n }, [shouldRender, hasRendered])\n\n return (\n
\n {hasRendered ? children : null}\n
\n )\n}\n", "'use client'\n\nimport type {\n ClientComponentProps,\n ClientField,\n FieldPaths,\n SanitizedFieldPermissions,\n} from 'payload'\n\nimport React from 'react'\n\nimport { ArrayField } from '../../fields/Array/index.js'\nimport { BlocksField } from '../../fields/Blocks/index.js'\nimport { CheckboxField } from '../../fields/Checkbox/index.js'\nimport { CodeField } from '../../fields/Code/index.js'\nimport { CollapsibleField } from '../../fields/Collapsible/index.js'\nimport { DateTimeField } from '../../fields/DateTime/index.js'\nimport { EmailField } from '../../fields/Email/index.js'\nimport { GroupField } from '../../fields/Group/index.js'\nimport { HiddenField } from '../../fields/Hidden/index.js'\nimport { JoinField } from '../../fields/Join/index.js'\nimport { JSONField } from '../../fields/JSON/index.js'\nimport { NumberField } from '../../fields/Number/index.js'\nimport { PointField } from '../../fields/Point/index.js'\nimport { RadioGroupField } from '../../fields/RadioGroup/index.js'\nimport { RelationshipField } from '../../fields/Relationship/index.js'\nimport { RichTextField } from '../../fields/RichText/index.js'\nimport { RowField } from '../../fields/Row/index.js'\nimport { SelectField } from '../../fields/Select/index.js'\nimport { TabsField } from '../../fields/Tabs/index.js'\nimport { TextField } from '../../fields/Text/index.js'\nimport { TextareaField } from '../../fields/Textarea/index.js'\nimport { UIField } from '../../fields/UI/index.js'\nimport { UploadField } from '../../fields/Upload/index.js'\nimport { useFormFields } from '../../forms/Form/index.js'\n\ntype RenderFieldProps = {\n clientFieldConfig: ClientField\n permissions: SanitizedFieldPermissions\n} & FieldPaths &\n Pick\n\nexport function RenderField({\n clientFieldConfig,\n forceRender,\n indexPath,\n parentPath,\n parentSchemaPath,\n path,\n permissions,\n readOnly,\n schemaPath,\n}: RenderFieldProps) {\n const CustomField = useFormFields(([fields]) => fields && fields?.[path]?.customComponents?.Field)\n\n const baseFieldProps: Pick<\n ClientComponentProps,\n 'forceRender' | 'permissions' | 'readOnly' | 'schemaPath'\n > = {\n forceRender,\n permissions,\n readOnly,\n schemaPath,\n }\n\n if (clientFieldConfig.admin?.hidden) {\n return \n }\n\n if (CustomField !== undefined) {\n return CustomField || null\n }\n\n const iterableFieldProps = {\n ...baseFieldProps,\n indexPath,\n parentPath,\n parentSchemaPath,\n }\n\n switch (clientFieldConfig.type) {\n case 'array':\n return \n\n case 'blocks':\n return \n\n case 'checkbox':\n return \n\n case 'code':\n return \n\n case 'collapsible':\n return \n\n case 'date':\n return \n\n case 'email':\n return \n\n case 'group':\n return \n\n case 'join':\n return \n\n case 'json':\n return \n\n case 'number':\n return \n\n case 'point':\n return \n\n case 'radio':\n return \n\n case 'relationship':\n return \n\n case 'richText':\n return \n\n case 'row':\n return \n\n case 'select':\n return \n\n case 'tabs':\n return \n\n case 'text':\n return \n\n case 'textarea':\n return \n\n case 'ui':\n return \n\n case 'upload':\n return \n }\n}\n", "'use client'\nimport type { BlocksFieldClientComponent, ClientBlock } from 'payload'\n\nimport { getTranslation } from '@payloadcms/translations'\nimport React, { Fragment, useCallback, useMemo } from 'react'\nimport { toast } from 'sonner'\n\nimport type { ClipboardPasteData } from '../../elements/ClipboardAction/types.js'\n\nimport { Banner } from '../../elements/Banner/index.js'\nimport { Button } from '../../elements/Button/index.js'\nimport { clipboardCopy, clipboardPaste } from '../../elements/ClipboardAction/clipboardUtilities.js'\nimport { ClipboardAction } from '../../elements/ClipboardAction/index.js'\nimport {\n mergeFormStateFromClipboard,\n reduceFormStateByPath,\n} from '../../elements/ClipboardAction/mergeFormStateFromClipboard.js'\nimport { DraggableSortableItem } from '../../elements/DraggableSortable/DraggableSortableItem/index.js'\nimport { DraggableSortable } from '../../elements/DraggableSortable/index.js'\nimport { DrawerToggler } from '../../elements/Drawer/index.js'\nimport { useDrawerSlug } from '../../elements/Drawer/useDrawerSlug.js'\nimport { ErrorPill } from '../../elements/ErrorPill/index.js'\nimport { RenderCustomComponent } from '../../elements/RenderCustomComponent/index.js'\nimport { useForm, useFormSubmitted } from '../../forms/Form/context.js'\nimport { extractRowsAndCollapsedIDs, toggleAllRows } from '../../forms/Form/rowHelpers.js'\nimport { NullifyLocaleField } from '../../forms/NullifyField/index.js'\nimport { useField } from '../../forms/useField/index.js'\nimport { withCondition } from '../../forms/withCondition/index.js'\nimport { useConfig } from '../../providers/Config/index.js'\nimport { useDocumentInfo } from '../../providers/DocumentInfo/index.js'\nimport { useLocale } from '../../providers/Locale/index.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { scrollToID } from '../../utilities/scrollToID.js'\nimport './index.scss'\nimport { FieldDescription } from '../FieldDescription/index.js'\nimport { FieldError } from '../FieldError/index.js'\nimport { FieldLabel } from '../FieldLabel/index.js'\nimport { mergeFieldStyles } from '../mergeFieldStyles.js'\nimport { fieldBaseClass } from '../shared/index.js'\nimport { BlockRow } from './BlockRow.js'\nimport { BlocksDrawer } from './BlocksDrawer/index.js'\n\nconst baseClass = 'blocks-field'\n\nconst BlocksFieldComponent: BlocksFieldClientComponent = (props) => {\n const { i18n, t } = useTranslation()\n\n const {\n field,\n field: {\n name,\n type,\n admin: { className, description, isSortable = true } = {},\n blockReferences,\n blocks,\n label,\n labels: labelsFromProps,\n localized,\n maxRows,\n minRows: minRowsProp,\n required,\n },\n path: pathFromProps,\n permissions,\n readOnly,\n schemaPath: schemaPathFromProps,\n validate,\n } = props\n\n const schemaPath = schemaPathFromProps ?? name\n\n const minRows = (minRowsProp ?? required) ? 1 : 0\n\n const { setDocFieldPreferences } = useDocumentInfo()\n const {\n addFieldRow,\n dispatchFields,\n getFields,\n moveFieldRow,\n removeFieldRow,\n replaceState,\n setModified,\n } = useForm()\n const { code: locale } = useLocale()\n const {\n config: { localization },\n config,\n } = useConfig()\n const drawerSlug = useDrawerSlug('blocks-drawer')\n const submitted = useFormSubmitted()\n\n const labels = {\n plural: t('fields:blocks'),\n singular: t('fields:block'),\n ...labelsFromProps,\n }\n\n const editingDefaultLocale = (() => {\n if (localization && localization.fallback) {\n const defaultLocale = localization.defaultLocale\n return locale === defaultLocale\n }\n\n return true\n })()\n\n const memoizedValidate = useCallback(\n (value, options) => {\n // alternative locales can be null\n if (!editingDefaultLocale && value === null) {\n return true\n }\n if (typeof validate === 'function') {\n return validate(value, { ...options, maxRows, minRows, required })\n }\n },\n [maxRows, minRows, required, validate, editingDefaultLocale],\n )\n\n const {\n blocksFilterOptions,\n customComponents: { AfterInput, BeforeInput, Description, Error, Label } = {},\n disabled,\n errorPaths,\n path,\n rows = [],\n showError,\n valid,\n value,\n } = useField({\n hasRows: true,\n potentiallyStalePath: pathFromProps,\n validate: memoizedValidate,\n })\n\n const { clientBlocks, clientBlocksAfterFilter } = useMemo(() => {\n let resolvedBlocks: ClientBlock[] = []\n\n if (!blockReferences) {\n resolvedBlocks = blocks\n } else {\n for (const blockReference of blockReferences) {\n const block =\n typeof blockReference === 'string' ? config.blocksMap[blockReference] : blockReference\n if (block) {\n resolvedBlocks.push(block)\n }\n }\n }\n\n if (Array.isArray(blocksFilterOptions)) {\n const clientBlocksAfterFilter = resolvedBlocks.filter((block) => {\n const blockSlug = typeof block === 'string' ? block : block.slug\n return blocksFilterOptions.includes(blockSlug)\n })\n\n return {\n clientBlocks: resolvedBlocks,\n clientBlocksAfterFilter,\n }\n }\n return {\n clientBlocks: resolvedBlocks,\n clientBlocksAfterFilter: resolvedBlocks,\n }\n }, [blockReferences, blocks, blocksFilterOptions, config.blocksMap])\n\n const addRow = useCallback(\n (rowIndex: number, blockType: string) => {\n addFieldRow({\n blockType,\n path,\n rowIndex,\n schemaPath,\n })\n\n setTimeout(() => {\n scrollToID(`${path}-row-${rowIndex + 1}`)\n }, 0)\n },\n [addFieldRow, path, schemaPath],\n )\n\n const duplicateRow = useCallback(\n (rowIndex: number) => {\n dispatchFields({ type: 'DUPLICATE_ROW', path, rowIndex })\n setModified(true)\n\n setTimeout(() => {\n scrollToID(`${path}-row-${rowIndex + 1}`)\n }, 0)\n },\n [dispatchFields, path, setModified],\n )\n\n const removeRow = useCallback(\n (rowIndex: number) => {\n removeFieldRow({\n path,\n rowIndex,\n })\n },\n [path, removeFieldRow],\n )\n\n const moveRow = useCallback(\n (moveFromIndex: number, moveToIndex: number) => {\n moveFieldRow({ moveFromIndex, moveToIndex, path })\n },\n [moveFieldRow, path],\n )\n\n const toggleCollapseAll = useCallback(\n (collapsed: boolean) => {\n const { collapsedIDs, updatedRows } = toggleAllRows({\n collapsed,\n rows,\n })\n\n dispatchFields({ type: 'SET_ALL_ROWS_COLLAPSED', path, updatedRows })\n setDocFieldPreferences(path, { collapsed: collapsedIDs })\n },\n [dispatchFields, path, rows, setDocFieldPreferences],\n )\n\n const setCollapse = useCallback(\n (rowID: string, collapsed: boolean) => {\n const { collapsedIDs, updatedRows } = extractRowsAndCollapsedIDs({\n collapsed,\n rowID,\n rows,\n })\n\n dispatchFields({ type: 'SET_ROW_COLLAPSED', path, updatedRows })\n setDocFieldPreferences(path, { collapsed: collapsedIDs })\n },\n [dispatchFields, path, rows, setDocFieldPreferences],\n )\n\n const copyRow = useCallback(\n (rowIndex: number) => {\n const clipboardResult = clipboardCopy({\n type,\n blocks: clientBlocks,\n getDataToCopy: () =>\n reduceFormStateByPath({\n formState: { ...getFields() },\n path,\n rowIndex,\n }),\n path,\n rowIndex,\n t,\n })\n\n if (typeof clipboardResult === 'string') {\n toast.error(clipboardResult)\n } else {\n toast.success(t('general:copied'))\n }\n },\n [clientBlocks, path, t, type, getFields],\n )\n\n const pasteRow = useCallback(\n (rowIndex: number) => {\n const pasteArgs = {\n onPaste: (dataFromClipboard: ClipboardPasteData) => {\n const formState = { ...getFields() }\n const newState = mergeFormStateFromClipboard({\n dataFromClipboard,\n formState,\n path,\n rowIndex,\n })\n replaceState(newState)\n setModified(true)\n },\n path,\n schemaBlocks: clientBlocks,\n t,\n }\n\n const clipboardResult = clipboardPaste(pasteArgs)\n\n if (typeof clipboardResult === 'string') {\n toast.error(clipboardResult)\n }\n },\n [clientBlocks, getFields, path, replaceState, setModified, t],\n )\n\n const pasteBlocks = useCallback(\n (dataFromClipboard: ClipboardPasteData) => {\n const formState = { ...getFields() }\n const newState = mergeFormStateFromClipboard({\n dataFromClipboard,\n formState,\n path,\n })\n replaceState(newState)\n setModified(true)\n },\n [getFields, path, replaceState, setModified],\n )\n\n const hasMaxRows = maxRows && rows.length >= maxRows\n\n const fieldErrorCount = errorPaths.length\n const fieldHasErrors = submitted && fieldErrorCount + (valid ? 0 : 1) > 0\n\n const showMinRows = rows.length < minRows || (required && rows.length === 0)\n const showRequired = readOnly && rows.length === 0\n\n const styles = useMemo(() => mergeFieldStyles(field), [field])\n\n return (\n \n {showError && (\n }\n />\n )}\n
\n
\n
\n

\n \n }\n />\n

\n {fieldHasErrors && fieldErrorCount > 0 && (\n \n )}\n
\n
    \n {rows.length > 0 && (\n \n
  • \n toggleCollapseAll(true)}\n type=\"button\"\n >\n {t('fields:collapseAll')}\n \n
  • \n
  • \n toggleCollapseAll(false)}\n type=\"button\"\n >\n {t('fields:showAll')}\n \n
  • \n
    \n )}\n
  • \n 0}\n allowPaste={!readOnly}\n blocks={clientBlocks}\n className={`${baseClass}__header-action`}\n disabled={disabled}\n getDataToCopy={() =>\n reduceFormStateByPath({\n formState: { ...getFields() },\n path,\n })\n }\n onPaste={pasteBlocks}\n path={path}\n type={type}\n />\n
  • \n
\n
\n }\n />\n
\n {BeforeInput}\n \n {(rows.length > 0 || (!valid && (showRequired || showMinRows))) && (\n row.id)}\n onDragEnd={({ moveFromIndex, moveToIndex }) => moveRow(moveFromIndex, moveToIndex)}\n >\n {rows.map((row, i) => {\n const { blockType, isLoading } = row\n\n const blockConfig: ClientBlock =\n config.blocksMap[blockType] ?? clientBlocks.find((block) => block.slug === blockType)\n\n if (blockConfig) {\n const rowPath = `${path}.${i}`\n\n const rowErrorCount = errorPaths.filter((errorPath) =>\n errorPath.startsWith(rowPath + '.'),\n ).length\n\n return (\n \n {(draggableSortableItemProps) => (\n \n )}\n \n )\n }\n\n return null\n })}\n {!editingDefaultLocale && (\n \n {showMinRows && (\n \n {t('validation:requiresAtLeast', {\n count: minRows,\n label:\n getTranslation(minRows > 1 ? labels.plural : labels.singular, i18n) ||\n t(minRows > 1 ? 'general:row' : 'general:rows'),\n })}\n \n )}\n {showRequired && (\n \n {t('validation:fieldHasNo', { label: getTranslation(labels.plural, i18n) })}\n \n )}\n \n )}\n \n )}\n {!hasMaxRows && (\n \n \n \n {t('fields:addLabel', { label: getTranslation(labels.singular, i18n) })}\n \n \n \n \n )}\n {AfterInput}\n \n )\n}\n\nexport const BlocksField = withCondition(BlocksFieldComponent)\n", "'use client'\nimport type { ClientBlock, ClientField, Labels, Row, SanitizedFieldPermissions } from 'payload'\n\nimport { getTranslation } from '@payloadcms/translations'\nimport React from 'react'\n\nimport type { UseDraggableSortableReturn } from '../../elements/DraggableSortable/useDraggableSortable/types.js'\nimport type { RenderFieldsProps } from '../../forms/RenderFields/types.js'\n\nimport { Collapsible } from '../../elements/Collapsible/index.js'\nimport { ErrorPill } from '../../elements/ErrorPill/index.js'\nimport { Pill } from '../../elements/Pill/index.js'\nimport { ShimmerEffect } from '../../elements/ShimmerEffect/index.js'\nimport { useFormSubmitted } from '../../forms/Form/context.js'\nimport { RenderFields } from '../../forms/RenderFields/index.js'\nimport { RowLabel } from '../../forms/RowLabel/index.js'\nimport { useThrottledValue } from '../../hooks/useThrottledValue.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { RowActions } from './RowActions.js'\nimport { SectionTitle } from './SectionTitle/index.js'\n\nconst baseClass = 'blocks-field'\n\ntype BlocksFieldProps = {\n addRow: (rowIndex: number, blockType: string) => Promise | void\n block: ClientBlock\n blocks: (ClientBlock | string)[] | ClientBlock[]\n copyRow: (rowIndex: number) => void\n duplicateRow: (rowIndex: number) => void\n errorCount: number\n fields: ClientField[]\n hasMaxRows?: boolean\n isLoading?: boolean\n isSortable?: boolean\n Label?: React.ReactNode\n labels: Labels\n moveRow: (fromIndex: number, toIndex: number) => void\n parentPath: string\n pasteRow: (rowIndex: number) => void\n path: string\n permissions: SanitizedFieldPermissions\n readOnly: boolean\n removeRow: (rowIndex: number) => void\n row: Row\n rowCount: number\n rowIndex: number\n schemaPath: string\n setCollapse: (id: string, collapsed: boolean) => void\n} & UseDraggableSortableReturn\n\nexport const BlockRow: React.FC = ({\n addRow,\n attributes,\n block,\n blocks,\n copyRow,\n duplicateRow,\n errorCount,\n fields,\n hasMaxRows,\n isLoading: isLoadingFromProps,\n isSortable,\n Label,\n labels,\n listeners,\n moveRow,\n parentPath,\n pasteRow,\n path,\n permissions,\n readOnly,\n removeRow,\n row,\n rowCount,\n rowIndex,\n schemaPath,\n setCollapse,\n setNodeRef,\n transform,\n}) => {\n const isLoading = useThrottledValue(isLoadingFromProps, 500)\n\n const { i18n } = useTranslation()\n const hasSubmitted = useFormSubmitted()\n\n const fieldHasErrors = hasSubmitted && errorCount > 0\n\n const showBlockName = !block.admin?.disableBlockName\n\n const classNames = [\n `${baseClass}__row`,\n fieldHasErrors ? `${baseClass}__row--has-errors` : `${baseClass}__row--no-errors`,\n ]\n .filter(Boolean)\n .join(' ')\n\n let blockPermissions: RenderFieldsProps['permissions'] = true\n\n if (permissions === true) {\n blockPermissions = true\n } else {\n const permissionsBlockSpecific = permissions?.blocks?.[block.slug] || permissions?.blocks\n if (permissionsBlockSpecific === true) {\n blockPermissions = true\n } else if (permissionsBlockSpecific?.fields) {\n blockPermissions = permissionsBlockSpecific.fields\n } else {\n // Check if we should fall back to read-only mode based on permission structure\n // This handles cases where field-level access control exists but block permissions were sanitized\n if (typeof permissions === 'object' && permissions && !permissionsBlockSpecific) {\n // If permissions object exists but has no block-specific permissions,\n // check if it has any restrictive characteristics\n const hasReadPermission = permissions.read === true\n const missingCreateOrUpdate = !permissions.create || !permissions.update\n const hasRestrictiveStructure =\n hasReadPermission &&\n (missingCreateOrUpdate ||\n (typeof permissions === 'object' &&\n Object.keys(permissions).length === 1 &&\n permissions.read))\n\n if (hasRestrictiveStructure) {\n blockPermissions = { read: true }\n } else {\n blockPermissions = permissionsBlockSpecific?.fields\n }\n } else {\n blockPermissions = permissionsBlockSpecific?.fields\n }\n }\n }\n\n return (\n \n \n ) : undefined\n }\n className={classNames}\n collapsibleStyle={fieldHasErrors ? 'error' : 'default'}\n dragHandleProps={\n isSortable\n ? {\n id: row.id,\n attributes,\n listeners,\n }\n : undefined\n }\n header={\n isLoading ? (\n \n ) : (\n
\n \n \n {String(rowIndex + 1).padStart(2, '0')}\n \n \n {getTranslation(block.labels.singular, i18n)}\n \n {showBlockName && (\n \n )}\n \n }\n path={path}\n rowNumber={rowIndex}\n />\n {fieldHasErrors && }\n
\n )\n }\n isCollapsed={row.collapsed}\n key={row.id}\n onToggle={(collapsed) => setCollapse(row.id, collapsed)}\n >\n {isLoading ? (\n \n ) : (\n \n )}\n \n \n )\n}\n", "'use client'\nimport type { ElementType, HTMLAttributes } from 'react'\n\nimport React, { useEffect, useState } from 'react' // TODO: abstract this out to support all routers\n\nimport { Link } from '../Link/index.js'\n\nexport type PillStyle =\n | 'always-white'\n | 'dark'\n | 'error'\n | 'light'\n | 'light-gray'\n | 'success'\n | 'warning'\n | 'white'\n\nexport type PillProps = {\n alignIcon?: 'left' | 'right'\n 'aria-checked'?: boolean\n 'aria-controls'?: string\n 'aria-expanded'?: boolean\n 'aria-label'?: string\n children?: React.ReactNode\n className?: string\n draggable?: boolean\n elementProps?: {\n ref: React.RefCallback\n } & HTMLAttributes\n icon?: React.ReactNode\n id?: string\n onClick?: () => void\n /**\n * @default 'light'\n */\n pillStyle?: PillStyle\n rounded?: boolean\n size?: 'medium' | 'small'\n to?: string\n}\n\nexport type RenderedTypeProps = {\n children: React.ReactNode\n className?: string\n onClick?: () => void\n to: string\n type?: 'button'\n}\n\nimport { useDraggableSortable } from '../DraggableSortable/useDraggableSortable/index.js'\nimport './index.scss'\n\nconst baseClass = 'pill'\n\nconst DraggablePill: React.FC = (props) => {\n const { id, className } = props\n\n const { attributes, isDragging, listeners, setNodeRef, transform } = useDraggableSortable({\n id,\n })\n\n return (\n \n )\n}\n\nconst StaticPill: React.FC = (props) => {\n const {\n id,\n alignIcon = 'right',\n 'aria-checked': ariaChecked,\n 'aria-controls': ariaControls,\n 'aria-expanded': ariaExpanded,\n 'aria-label': ariaLabel,\n children,\n className,\n draggable,\n elementProps,\n icon,\n onClick,\n pillStyle = 'light',\n rounded,\n size = 'medium',\n to,\n } = props\n\n const [isHydrated, setIsHydrated] = useState(false)\n\n useEffect(() => {\n setIsHydrated(true)\n }, [])\n\n const isButton = onClick && !to\n\n const classes = [\n baseClass,\n `${baseClass}--style-${pillStyle}`,\n `${baseClass}--size-${size}`,\n className && className,\n to && `${baseClass}--has-link`,\n (to || onClick) && `${baseClass}--has-action`,\n icon && `${baseClass}--has-icon`,\n icon && `${baseClass}--align-icon-${alignIcon}`,\n draggable && `${baseClass}--draggable`,\n rounded && `${baseClass}--rounded`,\n ]\n .filter(Boolean)\n .join(' ')\n\n let Element: ElementType | React.FC = 'div'\n\n if (isButton) {\n Element = 'button'\n }\n\n if (to) {\n Element = Link\n }\n\n return (\n \n {children}\n {Boolean(icon) && {icon}}\n \n )\n}\n\nexport const Pill: React.FC = (props) => {\n const { draggable } = props\n\n if (draggable) {\n return \n }\n return \n}\n", "import { useEffect, useState } from 'react'\n\n/**\n * A custom React hook to throttle a value so that it updates no more than once every `delay` milliseconds.\n * @param {any} value - The value to be throttled.\n * @param {number} delay - The minimum delay (in milliseconds) between updates.\n * @returns {any} - The throttled value.\n */\nexport function useThrottledValue(value, delay) {\n const [throttledValue, setThrottledValue] = useState(value)\n\n useEffect(() => {\n const handler = setTimeout(() => {\n setThrottledValue(value)\n }, delay)\n\n // Cleanup the timeout if the value changes before the delay is completed\n return () => {\n clearTimeout(handler)\n }\n }, [value, delay])\n\n return throttledValue\n}\n", "'use client'\nimport type { ClientBlock, ClientField, Labels } from 'payload'\n\nimport { useModal } from '@faceless-ui/modal'\nimport React from 'react'\n\nimport { ArrayAction } from '../../elements/ArrayAction/index.js'\nimport { useDrawerSlug } from '../../elements/Drawer/useDrawerSlug.js'\nimport { BlocksDrawer } from './BlocksDrawer/index.js'\n\nexport const RowActions: React.FC<{\n readonly addRow: (rowIndex: number, blockType: string) => Promise | void\n readonly blocks: (ClientBlock | string)[]\n readonly blockType: string\n readonly copyRow: (rowIndex: number) => void\n readonly duplicateRow: (rowIndex: number, blockType: string) => void\n readonly fields: ClientField[]\n readonly hasMaxRows?: boolean\n readonly isSortable?: boolean\n readonly labels: Labels\n readonly moveRow: (fromIndex: number, toIndex: number) => void\n readonly pasteRow: (rowIndex: number) => void\n readonly removeRow: (rowIndex: number) => void\n readonly rowCount: number\n readonly rowIndex: number\n}> = (props) => {\n const {\n addRow,\n blocks,\n blockType,\n copyRow,\n duplicateRow,\n hasMaxRows,\n isSortable,\n labels,\n moveRow,\n pasteRow,\n removeRow,\n rowCount,\n rowIndex,\n } = props\n\n const { closeModal, openModal } = useModal()\n const drawerSlug = useDrawerSlug('blocks-drawer')\n\n const [indexToAdd, setIndexToAdd] = React.useState(null)\n\n return (\n \n {\n if (typeof addRow === 'function') {\n void addRow(indexToAdd, rowBlockType)\n }\n closeModal(drawerSlug)\n }}\n addRowIndex={rowIndex}\n blocks={blocks}\n drawerSlug={drawerSlug}\n labels={labels}\n />\n {\n setIndexToAdd(index)\n openModal(drawerSlug)\n }}\n copyRow={copyRow}\n duplicateRow={() => duplicateRow(rowIndex, blockType)}\n hasMaxRows={hasMaxRows}\n index={rowIndex}\n isSortable={isSortable}\n moveRow={moveRow}\n pasteRow={pasteRow}\n removeRow={removeRow}\n rowCount={rowCount}\n />\n \n )\n}\n", "'use client'\nimport type { ClientBlock, Labels } from 'payload'\n\nimport { useModal } from '@faceless-ui/modal'\nimport { getTranslation } from '@payloadcms/translations'\nimport React, { useEffect } from 'react'\n\nimport { Drawer } from '../../../elements/Drawer/index.js'\nimport { useTranslation } from '../../../providers/Translation/index.js'\nimport { BlockSelector } from '../BlockSelector/index.js'\n\nexport type Props = {\n readonly addRow: (index: number, blockType?: string) => Promise | void\n readonly addRowIndex: number\n readonly blocks: (ClientBlock | string)[]\n readonly drawerSlug: string\n readonly labels: Labels\n}\n\nexport const BlocksDrawer: React.FC = (props) => {\n const { addRow, addRowIndex, blocks, drawerSlug, labels } = props\n\n const { closeModal, isModalOpen } = useModal()\n const { i18n, t } = useTranslation()\n const [searchTermOverride, setSearchTermOverride] = React.useState('')\n\n useEffect(() => {\n if (!isModalOpen(drawerSlug)) {\n setSearchTermOverride('')\n }\n }, [isModalOpen, drawerSlug])\n\n return (\n \n {\n void addRow(addRowIndex, slug)\n closeModal(drawerSlug)\n }}\n searchTerm={searchTermOverride}\n />\n \n )\n}\n", "'use client'\nimport type { I18nClient } from '@payloadcms/translations'\nimport type { ClientBlock } from 'payload'\n\nimport { getTranslation } from '@payloadcms/translations'\nimport React, { Fragment, useEffect, useMemo, useState } from 'react'\n\nimport { ThumbnailCard } from '../../../elements/ThumbnailCard/index.js'\nimport { DefaultBlockImage } from '../../../graphics/DefaultBlockImage/index.js'\nimport { useControllableState } from '../../../hooks/useControllableState.js'\nimport { useConfig } from '../../../providers/Config/index.js'\nimport { useTranslation } from '../../../providers/Translation/index.js'\nimport { BlockSearch } from './BlockSearch/index.js'\nimport './index.scss'\n\nexport type Props = {\n readonly blocks: (ClientBlock | string)[]\n readonly onSelect?: (blockType: string) => void\n /**\n * Control the search term state externally\n */\n searchTerm?: string\n}\n\nconst baseClass = 'blocks-drawer'\n\nconst getBlockLabel = (block: ClientBlock, i18n: I18nClient) => {\n if (typeof block.labels.singular === 'string') {\n return block.labels.singular.toLowerCase()\n }\n if (typeof block.labels.singular === 'object') {\n return getTranslation(block.labels.singular, i18n).toLowerCase()\n }\n return ''\n}\n\nexport const BlockSelector: React.FC = (props) => {\n const { blocks, onSelect, searchTerm: searchTermFromProps } = props\n\n const [searchTerm, setSearchTerm] = useControllableState(searchTermFromProps ?? '')\n\n const [filteredBlocks, setFilteredBlocks] = useState(blocks)\n const { i18n } = useTranslation()\n const { config } = useConfig()\n\n const blockGroups = useMemo(() => {\n const groups: Record = {\n _none: [],\n }\n\n filteredBlocks.forEach((block) => {\n if (typeof block === 'object' && block.admin?.group) {\n const group = block.admin.group\n const label = typeof group === 'string' ? group : getTranslation(group, i18n)\n\n if (Object.hasOwn(groups, label)) {\n groups[label].push(block)\n } else {\n groups[label] = [block]\n }\n } else {\n groups._none.push(block)\n }\n })\n\n return groups\n }, [filteredBlocks, i18n])\n\n useEffect(() => {\n const searchTermToUse = searchTerm.toLowerCase()\n\n const matchingBlocks = blocks?.reduce((matchedBlocks, _block) => {\n const block = typeof _block === 'string' ? config.blocksMap[_block] : _block\n const blockLabel = getBlockLabel(block, i18n)\n if (blockLabel.includes(searchTermToUse)) {\n matchedBlocks.push(block)\n }\n return matchedBlocks\n }, [])\n\n setFilteredBlocks(matchingBlocks)\n }, [searchTerm, blocks, i18n, config.blocksMap])\n\n return (\n \n \n
\n
    \n {Object.entries(blockGroups).map(([groupLabel, groupBlocks]) =>\n !groupBlocks.length ? null : (\n \n {groupLabel !== '_none' && (\n

    {groupLabel}

    \n )}\n
      \n {groupBlocks.map((_block, index) => {\n const block = typeof _block === 'string' ? config.blocksMap[_block] : _block\n\n const { slug, imageAltText, imageURL, labels: blockLabels } = block\n\n return (\n
    • \n {\n if (typeof onSelect === 'function') {\n onSelect(slug)\n }\n }}\n thumbnail={\n
      \n {imageURL ? (\n {imageAltText}\n ) : (\n \n )}\n
      \n }\n />\n
    • \n )\n })}\n
    \n \n ),\n )}\n
\n
\n
\n )\n}\n", "'use client'\nimport type { ClientCollectionConfig, TypeWithID } from 'payload'\n\nimport React from 'react'\n\nimport { useConfig } from '../../providers/Config/index.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { formatDocTitle } from '../../utilities/formatDocTitle/index.js'\nimport './index.scss'\n\nexport type ThumbnailCardProps = {\n alignLabel?: 'center' | 'left'\n className?: string\n collection?: ClientCollectionConfig\n doc?: { filename?: string } & TypeWithID\n label?: string\n onClick?: () => void\n onKeyDown?: () => void\n thumbnail: React.ReactNode\n}\n\nconst baseClass = 'thumbnail-card'\n\nexport const ThumbnailCard: React.FC = (props) => {\n const {\n alignLabel,\n className,\n collection,\n doc,\n label: labelFromProps,\n onClick,\n thumbnail,\n } = props\n\n const { config } = useConfig()\n\n const { i18n } = useTranslation()\n\n const classes = [\n baseClass,\n className,\n typeof onClick === 'function' && `${baseClass}--has-on-click`,\n alignLabel && `${baseClass}--align-label-${alignLabel}`,\n ]\n .filter(Boolean)\n .join(' ')\n\n let title = labelFromProps\n\n if (!title) {\n title = formatDocTitle({\n collectionConfig: collection,\n data: doc,\n dateFormat: config.admin.dateFormat,\n fallback: doc?.filename,\n i18n,\n })\n }\n\n return (\n \n )\n}\n", "import React, { useState } from 'react'\nimport { v4 as uuid } from 'uuid'\n\nexport const DefaultBlockImage: React.FC = () => {\n const [patternID] = useState(() => `pattern${uuid()}`)\n\n return (\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n )\n}\n", "import validate from './validate.js';\n\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nvar byteToHex = [];\nfor (var i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n //\n // Note to future-self: No, you can't remove the `toLowerCase()` call.\n // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351\n return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n var uuid = unsafeStringify(arr, offset);\n // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nexport default stringify;", "// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\n\nvar getRandomValues;\nvar rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n return getRandomValues(rnds8);\n}", "var randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nexport default {\n randomUUID\n};", "import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n options = options || {};\n var rnds = options.random || (options.rng || rng)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n offset = offset || 0;\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return unsafeStringify(rnds);\n}\nexport default v4;", "'use client'\nimport React from 'react'\n\nimport { SearchIcon } from '../../../../icons/Search/index.js'\nimport { useTranslation } from '../../../../providers/Translation/index.js'\nimport './index.scss'\n\nconst baseClass = 'block-search'\n\nexport const BlockSearch: React.FC<{ setSearchTerm: (term: string) => void }> = (props) => {\n const { setSearchTerm } = props\n const { t } = useTranslation()\n\n const handleChange = (e) => {\n setSearchTerm(e.target.value)\n }\n\n return (\n
\n \n \n
\n )\n}\n", "import React from 'react'\n\nimport './index.scss'\n\nexport const SearchIcon: React.FC = () => (\n \n \n \n)\n", "'use client'\nimport React from 'react'\n\nimport { useField } from '../../../forms/useField/index.js'\nimport { useTranslation } from '../../../providers/Translation/index.js'\nimport './index.scss'\n\nconst baseClass = 'section-title'\n\nexport type Props = {\n customOnChange?: (e: React.ChangeEvent) => void\n customValue?: string\n path: string\n readOnly: boolean\n}\n\n/**\n * An input field representing the block's `blockName` property - responsible for reading and saving the `blockName`\n * property from/into the provided path.\n */\nexport const SectionTitle: React.FC = (props) => {\n const { customOnChange, customValue, path, readOnly } = props\n\n const { setValue, value } = useField({ path })\n const { t } = useTranslation()\n\n const classes = [baseClass].filter(Boolean).join(' ')\n\n const onChange =\n customOnChange ||\n ((e) => {\n e.stopPropagation()\n e.preventDefault()\n setValue(e.target.value)\n })\n\n return (\n
\n \n
\n )\n}\n", "'use client'\nimport type { CodeFieldClientComponent } from 'payload'\n\nimport React, { useCallback, useEffect, useMemo, useState } from 'react'\n\nimport { CodeEditor } from '../../elements/CodeEditor/index.js'\nimport { RenderCustomComponent } from '../../elements/RenderCustomComponent/index.js'\nimport { FieldDescription } from '../../fields/FieldDescription/index.js'\nimport { FieldError } from '../../fields/FieldError/index.js'\nimport { FieldLabel } from '../../fields/FieldLabel/index.js'\nimport { useField } from '../../forms/useField/index.js'\nimport { withCondition } from '../../forms/withCondition/index.js'\nimport { mergeFieldStyles } from '../mergeFieldStyles.js'\nimport { fieldBaseClass } from '../shared/index.js'\nimport './index.scss'\n\nconst prismToMonacoLanguageMap = {\n js: 'javascript',\n ts: 'typescript',\n tsx: 'typescript',\n}\n\nconst baseClass = 'code-field'\n\nconst CodeFieldComponent: CodeFieldClientComponent = (props) => {\n const {\n field,\n field: {\n admin: { className, description, editorOptions, editorProps, language = 'javascript' } = {},\n label,\n localized,\n required,\n },\n onMount,\n path: pathFromProps,\n readOnly,\n validate,\n } = props\n\n const inputChangeFromRef = React.useRef<'formState' | 'internalEditor'>('formState')\n const [recalculatedHeightAt, setRecalculatedHeightAt] = useState(Date.now())\n\n const memoizedValidate = useCallback(\n (value, options) => {\n if (typeof validate === 'function') {\n return validate(value, { ...options, required })\n }\n },\n [validate, required],\n )\n\n const {\n customComponents: { AfterInput, BeforeInput, Description, Error, Label } = {},\n disabled,\n initialValue,\n path,\n setValue,\n showError,\n value,\n } = useField({\n potentiallyStalePath: pathFromProps,\n validate: memoizedValidate,\n })\n\n const stringValueRef = React.useRef(\n (value || initialValue) !== undefined ? (value ?? initialValue) : undefined,\n )\n\n const handleChange = useCallback(\n (val: string) => {\n if (readOnly || disabled) {\n return\n }\n inputChangeFromRef.current = 'internalEditor'\n\n try {\n setValue(val ? val : null)\n stringValueRef.current = val\n } catch (e) {\n setValue(val ? val : null)\n stringValueRef.current = val\n }\n },\n [readOnly, disabled, setValue],\n )\n\n useEffect(() => {\n if (inputChangeFromRef.current === 'formState') {\n stringValueRef.current =\n (value || initialValue) !== undefined ? (value ?? initialValue) : undefined\n setRecalculatedHeightAt(Date.now())\n }\n\n inputChangeFromRef.current = 'formState'\n }, [initialValue, path, value])\n\n const styles = useMemo(() => mergeFieldStyles(field), [field])\n\n return (\n \n \n }\n />\n
\n }\n />\n {BeforeInput}\n \n {AfterInput}\n
\n }\n />\n \n )\n}\n\nexport const CodeField = withCondition(CodeFieldComponent)\n", "'use client'\nimport React, { lazy, Suspense } from 'react'\n\nimport type { Props } from './types.js'\n\nimport { ShimmerEffect } from '../ShimmerEffect/index.js'\n\nconst LazyEditor = lazy(() => import('./CodeEditor.js'))\n\nexport type { Props }\n\nexport const CodeEditor: React.FC = (props) => {\n return (\n }>\n \n \n )\n}\n", "'use client'\nimport type { CollapsibleFieldClientComponent, DocumentPreferences } from 'payload'\n\nimport { getTranslation } from '@payloadcms/translations'\nimport React, { Fragment, useCallback, useEffect, useMemo, useState } from 'react'\n\nimport { Collapsible as CollapsibleElement } from '../../elements/Collapsible/index.js'\nimport { ErrorPill } from '../../elements/ErrorPill/index.js'\nimport { RenderCustomComponent } from '../../elements/RenderCustomComponent/index.js'\nimport { FieldDescription } from '../../fields/FieldDescription/index.js'\nimport { RenderFields } from '../../forms/RenderFields/index.js'\nimport { RowLabel } from '../../forms/RowLabel/index.js'\nimport { useField } from '../../forms/useField/index.js'\nimport { WatchChildErrors } from '../../forms/WatchChildErrors/index.js'\nimport { withCondition } from '../../forms/withCondition/index.js'\nimport { useDocumentInfo } from '../../providers/DocumentInfo/index.js'\nimport { usePreferences } from '../../providers/Preferences/index.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { mergeFieldStyles } from '../mergeFieldStyles.js'\nimport './index.scss'\nimport { fieldBaseClass } from '../shared/index.js'\n\nconst baseClass = 'collapsible-field'\n\nconst CollapsibleFieldComponent: CollapsibleFieldClientComponent = (props) => {\n const {\n field,\n field: { admin: { className, description, initCollapsed = false } = {}, fields, label } = {},\n indexPath,\n parentPath,\n parentSchemaPath,\n path,\n permissions,\n readOnly,\n } = props\n\n const { i18n } = useTranslation()\n const { getPreference, setPreference } = usePreferences()\n const { preferencesKey } = useDocumentInfo()\n const [collapsedOnMount, setCollapsedOnMount] = useState()\n const fieldPreferencesKey = `collapsible-${path?.replace(/\\./g, '__')}`\n const [errorCount, setErrorCount] = useState(0)\n const fieldHasErrors = errorCount > 0\n\n const { customComponents: { AfterInput, BeforeInput, Description, Label } = {}, disabled } =\n useField({\n path,\n })\n\n const onToggle = useCallback(\n async (newCollapsedState: boolean): Promise => {\n const existingPreferences: DocumentPreferences = await getPreference(preferencesKey)\n\n if (preferencesKey) {\n void setPreference(preferencesKey, {\n ...existingPreferences,\n ...(path\n ? {\n fields: {\n ...(existingPreferences?.fields || {}),\n [path]: {\n ...existingPreferences?.fields?.[path],\n collapsed: newCollapsedState,\n },\n },\n }\n : {\n fields: {\n ...(existingPreferences?.fields || {}),\n [fieldPreferencesKey]: {\n ...existingPreferences?.fields?.[fieldPreferencesKey],\n collapsed: newCollapsedState,\n },\n },\n }),\n })\n }\n },\n [preferencesKey, fieldPreferencesKey, getPreference, setPreference, path],\n )\n\n useEffect(() => {\n const fetchInitialState = async () => {\n if (preferencesKey) {\n const preferences = await getPreference(preferencesKey)\n const specificPreference = path\n ? preferences?.fields?.[path]?.collapsed\n : preferences?.fields?.[fieldPreferencesKey]?.collapsed\n\n if (specificPreference !== undefined) {\n setCollapsedOnMount(Boolean(specificPreference))\n } else {\n setCollapsedOnMount(typeof initCollapsed === 'boolean' ? initCollapsed : false)\n }\n } else {\n setCollapsedOnMount(typeof initCollapsed === 'boolean' ? initCollapsed : false)\n }\n }\n\n void fetchInitialState()\n }, [getPreference, preferencesKey, fieldPreferencesKey, initCollapsed, path])\n\n const styles = useMemo(() => mergeFieldStyles(field), [field])\n\n if (typeof collapsedOnMount !== 'boolean') {\n return null\n }\n\n return (\n \n \n \n {BeforeInput}\n \n \n {fieldHasErrors && }\n \n }\n initCollapsed={collapsedOnMount}\n onToggle={onToggle}\n >\n \n \n {AfterInput}\n }\n />\n \n \n )\n}\n\nexport const CollapsibleField = withCondition(CollapsibleFieldComponent)\n", "'use client'\nimport type { ClientField } from 'payload'\nimport type React from 'react'\n\nimport { useThrottledEffect } from '../../hooks/useThrottledEffect.js'\nimport { useAllFormFields, useFormSubmitted } from '../Form/context.js'\nimport { buildPathSegments } from './buildPathSegments.js'\n\ntype TrackSubSchemaErrorCountProps = {\n fields?: ClientField[]\n /**\n * This path should only include path segments that affect data\n * i.e. it should not include _index-0 type segments\n *\n * For collapsibles and tabs you can simply pass their parent path\n */\n path: (number | string)[]\n setErrorCount: (count: number) => void\n}\nexport const WatchChildErrors: React.FC = ({\n fields,\n path: parentPath,\n setErrorCount,\n}) => {\n const [formState] = useAllFormFields()\n const hasSubmitted = useFormSubmitted()\n\n const segmentsToMatch = buildPathSegments(fields)\n\n useThrottledEffect(\n () => {\n if (hasSubmitted) {\n let errorCount = 0\n Object.entries(formState).forEach(([key]) => {\n const matchingSegment = segmentsToMatch?.some((segment) => {\n const segmentToMatch = [...parentPath, segment].join('.')\n // match fields with same parent path\n if (segmentToMatch.endsWith('.')) {\n // Match both nested fields (key starts with segmentToMatch)\n // and the field itself (key equals segmentToMatch without trailing dot)\n const pathWithoutDot = segmentToMatch.slice(0, -1)\n return key.startsWith(segmentToMatch) || key === pathWithoutDot\n }\n // match fields with same path\n return key === segmentToMatch\n })\n\n if (matchingSegment) {\n const pathState = formState[key]\n if ('valid' in pathState && !pathState.valid) {\n errorCount += 1\n }\n }\n })\n setErrorCount(errorCount)\n }\n },\n 250,\n [formState, hasSubmitted, fields],\n )\n\n return null\n}\n", "'use client'\nimport type { ClientField } from 'payload'\n\nimport { fieldAffectsData } from 'payload/shared'\n\nexport const buildPathSegments = (fields: ClientField[]): (`${string}.` | string)[] => {\n return fields.reduce((acc: (`${string}.` | string)[], field) => {\n const fields: ClientField[] = 'fields' in field ? field.fields : undefined\n\n if (fields) {\n if (fieldAffectsData(field)) {\n // group, block, array\n acc.push(`${field.name}.`)\n } else {\n // rows, collapsibles, unnamed-tab\n acc.push(...buildPathSegments(fields))\n }\n } else if (field.type === 'tabs') {\n // tabs\n if ('tabs' in field) {\n field.tabs?.forEach((tab) => {\n if ('name' in tab) {\n acc.push(`${tab.name}.`)\n } else {\n acc.push(...buildPathSegments(tab.fields))\n }\n })\n }\n } else if (fieldAffectsData(field)) {\n // text, number, date, etc.\n acc.push(field.name)\n }\n\n return acc\n }, [])\n}\n", "'use client'\nimport type { DateFieldClientComponent, DateFieldValidation } from 'payload'\n\nimport { TZDateMini as TZDate } from '@date-fns/tz/date/mini'\nimport { getTranslation } from '@payloadcms/translations'\nimport { transpose } from 'date-fns'\nimport { useCallback, useMemo } from 'react'\n\nimport { DatePickerField } from '../../elements/DatePicker/index.js'\nimport { RenderCustomComponent } from '../../elements/RenderCustomComponent/index.js'\nimport { TimezonePicker } from '../../elements/TimezonePicker/index.js'\nimport { FieldDescription } from '../../fields/FieldDescription/index.js'\nimport { FieldError } from '../../fields/FieldError/index.js'\nimport { FieldLabel } from '../../fields/FieldLabel/index.js'\nimport { useForm, useFormFields } from '../../forms/Form/context.js'\nimport { useField } from '../../forms/useField/index.js'\nimport './index.scss'\nimport { withCondition } from '../../forms/withCondition/index.js'\nimport { useConfig } from '../../providers/Config/index.js'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { mergeFieldStyles } from '../mergeFieldStyles.js'\nimport { fieldBaseClass } from '../shared/index.js'\n\nconst baseClass = 'date-time-field'\n\nconst DateTimeFieldComponent: DateFieldClientComponent = (props) => {\n const {\n field,\n field: {\n admin: { className, date: datePickerProps, description, placeholder } = {},\n label,\n localized,\n required,\n timezone,\n },\n path: pathFromProps,\n readOnly,\n validate,\n } = props\n\n const pickerAppearance = datePickerProps?.pickerAppearance || 'default'\n\n // Get the user timezone so we can adjust the displayed value against it\n const userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone\n\n const { config } = useConfig()\n const { i18n } = useTranslation()\n const { dispatchFields, setModified } = useForm()\n\n const memoizedValidate: DateFieldValidation = useCallback(\n (value, options) => {\n if (typeof validate === 'function') {\n return validate(value, { ...options, required })\n }\n },\n [validate, required],\n )\n\n const {\n customComponents: { AfterInput, BeforeInput, Description, Error, Label } = {},\n disabled,\n path,\n setValue,\n showError,\n value,\n } = useField({\n potentiallyStalePath: pathFromProps,\n validate: memoizedValidate,\n })\n\n const timezonePath = path + '_tz'\n const timezoneField = useFormFields(([fields, _]) => fields?.[timezonePath])\n\n const supportedTimezones = useMemo(() => {\n if (timezone && typeof timezone === 'object' && timezone.supportedTimezones) {\n return timezone.supportedTimezones\n }\n\n return config.admin.timezones.supportedTimezones\n }, [config.admin.timezones.supportedTimezones, timezone])\n\n /**\n * Date appearance doesn't include timestamps,\n * which means we need to pin the time to always 12:00 for the selected date\n */\n const isDateOnly = ['dayOnly', 'default', 'monthOnly'].includes(pickerAppearance)\n const selectedTimezone = timezoneField?.value as string\n const timezoneRequired =\n required || (timezone && typeof timezone === 'object' && timezone.required)\n\n // The displayed value should be the original value, adjusted to the user's timezone\n const displayedValue = useMemo(() => {\n if (timezone && selectedTimezone && userTimezone && value) {\n // Create TZDate instances for the selected timezone and the user's timezone\n // These instances allow us to transpose the date between timezones while keeping the same time value\n const DateWithOriginalTz = TZDate.tz(selectedTimezone)\n const DateWithUserTz = TZDate.tz(userTimezone)\n\n const modifiedDate = new TZDate(value).withTimeZone(selectedTimezone)\n\n // Transpose the date to the selected timezone\n const dateWithTimezone = transpose(modifiedDate, DateWithOriginalTz)\n\n // Transpose the date to the user's timezone - this is necessary because the react-datepicker component insists on displaying the date in the user's timezone\n const dateWithUserTimezone = transpose(dateWithTimezone, DateWithUserTz)\n\n return dateWithUserTimezone.toISOString()\n }\n\n return value\n }, [timezone, selectedTimezone, value, userTimezone])\n\n const styles = useMemo(() => mergeFieldStyles(field), [field])\n\n const onChange = useCallback(\n (incomingDate: Date) => {\n if (!(readOnly || disabled)) {\n if (timezone && selectedTimezone && incomingDate) {\n // Create TZDate instances for the selected timezone\n const TZDateWithSelectedTz = TZDate.tz(selectedTimezone)\n\n if (isDateOnly) {\n // We need to offset this hardcoded hour offset from the DatePicker elemenent\n // this can be removed in 4.0 when we remove the hardcoded offset as it is a breaking change\n // const tzOffset = incomingDate.getTimezoneOffset() / 60\n const incomingOffset = incomingDate.getTimezoneOffset() / 60\n const originalHour = incomingDate.getHours() + incomingOffset\n incomingDate.setHours(originalHour)\n\n // Convert the original date as picked into the desired timezone.\n const dateToSelectedTz = transpose(incomingDate, TZDateWithSelectedTz)\n\n setValue(dateToSelectedTz.toISOString() || null)\n } else {\n // Creates a TZDate instance for the user's timezone — this is default behaviour of TZDate as it wraps the Date constructor\n const dateToUserTz = new TZDate(incomingDate)\n // Transpose the date to the selected timezone\n const dateWithTimezone = transpose(dateToUserTz, TZDateWithSelectedTz)\n\n setValue(dateWithTimezone.toISOString() || null)\n }\n } else {\n setValue(incomingDate?.toISOString() || null)\n }\n }\n },\n [readOnly, disabled, timezone, selectedTimezone, isDateOnly, setValue],\n )\n\n const onChangeTimezone = useCallback(\n (timezone: string) => {\n if (timezonePath) {\n dispatchFields({\n type: 'UPDATE',\n path: timezonePath,\n value: timezone,\n })\n\n setModified(true)\n }\n },\n [dispatchFields, setModified, timezonePath],\n )\n\n return (\n \n \n }\n />\n
\n }\n />\n {BeforeInput}\n \n {timezone && supportedTimezones.length > 0 && (\n \n )}\n {AfterInput}\n
\n }\n />\n \n )\n}\n\nexport const DateTimeField = withCondition(DateTimeFieldComponent)\n", "'use client'\nimport React, { lazy, Suspense } from 'react'\n\nimport type { Props } from './types.js'\n\nimport { ShimmerEffect } from '../ShimmerEffect/index.js'\n\nconst DatePicker = lazy(() => import('./DatePicker.js'))\n\nexport const DatePickerField: React.FC = (props) => (\n }>\n \n \n)\n", "'use client'\n\nimport type { OptionObject } from 'payload'\nimport type React from 'react'\n\nimport { useMemo } from 'react'\n\nimport type { Props } from './types.js'\n\nimport { FieldLabel } from '../../fields/FieldLabel/index.js'\nimport './index.scss'\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { ReactSelect } from '../ReactSelect/index.js'\nimport { formatOptions } from '../WhereBuilder/Condition/Select/formatOptions.js'\n\nexport const TimezonePicker: React.FC = (props) => {\n const {\n id,\n onChange: onChangeFromProps,\n options: optionsFromProps,\n readOnly: readOnlyFromProps,\n required,\n selectedTimezone: selectedTimezoneFromProps,\n } = props\n\n const { t } = useTranslation()\n\n const options = formatOptions(optionsFromProps)\n\n const selectedTimezone = useMemo(() => {\n return options.find((t) => {\n const value = typeof t === 'string' ? t : t.value\n return value === (selectedTimezoneFromProps || 'UTC')\n })\n }, [options, selectedTimezoneFromProps])\n\n const readOnly = Boolean(readOnlyFromProps) || options.length === 1\n\n return (\n
\n \n {\n if (onChangeFromProps) {\n onChangeFromProps(val?.value || '')\n }\n }}\n options={options}\n value={selectedTimezone}\n />\n
\n )\n}\n", "'use client'\nimport type { KeyboardEventHandler } from 'react'\n\nimport { arrayMove } from '@dnd-kit/sortable'\nimport { getTranslation } from '@payloadcms/translations'\nimport React, { useEffect, useId } from 'react'\nimport Select, { type StylesConfig } from 'react-select'\nimport CreatableSelect from 'react-select/creatable'\n\nimport type { Option, ReactSelectAdapterProps } from './types.js'\nexport type { Option } from './types.js'\n\nimport { useTranslation } from '../../providers/Translation/index.js'\nimport { DraggableSortable } from '../DraggableSortable/index.js'\nimport { ShimmerEffect } from '../ShimmerEffect/index.js'\nimport { ClearIndicator } from './ClearIndicator/index.js'\nimport { Control } from './Control/index.js'\nimport { DropdownIndicator } from './DropdownIndicator/index.js'\nimport './index.scss'\nimport { Input } from './Input/index.js'\nimport { generateMultiValueDraggableID, MultiValue } from './MultiValue/index.js'\nimport { MultiValueLabel } from './MultiValueLabel/index.js'\nimport { MultiValueRemove } from './MultiValueRemove/index.js'\nimport { SingleValue } from './SingleValue/index.js'\nimport { ValueContainer } from './ValueContainer/index.js'\n\nconst createOption = (label: string) => ({\n label,\n value: label,\n})\n\nconst SelectAdapter: React.FC = (props) => {\n const { i18n, t } = useTranslation()\n const [inputValue, setInputValue] = React.useState('') // for creatable select\n const uuid = useId()\n const [hasMounted, setHasMounted] = React.useState(false)\n\n useEffect(() => {\n setHasMounted(true)\n }, [])\n\n const {\n className,\n components,\n customProps,\n disabled = false,\n filterOption = undefined,\n getOptionValue,\n isClearable = true,\n isCreatable,\n isLoading,\n isSearchable = true,\n noOptionsMessage = () => t('general:noOptions'),\n numberOnly = false,\n onChange,\n onMenuClose,\n onMenuOpen,\n options,\n placeholder = t('general:selectValue'),\n showError,\n value,\n } = props\n\n const loadingMessage = () => t('general:loading') + '...'\n\n const classes = [className, 'react-select', showError && 'react-select--error']\n .filter(Boolean)\n .join(' ')\n\n const styles: StylesConfig