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Ae,OAAO;qBACrB,oBAAC;QACC,kBAAkB,YAAY,QAAQ;QAEvC,0BAAY,oBAAC;QAAU,WAAW;SAAgB,MAClD,OAAO,aAAa,aAAa,aAAa;AAGrD;AAEA;;;;;CAKC,GACD,MAAM,gBAAgB;IACpB,KAAK;IACL,QAAQ;AACV;AAEA,SAAS,cAAc,MAAM;IAC3B,IAAI,cAAc,GAAG,KAAK,QAAQ;QAChC,OAAO,cAAc,MAAM;IAC7B;IAEA,MAAM,SAAS,CAAC;IAEhB,IAAI;QACF,OAAO,OAAO,CAAC,UAAU,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,KAAK,MAAM;YAChD,MAAM,QAAQ,IAAI,KAAK,CAAC;YACxB,IAAI,OAAO;YAEX,MAAM,OAAO,CAAC,CAAC,WAAW;gBACxB,IAAI,UAAU,MAAM,MAAM,GAAG,GAAG;oBAC9B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,IAAI,CAAC;oBACtC,OAAO,IAAI,CAAC,UAAU;gBACxB,OAAO;oBACL,IAAI,CAAC,UAAU,GAAG,OAAO;gBAC3B;YACF;QACF;QAEA,cAAc,GAAG,GAAG;QACpB,cAAc,MAAM,GAAG;IACzB,EAAE,OAAO,KAAK;IACZ,SAAS;IACX;IAEA,OAAO;AACT;AAEA;;;;;CAKC,GACD,OAAO,MAAM,WAAW;IACtB,MAAM,QAAQ;IACd,MAAM,EAAE,SAAS,EAAE,eAAe,EAAE,GAAG;IAEvC,OAAO;QACL,eAAe;QACf,QAAQ,cAAc,OAAO;QAC7B;QACA;IACF;AACF,EAAE","file":"index.mjs","sourcesContent":["'use client';\n\n/* eslint-disable @typescript-eslint/no-empty-function */\n/* eslint-disable no-underscore-dangle */\nimport React, {\n  useState,\n  useRef,\n  useEffect,\n  useCallback,\n  useMemo,\n} from 'react';\nimport classnames from 'classnames';\nimport { ChakraProvider } from '@chakra-ui/provider';\nimport { ColorModeScript, useColorMode } from '@chakra-ui/color-mode';\nimport { useTheme as useChakraTheme } from '@chakra-ui/system';\nimport { extendTheme } from '@chakra-ui/theme-utils';\n\nlet cachedReports = [];\nlet interval;\n\n/**\n * Get the clutch inspector at the current version\n */\nconst getInspector = () =>\n  typeof window !== 'undefined' ? window?.__CLUTCH_INSPECTOR__?.v1 : undefined;\n\n/**\n * Clears the interval that sends cached reports\n * to the inspector\n */\nconst clearCachedReportsInterval = () => {\n  clearInterval(interval);\n  interval = undefined;\n};\n\n/**\n * Sends reports that were cached before the inspector was ready\n */\nconst sendCachedReports = () => {\n  const inspector = getInspector();\n\n  // if the inspector is ready, clear the interval as we can report directly from now on\n  if (inspector && interval) {\n    clearCachedReportsInterval();\n  }\n\n  if (cachedReports.length === 0) {\n    return;\n  }\n\n  if (inspector) {\n    cachedReports.forEach(({ computedKey, report, clutchInternalId }) => {\n      inspector.report?.(computedKey, report, clutchInternalId);\n    });\n\n    cachedReports = [];\n  }\n};\n\n/**\n * Sends a report to the inspector\n */\nconst sendReport = (computedKey, report, clutchInternalId) => {\n  const inspector = getInspector();\n\n  if (!inspector) {\n    cachedReports.push({\n      computedKey,\n      report,\n      clutchInternalId,\n    });\n\n    if (!interval) {\n      interval = setInterval(sendCachedReports, 1000);\n    }\n  } else {\n    if (cachedReports.length) {\n      sendCachedReports();\n    }\n\n    inspector.report?.(computedKey, report, clutchInternalId);\n  }\n};\n\n/**\n * mClassnames - Merges class names\n *\n * @param {*} valueA\n * @param {<*>} ...oterhValues\n *\n * @returns {*} resulting value\n */\nexport const cx = classnames;\n\n/**\n * tryCatch - tries to run the passed fn\n *\n * @param {Function} fn\n *\n * @returns {*}\n */\nexport function tryCatch(fn, ...args) {\n  let result;\n\n  try {\n    if (typeof fn !== 'function') {\n      throw new Error(\n        'Code property on an instance is not exporting a function',\n      );\n    }\n\n    result = fn(...args);\n  } catch (err) {\n    // eslint-disable-next-line\n    console.error(err);\n  }\n\n  return result;\n}\n\n/**\n * deserializeDebugKey - deserializes a debug key string\n * composed of ${scopeId}#${id}#${customKey}\n *\n * @param {String} debugKey\n *\n * @returns {Array<String>} [scopeId, id, customKey]\n */\nconst deserializeDebugKey = (debugKey) =>\n  String(debugKey)\n    .match(/(.+?)#(.+?)#(.*)/)\n    ?.slice(1) || [];\n\n/**\n * calculateScope - calculates next scope id based on debugKey\n *\n * @param {String} debugKey\n *\n * @returns {String} new scopeId\n */\nconst calculateScope = (debugKey) => {\n  const [previousScope, rootInstanceId] = deserializeDebugKey(debugKey);\n\n  return previousScope && previousScope !== '0'\n    ? `${previousScope}.${rootInstanceId}`\n    : rootInstanceId || '0';\n};\n\nlet instanceCounter = 0;\n\n/**\n * useOwnerScopeIdRef - Returns a ref to the owner scope id\n * @param {String} dataD\n * @returns {Object} ownerScopeIdRef\n */\nconst useOwnerScopeIdRef = (dataD) => {\n  const ownerScopeIdRef = useRef(null);\n\n  if (!ownerScopeIdRef.current) {\n    ownerScopeIdRef.current = calculateScope(dataD) || String(instanceCounter);\n    instanceCounter += 1;\n  }\n\n  return ownerScopeIdRef;\n};\n\n/**\n * generateComputedKey - generates a computed key based on the owner scope id\n * and the instance id\n * @param {String} ownerScopeIdRef\n * @param {String} instanceId\n * @param {String} customKey\n * @returns {String} computedKey\n */\nconst generateComputedKey = (ownerScopeIdRef, instanceId, customKey = '') =>\n  [ownerScopeIdRef, instanceId, customKey].join('#');\n\n/**\n * getInspectorWhenReady - tries to get the inspector every 500ms\n * (waits 500ms and tries again)\n * @returns {Promise<*>} inspector\n */\nconst getInspectorWhenReady = async () => {\n  const inspector = getInspector();\n\n  if (inspector) {\n    return inspector;\n  }\n\n  // wait 500ms and try again\n  await new Promise((resolve) => setTimeout(resolve, 500));\n\n  return getInspectorWhenReady();\n};\n\n/**\n * useInspector - returns the inspector when available\n * @returns {Object} inspector\n */\nconst useInspector = () => {\n  const [inspector, setInspector] = useState(getInspector);\n\n  useEffect(() => {\n    let subscribed;\n\n    if (!inspector) {\n      subscribed = true;\n      getInspectorWhenReady().then((loadedInspector) => {\n        if (subscribed) {\n          setInspector(loadedInspector);\n        }\n      });\n    }\n\n    return () => {\n      subscribed = false;\n    };\n  }, []);\n\n  return inspector;\n};\n\n/**\n * useTemporaryVariants - returns the variants to be used by the component\n * Applies temporary variants set through the inspector on top of the\n * instance defined variants\n * @param {Object} variants\n * @param {String} instanceKey\n * @returns {Object} temporary variants\n */\nconst useTemporaryVariants = (variants, instanceKey) => {\n  const inspector = useInspector(instanceKey);\n  const [tempVariants, setTempVariants] = useState(() =>\n    inspector\n      ? inspector?.variantsInspector?.getTemporaryVariants?.(instanceKey)\n      : {},\n  );\n\n  // listener effect\n  useEffect(() => {\n    let unsubscribe;\n\n    if (inspector) {\n      unsubscribe = inspector?.variantsInspector?.generateSubscribeCallback(\n        instanceKey,\n        setTempVariants,\n      );\n      const currentVariants =\n        inspector?.variantsInspector?.getTemporaryVariants?.(instanceKey);\n\n      if (currentVariants) {\n        setTempVariants(currentVariants);\n      }\n    }\n\n    return unsubscribe;\n  }, [inspector, setTempVariants, instanceKey]);\n\n  return useMemo(\n    () => ({ ...variants, ...tempVariants }),\n    [variants, tempVariants],\n  );\n};\n\n/**\n * useReport - called at the head of a clutch composed component\n *\n * @param {String} instanceId\n * @param {String} propsArg - component props\n * @param {String} variants - component computed variants state\n * @param {*Object} ref - component ref (optional)\n *\n * @returns {[Object, Function, Object]} [report, getKey, props]\n */\nexport const useReport = (instanceId, propsArg, vars, variants, ref) => {\n  const props = { ...propsArg };\n  const dataD = props['data-d'];\n\n  if (ref) {\n    props.ref = ref;\n  }\n\n  delete props['data-d'];\n\n  const ownerScopeIdRef = useOwnerScopeIdRef(dataD);\n  const instanceKey = generateComputedKey(\n    ownerScopeIdRef.current,\n    instanceId,\n    '',\n  );\n\n  // own report (master instance)\n  const report = {\n    instanceId,\n    propertyName: 'COMPOSITION',\n    props,\n    vars,\n    variants,\n  };\n\n  sendReport(instanceKey, report);\n\n  // drop reports logic\n  useEffect(() => {\n    if (getInspector()?.cancelDropReports && ownerScopeIdRef.current) {\n      getInspector().cancelDropReports(ownerScopeIdRef.current);\n    }\n\n    return () => {\n      if (getInspector()?.dropReports && ownerScopeIdRef.current) {\n        getInspector().dropReports(ownerScopeIdRef.current);\n      }\n    };\n  }, [dataD]);\n\n  // get key handler for children instances\n  const getKey = useCallback(\n    (childReport, childId, customKey, clutchInternalId) => {\n      const key = generateComputedKey(\n        ownerScopeIdRef.current,\n        childId,\n        customKey,\n      );\n\n      sendReport(key, childReport, clutchInternalId);\n\n      return key;\n    },\n    [ownerScopeIdRef.current],\n  );\n\n  const temporaryVariants = useTemporaryVariants(variants, instanceKey);\n\n  return [report, getKey, props, temporaryVariants];\n};\n\n/**\n * getReport - generates a report object based on previous report and new data\n *\n * @param {String} instanceId\n * @param {String} propertyName\n * @param {Object} parentReport\n * @param {Object} newVariables\n *\n * @returns {[Object, Object]}\n */\nexport const getReport = (\n  instanceId,\n  propertyName,\n  parentReport,\n  newVariablesName,\n  newVars,\n) => {\n  let { vars } = parentReport || {};\n\n  if (newVars?.length) {\n    vars = { ...parentReport.vars, [newVariablesName]: newVars[0] };\n\n    // in case the render props pass multiple arguments\n    // we include a new namespace with the full vars list\n    if (newVars.length > 1) {\n      vars[`${newVariablesName}Args`] = newVars;\n    }\n  }\n\n  const report = {\n    instanceId,\n    propertyName,\n    vars,\n    parentReport,\n  };\n\n  return [report, vars];\n};\n\n/**\n * Color mode component that handles changes to the color mode\n *\n * @param {Object} theme\n * @param {React.Node} children\n */\nfunction ColorMode({ colorMode }) {\n  const { colorMode: currentColorMode, toggleColorMode } = useColorMode();\n\n  useMemo(() => {\n    if (currentColorMode !== colorMode) {\n      toggleColorMode();\n    }\n  }, [colorMode, currentColorMode]);\n\n  return null;\n}\n\n/**\n * Theme component provider\n *\n * @param {Object} theme\n * @param {React.Node} children\n */\nexport function Theme({ theme = {}, colorMode, children }) {\n  const config = {\n    ...theme?.config,\n    cssVarPrefix: '',\n  };\n\n  // force color mode\n  if (colorMode) {\n    config.initialColorMode = colorMode;\n    config.useSystemColorMode = false;\n  }\n\n  const finalTheme = extendTheme({ ...theme, config });\n\n  return (\n    <ChakraProvider theme={finalTheme}>\n      <ColorModeScript\n        initialColorMode={finalTheme?.config?.initialColorMode}\n      />\n      {colorMode ? <ColorMode colorMode={colorMode} /> : null}\n      {typeof children === 'function' ? children() : children}\n    </ChakraProvider>\n  );\n}\n\n/**\n * processCssMap - parses chakra theme values into a more digestable object\n *\n * @param {Object} theme\n * @param {React.Node} children\n */\nconst cachedProcess = {\n  map: undefined,\n  result: undefined,\n};\n\nfunction processCssMap(cssMap) {\n  if (cachedProcess.map === cssMap) {\n    return cachedProcess.result;\n  }\n\n  const result = {};\n\n  try {\n    Object.entries(cssMap || {}).forEach(([key, value]) => {\n      const split = key.split('.');\n      let curr = result;\n\n      split.forEach((splitPath, index) => {\n        if (index !== split.length - 1) {\n          curr[splitPath] = curr[splitPath] || {};\n          curr = curr[splitPath];\n        } else {\n          curr[splitPath] = value?.varRef;\n        }\n      });\n    });\n\n    cachedProcess.map = cssMap;\n    cachedProcess.result = result;\n  } catch (err) {\n    // ignore\n  }\n\n  return result;\n}\n\n/**\n * useTheme - returns the theme and helper functions to handle theming\n *\n * @param {Object} theme\n * @param {React.Node} children\n */\nexport const useTheme = () => {\n  const theme = useChakraTheme();\n  const { colorMode, toggleColorMode } = useColorMode();\n\n  return {\n    configuration: theme,\n    tokens: processCssMap(theme?.__cssMap),\n    colorMode,\n    toggleColorMode,\n  };\n};\n"]}