{"version":3,"file":"index.cjs","names":["is","is","is","is","is","is","is","CloseButton","DefaultTooltip","autoUpdate","Beacon","Portal","is","Floater","Step","Portal","Loader","Overlay"],"sources":["../src/defaults.ts","../src/literals/index.ts","../src/modules/helpers.tsx","../src/modules/dom.ts","../src/styles.ts","../src/modules/step.ts","../src/modules/store.ts","../src/hooks/useControls.ts","../src/hooks/useDebugLogger.ts","../src/hooks/useEventEmitter.ts","../src/modules/changes.ts","../src/hooks/useLifecycleEffect.ts","../src/hooks/usePropSync.ts","../src/hooks/useScrollEffect.ts","../src/hooks/useTourEngine.ts","../src/hooks/usePortalElement.ts","../src/components/Loader.tsx","../src/hooks/useTargetPosition.ts","../src/modules/svg.ts","../src/components/Overlay.tsx","../src/components/Portal.tsx","../src/hooks/useFocusTrap.ts","../src/components/Arrow.tsx","../src/components/Beacon.tsx","../src/components/Tooltip/CloseButton.tsx","../src/components/Tooltip/DefaultTooltip.tsx","../src/components/Tooltip/index.tsx","../src/components/Floater.tsx","../src/components/Step.tsx","../src/components/TourRenderer.tsx","../src/hooks/useJoyride.tsx","../src/index.tsx"],"sourcesContent":["import type { FloatingOptions, Locale, Options, Props, Step } from '~/types';\n\nexport const defaultOptions: Required> = {\n arrowBase: 32,\n arrowColor: '#ffffff',\n arrowSize: 16,\n arrowSpacing: 12,\n backgroundColor: '#ffffff',\n beaconSize: 36,\n beaconTrigger: 'click',\n beforeTimeout: 5000,\n blockTargetInteraction: false,\n buttons: ['back', 'close', 'primary'],\n closeButtonAction: 'close',\n disableFocusTrap: false,\n dismissKeyAction: 'close',\n hideOverlay: false,\n loaderDelay: 300,\n offset: 10,\n overlayClickAction: 'close',\n overlayColor: '#00000080',\n primaryColor: '#000000',\n scrollDuration: 300,\n scrollOffset: 20,\n showProgress: false,\n skipBeacon: false,\n skipScroll: false,\n spotlightPadding: 10,\n spotlightRadius: 4,\n targetWaitTimeout: 1000,\n textColor: '#000000',\n width: 380,\n zIndex: 100,\n};\n\nexport const defaultFloatingOptions: FloatingOptions = {\n beaconOptions: {\n offset: -18,\n },\n};\n\nexport const defaultLocale: Locale = {\n back: 'Back',\n close: 'Close',\n last: 'Last',\n next: 'Next',\n nextWithProgress: 'Next ({current} of {total})',\n open: 'Open the dialog',\n skip: 'Skip',\n};\n\nexport const defaultStep = {\n isFixed: false,\n locale: defaultLocale,\n placement: 'bottom',\n} satisfies Omit;\n\nexport const defaultProps = {\n continuous: false,\n debug: false,\n run: false,\n scrollToFirstStep: false,\n steps: [],\n} satisfies Props;\n","export const ACTIONS = {\n INIT: 'init',\n START: 'start',\n STOP: 'stop',\n RESET: 'reset',\n PREV: 'prev',\n NEXT: 'next',\n GO: 'go',\n CLOSE: 'close',\n SKIP: 'skip',\n REPLAY: 'replay',\n UPDATE: 'update',\n COMPLETE: 'complete',\n} as const;\n\nexport const EVENTS = {\n TOUR_START: 'tour:start',\n STEP_BEFORE_HOOK: 'step:before_hook',\n STEP_BEFORE: 'step:before',\n SCROLL_START: 'scroll:start',\n SCROLL_END: 'scroll:end',\n BEACON: 'beacon',\n TOOLTIP: 'tooltip',\n STEP_AFTER: 'step:after',\n STEP_AFTER_HOOK: 'step:after_hook',\n TOUR_END: 'tour:end',\n TOUR_STATUS: 'tour:status',\n TARGET_NOT_FOUND: 'error:target_not_found',\n ERROR: 'error',\n} as const;\n\nexport const LIFECYCLE = {\n INIT: 'init',\n READY: 'ready',\n BEACON_BEFORE: 'beacon_before',\n BEACON: 'beacon',\n TOOLTIP_BEFORE: 'tooltip_before',\n TOOLTIP: 'tooltip',\n COMPLETE: 'complete',\n} as const;\n\nexport const ORIGIN = {\n BUTTON_BACK: 'button_back',\n BUTTON_CLOSE: 'button_close',\n BUTTON_PRIMARY: 'button_primary',\n BUTTON_SKIP: 'button_skip',\n KEYBOARD: 'keyboard',\n OVERLAY: 'overlay',\n} as const;\n\nexport const STATUS = {\n IDLE: 'idle',\n READY: 'ready',\n WAITING: 'waiting',\n RUNNING: 'running',\n PAUSED: 'paused',\n SKIPPED: 'skipped',\n FINISHED: 'finished',\n} as const;\n\nexport const PORTAL_ELEMENT_ID = 'react-joyride-portal';\n","import { cloneElement, type FC, isValidElement, type ReactElement, type ReactNode } from 'react';\nimport innerText from 'react-innertext';\nimport deepmergeFactory from '@fastify/deepmerge';\nimport is from 'is-lite';\n\nimport type { AnyObject, NarrowPlainObject, PlainObject, Simplify } from '~/types';\n\ntype RemoveType = {\n [Key in keyof TObject as TObject[Key] extends TExclude ? never : Key]: TObject[Key];\n};\n\ninterface GetReactNodeTextOptions {\n defaultValue?: any;\n step?: number;\n steps?: number;\n}\n\n/**\n * Remove properties with undefined value from an object\n */\nexport function cleanUpObject(input: T) {\n const output: Record = {};\n\n for (const key in input) {\n if (input[key] !== undefined) {\n output[key] = input[key];\n }\n }\n\n return output as RemoveType;\n}\n\nexport function deepMerge(...objects: object[]): T {\n return deepmergeFactory({\n all: true,\n isMergeableObject: (value): value is object =>\n !(!is.plainObject(value) || isValidElement(value)),\n })(...objects) as T;\n}\n\n/**\n * Get Object type\n */\nexport function getObjectType(value: unknown): string {\n return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();\n}\n\nexport function getReactNodeText(input: ReactNode, options: GetReactNodeTextOptions = {}): string {\n const { defaultValue, step, steps } = options;\n let text = innerText(input);\n\n if (!text) {\n if (\n isValidElement(input) &&\n !Object.values(input.props as Record).length &&\n getObjectType(input.type) === 'function'\n ) {\n try {\n const component = (input.type as FC)({}) as ReactNode;\n\n text = getReactNodeText(component, options);\n } catch {\n text = innerText(defaultValue);\n }\n } else {\n text = innerText(defaultValue);\n }\n } else if ((text.includes('{current}') || text.includes('{total}')) && step && steps) {\n text = text.replace('{current}', step.toString()).replace('{total}', steps.toString());\n }\n\n return text;\n}\n\n/**\n * Log method calls if debug is enabled\n */\nexport function log(debug: boolean, scope: string, title: string, ...data: unknown[]): void {\n if (!debug) {\n return;\n }\n\n const now = new Date();\n const time = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}.${String(now.getMilliseconds()).padStart(3, '0')}`;\n\n // eslint-disable-next-line no-console\n console.log(\n `${scope} %c${title}%c ${time}`,\n 'font-weight: bold',\n 'color: gray; font-weight: normal',\n ...data,\n );\n}\n\n/**\n * Merges the defaultProps with literal values with the incoming props, removing undefined values from it that would override the defaultProps.\n * The result is a type-safe object with the defaultProps as required properties.\n */\nexport function mergeProps, TProps extends PlainObject>(\n defaultProps: TDefaultProps,\n props: TProps,\n) {\n const cleanProps = cleanUpObject(props);\n\n return { ...defaultProps, ...cleanProps } as unknown as Simplify<\n TProps & Required>\n >;\n}\n\n/**\n * A function that does nothing.\n */\nexport function noop() {\n return undefined;\n}\n\n/**\n * Type-safe Object.keys()\n */\nexport function objectKeys(input: T) {\n return Object.keys(input) as Array;\n}\n\n/**\n * Remove properties from an object\n */\nexport function omit, K extends keyof T>(\n input: NarrowPlainObject,\n ...filter: K[]\n) {\n if (!is.plainObject(input)) {\n throw new TypeError('Expected an object');\n }\n\n const output: any = {};\n\n for (const key in input) {\n /* istanbul ignore else */\n if ({}.hasOwnProperty.call(input, key) && !filter.includes(key as unknown as K)) {\n output[key] = input[key];\n }\n }\n\n return output as Omit;\n}\n\n/**\n * Select properties from an object\n */\nexport function pick, K extends keyof T>(\n input: NarrowPlainObject,\n ...filter: K[]\n) {\n if (!is.plainObject(input)) {\n throw new TypeError('Expected an object');\n }\n\n if (!filter.length) {\n return input;\n }\n\n const output: any = {};\n\n for (const key in input) {\n /* istanbul ignore else */\n if ({}.hasOwnProperty.call(input, key) && filter.includes(key as unknown as K)) {\n output[key] = input[key];\n }\n }\n\n return output as Pick;\n}\n\nexport function replaceLocaleContent(input: ReactNode, step: number, steps: number): ReactNode {\n const replacer = (text: string) =>\n text.replace('{current}', String(step)).replace('{total}', String(steps));\n\n if (getObjectType(input) === 'string') {\n return replacer(input as string);\n }\n\n if (!isValidElement(input)) {\n return input;\n }\n\n const { children } = input.props as { children?: ReactNode };\n\n if (is.string(children) && children.includes('{current}')) {\n return cloneElement(input as ReactElement<{ children?: ReactNode }>, {\n children: replacer(children),\n });\n }\n\n if (Array.isArray(children)) {\n return cloneElement(input as ReactElement<{ children?: ReactNode }>, {\n children: children.map((child: ReactNode) => {\n if (typeof child === 'string') {\n return replacer(child);\n }\n\n return replaceLocaleContent(child, step, steps);\n }),\n });\n }\n\n if (is.function(input.type) && !Object.values(input.props as Record).length) {\n try {\n const component = (input.type as FC)({}) as ReactNode;\n\n return replaceLocaleContent(component, step, steps);\n } catch {\n return input;\n }\n }\n\n return input;\n}\n\n/**\n * Sort object keys\n */\nexport function sortObjectKeys(input: T) {\n return objectKeys(input)\n .sort()\n .reduce((acc, key) => {\n acc[key] = input[key];\n\n return acc;\n }, {} as T);\n}\n","import scroll from 'scroll';\nimport scrollParent from 'scrollparent';\n\nimport { LIFECYCLE } from '~/literals';\n\nimport type { Lifecycle, StepMerged, StepTarget } from '~/types';\n\ninterface NeedsScrollingOptions {\n isFirstStep: boolean;\n scrollToFirstStep: boolean;\n step: StepMerged;\n target: HTMLElement | null;\n targetLifecycle?: Lifecycle;\n}\n\nexport function canUseDOM() {\n return !!(typeof window !== 'undefined' && window.document?.createElement);\n}\n\n/**\n * Get the absolute document-relative offset of an element by walking up the offsetParent chain.\n */\nexport function getAbsoluteOffset(element: HTMLElement): { left: number; top: number } {\n let top = 0;\n let left = 0;\n let current: HTMLElement | null = element;\n\n while (current) {\n top += current.offsetTop;\n left += current.offsetLeft;\n current = current.offsetParent as HTMLElement | null;\n }\n\n return { left, top };\n}\n\n/**\n * Find the bounding client rect\n */\nexport function getClientRect(element: HTMLElement | null) {\n if (!element) {\n return null;\n }\n\n return element.getBoundingClientRect();\n}\n\n/**\n * Helper function to get the browser-normalized \"document height\"\n */\nexport function getDocumentHeight(median = false): number {\n const { body, documentElement } = document;\n\n if (!body || !documentElement) {\n return 0;\n }\n\n if (median) {\n const heights = [\n body.scrollHeight,\n body.offsetHeight,\n documentElement.clientHeight,\n documentElement.scrollHeight,\n documentElement.offsetHeight,\n ].sort((a, b) => a - b);\n const middle = Math.floor(heights.length / 2);\n\n if (heights.length % 2 === 0) {\n return (heights[middle - 1] + heights[middle]) / 2;\n }\n\n return heights[middle];\n }\n\n return Math.max(\n body.scrollHeight,\n body.offsetHeight,\n documentElement.clientHeight,\n documentElement.scrollHeight,\n documentElement.offsetHeight,\n );\n}\n\n/**\n * Find and return the target DOM element based on a step's 'target'.\n */\nexport function getElement(element?: StepTarget): HTMLElement | null {\n if (!element) {\n return null;\n }\n\n if (typeof element === 'function') {\n try {\n return element();\n } catch (error: any) {\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n return null;\n }\n }\n\n if (typeof element === 'object' && 'current' in element) {\n return element.current;\n }\n\n if (typeof element === 'string') {\n try {\n return document.querySelector(element);\n } catch (error: any) {\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n return null;\n }\n }\n\n return element;\n}\n\n/**\n * Find and return the target DOM element based on a step's 'target'.\n */\nexport function getElementPosition(\n element: HTMLElement | null,\n offset: number,\n isFixed?: boolean,\n): number {\n const elementRect = getClientRect(element);\n const parent = getScrollParent(element);\n const hasScrollParent = parent ? !parent.isSameNode(scrollDocument()) : false;\n const isFixedTarget = isFixed ?? hasPosition(element);\n let parentTop = 0;\n let top = elementRect?.top ?? 0;\n\n if (hasScrollParent && isFixedTarget) {\n top = elementRect?.top ?? 0;\n } else if (parent instanceof HTMLElement) {\n parentTop = parent.scrollTop;\n\n if (!hasScrollParent && !isFixedTarget) {\n top += parentTop;\n }\n\n if (!parent.isSameNode(scrollDocument())) {\n top += scrollDocument().scrollTop;\n }\n }\n\n return Math.floor(top - offset);\n}\n\n/**\n * Get the scroll parent of an element.\n * If the detected parent doesn't actually scroll, fall back to the document.\n */\nexport function getScrollParent(element: HTMLElement | null, forListener?: boolean) {\n if (!element) {\n return scrollDocument();\n }\n\n const parent = scrollParent(element) as HTMLElement;\n\n if (parent) {\n if (parent.isSameNode(scrollDocument())) {\n if (forListener) {\n return document;\n }\n\n return scrollDocument();\n }\n\n const hasScrolling = parent.scrollHeight > parent.offsetHeight;\n\n if (!hasScrolling) {\n return scrollDocument();\n }\n }\n\n return parent;\n}\n\nexport function getScrollTargetToCenter(element: Element): number {\n const rect = element.getBoundingClientRect();\n const documentElement = scrollDocument();\n const containerCenter = rect.top + rect.height / 2;\n const viewportCenter = window.innerHeight / 2;\n\n return Math.max(0, documentElement.scrollTop + containerCenter - viewportCenter);\n}\n\n/**\n * Get the scrollTop position\n */\nexport function getScrollTo(element: HTMLElement | null, offset: number): number {\n if (!element) {\n return 0;\n }\n\n const parentElement = scrollParent(element) ?? (scrollDocument() as HTMLElement);\n const scrollMarginTop = parseFloat(getComputedStyle(element).scrollMarginTop) || 0;\n\n const parentRect = getClientRect(parentElement);\n const parentScrollTop = parentElement.scrollTop ?? 0;\n\n const { offsetTop = 0, scrollTop = 0 } = parentElement;\n let top = element.getBoundingClientRect().top + scrollTop;\n\n if (!!offsetTop && (hasCustomScrollParent(element) || hasCustomOffsetParent(element))) {\n const elementRect = element.getBoundingClientRect();\n const elementTopInContainer = elementRect.top - (parentRect?.top ?? 0);\n const elementBottomInContainer = elementTopInContainer + elementRect.height;\n const containerHeight = parentElement.clientHeight;\n const margin = containerHeight * 0.2;\n\n // eslint-disable-next-line unicorn/prefer-ternary\n if (elementTopInContainer >= margin && elementBottomInContainer <= containerHeight - margin) {\n top = parentScrollTop;\n } else {\n top = elementTopInContainer + parentScrollTop;\n }\n }\n\n const output = Math.floor(top - offset - scrollMarginTop);\n\n return output < 0 ? 0 : output;\n}\n\n/**\n * Check if the element has custom offset parent\n */\nexport function hasCustomOffsetParent(element: HTMLElement): boolean {\n return element.offsetParent !== document.body;\n}\n\n/**\n * Check if the element has custom scroll parent\n */\nexport function hasCustomScrollParent(element: HTMLElement | null): boolean {\n if (!element) {\n return false;\n }\n\n const parent = getScrollParent(element);\n\n return parent ? !parent.isSameNode(scrollDocument()) : false;\n}\n\n/**\n * Check if an element has fixed/sticky position\n */\nexport function hasPosition(el: Element | Node | null, type: string = 'fixed'): boolean {\n if (!el || !(el instanceof Element)) {\n return false;\n }\n\n const { nodeName } = el;\n\n if (nodeName === 'BODY' || nodeName === 'HTML') {\n return false;\n }\n\n if (getComputedStyle(el).position === type) {\n return true;\n }\n\n if (!el.parentNode) {\n return false;\n }\n\n return hasPosition(el.parentNode, type);\n}\n\n/**\n * Check if the element is visible\n */\nexport function isElementVisible(element: HTMLElement): boolean {\n if (!element) {\n return false;\n }\n\n let parentElement: HTMLElement | null = element;\n\n while (parentElement) {\n if (parentElement === document.body) {\n break;\n }\n\n if (parentElement instanceof HTMLElement) {\n const { display, visibility } = getComputedStyle(parentElement);\n\n if (display === 'none' || visibility === 'hidden') {\n return false;\n }\n }\n\n parentElement = parentElement.parentElement ?? null;\n }\n\n return true;\n}\n\nexport function needsScrolling(options: NeedsScrollingOptions): boolean {\n const { isFirstStep, scrollToFirstStep, step, target, targetLifecycle } = options;\n\n if (\n step.skipScroll ||\n (isFirstStep && !scrollToFirstStep && targetLifecycle !== LIFECYCLE.TOOLTIP) ||\n step.placement === 'center'\n ) {\n return false;\n }\n\n const parent = (target?.isConnected ? getScrollParent(target) : scrollDocument()) as Element;\n const isCustomScrollParent = parent ? !parent.isSameNode(scrollDocument()) : false;\n\n if ((step.isFixed || hasPosition(target)) && !isCustomScrollParent) {\n return false;\n }\n\n return parent.scrollHeight > parent.clientHeight;\n}\n\nexport function scrollDocument(): Element | HTMLElement {\n return document.scrollingElement ?? document.documentElement;\n}\n\n/**\n * Scroll to position\n */\nexport function scrollTo(\n value: number,\n options: { duration?: number; element: Element | HTMLElement },\n): { cancel: () => void; promise: Promise } {\n const { duration, element } = options;\n\n let cancel: () => void = () => {};\n\n const promise = new Promise(resolve => {\n const { scrollTop } = element;\n\n const limit = value > scrollTop ? value - scrollTop : scrollTop - value;\n\n cancel = scroll.top(\n element as HTMLElement,\n value,\n { duration: limit < 100 ? 50 : duration },\n () => {\n resolve();\n },\n );\n });\n\n return { cancel, promise };\n}\n","import { canUseDOM } from '~/modules/dom';\nimport { deepMerge } from '~/modules/helpers';\n\nimport type { Props, StepMerged, Styles } from '~/types';\n\n/**\n * Convert hex to RGB\n */\nexport function hexToRGB(hex: string): Array {\n const shorthandRegex = /^#?([\\da-f])([\\da-f])([\\da-f])$/i;\n const properHex = hex.replace(shorthandRegex, (_m, r, g, b) => r + r + g + g + b + b);\n\n const result = /^#?([\\da-f]{2})([\\da-f]{2})([\\da-f]{2})/i.exec(properHex);\n\n return result ? [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)] : [];\n}\n\nconst buttonReset = {\n backgroundColor: 'transparent',\n border: 0,\n borderRadius: 0,\n color: '#555555',\n cursor: 'pointer',\n fontSize: 16,\n lineHeight: 1,\n padding: 0,\n WebkitAppearance: 'none',\n};\n\nconst buttonBase = {\n ...buttonReset,\n borderRadius: 4,\n padding: 8,\n};\n\nexport default function getStyles(props: Props, step: StepMerged) {\n const { styles } = props;\n const mergedStyles = deepMerge(styles ?? {}, step.styles ?? {});\n let { width } = step;\n\n if (canUseDOM()) {\n width = typeof width === 'number' && window.innerWidth < width ? window.innerWidth - 30 : width;\n }\n\n const overlay = {\n bottom: 0,\n left: 0,\n overflow: 'hidden',\n position: 'absolute',\n right: 0,\n top: 0,\n zIndex: step.zIndex,\n };\n\n const defaultStyles = {\n arrow: {\n alignItems: 'center',\n color: step.arrowColor,\n display: 'inline-flex',\n justifyContent: 'center',\n position: 'absolute',\n },\n beaconWrapper: {\n ...buttonReset,\n display: 'inline-flex',\n borderRadius: '50%',\n position: 'relative',\n },\n beacon: {\n height: step.beaconSize,\n width: step.beaconSize,\n },\n beaconInner: {\n animation: 'joyride-beacon-inner 1.2s infinite ease-in-out',\n backgroundColor: step.primaryColor,\n borderRadius: '50%',\n display: 'block',\n height: '50%',\n left: '50%',\n opacity: 0.7,\n position: 'absolute',\n top: '50%',\n transform: 'translate(-50%, -50%)',\n width: '50%',\n },\n beaconOuter: {\n animation: 'joyride-beacon-outer 1.2s infinite ease-in-out',\n backgroundColor: `rgba(${hexToRGB(step.primaryColor).join(',')}, 0.2)`,\n border: `2px solid ${step.primaryColor}`,\n borderRadius: '50%',\n boxSizing: 'border-box',\n display: 'block',\n height: '100%',\n left: 0,\n opacity: 0.9,\n position: 'absolute',\n top: 0,\n transformOrigin: 'center',\n width: '100%',\n },\n buttonBack: {\n ...buttonBase,\n color: step.primaryColor,\n marginLeft: 'auto',\n marginRight: 5,\n },\n buttonClose: {\n ...buttonBase,\n color: step.textColor,\n height: 12,\n padding: 8,\n position: 'absolute',\n right: 0,\n top: 0,\n width: 12,\n },\n buttonPrimary: {\n ...buttonBase,\n backgroundColor: step.primaryColor,\n color: step.backgroundColor,\n },\n buttonSkip: {\n ...buttonBase,\n color: step.textColor,\n fontSize: 14,\n },\n floater: {\n display: 'inline-block',\n filter: 'drop-shadow(0 0 3px rgba(0, 0, 0, 0.3))',\n maxWidth: '100%',\n transition: 'opacity 0.3s',\n },\n loader: {\n alignItems: 'center',\n display: 'flex',\n height: 48,\n inset: 0,\n justifyContent: 'center',\n pointerEvents: 'none',\n position: 'fixed',\n width: 48,\n zIndex: step.zIndex + 1,\n },\n overlay: {\n ...overlay,\n backgroundColor: step.overlayColor,\n },\n spotlight: {},\n tooltip: {\n backgroundColor: step.backgroundColor,\n borderRadius: 5,\n boxSizing: 'border-box',\n color: step.textColor,\n fontSize: 16,\n maxWidth: '100%',\n padding: 12,\n position: 'relative',\n width,\n },\n tooltipContainer: {\n lineHeight: 1.4,\n textAlign: 'center',\n },\n tooltipTitle: {\n fontSize: 18,\n margin: 0,\n },\n tooltipContent: {\n paddingBottom: 12,\n paddingTop: 12,\n },\n tooltipFooter: {\n alignItems: 'center',\n display: 'flex',\n justifyContent: 'flex-end',\n },\n tooltipFooterSpacer: {\n flex: 1,\n },\n };\n\n return deepMerge(defaultStyles, mergedStyles);\n}\n","import is from 'is-lite';\n\nimport { defaultFloatingOptions, defaultLocale, defaultOptions, defaultStep } from '~/defaults';\nimport { ACTIONS } from '~/literals';\nimport getStyles from '~/styles';\n\nimport type {\n Actions,\n FloatingOptions,\n Locale,\n Options,\n Props,\n SpotlightPadding,\n State,\n Step,\n StepMerged,\n} from '~/types';\n\nimport { deepMerge, log, pick } from './helpers';\n\nconst optionFieldNames = [\n 'after',\n 'arrowBase',\n 'arrowColor',\n 'arrowSize',\n 'arrowSpacing',\n 'backgroundColor',\n 'beaconSize',\n 'beaconTrigger',\n 'before',\n 'beforeTimeout',\n 'buttons',\n 'closeButtonAction',\n 'skipBeacon',\n 'dismissKeyAction',\n 'disableFocusTrap',\n 'hideOverlay',\n 'skipScroll',\n 'blockTargetInteraction',\n 'loaderDelay',\n 'offset',\n 'overlayClickAction',\n 'overlayColor',\n 'primaryColor',\n 'scrollDuration',\n 'scrollOffset',\n 'showProgress',\n 'spotlightPadding',\n 'spotlightRadius',\n 'targetWaitTimeout',\n 'textColor',\n 'width',\n 'zIndex',\n] as const satisfies ReadonlyArray;\n\nexport function getMergedStep(props: Props, currentStep?: Step): StepMerged | null {\n if (!currentStep) {\n return null;\n }\n\n const mergedStep = deepMerge(\n defaultStep,\n pick(\n props,\n 'arrowComponent',\n 'beaconComponent',\n 'floatingOptions',\n 'loaderComponent',\n 'locale',\n 'styles',\n 'tooltipComponent',\n ),\n currentStep,\n );\n\n const mergedOptions = deepMerge(\n defaultOptions,\n props.options ?? {},\n pick(currentStep, ...optionFieldNames),\n );\n\n const mergedStyles = getStyles(props, { ...mergedStep, ...mergedOptions } as StepMerged);\n\n const floatingOptions = deepMerge(\n defaultFloatingOptions,\n props.floatingOptions ?? {},\n mergedStep.floatingOptions ?? {},\n );\n\n return {\n ...mergedStep,\n ...mergedOptions,\n locale: deepMerge(defaultLocale, props.locale ?? {}, mergedStep.locale || {}),\n floatingOptions,\n spotlightPadding: normalizeSpotlightPadding(mergedOptions.spotlightPadding),\n styles: mergedStyles,\n };\n}\n\nexport function normalizeSpotlightPadding(\n value: number | SpotlightPadding | undefined,\n): Required {\n if (typeof value === 'number') {\n return { top: value, right: value, bottom: value, left: value };\n }\n\n return {\n top: value?.top ?? 0,\n right: value?.right ?? 0,\n bottom: value?.bottom ?? 0,\n left: value?.left ?? 0,\n };\n}\n\n/**\n * Decide if the step shouldn't skip the beacon\n */\nexport function shouldHideBeacon(step: Step, state: State, continuous: boolean): boolean {\n const { action } = state;\n\n const withContinuous = continuous && ([ACTIONS.PREV, ACTIONS.NEXT] as Actions[]).includes(action);\n\n return step.skipBeacon || step.placement === 'center' || withContinuous;\n}\n\n/**\n * Validate if a step is valid\n */\nexport function validateStep(step: Step, debug: boolean = false): boolean {\n if (!is.plainObject(step)) {\n log(debug, 'tour', 'step must be an object');\n\n return false;\n }\n\n if (!step.target) {\n log(debug, 'tour', 'target is missing from the step');\n\n return false;\n }\n\n return true;\n}\n\n/**\n * Validate if steps are valid\n */\nexport function validateSteps(steps: Array, debug: boolean = false): boolean {\n if (!is.array(steps)) {\n log(debug, 'tour', 'steps must be an array');\n\n return false;\n }\n\n return steps.every(d => validateStep(d, debug));\n}\n","import deepEqual from '@gilbarbara/deep-equal';\nimport is from 'is-lite';\n\nimport { ACTIONS, LIFECYCLE, STATUS } from '~/literals';\nimport { log, omit } from '~/modules/helpers';\nimport { getMergedStep } from '~/modules/step';\n\nimport type {\n Controls,\n EventData,\n EventHandler,\n Events,\n PositionData,\n Props,\n State,\n Step,\n StepMerged,\n} from '~/types';\n\ntype Listener = (state: StoreState) => void;\n\n/** Internal store state. Extends `State` with positioning tracking. */\nexport type StoreState = State & { positioned: boolean };\n\nclass Store {\n private beaconPosition: PositionData | null = null;\n private readonly debug: boolean;\n private readonly eventListeners: Map> = new Map();\n private readonly listeners: Set = new Set();\n private readonly props: Props;\n private snapshot: StoreState;\n private state: StoreState;\n private steps: Array;\n private tooltipPosition: PositionData | null = null;\n\n constructor(options?: Props) {\n const { initialStepIndex, stepIndex, steps = [] } = options ?? {};\n const isControlled = is.number(stepIndex);\n\n let startIndex = 0;\n\n this.debug = options?.debug ?? false;\n\n if (isControlled) {\n startIndex = stepIndex;\n\n if (is.number(initialStepIndex)) {\n log(this.debug, 'tour', 'initialStepIndex is ignored in controlled mode');\n }\n } else if (is.number(initialStepIndex)) {\n if (initialStepIndex >= 0 && initialStepIndex < steps.length) {\n startIndex = initialStepIndex;\n } else if (steps.length > 0) {\n log(this.debug, 'tour', 'initialStepIndex is out of bounds');\n }\n }\n\n this.props = options ?? { steps: [] };\n this.steps = steps;\n this.state = {\n action: ACTIONS.INIT,\n controlled: isControlled,\n index: startIndex,\n lifecycle: LIFECYCLE.INIT,\n origin: null,\n positioned: false,\n scrolling: false,\n size: steps.length,\n status: steps.length ? STATUS.READY : STATUS.IDLE,\n waiting: false,\n };\n this.snapshot = Object.freeze({ ...this.state });\n }\n\n private applyTransitions(draft: StoreState): StoreState {\n if (draft.status === STATUS.WAITING && draft.size > 0) {\n return { ...draft, status: STATUS.RUNNING };\n }\n\n return draft;\n }\n\n private getStep(nextIndex?: number): StepMerged | null {\n return getMergedStep(this.props, this.steps[nextIndex ?? this.state.index]);\n }\n\n public cleanupPositionData = () => {\n this.beaconPosition = null;\n this.tooltipPosition = null;\n };\n\n public getPositionData = (name: 'beacon' | 'tooltip'): PositionData | null => {\n if (name === 'beacon') {\n return this.beaconPosition;\n }\n\n return this.tooltipPosition;\n };\n\n public getServerSnapshot = (): StoreState => this.snapshot;\n\n public getSnapshot = (): StoreState => this.snapshot;\n\n public getEventState = (): Omit => omit(this.snapshot, 'positioned');\n\n public getState = (): State => omit(this.snapshot, 'positioned');\n\n public setPositionData = (name: 'beacon' | 'tooltip', data: PositionData) => {\n const previous = name === 'beacon' ? this.beaconPosition : this.tooltipPosition;\n\n if (previous?.placement !== data.placement) {\n log(this.debug, `step:${this.state.index}`, 'positioned', `${name} ${data.placement}`);\n }\n\n if (name === 'beacon') {\n this.beaconPosition = data;\n } else {\n this.tooltipPosition = data;\n }\n\n const isBeforePhase =\n this.state.lifecycle === LIFECYCLE.BEACON_BEFORE ||\n this.state.lifecycle === LIFECYCLE.TOOLTIP_BEFORE;\n\n if (isBeforePhase && !this.state.positioned) {\n this.updateState({ positioned: true });\n }\n\n const onPosition = this.getStep()?.floatingOptions?.onPosition;\n\n if (onPosition) {\n onPosition(data);\n }\n };\n\n public setSteps = (steps: Array) => {\n this.steps = steps;\n\n this.updateState({ size: steps.length });\n };\n\n public dispatch = (data: EventData, controls: Controls): void => {\n const handlers = this.eventListeners.get(data.type);\n\n if (handlers) {\n for (const handler of handlers) {\n try {\n handler(data, controls);\n } catch {\n // fire-and-forget: don't let subscriber errors break the tour or other subscribers\n }\n }\n }\n };\n\n public on = (eventType: Events, handler: EventHandler): (() => void) => {\n let handlers = this.eventListeners.get(eventType);\n\n if (!handlers) {\n handlers = new Set();\n this.eventListeners.set(eventType, handlers);\n }\n\n handlers.add(handler);\n\n return () => {\n handlers.delete(handler);\n };\n };\n\n public subscribe = (listener: Listener): (() => void) => {\n this.listeners.add(listener);\n\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n public updateState = (patch: Partial, forceIndex = false) => {\n const { controlled, index } = this.state;\n const previousSnapshot = this.snapshot;\n\n const resolvedIndex =\n controlled && !forceIndex && patch.index !== undefined ? index : (patch.index ?? index);\n\n const merged: StoreState = {\n action: patch.action ?? this.state.action,\n controlled,\n index: resolvedIndex,\n lifecycle: patch.lifecycle ?? this.state.lifecycle,\n origin: patch.origin ?? null,\n positioned: patch.positioned ?? this.state.positioned,\n scrolling: patch.scrolling ?? this.state.scrolling,\n size: patch.size ?? this.state.size,\n status: patch.status ?? this.state.status,\n waiting: patch.waiting ?? this.state.waiting,\n };\n\n const final = this.applyTransitions(merged);\n\n this.state = final;\n\n if (!deepEqual(previousSnapshot, final)) {\n this.snapshot = Object.freeze({ ...final });\n\n for (const listener of this.listeners) {\n listener(this.snapshot);\n }\n }\n };\n}\n\nexport default function createStore(options?: Props) {\n return new Store(options);\n}\n","import { type RefObject, useMemo, useRef } from 'react';\nimport is from 'is-lite';\n\nimport { ACTIONS, LIFECYCLE, STATUS } from '~/literals';\nimport { log, omit } from '~/modules/helpers';\nimport createStore from '~/modules/store';\nimport type { StoreState } from '~/modules/store';\n\nimport type { Controls, Origin, Status } from '~/types';\n\nfunction getUpdatedIndex(nextIndex: number, size: number): number {\n return Math.min(Math.max(nextIndex, 0), size);\n}\n\nexport default function useControls(\n store: RefObject>,\n debug: boolean,\n clearFailures: () => void,\n): Controls {\n const debugRef = useRef(debug);\n const clearFailuresRef = useRef(clearFailures);\n\n debugRef.current = debug;\n clearFailuresRef.current = clearFailures;\n\n return useMemo(() => {\n const getState = (): StoreState => store.current.getSnapshot();\n\n const close = (origin: Origin | null = null) => {\n const { index, status } = getState();\n\n if (status !== STATUS.RUNNING) {\n return;\n }\n\n store.current.updateState({\n action: ACTIONS.CLOSE,\n index: index + 1,\n origin,\n lifecycle: LIFECYCLE.COMPLETE,\n positioned: false,\n scrolling: false,\n waiting: false,\n });\n };\n\n const go = (nextIndex: number) => {\n const { controlled, size, status } = getState();\n\n if (controlled) {\n log(debugRef.current, 'tour', 'go() is not supported in controlled mode');\n\n return;\n }\n\n if (status !== STATUS.RUNNING) {\n return;\n }\n\n store.current.updateState({\n action: ACTIONS.GO,\n index: nextIndex,\n lifecycle: LIFECYCLE.COMPLETE,\n positioned: false,\n scrolling: false,\n status: nextIndex < size ? status : STATUS.FINISHED,\n waiting: false,\n });\n };\n\n const info = () => omit(store.current.getSnapshot(), 'positioned');\n\n const next = (origin?: Origin | null) => {\n const { index, size, status } = getState();\n\n if (status !== STATUS.RUNNING) {\n return;\n }\n\n store.current.updateState({\n action: ACTIONS.NEXT,\n index: getUpdatedIndex(index + 1, size),\n lifecycle: LIFECYCLE.COMPLETE,\n origin,\n positioned: false,\n scrolling: false,\n waiting: false,\n });\n };\n\n const open = () => {\n const { status } = getState();\n\n if (status !== STATUS.RUNNING) {\n return;\n }\n\n store.current.updateState({\n action: ACTIONS.UPDATE,\n lifecycle: LIFECYCLE.TOOLTIP_BEFORE,\n positioned: false,\n scrolling: false,\n waiting: false,\n });\n };\n\n const previous = (origin?: Origin | null) => {\n const { index, size, status } = getState();\n\n if (status !== STATUS.RUNNING) {\n return;\n }\n\n store.current.updateState({\n action: ACTIONS.PREV,\n index: getUpdatedIndex(index - 1, size),\n lifecycle: LIFECYCLE.COMPLETE,\n origin,\n positioned: false,\n scrolling: false,\n waiting: false,\n });\n };\n\n const replay = (origin?: Origin | null) => {\n const { lifecycle, status } = getState();\n\n if (status !== STATUS.RUNNING || lifecycle !== LIFECYCLE.TOOLTIP) {\n return;\n }\n\n store.current.updateState({\n action: ACTIONS.REPLAY,\n lifecycle: LIFECYCLE.COMPLETE,\n origin,\n positioned: false,\n scrolling: false,\n waiting: false,\n });\n };\n\n const reset = (restart = false) => {\n const { controlled } = getState();\n\n if (controlled) {\n log(debugRef.current, 'tour', 'reset() is not supported in controlled mode');\n\n return;\n }\n\n clearFailuresRef.current();\n store.current.updateState({\n action: ACTIONS.RESET,\n index: 0,\n lifecycle: LIFECYCLE.INIT,\n positioned: false,\n scrolling: false,\n status: restart ? STATUS.RUNNING : STATUS.READY,\n waiting: false,\n });\n };\n\n const skip = (origin?: Extract | null) => {\n const { status } = getState();\n\n if (status !== STATUS.RUNNING) {\n return;\n }\n\n store.current.updateState({\n action: ACTIONS.SKIP,\n lifecycle: LIFECYCLE.COMPLETE,\n origin,\n positioned: false,\n scrolling: false,\n status: STATUS.SKIPPED,\n waiting: false,\n });\n };\n\n const start = (nextIndex?: number) => {\n const { index, size } = getState();\n\n clearFailuresRef.current();\n store.current.updateState(\n {\n action: ACTIONS.START,\n index: is.number(nextIndex) ? nextIndex : index,\n lifecycle: LIFECYCLE.INIT,\n positioned: false,\n scrolling: false,\n status: size ? STATUS.RUNNING : STATUS.WAITING,\n waiting: false,\n },\n true,\n );\n };\n\n const stop = (advance = false) => {\n const { index, status } = getState();\n\n if (([STATUS.FINISHED, STATUS.SKIPPED] as Array).includes(status)) {\n return;\n }\n\n store.current.updateState({\n action: ACTIONS.STOP,\n index: index + (advance ? 1 : 0),\n lifecycle: LIFECYCLE.COMPLETE,\n positioned: false,\n scrolling: false,\n status: STATUS.PAUSED,\n waiting: false,\n });\n };\n\n return { close, go, info, next, open, prev: previous, replay, reset, skip, start, stop };\n }, [store]);\n}\n","import { type RefObject, useEffect, useRef } from 'react';\n\nimport { log } from '~/modules/helpers';\nimport type createStore from '~/modules/store';\nimport type { StoreState } from '~/modules/store';\n\nconst skipFields = new Set(['origin', 'positioned']);\n\nexport default function useDebugLogger(\n store: RefObject>,\n debug: boolean,\n): void {\n const previousRef = useRef(null);\n\n useEffect(() => {\n if (!debug) {\n return undefined;\n }\n\n const current = store.current.getSnapshot();\n\n log(true, 'tour', 'init', current);\n previousRef.current = current;\n\n return store.current.subscribe(state => {\n const previous = previousRef.current;\n\n previousRef.current = state;\n\n if (!previous) {\n return;\n }\n\n const changes: Record = {};\n let isTourLevel = false;\n\n for (const key of Object.keys(state) as Array) {\n if (state[key] !== previous[key] && !skipFields.has(key)) {\n changes[key] = { from: previous[key], to: state[key] };\n\n if (key === 'status' || key === 'size') {\n isTourLevel = true;\n }\n }\n }\n\n if (Object.keys(changes).length) {\n const outOfBounds = !isTourLevel && state.index >= state.size;\n\n if (!outOfBounds) {\n const scope = isTourLevel ? 'tour' : `step:${state.index}`;\n\n log(true, scope, 'state', changes);\n }\n }\n });\n }, [debug, store]);\n}\n","import { type RefObject, useCallback, useRef } from 'react';\n\nimport createStore from '~/modules/store';\n\nimport type {\n Actions,\n Controls,\n EventData,\n EventHandler,\n Events,\n Lifecycle,\n ScrollData,\n StepMerged,\n} from '~/types';\n\nexport type EmitEvent = (\n type: Events,\n step: StepMerged,\n overrides?: {\n action?: Actions;\n error?: Error | null;\n index?: number;\n lifecycle?: Lifecycle;\n scroll?: ScrollData | null;\n },\n) => void;\n\nexport default function useEventEmitter(\n onEvent: EventHandler | undefined,\n controls: Controls,\n store: RefObject>,\n): EmitEvent {\n const onEventRef = useRef(onEvent);\n const controlsRef = useRef(controls);\n\n onEventRef.current = onEvent;\n controlsRef.current = controls;\n\n return useCallback(\n (type, step, overrides) => {\n const data: EventData = {\n ...store.current.getEventState(),\n error: null,\n scroll: null,\n step,\n type,\n ...overrides,\n };\n\n onEventRef.current?.(data, controlsRef.current);\n store.current.dispatch(data, controlsRef.current);\n },\n [store],\n );\n}\n","import type { StoreState } from '~/modules/store';\n\nexport function treeChanges = StoreState>(state: T, previous: T) {\n return {\n hasChanged(key: K): boolean {\n return state[key] !== previous[key];\n },\n hasChangedTo(key: K, value: T[K] | T[K][]): boolean {\n const current = state[key];\n const previousValue = previous[key];\n\n if (Array.isArray(value)) {\n return value.includes(current) && !value.includes(previousValue);\n }\n\n return current === value && previousValue !== value;\n },\n previous,\n };\n}\n","import { type RefObject, useEffect, useRef } from 'react';\nimport { usePrevious } from '@gilbarbara/hooks';\n\nimport type { EmitEvent } from '~/hooks/useEventEmitter';\nimport type { AddFailure, MergedProps } from '~/hooks/useTourEngine';\nimport { ACTIONS, EVENTS, LIFECYCLE, STATUS } from '~/literals';\nimport { treeChanges } from '~/modules/changes';\nimport { getElement, isElementVisible, needsScrolling } from '~/modules/dom';\nimport { log } from '~/modules/helpers';\nimport { getMergedStep, shouldHideBeacon } from '~/modules/step';\nimport createStore from '~/modules/store';\nimport type { StoreState } from '~/modules/store';\n\nimport type { Actions, Controls, StepMerged, StepTarget } from '~/types';\n\ninterface UseLifecycleEffectOptions {\n addFailure: AddFailure;\n controls: Controls;\n emitEvent: EmitEvent;\n previousState: StoreState | undefined;\n props: MergedProps;\n state: StoreState;\n step: StepMerged | null;\n store: RefObject>;\n}\n\nexport default function useLifecycleEffect(options: UseLifecycleEffectOptions): void {\n const { addFailure, controls, emitEvent, previousState, props, state, step, store } = options;\n const { action, index, lifecycle, positioned, scrolling, size, status } = state;\n\n const previousStep = usePrevious(step) ?? null;\n\n const lastAction = useRef(null);\n const propsRef = useRef(props);\n const stateRef = useRef(state);\n const previousStateRef = useRef(previousState);\n const stepRef = useRef(step);\n const previousStepRef = useRef(previousStep);\n const controlsRef = useRef(controls);\n const pollingRef = useRef | null>(null);\n const pollingTargetRef = useRef(null);\n const beforeRef = useRef<{ cancel: () => void } | null>(null);\n\n propsRef.current = props;\n stateRef.current = state;\n previousStateRef.current = previousState;\n stepRef.current = step;\n previousStepRef.current = previousStep;\n controlsRef.current = controls;\n\n const cleanup = () => {\n if (pollingRef.current) {\n clearInterval(pollingRef.current);\n pollingRef.current = null;\n }\n\n pollingTargetRef.current = null;\n\n if (beforeRef.current) {\n beforeRef.current.cancel();\n beforeRef.current = null;\n }\n };\n\n // Effect 1: Action tracking\n useEffect(() => {\n if (!previousStateRef.current) {\n return;\n }\n\n const { hasChangedTo } = treeChanges(stateRef.current, previousStateRef.current);\n\n const isAfterAction = hasChangedTo('action', [\n ACTIONS.NEXT,\n ACTIONS.PREV,\n ACTIONS.SKIP,\n ACTIONS.CLOSE,\n ACTIONS.REPLAY,\n ]);\n\n const isStaleAfterStart =\n action === ACTIONS.START &&\n (lastAction.current === ACTIONS.CLOSE || lastAction.current === ACTIONS.REPLAY);\n\n if (isAfterAction || isStaleAfterStart) {\n lastAction.current = action;\n }\n }, [action]);\n\n // Effect 2: Target resolution (INIT → READY)\n useEffect(() => {\n if (!previousStateRef.current) {\n return () => {\n cleanup();\n };\n }\n\n const { hasChanged } = treeChanges(stateRef.current, previousStateRef.current);\n const currentStep = stepRef.current;\n\n if (hasChanged('index')) {\n cleanup();\n }\n\n if (status !== STATUS.RUNNING || !currentStep || lifecycle !== LIFECYCLE.INIT) {\n return () => {\n cleanup();\n };\n }\n\n // Fire tour:start before any step processing when status just changed to RUNNING\n const { hasChangedTo: hasStatusChangedTo } = treeChanges(\n stateRef.current,\n previousStateRef.current,\n );\n\n if (\n hasStatusChangedTo('status', STATUS.RUNNING) &&\n ([STATUS.IDLE, STATUS.READY, STATUS.PAUSED] as string[]).includes(\n previousStateRef.current.status,\n )\n ) {\n emitEvent(EVENTS.TOUR_START, currentStep);\n }\n\n store.current.cleanupPositionData();\n\n const { debug } = propsRef.current;\n\n if (currentStep.before && !beforeRef.current) {\n log(debug, `step:${index}`, 'before()', currentStep);\n beforeRef.current = { cancel: () => {} };\n\n store.current.updateState({ waiting: true });\n\n emitEvent(EVENTS.STEP_BEFORE_HOOK, currentStep, {\n action: lastAction.current ?? stateRef.current.action,\n });\n\n const proceed = () => {\n beforeRef.current = null;\n store.current.updateState({\n action: lastAction.current ?? stateRef.current.action,\n waiting: false,\n lifecycle: LIFECYCLE.READY,\n });\n };\n\n const abortController = new AbortController();\n const timeout = currentStep.beforeTimeout;\n\n beforeRef.current = { cancel: () => abortController.abort() };\n\n const timeoutId = timeout\n ? setTimeout(() => {\n if (!abortController.signal.aborted) {\n log(debug, `step:${index}`, 'before()', 'timed out', `${timeout}ms`);\n abortController.abort();\n addFailure(currentStep, 'before_hook');\n emitEvent(EVENTS.ERROR, currentStep, {\n error: new Error('Step before hook timed out'),\n });\n proceed();\n }\n }, timeout)\n : null;\n\n currentStep\n .before({\n ...store.current.getState(),\n action: lastAction.current ?? store.current.getState().action,\n step: currentStep,\n })\n .then(() => {\n if (!abortController.signal.aborted) {\n if (timeoutId) clearTimeout(timeoutId);\n proceed();\n }\n })\n .catch((error: unknown) => {\n if (!abortController.signal.aborted) {\n if (timeoutId) clearTimeout(timeoutId);\n addFailure(currentStep, 'before_hook');\n emitEvent(EVENTS.ERROR, currentStep, {\n error: error instanceof Error ? error : new Error(String(error)),\n });\n proceed();\n }\n });\n } else if (!beforeRef.current) {\n if (pollingRef.current && pollingTargetRef.current !== currentStep.target) {\n cleanup();\n }\n\n const element = getElement(currentStep.target);\n const targetAvailable = element && isElementVisible(element);\n\n if (targetAvailable) {\n cleanup();\n store.current.updateState({\n action: lastAction.current ?? ACTIONS.UPDATE,\n lifecycle: LIFECYCLE.READY,\n waiting: false,\n });\n } else if (currentStep.targetWaitTimeout === 0) {\n store.current.updateState({\n action: lastAction.current ?? ACTIONS.UPDATE,\n lifecycle: LIFECYCLE.READY,\n waiting: false,\n });\n } else if (!pollingRef.current) {\n const { targetWaitTimeout } = currentStep;\n\n const startTime = Date.now();\n\n pollingTargetRef.current = currentStep.target;\n log(debug, `step:${index}`, 'polling', 'started', `${targetWaitTimeout}ms`);\n\n store.current.updateState({ waiting: true });\n\n pollingRef.current = setInterval(() => {\n const el = getElement(currentStep.target);\n const elapsed = Date.now() - startTime;\n const timedOut = elapsed >= targetWaitTimeout;\n\n if ((el && isElementVisible(el)) || timedOut) {\n log(\n debug,\n `step:${index}`,\n 'polling',\n el && isElementVisible(el) ? 'found' : 'timed out',\n `${elapsed}ms`,\n );\n cleanup();\n store.current.updateState({\n action: lastAction.current ?? ACTIONS.UPDATE,\n lifecycle: LIFECYCLE.READY,\n waiting: false,\n });\n }\n }, 100);\n }\n }\n\n return () => {\n cleanup();\n };\n }, [addFailure, emitEvent, index, lifecycle, status, store]);\n\n // Effect 3: Step presentation (READY → *_BEFORE → BEACON/TOOLTIP) + target not found\n // eslint-disable-next-line sonarjs/cognitive-complexity\n useEffect(() => {\n if (!previousStateRef.current) {\n return;\n }\n\n const { hasChanged, hasChangedTo, previous } = treeChanges(\n stateRef.current,\n previousStateRef.current,\n );\n const currentStep = stepRef.current;\n\n if (!currentStep) {\n return;\n }\n\n const element = getElement(currentStep.target);\n const elementExists = !!element;\n\n if (elementExists && isElementVisible(element)) {\n if (hasChangedTo('lifecycle', LIFECYCLE.READY) && previous.lifecycle === LIFECYCLE.INIT) {\n emitEvent(EVENTS.STEP_BEFORE, currentStep, {\n action: lastAction.current ?? stateRef.current.action,\n });\n }\n\n if (hasChangedTo('lifecycle', LIFECYCLE.READY)) {\n const currentState = stateRef.current;\n const finalLifecycle = shouldHideBeacon(\n currentStep,\n currentState,\n propsRef.current.continuous,\n )\n ? LIFECYCLE.TOOLTIP\n : LIFECYCLE.BEACON;\n\n const target = getElement(\n currentStep.scrollTarget ?? currentStep.spotlightTarget ?? currentStep.target,\n );\n const willScroll = needsScrolling({\n isFirstStep: currentState.index === 0,\n scrollToFirstStep: propsRef.current.scrollToFirstStep,\n step: currentStep,\n target,\n targetLifecycle: finalLifecycle,\n });\n\n const beforeLifecycle =\n finalLifecycle === LIFECYCLE.TOOLTIP ? LIFECYCLE.TOOLTIP_BEFORE : LIFECYCLE.BEACON_BEFORE;\n\n log(propsRef.current.debug, `step:${index}`, 'scroll', willScroll ? 'needed' : 'skipped');\n\n store.current.updateState({\n action: ACTIONS.UPDATE,\n lifecycle: beforeLifecycle,\n scrolling: willScroll,\n });\n }\n } else if (\n stateRef.current.status === STATUS.RUNNING &&\n lifecycle !== LIFECYCLE.INIT &&\n lifecycle !== LIFECYCLE.COMPLETE &&\n hasChanged('lifecycle')\n ) {\n log(\n propsRef.current.debug,\n `step:${index}`,\n elementExists ? 'Target not visible' : 'Target not mounted',\n currentStep,\n );\n\n addFailure(currentStep, 'target_not_found');\n emitEvent(EVENTS.TARGET_NOT_FOUND, currentStep);\n\n const currentState = stateRef.current;\n\n if (!currentState.controlled) {\n store.current.updateState({\n action: ACTIONS.UPDATE,\n index: currentState.index + (currentState.action === ACTIONS.PREV ? -1 : 1),\n lifecycle: LIFECYCLE.INIT,\n });\n }\n }\n }, [addFailure, emitEvent, index, lifecycle, store]);\n\n // Effect 4: *_BEFORE → BEACON/TOOLTIP transition + lifecycle callbacks\n // eslint-disable-next-line sonarjs/cognitive-complexity\n useEffect(() => {\n if (!previousStateRef.current) {\n return;\n }\n\n const { hasChangedTo, previous } = treeChanges(stateRef.current, previousStateRef.current);\n const currentStep = stepRef.current;\n const previousStepValue = previousStepRef.current;\n\n // BEACON → TOOLTIP_BEFORE: check if scroll adjustment is needed\n if (\n currentStep &&\n hasChangedTo('lifecycle', LIFECYCLE.TOOLTIP_BEFORE) &&\n previous.lifecycle === LIFECYCLE.BEACON\n ) {\n const target = getElement(\n currentStep.scrollTarget ?? currentStep.spotlightTarget ?? currentStep.target,\n );\n const willScroll = needsScrolling({\n isFirstStep: stateRef.current.index === 0,\n scrollToFirstStep: propsRef.current.scrollToFirstStep,\n step: currentStep,\n target,\n targetLifecycle: LIFECYCLE.TOOLTIP,\n });\n\n if (willScroll) {\n store.current.updateState({ scrolling: true, positioned: false });\n\n return;\n }\n }\n\n // *_BEFORE → BEACON/TOOLTIP when scroll is done\n const isBeforePhase =\n lifecycle === LIFECYCLE.BEACON_BEFORE || lifecycle === LIFECYCLE.TOOLTIP_BEFORE;\n\n if (currentStep && isBeforePhase && !scrolling) {\n const finalLifecycle =\n lifecycle === LIFECYCLE.TOOLTIP_BEFORE ? LIFECYCLE.TOOLTIP : LIFECYCLE.BEACON;\n\n store.current.updateState({\n action: ACTIONS.UPDATE,\n lifecycle: finalLifecycle,\n });\n }\n\n if (currentStep && hasChangedTo('lifecycle', LIFECYCLE.BEACON)) {\n emitEvent(EVENTS.BEACON, currentStep);\n }\n\n if (currentStep && hasChangedTo('lifecycle', LIFECYCLE.TOOLTIP)) {\n emitEvent(EVENTS.TOOLTIP, currentStep);\n }\n\n const currentState = stateRef.current;\n const isRunningOrPausedWithStep =\n currentState.status === STATUS.RUNNING ||\n (currentState.controlled && currentState.status === STATUS.PAUSED && !!currentStep);\n const shouldFireStepAfter =\n isRunningOrPausedWithStep &&\n previousStepValue &&\n hasChangedTo('lifecycle', LIFECYCLE.COMPLETE) &&\n previous.lifecycle === LIFECYCLE.TOOLTIP;\n\n if (shouldFireStepAfter) {\n emitEvent(EVENTS.STEP_AFTER, previousStepValue, {\n action: lastAction.current ?? ACTIONS.UPDATE,\n index: previous.index ?? currentState.index,\n lifecycle: currentState.lifecycle,\n });\n\n if (previousStepValue.after) {\n emitEvent(EVENTS.STEP_AFTER_HOOK, previousStepValue, {\n action: lastAction.current ?? ACTIONS.UPDATE,\n index: previous.index ?? currentState.index,\n lifecycle: currentState.lifecycle,\n });\n\n try {\n previousStepValue.after({\n ...store.current.getState(),\n action: lastAction.current ?? ACTIONS.UPDATE,\n index: previous.index ?? currentState.index,\n lifecycle: currentState.lifecycle,\n step: previousStepValue,\n });\n } catch {\n // fire-and-forget: don't let user code break the tour\n }\n }\n }\n }, [emitEvent, lifecycle, positioned, scrolling, store]);\n\n // Effect 5: Tour flow + tour-level callbacks\n // eslint-disable-next-line sonarjs/cognitive-complexity\n useEffect(() => {\n if (!previousStateRef.current) {\n return;\n }\n\n const { hasChangedTo, previous } = treeChanges(stateRef.current, previousStateRef.current);\n const currentStep = stepRef.current;\n const previousStepValue = previousStepRef.current;\n\n if (hasChangedTo('action', ACTIONS.REPLAY) && hasChangedTo('lifecycle', LIFECYCLE.COMPLETE)) {\n store.current.updateState({ lifecycle: LIFECYCLE.INIT });\n\n return;\n }\n\n if (size && !currentStep && lifecycle === LIFECYCLE.INIT) {\n store.current.updateState({\n action: ACTIONS.UPDATE,\n lifecycle: LIFECYCLE.COMPLETE,\n status: STATUS.FINISHED,\n });\n }\n\n if (\n !stateRef.current.controlled &&\n status === STATUS.RUNNING &&\n hasChangedTo('lifecycle', LIFECYCLE.COMPLETE) &&\n index < size\n ) {\n store.current.updateState({ action: ACTIONS.UPDATE, lifecycle: LIFECYCLE.INIT });\n }\n\n if (hasChangedTo('lifecycle', LIFECYCLE.COMPLETE) && index >= size) {\n store.current.updateState({\n action: ACTIONS.UPDATE,\n lifecycle: LIFECYCLE.COMPLETE,\n status: STATUS.FINISHED,\n });\n }\n\n const tourEndStep =\n currentStep ??\n previousStepValue ??\n getMergedStep(propsRef.current, propsRef.current.steps[index - 1]);\n\n if (tourEndStep && hasChangedTo('status', [STATUS.FINISHED, STATUS.SKIPPED])) {\n let tourEndIndex: number;\n\n if (currentStep) {\n tourEndIndex = index;\n } else if (previousStepValue) {\n tourEndIndex = previous.index ?? index;\n } else {\n tourEndIndex = index - 1;\n }\n\n emitEvent(EVENTS.TOUR_END, tourEndStep, { index: tourEndIndex });\n\n if (!stateRef.current.controlled) {\n controlsRef.current.reset();\n }\n\n lastAction.current = null;\n }\n\n // tour:start is emitted in Effect 2 (before step processing) to ensure correct event order\n\n if (currentStep && hasChangedTo('action', ACTIONS.STOP)) {\n lastAction.current = null;\n emitEvent(EVENTS.TOUR_STATUS, currentStep);\n }\n\n if (currentStep && hasChangedTo('action', ACTIONS.RESET)) {\n emitEvent(EVENTS.TOUR_STATUS, currentStep);\n lastAction.current = null;\n }\n }, [action, emitEvent, index, lifecycle, size, status, store]);\n}\n","import { type RefObject, useEffect, useRef } from 'react';\nimport isEqual from '@gilbarbara/deep-equal';\nimport is from 'is-lite';\n\nimport type { EmitEvent } from '~/hooks/useEventEmitter';\nimport type { MergedProps } from '~/hooks/useTourEngine';\nimport { ACTIONS, EVENTS, LIFECYCLE, STATUS } from '~/literals';\nimport { treeChanges } from '~/modules/changes';\nimport { log } from '~/modules/helpers';\nimport { validateSteps } from '~/modules/step';\nimport createStore from '~/modules/store';\nimport type { StoreState } from '~/modules/store';\n\nimport type { Actions, Controls, Status, StepMerged } from '~/types';\n\ninterface UsePropSyncParams {\n controls: Controls;\n emitEvent: EmitEvent;\n props: MergedProps;\n state: StoreState;\n store: RefObject>;\n}\n\nexport default function usePropSync({\n controls,\n emitEvent,\n props,\n state,\n store,\n}: UsePropSyncParams): void {\n const { debug, initialStepIndex, run, stepIndex, steps } = props;\n\n const previousPropsRef = useRef(undefined);\n const stateRef = useRef(state);\n const controlsRef = useRef(controls);\n\n stateRef.current = state;\n controlsRef.current = controls;\n\n useEffect(() => {\n const previousProps = previousPropsRef.current;\n\n previousPropsRef.current = props;\n\n if (!previousProps || props === previousProps) {\n return;\n }\n\n const { hasChanged } = treeChanges(props, previousProps);\n\n if (!isEqual(previousProps.steps, steps)) {\n if (validateSteps(steps, debug)) {\n store.current.setSteps(steps);\n } else {\n log(debug, 'tour', 'Steps are not valid', steps);\n emitEvent(EVENTS.ERROR, (steps[0] ?? { target: '', content: '' }) as StepMerged, {\n error: new Error('Steps are not valid'),\n });\n }\n }\n\n if (hasChanged('run')) {\n if (run) {\n if (store.current.getState().size) {\n controlsRef.current.start(stepIndex ?? initialStepIndex);\n }\n } else {\n controlsRef.current.stop();\n }\n } else if (is.number(stepIndex) && hasChanged('stepIndex')) {\n const nextAction: Actions =\n is.number(previousProps.stepIndex) && previousProps.stepIndex < stepIndex\n ? ACTIONS.NEXT\n : ACTIONS.PREV;\n\n if (!([STATUS.FINISHED, STATUS.SKIPPED] as Array).includes(stateRef.current.status)) {\n store.current.updateState(\n { action: nextAction, index: stepIndex, lifecycle: LIFECYCLE.INIT, positioned: false },\n true,\n );\n }\n }\n }, [debug, emitEvent, initialStepIndex, props, run, stepIndex, steps, store]);\n}\n","import { type RefObject, useEffect, useRef } from 'react';\n\nimport type { EmitEvent } from '~/hooks/useEventEmitter';\nimport type { MergedProps } from '~/hooks/useTourEngine';\nimport { EVENTS, LIFECYCLE, STATUS } from '~/literals';\nimport { treeChanges } from '~/modules/changes';\nimport {\n getElement,\n getScrollParent,\n getScrollTargetToCenter,\n getScrollTo,\n hasPosition,\n scrollDocument,\n scrollTo,\n} from '~/modules/dom';\nimport { log } from '~/modules/helpers';\nimport createStore from '~/modules/store';\nimport type { StoreState } from '~/modules/store';\n\nimport type { Lifecycle, PositionData, StepMerged } from '~/types';\n\ninterface UseScrollEffectParams {\n emitEvent: EmitEvent;\n previousState: StoreState | undefined;\n props: MergedProps;\n state: StoreState;\n step: StepMerged | null;\n store: RefObject>;\n}\n\nfunction adjustForPlacement(\n scrollY: number,\n options: {\n beaconPosition: PositionData | null;\n lifecycle: Lifecycle;\n scrollOffset: number;\n step: StepMerged;\n },\n): number {\n const { beaconPosition, lifecycle, scrollOffset, step } = options;\n\n if (step.scrollTarget || step.spotlightTarget) {\n return Math.max(0, scrollY);\n }\n\n let adjustedY = scrollY - step.spotlightPadding.top;\n\n if (lifecycle === LIFECYCLE.BEACON_BEFORE && beaconPosition?.placement) {\n const y = getMainAxisOffset(beaconPosition);\n\n if (!['bottom'].includes(beaconPosition.placement)) {\n adjustedY += Math.floor(y - scrollOffset);\n }\n } else if (lifecycle === LIFECYCLE.TOOLTIP_BEFORE) {\n const { placement } = step;\n\n if (placement === 'top') {\n const floaterElement = document.querySelector('.react-joyride__floater');\n const floaterHeight = floaterElement?.getBoundingClientRect().height ?? 0;\n const arrowSize = step.floatingOptions?.hideArrow ? 0 : step.arrowSize;\n const gap = step.offset + step.spotlightPadding.top + arrowSize;\n\n adjustedY -= floaterHeight + gap;\n } else if (placement === 'left' || placement === 'right') {\n const floaterElement = document.querySelector('.react-joyride__floater');\n const floaterHeight = floaterElement?.getBoundingClientRect().height ?? 0;\n const targetEl = getElement(step.target);\n const targetHeight = targetEl?.getBoundingClientRect().height ?? 0;\n\n // After base scroll, the target center sits at this distance from viewport top\n const targetCenterY = scrollOffset + step.spotlightPadding.top + targetHeight / 2;\n // The floater is centered on the target, so its top edge would be here\n const floaterTopY = targetCenterY - floaterHeight / 2;\n\n if (floaterTopY < scrollOffset) {\n adjustedY -= scrollOffset - floaterTopY;\n }\n }\n }\n\n return Math.max(0, adjustedY);\n}\n\nfunction getMainAxisOffset(data: PositionData): number {\n const offsetData = data.middlewareData?.offset as { x: number; y: number } | undefined;\n\n if (!offsetData) {\n return 0;\n }\n\n return ['left', 'right'].some(p => data.placement.startsWith(p)) ? offsetData.x : offsetData.y;\n}\n\nexport default function useScrollEffect({\n emitEvent,\n previousState,\n props,\n state,\n step,\n store,\n}: UseScrollEffectParams): void {\n const { index, lifecycle, positioned, scrolling, status } = state;\n const cancelScrollRef = useRef<(() => void) | null>(null);\n const stateRef = useRef(state);\n const previousStateRef = useRef(previousState);\n const propsRef = useRef(props);\n const stepRef = useRef(step);\n\n stateRef.current = state;\n previousStateRef.current = previousState;\n propsRef.current = props;\n stepRef.current = step;\n\n useEffect(() => {\n return () => {\n cancelScrollRef.current?.();\n };\n }, []);\n\n useEffect(() => {\n if (!previousStateRef.current || !stepRef.current) {\n return;\n }\n\n const { hasChangedTo } = treeChanges(stateRef.current, previousStateRef.current);\n const currentStep = stepRef.current;\n const { debug } = propsRef.current;\n const { scrollDuration } = currentStep;\n\n const isBeforePhase =\n lifecycle === LIFECYCLE.BEACON_BEFORE || lifecycle === LIFECYCLE.TOOLTIP_BEFORE;\n\n if (\n status === STATUS.RUNNING &&\n isBeforePhase &&\n scrolling &&\n hasChangedTo('positioned', true)\n ) {\n const target = getElement(\n currentStep.scrollTarget ?? currentStep.spotlightTarget ?? currentStep.target,\n );\n const beaconPosition = store.current.getPositionData('beacon');\n const scrollParent = getScrollParent(target);\n const hasCustomScroll = scrollParent ? !scrollParent.isSameNode(scrollDocument()) : false;\n\n cancelScrollRef.current?.();\n\n const handleScroll = async () => {\n if (hasCustomScroll && !hasPosition(scrollParent as HTMLElement)) {\n const pageElement = scrollDocument();\n const pageScrollY = getScrollTargetToCenter(scrollParent as Element);\n const pageScrollData = {\n initial: pageElement.scrollTop,\n target: pageScrollY,\n element: pageElement,\n duration: scrollDuration,\n };\n\n emitEvent(EVENTS.SCROLL_START, currentStep, { scroll: pageScrollData });\n\n const { cancel: cancelPage, promise: pagePromise } = scrollTo(pageScrollY, {\n element: pageElement,\n duration: scrollDuration,\n });\n\n cancelScrollRef.current = cancelPage;\n await pagePromise;\n\n emitEvent(EVENTS.SCROLL_END, currentStep, { scroll: pageScrollData });\n }\n\n const baseScrollY = Math.floor(getScrollTo(target, currentStep.scrollOffset)) || 0;\n const scrollY = hasCustomScroll\n ? baseScrollY\n : adjustForPlacement(baseScrollY, {\n beaconPosition,\n lifecycle,\n scrollOffset: currentStep.scrollOffset,\n step: currentStep,\n });\n\n log(\n debug,\n `step:${index}`,\n 'scroll',\n hasCustomScroll ? 'custom' : 'document',\n `${baseScrollY} → ${scrollY}`,\n );\n\n const scrollElement = scrollParent as Element;\n const scrollData = {\n initial: scrollElement.scrollTop,\n target: scrollY,\n element: scrollElement,\n duration: scrollDuration,\n };\n\n emitEvent(EVENTS.SCROLL_START, currentStep, { scroll: scrollData });\n\n const { cancel, promise } = scrollTo(scrollY, {\n element: scrollElement,\n duration: scrollDuration,\n });\n\n cancelScrollRef.current = cancel;\n await promise;\n\n emitEvent(EVENTS.SCROLL_END, currentStep, { scroll: scrollData });\n store.current.updateState({ scrolling: false });\n };\n\n handleScroll().catch(() => {\n store.current.updateState({ scrolling: false });\n });\n }\n }, [emitEvent, index, lifecycle, positioned, scrolling, status, store]);\n}\n","import { type RefObject, useCallback, useMemo, useRef, useState } from 'react';\nimport { useMemoDeepCompare, useMount, usePrevious, useUpdateEffect } from '@gilbarbara/hooks';\nimport { useSyncExternalStore } from 'use-sync-external-store/shim';\n\nimport { defaultProps } from '~/defaults';\nimport useControls from '~/hooks/useControls';\nimport useDebugLogger from '~/hooks/useDebugLogger';\nimport useEventEmitter from '~/hooks/useEventEmitter';\nimport useLifecycleEffect from '~/hooks/useLifecycleEffect';\nimport usePropSync from '~/hooks/usePropSync';\nimport useScrollEffect from '~/hooks/useScrollEffect';\nimport { STATUS } from '~/literals';\nimport { mergeProps } from '~/modules/helpers';\nimport { getMergedStep, validateSteps } from '~/modules/step';\nimport createStore from '~/modules/store';\nimport type { StoreState } from '~/modules/store';\n\nimport type { Controls, FailureReason, Props, StepFailure, StepMerged } from '~/types';\n\nexport type AddFailure = (step: StepMerged, reason: FailureReason) => void;\n\nexport type MergedProps = ReturnType>;\n\nexport interface UseTourEngineReturn {\n controls: Controls;\n failures: StepFailure[];\n mergedProps: MergedProps;\n state: StoreState;\n step: StepMerged | null;\n store: RefObject>;\n}\n\nexport default function useTourEngine(props: Props): UseTourEngineReturn {\n const mergedProps = useMemoDeepCompare(() => mergeProps(defaultProps, props), [props]);\n const { debug, initialStepIndex, onEvent, run, stepIndex, steps } = mergedProps;\n\n const store = useRef(createStore(mergedProps));\n const state = useSyncExternalStore(\n store.current.subscribe,\n store.current.getSnapshot,\n store.current.getServerSnapshot,\n );\n\n const [failures, setFailures] = useState([]);\n\n const addFailure: AddFailure = useCallback((failedStep, reason) => {\n setFailures(previous => [...previous, { reason, step: failedStep }]);\n }, []);\n\n const clearFailures = useCallback(() => {\n setFailures([]);\n }, []);\n\n useDebugLogger(store, debug);\n\n const controls = useControls(store, debug, clearFailures);\n const emitEvent = useEventEmitter(onEvent, controls, store);\n\n const { index, size, status } = state;\n\n const previousState = usePrevious(state);\n\n const step = useMemo(() => getMergedStep(mergedProps, steps[index]), [index, mergedProps, steps]);\n\n useMount(() => {\n if (run && size && validateSteps(steps, debug)) {\n controls.start(stepIndex ?? initialStepIndex);\n }\n });\n\n useUpdateEffect(() => {\n if (run && size && status === STATUS.IDLE) {\n store.current.updateState({ status: STATUS.READY });\n }\n }, [run, size, status]);\n\n usePropSync({\n controls,\n emitEvent,\n props: mergedProps,\n state,\n store,\n });\n\n useLifecycleEffect({\n addFailure,\n controls,\n emitEvent,\n previousState,\n props: mergedProps,\n state,\n step,\n store,\n });\n\n useScrollEffect({\n emitEvent,\n previousState,\n props: mergedProps,\n state,\n step,\n store,\n });\n\n return { controls, failures, mergedProps, state, step, store };\n}\n","import { useEffect, useState } from 'react';\nimport is from 'is-lite';\n\nimport { PORTAL_ELEMENT_ID } from '~/literals';\n\nimport type { SelectorOrElement } from '~/types';\n\nexport function usePortalElement(portalElement?: SelectorOrElement) {\n const [element, setElement] = useState(null);\n\n useEffect(() => {\n let createdElement: HTMLElement | null = null;\n let isExternal = false;\n\n if (portalElement) {\n if (is.domElement(portalElement)) {\n createdElement = portalElement;\n isExternal = true;\n } else {\n const portal = document.querySelector(portalElement);\n\n if (portal) {\n createdElement = portal as HTMLElement;\n }\n }\n } else {\n const portal = document.createElement('div');\n\n portal.id = PORTAL_ELEMENT_ID;\n\n document.body.appendChild(portal);\n createdElement = portal;\n }\n\n setElement(createdElement);\n\n return () => {\n if (!createdElement || isExternal) {\n return;\n }\n\n if (createdElement.parentNode === document.body) {\n document.body.removeChild(createdElement);\n }\n };\n }, [portalElement]);\n\n return element;\n}\n","import { type CSSProperties, useEffect } from 'react';\n\nimport { noop } from '~/modules/helpers';\n\nimport type { LoaderRenderProps, Props, Simplify } from '~/types';\n\ntype LoaderProps = Simplify & LoaderRenderProps>;\n\nconst spinnerStyles: CSSProperties = {\n animation: 'joyride-loader-spin 1s linear infinite',\n border: '5px solid rgba(0, 0, 0, 0.1)',\n borderRadius: '50%',\n borderTopColor: '#555',\n};\n\nexport default function JoyrideLoader({ nonce, step }: LoaderProps) {\n const { loaderComponent } = step;\n\n const hasLoaderComponent = Boolean(loaderComponent);\n\n useEffect(() => {\n if (hasLoaderComponent) {\n return noop;\n }\n\n if (document.getElementById('joyride-loader-animation')) {\n return noop;\n }\n\n const style = document.createElement('style');\n\n style.id = 'joyride-loader-animation';\n\n if (nonce) {\n style.setAttribute('nonce', nonce);\n }\n\n style.appendChild(\n document.createTextNode(`\n @keyframes joyride-loader-spin {\n to { transform: rotate(360deg); }\n }\n `),\n );\n\n document.head.appendChild(style);\n\n return () => {\n const insertedStyle = document.getElementById('joyride-loader-animation');\n\n if (insertedStyle?.parentNode) {\n insertedStyle.parentNode.removeChild(insertedStyle);\n }\n };\n }, [hasLoaderComponent, nonce]);\n\n if (loaderComponent === null) {\n return null;\n }\n\n const { height, width, ...loaderStyle } = step.styles.loader;\n\n let content;\n\n if (loaderComponent) {\n const CustomLoader = loaderComponent;\n\n content = ;\n } else {\n content = (\n
\n );\n }\n\n return (\n
\n {content}\n
\n );\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\n\nimport {\n getClientRect,\n getElement,\n getElementPosition,\n getScrollParent,\n hasPosition,\n} from '~/modules/dom';\n\nimport type { SpotlightPadding, StepTarget } from '~/types';\n\nexport interface TargetRect {\n height: number;\n isFixed: boolean;\n left: number;\n top: number;\n width: number;\n}\n\nconst defaultRect: TargetRect = {\n height: 0,\n isFixed: false,\n left: 0,\n top: 0,\n width: 0,\n};\n\nfunction computeRect(target: StepTarget, spotlightPadding: Required): TargetRect {\n const element = getElement(target);\n\n if (!element) {\n return defaultRect;\n }\n\n const elementRect = getClientRect(element);\n const isFixed = hasPosition(element);\n const top = getElementPosition(element, spotlightPadding.top, isFixed);\n\n return {\n height: Math.round((elementRect?.height ?? 0) + spotlightPadding.top + spotlightPadding.bottom),\n isFixed,\n left: Math.round((elementRect?.left ?? 0) - spotlightPadding.left),\n top,\n width: Math.round((elementRect?.width ?? 0) + spotlightPadding.left + spotlightPadding.right),\n };\n}\n\nexport default function useTargetPosition(\n target: StepTarget,\n spotlightPadding: Required,\n force: boolean,\n): TargetRect {\n const [rect, setRect] = useState(() => computeRect(target, spotlightPadding));\n const timeoutRef = useRef(undefined);\n const scrollParentRef = useRef(null);\n const previousForceRef = useRef(force);\n const observerRef = useRef(null);\n\n const updateRect = useCallback(() => {\n clearTimeout(timeoutRef.current);\n\n timeoutRef.current = window.setTimeout(() => {\n setRect(previous => {\n const next = computeRect(target, spotlightPadding);\n\n if (\n previous.top === next.top &&\n previous.left === next.left &&\n previous.width === next.width &&\n previous.height === next.height &&\n previous.isFixed === next.isFixed\n ) {\n return previous;\n }\n\n return next;\n });\n }, 100);\n }, [target, spotlightPadding]);\n\n useEffect(() => {\n let mutationObserver: MutationObserver | null = null;\n\n const setup = (element: HTMLElement) => {\n scrollParentRef.current = getScrollParent(element, true);\n\n if (scrollParentRef.current) {\n scrollParentRef.current.addEventListener('scroll', updateRect, { passive: true });\n }\n\n window.addEventListener('scroll', updateRect, { passive: true });\n window.addEventListener('resize', updateRect);\n\n if (typeof ResizeObserver !== 'undefined') {\n observerRef.current = new ResizeObserver(updateRect);\n observerRef.current.observe(element);\n }\n\n setRect(computeRect(target, spotlightPadding));\n };\n\n const element = getElement(target);\n\n if (element) {\n setup(element);\n } else {\n // Target not in DOM yet — watch for it\n mutationObserver = new MutationObserver(() => {\n const el = getElement(target);\n\n if (el) {\n mutationObserver?.disconnect();\n mutationObserver = null;\n setup(el);\n }\n });\n\n mutationObserver.observe(document.body, { childList: true, subtree: true });\n }\n\n return () => {\n mutationObserver?.disconnect();\n\n if (scrollParentRef.current) {\n scrollParentRef.current.removeEventListener('scroll', updateRect);\n }\n\n window.removeEventListener('scroll', updateRect);\n window.removeEventListener('resize', updateRect);\n\n observerRef.current?.disconnect();\n clearTimeout(timeoutRef.current);\n };\n }, [target, spotlightPadding, updateRect]);\n\n // Persist to state and track transitions after render\n useEffect(() => {\n if (previousForceRef.current && !force) {\n setRect(computeRect(target, spotlightPadding));\n }\n\n previousForceRef.current = force;\n }, [force, target, spotlightPadding]);\n\n // Synchronous override: when scrolling just ended, return fresh rect immediately\n let finalRect = rect;\n\n if (previousForceRef.current && !force) {\n finalRect = computeRect(target, spotlightPadding);\n }\n\n return finalRect;\n}\n","export function generateOverlayPath(\n overlayWidth: number,\n overlayHeight: number,\n cutout: string,\n): string {\n let path = `M0 0H${overlayWidth}V${overlayHeight}H0Z`;\n\n if (cutout) {\n path += ` ${cutout}`;\n }\n\n return path;\n}\n\nexport function generateSpotlightPath(\n x: number,\n y: number,\n width: number,\n height: number,\n borderRadius: number,\n): string {\n if (width <= 0 || height <= 0) {\n return '';\n }\n\n const r = Math.max(0, Math.min(borderRadius, width / 2, height / 2));\n\n let path = `M${x + r} ${y}`;\n\n path += `H${x + width - r}`;\n path += `A${r} ${r} 0 0 1 ${x + width} ${y + r}`;\n path += `V${y + height - r}`;\n path += `A${r} ${r} 0 0 1 ${x + width - r} ${y + height}`;\n path += `H${x + r}`;\n path += `A${r} ${r} 0 0 1 ${x} ${y + height - r}`;\n path += `V${y + r}`;\n path += `A${r} ${r} 0 0 1 ${x + r} ${y}Z`;\n\n return path;\n}\n","import { type CSSProperties, useEffect, useMemo, useRef, useState } from 'react';\nimport { useWindowSize } from '@gilbarbara/hooks';\n\nimport useTargetPosition from '~/hooks/useTargetPosition';\nimport { LIFECYCLE } from '~/literals';\nimport { getAbsoluteOffset, getDocumentHeight, getElement } from '~/modules/dom';\nimport { generateOverlayPath, generateSpotlightPath } from '~/modules/svg';\n\nimport type { Lifecycle, Simplify, StepMerged } from '~/types';\n\nexport type OverlayProps = Simplify<\n StepMerged & {\n continuous: boolean;\n lifecycle: Lifecycle;\n onClickOverlay: () => void;\n portalElement?: HTMLElement | null;\n scrolling: boolean;\n waiting: boolean;\n }\n>;\n\nconst hiddenLifecycles: Lifecycle[] = [LIFECYCLE.BEACON_BEFORE, LIFECYCLE.BEACON];\n\nexport default function JoyrideOverlay(props: OverlayProps) {\n const {\n blockTargetInteraction,\n continuous,\n hideOverlay,\n lifecycle,\n onClickOverlay,\n overlayClickAction,\n placement,\n portalElement,\n scrolling,\n spotlightPadding,\n spotlightRadius,\n spotlightTarget,\n styles,\n target,\n waiting,\n } = props;\n const windowSize = useWindowSize();\n const targetRect = useTargetPosition(\n spotlightTarget ?? target,\n spotlightPadding,\n scrolling || waiting,\n );\n const overlayRef = useRef(null);\n\n const showSpotlight =\n (lifecycle === LIFECYCLE.TOOLTIP || lifecycle === LIFECYCLE.TOOLTIP_BEFORE) &&\n placement !== 'center';\n const [spotlightReady, setSpotlightReady] = useState(false);\n\n const container = portalElement ? (overlayRef.current?.offsetParent as HTMLElement | null) : null;\n const overlayWidth = container?.clientWidth ?? windowSize.width;\n const overlayHeight = container?.clientHeight ?? getDocumentHeight() ?? windowSize.height;\n\n const overlayColor = (styles.overlay?.backgroundColor ?? 'rgba(0, 0, 0, 0.5)') as string;\n\n const overlayStyles = useMemo(() => {\n const { backgroundColor: _bg, mixBlendMode: _mbm, ...rest } = styles.overlay;\n\n return {\n height: overlayHeight,\n pointerEvents: 'none',\n ...rest,\n } as CSSProperties;\n }, [overlayHeight, styles.overlay]);\n\n const showCutout = showSpotlight && !scrolling && !waiting;\n\n useEffect(() => {\n if (showCutout) {\n requestAnimationFrame(() => setSpotlightReady(true));\n } else {\n setSpotlightReady(false);\n }\n }, [showCutout]);\n\n const isHiddenInContinuous = continuous && hiddenLifecycles.includes(lifecycle);\n const isHiddenInNonContinuous = !continuous && lifecycle !== LIFECYCLE.TOOLTIP;\n\n if (hideOverlay || (!waiting && (isHiddenInContinuous || isHiddenInNonContinuous))) {\n return null;\n }\n\n // When using a custom portal, compute spotlight in layout space (offsetTop/offsetLeft/offsetWidth/offsetHeight)\n // because targetRect uses getBoundingClientRect() which is viewport-relative and doesn't match the SVG's layout space.\n let coverPath = '';\n\n if (showCutout) {\n if (portalElement && container) {\n const targetEl = getElement(spotlightTarget ?? target);\n\n if (targetEl) {\n const targetOffset = getAbsoluteOffset(targetEl);\n const containerOffset = getAbsoluteOffset(container);\n\n coverPath = generateSpotlightPath(\n targetOffset.left - containerOffset.left - spotlightPadding.left,\n targetOffset.top - containerOffset.top - spotlightPadding.top,\n targetEl.offsetWidth + spotlightPadding.left + spotlightPadding.right,\n targetEl.offsetHeight + spotlightPadding.top + spotlightPadding.bottom,\n spotlightRadius,\n );\n }\n } else {\n coverPath = generateSpotlightPath(\n targetRect.left,\n targetRect.top,\n targetRect.width,\n targetRect.height,\n spotlightRadius,\n );\n }\n }\n\n const path = generateOverlayPath(overlayWidth, overlayHeight, coverPath);\n\n return (\n \n \n \n {coverPath && (\n \n )}\n {coverPath && Object.keys(styles.spotlight).length > 0 && (\n \n )}\n \n
\n );\n}\n","import type { ReactNode } from 'react';\nimport { createPortal } from 'react-dom';\n\ninterface Props {\n children: ReactNode;\n element: HTMLElement | null;\n}\n\nexport default function JoyridePortal(props: Props) {\n const { children, element } = props;\n\n if (!element) {\n return null;\n }\n\n return createPortal(children, element);\n}\n","import { useEffect, useRef } from 'react';\n\nimport { noop } from '~/modules/helpers';\n\nconst TABBABLE_SELECTOR =\n 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), area[href], [tabindex]:not([tabindex=\"-1\"]), [contenteditable]';\n\nexport default function useFocusTrap(element: HTMLElement | null, selector?: string | null): void {\n const previousFocus = useRef(null);\n\n useEffect(() => {\n if (!element) {\n return noop;\n }\n\n previousFocus.current = document.activeElement as HTMLElement | null;\n\n const handleKeyDown = (event: KeyboardEvent) => {\n if (event.key !== 'Tab') {\n return;\n }\n\n const elements = [...element.querySelectorAll(TABBABLE_SELECTOR)];\n const { shiftKey } = event;\n\n if (!elements.length) {\n return;\n }\n\n event.preventDefault();\n\n let index = document.activeElement\n ? elements.indexOf(document.activeElement as HTMLElement)\n : 0;\n\n if (index === -1 || (!shiftKey && index + 1 === elements.length)) {\n index = 0;\n } else if (shiftKey && index === 0) {\n index = elements.length - 1;\n } else {\n index += shiftKey ? -1 : 1;\n }\n\n elements[index].focus();\n };\n\n element.addEventListener('keydown', handleKeyDown, false);\n\n let timerId: ReturnType | undefined;\n\n if (selector) {\n const target = element.querySelector(selector);\n\n if (target) {\n // Delay focus to allow Floater's CSS transition to complete\n timerId = setTimeout(() => {\n target.focus({ preventScroll: true });\n }, 100);\n }\n }\n\n return () => {\n element.removeEventListener('keydown', handleKeyDown);\n\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n\n previousFocus.current?.focus({ preventScroll: true });\n };\n }, [element, selector]);\n}\n","import type { CSSProperties, ElementType, Ref } from 'react';\n\nimport type { ArrowRenderProps, Placement } from '~/types';\n\ninterface ArrowProps {\n arrowComponent?: ElementType;\n arrowRef: Ref;\n base: number;\n placement: Placement;\n position: { x?: number; y?: number } | undefined;\n size: number;\n styles: CSSProperties;\n}\n\nfunction getDimensions(placement: Placement, base: number, size: number) {\n const [side] = placement.split('-');\n\n switch (side) {\n case 'top':\n case 'bottom':\n return { width: base, height: size };\n case 'left':\n case 'right':\n return { width: size, height: base };\n default:\n return null;\n }\n}\n\nfunction getPoints(placement: Placement, base: number, size: number) {\n const [side] = placement.split('-');\n\n switch (side) {\n case 'top':\n return {\n points: `0,0 ${base / 2},${size} ${base},0`,\n ...getDimensions(placement, base, size),\n };\n case 'bottom':\n return {\n points: `${base},${size} ${base / 2},0 0,${size}`,\n ...getDimensions(placement, base, size),\n };\n case 'left':\n return {\n points: `0,0 ${size},${base / 2} 0,${base}`,\n ...getDimensions(placement, base, size),\n };\n case 'right':\n return {\n points: `${size},${base} ${size},0 0,${base / 2}`,\n ...getDimensions(placement, base, size),\n };\n default:\n return null;\n }\n}\n\nfunction getPositionStyle(\n placement: Placement,\n position: { x?: number; y?: number } | undefined,\n size: number,\n base: number,\n): CSSProperties {\n if (!position) {\n return {};\n }\n\n const [side] = placement.split('-');\n\n switch (side) {\n case 'top':\n return { bottom: -size, left: position.x ?? 0, ...getDimensions(placement, base, size) };\n case 'bottom':\n return { top: -size, left: position.x ?? 0, ...getDimensions(placement, base, size) };\n case 'left':\n return { right: -size, top: position.y ?? 0, ...getDimensions(placement, base, size) };\n case 'right':\n return { left: -size, top: position.y ?? 0, ...getDimensions(placement, base, size) };\n default:\n return {};\n }\n}\n\nexport default function Arrow({\n arrowComponent,\n arrowRef,\n base,\n placement,\n position,\n size,\n styles,\n}: ArrowProps) {\n const ArrowComponent = arrowComponent;\n\n let content = null;\n\n if (ArrowComponent) {\n const dimensions = getDimensions(placement, base, size);\n\n if (!dimensions) {\n return null;\n }\n\n content = (\n \n \n \n );\n } else {\n const svg = getPoints(placement, base, size);\n\n if (!svg) {\n return null;\n }\n\n content = (\n \n \n \n );\n }\n\n return (\n \n {content}\n \n );\n}\n","import { type MouseEventHandler, useEffect, useRef } from 'react';\nimport is from 'is-lite';\n\nimport { getReactNodeText, noop } from '~/modules/helpers';\n\nimport type { BeaconRenderProps, Locale, Props, Simplify, Styles } from '~/types';\n\ntype BeaconProps = Simplify<\n Pick &\n BeaconRenderProps & {\n locale: Locale;\n onInteract: MouseEventHandler;\n shouldFocus: boolean;\n styles: Styles;\n }\n>;\n\nexport default function JoyrideBeacon(props: BeaconProps) {\n const {\n beaconComponent,\n continuous,\n index,\n isLastStep,\n locale,\n nonce,\n onInteract,\n shouldFocus,\n size,\n step,\n styles,\n } = props;\n const beaconRef = useRef(null);\n\n const hasBeaconComponent = Boolean(beaconComponent);\n\n useEffect(() => {\n if (hasBeaconComponent) {\n return noop;\n }\n\n if (document.getElementById('joyride-beacon-animation')) {\n return noop;\n }\n\n const style = document.createElement('style');\n\n style.id = 'joyride-beacon-animation';\n\n if (nonce) {\n style.setAttribute('nonce', nonce);\n }\n\n const css = `\n @keyframes joyride-beacon-inner {\n 20% {\n opacity: 0.9;\n }\n\n 90% {\n opacity: 0.7;\n }\n }\n\n @keyframes joyride-beacon-outer {\n 0% {\n transform: scale(1);\n }\n\n 45% {\n opacity: 0.7;\n transform: scale(0.75);\n }\n\n 100% {\n opacity: 0.9;\n transform: scale(1);\n }\n }\n `;\n\n style.appendChild(document.createTextNode(css));\n\n document.head.appendChild(style);\n\n const focusTimer = setTimeout(() => {\n if (is.domElement(beaconRef.current) && shouldFocus) {\n beaconRef.current.focus();\n }\n }, 0);\n\n return () => {\n clearTimeout(focusTimer);\n\n const insertedStyle = document.getElementById('joyride-beacon-animation');\n\n if (insertedStyle?.parentNode) {\n insertedStyle.parentNode.removeChild(insertedStyle);\n }\n };\n }, [hasBeaconComponent, nonce, shouldFocus]);\n\n const title = getReactNodeText(locale.open);\n let content;\n\n if (beaconComponent) {\n const BeaconComponent = beaconComponent;\n\n content = (\n \n );\n } else {\n content = (\n \n \n \n \n );\n }\n\n return (\n \n {content}\n \n );\n}\n","import type { CSSProperties } from 'react';\n\ninterface Props {\n styles: CSSProperties;\n}\n\nexport default function JoyrideTooltipCloseButton({ styles, ...props }: Props) {\n const { color, height, width, ...style } = styles;\n\n return (\n \n );\n}\n","import type { ReactNode } from 'react';\n\nimport { getReactNodeText } from '~/modules/helpers';\n\nimport type { TooltipRenderProps } from '~/types';\n\nimport CloseButton from './CloseButton';\n\nexport default function JoyrideDefaultTooltip(props: TooltipRenderProps) {\n const { backProps, closeProps, index, isLastStep, primaryProps, skipProps, step, tooltipProps } =\n props;\n const { buttons, content, styles, title } = step;\n const buttonElements: Record = {};\n\n if (buttons.includes('primary')) {\n buttonElements.primary = (\n \n );\n }\n\n if (buttons.includes('skip') && !isLastStep) {\n buttonElements.skip = (\n \n );\n }\n\n if (buttons.includes('back') && index > 0) {\n buttonElements.back = (\n