{ "version": 3, "sources": ["../../../node_modules/react/cjs/react.development.js", "../../../node_modules/react/index.js", "../../../node_modules/scheduler/cjs/scheduler.development.js", "../../../node_modules/scheduler/index.js", "../../../node_modules/react-dom/cjs/react-dom.development.js", "../../../node_modules/react-dom/index.js", "../../../node_modules/inline-style-parser/index.js", "../../../node_modules/style-to-object/src/index.ts", "../../../node_modules/style-to-js/src/utilities.ts", "../../../node_modules/style-to-js/src/index.ts", "../../../node_modules/react/cjs/react-jsx-runtime.development.js", "../../../node_modules/react/jsx-runtime.js", "../../../node_modules/extend/index.js", "../../../node_modules/react-is/cjs/react-is.development.js", "../../../node_modules/react-is/index.js", "../../../node_modules/object-assign/index.js", "../../../node_modules/prop-types/lib/ReactPropTypesSecret.js", "../../../node_modules/prop-types/lib/has.js", "../../../node_modules/prop-types/checkPropTypes.js", "../../../node_modules/prop-types/factoryWithTypeCheckers.js", "../../../node_modules/prop-types/index.js", "../../../node_modules/lodash/isArray.js", "../../../node_modules/lodash/_freeGlobal.js", "../../../node_modules/lodash/_root.js", "../../../node_modules/lodash/_Symbol.js", "../../../node_modules/lodash/_getRawTag.js", "../../../node_modules/lodash/_objectToString.js", "../../../node_modules/lodash/_baseGetTag.js", "../../../node_modules/lodash/isObjectLike.js", "../../../node_modules/lodash/isSymbol.js", "../../../node_modules/lodash/_isKey.js", "../../../node_modules/lodash/isObject.js", "../../../node_modules/lodash/isFunction.js", "../../../node_modules/lodash/_coreJsData.js", "../../../node_modules/lodash/_isMasked.js", "../../../node_modules/lodash/_toSource.js", "../../../node_modules/lodash/_baseIsNative.js", "../../../node_modules/lodash/_getValue.js", "../../../node_modules/lodash/_getNative.js", "../../../node_modules/lodash/_nativeCreate.js", "../../../node_modules/lodash/_hashClear.js", "../../../node_modules/lodash/_hashDelete.js", "../../../node_modules/lodash/_hashGet.js", "../../../node_modules/lodash/_hashHas.js", "../../../node_modules/lodash/_hashSet.js", "../../../node_modules/lodash/_Hash.js", "../../../node_modules/lodash/_listCacheClear.js", "../../../node_modules/lodash/eq.js", "../../../node_modules/lodash/_assocIndexOf.js", "../../../node_modules/lodash/_listCacheDelete.js", "../../../node_modules/lodash/_listCacheGet.js", "../../../node_modules/lodash/_listCacheHas.js", "../../../node_modules/lodash/_listCacheSet.js", "../../../node_modules/lodash/_ListCache.js", "../../../node_modules/lodash/_Map.js", "../../../node_modules/lodash/_mapCacheClear.js", "../../../node_modules/lodash/_isKeyable.js", "../../../node_modules/lodash/_getMapData.js", "../../../node_modules/lodash/_mapCacheDelete.js", "../../../node_modules/lodash/_mapCacheGet.js", "../../../node_modules/lodash/_mapCacheHas.js", "../../../node_modules/lodash/_mapCacheSet.js", "../../../node_modules/lodash/_MapCache.js", "../../../node_modules/lodash/memoize.js", "../../../node_modules/lodash/_memoizeCapped.js", "../../../node_modules/lodash/_stringToPath.js", "../../../node_modules/lodash/_arrayMap.js", "../../../node_modules/lodash/_baseToString.js", "../../../node_modules/lodash/toString.js", "../../../node_modules/lodash/_castPath.js", "../../../node_modules/lodash/_toKey.js", "../../../node_modules/lodash/_baseGet.js", "../../../node_modules/lodash/get.js", "../../../node_modules/lodash/isNil.js", "../../../node_modules/lodash/isString.js", "../../../node_modules/recharts/node_modules/react-is/cjs/react-is.development.js", "../../../node_modules/recharts/node_modules/react-is/index.js", "../../../node_modules/lodash/isNumber.js", "../../../node_modules/lodash/isNaN.js", "../../../node_modules/lodash/_baseSlice.js", "../../../node_modules/lodash/_castSlice.js", "../../../node_modules/lodash/_hasUnicode.js", "../../../node_modules/lodash/_asciiToArray.js", "../../../node_modules/lodash/_unicodeToArray.js", "../../../node_modules/lodash/_stringToArray.js", "../../../node_modules/lodash/_createCaseFirst.js", "../../../node_modules/lodash/upperFirst.js", "../../../node_modules/lodash/_stackClear.js", "../../../node_modules/lodash/_stackDelete.js", "../../../node_modules/lodash/_stackGet.js", "../../../node_modules/lodash/_stackHas.js", "../../../node_modules/lodash/_stackSet.js", "../../../node_modules/lodash/_Stack.js", "../../../node_modules/lodash/_setCacheAdd.js", "../../../node_modules/lodash/_setCacheHas.js", "../../../node_modules/lodash/_SetCache.js", "../../../node_modules/lodash/_arraySome.js", "../../../node_modules/lodash/_cacheHas.js", "../../../node_modules/lodash/_equalArrays.js", "../../../node_modules/lodash/_Uint8Array.js", "../../../node_modules/lodash/_mapToArray.js", "../../../node_modules/lodash/_setToArray.js", "../../../node_modules/lodash/_equalByTag.js", "../../../node_modules/lodash/_arrayPush.js", "../../../node_modules/lodash/_baseGetAllKeys.js", "../../../node_modules/lodash/_arrayFilter.js", "../../../node_modules/lodash/stubArray.js", "../../../node_modules/lodash/_getSymbols.js", "../../../node_modules/lodash/_baseTimes.js", "../../../node_modules/lodash/_baseIsArguments.js", "../../../node_modules/lodash/isArguments.js", "../../../node_modules/lodash/stubFalse.js", "../../../node_modules/lodash/isBuffer.js", "../../../node_modules/lodash/_isIndex.js", "../../../node_modules/lodash/isLength.js", "../../../node_modules/lodash/_baseIsTypedArray.js", "../../../node_modules/lodash/_baseUnary.js", "../../../node_modules/lodash/_nodeUtil.js", "../../../node_modules/lodash/isTypedArray.js", "../../../node_modules/lodash/_arrayLikeKeys.js", "../../../node_modules/lodash/_isPrototype.js", "../../../node_modules/lodash/_overArg.js", "../../../node_modules/lodash/_nativeKeys.js", "../../../node_modules/lodash/_baseKeys.js", "../../../node_modules/lodash/isArrayLike.js", "../../../node_modules/lodash/keys.js", "../../../node_modules/lodash/_getAllKeys.js", "../../../node_modules/lodash/_equalObjects.js", "../../../node_modules/lodash/_DataView.js", "../../../node_modules/lodash/_Promise.js", "../../../node_modules/lodash/_Set.js", "../../../node_modules/lodash/_WeakMap.js", "../../../node_modules/lodash/_getTag.js", "../../../node_modules/lodash/_baseIsEqualDeep.js", "../../../node_modules/lodash/_baseIsEqual.js", "../../../node_modules/lodash/_baseIsMatch.js", "../../../node_modules/lodash/_isStrictComparable.js", "../../../node_modules/lodash/_getMatchData.js", "../../../node_modules/lodash/_matchesStrictComparable.js", "../../../node_modules/lodash/_baseMatches.js", "../../../node_modules/lodash/_baseHasIn.js", "../../../node_modules/lodash/_hasPath.js", "../../../node_modules/lodash/hasIn.js", "../../../node_modules/lodash/_baseMatchesProperty.js", "../../../node_modules/lodash/identity.js", "../../../node_modules/lodash/_baseProperty.js", "../../../node_modules/lodash/_basePropertyDeep.js", "../../../node_modules/lodash/property.js", "../../../node_modules/lodash/_baseIteratee.js", "../../../node_modules/lodash/_baseFindIndex.js", "../../../node_modules/lodash/_baseIsNaN.js", "../../../node_modules/lodash/_strictIndexOf.js", "../../../node_modules/lodash/_baseIndexOf.js", "../../../node_modules/lodash/_arrayIncludes.js", "../../../node_modules/lodash/_arrayIncludesWith.js", "../../../node_modules/lodash/noop.js", "../../../node_modules/lodash/_createSet.js", "../../../node_modules/lodash/_baseUniq.js", "../../../node_modules/lodash/uniqBy.js", "../../../node_modules/lodash/_isFlattenable.js", "../../../node_modules/lodash/_baseFlatten.js", "../../../node_modules/lodash/_createBaseFor.js", "../../../node_modules/lodash/_baseFor.js", "../../../node_modules/lodash/_baseForOwn.js", "../../../node_modules/lodash/_createBaseEach.js", "../../../node_modules/lodash/_baseEach.js", "../../../node_modules/lodash/_baseMap.js", "../../../node_modules/lodash/_baseSortBy.js", "../../../node_modules/lodash/_compareAscending.js", "../../../node_modules/lodash/_compareMultiple.js", "../../../node_modules/lodash/_baseOrderBy.js", "../../../node_modules/lodash/_apply.js", "../../../node_modules/lodash/_overRest.js", "../../../node_modules/lodash/constant.js", "../../../node_modules/lodash/_defineProperty.js", "../../../node_modules/lodash/_baseSetToString.js", "../../../node_modules/lodash/_shortOut.js", "../../../node_modules/lodash/_setToString.js", "../../../node_modules/lodash/_baseRest.js", "../../../node_modules/lodash/_isIterateeCall.js", "../../../node_modules/lodash/sortBy.js", "../../../node_modules/lodash/now.js", "../../../node_modules/lodash/_trimmedEndIndex.js", "../../../node_modules/lodash/_baseTrim.js", "../../../node_modules/lodash/toNumber.js", "../../../node_modules/lodash/debounce.js", "../../../node_modules/lodash/throttle.js", "../../../node_modules/lodash/_baseExtremum.js", "../../../node_modules/lodash/_baseGt.js", "../../../node_modules/lodash/max.js", "../../../node_modules/lodash/_baseLt.js", "../../../node_modules/lodash/min.js", "../../../node_modules/lodash/map.js", "../../../node_modules/lodash/flatMap.js", "../../../node_modules/lodash/isEqual.js", "../../../node_modules/decimal.js-light/decimal.js", "../../../node_modules/lodash/last.js", "../../../node_modules/lodash/maxBy.js", "../../../node_modules/lodash/minBy.js", "../../../node_modules/lodash/_getPrototype.js", "../../../node_modules/lodash/isPlainObject.js", "../../../node_modules/lodash/isBoolean.js", "../../../node_modules/lodash/_baseRange.js", "../../../node_modules/lodash/toFinite.js", "../../../node_modules/lodash/_createRange.js", "../../../node_modules/lodash/range.js", "../../../node_modules/lodash/_baseSome.js", "../../../node_modules/lodash/some.js", "../../../node_modules/lodash/_baseAssignValue.js", "../../../node_modules/lodash/mapValues.js", "../../../node_modules/lodash/_arrayEvery.js", "../../../node_modules/lodash/_baseEvery.js", "../../../node_modules/lodash/every.js", "../../../node_modules/lodash/_createFind.js", "../../../node_modules/lodash/toInteger.js", "../../../node_modules/lodash/findIndex.js", "../../../node_modules/lodash/find.js", "../../../node_modules/eventemitter3/index.js", "../../javascript/application.js", "../../../node_modules/@remix-run/router/history.ts", "../../../node_modules/@remix-run/router/utils.ts", "../../../node_modules/@remix-run/router/router.ts", "../../../node_modules/react-router/lib/context.ts", "../../../node_modules/react-router/lib/hooks.tsx", "../../../node_modules/react-router/lib/deprecations.ts", "../../../node_modules/react-router/lib/components.tsx", "../../../node_modules/react-router/index.ts", "../../../node_modules/react-router-dom/dom.ts", "../../../node_modules/react-router-dom/index.tsx", "../../javascript/components/GetStarted.jsx", "../../../node_modules/mixpanel-browser/dist/mixpanel.module.js", "../../../node_modules/axios/lib/helpers/bind.js", "../../../node_modules/axios/lib/utils.js", "../../../node_modules/axios/lib/core/AxiosError.js", "../../../node_modules/axios/lib/helpers/null.js", "../../../node_modules/axios/lib/helpers/toFormData.js", "../../../node_modules/axios/lib/helpers/AxiosURLSearchParams.js", "../../../node_modules/axios/lib/helpers/buildURL.js", "../../../node_modules/axios/lib/core/InterceptorManager.js", "../../../node_modules/axios/lib/defaults/transitional.js", "../../../node_modules/axios/lib/platform/browser/classes/URLSearchParams.js", "../../../node_modules/axios/lib/platform/browser/classes/FormData.js", "../../../node_modules/axios/lib/platform/browser/classes/Blob.js", "../../../node_modules/axios/lib/platform/browser/index.js", "../../../node_modules/axios/lib/platform/common/utils.js", "../../../node_modules/axios/lib/platform/index.js", "../../../node_modules/axios/lib/helpers/toURLEncodedForm.js", "../../../node_modules/axios/lib/helpers/formDataToJSON.js", "../../../node_modules/axios/lib/defaults/index.js", "../../../node_modules/axios/lib/helpers/parseHeaders.js", "../../../node_modules/axios/lib/core/AxiosHeaders.js", "../../../node_modules/axios/lib/core/transformData.js", "../../../node_modules/axios/lib/cancel/isCancel.js", "../../../node_modules/axios/lib/cancel/CanceledError.js", "../../../node_modules/axios/lib/core/settle.js", "../../../node_modules/axios/lib/helpers/parseProtocol.js", "../../../node_modules/axios/lib/helpers/speedometer.js", "../../../node_modules/axios/lib/helpers/throttle.js", "../../../node_modules/axios/lib/helpers/progressEventReducer.js", "../../../node_modules/axios/lib/helpers/isURLSameOrigin.js", "../../../node_modules/axios/lib/helpers/cookies.js", "../../../node_modules/axios/lib/helpers/isAbsoluteURL.js", "../../../node_modules/axios/lib/helpers/combineURLs.js", "../../../node_modules/axios/lib/core/buildFullPath.js", "../../../node_modules/axios/lib/core/mergeConfig.js", "../../../node_modules/axios/lib/helpers/resolveConfig.js", "../../../node_modules/axios/lib/adapters/xhr.js", "../../../node_modules/axios/lib/helpers/composeSignals.js", "../../../node_modules/axios/lib/helpers/trackStream.js", "../../../node_modules/axios/lib/adapters/fetch.js", "../../../node_modules/axios/lib/adapters/adapters.js", "../../../node_modules/axios/lib/core/dispatchRequest.js", "../../../node_modules/axios/lib/env/data.js", "../../../node_modules/axios/lib/helpers/validator.js", "../../../node_modules/axios/lib/core/Axios.js", "../../../node_modules/axios/lib/cancel/CancelToken.js", "../../../node_modules/axios/lib/helpers/spread.js", "../../../node_modules/axios/lib/helpers/isAxiosError.js", "../../../node_modules/axios/lib/helpers/HttpStatusCode.js", "../../../node_modules/axios/lib/axios.js", "../../../node_modules/axios/index.js", "../../javascript/components/AxiosConfig.jsx", "../../javascript/components/Analytics/mixpanel.js", "../../javascript/context/AuthContext.js", "../../javascript/components/App.js", "../../javascript/components/Help/HelpCenterPage.jsx", "../../../node_modules/devlop/lib/default.js", "../../../node_modules/comma-separated-tokens/index.js", "../../../node_modules/estree-util-is-identifier-name/lib/index.js", "../../../node_modules/hast-util-whitespace/lib/index.js", "../../../node_modules/property-information/lib/util/schema.js", "../../../node_modules/property-information/lib/util/merge.js", "../../../node_modules/property-information/lib/normalize.js", "../../../node_modules/property-information/lib/util/info.js", "../../../node_modules/property-information/lib/util/types.js", "../../../node_modules/property-information/lib/util/defined-info.js", "../../../node_modules/property-information/lib/util/create.js", "../../../node_modules/property-information/lib/aria.js", "../../../node_modules/property-information/lib/util/case-sensitive-transform.js", "../../../node_modules/property-information/lib/util/case-insensitive-transform.js", "../../../node_modules/property-information/lib/html.js", "../../../node_modules/property-information/lib/svg.js", "../../../node_modules/property-information/lib/xlink.js", "../../../node_modules/property-information/lib/xmlns.js", "../../../node_modules/property-information/lib/xml.js", "../../../node_modules/property-information/lib/hast-to-react.js", "../../../node_modules/property-information/lib/find.js", "../../../node_modules/property-information/index.js", "../../../node_modules/space-separated-tokens/index.js", "../../../node_modules/hast-util-to-jsx-runtime/lib/index.js", "../../../node_modules/unist-util-position/lib/index.js", "../../../node_modules/unist-util-stringify-position/lib/index.js", "../../../node_modules/vfile-message/lib/index.js", "../../../node_modules/html-url-attributes/lib/index.js", "../../../node_modules/react-markdown/lib/index.js", "../../../node_modules/mdast-util-to-string/lib/index.js", "../../../node_modules/decode-named-character-reference/index.dom.js", "../../../node_modules/micromark-util-chunked/index.js", "../../../node_modules/micromark-util-combine-extensions/index.js", "../../../node_modules/micromark-util-decode-numeric-character-reference/index.js", "../../../node_modules/micromark-util-normalize-identifier/index.js", "../../../node_modules/micromark-util-character/index.js", "../../../node_modules/micromark-util-sanitize-uri/index.js", "../../../node_modules/micromark-factory-space/index.js", "../../../node_modules/micromark/lib/initialize/content.js", "../../../node_modules/micromark/lib/initialize/document.js", "../../../node_modules/micromark-util-classify-character/index.js", "../../../node_modules/micromark-util-resolve-all/index.js", "../../../node_modules/micromark-core-commonmark/lib/attention.js", "../../../node_modules/micromark-core-commonmark/lib/autolink.js", "../../../node_modules/micromark-core-commonmark/lib/blank-line.js", "../../../node_modules/micromark-core-commonmark/lib/block-quote.js", "../../../node_modules/micromark-core-commonmark/lib/character-escape.js", "../../../node_modules/micromark-core-commonmark/lib/character-reference.js", "../../../node_modules/micromark-core-commonmark/lib/code-fenced.js", "../../../node_modules/micromark-core-commonmark/lib/code-indented.js", "../../../node_modules/micromark-core-commonmark/lib/code-text.js", "../../../node_modules/micromark-util-subtokenize/lib/splice-buffer.js", "../../../node_modules/micromark-util-subtokenize/index.js", "../../../node_modules/micromark-core-commonmark/lib/content.js", "../../../node_modules/micromark-factory-destination/index.js", "../../../node_modules/micromark-factory-label/index.js", "../../../node_modules/micromark-factory-title/index.js", "../../../node_modules/micromark-factory-whitespace/index.js", "../../../node_modules/micromark-core-commonmark/lib/definition.js", "../../../node_modules/micromark-core-commonmark/lib/hard-break-escape.js", "../../../node_modules/micromark-core-commonmark/lib/heading-atx.js", "../../../node_modules/micromark-util-html-tag-name/index.js", "../../../node_modules/micromark-core-commonmark/lib/html-flow.js", "../../../node_modules/micromark-core-commonmark/lib/html-text.js", "../../../node_modules/micromark-core-commonmark/lib/label-end.js", "../../../node_modules/micromark-core-commonmark/lib/label-start-image.js", "../../../node_modules/micromark-core-commonmark/lib/label-start-link.js", "../../../node_modules/micromark-core-commonmark/lib/line-ending.js", "../../../node_modules/micromark-core-commonmark/lib/thematic-break.js", "../../../node_modules/micromark-core-commonmark/lib/list.js", "../../../node_modules/micromark-core-commonmark/lib/setext-underline.js", "../../../node_modules/micromark/lib/initialize/flow.js", "../../../node_modules/micromark/lib/initialize/text.js", "../../../node_modules/micromark/lib/constructs.js", "../../../node_modules/micromark/lib/create-tokenizer.js", "../../../node_modules/micromark/lib/parse.js", "../../../node_modules/micromark/lib/postprocess.js", "../../../node_modules/micromark/lib/preprocess.js", "../../../node_modules/micromark-util-decode-string/index.js", "../../../node_modules/mdast-util-from-markdown/lib/index.js", "../../../node_modules/remark-parse/lib/index.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/blockquote.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/break.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/code.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/delete.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/emphasis.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/footnote-reference.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/heading.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/html.js", "../../../node_modules/mdast-util-to-hast/lib/revert.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/image-reference.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/image.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/inline-code.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/link-reference.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/link.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/list-item.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/list.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/paragraph.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/root.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/strong.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/table.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/table-row.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/table-cell.js", "../../../node_modules/trim-lines/index.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/text.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/thematic-break.js", "../../../node_modules/mdast-util-to-hast/lib/handlers/index.js", "../../../node_modules/@ungap/structured-clone/esm/types.js", "../../../node_modules/@ungap/structured-clone/esm/deserialize.js", "../../../node_modules/@ungap/structured-clone/esm/serialize.js", "../../../node_modules/@ungap/structured-clone/esm/index.js", "../../../node_modules/mdast-util-to-hast/lib/footer.js", "../../../node_modules/unist-util-is/lib/index.js", "../../../node_modules/unist-util-visit-parents/lib/color.js", "../../../node_modules/unist-util-visit-parents/lib/index.js", "../../../node_modules/unist-util-visit/lib/index.js", "../../../node_modules/mdast-util-to-hast/lib/state.js", "../../../node_modules/mdast-util-to-hast/lib/index.js", "../../../node_modules/remark-rehype/lib/index.js", "../../../node_modules/bail/index.js", "../../../node_modules/unified/lib/index.js", "../../../node_modules/is-plain-obj/index.js", "../../../node_modules/trough/lib/index.js", "../../../node_modules/vfile/lib/minpath.browser.js", "../../../node_modules/vfile/lib/minproc.browser.js", "../../../node_modules/vfile/lib/minurl.shared.js", "../../../node_modules/vfile/lib/minurl.browser.js", "../../../node_modules/vfile/lib/index.js", "../../../node_modules/unified/lib/callable-instance.js", "../../../node_modules/shared/src/utils.ts", "../../../node_modules/lucide-react/src/defaultAttributes.ts", "../../../node_modules/lucide-react/src/Icon.ts", "../../../node_modules/lucide-react/src/createLucideIcon.ts", "../../../node_modules/lucide-react/src/icons/activity.ts", "../../../node_modules/lucide-react/src/icons/archive.ts", "../../../node_modules/lucide-react/src/icons/arrow-down-right.ts", "../../../node_modules/lucide-react/src/icons/arrow-down.ts", "../../../node_modules/lucide-react/src/icons/arrow-left.ts", "../../../node_modules/lucide-react/src/icons/arrow-right.ts", "../../../node_modules/lucide-react/src/icons/arrow-up-right.ts", "../../../node_modules/lucide-react/src/icons/arrow-up.ts", "../../../node_modules/lucide-react/src/icons/award.ts", "../../../node_modules/lucide-react/src/icons/ban.ts", "../../../node_modules/lucide-react/src/icons/book-open.ts", "../../../node_modules/lucide-react/src/icons/briefcase.ts", "../../../node_modules/lucide-react/src/icons/building-2.ts", "../../../node_modules/lucide-react/src/icons/building.ts", "../../../node_modules/lucide-react/src/icons/calendar-clock.ts", "../../../node_modules/lucide-react/src/icons/calendar-days.ts", "../../../node_modules/lucide-react/src/icons/calendar.ts", "../../../node_modules/lucide-react/src/icons/chart-column.ts", "../../../node_modules/lucide-react/src/icons/chart-line.ts", "../../../node_modules/lucide-react/src/icons/chart-no-axes-column-increasing.ts", "../../../node_modules/lucide-react/src/icons/chart-no-axes-column.ts", "../../../node_modules/lucide-react/src/icons/chart-pie.ts", "../../../node_modules/lucide-react/src/icons/check.ts", "../../../node_modules/lucide-react/src/icons/chevron-down.ts", "../../../node_modules/lucide-react/src/icons/chevron-left.ts", "../../../node_modules/lucide-react/src/icons/chevron-right.ts", "../../../node_modules/lucide-react/src/icons/chevron-up.ts", "../../../node_modules/lucide-react/src/icons/chevrons-left.ts", "../../../node_modules/lucide-react/src/icons/chevrons-right.ts", "../../../node_modules/lucide-react/src/icons/circle-alert.ts", "../../../node_modules/lucide-react/src/icons/circle-arrow-right.ts", "../../../node_modules/lucide-react/src/icons/circle-check.ts", "../../../node_modules/lucide-react/src/icons/circle-check-big.ts", "../../../node_modules/lucide-react/src/icons/circle-help.ts", "../../../node_modules/lucide-react/src/icons/circle-plus.ts", "../../../node_modules/lucide-react/src/icons/circle-user.ts", "../../../node_modules/lucide-react/src/icons/circle-x.ts", "../../../node_modules/lucide-react/src/icons/circle.ts", "../../../node_modules/lucide-react/src/icons/clipboard-list.ts", "../../../node_modules/lucide-react/src/icons/clock.ts", "../../../node_modules/lucide-react/src/icons/cloud-upload.ts", "../../../node_modules/lucide-react/src/icons/code.ts", "../../../node_modules/lucide-react/src/icons/compass.ts", "../../../node_modules/lucide-react/src/icons/copy.ts", "../../../node_modules/lucide-react/src/icons/credit-card.ts", "../../../node_modules/lucide-react/src/icons/crown.ts", "../../../node_modules/lucide-react/src/icons/database.ts", "../../../node_modules/lucide-react/src/icons/dollar-sign.ts", "../../../node_modules/lucide-react/src/icons/download.ts", "../../../node_modules/lucide-react/src/icons/ellipsis.ts", "../../../node_modules/lucide-react/src/icons/external-link.ts", "../../../node_modules/lucide-react/src/icons/eye-off.ts", "../../../node_modules/lucide-react/src/icons/eye.ts", "../../../node_modules/lucide-react/src/icons/file-chart-column-increasing.ts", "../../../node_modules/lucide-react/src/icons/file-check.ts", "../../../node_modules/lucide-react/src/icons/file-search.ts", "../../../node_modules/lucide-react/src/icons/file-spreadsheet.ts", "../../../node_modules/lucide-react/src/icons/file-text.ts", "../../../node_modules/lucide-react/src/icons/folder.ts", "../../../node_modules/lucide-react/src/icons/funnel.ts", "../../../node_modules/lucide-react/src/icons/gauge.ts", "../../../node_modules/lucide-react/src/icons/git-branch.ts", "../../../node_modules/lucide-react/src/icons/globe.ts", "../../../node_modules/lucide-react/src/icons/hard-drive.ts", "../../../node_modules/lucide-react/src/icons/hash.ts", "../../../node_modules/lucide-react/src/icons/heart.ts", "../../../node_modules/lucide-react/src/icons/image.ts", "../../../node_modules/lucide-react/src/icons/info.ts", "../../../node_modules/lucide-react/src/icons/key-round.ts", "../../../node_modules/lucide-react/src/icons/key.ts", "../../../node_modules/lucide-react/src/icons/layers.ts", "../../../node_modules/lucide-react/src/icons/layout-dashboard.ts", "../../../node_modules/lucide-react/src/icons/layout-template.ts", "../../../node_modules/lucide-react/src/icons/lightbulb.ts", "../../../node_modules/lucide-react/src/icons/link-2.ts", "../../../node_modules/lucide-react/src/icons/link.ts", "../../../node_modules/lucide-react/src/icons/list-checks.ts", "../../../node_modules/lucide-react/src/icons/list-plus.ts", "../../../node_modules/lucide-react/src/icons/list.ts", "../../../node_modules/lucide-react/src/icons/loader-circle.ts", "../../../node_modules/lucide-react/src/icons/loader.ts", "../../../node_modules/lucide-react/src/icons/lock.ts", "../../../node_modules/lucide-react/src/icons/log-in.ts", "../../../node_modules/lucide-react/src/icons/log-out.ts", "../../../node_modules/lucide-react/src/icons/mail.ts", "../../../node_modules/lucide-react/src/icons/map-pin.ts", "../../../node_modules/lucide-react/src/icons/maximize-2.ts", "../../../node_modules/lucide-react/src/icons/menu.ts", "../../../node_modules/lucide-react/src/icons/message-circle.ts", "../../../node_modules/lucide-react/src/icons/message-square.ts", "../../../node_modules/lucide-react/src/icons/minimize-2.ts", "../../../node_modules/lucide-react/src/icons/minus.ts", "../../../node_modules/lucide-react/src/icons/monitor.ts", "../../../node_modules/lucide-react/src/icons/network.ts", "../../../node_modules/lucide-react/src/icons/newspaper.ts", "../../../node_modules/lucide-react/src/icons/palette.ts", "../../../node_modules/lucide-react/src/icons/panel-left-close.ts", "../../../node_modules/lucide-react/src/icons/panel-left.ts", "../../../node_modules/lucide-react/src/icons/panels-top-left.ts", "../../../node_modules/lucide-react/src/icons/pen-line.ts", "../../../node_modules/lucide-react/src/icons/pen-tool.ts", "../../../node_modules/lucide-react/src/icons/pen.ts", "../../../node_modules/lucide-react/src/icons/pencil.ts", "../../../node_modules/lucide-react/src/icons/play.ts", "../../../node_modules/lucide-react/src/icons/plus.ts", "../../../node_modules/lucide-react/src/icons/plug.ts", "../../../node_modules/lucide-react/src/icons/presentation.ts", "../../../node_modules/lucide-react/src/icons/printer.ts", "../../../node_modules/lucide-react/src/icons/quote.ts", "../../../node_modules/lucide-react/src/icons/refresh-cw.ts", "../../../node_modules/lucide-react/src/icons/rocket.ts", "../../../node_modules/lucide-react/src/icons/rotate-ccw.ts", "../../../node_modules/lucide-react/src/icons/save.ts", "../../../node_modules/lucide-react/src/icons/search.ts", "../../../node_modules/lucide-react/src/icons/send.ts", "../../../node_modules/lucide-react/src/icons/server.ts", "../../../node_modules/lucide-react/src/icons/settings.ts", "../../../node_modules/lucide-react/src/icons/shield-check.ts", "../../../node_modules/lucide-react/src/icons/shield.ts", "../../../node_modules/lucide-react/src/icons/shopping-cart.ts", "../../../node_modules/lucide-react/src/icons/sparkles.ts", "../../../node_modules/lucide-react/src/icons/square-pen.ts", "../../../node_modules/lucide-react/src/icons/star.ts", "../../../node_modules/lucide-react/src/icons/tag.ts", "../../../node_modules/lucide-react/src/icons/tags.ts", "../../../node_modules/lucide-react/src/icons/target.ts", "../../../node_modules/lucide-react/src/icons/thumbs-down.ts", "../../../node_modules/lucide-react/src/icons/thumbs-up.ts", "../../../node_modules/lucide-react/src/icons/toggle-left.ts", "../../../node_modules/lucide-react/src/icons/toggle-right.ts", "../../../node_modules/lucide-react/src/icons/trash-2.ts", "../../../node_modules/lucide-react/src/icons/trash.ts", "../../../node_modules/lucide-react/src/icons/trending-down.ts", "../../../node_modules/lucide-react/src/icons/trending-up.ts", "../../../node_modules/lucide-react/src/icons/triangle-alert.ts", "../../../node_modules/lucide-react/src/icons/trophy.ts", "../../../node_modules/lucide-react/src/icons/undo-2.ts", "../../../node_modules/lucide-react/src/icons/upload.ts", "../../../node_modules/lucide-react/src/icons/user-check.ts", "../../../node_modules/lucide-react/src/icons/user-minus.ts", "../../../node_modules/lucide-react/src/icons/user-plus.ts", "../../../node_modules/lucide-react/src/icons/user.ts", "../../../node_modules/lucide-react/src/icons/users.ts", "../../../node_modules/lucide-react/src/icons/wrench.ts", "../../../node_modules/lucide-react/src/icons/x.ts", "../../../node_modules/lucide-react/src/icons/zap.ts", "../../javascript/components/Manage/InstagramSuccess.jsx", "../../javascript/components/Manage/InviteAccountCreation.js", "../../javascript/components/WaitlistSignup.js", "../../javascript/context/ProjectDashboardContext.js", "../../javascript/components/SignIn.jsx", "../../javascript/components/Manage/Setup.jsx", "../../javascript/components/Manage/Playground.jsx", "../../../node_modules/@rails/actioncable/app/assets/javascripts/actioncable.esm.js", "../../javascript/components/Manage/Integrations.jsx", "../../javascript/components/Home/HomePage.jsx", "../../javascript/components/Home/NavBar.jsx", "../../javascript/components/Home/Hero.jsx", "../../javascript/components/Home/Stats.jsx", "../../javascript/components/Home/HowItWorks.jsx", "../../javascript/components/Home/Features.jsx", "../../javascript/components/Home/Testimonials.jsx", "../../javascript/components/Home/Pricing.jsx", "../../javascript/components/Home/FAQ.jsx", "../../javascript/components/Home/CTA.jsx", "../../javascript/components/Home/Footer.jsx", "../../javascript/components/Analytics/PageViewTracker.js", "../../javascript/components/shared/AdminRoute.jsx", "../../javascript/components/Content/ConsentForm.jsx", "../../javascript/components/Demos/VegasJackDemo.js", "../../javascript/components/Demos/SakeDemoPage.jsx", "../../javascript/components/Demos/IframeDemo.jsx", "../../javascript/components/Manage/ManagedAccountCreation.jsx", "../../javascript/components/Manage/Account.jsx", "../../javascript/components/Geo/Onboarding.js", "../../javascript/components/Geo/Dashboard.js", "../../javascript/components/Geo/Overview.js", "../../../node_modules/recharts/es6/container/Surface.js", "../../../node_modules/clsx/dist/clsx.mjs", "../../../node_modules/recharts/es6/util/ReactUtils.js", "../../../node_modules/recharts/es6/util/DataUtils.js", "../../../node_modules/recharts/es6/util/ShallowEqual.js", "../../../node_modules/recharts/es6/util/types.js", "../../../node_modules/recharts/es6/container/Layer.js", "../../../node_modules/recharts/es6/component/Legend.js", "../../../node_modules/recharts/es6/component/DefaultLegendContent.js", "../../../node_modules/recharts/es6/util/LogUtils.js", "../../../node_modules/recharts/es6/shape/Symbols.js", "../../../node_modules/d3-shape/src/constant.js", "../../../node_modules/d3-shape/src/math.js", "../../../node_modules/d3-path/src/path.js", "../../../node_modules/d3-shape/src/path.js", "../../../node_modules/d3-shape/src/array.js", "../../../node_modules/d3-shape/src/curve/linear.js", "../../../node_modules/d3-shape/src/point.js", "../../../node_modules/d3-shape/src/line.js", "../../../node_modules/d3-shape/src/area.js", "../../../node_modules/d3-shape/src/curve/bump.js", "../../../node_modules/d3-shape/src/symbol/circle.js", "../../../node_modules/d3-shape/src/symbol/cross.js", "../../../node_modules/d3-shape/src/symbol/diamond.js", "../../../node_modules/d3-shape/src/symbol/square.js", "../../../node_modules/d3-shape/src/symbol/star.js", "../../../node_modules/d3-shape/src/symbol/triangle.js", "../../../node_modules/d3-shape/src/symbol/wye.js", "../../../node_modules/d3-shape/src/symbol.js", "../../../node_modules/d3-shape/src/noop.js", "../../../node_modules/d3-shape/src/curve/basis.js", "../../../node_modules/d3-shape/src/curve/basisClosed.js", "../../../node_modules/d3-shape/src/curve/basisOpen.js", "../../../node_modules/d3-shape/src/curve/linearClosed.js", "../../../node_modules/d3-shape/src/curve/monotone.js", "../../../node_modules/d3-shape/src/curve/natural.js", "../../../node_modules/d3-shape/src/curve/step.js", "../../../node_modules/d3-shape/src/offset/none.js", "../../../node_modules/d3-shape/src/order/none.js", "../../../node_modules/d3-shape/src/stack.js", "../../../node_modules/d3-shape/src/offset/expand.js", "../../../node_modules/d3-shape/src/offset/silhouette.js", "../../../node_modules/d3-shape/src/offset/wiggle.js", "../../../node_modules/recharts/es6/util/payload/getUniqPayload.js", "../../../node_modules/recharts/es6/component/Tooltip.js", "../../../node_modules/recharts/es6/component/DefaultTooltipContent.js", "../../../node_modules/recharts/es6/component/TooltipBoundingBox.js", "../../../node_modules/recharts/es6/util/tooltip/translate.js", "../../../node_modules/recharts/es6/util/Global.js", "../../../node_modules/recharts/es6/component/ResponsiveContainer.js", "../../../node_modules/recharts/es6/component/Cell.js", "../../../node_modules/recharts/es6/component/Text.js", "../../../node_modules/recharts/es6/util/DOMUtils.js", "../../../node_modules/recharts/es6/util/ReduceCSSCalc.js", "../../../node_modules/recharts/es6/component/Label.js", "../../../node_modules/recharts/es6/util/PolarUtils.js", "../../../node_modules/victory-vendor/es/d3-scale.js", "../../../node_modules/d3-array/src/ascending.js", "../../../node_modules/d3-array/src/descending.js", "../../../node_modules/d3-array/src/bisector.js", "../../../node_modules/d3-array/src/number.js", "../../../node_modules/d3-array/src/bisect.js", "../../../node_modules/internmap/src/index.js", "../../../node_modules/d3-array/src/sort.js", "../../../node_modules/d3-array/src/ticks.js", "../../../node_modules/d3-array/src/max.js", "../../../node_modules/d3-array/src/min.js", "../../../node_modules/d3-array/src/quickselect.js", "../../../node_modules/d3-array/src/quantile.js", "../../../node_modules/d3-array/src/range.js", "../../../node_modules/d3-scale/src/init.js", "../../../node_modules/d3-scale/src/ordinal.js", "../../../node_modules/d3-scale/src/band.js", "../../../node_modules/d3-color/src/define.js", "../../../node_modules/d3-color/src/color.js", "../../../node_modules/d3-interpolate/src/basis.js", "../../../node_modules/d3-interpolate/src/basisClosed.js", "../../../node_modules/d3-interpolate/src/constant.js", "../../../node_modules/d3-interpolate/src/color.js", "../../../node_modules/d3-interpolate/src/rgb.js", "../../../node_modules/d3-interpolate/src/numberArray.js", "../../../node_modules/d3-interpolate/src/array.js", "../../../node_modules/d3-interpolate/src/date.js", "../../../node_modules/d3-interpolate/src/number.js", "../../../node_modules/d3-interpolate/src/object.js", "../../../node_modules/d3-interpolate/src/string.js", "../../../node_modules/d3-interpolate/src/value.js", "../../../node_modules/d3-interpolate/src/round.js", "../../../node_modules/d3-interpolate/src/piecewise.js", "../../../node_modules/d3-scale/src/constant.js", "../../../node_modules/d3-scale/src/number.js", "../../../node_modules/d3-scale/src/continuous.js", "../../../node_modules/d3-format/src/formatDecimal.js", "../../../node_modules/d3-format/src/exponent.js", "../../../node_modules/d3-format/src/formatGroup.js", "../../../node_modules/d3-format/src/formatNumerals.js", "../../../node_modules/d3-format/src/formatSpecifier.js", "../../../node_modules/d3-format/src/formatTrim.js", "../../../node_modules/d3-format/src/formatPrefixAuto.js", "../../../node_modules/d3-format/src/formatRounded.js", "../../../node_modules/d3-format/src/formatTypes.js", "../../../node_modules/d3-format/src/identity.js", "../../../node_modules/d3-format/src/locale.js", "../../../node_modules/d3-format/src/defaultLocale.js", "../../../node_modules/d3-format/src/precisionFixed.js", "../../../node_modules/d3-format/src/precisionPrefix.js", "../../../node_modules/d3-format/src/precisionRound.js", "../../../node_modules/d3-scale/src/tickFormat.js", "../../../node_modules/d3-scale/src/linear.js", "../../../node_modules/d3-scale/src/identity.js", "../../../node_modules/d3-scale/src/nice.js", "../../../node_modules/d3-scale/src/log.js", "../../../node_modules/d3-scale/src/symlog.js", "../../../node_modules/d3-scale/src/pow.js", "../../../node_modules/d3-scale/src/radial.js", "../../../node_modules/d3-scale/src/quantile.js", "../../../node_modules/d3-scale/src/quantize.js", "../../../node_modules/d3-scale/src/threshold.js", "../../../node_modules/d3-time/src/interval.js", "../../../node_modules/d3-time/src/millisecond.js", "../../../node_modules/d3-time/src/duration.js", "../../../node_modules/d3-time/src/second.js", "../../../node_modules/d3-time/src/minute.js", "../../../node_modules/d3-time/src/hour.js", "../../../node_modules/d3-time/src/day.js", "../../../node_modules/d3-time/src/week.js", "../../../node_modules/d3-time/src/month.js", "../../../node_modules/d3-time/src/year.js", "../../../node_modules/d3-time/src/ticks.js", "../../../node_modules/d3-time-format/src/locale.js", "../../../node_modules/d3-time-format/src/defaultLocale.js", "../../../node_modules/d3-scale/src/time.js", "../../../node_modules/d3-scale/src/utcTime.js", "../../../node_modules/d3-scale/src/sequential.js", "../../../node_modules/d3-scale/src/sequentialQuantile.js", "../../../node_modules/d3-scale/src/diverging.js", "../../../node_modules/recharts/es6/util/ChartUtils.js", "../../../node_modules/recharts-scale/es6/getNiceTickValues.js", "../../../node_modules/recharts-scale/es6/util/utils.js", "../../../node_modules/recharts-scale/es6/util/arithmetic.js", "../../../node_modules/recharts/es6/cartesian/ErrorBar.js", "../../../node_modules/tiny-invariant/dist/esm/tiny-invariant.js", "../../../node_modules/recharts/es6/util/getLegendProps.js", "../../../node_modules/recharts/es6/component/LabelList.js", "../../../node_modules/recharts/es6/shape/Sector.js", "../../../node_modules/recharts/es6/shape/Curve.js", "../../../node_modules/recharts/es6/shape/Rectangle.js", "../../../node_modules/react-smooth/es6/Animate.js", "../../../node_modules/src/utils.ts", "../../../node_modules/src/equals.ts", "../../../node_modules/src/comparator.ts", "../../../node_modules/src/index.ts", "../../../node_modules/react-smooth/es6/setRafTimeout.js", "../../../node_modules/react-smooth/es6/AnimateManager.js", "../../../node_modules/react-smooth/es6/util.js", "../../../node_modules/react-smooth/es6/easing.js", "../../../node_modules/react-smooth/es6/configUpdate.js", "../../../node_modules/react-smooth/es6/index.js", "../../../node_modules/recharts/es6/shape/Polygon.js", "../../../node_modules/recharts/es6/shape/Dot.js", "../../../node_modules/recharts/es6/shape/Cross.js", "../../../node_modules/recharts/es6/polar/PolarRadiusAxis.js", "../../../node_modules/recharts/es6/polar/PolarAngleAxis.js", "../../../node_modules/recharts/es6/polar/Pie.js", "../../../node_modules/recharts/es6/util/ActiveShapeUtils.js", "../../../node_modules/recharts/es6/shape/Trapezoid.js", "../../../node_modules/recharts/es6/cartesian/Brush.js", "../../../node_modules/recharts/es6/util/CssPrefixUtils.js", "../../../node_modules/recharts/es6/cartesian/ReferenceLine.js", "../../../node_modules/recharts/es6/util/IfOverflowMatches.js", "../../../node_modules/recharts/es6/util/CartesianUtils.js", "../../../node_modules/recharts/es6/cartesian/Bar.js", "../../../node_modules/recharts/es6/util/BarUtils.js", "../../../node_modules/recharts/es6/context/chartLayoutContext.js", "../../../node_modules/recharts/es6/util/calculateViewBox.js", "../../../node_modules/recharts/es6/cartesian/ReferenceDot.js", "../../../node_modules/recharts/es6/cartesian/ReferenceArea.js", "../../../node_modules/recharts/es6/cartesian/CartesianAxis.js", "../../../node_modules/recharts/es6/cartesian/getTicks.js", "../../../node_modules/recharts/es6/util/getEveryNthWithCondition.js", "../../../node_modules/recharts/es6/util/TickUtils.js", "../../../node_modules/recharts/es6/cartesian/getEquidistantTicks.js", "../../../node_modules/recharts/es6/cartesian/CartesianGrid.js", "../../../node_modules/recharts/es6/cartesian/Line.js", "../../../node_modules/recharts/es6/cartesian/Area.js", "../../../node_modules/recharts/es6/cartesian/XAxis.js", "../../../node_modules/recharts/es6/cartesian/YAxis.js", "../../../node_modules/recharts/es6/chart/generateCategoricalChart.js", "../../../node_modules/recharts/es6/util/DetectReferenceElementsDomain.js", "../../../node_modules/recharts/es6/util/Events.js", "../../../node_modules/recharts/es6/chart/AccessibilityManager.js", "../../../node_modules/recharts/es6/util/isDomainSpecifiedByUser.js", "../../../node_modules/recharts/es6/component/Cursor.js", "../../../node_modules/recharts/es6/util/cursor/getCursorRectangle.js", "../../../node_modules/recharts/es6/util/cursor/getRadialCursorPoints.js", "../../../node_modules/recharts/es6/util/cursor/getCursorPoints.js", "../../../node_modules/recharts/es6/chart/LineChart.js", "../../../node_modules/recharts/es6/chart/BarChart.js", "../../../node_modules/recharts/es6/chart/PieChart.js", "../../../node_modules/recharts/es6/chart/AreaChart.js", "../../javascript/components/Geo/Prompts.js", "../../javascript/components/Geo/CompetitorAnalysis.js", "../../javascript/components/Geo/Optimization.js", "../../javascript/components/Dashboard/Workspace.js", "../../javascript/components/Dashboard/Projects/ProjectForm.js", "../../javascript/components/Dashboard/Projects/CompetitorDetailsDrawer.js", "../../javascript/components/Dashboard/Projects/ProjectDashboard.js", "../../javascript/components/Dashboard/Projects/PromptAnalytics.js", "../../javascript/components/Dashboard/Projects/SideDrawer.js", "../../javascript/components/Dashboard/Projects/ResponseCard.js", "../../javascript/components/Dashboard/Projects/ProjectLinks.js", "../../javascript/components/Dashboard/Projects/ProjectOverview.js", "../../javascript/components/Dashboard/Projects/UnifiedPromptManagement.js", "../../javascript/components/Dashboard/Projects/TopicView.js", "../../javascript/components/Dashboard/Projects/PromptResearch.js", "../../javascript/components/Dashboard/Projects/ManageTopic.js", "../../javascript/components/Dashboard/Projects/EditTopic.js", "../../javascript/components/Dashboard/Projects/PromptForm.js", "../../javascript/components/Dashboard/Projects/CompetitorAnalysis.js", "../../javascript/components/Dashboard/Projects/SortableTopicBreakdownTable.js", "../../javascript/components/Dashboard/Projects/SentimentAnalysis.js", "../../javascript/components/Dashboard/Projects/ContentAnalysis/ContentAnalysis.js", "../../javascript/components/Dashboard/Projects/ContentAnalysis/tabs/OverviewTab.js", "../../javascript/components/Dashboard/Projects/ContentAnalysis/tabs/EntityTab.js", "../../javascript/components/Dashboard/Projects/ContentAnalysis/tabs/ClaimTab.js", "../../javascript/components/Dashboard/Projects/ContentAnalysis/tabs/StructureTab.js", "../../javascript/components/Dashboard/Projects/ContentAnalysis/tabs/TechnicalTab.js", "../../javascript/components/Dashboard/Projects/ContentAnalysis/AnalysisList.js", "../../javascript/components/Dashboard/Projects/ContentAnalysis/AnalysisOverview.js", "../../javascript/components/Dashboard/Projects/Optimization.js", "../../javascript/components/Dashboard/Projects/ExploreConversations.js", "../../javascript/components/Dashboard/Projects/ConversationExplorer.js", "../../javascript/components/Dashboard/Projects/Opportunities.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/OpportunityDetailsSidepanel.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/OpportunityContextContainer.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/VisibilityPromptContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/VisibilityTopicContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/CompetitorTopicContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/CompetitorCompanyContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/ContentCoverageTopicContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/OnPageLinkContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/OnPageLogicFlowContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/OnPageEntityMappingContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/OnPageClaimClarityContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/OnPageSchemaMarkupContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/OnPageInformationArchitectureContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/TechnicalLinkContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/TechnicalLoadTimeContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/TechnicalFrontLoadingContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/TechnicalInformationDensityContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/CitationRateTopicContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/CitationThirdPartyContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/SentimentPromptContext.js", "../../javascript/components/Dashboard/Projects/OpportunityContext/SentimentThemeContext.js", "../../javascript/components/Dashboard/Projects/Strategy.js", "../../javascript/components/Dashboard/Projects/StrategySubcomponents/OpportunityDetailsSideDrawer.js", "../../javascript/components/Dashboard/Projects/StrategySubcomponents/Timeline.js", "../../javascript/components/Dashboard/Projects/Measurement.js", "../../javascript/components/Dashboard/Projects/LockedFeatureView.js", "../../javascript/components/Dashboard/Projects/DataExportSection.js", "../../javascript/components/Admin/RunsDashboard.js", "../../javascript/components/shared/AppLayout.jsx", "../../javascript/components/shared/TrialIndicator.js", "../../javascript/components/shared/AuditIndicator.js", "../../javascript/components/Home/ContactUs.js", "../../javascript/components/OptimizationPrototype/OptimizationPrototype.js", "../../javascript/components/PromptBankGeneration/PromptBankGeneration.js", "../../javascript/components/Audit/AuditResults.js", "../../javascript/components/Audit/VisibilityAnalysis.js", "../../javascript/components/Audit/AuditCategoryAnalysis.js", "../../javascript/components/Audit/PrimaryScaleGraph.js", "../../javascript/components/Audit/QuadBuckets.js", "../../javascript/components/Audit/CompetitorAnalysis.js", "../../javascript/components/Audit/PieChart.js", "../../javascript/components/Audit/ScrollableTable.js", "../../javascript/components/Audit/SentimentAnalysis.js", "../../javascript/components/Audit/SentimentThemes.jsx", "../../javascript/components/Audit/CitationAnalysis.js", "../../javascript/components/Audit/OnPageAnalysis.js", "../../javascript/components/Audit/BasicScaleGraph.js", "../../javascript/components/Audit/ContentGapAnalysis.js", "../../javascript/components/Audit/TechnicalAnalysis.js", "../../javascript/components/Audit/CreateAudit.js", "../../javascript/components/Audit/ClientSetup.js", "../../javascript/components/Audit/ClientInfo.js", "../../javascript/components/Audit/Keywords.js", "../../javascript/components/Audit/Topics.js", "../../javascript/components/Audit/Competitors.js", "../../javascript/components/Clients/ClientLayout.js", "../../javascript/components/Clients/ClientDashboard.js", "../../javascript/components/Clients/ClientDataViewer.js", "../../javascript/components/Clients/ClientSettings.js", "../../javascript/components/Clients/PrProfileSection.js", "../../javascript/components/seo_platform/reports/ReportSetup.js", "../../javascript/components/seo_platform/reports/ReportBuilder.js", "../../javascript/components/seo_platform/strategy/StrategyPage.js", "../../javascript/components/shared/streamChat.js", "../../javascript/components/seo_platform/track.js", "../../javascript/components/seo_platform/strategy/EditRequests.js", "../../javascript/components/seo_platform/strategy/RefreshLauncher.js", "../../javascript/components/seo_platform/strategy/AssessmentProgress.js", "../../javascript/components/seo_platform/strategy/IntakeSnapshotModal.js", "../../javascript/components/shared/MarkdownText.js", "../../javascript/components/shared/ChatExpandOverlay.js", "../../../node_modules/ccount/index.js", "../../../node_modules/escape-string-regexp/index.js", "../../../node_modules/mdast-util-find-and-replace/lib/index.js", "../../../node_modules/mdast-util-gfm-autolink-literal/lib/index.js", "../../../node_modules/mdast-util-gfm-footnote/lib/index.js", "../../../node_modules/mdast-util-gfm-strikethrough/lib/index.js", "../../../node_modules/markdown-table/index.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/blockquote.js", "../../../node_modules/mdast-util-to-markdown/lib/util/pattern-in-scope.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/break.js", "../../../node_modules/longest-streak/index.js", "../../../node_modules/mdast-util-to-markdown/lib/util/format-code-as-indented.js", "../../../node_modules/mdast-util-to-markdown/lib/util/check-fence.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/code.js", "../../../node_modules/mdast-util-to-markdown/lib/util/check-quote.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/definition.js", "../../../node_modules/mdast-util-to-markdown/lib/util/check-emphasis.js", "../../../node_modules/mdast-util-to-markdown/lib/util/encode-character-reference.js", "../../../node_modules/mdast-util-to-markdown/lib/util/encode-info.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/emphasis.js", "../../../node_modules/mdast-util-to-markdown/lib/util/format-heading-as-setext.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/heading.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/html.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/image.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/image-reference.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/inline-code.js", "../../../node_modules/mdast-util-to-markdown/lib/util/format-link-as-autolink.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/link.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/link-reference.js", "../../../node_modules/mdast-util-to-markdown/lib/util/check-bullet.js", "../../../node_modules/mdast-util-to-markdown/lib/util/check-bullet-other.js", "../../../node_modules/mdast-util-to-markdown/lib/util/check-bullet-ordered.js", "../../../node_modules/mdast-util-to-markdown/lib/util/check-rule.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/list.js", "../../../node_modules/mdast-util-to-markdown/lib/util/check-list-item-indent.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/list-item.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/paragraph.js", "../../../node_modules/mdast-util-phrasing/lib/index.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/root.js", "../../../node_modules/mdast-util-to-markdown/lib/util/check-strong.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/strong.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/text.js", "../../../node_modules/mdast-util-to-markdown/lib/util/check-rule-repetition.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/thematic-break.js", "../../../node_modules/mdast-util-to-markdown/lib/handle/index.js", "../../../node_modules/mdast-util-gfm-table/lib/index.js", "../../../node_modules/mdast-util-gfm-task-list-item/lib/index.js", "../../../node_modules/mdast-util-gfm/lib/index.js", "../../../node_modules/micromark-extension-gfm-autolink-literal/lib/syntax.js", "../../../node_modules/micromark-extension-gfm-footnote/lib/syntax.js", "../../../node_modules/micromark-extension-gfm-strikethrough/lib/syntax.js", "../../../node_modules/micromark-extension-gfm-table/lib/edit-map.js", "../../../node_modules/micromark-extension-gfm-table/lib/infer.js", "../../../node_modules/micromark-extension-gfm-table/lib/syntax.js", "../../../node_modules/micromark-extension-gfm-task-list-item/lib/syntax.js", "../../../node_modules/micromark-extension-gfm/index.js", "../../../node_modules/remark-gfm/lib/index.js", "../../javascript/components/seo_platform/strategy/RegenerateStrategyPage.js", "../../javascript/components/seo_platform/onboarding/IntakeStep.js", "../../javascript/components/shared/KeywordPlanEditor.js", "../../javascript/components/seo_platform/metrics/ClientMetrics.js", "../../javascript/components/seo_platform/plan/ProjectPlanPage.js", "../../javascript/components/seo_platform/plan/ProjectPlanInitiativePage.js", "../../javascript/components/seo_platform/plan/ProjectPlanStepPage.js", "../../javascript/components/seo_platform/work/WorkPage.js", "../../javascript/components/seo_platform/work/DeployPanel.js", "../../javascript/components/seo_platform/work/linkifySteps.js", "../../javascript/components/seo_platform/results/ResultsPage.js", "../../javascript/components/shared/DirectUserRedirect.js", "../../javascript/components/seo_platform/weekly/WeeklyPage.js", "../../javascript/components/seo_platform/strategy/StrategyPrintPage.js", "../../javascript/components/Settings/TeamSettings.js", "../../javascript/components/Invitations/AcceptInvitation.js", "../../javascript/components/Admin/ClientDetailPage.js", "../../javascript/components/Admin/UserDetailPage.js", "../../javascript/components/seo_platform/agent/Agents.js", "../../javascript/components/seo_platform/agent/AgentRunner.js", "../../javascript/components/seo_platform/adhoc/AskVisto.js", "../../javascript/components/seo_platform/adhoc/InsightChart.js", "../../javascript/components/seo_platform/onboarding/ClientSetupV2.js", "../../javascript/components/seo_platform/onboarding/ClientDetailsStep.js", "../../javascript/components/seo_platform/onboarding/GoogleDataConnectionStep.js", "../../javascript/components/seo_platform/onboarding/CompetitorsStep.js", "../../javascript/components/seo_platform/agent/RunResult.js", "../../javascript/components/Admin/AdminDashboard.js", "../../javascript/components/Admin/ProjectsDashboard.js", "../../javascript/components/Admin/SnapshotsDashboard.js", "../../javascript/components/Admin/SystemLogsDashboard.js", "../../javascript/components/Admin/ClientsDashboard.js", "../../javascript/components/Admin/ProjectDetails.js", "../../javascript/components/Snapshot/SnapshotReport.js", "../../javascript/components/Snapshot/SnapshotReportProgress.js", "../../javascript/components/Snapshot/ContactFormModal.js", "../../javascript/components/Snapshot/SnapshotForm.js", "../../javascript/components/Snapshot/SnapshotFormDD.js", "../../javascript/components/Snapshot/SnapshotReportDD.js", "../../javascript/components/Admin/AdminProjectSeedForm.js", "../../javascript/components/Admin/UsersDashboard.js", "../../javascript/components/Admin/CreateDirectUserModal.js", "../../javascript/components/Admin/FeatureTogglesDashboard.js", "../../javascript/components/shared/ClarityUserTracking.js", "../../javascript/components/Admin/AuditResultsDashboard.js", "../../javascript/components/Admin/AuditLogsDashboard.js", "../../javascript/components/Admin/BrowserJobsDashboard.js", "../../javascript/components/Admin/OutboundBatchesDashboard.js", "../../javascript/components/Admin/OutboundBatchDetail.js", "../../javascript/components/Admin/PrInboundEmailsDashboard.js", "../../javascript/components/Admin/PrRepliesDashboard.js", "../../javascript/components/Clients/PrReplies.js", "../../javascript/components/Admin/BrowserJobDetail.js", "../../javascript/components/Admin/DeploymentDebug.js", "../../javascript/components/Admin/ProspectMeetingsDashboard.js", "../../javascript/components/shared/Header.jsx"], "sourcesContent": ["/**\n * @license React\n * react.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n\n 'use strict';\n\n/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());\n}\n var ReactVersion = '18.3.1';\n\n// ATTENTION\n// When adding new symbols to this file,\n// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'\n// The Symbol used to tag the ReactElement-like types.\nvar REACT_ELEMENT_TYPE = Symbol.for('react.element');\nvar REACT_PORTAL_TYPE = Symbol.for('react.portal');\nvar REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');\nvar REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');\nvar REACT_PROFILER_TYPE = Symbol.for('react.profiler');\nvar REACT_PROVIDER_TYPE = Symbol.for('react.provider');\nvar REACT_CONTEXT_TYPE = Symbol.for('react.context');\nvar REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');\nvar REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');\nvar REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');\nvar REACT_MEMO_TYPE = Symbol.for('react.memo');\nvar REACT_LAZY_TYPE = Symbol.for('react.lazy');\nvar REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');\nvar MAYBE_ITERATOR_SYMBOL = Symbol.iterator;\nvar FAUX_ITERATOR_SYMBOL = '@@iterator';\nfunction getIteratorFn(maybeIterable) {\n if (maybeIterable === null || typeof maybeIterable !== 'object') {\n return null;\n }\n\n var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];\n\n if (typeof maybeIterator === 'function') {\n return maybeIterator;\n }\n\n return null;\n}\n\n/**\n * Keeps track of the current dispatcher.\n */\nvar ReactCurrentDispatcher = {\n /**\n * @internal\n * @type {ReactComponent}\n */\n current: null\n};\n\n/**\n * Keeps track of the current batch's configuration such as how long an update\n * should suspend for if it needs to.\n */\nvar ReactCurrentBatchConfig = {\n transition: null\n};\n\nvar ReactCurrentActQueue = {\n current: null,\n // Used to reproduce behavior of `batchedUpdates` in legacy mode.\n isBatchingLegacy: false,\n didScheduleLegacyUpdate: false\n};\n\n/**\n * Keeps track of the current owner.\n *\n * The current owner is the component who should own any components that are\n * currently being constructed.\n */\nvar ReactCurrentOwner = {\n /**\n * @internal\n * @type {ReactComponent}\n */\n current: null\n};\n\nvar ReactDebugCurrentFrame = {};\nvar currentExtraStackFrame = null;\nfunction setExtraStackFrame(stack) {\n {\n currentExtraStackFrame = stack;\n }\n}\n\n{\n ReactDebugCurrentFrame.setExtraStackFrame = function (stack) {\n {\n currentExtraStackFrame = stack;\n }\n }; // Stack implementation injected by the current renderer.\n\n\n ReactDebugCurrentFrame.getCurrentStack = null;\n\n ReactDebugCurrentFrame.getStackAddendum = function () {\n var stack = ''; // Add an extra top frame while an element is being validated\n\n if (currentExtraStackFrame) {\n stack += currentExtraStackFrame;\n } // Delegate to the injected renderer-specific implementation\n\n\n var impl = ReactDebugCurrentFrame.getCurrentStack;\n\n if (impl) {\n stack += impl() || '';\n }\n\n return stack;\n };\n}\n\n// -----------------------------------------------------------------------------\n\nvar enableScopeAPI = false; // Experimental Create Event Handle API.\nvar enableCacheElement = false;\nvar enableTransitionTracing = false; // No known bugs, but needs performance testing\n\nvar enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber\n// stuff. Intended to enable React core members to more easily debug scheduling\n// issues in DEV builds.\n\nvar enableDebugTracing = false; // Track which Fiber(s) schedule render work.\n\nvar ReactSharedInternals = {\n ReactCurrentDispatcher: ReactCurrentDispatcher,\n ReactCurrentBatchConfig: ReactCurrentBatchConfig,\n ReactCurrentOwner: ReactCurrentOwner\n};\n\n{\n ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;\n ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue;\n}\n\n// by calls to these methods by a Babel plugin.\n//\n// In PROD (or in packages without access to React internals),\n// they are left as they are instead.\n\nfunction warn(format) {\n {\n {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n printWarning('warn', format, args);\n }\n }\n}\nfunction error(format) {\n {\n {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n printWarning('error', format, args);\n }\n }\n}\n\nfunction printWarning(level, format, args) {\n // When changing this logic, you might want to also\n // update consoleWithStackDev.www.js as well.\n {\n var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n if (stack !== '') {\n format += '%s';\n args = args.concat([stack]);\n } // eslint-disable-next-line react-internal/safe-string-coercion\n\n\n var argsWithFormat = args.map(function (item) {\n return String(item);\n }); // Careful: RN currently depends on this prefix\n\n argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n // breaks IE9: https://github.com/facebook/react/issues/13610\n // eslint-disable-next-line react-internal/no-production-logging\n\n Function.prototype.apply.call(console[level], console, argsWithFormat);\n }\n}\n\nvar didWarnStateUpdateForUnmountedComponent = {};\n\nfunction warnNoop(publicInstance, callerName) {\n {\n var _constructor = publicInstance.constructor;\n var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';\n var warningKey = componentName + \".\" + callerName;\n\n if (didWarnStateUpdateForUnmountedComponent[warningKey]) {\n return;\n }\n\n error(\"Can't call %s on a component that is not yet mounted. \" + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);\n\n didWarnStateUpdateForUnmountedComponent[warningKey] = true;\n }\n}\n/**\n * This is the abstract API for an update queue.\n */\n\n\nvar ReactNoopUpdateQueue = {\n /**\n * Checks whether or not this composite component is mounted.\n * @param {ReactClass} publicInstance The instance we want to test.\n * @return {boolean} True if mounted, false otherwise.\n * @protected\n * @final\n */\n isMounted: function (publicInstance) {\n return false;\n },\n\n /**\n * Forces an update. This should only be invoked when it is known with\n * certainty that we are **not** in a DOM transaction.\n *\n * You may want to call this when you know that some deeper aspect of the\n * component's state has changed but `setState` was not called.\n *\n * This will not invoke `shouldComponentUpdate`, but it will invoke\n * `componentWillUpdate` and `componentDidUpdate`.\n *\n * @param {ReactClass} publicInstance The instance that should rerender.\n * @param {?function} callback Called after component is updated.\n * @param {?string} callerName name of the calling function in the public API.\n * @internal\n */\n enqueueForceUpdate: function (publicInstance, callback, callerName) {\n warnNoop(publicInstance, 'forceUpdate');\n },\n\n /**\n * Replaces all of the state. Always use this or `setState` to mutate state.\n * You should treat `this.state` as immutable.\n *\n * There is no guarantee that `this.state` will be immediately updated, so\n * accessing `this.state` after calling this method may return the old value.\n *\n * @param {ReactClass} publicInstance The instance that should rerender.\n * @param {object} completeState Next state.\n * @param {?function} callback Called after component is updated.\n * @param {?string} callerName name of the calling function in the public API.\n * @internal\n */\n enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {\n warnNoop(publicInstance, 'replaceState');\n },\n\n /**\n * Sets a subset of the state. This only exists because _pendingState is\n * internal. This provides a merging strategy that is not available to deep\n * properties which is confusing. TODO: Expose pendingState or don't use it\n * during the merge.\n *\n * @param {ReactClass} publicInstance The instance that should rerender.\n * @param {object} partialState Next partial state to be merged with state.\n * @param {?function} callback Called after component is updated.\n * @param {?string} Name of the calling function in the public API.\n * @internal\n */\n enqueueSetState: function (publicInstance, partialState, callback, callerName) {\n warnNoop(publicInstance, 'setState');\n }\n};\n\nvar assign = Object.assign;\n\nvar emptyObject = {};\n\n{\n Object.freeze(emptyObject);\n}\n/**\n * Base class helpers for the updating state of a component.\n */\n\n\nfunction Component(props, context, updater) {\n this.props = props;\n this.context = context; // If a component has string refs, we will assign a different object later.\n\n this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the\n // renderer.\n\n this.updater = updater || ReactNoopUpdateQueue;\n}\n\nComponent.prototype.isReactComponent = {};\n/**\n * Sets a subset of the state. Always use this to mutate\n * state. You should treat `this.state` as immutable.\n *\n * There is no guarantee that `this.state` will be immediately updated, so\n * accessing `this.state` after calling this method may return the old value.\n *\n * There is no guarantee that calls to `setState` will run synchronously,\n * as they may eventually be batched together. You can provide an optional\n * callback that will be executed when the call to setState is actually\n * completed.\n *\n * When a function is provided to setState, it will be called at some point in\n * the future (not synchronously). It will be called with the up to date\n * component arguments (state, props, context). These values can be different\n * from this.* because your function may be called after receiveProps but before\n * shouldComponentUpdate, and this new state, props, and context will not yet be\n * assigned to this.\n *\n * @param {object|function} partialState Next partial state or function to\n * produce next partial state to be merged with current state.\n * @param {?function} callback Called after state is updated.\n * @final\n * @protected\n */\n\nComponent.prototype.setState = function (partialState, callback) {\n if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null) {\n throw new Error('setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.');\n }\n\n this.updater.enqueueSetState(this, partialState, callback, 'setState');\n};\n/**\n * Forces an update. This should only be invoked when it is known with\n * certainty that we are **not** in a DOM transaction.\n *\n * You may want to call this when you know that some deeper aspect of the\n * component's state has changed but `setState` was not called.\n *\n * This will not invoke `shouldComponentUpdate`, but it will invoke\n * `componentWillUpdate` and `componentDidUpdate`.\n *\n * @param {?function} callback Called after update is complete.\n * @final\n * @protected\n */\n\n\nComponent.prototype.forceUpdate = function (callback) {\n this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');\n};\n/**\n * Deprecated APIs. These APIs used to exist on classic React classes but since\n * we would like to deprecate them, we're not going to move them over to this\n * modern base class. Instead, we define a getter that warns if it's accessed.\n */\n\n\n{\n var deprecatedAPIs = {\n isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],\n replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']\n };\n\n var defineDeprecationWarning = function (methodName, info) {\n Object.defineProperty(Component.prototype, methodName, {\n get: function () {\n warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);\n\n return undefined;\n }\n });\n };\n\n for (var fnName in deprecatedAPIs) {\n if (deprecatedAPIs.hasOwnProperty(fnName)) {\n defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);\n }\n }\n}\n\nfunction ComponentDummy() {}\n\nComponentDummy.prototype = Component.prototype;\n/**\n * Convenience component with default shallow equality check for sCU.\n */\n\nfunction PureComponent(props, context, updater) {\n this.props = props;\n this.context = context; // If a component has string refs, we will assign a different object later.\n\n this.refs = emptyObject;\n this.updater = updater || ReactNoopUpdateQueue;\n}\n\nvar pureComponentPrototype = PureComponent.prototype = new ComponentDummy();\npureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.\n\nassign(pureComponentPrototype, Component.prototype);\npureComponentPrototype.isPureReactComponent = true;\n\n// an immutable object with a single mutable value\nfunction createRef() {\n var refObject = {\n current: null\n };\n\n {\n Object.seal(refObject);\n }\n\n return refObject;\n}\n\nvar isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare\n\nfunction isArray(a) {\n return isArrayImpl(a);\n}\n\n/*\n * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol\n * and Temporal.* types. See https://github.com/facebook/react/pull/22064.\n *\n * The functions in this module will throw an easier-to-understand,\n * easier-to-debug exception with a clear errors message message explaining the\n * problem. (Instead of a confusing exception thrown inside the implementation\n * of the `value` object).\n */\n// $FlowFixMe only called in DEV, so void return is not possible.\nfunction typeName(value) {\n {\n // toStringTag is needed for namespaced types like Temporal.Instant\n var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;\n var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';\n return type;\n }\n} // $FlowFixMe only called in DEV, so void return is not possible.\n\n\nfunction willCoercionThrow(value) {\n {\n try {\n testStringCoercion(value);\n return false;\n } catch (e) {\n return true;\n }\n }\n}\n\nfunction testStringCoercion(value) {\n // If you ended up here by following an exception call stack, here's what's\n // happened: you supplied an object or symbol value to React (as a prop, key,\n // DOM attribute, CSS property, string ref, etc.) and when React tried to\n // coerce it to a string using `'' + value`, an exception was thrown.\n //\n // The most common types that will cause this exception are `Symbol` instances\n // and Temporal objects like `Temporal.Instant`. But any object that has a\n // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this\n // exception. (Library authors do this to prevent users from using built-in\n // numeric operators like `+` or comparison operators like `>=` because custom\n // methods are needed to perform accurate arithmetic or comparison.)\n //\n // To fix the problem, coerce this object or symbol value to a string before\n // passing it to React. The most reliable way is usually `String(value)`.\n //\n // To find which value is throwing, check the browser or debugger console.\n // Before this exception was thrown, there should be `console.error` output\n // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the\n // problem and how that type was used: key, atrribute, input value prop, etc.\n // In most cases, this console output also shows the component and its\n // ancestor components where the exception happened.\n //\n // eslint-disable-next-line react-internal/safe-string-coercion\n return '' + value;\n}\nfunction checkKeyStringCoercion(value) {\n {\n if (willCoercionThrow(value)) {\n error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));\n\n return testStringCoercion(value); // throw (to help callers find troubleshooting comments)\n }\n }\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n var displayName = outerType.displayName;\n\n if (displayName) {\n return displayName;\n }\n\n var functionName = innerType.displayName || innerType.name || '';\n return functionName !== '' ? wrapperName + \"(\" + functionName + \")\" : wrapperName;\n} // Keep in sync with react-reconciler/getComponentNameFromFiber\n\n\nfunction getContextName(type) {\n return type.displayName || 'Context';\n} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.\n\n\nfunction getComponentNameFromType(type) {\n if (type == null) {\n // Host root, text node or just invalid type.\n return null;\n }\n\n {\n if (typeof type.tag === 'number') {\n error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');\n }\n }\n\n if (typeof type === 'function') {\n return type.displayName || type.name || null;\n }\n\n if (typeof type === 'string') {\n return type;\n }\n\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return 'Fragment';\n\n case REACT_PORTAL_TYPE:\n return 'Portal';\n\n case REACT_PROFILER_TYPE:\n return 'Profiler';\n\n case REACT_STRICT_MODE_TYPE:\n return 'StrictMode';\n\n case REACT_SUSPENSE_TYPE:\n return 'Suspense';\n\n case REACT_SUSPENSE_LIST_TYPE:\n return 'SuspenseList';\n\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_CONTEXT_TYPE:\n var context = type;\n return getContextName(context) + '.Consumer';\n\n case REACT_PROVIDER_TYPE:\n var provider = type;\n return getContextName(provider._context) + '.Provider';\n\n case REACT_FORWARD_REF_TYPE:\n return getWrappedName(type, type.render, 'ForwardRef');\n\n case REACT_MEMO_TYPE:\n var outerName = type.displayName || null;\n\n if (outerName !== null) {\n return outerName;\n }\n\n return getComponentNameFromType(type.type) || 'Memo';\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n return getComponentNameFromType(init(payload));\n } catch (x) {\n return null;\n }\n }\n\n // eslint-disable-next-line no-fallthrough\n }\n }\n\n return null;\n}\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar RESERVED_PROPS = {\n key: true,\n ref: true,\n __self: true,\n __source: true\n};\nvar specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;\n\n{\n didWarnAboutStringRefs = {};\n}\n\nfunction hasValidRef(config) {\n {\n if (hasOwnProperty.call(config, 'ref')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.ref !== undefined;\n}\n\nfunction hasValidKey(config) {\n {\n if (hasOwnProperty.call(config, 'key')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'key').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.key !== undefined;\n}\n\nfunction defineKeyPropWarningGetter(props, displayName) {\n var warnAboutAccessingKey = function () {\n {\n if (!specialPropKeyWarningShown) {\n specialPropKeyWarningShown = true;\n\n error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);\n }\n }\n };\n\n warnAboutAccessingKey.isReactWarning = true;\n Object.defineProperty(props, 'key', {\n get: warnAboutAccessingKey,\n configurable: true\n });\n}\n\nfunction defineRefPropWarningGetter(props, displayName) {\n var warnAboutAccessingRef = function () {\n {\n if (!specialPropRefWarningShown) {\n specialPropRefWarningShown = true;\n\n error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);\n }\n }\n };\n\n warnAboutAccessingRef.isReactWarning = true;\n Object.defineProperty(props, 'ref', {\n get: warnAboutAccessingRef,\n configurable: true\n });\n}\n\nfunction warnIfStringRefCannotBeAutoConverted(config) {\n {\n if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {\n var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);\n\n if (!didWarnAboutStringRefs[componentName]) {\n error('Component \"%s\" contains the string ref \"%s\". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref);\n\n didWarnAboutStringRefs[componentName] = true;\n }\n }\n }\n}\n/**\n * Factory method to create a new React element. This no longer adheres to\n * the class pattern, so do not use new to call it. Also, instanceof check\n * will not work. Instead test $$typeof field against Symbol.for('react.element') to check\n * if something is a React Element.\n *\n * @param {*} type\n * @param {*} props\n * @param {*} key\n * @param {string|object} ref\n * @param {*} owner\n * @param {*} self A *temporary* helper to detect places where `this` is\n * different from the `owner` when React.createElement is called, so that we\n * can warn. We want to get rid of owner and replace string `ref`s with arrow\n * functions, and as long as `this` and owner are the same, there will be no\n * change in behavior.\n * @param {*} source An annotation object (added by a transpiler or otherwise)\n * indicating filename, line number, and/or other information.\n * @internal\n */\n\n\nvar ReactElement = function (type, key, ref, self, source, owner, props) {\n var element = {\n // This tag allows us to uniquely identify this as a React Element\n $$typeof: REACT_ELEMENT_TYPE,\n // Built-in properties that belong on the element\n type: type,\n key: key,\n ref: ref,\n props: props,\n // Record the component responsible for creating this element.\n _owner: owner\n };\n\n {\n // The validation flag is currently mutative. We put it on\n // an external backing store so that we can freeze the whole object.\n // This can be replaced with a WeakMap once they are implemented in\n // commonly used development environments.\n element._store = {}; // To make comparing ReactElements easier for testing purposes, we make\n // the validation flag non-enumerable (where possible, which should\n // include every environment we run tests in), so the test framework\n // ignores it.\n\n Object.defineProperty(element._store, 'validated', {\n configurable: false,\n enumerable: false,\n writable: true,\n value: false\n }); // self and source are DEV only properties.\n\n Object.defineProperty(element, '_self', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: self\n }); // Two elements created in two different places should be considered\n // equal for testing purposes and therefore we hide it from enumeration.\n\n Object.defineProperty(element, '_source', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: source\n });\n\n if (Object.freeze) {\n Object.freeze(element.props);\n Object.freeze(element);\n }\n }\n\n return element;\n};\n/**\n * Create and return a new ReactElement of the given type.\n * See https://reactjs.org/docs/react-api.html#createelement\n */\n\nfunction createElement(type, config, children) {\n var propName; // Reserved names are extracted\n\n var props = {};\n var key = null;\n var ref = null;\n var self = null;\n var source = null;\n\n if (config != null) {\n if (hasValidRef(config)) {\n ref = config.ref;\n\n {\n warnIfStringRefCannotBeAutoConverted(config);\n }\n }\n\n if (hasValidKey(config)) {\n {\n checkKeyStringCoercion(config.key);\n }\n\n key = '' + config.key;\n }\n\n self = config.__self === undefined ? null : config.__self;\n source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object\n\n for (propName in config) {\n if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n props[propName] = config[propName];\n }\n }\n } // Children can be more than one argument, and those are transferred onto\n // the newly allocated props object.\n\n\n var childrenLength = arguments.length - 2;\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 2];\n }\n\n {\n if (Object.freeze) {\n Object.freeze(childArray);\n }\n }\n\n props.children = childArray;\n } // Resolve default props\n\n\n if (type && type.defaultProps) {\n var defaultProps = type.defaultProps;\n\n for (propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n }\n\n {\n if (key || ref) {\n var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;\n\n if (key) {\n defineKeyPropWarningGetter(props, displayName);\n }\n\n if (ref) {\n defineRefPropWarningGetter(props, displayName);\n }\n }\n }\n\n return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);\n}\nfunction cloneAndReplaceKey(oldElement, newKey) {\n var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);\n return newElement;\n}\n/**\n * Clone and return a new ReactElement using element as the starting point.\n * See https://reactjs.org/docs/react-api.html#cloneelement\n */\n\nfunction cloneElement(element, config, children) {\n if (element === null || element === undefined) {\n throw new Error(\"React.cloneElement(...): The argument must be a React element, but you passed \" + element + \".\");\n }\n\n var propName; // Original props are copied\n\n var props = assign({}, element.props); // Reserved names are extracted\n\n var key = element.key;\n var ref = element.ref; // Self is preserved since the owner is preserved.\n\n var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a\n // transpiler, and the original source is probably a better indicator of the\n // true owner.\n\n var source = element._source; // Owner will be preserved, unless ref is overridden\n\n var owner = element._owner;\n\n if (config != null) {\n if (hasValidRef(config)) {\n // Silently steal the ref from the parent.\n ref = config.ref;\n owner = ReactCurrentOwner.current;\n }\n\n if (hasValidKey(config)) {\n {\n checkKeyStringCoercion(config.key);\n }\n\n key = '' + config.key;\n } // Remaining properties override existing props\n\n\n var defaultProps;\n\n if (element.type && element.type.defaultProps) {\n defaultProps = element.type.defaultProps;\n }\n\n for (propName in config) {\n if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n if (config[propName] === undefined && defaultProps !== undefined) {\n // Resolve default props\n props[propName] = defaultProps[propName];\n } else {\n props[propName] = config[propName];\n }\n }\n }\n } // Children can be more than one argument, and those are transferred onto\n // the newly allocated props object.\n\n\n var childrenLength = arguments.length - 2;\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 2];\n }\n\n props.children = childArray;\n }\n\n return ReactElement(element.type, key, ref, self, source, owner, props);\n}\n/**\n * Verifies the object is a ReactElement.\n * See https://reactjs.org/docs/react-api.html#isvalidelement\n * @param {?object} object\n * @return {boolean} True if `object` is a ReactElement.\n * @final\n */\n\nfunction isValidElement(object) {\n return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n}\n\nvar SEPARATOR = '.';\nvar SUBSEPARATOR = ':';\n/**\n * Escape and wrap key so it is safe to use as a reactid\n *\n * @param {string} key to be escaped.\n * @return {string} the escaped key.\n */\n\nfunction escape(key) {\n var escapeRegex = /[=:]/g;\n var escaperLookup = {\n '=': '=0',\n ':': '=2'\n };\n var escapedString = key.replace(escapeRegex, function (match) {\n return escaperLookup[match];\n });\n return '$' + escapedString;\n}\n/**\n * TODO: Test that a single child and an array with one item have the same key\n * pattern.\n */\n\n\nvar didWarnAboutMaps = false;\nvar userProvidedKeyEscapeRegex = /\\/+/g;\n\nfunction escapeUserProvidedKey(text) {\n return text.replace(userProvidedKeyEscapeRegex, '$&/');\n}\n/**\n * Generate a key string that identifies a element within a set.\n *\n * @param {*} element A element that could contain a manual key.\n * @param {number} index Index that is used if a manual key is not provided.\n * @return {string}\n */\n\n\nfunction getElementKey(element, index) {\n // Do some typechecking here since we call this blindly. We want to ensure\n // that we don't block potential future ES APIs.\n if (typeof element === 'object' && element !== null && element.key != null) {\n // Explicit key\n {\n checkKeyStringCoercion(element.key);\n }\n\n return escape('' + element.key);\n } // Implicit key determined by the index in the set\n\n\n return index.toString(36);\n}\n\nfunction mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {\n var type = typeof children;\n\n if (type === 'undefined' || type === 'boolean') {\n // All of the above are perceived as null.\n children = null;\n }\n\n var invokeCallback = false;\n\n if (children === null) {\n invokeCallback = true;\n } else {\n switch (type) {\n case 'string':\n case 'number':\n invokeCallback = true;\n break;\n\n case 'object':\n switch (children.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_PORTAL_TYPE:\n invokeCallback = true;\n }\n\n }\n }\n\n if (invokeCallback) {\n var _child = children;\n var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array\n // so that it's consistent if the number of children grows:\n\n var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;\n\n if (isArray(mappedChild)) {\n var escapedChildKey = '';\n\n if (childKey != null) {\n escapedChildKey = escapeUserProvidedKey(childKey) + '/';\n }\n\n mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) {\n return c;\n });\n } else if (mappedChild != null) {\n if (isValidElement(mappedChild)) {\n {\n // The `if` statement here prevents auto-disabling of the safe\n // coercion ESLint rule, so we must manually disable it below.\n // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key\n if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) {\n checkKeyStringCoercion(mappedChild.key);\n }\n }\n\n mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as\n // traverseAllChildren used to do for objects as children\n escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key\n mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number\n // eslint-disable-next-line react-internal/safe-string-coercion\n escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey);\n }\n\n array.push(mappedChild);\n }\n\n return 1;\n }\n\n var child;\n var nextName;\n var subtreeCount = 0; // Count of children found in the current subtree.\n\n var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;\n\n if (isArray(children)) {\n for (var i = 0; i < children.length; i++) {\n child = children[i];\n nextName = nextNamePrefix + getElementKey(child, i);\n subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);\n }\n } else {\n var iteratorFn = getIteratorFn(children);\n\n if (typeof iteratorFn === 'function') {\n var iterableChildren = children;\n\n {\n // Warn about using Maps as children\n if (iteratorFn === iterableChildren.entries) {\n if (!didWarnAboutMaps) {\n warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');\n }\n\n didWarnAboutMaps = true;\n }\n }\n\n var iterator = iteratorFn.call(iterableChildren);\n var step;\n var ii = 0;\n\n while (!(step = iterator.next()).done) {\n child = step.value;\n nextName = nextNamePrefix + getElementKey(child, ii++);\n subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);\n }\n } else if (type === 'object') {\n // eslint-disable-next-line react-internal/safe-string-coercion\n var childrenString = String(children);\n throw new Error(\"Objects are not valid as a React child (found: \" + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + \"). \" + 'If you meant to render a collection of children, use an array ' + 'instead.');\n }\n }\n\n return subtreeCount;\n}\n\n/**\n * Maps children that are typically specified as `props.children`.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrenmap\n *\n * The provided mapFunction(child, index) will be called for each\n * leaf child.\n *\n * @param {?*} children Children tree container.\n * @param {function(*, int)} func The map function.\n * @param {*} context Context for mapFunction.\n * @return {object} Object containing the ordered map of results.\n */\nfunction mapChildren(children, func, context) {\n if (children == null) {\n return children;\n }\n\n var result = [];\n var count = 0;\n mapIntoArray(children, result, '', '', function (child) {\n return func.call(context, child, count++);\n });\n return result;\n}\n/**\n * Count the number of children that are typically specified as\n * `props.children`.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrencount\n *\n * @param {?*} children Children tree container.\n * @return {number} The number of children.\n */\n\n\nfunction countChildren(children) {\n var n = 0;\n mapChildren(children, function () {\n n++; // Don't return anything\n });\n return n;\n}\n\n/**\n * Iterates through children that are typically specified as `props.children`.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrenforeach\n *\n * The provided forEachFunc(child, index) will be called for each\n * leaf child.\n *\n * @param {?*} children Children tree container.\n * @param {function(*, int)} forEachFunc\n * @param {*} forEachContext Context for forEachContext.\n */\nfunction forEachChildren(children, forEachFunc, forEachContext) {\n mapChildren(children, function () {\n forEachFunc.apply(this, arguments); // Don't return anything.\n }, forEachContext);\n}\n/**\n * Flatten a children object (typically specified as `props.children`) and\n * return an array with appropriately re-keyed children.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrentoarray\n */\n\n\nfunction toArray(children) {\n return mapChildren(children, function (child) {\n return child;\n }) || [];\n}\n/**\n * Returns the first child in a collection of children and verifies that there\n * is only one child in the collection.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrenonly\n *\n * The current implementation of this function assumes that a single child gets\n * passed without a wrapper, but the purpose of this helper function is to\n * abstract away the particular structure of children.\n *\n * @param {?object} children Child collection structure.\n * @return {ReactElement} The first and only `ReactElement` contained in the\n * structure.\n */\n\n\nfunction onlyChild(children) {\n if (!isValidElement(children)) {\n throw new Error('React.Children.only expected to receive a single React element child.');\n }\n\n return children;\n}\n\nfunction createContext(defaultValue) {\n // TODO: Second argument used to be an optional `calculateChangedBits`\n // function. Warn to reserve for future use?\n var context = {\n $$typeof: REACT_CONTEXT_TYPE,\n // As a workaround to support multiple concurrent renderers, we categorize\n // some renderers as primary and others as secondary. We only expect\n // there to be two concurrent renderers at most: React Native (primary) and\n // Fabric (secondary); React DOM (primary) and React ART (secondary).\n // Secondary renderers store their context values on separate fields.\n _currentValue: defaultValue,\n _currentValue2: defaultValue,\n // Used to track how many concurrent renderers this context currently\n // supports within in a single renderer. Such as parallel server rendering.\n _threadCount: 0,\n // These are circular\n Provider: null,\n Consumer: null,\n // Add these to use same hidden class in VM as ServerContext\n _defaultValue: null,\n _globalName: null\n };\n context.Provider = {\n $$typeof: REACT_PROVIDER_TYPE,\n _context: context\n };\n var hasWarnedAboutUsingNestedContextConsumers = false;\n var hasWarnedAboutUsingConsumerProvider = false;\n var hasWarnedAboutDisplayNameOnConsumer = false;\n\n {\n // A separate object, but proxies back to the original context object for\n // backwards compatibility. It has a different $$typeof, so we can properly\n // warn for the incorrect usage of Context as a Consumer.\n var Consumer = {\n $$typeof: REACT_CONTEXT_TYPE,\n _context: context\n }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here\n\n Object.defineProperties(Consumer, {\n Provider: {\n get: function () {\n if (!hasWarnedAboutUsingConsumerProvider) {\n hasWarnedAboutUsingConsumerProvider = true;\n\n error('Rendering is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?');\n }\n\n return context.Provider;\n },\n set: function (_Provider) {\n context.Provider = _Provider;\n }\n },\n _currentValue: {\n get: function () {\n return context._currentValue;\n },\n set: function (_currentValue) {\n context._currentValue = _currentValue;\n }\n },\n _currentValue2: {\n get: function () {\n return context._currentValue2;\n },\n set: function (_currentValue2) {\n context._currentValue2 = _currentValue2;\n }\n },\n _threadCount: {\n get: function () {\n return context._threadCount;\n },\n set: function (_threadCount) {\n context._threadCount = _threadCount;\n }\n },\n Consumer: {\n get: function () {\n if (!hasWarnedAboutUsingNestedContextConsumers) {\n hasWarnedAboutUsingNestedContextConsumers = true;\n\n error('Rendering is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?');\n }\n\n return context.Consumer;\n }\n },\n displayName: {\n get: function () {\n return context.displayName;\n },\n set: function (displayName) {\n if (!hasWarnedAboutDisplayNameOnConsumer) {\n warn('Setting `displayName` on Context.Consumer has no effect. ' + \"You should set it directly on the context with Context.displayName = '%s'.\", displayName);\n\n hasWarnedAboutDisplayNameOnConsumer = true;\n }\n }\n }\n }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty\n\n context.Consumer = Consumer;\n }\n\n {\n context._currentRenderer = null;\n context._currentRenderer2 = null;\n }\n\n return context;\n}\n\nvar Uninitialized = -1;\nvar Pending = 0;\nvar Resolved = 1;\nvar Rejected = 2;\n\nfunction lazyInitializer(payload) {\n if (payload._status === Uninitialized) {\n var ctor = payload._result;\n var thenable = ctor(); // Transition to the next state.\n // This might throw either because it's missing or throws. If so, we treat it\n // as still uninitialized and try again next time. Which is the same as what\n // happens if the ctor or any wrappers processing the ctor throws. This might\n // end up fixing it if the resolution was a concurrency bug.\n\n thenable.then(function (moduleObject) {\n if (payload._status === Pending || payload._status === Uninitialized) {\n // Transition to the next state.\n var resolved = payload;\n resolved._status = Resolved;\n resolved._result = moduleObject;\n }\n }, function (error) {\n if (payload._status === Pending || payload._status === Uninitialized) {\n // Transition to the next state.\n var rejected = payload;\n rejected._status = Rejected;\n rejected._result = error;\n }\n });\n\n if (payload._status === Uninitialized) {\n // In case, we're still uninitialized, then we're waiting for the thenable\n // to resolve. Set it as pending in the meantime.\n var pending = payload;\n pending._status = Pending;\n pending._result = thenable;\n }\n }\n\n if (payload._status === Resolved) {\n var moduleObject = payload._result;\n\n {\n if (moduleObject === undefined) {\n error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\\n\\nYour code should look like: \\n ' + // Break up imports to avoid accidentally parsing them as dependencies.\n 'const MyComponent = lazy(() => imp' + \"ort('./MyComponent'))\\n\\n\" + 'Did you accidentally put curly braces around the import?', moduleObject);\n }\n }\n\n {\n if (!('default' in moduleObject)) {\n error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\\n\\nYour code should look like: \\n ' + // Break up imports to avoid accidentally parsing them as dependencies.\n 'const MyComponent = lazy(() => imp' + \"ort('./MyComponent'))\", moduleObject);\n }\n }\n\n return moduleObject.default;\n } else {\n throw payload._result;\n }\n}\n\nfunction lazy(ctor) {\n var payload = {\n // We use these fields to store the result.\n _status: Uninitialized,\n _result: ctor\n };\n var lazyType = {\n $$typeof: REACT_LAZY_TYPE,\n _payload: payload,\n _init: lazyInitializer\n };\n\n {\n // In production, this would just set it on the object.\n var defaultProps;\n var propTypes; // $FlowFixMe\n\n Object.defineProperties(lazyType, {\n defaultProps: {\n configurable: true,\n get: function () {\n return defaultProps;\n },\n set: function (newDefaultProps) {\n error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');\n\n defaultProps = newDefaultProps; // Match production behavior more closely:\n // $FlowFixMe\n\n Object.defineProperty(lazyType, 'defaultProps', {\n enumerable: true\n });\n }\n },\n propTypes: {\n configurable: true,\n get: function () {\n return propTypes;\n },\n set: function (newPropTypes) {\n error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');\n\n propTypes = newPropTypes; // Match production behavior more closely:\n // $FlowFixMe\n\n Object.defineProperty(lazyType, 'propTypes', {\n enumerable: true\n });\n }\n }\n });\n }\n\n return lazyType;\n}\n\nfunction forwardRef(render) {\n {\n if (render != null && render.$$typeof === REACT_MEMO_TYPE) {\n error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).');\n } else if (typeof render !== 'function') {\n error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render);\n } else {\n if (render.length !== 0 && render.length !== 2) {\n error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.');\n }\n }\n\n if (render != null) {\n if (render.defaultProps != null || render.propTypes != null) {\n error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?');\n }\n }\n }\n\n var elementType = {\n $$typeof: REACT_FORWARD_REF_TYPE,\n render: render\n };\n\n {\n var ownName;\n Object.defineProperty(elementType, 'displayName', {\n enumerable: false,\n configurable: true,\n get: function () {\n return ownName;\n },\n set: function (name) {\n ownName = name; // The inner component shouldn't inherit this display name in most cases,\n // because the component may be used elsewhere.\n // But it's nice for anonymous functions to inherit the name,\n // so that our component-stack generation logic will display their frames.\n // An anonymous function generally suggests a pattern like:\n // React.forwardRef((props, ref) => {...});\n // This kind of inner function is not used elsewhere so the side effect is okay.\n\n if (!render.name && !render.displayName) {\n render.displayName = name;\n }\n }\n });\n }\n\n return elementType;\n}\n\nvar REACT_MODULE_REFERENCE;\n\n{\n REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');\n}\n\nfunction isValidElementType(type) {\n if (typeof type === 'string' || typeof type === 'function') {\n return true;\n } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).\n\n\n if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) {\n return true;\n }\n\n if (typeof type === 'object' && type !== null) {\n if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object\n // types supported by any Flight configuration anywhere since\n // we don't know which Flight build this will end up being used\n // with.\n type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction memo(type, compare) {\n {\n if (!isValidElementType(type)) {\n error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type);\n }\n }\n\n var elementType = {\n $$typeof: REACT_MEMO_TYPE,\n type: type,\n compare: compare === undefined ? null : compare\n };\n\n {\n var ownName;\n Object.defineProperty(elementType, 'displayName', {\n enumerable: false,\n configurable: true,\n get: function () {\n return ownName;\n },\n set: function (name) {\n ownName = name; // The inner component shouldn't inherit this display name in most cases,\n // because the component may be used elsewhere.\n // But it's nice for anonymous functions to inherit the name,\n // so that our component-stack generation logic will display their frames.\n // An anonymous function generally suggests a pattern like:\n // React.memo((props) => {...});\n // This kind of inner function is not used elsewhere so the side effect is okay.\n\n if (!type.name && !type.displayName) {\n type.displayName = name;\n }\n }\n });\n }\n\n return elementType;\n}\n\nfunction resolveDispatcher() {\n var dispatcher = ReactCurrentDispatcher.current;\n\n {\n if (dispatcher === null) {\n error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\\n' + '2. You might be breaking the Rules of Hooks\\n' + '3. You might have more than one copy of React in the same app\\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');\n }\n } // Will result in a null access error if accessed outside render phase. We\n // intentionally don't throw our own error because this is in a hot path.\n // Also helps ensure this is inlined.\n\n\n return dispatcher;\n}\nfunction useContext(Context) {\n var dispatcher = resolveDispatcher();\n\n {\n // TODO: add a more generic warning for invalid values.\n if (Context._context !== undefined) {\n var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs\n // and nobody should be using this in existing code.\n\n if (realContext.Consumer === Context) {\n error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?');\n } else if (realContext.Provider === Context) {\n error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?');\n }\n }\n }\n\n return dispatcher.useContext(Context);\n}\nfunction useState(initialState) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useState(initialState);\n}\nfunction useReducer(reducer, initialArg, init) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useReducer(reducer, initialArg, init);\n}\nfunction useRef(initialValue) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useRef(initialValue);\n}\nfunction useEffect(create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useEffect(create, deps);\n}\nfunction useInsertionEffect(create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useInsertionEffect(create, deps);\n}\nfunction useLayoutEffect(create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useLayoutEffect(create, deps);\n}\nfunction useCallback(callback, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useCallback(callback, deps);\n}\nfunction useMemo(create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useMemo(create, deps);\n}\nfunction useImperativeHandle(ref, create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useImperativeHandle(ref, create, deps);\n}\nfunction useDebugValue(value, formatterFn) {\n {\n var dispatcher = resolveDispatcher();\n return dispatcher.useDebugValue(value, formatterFn);\n }\n}\nfunction useTransition() {\n var dispatcher = resolveDispatcher();\n return dispatcher.useTransition();\n}\nfunction useDeferredValue(value) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useDeferredValue(value);\n}\nfunction useId() {\n var dispatcher = resolveDispatcher();\n return dispatcher.useId();\n}\nfunction useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n}\n\n// Helpers to patch console.logs to avoid logging during side-effect free\n// replaying on render function. This currently only patches the object\n// lazily which won't cover if the log function was extracted eagerly.\n// We could also eagerly patch the method.\nvar disabledDepth = 0;\nvar prevLog;\nvar prevInfo;\nvar prevWarn;\nvar prevError;\nvar prevGroup;\nvar prevGroupCollapsed;\nvar prevGroupEnd;\n\nfunction disabledLog() {}\n\ndisabledLog.__reactDisabledLog = true;\nfunction disableLogs() {\n {\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n prevLog = console.log;\n prevInfo = console.info;\n prevWarn = console.warn;\n prevError = console.error;\n prevGroup = console.group;\n prevGroupCollapsed = console.groupCollapsed;\n prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099\n\n var props = {\n configurable: true,\n enumerable: true,\n value: disabledLog,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n info: props,\n log: props,\n warn: props,\n error: props,\n group: props,\n groupCollapsed: props,\n groupEnd: props\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n disabledDepth++;\n }\n}\nfunction reenableLogs() {\n {\n disabledDepth--;\n\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n var props = {\n configurable: true,\n enumerable: true,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n log: assign({}, props, {\n value: prevLog\n }),\n info: assign({}, props, {\n value: prevInfo\n }),\n warn: assign({}, props, {\n value: prevWarn\n }),\n error: assign({}, props, {\n value: prevError\n }),\n group: assign({}, props, {\n value: prevGroup\n }),\n groupCollapsed: assign({}, props, {\n value: prevGroupCollapsed\n }),\n groupEnd: assign({}, props, {\n value: prevGroupEnd\n })\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n if (disabledDepth < 0) {\n error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');\n }\n }\n}\n\nvar ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;\nvar prefix;\nfunction describeBuiltInComponentFrame(name, source, ownerFn) {\n {\n if (prefix === undefined) {\n // Extract the VM specific prefix used by each line.\n try {\n throw Error();\n } catch (x) {\n var match = x.stack.trim().match(/\\n( *(at )?)/);\n prefix = match && match[1] || '';\n }\n } // We use the prefix to ensure our stacks line up with native stack frames.\n\n\n return '\\n' + prefix + name;\n }\n}\nvar reentry = false;\nvar componentFrameCache;\n\n{\n var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;\n componentFrameCache = new PossiblyWeakMap();\n}\n\nfunction describeNativeComponentFrame(fn, construct) {\n // If something asked for a stack inside a fake render, it should get ignored.\n if ( !fn || reentry) {\n return '';\n }\n\n {\n var frame = componentFrameCache.get(fn);\n\n if (frame !== undefined) {\n return frame;\n }\n }\n\n var control;\n reentry = true;\n var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.\n\n Error.prepareStackTrace = undefined;\n var previousDispatcher;\n\n {\n previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function\n // for warnings.\n\n ReactCurrentDispatcher$1.current = null;\n disableLogs();\n }\n\n try {\n // This should throw.\n if (construct) {\n // Something should be setting the props in the constructor.\n var Fake = function () {\n throw Error();\n }; // $FlowFixMe\n\n\n Object.defineProperty(Fake.prototype, 'props', {\n set: function () {\n // We use a throwing setter instead of frozen or non-writable props\n // because that won't throw in a non-strict mode function.\n throw Error();\n }\n });\n\n if (typeof Reflect === 'object' && Reflect.construct) {\n // We construct a different control for this case to include any extra\n // frames added by the construct call.\n try {\n Reflect.construct(Fake, []);\n } catch (x) {\n control = x;\n }\n\n Reflect.construct(fn, [], Fake);\n } else {\n try {\n Fake.call();\n } catch (x) {\n control = x;\n }\n\n fn.call(Fake.prototype);\n }\n } else {\n try {\n throw Error();\n } catch (x) {\n control = x;\n }\n\n fn();\n }\n } catch (sample) {\n // This is inlined manually because closure doesn't do it for us.\n if (sample && control && typeof sample.stack === 'string') {\n // This extracts the first frame from the sample that isn't also in the control.\n // Skipping one frame that we assume is the frame that calls the two.\n var sampleLines = sample.stack.split('\\n');\n var controlLines = control.stack.split('\\n');\n var s = sampleLines.length - 1;\n var c = controlLines.length - 1;\n\n while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {\n // We expect at least one stack frame to be shared.\n // Typically this will be the root most one. However, stack frames may be\n // cut off due to maximum stack limits. In this case, one maybe cut off\n // earlier than the other. We assume that the sample is longer or the same\n // and there for cut off earlier. So we should find the root most frame in\n // the sample somewhere in the control.\n c--;\n }\n\n for (; s >= 1 && c >= 0; s--, c--) {\n // Next we find the first one that isn't the same which should be the\n // frame that called our sample function and the control.\n if (sampleLines[s] !== controlLines[c]) {\n // In V8, the first line is describing the message but other VMs don't.\n // If we're about to return the first line, and the control is also on the same\n // line, that's a pretty good indicator that our sample threw at same line as\n // the control. I.e. before we entered the sample frame. So we ignore this result.\n // This can happen if you passed a class to function component, or non-function.\n if (s !== 1 || c !== 1) {\n do {\n s--;\n c--; // We may still have similar intermediate frames from the construct call.\n // The next one that isn't the same should be our match though.\n\n if (c < 0 || sampleLines[s] !== controlLines[c]) {\n // V8 adds a \"new\" prefix for native classes. Let's remove it to make it prettier.\n var _frame = '\\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled \"\"\n // but we have a user-provided \"displayName\"\n // splice it in to make the stack more readable.\n\n\n if (fn.displayName && _frame.includes('')) {\n _frame = _frame.replace('', fn.displayName);\n }\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, _frame);\n }\n } // Return the line we found.\n\n\n return _frame;\n }\n } while (s >= 1 && c >= 0);\n }\n\n break;\n }\n }\n }\n } finally {\n reentry = false;\n\n {\n ReactCurrentDispatcher$1.current = previousDispatcher;\n reenableLogs();\n }\n\n Error.prepareStackTrace = previousPrepareStackTrace;\n } // Fallback to just using the name if we couldn't make it throw.\n\n\n var name = fn ? fn.displayName || fn.name : '';\n var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, syntheticFrame);\n }\n }\n\n return syntheticFrame;\n}\nfunction describeFunctionComponentFrame(fn, source, ownerFn) {\n {\n return describeNativeComponentFrame(fn, false);\n }\n}\n\nfunction shouldConstruct(Component) {\n var prototype = Component.prototype;\n return !!(prototype && prototype.isReactComponent);\n}\n\nfunction describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {\n\n if (type == null) {\n return '';\n }\n\n if (typeof type === 'function') {\n {\n return describeNativeComponentFrame(type, shouldConstruct(type));\n }\n }\n\n if (typeof type === 'string') {\n return describeBuiltInComponentFrame(type);\n }\n\n switch (type) {\n case REACT_SUSPENSE_TYPE:\n return describeBuiltInComponentFrame('Suspense');\n\n case REACT_SUSPENSE_LIST_TYPE:\n return describeBuiltInComponentFrame('SuspenseList');\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_FORWARD_REF_TYPE:\n return describeFunctionComponentFrame(type.render);\n\n case REACT_MEMO_TYPE:\n // Memo may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n // Lazy may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);\n } catch (x) {}\n }\n }\n }\n\n return '';\n}\n\nvar loggedTypeFailures = {};\nvar ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement(element) {\n {\n if (element) {\n var owner = element._owner;\n var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n ReactDebugCurrentFrame$1.setExtraStackFrame(stack);\n } else {\n ReactDebugCurrentFrame$1.setExtraStackFrame(null);\n }\n }\n}\n\nfunction checkPropTypes(typeSpecs, values, location, componentName, element) {\n {\n // $FlowFixMe This is okay but Flow doesn't know it.\n var has = Function.call.bind(hasOwnProperty);\n\n for (var typeSpecName in typeSpecs) {\n if (has(typeSpecs, typeSpecName)) {\n var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to\n // fail the render phase where it didn't fail before. So we log it.\n // After these have been cleaned up, we'll let them throw.\n\n try {\n // This is intentionally an invariant that gets caught. It's the same\n // behavior as without this statement except with a better message.\n if (typeof typeSpecs[typeSpecName] !== 'function') {\n // eslint-disable-next-line react-internal/prod-error-codes\n var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');\n err.name = 'Invariant Violation';\n throw err;\n }\n\n error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');\n } catch (ex) {\n error$1 = ex;\n }\n\n if (error$1 && !(error$1 instanceof Error)) {\n setCurrentlyValidatingElement(element);\n\n error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);\n\n setCurrentlyValidatingElement(null);\n }\n\n if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {\n // Only monitor this failure once because there tends to be a lot of the\n // same error.\n loggedTypeFailures[error$1.message] = true;\n setCurrentlyValidatingElement(element);\n\n error('Failed %s type: %s', location, error$1.message);\n\n setCurrentlyValidatingElement(null);\n }\n }\n }\n }\n}\n\nfunction setCurrentlyValidatingElement$1(element) {\n {\n if (element) {\n var owner = element._owner;\n var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n setExtraStackFrame(stack);\n } else {\n setExtraStackFrame(null);\n }\n }\n}\n\nvar propTypesMisspellWarningShown;\n\n{\n propTypesMisspellWarningShown = false;\n}\n\nfunction getDeclarationErrorAddendum() {\n if (ReactCurrentOwner.current) {\n var name = getComponentNameFromType(ReactCurrentOwner.current.type);\n\n if (name) {\n return '\\n\\nCheck the render method of `' + name + '`.';\n }\n }\n\n return '';\n}\n\nfunction getSourceInfoErrorAddendum(source) {\n if (source !== undefined) {\n var fileName = source.fileName.replace(/^.*[\\\\\\/]/, '');\n var lineNumber = source.lineNumber;\n return '\\n\\nCheck your code at ' + fileName + ':' + lineNumber + '.';\n }\n\n return '';\n}\n\nfunction getSourceInfoErrorAddendumForProps(elementProps) {\n if (elementProps !== null && elementProps !== undefined) {\n return getSourceInfoErrorAddendum(elementProps.__source);\n }\n\n return '';\n}\n/**\n * Warn if there's no key explicitly set on dynamic arrays of children or\n * object keys are not valid. This allows us to keep track of children between\n * updates.\n */\n\n\nvar ownerHasKeyUseWarning = {};\n\nfunction getCurrentComponentErrorInfo(parentType) {\n var info = getDeclarationErrorAddendum();\n\n if (!info) {\n var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;\n\n if (parentName) {\n info = \"\\n\\nCheck the top-level render call using <\" + parentName + \">.\";\n }\n }\n\n return info;\n}\n/**\n * Warn if the element doesn't have an explicit key assigned to it.\n * This element is in an array. The array could grow and shrink or be\n * reordered. All children that haven't already been validated are required to\n * have a \"key\" property assigned to it. Error statuses are cached so a warning\n * will only be shown once.\n *\n * @internal\n * @param {ReactElement} element Element that requires a key.\n * @param {*} parentType element's parent's type.\n */\n\n\nfunction validateExplicitKey(element, parentType) {\n if (!element._store || element._store.validated || element.key != null) {\n return;\n }\n\n element._store.validated = true;\n var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);\n\n if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {\n return;\n }\n\n ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a\n // property, it may be the creator of the child that's responsible for\n // assigning it a key.\n\n var childOwner = '';\n\n if (element && element._owner && element._owner !== ReactCurrentOwner.current) {\n // Give the component that originally created this child.\n childOwner = \" It was passed a child from \" + getComponentNameFromType(element._owner.type) + \".\";\n }\n\n {\n setCurrentlyValidatingElement$1(element);\n\n error('Each child in a list should have a unique \"key\" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);\n\n setCurrentlyValidatingElement$1(null);\n }\n}\n/**\n * Ensure that every element either is passed in a static location, in an\n * array with an explicit keys property defined, or in an object literal\n * with valid key property.\n *\n * @internal\n * @param {ReactNode} node Statically passed child of any type.\n * @param {*} parentType node's parent's type.\n */\n\n\nfunction validateChildKeys(node, parentType) {\n if (typeof node !== 'object') {\n return;\n }\n\n if (isArray(node)) {\n for (var i = 0; i < node.length; i++) {\n var child = node[i];\n\n if (isValidElement(child)) {\n validateExplicitKey(child, parentType);\n }\n }\n } else if (isValidElement(node)) {\n // This element was passed in a valid location.\n if (node._store) {\n node._store.validated = true;\n }\n } else if (node) {\n var iteratorFn = getIteratorFn(node);\n\n if (typeof iteratorFn === 'function') {\n // Entry iterators used to provide implicit keys,\n // but now we print a separate warning for them later.\n if (iteratorFn !== node.entries) {\n var iterator = iteratorFn.call(node);\n var step;\n\n while (!(step = iterator.next()).done) {\n if (isValidElement(step.value)) {\n validateExplicitKey(step.value, parentType);\n }\n }\n }\n }\n }\n}\n/**\n * Given an element, validate that its props follow the propTypes definition,\n * provided by the type.\n *\n * @param {ReactElement} element\n */\n\n\nfunction validatePropTypes(element) {\n {\n var type = element.type;\n\n if (type === null || type === undefined || typeof type === 'string') {\n return;\n }\n\n var propTypes;\n\n if (typeof type === 'function') {\n propTypes = type.propTypes;\n } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.\n // Inner props are checked in the reconciler.\n type.$$typeof === REACT_MEMO_TYPE)) {\n propTypes = type.propTypes;\n } else {\n return;\n }\n\n if (propTypes) {\n // Intentionally inside to avoid triggering lazy initializers:\n var name = getComponentNameFromType(type);\n checkPropTypes(propTypes, element.props, 'prop', name, element);\n } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {\n propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:\n\n var _name = getComponentNameFromType(type);\n\n error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');\n }\n\n if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {\n error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');\n }\n }\n}\n/**\n * Given a fragment, validate that it can only be provided with fragment props\n * @param {ReactElement} fragment\n */\n\n\nfunction validateFragmentProps(fragment) {\n {\n var keys = Object.keys(fragment.props);\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n\n if (key !== 'children' && key !== 'key') {\n setCurrentlyValidatingElement$1(fragment);\n\n error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);\n\n setCurrentlyValidatingElement$1(null);\n break;\n }\n }\n\n if (fragment.ref !== null) {\n setCurrentlyValidatingElement$1(fragment);\n\n error('Invalid attribute `ref` supplied to `React.Fragment`.');\n\n setCurrentlyValidatingElement$1(null);\n }\n }\n}\nfunction createElementWithValidation(type, props, children) {\n var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to\n // succeed and there will likely be errors in render.\n\n if (!validType) {\n var info = '';\n\n if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {\n info += ' You likely forgot to export your component from the file ' + \"it's defined in, or you might have mixed up default and named imports.\";\n }\n\n var sourceInfo = getSourceInfoErrorAddendumForProps(props);\n\n if (sourceInfo) {\n info += sourceInfo;\n } else {\n info += getDeclarationErrorAddendum();\n }\n\n var typeString;\n\n if (type === null) {\n typeString = 'null';\n } else if (isArray(type)) {\n typeString = 'array';\n } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {\n typeString = \"<\" + (getComponentNameFromType(type.type) || 'Unknown') + \" />\";\n info = ' Did you accidentally export a JSX literal instead of a component?';\n } else {\n typeString = typeof type;\n }\n\n {\n error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);\n }\n }\n\n var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.\n // TODO: Drop this when these are no longer allowed as the type argument.\n\n if (element == null) {\n return element;\n } // Skip key warning if the type isn't valid since our key validation logic\n // doesn't expect a non-string/function type and can throw confusing errors.\n // We don't want exception behavior to differ between dev and prod.\n // (Rendering will throw with a helpful message and as soon as the type is\n // fixed, the key warnings will appear.)\n\n\n if (validType) {\n for (var i = 2; i < arguments.length; i++) {\n validateChildKeys(arguments[i], type);\n }\n }\n\n if (type === REACT_FRAGMENT_TYPE) {\n validateFragmentProps(element);\n } else {\n validatePropTypes(element);\n }\n\n return element;\n}\nvar didWarnAboutDeprecatedCreateFactory = false;\nfunction createFactoryWithValidation(type) {\n var validatedFactory = createElementWithValidation.bind(null, type);\n validatedFactory.type = type;\n\n {\n if (!didWarnAboutDeprecatedCreateFactory) {\n didWarnAboutDeprecatedCreateFactory = true;\n\n warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');\n } // Legacy hook: remove it\n\n\n Object.defineProperty(validatedFactory, 'type', {\n enumerable: false,\n get: function () {\n warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');\n\n Object.defineProperty(this, 'type', {\n value: type\n });\n return type;\n }\n });\n }\n\n return validatedFactory;\n}\nfunction cloneElementWithValidation(element, props, children) {\n var newElement = cloneElement.apply(this, arguments);\n\n for (var i = 2; i < arguments.length; i++) {\n validateChildKeys(arguments[i], newElement.type);\n }\n\n validatePropTypes(newElement);\n return newElement;\n}\n\nfunction startTransition(scope, options) {\n var prevTransition = ReactCurrentBatchConfig.transition;\n ReactCurrentBatchConfig.transition = {};\n var currentTransition = ReactCurrentBatchConfig.transition;\n\n {\n ReactCurrentBatchConfig.transition._updatedFibers = new Set();\n }\n\n try {\n scope();\n } finally {\n ReactCurrentBatchConfig.transition = prevTransition;\n\n {\n if (prevTransition === null && currentTransition._updatedFibers) {\n var updatedFibersCount = currentTransition._updatedFibers.size;\n\n if (updatedFibersCount > 10) {\n warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.');\n }\n\n currentTransition._updatedFibers.clear();\n }\n }\n }\n}\n\nvar didWarnAboutMessageChannel = false;\nvar enqueueTaskImpl = null;\nfunction enqueueTask(task) {\n if (enqueueTaskImpl === null) {\n try {\n // read require off the module object to get around the bundlers.\n // we don't want them to detect a require and bundle a Node polyfill.\n var requireString = ('require' + Math.random()).slice(0, 7);\n var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's\n // version of setImmediate, bypassing fake timers if any.\n\n enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate;\n } catch (_err) {\n // we're in a browser\n // we can't use regular timers because they may still be faked\n // so we try MessageChannel+postMessage instead\n enqueueTaskImpl = function (callback) {\n {\n if (didWarnAboutMessageChannel === false) {\n didWarnAboutMessageChannel = true;\n\n if (typeof MessageChannel === 'undefined') {\n error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.');\n }\n }\n }\n\n var channel = new MessageChannel();\n channel.port1.onmessage = callback;\n channel.port2.postMessage(undefined);\n };\n }\n }\n\n return enqueueTaskImpl(task);\n}\n\nvar actScopeDepth = 0;\nvar didWarnNoAwaitAct = false;\nfunction act(callback) {\n {\n // `act` calls can be nested, so we track the depth. This represents the\n // number of `act` scopes on the stack.\n var prevActScopeDepth = actScopeDepth;\n actScopeDepth++;\n\n if (ReactCurrentActQueue.current === null) {\n // This is the outermost `act` scope. Initialize the queue. The reconciler\n // will detect the queue and use it instead of Scheduler.\n ReactCurrentActQueue.current = [];\n }\n\n var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy;\n var result;\n\n try {\n // Used to reproduce behavior of `batchedUpdates` in legacy mode. Only\n // set to `true` while the given callback is executed, not for updates\n // triggered during an async event, because this is how the legacy\n // implementation of `act` behaved.\n ReactCurrentActQueue.isBatchingLegacy = true;\n result = callback(); // Replicate behavior of original `act` implementation in legacy mode,\n // which flushed updates immediately after the scope function exits, even\n // if it's an async function.\n\n if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) {\n var queue = ReactCurrentActQueue.current;\n\n if (queue !== null) {\n ReactCurrentActQueue.didScheduleLegacyUpdate = false;\n flushActQueue(queue);\n }\n }\n } catch (error) {\n popActScope(prevActScopeDepth);\n throw error;\n } finally {\n ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy;\n }\n\n if (result !== null && typeof result === 'object' && typeof result.then === 'function') {\n var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait\n // for it to resolve before exiting the current scope.\n\n var wasAwaited = false;\n var thenable = {\n then: function (resolve, reject) {\n wasAwaited = true;\n thenableResult.then(function (returnValue) {\n popActScope(prevActScopeDepth);\n\n if (actScopeDepth === 0) {\n // We've exited the outermost act scope. Recursively flush the\n // queue until there's no remaining work.\n recursivelyFlushAsyncActWork(returnValue, resolve, reject);\n } else {\n resolve(returnValue);\n }\n }, function (error) {\n // The callback threw an error.\n popActScope(prevActScopeDepth);\n reject(error);\n });\n }\n };\n\n {\n if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') {\n // eslint-disable-next-line no-undef\n Promise.resolve().then(function () {}).then(function () {\n if (!wasAwaited) {\n didWarnNoAwaitAct = true;\n\n error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);');\n }\n });\n }\n }\n\n return thenable;\n } else {\n var returnValue = result; // The callback is not an async function. Exit the current scope\n // immediately, without awaiting.\n\n popActScope(prevActScopeDepth);\n\n if (actScopeDepth === 0) {\n // Exiting the outermost act scope. Flush the queue.\n var _queue = ReactCurrentActQueue.current;\n\n if (_queue !== null) {\n flushActQueue(_queue);\n ReactCurrentActQueue.current = null;\n } // Return a thenable. If the user awaits it, we'll flush again in\n // case additional work was scheduled by a microtask.\n\n\n var _thenable = {\n then: function (resolve, reject) {\n // Confirm we haven't re-entered another `act` scope, in case\n // the user does something weird like await the thenable\n // multiple times.\n if (ReactCurrentActQueue.current === null) {\n // Recursively flush the queue until there's no remaining work.\n ReactCurrentActQueue.current = [];\n recursivelyFlushAsyncActWork(returnValue, resolve, reject);\n } else {\n resolve(returnValue);\n }\n }\n };\n return _thenable;\n } else {\n // Since we're inside a nested `act` scope, the returned thenable\n // immediately resolves. The outer scope will flush the queue.\n var _thenable2 = {\n then: function (resolve, reject) {\n resolve(returnValue);\n }\n };\n return _thenable2;\n }\n }\n }\n}\n\nfunction popActScope(prevActScopeDepth) {\n {\n if (prevActScopeDepth !== actScopeDepth - 1) {\n error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');\n }\n\n actScopeDepth = prevActScopeDepth;\n }\n}\n\nfunction recursivelyFlushAsyncActWork(returnValue, resolve, reject) {\n {\n var queue = ReactCurrentActQueue.current;\n\n if (queue !== null) {\n try {\n flushActQueue(queue);\n enqueueTask(function () {\n if (queue.length === 0) {\n // No additional work was scheduled. Finish.\n ReactCurrentActQueue.current = null;\n resolve(returnValue);\n } else {\n // Keep flushing work until there's none left.\n recursivelyFlushAsyncActWork(returnValue, resolve, reject);\n }\n });\n } catch (error) {\n reject(error);\n }\n } else {\n resolve(returnValue);\n }\n }\n}\n\nvar isFlushing = false;\n\nfunction flushActQueue(queue) {\n {\n if (!isFlushing) {\n // Prevent re-entrance.\n isFlushing = true;\n var i = 0;\n\n try {\n for (; i < queue.length; i++) {\n var callback = queue[i];\n\n do {\n callback = callback(true);\n } while (callback !== null);\n }\n\n queue.length = 0;\n } catch (error) {\n // If something throws, leave the remaining callbacks on the queue.\n queue = queue.slice(i + 1);\n throw error;\n } finally {\n isFlushing = false;\n }\n }\n }\n}\n\nvar createElement$1 = createElementWithValidation ;\nvar cloneElement$1 = cloneElementWithValidation ;\nvar createFactory = createFactoryWithValidation ;\nvar Children = {\n map: mapChildren,\n forEach: forEachChildren,\n count: countChildren,\n toArray: toArray,\n only: onlyChild\n};\n\nexports.Children = Children;\nexports.Component = Component;\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.Profiler = REACT_PROFILER_TYPE;\nexports.PureComponent = PureComponent;\nexports.StrictMode = REACT_STRICT_MODE_TYPE;\nexports.Suspense = REACT_SUSPENSE_TYPE;\nexports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals;\nexports.act = act;\nexports.cloneElement = cloneElement$1;\nexports.createContext = createContext;\nexports.createElement = createElement$1;\nexports.createFactory = createFactory;\nexports.createRef = createRef;\nexports.forwardRef = forwardRef;\nexports.isValidElement = isValidElement;\nexports.lazy = lazy;\nexports.memo = memo;\nexports.startTransition = startTransition;\nexports.unstable_act = act;\nexports.useCallback = useCallback;\nexports.useContext = useContext;\nexports.useDebugValue = useDebugValue;\nexports.useDeferredValue = useDeferredValue;\nexports.useEffect = useEffect;\nexports.useId = useId;\nexports.useImperativeHandle = useImperativeHandle;\nexports.useInsertionEffect = useInsertionEffect;\nexports.useLayoutEffect = useLayoutEffect;\nexports.useMemo = useMemo;\nexports.useReducer = useReducer;\nexports.useRef = useRef;\nexports.useState = useState;\nexports.useSyncExternalStore = useSyncExternalStore;\nexports.useTransition = useTransition;\nexports.version = ReactVersion;\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());\n}\n \n })();\n}\n", "'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react.production.min.js');\n} else {\n module.exports = require('./cjs/react.development.js');\n}\n", "/**\n * @license React\n * scheduler.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n\n 'use strict';\n\n/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());\n}\n var enableSchedulerDebugging = false;\nvar enableProfiling = false;\nvar frameYieldMs = 5;\n\nfunction push(heap, node) {\n var index = heap.length;\n heap.push(node);\n siftUp(heap, node, index);\n}\nfunction peek(heap) {\n return heap.length === 0 ? null : heap[0];\n}\nfunction pop(heap) {\n if (heap.length === 0) {\n return null;\n }\n\n var first = heap[0];\n var last = heap.pop();\n\n if (last !== first) {\n heap[0] = last;\n siftDown(heap, last, 0);\n }\n\n return first;\n}\n\nfunction siftUp(heap, node, i) {\n var index = i;\n\n while (index > 0) {\n var parentIndex = index - 1 >>> 1;\n var parent = heap[parentIndex];\n\n if (compare(parent, node) > 0) {\n // The parent is larger. Swap positions.\n heap[parentIndex] = node;\n heap[index] = parent;\n index = parentIndex;\n } else {\n // The parent is smaller. Exit.\n return;\n }\n }\n}\n\nfunction siftDown(heap, node, i) {\n var index = i;\n var length = heap.length;\n var halfLength = length >>> 1;\n\n while (index < halfLength) {\n var leftIndex = (index + 1) * 2 - 1;\n var left = heap[leftIndex];\n var rightIndex = leftIndex + 1;\n var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.\n\n if (compare(left, node) < 0) {\n if (rightIndex < length && compare(right, left) < 0) {\n heap[index] = right;\n heap[rightIndex] = node;\n index = rightIndex;\n } else {\n heap[index] = left;\n heap[leftIndex] = node;\n index = leftIndex;\n }\n } else if (rightIndex < length && compare(right, node) < 0) {\n heap[index] = right;\n heap[rightIndex] = node;\n index = rightIndex;\n } else {\n // Neither child is smaller. Exit.\n return;\n }\n }\n}\n\nfunction compare(a, b) {\n // Compare sort index first, then task id.\n var diff = a.sortIndex - b.sortIndex;\n return diff !== 0 ? diff : a.id - b.id;\n}\n\n// TODO: Use symbols?\nvar ImmediatePriority = 1;\nvar UserBlockingPriority = 2;\nvar NormalPriority = 3;\nvar LowPriority = 4;\nvar IdlePriority = 5;\n\nfunction markTaskErrored(task, ms) {\n}\n\n/* eslint-disable no-var */\n\nvar hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function';\n\nif (hasPerformanceNow) {\n var localPerformance = performance;\n\n exports.unstable_now = function () {\n return localPerformance.now();\n };\n} else {\n var localDate = Date;\n var initialTime = localDate.now();\n\n exports.unstable_now = function () {\n return localDate.now() - initialTime;\n };\n} // Max 31 bit integer. The max integer size in V8 for 32-bit systems.\n// Math.pow(2, 30) - 1\n// 0b111111111111111111111111111111\n\n\nvar maxSigned31BitInt = 1073741823; // Times out immediately\n\nvar IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out\n\nvar USER_BLOCKING_PRIORITY_TIMEOUT = 250;\nvar NORMAL_PRIORITY_TIMEOUT = 5000;\nvar LOW_PRIORITY_TIMEOUT = 10000; // Never times out\n\nvar IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap\n\nvar taskQueue = [];\nvar timerQueue = []; // Incrementing id counter. Used to maintain insertion order.\n\nvar taskIdCounter = 1; // Pausing the scheduler is useful for debugging.\nvar currentTask = null;\nvar currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance.\n\nvar isPerformingWork = false;\nvar isHostCallbackScheduled = false;\nvar isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them.\n\nvar localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null;\nvar localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null;\nvar localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom\n\nvar isInputPending = typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null;\n\nfunction advanceTimers(currentTime) {\n // Check for tasks that are no longer delayed and add them to the queue.\n var timer = peek(timerQueue);\n\n while (timer !== null) {\n if (timer.callback === null) {\n // Timer was cancelled.\n pop(timerQueue);\n } else if (timer.startTime <= currentTime) {\n // Timer fired. Transfer to the task queue.\n pop(timerQueue);\n timer.sortIndex = timer.expirationTime;\n push(taskQueue, timer);\n } else {\n // Remaining timers are pending.\n return;\n }\n\n timer = peek(timerQueue);\n }\n}\n\nfunction handleTimeout(currentTime) {\n isHostTimeoutScheduled = false;\n advanceTimers(currentTime);\n\n if (!isHostCallbackScheduled) {\n if (peek(taskQueue) !== null) {\n isHostCallbackScheduled = true;\n requestHostCallback(flushWork);\n } else {\n var firstTimer = peek(timerQueue);\n\n if (firstTimer !== null) {\n requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);\n }\n }\n }\n}\n\nfunction flushWork(hasTimeRemaining, initialTime) {\n\n\n isHostCallbackScheduled = false;\n\n if (isHostTimeoutScheduled) {\n // We scheduled a timeout but it's no longer needed. Cancel it.\n isHostTimeoutScheduled = false;\n cancelHostTimeout();\n }\n\n isPerformingWork = true;\n var previousPriorityLevel = currentPriorityLevel;\n\n try {\n if (enableProfiling) {\n try {\n return workLoop(hasTimeRemaining, initialTime);\n } catch (error) {\n if (currentTask !== null) {\n var currentTime = exports.unstable_now();\n markTaskErrored(currentTask, currentTime);\n currentTask.isQueued = false;\n }\n\n throw error;\n }\n } else {\n // No catch in prod code path.\n return workLoop(hasTimeRemaining, initialTime);\n }\n } finally {\n currentTask = null;\n currentPriorityLevel = previousPriorityLevel;\n isPerformingWork = false;\n }\n}\n\nfunction workLoop(hasTimeRemaining, initialTime) {\n var currentTime = initialTime;\n advanceTimers(currentTime);\n currentTask = peek(taskQueue);\n\n while (currentTask !== null && !(enableSchedulerDebugging )) {\n if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {\n // This currentTask hasn't expired, and we've reached the deadline.\n break;\n }\n\n var callback = currentTask.callback;\n\n if (typeof callback === 'function') {\n currentTask.callback = null;\n currentPriorityLevel = currentTask.priorityLevel;\n var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;\n\n var continuationCallback = callback(didUserCallbackTimeout);\n currentTime = exports.unstable_now();\n\n if (typeof continuationCallback === 'function') {\n currentTask.callback = continuationCallback;\n } else {\n\n if (currentTask === peek(taskQueue)) {\n pop(taskQueue);\n }\n }\n\n advanceTimers(currentTime);\n } else {\n pop(taskQueue);\n }\n\n currentTask = peek(taskQueue);\n } // Return whether there's additional work\n\n\n if (currentTask !== null) {\n return true;\n } else {\n var firstTimer = peek(timerQueue);\n\n if (firstTimer !== null) {\n requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);\n }\n\n return false;\n }\n}\n\nfunction unstable_runWithPriority(priorityLevel, eventHandler) {\n switch (priorityLevel) {\n case ImmediatePriority:\n case UserBlockingPriority:\n case NormalPriority:\n case LowPriority:\n case IdlePriority:\n break;\n\n default:\n priorityLevel = NormalPriority;\n }\n\n var previousPriorityLevel = currentPriorityLevel;\n currentPriorityLevel = priorityLevel;\n\n try {\n return eventHandler();\n } finally {\n currentPriorityLevel = previousPriorityLevel;\n }\n}\n\nfunction unstable_next(eventHandler) {\n var priorityLevel;\n\n switch (currentPriorityLevel) {\n case ImmediatePriority:\n case UserBlockingPriority:\n case NormalPriority:\n // Shift down to normal priority\n priorityLevel = NormalPriority;\n break;\n\n default:\n // Anything lower than normal priority should remain at the current level.\n priorityLevel = currentPriorityLevel;\n break;\n }\n\n var previousPriorityLevel = currentPriorityLevel;\n currentPriorityLevel = priorityLevel;\n\n try {\n return eventHandler();\n } finally {\n currentPriorityLevel = previousPriorityLevel;\n }\n}\n\nfunction unstable_wrapCallback(callback) {\n var parentPriorityLevel = currentPriorityLevel;\n return function () {\n // This is a fork of runWithPriority, inlined for performance.\n var previousPriorityLevel = currentPriorityLevel;\n currentPriorityLevel = parentPriorityLevel;\n\n try {\n return callback.apply(this, arguments);\n } finally {\n currentPriorityLevel = previousPriorityLevel;\n }\n };\n}\n\nfunction unstable_scheduleCallback(priorityLevel, callback, options) {\n var currentTime = exports.unstable_now();\n var startTime;\n\n if (typeof options === 'object' && options !== null) {\n var delay = options.delay;\n\n if (typeof delay === 'number' && delay > 0) {\n startTime = currentTime + delay;\n } else {\n startTime = currentTime;\n }\n } else {\n startTime = currentTime;\n }\n\n var timeout;\n\n switch (priorityLevel) {\n case ImmediatePriority:\n timeout = IMMEDIATE_PRIORITY_TIMEOUT;\n break;\n\n case UserBlockingPriority:\n timeout = USER_BLOCKING_PRIORITY_TIMEOUT;\n break;\n\n case IdlePriority:\n timeout = IDLE_PRIORITY_TIMEOUT;\n break;\n\n case LowPriority:\n timeout = LOW_PRIORITY_TIMEOUT;\n break;\n\n case NormalPriority:\n default:\n timeout = NORMAL_PRIORITY_TIMEOUT;\n break;\n }\n\n var expirationTime = startTime + timeout;\n var newTask = {\n id: taskIdCounter++,\n callback: callback,\n priorityLevel: priorityLevel,\n startTime: startTime,\n expirationTime: expirationTime,\n sortIndex: -1\n };\n\n if (startTime > currentTime) {\n // This is a delayed task.\n newTask.sortIndex = startTime;\n push(timerQueue, newTask);\n\n if (peek(taskQueue) === null && newTask === peek(timerQueue)) {\n // All tasks are delayed, and this is the task with the earliest delay.\n if (isHostTimeoutScheduled) {\n // Cancel an existing timeout.\n cancelHostTimeout();\n } else {\n isHostTimeoutScheduled = true;\n } // Schedule a timeout.\n\n\n requestHostTimeout(handleTimeout, startTime - currentTime);\n }\n } else {\n newTask.sortIndex = expirationTime;\n push(taskQueue, newTask);\n // wait until the next time we yield.\n\n\n if (!isHostCallbackScheduled && !isPerformingWork) {\n isHostCallbackScheduled = true;\n requestHostCallback(flushWork);\n }\n }\n\n return newTask;\n}\n\nfunction unstable_pauseExecution() {\n}\n\nfunction unstable_continueExecution() {\n\n if (!isHostCallbackScheduled && !isPerformingWork) {\n isHostCallbackScheduled = true;\n requestHostCallback(flushWork);\n }\n}\n\nfunction unstable_getFirstCallbackNode() {\n return peek(taskQueue);\n}\n\nfunction unstable_cancelCallback(task) {\n // remove from the queue because you can't remove arbitrary nodes from an\n // array based heap, only the first one.)\n\n\n task.callback = null;\n}\n\nfunction unstable_getCurrentPriorityLevel() {\n return currentPriorityLevel;\n}\n\nvar isMessageLoopRunning = false;\nvar scheduledHostCallback = null;\nvar taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main\n// thread, like user events. By default, it yields multiple times per frame.\n// It does not attempt to align with frame boundaries, since most tasks don't\n// need to be frame aligned; for those that do, use requestAnimationFrame.\n\nvar frameInterval = frameYieldMs;\nvar startTime = -1;\n\nfunction shouldYieldToHost() {\n var timeElapsed = exports.unstable_now() - startTime;\n\n if (timeElapsed < frameInterval) {\n // The main thread has only been blocked for a really short amount of time;\n // smaller than a single frame. Don't yield yet.\n return false;\n } // The main thread has been blocked for a non-negligible amount of time. We\n\n\n return true;\n}\n\nfunction requestPaint() {\n\n}\n\nfunction forceFrameRate(fps) {\n if (fps < 0 || fps > 125) {\n // Using console['error'] to evade Babel and ESLint\n console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported');\n return;\n }\n\n if (fps > 0) {\n frameInterval = Math.floor(1000 / fps);\n } else {\n // reset the framerate\n frameInterval = frameYieldMs;\n }\n}\n\nvar performWorkUntilDeadline = function () {\n if (scheduledHostCallback !== null) {\n var currentTime = exports.unstable_now(); // Keep track of the start time so we can measure how long the main thread\n // has been blocked.\n\n startTime = currentTime;\n var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the\n // error can be observed.\n //\n // Intentionally not using a try-catch, since that makes some debugging\n // techniques harder. Instead, if `scheduledHostCallback` errors, then\n // `hasMoreWork` will remain true, and we'll continue the work loop.\n\n var hasMoreWork = true;\n\n try {\n hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);\n } finally {\n if (hasMoreWork) {\n // If there's more work, schedule the next message event at the end\n // of the preceding one.\n schedulePerformWorkUntilDeadline();\n } else {\n isMessageLoopRunning = false;\n scheduledHostCallback = null;\n }\n }\n } else {\n isMessageLoopRunning = false;\n } // Yielding to the browser will give it a chance to paint, so we can\n};\n\nvar schedulePerformWorkUntilDeadline;\n\nif (typeof localSetImmediate === 'function') {\n // Node.js and old IE.\n // There's a few reasons for why we prefer setImmediate.\n //\n // Unlike MessageChannel, it doesn't prevent a Node.js process from exiting.\n // (Even though this is a DOM fork of the Scheduler, you could get here\n // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.)\n // https://github.com/facebook/react/issues/20756\n //\n // But also, it runs earlier which is the semantic we want.\n // If other browsers ever implement it, it's better to use it.\n // Although both of these would be inferior to native scheduling.\n schedulePerformWorkUntilDeadline = function () {\n localSetImmediate(performWorkUntilDeadline);\n };\n} else if (typeof MessageChannel !== 'undefined') {\n // DOM and Worker environments.\n // We prefer MessageChannel because of the 4ms setTimeout clamping.\n var channel = new MessageChannel();\n var port = channel.port2;\n channel.port1.onmessage = performWorkUntilDeadline;\n\n schedulePerformWorkUntilDeadline = function () {\n port.postMessage(null);\n };\n} else {\n // We should only fallback here in non-browser environments.\n schedulePerformWorkUntilDeadline = function () {\n localSetTimeout(performWorkUntilDeadline, 0);\n };\n}\n\nfunction requestHostCallback(callback) {\n scheduledHostCallback = callback;\n\n if (!isMessageLoopRunning) {\n isMessageLoopRunning = true;\n schedulePerformWorkUntilDeadline();\n }\n}\n\nfunction requestHostTimeout(callback, ms) {\n taskTimeoutID = localSetTimeout(function () {\n callback(exports.unstable_now());\n }, ms);\n}\n\nfunction cancelHostTimeout() {\n localClearTimeout(taskTimeoutID);\n taskTimeoutID = -1;\n}\n\nvar unstable_requestPaint = requestPaint;\nvar unstable_Profiling = null;\n\nexports.unstable_IdlePriority = IdlePriority;\nexports.unstable_ImmediatePriority = ImmediatePriority;\nexports.unstable_LowPriority = LowPriority;\nexports.unstable_NormalPriority = NormalPriority;\nexports.unstable_Profiling = unstable_Profiling;\nexports.unstable_UserBlockingPriority = UserBlockingPriority;\nexports.unstable_cancelCallback = unstable_cancelCallback;\nexports.unstable_continueExecution = unstable_continueExecution;\nexports.unstable_forceFrameRate = forceFrameRate;\nexports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;\nexports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode;\nexports.unstable_next = unstable_next;\nexports.unstable_pauseExecution = unstable_pauseExecution;\nexports.unstable_requestPaint = unstable_requestPaint;\nexports.unstable_runWithPriority = unstable_runWithPriority;\nexports.unstable_scheduleCallback = unstable_scheduleCallback;\nexports.unstable_shouldYield = shouldYieldToHost;\nexports.unstable_wrapCallback = unstable_wrapCallback;\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());\n}\n \n })();\n}\n", "'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n", "/**\n * @license React\n * react-dom.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n\n 'use strict';\n\n/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());\n}\n var React = require('react');\nvar Scheduler = require('scheduler');\n\nvar ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n\nvar suppressWarning = false;\nfunction setSuppressWarning(newSuppressWarning) {\n {\n suppressWarning = newSuppressWarning;\n }\n} // In DEV, calls to console.warn and console.error get replaced\n// by calls to these methods by a Babel plugin.\n//\n// In PROD (or in packages without access to React internals),\n// they are left as they are instead.\n\nfunction warn(format) {\n {\n if (!suppressWarning) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n printWarning('warn', format, args);\n }\n }\n}\nfunction error(format) {\n {\n if (!suppressWarning) {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n printWarning('error', format, args);\n }\n }\n}\n\nfunction printWarning(level, format, args) {\n // When changing this logic, you might want to also\n // update consoleWithStackDev.www.js as well.\n {\n var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n if (stack !== '') {\n format += '%s';\n args = args.concat([stack]);\n } // eslint-disable-next-line react-internal/safe-string-coercion\n\n\n var argsWithFormat = args.map(function (item) {\n return String(item);\n }); // Careful: RN currently depends on this prefix\n\n argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n // breaks IE9: https://github.com/facebook/react/issues/13610\n // eslint-disable-next-line react-internal/no-production-logging\n\n Function.prototype.apply.call(console[level], console, argsWithFormat);\n }\n}\n\nvar FunctionComponent = 0;\nvar ClassComponent = 1;\nvar IndeterminateComponent = 2; // Before we know whether it is function or class\n\nvar HostRoot = 3; // Root of a host tree. Could be nested inside another node.\n\nvar HostPortal = 4; // A subtree. Could be an entry point to a different renderer.\n\nvar HostComponent = 5;\nvar HostText = 6;\nvar Fragment = 7;\nvar Mode = 8;\nvar ContextConsumer = 9;\nvar ContextProvider = 10;\nvar ForwardRef = 11;\nvar Profiler = 12;\nvar SuspenseComponent = 13;\nvar MemoComponent = 14;\nvar SimpleMemoComponent = 15;\nvar LazyComponent = 16;\nvar IncompleteClassComponent = 17;\nvar DehydratedFragment = 18;\nvar SuspenseListComponent = 19;\nvar ScopeComponent = 21;\nvar OffscreenComponent = 22;\nvar LegacyHiddenComponent = 23;\nvar CacheComponent = 24;\nvar TracingMarkerComponent = 25;\n\n// -----------------------------------------------------------------------------\n\nvar enableClientRenderFallbackOnTextMismatch = true; // TODO: Need to review this code one more time before landing\n// the react-reconciler package.\n\nvar enableNewReconciler = false; // Support legacy Primer support on internal FB www\n\nvar enableLazyContextPropagation = false; // FB-only usage. The new API has different semantics.\n\nvar enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber\n\nvar enableSuspenseAvoidThisFallback = false; // Enables unstable_avoidThisFallback feature in Fizz\n// React DOM Chopping Block\n//\n// Similar to main Chopping Block but only flags related to React DOM. These are\n// grouped because we will likely batch all of them into a single major release.\n// -----------------------------------------------------------------------------\n// Disable support for comment nodes as React DOM containers. Already disabled\n// in open source, but www codebase still relies on it. Need to remove.\n\nvar disableCommentsAsDOMContainers = true; // Disable javascript: URL strings in href for XSS protection.\n// and client rendering, mostly to allow JSX attributes to apply to the custom\n// element's object properties instead of only HTML attributes.\n// https://github.com/facebook/react/issues/11347\n\nvar enableCustomElementPropertySupport = false; // Disables children for \n \n\n
\n \n \n
\n\n
\n \n {isSubmitting ? (\n
\n \n \n \n \n Processing...\n
\n ) : (\n 'Complete Registration'\n )}\n \n
\n \n \n );\n};\n\nexport default CompanyOnboardingForm;", "import React, { useState, useContext, useEffect } from 'react';\nimport { useNavigate, Routes, Route } from 'react-router-dom';\nimport Overview from './Overview';\nimport Prompts from './Prompts';\nimport CompetitorAnalysis from './CompetitorAnalysis';\nimport Optimization from './Optimization';\n\n// Main ProjectDashboard Component\nconst Dashboard = () => {\n const [activeTab, setActiveTab] = useState('overview');\n const navigate = useNavigate();\n\n // Navigation items\n const navItems = [\n { id: 'overview', label: 'Overview', icon: 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6' },\n { id: 'prompts', label: 'Prompts', icon: 'M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9a2 2 0 00-2-2h-2m-4-3H9M7 16h6M7 8h6v4H7V8z' },\n { id: 'competitor-analysis', label: 'Competitor Analysis', icon: 'M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z' },\n { id: 'optimization', label: 'Optimization', icon: 'M13 10V3L4 14h7v7l9-11h-7z' },\n ];\n\n // Handle tab changes\n const handleTabChange = (tabId) => {\n setActiveTab(tabId);\n navigate(`/dashboard/${tabId}`);\n };\n\n // Render content based on active tab\n const renderContent = () => {\n switch (activeTab) {\n case 'overview':\n return ;\n case 'prompts':\n return ;\n case 'competitor-analysis':\n return ;\n case 'optimization':\n return ;\n default:\n return ;\n }\n };\n\n return (\n
\n {/* Sidebar */}\n
\n
\n

LoveItAI

\n

Dashboard

\n
\n\n \n
\n\n {/* Main Content */}\n
\n {renderContent()}\n
\n\n {/*/!* Routes for direct URL access *!/*/}\n {/**/}\n {/* } />*/}\n {/* } />*/}\n {/* } />*/}\n {/* } />*/}\n {/* } />*/}\n {/**/}\n
\n );\n};\n\nexport default Dashboard;", "import React from 'react';\nimport { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, ReferenceLine } from 'recharts';\n\nconst Overview = () => {\n // Data for Nike - full year ending in March with upward trend after November\n const nikeData = [\n { month: 'Apr', marketShare: 39, sentiment: 75, queryVolume: 4200 },\n { month: 'May', marketShare: 40, sentiment: 76, queryVolume: 4400 },\n { month: 'Jun', marketShare: 42, sentiment: 78, queryVolume: 4600 },\n { month: 'Jul', marketShare: 41, sentiment: 77, queryVolume: 4500 },\n { month: 'Aug', marketShare: 43, sentiment: 80, queryVolume: 5200 },\n { month: 'Sep', marketShare: 45, sentiment: 82, queryVolume: 5000 },\n { month: 'Oct', marketShare: 44, sentiment: 81, queryVolume: 4700 },\n { month: 'Nov', marketShare: 46, sentiment: 83, queryVolume: 4300, optimization: true },\n { month: 'Dec', marketShare: 48, sentiment: 85, queryVolume: 5200 },\n { month: 'Jan', marketShare: 50, sentiment: 87, queryVolume: 5800 },\n { month: 'Feb', marketShare: 52, sentiment: 89, queryVolume: 6300 },\n { month: 'Mar', marketShare: 54, sentiment: 91, queryVolume: 6800 },\n ];\n\n // Insights derived from ChatGPT user queries about Nike\n const strengths = [\n { title: 'Product Authentication Interest', description: 'High volume of queries about verifying authentic Nike products shows strong brand value' },\n { title: 'Technology Curiosity', description: 'Frequent questions about Nike tech features (Air, React, Flyknit) indicates innovation resonance' },\n { title: 'Limited Edition Appeal', description: 'Significant search volume for release dates and drop information showing collectible demand' }\n ];\n\n const weaknesses = [\n { title: 'Size & Fit Confusion', description: 'Common queries about sizing inconsistencies across different Nike product lines' },\n { title: 'Durability Concerns', description: 'Recurring questions about product longevity, particularly for running and training shoes' },\n { title: 'Sustainability Queries', description: 'Increasing user questions about environmental practices and sustainable materials' }\n ];\n\n // Nike brand color\n const nikeColor = '#ff671f'; // Nike orange\n\n // Custom tooltip component for charts to show optimization information\n const CustomTooltip = ({ active, payload, label }) => {\n if (active && payload && payload.length) {\n const dataPoint = nikeData.find(item => item.month === label);\n return (\n
\n

{label}

\n {payload.map((entry, index) => (\n

\n {entry.name}: {entry.value}\n

\n ))}\n {dataPoint && dataPoint.optimization && (\n
\n

AI-Ready FAQ Implementation

\n

Based on Strategic AI Prompting recommendation

\n
\n )}\n
\n );\n }\n return null;\n };\n\n return (\n
\n

Nike Brand Dashboard

\n\n {/* Primary Section: Strengths and Weaknesses */}\n
\n

LLM User Insights

\n
\n
\n

Positive Engagement Areas

\n
\n {strengths.map((item, index) => (\n
\n
{item.title}
\n

{item.description}

\n
\n ))}\n
\n
\n
\n

Customer Pain Points

\n
\n {weaknesses.map((item, index) => (\n
\n
{item.title}
\n

{item.description}

\n
\n ))}\n
\n
\n
\n
\n\n {/* Secondary Section: Charts */}\n
\n {/* Market Share Chart */}\n
\n

Visibility Score

\n
\n \n \n \n \n \n } />\n \n \n \n \n \n
\n
\n\n {/* Sentiment Score Chart */}\n
\n

User Sentiment Score

\n
\n \n \n \n \n \n } />\n \n \n \n \n \n
\n
\n\n {/* Query Volume Chart */}\n
\n

Gen AI Traffic Volume

\n
\n \n \n \n \n \n } />\n \n \n \n \n \n
\n
\n
\n
\n );\n};\n\nexport default Overview;", "var _excluded = [\"children\", \"width\", \"height\", \"viewBox\", \"className\", \"style\", \"title\", \"desc\"];\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\n/**\n * @fileOverview Surface\n */\nimport React from 'react';\nimport clsx from 'clsx';\nimport { filterProps } from '../util/ReactUtils';\nexport function Surface(props) {\n var children = props.children,\n width = props.width,\n height = props.height,\n viewBox = props.viewBox,\n className = props.className,\n style = props.style,\n title = props.title,\n desc = props.desc,\n others = _objectWithoutProperties(props, _excluded);\n var svgView = viewBox || {\n width: width,\n height: height,\n x: 0,\n y: 0\n };\n var layerClass = clsx('recharts-surface', className);\n return /*#__PURE__*/React.createElement(\"svg\", _extends({}, filterProps(others, true, 'svg'), {\n className: layerClass,\n width: width,\n height: height,\n style: style,\n viewBox: \"\".concat(svgView.x, \" \").concat(svgView.y, \" \").concat(svgView.width, \" \").concat(svgView.height)\n }), /*#__PURE__*/React.createElement(\"title\", null, title), /*#__PURE__*/React.createElement(\"desc\", null, desc), children);\n}", "function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nimport get from 'lodash/get';\nimport isNil from 'lodash/isNil';\nimport isString from 'lodash/isString';\nimport isFunction from 'lodash/isFunction';\nimport isObject from 'lodash/isObject';\nimport { Children, isValidElement } from 'react';\nimport { isFragment } from 'react-is';\nimport { isNumber } from './DataUtils';\nimport { shallowEqual } from './ShallowEqual';\nimport { FilteredElementKeyMap, SVGElementPropKeys, EventKeys } from './types';\nvar REACT_BROWSER_EVENT_MAP = {\n click: 'onClick',\n mousedown: 'onMouseDown',\n mouseup: 'onMouseUp',\n mouseover: 'onMouseOver',\n mousemove: 'onMouseMove',\n mouseout: 'onMouseOut',\n mouseenter: 'onMouseEnter',\n mouseleave: 'onMouseLeave',\n touchcancel: 'onTouchCancel',\n touchend: 'onTouchEnd',\n touchmove: 'onTouchMove',\n touchstart: 'onTouchStart',\n contextmenu: 'onContextMenu',\n dblclick: 'onDoubleClick'\n};\nexport var SCALE_TYPES = ['auto', 'linear', 'pow', 'sqrt', 'log', 'identity', 'time', 'band', 'point', 'ordinal', 'quantile', 'quantize', 'utc', 'sequential', 'threshold'];\nexport var LEGEND_TYPES = ['plainline', 'line', 'square', 'rect', 'circle', 'cross', 'diamond', 'star', 'triangle', 'wye', 'none'];\nexport var TOOLTIP_TYPES = ['none'];\n\n/**\n * Get the display name of a component\n * @param {Object} Comp Specified Component\n * @return {String} Display name of Component\n */\nexport var getDisplayName = function getDisplayName(Comp) {\n if (typeof Comp === 'string') {\n return Comp;\n }\n if (!Comp) {\n return '';\n }\n return Comp.displayName || Comp.name || 'Component';\n};\n\n// `toArray` gets called multiple times during the render\n// so we can memoize last invocation (since reference to `children` is the same)\nvar lastChildren = null;\nvar lastResult = null;\nexport var toArray = function toArray(children) {\n if (children === lastChildren && Array.isArray(lastResult)) {\n return lastResult;\n }\n var result = [];\n Children.forEach(children, function (child) {\n if (isNil(child)) return;\n if (isFragment(child)) {\n result = result.concat(toArray(child.props.children));\n } else {\n // @ts-expect-error this could still be Iterable and TS does not like that\n result.push(child);\n }\n });\n lastResult = result;\n lastChildren = children;\n return result;\n};\n\n/*\n * Find and return all matched children by type.\n * `type` must be a React.ComponentType\n */\nexport function findAllByType(children, type) {\n var result = [];\n var types = [];\n if (Array.isArray(type)) {\n types = type.map(function (t) {\n return getDisplayName(t);\n });\n } else {\n types = [getDisplayName(type)];\n }\n toArray(children).forEach(function (child) {\n var childType = get(child, 'type.displayName') || get(child, 'type.name');\n if (types.indexOf(childType) !== -1) {\n result.push(child);\n }\n });\n return result;\n}\n\n/*\n * Return the first matched child by type, return null otherwise.\n * `type` must be a React.ComponentType\n */\nexport function findChildByType(children, type) {\n var result = findAllByType(children, type);\n return result && result[0];\n}\n\n/*\n * Create a new array of children excluding the ones matched the type\n */\nexport var withoutType = function withoutType(children, type) {\n var newChildren = [];\n var types;\n if (Array.isArray(type)) {\n types = type.map(function (t) {\n return getDisplayName(t);\n });\n } else {\n types = [getDisplayName(type)];\n }\n toArray(children).forEach(function (child) {\n var displayName = get(child, 'type.displayName');\n if (displayName && types.indexOf(displayName) !== -1) {\n return;\n }\n newChildren.push(child);\n });\n return newChildren;\n};\n\n/**\n * validate the width and height props of a chart element\n * @param {Object} el A chart element\n * @return {Boolean} true If the props width and height are number, and greater than 0\n */\nexport var validateWidthHeight = function validateWidthHeight(el) {\n if (!el || !el.props) {\n return false;\n }\n var _el$props = el.props,\n width = _el$props.width,\n height = _el$props.height;\n if (!isNumber(width) || width <= 0 || !isNumber(height) || height <= 0) {\n return false;\n }\n return true;\n};\nvar SVG_TAGS = ['a', 'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animate', 'animateColor', 'animateMotion', 'animateTransform', 'circle', 'clipPath', 'color-profile', 'cursor', 'defs', 'desc', 'ellipse', 'feBlend', 'feColormatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence', 'filter', 'font', 'font-face', 'font-face-format', 'font-face-name', 'font-face-url', 'foreignObject', 'g', 'glyph', 'glyphRef', 'hkern', 'image', 'line', 'lineGradient', 'marker', 'mask', 'metadata', 'missing-glyph', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'script', 'set', 'stop', 'style', 'svg', 'switch', 'symbol', 'text', 'textPath', 'title', 'tref', 'tspan', 'use', 'view', 'vkern'];\nvar isSvgElement = function isSvgElement(child) {\n return child && child.type && isString(child.type) && SVG_TAGS.indexOf(child.type) >= 0;\n};\nexport var hasClipDot = function hasClipDot(dot) {\n return dot && _typeof(dot) === 'object' && 'clipDot' in dot;\n};\n\n/**\n * Checks if the property is valid to spread onto an SVG element or onto a specific component\n * @param {unknown} property property value currently being compared\n * @param {string} key property key currently being compared\n * @param {boolean} includeEvents if events are included in spreadable props\n * @param {boolean} svgElementType checks against map of SVG element types to attributes\n * @returns {boolean} is prop valid\n */\nexport var isValidSpreadableProp = function isValidSpreadableProp(property, key, includeEvents, svgElementType) {\n var _FilteredElementKeyMa;\n /**\n * If the svg element type is explicitly included, check against the filtered element key map\n * to determine if there are attributes that should only exist on that element type.\n * @todo Add an internal cjs version of https://github.com/wooorm/svg-element-attributes for full coverage.\n */\n var matchingElementTypeKeys = (_FilteredElementKeyMa = FilteredElementKeyMap === null || FilteredElementKeyMap === void 0 ? void 0 : FilteredElementKeyMap[svgElementType]) !== null && _FilteredElementKeyMa !== void 0 ? _FilteredElementKeyMa : [];\n return key.startsWith('data-') || !isFunction(property) && (svgElementType && matchingElementTypeKeys.includes(key) || SVGElementPropKeys.includes(key)) || includeEvents && EventKeys.includes(key);\n};\n\n/**\n * Filter all the svg elements of children\n * @param {Array} children The children of a react element\n * @return {Array} All the svg elements\n */\nexport var filterSvgElements = function filterSvgElements(children) {\n var svgElements = [];\n toArray(children).forEach(function (entry) {\n if (isSvgElement(entry)) {\n svgElements.push(entry);\n }\n });\n return svgElements;\n};\nexport var filterProps = function filterProps(props, includeEvents, svgElementType) {\n if (!props || typeof props === 'function' || typeof props === 'boolean') {\n return null;\n }\n var inputProps = props;\n if ( /*#__PURE__*/isValidElement(props)) {\n inputProps = props.props;\n }\n if (!isObject(inputProps)) {\n return null;\n }\n var out = {};\n\n /**\n * Props are blindly spread onto SVG elements. This loop filters out properties that we don't want to spread.\n * Items filtered out are as follows:\n * - functions in properties that are SVG attributes (functions are included when includeEvents is true)\n * - props that are SVG attributes but don't matched the passed svgElementType\n * - any prop that is not in SVGElementPropKeys (or in EventKeys if includeEvents is true)\n */\n Object.keys(inputProps).forEach(function (key) {\n var _inputProps;\n if (isValidSpreadableProp((_inputProps = inputProps) === null || _inputProps === void 0 ? void 0 : _inputProps[key], key, includeEvents, svgElementType)) {\n out[key] = inputProps[key];\n }\n });\n return out;\n};\n\n/**\n * Wether props of children changed\n * @param {Object} nextChildren The latest children\n * @param {Object} prevChildren The prev children\n * @return {Boolean} equal or not\n */\nexport var isChildrenEqual = function isChildrenEqual(nextChildren, prevChildren) {\n if (nextChildren === prevChildren) {\n return true;\n }\n var count = Children.count(nextChildren);\n if (count !== Children.count(prevChildren)) {\n return false;\n }\n if (count === 0) {\n return true;\n }\n if (count === 1) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return isSingleChildEqual(Array.isArray(nextChildren) ? nextChildren[0] : nextChildren, Array.isArray(prevChildren) ? prevChildren[0] : prevChildren);\n }\n for (var i = 0; i < count; i++) {\n var nextChild = nextChildren[i];\n var prevChild = prevChildren[i];\n if (Array.isArray(nextChild) || Array.isArray(prevChild)) {\n if (!isChildrenEqual(nextChild, prevChild)) {\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n } else if (!isSingleChildEqual(nextChild, prevChild)) {\n return false;\n }\n }\n return true;\n};\nexport var isSingleChildEqual = function isSingleChildEqual(nextChild, prevChild) {\n if (isNil(nextChild) && isNil(prevChild)) {\n return true;\n }\n if (!isNil(nextChild) && !isNil(prevChild)) {\n var _ref = nextChild.props || {},\n nextChildren = _ref.children,\n nextProps = _objectWithoutProperties(_ref, _excluded);\n var _ref2 = prevChild.props || {},\n prevChildren = _ref2.children,\n prevProps = _objectWithoutProperties(_ref2, _excluded2);\n if (nextChildren && prevChildren) {\n return shallowEqual(nextProps, prevProps) && isChildrenEqual(nextChildren, prevChildren);\n }\n if (!nextChildren && !prevChildren) {\n return shallowEqual(nextProps, prevProps);\n }\n return false;\n }\n return false;\n};\nexport var renderByOrder = function renderByOrder(children, renderMap) {\n var elements = [];\n var record = {};\n toArray(children).forEach(function (child, index) {\n if (isSvgElement(child)) {\n elements.push(child);\n } else if (child) {\n var displayName = getDisplayName(child.type);\n var _ref3 = renderMap[displayName] || {},\n handler = _ref3.handler,\n once = _ref3.once;\n if (handler && (!once || !record[displayName])) {\n var results = handler(child, displayName, index);\n elements.push(results);\n record[displayName] = true;\n }\n }\n });\n return elements;\n};\nexport var getReactEventByType = function getReactEventByType(e) {\n var type = e && e.type;\n if (type && REACT_BROWSER_EVENT_MAP[type]) {\n return REACT_BROWSER_EVENT_MAP[type];\n }\n return null;\n};\nexport var parseChildIndex = function parseChildIndex(child, children) {\n return toArray(children).indexOf(child);\n};", "import isString from 'lodash/isString';\nimport isNan from 'lodash/isNaN';\nimport get from 'lodash/get';\nimport lodashIsNumber from 'lodash/isNumber';\nimport isNil from 'lodash/isNil';\nexport var mathSign = function mathSign(value) {\n if (value === 0) {\n return 0;\n }\n if (value > 0) {\n return 1;\n }\n return -1;\n};\nexport var isPercent = function isPercent(value) {\n return isString(value) && value.indexOf('%') === value.length - 1;\n};\nexport var isNumber = function isNumber(value) {\n return lodashIsNumber(value) && !isNan(value);\n};\nexport var isNullish = function isNullish(value) {\n return isNil(value);\n};\nexport var isNumOrStr = function isNumOrStr(value) {\n return isNumber(value) || isString(value);\n};\nvar idCounter = 0;\nexport var uniqueId = function uniqueId(prefix) {\n var id = ++idCounter;\n return \"\".concat(prefix || '').concat(id);\n};\n\n/**\n * Get percent value of a total value\n * @param {number|string} percent A percent\n * @param {number} totalValue Total value\n * @param {number} defaultValue The value returned when percent is undefined or invalid\n * @param {boolean} validate If set to be true, the result will be validated\n * @return {number} value\n */\nexport var getPercentValue = function getPercentValue(percent, totalValue) {\n var defaultValue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;\n var validate = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n if (!isNumber(percent) && !isString(percent)) {\n return defaultValue;\n }\n var value;\n if (isPercent(percent)) {\n var index = percent.indexOf('%');\n value = totalValue * parseFloat(percent.slice(0, index)) / 100;\n } else {\n value = +percent;\n }\n if (isNan(value)) {\n value = defaultValue;\n }\n if (validate && value > totalValue) {\n value = totalValue;\n }\n return value;\n};\nexport var getAnyElementOfObject = function getAnyElementOfObject(obj) {\n if (!obj) {\n return null;\n }\n var keys = Object.keys(obj);\n if (keys && keys.length) {\n return obj[keys[0]];\n }\n return null;\n};\nexport var hasDuplicate = function hasDuplicate(ary) {\n if (!Array.isArray(ary)) {\n return false;\n }\n var len = ary.length;\n var cache = {};\n for (var i = 0; i < len; i++) {\n if (!cache[ary[i]]) {\n cache[ary[i]] = true;\n } else {\n return true;\n }\n }\n return false;\n};\n\n/* @todo consider to rename this function into `getInterpolator` */\nexport var interpolateNumber = function interpolateNumber(numberA, numberB) {\n if (isNumber(numberA) && isNumber(numberB)) {\n return function (t) {\n return numberA + t * (numberB - numberA);\n };\n }\n return function () {\n return numberB;\n };\n};\nexport function findEntryInArray(ary, specifiedKey, specifiedValue) {\n if (!ary || !ary.length) {\n return null;\n }\n return ary.find(function (entry) {\n return entry && (typeof specifiedKey === 'function' ? specifiedKey(entry) : get(entry, specifiedKey)) === specifiedValue;\n });\n}\n\n/**\n * The least square linear regression\n * @param {Array} data The array of points\n * @returns {Object} The domain of x, and the parameter of linear function\n */\nexport var getLinearRegression = function getLinearRegression(data) {\n if (!data || !data.length) {\n return null;\n }\n var len = data.length;\n var xsum = 0;\n var ysum = 0;\n var xysum = 0;\n var xxsum = 0;\n var xmin = Infinity;\n var xmax = -Infinity;\n var xcurrent = 0;\n var ycurrent = 0;\n for (var i = 0; i < len; i++) {\n xcurrent = data[i].cx || 0;\n ycurrent = data[i].cy || 0;\n xsum += xcurrent;\n ysum += ycurrent;\n xysum += xcurrent * ycurrent;\n xxsum += xcurrent * xcurrent;\n xmin = Math.min(xmin, xcurrent);\n xmax = Math.max(xmax, xcurrent);\n }\n var a = len * xxsum !== xsum * xsum ? (len * xysum - xsum * ysum) / (len * xxsum - xsum * xsum) : 0;\n return {\n xmin: xmin,\n xmax: xmax,\n a: a,\n b: (ysum - a * xsum) / len\n };\n};\n\n/**\n * Compare values.\n *\n * This function is intended to be passed to `Array.prototype.sort()`. It properly compares generic homogeneous arrays that are either `string[]`,\n * `number[]`, or `Date[]`. When comparing heterogeneous arrays or homogeneous arrays of other types, it will attempt to compare items properly but\n * will fall back to string comparison for mismatched or unsupported types.\n *\n * For some background, `Array.prototype.sort()`'s default comparator coerces each of the array's items into a string and compares the strings. This\n * often leads to undesirable behavior, especially with numerical items.\n *\n * @param {unknown} a The first item to compare\n * @param {unknown} b The second item to compare\n * @return {number} A negative number if a < b, a positive number if a > b, 0 if equal\n */\nexport var compareValues = function compareValues(a, b) {\n if (isNumber(a) && isNumber(b)) {\n return a - b;\n }\n if (isString(a) && isString(b)) {\n return a.localeCompare(b);\n }\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() - b.getTime();\n }\n return String(a).localeCompare(String(b));\n};", "export function shallowEqual(a, b) {\n /* eslint-disable no-restricted-syntax */\n for (var key in a) {\n if ({}.hasOwnProperty.call(a, key) && (!{}.hasOwnProperty.call(b, key) || a[key] !== b[key])) {\n return false;\n }\n }\n for (var _key in b) {\n if ({}.hasOwnProperty.call(b, _key) && !{}.hasOwnProperty.call(a, _key)) {\n return false;\n }\n }\n return true;\n}", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nimport { isValidElement } from 'react';\nimport isObject from 'lodash/isObject';\n\n/**\n * Determines how values are stacked:\n *\n * - `none` is the default, it adds values on top of each other. No smarts. Negative values will overlap.\n * - `expand` make it so that the values always add up to 1 - so the chart will look like a rectangle.\n * - `wiggle` and `silhouette` tries to keep the chart centered.\n * - `sign` stacks positive values above zero and negative values below zero. Similar to `none` but handles negatives.\n * - `positive` ignores all negative values, and then behaves like \\`none\\`.\n *\n * Also see https://d3js.org/d3-shape/stack#stack-offsets\n * (note that the `diverging` offset in d3 is named `sign` in recharts)\n */\n\n//\n// Event Handler Types -- Copied from @types/react/index.d.ts and adapted for Props.\n//\n\nvar SVGContainerPropKeys = ['viewBox', 'children'];\nexport var SVGElementPropKeys = ['aria-activedescendant', 'aria-atomic', 'aria-autocomplete', 'aria-busy', 'aria-checked', 'aria-colcount', 'aria-colindex', 'aria-colspan', 'aria-controls', 'aria-current', 'aria-describedby', 'aria-details', 'aria-disabled', 'aria-errormessage', 'aria-expanded', 'aria-flowto', 'aria-haspopup', 'aria-hidden', 'aria-invalid', 'aria-keyshortcuts', 'aria-label', 'aria-labelledby', 'aria-level', 'aria-live', 'aria-modal', 'aria-multiline', 'aria-multiselectable', 'aria-orientation', 'aria-owns', 'aria-placeholder', 'aria-posinset', 'aria-pressed', 'aria-readonly', 'aria-relevant', 'aria-required', 'aria-roledescription', 'aria-rowcount', 'aria-rowindex', 'aria-rowspan', 'aria-selected', 'aria-setsize', 'aria-sort', 'aria-valuemax', 'aria-valuemin', 'aria-valuenow', 'aria-valuetext', 'className', 'color', 'height', 'id', 'lang', 'max', 'media', 'method', 'min', 'name', 'style',\n/*\n * removed 'type' SVGElementPropKey because we do not currently use any SVG elements\n * that can use it and it conflicts with the recharts prop 'type'\n * https://github.com/recharts/recharts/pull/3327\n * https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/type\n */\n// 'type',\n'target', 'width', 'role', 'tabIndex', 'accentHeight', 'accumulate', 'additive', 'alignmentBaseline', 'allowReorder', 'alphabetic', 'amplitude', 'arabicForm', 'ascent', 'attributeName', 'attributeType', 'autoReverse', 'azimuth', 'baseFrequency', 'baselineShift', 'baseProfile', 'bbox', 'begin', 'bias', 'by', 'calcMode', 'capHeight', 'clip', 'clipPath', 'clipPathUnits', 'clipRule', 'colorInterpolation', 'colorInterpolationFilters', 'colorProfile', 'colorRendering', 'contentScriptType', 'contentStyleType', 'cursor', 'cx', 'cy', 'd', 'decelerate', 'descent', 'diffuseConstant', 'direction', 'display', 'divisor', 'dominantBaseline', 'dur', 'dx', 'dy', 'edgeMode', 'elevation', 'enableBackground', 'end', 'exponent', 'externalResourcesRequired', 'fill', 'fillOpacity', 'fillRule', 'filter', 'filterRes', 'filterUnits', 'floodColor', 'floodOpacity', 'focusable', 'fontFamily', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontWeight', 'format', 'from', 'fx', 'fy', 'g1', 'g2', 'glyphName', 'glyphOrientationHorizontal', 'glyphOrientationVertical', 'glyphRef', 'gradientTransform', 'gradientUnits', 'hanging', 'horizAdvX', 'horizOriginX', 'href', 'ideographic', 'imageRendering', 'in2', 'in', 'intercept', 'k1', 'k2', 'k3', 'k4', 'k', 'kernelMatrix', 'kernelUnitLength', 'kerning', 'keyPoints', 'keySplines', 'keyTimes', 'lengthAdjust', 'letterSpacing', 'lightingColor', 'limitingConeAngle', 'local', 'markerEnd', 'markerHeight', 'markerMid', 'markerStart', 'markerUnits', 'markerWidth', 'mask', 'maskContentUnits', 'maskUnits', 'mathematical', 'mode', 'numOctaves', 'offset', 'opacity', 'operator', 'order', 'orient', 'orientation', 'origin', 'overflow', 'overlinePosition', 'overlineThickness', 'paintOrder', 'panose1', 'pathLength', 'patternContentUnits', 'patternTransform', 'patternUnits', 'pointerEvents', 'pointsAtX', 'pointsAtY', 'pointsAtZ', 'preserveAlpha', 'preserveAspectRatio', 'primitiveUnits', 'r', 'radius', 'refX', 'refY', 'renderingIntent', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'result', 'rotate', 'rx', 'ry', 'seed', 'shapeRendering', 'slope', 'spacing', 'specularConstant', 'specularExponent', 'speed', 'spreadMethod', 'startOffset', 'stdDeviation', 'stemh', 'stemv', 'stitchTiles', 'stopColor', 'stopOpacity', 'strikethroughPosition', 'strikethroughThickness', 'string', 'stroke', 'strokeDasharray', 'strokeDashoffset', 'strokeLinecap', 'strokeLinejoin', 'strokeMiterlimit', 'strokeOpacity', 'strokeWidth', 'surfaceScale', 'systemLanguage', 'tableValues', 'targetX', 'targetY', 'textAnchor', 'textDecoration', 'textLength', 'textRendering', 'to', 'transform', 'u1', 'u2', 'underlinePosition', 'underlineThickness', 'unicode', 'unicodeBidi', 'unicodeRange', 'unitsPerEm', 'vAlphabetic', 'values', 'vectorEffect', 'version', 'vertAdvY', 'vertOriginX', 'vertOriginY', 'vHanging', 'vIdeographic', 'viewTarget', 'visibility', 'vMathematical', 'widths', 'wordSpacing', 'writingMode', 'x1', 'x2', 'x', 'xChannelSelector', 'xHeight', 'xlinkActuate', 'xlinkArcrole', 'xlinkHref', 'xlinkRole', 'xlinkShow', 'xlinkTitle', 'xlinkType', 'xmlBase', 'xmlLang', 'xmlns', 'xmlnsXlink', 'xmlSpace', 'y1', 'y2', 'y', 'yChannelSelector', 'z', 'zoomAndPan', 'ref', 'key', 'angle'];\nvar PolyElementKeys = ['points', 'pathLength'];\n\n/** svg element types that have specific attribute filtration requirements */\n\n/** map of svg element types to unique svg attributes that belong to that element */\nexport var FilteredElementKeyMap = {\n svg: SVGContainerPropKeys,\n polygon: PolyElementKeys,\n polyline: PolyElementKeys\n};\nexport var EventKeys = ['dangerouslySetInnerHTML', 'onCopy', 'onCopyCapture', 'onCut', 'onCutCapture', 'onPaste', 'onPasteCapture', 'onCompositionEnd', 'onCompositionEndCapture', 'onCompositionStart', 'onCompositionStartCapture', 'onCompositionUpdate', 'onCompositionUpdateCapture', 'onFocus', 'onFocusCapture', 'onBlur', 'onBlurCapture', 'onChange', 'onChangeCapture', 'onBeforeInput', 'onBeforeInputCapture', 'onInput', 'onInputCapture', 'onReset', 'onResetCapture', 'onSubmit', 'onSubmitCapture', 'onInvalid', 'onInvalidCapture', 'onLoad', 'onLoadCapture', 'onError', 'onErrorCapture', 'onKeyDown', 'onKeyDownCapture', 'onKeyPress', 'onKeyPressCapture', 'onKeyUp', 'onKeyUpCapture', 'onAbort', 'onAbortCapture', 'onCanPlay', 'onCanPlayCapture', 'onCanPlayThrough', 'onCanPlayThroughCapture', 'onDurationChange', 'onDurationChangeCapture', 'onEmptied', 'onEmptiedCapture', 'onEncrypted', 'onEncryptedCapture', 'onEnded', 'onEndedCapture', 'onLoadedData', 'onLoadedDataCapture', 'onLoadedMetadata', 'onLoadedMetadataCapture', 'onLoadStart', 'onLoadStartCapture', 'onPause', 'onPauseCapture', 'onPlay', 'onPlayCapture', 'onPlaying', 'onPlayingCapture', 'onProgress', 'onProgressCapture', 'onRateChange', 'onRateChangeCapture', 'onSeeked', 'onSeekedCapture', 'onSeeking', 'onSeekingCapture', 'onStalled', 'onStalledCapture', 'onSuspend', 'onSuspendCapture', 'onTimeUpdate', 'onTimeUpdateCapture', 'onVolumeChange', 'onVolumeChangeCapture', 'onWaiting', 'onWaitingCapture', 'onAuxClick', 'onAuxClickCapture', 'onClick', 'onClickCapture', 'onContextMenu', 'onContextMenuCapture', 'onDoubleClick', 'onDoubleClickCapture', 'onDrag', 'onDragCapture', 'onDragEnd', 'onDragEndCapture', 'onDragEnter', 'onDragEnterCapture', 'onDragExit', 'onDragExitCapture', 'onDragLeave', 'onDragLeaveCapture', 'onDragOver', 'onDragOverCapture', 'onDragStart', 'onDragStartCapture', 'onDrop', 'onDropCapture', 'onMouseDown', 'onMouseDownCapture', 'onMouseEnter', 'onMouseLeave', 'onMouseMove', 'onMouseMoveCapture', 'onMouseOut', 'onMouseOutCapture', 'onMouseOver', 'onMouseOverCapture', 'onMouseUp', 'onMouseUpCapture', 'onSelect', 'onSelectCapture', 'onTouchCancel', 'onTouchCancelCapture', 'onTouchEnd', 'onTouchEndCapture', 'onTouchMove', 'onTouchMoveCapture', 'onTouchStart', 'onTouchStartCapture', 'onPointerDown', 'onPointerDownCapture', 'onPointerMove', 'onPointerMoveCapture', 'onPointerUp', 'onPointerUpCapture', 'onPointerCancel', 'onPointerCancelCapture', 'onPointerEnter', 'onPointerEnterCapture', 'onPointerLeave', 'onPointerLeaveCapture', 'onPointerOver', 'onPointerOverCapture', 'onPointerOut', 'onPointerOutCapture', 'onGotPointerCapture', 'onGotPointerCaptureCapture', 'onLostPointerCapture', 'onLostPointerCaptureCapture', 'onScroll', 'onScrollCapture', 'onWheel', 'onWheelCapture', 'onAnimationStart', 'onAnimationStartCapture', 'onAnimationEnd', 'onAnimationEndCapture', 'onAnimationIteration', 'onAnimationIterationCapture', 'onTransitionEnd', 'onTransitionEndCapture'];\n\n/** The type of easing function to use for animations */\n\n/** Specifies the duration of animation, the unit of this option is ms. */\n\n/** the offset of a chart, which define the blank space all around */\n\n/**\n * The domain of axis.\n * This is the definition\n *\n * Numeric domain is always defined by an array of exactly two values, for the min and the max of the axis.\n * Categorical domain is defined as array of all possible values.\n *\n * Can be specified in many ways:\n * - array of numbers\n * - with special strings like 'dataMin' and 'dataMax'\n * - with special string math like 'dataMin - 100'\n * - with keyword 'auto'\n * - or a function\n * - array of functions\n * - or a combination of the above\n */\n\n/**\n * NumberDomain is an evaluated {@link AxisDomain}.\n * Unlike {@link AxisDomain}, it has no variety - it's a tuple of two number.\n * This is after all the keywords and functions were evaluated and what is left is [min, max].\n *\n * Know that the min, max values are not guaranteed to be nice numbers - values like -Infinity or NaN are possible.\n *\n * There are also `category` axes that have different things than numbers in their domain.\n */\n\n/** The props definition of base axis */\n\n/** Defines how ticks are placed and whether / how tick collisions are handled.\n * 'preserveStart' keeps the left tick on collision and ensures that the first tick is always shown.\n * 'preserveEnd' keeps the right tick on collision and ensures that the last tick is always shown.\n * 'preserveStartEnd' keeps the left tick on collision and ensures that the first and last ticks are always shown.\n * 'equidistantPreserveStart' selects a number N such that every nTh tick will be shown without collision.\n */\n\nexport var adaptEventHandlers = function adaptEventHandlers(props, newHandler) {\n if (!props || typeof props === 'function' || typeof props === 'boolean') {\n return null;\n }\n var inputProps = props;\n if ( /*#__PURE__*/isValidElement(props)) {\n inputProps = props.props;\n }\n if (!isObject(inputProps)) {\n return null;\n }\n var out = {};\n Object.keys(inputProps).forEach(function (key) {\n if (EventKeys.includes(key)) {\n out[key] = newHandler || function (e) {\n return inputProps[key](inputProps, e);\n };\n }\n });\n return out;\n};\nvar getEventHandlerOfChild = function getEventHandlerOfChild(originalHandler, data, index) {\n return function (e) {\n originalHandler(data, index, e);\n return null;\n };\n};\nexport var adaptEventsOfChild = function adaptEventsOfChild(props, data, index) {\n if (!isObject(props) || _typeof(props) !== 'object') {\n return null;\n }\n var out = null;\n Object.keys(props).forEach(function (key) {\n var item = props[key];\n if (EventKeys.includes(key) && typeof item === 'function') {\n if (!out) out = {};\n out[key] = getEventHandlerOfChild(item, data, index);\n }\n });\n return out;\n};", "var _excluded = [\"children\", \"className\"];\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\nimport React from 'react';\nimport clsx from 'clsx';\nimport { filterProps } from '../util/ReactUtils';\nexport var Layer = /*#__PURE__*/React.forwardRef(function (props, ref) {\n var children = props.children,\n className = props.className,\n others = _objectWithoutProperties(props, _excluded);\n var layerClass = clsx('recharts-layer', className);\n return /*#__PURE__*/React.createElement(\"g\", _extends({\n className: layerClass\n }, filterProps(others, true), {\n ref: ref\n }), children);\n});", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nvar _excluded = [\"ref\"];\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\n/**\n * @fileOverview Legend\n */\nimport React, { PureComponent } from 'react';\nimport { DefaultLegendContent } from './DefaultLegendContent';\nimport { isNumber } from '../util/DataUtils';\nimport { getUniqPayload } from '../util/payload/getUniqPayload';\nfunction defaultUniqBy(entry) {\n return entry.value;\n}\nfunction renderContent(content, props) {\n if ( /*#__PURE__*/React.isValidElement(content)) {\n return /*#__PURE__*/React.cloneElement(content, props);\n }\n if (typeof content === 'function') {\n return /*#__PURE__*/React.createElement(content, props);\n }\n var ref = props.ref,\n otherProps = _objectWithoutProperties(props, _excluded);\n return /*#__PURE__*/React.createElement(DefaultLegendContent, otherProps);\n}\nvar EPS = 1;\nexport var Legend = /*#__PURE__*/function (_PureComponent) {\n function Legend() {\n var _this;\n _classCallCheck(this, Legend);\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n _this = _callSuper(this, Legend, [].concat(args));\n _defineProperty(_this, \"lastBoundingBox\", {\n width: -1,\n height: -1\n });\n return _this;\n }\n _inherits(Legend, _PureComponent);\n return _createClass(Legend, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n this.updateBBox();\n }\n }, {\n key: \"componentDidUpdate\",\n value: function componentDidUpdate() {\n this.updateBBox();\n }\n }, {\n key: \"getBBox\",\n value: function getBBox() {\n if (this.wrapperNode && this.wrapperNode.getBoundingClientRect) {\n var box = this.wrapperNode.getBoundingClientRect();\n box.height = this.wrapperNode.offsetHeight;\n box.width = this.wrapperNode.offsetWidth;\n return box;\n }\n return null;\n }\n }, {\n key: \"updateBBox\",\n value: function updateBBox() {\n var onBBoxUpdate = this.props.onBBoxUpdate;\n var box = this.getBBox();\n if (box) {\n if (Math.abs(box.width - this.lastBoundingBox.width) > EPS || Math.abs(box.height - this.lastBoundingBox.height) > EPS) {\n this.lastBoundingBox.width = box.width;\n this.lastBoundingBox.height = box.height;\n if (onBBoxUpdate) {\n onBBoxUpdate(box);\n }\n }\n } else if (this.lastBoundingBox.width !== -1 || this.lastBoundingBox.height !== -1) {\n this.lastBoundingBox.width = -1;\n this.lastBoundingBox.height = -1;\n if (onBBoxUpdate) {\n onBBoxUpdate(null);\n }\n }\n }\n }, {\n key: \"getBBoxSnapshot\",\n value: function getBBoxSnapshot() {\n if (this.lastBoundingBox.width >= 0 && this.lastBoundingBox.height >= 0) {\n return _objectSpread({}, this.lastBoundingBox);\n }\n return {\n width: 0,\n height: 0\n };\n }\n }, {\n key: \"getDefaultPosition\",\n value: function getDefaultPosition(style) {\n var _this$props = this.props,\n layout = _this$props.layout,\n align = _this$props.align,\n verticalAlign = _this$props.verticalAlign,\n margin = _this$props.margin,\n chartWidth = _this$props.chartWidth,\n chartHeight = _this$props.chartHeight;\n var hPos, vPos;\n if (!style || (style.left === undefined || style.left === null) && (style.right === undefined || style.right === null)) {\n if (align === 'center' && layout === 'vertical') {\n var box = this.getBBoxSnapshot();\n hPos = {\n left: ((chartWidth || 0) - box.width) / 2\n };\n } else {\n hPos = align === 'right' ? {\n right: margin && margin.right || 0\n } : {\n left: margin && margin.left || 0\n };\n }\n }\n if (!style || (style.top === undefined || style.top === null) && (style.bottom === undefined || style.bottom === null)) {\n if (verticalAlign === 'middle') {\n var _box = this.getBBoxSnapshot();\n vPos = {\n top: ((chartHeight || 0) - _box.height) / 2\n };\n } else {\n vPos = verticalAlign === 'bottom' ? {\n bottom: margin && margin.bottom || 0\n } : {\n top: margin && margin.top || 0\n };\n }\n }\n return _objectSpread(_objectSpread({}, hPos), vPos);\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this2 = this;\n var _this$props2 = this.props,\n content = _this$props2.content,\n width = _this$props2.width,\n height = _this$props2.height,\n wrapperStyle = _this$props2.wrapperStyle,\n payloadUniqBy = _this$props2.payloadUniqBy,\n payload = _this$props2.payload;\n var outerStyle = _objectSpread(_objectSpread({\n position: 'absolute',\n width: width || 'auto',\n height: height || 'auto'\n }, this.getDefaultPosition(wrapperStyle)), wrapperStyle);\n return /*#__PURE__*/React.createElement(\"div\", {\n className: \"recharts-legend-wrapper\",\n style: outerStyle,\n ref: function ref(node) {\n _this2.wrapperNode = node;\n }\n }, renderContent(content, _objectSpread(_objectSpread({}, this.props), {}, {\n payload: getUniqPayload(payload, payloadUniqBy, defaultUniqBy)\n })));\n }\n }], [{\n key: \"getWithHeight\",\n value: function getWithHeight(item, chartWidth) {\n var _this$defaultProps$it = _objectSpread(_objectSpread({}, this.defaultProps), item.props),\n layout = _this$defaultProps$it.layout;\n if (layout === 'vertical' && isNumber(item.props.height)) {\n return {\n height: item.props.height\n };\n }\n if (layout === 'horizontal') {\n return {\n width: item.props.width || chartWidth\n };\n }\n return null;\n }\n }]);\n}(PureComponent);\n_defineProperty(Legend, \"displayName\", 'Legend');\n_defineProperty(Legend, \"defaultProps\", {\n iconSize: 14,\n layout: 'horizontal',\n align: 'center',\n verticalAlign: 'bottom'\n});", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Default Legend Content\n */\nimport React, { PureComponent } from 'react';\nimport isFunction from 'lodash/isFunction';\nimport clsx from 'clsx';\nimport { warn } from '../util/LogUtils';\nimport { Surface } from '../container/Surface';\nimport { Symbols } from '../shape/Symbols';\nimport { adaptEventsOfChild } from '../util/types';\nvar SIZE = 32;\nexport var DefaultLegendContent = /*#__PURE__*/function (_PureComponent) {\n function DefaultLegendContent() {\n _classCallCheck(this, DefaultLegendContent);\n return _callSuper(this, DefaultLegendContent, arguments);\n }\n _inherits(DefaultLegendContent, _PureComponent);\n return _createClass(DefaultLegendContent, [{\n key: \"renderIcon\",\n value:\n /**\n * Render the path of icon\n * @param {Object} data Data of each legend item\n * @return {String} Path element\n */\n function renderIcon(data) {\n var inactiveColor = this.props.inactiveColor;\n var halfSize = SIZE / 2;\n var sixthSize = SIZE / 6;\n var thirdSize = SIZE / 3;\n var color = data.inactive ? inactiveColor : data.color;\n if (data.type === 'plainline') {\n return /*#__PURE__*/React.createElement(\"line\", {\n strokeWidth: 4,\n fill: \"none\",\n stroke: color,\n strokeDasharray: data.payload.strokeDasharray,\n x1: 0,\n y1: halfSize,\n x2: SIZE,\n y2: halfSize,\n className: \"recharts-legend-icon\"\n });\n }\n if (data.type === 'line') {\n return /*#__PURE__*/React.createElement(\"path\", {\n strokeWidth: 4,\n fill: \"none\",\n stroke: color,\n d: \"M0,\".concat(halfSize, \"h\").concat(thirdSize, \"\\n A\").concat(sixthSize, \",\").concat(sixthSize, \",0,1,1,\").concat(2 * thirdSize, \",\").concat(halfSize, \"\\n H\").concat(SIZE, \"M\").concat(2 * thirdSize, \",\").concat(halfSize, \"\\n A\").concat(sixthSize, \",\").concat(sixthSize, \",0,1,1,\").concat(thirdSize, \",\").concat(halfSize),\n className: \"recharts-legend-icon\"\n });\n }\n if (data.type === 'rect') {\n return /*#__PURE__*/React.createElement(\"path\", {\n stroke: \"none\",\n fill: color,\n d: \"M0,\".concat(SIZE / 8, \"h\").concat(SIZE, \"v\").concat(SIZE * 3 / 4, \"h\").concat(-SIZE, \"z\"),\n className: \"recharts-legend-icon\"\n });\n }\n if ( /*#__PURE__*/React.isValidElement(data.legendIcon)) {\n var iconProps = _objectSpread({}, data);\n delete iconProps.legendIcon;\n return /*#__PURE__*/React.cloneElement(data.legendIcon, iconProps);\n }\n return /*#__PURE__*/React.createElement(Symbols, {\n fill: color,\n cx: halfSize,\n cy: halfSize,\n size: SIZE,\n sizeType: \"diameter\",\n type: data.type\n });\n }\n\n /**\n * Draw items of legend\n * @return {ReactElement} Items\n */\n }, {\n key: \"renderItems\",\n value: function renderItems() {\n var _this = this;\n var _this$props = this.props,\n payload = _this$props.payload,\n iconSize = _this$props.iconSize,\n layout = _this$props.layout,\n formatter = _this$props.formatter,\n inactiveColor = _this$props.inactiveColor;\n var viewBox = {\n x: 0,\n y: 0,\n width: SIZE,\n height: SIZE\n };\n var itemStyle = {\n display: layout === 'horizontal' ? 'inline-block' : 'block',\n marginRight: 10\n };\n var svgStyle = {\n display: 'inline-block',\n verticalAlign: 'middle',\n marginRight: 4\n };\n return payload.map(function (entry, i) {\n var finalFormatter = entry.formatter || formatter;\n var className = clsx(_defineProperty(_defineProperty({\n 'recharts-legend-item': true\n }, \"legend-item-\".concat(i), true), \"inactive\", entry.inactive));\n if (entry.type === 'none') {\n return null;\n }\n\n // Do not render entry.value as functions. Always require static string properties.\n var entryValue = !isFunction(entry.value) ? entry.value : null;\n warn(!isFunction(entry.value), \"The name property is also required when using a function for the dataKey of a chart's cartesian components. Ex: \" // eslint-disable-line max-len\n );\n var color = entry.inactive ? inactiveColor : entry.color;\n return /*#__PURE__*/React.createElement(\"li\", _extends({\n className: className,\n style: itemStyle\n // eslint-disable-next-line react/no-array-index-key\n ,\n key: \"legend-item-\".concat(i)\n }, adaptEventsOfChild(_this.props, entry, i)), /*#__PURE__*/React.createElement(Surface, {\n width: iconSize,\n height: iconSize,\n viewBox: viewBox,\n style: svgStyle\n }, _this.renderIcon(entry)), /*#__PURE__*/React.createElement(\"span\", {\n className: \"recharts-legend-item-text\",\n style: {\n color: color\n }\n }, finalFormatter ? finalFormatter(entryValue, entry, i) : entryValue));\n });\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this$props2 = this.props,\n payload = _this$props2.payload,\n layout = _this$props2.layout,\n align = _this$props2.align;\n if (!payload || !payload.length) {\n return null;\n }\n var finalStyle = {\n padding: 0,\n margin: 0,\n textAlign: layout === 'horizontal' ? align : 'left'\n };\n return /*#__PURE__*/React.createElement(\"ul\", {\n className: \"recharts-default-legend\",\n style: finalStyle\n }, this.renderItems());\n }\n }]);\n}(PureComponent);\n_defineProperty(DefaultLegendContent, \"displayName\", 'Legend');\n_defineProperty(DefaultLegendContent, \"defaultProps\", {\n iconSize: 14,\n layout: 'horizontal',\n align: 'center',\n verticalAlign: 'middle',\n inactiveColor: '#ccc'\n});", "/* eslint no-console: 0 */\nvar isDev = process.env.NODE_ENV !== 'production';\nexport var warn = function warn(condition, format) {\n for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n args[_key - 2] = arguments[_key];\n }\n if (isDev && typeof console !== 'undefined' && console.warn) {\n if (format === undefined) {\n console.warn('LogUtils requires an error message argument');\n }\n if (!condition) {\n if (format === undefined) {\n console.warn('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');\n } else {\n var argIndex = 0;\n console.warn(format.replace(/%s/g, function () {\n return args[argIndex++];\n }));\n }\n }\n }\n};", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nvar _excluded = [\"type\", \"size\", \"sizeType\"];\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\n/**\n * @fileOverview Curve\n */\nimport React from 'react';\nimport upperFirst from 'lodash/upperFirst';\nimport { symbol as shapeSymbol, symbolCircle, symbolCross, symbolDiamond, symbolSquare, symbolStar, symbolTriangle, symbolWye } from 'victory-vendor/d3-shape';\nimport clsx from 'clsx';\nimport { filterProps } from '../util/ReactUtils';\nvar symbolFactories = {\n symbolCircle: symbolCircle,\n symbolCross: symbolCross,\n symbolDiamond: symbolDiamond,\n symbolSquare: symbolSquare,\n symbolStar: symbolStar,\n symbolTriangle: symbolTriangle,\n symbolWye: symbolWye\n};\nvar RADIAN = Math.PI / 180;\nvar getSymbolFactory = function getSymbolFactory(type) {\n var name = \"symbol\".concat(upperFirst(type));\n return symbolFactories[name] || symbolCircle;\n};\nvar calculateAreaSize = function calculateAreaSize(size, sizeType, type) {\n if (sizeType === 'area') {\n return size;\n }\n switch (type) {\n case 'cross':\n return 5 * size * size / 9;\n case 'diamond':\n return 0.5 * size * size / Math.sqrt(3);\n case 'square':\n return size * size;\n case 'star':\n {\n var angle = 18 * RADIAN;\n return 1.25 * size * size * (Math.tan(angle) - Math.tan(angle * 2) * Math.pow(Math.tan(angle), 2));\n }\n case 'triangle':\n return Math.sqrt(3) * size * size / 4;\n case 'wye':\n return (21 - 10 * Math.sqrt(3)) * size * size / 8;\n default:\n return Math.PI * size * size / 4;\n }\n};\nvar registerSymbol = function registerSymbol(key, factory) {\n symbolFactories[\"symbol\".concat(upperFirst(key))] = factory;\n};\nexport var Symbols = function Symbols(_ref) {\n var _ref$type = _ref.type,\n type = _ref$type === void 0 ? 'circle' : _ref$type,\n _ref$size = _ref.size,\n size = _ref$size === void 0 ? 64 : _ref$size,\n _ref$sizeType = _ref.sizeType,\n sizeType = _ref$sizeType === void 0 ? 'area' : _ref$sizeType,\n rest = _objectWithoutProperties(_ref, _excluded);\n var props = _objectSpread(_objectSpread({}, rest), {}, {\n type: type,\n size: size,\n sizeType: sizeType\n });\n\n /**\n * Calculate the path of curve\n * @return {String} path\n */\n var getPath = function getPath() {\n var symbolFactory = getSymbolFactory(type);\n var symbol = shapeSymbol().type(symbolFactory).size(calculateAreaSize(size, sizeType, type));\n return symbol();\n };\n var className = props.className,\n cx = props.cx,\n cy = props.cy;\n var filteredProps = filterProps(props, true);\n if (cx === +cx && cy === +cy && size === +size) {\n return /*#__PURE__*/React.createElement(\"path\", _extends({}, filteredProps, {\n className: clsx('recharts-symbols', className),\n transform: \"translate(\".concat(cx, \", \").concat(cy, \")\"),\n d: getPath()\n }));\n }\n return null;\n};\nSymbols.registerSymbol = registerSymbol;", "export default function(x) {\n return function constant() {\n return x;\n };\n}\n", "export const abs = Math.abs;\nexport const atan2 = Math.atan2;\nexport const cos = Math.cos;\nexport const max = Math.max;\nexport const min = Math.min;\nexport const sin = Math.sin;\nexport const sqrt = Math.sqrt;\n\nexport const epsilon = 1e-12;\nexport const pi = Math.PI;\nexport const halfPi = pi / 2;\nexport const tau = 2 * pi;\n\nexport function acos(x) {\n return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);\n}\n\nexport function asin(x) {\n return x >= 1 ? halfPi : x <= -1 ? -halfPi : Math.asin(x);\n}\n", "const pi = Math.PI,\n tau = 2 * pi,\n epsilon = 1e-6,\n tauEpsilon = tau - epsilon;\n\nfunction append(strings) {\n this._ += strings[0];\n for (let i = 1, n = strings.length; i < n; ++i) {\n this._ += arguments[i] + strings[i];\n }\n}\n\nfunction appendRound(digits) {\n let d = Math.floor(digits);\n if (!(d >= 0)) throw new Error(`invalid digits: ${digits}`);\n if (d > 15) return append;\n const k = 10 ** d;\n return function(strings) {\n this._ += strings[0];\n for (let i = 1, n = strings.length; i < n; ++i) {\n this._ += Math.round(arguments[i] * k) / k + strings[i];\n }\n };\n}\n\nexport class Path {\n constructor(digits) {\n this._x0 = this._y0 = // start of current subpath\n this._x1 = this._y1 = null; // end of current subpath\n this._ = \"\";\n this._append = digits == null ? append : appendRound(digits);\n }\n moveTo(x, y) {\n this._append`M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}`;\n }\n closePath() {\n if (this._x1 !== null) {\n this._x1 = this._x0, this._y1 = this._y0;\n this._append`Z`;\n }\n }\n lineTo(x, y) {\n this._append`L${this._x1 = +x},${this._y1 = +y}`;\n }\n quadraticCurveTo(x1, y1, x, y) {\n this._append`Q${+x1},${+y1},${this._x1 = +x},${this._y1 = +y}`;\n }\n bezierCurveTo(x1, y1, x2, y2, x, y) {\n this._append`C${+x1},${+y1},${+x2},${+y2},${this._x1 = +x},${this._y1 = +y}`;\n }\n arcTo(x1, y1, x2, y2, r) {\n x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;\n\n // Is the radius negative? Error.\n if (r < 0) throw new Error(`negative radius: ${r}`);\n\n let x0 = this._x1,\n y0 = this._y1,\n x21 = x2 - x1,\n y21 = y2 - y1,\n x01 = x0 - x1,\n y01 = y0 - y1,\n l01_2 = x01 * x01 + y01 * y01;\n\n // Is this path empty? Move to (x1,y1).\n if (this._x1 === null) {\n this._append`M${this._x1 = x1},${this._y1 = y1}`;\n }\n\n // Or, is (x1,y1) coincident with (x0,y0)? Do nothing.\n else if (!(l01_2 > epsilon));\n\n // Or, are (x0,y0), (x1,y1) and (x2,y2) collinear?\n // Equivalently, is (x1,y1) coincident with (x2,y2)?\n // Or, is the radius zero? Line to (x1,y1).\n else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon) || !r) {\n this._append`L${this._x1 = x1},${this._y1 = y1}`;\n }\n\n // Otherwise, draw an arc!\n else {\n let x20 = x2 - x0,\n y20 = y2 - y0,\n l21_2 = x21 * x21 + y21 * y21,\n l20_2 = x20 * x20 + y20 * y20,\n l21 = Math.sqrt(l21_2),\n l01 = Math.sqrt(l01_2),\n l = r * Math.tan((pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2),\n t01 = l / l01,\n t21 = l / l21;\n\n // If the start tangent is not coincident with (x0,y0), line to.\n if (Math.abs(t01 - 1) > epsilon) {\n this._append`L${x1 + t01 * x01},${y1 + t01 * y01}`;\n }\n\n this._append`A${r},${r},0,0,${+(y01 * x20 > x01 * y20)},${this._x1 = x1 + t21 * x21},${this._y1 = y1 + t21 * y21}`;\n }\n }\n arc(x, y, r, a0, a1, ccw) {\n x = +x, y = +y, r = +r, ccw = !!ccw;\n\n // Is the radius negative? Error.\n if (r < 0) throw new Error(`negative radius: ${r}`);\n\n let dx = r * Math.cos(a0),\n dy = r * Math.sin(a0),\n x0 = x + dx,\n y0 = y + dy,\n cw = 1 ^ ccw,\n da = ccw ? a0 - a1 : a1 - a0;\n\n // Is this path empty? Move to (x0,y0).\n if (this._x1 === null) {\n this._append`M${x0},${y0}`;\n }\n\n // Or, is (x0,y0) not coincident with the previous point? Line to (x0,y0).\n else if (Math.abs(this._x1 - x0) > epsilon || Math.abs(this._y1 - y0) > epsilon) {\n this._append`L${x0},${y0}`;\n }\n\n // Is this arc empty? We\u2019re done.\n if (!r) return;\n\n // Does the angle go the wrong way? Flip the direction.\n if (da < 0) da = da % tau + tau;\n\n // Is this a complete circle? Draw two arcs to complete the circle.\n if (da > tauEpsilon) {\n this._append`A${r},${r},0,1,${cw},${x - dx},${y - dy}A${r},${r},0,1,${cw},${this._x1 = x0},${this._y1 = y0}`;\n }\n\n // Is this arc non-empty? Draw an arc!\n else if (da > epsilon) {\n this._append`A${r},${r},0,${+(da >= pi)},${cw},${this._x1 = x + r * Math.cos(a1)},${this._y1 = y + r * Math.sin(a1)}`;\n }\n }\n rect(x, y, w, h) {\n this._append`M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}h${w = +w}v${+h}h${-w}Z`;\n }\n toString() {\n return this._;\n }\n}\n\nexport function path() {\n return new Path;\n}\n\n// Allow instanceof d3.path\npath.prototype = Path.prototype;\n\nexport function pathRound(digits = 3) {\n return new Path(+digits);\n}\n", "import {Path} from \"d3-path\";\n\nexport function withPath(shape) {\n let digits = 3;\n\n shape.digits = function(_) {\n if (!arguments.length) return digits;\n if (_ == null) {\n digits = null;\n } else {\n const d = Math.floor(_);\n if (!(d >= 0)) throw new RangeError(`invalid digits: ${_}`);\n digits = d;\n }\n return shape;\n };\n\n return () => new Path(digits);\n}\n", "export var slice = Array.prototype.slice;\n\nexport default function(x) {\n return typeof x === \"object\" && \"length\" in x\n ? x // Array, TypedArray, NodeList, array-like\n : Array.from(x); // Map, Set, iterable, string, or anything else\n}\n", "function Linear(context) {\n this._context = context;\n}\n\nLinear.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._point = 0;\n },\n lineEnd: function() {\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;\n case 1: this._point = 2; // falls through\n default: this._context.lineTo(x, y); break;\n }\n }\n};\n\nexport default function(context) {\n return new Linear(context);\n}\n", "export function x(p) {\n return p[0];\n}\n\nexport function y(p) {\n return p[1];\n}\n", "import array from \"./array.js\";\nimport constant from \"./constant.js\";\nimport curveLinear from \"./curve/linear.js\";\nimport {withPath} from \"./path.js\";\nimport {x as pointX, y as pointY} from \"./point.js\";\n\nexport default function(x, y) {\n var defined = constant(true),\n context = null,\n curve = curveLinear,\n output = null,\n path = withPath(line);\n\n x = typeof x === \"function\" ? x : (x === undefined) ? pointX : constant(x);\n y = typeof y === \"function\" ? y : (y === undefined) ? pointY : constant(y);\n\n function line(data) {\n var i,\n n = (data = array(data)).length,\n d,\n defined0 = false,\n buffer;\n\n if (context == null) output = curve(buffer = path());\n\n for (i = 0; i <= n; ++i) {\n if (!(i < n && defined(d = data[i], i, data)) === defined0) {\n if (defined0 = !defined0) output.lineStart();\n else output.lineEnd();\n }\n if (defined0) output.point(+x(d, i, data), +y(d, i, data));\n }\n\n if (buffer) return output = null, buffer + \"\" || null;\n }\n\n line.x = function(_) {\n return arguments.length ? (x = typeof _ === \"function\" ? _ : constant(+_), line) : x;\n };\n\n line.y = function(_) {\n return arguments.length ? (y = typeof _ === \"function\" ? _ : constant(+_), line) : y;\n };\n\n line.defined = function(_) {\n return arguments.length ? (defined = typeof _ === \"function\" ? _ : constant(!!_), line) : defined;\n };\n\n line.curve = function(_) {\n return arguments.length ? (curve = _, context != null && (output = curve(context)), line) : curve;\n };\n\n line.context = function(_) {\n return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), line) : context;\n };\n\n return line;\n}\n", "import array from \"./array.js\";\nimport constant from \"./constant.js\";\nimport curveLinear from \"./curve/linear.js\";\nimport line from \"./line.js\";\nimport {withPath} from \"./path.js\";\nimport {x as pointX, y as pointY} from \"./point.js\";\n\nexport default function(x0, y0, y1) {\n var x1 = null,\n defined = constant(true),\n context = null,\n curve = curveLinear,\n output = null,\n path = withPath(area);\n\n x0 = typeof x0 === \"function\" ? x0 : (x0 === undefined) ? pointX : constant(+x0);\n y0 = typeof y0 === \"function\" ? y0 : (y0 === undefined) ? constant(0) : constant(+y0);\n y1 = typeof y1 === \"function\" ? y1 : (y1 === undefined) ? pointY : constant(+y1);\n\n function area(data) {\n var i,\n j,\n k,\n n = (data = array(data)).length,\n d,\n defined0 = false,\n buffer,\n x0z = new Array(n),\n y0z = new Array(n);\n\n if (context == null) output = curve(buffer = path());\n\n for (i = 0; i <= n; ++i) {\n if (!(i < n && defined(d = data[i], i, data)) === defined0) {\n if (defined0 = !defined0) {\n j = i;\n output.areaStart();\n output.lineStart();\n } else {\n output.lineEnd();\n output.lineStart();\n for (k = i - 1; k >= j; --k) {\n output.point(x0z[k], y0z[k]);\n }\n output.lineEnd();\n output.areaEnd();\n }\n }\n if (defined0) {\n x0z[i] = +x0(d, i, data), y0z[i] = +y0(d, i, data);\n output.point(x1 ? +x1(d, i, data) : x0z[i], y1 ? +y1(d, i, data) : y0z[i]);\n }\n }\n\n if (buffer) return output = null, buffer + \"\" || null;\n }\n\n function arealine() {\n return line().defined(defined).curve(curve).context(context);\n }\n\n area.x = function(_) {\n return arguments.length ? (x0 = typeof _ === \"function\" ? _ : constant(+_), x1 = null, area) : x0;\n };\n\n area.x0 = function(_) {\n return arguments.length ? (x0 = typeof _ === \"function\" ? _ : constant(+_), area) : x0;\n };\n\n area.x1 = function(_) {\n return arguments.length ? (x1 = _ == null ? null : typeof _ === \"function\" ? _ : constant(+_), area) : x1;\n };\n\n area.y = function(_) {\n return arguments.length ? (y0 = typeof _ === \"function\" ? _ : constant(+_), y1 = null, area) : y0;\n };\n\n area.y0 = function(_) {\n return arguments.length ? (y0 = typeof _ === \"function\" ? _ : constant(+_), area) : y0;\n };\n\n area.y1 = function(_) {\n return arguments.length ? (y1 = _ == null ? null : typeof _ === \"function\" ? _ : constant(+_), area) : y1;\n };\n\n area.lineX0 =\n area.lineY0 = function() {\n return arealine().x(x0).y(y0);\n };\n\n area.lineY1 = function() {\n return arealine().x(x0).y(y1);\n };\n\n area.lineX1 = function() {\n return arealine().x(x1).y(y0);\n };\n\n area.defined = function(_) {\n return arguments.length ? (defined = typeof _ === \"function\" ? _ : constant(!!_), area) : defined;\n };\n\n area.curve = function(_) {\n return arguments.length ? (curve = _, context != null && (output = curve(context)), area) : curve;\n };\n\n area.context = function(_) {\n return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), area) : context;\n };\n\n return area;\n}\n", "import pointRadial from \"../pointRadial.js\";\n\nclass Bump {\n constructor(context, x) {\n this._context = context;\n this._x = x;\n }\n areaStart() {\n this._line = 0;\n }\n areaEnd() {\n this._line = NaN;\n }\n lineStart() {\n this._point = 0;\n }\n lineEnd() {\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n this._line = 1 - this._line;\n }\n point(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: {\n this._point = 1;\n if (this._line) this._context.lineTo(x, y);\n else this._context.moveTo(x, y);\n break;\n }\n case 1: this._point = 2; // falls through\n default: {\n if (this._x) this._context.bezierCurveTo(this._x0 = (this._x0 + x) / 2, this._y0, this._x0, y, x, y);\n else this._context.bezierCurveTo(this._x0, this._y0 = (this._y0 + y) / 2, x, this._y0, x, y);\n break;\n }\n }\n this._x0 = x, this._y0 = y;\n }\n}\n\nclass BumpRadial {\n constructor(context) {\n this._context = context;\n }\n lineStart() {\n this._point = 0;\n }\n lineEnd() {}\n point(x, y) {\n x = +x, y = +y;\n if (this._point === 0) {\n this._point = 1;\n } else {\n const p0 = pointRadial(this._x0, this._y0);\n const p1 = pointRadial(this._x0, this._y0 = (this._y0 + y) / 2);\n const p2 = pointRadial(x, this._y0);\n const p3 = pointRadial(x, y);\n this._context.moveTo(...p0);\n this._context.bezierCurveTo(...p1, ...p2, ...p3);\n }\n this._x0 = x, this._y0 = y;\n }\n}\n\nexport function bumpX(context) {\n return new Bump(context, true);\n}\n\nexport function bumpY(context) {\n return new Bump(context, false);\n}\n\nexport function bumpRadial(context) {\n return new BumpRadial(context);\n}\n", "import {pi, sqrt, tau} from \"../math.js\";\n\nexport default {\n draw(context, size) {\n const r = sqrt(size / pi);\n context.moveTo(r, 0);\n context.arc(0, 0, r, 0, tau);\n }\n};\n", "import {sqrt} from \"../math.js\";\n\nexport default {\n draw(context, size) {\n const r = sqrt(size / 5) / 2;\n context.moveTo(-3 * r, -r);\n context.lineTo(-r, -r);\n context.lineTo(-r, -3 * r);\n context.lineTo(r, -3 * r);\n context.lineTo(r, -r);\n context.lineTo(3 * r, -r);\n context.lineTo(3 * r, r);\n context.lineTo(r, r);\n context.lineTo(r, 3 * r);\n context.lineTo(-r, 3 * r);\n context.lineTo(-r, r);\n context.lineTo(-3 * r, r);\n context.closePath();\n }\n};\n", "import {sqrt} from \"../math.js\";\n\nconst tan30 = sqrt(1 / 3);\nconst tan30_2 = tan30 * 2;\n\nexport default {\n draw(context, size) {\n const y = sqrt(size / tan30_2);\n const x = y * tan30;\n context.moveTo(0, -y);\n context.lineTo(x, 0);\n context.lineTo(0, y);\n context.lineTo(-x, 0);\n context.closePath();\n }\n};\n", "import {sqrt} from \"../math.js\";\n\nexport default {\n draw(context, size) {\n const w = sqrt(size);\n const x = -w / 2;\n context.rect(x, x, w, w);\n }\n};\n", "import {sin, cos, sqrt, pi, tau} from \"../math.js\";\n\nconst ka = 0.89081309152928522810;\nconst kr = sin(pi / 10) / sin(7 * pi / 10);\nconst kx = sin(tau / 10) * kr;\nconst ky = -cos(tau / 10) * kr;\n\nexport default {\n draw(context, size) {\n const r = sqrt(size * ka);\n const x = kx * r;\n const y = ky * r;\n context.moveTo(0, -r);\n context.lineTo(x, y);\n for (let i = 1; i < 5; ++i) {\n const a = tau * i / 5;\n const c = cos(a);\n const s = sin(a);\n context.lineTo(s * r, -c * r);\n context.lineTo(c * x - s * y, s * x + c * y);\n }\n context.closePath();\n }\n};\n", "import {sqrt} from \"../math.js\";\n\nconst sqrt3 = sqrt(3);\n\nexport default {\n draw(context, size) {\n const y = -sqrt(size / (sqrt3 * 3));\n context.moveTo(0, y * 2);\n context.lineTo(-sqrt3 * y, -y);\n context.lineTo(sqrt3 * y, -y);\n context.closePath();\n }\n};\n", "import {sqrt} from \"../math.js\";\n\nconst c = -0.5;\nconst s = sqrt(3) / 2;\nconst k = 1 / sqrt(12);\nconst a = (k / 2 + 1) * 3;\n\nexport default {\n draw(context, size) {\n const r = sqrt(size / a);\n const x0 = r / 2, y0 = r * k;\n const x1 = x0, y1 = r * k + r;\n const x2 = -x1, y2 = y1;\n context.moveTo(x0, y0);\n context.lineTo(x1, y1);\n context.lineTo(x2, y2);\n context.lineTo(c * x0 - s * y0, s * x0 + c * y0);\n context.lineTo(c * x1 - s * y1, s * x1 + c * y1);\n context.lineTo(c * x2 - s * y2, s * x2 + c * y2);\n context.lineTo(c * x0 + s * y0, c * y0 - s * x0);\n context.lineTo(c * x1 + s * y1, c * y1 - s * x1);\n context.lineTo(c * x2 + s * y2, c * y2 - s * x2);\n context.closePath();\n }\n};\n", "import constant from \"./constant.js\";\nimport {withPath} from \"./path.js\";\nimport asterisk from \"./symbol/asterisk.js\";\nimport circle from \"./symbol/circle.js\";\nimport cross from \"./symbol/cross.js\";\nimport diamond from \"./symbol/diamond.js\";\nimport diamond2 from \"./symbol/diamond2.js\";\nimport plus from \"./symbol/plus.js\";\nimport square from \"./symbol/square.js\";\nimport square2 from \"./symbol/square2.js\";\nimport star from \"./symbol/star.js\";\nimport triangle from \"./symbol/triangle.js\";\nimport triangle2 from \"./symbol/triangle2.js\";\nimport wye from \"./symbol/wye.js\";\nimport times from \"./symbol/times.js\";\n\n// These symbols are designed to be filled.\nexport const symbolsFill = [\n circle,\n cross,\n diamond,\n square,\n star,\n triangle,\n wye\n];\n\n// These symbols are designed to be stroked (with a width of 1.5px and round caps).\nexport const symbolsStroke = [\n circle,\n plus,\n times,\n triangle2,\n asterisk,\n square2,\n diamond2\n];\n\nexport default function Symbol(type, size) {\n let context = null,\n path = withPath(symbol);\n\n type = typeof type === \"function\" ? type : constant(type || circle);\n size = typeof size === \"function\" ? size : constant(size === undefined ? 64 : +size);\n\n function symbol() {\n let buffer;\n if (!context) context = buffer = path();\n type.apply(this, arguments).draw(context, +size.apply(this, arguments));\n if (buffer) return context = null, buffer + \"\" || null;\n }\n\n symbol.type = function(_) {\n return arguments.length ? (type = typeof _ === \"function\" ? _ : constant(_), symbol) : type;\n };\n\n symbol.size = function(_) {\n return arguments.length ? (size = typeof _ === \"function\" ? _ : constant(+_), symbol) : size;\n };\n\n symbol.context = function(_) {\n return arguments.length ? (context = _ == null ? null : _, symbol) : context;\n };\n\n return symbol;\n}\n", "export default function() {}\n", "export function point(that, x, y) {\n that._context.bezierCurveTo(\n (2 * that._x0 + that._x1) / 3,\n (2 * that._y0 + that._y1) / 3,\n (that._x0 + 2 * that._x1) / 3,\n (that._y0 + 2 * that._y1) / 3,\n (that._x0 + 4 * that._x1 + x) / 6,\n (that._y0 + 4 * that._y1 + y) / 6\n );\n}\n\nexport function Basis(context) {\n this._context = context;\n}\n\nBasis.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 =\n this._y0 = this._y1 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 3: point(this, this._x1, this._y1); // falls through\n case 2: this._context.lineTo(this._x1, this._y1); break;\n }\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;\n case 1: this._point = 2; break;\n case 2: this._point = 3; this._context.lineTo((5 * this._x0 + this._x1) / 6, (5 * this._y0 + this._y1) / 6); // falls through\n default: point(this, x, y); break;\n }\n this._x0 = this._x1, this._x1 = x;\n this._y0 = this._y1, this._y1 = y;\n }\n};\n\nexport default function(context) {\n return new Basis(context);\n}\n", "import noop from \"../noop.js\";\nimport {point} from \"./basis.js\";\n\nfunction BasisClosed(context) {\n this._context = context;\n}\n\nBasisClosed.prototype = {\n areaStart: noop,\n areaEnd: noop,\n lineStart: function() {\n this._x0 = this._x1 = this._x2 = this._x3 = this._x4 =\n this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 1: {\n this._context.moveTo(this._x2, this._y2);\n this._context.closePath();\n break;\n }\n case 2: {\n this._context.moveTo((this._x2 + 2 * this._x3) / 3, (this._y2 + 2 * this._y3) / 3);\n this._context.lineTo((this._x3 + 2 * this._x2) / 3, (this._y3 + 2 * this._y2) / 3);\n this._context.closePath();\n break;\n }\n case 3: {\n this.point(this._x2, this._y2);\n this.point(this._x3, this._y3);\n this.point(this._x4, this._y4);\n break;\n }\n }\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; this._x2 = x, this._y2 = y; break;\n case 1: this._point = 2; this._x3 = x, this._y3 = y; break;\n case 2: this._point = 3; this._x4 = x, this._y4 = y; this._context.moveTo((this._x0 + 4 * this._x1 + x) / 6, (this._y0 + 4 * this._y1 + y) / 6); break;\n default: point(this, x, y); break;\n }\n this._x0 = this._x1, this._x1 = x;\n this._y0 = this._y1, this._y1 = y;\n }\n};\n\nexport default function(context) {\n return new BasisClosed(context);\n}\n", "import {point} from \"./basis.js\";\n\nfunction BasisOpen(context) {\n this._context = context;\n}\n\nBasisOpen.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 =\n this._y0 = this._y1 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; break;\n case 1: this._point = 2; break;\n case 2: this._point = 3; var x0 = (this._x0 + 4 * this._x1 + x) / 6, y0 = (this._y0 + 4 * this._y1 + y) / 6; this._line ? this._context.lineTo(x0, y0) : this._context.moveTo(x0, y0); break;\n case 3: this._point = 4; // falls through\n default: point(this, x, y); break;\n }\n this._x0 = this._x1, this._x1 = x;\n this._y0 = this._y1, this._y1 = y;\n }\n};\n\nexport default function(context) {\n return new BasisOpen(context);\n}\n", "import noop from \"../noop.js\";\n\nfunction LinearClosed(context) {\n this._context = context;\n}\n\nLinearClosed.prototype = {\n areaStart: noop,\n areaEnd: noop,\n lineStart: function() {\n this._point = 0;\n },\n lineEnd: function() {\n if (this._point) this._context.closePath();\n },\n point: function(x, y) {\n x = +x, y = +y;\n if (this._point) this._context.lineTo(x, y);\n else this._point = 1, this._context.moveTo(x, y);\n }\n};\n\nexport default function(context) {\n return new LinearClosed(context);\n}\n", "function sign(x) {\n return x < 0 ? -1 : 1;\n}\n\n// Calculate the slopes of the tangents (Hermite-type interpolation) based on\n// the following paper: Steffen, M. 1990. A Simple Method for Monotonic\n// Interpolation in One Dimension. Astronomy and Astrophysics, Vol. 239, NO.\n// NOV(II), P. 443, 1990.\nfunction slope3(that, x2, y2) {\n var h0 = that._x1 - that._x0,\n h1 = x2 - that._x1,\n s0 = (that._y1 - that._y0) / (h0 || h1 < 0 && -0),\n s1 = (y2 - that._y1) / (h1 || h0 < 0 && -0),\n p = (s0 * h1 + s1 * h0) / (h0 + h1);\n return (sign(s0) + sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0;\n}\n\n// Calculate a one-sided slope.\nfunction slope2(that, t) {\n var h = that._x1 - that._x0;\n return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t;\n}\n\n// According to https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Representations\n// \"you can express cubic Hermite interpolation in terms of cubic B\u00E9zier curves\n// with respect to the four values p0, p0 + m0 / 3, p1 - m1 / 3, p1\".\nfunction point(that, t0, t1) {\n var x0 = that._x0,\n y0 = that._y0,\n x1 = that._x1,\n y1 = that._y1,\n dx = (x1 - x0) / 3;\n that._context.bezierCurveTo(x0 + dx, y0 + dx * t0, x1 - dx, y1 - dx * t1, x1, y1);\n}\n\nfunction MonotoneX(context) {\n this._context = context;\n}\n\nMonotoneX.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 =\n this._y0 = this._y1 =\n this._t0 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 2: this._context.lineTo(this._x1, this._y1); break;\n case 3: point(this, this._t0, slope2(this, this._t0)); break;\n }\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n var t1 = NaN;\n\n x = +x, y = +y;\n if (x === this._x1 && y === this._y1) return; // Ignore coincident points.\n switch (this._point) {\n case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;\n case 1: this._point = 2; break;\n case 2: this._point = 3; point(this, slope2(this, t1 = slope3(this, x, y)), t1); break;\n default: point(this, this._t0, t1 = slope3(this, x, y)); break;\n }\n\n this._x0 = this._x1, this._x1 = x;\n this._y0 = this._y1, this._y1 = y;\n this._t0 = t1;\n }\n}\n\nfunction MonotoneY(context) {\n this._context = new ReflectContext(context);\n}\n\n(MonotoneY.prototype = Object.create(MonotoneX.prototype)).point = function(x, y) {\n MonotoneX.prototype.point.call(this, y, x);\n};\n\nfunction ReflectContext(context) {\n this._context = context;\n}\n\nReflectContext.prototype = {\n moveTo: function(x, y) { this._context.moveTo(y, x); },\n closePath: function() { this._context.closePath(); },\n lineTo: function(x, y) { this._context.lineTo(y, x); },\n bezierCurveTo: function(x1, y1, x2, y2, x, y) { this._context.bezierCurveTo(y1, x1, y2, x2, y, x); }\n};\n\nexport function monotoneX(context) {\n return new MonotoneX(context);\n}\n\nexport function monotoneY(context) {\n return new MonotoneY(context);\n}\n", "function Natural(context) {\n this._context = context;\n}\n\nNatural.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x = [];\n this._y = [];\n },\n lineEnd: function() {\n var x = this._x,\n y = this._y,\n n = x.length;\n\n if (n) {\n this._line ? this._context.lineTo(x[0], y[0]) : this._context.moveTo(x[0], y[0]);\n if (n === 2) {\n this._context.lineTo(x[1], y[1]);\n } else {\n var px = controlPoints(x),\n py = controlPoints(y);\n for (var i0 = 0, i1 = 1; i1 < n; ++i0, ++i1) {\n this._context.bezierCurveTo(px[0][i0], py[0][i0], px[1][i0], py[1][i0], x[i1], y[i1]);\n }\n }\n }\n\n if (this._line || (this._line !== 0 && n === 1)) this._context.closePath();\n this._line = 1 - this._line;\n this._x = this._y = null;\n },\n point: function(x, y) {\n this._x.push(+x);\n this._y.push(+y);\n }\n};\n\n// See https://www.particleincell.com/2012/bezier-splines/ for derivation.\nfunction controlPoints(x) {\n var i,\n n = x.length - 1,\n m,\n a = new Array(n),\n b = new Array(n),\n r = new Array(n);\n a[0] = 0, b[0] = 2, r[0] = x[0] + 2 * x[1];\n for (i = 1; i < n - 1; ++i) a[i] = 1, b[i] = 4, r[i] = 4 * x[i] + 2 * x[i + 1];\n a[n - 1] = 2, b[n - 1] = 7, r[n - 1] = 8 * x[n - 1] + x[n];\n for (i = 1; i < n; ++i) m = a[i] / b[i - 1], b[i] -= m, r[i] -= m * r[i - 1];\n a[n - 1] = r[n - 1] / b[n - 1];\n for (i = n - 2; i >= 0; --i) a[i] = (r[i] - a[i + 1]) / b[i];\n b[n - 1] = (x[n] + a[n - 1]) / 2;\n for (i = 0; i < n - 1; ++i) b[i] = 2 * x[i + 1] - a[i + 1];\n return [a, b];\n}\n\nexport default function(context) {\n return new Natural(context);\n}\n", "function Step(context, t) {\n this._context = context;\n this._t = t;\n}\n\nStep.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x = this._y = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n if (0 < this._t && this._t < 1 && this._point === 2) this._context.lineTo(this._x, this._y);\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n if (this._line >= 0) this._t = 1 - this._t, this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;\n case 1: this._point = 2; // falls through\n default: {\n if (this._t <= 0) {\n this._context.lineTo(this._x, y);\n this._context.lineTo(x, y);\n } else {\n var x1 = this._x * (1 - this._t) + x * this._t;\n this._context.lineTo(x1, this._y);\n this._context.lineTo(x1, y);\n }\n break;\n }\n }\n this._x = x, this._y = y;\n }\n};\n\nexport default function(context) {\n return new Step(context, 0.5);\n}\n\nexport function stepBefore(context) {\n return new Step(context, 0);\n}\n\nexport function stepAfter(context) {\n return new Step(context, 1);\n}\n", "export default function(series, order) {\n if (!((n = series.length) > 1)) return;\n for (var i = 1, j, s0, s1 = series[order[0]], n, m = s1.length; i < n; ++i) {\n s0 = s1, s1 = series[order[i]];\n for (j = 0; j < m; ++j) {\n s1[j][1] += s1[j][0] = isNaN(s0[j][1]) ? s0[j][0] : s0[j][1];\n }\n }\n}\n", "export default function(series) {\n var n = series.length, o = new Array(n);\n while (--n >= 0) o[n] = n;\n return o;\n}\n", "import array from \"./array.js\";\nimport constant from \"./constant.js\";\nimport offsetNone from \"./offset/none.js\";\nimport orderNone from \"./order/none.js\";\n\nfunction stackValue(d, key) {\n return d[key];\n}\n\nfunction stackSeries(key) {\n const series = [];\n series.key = key;\n return series;\n}\n\nexport default function() {\n var keys = constant([]),\n order = orderNone,\n offset = offsetNone,\n value = stackValue;\n\n function stack(data) {\n var sz = Array.from(keys.apply(this, arguments), stackSeries),\n i, n = sz.length, j = -1,\n oz;\n\n for (const d of data) {\n for (i = 0, ++j; i < n; ++i) {\n (sz[i][j] = [0, +value(d, sz[i].key, j, data)]).data = d;\n }\n }\n\n for (i = 0, oz = array(order(sz)); i < n; ++i) {\n sz[oz[i]].index = i;\n }\n\n offset(sz, oz);\n return sz;\n }\n\n stack.keys = function(_) {\n return arguments.length ? (keys = typeof _ === \"function\" ? _ : constant(Array.from(_)), stack) : keys;\n };\n\n stack.value = function(_) {\n return arguments.length ? (value = typeof _ === \"function\" ? _ : constant(+_), stack) : value;\n };\n\n stack.order = function(_) {\n return arguments.length ? (order = _ == null ? orderNone : typeof _ === \"function\" ? _ : constant(Array.from(_)), stack) : order;\n };\n\n stack.offset = function(_) {\n return arguments.length ? (offset = _ == null ? offsetNone : _, stack) : offset;\n };\n\n return stack;\n}\n", "import none from \"./none.js\";\n\nexport default function(series, order) {\n if (!((n = series.length) > 0)) return;\n for (var i, n, j = 0, m = series[0].length, y; j < m; ++j) {\n for (y = i = 0; i < n; ++i) y += series[i][j][1] || 0;\n if (y) for (i = 0; i < n; ++i) series[i][j][1] /= y;\n }\n none(series, order);\n}\n", "import none from \"./none.js\";\n\nexport default function(series, order) {\n if (!((n = series.length) > 0)) return;\n for (var j = 0, s0 = series[order[0]], n, m = s0.length; j < m; ++j) {\n for (var i = 0, y = 0; i < n; ++i) y += series[i][j][1] || 0;\n s0[j][1] += s0[j][0] = -y / 2;\n }\n none(series, order);\n}\n", "import none from \"./none.js\";\n\nexport default function(series, order) {\n if (!((n = series.length) > 0) || !((m = (s0 = series[order[0]]).length) > 0)) return;\n for (var y = 0, j = 1, s0, m, n; j < m; ++j) {\n for (var i = 0, s1 = 0, s2 = 0; i < n; ++i) {\n var si = series[order[i]],\n sij0 = si[j][1] || 0,\n sij1 = si[j - 1][1] || 0,\n s3 = (sij0 - sij1) / 2;\n for (var k = 0; k < i; ++k) {\n var sk = series[order[k]],\n skj0 = sk[j][1] || 0,\n skj1 = sk[j - 1][1] || 0;\n s3 += skj0 - skj1;\n }\n s1 += sij0, s2 += s3 * sij0;\n }\n s0[j - 1][1] += s0[j - 1][0] = y;\n if (s1) y -= s2 / s1;\n }\n s0[j - 1][1] += s0[j - 1][0] = y;\n none(series, order);\n}\n", "import uniqBy from 'lodash/uniqBy';\nimport isFunction from 'lodash/isFunction';\n\n/**\n * This is configuration option that decides how to filter for unique values only:\n *\n * - `false` means \"no filter\"\n * - `true` means \"use recharts default filter\"\n * - function means \"use return of this function as the default key\"\n */\n\nexport function getUniqPayload(payload, option, defaultUniqBy) {\n if (option === true) {\n return uniqBy(payload, defaultUniqBy);\n }\n if (isFunction(option)) {\n return uniqBy(payload, option);\n }\n return payload;\n}", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Tooltip\n */\nimport React, { PureComponent } from 'react';\nimport { DefaultTooltipContent } from './DefaultTooltipContent';\nimport { TooltipBoundingBox } from './TooltipBoundingBox';\nimport { Global } from '../util/Global';\nimport { getUniqPayload } from '../util/payload/getUniqPayload';\nfunction defaultUniqBy(entry) {\n return entry.dataKey;\n}\nfunction renderContent(content, props) {\n if ( /*#__PURE__*/React.isValidElement(content)) {\n return /*#__PURE__*/React.cloneElement(content, props);\n }\n if (typeof content === 'function') {\n return /*#__PURE__*/React.createElement(content, props);\n }\n return /*#__PURE__*/React.createElement(DefaultTooltipContent, props);\n}\nexport var Tooltip = /*#__PURE__*/function (_PureComponent) {\n function Tooltip() {\n _classCallCheck(this, Tooltip);\n return _callSuper(this, Tooltip, arguments);\n }\n _inherits(Tooltip, _PureComponent);\n return _createClass(Tooltip, [{\n key: \"render\",\n value: function render() {\n var _this = this;\n var _this$props = this.props,\n active = _this$props.active,\n allowEscapeViewBox = _this$props.allowEscapeViewBox,\n animationDuration = _this$props.animationDuration,\n animationEasing = _this$props.animationEasing,\n content = _this$props.content,\n coordinate = _this$props.coordinate,\n filterNull = _this$props.filterNull,\n isAnimationActive = _this$props.isAnimationActive,\n offset = _this$props.offset,\n payload = _this$props.payload,\n payloadUniqBy = _this$props.payloadUniqBy,\n position = _this$props.position,\n reverseDirection = _this$props.reverseDirection,\n useTranslate3d = _this$props.useTranslate3d,\n viewBox = _this$props.viewBox,\n wrapperStyle = _this$props.wrapperStyle;\n var finalPayload = payload !== null && payload !== void 0 ? payload : [];\n if (filterNull && finalPayload.length) {\n finalPayload = getUniqPayload(payload.filter(function (entry) {\n return entry.value != null && (entry.hide !== true || _this.props.includeHidden);\n }), payloadUniqBy, defaultUniqBy);\n }\n var hasPayload = finalPayload.length > 0;\n return /*#__PURE__*/React.createElement(TooltipBoundingBox, {\n allowEscapeViewBox: allowEscapeViewBox,\n animationDuration: animationDuration,\n animationEasing: animationEasing,\n isAnimationActive: isAnimationActive,\n active: active,\n coordinate: coordinate,\n hasPayload: hasPayload,\n offset: offset,\n position: position,\n reverseDirection: reverseDirection,\n useTranslate3d: useTranslate3d,\n viewBox: viewBox,\n wrapperStyle: wrapperStyle\n }, renderContent(content, _objectSpread(_objectSpread({}, this.props), {}, {\n payload: finalPayload\n })));\n }\n }]);\n}(PureComponent);\n_defineProperty(Tooltip, \"displayName\", 'Tooltip');\n_defineProperty(Tooltip, \"defaultProps\", {\n accessibilityLayer: false,\n allowEscapeViewBox: {\n x: false,\n y: false\n },\n animationDuration: 400,\n animationEasing: 'ease',\n contentStyle: {},\n coordinate: {\n x: 0,\n y: 0\n },\n cursor: true,\n cursorStyle: {},\n filterNull: true,\n isAnimationActive: !Global.isSsr,\n itemStyle: {},\n labelStyle: {},\n offset: 10,\n reverseDirection: {\n x: false,\n y: false\n },\n separator: ' : ',\n trigger: 'hover',\n useTranslate3d: false,\n viewBox: {\n x: 0,\n y: 0,\n height: 0,\n width: 0\n },\n wrapperStyle: {}\n});", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Default Tooltip Content\n */\n\nimport React from 'react';\nimport sortBy from 'lodash/sortBy';\nimport isNil from 'lodash/isNil';\nimport clsx from 'clsx';\nimport { isNumOrStr } from '../util/DataUtils';\nfunction defaultFormatter(value) {\n return Array.isArray(value) && isNumOrStr(value[0]) && isNumOrStr(value[1]) ? value.join(' ~ ') : value;\n}\nexport var DefaultTooltipContent = function DefaultTooltipContent(props) {\n var _props$separator = props.separator,\n separator = _props$separator === void 0 ? ' : ' : _props$separator,\n _props$contentStyle = props.contentStyle,\n contentStyle = _props$contentStyle === void 0 ? {} : _props$contentStyle,\n _props$itemStyle = props.itemStyle,\n itemStyle = _props$itemStyle === void 0 ? {} : _props$itemStyle,\n _props$labelStyle = props.labelStyle,\n labelStyle = _props$labelStyle === void 0 ? {} : _props$labelStyle,\n payload = props.payload,\n formatter = props.formatter,\n itemSorter = props.itemSorter,\n wrapperClassName = props.wrapperClassName,\n labelClassName = props.labelClassName,\n label = props.label,\n labelFormatter = props.labelFormatter,\n _props$accessibilityL = props.accessibilityLayer,\n accessibilityLayer = _props$accessibilityL === void 0 ? false : _props$accessibilityL;\n var renderContent = function renderContent() {\n if (payload && payload.length) {\n var listStyle = {\n padding: 0,\n margin: 0\n };\n var items = (itemSorter ? sortBy(payload, itemSorter) : payload).map(function (entry, i) {\n if (entry.type === 'none') {\n return null;\n }\n var finalItemStyle = _objectSpread({\n display: 'block',\n paddingTop: 4,\n paddingBottom: 4,\n color: entry.color || '#000'\n }, itemStyle);\n var finalFormatter = entry.formatter || formatter || defaultFormatter;\n var value = entry.value,\n name = entry.name;\n var finalValue = value;\n var finalName = name;\n if (finalFormatter && finalValue != null && finalName != null) {\n var formatted = finalFormatter(value, name, entry, i, payload);\n if (Array.isArray(formatted)) {\n var _formatted = _slicedToArray(formatted, 2);\n finalValue = _formatted[0];\n finalName = _formatted[1];\n } else {\n finalValue = formatted;\n }\n }\n return (\n /*#__PURE__*/\n // eslint-disable-next-line react/no-array-index-key\n React.createElement(\"li\", {\n className: \"recharts-tooltip-item\",\n key: \"tooltip-item-\".concat(i),\n style: finalItemStyle\n }, isNumOrStr(finalName) ? /*#__PURE__*/React.createElement(\"span\", {\n className: \"recharts-tooltip-item-name\"\n }, finalName) : null, isNumOrStr(finalName) ? /*#__PURE__*/React.createElement(\"span\", {\n className: \"recharts-tooltip-item-separator\"\n }, separator) : null, /*#__PURE__*/React.createElement(\"span\", {\n className: \"recharts-tooltip-item-value\"\n }, finalValue), /*#__PURE__*/React.createElement(\"span\", {\n className: \"recharts-tooltip-item-unit\"\n }, entry.unit || ''))\n );\n });\n return /*#__PURE__*/React.createElement(\"ul\", {\n className: \"recharts-tooltip-item-list\",\n style: listStyle\n }, items);\n }\n return null;\n };\n var finalStyle = _objectSpread({\n margin: 0,\n padding: 10,\n backgroundColor: '#fff',\n border: '1px solid #ccc',\n whiteSpace: 'nowrap'\n }, contentStyle);\n var finalLabelStyle = _objectSpread({\n margin: 0\n }, labelStyle);\n var hasLabel = !isNil(label);\n var finalLabel = hasLabel ? label : '';\n var wrapperCN = clsx('recharts-default-tooltip', wrapperClassName);\n var labelCN = clsx('recharts-tooltip-label', labelClassName);\n if (hasLabel && labelFormatter && payload !== undefined && payload !== null) {\n finalLabel = labelFormatter(label, payload);\n }\n var accessibilityAttributes = accessibilityLayer ? {\n role: 'status',\n 'aria-live': 'assertive'\n } : {};\n return /*#__PURE__*/React.createElement(\"div\", _extends({\n className: wrapperCN,\n style: finalStyle\n }, accessibilityAttributes), /*#__PURE__*/React.createElement(\"p\", {\n className: labelCN,\n style: finalLabelStyle\n }, /*#__PURE__*/React.isValidElement(finalLabel) ? finalLabel : \"\".concat(finalLabel)), renderContent());\n};", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nimport React, { PureComponent } from 'react';\nimport { getTooltipTranslate } from '../util/tooltip/translate';\nvar EPSILON = 1;\nexport var TooltipBoundingBox = /*#__PURE__*/function (_PureComponent) {\n function TooltipBoundingBox() {\n var _this;\n _classCallCheck(this, TooltipBoundingBox);\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n _this = _callSuper(this, TooltipBoundingBox, [].concat(args));\n _defineProperty(_this, \"state\", {\n dismissed: false,\n dismissedAtCoordinate: {\n x: 0,\n y: 0\n },\n lastBoundingBox: {\n width: -1,\n height: -1\n }\n });\n _defineProperty(_this, \"handleKeyDown\", function (event) {\n if (event.key === 'Escape') {\n var _this$props$coordinat, _this$props$coordinat2, _this$props$coordinat3, _this$props$coordinat4;\n _this.setState({\n dismissed: true,\n dismissedAtCoordinate: {\n x: (_this$props$coordinat = (_this$props$coordinat2 = _this.props.coordinate) === null || _this$props$coordinat2 === void 0 ? void 0 : _this$props$coordinat2.x) !== null && _this$props$coordinat !== void 0 ? _this$props$coordinat : 0,\n y: (_this$props$coordinat3 = (_this$props$coordinat4 = _this.props.coordinate) === null || _this$props$coordinat4 === void 0 ? void 0 : _this$props$coordinat4.y) !== null && _this$props$coordinat3 !== void 0 ? _this$props$coordinat3 : 0\n }\n });\n }\n });\n return _this;\n }\n _inherits(TooltipBoundingBox, _PureComponent);\n return _createClass(TooltipBoundingBox, [{\n key: \"updateBBox\",\n value: function updateBBox() {\n if (this.wrapperNode && this.wrapperNode.getBoundingClientRect) {\n var box = this.wrapperNode.getBoundingClientRect();\n if (Math.abs(box.width - this.state.lastBoundingBox.width) > EPSILON || Math.abs(box.height - this.state.lastBoundingBox.height) > EPSILON) {\n this.setState({\n lastBoundingBox: {\n width: box.width,\n height: box.height\n }\n });\n }\n } else if (this.state.lastBoundingBox.width !== -1 || this.state.lastBoundingBox.height !== -1) {\n this.setState({\n lastBoundingBox: {\n width: -1,\n height: -1\n }\n });\n }\n }\n }, {\n key: \"componentDidMount\",\n value: function componentDidMount() {\n document.addEventListener('keydown', this.handleKeyDown);\n this.updateBBox();\n }\n }, {\n key: \"componentWillUnmount\",\n value: function componentWillUnmount() {\n document.removeEventListener('keydown', this.handleKeyDown);\n }\n }, {\n key: \"componentDidUpdate\",\n value: function componentDidUpdate() {\n var _this$props$coordinat5, _this$props$coordinat6;\n if (this.props.active) {\n this.updateBBox();\n }\n if (!this.state.dismissed) {\n return;\n }\n if (((_this$props$coordinat5 = this.props.coordinate) === null || _this$props$coordinat5 === void 0 ? void 0 : _this$props$coordinat5.x) !== this.state.dismissedAtCoordinate.x || ((_this$props$coordinat6 = this.props.coordinate) === null || _this$props$coordinat6 === void 0 ? void 0 : _this$props$coordinat6.y) !== this.state.dismissedAtCoordinate.y) {\n this.state.dismissed = false;\n }\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this2 = this;\n var _this$props = this.props,\n active = _this$props.active,\n allowEscapeViewBox = _this$props.allowEscapeViewBox,\n animationDuration = _this$props.animationDuration,\n animationEasing = _this$props.animationEasing,\n children = _this$props.children,\n coordinate = _this$props.coordinate,\n hasPayload = _this$props.hasPayload,\n isAnimationActive = _this$props.isAnimationActive,\n offset = _this$props.offset,\n position = _this$props.position,\n reverseDirection = _this$props.reverseDirection,\n useTranslate3d = _this$props.useTranslate3d,\n viewBox = _this$props.viewBox,\n wrapperStyle = _this$props.wrapperStyle;\n var _getTooltipTranslate = getTooltipTranslate({\n allowEscapeViewBox: allowEscapeViewBox,\n coordinate: coordinate,\n offsetTopLeft: offset,\n position: position,\n reverseDirection: reverseDirection,\n tooltipBox: this.state.lastBoundingBox,\n useTranslate3d: useTranslate3d,\n viewBox: viewBox\n }),\n cssClasses = _getTooltipTranslate.cssClasses,\n cssProperties = _getTooltipTranslate.cssProperties;\n var outerStyle = _objectSpread(_objectSpread({\n transition: isAnimationActive && active ? \"transform \".concat(animationDuration, \"ms \").concat(animationEasing) : undefined\n }, cssProperties), {}, {\n pointerEvents: 'none',\n visibility: !this.state.dismissed && active && hasPayload ? 'visible' : 'hidden',\n position: 'absolute',\n top: 0,\n left: 0\n }, wrapperStyle);\n return (\n /*#__PURE__*/\n // This element allow listening to the `Escape` key.\n // See https://github.com/recharts/recharts/pull/2925\n React.createElement(\"div\", {\n tabIndex: -1,\n className: cssClasses,\n style: outerStyle,\n ref: function ref(node) {\n _this2.wrapperNode = node;\n }\n }, children)\n );\n }\n }]);\n}(PureComponent);", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nimport clsx from 'clsx';\nimport { isNumber } from '../DataUtils';\nvar CSS_CLASS_PREFIX = 'recharts-tooltip-wrapper';\nvar TOOLTIP_HIDDEN = {\n visibility: 'hidden'\n};\nexport function getTooltipCSSClassName(_ref) {\n var coordinate = _ref.coordinate,\n translateX = _ref.translateX,\n translateY = _ref.translateY;\n return clsx(CSS_CLASS_PREFIX, _defineProperty(_defineProperty(_defineProperty(_defineProperty({}, \"\".concat(CSS_CLASS_PREFIX, \"-right\"), isNumber(translateX) && coordinate && isNumber(coordinate.x) && translateX >= coordinate.x), \"\".concat(CSS_CLASS_PREFIX, \"-left\"), isNumber(translateX) && coordinate && isNumber(coordinate.x) && translateX < coordinate.x), \"\".concat(CSS_CLASS_PREFIX, \"-bottom\"), isNumber(translateY) && coordinate && isNumber(coordinate.y) && translateY >= coordinate.y), \"\".concat(CSS_CLASS_PREFIX, \"-top\"), isNumber(translateY) && coordinate && isNumber(coordinate.y) && translateY < coordinate.y));\n}\nexport function getTooltipTranslateXY(_ref2) {\n var allowEscapeViewBox = _ref2.allowEscapeViewBox,\n coordinate = _ref2.coordinate,\n key = _ref2.key,\n offsetTopLeft = _ref2.offsetTopLeft,\n position = _ref2.position,\n reverseDirection = _ref2.reverseDirection,\n tooltipDimension = _ref2.tooltipDimension,\n viewBox = _ref2.viewBox,\n viewBoxDimension = _ref2.viewBoxDimension;\n if (position && isNumber(position[key])) {\n return position[key];\n }\n var negative = coordinate[key] - tooltipDimension - offsetTopLeft;\n var positive = coordinate[key] + offsetTopLeft;\n if (allowEscapeViewBox[key]) {\n return reverseDirection[key] ? negative : positive;\n }\n if (reverseDirection[key]) {\n var _tooltipBoundary = negative;\n var _viewBoxBoundary = viewBox[key];\n if (_tooltipBoundary < _viewBoxBoundary) {\n return Math.max(positive, viewBox[key]);\n }\n return Math.max(negative, viewBox[key]);\n }\n var tooltipBoundary = positive + tooltipDimension;\n var viewBoxBoundary = viewBox[key] + viewBoxDimension;\n if (tooltipBoundary > viewBoxBoundary) {\n return Math.max(negative, viewBox[key]);\n }\n return Math.max(positive, viewBox[key]);\n}\nexport function getTransformStyle(_ref3) {\n var translateX = _ref3.translateX,\n translateY = _ref3.translateY,\n useTranslate3d = _ref3.useTranslate3d;\n return {\n transform: useTranslate3d ? \"translate3d(\".concat(translateX, \"px, \").concat(translateY, \"px, 0)\") : \"translate(\".concat(translateX, \"px, \").concat(translateY, \"px)\")\n };\n}\nexport function getTooltipTranslate(_ref4) {\n var allowEscapeViewBox = _ref4.allowEscapeViewBox,\n coordinate = _ref4.coordinate,\n offsetTopLeft = _ref4.offsetTopLeft,\n position = _ref4.position,\n reverseDirection = _ref4.reverseDirection,\n tooltipBox = _ref4.tooltipBox,\n useTranslate3d = _ref4.useTranslate3d,\n viewBox = _ref4.viewBox;\n var cssProperties, translateX, translateY;\n if (tooltipBox.height > 0 && tooltipBox.width > 0 && coordinate) {\n translateX = getTooltipTranslateXY({\n allowEscapeViewBox: allowEscapeViewBox,\n coordinate: coordinate,\n key: 'x',\n offsetTopLeft: offsetTopLeft,\n position: position,\n reverseDirection: reverseDirection,\n tooltipDimension: tooltipBox.width,\n viewBox: viewBox,\n viewBoxDimension: viewBox.width\n });\n translateY = getTooltipTranslateXY({\n allowEscapeViewBox: allowEscapeViewBox,\n coordinate: coordinate,\n key: 'y',\n offsetTopLeft: offsetTopLeft,\n position: position,\n reverseDirection: reverseDirection,\n tooltipDimension: tooltipBox.height,\n viewBox: viewBox,\n viewBoxDimension: viewBox.height\n });\n cssProperties = getTransformStyle({\n translateX: translateX,\n translateY: translateY,\n useTranslate3d: useTranslate3d\n });\n } else {\n cssProperties = TOOLTIP_HIDDEN;\n }\n return {\n cssProperties: cssProperties,\n cssClasses: getTooltipCSSClassName({\n translateX: translateX,\n translateY: translateY,\n coordinate: coordinate\n })\n };\n}", "var parseIsSsrByDefault = function parseIsSsrByDefault() {\n return !(typeof window !== 'undefined' && window.document && window.document.createElement && window.setTimeout);\n};\nexport var Global = {\n isSsr: parseIsSsrByDefault(),\n get: function get(key) {\n return Global[key];\n },\n set: function set(key, value) {\n if (typeof key === 'string') {\n Global[key] = value;\n } else {\n var keys = Object.keys(key);\n if (keys && keys.length) {\n keys.forEach(function (k) {\n Global[k] = key[k];\n });\n }\n }\n }\n};", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n/**\n * @fileOverview Wrapper component to make charts adapt to the size of parent * DOM\n */\nimport clsx from 'clsx';\nimport React, { forwardRef, cloneElement, useState, useImperativeHandle, useRef, useEffect, useMemo, useCallback } from 'react';\nimport throttle from 'lodash/throttle';\nimport { isPercent } from '../util/DataUtils';\nimport { warn } from '../util/LogUtils';\nimport { getDisplayName } from '../util/ReactUtils';\nexport var ResponsiveContainer = /*#__PURE__*/forwardRef(function (_ref, ref) {\n var aspect = _ref.aspect,\n _ref$initialDimension = _ref.initialDimension,\n initialDimension = _ref$initialDimension === void 0 ? {\n width: -1,\n height: -1\n } : _ref$initialDimension,\n _ref$width = _ref.width,\n width = _ref$width === void 0 ? '100%' : _ref$width,\n _ref$height = _ref.height,\n height = _ref$height === void 0 ? '100%' : _ref$height,\n _ref$minWidth = _ref.minWidth,\n minWidth = _ref$minWidth === void 0 ? 0 : _ref$minWidth,\n minHeight = _ref.minHeight,\n maxHeight = _ref.maxHeight,\n children = _ref.children,\n _ref$debounce = _ref.debounce,\n debounce = _ref$debounce === void 0 ? 0 : _ref$debounce,\n id = _ref.id,\n className = _ref.className,\n onResize = _ref.onResize,\n _ref$style = _ref.style,\n style = _ref$style === void 0 ? {} : _ref$style;\n var containerRef = useRef(null);\n var onResizeRef = useRef();\n onResizeRef.current = onResize;\n useImperativeHandle(ref, function () {\n return Object.defineProperty(containerRef.current, 'current', {\n get: function get() {\n // eslint-disable-next-line no-console\n console.warn('The usage of ref.current.current is deprecated and will no longer be supported.');\n return containerRef.current;\n },\n configurable: true\n });\n });\n var _useState = useState({\n containerWidth: initialDimension.width,\n containerHeight: initialDimension.height\n }),\n _useState2 = _slicedToArray(_useState, 2),\n sizes = _useState2[0],\n setSizes = _useState2[1];\n var setContainerSize = useCallback(function (newWidth, newHeight) {\n setSizes(function (prevState) {\n var roundedWidth = Math.round(newWidth);\n var roundedHeight = Math.round(newHeight);\n if (prevState.containerWidth === roundedWidth && prevState.containerHeight === roundedHeight) {\n return prevState;\n }\n return {\n containerWidth: roundedWidth,\n containerHeight: roundedHeight\n };\n });\n }, []);\n useEffect(function () {\n var callback = function callback(entries) {\n var _onResizeRef$current;\n var _entries$0$contentRec = entries[0].contentRect,\n containerWidth = _entries$0$contentRec.width,\n containerHeight = _entries$0$contentRec.height;\n setContainerSize(containerWidth, containerHeight);\n (_onResizeRef$current = onResizeRef.current) === null || _onResizeRef$current === void 0 || _onResizeRef$current.call(onResizeRef, containerWidth, containerHeight);\n };\n if (debounce > 0) {\n callback = throttle(callback, debounce, {\n trailing: true,\n leading: false\n });\n }\n var observer = new ResizeObserver(callback);\n var _containerRef$current = containerRef.current.getBoundingClientRect(),\n containerWidth = _containerRef$current.width,\n containerHeight = _containerRef$current.height;\n setContainerSize(containerWidth, containerHeight);\n observer.observe(containerRef.current);\n return function () {\n observer.disconnect();\n };\n }, [setContainerSize, debounce]);\n var chartContent = useMemo(function () {\n var containerWidth = sizes.containerWidth,\n containerHeight = sizes.containerHeight;\n if (containerWidth < 0 || containerHeight < 0) {\n return null;\n }\n warn(isPercent(width) || isPercent(height), \"The width(%s) and height(%s) are both fixed numbers,\\n maybe you don't need to use a ResponsiveContainer.\", width, height);\n warn(!aspect || aspect > 0, 'The aspect(%s) must be greater than zero.', aspect);\n var calculatedWidth = isPercent(width) ? containerWidth : width;\n var calculatedHeight = isPercent(height) ? containerHeight : height;\n if (aspect && aspect > 0) {\n // Preserve the desired aspect ratio\n if (calculatedWidth) {\n // Will default to using width for aspect ratio\n calculatedHeight = calculatedWidth / aspect;\n } else if (calculatedHeight) {\n // But we should also take height into consideration\n calculatedWidth = calculatedHeight * aspect;\n }\n\n // if maxHeight is set, overwrite if calculatedHeight is greater than maxHeight\n if (maxHeight && calculatedHeight > maxHeight) {\n calculatedHeight = maxHeight;\n }\n }\n warn(calculatedWidth > 0 || calculatedHeight > 0, \"The width(%s) and height(%s) of chart should be greater than 0,\\n please check the style of container, or the props width(%s) and height(%s),\\n or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the\\n height and width.\", calculatedWidth, calculatedHeight, width, height, minWidth, minHeight, aspect);\n var isCharts = !Array.isArray(children) && getDisplayName(children.type).endsWith('Chart');\n return React.Children.map(children, function (child) {\n if ( /*#__PURE__*/React.isValidElement(child)) {\n return /*#__PURE__*/cloneElement(child, _objectSpread({\n width: calculatedWidth,\n height: calculatedHeight\n }, isCharts ? {\n style: _objectSpread({\n height: '100%',\n width: '100%',\n maxHeight: calculatedHeight,\n maxWidth: calculatedWidth\n }, child.props.style)\n } : {}));\n }\n return child;\n });\n }, [aspect, children, height, maxHeight, minHeight, minWidth, sizes, width]);\n return /*#__PURE__*/React.createElement(\"div\", {\n id: id ? \"\".concat(id) : undefined,\n className: clsx('recharts-responsive-container', className),\n style: _objectSpread(_objectSpread({}, style), {}, {\n width: width,\n height: height,\n minWidth: minWidth,\n minHeight: minHeight,\n maxHeight: maxHeight\n }),\n ref: containerRef\n }, chartContent);\n});", "/**\n * @fileOverview Cross\n */\n\nexport var Cell = function Cell(_props) {\n return null;\n};\nCell.displayName = 'Cell';", "var _excluded = [\"x\", \"y\", \"lineHeight\", \"capHeight\", \"scaleToFit\", \"textAnchor\", \"verticalAnchor\", \"fill\"],\n _excluded2 = [\"dx\", \"dy\", \"angle\", \"className\", \"breakAll\"];\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nimport React, { useMemo } from 'react';\nimport isNil from 'lodash/isNil';\nimport clsx from 'clsx';\nimport { isNumber, isNumOrStr } from '../util/DataUtils';\nimport { Global } from '../util/Global';\nimport { filterProps } from '../util/ReactUtils';\nimport { getStringSize } from '../util/DOMUtils';\nimport { reduceCSSCalc } from '../util/ReduceCSSCalc';\nvar BREAKING_SPACES = /[ \\f\\n\\r\\t\\v\\u2028\\u2029]+/;\nvar calculateWordWidths = function calculateWordWidths(_ref) {\n var children = _ref.children,\n breakAll = _ref.breakAll,\n style = _ref.style;\n try {\n var words = [];\n if (!isNil(children)) {\n if (breakAll) {\n words = children.toString().split('');\n } else {\n words = children.toString().split(BREAKING_SPACES);\n }\n }\n var wordsWithComputedWidth = words.map(function (word) {\n return {\n word: word,\n width: getStringSize(word, style).width\n };\n });\n var spaceWidth = breakAll ? 0 : getStringSize(\"\\xA0\", style).width;\n return {\n wordsWithComputedWidth: wordsWithComputedWidth,\n spaceWidth: spaceWidth\n };\n } catch (e) {\n return null;\n }\n};\nvar calculateWordsByLines = function calculateWordsByLines(_ref2, initialWordsWithComputedWith, spaceWidth, lineWidth, scaleToFit) {\n var maxLines = _ref2.maxLines,\n children = _ref2.children,\n style = _ref2.style,\n breakAll = _ref2.breakAll;\n var shouldLimitLines = isNumber(maxLines);\n var text = children;\n var calculate = function calculate() {\n var words = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n return words.reduce(function (result, _ref3) {\n var word = _ref3.word,\n width = _ref3.width;\n var currentLine = result[result.length - 1];\n if (currentLine && (lineWidth == null || scaleToFit || currentLine.width + width + spaceWidth < Number(lineWidth))) {\n // Word can be added to an existing line\n currentLine.words.push(word);\n currentLine.width += width + spaceWidth;\n } else {\n // Add first word to line or word is too long to scaleToFit on existing line\n var newLine = {\n words: [word],\n width: width\n };\n result.push(newLine);\n }\n return result;\n }, []);\n };\n var originalResult = calculate(initialWordsWithComputedWith);\n var findLongestLine = function findLongestLine(words) {\n return words.reduce(function (a, b) {\n return a.width > b.width ? a : b;\n });\n };\n if (!shouldLimitLines) {\n return originalResult;\n }\n var suffix = '\u2026';\n var checkOverflow = function checkOverflow(index) {\n var tempText = text.slice(0, index);\n var words = calculateWordWidths({\n breakAll: breakAll,\n style: style,\n children: tempText + suffix\n }).wordsWithComputedWidth;\n var result = calculate(words);\n var doesOverflow = result.length > maxLines || findLongestLine(result).width > Number(lineWidth);\n return [doesOverflow, result];\n };\n var start = 0;\n var end = text.length - 1;\n var iterations = 0;\n var trimmedResult;\n while (start <= end && iterations <= text.length - 1) {\n var middle = Math.floor((start + end) / 2);\n var prev = middle - 1;\n var _checkOverflow = checkOverflow(prev),\n _checkOverflow2 = _slicedToArray(_checkOverflow, 2),\n doesPrevOverflow = _checkOverflow2[0],\n result = _checkOverflow2[1];\n var _checkOverflow3 = checkOverflow(middle),\n _checkOverflow4 = _slicedToArray(_checkOverflow3, 1),\n doesMiddleOverflow = _checkOverflow4[0];\n if (!doesPrevOverflow && !doesMiddleOverflow) {\n start = middle + 1;\n }\n if (doesPrevOverflow && doesMiddleOverflow) {\n end = middle - 1;\n }\n if (!doesPrevOverflow && doesMiddleOverflow) {\n trimmedResult = result;\n break;\n }\n iterations++;\n }\n\n // Fallback to originalResult (result without trimming) if we cannot find the\n // where to trim. This should not happen :tm:\n return trimmedResult || originalResult;\n};\nvar getWordsWithoutCalculate = function getWordsWithoutCalculate(children) {\n var words = !isNil(children) ? children.toString().split(BREAKING_SPACES) : [];\n return [{\n words: words\n }];\n};\nvar getWordsByLines = function getWordsByLines(_ref4) {\n var width = _ref4.width,\n scaleToFit = _ref4.scaleToFit,\n children = _ref4.children,\n style = _ref4.style,\n breakAll = _ref4.breakAll,\n maxLines = _ref4.maxLines;\n // Only perform calculations if using features that require them (multiline, scaleToFit)\n if ((width || scaleToFit) && !Global.isSsr) {\n var wordsWithComputedWidth, spaceWidth;\n var wordWidths = calculateWordWidths({\n breakAll: breakAll,\n children: children,\n style: style\n });\n if (wordWidths) {\n var wcw = wordWidths.wordsWithComputedWidth,\n sw = wordWidths.spaceWidth;\n wordsWithComputedWidth = wcw;\n spaceWidth = sw;\n } else {\n return getWordsWithoutCalculate(children);\n }\n return calculateWordsByLines({\n breakAll: breakAll,\n children: children,\n maxLines: maxLines,\n style: style\n }, wordsWithComputedWidth, spaceWidth, width, scaleToFit);\n }\n return getWordsWithoutCalculate(children);\n};\nvar DEFAULT_FILL = '#808080';\nexport var Text = function Text(_ref5) {\n var _ref5$x = _ref5.x,\n propsX = _ref5$x === void 0 ? 0 : _ref5$x,\n _ref5$y = _ref5.y,\n propsY = _ref5$y === void 0 ? 0 : _ref5$y,\n _ref5$lineHeight = _ref5.lineHeight,\n lineHeight = _ref5$lineHeight === void 0 ? '1em' : _ref5$lineHeight,\n _ref5$capHeight = _ref5.capHeight,\n capHeight = _ref5$capHeight === void 0 ? '0.71em' : _ref5$capHeight,\n _ref5$scaleToFit = _ref5.scaleToFit,\n scaleToFit = _ref5$scaleToFit === void 0 ? false : _ref5$scaleToFit,\n _ref5$textAnchor = _ref5.textAnchor,\n textAnchor = _ref5$textAnchor === void 0 ? 'start' : _ref5$textAnchor,\n _ref5$verticalAnchor = _ref5.verticalAnchor,\n verticalAnchor = _ref5$verticalAnchor === void 0 ? 'end' : _ref5$verticalAnchor,\n _ref5$fill = _ref5.fill,\n fill = _ref5$fill === void 0 ? DEFAULT_FILL : _ref5$fill,\n props = _objectWithoutProperties(_ref5, _excluded);\n var wordsByLines = useMemo(function () {\n return getWordsByLines({\n breakAll: props.breakAll,\n children: props.children,\n maxLines: props.maxLines,\n scaleToFit: scaleToFit,\n style: props.style,\n width: props.width\n });\n }, [props.breakAll, props.children, props.maxLines, scaleToFit, props.style, props.width]);\n var dx = props.dx,\n dy = props.dy,\n angle = props.angle,\n className = props.className,\n breakAll = props.breakAll,\n textProps = _objectWithoutProperties(props, _excluded2);\n if (!isNumOrStr(propsX) || !isNumOrStr(propsY)) {\n return null;\n }\n var x = propsX + (isNumber(dx) ? dx : 0);\n var y = propsY + (isNumber(dy) ? dy : 0);\n var startDy;\n switch (verticalAnchor) {\n case 'start':\n startDy = reduceCSSCalc(\"calc(\".concat(capHeight, \")\"));\n break;\n case 'middle':\n startDy = reduceCSSCalc(\"calc(\".concat((wordsByLines.length - 1) / 2, \" * -\").concat(lineHeight, \" + (\").concat(capHeight, \" / 2))\"));\n break;\n default:\n startDy = reduceCSSCalc(\"calc(\".concat(wordsByLines.length - 1, \" * -\").concat(lineHeight, \")\"));\n break;\n }\n var transforms = [];\n if (scaleToFit) {\n var lineWidth = wordsByLines[0].width;\n var width = props.width;\n transforms.push(\"scale(\".concat((isNumber(width) ? width / lineWidth : 1) / lineWidth, \")\"));\n }\n if (angle) {\n transforms.push(\"rotate(\".concat(angle, \", \").concat(x, \", \").concat(y, \")\"));\n }\n if (transforms.length) {\n textProps.transform = transforms.join(' ');\n }\n return /*#__PURE__*/React.createElement(\"text\", _extends({}, filterProps(textProps, true), {\n x: x,\n y: y,\n className: clsx('recharts-text', className),\n textAnchor: textAnchor,\n fill: fill.includes('url') ? DEFAULT_FILL : fill\n }), wordsByLines.map(function (line, index) {\n var words = line.words.join(breakAll ? '' : ' ');\n return (\n /*#__PURE__*/\n // duplicate words will cause duplicate keys\n // eslint-disable-next-line react/no-array-index-key\n React.createElement(\"tspan\", {\n x: x,\n dy: index === 0 ? startDy : lineHeight,\n key: \"\".concat(words, \"-\").concat(index)\n }, words)\n );\n }));\n};", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nimport { Global } from './Global';\nvar stringCache = {\n widthCache: {},\n cacheCount: 0\n};\nvar MAX_CACHE_NUM = 2000;\nvar SPAN_STYLE = {\n position: 'absolute',\n top: '-20000px',\n left: 0,\n padding: 0,\n margin: 0,\n border: 'none',\n whiteSpace: 'pre'\n};\nvar STYLE_LIST = ['minWidth', 'maxWidth', 'width', 'minHeight', 'maxHeight', 'height', 'top', 'left', 'fontSize', 'lineHeight', 'padding', 'margin', 'paddingLeft', 'paddingRight', 'paddingTop', 'paddingBottom', 'marginLeft', 'marginRight', 'marginTop', 'marginBottom'];\nvar MEASUREMENT_SPAN_ID = 'recharts_measurement_span';\nfunction autoCompleteStyle(name, value) {\n if (STYLE_LIST.indexOf(name) >= 0 && value === +value) {\n return \"\".concat(value, \"px\");\n }\n return value;\n}\nfunction camelToMiddleLine(text) {\n var strs = text.split('');\n var formatStrs = strs.reduce(function (result, entry) {\n if (entry === entry.toUpperCase()) {\n return [].concat(_toConsumableArray(result), ['-', entry.toLowerCase()]);\n }\n return [].concat(_toConsumableArray(result), [entry]);\n }, []);\n return formatStrs.join('');\n}\nexport var getStyleString = function getStyleString(style) {\n return Object.keys(style).reduce(function (result, s) {\n return \"\".concat(result).concat(camelToMiddleLine(s), \":\").concat(autoCompleteStyle(s, style[s]), \";\");\n }, '');\n};\nfunction removeInvalidKeys(obj) {\n var copyObj = _objectSpread({}, obj);\n Object.keys(copyObj).forEach(function (key) {\n if (!copyObj[key]) {\n delete copyObj[key];\n }\n });\n return copyObj;\n}\nexport var getStringSize = function getStringSize(text) {\n var style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n if (text === undefined || text === null || Global.isSsr) {\n return {\n width: 0,\n height: 0\n };\n }\n var copyStyle = removeInvalidKeys(style);\n var cacheKey = JSON.stringify({\n text: text,\n copyStyle: copyStyle\n });\n if (stringCache.widthCache[cacheKey]) {\n return stringCache.widthCache[cacheKey];\n }\n try {\n var measurementSpan = document.getElementById(MEASUREMENT_SPAN_ID);\n if (!measurementSpan) {\n measurementSpan = document.createElement('span');\n measurementSpan.setAttribute('id', MEASUREMENT_SPAN_ID);\n measurementSpan.setAttribute('aria-hidden', 'true');\n document.body.appendChild(measurementSpan);\n }\n // Need to use CSS Object Model (CSSOM) to be able to comply with Content Security Policy (CSP)\n // https://en.wikipedia.org/wiki/Content_Security_Policy\n var measurementSpanStyle = _objectSpread(_objectSpread({}, SPAN_STYLE), copyStyle);\n Object.assign(measurementSpan.style, measurementSpanStyle);\n measurementSpan.textContent = \"\".concat(text);\n var rect = measurementSpan.getBoundingClientRect();\n var result = {\n width: rect.width,\n height: rect.height\n };\n stringCache.widthCache[cacheKey] = result;\n if (++stringCache.cacheCount > MAX_CACHE_NUM) {\n stringCache.cacheCount = 0;\n stringCache.widthCache = {};\n }\n return result;\n } catch (e) {\n return {\n width: 0,\n height: 0\n };\n }\n};\nexport var getOffset = function getOffset(rect) {\n return {\n top: rect.top + window.scrollY - document.documentElement.clientTop,\n left: rect.left + window.scrollX - document.documentElement.clientLeft\n };\n};", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar MULTIPLY_OR_DIVIDE_REGEX = /(-?\\d+(?:\\.\\d+)?[a-zA-Z%]*)([*/])(-?\\d+(?:\\.\\d+)?[a-zA-Z%]*)/;\nvar ADD_OR_SUBTRACT_REGEX = /(-?\\d+(?:\\.\\d+)?[a-zA-Z%]*)([+-])(-?\\d+(?:\\.\\d+)?[a-zA-Z%]*)/;\nvar CSS_LENGTH_UNIT_REGEX = /^px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q$/;\nvar NUM_SPLIT_REGEX = /(-?\\d+(?:\\.\\d+)?)([a-zA-Z%]+)?/;\nvar CONVERSION_RATES = {\n cm: 96 / 2.54,\n mm: 96 / 25.4,\n pt: 96 / 72,\n pc: 96 / 6,\n \"in\": 96,\n Q: 96 / (2.54 * 40),\n px: 1\n};\nvar FIXED_CSS_LENGTH_UNITS = Object.keys(CONVERSION_RATES);\nvar STR_NAN = 'NaN';\nfunction convertToPx(value, unit) {\n return value * CONVERSION_RATES[unit];\n}\nvar DecimalCSS = /*#__PURE__*/function () {\n function DecimalCSS(num, unit) {\n _classCallCheck(this, DecimalCSS);\n this.num = num;\n this.unit = unit;\n this.num = num;\n this.unit = unit;\n if (Number.isNaN(num)) {\n this.unit = '';\n }\n if (unit !== '' && !CSS_LENGTH_UNIT_REGEX.test(unit)) {\n this.num = NaN;\n this.unit = '';\n }\n if (FIXED_CSS_LENGTH_UNITS.includes(unit)) {\n this.num = convertToPx(num, unit);\n this.unit = 'px';\n }\n }\n return _createClass(DecimalCSS, [{\n key: \"add\",\n value: function add(other) {\n if (this.unit !== other.unit) {\n return new DecimalCSS(NaN, '');\n }\n return new DecimalCSS(this.num + other.num, this.unit);\n }\n }, {\n key: \"subtract\",\n value: function subtract(other) {\n if (this.unit !== other.unit) {\n return new DecimalCSS(NaN, '');\n }\n return new DecimalCSS(this.num - other.num, this.unit);\n }\n }, {\n key: \"multiply\",\n value: function multiply(other) {\n if (this.unit !== '' && other.unit !== '' && this.unit !== other.unit) {\n return new DecimalCSS(NaN, '');\n }\n return new DecimalCSS(this.num * other.num, this.unit || other.unit);\n }\n }, {\n key: \"divide\",\n value: function divide(other) {\n if (this.unit !== '' && other.unit !== '' && this.unit !== other.unit) {\n return new DecimalCSS(NaN, '');\n }\n return new DecimalCSS(this.num / other.num, this.unit || other.unit);\n }\n }, {\n key: \"toString\",\n value: function toString() {\n return \"\".concat(this.num).concat(this.unit);\n }\n }, {\n key: \"isNaN\",\n value: function isNaN() {\n return Number.isNaN(this.num);\n }\n }], [{\n key: \"parse\",\n value: function parse(str) {\n var _NUM_SPLIT_REGEX$exec;\n var _ref = (_NUM_SPLIT_REGEX$exec = NUM_SPLIT_REGEX.exec(str)) !== null && _NUM_SPLIT_REGEX$exec !== void 0 ? _NUM_SPLIT_REGEX$exec : [],\n _ref2 = _slicedToArray(_ref, 3),\n numStr = _ref2[1],\n unit = _ref2[2];\n return new DecimalCSS(parseFloat(numStr), unit !== null && unit !== void 0 ? unit : '');\n }\n }]);\n}();\nfunction calculateArithmetic(expr) {\n if (expr.includes(STR_NAN)) {\n return STR_NAN;\n }\n var newExpr = expr;\n while (newExpr.includes('*') || newExpr.includes('/')) {\n var _MULTIPLY_OR_DIVIDE_R;\n var _ref3 = (_MULTIPLY_OR_DIVIDE_R = MULTIPLY_OR_DIVIDE_REGEX.exec(newExpr)) !== null && _MULTIPLY_OR_DIVIDE_R !== void 0 ? _MULTIPLY_OR_DIVIDE_R : [],\n _ref4 = _slicedToArray(_ref3, 4),\n leftOperand = _ref4[1],\n operator = _ref4[2],\n rightOperand = _ref4[3];\n var lTs = DecimalCSS.parse(leftOperand !== null && leftOperand !== void 0 ? leftOperand : '');\n var rTs = DecimalCSS.parse(rightOperand !== null && rightOperand !== void 0 ? rightOperand : '');\n var result = operator === '*' ? lTs.multiply(rTs) : lTs.divide(rTs);\n if (result.isNaN()) {\n return STR_NAN;\n }\n newExpr = newExpr.replace(MULTIPLY_OR_DIVIDE_REGEX, result.toString());\n }\n while (newExpr.includes('+') || /.-\\d+(?:\\.\\d+)?/.test(newExpr)) {\n var _ADD_OR_SUBTRACT_REGE;\n var _ref5 = (_ADD_OR_SUBTRACT_REGE = ADD_OR_SUBTRACT_REGEX.exec(newExpr)) !== null && _ADD_OR_SUBTRACT_REGE !== void 0 ? _ADD_OR_SUBTRACT_REGE : [],\n _ref6 = _slicedToArray(_ref5, 4),\n _leftOperand = _ref6[1],\n _operator = _ref6[2],\n _rightOperand = _ref6[3];\n var _lTs = DecimalCSS.parse(_leftOperand !== null && _leftOperand !== void 0 ? _leftOperand : '');\n var _rTs = DecimalCSS.parse(_rightOperand !== null && _rightOperand !== void 0 ? _rightOperand : '');\n var _result = _operator === '+' ? _lTs.add(_rTs) : _lTs.subtract(_rTs);\n if (_result.isNaN()) {\n return STR_NAN;\n }\n newExpr = newExpr.replace(ADD_OR_SUBTRACT_REGEX, _result.toString());\n }\n return newExpr;\n}\nvar PARENTHESES_REGEX = /\\(([^()]*)\\)/;\nfunction calculateParentheses(expr) {\n var newExpr = expr;\n while (newExpr.includes('(')) {\n var _PARENTHESES_REGEX$ex = PARENTHESES_REGEX.exec(newExpr),\n _PARENTHESES_REGEX$ex2 = _slicedToArray(_PARENTHESES_REGEX$ex, 2),\n parentheticalExpression = _PARENTHESES_REGEX$ex2[1];\n newExpr = newExpr.replace(PARENTHESES_REGEX, calculateArithmetic(parentheticalExpression));\n }\n return newExpr;\n}\nfunction evaluateExpression(expression) {\n var newExpr = expression.replace(/\\s+/g, '');\n newExpr = calculateParentheses(newExpr);\n newExpr = calculateArithmetic(newExpr);\n return newExpr;\n}\nexport function safeEvaluateExpression(expression) {\n try {\n return evaluateExpression(expression);\n } catch (e) {\n /* istanbul ignore next */\n return STR_NAN;\n }\n}\nexport function reduceCSSCalc(expression) {\n var result = safeEvaluateExpression(expression.slice(5, -1));\n if (result === STR_NAN) {\n // notify the user\n return '';\n }\n return result;\n}", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nvar _excluded = [\"offset\"];\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nimport React, { cloneElement, isValidElement, createElement } from 'react';\nimport isNil from 'lodash/isNil';\nimport isFunction from 'lodash/isFunction';\nimport isObject from 'lodash/isObject';\nimport clsx from 'clsx';\nimport { Text } from './Text';\nimport { findAllByType, filterProps } from '../util/ReactUtils';\nimport { isNumOrStr, isNumber, isPercent, getPercentValue, uniqueId, mathSign } from '../util/DataUtils';\nimport { polarToCartesian } from '../util/PolarUtils';\nvar getLabel = function getLabel(props) {\n var value = props.value,\n formatter = props.formatter;\n var label = isNil(props.children) ? value : props.children;\n if (isFunction(formatter)) {\n return formatter(label);\n }\n return label;\n};\nvar getDeltaAngle = function getDeltaAngle(startAngle, endAngle) {\n var sign = mathSign(endAngle - startAngle);\n var deltaAngle = Math.min(Math.abs(endAngle - startAngle), 360);\n return sign * deltaAngle;\n};\nvar renderRadialLabel = function renderRadialLabel(labelProps, label, attrs) {\n var position = labelProps.position,\n viewBox = labelProps.viewBox,\n offset = labelProps.offset,\n className = labelProps.className;\n var _ref = viewBox,\n cx = _ref.cx,\n cy = _ref.cy,\n innerRadius = _ref.innerRadius,\n outerRadius = _ref.outerRadius,\n startAngle = _ref.startAngle,\n endAngle = _ref.endAngle,\n clockWise = _ref.clockWise;\n var radius = (innerRadius + outerRadius) / 2;\n var deltaAngle = getDeltaAngle(startAngle, endAngle);\n var sign = deltaAngle >= 0 ? 1 : -1;\n var labelAngle, direction;\n if (position === 'insideStart') {\n labelAngle = startAngle + sign * offset;\n direction = clockWise;\n } else if (position === 'insideEnd') {\n labelAngle = endAngle - sign * offset;\n direction = !clockWise;\n } else if (position === 'end') {\n labelAngle = endAngle + sign * offset;\n direction = clockWise;\n }\n direction = deltaAngle <= 0 ? direction : !direction;\n var startPoint = polarToCartesian(cx, cy, radius, labelAngle);\n var endPoint = polarToCartesian(cx, cy, radius, labelAngle + (direction ? 1 : -1) * 359);\n var path = \"M\".concat(startPoint.x, \",\").concat(startPoint.y, \"\\n A\").concat(radius, \",\").concat(radius, \",0,1,\").concat(direction ? 0 : 1, \",\\n \").concat(endPoint.x, \",\").concat(endPoint.y);\n var id = isNil(labelProps.id) ? uniqueId('recharts-radial-line-') : labelProps.id;\n return /*#__PURE__*/React.createElement(\"text\", _extends({}, attrs, {\n dominantBaseline: \"central\",\n className: clsx('recharts-radial-bar-label', className)\n }), /*#__PURE__*/React.createElement(\"defs\", null, /*#__PURE__*/React.createElement(\"path\", {\n id: id,\n d: path\n })), /*#__PURE__*/React.createElement(\"textPath\", {\n xlinkHref: \"#\".concat(id)\n }, label));\n};\nvar getAttrsOfPolarLabel = function getAttrsOfPolarLabel(props) {\n var viewBox = props.viewBox,\n offset = props.offset,\n position = props.position;\n var _ref2 = viewBox,\n cx = _ref2.cx,\n cy = _ref2.cy,\n innerRadius = _ref2.innerRadius,\n outerRadius = _ref2.outerRadius,\n startAngle = _ref2.startAngle,\n endAngle = _ref2.endAngle;\n var midAngle = (startAngle + endAngle) / 2;\n if (position === 'outside') {\n var _polarToCartesian = polarToCartesian(cx, cy, outerRadius + offset, midAngle),\n _x = _polarToCartesian.x,\n _y = _polarToCartesian.y;\n return {\n x: _x,\n y: _y,\n textAnchor: _x >= cx ? 'start' : 'end',\n verticalAnchor: 'middle'\n };\n }\n if (position === 'center') {\n return {\n x: cx,\n y: cy,\n textAnchor: 'middle',\n verticalAnchor: 'middle'\n };\n }\n if (position === 'centerTop') {\n return {\n x: cx,\n y: cy,\n textAnchor: 'middle',\n verticalAnchor: 'start'\n };\n }\n if (position === 'centerBottom') {\n return {\n x: cx,\n y: cy,\n textAnchor: 'middle',\n verticalAnchor: 'end'\n };\n }\n var r = (innerRadius + outerRadius) / 2;\n var _polarToCartesian2 = polarToCartesian(cx, cy, r, midAngle),\n x = _polarToCartesian2.x,\n y = _polarToCartesian2.y;\n return {\n x: x,\n y: y,\n textAnchor: 'middle',\n verticalAnchor: 'middle'\n };\n};\nvar getAttrsOfCartesianLabel = function getAttrsOfCartesianLabel(props) {\n var viewBox = props.viewBox,\n parentViewBox = props.parentViewBox,\n offset = props.offset,\n position = props.position;\n var _ref3 = viewBox,\n x = _ref3.x,\n y = _ref3.y,\n width = _ref3.width,\n height = _ref3.height;\n\n // Define vertical offsets and position inverts based on the value being positive or negative\n var verticalSign = height >= 0 ? 1 : -1;\n var verticalOffset = verticalSign * offset;\n var verticalEnd = verticalSign > 0 ? 'end' : 'start';\n var verticalStart = verticalSign > 0 ? 'start' : 'end';\n\n // Define horizontal offsets and position inverts based on the value being positive or negative\n var horizontalSign = width >= 0 ? 1 : -1;\n var horizontalOffset = horizontalSign * offset;\n var horizontalEnd = horizontalSign > 0 ? 'end' : 'start';\n var horizontalStart = horizontalSign > 0 ? 'start' : 'end';\n if (position === 'top') {\n var attrs = {\n x: x + width / 2,\n y: y - verticalSign * offset,\n textAnchor: 'middle',\n verticalAnchor: verticalEnd\n };\n return _objectSpread(_objectSpread({}, attrs), parentViewBox ? {\n height: Math.max(y - parentViewBox.y, 0),\n width: width\n } : {});\n }\n if (position === 'bottom') {\n var _attrs = {\n x: x + width / 2,\n y: y + height + verticalOffset,\n textAnchor: 'middle',\n verticalAnchor: verticalStart\n };\n return _objectSpread(_objectSpread({}, _attrs), parentViewBox ? {\n height: Math.max(parentViewBox.y + parentViewBox.height - (y + height), 0),\n width: width\n } : {});\n }\n if (position === 'left') {\n var _attrs2 = {\n x: x - horizontalOffset,\n y: y + height / 2,\n textAnchor: horizontalEnd,\n verticalAnchor: 'middle'\n };\n return _objectSpread(_objectSpread({}, _attrs2), parentViewBox ? {\n width: Math.max(_attrs2.x - parentViewBox.x, 0),\n height: height\n } : {});\n }\n if (position === 'right') {\n var _attrs3 = {\n x: x + width + horizontalOffset,\n y: y + height / 2,\n textAnchor: horizontalStart,\n verticalAnchor: 'middle'\n };\n return _objectSpread(_objectSpread({}, _attrs3), parentViewBox ? {\n width: Math.max(parentViewBox.x + parentViewBox.width - _attrs3.x, 0),\n height: height\n } : {});\n }\n var sizeAttrs = parentViewBox ? {\n width: width,\n height: height\n } : {};\n if (position === 'insideLeft') {\n return _objectSpread({\n x: x + horizontalOffset,\n y: y + height / 2,\n textAnchor: horizontalStart,\n verticalAnchor: 'middle'\n }, sizeAttrs);\n }\n if (position === 'insideRight') {\n return _objectSpread({\n x: x + width - horizontalOffset,\n y: y + height / 2,\n textAnchor: horizontalEnd,\n verticalAnchor: 'middle'\n }, sizeAttrs);\n }\n if (position === 'insideTop') {\n return _objectSpread({\n x: x + width / 2,\n y: y + verticalOffset,\n textAnchor: 'middle',\n verticalAnchor: verticalStart\n }, sizeAttrs);\n }\n if (position === 'insideBottom') {\n return _objectSpread({\n x: x + width / 2,\n y: y + height - verticalOffset,\n textAnchor: 'middle',\n verticalAnchor: verticalEnd\n }, sizeAttrs);\n }\n if (position === 'insideTopLeft') {\n return _objectSpread({\n x: x + horizontalOffset,\n y: y + verticalOffset,\n textAnchor: horizontalStart,\n verticalAnchor: verticalStart\n }, sizeAttrs);\n }\n if (position === 'insideTopRight') {\n return _objectSpread({\n x: x + width - horizontalOffset,\n y: y + verticalOffset,\n textAnchor: horizontalEnd,\n verticalAnchor: verticalStart\n }, sizeAttrs);\n }\n if (position === 'insideBottomLeft') {\n return _objectSpread({\n x: x + horizontalOffset,\n y: y + height - verticalOffset,\n textAnchor: horizontalStart,\n verticalAnchor: verticalEnd\n }, sizeAttrs);\n }\n if (position === 'insideBottomRight') {\n return _objectSpread({\n x: x + width - horizontalOffset,\n y: y + height - verticalOffset,\n textAnchor: horizontalEnd,\n verticalAnchor: verticalEnd\n }, sizeAttrs);\n }\n if (isObject(position) && (isNumber(position.x) || isPercent(position.x)) && (isNumber(position.y) || isPercent(position.y))) {\n return _objectSpread({\n x: x + getPercentValue(position.x, width),\n y: y + getPercentValue(position.y, height),\n textAnchor: 'end',\n verticalAnchor: 'end'\n }, sizeAttrs);\n }\n return _objectSpread({\n x: x + width / 2,\n y: y + height / 2,\n textAnchor: 'middle',\n verticalAnchor: 'middle'\n }, sizeAttrs);\n};\nvar isPolar = function isPolar(viewBox) {\n return 'cx' in viewBox && isNumber(viewBox.cx);\n};\nexport function Label(_ref4) {\n var _ref4$offset = _ref4.offset,\n offset = _ref4$offset === void 0 ? 5 : _ref4$offset,\n restProps = _objectWithoutProperties(_ref4, _excluded);\n var props = _objectSpread({\n offset: offset\n }, restProps);\n var viewBox = props.viewBox,\n position = props.position,\n value = props.value,\n children = props.children,\n content = props.content,\n _props$className = props.className,\n className = _props$className === void 0 ? '' : _props$className,\n textBreakAll = props.textBreakAll;\n if (!viewBox || isNil(value) && isNil(children) && ! /*#__PURE__*/isValidElement(content) && !isFunction(content)) {\n return null;\n }\n if ( /*#__PURE__*/isValidElement(content)) {\n return /*#__PURE__*/cloneElement(content, props);\n }\n var label;\n if (isFunction(content)) {\n label = /*#__PURE__*/createElement(content, props);\n if ( /*#__PURE__*/isValidElement(label)) {\n return label;\n }\n } else {\n label = getLabel(props);\n }\n var isPolarLabel = isPolar(viewBox);\n var attrs = filterProps(props, true);\n if (isPolarLabel && (position === 'insideStart' || position === 'insideEnd' || position === 'end')) {\n return renderRadialLabel(props, label, attrs);\n }\n var positionAttrs = isPolarLabel ? getAttrsOfPolarLabel(props) : getAttrsOfCartesianLabel(props);\n return /*#__PURE__*/React.createElement(Text, _extends({\n className: clsx('recharts-label', className)\n }, attrs, positionAttrs, {\n breakAll: textBreakAll\n }), label);\n}\nLabel.displayName = 'Label';\nvar parseViewBox = function parseViewBox(props) {\n var cx = props.cx,\n cy = props.cy,\n angle = props.angle,\n startAngle = props.startAngle,\n endAngle = props.endAngle,\n r = props.r,\n radius = props.radius,\n innerRadius = props.innerRadius,\n outerRadius = props.outerRadius,\n x = props.x,\n y = props.y,\n top = props.top,\n left = props.left,\n width = props.width,\n height = props.height,\n clockWise = props.clockWise,\n labelViewBox = props.labelViewBox;\n if (labelViewBox) {\n return labelViewBox;\n }\n if (isNumber(width) && isNumber(height)) {\n if (isNumber(x) && isNumber(y)) {\n return {\n x: x,\n y: y,\n width: width,\n height: height\n };\n }\n if (isNumber(top) && isNumber(left)) {\n return {\n x: top,\n y: left,\n width: width,\n height: height\n };\n }\n }\n if (isNumber(x) && isNumber(y)) {\n return {\n x: x,\n y: y,\n width: 0,\n height: 0\n };\n }\n if (isNumber(cx) && isNumber(cy)) {\n return {\n cx: cx,\n cy: cy,\n startAngle: startAngle || angle || 0,\n endAngle: endAngle || angle || 0,\n innerRadius: innerRadius || 0,\n outerRadius: outerRadius || radius || r || 0,\n clockWise: clockWise\n };\n }\n if (props.viewBox) {\n return props.viewBox;\n }\n return {};\n};\nvar parseLabel = function parseLabel(label, viewBox) {\n if (!label) {\n return null;\n }\n if (label === true) {\n return /*#__PURE__*/React.createElement(Label, {\n key: \"label-implicit\",\n viewBox: viewBox\n });\n }\n if (isNumOrStr(label)) {\n return /*#__PURE__*/React.createElement(Label, {\n key: \"label-implicit\",\n viewBox: viewBox,\n value: label\n });\n }\n if ( /*#__PURE__*/isValidElement(label)) {\n if (label.type === Label) {\n return /*#__PURE__*/cloneElement(label, {\n key: 'label-implicit',\n viewBox: viewBox\n });\n }\n return /*#__PURE__*/React.createElement(Label, {\n key: \"label-implicit\",\n content: label,\n viewBox: viewBox\n });\n }\n if (isFunction(label)) {\n return /*#__PURE__*/React.createElement(Label, {\n key: \"label-implicit\",\n content: label,\n viewBox: viewBox\n });\n }\n if (isObject(label)) {\n return /*#__PURE__*/React.createElement(Label, _extends({\n viewBox: viewBox\n }, label, {\n key: \"label-implicit\"\n }));\n }\n return null;\n};\nvar renderCallByParent = function renderCallByParent(parentProps, viewBox) {\n var checkPropsLabel = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n if (!parentProps || !parentProps.children && checkPropsLabel && !parentProps.label) {\n return null;\n }\n var children = parentProps.children;\n var parentViewBox = parseViewBox(parentProps);\n var explicitChildren = findAllByType(children, Label).map(function (child, index) {\n return /*#__PURE__*/cloneElement(child, {\n viewBox: viewBox || parentViewBox,\n // eslint-disable-next-line react/no-array-index-key\n key: \"label-\".concat(index)\n });\n });\n if (!checkPropsLabel) {\n return explicitChildren;\n }\n var implicitLabel = parseLabel(parentProps.label, viewBox || parentViewBox);\n return [implicitLabel].concat(_toConsumableArray(explicitChildren));\n};\nLabel.parseViewBox = parseViewBox;\nLabel.renderCallByParent = renderCallByParent;", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nimport isNil from 'lodash/isNil';\nimport { isValidElement } from 'react';\nimport isFunction from 'lodash/isFunction';\nimport { getPercentValue } from './DataUtils';\nimport { parseScale, checkDomainOfScale, getTicksOfScale } from './ChartUtils';\nexport var RADIAN = Math.PI / 180;\nexport var degreeToRadian = function degreeToRadian(angle) {\n return angle * Math.PI / 180;\n};\nexport var radianToDegree = function radianToDegree(angleInRadian) {\n return angleInRadian * 180 / Math.PI;\n};\nexport var polarToCartesian = function polarToCartesian(cx, cy, radius, angle) {\n return {\n x: cx + Math.cos(-RADIAN * angle) * radius,\n y: cy + Math.sin(-RADIAN * angle) * radius\n };\n};\nexport var getMaxRadius = function getMaxRadius(width, height) {\n var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0\n };\n return Math.min(Math.abs(width - (offset.left || 0) - (offset.right || 0)), Math.abs(height - (offset.top || 0) - (offset.bottom || 0))) / 2;\n};\n\n/**\n * Calculate the scale function, position, width, height of axes\n * @param {Object} props Latest props\n * @param {Object} axisMap The configuration of axes\n * @param {Object} offset The offset of main part in the svg element\n * @param {Object} axisType The type of axes, radius-axis or angle-axis\n * @param {String} chartName The name of chart\n * @return {Object} Configuration\n */\nexport var formatAxisMap = function formatAxisMap(props, axisMap, offset, axisType, chartName) {\n var width = props.width,\n height = props.height;\n var startAngle = props.startAngle,\n endAngle = props.endAngle;\n var cx = getPercentValue(props.cx, width, width / 2);\n var cy = getPercentValue(props.cy, height, height / 2);\n var maxRadius = getMaxRadius(width, height, offset);\n var innerRadius = getPercentValue(props.innerRadius, maxRadius, 0);\n var outerRadius = getPercentValue(props.outerRadius, maxRadius, maxRadius * 0.8);\n var ids = Object.keys(axisMap);\n return ids.reduce(function (result, id) {\n var axis = axisMap[id];\n var domain = axis.domain,\n reversed = axis.reversed;\n var range;\n if (isNil(axis.range)) {\n if (axisType === 'angleAxis') {\n range = [startAngle, endAngle];\n } else if (axisType === 'radiusAxis') {\n range = [innerRadius, outerRadius];\n }\n if (reversed) {\n range = [range[1], range[0]];\n }\n } else {\n range = axis.range;\n var _range = range;\n var _range2 = _slicedToArray(_range, 2);\n startAngle = _range2[0];\n endAngle = _range2[1];\n }\n var _parseScale = parseScale(axis, chartName),\n realScaleType = _parseScale.realScaleType,\n scale = _parseScale.scale;\n scale.domain(domain).range(range);\n checkDomainOfScale(scale);\n var ticks = getTicksOfScale(scale, _objectSpread(_objectSpread({}, axis), {}, {\n realScaleType: realScaleType\n }));\n var finalAxis = _objectSpread(_objectSpread(_objectSpread({}, axis), ticks), {}, {\n range: range,\n radius: outerRadius,\n realScaleType: realScaleType,\n scale: scale,\n cx: cx,\n cy: cy,\n innerRadius: innerRadius,\n outerRadius: outerRadius,\n startAngle: startAngle,\n endAngle: endAngle\n });\n return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, id, finalAxis));\n }, {});\n};\nexport var distanceBetweenPoints = function distanceBetweenPoints(point, anotherPoint) {\n var x1 = point.x,\n y1 = point.y;\n var x2 = anotherPoint.x,\n y2 = anotherPoint.y;\n return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));\n};\nexport var getAngleOfPoint = function getAngleOfPoint(_ref, _ref2) {\n var x = _ref.x,\n y = _ref.y;\n var cx = _ref2.cx,\n cy = _ref2.cy;\n var radius = distanceBetweenPoints({\n x: x,\n y: y\n }, {\n x: cx,\n y: cy\n });\n if (radius <= 0) {\n return {\n radius: radius\n };\n }\n var cos = (x - cx) / radius;\n var angleInRadian = Math.acos(cos);\n if (y > cy) {\n angleInRadian = 2 * Math.PI - angleInRadian;\n }\n return {\n radius: radius,\n angle: radianToDegree(angleInRadian),\n angleInRadian: angleInRadian\n };\n};\nexport var formatAngleOfSector = function formatAngleOfSector(_ref3) {\n var startAngle = _ref3.startAngle,\n endAngle = _ref3.endAngle;\n var startCnt = Math.floor(startAngle / 360);\n var endCnt = Math.floor(endAngle / 360);\n var min = Math.min(startCnt, endCnt);\n return {\n startAngle: startAngle - min * 360,\n endAngle: endAngle - min * 360\n };\n};\nvar reverseFormatAngleOfSetor = function reverseFormatAngleOfSetor(angle, _ref4) {\n var startAngle = _ref4.startAngle,\n endAngle = _ref4.endAngle;\n var startCnt = Math.floor(startAngle / 360);\n var endCnt = Math.floor(endAngle / 360);\n var min = Math.min(startCnt, endCnt);\n return angle + min * 360;\n};\nexport var inRangeOfSector = function inRangeOfSector(_ref5, sector) {\n var x = _ref5.x,\n y = _ref5.y;\n var _getAngleOfPoint = getAngleOfPoint({\n x: x,\n y: y\n }, sector),\n radius = _getAngleOfPoint.radius,\n angle = _getAngleOfPoint.angle;\n var innerRadius = sector.innerRadius,\n outerRadius = sector.outerRadius;\n if (radius < innerRadius || radius > outerRadius) {\n return false;\n }\n if (radius === 0) {\n return true;\n }\n var _formatAngleOfSector = formatAngleOfSector(sector),\n startAngle = _formatAngleOfSector.startAngle,\n endAngle = _formatAngleOfSector.endAngle;\n var formatAngle = angle;\n var inRange;\n if (startAngle <= endAngle) {\n while (formatAngle > endAngle) {\n formatAngle -= 360;\n }\n while (formatAngle < startAngle) {\n formatAngle += 360;\n }\n inRange = formatAngle >= startAngle && formatAngle <= endAngle;\n } else {\n while (formatAngle > startAngle) {\n formatAngle -= 360;\n }\n while (formatAngle < endAngle) {\n formatAngle += 360;\n }\n inRange = formatAngle >= endAngle && formatAngle <= startAngle;\n }\n if (inRange) {\n return _objectSpread(_objectSpread({}, sector), {}, {\n radius: radius,\n angle: reverseFormatAngleOfSetor(formatAngle, sector)\n });\n }\n return null;\n};\nexport var getTickClassName = function getTickClassName(tick) {\n return ! /*#__PURE__*/isValidElement(tick) && !isFunction(tick) && typeof tick !== 'boolean' ? tick.className : '';\n};", "\n// `victory-vendor/d3-scale` (ESM)\n// See upstream license: https://github.com/d3/d3-scale/blob/main/LICENSE\n//\n// Our ESM package uses the underlying installed dependencies of `node_modules/d3-scale`\nexport * from \"d3-scale\";\n", "export default function ascending(a, b) {\n return a == null || b == null ? NaN : a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;\n}\n", "export default function descending(a, b) {\n return a == null || b == null ? NaN\n : b < a ? -1\n : b > a ? 1\n : b >= a ? 0\n : NaN;\n}\n", "import ascending from \"./ascending.js\";\nimport descending from \"./descending.js\";\n\nexport default function bisector(f) {\n let compare1, compare2, delta;\n\n // If an accessor is specified, promote it to a comparator. In this case we\n // can test whether the search value is (self-) comparable. We can\u2019t do this\n // for a comparator (except for specific, known comparators) because we can\u2019t\n // tell if the comparator is symmetric, and an asymmetric comparator can\u2019t be\n // used to test whether a single value is comparable.\n if (f.length !== 2) {\n compare1 = ascending;\n compare2 = (d, x) => ascending(f(d), x);\n delta = (d, x) => f(d) - x;\n } else {\n compare1 = f === ascending || f === descending ? f : zero;\n compare2 = f;\n delta = f;\n }\n\n function left(a, x, lo = 0, hi = a.length) {\n if (lo < hi) {\n if (compare1(x, x) !== 0) return hi;\n do {\n const mid = (lo + hi) >>> 1;\n if (compare2(a[mid], x) < 0) lo = mid + 1;\n else hi = mid;\n } while (lo < hi);\n }\n return lo;\n }\n\n function right(a, x, lo = 0, hi = a.length) {\n if (lo < hi) {\n if (compare1(x, x) !== 0) return hi;\n do {\n const mid = (lo + hi) >>> 1;\n if (compare2(a[mid], x) <= 0) lo = mid + 1;\n else hi = mid;\n } while (lo < hi);\n }\n return lo;\n }\n\n function center(a, x, lo = 0, hi = a.length) {\n const i = left(a, x, lo, hi - 1);\n return i > lo && delta(a[i - 1], x) > -delta(a[i], x) ? i - 1 : i;\n }\n\n return {left, center, right};\n}\n\nfunction zero() {\n return 0;\n}\n", "export default function number(x) {\n return x === null ? NaN : +x;\n}\n\nexport function* numbers(values, valueof) {\n if (valueof === undefined) {\n for (let value of values) {\n if (value != null && (value = +value) >= value) {\n yield value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {\n yield value;\n }\n }\n }\n}\n", "import ascending from \"./ascending.js\";\nimport bisector from \"./bisector.js\";\nimport number from \"./number.js\";\n\nconst ascendingBisect = bisector(ascending);\nexport const bisectRight = ascendingBisect.right;\nexport const bisectLeft = ascendingBisect.left;\nexport const bisectCenter = bisector(number).center;\nexport default bisectRight;\n", "export class InternMap extends Map {\n constructor(entries, key = keyof) {\n super();\n Object.defineProperties(this, {_intern: {value: new Map()}, _key: {value: key}});\n if (entries != null) for (const [key, value] of entries) this.set(key, value);\n }\n get(key) {\n return super.get(intern_get(this, key));\n }\n has(key) {\n return super.has(intern_get(this, key));\n }\n set(key, value) {\n return super.set(intern_set(this, key), value);\n }\n delete(key) {\n return super.delete(intern_delete(this, key));\n }\n}\n\nexport class InternSet extends Set {\n constructor(values, key = keyof) {\n super();\n Object.defineProperties(this, {_intern: {value: new Map()}, _key: {value: key}});\n if (values != null) for (const value of values) this.add(value);\n }\n has(value) {\n return super.has(intern_get(this, value));\n }\n add(value) {\n return super.add(intern_set(this, value));\n }\n delete(value) {\n return super.delete(intern_delete(this, value));\n }\n}\n\nfunction intern_get({_intern, _key}, value) {\n const key = _key(value);\n return _intern.has(key) ? _intern.get(key) : value;\n}\n\nfunction intern_set({_intern, _key}, value) {\n const key = _key(value);\n if (_intern.has(key)) return _intern.get(key);\n _intern.set(key, value);\n return value;\n}\n\nfunction intern_delete({_intern, _key}, value) {\n const key = _key(value);\n if (_intern.has(key)) {\n value = _intern.get(key);\n _intern.delete(key);\n }\n return value;\n}\n\nfunction keyof(value) {\n return value !== null && typeof value === \"object\" ? value.valueOf() : value;\n}\n", "import ascending from \"./ascending.js\";\nimport permute from \"./permute.js\";\n\nexport default function sort(values, ...F) {\n if (typeof values[Symbol.iterator] !== \"function\") throw new TypeError(\"values is not iterable\");\n values = Array.from(values);\n let [f] = F;\n if ((f && f.length !== 2) || F.length > 1) {\n const index = Uint32Array.from(values, (d, i) => i);\n if (F.length > 1) {\n F = F.map(f => values.map(f));\n index.sort((i, j) => {\n for (const f of F) {\n const c = ascendingDefined(f[i], f[j]);\n if (c) return c;\n }\n });\n } else {\n f = values.map(f);\n index.sort((i, j) => ascendingDefined(f[i], f[j]));\n }\n return permute(values, index);\n }\n return values.sort(compareDefined(f));\n}\n\nexport function compareDefined(compare = ascending) {\n if (compare === ascending) return ascendingDefined;\n if (typeof compare !== \"function\") throw new TypeError(\"compare is not a function\");\n return (a, b) => {\n const x = compare(a, b);\n if (x || x === 0) return x;\n return (compare(b, b) === 0) - (compare(a, a) === 0);\n };\n}\n\nexport function ascendingDefined(a, b) {\n return (a == null || !(a >= a)) - (b == null || !(b >= b)) || (a < b ? -1 : a > b ? 1 : 0);\n}\n", "const e10 = Math.sqrt(50),\n e5 = Math.sqrt(10),\n e2 = Math.sqrt(2);\n\nfunction tickSpec(start, stop, count) {\n const step = (stop - start) / Math.max(0, count),\n power = Math.floor(Math.log10(step)),\n error = step / Math.pow(10, power),\n factor = error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1;\n let i1, i2, inc;\n if (power < 0) {\n inc = Math.pow(10, -power) / factor;\n i1 = Math.round(start * inc);\n i2 = Math.round(stop * inc);\n if (i1 / inc < start) ++i1;\n if (i2 / inc > stop) --i2;\n inc = -inc;\n } else {\n inc = Math.pow(10, power) * factor;\n i1 = Math.round(start / inc);\n i2 = Math.round(stop / inc);\n if (i1 * inc < start) ++i1;\n if (i2 * inc > stop) --i2;\n }\n if (i2 < i1 && 0.5 <= count && count < 2) return tickSpec(start, stop, count * 2);\n return [i1, i2, inc];\n}\n\nexport default function ticks(start, stop, count) {\n stop = +stop, start = +start, count = +count;\n if (!(count > 0)) return [];\n if (start === stop) return [start];\n const reverse = stop < start, [i1, i2, inc] = reverse ? tickSpec(stop, start, count) : tickSpec(start, stop, count);\n if (!(i2 >= i1)) return [];\n const n = i2 - i1 + 1, ticks = new Array(n);\n if (reverse) {\n if (inc < 0) for (let i = 0; i < n; ++i) ticks[i] = (i2 - i) / -inc;\n else for (let i = 0; i < n; ++i) ticks[i] = (i2 - i) * inc;\n } else {\n if (inc < 0) for (let i = 0; i < n; ++i) ticks[i] = (i1 + i) / -inc;\n else for (let i = 0; i < n; ++i) ticks[i] = (i1 + i) * inc;\n }\n return ticks;\n}\n\nexport function tickIncrement(start, stop, count) {\n stop = +stop, start = +start, count = +count;\n return tickSpec(start, stop, count)[2];\n}\n\nexport function tickStep(start, stop, count) {\n stop = +stop, start = +start, count = +count;\n const reverse = stop < start, inc = reverse ? tickIncrement(stop, start, count) : tickIncrement(start, stop, count);\n return (reverse ? -1 : 1) * (inc < 0 ? 1 / -inc : inc);\n}\n", "export default function max(values, valueof) {\n let max;\n if (valueof === undefined) {\n for (const value of values) {\n if (value != null\n && (max < value || (max === undefined && value >= value))) {\n max = value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null\n && (max < value || (max === undefined && value >= value))) {\n max = value;\n }\n }\n }\n return max;\n}\n", "export default function min(values, valueof) {\n let min;\n if (valueof === undefined) {\n for (const value of values) {\n if (value != null\n && (min > value || (min === undefined && value >= value))) {\n min = value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null\n && (min > value || (min === undefined && value >= value))) {\n min = value;\n }\n }\n }\n return min;\n}\n", "import {ascendingDefined, compareDefined} from \"./sort.js\";\n\n// Based on https://github.com/mourner/quickselect\n// ISC license, Copyright 2018 Vladimir Agafonkin.\nexport default function quickselect(array, k, left = 0, right = Infinity, compare) {\n k = Math.floor(k);\n left = Math.floor(Math.max(0, left));\n right = Math.floor(Math.min(array.length - 1, right));\n\n if (!(left <= k && k <= right)) return array;\n\n compare = compare === undefined ? ascendingDefined : compareDefined(compare);\n\n while (right > left) {\n if (right - left > 600) {\n const n = right - left + 1;\n const m = k - left + 1;\n const z = Math.log(n);\n const s = 0.5 * Math.exp(2 * z / 3);\n const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));\n const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));\n quickselect(array, k, newLeft, newRight, compare);\n }\n\n const t = array[k];\n let i = left;\n let j = right;\n\n swap(array, left, k);\n if (compare(array[right], t) > 0) swap(array, left, right);\n\n while (i < j) {\n swap(array, i, j), ++i, --j;\n while (compare(array[i], t) < 0) ++i;\n while (compare(array[j], t) > 0) --j;\n }\n\n if (compare(array[left], t) === 0) swap(array, left, j);\n else ++j, swap(array, j, right);\n\n if (j <= k) left = j + 1;\n if (k <= j) right = j - 1;\n }\n\n return array;\n}\n\nfunction swap(array, i, j) {\n const t = array[i];\n array[i] = array[j];\n array[j] = t;\n}\n", "import max from \"./max.js\";\nimport maxIndex from \"./maxIndex.js\";\nimport min from \"./min.js\";\nimport minIndex from \"./minIndex.js\";\nimport quickselect from \"./quickselect.js\";\nimport number, {numbers} from \"./number.js\";\nimport {ascendingDefined} from \"./sort.js\";\nimport greatest from \"./greatest.js\";\n\nexport default function quantile(values, p, valueof) {\n values = Float64Array.from(numbers(values, valueof));\n if (!(n = values.length) || isNaN(p = +p)) return;\n if (p <= 0 || n < 2) return min(values);\n if (p >= 1) return max(values);\n var n,\n i = (n - 1) * p,\n i0 = Math.floor(i),\n value0 = max(quickselect(values, i0).subarray(0, i0 + 1)),\n value1 = min(values.subarray(i0 + 1));\n return value0 + (value1 - value0) * (i - i0);\n}\n\nexport function quantileSorted(values, p, valueof = number) {\n if (!(n = values.length) || isNaN(p = +p)) return;\n if (p <= 0 || n < 2) return +valueof(values[0], 0, values);\n if (p >= 1) return +valueof(values[n - 1], n - 1, values);\n var n,\n i = (n - 1) * p,\n i0 = Math.floor(i),\n value0 = +valueof(values[i0], i0, values),\n value1 = +valueof(values[i0 + 1], i0 + 1, values);\n return value0 + (value1 - value0) * (i - i0);\n}\n\nexport function quantileIndex(values, p, valueof = number) {\n if (isNaN(p = +p)) return;\n numbers = Float64Array.from(values, (_, i) => number(valueof(values[i], i, values)));\n if (p <= 0) return minIndex(numbers);\n if (p >= 1) return maxIndex(numbers);\n var numbers,\n index = Uint32Array.from(values, (_, i) => i),\n j = numbers.length - 1,\n i = Math.floor(j * p);\n quickselect(index, i, 0, j, (i, j) => ascendingDefined(numbers[i], numbers[j]));\n i = greatest(index.subarray(0, i + 1), (i) => numbers[i]);\n return i >= 0 ? i : -1;\n}\n", "export default function range(start, stop, step) {\n start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;\n\n var i = -1,\n n = Math.max(0, Math.ceil((stop - start) / step)) | 0,\n range = new Array(n);\n\n while (++i < n) {\n range[i] = start + i * step;\n }\n\n return range;\n}\n", "export function initRange(domain, range) {\n switch (arguments.length) {\n case 0: break;\n case 1: this.range(domain); break;\n default: this.range(range).domain(domain); break;\n }\n return this;\n}\n\nexport function initInterpolator(domain, interpolator) {\n switch (arguments.length) {\n case 0: break;\n case 1: {\n if (typeof domain === \"function\") this.interpolator(domain);\n else this.range(domain);\n break;\n }\n default: {\n this.domain(domain);\n if (typeof interpolator === \"function\") this.interpolator(interpolator);\n else this.range(interpolator);\n break;\n }\n }\n return this;\n}\n", "import {InternMap} from \"d3-array\";\nimport {initRange} from \"./init.js\";\n\nexport const implicit = Symbol(\"implicit\");\n\nexport default function ordinal() {\n var index = new InternMap(),\n domain = [],\n range = [],\n unknown = implicit;\n\n function scale(d) {\n let i = index.get(d);\n if (i === undefined) {\n if (unknown !== implicit) return unknown;\n index.set(d, i = domain.push(d) - 1);\n }\n return range[i % range.length];\n }\n\n scale.domain = function(_) {\n if (!arguments.length) return domain.slice();\n domain = [], index = new InternMap();\n for (const value of _) {\n if (index.has(value)) continue;\n index.set(value, domain.push(value) - 1);\n }\n return scale;\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = Array.from(_), scale) : range.slice();\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n scale.copy = function() {\n return ordinal(domain, range).unknown(unknown);\n };\n\n initRange.apply(scale, arguments);\n\n return scale;\n}\n", "import {range as sequence} from \"d3-array\";\nimport {initRange} from \"./init.js\";\nimport ordinal from \"./ordinal.js\";\n\nexport default function band() {\n var scale = ordinal().unknown(undefined),\n domain = scale.domain,\n ordinalRange = scale.range,\n r0 = 0,\n r1 = 1,\n step,\n bandwidth,\n round = false,\n paddingInner = 0,\n paddingOuter = 0,\n align = 0.5;\n\n delete scale.unknown;\n\n function rescale() {\n var n = domain().length,\n reverse = r1 < r0,\n start = reverse ? r1 : r0,\n stop = reverse ? r0 : r1;\n step = (stop - start) / Math.max(1, n - paddingInner + paddingOuter * 2);\n if (round) step = Math.floor(step);\n start += (stop - start - step * (n - paddingInner)) * align;\n bandwidth = step * (1 - paddingInner);\n if (round) start = Math.round(start), bandwidth = Math.round(bandwidth);\n var values = sequence(n).map(function(i) { return start + step * i; });\n return ordinalRange(reverse ? values.reverse() : values);\n }\n\n scale.domain = function(_) {\n return arguments.length ? (domain(_), rescale()) : domain();\n };\n\n scale.range = function(_) {\n return arguments.length ? ([r0, r1] = _, r0 = +r0, r1 = +r1, rescale()) : [r0, r1];\n };\n\n scale.rangeRound = function(_) {\n return [r0, r1] = _, r0 = +r0, r1 = +r1, round = true, rescale();\n };\n\n scale.bandwidth = function() {\n return bandwidth;\n };\n\n scale.step = function() {\n return step;\n };\n\n scale.round = function(_) {\n return arguments.length ? (round = !!_, rescale()) : round;\n };\n\n scale.padding = function(_) {\n return arguments.length ? (paddingInner = Math.min(1, paddingOuter = +_), rescale()) : paddingInner;\n };\n\n scale.paddingInner = function(_) {\n return arguments.length ? (paddingInner = Math.min(1, _), rescale()) : paddingInner;\n };\n\n scale.paddingOuter = function(_) {\n return arguments.length ? (paddingOuter = +_, rescale()) : paddingOuter;\n };\n\n scale.align = function(_) {\n return arguments.length ? (align = Math.max(0, Math.min(1, _)), rescale()) : align;\n };\n\n scale.copy = function() {\n return band(domain(), [r0, r1])\n .round(round)\n .paddingInner(paddingInner)\n .paddingOuter(paddingOuter)\n .align(align);\n };\n\n return initRange.apply(rescale(), arguments);\n}\n\nfunction pointish(scale) {\n var copy = scale.copy;\n\n scale.padding = scale.paddingOuter;\n delete scale.paddingInner;\n delete scale.paddingOuter;\n\n scale.copy = function() {\n return pointish(copy());\n };\n\n return scale;\n}\n\nexport function point() {\n return pointish(band.apply(null, arguments).paddingInner(1));\n}\n", "export default function(constructor, factory, prototype) {\n constructor.prototype = factory.prototype = prototype;\n prototype.constructor = constructor;\n}\n\nexport function extend(parent, definition) {\n var prototype = Object.create(parent.prototype);\n for (var key in definition) prototype[key] = definition[key];\n return prototype;\n}\n", "import define, {extend} from \"./define.js\";\n\nexport function Color() {}\n\nexport var darker = 0.7;\nexport var brighter = 1 / darker;\n\nvar reI = \"\\\\s*([+-]?\\\\d+)\\\\s*\",\n reN = \"\\\\s*([+-]?(?:\\\\d*\\\\.)?\\\\d+(?:[eE][+-]?\\\\d+)?)\\\\s*\",\n reP = \"\\\\s*([+-]?(?:\\\\d*\\\\.)?\\\\d+(?:[eE][+-]?\\\\d+)?)%\\\\s*\",\n reHex = /^#([0-9a-f]{3,8})$/,\n reRgbInteger = new RegExp(`^rgb\\\\(${reI},${reI},${reI}\\\\)$`),\n reRgbPercent = new RegExp(`^rgb\\\\(${reP},${reP},${reP}\\\\)$`),\n reRgbaInteger = new RegExp(`^rgba\\\\(${reI},${reI},${reI},${reN}\\\\)$`),\n reRgbaPercent = new RegExp(`^rgba\\\\(${reP},${reP},${reP},${reN}\\\\)$`),\n reHslPercent = new RegExp(`^hsl\\\\(${reN},${reP},${reP}\\\\)$`),\n reHslaPercent = new RegExp(`^hsla\\\\(${reN},${reP},${reP},${reN}\\\\)$`);\n\nvar named = {\n aliceblue: 0xf0f8ff,\n antiquewhite: 0xfaebd7,\n aqua: 0x00ffff,\n aquamarine: 0x7fffd4,\n azure: 0xf0ffff,\n beige: 0xf5f5dc,\n bisque: 0xffe4c4,\n black: 0x000000,\n blanchedalmond: 0xffebcd,\n blue: 0x0000ff,\n blueviolet: 0x8a2be2,\n brown: 0xa52a2a,\n burlywood: 0xdeb887,\n cadetblue: 0x5f9ea0,\n chartreuse: 0x7fff00,\n chocolate: 0xd2691e,\n coral: 0xff7f50,\n cornflowerblue: 0x6495ed,\n cornsilk: 0xfff8dc,\n crimson: 0xdc143c,\n cyan: 0x00ffff,\n darkblue: 0x00008b,\n darkcyan: 0x008b8b,\n darkgoldenrod: 0xb8860b,\n darkgray: 0xa9a9a9,\n darkgreen: 0x006400,\n darkgrey: 0xa9a9a9,\n darkkhaki: 0xbdb76b,\n darkmagenta: 0x8b008b,\n darkolivegreen: 0x556b2f,\n darkorange: 0xff8c00,\n darkorchid: 0x9932cc,\n darkred: 0x8b0000,\n darksalmon: 0xe9967a,\n darkseagreen: 0x8fbc8f,\n darkslateblue: 0x483d8b,\n darkslategray: 0x2f4f4f,\n darkslategrey: 0x2f4f4f,\n darkturquoise: 0x00ced1,\n darkviolet: 0x9400d3,\n deeppink: 0xff1493,\n deepskyblue: 0x00bfff,\n dimgray: 0x696969,\n dimgrey: 0x696969,\n dodgerblue: 0x1e90ff,\n firebrick: 0xb22222,\n floralwhite: 0xfffaf0,\n forestgreen: 0x228b22,\n fuchsia: 0xff00ff,\n gainsboro: 0xdcdcdc,\n ghostwhite: 0xf8f8ff,\n gold: 0xffd700,\n goldenrod: 0xdaa520,\n gray: 0x808080,\n green: 0x008000,\n greenyellow: 0xadff2f,\n grey: 0x808080,\n honeydew: 0xf0fff0,\n hotpink: 0xff69b4,\n indianred: 0xcd5c5c,\n indigo: 0x4b0082,\n ivory: 0xfffff0,\n khaki: 0xf0e68c,\n lavender: 0xe6e6fa,\n lavenderblush: 0xfff0f5,\n lawngreen: 0x7cfc00,\n lemonchiffon: 0xfffacd,\n lightblue: 0xadd8e6,\n lightcoral: 0xf08080,\n lightcyan: 0xe0ffff,\n lightgoldenrodyellow: 0xfafad2,\n lightgray: 0xd3d3d3,\n lightgreen: 0x90ee90,\n lightgrey: 0xd3d3d3,\n lightpink: 0xffb6c1,\n lightsalmon: 0xffa07a,\n lightseagreen: 0x20b2aa,\n lightskyblue: 0x87cefa,\n lightslategray: 0x778899,\n lightslategrey: 0x778899,\n lightsteelblue: 0xb0c4de,\n lightyellow: 0xffffe0,\n lime: 0x00ff00,\n limegreen: 0x32cd32,\n linen: 0xfaf0e6,\n magenta: 0xff00ff,\n maroon: 0x800000,\n mediumaquamarine: 0x66cdaa,\n mediumblue: 0x0000cd,\n mediumorchid: 0xba55d3,\n mediumpurple: 0x9370db,\n mediumseagreen: 0x3cb371,\n mediumslateblue: 0x7b68ee,\n mediumspringgreen: 0x00fa9a,\n mediumturquoise: 0x48d1cc,\n mediumvioletred: 0xc71585,\n midnightblue: 0x191970,\n mintcream: 0xf5fffa,\n mistyrose: 0xffe4e1,\n moccasin: 0xffe4b5,\n navajowhite: 0xffdead,\n navy: 0x000080,\n oldlace: 0xfdf5e6,\n olive: 0x808000,\n olivedrab: 0x6b8e23,\n orange: 0xffa500,\n orangered: 0xff4500,\n orchid: 0xda70d6,\n palegoldenrod: 0xeee8aa,\n palegreen: 0x98fb98,\n paleturquoise: 0xafeeee,\n palevioletred: 0xdb7093,\n papayawhip: 0xffefd5,\n peachpuff: 0xffdab9,\n peru: 0xcd853f,\n pink: 0xffc0cb,\n plum: 0xdda0dd,\n powderblue: 0xb0e0e6,\n purple: 0x800080,\n rebeccapurple: 0x663399,\n red: 0xff0000,\n rosybrown: 0xbc8f8f,\n royalblue: 0x4169e1,\n saddlebrown: 0x8b4513,\n salmon: 0xfa8072,\n sandybrown: 0xf4a460,\n seagreen: 0x2e8b57,\n seashell: 0xfff5ee,\n sienna: 0xa0522d,\n silver: 0xc0c0c0,\n skyblue: 0x87ceeb,\n slateblue: 0x6a5acd,\n slategray: 0x708090,\n slategrey: 0x708090,\n snow: 0xfffafa,\n springgreen: 0x00ff7f,\n steelblue: 0x4682b4,\n tan: 0xd2b48c,\n teal: 0x008080,\n thistle: 0xd8bfd8,\n tomato: 0xff6347,\n turquoise: 0x40e0d0,\n violet: 0xee82ee,\n wheat: 0xf5deb3,\n white: 0xffffff,\n whitesmoke: 0xf5f5f5,\n yellow: 0xffff00,\n yellowgreen: 0x9acd32\n};\n\ndefine(Color, color, {\n copy(channels) {\n return Object.assign(new this.constructor, this, channels);\n },\n displayable() {\n return this.rgb().displayable();\n },\n hex: color_formatHex, // Deprecated! Use color.formatHex.\n formatHex: color_formatHex,\n formatHex8: color_formatHex8,\n formatHsl: color_formatHsl,\n formatRgb: color_formatRgb,\n toString: color_formatRgb\n});\n\nfunction color_formatHex() {\n return this.rgb().formatHex();\n}\n\nfunction color_formatHex8() {\n return this.rgb().formatHex8();\n}\n\nfunction color_formatHsl() {\n return hslConvert(this).formatHsl();\n}\n\nfunction color_formatRgb() {\n return this.rgb().formatRgb();\n}\n\nexport default function color(format) {\n var m, l;\n format = (format + \"\").trim().toLowerCase();\n return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000\n : l === 3 ? new Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00\n : l === 8 ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000\n : l === 4 ? rgba((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000\n : null) // invalid hex\n : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)\n : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)\n : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)\n : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)\n : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)\n : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)\n : named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins\n : format === \"transparent\" ? new Rgb(NaN, NaN, NaN, 0)\n : null;\n}\n\nfunction rgbn(n) {\n return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);\n}\n\nfunction rgba(r, g, b, a) {\n if (a <= 0) r = g = b = NaN;\n return new Rgb(r, g, b, a);\n}\n\nexport function rgbConvert(o) {\n if (!(o instanceof Color)) o = color(o);\n if (!o) return new Rgb;\n o = o.rgb();\n return new Rgb(o.r, o.g, o.b, o.opacity);\n}\n\nexport function rgb(r, g, b, opacity) {\n return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);\n}\n\nexport function Rgb(r, g, b, opacity) {\n this.r = +r;\n this.g = +g;\n this.b = +b;\n this.opacity = +opacity;\n}\n\ndefine(Rgb, rgb, extend(Color, {\n brighter(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);\n },\n darker(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);\n },\n rgb() {\n return this;\n },\n clamp() {\n return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity));\n },\n displayable() {\n return (-0.5 <= this.r && this.r < 255.5)\n && (-0.5 <= this.g && this.g < 255.5)\n && (-0.5 <= this.b && this.b < 255.5)\n && (0 <= this.opacity && this.opacity <= 1);\n },\n hex: rgb_formatHex, // Deprecated! Use color.formatHex.\n formatHex: rgb_formatHex,\n formatHex8: rgb_formatHex8,\n formatRgb: rgb_formatRgb,\n toString: rgb_formatRgb\n}));\n\nfunction rgb_formatHex() {\n return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`;\n}\n\nfunction rgb_formatHex8() {\n return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;\n}\n\nfunction rgb_formatRgb() {\n const a = clampa(this.opacity);\n return `${a === 1 ? \"rgb(\" : \"rgba(\"}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? \")\" : `, ${a})`}`;\n}\n\nfunction clampa(opacity) {\n return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));\n}\n\nfunction clampi(value) {\n return Math.max(0, Math.min(255, Math.round(value) || 0));\n}\n\nfunction hex(value) {\n value = clampi(value);\n return (value < 16 ? \"0\" : \"\") + value.toString(16);\n}\n\nfunction hsla(h, s, l, a) {\n if (a <= 0) h = s = l = NaN;\n else if (l <= 0 || l >= 1) h = s = NaN;\n else if (s <= 0) h = NaN;\n return new Hsl(h, s, l, a);\n}\n\nexport function hslConvert(o) {\n if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);\n if (!(o instanceof Color)) o = color(o);\n if (!o) return new Hsl;\n if (o instanceof Hsl) return o;\n o = o.rgb();\n var r = o.r / 255,\n g = o.g / 255,\n b = o.b / 255,\n min = Math.min(r, g, b),\n max = Math.max(r, g, b),\n h = NaN,\n s = max - min,\n l = (max + min) / 2;\n if (s) {\n if (r === max) h = (g - b) / s + (g < b) * 6;\n else if (g === max) h = (b - r) / s + 2;\n else h = (r - g) / s + 4;\n s /= l < 0.5 ? max + min : 2 - max - min;\n h *= 60;\n } else {\n s = l > 0 && l < 1 ? 0 : h;\n }\n return new Hsl(h, s, l, o.opacity);\n}\n\nexport function hsl(h, s, l, opacity) {\n return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);\n}\n\nfunction Hsl(h, s, l, opacity) {\n this.h = +h;\n this.s = +s;\n this.l = +l;\n this.opacity = +opacity;\n}\n\ndefine(Hsl, hsl, extend(Color, {\n brighter(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Hsl(this.h, this.s, this.l * k, this.opacity);\n },\n darker(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Hsl(this.h, this.s, this.l * k, this.opacity);\n },\n rgb() {\n var h = this.h % 360 + (this.h < 0) * 360,\n s = isNaN(h) || isNaN(this.s) ? 0 : this.s,\n l = this.l,\n m2 = l + (l < 0.5 ? l : 1 - l) * s,\n m1 = 2 * l - m2;\n return new Rgb(\n hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),\n hsl2rgb(h, m1, m2),\n hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),\n this.opacity\n );\n },\n clamp() {\n return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity));\n },\n displayable() {\n return (0 <= this.s && this.s <= 1 || isNaN(this.s))\n && (0 <= this.l && this.l <= 1)\n && (0 <= this.opacity && this.opacity <= 1);\n },\n formatHsl() {\n const a = clampa(this.opacity);\n return `${a === 1 ? \"hsl(\" : \"hsla(\"}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? \")\" : `, ${a})`}`;\n }\n}));\n\nfunction clamph(value) {\n value = (value || 0) % 360;\n return value < 0 ? value + 360 : value;\n}\n\nfunction clampt(value) {\n return Math.max(0, Math.min(1, value || 0));\n}\n\n/* From FvD 13.37, CSS Color Module Level 3 */\nfunction hsl2rgb(h, m1, m2) {\n return (h < 60 ? m1 + (m2 - m1) * h / 60\n : h < 180 ? m2\n : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60\n : m1) * 255;\n}\n", "export function basis(t1, v0, v1, v2, v3) {\n var t2 = t1 * t1, t3 = t2 * t1;\n return ((1 - 3 * t1 + 3 * t2 - t3) * v0\n + (4 - 6 * t2 + 3 * t3) * v1\n + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2\n + t3 * v3) / 6;\n}\n\nexport default function(values) {\n var n = values.length - 1;\n return function(t) {\n var i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n),\n v1 = values[i],\n v2 = values[i + 1],\n v0 = i > 0 ? values[i - 1] : 2 * v1 - v2,\n v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;\n return basis((t - i / n) * n, v0, v1, v2, v3);\n };\n}\n", "import {basis} from \"./basis.js\";\n\nexport default function(values) {\n var n = values.length;\n return function(t) {\n var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n),\n v0 = values[(i + n - 1) % n],\n v1 = values[i % n],\n v2 = values[(i + 1) % n],\n v3 = values[(i + 2) % n];\n return basis((t - i / n) * n, v0, v1, v2, v3);\n };\n}\n", "export default x => () => x;\n", "import constant from \"./constant.js\";\n\nfunction linear(a, d) {\n return function(t) {\n return a + t * d;\n };\n}\n\nfunction exponential(a, b, y) {\n return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {\n return Math.pow(a + t * b, y);\n };\n}\n\nexport function hue(a, b) {\n var d = b - a;\n return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant(isNaN(a) ? b : a);\n}\n\nexport function gamma(y) {\n return (y = +y) === 1 ? nogamma : function(a, b) {\n return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a);\n };\n}\n\nexport default function nogamma(a, b) {\n var d = b - a;\n return d ? linear(a, d) : constant(isNaN(a) ? b : a);\n}\n", "import {rgb as colorRgb} from \"d3-color\";\nimport basis from \"./basis.js\";\nimport basisClosed from \"./basisClosed.js\";\nimport nogamma, {gamma} from \"./color.js\";\n\nexport default (function rgbGamma(y) {\n var color = gamma(y);\n\n function rgb(start, end) {\n var r = color((start = colorRgb(start)).r, (end = colorRgb(end)).r),\n g = color(start.g, end.g),\n b = color(start.b, end.b),\n opacity = nogamma(start.opacity, end.opacity);\n return function(t) {\n start.r = r(t);\n start.g = g(t);\n start.b = b(t);\n start.opacity = opacity(t);\n return start + \"\";\n };\n }\n\n rgb.gamma = rgbGamma;\n\n return rgb;\n})(1);\n\nfunction rgbSpline(spline) {\n return function(colors) {\n var n = colors.length,\n r = new Array(n),\n g = new Array(n),\n b = new Array(n),\n i, color;\n for (i = 0; i < n; ++i) {\n color = colorRgb(colors[i]);\n r[i] = color.r || 0;\n g[i] = color.g || 0;\n b[i] = color.b || 0;\n }\n r = spline(r);\n g = spline(g);\n b = spline(b);\n color.opacity = 1;\n return function(t) {\n color.r = r(t);\n color.g = g(t);\n color.b = b(t);\n return color + \"\";\n };\n };\n}\n\nexport var rgbBasis = rgbSpline(basis);\nexport var rgbBasisClosed = rgbSpline(basisClosed);\n", "export default function(a, b) {\n if (!b) b = [];\n var n = a ? Math.min(b.length, a.length) : 0,\n c = b.slice(),\n i;\n return function(t) {\n for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t) + b[i] * t;\n return c;\n };\n}\n\nexport function isNumberArray(x) {\n return ArrayBuffer.isView(x) && !(x instanceof DataView);\n}\n", "import value from \"./value.js\";\nimport numberArray, {isNumberArray} from \"./numberArray.js\";\n\nexport default function(a, b) {\n return (isNumberArray(b) ? numberArray : genericArray)(a, b);\n}\n\nexport function genericArray(a, b) {\n var nb = b ? b.length : 0,\n na = a ? Math.min(nb, a.length) : 0,\n x = new Array(na),\n c = new Array(nb),\n i;\n\n for (i = 0; i < na; ++i) x[i] = value(a[i], b[i]);\n for (; i < nb; ++i) c[i] = b[i];\n\n return function(t) {\n for (i = 0; i < na; ++i) c[i] = x[i](t);\n return c;\n };\n}\n", "export default function(a, b) {\n var d = new Date;\n return a = +a, b = +b, function(t) {\n return d.setTime(a * (1 - t) + b * t), d;\n };\n}\n", "export default function(a, b) {\n return a = +a, b = +b, function(t) {\n return a * (1 - t) + b * t;\n };\n}\n", "import value from \"./value.js\";\n\nexport default function(a, b) {\n var i = {},\n c = {},\n k;\n\n if (a === null || typeof a !== \"object\") a = {};\n if (b === null || typeof b !== \"object\") b = {};\n\n for (k in b) {\n if (k in a) {\n i[k] = value(a[k], b[k]);\n } else {\n c[k] = b[k];\n }\n }\n\n return function(t) {\n for (k in i) c[k] = i[k](t);\n return c;\n };\n}\n", "import number from \"./number.js\";\n\nvar reA = /[-+]?(?:\\d+\\.?\\d*|\\.?\\d+)(?:[eE][-+]?\\d+)?/g,\n reB = new RegExp(reA.source, \"g\");\n\nfunction zero(b) {\n return function() {\n return b;\n };\n}\n\nfunction one(b) {\n return function(t) {\n return b(t) + \"\";\n };\n}\n\nexport default function(a, b) {\n var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b\n am, // current match in a\n bm, // current match in b\n bs, // string preceding current number in b, if any\n i = -1, // index in s\n s = [], // string constants and placeholders\n q = []; // number interpolators\n\n // Coerce inputs to strings.\n a = a + \"\", b = b + \"\";\n\n // Interpolate pairs of numbers in a & b.\n while ((am = reA.exec(a))\n && (bm = reB.exec(b))) {\n if ((bs = bm.index) > bi) { // a string precedes the next number in b\n bs = b.slice(bi, bs);\n if (s[i]) s[i] += bs; // coalesce with previous string\n else s[++i] = bs;\n }\n if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match\n if (s[i]) s[i] += bm; // coalesce with previous string\n else s[++i] = bm;\n } else { // interpolate non-matching numbers\n s[++i] = null;\n q.push({i: i, x: number(am, bm)});\n }\n bi = reB.lastIndex;\n }\n\n // Add remains of b.\n if (bi < b.length) {\n bs = b.slice(bi);\n if (s[i]) s[i] += bs; // coalesce with previous string\n else s[++i] = bs;\n }\n\n // Special optimization for only a single match.\n // Otherwise, interpolate each of the numbers and rejoin the string.\n return s.length < 2 ? (q[0]\n ? one(q[0].x)\n : zero(b))\n : (b = q.length, function(t) {\n for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);\n return s.join(\"\");\n });\n}\n", "import {color} from \"d3-color\";\nimport rgb from \"./rgb.js\";\nimport {genericArray} from \"./array.js\";\nimport date from \"./date.js\";\nimport number from \"./number.js\";\nimport object from \"./object.js\";\nimport string from \"./string.js\";\nimport constant from \"./constant.js\";\nimport numberArray, {isNumberArray} from \"./numberArray.js\";\n\nexport default function(a, b) {\n var t = typeof b, c;\n return b == null || t === \"boolean\" ? constant(b)\n : (t === \"number\" ? number\n : t === \"string\" ? ((c = color(b)) ? (b = c, rgb) : string)\n : b instanceof color ? rgb\n : b instanceof Date ? date\n : isNumberArray(b) ? numberArray\n : Array.isArray(b) ? genericArray\n : typeof b.valueOf !== \"function\" && typeof b.toString !== \"function\" || isNaN(b) ? object\n : number)(a, b);\n}\n", "export default function(a, b) {\n return a = +a, b = +b, function(t) {\n return Math.round(a * (1 - t) + b * t);\n };\n}\n", "import {default as value} from \"./value.js\";\n\nexport default function piecewise(interpolate, values) {\n if (values === undefined) values = interpolate, interpolate = value;\n var i = 0, n = values.length - 1, v = values[0], I = new Array(n < 0 ? 0 : n);\n while (i < n) I[i] = interpolate(v, v = values[++i]);\n return function(t) {\n var i = Math.max(0, Math.min(n - 1, Math.floor(t *= n)));\n return I[i](t - i);\n };\n}\n", "export default function constants(x) {\n return function() {\n return x;\n };\n}\n", "export default function number(x) {\n return +x;\n}\n", "import {bisect} from \"d3-array\";\nimport {interpolate as interpolateValue, interpolateNumber, interpolateRound} from \"d3-interpolate\";\nimport constant from \"./constant.js\";\nimport number from \"./number.js\";\n\nvar unit = [0, 1];\n\nexport function identity(x) {\n return x;\n}\n\nfunction normalize(a, b) {\n return (b -= (a = +a))\n ? function(x) { return (x - a) / b; }\n : constant(isNaN(b) ? NaN : 0.5);\n}\n\nfunction clamper(a, b) {\n var t;\n if (a > b) t = a, a = b, b = t;\n return function(x) { return Math.max(a, Math.min(b, x)); };\n}\n\n// normalize(a, b)(x) takes a domain value x in [a,b] and returns the corresponding parameter t in [0,1].\n// interpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding range value x in [a,b].\nfunction bimap(domain, range, interpolate) {\n var d0 = domain[0], d1 = domain[1], r0 = range[0], r1 = range[1];\n if (d1 < d0) d0 = normalize(d1, d0), r0 = interpolate(r1, r0);\n else d0 = normalize(d0, d1), r0 = interpolate(r0, r1);\n return function(x) { return r0(d0(x)); };\n}\n\nfunction polymap(domain, range, interpolate) {\n var j = Math.min(domain.length, range.length) - 1,\n d = new Array(j),\n r = new Array(j),\n i = -1;\n\n // Reverse descending domains.\n if (domain[j] < domain[0]) {\n domain = domain.slice().reverse();\n range = range.slice().reverse();\n }\n\n while (++i < j) {\n d[i] = normalize(domain[i], domain[i + 1]);\n r[i] = interpolate(range[i], range[i + 1]);\n }\n\n return function(x) {\n var i = bisect(domain, x, 1, j) - 1;\n return r[i](d[i](x));\n };\n}\n\nexport function copy(source, target) {\n return target\n .domain(source.domain())\n .range(source.range())\n .interpolate(source.interpolate())\n .clamp(source.clamp())\n .unknown(source.unknown());\n}\n\nexport function transformer() {\n var domain = unit,\n range = unit,\n interpolate = interpolateValue,\n transform,\n untransform,\n unknown,\n clamp = identity,\n piecewise,\n output,\n input;\n\n function rescale() {\n var n = Math.min(domain.length, range.length);\n if (clamp !== identity) clamp = clamper(domain[0], domain[n - 1]);\n piecewise = n > 2 ? polymap : bimap;\n output = input = null;\n return scale;\n }\n\n function scale(x) {\n return x == null || isNaN(x = +x) ? unknown : (output || (output = piecewise(domain.map(transform), range, interpolate)))(transform(clamp(x)));\n }\n\n scale.invert = function(y) {\n return clamp(untransform((input || (input = piecewise(range, domain.map(transform), interpolateNumber)))(y)));\n };\n\n scale.domain = function(_) {\n return arguments.length ? (domain = Array.from(_, number), rescale()) : domain.slice();\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = Array.from(_), rescale()) : range.slice();\n };\n\n scale.rangeRound = function(_) {\n return range = Array.from(_), interpolate = interpolateRound, rescale();\n };\n\n scale.clamp = function(_) {\n return arguments.length ? (clamp = _ ? true : identity, rescale()) : clamp !== identity;\n };\n\n scale.interpolate = function(_) {\n return arguments.length ? (interpolate = _, rescale()) : interpolate;\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n return function(t, u) {\n transform = t, untransform = u;\n return rescale();\n };\n}\n\nexport default function continuous() {\n return transformer()(identity, identity);\n}\n", "export default function(x) {\n return Math.abs(x = Math.round(x)) >= 1e21\n ? x.toLocaleString(\"en\").replace(/,/g, \"\")\n : x.toString(10);\n}\n\n// Computes the decimal coefficient and exponent of the specified number x with\n// significant digits p, where x is positive and p is in [1, 21] or undefined.\n// For example, formatDecimalParts(1.23) returns [\"123\", 0].\nexport function formatDecimalParts(x, p) {\n if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf(\"e\")) < 0) return null; // NaN, \u00B1Infinity\n var i, coefficient = x.slice(0, i);\n\n // The string returned by toExponential either has the form \\d\\.\\d+e[-+]\\d+\n // (e.g., 1.2e+3) or the form \\de[-+]\\d+ (e.g., 1e+3).\n return [\n coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,\n +x.slice(i + 1)\n ];\n}\n", "import {formatDecimalParts} from \"./formatDecimal.js\";\n\nexport default function(x) {\n return x = formatDecimalParts(Math.abs(x)), x ? x[1] : NaN;\n}\n", "export default function(grouping, thousands) {\n return function(value, width) {\n var i = value.length,\n t = [],\n j = 0,\n g = grouping[0],\n length = 0;\n\n while (i > 0 && g > 0) {\n if (length + g + 1 > width) g = Math.max(1, width - length);\n t.push(value.substring(i -= g, i + g));\n if ((length += g + 1) > width) break;\n g = grouping[j = (j + 1) % grouping.length];\n }\n\n return t.reverse().join(thousands);\n };\n}\n", "export default function(numerals) {\n return function(value) {\n return value.replace(/[0-9]/g, function(i) {\n return numerals[+i];\n });\n };\n}\n", "// [[fill]align][sign][symbol][0][width][,][.precision][~][type]\nvar re = /^(?:(.)?([<>=^]))?([+\\-( ])?([$#])?(0)?(\\d+)?(,)?(\\.\\d+)?(~)?([a-z%])?$/i;\n\nexport default function formatSpecifier(specifier) {\n if (!(match = re.exec(specifier))) throw new Error(\"invalid format: \" + specifier);\n var match;\n return new FormatSpecifier({\n fill: match[1],\n align: match[2],\n sign: match[3],\n symbol: match[4],\n zero: match[5],\n width: match[6],\n comma: match[7],\n precision: match[8] && match[8].slice(1),\n trim: match[9],\n type: match[10]\n });\n}\n\nformatSpecifier.prototype = FormatSpecifier.prototype; // instanceof\n\nexport function FormatSpecifier(specifier) {\n this.fill = specifier.fill === undefined ? \" \" : specifier.fill + \"\";\n this.align = specifier.align === undefined ? \">\" : specifier.align + \"\";\n this.sign = specifier.sign === undefined ? \"-\" : specifier.sign + \"\";\n this.symbol = specifier.symbol === undefined ? \"\" : specifier.symbol + \"\";\n this.zero = !!specifier.zero;\n this.width = specifier.width === undefined ? undefined : +specifier.width;\n this.comma = !!specifier.comma;\n this.precision = specifier.precision === undefined ? undefined : +specifier.precision;\n this.trim = !!specifier.trim;\n this.type = specifier.type === undefined ? \"\" : specifier.type + \"\";\n}\n\nFormatSpecifier.prototype.toString = function() {\n return this.fill\n + this.align\n + this.sign\n + this.symbol\n + (this.zero ? \"0\" : \"\")\n + (this.width === undefined ? \"\" : Math.max(1, this.width | 0))\n + (this.comma ? \",\" : \"\")\n + (this.precision === undefined ? \"\" : \".\" + Math.max(0, this.precision | 0))\n + (this.trim ? \"~\" : \"\")\n + this.type;\n};\n", "// Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.\nexport default function(s) {\n out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {\n switch (s[i]) {\n case \".\": i0 = i1 = i; break;\n case \"0\": if (i0 === 0) i0 = i; i1 = i; break;\n default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break;\n }\n }\n return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;\n}\n", "import {formatDecimalParts} from \"./formatDecimal.js\";\n\nexport var prefixExponent;\n\nexport default function(x, p) {\n var d = formatDecimalParts(x, p);\n if (!d) return x + \"\";\n var coefficient = d[0],\n exponent = d[1],\n i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,\n n = coefficient.length;\n return i === n ? coefficient\n : i > n ? coefficient + new Array(i - n + 1).join(\"0\")\n : i > 0 ? coefficient.slice(0, i) + \".\" + coefficient.slice(i)\n : \"0.\" + new Array(1 - i).join(\"0\") + formatDecimalParts(x, Math.max(0, p + i - 1))[0]; // less than 1y!\n}\n", "import {formatDecimalParts} from \"./formatDecimal.js\";\n\nexport default function(x, p) {\n var d = formatDecimalParts(x, p);\n if (!d) return x + \"\";\n var coefficient = d[0],\n exponent = d[1];\n return exponent < 0 ? \"0.\" + new Array(-exponent).join(\"0\") + coefficient\n : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + \".\" + coefficient.slice(exponent + 1)\n : coefficient + new Array(exponent - coefficient.length + 2).join(\"0\");\n}\n", "import formatDecimal from \"./formatDecimal.js\";\nimport formatPrefixAuto from \"./formatPrefixAuto.js\";\nimport formatRounded from \"./formatRounded.js\";\n\nexport default {\n \"%\": (x, p) => (x * 100).toFixed(p),\n \"b\": (x) => Math.round(x).toString(2),\n \"c\": (x) => x + \"\",\n \"d\": formatDecimal,\n \"e\": (x, p) => x.toExponential(p),\n \"f\": (x, p) => x.toFixed(p),\n \"g\": (x, p) => x.toPrecision(p),\n \"o\": (x) => Math.round(x).toString(8),\n \"p\": (x, p) => formatRounded(x * 100, p),\n \"r\": formatRounded,\n \"s\": formatPrefixAuto,\n \"X\": (x) => Math.round(x).toString(16).toUpperCase(),\n \"x\": (x) => Math.round(x).toString(16)\n};\n", "export default function(x) {\n return x;\n}\n", "import exponent from \"./exponent.js\";\nimport formatGroup from \"./formatGroup.js\";\nimport formatNumerals from \"./formatNumerals.js\";\nimport formatSpecifier from \"./formatSpecifier.js\";\nimport formatTrim from \"./formatTrim.js\";\nimport formatTypes from \"./formatTypes.js\";\nimport {prefixExponent} from \"./formatPrefixAuto.js\";\nimport identity from \"./identity.js\";\n\nvar map = Array.prototype.map,\n prefixes = [\"y\",\"z\",\"a\",\"f\",\"p\",\"n\",\"\u00B5\",\"m\",\"\",\"k\",\"M\",\"G\",\"T\",\"P\",\"E\",\"Z\",\"Y\"];\n\nexport default function(locale) {\n var group = locale.grouping === undefined || locale.thousands === undefined ? identity : formatGroup(map.call(locale.grouping, Number), locale.thousands + \"\"),\n currencyPrefix = locale.currency === undefined ? \"\" : locale.currency[0] + \"\",\n currencySuffix = locale.currency === undefined ? \"\" : locale.currency[1] + \"\",\n decimal = locale.decimal === undefined ? \".\" : locale.decimal + \"\",\n numerals = locale.numerals === undefined ? identity : formatNumerals(map.call(locale.numerals, String)),\n percent = locale.percent === undefined ? \"%\" : locale.percent + \"\",\n minus = locale.minus === undefined ? \"\u2212\" : locale.minus + \"\",\n nan = locale.nan === undefined ? \"NaN\" : locale.nan + \"\";\n\n function newFormat(specifier) {\n specifier = formatSpecifier(specifier);\n\n var fill = specifier.fill,\n align = specifier.align,\n sign = specifier.sign,\n symbol = specifier.symbol,\n zero = specifier.zero,\n width = specifier.width,\n comma = specifier.comma,\n precision = specifier.precision,\n trim = specifier.trim,\n type = specifier.type;\n\n // The \"n\" type is an alias for \",g\".\n if (type === \"n\") comma = true, type = \"g\";\n\n // The \"\" type, and any invalid type, is an alias for \".12~g\".\n else if (!formatTypes[type]) precision === undefined && (precision = 12), trim = true, type = \"g\";\n\n // If zero fill is specified, padding goes after sign and before digits.\n if (zero || (fill === \"0\" && align === \"=\")) zero = true, fill = \"0\", align = \"=\";\n\n // Compute the prefix and suffix.\n // For SI-prefix, the suffix is lazily computed.\n var prefix = symbol === \"$\" ? currencyPrefix : symbol === \"#\" && /[boxX]/.test(type) ? \"0\" + type.toLowerCase() : \"\",\n suffix = symbol === \"$\" ? currencySuffix : /[%p]/.test(type) ? percent : \"\";\n\n // What format function should we use?\n // Is this an integer type?\n // Can this type generate exponential notation?\n var formatType = formatTypes[type],\n maybeSuffix = /[defgprs%]/.test(type);\n\n // Set the default precision if not specified,\n // or clamp the specified precision to the supported range.\n // For significant precision, it must be in [1, 21].\n // For fixed precision, it must be in [0, 20].\n precision = precision === undefined ? 6\n : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))\n : Math.max(0, Math.min(20, precision));\n\n function format(value) {\n var valuePrefix = prefix,\n valueSuffix = suffix,\n i, n, c;\n\n if (type === \"c\") {\n valueSuffix = formatType(value) + valueSuffix;\n value = \"\";\n } else {\n value = +value;\n\n // Determine the sign. -0 is not less than 0, but 1 / -0 is!\n var valueNegative = value < 0 || 1 / value < 0;\n\n // Perform the initial formatting.\n value = isNaN(value) ? nan : formatType(Math.abs(value), precision);\n\n // Trim insignificant zeros.\n if (trim) value = formatTrim(value);\n\n // If a negative value rounds to zero after formatting, and no explicit positive sign is requested, hide the sign.\n if (valueNegative && +value === 0 && sign !== \"+\") valueNegative = false;\n\n // Compute the prefix and suffix.\n valuePrefix = (valueNegative ? (sign === \"(\" ? sign : minus) : sign === \"-\" || sign === \"(\" ? \"\" : sign) + valuePrefix;\n valueSuffix = (type === \"s\" ? prefixes[8 + prefixExponent / 3] : \"\") + valueSuffix + (valueNegative && sign === \"(\" ? \")\" : \"\");\n\n // Break the formatted value into the integer \u201Cvalue\u201D part that can be\n // grouped, and fractional or exponential \u201Csuffix\u201D part that is not.\n if (maybeSuffix) {\n i = -1, n = value.length;\n while (++i < n) {\n if (c = value.charCodeAt(i), 48 > c || c > 57) {\n valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;\n value = value.slice(0, i);\n break;\n }\n }\n }\n }\n\n // If the fill character is not \"0\", grouping is applied before padding.\n if (comma && !zero) value = group(value, Infinity);\n\n // Compute the padding.\n var length = valuePrefix.length + value.length + valueSuffix.length,\n padding = length < width ? new Array(width - length + 1).join(fill) : \"\";\n\n // If the fill character is \"0\", grouping is applied after padding.\n if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = \"\";\n\n // Reconstruct the final output based on the desired alignment.\n switch (align) {\n case \"<\": value = valuePrefix + value + valueSuffix + padding; break;\n case \"=\": value = valuePrefix + padding + value + valueSuffix; break;\n case \"^\": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;\n default: value = padding + valuePrefix + value + valueSuffix; break;\n }\n\n return numerals(value);\n }\n\n format.toString = function() {\n return specifier + \"\";\n };\n\n return format;\n }\n\n function formatPrefix(specifier, value) {\n var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = \"f\", specifier)),\n e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3,\n k = Math.pow(10, -e),\n prefix = prefixes[8 + e / 3];\n return function(value) {\n return f(k * value) + prefix;\n };\n }\n\n return {\n format: newFormat,\n formatPrefix: formatPrefix\n };\n}\n", "import formatLocale from \"./locale.js\";\n\nvar locale;\nexport var format;\nexport var formatPrefix;\n\ndefaultLocale({\n thousands: \",\",\n grouping: [3],\n currency: [\"$\", \"\"]\n});\n\nexport default function defaultLocale(definition) {\n locale = formatLocale(definition);\n format = locale.format;\n formatPrefix = locale.formatPrefix;\n return locale;\n}\n", "import exponent from \"./exponent.js\";\n\nexport default function(step) {\n return Math.max(0, -exponent(Math.abs(step)));\n}\n", "import exponent from \"./exponent.js\";\n\nexport default function(step, value) {\n return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3 - exponent(Math.abs(step)));\n}\n", "import exponent from \"./exponent.js\";\n\nexport default function(step, max) {\n step = Math.abs(step), max = Math.abs(max) - step;\n return Math.max(0, exponent(max) - exponent(step)) + 1;\n}\n", "import {tickStep} from \"d3-array\";\nimport {format, formatPrefix, formatSpecifier, precisionFixed, precisionPrefix, precisionRound} from \"d3-format\";\n\nexport default function tickFormat(start, stop, count, specifier) {\n var step = tickStep(start, stop, count),\n precision;\n specifier = formatSpecifier(specifier == null ? \",f\" : specifier);\n switch (specifier.type) {\n case \"s\": {\n var value = Math.max(Math.abs(start), Math.abs(stop));\n if (specifier.precision == null && !isNaN(precision = precisionPrefix(step, value))) specifier.precision = precision;\n return formatPrefix(specifier, value);\n }\n case \"\":\n case \"e\":\n case \"g\":\n case \"p\":\n case \"r\": {\n if (specifier.precision == null && !isNaN(precision = precisionRound(step, Math.max(Math.abs(start), Math.abs(stop))))) specifier.precision = precision - (specifier.type === \"e\");\n break;\n }\n case \"f\":\n case \"%\": {\n if (specifier.precision == null && !isNaN(precision = precisionFixed(step))) specifier.precision = precision - (specifier.type === \"%\") * 2;\n break;\n }\n }\n return format(specifier);\n}\n", "import {ticks, tickIncrement} from \"d3-array\";\nimport continuous, {copy} from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\nimport tickFormat from \"./tickFormat.js\";\n\nexport function linearish(scale) {\n var domain = scale.domain;\n\n scale.ticks = function(count) {\n var d = domain();\n return ticks(d[0], d[d.length - 1], count == null ? 10 : count);\n };\n\n scale.tickFormat = function(count, specifier) {\n var d = domain();\n return tickFormat(d[0], d[d.length - 1], count == null ? 10 : count, specifier);\n };\n\n scale.nice = function(count) {\n if (count == null) count = 10;\n\n var d = domain();\n var i0 = 0;\n var i1 = d.length - 1;\n var start = d[i0];\n var stop = d[i1];\n var prestep;\n var step;\n var maxIter = 10;\n\n if (stop < start) {\n step = start, start = stop, stop = step;\n step = i0, i0 = i1, i1 = step;\n }\n \n while (maxIter-- > 0) {\n step = tickIncrement(start, stop, count);\n if (step === prestep) {\n d[i0] = start\n d[i1] = stop\n return domain(d);\n } else if (step > 0) {\n start = Math.floor(start / step) * step;\n stop = Math.ceil(stop / step) * step;\n } else if (step < 0) {\n start = Math.ceil(start * step) / step;\n stop = Math.floor(stop * step) / step;\n } else {\n break;\n }\n prestep = step;\n }\n\n return scale;\n };\n\n return scale;\n}\n\nexport default function linear() {\n var scale = continuous();\n\n scale.copy = function() {\n return copy(scale, linear());\n };\n\n initRange.apply(scale, arguments);\n\n return linearish(scale);\n}\n", "import {linearish} from \"./linear.js\";\nimport number from \"./number.js\";\n\nexport default function identity(domain) {\n var unknown;\n\n function scale(x) {\n return x == null || isNaN(x = +x) ? unknown : x;\n }\n\n scale.invert = scale;\n\n scale.domain = scale.range = function(_) {\n return arguments.length ? (domain = Array.from(_, number), scale) : domain.slice();\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n scale.copy = function() {\n return identity(domain).unknown(unknown);\n };\n\n domain = arguments.length ? Array.from(domain, number) : [0, 1];\n\n return linearish(scale);\n}\n", "export default function nice(domain, interval) {\n domain = domain.slice();\n\n var i0 = 0,\n i1 = domain.length - 1,\n x0 = domain[i0],\n x1 = domain[i1],\n t;\n\n if (x1 < x0) {\n t = i0, i0 = i1, i1 = t;\n t = x0, x0 = x1, x1 = t;\n }\n\n domain[i0] = interval.floor(x0);\n domain[i1] = interval.ceil(x1);\n return domain;\n}\n", "import {ticks} from \"d3-array\";\nimport {format, formatSpecifier} from \"d3-format\";\nimport nice from \"./nice.js\";\nimport {copy, transformer} from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\n\nfunction transformLog(x) {\n return Math.log(x);\n}\n\nfunction transformExp(x) {\n return Math.exp(x);\n}\n\nfunction transformLogn(x) {\n return -Math.log(-x);\n}\n\nfunction transformExpn(x) {\n return -Math.exp(-x);\n}\n\nfunction pow10(x) {\n return isFinite(x) ? +(\"1e\" + x) : x < 0 ? 0 : x;\n}\n\nfunction powp(base) {\n return base === 10 ? pow10\n : base === Math.E ? Math.exp\n : x => Math.pow(base, x);\n}\n\nfunction logp(base) {\n return base === Math.E ? Math.log\n : base === 10 && Math.log10\n || base === 2 && Math.log2\n || (base = Math.log(base), x => Math.log(x) / base);\n}\n\nfunction reflect(f) {\n return (x, k) => -f(-x, k);\n}\n\nexport function loggish(transform) {\n const scale = transform(transformLog, transformExp);\n const domain = scale.domain;\n let base = 10;\n let logs;\n let pows;\n\n function rescale() {\n logs = logp(base), pows = powp(base);\n if (domain()[0] < 0) {\n logs = reflect(logs), pows = reflect(pows);\n transform(transformLogn, transformExpn);\n } else {\n transform(transformLog, transformExp);\n }\n return scale;\n }\n\n scale.base = function(_) {\n return arguments.length ? (base = +_, rescale()) : base;\n };\n\n scale.domain = function(_) {\n return arguments.length ? (domain(_), rescale()) : domain();\n };\n\n scale.ticks = count => {\n const d = domain();\n let u = d[0];\n let v = d[d.length - 1];\n const r = v < u;\n\n if (r) ([u, v] = [v, u]);\n\n let i = logs(u);\n let j = logs(v);\n let k;\n let t;\n const n = count == null ? 10 : +count;\n let z = [];\n\n if (!(base % 1) && j - i < n) {\n i = Math.floor(i), j = Math.ceil(j);\n if (u > 0) for (; i <= j; ++i) {\n for (k = 1; k < base; ++k) {\n t = i < 0 ? k / pows(-i) : k * pows(i);\n if (t < u) continue;\n if (t > v) break;\n z.push(t);\n }\n } else for (; i <= j; ++i) {\n for (k = base - 1; k >= 1; --k) {\n t = i > 0 ? k / pows(-i) : k * pows(i);\n if (t < u) continue;\n if (t > v) break;\n z.push(t);\n }\n }\n if (z.length * 2 < n) z = ticks(u, v, n);\n } else {\n z = ticks(i, j, Math.min(j - i, n)).map(pows);\n }\n return r ? z.reverse() : z;\n };\n\n scale.tickFormat = (count, specifier) => {\n if (count == null) count = 10;\n if (specifier == null) specifier = base === 10 ? \"s\" : \",\";\n if (typeof specifier !== \"function\") {\n if (!(base % 1) && (specifier = formatSpecifier(specifier)).precision == null) specifier.trim = true;\n specifier = format(specifier);\n }\n if (count === Infinity) return specifier;\n const k = Math.max(1, base * count / scale.ticks().length); // TODO fast estimate?\n return d => {\n let i = d / pows(Math.round(logs(d)));\n if (i * base < base - 0.5) i *= base;\n return i <= k ? specifier(d) : \"\";\n };\n };\n\n scale.nice = () => {\n return domain(nice(domain(), {\n floor: x => pows(Math.floor(logs(x))),\n ceil: x => pows(Math.ceil(logs(x)))\n }));\n };\n\n return scale;\n}\n\nexport default function log() {\n const scale = loggish(transformer()).domain([1, 10]);\n scale.copy = () => copy(scale, log()).base(scale.base());\n initRange.apply(scale, arguments);\n return scale;\n}\n", "import {linearish} from \"./linear.js\";\nimport {copy, transformer} from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\n\nfunction transformSymlog(c) {\n return function(x) {\n return Math.sign(x) * Math.log1p(Math.abs(x / c));\n };\n}\n\nfunction transformSymexp(c) {\n return function(x) {\n return Math.sign(x) * Math.expm1(Math.abs(x)) * c;\n };\n}\n\nexport function symlogish(transform) {\n var c = 1, scale = transform(transformSymlog(c), transformSymexp(c));\n\n scale.constant = function(_) {\n return arguments.length ? transform(transformSymlog(c = +_), transformSymexp(c)) : c;\n };\n\n return linearish(scale);\n}\n\nexport default function symlog() {\n var scale = symlogish(transformer());\n\n scale.copy = function() {\n return copy(scale, symlog()).constant(scale.constant());\n };\n\n return initRange.apply(scale, arguments);\n}\n", "import {linearish} from \"./linear.js\";\nimport {copy, identity, transformer} from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\n\nfunction transformPow(exponent) {\n return function(x) {\n return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);\n };\n}\n\nfunction transformSqrt(x) {\n return x < 0 ? -Math.sqrt(-x) : Math.sqrt(x);\n}\n\nfunction transformSquare(x) {\n return x < 0 ? -x * x : x * x;\n}\n\nexport function powish(transform) {\n var scale = transform(identity, identity),\n exponent = 1;\n\n function rescale() {\n return exponent === 1 ? transform(identity, identity)\n : exponent === 0.5 ? transform(transformSqrt, transformSquare)\n : transform(transformPow(exponent), transformPow(1 / exponent));\n }\n\n scale.exponent = function(_) {\n return arguments.length ? (exponent = +_, rescale()) : exponent;\n };\n\n return linearish(scale);\n}\n\nexport default function pow() {\n var scale = powish(transformer());\n\n scale.copy = function() {\n return copy(scale, pow()).exponent(scale.exponent());\n };\n\n initRange.apply(scale, arguments);\n\n return scale;\n}\n\nexport function sqrt() {\n return pow.apply(null, arguments).exponent(0.5);\n}\n", "import continuous from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\nimport {linearish} from \"./linear.js\";\nimport number from \"./number.js\";\n\nfunction square(x) {\n return Math.sign(x) * x * x;\n}\n\nfunction unsquare(x) {\n return Math.sign(x) * Math.sqrt(Math.abs(x));\n}\n\nexport default function radial() {\n var squared = continuous(),\n range = [0, 1],\n round = false,\n unknown;\n\n function scale(x) {\n var y = unsquare(squared(x));\n return isNaN(y) ? unknown : round ? Math.round(y) : y;\n }\n\n scale.invert = function(y) {\n return squared.invert(square(y));\n };\n\n scale.domain = function(_) {\n return arguments.length ? (squared.domain(_), scale) : squared.domain();\n };\n\n scale.range = function(_) {\n return arguments.length ? (squared.range((range = Array.from(_, number)).map(square)), scale) : range.slice();\n };\n\n scale.rangeRound = function(_) {\n return scale.range(_).round(true);\n };\n\n scale.round = function(_) {\n return arguments.length ? (round = !!_, scale) : round;\n };\n\n scale.clamp = function(_) {\n return arguments.length ? (squared.clamp(_), scale) : squared.clamp();\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n scale.copy = function() {\n return radial(squared.domain(), range)\n .round(round)\n .clamp(squared.clamp())\n .unknown(unknown);\n };\n\n initRange.apply(scale, arguments);\n\n return linearish(scale);\n}\n", "import {ascending, bisect, quantileSorted as threshold} from \"d3-array\";\nimport {initRange} from \"./init.js\";\n\nexport default function quantile() {\n var domain = [],\n range = [],\n thresholds = [],\n unknown;\n\n function rescale() {\n var i = 0, n = Math.max(1, range.length);\n thresholds = new Array(n - 1);\n while (++i < n) thresholds[i - 1] = threshold(domain, i / n);\n return scale;\n }\n\n function scale(x) {\n return x == null || isNaN(x = +x) ? unknown : range[bisect(thresholds, x)];\n }\n\n scale.invertExtent = function(y) {\n var i = range.indexOf(y);\n return i < 0 ? [NaN, NaN] : [\n i > 0 ? thresholds[i - 1] : domain[0],\n i < thresholds.length ? thresholds[i] : domain[domain.length - 1]\n ];\n };\n\n scale.domain = function(_) {\n if (!arguments.length) return domain.slice();\n domain = [];\n for (let d of _) if (d != null && !isNaN(d = +d)) domain.push(d);\n domain.sort(ascending);\n return rescale();\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = Array.from(_), rescale()) : range.slice();\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n scale.quantiles = function() {\n return thresholds.slice();\n };\n\n scale.copy = function() {\n return quantile()\n .domain(domain)\n .range(range)\n .unknown(unknown);\n };\n\n return initRange.apply(scale, arguments);\n}\n", "import {bisect} from \"d3-array\";\nimport {linearish} from \"./linear.js\";\nimport {initRange} from \"./init.js\";\n\nexport default function quantize() {\n var x0 = 0,\n x1 = 1,\n n = 1,\n domain = [0.5],\n range = [0, 1],\n unknown;\n\n function scale(x) {\n return x != null && x <= x ? range[bisect(domain, x, 0, n)] : unknown;\n }\n\n function rescale() {\n var i = -1;\n domain = new Array(n);\n while (++i < n) domain[i] = ((i + 1) * x1 - (i - n) * x0) / (n + 1);\n return scale;\n }\n\n scale.domain = function(_) {\n return arguments.length ? ([x0, x1] = _, x0 = +x0, x1 = +x1, rescale()) : [x0, x1];\n };\n\n scale.range = function(_) {\n return arguments.length ? (n = (range = Array.from(_)).length - 1, rescale()) : range.slice();\n };\n\n scale.invertExtent = function(y) {\n var i = range.indexOf(y);\n return i < 0 ? [NaN, NaN]\n : i < 1 ? [x0, domain[0]]\n : i >= n ? [domain[n - 1], x1]\n : [domain[i - 1], domain[i]];\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : scale;\n };\n\n scale.thresholds = function() {\n return domain.slice();\n };\n\n scale.copy = function() {\n return quantize()\n .domain([x0, x1])\n .range(range)\n .unknown(unknown);\n };\n\n return initRange.apply(linearish(scale), arguments);\n}\n", "import {bisect} from \"d3-array\";\nimport {initRange} from \"./init.js\";\n\nexport default function threshold() {\n var domain = [0.5],\n range = [0, 1],\n unknown,\n n = 1;\n\n function scale(x) {\n return x != null && x <= x ? range[bisect(domain, x, 0, n)] : unknown;\n }\n\n scale.domain = function(_) {\n return arguments.length ? (domain = Array.from(_), n = Math.min(domain.length, range.length - 1), scale) : domain.slice();\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = Array.from(_), n = Math.min(domain.length, range.length - 1), scale) : range.slice();\n };\n\n scale.invertExtent = function(y) {\n var i = range.indexOf(y);\n return [domain[i - 1], domain[i]];\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n scale.copy = function() {\n return threshold()\n .domain(domain)\n .range(range)\n .unknown(unknown);\n };\n\n return initRange.apply(scale, arguments);\n}\n", "const t0 = new Date, t1 = new Date;\n\nexport function timeInterval(floori, offseti, count, field) {\n\n function interval(date) {\n return floori(date = arguments.length === 0 ? new Date : new Date(+date)), date;\n }\n\n interval.floor = (date) => {\n return floori(date = new Date(+date)), date;\n };\n\n interval.ceil = (date) => {\n return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;\n };\n\n interval.round = (date) => {\n const d0 = interval(date), d1 = interval.ceil(date);\n return date - d0 < d1 - date ? d0 : d1;\n };\n\n interval.offset = (date, step) => {\n return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date;\n };\n\n interval.range = (start, stop, step) => {\n const range = [];\n start = interval.ceil(start);\n step = step == null ? 1 : Math.floor(step);\n if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date\n let previous;\n do range.push(previous = new Date(+start)), offseti(start, step), floori(start);\n while (previous < start && start < stop);\n return range;\n };\n\n interval.filter = (test) => {\n return timeInterval((date) => {\n if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1);\n }, (date, step) => {\n if (date >= date) {\n if (step < 0) while (++step <= 0) {\n while (offseti(date, -1), !test(date)) {} // eslint-disable-line no-empty\n } else while (--step >= 0) {\n while (offseti(date, +1), !test(date)) {} // eslint-disable-line no-empty\n }\n }\n });\n };\n\n if (count) {\n interval.count = (start, end) => {\n t0.setTime(+start), t1.setTime(+end);\n floori(t0), floori(t1);\n return Math.floor(count(t0, t1));\n };\n\n interval.every = (step) => {\n step = Math.floor(step);\n return !isFinite(step) || !(step > 0) ? null\n : !(step > 1) ? interval\n : interval.filter(field\n ? (d) => field(d) % step === 0\n : (d) => interval.count(0, d) % step === 0);\n };\n }\n\n return interval;\n}\n", "import {timeInterval} from \"./interval.js\";\n\nexport const millisecond = timeInterval(() => {\n // noop\n}, (date, step) => {\n date.setTime(+date + step);\n}, (start, end) => {\n return end - start;\n});\n\n// An optimized implementation for this simple case.\nmillisecond.every = (k) => {\n k = Math.floor(k);\n if (!isFinite(k) || !(k > 0)) return null;\n if (!(k > 1)) return millisecond;\n return timeInterval((date) => {\n date.setTime(Math.floor(date / k) * k);\n }, (date, step) => {\n date.setTime(+date + step * k);\n }, (start, end) => {\n return (end - start) / k;\n });\n};\n\nexport const milliseconds = millisecond.range;\n", "export const durationSecond = 1000;\nexport const durationMinute = durationSecond * 60;\nexport const durationHour = durationMinute * 60;\nexport const durationDay = durationHour * 24;\nexport const durationWeek = durationDay * 7;\nexport const durationMonth = durationDay * 30;\nexport const durationYear = durationDay * 365;\n", "import {timeInterval} from \"./interval.js\";\nimport {durationSecond} from \"./duration.js\";\n\nexport const second = timeInterval((date) => {\n date.setTime(date - date.getMilliseconds());\n}, (date, step) => {\n date.setTime(+date + step * durationSecond);\n}, (start, end) => {\n return (end - start) / durationSecond;\n}, (date) => {\n return date.getUTCSeconds();\n});\n\nexport const seconds = second.range;\n", "import {timeInterval} from \"./interval.js\";\nimport {durationMinute, durationSecond} from \"./duration.js\";\n\nexport const timeMinute = timeInterval((date) => {\n date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond);\n}, (date, step) => {\n date.setTime(+date + step * durationMinute);\n}, (start, end) => {\n return (end - start) / durationMinute;\n}, (date) => {\n return date.getMinutes();\n});\n\nexport const timeMinutes = timeMinute.range;\n\nexport const utcMinute = timeInterval((date) => {\n date.setUTCSeconds(0, 0);\n}, (date, step) => {\n date.setTime(+date + step * durationMinute);\n}, (start, end) => {\n return (end - start) / durationMinute;\n}, (date) => {\n return date.getUTCMinutes();\n});\n\nexport const utcMinutes = utcMinute.range;\n", "import {timeInterval} from \"./interval.js\";\nimport {durationHour, durationMinute, durationSecond} from \"./duration.js\";\n\nexport const timeHour = timeInterval((date) => {\n date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond - date.getMinutes() * durationMinute);\n}, (date, step) => {\n date.setTime(+date + step * durationHour);\n}, (start, end) => {\n return (end - start) / durationHour;\n}, (date) => {\n return date.getHours();\n});\n\nexport const timeHours = timeHour.range;\n\nexport const utcHour = timeInterval((date) => {\n date.setUTCMinutes(0, 0, 0);\n}, (date, step) => {\n date.setTime(+date + step * durationHour);\n}, (start, end) => {\n return (end - start) / durationHour;\n}, (date) => {\n return date.getUTCHours();\n});\n\nexport const utcHours = utcHour.range;\n", "import {timeInterval} from \"./interval.js\";\nimport {durationDay, durationMinute} from \"./duration.js\";\n\nexport const timeDay = timeInterval(\n date => date.setHours(0, 0, 0, 0),\n (date, step) => date.setDate(date.getDate() + step),\n (start, end) => (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay,\n date => date.getDate() - 1\n);\n\nexport const timeDays = timeDay.range;\n\nexport const utcDay = timeInterval((date) => {\n date.setUTCHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setUTCDate(date.getUTCDate() + step);\n}, (start, end) => {\n return (end - start) / durationDay;\n}, (date) => {\n return date.getUTCDate() - 1;\n});\n\nexport const utcDays = utcDay.range;\n\nexport const unixDay = timeInterval((date) => {\n date.setUTCHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setUTCDate(date.getUTCDate() + step);\n}, (start, end) => {\n return (end - start) / durationDay;\n}, (date) => {\n return Math.floor(date / durationDay);\n});\n\nexport const unixDays = unixDay.range;\n", "import {timeInterval} from \"./interval.js\";\nimport {durationMinute, durationWeek} from \"./duration.js\";\n\nfunction timeWeekday(i) {\n return timeInterval((date) => {\n date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7);\n date.setHours(0, 0, 0, 0);\n }, (date, step) => {\n date.setDate(date.getDate() + step * 7);\n }, (start, end) => {\n return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek;\n });\n}\n\nexport const timeSunday = timeWeekday(0);\nexport const timeMonday = timeWeekday(1);\nexport const timeTuesday = timeWeekday(2);\nexport const timeWednesday = timeWeekday(3);\nexport const timeThursday = timeWeekday(4);\nexport const timeFriday = timeWeekday(5);\nexport const timeSaturday = timeWeekday(6);\n\nexport const timeSundays = timeSunday.range;\nexport const timeMondays = timeMonday.range;\nexport const timeTuesdays = timeTuesday.range;\nexport const timeWednesdays = timeWednesday.range;\nexport const timeThursdays = timeThursday.range;\nexport const timeFridays = timeFriday.range;\nexport const timeSaturdays = timeSaturday.range;\n\nfunction utcWeekday(i) {\n return timeInterval((date) => {\n date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7);\n date.setUTCHours(0, 0, 0, 0);\n }, (date, step) => {\n date.setUTCDate(date.getUTCDate() + step * 7);\n }, (start, end) => {\n return (end - start) / durationWeek;\n });\n}\n\nexport const utcSunday = utcWeekday(0);\nexport const utcMonday = utcWeekday(1);\nexport const utcTuesday = utcWeekday(2);\nexport const utcWednesday = utcWeekday(3);\nexport const utcThursday = utcWeekday(4);\nexport const utcFriday = utcWeekday(5);\nexport const utcSaturday = utcWeekday(6);\n\nexport const utcSundays = utcSunday.range;\nexport const utcMondays = utcMonday.range;\nexport const utcTuesdays = utcTuesday.range;\nexport const utcWednesdays = utcWednesday.range;\nexport const utcThursdays = utcThursday.range;\nexport const utcFridays = utcFriday.range;\nexport const utcSaturdays = utcSaturday.range;\n", "import {timeInterval} from \"./interval.js\";\n\nexport const timeMonth = timeInterval((date) => {\n date.setDate(1);\n date.setHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setMonth(date.getMonth() + step);\n}, (start, end) => {\n return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;\n}, (date) => {\n return date.getMonth();\n});\n\nexport const timeMonths = timeMonth.range;\n\nexport const utcMonth = timeInterval((date) => {\n date.setUTCDate(1);\n date.setUTCHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setUTCMonth(date.getUTCMonth() + step);\n}, (start, end) => {\n return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;\n}, (date) => {\n return date.getUTCMonth();\n});\n\nexport const utcMonths = utcMonth.range;\n", "import {timeInterval} from \"./interval.js\";\n\nexport const timeYear = timeInterval((date) => {\n date.setMonth(0, 1);\n date.setHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setFullYear(date.getFullYear() + step);\n}, (start, end) => {\n return end.getFullYear() - start.getFullYear();\n}, (date) => {\n return date.getFullYear();\n});\n\n// An optimized implementation for this simple case.\ntimeYear.every = (k) => {\n return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date) => {\n date.setFullYear(Math.floor(date.getFullYear() / k) * k);\n date.setMonth(0, 1);\n date.setHours(0, 0, 0, 0);\n }, (date, step) => {\n date.setFullYear(date.getFullYear() + step * k);\n });\n};\n\nexport const timeYears = timeYear.range;\n\nexport const utcYear = timeInterval((date) => {\n date.setUTCMonth(0, 1);\n date.setUTCHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setUTCFullYear(date.getUTCFullYear() + step);\n}, (start, end) => {\n return end.getUTCFullYear() - start.getUTCFullYear();\n}, (date) => {\n return date.getUTCFullYear();\n});\n\n// An optimized implementation for this simple case.\nutcYear.every = (k) => {\n return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date) => {\n date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k);\n date.setUTCMonth(0, 1);\n date.setUTCHours(0, 0, 0, 0);\n }, (date, step) => {\n date.setUTCFullYear(date.getUTCFullYear() + step * k);\n });\n};\n\nexport const utcYears = utcYear.range;\n", "import {bisector, tickStep} from \"d3-array\";\nimport {durationDay, durationHour, durationMinute, durationMonth, durationSecond, durationWeek, durationYear} from \"./duration.js\";\nimport {millisecond} from \"./millisecond.js\";\nimport {second} from \"./second.js\";\nimport {timeMinute, utcMinute} from \"./minute.js\";\nimport {timeHour, utcHour} from \"./hour.js\";\nimport {timeDay, unixDay} from \"./day.js\";\nimport {timeSunday, utcSunday} from \"./week.js\";\nimport {timeMonth, utcMonth} from \"./month.js\";\nimport {timeYear, utcYear} from \"./year.js\";\n\nfunction ticker(year, month, week, day, hour, minute) {\n\n const tickIntervals = [\n [second, 1, durationSecond],\n [second, 5, 5 * durationSecond],\n [second, 15, 15 * durationSecond],\n [second, 30, 30 * durationSecond],\n [minute, 1, durationMinute],\n [minute, 5, 5 * durationMinute],\n [minute, 15, 15 * durationMinute],\n [minute, 30, 30 * durationMinute],\n [ hour, 1, durationHour ],\n [ hour, 3, 3 * durationHour ],\n [ hour, 6, 6 * durationHour ],\n [ hour, 12, 12 * durationHour ],\n [ day, 1, durationDay ],\n [ day, 2, 2 * durationDay ],\n [ week, 1, durationWeek ],\n [ month, 1, durationMonth ],\n [ month, 3, 3 * durationMonth ],\n [ year, 1, durationYear ]\n ];\n\n function ticks(start, stop, count) {\n const reverse = stop < start;\n if (reverse) [start, stop] = [stop, start];\n const interval = count && typeof count.range === \"function\" ? count : tickInterval(start, stop, count);\n const ticks = interval ? interval.range(start, +stop + 1) : []; // inclusive stop\n return reverse ? ticks.reverse() : ticks;\n }\n\n function tickInterval(start, stop, count) {\n const target = Math.abs(stop - start) / count;\n const i = bisector(([,, step]) => step).right(tickIntervals, target);\n if (i === tickIntervals.length) return year.every(tickStep(start / durationYear, stop / durationYear, count));\n if (i === 0) return millisecond.every(Math.max(tickStep(start, stop, count), 1));\n const [t, step] = tickIntervals[target / tickIntervals[i - 1][2] < tickIntervals[i][2] / target ? i - 1 : i];\n return t.every(step);\n }\n\n return [ticks, tickInterval];\n}\n\nconst [utcTicks, utcTickInterval] = ticker(utcYear, utcMonth, utcSunday, unixDay, utcHour, utcMinute);\nconst [timeTicks, timeTickInterval] = ticker(timeYear, timeMonth, timeSunday, timeDay, timeHour, timeMinute);\n\nexport {utcTicks, utcTickInterval, timeTicks, timeTickInterval};\n", "import {\n timeDay,\n timeSunday,\n timeMonday,\n timeThursday,\n timeYear,\n utcDay,\n utcSunday,\n utcMonday,\n utcThursday,\n utcYear\n} from \"d3-time\";\n\nfunction localDate(d) {\n if (0 <= d.y && d.y < 100) {\n var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);\n date.setFullYear(d.y);\n return date;\n }\n return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);\n}\n\nfunction utcDate(d) {\n if (0 <= d.y && d.y < 100) {\n var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));\n date.setUTCFullYear(d.y);\n return date;\n }\n return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));\n}\n\nfunction newDate(y, m, d) {\n return {y: y, m: m, d: d, H: 0, M: 0, S: 0, L: 0};\n}\n\nexport default function formatLocale(locale) {\n var locale_dateTime = locale.dateTime,\n locale_date = locale.date,\n locale_time = locale.time,\n locale_periods = locale.periods,\n locale_weekdays = locale.days,\n locale_shortWeekdays = locale.shortDays,\n locale_months = locale.months,\n locale_shortMonths = locale.shortMonths;\n\n var periodRe = formatRe(locale_periods),\n periodLookup = formatLookup(locale_periods),\n weekdayRe = formatRe(locale_weekdays),\n weekdayLookup = formatLookup(locale_weekdays),\n shortWeekdayRe = formatRe(locale_shortWeekdays),\n shortWeekdayLookup = formatLookup(locale_shortWeekdays),\n monthRe = formatRe(locale_months),\n monthLookup = formatLookup(locale_months),\n shortMonthRe = formatRe(locale_shortMonths),\n shortMonthLookup = formatLookup(locale_shortMonths);\n\n var formats = {\n \"a\": formatShortWeekday,\n \"A\": formatWeekday,\n \"b\": formatShortMonth,\n \"B\": formatMonth,\n \"c\": null,\n \"d\": formatDayOfMonth,\n \"e\": formatDayOfMonth,\n \"f\": formatMicroseconds,\n \"g\": formatYearISO,\n \"G\": formatFullYearISO,\n \"H\": formatHour24,\n \"I\": formatHour12,\n \"j\": formatDayOfYear,\n \"L\": formatMilliseconds,\n \"m\": formatMonthNumber,\n \"M\": formatMinutes,\n \"p\": formatPeriod,\n \"q\": formatQuarter,\n \"Q\": formatUnixTimestamp,\n \"s\": formatUnixTimestampSeconds,\n \"S\": formatSeconds,\n \"u\": formatWeekdayNumberMonday,\n \"U\": formatWeekNumberSunday,\n \"V\": formatWeekNumberISO,\n \"w\": formatWeekdayNumberSunday,\n \"W\": formatWeekNumberMonday,\n \"x\": null,\n \"X\": null,\n \"y\": formatYear,\n \"Y\": formatFullYear,\n \"Z\": formatZone,\n \"%\": formatLiteralPercent\n };\n\n var utcFormats = {\n \"a\": formatUTCShortWeekday,\n \"A\": formatUTCWeekday,\n \"b\": formatUTCShortMonth,\n \"B\": formatUTCMonth,\n \"c\": null,\n \"d\": formatUTCDayOfMonth,\n \"e\": formatUTCDayOfMonth,\n \"f\": formatUTCMicroseconds,\n \"g\": formatUTCYearISO,\n \"G\": formatUTCFullYearISO,\n \"H\": formatUTCHour24,\n \"I\": formatUTCHour12,\n \"j\": formatUTCDayOfYear,\n \"L\": formatUTCMilliseconds,\n \"m\": formatUTCMonthNumber,\n \"M\": formatUTCMinutes,\n \"p\": formatUTCPeriod,\n \"q\": formatUTCQuarter,\n \"Q\": formatUnixTimestamp,\n \"s\": formatUnixTimestampSeconds,\n \"S\": formatUTCSeconds,\n \"u\": formatUTCWeekdayNumberMonday,\n \"U\": formatUTCWeekNumberSunday,\n \"V\": formatUTCWeekNumberISO,\n \"w\": formatUTCWeekdayNumberSunday,\n \"W\": formatUTCWeekNumberMonday,\n \"x\": null,\n \"X\": null,\n \"y\": formatUTCYear,\n \"Y\": formatUTCFullYear,\n \"Z\": formatUTCZone,\n \"%\": formatLiteralPercent\n };\n\n var parses = {\n \"a\": parseShortWeekday,\n \"A\": parseWeekday,\n \"b\": parseShortMonth,\n \"B\": parseMonth,\n \"c\": parseLocaleDateTime,\n \"d\": parseDayOfMonth,\n \"e\": parseDayOfMonth,\n \"f\": parseMicroseconds,\n \"g\": parseYear,\n \"G\": parseFullYear,\n \"H\": parseHour24,\n \"I\": parseHour24,\n \"j\": parseDayOfYear,\n \"L\": parseMilliseconds,\n \"m\": parseMonthNumber,\n \"M\": parseMinutes,\n \"p\": parsePeriod,\n \"q\": parseQuarter,\n \"Q\": parseUnixTimestamp,\n \"s\": parseUnixTimestampSeconds,\n \"S\": parseSeconds,\n \"u\": parseWeekdayNumberMonday,\n \"U\": parseWeekNumberSunday,\n \"V\": parseWeekNumberISO,\n \"w\": parseWeekdayNumberSunday,\n \"W\": parseWeekNumberMonday,\n \"x\": parseLocaleDate,\n \"X\": parseLocaleTime,\n \"y\": parseYear,\n \"Y\": parseFullYear,\n \"Z\": parseZone,\n \"%\": parseLiteralPercent\n };\n\n // These recursive directive definitions must be deferred.\n formats.x = newFormat(locale_date, formats);\n formats.X = newFormat(locale_time, formats);\n formats.c = newFormat(locale_dateTime, formats);\n utcFormats.x = newFormat(locale_date, utcFormats);\n utcFormats.X = newFormat(locale_time, utcFormats);\n utcFormats.c = newFormat(locale_dateTime, utcFormats);\n\n function newFormat(specifier, formats) {\n return function(date) {\n var string = [],\n i = -1,\n j = 0,\n n = specifier.length,\n c,\n pad,\n format;\n\n if (!(date instanceof Date)) date = new Date(+date);\n\n while (++i < n) {\n if (specifier.charCodeAt(i) === 37) {\n string.push(specifier.slice(j, i));\n if ((pad = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i);\n else pad = c === \"e\" ? \" \" : \"0\";\n if (format = formats[c]) c = format(date, pad);\n string.push(c);\n j = i + 1;\n }\n }\n\n string.push(specifier.slice(j, i));\n return string.join(\"\");\n };\n }\n\n function newParse(specifier, Z) {\n return function(string) {\n var d = newDate(1900, undefined, 1),\n i = parseSpecifier(d, specifier, string += \"\", 0),\n week, day;\n if (i != string.length) return null;\n\n // If a UNIX timestamp is specified, return it.\n if (\"Q\" in d) return new Date(d.Q);\n if (\"s\" in d) return new Date(d.s * 1000 + (\"L\" in d ? d.L : 0));\n\n // If this is utcParse, never use the local timezone.\n if (Z && !(\"Z\" in d)) d.Z = 0;\n\n // The am-pm flag is 0 for AM, and 1 for PM.\n if (\"p\" in d) d.H = d.H % 12 + d.p * 12;\n\n // If the month was not specified, inherit from the quarter.\n if (d.m === undefined) d.m = \"q\" in d ? d.q : 0;\n\n // Convert day-of-week and week-of-year to day-of-year.\n if (\"V\" in d) {\n if (d.V < 1 || d.V > 53) return null;\n if (!(\"w\" in d)) d.w = 1;\n if (\"Z\" in d) {\n week = utcDate(newDate(d.y, 0, 1)), day = week.getUTCDay();\n week = day > 4 || day === 0 ? utcMonday.ceil(week) : utcMonday(week);\n week = utcDay.offset(week, (d.V - 1) * 7);\n d.y = week.getUTCFullYear();\n d.m = week.getUTCMonth();\n d.d = week.getUTCDate() + (d.w + 6) % 7;\n } else {\n week = localDate(newDate(d.y, 0, 1)), day = week.getDay();\n week = day > 4 || day === 0 ? timeMonday.ceil(week) : timeMonday(week);\n week = timeDay.offset(week, (d.V - 1) * 7);\n d.y = week.getFullYear();\n d.m = week.getMonth();\n d.d = week.getDate() + (d.w + 6) % 7;\n }\n } else if (\"W\" in d || \"U\" in d) {\n if (!(\"w\" in d)) d.w = \"u\" in d ? d.u % 7 : \"W\" in d ? 1 : 0;\n day = \"Z\" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay();\n d.m = 0;\n d.d = \"W\" in d ? (d.w + 6) % 7 + d.W * 7 - (day + 5) % 7 : d.w + d.U * 7 - (day + 6) % 7;\n }\n\n // If a time zone is specified, all fields are interpreted as UTC and then\n // offset according to the specified time zone.\n if (\"Z\" in d) {\n d.H += d.Z / 100 | 0;\n d.M += d.Z % 100;\n return utcDate(d);\n }\n\n // Otherwise, all fields are in local time.\n return localDate(d);\n };\n }\n\n function parseSpecifier(d, specifier, string, j) {\n var i = 0,\n n = specifier.length,\n m = string.length,\n c,\n parse;\n\n while (i < n) {\n if (j >= m) return -1;\n c = specifier.charCodeAt(i++);\n if (c === 37) {\n c = specifier.charAt(i++);\n parse = parses[c in pads ? specifier.charAt(i++) : c];\n if (!parse || ((j = parse(d, string, j)) < 0)) return -1;\n } else if (c != string.charCodeAt(j++)) {\n return -1;\n }\n }\n\n return j;\n }\n\n function parsePeriod(d, string, i) {\n var n = periodRe.exec(string.slice(i));\n return n ? (d.p = periodLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseShortWeekday(d, string, i) {\n var n = shortWeekdayRe.exec(string.slice(i));\n return n ? (d.w = shortWeekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseWeekday(d, string, i) {\n var n = weekdayRe.exec(string.slice(i));\n return n ? (d.w = weekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseShortMonth(d, string, i) {\n var n = shortMonthRe.exec(string.slice(i));\n return n ? (d.m = shortMonthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseMonth(d, string, i) {\n var n = monthRe.exec(string.slice(i));\n return n ? (d.m = monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseLocaleDateTime(d, string, i) {\n return parseSpecifier(d, locale_dateTime, string, i);\n }\n\n function parseLocaleDate(d, string, i) {\n return parseSpecifier(d, locale_date, string, i);\n }\n\n function parseLocaleTime(d, string, i) {\n return parseSpecifier(d, locale_time, string, i);\n }\n\n function formatShortWeekday(d) {\n return locale_shortWeekdays[d.getDay()];\n }\n\n function formatWeekday(d) {\n return locale_weekdays[d.getDay()];\n }\n\n function formatShortMonth(d) {\n return locale_shortMonths[d.getMonth()];\n }\n\n function formatMonth(d) {\n return locale_months[d.getMonth()];\n }\n\n function formatPeriod(d) {\n return locale_periods[+(d.getHours() >= 12)];\n }\n\n function formatQuarter(d) {\n return 1 + ~~(d.getMonth() / 3);\n }\n\n function formatUTCShortWeekday(d) {\n return locale_shortWeekdays[d.getUTCDay()];\n }\n\n function formatUTCWeekday(d) {\n return locale_weekdays[d.getUTCDay()];\n }\n\n function formatUTCShortMonth(d) {\n return locale_shortMonths[d.getUTCMonth()];\n }\n\n function formatUTCMonth(d) {\n return locale_months[d.getUTCMonth()];\n }\n\n function formatUTCPeriod(d) {\n return locale_periods[+(d.getUTCHours() >= 12)];\n }\n\n function formatUTCQuarter(d) {\n return 1 + ~~(d.getUTCMonth() / 3);\n }\n\n return {\n format: function(specifier) {\n var f = newFormat(specifier += \"\", formats);\n f.toString = function() { return specifier; };\n return f;\n },\n parse: function(specifier) {\n var p = newParse(specifier += \"\", false);\n p.toString = function() { return specifier; };\n return p;\n },\n utcFormat: function(specifier) {\n var f = newFormat(specifier += \"\", utcFormats);\n f.toString = function() { return specifier; };\n return f;\n },\n utcParse: function(specifier) {\n var p = newParse(specifier += \"\", true);\n p.toString = function() { return specifier; };\n return p;\n }\n };\n}\n\nvar pads = {\"-\": \"\", \"_\": \" \", \"0\": \"0\"},\n numberRe = /^\\s*\\d+/, // note: ignores next directive\n percentRe = /^%/,\n requoteRe = /[\\\\^$*+?|[\\]().{}]/g;\n\nfunction pad(value, fill, width) {\n var sign = value < 0 ? \"-\" : \"\",\n string = (sign ? -value : value) + \"\",\n length = string.length;\n return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);\n}\n\nfunction requote(s) {\n return s.replace(requoteRe, \"\\\\$&\");\n}\n\nfunction formatRe(names) {\n return new RegExp(\"^(?:\" + names.map(requote).join(\"|\") + \")\", \"i\");\n}\n\nfunction formatLookup(names) {\n return new Map(names.map((name, i) => [name.toLowerCase(), i]));\n}\n\nfunction parseWeekdayNumberSunday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.w = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekdayNumberMonday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.u = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberSunday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.U = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberISO(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.V = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberMonday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.W = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseFullYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 4));\n return n ? (d.y = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1;\n}\n\nfunction parseZone(d, string, i) {\n var n = /^(Z)|([+-]\\d\\d)(?::?(\\d\\d))?/.exec(string.slice(i, i + 6));\n return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || \"00\")), i + n[0].length) : -1;\n}\n\nfunction parseQuarter(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1;\n}\n\nfunction parseMonthNumber(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.m = n[0] - 1, i + n[0].length) : -1;\n}\n\nfunction parseDayOfMonth(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.d = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseDayOfYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 3));\n return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseHour24(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.H = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMinutes(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.M = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseSeconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.S = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMilliseconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 3));\n return n ? (d.L = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMicroseconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 6));\n return n ? (d.L = Math.floor(n[0] / 1000), i + n[0].length) : -1;\n}\n\nfunction parseLiteralPercent(d, string, i) {\n var n = percentRe.exec(string.slice(i, i + 1));\n return n ? i + n[0].length : -1;\n}\n\nfunction parseUnixTimestamp(d, string, i) {\n var n = numberRe.exec(string.slice(i));\n return n ? (d.Q = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseUnixTimestampSeconds(d, string, i) {\n var n = numberRe.exec(string.slice(i));\n return n ? (d.s = +n[0], i + n[0].length) : -1;\n}\n\nfunction formatDayOfMonth(d, p) {\n return pad(d.getDate(), p, 2);\n}\n\nfunction formatHour24(d, p) {\n return pad(d.getHours(), p, 2);\n}\n\nfunction formatHour12(d, p) {\n return pad(d.getHours() % 12 || 12, p, 2);\n}\n\nfunction formatDayOfYear(d, p) {\n return pad(1 + timeDay.count(timeYear(d), d), p, 3);\n}\n\nfunction formatMilliseconds(d, p) {\n return pad(d.getMilliseconds(), p, 3);\n}\n\nfunction formatMicroseconds(d, p) {\n return formatMilliseconds(d, p) + \"000\";\n}\n\nfunction formatMonthNumber(d, p) {\n return pad(d.getMonth() + 1, p, 2);\n}\n\nfunction formatMinutes(d, p) {\n return pad(d.getMinutes(), p, 2);\n}\n\nfunction formatSeconds(d, p) {\n return pad(d.getSeconds(), p, 2);\n}\n\nfunction formatWeekdayNumberMonday(d) {\n var day = d.getDay();\n return day === 0 ? 7 : day;\n}\n\nfunction formatWeekNumberSunday(d, p) {\n return pad(timeSunday.count(timeYear(d) - 1, d), p, 2);\n}\n\nfunction dISO(d) {\n var day = d.getDay();\n return (day >= 4 || day === 0) ? timeThursday(d) : timeThursday.ceil(d);\n}\n\nfunction formatWeekNumberISO(d, p) {\n d = dISO(d);\n return pad(timeThursday.count(timeYear(d), d) + (timeYear(d).getDay() === 4), p, 2);\n}\n\nfunction formatWeekdayNumberSunday(d) {\n return d.getDay();\n}\n\nfunction formatWeekNumberMonday(d, p) {\n return pad(timeMonday.count(timeYear(d) - 1, d), p, 2);\n}\n\nfunction formatYear(d, p) {\n return pad(d.getFullYear() % 100, p, 2);\n}\n\nfunction formatYearISO(d, p) {\n d = dISO(d);\n return pad(d.getFullYear() % 100, p, 2);\n}\n\nfunction formatFullYear(d, p) {\n return pad(d.getFullYear() % 10000, p, 4);\n}\n\nfunction formatFullYearISO(d, p) {\n var day = d.getDay();\n d = (day >= 4 || day === 0) ? timeThursday(d) : timeThursday.ceil(d);\n return pad(d.getFullYear() % 10000, p, 4);\n}\n\nfunction formatZone(d) {\n var z = d.getTimezoneOffset();\n return (z > 0 ? \"-\" : (z *= -1, \"+\"))\n + pad(z / 60 | 0, \"0\", 2)\n + pad(z % 60, \"0\", 2);\n}\n\nfunction formatUTCDayOfMonth(d, p) {\n return pad(d.getUTCDate(), p, 2);\n}\n\nfunction formatUTCHour24(d, p) {\n return pad(d.getUTCHours(), p, 2);\n}\n\nfunction formatUTCHour12(d, p) {\n return pad(d.getUTCHours() % 12 || 12, p, 2);\n}\n\nfunction formatUTCDayOfYear(d, p) {\n return pad(1 + utcDay.count(utcYear(d), d), p, 3);\n}\n\nfunction formatUTCMilliseconds(d, p) {\n return pad(d.getUTCMilliseconds(), p, 3);\n}\n\nfunction formatUTCMicroseconds(d, p) {\n return formatUTCMilliseconds(d, p) + \"000\";\n}\n\nfunction formatUTCMonthNumber(d, p) {\n return pad(d.getUTCMonth() + 1, p, 2);\n}\n\nfunction formatUTCMinutes(d, p) {\n return pad(d.getUTCMinutes(), p, 2);\n}\n\nfunction formatUTCSeconds(d, p) {\n return pad(d.getUTCSeconds(), p, 2);\n}\n\nfunction formatUTCWeekdayNumberMonday(d) {\n var dow = d.getUTCDay();\n return dow === 0 ? 7 : dow;\n}\n\nfunction formatUTCWeekNumberSunday(d, p) {\n return pad(utcSunday.count(utcYear(d) - 1, d), p, 2);\n}\n\nfunction UTCdISO(d) {\n var day = d.getUTCDay();\n return (day >= 4 || day === 0) ? utcThursday(d) : utcThursday.ceil(d);\n}\n\nfunction formatUTCWeekNumberISO(d, p) {\n d = UTCdISO(d);\n return pad(utcThursday.count(utcYear(d), d) + (utcYear(d).getUTCDay() === 4), p, 2);\n}\n\nfunction formatUTCWeekdayNumberSunday(d) {\n return d.getUTCDay();\n}\n\nfunction formatUTCWeekNumberMonday(d, p) {\n return pad(utcMonday.count(utcYear(d) - 1, d), p, 2);\n}\n\nfunction formatUTCYear(d, p) {\n return pad(d.getUTCFullYear() % 100, p, 2);\n}\n\nfunction formatUTCYearISO(d, p) {\n d = UTCdISO(d);\n return pad(d.getUTCFullYear() % 100, p, 2);\n}\n\nfunction formatUTCFullYear(d, p) {\n return pad(d.getUTCFullYear() % 10000, p, 4);\n}\n\nfunction formatUTCFullYearISO(d, p) {\n var day = d.getUTCDay();\n d = (day >= 4 || day === 0) ? utcThursday(d) : utcThursday.ceil(d);\n return pad(d.getUTCFullYear() % 10000, p, 4);\n}\n\nfunction formatUTCZone() {\n return \"+0000\";\n}\n\nfunction formatLiteralPercent() {\n return \"%\";\n}\n\nfunction formatUnixTimestamp(d) {\n return +d;\n}\n\nfunction formatUnixTimestampSeconds(d) {\n return Math.floor(+d / 1000);\n}\n", "import formatLocale from \"./locale.js\";\n\nvar locale;\nexport var timeFormat;\nexport var timeParse;\nexport var utcFormat;\nexport var utcParse;\n\ndefaultLocale({\n dateTime: \"%x, %X\",\n date: \"%-m/%-d/%Y\",\n time: \"%-I:%M:%S %p\",\n periods: [\"AM\", \"PM\"],\n days: [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"],\n shortDays: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"],\n months: [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"],\n shortMonths: [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\n});\n\nexport default function defaultLocale(definition) {\n locale = formatLocale(definition);\n timeFormat = locale.format;\n timeParse = locale.parse;\n utcFormat = locale.utcFormat;\n utcParse = locale.utcParse;\n return locale;\n}\n", "import {timeYear, timeMonth, timeWeek, timeDay, timeHour, timeMinute, timeSecond, timeTicks, timeTickInterval} from \"d3-time\";\nimport {timeFormat} from \"d3-time-format\";\nimport continuous, {copy} from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\nimport nice from \"./nice.js\";\n\nfunction date(t) {\n return new Date(t);\n}\n\nfunction number(t) {\n return t instanceof Date ? +t : +new Date(+t);\n}\n\nexport function calendar(ticks, tickInterval, year, month, week, day, hour, minute, second, format) {\n var scale = continuous(),\n invert = scale.invert,\n domain = scale.domain;\n\n var formatMillisecond = format(\".%L\"),\n formatSecond = format(\":%S\"),\n formatMinute = format(\"%I:%M\"),\n formatHour = format(\"%I %p\"),\n formatDay = format(\"%a %d\"),\n formatWeek = format(\"%b %d\"),\n formatMonth = format(\"%B\"),\n formatYear = format(\"%Y\");\n\n function tickFormat(date) {\n return (second(date) < date ? formatMillisecond\n : minute(date) < date ? formatSecond\n : hour(date) < date ? formatMinute\n : day(date) < date ? formatHour\n : month(date) < date ? (week(date) < date ? formatDay : formatWeek)\n : year(date) < date ? formatMonth\n : formatYear)(date);\n }\n\n scale.invert = function(y) {\n return new Date(invert(y));\n };\n\n scale.domain = function(_) {\n return arguments.length ? domain(Array.from(_, number)) : domain().map(date);\n };\n\n scale.ticks = function(interval) {\n var d = domain();\n return ticks(d[0], d[d.length - 1], interval == null ? 10 : interval);\n };\n\n scale.tickFormat = function(count, specifier) {\n return specifier == null ? tickFormat : format(specifier);\n };\n\n scale.nice = function(interval) {\n var d = domain();\n if (!interval || typeof interval.range !== \"function\") interval = tickInterval(d[0], d[d.length - 1], interval == null ? 10 : interval);\n return interval ? domain(nice(d, interval)) : scale;\n };\n\n scale.copy = function() {\n return copy(scale, calendar(ticks, tickInterval, year, month, week, day, hour, minute, second, format));\n };\n\n return scale;\n}\n\nexport default function time() {\n return initRange.apply(calendar(timeTicks, timeTickInterval, timeYear, timeMonth, timeWeek, timeDay, timeHour, timeMinute, timeSecond, timeFormat).domain([new Date(2000, 0, 1), new Date(2000, 0, 2)]), arguments);\n}\n", "import {utcYear, utcMonth, utcWeek, utcDay, utcHour, utcMinute, utcSecond, utcTicks, utcTickInterval} from \"d3-time\";\nimport {utcFormat} from \"d3-time-format\";\nimport {calendar} from \"./time.js\";\nimport {initRange} from \"./init.js\";\n\nexport default function utcTime() {\n return initRange.apply(calendar(utcTicks, utcTickInterval, utcYear, utcMonth, utcWeek, utcDay, utcHour, utcMinute, utcSecond, utcFormat).domain([Date.UTC(2000, 0, 1), Date.UTC(2000, 0, 2)]), arguments);\n}\n", "import {interpolate, interpolateRound} from \"d3-interpolate\";\nimport {identity} from \"./continuous.js\";\nimport {initInterpolator} from \"./init.js\";\nimport {linearish} from \"./linear.js\";\nimport {loggish} from \"./log.js\";\nimport {symlogish} from \"./symlog.js\";\nimport {powish} from \"./pow.js\";\n\nfunction transformer() {\n var x0 = 0,\n x1 = 1,\n t0,\n t1,\n k10,\n transform,\n interpolator = identity,\n clamp = false,\n unknown;\n\n function scale(x) {\n return x == null || isNaN(x = +x) ? unknown : interpolator(k10 === 0 ? 0.5 : (x = (transform(x) - t0) * k10, clamp ? Math.max(0, Math.min(1, x)) : x));\n }\n\n scale.domain = function(_) {\n return arguments.length ? ([x0, x1] = _, t0 = transform(x0 = +x0), t1 = transform(x1 = +x1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0), scale) : [x0, x1];\n };\n\n scale.clamp = function(_) {\n return arguments.length ? (clamp = !!_, scale) : clamp;\n };\n\n scale.interpolator = function(_) {\n return arguments.length ? (interpolator = _, scale) : interpolator;\n };\n\n function range(interpolate) {\n return function(_) {\n var r0, r1;\n return arguments.length ? ([r0, r1] = _, interpolator = interpolate(r0, r1), scale) : [interpolator(0), interpolator(1)];\n };\n }\n\n scale.range = range(interpolate);\n\n scale.rangeRound = range(interpolateRound);\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n return function(t) {\n transform = t, t0 = t(x0), t1 = t(x1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0);\n return scale;\n };\n}\n\nexport function copy(source, target) {\n return target\n .domain(source.domain())\n .interpolator(source.interpolator())\n .clamp(source.clamp())\n .unknown(source.unknown());\n}\n\nexport default function sequential() {\n var scale = linearish(transformer()(identity));\n\n scale.copy = function() {\n return copy(scale, sequential());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialLog() {\n var scale = loggish(transformer()).domain([1, 10]);\n\n scale.copy = function() {\n return copy(scale, sequentialLog()).base(scale.base());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialSymlog() {\n var scale = symlogish(transformer());\n\n scale.copy = function() {\n return copy(scale, sequentialSymlog()).constant(scale.constant());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialPow() {\n var scale = powish(transformer());\n\n scale.copy = function() {\n return copy(scale, sequentialPow()).exponent(scale.exponent());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialSqrt() {\n return sequentialPow.apply(null, arguments).exponent(0.5);\n}\n", "import {ascending, bisect, quantile} from \"d3-array\";\nimport {identity} from \"./continuous.js\";\nimport {initInterpolator} from \"./init.js\";\n\nexport default function sequentialQuantile() {\n var domain = [],\n interpolator = identity;\n\n function scale(x) {\n if (x != null && !isNaN(x = +x)) return interpolator((bisect(domain, x, 1) - 1) / (domain.length - 1));\n }\n\n scale.domain = function(_) {\n if (!arguments.length) return domain.slice();\n domain = [];\n for (let d of _) if (d != null && !isNaN(d = +d)) domain.push(d);\n domain.sort(ascending);\n return scale;\n };\n\n scale.interpolator = function(_) {\n return arguments.length ? (interpolator = _, scale) : interpolator;\n };\n\n scale.range = function() {\n return domain.map((d, i) => interpolator(i / (domain.length - 1)));\n };\n\n scale.quantiles = function(n) {\n return Array.from({length: n + 1}, (_, i) => quantile(domain, i / n));\n };\n\n scale.copy = function() {\n return sequentialQuantile(interpolator).domain(domain);\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n", "import {interpolate, interpolateRound, piecewise} from \"d3-interpolate\";\nimport {identity} from \"./continuous.js\";\nimport {initInterpolator} from \"./init.js\";\nimport {linearish} from \"./linear.js\";\nimport {loggish} from \"./log.js\";\nimport {copy} from \"./sequential.js\";\nimport {symlogish} from \"./symlog.js\";\nimport {powish} from \"./pow.js\";\n\nfunction transformer() {\n var x0 = 0,\n x1 = 0.5,\n x2 = 1,\n s = 1,\n t0,\n t1,\n t2,\n k10,\n k21,\n interpolator = identity,\n transform,\n clamp = false,\n unknown;\n\n function scale(x) {\n return isNaN(x = +x) ? unknown : (x = 0.5 + ((x = +transform(x)) - t1) * (s * x < s * t1 ? k10 : k21), interpolator(clamp ? Math.max(0, Math.min(1, x)) : x));\n }\n\n scale.domain = function(_) {\n return arguments.length ? ([x0, x1, x2] = _, t0 = transform(x0 = +x0), t1 = transform(x1 = +x1), t2 = transform(x2 = +x2), k10 = t0 === t1 ? 0 : 0.5 / (t1 - t0), k21 = t1 === t2 ? 0 : 0.5 / (t2 - t1), s = t1 < t0 ? -1 : 1, scale) : [x0, x1, x2];\n };\n\n scale.clamp = function(_) {\n return arguments.length ? (clamp = !!_, scale) : clamp;\n };\n\n scale.interpolator = function(_) {\n return arguments.length ? (interpolator = _, scale) : interpolator;\n };\n\n function range(interpolate) {\n return function(_) {\n var r0, r1, r2;\n return arguments.length ? ([r0, r1, r2] = _, interpolator = piecewise(interpolate, [r0, r1, r2]), scale) : [interpolator(0), interpolator(0.5), interpolator(1)];\n };\n }\n\n scale.range = range(interpolate);\n\n scale.rangeRound = range(interpolateRound);\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n return function(t) {\n transform = t, t0 = t(x0), t1 = t(x1), t2 = t(x2), k10 = t0 === t1 ? 0 : 0.5 / (t1 - t0), k21 = t1 === t2 ? 0 : 0.5 / (t2 - t1), s = t1 < t0 ? -1 : 1;\n return scale;\n };\n}\n\nexport default function diverging() {\n var scale = linearish(transformer()(identity));\n\n scale.copy = function() {\n return copy(scale, diverging());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function divergingLog() {\n var scale = loggish(transformer()).domain([0.1, 1, 10]);\n\n scale.copy = function() {\n return copy(scale, divergingLog()).base(scale.base());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function divergingSymlog() {\n var scale = symlogish(transformer());\n\n scale.copy = function() {\n return copy(scale, divergingSymlog()).constant(scale.constant());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function divergingPow() {\n var scale = powish(transformer());\n\n scale.copy = function() {\n return copy(scale, divergingPow()).exponent(scale.exponent());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function divergingSqrt() {\n return divergingPow.apply(null, arguments).exponent(0.5);\n}\n", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nimport * as d3Scales from 'victory-vendor/d3-scale';\nimport { stack as shapeStack, stackOffsetExpand, stackOffsetNone, stackOffsetSilhouette, stackOffsetWiggle, stackOrderNone } from 'victory-vendor/d3-shape';\nimport max from 'lodash/max';\nimport min from 'lodash/min';\nimport isNil from 'lodash/isNil';\nimport isFunction from 'lodash/isFunction';\nimport isString from 'lodash/isString';\nimport get from 'lodash/get';\nimport flatMap from 'lodash/flatMap';\nimport isNan from 'lodash/isNaN';\nimport upperFirst from 'lodash/upperFirst';\nimport isEqual from 'lodash/isEqual';\nimport sortBy from 'lodash/sortBy';\nimport { getNiceTickValues, getTickValuesFixedDomain } from 'recharts-scale';\nimport { ErrorBar } from '../cartesian/ErrorBar';\nimport { findEntryInArray, getPercentValue, isNumber, isNumOrStr, mathSign, uniqueId } from './DataUtils';\nimport { filterProps, findAllByType, getDisplayName } from './ReactUtils';\n// TODO: Cause of circular dependency. Needs refactor.\n// import { RadiusAxisProps, AngleAxisProps } from '../polar/types';\n\nimport { getLegendProps } from './getLegendProps';\n\n// Exported for backwards compatibility\nexport { getLegendProps };\nexport function getValueByDataKey(obj, dataKey, defaultValue) {\n if (isNil(obj) || isNil(dataKey)) {\n return defaultValue;\n }\n if (isNumOrStr(dataKey)) {\n return get(obj, dataKey, defaultValue);\n }\n if (isFunction(dataKey)) {\n return dataKey(obj);\n }\n return defaultValue;\n}\n/**\n * Get domain of data by key.\n * @param {Array} data The data displayed in the chart\n * @param {String} key The unique key of a group of data\n * @param {String} type The type of axis\n * @param {Boolean} filterNil Whether or not filter nil values\n * @return {Array} Domain of data\n */\nexport function getDomainOfDataByKey(data, key, type, filterNil) {\n var flattenData = flatMap(data, function (entry) {\n return getValueByDataKey(entry, key);\n });\n if (type === 'number') {\n // @ts-expect-error parseFloat type only accepts strings\n var domain = flattenData.filter(function (entry) {\n return isNumber(entry) || parseFloat(entry);\n });\n return domain.length ? [min(domain), max(domain)] : [Infinity, -Infinity];\n }\n var validateData = filterNil ? flattenData.filter(function (entry) {\n return !isNil(entry);\n }) : flattenData;\n\n // Supports x-axis of Date type\n return validateData.map(function (entry) {\n return isNumOrStr(entry) || entry instanceof Date ? entry : '';\n });\n}\nexport var calculateActiveTickIndex = function calculateActiveTickIndex(coordinate) {\n var _ticks$length;\n var ticks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n var unsortedTicks = arguments.length > 2 ? arguments[2] : undefined;\n var axis = arguments.length > 3 ? arguments[3] : undefined;\n var index = -1;\n var len = (_ticks$length = ticks === null || ticks === void 0 ? void 0 : ticks.length) !== null && _ticks$length !== void 0 ? _ticks$length : 0;\n\n // if there are 1 or less ticks ticks then the active tick is at index 0\n if (len <= 1) {\n return 0;\n }\n if (axis && axis.axisType === 'angleAxis' && Math.abs(Math.abs(axis.range[1] - axis.range[0]) - 360) <= 1e-6) {\n var range = axis.range;\n // ticks are distributed in a circle\n for (var i = 0; i < len; i++) {\n var before = i > 0 ? unsortedTicks[i - 1].coordinate : unsortedTicks[len - 1].coordinate;\n var cur = unsortedTicks[i].coordinate;\n var after = i >= len - 1 ? unsortedTicks[0].coordinate : unsortedTicks[i + 1].coordinate;\n var sameDirectionCoord = void 0;\n if (mathSign(cur - before) !== mathSign(after - cur)) {\n var diffInterval = [];\n if (mathSign(after - cur) === mathSign(range[1] - range[0])) {\n sameDirectionCoord = after;\n var curInRange = cur + range[1] - range[0];\n diffInterval[0] = Math.min(curInRange, (curInRange + before) / 2);\n diffInterval[1] = Math.max(curInRange, (curInRange + before) / 2);\n } else {\n sameDirectionCoord = before;\n var afterInRange = after + range[1] - range[0];\n diffInterval[0] = Math.min(cur, (afterInRange + cur) / 2);\n diffInterval[1] = Math.max(cur, (afterInRange + cur) / 2);\n }\n var sameInterval = [Math.min(cur, (sameDirectionCoord + cur) / 2), Math.max(cur, (sameDirectionCoord + cur) / 2)];\n if (coordinate > sameInterval[0] && coordinate <= sameInterval[1] || coordinate >= diffInterval[0] && coordinate <= diffInterval[1]) {\n index = unsortedTicks[i].index;\n break;\n }\n } else {\n var minValue = Math.min(before, after);\n var maxValue = Math.max(before, after);\n if (coordinate > (minValue + cur) / 2 && coordinate <= (maxValue + cur) / 2) {\n index = unsortedTicks[i].index;\n break;\n }\n }\n }\n } else {\n // ticks are distributed in a single direction\n for (var _i = 0; _i < len; _i++) {\n if (_i === 0 && coordinate <= (ticks[_i].coordinate + ticks[_i + 1].coordinate) / 2 || _i > 0 && _i < len - 1 && coordinate > (ticks[_i].coordinate + ticks[_i - 1].coordinate) / 2 && coordinate <= (ticks[_i].coordinate + ticks[_i + 1].coordinate) / 2 || _i === len - 1 && coordinate > (ticks[_i].coordinate + ticks[_i - 1].coordinate) / 2) {\n index = ticks[_i].index;\n break;\n }\n }\n }\n return index;\n};\n\n/**\n * Get the main color of each graphic item\n * @param {ReactElement} item A graphic item\n * @return {String} Color\n */\nexport var getMainColorOfGraphicItem = function getMainColorOfGraphicItem(item) {\n var _item$type;\n var _ref = item,\n displayName = _ref.type.displayName; // TODO: check if displayName is valid.\n var defaultedProps = (_item$type = item.type) !== null && _item$type !== void 0 && _item$type.defaultProps ? _objectSpread(_objectSpread({}, item.type.defaultProps), item.props) : item.props;\n var stroke = defaultedProps.stroke,\n fill = defaultedProps.fill;\n var result;\n switch (displayName) {\n case 'Line':\n result = stroke;\n break;\n case 'Area':\n case 'Radar':\n result = stroke && stroke !== 'none' ? stroke : fill;\n break;\n default:\n result = fill;\n break;\n }\n return result;\n};\n/**\n * Calculate the size of all groups for stacked bar graph\n * @param {Object} stackGroups The items grouped by axisId and stackId\n * @return {Object} The size of all groups\n */\nexport var getBarSizeList = function getBarSizeList(_ref2) {\n var globalSize = _ref2.barSize,\n totalSize = _ref2.totalSize,\n _ref2$stackGroups = _ref2.stackGroups,\n stackGroups = _ref2$stackGroups === void 0 ? {} : _ref2$stackGroups;\n if (!stackGroups) {\n return {};\n }\n var result = {};\n var numericAxisIds = Object.keys(stackGroups);\n for (var i = 0, len = numericAxisIds.length; i < len; i++) {\n var sgs = stackGroups[numericAxisIds[i]].stackGroups;\n var stackIds = Object.keys(sgs);\n for (var j = 0, sLen = stackIds.length; j < sLen; j++) {\n var _sgs$stackIds$j = sgs[stackIds[j]],\n items = _sgs$stackIds$j.items,\n cateAxisId = _sgs$stackIds$j.cateAxisId;\n var barItems = items.filter(function (item) {\n return getDisplayName(item.type).indexOf('Bar') >= 0;\n });\n if (barItems && barItems.length) {\n var barItemDefaultProps = barItems[0].type.defaultProps;\n var barItemProps = barItemDefaultProps !== undefined ? _objectSpread(_objectSpread({}, barItemDefaultProps), barItems[0].props) : barItems[0].props;\n var selfSize = barItemProps.barSize;\n var cateId = barItemProps[cateAxisId];\n if (!result[cateId]) {\n result[cateId] = [];\n }\n var barSize = isNil(selfSize) ? globalSize : selfSize;\n result[cateId].push({\n item: barItems[0],\n stackList: barItems.slice(1),\n barSize: isNil(barSize) ? undefined : getPercentValue(barSize, totalSize, 0)\n });\n }\n }\n }\n return result;\n};\n/**\n * Calculate the size of each bar and offset between start of band and the bar\n *\n * @param {number} bandSize is the size of area where bars can render\n * @param {number | string} barGap is the gap size, as a percentage of `bandSize`.\n * Can be defined as number or percent string\n * @param {number | string} barCategoryGap is the gap size, as a percentage of `bandSize`.\n * Can be defined as number or percent string\n * @param {Array} sizeList Sizes of all groups\n * @param {number} maxBarSize The maximum size of each bar\n * @return {Array} The size and offset of each bar\n */\nexport var getBarPosition = function getBarPosition(_ref3) {\n var barGap = _ref3.barGap,\n barCategoryGap = _ref3.barCategoryGap,\n bandSize = _ref3.bandSize,\n _ref3$sizeList = _ref3.sizeList,\n sizeList = _ref3$sizeList === void 0 ? [] : _ref3$sizeList,\n maxBarSize = _ref3.maxBarSize;\n var len = sizeList.length;\n if (len < 1) return null;\n var realBarGap = getPercentValue(barGap, bandSize, 0, true);\n var result;\n var initialValue = [];\n\n // whether or not is barSize setted by user\n if (sizeList[0].barSize === +sizeList[0].barSize) {\n var useFull = false;\n var fullBarSize = bandSize / len;\n // @ts-expect-error the type check above does not check for type number explicitly\n var sum = sizeList.reduce(function (res, entry) {\n return res + entry.barSize || 0;\n }, 0);\n sum += (len - 1) * realBarGap;\n if (sum >= bandSize) {\n sum -= (len - 1) * realBarGap;\n realBarGap = 0;\n }\n if (sum >= bandSize && fullBarSize > 0) {\n useFull = true;\n fullBarSize *= 0.9;\n sum = len * fullBarSize;\n }\n var offset = (bandSize - sum) / 2 >> 0;\n var prev = {\n offset: offset - realBarGap,\n size: 0\n };\n result = sizeList.reduce(function (res, entry) {\n var newPosition = {\n item: entry.item,\n position: {\n offset: prev.offset + prev.size + realBarGap,\n // @ts-expect-error the type check above does not check for type number explicitly\n size: useFull ? fullBarSize : entry.barSize\n }\n };\n var newRes = [].concat(_toConsumableArray(res), [newPosition]);\n prev = newRes[newRes.length - 1].position;\n if (entry.stackList && entry.stackList.length) {\n entry.stackList.forEach(function (item) {\n newRes.push({\n item: item,\n position: prev\n });\n });\n }\n return newRes;\n }, initialValue);\n } else {\n var _offset = getPercentValue(barCategoryGap, bandSize, 0, true);\n if (bandSize - 2 * _offset - (len - 1) * realBarGap <= 0) {\n realBarGap = 0;\n }\n var originalSize = (bandSize - 2 * _offset - (len - 1) * realBarGap) / len;\n if (originalSize > 1) {\n originalSize >>= 0;\n }\n var size = maxBarSize === +maxBarSize ? Math.min(originalSize, maxBarSize) : originalSize;\n result = sizeList.reduce(function (res, entry, i) {\n var newRes = [].concat(_toConsumableArray(res), [{\n item: entry.item,\n position: {\n offset: _offset + (originalSize + realBarGap) * i + (originalSize - size) / 2,\n size: size\n }\n }]);\n if (entry.stackList && entry.stackList.length) {\n entry.stackList.forEach(function (item) {\n newRes.push({\n item: item,\n position: newRes[newRes.length - 1].position\n });\n });\n }\n return newRes;\n }, initialValue);\n }\n return result;\n};\nexport var appendOffsetOfLegend = function appendOffsetOfLegend(offset, _unused, props, legendBox) {\n var children = props.children,\n width = props.width,\n margin = props.margin;\n var legendWidth = width - (margin.left || 0) - (margin.right || 0);\n var legendProps = getLegendProps({\n children: children,\n legendWidth: legendWidth\n });\n if (legendProps) {\n var _ref4 = legendBox || {},\n boxWidth = _ref4.width,\n boxHeight = _ref4.height;\n var align = legendProps.align,\n verticalAlign = legendProps.verticalAlign,\n layout = legendProps.layout;\n if ((layout === 'vertical' || layout === 'horizontal' && verticalAlign === 'middle') && align !== 'center' && isNumber(offset[align])) {\n return _objectSpread(_objectSpread({}, offset), {}, _defineProperty({}, align, offset[align] + (boxWidth || 0)));\n }\n if ((layout === 'horizontal' || layout === 'vertical' && align === 'center') && verticalAlign !== 'middle' && isNumber(offset[verticalAlign])) {\n return _objectSpread(_objectSpread({}, offset), {}, _defineProperty({}, verticalAlign, offset[verticalAlign] + (boxHeight || 0)));\n }\n }\n return offset;\n};\nvar isErrorBarRelevantForAxis = function isErrorBarRelevantForAxis(layout, axisType, direction) {\n if (isNil(axisType)) {\n return true;\n }\n if (layout === 'horizontal') {\n return axisType === 'yAxis';\n }\n if (layout === 'vertical') {\n return axisType === 'xAxis';\n }\n if (direction === 'x') {\n return axisType === 'xAxis';\n }\n if (direction === 'y') {\n return axisType === 'yAxis';\n }\n return true;\n};\nexport var getDomainOfErrorBars = function getDomainOfErrorBars(data, item, dataKey, layout, axisType) {\n var children = item.props.children;\n var errorBars = findAllByType(children, ErrorBar).filter(function (errorBarChild) {\n return isErrorBarRelevantForAxis(layout, axisType, errorBarChild.props.direction);\n });\n if (errorBars && errorBars.length) {\n var keys = errorBars.map(function (errorBarChild) {\n return errorBarChild.props.dataKey;\n });\n return data.reduce(function (result, entry) {\n var entryValue = getValueByDataKey(entry, dataKey);\n if (isNil(entryValue)) return result;\n var mainValue = Array.isArray(entryValue) ? [min(entryValue), max(entryValue)] : [entryValue, entryValue];\n var errorDomain = keys.reduce(function (prevErrorArr, k) {\n var errorValue = getValueByDataKey(entry, k, 0);\n var lowerValue = mainValue[0] - Math.abs(Array.isArray(errorValue) ? errorValue[0] : errorValue);\n var upperValue = mainValue[1] + Math.abs(Array.isArray(errorValue) ? errorValue[1] : errorValue);\n return [Math.min(lowerValue, prevErrorArr[0]), Math.max(upperValue, prevErrorArr[1])];\n }, [Infinity, -Infinity]);\n return [Math.min(errorDomain[0], result[0]), Math.max(errorDomain[1], result[1])];\n }, [Infinity, -Infinity]);\n }\n return null;\n};\nexport var parseErrorBarsOfAxis = function parseErrorBarsOfAxis(data, items, dataKey, axisType, layout) {\n var domains = items.map(function (item) {\n return getDomainOfErrorBars(data, item, dataKey, layout, axisType);\n }).filter(function (entry) {\n return !isNil(entry);\n });\n if (domains && domains.length) {\n return domains.reduce(function (result, entry) {\n return [Math.min(result[0], entry[0]), Math.max(result[1], entry[1])];\n }, [Infinity, -Infinity]);\n }\n return null;\n};\n\n/**\n * Get domain of data by the configuration of item element\n * @param {Array} data The data displayed in the chart\n * @param {Array} items The instances of item\n * @param {String} type The type of axis, number - Number Axis, category - Category Axis\n * @param {LayoutType} layout The type of layout\n * @param {Boolean} filterNil Whether or not filter nil values\n * @return {Array} Domain\n */\nexport var getDomainOfItemsWithSameAxis = function getDomainOfItemsWithSameAxis(data, items, type, layout, filterNil) {\n var domains = items.map(function (item) {\n var dataKey = item.props.dataKey;\n if (type === 'number' && dataKey) {\n return getDomainOfErrorBars(data, item, dataKey, layout) || getDomainOfDataByKey(data, dataKey, type, filterNil);\n }\n return getDomainOfDataByKey(data, dataKey, type, filterNil);\n });\n if (type === 'number') {\n // Calculate the domain of number axis\n return domains.reduce(\n // @ts-expect-error if (type === number) means that the domain is numerical type\n // - but this link is missing in the type definition\n function (result, entry) {\n return [Math.min(result[0], entry[0]), Math.max(result[1], entry[1])];\n }, [Infinity, -Infinity]);\n }\n var tag = {};\n // Get the union set of category axis\n return domains.reduce(function (result, entry) {\n for (var i = 0, len = entry.length; i < len; i++) {\n // @ts-expect-error Date cannot index an object\n if (!tag[entry[i]]) {\n // @ts-expect-error Date cannot index an object\n tag[entry[i]] = true;\n\n // @ts-expect-error Date cannot index an object\n result.push(entry[i]);\n }\n }\n return result;\n }, []);\n};\nexport var isCategoricalAxis = function isCategoricalAxis(layout, axisType) {\n return layout === 'horizontal' && axisType === 'xAxis' || layout === 'vertical' && axisType === 'yAxis' || layout === 'centric' && axisType === 'angleAxis' || layout === 'radial' && axisType === 'radiusAxis';\n};\n\n/**\n * Calculate the Coordinates of grid\n * @param {Array} ticks The ticks in axis\n * @param {Number} minValue The minimun value of axis\n * @param {Number} maxValue The maximun value of axis\n * @param {boolean} syncWithTicks Synchronize grid lines with ticks or not\n * @return {Array} Coordinates\n */\nexport var getCoordinatesOfGrid = function getCoordinatesOfGrid(ticks, minValue, maxValue, syncWithTicks) {\n if (syncWithTicks) {\n return ticks.map(function (entry) {\n return entry.coordinate;\n });\n }\n var hasMin, hasMax;\n var values = ticks.map(function (entry) {\n if (entry.coordinate === minValue) {\n hasMin = true;\n }\n if (entry.coordinate === maxValue) {\n hasMax = true;\n }\n return entry.coordinate;\n });\n if (!hasMin) {\n values.push(minValue);\n }\n if (!hasMax) {\n values.push(maxValue);\n }\n return values;\n};\n\n/**\n * Get the ticks of an axis\n * @param {Object} axis The configuration of an axis\n * @param {Boolean} isGrid Whether or not are the ticks in grid\n * @param {Boolean} isAll Return the ticks of all the points or not\n * @return {Array} Ticks\n */\nexport var getTicksOfAxis = function getTicksOfAxis(axis, isGrid, isAll) {\n if (!axis) return null;\n var scale = axis.scale;\n var duplicateDomain = axis.duplicateDomain,\n type = axis.type,\n range = axis.range;\n var offsetForBand = axis.realScaleType === 'scaleBand' ? scale.bandwidth() / 2 : 2;\n var offset = (isGrid || isAll) && type === 'category' && scale.bandwidth ? scale.bandwidth() / offsetForBand : 0;\n offset = axis.axisType === 'angleAxis' && (range === null || range === void 0 ? void 0 : range.length) >= 2 ? mathSign(range[0] - range[1]) * 2 * offset : offset;\n\n // The ticks set by user should only affect the ticks adjacent to axis line\n if (isGrid && (axis.ticks || axis.niceTicks)) {\n var result = (axis.ticks || axis.niceTicks).map(function (entry) {\n var scaleContent = duplicateDomain ? duplicateDomain.indexOf(entry) : entry;\n return {\n // If the scaleContent is not a number, the coordinate will be NaN.\n // That could be the case for example with a PointScale and a string as domain.\n coordinate: scale(scaleContent) + offset,\n value: entry,\n offset: offset\n };\n });\n return result.filter(function (row) {\n return !isNan(row.coordinate);\n });\n }\n\n // When axis is a categorial axis, but the type of axis is number or the scale of axis is not \"auto\"\n if (axis.isCategorical && axis.categoricalDomain) {\n return axis.categoricalDomain.map(function (entry, index) {\n return {\n coordinate: scale(entry) + offset,\n value: entry,\n index: index,\n offset: offset\n };\n });\n }\n if (scale.ticks && !isAll) {\n return scale.ticks(axis.tickCount).map(function (entry) {\n return {\n coordinate: scale(entry) + offset,\n value: entry,\n offset: offset\n };\n });\n }\n\n // When axis has duplicated text, serial numbers are used to generate scale\n return scale.domain().map(function (entry, index) {\n return {\n coordinate: scale(entry) + offset,\n value: duplicateDomain ? duplicateDomain[entry] : entry,\n index: index,\n offset: offset\n };\n });\n};\n\n/**\n * combine the handlers\n * @param {Function} defaultHandler Internal private handler\n * @param {Function} childHandler Handler function specified in child component\n * @return {Function} The combined handler\n */\n\nvar handlerWeakMap = new WeakMap();\nexport var combineEventHandlers = function combineEventHandlers(defaultHandler, childHandler) {\n if (typeof childHandler !== 'function') {\n return defaultHandler;\n }\n if (!handlerWeakMap.has(defaultHandler)) {\n handlerWeakMap.set(defaultHandler, new WeakMap());\n }\n var childWeakMap = handlerWeakMap.get(defaultHandler);\n if (childWeakMap.has(childHandler)) {\n return childWeakMap.get(childHandler);\n }\n var combineHandler = function combineHandler() {\n defaultHandler.apply(void 0, arguments);\n childHandler.apply(void 0, arguments);\n };\n childWeakMap.set(childHandler, combineHandler);\n return combineHandler;\n};\n\n/**\n * Parse the scale function of axis\n * @param {Object} axis The option of axis\n * @param {String} chartType The displayName of chart\n * @param {Boolean} hasBar if it has a bar\n * @return {object} The scale function and resolved name\n */\nexport var parseScale = function parseScale(axis, chartType, hasBar) {\n var scale = axis.scale,\n type = axis.type,\n layout = axis.layout,\n axisType = axis.axisType;\n if (scale === 'auto') {\n if (layout === 'radial' && axisType === 'radiusAxis') {\n return {\n scale: d3Scales.scaleBand(),\n realScaleType: 'band'\n };\n }\n if (layout === 'radial' && axisType === 'angleAxis') {\n return {\n scale: d3Scales.scaleLinear(),\n realScaleType: 'linear'\n };\n }\n if (type === 'category' && chartType && (chartType.indexOf('LineChart') >= 0 || chartType.indexOf('AreaChart') >= 0 || chartType.indexOf('ComposedChart') >= 0 && !hasBar)) {\n return {\n scale: d3Scales.scalePoint(),\n realScaleType: 'point'\n };\n }\n if (type === 'category') {\n return {\n scale: d3Scales.scaleBand(),\n realScaleType: 'band'\n };\n }\n return {\n scale: d3Scales.scaleLinear(),\n realScaleType: 'linear'\n };\n }\n if (isString(scale)) {\n var name = \"scale\".concat(upperFirst(scale));\n return {\n scale: (d3Scales[name] || d3Scales.scalePoint)(),\n realScaleType: d3Scales[name] ? name : 'point'\n };\n }\n return isFunction(scale) ? {\n scale: scale\n } : {\n scale: d3Scales.scalePoint(),\n realScaleType: 'point'\n };\n};\nvar EPS = 1e-4;\nexport var checkDomainOfScale = function checkDomainOfScale(scale) {\n var domain = scale.domain();\n if (!domain || domain.length <= 2) {\n return;\n }\n var len = domain.length;\n var range = scale.range();\n var minValue = Math.min(range[0], range[1]) - EPS;\n var maxValue = Math.max(range[0], range[1]) + EPS;\n var first = scale(domain[0]);\n var last = scale(domain[len - 1]);\n if (first < minValue || first > maxValue || last < minValue || last > maxValue) {\n scale.domain([domain[0], domain[len - 1]]);\n }\n};\nexport var findPositionOfBar = function findPositionOfBar(barPosition, child) {\n if (!barPosition) {\n return null;\n }\n for (var i = 0, len = barPosition.length; i < len; i++) {\n if (barPosition[i].item === child) {\n return barPosition[i].position;\n }\n }\n return null;\n};\n\n/**\n * Both value and domain are tuples of two numbers\n * - but the type stays as array of numbers until we have better support in rest of the app\n * @param {Array} value input that will be truncated\n * @param {Array} domain boundaries\n * @returns {Array} tuple of two numbers\n */\nexport var truncateByDomain = function truncateByDomain(value, domain) {\n if (!domain || domain.length !== 2 || !isNumber(domain[0]) || !isNumber(domain[1])) {\n return value;\n }\n var minValue = Math.min(domain[0], domain[1]);\n var maxValue = Math.max(domain[0], domain[1]);\n var result = [value[0], value[1]];\n if (!isNumber(value[0]) || value[0] < minValue) {\n result[0] = minValue;\n }\n if (!isNumber(value[1]) || value[1] > maxValue) {\n result[1] = maxValue;\n }\n if (result[0] > maxValue) {\n result[0] = maxValue;\n }\n if (result[1] < minValue) {\n result[1] = minValue;\n }\n return result;\n};\n\n/**\n * Stacks all positive numbers above zero and all negative numbers below zero.\n *\n * If all values in the series are positive then this behaves the same as 'none' stacker.\n *\n * @param {Array} series from d3-shape Stack\n * @return {Array} series with applied offset\n */\nexport var offsetSign = function offsetSign(series) {\n var n = series.length;\n if (n <= 0) {\n return;\n }\n for (var j = 0, m = series[0].length; j < m; ++j) {\n var positive = 0;\n var negative = 0;\n for (var i = 0; i < n; ++i) {\n var value = isNan(series[i][j][1]) ? series[i][j][0] : series[i][j][1];\n\n /* eslint-disable prefer-destructuring, no-param-reassign */\n if (value >= 0) {\n series[i][j][0] = positive;\n series[i][j][1] = positive + value;\n positive = series[i][j][1];\n } else {\n series[i][j][0] = negative;\n series[i][j][1] = negative + value;\n negative = series[i][j][1];\n }\n /* eslint-enable prefer-destructuring, no-param-reassign */\n }\n }\n};\n\n/**\n * Replaces all negative values with zero when stacking data.\n *\n * If all values in the series are positive then this behaves the same as 'none' stacker.\n *\n * @param {Array} series from d3-shape Stack\n * @return {Array} series with applied offset\n */\nexport var offsetPositive = function offsetPositive(series) {\n var n = series.length;\n if (n <= 0) {\n return;\n }\n for (var j = 0, m = series[0].length; j < m; ++j) {\n var positive = 0;\n for (var i = 0; i < n; ++i) {\n var value = isNan(series[i][j][1]) ? series[i][j][0] : series[i][j][1];\n\n /* eslint-disable prefer-destructuring, no-param-reassign */\n if (value >= 0) {\n series[i][j][0] = positive;\n series[i][j][1] = positive + value;\n positive = series[i][j][1];\n } else {\n series[i][j][0] = 0;\n series[i][j][1] = 0;\n }\n /* eslint-enable prefer-destructuring, no-param-reassign */\n }\n }\n};\n\n/**\n * Function type to compute offset for stacked data.\n *\n * d3-shape has something fishy going on with its types.\n * In @definitelytyped/d3-shape, this function (the offset accessor) is typed as Series<> => void.\n * However! When I actually open the storybook I can see that the offset accessor actually receives Array>.\n * The same I can see in the source code itself:\n * https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/66042\n * That one unfortunately has no types but we can tell it passes three-dimensional array.\n *\n * Which leads me to believe that definitelytyped is wrong on this one.\n * There's open discussion on this topic without much attention:\n * https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/66042\n */\n\nvar STACK_OFFSET_MAP = {\n sign: offsetSign,\n // @ts-expect-error definitelytyped types are incorrect\n expand: stackOffsetExpand,\n // @ts-expect-error definitelytyped types are incorrect\n none: stackOffsetNone,\n // @ts-expect-error definitelytyped types are incorrect\n silhouette: stackOffsetSilhouette,\n // @ts-expect-error definitelytyped types are incorrect\n wiggle: stackOffsetWiggle,\n positive: offsetPositive\n};\nexport var getStackedData = function getStackedData(data, stackItems, offsetType) {\n var dataKeys = stackItems.map(function (item) {\n return item.props.dataKey;\n });\n var offsetAccessor = STACK_OFFSET_MAP[offsetType];\n var stack = shapeStack()\n // @ts-expect-error stack.keys type wants an array of strings, but we provide array of DataKeys\n .keys(dataKeys).value(function (d, key) {\n return +getValueByDataKey(d, key, 0);\n }).order(stackOrderNone)\n // @ts-expect-error definitelytyped types are incorrect\n .offset(offsetAccessor);\n return stack(data);\n};\nexport var getStackGroupsByAxisId = function getStackGroupsByAxisId(data, _items, numericAxisId, cateAxisId, offsetType, reverseStackOrder) {\n if (!data) {\n return null;\n }\n\n // reversing items to affect render order (for layering)\n var items = reverseStackOrder ? _items.reverse() : _items;\n var parentStackGroupsInitialValue = {};\n var stackGroups = items.reduce(function (result, item) {\n var _item$type2;\n var defaultedProps = (_item$type2 = item.type) !== null && _item$type2 !== void 0 && _item$type2.defaultProps ? _objectSpread(_objectSpread({}, item.type.defaultProps), item.props) : item.props;\n var stackId = defaultedProps.stackId,\n hide = defaultedProps.hide;\n if (hide) {\n return result;\n }\n var axisId = defaultedProps[numericAxisId];\n var parentGroup = result[axisId] || {\n hasStack: false,\n stackGroups: {}\n };\n if (isNumOrStr(stackId)) {\n var childGroup = parentGroup.stackGroups[stackId] || {\n numericAxisId: numericAxisId,\n cateAxisId: cateAxisId,\n items: []\n };\n childGroup.items.push(item);\n parentGroup.hasStack = true;\n parentGroup.stackGroups[stackId] = childGroup;\n } else {\n parentGroup.stackGroups[uniqueId('_stackId_')] = {\n numericAxisId: numericAxisId,\n cateAxisId: cateAxisId,\n items: [item]\n };\n }\n return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, axisId, parentGroup));\n }, parentStackGroupsInitialValue);\n var axisStackGroupsInitialValue = {};\n return Object.keys(stackGroups).reduce(function (result, axisId) {\n var group = stackGroups[axisId];\n if (group.hasStack) {\n var stackGroupsInitialValue = {};\n group.stackGroups = Object.keys(group.stackGroups).reduce(function (res, stackId) {\n var g = group.stackGroups[stackId];\n return _objectSpread(_objectSpread({}, res), {}, _defineProperty({}, stackId, {\n numericAxisId: numericAxisId,\n cateAxisId: cateAxisId,\n items: g.items,\n stackedData: getStackedData(data, g.items, offsetType)\n }));\n }, stackGroupsInitialValue);\n }\n return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, axisId, group));\n }, axisStackGroupsInitialValue);\n};\n\n/**\n * Configure the scale function of axis\n * @param {Object} scale The scale function\n * @param {Object} opts The configuration of axis\n * @return {Object} null\n */\nexport var getTicksOfScale = function getTicksOfScale(scale, opts) {\n var realScaleType = opts.realScaleType,\n type = opts.type,\n tickCount = opts.tickCount,\n originalDomain = opts.originalDomain,\n allowDecimals = opts.allowDecimals;\n var scaleType = realScaleType || opts.scale;\n if (scaleType !== 'auto' && scaleType !== 'linear') {\n return null;\n }\n if (tickCount && type === 'number' && originalDomain && (originalDomain[0] === 'auto' || originalDomain[1] === 'auto')) {\n // Calculate the ticks by the number of grid when the axis is a number axis\n var domain = scale.domain();\n if (!domain.length) {\n return null;\n }\n var tickValues = getNiceTickValues(domain, tickCount, allowDecimals);\n scale.domain([min(tickValues), max(tickValues)]);\n return {\n niceTicks: tickValues\n };\n }\n if (tickCount && type === 'number') {\n var _domain = scale.domain();\n var _tickValues = getTickValuesFixedDomain(_domain, tickCount, allowDecimals);\n return {\n niceTicks: _tickValues\n };\n }\n return null;\n};\nexport function getCateCoordinateOfLine(_ref5) {\n var axis = _ref5.axis,\n ticks = _ref5.ticks,\n bandSize = _ref5.bandSize,\n entry = _ref5.entry,\n index = _ref5.index,\n dataKey = _ref5.dataKey;\n if (axis.type === 'category') {\n // find coordinate of category axis by the value of category\n // @ts-expect-error why does this use direct object access instead of getValueByDataKey?\n if (!axis.allowDuplicatedCategory && axis.dataKey && !isNil(entry[axis.dataKey])) {\n // @ts-expect-error why does this use direct object access instead of getValueByDataKey?\n var matchedTick = findEntryInArray(ticks, 'value', entry[axis.dataKey]);\n if (matchedTick) {\n return matchedTick.coordinate + bandSize / 2;\n }\n }\n return ticks[index] ? ticks[index].coordinate + bandSize / 2 : null;\n }\n var value = getValueByDataKey(entry, !isNil(dataKey) ? dataKey : axis.dataKey);\n return !isNil(value) ? axis.scale(value) : null;\n}\nexport var getCateCoordinateOfBar = function getCateCoordinateOfBar(_ref6) {\n var axis = _ref6.axis,\n ticks = _ref6.ticks,\n offset = _ref6.offset,\n bandSize = _ref6.bandSize,\n entry = _ref6.entry,\n index = _ref6.index;\n if (axis.type === 'category') {\n return ticks[index] ? ticks[index].coordinate + offset : null;\n }\n var value = getValueByDataKey(entry, axis.dataKey, axis.domain[index]);\n return !isNil(value) ? axis.scale(value) - bandSize / 2 + offset : null;\n};\nexport var getBaseValueOfBar = function getBaseValueOfBar(_ref7) {\n var numericAxis = _ref7.numericAxis;\n var domain = numericAxis.scale.domain();\n if (numericAxis.type === 'number') {\n var minValue = Math.min(domain[0], domain[1]);\n var maxValue = Math.max(domain[0], domain[1]);\n if (minValue <= 0 && maxValue >= 0) {\n return 0;\n }\n if (maxValue < 0) {\n return maxValue;\n }\n return minValue;\n }\n return domain[0];\n};\nexport var getStackedDataOfItem = function getStackedDataOfItem(item, stackGroups) {\n var _item$type3;\n var defaultedProps = (_item$type3 = item.type) !== null && _item$type3 !== void 0 && _item$type3.defaultProps ? _objectSpread(_objectSpread({}, item.type.defaultProps), item.props) : item.props;\n var stackId = defaultedProps.stackId;\n if (isNumOrStr(stackId)) {\n var group = stackGroups[stackId];\n if (group) {\n var itemIndex = group.items.indexOf(item);\n return itemIndex >= 0 ? group.stackedData[itemIndex] : null;\n }\n }\n return null;\n};\nvar getDomainOfSingle = function getDomainOfSingle(data) {\n return data.reduce(function (result, entry) {\n return [min(entry.concat([result[0]]).filter(isNumber)), max(entry.concat([result[1]]).filter(isNumber))];\n }, [Infinity, -Infinity]);\n};\nexport var getDomainOfStackGroups = function getDomainOfStackGroups(stackGroups, startIndex, endIndex) {\n return Object.keys(stackGroups).reduce(function (result, stackId) {\n var group = stackGroups[stackId];\n var stackedData = group.stackedData;\n var domain = stackedData.reduce(function (res, entry) {\n var s = getDomainOfSingle(entry.slice(startIndex, endIndex + 1));\n return [Math.min(res[0], s[0]), Math.max(res[1], s[1])];\n }, [Infinity, -Infinity]);\n return [Math.min(domain[0], result[0]), Math.max(domain[1], result[1])];\n }, [Infinity, -Infinity]).map(function (result) {\n return result === Infinity || result === -Infinity ? 0 : result;\n });\n};\nexport var MIN_VALUE_REG = /^dataMin[\\s]*-[\\s]*([0-9]+([.]{1}[0-9]+){0,1})$/;\nexport var MAX_VALUE_REG = /^dataMax[\\s]*\\+[\\s]*([0-9]+([.]{1}[0-9]+){0,1})$/;\nexport var parseSpecifiedDomain = function parseSpecifiedDomain(specifiedDomain, dataDomain, allowDataOverflow) {\n if (isFunction(specifiedDomain)) {\n return specifiedDomain(dataDomain, allowDataOverflow);\n }\n if (!Array.isArray(specifiedDomain)) {\n return dataDomain;\n }\n var domain = [];\n\n /* eslint-disable prefer-destructuring */\n if (isNumber(specifiedDomain[0])) {\n domain[0] = allowDataOverflow ? specifiedDomain[0] : Math.min(specifiedDomain[0], dataDomain[0]);\n } else if (MIN_VALUE_REG.test(specifiedDomain[0])) {\n var value = +MIN_VALUE_REG.exec(specifiedDomain[0])[1];\n domain[0] = dataDomain[0] - value;\n } else if (isFunction(specifiedDomain[0])) {\n domain[0] = specifiedDomain[0](dataDomain[0]);\n } else {\n domain[0] = dataDomain[0];\n }\n if (isNumber(specifiedDomain[1])) {\n domain[1] = allowDataOverflow ? specifiedDomain[1] : Math.max(specifiedDomain[1], dataDomain[1]);\n } else if (MAX_VALUE_REG.test(specifiedDomain[1])) {\n var _value = +MAX_VALUE_REG.exec(specifiedDomain[1])[1];\n domain[1] = dataDomain[1] + _value;\n } else if (isFunction(specifiedDomain[1])) {\n domain[1] = specifiedDomain[1](dataDomain[1]);\n } else {\n domain[1] = dataDomain[1];\n }\n /* eslint-enable prefer-destructuring */\n\n return domain;\n};\n\n/**\n * Calculate the size between two category\n * @param {Object} axis The options of axis\n * @param {Array} ticks The ticks of axis\n * @param {Boolean} isBar if items in axis are bars\n * @return {Number} Size\n */\nexport var getBandSizeOfAxis = function getBandSizeOfAxis(axis, ticks, isBar) {\n // @ts-expect-error we need to rethink scale type\n if (axis && axis.scale && axis.scale.bandwidth) {\n // @ts-expect-error we need to rethink scale type\n var bandWidth = axis.scale.bandwidth();\n if (!isBar || bandWidth > 0) {\n return bandWidth;\n }\n }\n if (axis && ticks && ticks.length >= 2) {\n var orderedTicks = sortBy(ticks, function (o) {\n return o.coordinate;\n });\n var bandSize = Infinity;\n for (var i = 1, len = orderedTicks.length; i < len; i++) {\n var cur = orderedTicks[i];\n var prev = orderedTicks[i - 1];\n bandSize = Math.min((cur.coordinate || 0) - (prev.coordinate || 0), bandSize);\n }\n return bandSize === Infinity ? 0 : bandSize;\n }\n return isBar ? undefined : 0;\n};\n/**\n * parse the domain of a category axis when a domain is specified\n * @param {Array} specifiedDomain The domain specified by users\n * @param {Array} calculatedDomain The domain calculated by dateKey\n * @param {ReactElement} axisChild The axis ReactElement\n * @returns {Array} domains\n */\nexport var parseDomainOfCategoryAxis = function parseDomainOfCategoryAxis(specifiedDomain, calculatedDomain, axisChild) {\n if (!specifiedDomain || !specifiedDomain.length) {\n return calculatedDomain;\n }\n if (isEqual(specifiedDomain, get(axisChild, 'type.defaultProps.domain'))) {\n return calculatedDomain;\n }\n return specifiedDomain;\n};\nexport var getTooltipItem = function getTooltipItem(graphicalItem, payload) {\n var defaultedProps = graphicalItem.type.defaultProps ? _objectSpread(_objectSpread({}, graphicalItem.type.defaultProps), graphicalItem.props) : graphicalItem.props;\n var dataKey = defaultedProps.dataKey,\n name = defaultedProps.name,\n unit = defaultedProps.unit,\n formatter = defaultedProps.formatter,\n tooltipType = defaultedProps.tooltipType,\n chartType = defaultedProps.chartType,\n hide = defaultedProps.hide;\n return _objectSpread(_objectSpread({}, filterProps(graphicalItem, false)), {}, {\n dataKey: dataKey,\n unit: unit,\n formatter: formatter,\n name: name || dataKey,\n color: getMainColorOfGraphicItem(graphicalItem),\n value: getValueByDataKey(payload, dataKey),\n type: tooltipType,\n payload: payload,\n chartType: chartType,\n hide: hide\n });\n};", "function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && Symbol.iterator in Object(iter)) return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\n\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nfunction _iterableToArrayLimit(arr, i) { if (typeof Symbol === \"undefined\" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\n/**\n * @fileOverview calculate tick values of scale\n * @author xile611, arcthur\n * @date 2015-09-17\n */\nimport Decimal from 'decimal.js-light';\nimport { compose, range, memoize, map, reverse } from './util/utils';\nimport Arithmetic from './util/arithmetic';\n/**\n * Calculate a interval of a minimum value and a maximum value\n *\n * @param {Number} min The minimum value\n * @param {Number} max The maximum value\n * @return {Array} An interval\n */\n\nfunction getValidInterval(_ref) {\n var _ref2 = _slicedToArray(_ref, 2),\n min = _ref2[0],\n max = _ref2[1];\n\n var validMin = min,\n validMax = max; // exchange\n\n if (min > max) {\n validMin = max;\n validMax = min;\n }\n\n return [validMin, validMax];\n}\n/**\n * Calculate the step which is easy to understand between ticks, like 10, 20, 25\n *\n * @param {Decimal} roughStep The rough step calculated by deviding the\n * difference by the tickCount\n * @param {Boolean} allowDecimals Allow the ticks to be decimals or not\n * @param {Integer} correctionFactor A correction factor\n * @return {Decimal} The step which is easy to understand between two ticks\n */\n\n\nfunction getFormatStep(roughStep, allowDecimals, correctionFactor) {\n if (roughStep.lte(0)) {\n return new Decimal(0);\n }\n\n var digitCount = Arithmetic.getDigitCount(roughStep.toNumber()); // The ratio between the rough step and the smallest number which has a bigger\n // order of magnitudes than the rough step\n\n var digitCountValue = new Decimal(10).pow(digitCount);\n var stepRatio = roughStep.div(digitCountValue); // When an integer and a float multiplied, the accuracy of result may be wrong\n\n var stepRatioScale = digitCount !== 1 ? 0.05 : 0.1;\n var amendStepRatio = new Decimal(Math.ceil(stepRatio.div(stepRatioScale).toNumber())).add(correctionFactor).mul(stepRatioScale);\n var formatStep = amendStepRatio.mul(digitCountValue);\n return allowDecimals ? formatStep : new Decimal(Math.ceil(formatStep));\n}\n/**\n * calculate the ticks when the minimum value equals to the maximum value\n *\n * @param {Number} value The minimum valuue which is also the maximum value\n * @param {Integer} tickCount The count of ticks\n * @param {Boolean} allowDecimals Allow the ticks to be decimals or not\n * @return {Array} ticks\n */\n\n\nfunction getTickOfSingleValue(value, tickCount, allowDecimals) {\n var step = 1; // calculate the middle value of ticks\n\n var middle = new Decimal(value);\n\n if (!middle.isint() && allowDecimals) {\n var absVal = Math.abs(value);\n\n if (absVal < 1) {\n // The step should be a float number when the difference is smaller than 1\n step = new Decimal(10).pow(Arithmetic.getDigitCount(value) - 1);\n middle = new Decimal(Math.floor(middle.div(step).toNumber())).mul(step);\n } else if (absVal > 1) {\n // Return the maximum integer which is smaller than 'value' when 'value' is greater than 1\n middle = new Decimal(Math.floor(value));\n }\n } else if (value === 0) {\n middle = new Decimal(Math.floor((tickCount - 1) / 2));\n } else if (!allowDecimals) {\n middle = new Decimal(Math.floor(value));\n }\n\n var middleIndex = Math.floor((tickCount - 1) / 2);\n var fn = compose(map(function (n) {\n return middle.add(new Decimal(n - middleIndex).mul(step)).toNumber();\n }), range);\n return fn(0, tickCount);\n}\n/**\n * Calculate the step\n *\n * @param {Number} min The minimum value of an interval\n * @param {Number} max The maximum value of an interval\n * @param {Integer} tickCount The count of ticks\n * @param {Boolean} allowDecimals Allow the ticks to be decimals or not\n * @param {Number} correctionFactor A correction factor\n * @return {Object} The step, minimum value of ticks, maximum value of ticks\n */\n\n\nfunction calculateStep(min, max, tickCount, allowDecimals) {\n var correctionFactor = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;\n\n // dirty hack (for recharts' test)\n if (!Number.isFinite((max - min) / (tickCount - 1))) {\n return {\n step: new Decimal(0),\n tickMin: new Decimal(0),\n tickMax: new Decimal(0)\n };\n } // The step which is easy to understand between two ticks\n\n\n var step = getFormatStep(new Decimal(max).sub(min).div(tickCount - 1), allowDecimals, correctionFactor); // A medial value of ticks\n\n var middle; // When 0 is inside the interval, 0 should be a tick\n\n if (min <= 0 && max >= 0) {\n middle = new Decimal(0);\n } else {\n // calculate the middle value\n middle = new Decimal(min).add(max).div(2); // minus modulo value\n\n middle = middle.sub(new Decimal(middle).mod(step));\n }\n\n var belowCount = Math.ceil(middle.sub(min).div(step).toNumber());\n var upCount = Math.ceil(new Decimal(max).sub(middle).div(step).toNumber());\n var scaleCount = belowCount + upCount + 1;\n\n if (scaleCount > tickCount) {\n // When more ticks need to cover the interval, step should be bigger.\n return calculateStep(min, max, tickCount, allowDecimals, correctionFactor + 1);\n }\n\n if (scaleCount < tickCount) {\n // When less ticks can cover the interval, we should add some additional ticks\n upCount = max > 0 ? upCount + (tickCount - scaleCount) : upCount;\n belowCount = max > 0 ? belowCount : belowCount + (tickCount - scaleCount);\n }\n\n return {\n step: step,\n tickMin: middle.sub(new Decimal(belowCount).mul(step)),\n tickMax: middle.add(new Decimal(upCount).mul(step))\n };\n}\n/**\n * Calculate the ticks of an interval, the count of ticks will be guraranteed\n *\n * @param {Number} min, max min: The minimum value, max: The maximum value\n * @param {Integer} tickCount The count of ticks\n * @param {Boolean} allowDecimals Allow the ticks to be decimals or not\n * @return {Array} ticks\n */\n\n\nfunction getNiceTickValuesFn(_ref3) {\n var _ref4 = _slicedToArray(_ref3, 2),\n min = _ref4[0],\n max = _ref4[1];\n\n var tickCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 6;\n var allowDecimals = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n // More than two ticks should be return\n var count = Math.max(tickCount, 2);\n\n var _getValidInterval = getValidInterval([min, max]),\n _getValidInterval2 = _slicedToArray(_getValidInterval, 2),\n cormin = _getValidInterval2[0],\n cormax = _getValidInterval2[1];\n\n if (cormin === -Infinity || cormax === Infinity) {\n var _values = cormax === Infinity ? [cormin].concat(_toConsumableArray(range(0, tickCount - 1).map(function () {\n return Infinity;\n }))) : [].concat(_toConsumableArray(range(0, tickCount - 1).map(function () {\n return -Infinity;\n })), [cormax]);\n\n return min > max ? reverse(_values) : _values;\n }\n\n if (cormin === cormax) {\n return getTickOfSingleValue(cormin, tickCount, allowDecimals);\n } // Get the step between two ticks\n\n\n var _calculateStep = calculateStep(cormin, cormax, count, allowDecimals),\n step = _calculateStep.step,\n tickMin = _calculateStep.tickMin,\n tickMax = _calculateStep.tickMax;\n\n var values = Arithmetic.rangeStep(tickMin, tickMax.add(new Decimal(0.1).mul(step)), step);\n return min > max ? reverse(values) : values;\n}\n/**\n * Calculate the ticks of an interval, the count of ticks won't be guraranteed\n *\n * @param {Number} min, max min: The minimum value, max: The maximum value\n * @param {Integer} tickCount The count of ticks\n * @param {Boolean} allowDecimals Allow the ticks to be decimals or not\n * @return {Array} ticks\n */\n\n\nfunction getTickValuesFn(_ref5) {\n var _ref6 = _slicedToArray(_ref5, 2),\n min = _ref6[0],\n max = _ref6[1];\n\n var tickCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 6;\n var allowDecimals = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n // More than two ticks should be return\n var count = Math.max(tickCount, 2);\n\n var _getValidInterval3 = getValidInterval([min, max]),\n _getValidInterval4 = _slicedToArray(_getValidInterval3, 2),\n cormin = _getValidInterval4[0],\n cormax = _getValidInterval4[1];\n\n if (cormin === -Infinity || cormax === Infinity) {\n return [min, max];\n }\n\n if (cormin === cormax) {\n return getTickOfSingleValue(cormin, tickCount, allowDecimals);\n }\n\n var step = getFormatStep(new Decimal(cormax).sub(cormin).div(count - 1), allowDecimals, 0);\n var fn = compose(map(function (n) {\n return new Decimal(cormin).add(new Decimal(n).mul(step)).toNumber();\n }), range);\n var values = fn(0, count).filter(function (entry) {\n return entry >= cormin && entry <= cormax;\n });\n return min > max ? reverse(values) : values;\n}\n/**\n * Calculate the ticks of an interval, the count of ticks won't be guraranteed,\n * but the domain will be guaranteed\n *\n * @param {Number} min, max min: The minimum value, max: The maximum value\n * @param {Integer} tickCount The count of ticks\n * @param {Boolean} allowDecimals Allow the ticks to be decimals or not\n * @return {Array} ticks\n */\n\n\nfunction getTickValuesFixedDomainFn(_ref7, tickCount) {\n var _ref8 = _slicedToArray(_ref7, 2),\n min = _ref8[0],\n max = _ref8[1];\n\n var allowDecimals = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n\n // More than two ticks should be return\n var _getValidInterval5 = getValidInterval([min, max]),\n _getValidInterval6 = _slicedToArray(_getValidInterval5, 2),\n cormin = _getValidInterval6[0],\n cormax = _getValidInterval6[1];\n\n if (cormin === -Infinity || cormax === Infinity) {\n return [min, max];\n }\n\n if (cormin === cormax) {\n return [cormin];\n }\n\n var count = Math.max(tickCount, 2);\n var step = getFormatStep(new Decimal(cormax).sub(cormin).div(count - 1), allowDecimals, 0);\n var values = [].concat(_toConsumableArray(Arithmetic.rangeStep(new Decimal(cormin), new Decimal(cormax).sub(new Decimal(0.99).mul(step)), step)), [cormax]);\n return min > max ? reverse(values) : values;\n}\n\nexport var getNiceTickValues = memoize(getNiceTickValuesFn);\nexport var getTickValues = memoize(getTickValuesFn);\nexport var getTickValuesFixedDomain = memoize(getTickValuesFixedDomainFn);", "function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && Symbol.iterator in Object(iter)) return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nvar identity = function identity(i) {\n return i;\n};\n\nexport var PLACE_HOLDER = {\n '@@functional/placeholder': true\n};\n\nvar isPlaceHolder = function isPlaceHolder(val) {\n return val === PLACE_HOLDER;\n};\n\nvar curry0 = function curry0(fn) {\n return function _curried() {\n if (arguments.length === 0 || arguments.length === 1 && isPlaceHolder(arguments.length <= 0 ? undefined : arguments[0])) {\n return _curried;\n }\n\n return fn.apply(void 0, arguments);\n };\n};\n\nvar curryN = function curryN(n, fn) {\n if (n === 1) {\n return fn;\n }\n\n return curry0(function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n var argsLength = args.filter(function (arg) {\n return arg !== PLACE_HOLDER;\n }).length;\n\n if (argsLength >= n) {\n return fn.apply(void 0, args);\n }\n\n return curryN(n - argsLength, curry0(function () {\n for (var _len2 = arguments.length, restArgs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n restArgs[_key2] = arguments[_key2];\n }\n\n var newArgs = args.map(function (arg) {\n return isPlaceHolder(arg) ? restArgs.shift() : arg;\n });\n return fn.apply(void 0, _toConsumableArray(newArgs).concat(restArgs));\n }));\n });\n};\n\nexport var curry = function curry(fn) {\n return curryN(fn.length, fn);\n};\nexport var range = function range(begin, end) {\n var arr = [];\n\n for (var i = begin; i < end; ++i) {\n arr[i - begin] = i;\n }\n\n return arr;\n};\nexport var map = curry(function (fn, arr) {\n if (Array.isArray(arr)) {\n return arr.map(fn);\n }\n\n return Object.keys(arr).map(function (key) {\n return arr[key];\n }).map(fn);\n});\nexport var compose = function compose() {\n for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n args[_key3] = arguments[_key3];\n }\n\n if (!args.length) {\n return identity;\n }\n\n var fns = args.reverse(); // first function can receive multiply arguments\n\n var firstFn = fns[0];\n var tailsFn = fns.slice(1);\n return function () {\n return tailsFn.reduce(function (res, fn) {\n return fn(res);\n }, firstFn.apply(void 0, arguments));\n };\n};\nexport var reverse = function reverse(arr) {\n if (Array.isArray(arr)) {\n return arr.reverse();\n } // can be string\n\n\n return arr.split('').reverse.join('');\n};\nexport var memoize = function memoize(fn) {\n var lastArgs = null;\n var lastResult = null;\n return function () {\n for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n args[_key4] = arguments[_key4];\n }\n\n if (lastArgs && args.every(function (val, i) {\n return val === lastArgs[i];\n })) {\n return lastResult;\n }\n\n lastArgs = args;\n lastResult = fn.apply(void 0, args);\n return lastResult;\n };\n};", "/**\n * @fileOverview \u4E00\u4E9B\u516C\u7528\u7684\u8FD0\u7B97\u65B9\u6CD5\n * @author xile611\n * @date 2015-09-17\n */\nimport Decimal from 'decimal.js-light';\nimport { curry } from './utils';\n/**\n * \u83B7\u53D6\u6570\u503C\u7684\u4F4D\u6570\n * \u5176\u4E2D\u7EDD\u5BF9\u503C\u5C5E\u4E8E\u533A\u95F4[0.1, 1)\uFF0C \u5F97\u5230\u7684\u503C\u4E3A0\n * \u7EDD\u5BF9\u503C\u5C5E\u4E8E\u533A\u95F4[0.01, 0.1)\uFF0C\u5F97\u5230\u7684\u4F4D\u6570\u4E3A -1\n * \u7EDD\u5BF9\u503C\u5C5E\u4E8E\u533A\u95F4[0.001, 0.01)\uFF0C\u5F97\u5230\u7684\u4F4D\u6570\u4E3A -2\n *\n * @param {Number} value \u6570\u503C\n * @return {Integer} \u4F4D\u6570\n */\n\nfunction getDigitCount(value) {\n var result;\n\n if (value === 0) {\n result = 1;\n } else {\n result = Math.floor(new Decimal(value).abs().log(10).toNumber()) + 1;\n }\n\n return result;\n}\n/**\n * \u6309\u7167\u56FA\u5B9A\u7684\u6B65\u957F\u83B7\u53D6[start, end)\u8FD9\u4E2A\u533A\u95F4\u7684\u6570\u636E\n * \u5E76\u4E14\u9700\u8981\u5904\u7406js\u8BA1\u7B97\u7CBE\u5EA6\u7684\u95EE\u9898\n *\n * @param {Decimal} start \u8D77\u70B9\n * @param {Decimal} end \u7EC8\u70B9\uFF0C\u4E0D\u5305\u542B\u8BE5\u503C\n * @param {Decimal} step \u6B65\u957F\n * @return {Array} \u82E5\u5E72\u6570\u503C\n */\n\n\nfunction rangeStep(start, end, step) {\n var num = new Decimal(start);\n var i = 0;\n var result = []; // magic number to prevent infinite loop\n\n while (num.lt(end) && i < 100000) {\n result.push(num.toNumber());\n num = num.add(step);\n i++;\n }\n\n return result;\n}\n/**\n * \u5BF9\u6570\u503C\u8FDB\u884C\u7EBF\u6027\u63D2\u503C\n *\n * @param {Number} a \u5B9A\u4E49\u57DF\u7684\u6781\u70B9\n * @param {Number} b \u5B9A\u4E49\u57DF\u7684\u6781\u70B9\n * @param {Number} t [0, 1]\u5185\u7684\u67D0\u4E2A\u503C\n * @return {Number} \u5B9A\u4E49\u57DF\u5185\u7684\u67D0\u4E2A\u503C\n */\n\n\nvar interpolateNumber = curry(function (a, b, t) {\n var newA = +a;\n var newB = +b;\n return newA + t * (newB - newA);\n});\n/**\n * \u7EBF\u6027\u63D2\u503C\u7684\u9006\u8FD0\u7B97\n *\n * @param {Number} a \u5B9A\u4E49\u57DF\u7684\u6781\u70B9\n * @param {Number} b \u5B9A\u4E49\u57DF\u7684\u6781\u70B9\n * @param {Number} x \u53EF\u4EE5\u8BA4\u4E3A\u662F\u63D2\u503C\u540E\u7684\u4E00\u4E2A\u8F93\u51FA\u503C\n * @return {Number} \u5F53x\u5728 a ~ b\u8FD9\u4E2A\u8303\u56F4\u5185\u65F6\uFF0C\u8FD4\u56DE\u503C\u5C5E\u4E8E[0, 1]\n */\n\nvar uninterpolateNumber = curry(function (a, b, x) {\n var diff = b - +a;\n diff = diff || Infinity;\n return (x - a) / diff;\n});\n/**\n * \u7EBF\u6027\u63D2\u503C\u7684\u9006\u8FD0\u7B97\uFF0C\u5E76\u4E14\u6709\u622A\u65AD\u7684\u64CD\u4F5C\n *\n * @param {Number} a \u5B9A\u4E49\u57DF\u7684\u6781\u70B9\n * @param {Number} b \u5B9A\u4E49\u57DF\u7684\u6781\u70B9\n * @param {Number} x \u53EF\u4EE5\u8BA4\u4E3A\u662F\u63D2\u503C\u540E\u7684\u4E00\u4E2A\u8F93\u51FA\u503C\n * @return {Number} \u5F53x\u5728 a ~ b\u8FD9\u4E2A\u533A\u95F4\u5185\u65F6\uFF0C\u8FD4\u56DE\u503C\u5C5E\u4E8E[0, 1]\uFF0C\n * \u5F53x\u4E0D\u5728 a ~ b\u8FD9\u4E2A\u533A\u95F4\u65F6\uFF0C\u4F1A\u622A\u65AD\u5230 a ~ b \u8FD9\u4E2A\u533A\u95F4\n */\n\nvar uninterpolateTruncation = curry(function (a, b, x) {\n var diff = b - +a;\n diff = diff || Infinity;\n return Math.max(0, Math.min(1, (x - a) / diff));\n});\nexport default {\n rangeStep: rangeStep,\n getDigitCount: getDigitCount,\n interpolateNumber: interpolateNumber,\n uninterpolateNumber: uninterpolateNumber,\n uninterpolateTruncation: uninterpolateTruncation\n};", "var _excluded = [\"offset\", \"layout\", \"width\", \"dataKey\", \"data\", \"dataPointFormatter\", \"xAxis\", \"yAxis\"];\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Render a group of error bar\n */\nimport React from 'react';\nimport invariant from 'tiny-invariant';\nimport { Layer } from '../container/Layer';\nimport { filterProps } from '../util/ReactUtils';\n// eslint-disable-next-line react/prefer-stateless-function -- requires static defaultProps\nexport var ErrorBar = /*#__PURE__*/function (_React$Component) {\n function ErrorBar() {\n _classCallCheck(this, ErrorBar);\n return _callSuper(this, ErrorBar, arguments);\n }\n _inherits(ErrorBar, _React$Component);\n return _createClass(ErrorBar, [{\n key: \"render\",\n value: function render() {\n var _this$props = this.props,\n offset = _this$props.offset,\n layout = _this$props.layout,\n width = _this$props.width,\n dataKey = _this$props.dataKey,\n data = _this$props.data,\n dataPointFormatter = _this$props.dataPointFormatter,\n xAxis = _this$props.xAxis,\n yAxis = _this$props.yAxis,\n others = _objectWithoutProperties(_this$props, _excluded);\n var svgProps = filterProps(others, false);\n !!(this.props.direction === 'x' && xAxis.type !== 'number') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'ErrorBar requires Axis type property to be \"number\".') : invariant(false) : void 0;\n var errorBars = data.map(function (entry) {\n var _dataPointFormatter = dataPointFormatter(entry, dataKey),\n x = _dataPointFormatter.x,\n y = _dataPointFormatter.y,\n value = _dataPointFormatter.value,\n errorVal = _dataPointFormatter.errorVal;\n if (!errorVal) {\n return null;\n }\n var lineCoordinates = [];\n var lowBound, highBound;\n if (Array.isArray(errorVal)) {\n var _errorVal = _slicedToArray(errorVal, 2);\n lowBound = _errorVal[0];\n highBound = _errorVal[1];\n } else {\n lowBound = highBound = errorVal;\n }\n if (layout === 'vertical') {\n // error bar for horizontal charts, the y is fixed, x is a range value\n var scale = xAxis.scale;\n var yMid = y + offset;\n var yMin = yMid + width;\n var yMax = yMid - width;\n var xMin = scale(value - lowBound);\n var xMax = scale(value + highBound);\n\n // the right line of |--|\n lineCoordinates.push({\n x1: xMax,\n y1: yMin,\n x2: xMax,\n y2: yMax\n });\n // the middle line of |--|\n lineCoordinates.push({\n x1: xMin,\n y1: yMid,\n x2: xMax,\n y2: yMid\n });\n // the left line of |--|\n lineCoordinates.push({\n x1: xMin,\n y1: yMin,\n x2: xMin,\n y2: yMax\n });\n } else if (layout === 'horizontal') {\n // error bar for horizontal charts, the x is fixed, y is a range value\n var _scale = yAxis.scale;\n var xMid = x + offset;\n var _xMin = xMid - width;\n var _xMax = xMid + width;\n var _yMin = _scale(value - lowBound);\n var _yMax = _scale(value + highBound);\n\n // the top line\n lineCoordinates.push({\n x1: _xMin,\n y1: _yMax,\n x2: _xMax,\n y2: _yMax\n });\n // the middle line\n lineCoordinates.push({\n x1: xMid,\n y1: _yMin,\n x2: xMid,\n y2: _yMax\n });\n // the bottom line\n lineCoordinates.push({\n x1: _xMin,\n y1: _yMin,\n x2: _xMax,\n y2: _yMin\n });\n }\n return /*#__PURE__*/React.createElement(Layer, _extends({\n className: \"recharts-errorBar\",\n key: \"bar-\".concat(lineCoordinates.map(function (c) {\n return \"\".concat(c.x1, \"-\").concat(c.x2, \"-\").concat(c.y1, \"-\").concat(c.y2);\n }))\n }, svgProps), lineCoordinates.map(function (coordinates) {\n return /*#__PURE__*/React.createElement(\"line\", _extends({}, coordinates, {\n key: \"line-\".concat(coordinates.x1, \"-\").concat(coordinates.x2, \"-\").concat(coordinates.y1, \"-\").concat(coordinates.y2)\n }));\n }));\n });\n return /*#__PURE__*/React.createElement(Layer, {\n className: \"recharts-errorBars\"\n }, errorBars);\n }\n }]);\n}(React.Component);\n_defineProperty(ErrorBar, \"defaultProps\", {\n stroke: 'black',\n strokeWidth: 1.5,\n width: 5,\n offset: 0,\n layout: 'horizontal'\n});\n_defineProperty(ErrorBar, \"displayName\", 'ErrorBar');", "var isProduction = process.env.NODE_ENV === 'production';\nvar prefix = 'Invariant failed';\nfunction invariant(condition, message) {\n if (condition) {\n return;\n }\n if (isProduction) {\n throw new Error(prefix);\n }\n var provided = typeof message === 'function' ? message() : message;\n var value = provided ? \"\".concat(prefix, \": \").concat(provided) : prefix;\n throw new Error(value);\n}\n\nexport { invariant as default };\n", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nimport { Legend } from '../component/Legend';\nimport { getMainColorOfGraphicItem } from './ChartUtils';\nimport { findChildByType } from './ReactUtils';\nexport var getLegendProps = function getLegendProps(_ref) {\n var children = _ref.children,\n formattedGraphicalItems = _ref.formattedGraphicalItems,\n legendWidth = _ref.legendWidth,\n legendContent = _ref.legendContent;\n var legendItem = findChildByType(children, Legend);\n if (!legendItem) {\n return null;\n }\n var legendDefaultProps = Legend.defaultProps;\n var legendProps = legendDefaultProps !== undefined ? _objectSpread(_objectSpread({}, legendDefaultProps), legendItem.props) : {};\n var legendData;\n if (legendItem.props && legendItem.props.payload) {\n legendData = legendItem.props && legendItem.props.payload;\n } else if (legendContent === 'children') {\n legendData = (formattedGraphicalItems || []).reduce(function (result, _ref2) {\n var item = _ref2.item,\n props = _ref2.props;\n var data = props.sectors || props.data || [];\n return result.concat(data.map(function (entry) {\n return {\n type: legendItem.props.iconType || item.props.legendType,\n value: entry.name,\n color: entry.fill,\n payload: entry\n };\n }));\n }, []);\n } else {\n legendData = (formattedGraphicalItems || []).map(function (_ref3) {\n var item = _ref3.item;\n var itemDefaultProps = item.type.defaultProps;\n var itemProps = itemDefaultProps !== undefined ? _objectSpread(_objectSpread({}, itemDefaultProps), item.props) : {};\n var dataKey = itemProps.dataKey,\n name = itemProps.name,\n legendType = itemProps.legendType,\n hide = itemProps.hide;\n return {\n inactive: hide,\n dataKey: dataKey,\n type: legendProps.iconType || legendType || 'square',\n color: getMainColorOfGraphicItem(item),\n value: name || dataKey,\n // @ts-expect-error property strokeDasharray is required in Payload but optional in props\n payload: itemProps\n };\n });\n }\n return _objectSpread(_objectSpread(_objectSpread({}, legendProps), Legend.getWithHeight(legendItem, legendWidth)), {}, {\n payload: legendData,\n item: legendItem\n });\n};", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nvar _excluded = [\"valueAccessor\"],\n _excluded2 = [\"data\", \"dataKey\", \"clockWise\", \"id\", \"textBreakAll\"];\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\nimport React, { cloneElement } from 'react';\nimport isNil from 'lodash/isNil';\nimport isObject from 'lodash/isObject';\nimport isFunction from 'lodash/isFunction';\nimport last from 'lodash/last';\nimport { Label } from './Label';\nimport { Layer } from '../container/Layer';\nimport { findAllByType, filterProps } from '../util/ReactUtils';\nimport { getValueByDataKey } from '../util/ChartUtils';\nvar defaultAccessor = function defaultAccessor(entry) {\n return Array.isArray(entry.value) ? last(entry.value) : entry.value;\n};\nexport function LabelList(_ref) {\n var _ref$valueAccessor = _ref.valueAccessor,\n valueAccessor = _ref$valueAccessor === void 0 ? defaultAccessor : _ref$valueAccessor,\n restProps = _objectWithoutProperties(_ref, _excluded);\n var data = restProps.data,\n dataKey = restProps.dataKey,\n clockWise = restProps.clockWise,\n id = restProps.id,\n textBreakAll = restProps.textBreakAll,\n others = _objectWithoutProperties(restProps, _excluded2);\n if (!data || !data.length) {\n return null;\n }\n return /*#__PURE__*/React.createElement(Layer, {\n className: \"recharts-label-list\"\n }, data.map(function (entry, index) {\n var value = isNil(dataKey) ? valueAccessor(entry, index) : getValueByDataKey(entry && entry.payload, dataKey);\n var idProps = isNil(id) ? {} : {\n id: \"\".concat(id, \"-\").concat(index)\n };\n return /*#__PURE__*/React.createElement(Label, _extends({}, filterProps(entry, true), others, idProps, {\n parentViewBox: entry.parentViewBox,\n value: value,\n textBreakAll: textBreakAll,\n viewBox: Label.parseViewBox(isNil(clockWise) ? entry : _objectSpread(_objectSpread({}, entry), {}, {\n clockWise: clockWise\n })),\n key: \"label-\".concat(index) // eslint-disable-line react/no-array-index-key\n ,\n index: index\n }));\n }));\n}\nLabelList.displayName = 'LabelList';\nfunction parseLabelList(label, data) {\n if (!label) {\n return null;\n }\n if (label === true) {\n return /*#__PURE__*/React.createElement(LabelList, {\n key: \"labelList-implicit\",\n data: data\n });\n }\n if ( /*#__PURE__*/React.isValidElement(label) || isFunction(label)) {\n return /*#__PURE__*/React.createElement(LabelList, {\n key: \"labelList-implicit\",\n data: data,\n content: label\n });\n }\n if (isObject(label)) {\n return /*#__PURE__*/React.createElement(LabelList, _extends({\n data: data\n }, label, {\n key: \"labelList-implicit\"\n }));\n }\n return null;\n}\nfunction renderCallByParent(parentProps, data) {\n var checkPropsLabel = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n if (!parentProps || !parentProps.children && checkPropsLabel && !parentProps.label) {\n return null;\n }\n var children = parentProps.children;\n var explicitChildren = findAllByType(children, LabelList).map(function (child, index) {\n return /*#__PURE__*/cloneElement(child, {\n data: data,\n // eslint-disable-next-line react/no-array-index-key\n key: \"labelList-\".concat(index)\n });\n });\n if (!checkPropsLabel) {\n return explicitChildren;\n }\n var implicitLabelList = parseLabelList(parentProps.label, data);\n return [implicitLabelList].concat(_toConsumableArray(explicitChildren));\n}\nLabelList.renderCallByParent = renderCallByParent;", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Sector\n */\nimport React from 'react';\nimport clsx from 'clsx';\nimport { filterProps } from '../util/ReactUtils';\nimport { polarToCartesian, RADIAN } from '../util/PolarUtils';\nimport { getPercentValue, mathSign } from '../util/DataUtils';\nvar getDeltaAngle = function getDeltaAngle(startAngle, endAngle) {\n var sign = mathSign(endAngle - startAngle);\n var deltaAngle = Math.min(Math.abs(endAngle - startAngle), 359.999);\n return sign * deltaAngle;\n};\nvar getTangentCircle = function getTangentCircle(_ref) {\n var cx = _ref.cx,\n cy = _ref.cy,\n radius = _ref.radius,\n angle = _ref.angle,\n sign = _ref.sign,\n isExternal = _ref.isExternal,\n cornerRadius = _ref.cornerRadius,\n cornerIsExternal = _ref.cornerIsExternal;\n var centerRadius = cornerRadius * (isExternal ? 1 : -1) + radius;\n var theta = Math.asin(cornerRadius / centerRadius) / RADIAN;\n var centerAngle = cornerIsExternal ? angle : angle + sign * theta;\n var center = polarToCartesian(cx, cy, centerRadius, centerAngle);\n // The coordinate of point which is tangent to the circle\n var circleTangency = polarToCartesian(cx, cy, radius, centerAngle);\n // The coordinate of point which is tangent to the radius line\n var lineTangencyAngle = cornerIsExternal ? angle - sign * theta : angle;\n var lineTangency = polarToCartesian(cx, cy, centerRadius * Math.cos(theta * RADIAN), lineTangencyAngle);\n return {\n center: center,\n circleTangency: circleTangency,\n lineTangency: lineTangency,\n theta: theta\n };\n};\nvar getSectorPath = function getSectorPath(_ref2) {\n var cx = _ref2.cx,\n cy = _ref2.cy,\n innerRadius = _ref2.innerRadius,\n outerRadius = _ref2.outerRadius,\n startAngle = _ref2.startAngle,\n endAngle = _ref2.endAngle;\n var angle = getDeltaAngle(startAngle, endAngle);\n\n // When the angle of sector equals to 360, star point and end point coincide\n var tempEndAngle = startAngle + angle;\n var outerStartPoint = polarToCartesian(cx, cy, outerRadius, startAngle);\n var outerEndPoint = polarToCartesian(cx, cy, outerRadius, tempEndAngle);\n var path = \"M \".concat(outerStartPoint.x, \",\").concat(outerStartPoint.y, \"\\n A \").concat(outerRadius, \",\").concat(outerRadius, \",0,\\n \").concat(+(Math.abs(angle) > 180), \",\").concat(+(startAngle > tempEndAngle), \",\\n \").concat(outerEndPoint.x, \",\").concat(outerEndPoint.y, \"\\n \");\n if (innerRadius > 0) {\n var innerStartPoint = polarToCartesian(cx, cy, innerRadius, startAngle);\n var innerEndPoint = polarToCartesian(cx, cy, innerRadius, tempEndAngle);\n path += \"L \".concat(innerEndPoint.x, \",\").concat(innerEndPoint.y, \"\\n A \").concat(innerRadius, \",\").concat(innerRadius, \",0,\\n \").concat(+(Math.abs(angle) > 180), \",\").concat(+(startAngle <= tempEndAngle), \",\\n \").concat(innerStartPoint.x, \",\").concat(innerStartPoint.y, \" Z\");\n } else {\n path += \"L \".concat(cx, \",\").concat(cy, \" Z\");\n }\n return path;\n};\nvar getSectorWithCorner = function getSectorWithCorner(_ref3) {\n var cx = _ref3.cx,\n cy = _ref3.cy,\n innerRadius = _ref3.innerRadius,\n outerRadius = _ref3.outerRadius,\n cornerRadius = _ref3.cornerRadius,\n forceCornerRadius = _ref3.forceCornerRadius,\n cornerIsExternal = _ref3.cornerIsExternal,\n startAngle = _ref3.startAngle,\n endAngle = _ref3.endAngle;\n var sign = mathSign(endAngle - startAngle);\n var _getTangentCircle = getTangentCircle({\n cx: cx,\n cy: cy,\n radius: outerRadius,\n angle: startAngle,\n sign: sign,\n cornerRadius: cornerRadius,\n cornerIsExternal: cornerIsExternal\n }),\n soct = _getTangentCircle.circleTangency,\n solt = _getTangentCircle.lineTangency,\n sot = _getTangentCircle.theta;\n var _getTangentCircle2 = getTangentCircle({\n cx: cx,\n cy: cy,\n radius: outerRadius,\n angle: endAngle,\n sign: -sign,\n cornerRadius: cornerRadius,\n cornerIsExternal: cornerIsExternal\n }),\n eoct = _getTangentCircle2.circleTangency,\n eolt = _getTangentCircle2.lineTangency,\n eot = _getTangentCircle2.theta;\n var outerArcAngle = cornerIsExternal ? Math.abs(startAngle - endAngle) : Math.abs(startAngle - endAngle) - sot - eot;\n if (outerArcAngle < 0) {\n if (forceCornerRadius) {\n return \"M \".concat(solt.x, \",\").concat(solt.y, \"\\n a\").concat(cornerRadius, \",\").concat(cornerRadius, \",0,0,1,\").concat(cornerRadius * 2, \",0\\n a\").concat(cornerRadius, \",\").concat(cornerRadius, \",0,0,1,\").concat(-cornerRadius * 2, \",0\\n \");\n }\n return getSectorPath({\n cx: cx,\n cy: cy,\n innerRadius: innerRadius,\n outerRadius: outerRadius,\n startAngle: startAngle,\n endAngle: endAngle\n });\n }\n var path = \"M \".concat(solt.x, \",\").concat(solt.y, \"\\n A\").concat(cornerRadius, \",\").concat(cornerRadius, \",0,0,\").concat(+(sign < 0), \",\").concat(soct.x, \",\").concat(soct.y, \"\\n A\").concat(outerRadius, \",\").concat(outerRadius, \",0,\").concat(+(outerArcAngle > 180), \",\").concat(+(sign < 0), \",\").concat(eoct.x, \",\").concat(eoct.y, \"\\n A\").concat(cornerRadius, \",\").concat(cornerRadius, \",0,0,\").concat(+(sign < 0), \",\").concat(eolt.x, \",\").concat(eolt.y, \"\\n \");\n if (innerRadius > 0) {\n var _getTangentCircle3 = getTangentCircle({\n cx: cx,\n cy: cy,\n radius: innerRadius,\n angle: startAngle,\n sign: sign,\n isExternal: true,\n cornerRadius: cornerRadius,\n cornerIsExternal: cornerIsExternal\n }),\n sict = _getTangentCircle3.circleTangency,\n silt = _getTangentCircle3.lineTangency,\n sit = _getTangentCircle3.theta;\n var _getTangentCircle4 = getTangentCircle({\n cx: cx,\n cy: cy,\n radius: innerRadius,\n angle: endAngle,\n sign: -sign,\n isExternal: true,\n cornerRadius: cornerRadius,\n cornerIsExternal: cornerIsExternal\n }),\n eict = _getTangentCircle4.circleTangency,\n eilt = _getTangentCircle4.lineTangency,\n eit = _getTangentCircle4.theta;\n var innerArcAngle = cornerIsExternal ? Math.abs(startAngle - endAngle) : Math.abs(startAngle - endAngle) - sit - eit;\n if (innerArcAngle < 0 && cornerRadius === 0) {\n return \"\".concat(path, \"L\").concat(cx, \",\").concat(cy, \"Z\");\n }\n path += \"L\".concat(eilt.x, \",\").concat(eilt.y, \"\\n A\").concat(cornerRadius, \",\").concat(cornerRadius, \",0,0,\").concat(+(sign < 0), \",\").concat(eict.x, \",\").concat(eict.y, \"\\n A\").concat(innerRadius, \",\").concat(innerRadius, \",0,\").concat(+(innerArcAngle > 180), \",\").concat(+(sign > 0), \",\").concat(sict.x, \",\").concat(sict.y, \"\\n A\").concat(cornerRadius, \",\").concat(cornerRadius, \",0,0,\").concat(+(sign < 0), \",\").concat(silt.x, \",\").concat(silt.y, \"Z\");\n } else {\n path += \"L\".concat(cx, \",\").concat(cy, \"Z\");\n }\n return path;\n};\nvar defaultProps = {\n cx: 0,\n cy: 0,\n innerRadius: 0,\n outerRadius: 0,\n startAngle: 0,\n endAngle: 0,\n cornerRadius: 0,\n forceCornerRadius: false,\n cornerIsExternal: false\n};\nexport var Sector = function Sector(sectorProps) {\n var props = _objectSpread(_objectSpread({}, defaultProps), sectorProps);\n var cx = props.cx,\n cy = props.cy,\n innerRadius = props.innerRadius,\n outerRadius = props.outerRadius,\n cornerRadius = props.cornerRadius,\n forceCornerRadius = props.forceCornerRadius,\n cornerIsExternal = props.cornerIsExternal,\n startAngle = props.startAngle,\n endAngle = props.endAngle,\n className = props.className;\n if (outerRadius < innerRadius || startAngle === endAngle) {\n return null;\n }\n var layerClass = clsx('recharts-sector', className);\n var deltaRadius = outerRadius - innerRadius;\n var cr = getPercentValue(cornerRadius, deltaRadius, 0, true);\n var path;\n if (cr > 0 && Math.abs(startAngle - endAngle) < 360) {\n path = getSectorWithCorner({\n cx: cx,\n cy: cy,\n innerRadius: innerRadius,\n outerRadius: outerRadius,\n cornerRadius: Math.min(cr, deltaRadius / 2),\n forceCornerRadius: forceCornerRadius,\n cornerIsExternal: cornerIsExternal,\n startAngle: startAngle,\n endAngle: endAngle\n });\n } else {\n path = getSectorPath({\n cx: cx,\n cy: cy,\n innerRadius: innerRadius,\n outerRadius: outerRadius,\n startAngle: startAngle,\n endAngle: endAngle\n });\n }\n return /*#__PURE__*/React.createElement(\"path\", _extends({}, filterProps(props, true), {\n className: layerClass,\n d: path,\n role: \"img\"\n }));\n};", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Curve\n */\nimport * as React from 'react';\nimport { line as shapeLine, area as shapeArea, curveBasisClosed, curveBasisOpen, curveBasis, curveBumpX, curveBumpY, curveLinearClosed, curveLinear, curveMonotoneX, curveMonotoneY, curveNatural, curveStep, curveStepAfter, curveStepBefore } from 'victory-vendor/d3-shape';\nimport upperFirst from 'lodash/upperFirst';\nimport isFunction from 'lodash/isFunction';\nimport clsx from 'clsx';\nimport { adaptEventHandlers } from '../util/types';\nimport { filterProps } from '../util/ReactUtils';\nimport { isNumber } from '../util/DataUtils';\nvar CURVE_FACTORIES = {\n curveBasisClosed: curveBasisClosed,\n curveBasisOpen: curveBasisOpen,\n curveBasis: curveBasis,\n curveBumpX: curveBumpX,\n curveBumpY: curveBumpY,\n curveLinearClosed: curveLinearClosed,\n curveLinear: curveLinear,\n curveMonotoneX: curveMonotoneX,\n curveMonotoneY: curveMonotoneY,\n curveNatural: curveNatural,\n curveStep: curveStep,\n curveStepAfter: curveStepAfter,\n curveStepBefore: curveStepBefore\n};\nvar defined = function defined(p) {\n return p.x === +p.x && p.y === +p.y;\n};\nvar getX = function getX(p) {\n return p.x;\n};\nvar getY = function getY(p) {\n return p.y;\n};\nvar getCurveFactory = function getCurveFactory(type, layout) {\n if (isFunction(type)) {\n return type;\n }\n var name = \"curve\".concat(upperFirst(type));\n if ((name === 'curveMonotone' || name === 'curveBump') && layout) {\n return CURVE_FACTORIES[\"\".concat(name).concat(layout === 'vertical' ? 'Y' : 'X')];\n }\n return CURVE_FACTORIES[name] || curveLinear;\n};\n/**\n * Calculate the path of curve. Returns null if points is an empty array.\n * @return path or null\n */\nexport var getPath = function getPath(_ref) {\n var _ref$type = _ref.type,\n type = _ref$type === void 0 ? 'linear' : _ref$type,\n _ref$points = _ref.points,\n points = _ref$points === void 0 ? [] : _ref$points,\n baseLine = _ref.baseLine,\n layout = _ref.layout,\n _ref$connectNulls = _ref.connectNulls,\n connectNulls = _ref$connectNulls === void 0 ? false : _ref$connectNulls;\n var curveFactory = getCurveFactory(type, layout);\n var formatPoints = connectNulls ? points.filter(function (entry) {\n return defined(entry);\n }) : points;\n var lineFunction;\n if (Array.isArray(baseLine)) {\n var formatBaseLine = connectNulls ? baseLine.filter(function (base) {\n return defined(base);\n }) : baseLine;\n var areaPoints = formatPoints.map(function (entry, index) {\n return _objectSpread(_objectSpread({}, entry), {}, {\n base: formatBaseLine[index]\n });\n });\n if (layout === 'vertical') {\n lineFunction = shapeArea().y(getY).x1(getX).x0(function (d) {\n return d.base.x;\n });\n } else {\n lineFunction = shapeArea().x(getX).y1(getY).y0(function (d) {\n return d.base.y;\n });\n }\n lineFunction.defined(defined).curve(curveFactory);\n return lineFunction(areaPoints);\n }\n if (layout === 'vertical' && isNumber(baseLine)) {\n lineFunction = shapeArea().y(getY).x1(getX).x0(baseLine);\n } else if (isNumber(baseLine)) {\n lineFunction = shapeArea().x(getX).y1(getY).y0(baseLine);\n } else {\n lineFunction = shapeLine().x(getX).y(getY);\n }\n lineFunction.defined(defined).curve(curveFactory);\n return lineFunction(formatPoints);\n};\nexport var Curve = function Curve(props) {\n var className = props.className,\n points = props.points,\n path = props.path,\n pathRef = props.pathRef;\n if ((!points || !points.length) && !path) {\n return null;\n }\n var realPath = points && points.length ? getPath(props) : path;\n return /*#__PURE__*/React.createElement(\"path\", _extends({}, filterProps(props, false), adaptEventHandlers(props), {\n className: clsx('recharts-curve', className),\n d: realPath,\n ref: pathRef\n }));\n};", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Rectangle\n */\nimport React, { useEffect, useRef, useState } from 'react';\nimport clsx from 'clsx';\nimport Animate from 'react-smooth';\nimport { filterProps } from '../util/ReactUtils';\nvar getRectanglePath = function getRectanglePath(x, y, width, height, radius) {\n var maxRadius = Math.min(Math.abs(width) / 2, Math.abs(height) / 2);\n var ySign = height >= 0 ? 1 : -1;\n var xSign = width >= 0 ? 1 : -1;\n var clockWise = height >= 0 && width >= 0 || height < 0 && width < 0 ? 1 : 0;\n var path;\n if (maxRadius > 0 && radius instanceof Array) {\n var newRadius = [0, 0, 0, 0];\n for (var i = 0, len = 4; i < len; i++) {\n newRadius[i] = radius[i] > maxRadius ? maxRadius : radius[i];\n }\n path = \"M\".concat(x, \",\").concat(y + ySign * newRadius[0]);\n if (newRadius[0] > 0) {\n path += \"A \".concat(newRadius[0], \",\").concat(newRadius[0], \",0,0,\").concat(clockWise, \",\").concat(x + xSign * newRadius[0], \",\").concat(y);\n }\n path += \"L \".concat(x + width - xSign * newRadius[1], \",\").concat(y);\n if (newRadius[1] > 0) {\n path += \"A \".concat(newRadius[1], \",\").concat(newRadius[1], \",0,0,\").concat(clockWise, \",\\n \").concat(x + width, \",\").concat(y + ySign * newRadius[1]);\n }\n path += \"L \".concat(x + width, \",\").concat(y + height - ySign * newRadius[2]);\n if (newRadius[2] > 0) {\n path += \"A \".concat(newRadius[2], \",\").concat(newRadius[2], \",0,0,\").concat(clockWise, \",\\n \").concat(x + width - xSign * newRadius[2], \",\").concat(y + height);\n }\n path += \"L \".concat(x + xSign * newRadius[3], \",\").concat(y + height);\n if (newRadius[3] > 0) {\n path += \"A \".concat(newRadius[3], \",\").concat(newRadius[3], \",0,0,\").concat(clockWise, \",\\n \").concat(x, \",\").concat(y + height - ySign * newRadius[3]);\n }\n path += 'Z';\n } else if (maxRadius > 0 && radius === +radius && radius > 0) {\n var _newRadius = Math.min(maxRadius, radius);\n path = \"M \".concat(x, \",\").concat(y + ySign * _newRadius, \"\\n A \").concat(_newRadius, \",\").concat(_newRadius, \",0,0,\").concat(clockWise, \",\").concat(x + xSign * _newRadius, \",\").concat(y, \"\\n L \").concat(x + width - xSign * _newRadius, \",\").concat(y, \"\\n A \").concat(_newRadius, \",\").concat(_newRadius, \",0,0,\").concat(clockWise, \",\").concat(x + width, \",\").concat(y + ySign * _newRadius, \"\\n L \").concat(x + width, \",\").concat(y + height - ySign * _newRadius, \"\\n A \").concat(_newRadius, \",\").concat(_newRadius, \",0,0,\").concat(clockWise, \",\").concat(x + width - xSign * _newRadius, \",\").concat(y + height, \"\\n L \").concat(x + xSign * _newRadius, \",\").concat(y + height, \"\\n A \").concat(_newRadius, \",\").concat(_newRadius, \",0,0,\").concat(clockWise, \",\").concat(x, \",\").concat(y + height - ySign * _newRadius, \" Z\");\n } else {\n path = \"M \".concat(x, \",\").concat(y, \" h \").concat(width, \" v \").concat(height, \" h \").concat(-width, \" Z\");\n }\n return path;\n};\nexport var isInRectangle = function isInRectangle(point, rect) {\n if (!point || !rect) {\n return false;\n }\n var px = point.x,\n py = point.y;\n var x = rect.x,\n y = rect.y,\n width = rect.width,\n height = rect.height;\n if (Math.abs(width) > 0 && Math.abs(height) > 0) {\n var minX = Math.min(x, x + width);\n var maxX = Math.max(x, x + width);\n var minY = Math.min(y, y + height);\n var maxY = Math.max(y, y + height);\n return px >= minX && px <= maxX && py >= minY && py <= maxY;\n }\n return false;\n};\nvar defaultProps = {\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n // The radius of border\n // The radius of four corners when radius is a number\n // The radius of left-top, right-top, right-bottom, left-bottom when radius is an array\n radius: 0,\n isAnimationActive: false,\n isUpdateAnimationActive: false,\n animationBegin: 0,\n animationDuration: 1500,\n animationEasing: 'ease'\n};\nexport var Rectangle = function Rectangle(rectangleProps) {\n var props = _objectSpread(_objectSpread({}, defaultProps), rectangleProps);\n var pathRef = useRef();\n var _useState = useState(-1),\n _useState2 = _slicedToArray(_useState, 2),\n totalLength = _useState2[0],\n setTotalLength = _useState2[1];\n useEffect(function () {\n if (pathRef.current && pathRef.current.getTotalLength) {\n try {\n var pathTotalLength = pathRef.current.getTotalLength();\n if (pathTotalLength) {\n setTotalLength(pathTotalLength);\n }\n } catch (err) {\n // calculate total length error\n }\n }\n }, []);\n var x = props.x,\n y = props.y,\n width = props.width,\n height = props.height,\n radius = props.radius,\n className = props.className;\n var animationEasing = props.animationEasing,\n animationDuration = props.animationDuration,\n animationBegin = props.animationBegin,\n isAnimationActive = props.isAnimationActive,\n isUpdateAnimationActive = props.isUpdateAnimationActive;\n if (x !== +x || y !== +y || width !== +width || height !== +height || width === 0 || height === 0) {\n return null;\n }\n var layerClass = clsx('recharts-rectangle', className);\n if (!isUpdateAnimationActive) {\n return /*#__PURE__*/React.createElement(\"path\", _extends({}, filterProps(props, true), {\n className: layerClass,\n d: getRectanglePath(x, y, width, height, radius)\n }));\n }\n return /*#__PURE__*/React.createElement(Animate, {\n canBegin: totalLength > 0,\n from: {\n width: width,\n height: height,\n x: x,\n y: y\n },\n to: {\n width: width,\n height: height,\n x: x,\n y: y\n },\n duration: animationDuration,\n animationEasing: animationEasing,\n isActive: isUpdateAnimationActive\n }, function (_ref) {\n var currWidth = _ref.width,\n currHeight = _ref.height,\n currX = _ref.x,\n currY = _ref.y;\n return /*#__PURE__*/React.createElement(Animate, {\n canBegin: totalLength > 0,\n from: \"0px \".concat(totalLength === -1 ? 1 : totalLength, \"px\"),\n to: \"\".concat(totalLength, \"px 0px\"),\n attributeName: \"strokeDasharray\",\n begin: animationBegin,\n duration: animationDuration,\n isActive: isAnimationActive,\n easing: animationEasing\n }, /*#__PURE__*/React.createElement(\"path\", _extends({}, filterProps(props, true), {\n className: layerClass,\n d: getRectanglePath(currX, currY, currWidth, currHeight, radius),\n ref: pathRef\n })));\n });\n};", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nvar _excluded = [\"children\", \"begin\", \"duration\", \"attributeName\", \"easing\", \"isActive\", \"steps\", \"from\", \"to\", \"canBegin\", \"onAnimationEnd\", \"shouldReAnimate\", \"onAnimationReStart\"];\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nimport React, { PureComponent, cloneElement, Children } from 'react';\nimport PropTypes from 'prop-types';\nimport { deepEqual } from 'fast-equals';\nimport createAnimateManager from './AnimateManager';\nimport { configEasing } from './easing';\nimport configUpdate from './configUpdate';\nimport { getTransitionVal, identity } from './util';\nvar Animate = /*#__PURE__*/function (_PureComponent) {\n _inherits(Animate, _PureComponent);\n var _super = _createSuper(Animate);\n function Animate(props, context) {\n var _this;\n _classCallCheck(this, Animate);\n _this = _super.call(this, props, context);\n var _this$props = _this.props,\n isActive = _this$props.isActive,\n attributeName = _this$props.attributeName,\n from = _this$props.from,\n to = _this$props.to,\n steps = _this$props.steps,\n children = _this$props.children,\n duration = _this$props.duration;\n _this.handleStyleChange = _this.handleStyleChange.bind(_assertThisInitialized(_this));\n _this.changeStyle = _this.changeStyle.bind(_assertThisInitialized(_this));\n if (!isActive || duration <= 0) {\n _this.state = {\n style: {}\n };\n\n // if children is a function and animation is not active, set style to 'to'\n if (typeof children === 'function') {\n _this.state = {\n style: to\n };\n }\n return _possibleConstructorReturn(_this);\n }\n if (steps && steps.length) {\n _this.state = {\n style: steps[0].style\n };\n } else if (from) {\n if (typeof children === 'function') {\n _this.state = {\n style: from\n };\n return _possibleConstructorReturn(_this);\n }\n _this.state = {\n style: attributeName ? _defineProperty({}, attributeName, from) : from\n };\n } else {\n _this.state = {\n style: {}\n };\n }\n return _this;\n }\n _createClass(Animate, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n var _this$props2 = this.props,\n isActive = _this$props2.isActive,\n canBegin = _this$props2.canBegin;\n this.mounted = true;\n if (!isActive || !canBegin) {\n return;\n }\n this.runAnimation(this.props);\n }\n }, {\n key: \"componentDidUpdate\",\n value: function componentDidUpdate(prevProps) {\n var _this$props3 = this.props,\n isActive = _this$props3.isActive,\n canBegin = _this$props3.canBegin,\n attributeName = _this$props3.attributeName,\n shouldReAnimate = _this$props3.shouldReAnimate,\n to = _this$props3.to,\n currentFrom = _this$props3.from;\n var style = this.state.style;\n if (!canBegin) {\n return;\n }\n if (!isActive) {\n var newState = {\n style: attributeName ? _defineProperty({}, attributeName, to) : to\n };\n if (this.state && style) {\n if (attributeName && style[attributeName] !== to || !attributeName && style !== to) {\n // eslint-disable-next-line react/no-did-update-set-state\n this.setState(newState);\n }\n }\n return;\n }\n if (deepEqual(prevProps.to, to) && prevProps.canBegin && prevProps.isActive) {\n return;\n }\n var isTriggered = !prevProps.canBegin || !prevProps.isActive;\n if (this.manager) {\n this.manager.stop();\n }\n if (this.stopJSAnimation) {\n this.stopJSAnimation();\n }\n var from = isTriggered || shouldReAnimate ? currentFrom : prevProps.to;\n if (this.state && style) {\n var _newState = {\n style: attributeName ? _defineProperty({}, attributeName, from) : from\n };\n if (attributeName && style[attributeName] !== from || !attributeName && style !== from) {\n // eslint-disable-next-line react/no-did-update-set-state\n this.setState(_newState);\n }\n }\n this.runAnimation(_objectSpread(_objectSpread({}, this.props), {}, {\n from: from,\n begin: 0\n }));\n }\n }, {\n key: \"componentWillUnmount\",\n value: function componentWillUnmount() {\n this.mounted = false;\n var onAnimationEnd = this.props.onAnimationEnd;\n if (this.unSubscribe) {\n this.unSubscribe();\n }\n if (this.manager) {\n this.manager.stop();\n this.manager = null;\n }\n if (this.stopJSAnimation) {\n this.stopJSAnimation();\n }\n if (onAnimationEnd) {\n onAnimationEnd();\n }\n }\n }, {\n key: \"handleStyleChange\",\n value: function handleStyleChange(style) {\n this.changeStyle(style);\n }\n }, {\n key: \"changeStyle\",\n value: function changeStyle(style) {\n if (this.mounted) {\n this.setState({\n style: style\n });\n }\n }\n }, {\n key: \"runJSAnimation\",\n value: function runJSAnimation(props) {\n var _this2 = this;\n var from = props.from,\n to = props.to,\n duration = props.duration,\n easing = props.easing,\n begin = props.begin,\n onAnimationEnd = props.onAnimationEnd,\n onAnimationStart = props.onAnimationStart;\n var startAnimation = configUpdate(from, to, configEasing(easing), duration, this.changeStyle);\n var finalStartAnimation = function finalStartAnimation() {\n _this2.stopJSAnimation = startAnimation();\n };\n this.manager.start([onAnimationStart, begin, finalStartAnimation, duration, onAnimationEnd]);\n }\n }, {\n key: \"runStepAnimation\",\n value: function runStepAnimation(props) {\n var _this3 = this;\n var steps = props.steps,\n begin = props.begin,\n onAnimationStart = props.onAnimationStart;\n var _steps$ = steps[0],\n initialStyle = _steps$.style,\n _steps$$duration = _steps$.duration,\n initialTime = _steps$$duration === void 0 ? 0 : _steps$$duration;\n var addStyle = function addStyle(sequence, nextItem, index) {\n if (index === 0) {\n return sequence;\n }\n var duration = nextItem.duration,\n _nextItem$easing = nextItem.easing,\n easing = _nextItem$easing === void 0 ? 'ease' : _nextItem$easing,\n style = nextItem.style,\n nextProperties = nextItem.properties,\n onAnimationEnd = nextItem.onAnimationEnd;\n var preItem = index > 0 ? steps[index - 1] : nextItem;\n var properties = nextProperties || Object.keys(style);\n if (typeof easing === 'function' || easing === 'spring') {\n return [].concat(_toConsumableArray(sequence), [_this3.runJSAnimation.bind(_this3, {\n from: preItem.style,\n to: style,\n duration: duration,\n easing: easing\n }), duration]);\n }\n var transition = getTransitionVal(properties, duration, easing);\n var newStyle = _objectSpread(_objectSpread(_objectSpread({}, preItem.style), style), {}, {\n transition: transition\n });\n return [].concat(_toConsumableArray(sequence), [newStyle, duration, onAnimationEnd]).filter(identity);\n };\n return this.manager.start([onAnimationStart].concat(_toConsumableArray(steps.reduce(addStyle, [initialStyle, Math.max(initialTime, begin)])), [props.onAnimationEnd]));\n }\n }, {\n key: \"runAnimation\",\n value: function runAnimation(props) {\n if (!this.manager) {\n this.manager = createAnimateManager();\n }\n var begin = props.begin,\n duration = props.duration,\n attributeName = props.attributeName,\n propsTo = props.to,\n easing = props.easing,\n onAnimationStart = props.onAnimationStart,\n onAnimationEnd = props.onAnimationEnd,\n steps = props.steps,\n children = props.children;\n var manager = this.manager;\n this.unSubscribe = manager.subscribe(this.handleStyleChange);\n if (typeof easing === 'function' || typeof children === 'function' || easing === 'spring') {\n this.runJSAnimation(props);\n return;\n }\n if (steps.length > 1) {\n this.runStepAnimation(props);\n return;\n }\n var to = attributeName ? _defineProperty({}, attributeName, propsTo) : propsTo;\n var transition = getTransitionVal(Object.keys(to), duration, easing);\n manager.start([onAnimationStart, begin, _objectSpread(_objectSpread({}, to), {}, {\n transition: transition\n }), duration, onAnimationEnd]);\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this$props4 = this.props,\n children = _this$props4.children,\n begin = _this$props4.begin,\n duration = _this$props4.duration,\n attributeName = _this$props4.attributeName,\n easing = _this$props4.easing,\n isActive = _this$props4.isActive,\n steps = _this$props4.steps,\n from = _this$props4.from,\n to = _this$props4.to,\n canBegin = _this$props4.canBegin,\n onAnimationEnd = _this$props4.onAnimationEnd,\n shouldReAnimate = _this$props4.shouldReAnimate,\n onAnimationReStart = _this$props4.onAnimationReStart,\n others = _objectWithoutProperties(_this$props4, _excluded);\n var count = Children.count(children);\n // eslint-disable-next-line react/destructuring-assignment\n var stateStyle = this.state.style;\n if (typeof children === 'function') {\n return children(stateStyle);\n }\n if (!isActive || count === 0 || duration <= 0) {\n return children;\n }\n var cloneContainer = function cloneContainer(container) {\n var _container$props = container.props,\n _container$props$styl = _container$props.style,\n style = _container$props$styl === void 0 ? {} : _container$props$styl,\n className = _container$props.className;\n var res = /*#__PURE__*/cloneElement(container, _objectSpread(_objectSpread({}, others), {}, {\n style: _objectSpread(_objectSpread({}, style), stateStyle),\n className: className\n }));\n return res;\n };\n if (count === 1) {\n return cloneContainer(Children.only(children));\n }\n return /*#__PURE__*/React.createElement(\"div\", null, Children.map(children, function (child) {\n return cloneContainer(child);\n }));\n }\n }]);\n return Animate;\n}(PureComponent);\nAnimate.displayName = 'Animate';\nAnimate.defaultProps = {\n begin: 0,\n duration: 1000,\n from: '',\n to: '',\n attributeName: '',\n easing: 'ease',\n isActive: true,\n canBegin: true,\n steps: [],\n onAnimationEnd: function onAnimationEnd() {},\n onAnimationStart: function onAnimationStart() {}\n};\nAnimate.propTypes = {\n from: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),\n to: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),\n attributeName: PropTypes.string,\n // animation duration\n duration: PropTypes.number,\n begin: PropTypes.number,\n easing: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),\n steps: PropTypes.arrayOf(PropTypes.shape({\n duration: PropTypes.number.isRequired,\n style: PropTypes.object.isRequired,\n easing: PropTypes.oneOfType([PropTypes.oneOf(['ease', 'ease-in', 'ease-out', 'ease-in-out', 'linear']), PropTypes.func]),\n // transition css properties(dash case), optional\n properties: PropTypes.arrayOf('string'),\n onAnimationEnd: PropTypes.func\n })),\n children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),\n isActive: PropTypes.bool,\n canBegin: PropTypes.bool,\n onAnimationEnd: PropTypes.func,\n // decide if it should reanimate with initial from style when props change\n shouldReAnimate: PropTypes.bool,\n onAnimationStart: PropTypes.func,\n onAnimationReStart: PropTypes.func\n};\nexport default Animate;", "import type {\n AnyEqualityComparator,\n Cache,\n CircularState,\n Dictionary,\n State,\n TypeEqualityComparator,\n} from './internalTypes.js';\n\nconst { getOwnPropertyNames, getOwnPropertySymbols } = Object;\nconst { hasOwnProperty } = Object.prototype;\n\n/**\n * Combine two comparators into a single comparators.\n */\nexport function combineComparators(\n comparatorA: AnyEqualityComparator,\n comparatorB: AnyEqualityComparator,\n) {\n return function isEqual(a: A, b: B, state: State) {\n return comparatorA(a, b, state) && comparatorB(a, b, state);\n };\n}\n\n/**\n * Wrap the provided `areItemsEqual` method to manage the circular state, allowing\n * for circular references to be safely included in the comparison without creating\n * stack overflows.\n */\nexport function createIsCircular<\n AreItemsEqual extends TypeEqualityComparator,\n>(areItemsEqual: AreItemsEqual): AreItemsEqual {\n return function isCircular(\n a: any,\n b: any,\n state: CircularState>,\n ) {\n if (!a || !b || typeof a !== 'object' || typeof b !== 'object') {\n return areItemsEqual(a, b, state);\n }\n\n const { cache } = state;\n\n const cachedA = cache.get(a);\n const cachedB = cache.get(b);\n\n if (cachedA && cachedB) {\n return cachedA === b && cachedB === a;\n }\n\n cache.set(a, b);\n cache.set(b, a);\n\n const result = areItemsEqual(a, b, state);\n\n cache.delete(a);\n cache.delete(b);\n\n return result;\n } as AreItemsEqual;\n}\n\n/**\n * Get the `@@toStringTag` of the value, if it exists.\n */\nexport function getShortTag(value: any): string | undefined {\n return value != null ? value[Symbol.toStringTag] : undefined;\n}\n\n/**\n * Get the properties to strictly examine, which include both own properties that are\n * not enumerable and symbol properties.\n */\nexport function getStrictProperties(\n object: Dictionary,\n): Array {\n return (getOwnPropertyNames(object) as Array).concat(\n getOwnPropertySymbols(object),\n );\n}\n\n/**\n * Whether the object contains the property passed as an own property.\n */\nexport const hasOwn =\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n Object.hasOwn ||\n ((object: Dictionary, property: number | string | symbol) =>\n hasOwnProperty.call(object, property));\n\n/**\n * Whether the values passed are strictly equal or both NaN.\n */\nexport function sameValueZeroEqual(a: any, b: any): boolean {\n return a === b || (!a && !b && a !== a && b !== b);\n}\n", "import type {\n Dictionary,\n PrimitiveWrapper,\n State,\n TypedArray,\n} from './internalTypes.js';\nimport { getStrictProperties, hasOwn, sameValueZeroEqual } from './utils.js';\n\nconst PREACT_VNODE = '__v';\nconst PREACT_OWNER = '__o';\nconst REACT_OWNER = '_owner';\n\nconst { getOwnPropertyDescriptor, keys } = Object;\n\n/**\n * Whether the arrays are equal in value.\n */\nexport function areArraysEqual(a: any[], b: any[], state: State) {\n let index = a.length;\n\n if (b.length !== index) {\n return false;\n }\n\n while (index-- > 0) {\n if (!state.equals(a[index], b[index], index, index, a, b, state)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Whether the dates passed are equal in value.\n */\nexport function areDatesEqual(a: Date, b: Date): boolean {\n return sameValueZeroEqual(a.getTime(), b.getTime());\n}\n\n/**\n * Whether the errors passed are equal in value.\n */\nexport function areErrorsEqual(a: Error, b: Error): boolean {\n return (\n a.name === b.name &&\n a.message === b.message &&\n a.cause === b.cause &&\n a.stack === b.stack\n );\n}\n\n/**\n * Whether the functions passed are equal in value.\n */\nexport function areFunctionsEqual(\n a: (...args: any[]) => any,\n b: (...args: any[]) => any,\n): boolean {\n return a === b;\n}\n\n/**\n * Whether the `Map`s are equal in value.\n */\nexport function areMapsEqual(\n a: Map,\n b: Map,\n state: State,\n): boolean {\n const size = a.size;\n\n if (size !== b.size) {\n return false;\n }\n\n if (!size) {\n return true;\n }\n\n const matchedIndices = new Array(size);\n const aIterable = a.entries();\n\n let aResult: IteratorResult<[any, any]>;\n let bResult: IteratorResult<[any, any]>;\n let index = 0;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((aResult = aIterable.next())) {\n if (aResult.done) {\n break;\n }\n\n const bIterable = b.entries();\n\n let hasMatch = false;\n let matchIndex = 0;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((bResult = bIterable.next())) {\n if (bResult.done) {\n break;\n }\n\n if (matchedIndices[matchIndex]) {\n matchIndex++;\n continue;\n }\n\n const aEntry = aResult.value;\n const bEntry = bResult.value;\n\n if (\n state.equals(aEntry[0], bEntry[0], index, matchIndex, a, b, state) &&\n state.equals(aEntry[1], bEntry[1], aEntry[0], bEntry[0], a, b, state)\n ) {\n hasMatch = matchedIndices[matchIndex] = true;\n break;\n }\n\n matchIndex++;\n }\n\n if (!hasMatch) {\n return false;\n }\n\n index++;\n }\n\n return true;\n}\n\n/**\n * Whether the numbers are equal in value.\n */\nexport const areNumbersEqual = sameValueZeroEqual;\n\n/**\n * Whether the objects are equal in value.\n */\nexport function areObjectsEqual(\n a: Dictionary,\n b: Dictionary,\n state: State,\n): boolean {\n const properties = keys(a);\n\n let index = properties.length;\n\n if (keys(b).length !== index) {\n return false;\n }\n\n // Decrementing `while` showed faster results than either incrementing or\n // decrementing `for` loop and than an incrementing `while` loop. Declarative\n // methods like `some` / `every` were not used to avoid incurring the garbage\n // cost of anonymous callbacks.\n while (index-- > 0) {\n if (!isPropertyEqual(a, b, state, properties[index]!)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Whether the objects are equal in value with strict property checking.\n */\nexport function areObjectsEqualStrict(\n a: Dictionary,\n b: Dictionary,\n state: State,\n): boolean {\n const properties = getStrictProperties(a);\n\n let index = properties.length;\n\n if (getStrictProperties(b).length !== index) {\n return false;\n }\n\n let property: string | symbol;\n let descriptorA: ReturnType;\n let descriptorB: ReturnType;\n\n // Decrementing `while` showed faster results than either incrementing or\n // decrementing `for` loop and than an incrementing `while` loop. Declarative\n // methods like `some` / `every` were not used to avoid incurring the garbage\n // cost of anonymous callbacks.\n while (index-- > 0) {\n property = properties[index]!;\n\n if (!isPropertyEqual(a, b, state, property)) {\n return false;\n }\n\n descriptorA = getOwnPropertyDescriptor(a, property);\n descriptorB = getOwnPropertyDescriptor(b, property);\n\n if (\n (descriptorA || descriptorB) &&\n (!descriptorA ||\n !descriptorB ||\n descriptorA.configurable !== descriptorB.configurable ||\n descriptorA.enumerable !== descriptorB.enumerable ||\n descriptorA.writable !== descriptorB.writable)\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Whether the primitive wrappers passed are equal in value.\n */\nexport function arePrimitiveWrappersEqual(\n a: PrimitiveWrapper,\n b: PrimitiveWrapper,\n): boolean {\n return sameValueZeroEqual(a.valueOf(), b.valueOf());\n}\n\n/**\n * Whether the regexps passed are equal in value.\n */\nexport function areRegExpsEqual(a: RegExp, b: RegExp): boolean {\n return a.source === b.source && a.flags === b.flags;\n}\n\n/**\n * Whether the `Set`s are equal in value.\n */\nexport function areSetsEqual(\n a: Set,\n b: Set,\n state: State,\n): boolean {\n const size = a.size;\n\n if (size !== b.size) {\n return false;\n }\n\n if (!size) {\n return true;\n }\n\n const matchedIndices = new Array(size);\n const aIterable = a.values();\n\n let aResult: IteratorResult;\n let bResult: IteratorResult;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((aResult = aIterable.next())) {\n if (aResult.done) {\n break;\n }\n\n const bIterable = b.values();\n\n let hasMatch = false;\n let matchIndex = 0;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((bResult = bIterable.next())) {\n if (bResult.done) {\n break;\n }\n\n if (\n !matchedIndices[matchIndex] &&\n state.equals(\n aResult.value,\n bResult.value,\n aResult.value,\n bResult.value,\n a,\n b,\n state,\n )\n ) {\n hasMatch = matchedIndices[matchIndex] = true;\n break;\n }\n\n matchIndex++;\n }\n\n if (!hasMatch) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Whether the TypedArray instances are equal in value.\n */\nexport function areTypedArraysEqual(a: TypedArray, b: TypedArray) {\n let index = a.length;\n\n if (b.length !== index) {\n return false;\n }\n\n while (index-- > 0) {\n if (a[index] !== b[index]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Whether the URL instances are equal in value.\n */\nexport function areUrlsEqual(a: URL, b: URL): boolean {\n return (\n a.hostname === b.hostname &&\n a.pathname === b.pathname &&\n a.protocol === b.protocol &&\n a.port === b.port &&\n a.hash === b.hash &&\n a.username === b.username &&\n a.password === b.password\n );\n}\n\nfunction isPropertyEqual(\n a: Dictionary,\n b: Dictionary,\n state: State,\n property: string | symbol,\n) {\n if (\n (property === REACT_OWNER ||\n property === PREACT_OWNER ||\n property === PREACT_VNODE) &&\n (a.$$typeof || b.$$typeof)\n ) {\n return true;\n }\n\n return (\n hasOwn(b, property) &&\n state.equals(a[property], b[property], property, property, a, b, state)\n );\n}\n", "import {\n areArraysEqual as areArraysEqualDefault,\n areDatesEqual as areDatesEqualDefault,\n areErrorsEqual as areErrorsEqualDefault,\n areFunctionsEqual as areFunctionsEqualDefault,\n areMapsEqual as areMapsEqualDefault,\n areNumbersEqual as areNumbersEqualDefault,\n areObjectsEqual as areObjectsEqualDefault,\n areObjectsEqualStrict as areObjectsEqualStrictDefault,\n arePrimitiveWrappersEqual as arePrimitiveWrappersEqualDefault,\n areRegExpsEqual as areRegExpsEqualDefault,\n areSetsEqual as areSetsEqualDefault,\n areTypedArraysEqual as areTypedArraysEqualDefault,\n areUrlsEqual as areUrlsEqualDefault,\n} from './equals.js';\nimport type {\n ComparatorConfig,\n CreateState,\n CustomEqualCreatorOptions,\n EqualityComparator,\n InternalEqualityComparator,\n State,\n} from './internalTypes.js';\nimport { combineComparators, createIsCircular, getShortTag } from './utils.js';\n\nconst ARGUMENTS_TAG = '[object Arguments]';\nconst BOOLEAN_TAG = '[object Boolean]';\nconst DATE_TAG = '[object Date]';\nconst ERROR_TAG = '[object Error]';\nconst MAP_TAG = '[object Map]';\nconst NUMBER_TAG = '[object Number]';\nconst OBJECT_TAG = '[object Object]';\nconst REG_EXP_TAG = '[object RegExp]';\nconst SET_TAG = '[object Set]';\nconst STRING_TAG = '[object String]';\nconst URL_TAG = '[object URL]';\n\nconst { isArray } = Array;\nconst isTypedArray =\n typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function'\n ? ArrayBuffer.isView\n : null;\nconst { assign } = Object;\nconst getTag = Object.prototype.toString.call.bind(\n Object.prototype.toString,\n) as (a: object) => string;\n\ninterface CreateIsEqualOptions {\n circular: boolean;\n comparator: EqualityComparator;\n createState: CreateState | undefined;\n equals: InternalEqualityComparator;\n strict: boolean;\n}\n\n/**\n * Create a comparator method based on the type-specific equality comparators passed.\n */\nexport function createEqualityComparator({\n areArraysEqual,\n areDatesEqual,\n areErrorsEqual,\n areFunctionsEqual,\n areMapsEqual,\n areNumbersEqual,\n areObjectsEqual,\n arePrimitiveWrappersEqual,\n areRegExpsEqual,\n areSetsEqual,\n areTypedArraysEqual,\n areUrlsEqual,\n unknownTagComparators,\n}: ComparatorConfig): EqualityComparator {\n /**\n * compare the value of the two objects and return true if they are equivalent in values\n */\n return function comparator(a: any, b: any, state: State): boolean {\n // If the items are strictly equal, no need to do a value comparison.\n if (a === b) {\n return true;\n }\n\n // If either of the items are nullish and fail the strictly equal check\n // above, then they must be unequal.\n if (a == null || b == null) {\n return false;\n }\n\n const type = typeof a;\n\n if (type !== typeof b) {\n return false;\n }\n\n if (type !== 'object') {\n if (type === 'number') {\n return areNumbersEqual(a, b, state);\n }\n\n if (type === 'function') {\n return areFunctionsEqual(a, b, state);\n }\n\n // If a primitive value that is not strictly equal, it must be unequal.\n return false;\n }\n\n const constructor = a.constructor;\n\n // Checks are listed in order of commonality of use-case:\n // 1. Common complex object types (plain object, array)\n // 2. Common data values (date, regexp)\n // 3. Less-common complex object types (map, set)\n // 4. Less-common data values (promise, primitive wrappers)\n // Inherently this is both subjective and assumptive, however\n // when reviewing comparable libraries in the wild this order\n // appears to be generally consistent.\n\n // Constructors should match, otherwise there is potential for false positives\n // between class and subclass or custom object and POJO.\n if (constructor !== b.constructor) {\n return false;\n }\n\n // `isPlainObject` only checks against the object's own realm. Cross-realm\n // comparisons are rare, and will be handled in the ultimate fallback, so\n // we can avoid capturing the string tag.\n if (constructor === Object) {\n return areObjectsEqual(a, b, state);\n }\n\n // `isArray()` works on subclasses and is cross-realm, so we can avoid capturing\n // the string tag or doing an `instanceof` check.\n if (isArray(a)) {\n return areArraysEqual(a, b, state);\n }\n\n // `isTypedArray()` works on all possible TypedArray classes, so we can avoid\n // capturing the string tag or comparing against all possible constructors.\n if (isTypedArray != null && isTypedArray(a)) {\n return areTypedArraysEqual(a, b, state);\n }\n\n // Try to fast-path equality checks for other complex object types in the\n // same realm to avoid capturing the string tag. Strict equality is used\n // instead of `instanceof` because it is more performant for the common\n // use-case. If someone is subclassing a native class, it will be handled\n // with the string tag comparison.\n\n if (constructor === Date) {\n return areDatesEqual(a, b, state);\n }\n\n if (constructor === RegExp) {\n return areRegExpsEqual(a, b, state);\n }\n\n if (constructor === Map) {\n return areMapsEqual(a, b, state);\n }\n\n if (constructor === Set) {\n return areSetsEqual(a, b, state);\n }\n\n // Since this is a custom object, capture the string tag to determing its type.\n // This is reasonably performant in modern environments like v8 and SpiderMonkey.\n const tag = getTag(a as object);\n\n if (tag === DATE_TAG) {\n return areDatesEqual(a, b, state);\n }\n\n // For RegExp, the properties are not enumerable, and therefore will give false positives if\n // tested like a standard object.\n if (tag === REG_EXP_TAG) {\n return areRegExpsEqual(a, b, state);\n }\n\n if (tag === MAP_TAG) {\n return areMapsEqual(a, b, state);\n }\n\n if (tag === SET_TAG) {\n return areSetsEqual(a, b, state);\n }\n\n if (tag === OBJECT_TAG) {\n // The exception for value comparison is custom `Promise`-like class instances. These should\n // be treated the same as standard `Promise` objects, which means strict equality, and if\n // it reaches this point then that strict equality comparison has already failed.\n return (\n typeof a.then !== 'function' &&\n typeof b.then !== 'function' &&\n areObjectsEqual(a, b, state)\n );\n }\n\n // If a URL tag, it should be tested explicitly. Like RegExp, the properties are not\n // enumerable, and therefore will give false positives if tested like a standard object.\n if (tag === URL_TAG) {\n return areUrlsEqual(a, b, state);\n }\n\n // If an error tag, it should be tested explicitly. Like RegExp, the properties are not\n // enumerable, and therefore will give false positives if tested like a standard object.\n if (tag === ERROR_TAG) {\n return areErrorsEqual(a, b, state);\n }\n\n // If an arguments tag, it should be treated as a standard object.\n if (tag === ARGUMENTS_TAG) {\n return areObjectsEqual(a, b, state);\n }\n\n // As the penultimate fallback, check if the values passed are primitive wrappers. This\n // is very rare in modern JS, which is why it is deprioritized compared to all other object\n // types.\n if (tag === BOOLEAN_TAG || tag === NUMBER_TAG || tag === STRING_TAG) {\n return arePrimitiveWrappersEqual(a, b, state);\n }\n\n if (unknownTagComparators) {\n let unknownTagComparator = unknownTagComparators[tag];\n\n if (!unknownTagComparator) {\n const shortTag = getShortTag(a);\n\n if (shortTag) {\n unknownTagComparator = unknownTagComparators[shortTag];\n }\n }\n\n // If the custom config has an unknown tag comparator that matches the captured tag or the\n // @@toStringTag, it is the source of truth for whether the values are equal.\n if (unknownTagComparator) {\n return unknownTagComparator(a, b, state);\n }\n }\n\n // If not matching any tags that require a specific type of comparison, then we hard-code false because\n // the only thing remaining is strict equality, which has already been compared. This is for a few reasons:\n // - Certain types that cannot be introspected (e.g., `WeakMap`). For these types, this is the only\n // comparison that can be made.\n // - For types that can be introspected, but rarely have requirements to be compared\n // (`ArrayBuffer`, `DataView`, etc.), the cost is avoided to prioritize the common\n // use-cases (may be included in a future release, if requested enough).\n // - For types that can be introspected but do not have an objective definition of what\n // equality is (`Error`, etc.), the subjective decision is to be conservative and strictly compare.\n // In all cases, these decisions should be reevaluated based on changes to the language and\n // common development practices.\n return false;\n };\n}\n\n/**\n * Create the configuration object used for building comparators.\n */\nexport function createEqualityComparatorConfig({\n circular,\n createCustomConfig,\n strict,\n}: CustomEqualCreatorOptions): ComparatorConfig {\n let config = {\n areArraysEqual: strict\n ? areObjectsEqualStrictDefault\n : areArraysEqualDefault,\n areDatesEqual: areDatesEqualDefault,\n areErrorsEqual: areErrorsEqualDefault,\n areFunctionsEqual: areFunctionsEqualDefault,\n areMapsEqual: strict\n ? combineComparators(areMapsEqualDefault, areObjectsEqualStrictDefault)\n : areMapsEqualDefault,\n areNumbersEqual: areNumbersEqualDefault,\n areObjectsEqual: strict\n ? areObjectsEqualStrictDefault\n : areObjectsEqualDefault,\n arePrimitiveWrappersEqual: arePrimitiveWrappersEqualDefault,\n areRegExpsEqual: areRegExpsEqualDefault,\n areSetsEqual: strict\n ? combineComparators(areSetsEqualDefault, areObjectsEqualStrictDefault)\n : areSetsEqualDefault,\n areTypedArraysEqual: strict\n ? areObjectsEqualStrictDefault\n : areTypedArraysEqualDefault,\n areUrlsEqual: areUrlsEqualDefault,\n unknownTagComparators: undefined,\n };\n\n if (createCustomConfig) {\n config = assign({}, config, createCustomConfig(config));\n }\n\n if (circular) {\n const areArraysEqual = createIsCircular(config.areArraysEqual);\n const areMapsEqual = createIsCircular(config.areMapsEqual);\n const areObjectsEqual = createIsCircular(config.areObjectsEqual);\n const areSetsEqual = createIsCircular(config.areSetsEqual);\n\n config = assign({}, config, {\n areArraysEqual,\n areMapsEqual,\n areObjectsEqual,\n areSetsEqual,\n });\n }\n\n return config;\n}\n\n/**\n * Default equality comparator pass-through, used as the standard `isEqual` creator for\n * use inside the built comparator.\n */\nexport function createInternalEqualityComparator(\n compare: EqualityComparator,\n): InternalEqualityComparator {\n return function (\n a: any,\n b: any,\n _indexOrKeyA: any,\n _indexOrKeyB: any,\n _parentA: any,\n _parentB: any,\n state: State,\n ) {\n return compare(a, b, state);\n };\n}\n\n/**\n * Create the `isEqual` function used by the consuming application.\n */\nexport function createIsEqual({\n circular,\n comparator,\n createState,\n equals,\n strict,\n}: CreateIsEqualOptions) {\n if (createState) {\n return function isEqual(a: A, b: B): boolean {\n const { cache = circular ? new WeakMap() : undefined, meta } =\n createState();\n\n return comparator(a, b, {\n cache,\n equals,\n meta,\n strict,\n } as State);\n };\n }\n\n if (circular) {\n return function isEqual(a: A, b: B): boolean {\n return comparator(a, b, {\n cache: new WeakMap(),\n equals,\n meta: undefined as Meta,\n strict,\n } as State);\n };\n }\n\n const state = {\n cache: undefined,\n equals,\n meta: undefined,\n strict,\n } as State;\n\n return function isEqual(a: A, b: B): boolean {\n return comparator(a, b, state);\n };\n}\n", "import {\n createEqualityComparatorConfig,\n createEqualityComparator,\n createInternalEqualityComparator,\n createIsEqual,\n} from './comparator.js';\nimport type { CustomEqualCreatorOptions } from './internalTypes.js';\nimport { sameValueZeroEqual } from './utils.js';\n\nexport { sameValueZeroEqual };\nexport type {\n AnyEqualityComparator,\n Cache,\n CircularState,\n ComparatorConfig,\n CreateCustomComparatorConfig,\n CreateState,\n CustomEqualCreatorOptions,\n DefaultState,\n Dictionary,\n EqualityComparator,\n EqualityComparatorCreator,\n InternalEqualityComparator,\n PrimitiveWrapper,\n State,\n TypeEqualityComparator,\n TypedArray,\n} from './internalTypes.js';\n\n/**\n * Whether the items passed are deeply-equal in value.\n */\nexport const deepEqual = createCustomEqual();\n\n/**\n * Whether the items passed are deeply-equal in value based on strict comparison.\n */\nexport const strictDeepEqual = createCustomEqual({ strict: true });\n\n/**\n * Whether the items passed are deeply-equal in value, including circular references.\n */\nexport const circularDeepEqual = createCustomEqual({ circular: true });\n\n/**\n * Whether the items passed are deeply-equal in value, including circular references,\n * based on strict comparison.\n */\nexport const strictCircularDeepEqual = createCustomEqual({\n circular: true,\n strict: true,\n});\n\n/**\n * Whether the items passed are shallowly-equal in value.\n */\nexport const shallowEqual = createCustomEqual({\n createInternalComparator: () => sameValueZeroEqual,\n});\n\n/**\n * Whether the items passed are shallowly-equal in value based on strict comparison\n */\nexport const strictShallowEqual = createCustomEqual({\n strict: true,\n createInternalComparator: () => sameValueZeroEqual,\n});\n\n/**\n * Whether the items passed are shallowly-equal in value, including circular references.\n */\nexport const circularShallowEqual = createCustomEqual({\n circular: true,\n createInternalComparator: () => sameValueZeroEqual,\n});\n\n/**\n * Whether the items passed are shallowly-equal in value, including circular references,\n * based on strict comparison.\n */\nexport const strictCircularShallowEqual = createCustomEqual({\n circular: true,\n createInternalComparator: () => sameValueZeroEqual,\n strict: true,\n});\n\n/**\n * Create a custom equality comparison method.\n *\n * This can be done to create very targeted comparisons in extreme hot-path scenarios\n * where the standard methods are not performant enough, but can also be used to provide\n * support for legacy environments that do not support expected features like\n * `RegExp.prototype.flags` out of the box.\n */\nexport function createCustomEqual(\n options: CustomEqualCreatorOptions = {},\n) {\n const {\n circular = false,\n createInternalComparator: createCustomInternalComparator,\n createState,\n strict = false,\n } = options;\n\n const config = createEqualityComparatorConfig(options);\n const comparator = createEqualityComparator(config);\n const equals = createCustomInternalComparator\n ? createCustomInternalComparator(comparator)\n : createInternalEqualityComparator(comparator);\n\n return createIsEqual({ circular, comparator, createState, equals, strict });\n}\n", "function safeRequestAnimationFrame(callback) {\n if (typeof requestAnimationFrame !== 'undefined') requestAnimationFrame(callback);\n}\nexport default function setRafTimeout(callback) {\n var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n var currTime = -1;\n var shouldUpdate = function shouldUpdate(now) {\n if (currTime < 0) {\n currTime = now;\n }\n if (now - currTime > timeout) {\n callback(now);\n currTime = -1;\n } else {\n safeRequestAnimationFrame(shouldUpdate);\n }\n };\n requestAnimationFrame(shouldUpdate);\n}", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nimport setRafTimeout from './setRafTimeout';\nexport default function createAnimateManager() {\n var currStyle = {};\n var handleChange = function handleChange() {\n return null;\n };\n var shouldStop = false;\n var setStyle = function setStyle(_style) {\n if (shouldStop) {\n return;\n }\n if (Array.isArray(_style)) {\n if (!_style.length) {\n return;\n }\n var styles = _style;\n var _styles = _toArray(styles),\n curr = _styles[0],\n restStyles = _styles.slice(1);\n if (typeof curr === 'number') {\n setRafTimeout(setStyle.bind(null, restStyles), curr);\n return;\n }\n setStyle(curr);\n setRafTimeout(setStyle.bind(null, restStyles));\n return;\n }\n if (_typeof(_style) === 'object') {\n currStyle = _style;\n handleChange(currStyle);\n }\n if (typeof _style === 'function') {\n _style();\n }\n };\n return {\n stop: function stop() {\n shouldStop = true;\n },\n start: function start(style) {\n shouldStop = false;\n setStyle(style);\n },\n subscribe: function subscribe(_handleChange) {\n handleChange = _handleChange;\n return function () {\n handleChange = function handleChange() {\n return null;\n };\n };\n }\n };\n}", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\n/* eslint no-console: 0 */\n\nexport var getIntersectionKeys = function getIntersectionKeys(preObj, nextObj) {\n return [Object.keys(preObj), Object.keys(nextObj)].reduce(function (a, b) {\n return a.filter(function (c) {\n return b.includes(c);\n });\n });\n};\nexport var identity = function identity(param) {\n return param;\n};\n\n/*\n * @description: convert camel case to dash case\n * string => string\n */\nexport var getDashCase = function getDashCase(name) {\n return name.replace(/([A-Z])/g, function (v) {\n return \"-\".concat(v.toLowerCase());\n });\n};\nexport var log = function log() {\n var _console;\n (_console = console).log.apply(_console, arguments);\n};\n\n/*\n * @description: log the value of a varible\n * string => any => any\n */\nexport var debug = function debug(name) {\n return function (item) {\n log(name, item);\n return item;\n };\n};\n\n/*\n * @description: log name, args, return value of a function\n * function => function\n */\nexport var debugf = function debugf(tag, f) {\n return function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n var res = f.apply(void 0, args);\n var name = tag || f.name || 'anonymous function';\n var argNames = \"(\".concat(args.map(JSON.stringify).join(', '), \")\");\n log(\"\".concat(name, \": \").concat(argNames, \" => \").concat(JSON.stringify(res)));\n return res;\n };\n};\n\n/*\n * @description: map object on every element in this object.\n * (function, object) => object\n */\nexport var mapObject = function mapObject(fn, obj) {\n return Object.keys(obj).reduce(function (res, key) {\n return _objectSpread(_objectSpread({}, res), {}, _defineProperty({}, key, fn(key, obj[key])));\n }, {});\n};\nexport var getTransitionVal = function getTransitionVal(props, duration, easing) {\n return props.map(function (prop) {\n return \"\".concat(getDashCase(prop), \" \").concat(duration, \"ms \").concat(easing);\n }).join(',');\n};\nvar isDev = process.env.NODE_ENV !== 'production';\nexport var warn = function warn(condition, format, a, b, c, d, e, f) {\n if (isDev && typeof console !== 'undefined' && console.warn) {\n if (format === undefined) {\n console.warn('LogUtils requires an error message argument');\n }\n if (!condition) {\n if (format === undefined) {\n console.warn('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');\n } else {\n var args = [a, b, c, d, e, f];\n var argIndex = 0;\n console.warn(format.replace(/%s/g, function () {\n return args[argIndex++];\n }));\n }\n }\n }\n};", "function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nimport { warn } from './util';\nvar ACCURACY = 1e-4;\nvar cubicBezierFactor = function cubicBezierFactor(c1, c2) {\n return [0, 3 * c1, 3 * c2 - 6 * c1, 3 * c1 - 3 * c2 + 1];\n};\nvar multyTime = function multyTime(params, t) {\n return params.map(function (param, i) {\n return param * Math.pow(t, i);\n }).reduce(function (pre, curr) {\n return pre + curr;\n });\n};\nvar cubicBezier = function cubicBezier(c1, c2) {\n return function (t) {\n var params = cubicBezierFactor(c1, c2);\n return multyTime(params, t);\n };\n};\nvar derivativeCubicBezier = function derivativeCubicBezier(c1, c2) {\n return function (t) {\n var params = cubicBezierFactor(c1, c2);\n var newParams = [].concat(_toConsumableArray(params.map(function (param, i) {\n return param * i;\n }).slice(1)), [0]);\n return multyTime(newParams, t);\n };\n};\n\n// calculate cubic-bezier using Newton's method\nexport var configBezier = function configBezier() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n var x1 = args[0],\n y1 = args[1],\n x2 = args[2],\n y2 = args[3];\n if (args.length === 1) {\n switch (args[0]) {\n case 'linear':\n x1 = 0.0;\n y1 = 0.0;\n x2 = 1.0;\n y2 = 1.0;\n break;\n case 'ease':\n x1 = 0.25;\n y1 = 0.1;\n x2 = 0.25;\n y2 = 1.0;\n break;\n case 'ease-in':\n x1 = 0.42;\n y1 = 0.0;\n x2 = 1.0;\n y2 = 1.0;\n break;\n case 'ease-out':\n x1 = 0.42;\n y1 = 0.0;\n x2 = 0.58;\n y2 = 1.0;\n break;\n case 'ease-in-out':\n x1 = 0.0;\n y1 = 0.0;\n x2 = 0.58;\n y2 = 1.0;\n break;\n default:\n {\n var easing = args[0].split('(');\n if (easing[0] === 'cubic-bezier' && easing[1].split(')')[0].split(',').length === 4) {\n var _easing$1$split$0$spl = easing[1].split(')')[0].split(',').map(function (x) {\n return parseFloat(x);\n });\n var _easing$1$split$0$spl2 = _slicedToArray(_easing$1$split$0$spl, 4);\n x1 = _easing$1$split$0$spl2[0];\n y1 = _easing$1$split$0$spl2[1];\n x2 = _easing$1$split$0$spl2[2];\n y2 = _easing$1$split$0$spl2[3];\n } else {\n warn(false, '[configBezier]: arguments should be one of ' + \"oneOf 'linear', 'ease', 'ease-in', 'ease-out', \" + \"'ease-in-out','cubic-bezier(x1,y1,x2,y2)', instead received %s\", args);\n }\n }\n }\n }\n warn([x1, x2, y1, y2].every(function (num) {\n return typeof num === 'number' && num >= 0 && num <= 1;\n }), '[configBezier]: arguments should be x1, y1, x2, y2 of [0, 1] instead received %s', args);\n var curveX = cubicBezier(x1, x2);\n var curveY = cubicBezier(y1, y2);\n var derCurveX = derivativeCubicBezier(x1, x2);\n var rangeValue = function rangeValue(value) {\n if (value > 1) {\n return 1;\n }\n if (value < 0) {\n return 0;\n }\n return value;\n };\n var bezier = function bezier(_t) {\n var t = _t > 1 ? 1 : _t;\n var x = t;\n for (var i = 0; i < 8; ++i) {\n var evalT = curveX(x) - t;\n var derVal = derCurveX(x);\n if (Math.abs(evalT - t) < ACCURACY || derVal < ACCURACY) {\n return curveY(x);\n }\n x = rangeValue(x - evalT / derVal);\n }\n return curveY(x);\n };\n bezier.isStepper = false;\n return bezier;\n};\nexport var configSpring = function configSpring() {\n var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var _config$stiff = config.stiff,\n stiff = _config$stiff === void 0 ? 100 : _config$stiff,\n _config$damping = config.damping,\n damping = _config$damping === void 0 ? 8 : _config$damping,\n _config$dt = config.dt,\n dt = _config$dt === void 0 ? 17 : _config$dt;\n var stepper = function stepper(currX, destX, currV) {\n var FSpring = -(currX - destX) * stiff;\n var FDamping = currV * damping;\n var newV = currV + (FSpring - FDamping) * dt / 1000;\n var newX = currV * dt / 1000 + currX;\n if (Math.abs(newX - destX) < ACCURACY && Math.abs(newV) < ACCURACY) {\n return [destX, 0];\n }\n return [newX, newV];\n };\n stepper.isStepper = true;\n stepper.dt = dt;\n return stepper;\n};\nexport var configEasing = function configEasing() {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n var easing = args[0];\n if (typeof easing === 'string') {\n switch (easing) {\n case 'ease':\n case 'ease-in-out':\n case 'ease-out':\n case 'ease-in':\n case 'linear':\n return configBezier(easing);\n case 'spring':\n return configSpring();\n default:\n if (easing.split('(')[0] === 'cubic-bezier') {\n return configBezier(easing);\n }\n warn(false, \"[configEasing]: first argument should be one of 'ease', 'ease-in', \" + \"'ease-out', 'ease-in-out','cubic-bezier(x1,y1,x2,y2)', 'linear' and 'spring', instead received %s\", args);\n }\n }\n if (typeof easing === 'function') {\n return easing;\n }\n warn(false, '[configEasing]: first argument type should be function or string, instead received %s', args);\n return null;\n};", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nimport { getIntersectionKeys, mapObject } from './util';\nvar alpha = function alpha(begin, end, k) {\n return begin + (end - begin) * k;\n};\nvar needContinue = function needContinue(_ref) {\n var from = _ref.from,\n to = _ref.to;\n return from !== to;\n};\n\n/*\n * @description: cal new from value and velocity in each stepper\n * @return: { [styleProperty]: { from, to, velocity } }\n */\nvar calStepperVals = function calStepperVals(easing, preVals, steps) {\n var nextStepVals = mapObject(function (key, val) {\n if (needContinue(val)) {\n var _easing = easing(val.from, val.to, val.velocity),\n _easing2 = _slicedToArray(_easing, 2),\n newX = _easing2[0],\n newV = _easing2[1];\n return _objectSpread(_objectSpread({}, val), {}, {\n from: newX,\n velocity: newV\n });\n }\n return val;\n }, preVals);\n if (steps < 1) {\n return mapObject(function (key, val) {\n if (needContinue(val)) {\n return _objectSpread(_objectSpread({}, val), {}, {\n velocity: alpha(val.velocity, nextStepVals[key].velocity, steps),\n from: alpha(val.from, nextStepVals[key].from, steps)\n });\n }\n return val;\n }, preVals);\n }\n return calStepperVals(easing, nextStepVals, steps - 1);\n};\n\n// configure update function\nexport default (function (from, to, easing, duration, render) {\n var interKeys = getIntersectionKeys(from, to);\n var timingStyle = interKeys.reduce(function (res, key) {\n return _objectSpread(_objectSpread({}, res), {}, _defineProperty({}, key, [from[key], to[key]]));\n }, {});\n var stepperStyle = interKeys.reduce(function (res, key) {\n return _objectSpread(_objectSpread({}, res), {}, _defineProperty({}, key, {\n from: from[key],\n velocity: 0,\n to: to[key]\n }));\n }, {});\n var cafId = -1;\n var preTime;\n var beginTime;\n var update = function update() {\n return null;\n };\n var getCurrStyle = function getCurrStyle() {\n return mapObject(function (key, val) {\n return val.from;\n }, stepperStyle);\n };\n var shouldStopAnimation = function shouldStopAnimation() {\n return !Object.values(stepperStyle).filter(needContinue).length;\n };\n\n // stepper timing function like spring\n var stepperUpdate = function stepperUpdate(now) {\n if (!preTime) {\n preTime = now;\n }\n var deltaTime = now - preTime;\n var steps = deltaTime / easing.dt;\n stepperStyle = calStepperVals(easing, stepperStyle, steps);\n // get union set and add compatible prefix\n render(_objectSpread(_objectSpread(_objectSpread({}, from), to), getCurrStyle(stepperStyle)));\n preTime = now;\n if (!shouldStopAnimation()) {\n cafId = requestAnimationFrame(update);\n }\n };\n\n // t => val timing function like cubic-bezier\n var timingUpdate = function timingUpdate(now) {\n if (!beginTime) {\n beginTime = now;\n }\n var t = (now - beginTime) / duration;\n var currStyle = mapObject(function (key, val) {\n return alpha.apply(void 0, _toConsumableArray(val).concat([easing(t)]));\n }, timingStyle);\n\n // get union set and add compatible prefix\n render(_objectSpread(_objectSpread(_objectSpread({}, from), to), currStyle));\n if (t < 1) {\n cafId = requestAnimationFrame(update);\n } else {\n var finalStyle = mapObject(function (key, val) {\n return alpha.apply(void 0, _toConsumableArray(val).concat([easing(1)]));\n }, timingStyle);\n render(_objectSpread(_objectSpread(_objectSpread({}, from), to), finalStyle));\n }\n };\n update = easing.isStepper ? stepperUpdate : timingUpdate;\n\n // return start animation method\n return function () {\n requestAnimationFrame(update);\n\n // return stop animation method\n return function () {\n cancelAnimationFrame(cafId);\n };\n };\n});", "import Animate from './Animate';\nimport { configBezier, configSpring } from './easing';\nimport AnimateGroup from './AnimateGroup';\nexport { configSpring, configBezier, AnimateGroup };\nexport default Animate;", "var _excluded = [\"points\", \"className\", \"baseLinePoints\", \"connectNulls\"];\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\n/**\n * @fileOverview Polygon\n */\nimport React from 'react';\nimport clsx from 'clsx';\nimport { filterProps } from '../util/ReactUtils';\nvar isValidatePoint = function isValidatePoint(point) {\n return point && point.x === +point.x && point.y === +point.y;\n};\nvar getParsedPoints = function getParsedPoints() {\n var points = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n var segmentPoints = [[]];\n points.forEach(function (entry) {\n if (isValidatePoint(entry)) {\n segmentPoints[segmentPoints.length - 1].push(entry);\n } else if (segmentPoints[segmentPoints.length - 1].length > 0) {\n // add another path\n segmentPoints.push([]);\n }\n });\n if (isValidatePoint(points[0])) {\n segmentPoints[segmentPoints.length - 1].push(points[0]);\n }\n if (segmentPoints[segmentPoints.length - 1].length <= 0) {\n segmentPoints = segmentPoints.slice(0, -1);\n }\n return segmentPoints;\n};\nvar getSinglePolygonPath = function getSinglePolygonPath(points, connectNulls) {\n var segmentPoints = getParsedPoints(points);\n if (connectNulls) {\n segmentPoints = [segmentPoints.reduce(function (res, segPoints) {\n return [].concat(_toConsumableArray(res), _toConsumableArray(segPoints));\n }, [])];\n }\n var polygonPath = segmentPoints.map(function (segPoints) {\n return segPoints.reduce(function (path, point, index) {\n return \"\".concat(path).concat(index === 0 ? 'M' : 'L').concat(point.x, \",\").concat(point.y);\n }, '');\n }).join('');\n return segmentPoints.length === 1 ? \"\".concat(polygonPath, \"Z\") : polygonPath;\n};\nvar getRanglePath = function getRanglePath(points, baseLinePoints, connectNulls) {\n var outerPath = getSinglePolygonPath(points, connectNulls);\n return \"\".concat(outerPath.slice(-1) === 'Z' ? outerPath.slice(0, -1) : outerPath, \"L\").concat(getSinglePolygonPath(baseLinePoints.reverse(), connectNulls).slice(1));\n};\nexport var Polygon = function Polygon(props) {\n var points = props.points,\n className = props.className,\n baseLinePoints = props.baseLinePoints,\n connectNulls = props.connectNulls,\n others = _objectWithoutProperties(props, _excluded);\n if (!points || !points.length) {\n return null;\n }\n var layerClass = clsx('recharts-polygon', className);\n if (baseLinePoints && baseLinePoints.length) {\n var hasStroke = others.stroke && others.stroke !== 'none';\n var rangePath = getRanglePath(points, baseLinePoints, connectNulls);\n return /*#__PURE__*/React.createElement(\"g\", {\n className: layerClass\n }, /*#__PURE__*/React.createElement(\"path\", _extends({}, filterProps(others, true), {\n fill: rangePath.slice(-1) === 'Z' ? others.fill : 'none',\n stroke: \"none\",\n d: rangePath\n })), hasStroke ? /*#__PURE__*/React.createElement(\"path\", _extends({}, filterProps(others, true), {\n fill: \"none\",\n d: getSinglePolygonPath(points, connectNulls)\n })) : null, hasStroke ? /*#__PURE__*/React.createElement(\"path\", _extends({}, filterProps(others, true), {\n fill: \"none\",\n d: getSinglePolygonPath(baseLinePoints, connectNulls)\n })) : null);\n }\n var singlePath = getSinglePolygonPath(points, connectNulls);\n return /*#__PURE__*/React.createElement(\"path\", _extends({}, filterProps(others, true), {\n fill: singlePath.slice(-1) === 'Z' ? others.fill : 'none',\n className: layerClass,\n d: singlePath\n }));\n};", "function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n/**\n * @fileOverview Dot\n */\nimport * as React from 'react';\nimport clsx from 'clsx';\nimport { adaptEventHandlers } from '../util/types';\nimport { filterProps } from '../util/ReactUtils';\nexport var Dot = function Dot(props) {\n var cx = props.cx,\n cy = props.cy,\n r = props.r,\n className = props.className;\n var layerClass = clsx('recharts-dot', className);\n if (cx === +cx && cy === +cy && r === +r) {\n return /*#__PURE__*/React.createElement(\"circle\", _extends({}, filterProps(props, false), adaptEventHandlers(props), {\n className: layerClass,\n cx: cx,\n cy: cy,\n r: r\n }));\n }\n return null;\n};", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nvar _excluded = [\"x\", \"y\", \"top\", \"left\", \"width\", \"height\", \"className\"];\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\n/**\n * @fileOverview Cross\n */\nimport React from 'react';\nimport clsx from 'clsx';\nimport { isNumber } from '../util/DataUtils';\nimport { filterProps } from '../util/ReactUtils';\nvar getPath = function getPath(x, y, width, height, top, left) {\n return \"M\".concat(x, \",\").concat(top, \"v\").concat(height, \"M\").concat(left, \",\").concat(y, \"h\").concat(width);\n};\nexport var Cross = function Cross(_ref) {\n var _ref$x = _ref.x,\n x = _ref$x === void 0 ? 0 : _ref$x,\n _ref$y = _ref.y,\n y = _ref$y === void 0 ? 0 : _ref$y,\n _ref$top = _ref.top,\n top = _ref$top === void 0 ? 0 : _ref$top,\n _ref$left = _ref.left,\n left = _ref$left === void 0 ? 0 : _ref$left,\n _ref$width = _ref.width,\n width = _ref$width === void 0 ? 0 : _ref$width,\n _ref$height = _ref.height,\n height = _ref$height === void 0 ? 0 : _ref$height,\n className = _ref.className,\n rest = _objectWithoutProperties(_ref, _excluded);\n var props = _objectSpread({\n x: x,\n y: y,\n top: top,\n left: left,\n width: width,\n height: height\n }, rest);\n if (!isNumber(x) || !isNumber(y) || !isNumber(width) || !isNumber(height) || !isNumber(top) || !isNumber(left)) {\n return null;\n }\n return /*#__PURE__*/React.createElement(\"path\", _extends({}, filterProps(props, true), {\n className: clsx('recharts-cross', className),\n d: getPath(x, y, width, height, top, left)\n }));\n};", "var _excluded = [\"cx\", \"cy\", \"angle\", \"ticks\", \"axisLine\"],\n _excluded2 = [\"ticks\", \"tick\", \"angle\", \"tickFormatter\", \"stroke\"];\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview The axis of polar coordinate system\n */\nimport React, { PureComponent } from 'react';\nimport maxBy from 'lodash/maxBy';\nimport minBy from 'lodash/minBy';\nimport isFunction from 'lodash/isFunction';\nimport clsx from 'clsx';\nimport { Text } from '../component/Text';\nimport { Label } from '../component/Label';\nimport { Layer } from '../container/Layer';\nimport { getTickClassName, polarToCartesian } from '../util/PolarUtils';\nimport { adaptEventsOfChild } from '../util/types';\nimport { filterProps } from '../util/ReactUtils';\nexport var PolarRadiusAxis = /*#__PURE__*/function (_PureComponent) {\n function PolarRadiusAxis() {\n _classCallCheck(this, PolarRadiusAxis);\n return _callSuper(this, PolarRadiusAxis, arguments);\n }\n _inherits(PolarRadiusAxis, _PureComponent);\n return _createClass(PolarRadiusAxis, [{\n key: \"getTickValueCoord\",\n value:\n /**\n * Calculate the coordinate of tick\n * @param {Number} coordinate The radius of tick\n * @return {Object} (x, y)\n */\n function getTickValueCoord(_ref) {\n var coordinate = _ref.coordinate;\n var _this$props = this.props,\n angle = _this$props.angle,\n cx = _this$props.cx,\n cy = _this$props.cy;\n return polarToCartesian(cx, cy, coordinate, angle);\n }\n }, {\n key: \"getTickTextAnchor\",\n value: function getTickTextAnchor() {\n var orientation = this.props.orientation;\n var textAnchor;\n switch (orientation) {\n case 'left':\n textAnchor = 'end';\n break;\n case 'right':\n textAnchor = 'start';\n break;\n default:\n textAnchor = 'middle';\n break;\n }\n return textAnchor;\n }\n }, {\n key: \"getViewBox\",\n value: function getViewBox() {\n var _this$props2 = this.props,\n cx = _this$props2.cx,\n cy = _this$props2.cy,\n angle = _this$props2.angle,\n ticks = _this$props2.ticks;\n var maxRadiusTick = maxBy(ticks, function (entry) {\n return entry.coordinate || 0;\n });\n var minRadiusTick = minBy(ticks, function (entry) {\n return entry.coordinate || 0;\n });\n return {\n cx: cx,\n cy: cy,\n startAngle: angle,\n endAngle: angle,\n innerRadius: minRadiusTick.coordinate || 0,\n outerRadius: maxRadiusTick.coordinate || 0\n };\n }\n }, {\n key: \"renderAxisLine\",\n value: function renderAxisLine() {\n var _this$props3 = this.props,\n cx = _this$props3.cx,\n cy = _this$props3.cy,\n angle = _this$props3.angle,\n ticks = _this$props3.ticks,\n axisLine = _this$props3.axisLine,\n others = _objectWithoutProperties(_this$props3, _excluded);\n var extent = ticks.reduce(function (result, entry) {\n return [Math.min(result[0], entry.coordinate), Math.max(result[1], entry.coordinate)];\n }, [Infinity, -Infinity]);\n var point0 = polarToCartesian(cx, cy, extent[0], angle);\n var point1 = polarToCartesian(cx, cy, extent[1], angle);\n var props = _objectSpread(_objectSpread(_objectSpread({}, filterProps(others, false)), {}, {\n fill: 'none'\n }, filterProps(axisLine, false)), {}, {\n x1: point0.x,\n y1: point0.y,\n x2: point1.x,\n y2: point1.y\n });\n return /*#__PURE__*/React.createElement(\"line\", _extends({\n className: \"recharts-polar-radius-axis-line\"\n }, props));\n }\n }, {\n key: \"renderTicks\",\n value: function renderTicks() {\n var _this = this;\n var _this$props4 = this.props,\n ticks = _this$props4.ticks,\n tick = _this$props4.tick,\n angle = _this$props4.angle,\n tickFormatter = _this$props4.tickFormatter,\n stroke = _this$props4.stroke,\n others = _objectWithoutProperties(_this$props4, _excluded2);\n var textAnchor = this.getTickTextAnchor();\n var axisProps = filterProps(others, false);\n var customTickProps = filterProps(tick, false);\n var items = ticks.map(function (entry, i) {\n var coord = _this.getTickValueCoord(entry);\n var tickProps = _objectSpread(_objectSpread(_objectSpread(_objectSpread({\n textAnchor: textAnchor,\n transform: \"rotate(\".concat(90 - angle, \", \").concat(coord.x, \", \").concat(coord.y, \")\")\n }, axisProps), {}, {\n stroke: 'none',\n fill: stroke\n }, customTickProps), {}, {\n index: i\n }, coord), {}, {\n payload: entry\n });\n return /*#__PURE__*/React.createElement(Layer, _extends({\n className: clsx('recharts-polar-radius-axis-tick', getTickClassName(tick)),\n key: \"tick-\".concat(entry.coordinate)\n }, adaptEventsOfChild(_this.props, entry, i)), PolarRadiusAxis.renderTickItem(tick, tickProps, tickFormatter ? tickFormatter(entry.value, i) : entry.value));\n });\n return /*#__PURE__*/React.createElement(Layer, {\n className: \"recharts-polar-radius-axis-ticks\"\n }, items);\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this$props5 = this.props,\n ticks = _this$props5.ticks,\n axisLine = _this$props5.axisLine,\n tick = _this$props5.tick;\n if (!ticks || !ticks.length) {\n return null;\n }\n return /*#__PURE__*/React.createElement(Layer, {\n className: clsx('recharts-polar-radius-axis', this.props.className)\n }, axisLine && this.renderAxisLine(), tick && this.renderTicks(), Label.renderCallByParent(this.props, this.getViewBox()));\n }\n }], [{\n key: \"renderTickItem\",\n value: function renderTickItem(option, props, value) {\n var tickItem;\n if ( /*#__PURE__*/React.isValidElement(option)) {\n tickItem = /*#__PURE__*/React.cloneElement(option, props);\n } else if (isFunction(option)) {\n tickItem = option(props);\n } else {\n tickItem = /*#__PURE__*/React.createElement(Text, _extends({}, props, {\n className: \"recharts-polar-radius-axis-tick-value\"\n }), value);\n }\n return tickItem;\n }\n }]);\n}(PureComponent);\n_defineProperty(PolarRadiusAxis, \"displayName\", 'PolarRadiusAxis');\n_defineProperty(PolarRadiusAxis, \"axisType\", 'radiusAxis');\n_defineProperty(PolarRadiusAxis, \"defaultProps\", {\n type: 'number',\n radiusAxisId: 0,\n cx: 0,\n cy: 0,\n angle: 0,\n orientation: 'right',\n stroke: '#ccc',\n axisLine: true,\n tick: true,\n tickCount: 5,\n allowDataOverflow: false,\n scale: 'auto',\n allowDuplicatedCategory: true\n});", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Axis of radial direction\n */\nimport React, { PureComponent } from 'react';\nimport isFunction from 'lodash/isFunction';\nimport clsx from 'clsx';\nimport { Layer } from '../container/Layer';\nimport { Dot } from '../shape/Dot';\nimport { Polygon } from '../shape/Polygon';\nimport { Text } from '../component/Text';\nimport { adaptEventsOfChild } from '../util/types';\nimport { filterProps } from '../util/ReactUtils';\nimport { getTickClassName, polarToCartesian } from '../util/PolarUtils';\nvar RADIAN = Math.PI / 180;\nvar eps = 1e-5;\nexport var PolarAngleAxis = /*#__PURE__*/function (_PureComponent) {\n function PolarAngleAxis() {\n _classCallCheck(this, PolarAngleAxis);\n return _callSuper(this, PolarAngleAxis, arguments);\n }\n _inherits(PolarAngleAxis, _PureComponent);\n return _createClass(PolarAngleAxis, [{\n key: \"getTickLineCoord\",\n value:\n /**\n * Calculate the coordinate of line endpoint\n * @param {Object} data The Data if ticks\n * @return {Object} (x0, y0): The start point of text,\n * (x1, y1): The end point close to text,\n * (x2, y2): The end point close to axis\n */\n function getTickLineCoord(data) {\n var _this$props = this.props,\n cx = _this$props.cx,\n cy = _this$props.cy,\n radius = _this$props.radius,\n orientation = _this$props.orientation,\n tickSize = _this$props.tickSize;\n var tickLineSize = tickSize || 8;\n var p1 = polarToCartesian(cx, cy, radius, data.coordinate);\n var p2 = polarToCartesian(cx, cy, radius + (orientation === 'inner' ? -1 : 1) * tickLineSize, data.coordinate);\n return {\n x1: p1.x,\n y1: p1.y,\n x2: p2.x,\n y2: p2.y\n };\n }\n\n /**\n * Get the text-anchor of each tick\n * @param {Object} data Data of ticks\n * @return {String} text-anchor\n */\n }, {\n key: \"getTickTextAnchor\",\n value: function getTickTextAnchor(data) {\n var orientation = this.props.orientation;\n var cos = Math.cos(-data.coordinate * RADIAN);\n var textAnchor;\n if (cos > eps) {\n textAnchor = orientation === 'outer' ? 'start' : 'end';\n } else if (cos < -eps) {\n textAnchor = orientation === 'outer' ? 'end' : 'start';\n } else {\n textAnchor = 'middle';\n }\n return textAnchor;\n }\n }, {\n key: \"renderAxisLine\",\n value: function renderAxisLine() {\n var _this$props2 = this.props,\n cx = _this$props2.cx,\n cy = _this$props2.cy,\n radius = _this$props2.radius,\n axisLine = _this$props2.axisLine,\n axisLineType = _this$props2.axisLineType;\n var props = _objectSpread(_objectSpread({}, filterProps(this.props, false)), {}, {\n fill: 'none'\n }, filterProps(axisLine, false));\n if (axisLineType === 'circle') {\n return /*#__PURE__*/React.createElement(Dot, _extends({\n className: \"recharts-polar-angle-axis-line\"\n }, props, {\n cx: cx,\n cy: cy,\n r: radius\n }));\n }\n var ticks = this.props.ticks;\n var points = ticks.map(function (entry) {\n return polarToCartesian(cx, cy, radius, entry.coordinate);\n });\n return /*#__PURE__*/React.createElement(Polygon, _extends({\n className: \"recharts-polar-angle-axis-line\"\n }, props, {\n points: points\n }));\n }\n }, {\n key: \"renderTicks\",\n value: function renderTicks() {\n var _this = this;\n var _this$props3 = this.props,\n ticks = _this$props3.ticks,\n tick = _this$props3.tick,\n tickLine = _this$props3.tickLine,\n tickFormatter = _this$props3.tickFormatter,\n stroke = _this$props3.stroke;\n var axisProps = filterProps(this.props, false);\n var customTickProps = filterProps(tick, false);\n var tickLineProps = _objectSpread(_objectSpread({}, axisProps), {}, {\n fill: 'none'\n }, filterProps(tickLine, false));\n var items = ticks.map(function (entry, i) {\n var lineCoord = _this.getTickLineCoord(entry);\n var textAnchor = _this.getTickTextAnchor(entry);\n var tickProps = _objectSpread(_objectSpread(_objectSpread({\n textAnchor: textAnchor\n }, axisProps), {}, {\n stroke: 'none',\n fill: stroke\n }, customTickProps), {}, {\n index: i,\n payload: entry,\n x: lineCoord.x2,\n y: lineCoord.y2\n });\n return /*#__PURE__*/React.createElement(Layer, _extends({\n className: clsx('recharts-polar-angle-axis-tick', getTickClassName(tick)),\n key: \"tick-\".concat(entry.coordinate)\n }, adaptEventsOfChild(_this.props, entry, i)), tickLine && /*#__PURE__*/React.createElement(\"line\", _extends({\n className: \"recharts-polar-angle-axis-tick-line\"\n }, tickLineProps, lineCoord)), tick && PolarAngleAxis.renderTickItem(tick, tickProps, tickFormatter ? tickFormatter(entry.value, i) : entry.value));\n });\n return /*#__PURE__*/React.createElement(Layer, {\n className: \"recharts-polar-angle-axis-ticks\"\n }, items);\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this$props4 = this.props,\n ticks = _this$props4.ticks,\n radius = _this$props4.radius,\n axisLine = _this$props4.axisLine;\n if (radius <= 0 || !ticks || !ticks.length) {\n return null;\n }\n return /*#__PURE__*/React.createElement(Layer, {\n className: clsx('recharts-polar-angle-axis', this.props.className)\n }, axisLine && this.renderAxisLine(), this.renderTicks());\n }\n }], [{\n key: \"renderTickItem\",\n value: function renderTickItem(option, props, value) {\n var tickItem;\n if ( /*#__PURE__*/React.isValidElement(option)) {\n tickItem = /*#__PURE__*/React.cloneElement(option, props);\n } else if (isFunction(option)) {\n tickItem = option(props);\n } else {\n tickItem = /*#__PURE__*/React.createElement(Text, _extends({}, props, {\n className: \"recharts-polar-angle-axis-tick-value\"\n }), value);\n }\n return tickItem;\n }\n }]);\n}(PureComponent);\n_defineProperty(PolarAngleAxis, \"displayName\", 'PolarAngleAxis');\n_defineProperty(PolarAngleAxis, \"axisType\", 'angleAxis');\n_defineProperty(PolarAngleAxis, \"defaultProps\", {\n type: 'category',\n angleAxisId: 0,\n scale: 'auto',\n cx: 0,\n cy: 0,\n orientation: 'outer',\n axisLine: true,\n tickLine: true,\n tickSize: 8,\n tick: true,\n hide: false,\n allowDuplicatedCategory: true\n});", "var _Pie;\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Render sectors of a pie\n */\nimport React, { PureComponent } from 'react';\nimport Animate from 'react-smooth';\nimport get from 'lodash/get';\nimport isEqual from 'lodash/isEqual';\nimport isNil from 'lodash/isNil';\nimport isFunction from 'lodash/isFunction';\nimport clsx from 'clsx';\nimport { Layer } from '../container/Layer';\nimport { Curve } from '../shape/Curve';\nimport { Text } from '../component/Text';\nimport { Label } from '../component/Label';\nimport { LabelList } from '../component/LabelList';\nimport { Cell } from '../component/Cell';\nimport { findAllByType, filterProps } from '../util/ReactUtils';\nimport { Global } from '../util/Global';\nimport { polarToCartesian, getMaxRadius } from '../util/PolarUtils';\nimport { isNumber, getPercentValue, mathSign, interpolateNumber, uniqueId } from '../util/DataUtils';\nimport { getValueByDataKey } from '../util/ChartUtils';\nimport { warn } from '../util/LogUtils';\nimport { adaptEventsOfChild } from '../util/types';\nimport { Shape } from '../util/ActiveShapeUtils';\nexport var Pie = /*#__PURE__*/function (_PureComponent) {\n function Pie(props) {\n var _this;\n _classCallCheck(this, Pie);\n _this = _callSuper(this, Pie, [props]);\n _defineProperty(_this, \"pieRef\", null);\n _defineProperty(_this, \"sectorRefs\", []);\n _defineProperty(_this, \"id\", uniqueId('recharts-pie-'));\n _defineProperty(_this, \"handleAnimationEnd\", function () {\n var onAnimationEnd = _this.props.onAnimationEnd;\n _this.setState({\n isAnimationFinished: true\n });\n if (isFunction(onAnimationEnd)) {\n onAnimationEnd();\n }\n });\n _defineProperty(_this, \"handleAnimationStart\", function () {\n var onAnimationStart = _this.props.onAnimationStart;\n _this.setState({\n isAnimationFinished: false\n });\n if (isFunction(onAnimationStart)) {\n onAnimationStart();\n }\n });\n _this.state = {\n isAnimationFinished: !props.isAnimationActive,\n prevIsAnimationActive: props.isAnimationActive,\n prevAnimationId: props.animationId,\n sectorToFocus: 0\n };\n return _this;\n }\n _inherits(Pie, _PureComponent);\n return _createClass(Pie, [{\n key: \"isActiveIndex\",\n value: function isActiveIndex(i) {\n var activeIndex = this.props.activeIndex;\n if (Array.isArray(activeIndex)) {\n return activeIndex.indexOf(i) !== -1;\n }\n return i === activeIndex;\n }\n }, {\n key: \"hasActiveIndex\",\n value: function hasActiveIndex() {\n var activeIndex = this.props.activeIndex;\n return Array.isArray(activeIndex) ? activeIndex.length !== 0 : activeIndex || activeIndex === 0;\n }\n }, {\n key: \"renderLabels\",\n value: function renderLabels(sectors) {\n var isAnimationActive = this.props.isAnimationActive;\n if (isAnimationActive && !this.state.isAnimationFinished) {\n return null;\n }\n var _this$props = this.props,\n label = _this$props.label,\n labelLine = _this$props.labelLine,\n dataKey = _this$props.dataKey,\n valueKey = _this$props.valueKey;\n var pieProps = filterProps(this.props, false);\n var customLabelProps = filterProps(label, false);\n var customLabelLineProps = filterProps(labelLine, false);\n var offsetRadius = label && label.offsetRadius || 20;\n var labels = sectors.map(function (entry, i) {\n var midAngle = (entry.startAngle + entry.endAngle) / 2;\n var endPoint = polarToCartesian(entry.cx, entry.cy, entry.outerRadius + offsetRadius, midAngle);\n var labelProps = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, pieProps), entry), {}, {\n stroke: 'none'\n }, customLabelProps), {}, {\n index: i,\n textAnchor: Pie.getTextAnchor(endPoint.x, entry.cx)\n }, endPoint);\n var lineProps = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, pieProps), entry), {}, {\n fill: 'none',\n stroke: entry.fill\n }, customLabelLineProps), {}, {\n index: i,\n points: [polarToCartesian(entry.cx, entry.cy, entry.outerRadius, midAngle), endPoint]\n });\n var realDataKey = dataKey;\n // TODO: compatible to lower versions\n if (isNil(dataKey) && isNil(valueKey)) {\n realDataKey = 'value';\n } else if (isNil(dataKey)) {\n realDataKey = valueKey;\n }\n return (\n /*#__PURE__*/\n // eslint-disable-next-line react/no-array-index-key\n React.createElement(Layer, {\n key: \"label-\".concat(entry.startAngle, \"-\").concat(entry.endAngle, \"-\").concat(entry.midAngle, \"-\").concat(i)\n }, labelLine && Pie.renderLabelLineItem(labelLine, lineProps, 'line'), Pie.renderLabelItem(label, labelProps, getValueByDataKey(entry, realDataKey)))\n );\n });\n return /*#__PURE__*/React.createElement(Layer, {\n className: \"recharts-pie-labels\"\n }, labels);\n }\n }, {\n key: \"renderSectorsStatically\",\n value: function renderSectorsStatically(sectors) {\n var _this2 = this;\n var _this$props2 = this.props,\n activeShape = _this$props2.activeShape,\n blendStroke = _this$props2.blendStroke,\n inactiveShapeProp = _this$props2.inactiveShape;\n return sectors.map(function (entry, i) {\n if ((entry === null || entry === void 0 ? void 0 : entry.startAngle) === 0 && (entry === null || entry === void 0 ? void 0 : entry.endAngle) === 0 && sectors.length !== 1) return null;\n var isActive = _this2.isActiveIndex(i);\n var inactiveShape = inactiveShapeProp && _this2.hasActiveIndex() ? inactiveShapeProp : null;\n var sectorOptions = isActive ? activeShape : inactiveShape;\n var sectorProps = _objectSpread(_objectSpread({}, entry), {}, {\n stroke: blendStroke ? entry.fill : entry.stroke,\n tabIndex: -1\n });\n return /*#__PURE__*/React.createElement(Layer, _extends({\n ref: function ref(_ref) {\n if (_ref && !_this2.sectorRefs.includes(_ref)) {\n _this2.sectorRefs.push(_ref);\n }\n },\n tabIndex: -1,\n className: \"recharts-pie-sector\"\n }, adaptEventsOfChild(_this2.props, entry, i), {\n // eslint-disable-next-line react/no-array-index-key\n key: \"sector-\".concat(entry === null || entry === void 0 ? void 0 : entry.startAngle, \"-\").concat(entry === null || entry === void 0 ? void 0 : entry.endAngle, \"-\").concat(entry.midAngle, \"-\").concat(i)\n }), /*#__PURE__*/React.createElement(Shape, _extends({\n option: sectorOptions,\n isActive: isActive,\n shapeType: \"sector\"\n }, sectorProps)));\n });\n }\n }, {\n key: \"renderSectorsWithAnimation\",\n value: function renderSectorsWithAnimation() {\n var _this3 = this;\n var _this$props3 = this.props,\n sectors = _this$props3.sectors,\n isAnimationActive = _this$props3.isAnimationActive,\n animationBegin = _this$props3.animationBegin,\n animationDuration = _this$props3.animationDuration,\n animationEasing = _this$props3.animationEasing,\n animationId = _this$props3.animationId;\n var _this$state = this.state,\n prevSectors = _this$state.prevSectors,\n prevIsAnimationActive = _this$state.prevIsAnimationActive;\n return /*#__PURE__*/React.createElement(Animate, {\n begin: animationBegin,\n duration: animationDuration,\n isActive: isAnimationActive,\n easing: animationEasing,\n from: {\n t: 0\n },\n to: {\n t: 1\n },\n key: \"pie-\".concat(animationId, \"-\").concat(prevIsAnimationActive),\n onAnimationStart: this.handleAnimationStart,\n onAnimationEnd: this.handleAnimationEnd\n }, function (_ref2) {\n var t = _ref2.t;\n var stepData = [];\n var first = sectors && sectors[0];\n var curAngle = first.startAngle;\n sectors.forEach(function (entry, index) {\n var prev = prevSectors && prevSectors[index];\n var paddingAngle = index > 0 ? get(entry, 'paddingAngle', 0) : 0;\n if (prev) {\n var angleIp = interpolateNumber(prev.endAngle - prev.startAngle, entry.endAngle - entry.startAngle);\n var latest = _objectSpread(_objectSpread({}, entry), {}, {\n startAngle: curAngle + paddingAngle,\n endAngle: curAngle + angleIp(t) + paddingAngle\n });\n stepData.push(latest);\n curAngle = latest.endAngle;\n } else {\n var endAngle = entry.endAngle,\n startAngle = entry.startAngle;\n var interpolatorAngle = interpolateNumber(0, endAngle - startAngle);\n var deltaAngle = interpolatorAngle(t);\n var _latest = _objectSpread(_objectSpread({}, entry), {}, {\n startAngle: curAngle + paddingAngle,\n endAngle: curAngle + deltaAngle + paddingAngle\n });\n stepData.push(_latest);\n curAngle = _latest.endAngle;\n }\n });\n return /*#__PURE__*/React.createElement(Layer, null, _this3.renderSectorsStatically(stepData));\n });\n }\n }, {\n key: \"attachKeyboardHandlers\",\n value: function attachKeyboardHandlers(pieRef) {\n var _this4 = this;\n // eslint-disable-next-line no-param-reassign\n pieRef.onkeydown = function (e) {\n if (!e.altKey) {\n switch (e.key) {\n case 'ArrowLeft':\n {\n var next = ++_this4.state.sectorToFocus % _this4.sectorRefs.length;\n _this4.sectorRefs[next].focus();\n _this4.setState({\n sectorToFocus: next\n });\n break;\n }\n case 'ArrowRight':\n {\n var _next = --_this4.state.sectorToFocus < 0 ? _this4.sectorRefs.length - 1 : _this4.state.sectorToFocus % _this4.sectorRefs.length;\n _this4.sectorRefs[_next].focus();\n _this4.setState({\n sectorToFocus: _next\n });\n break;\n }\n case 'Escape':\n {\n _this4.sectorRefs[_this4.state.sectorToFocus].blur();\n _this4.setState({\n sectorToFocus: 0\n });\n break;\n }\n default:\n {\n // There is nothing to do here\n }\n }\n }\n };\n }\n }, {\n key: \"renderSectors\",\n value: function renderSectors() {\n var _this$props4 = this.props,\n sectors = _this$props4.sectors,\n isAnimationActive = _this$props4.isAnimationActive;\n var prevSectors = this.state.prevSectors;\n if (isAnimationActive && sectors && sectors.length && (!prevSectors || !isEqual(prevSectors, sectors))) {\n return this.renderSectorsWithAnimation();\n }\n return this.renderSectorsStatically(sectors);\n }\n }, {\n key: \"componentDidMount\",\n value: function componentDidMount() {\n if (this.pieRef) {\n this.attachKeyboardHandlers(this.pieRef);\n }\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this5 = this;\n var _this$props5 = this.props,\n hide = _this$props5.hide,\n sectors = _this$props5.sectors,\n className = _this$props5.className,\n label = _this$props5.label,\n cx = _this$props5.cx,\n cy = _this$props5.cy,\n innerRadius = _this$props5.innerRadius,\n outerRadius = _this$props5.outerRadius,\n isAnimationActive = _this$props5.isAnimationActive;\n var isAnimationFinished = this.state.isAnimationFinished;\n if (hide || !sectors || !sectors.length || !isNumber(cx) || !isNumber(cy) || !isNumber(innerRadius) || !isNumber(outerRadius)) {\n return null;\n }\n var layerClass = clsx('recharts-pie', className);\n return /*#__PURE__*/React.createElement(Layer, {\n tabIndex: this.props.rootTabIndex,\n className: layerClass,\n ref: function ref(_ref3) {\n _this5.pieRef = _ref3;\n }\n }, this.renderSectors(), label && this.renderLabels(sectors), Label.renderCallByParent(this.props, null, false), (!isAnimationActive || isAnimationFinished) && LabelList.renderCallByParent(this.props, sectors, false));\n }\n }], [{\n key: \"getDerivedStateFromProps\",\n value: function getDerivedStateFromProps(nextProps, prevState) {\n if (prevState.prevIsAnimationActive !== nextProps.isAnimationActive) {\n return {\n prevIsAnimationActive: nextProps.isAnimationActive,\n prevAnimationId: nextProps.animationId,\n curSectors: nextProps.sectors,\n prevSectors: [],\n isAnimationFinished: true\n };\n }\n if (nextProps.isAnimationActive && nextProps.animationId !== prevState.prevAnimationId) {\n return {\n prevAnimationId: nextProps.animationId,\n curSectors: nextProps.sectors,\n prevSectors: prevState.curSectors,\n isAnimationFinished: true\n };\n }\n if (nextProps.sectors !== prevState.curSectors) {\n return {\n curSectors: nextProps.sectors,\n isAnimationFinished: true\n };\n }\n return null;\n }\n }, {\n key: \"getTextAnchor\",\n value: function getTextAnchor(x, cx) {\n if (x > cx) {\n return 'start';\n }\n if (x < cx) {\n return 'end';\n }\n return 'middle';\n }\n }, {\n key: \"renderLabelLineItem\",\n value: function renderLabelLineItem(option, props, key) {\n if ( /*#__PURE__*/React.isValidElement(option)) {\n return /*#__PURE__*/React.cloneElement(option, props);\n }\n if (isFunction(option)) {\n return option(props);\n }\n var className = clsx('recharts-pie-label-line', typeof option !== 'boolean' ? option.className : '');\n return /*#__PURE__*/React.createElement(Curve, _extends({}, props, {\n key: key,\n type: \"linear\",\n className: className\n }));\n }\n }, {\n key: \"renderLabelItem\",\n value: function renderLabelItem(option, props, value) {\n if ( /*#__PURE__*/React.isValidElement(option)) {\n return /*#__PURE__*/React.cloneElement(option, props);\n }\n var label = value;\n if (isFunction(option)) {\n label = option(props);\n if ( /*#__PURE__*/React.isValidElement(label)) {\n return label;\n }\n }\n var className = clsx('recharts-pie-label-text', typeof option !== 'boolean' && !isFunction(option) ? option.className : '');\n return /*#__PURE__*/React.createElement(Text, _extends({}, props, {\n alignmentBaseline: \"middle\",\n className: className\n }), label);\n }\n }]);\n}(PureComponent);\n_Pie = Pie;\n_defineProperty(Pie, \"displayName\", 'Pie');\n_defineProperty(Pie, \"defaultProps\", {\n stroke: '#fff',\n fill: '#808080',\n legendType: 'rect',\n cx: '50%',\n cy: '50%',\n startAngle: 0,\n endAngle: 360,\n innerRadius: 0,\n outerRadius: '80%',\n paddingAngle: 0,\n labelLine: true,\n hide: false,\n minAngle: 0,\n isAnimationActive: !Global.isSsr,\n animationBegin: 400,\n animationDuration: 1500,\n animationEasing: 'ease',\n nameKey: 'name',\n blendStroke: false,\n rootTabIndex: 0\n});\n_defineProperty(Pie, \"parseDeltaAngle\", function (startAngle, endAngle) {\n var sign = mathSign(endAngle - startAngle);\n var deltaAngle = Math.min(Math.abs(endAngle - startAngle), 360);\n return sign * deltaAngle;\n});\n_defineProperty(Pie, \"getRealPieData\", function (itemProps) {\n var data = itemProps.data,\n children = itemProps.children;\n var presentationProps = filterProps(itemProps, false);\n var cells = findAllByType(children, Cell);\n if (data && data.length) {\n return data.map(function (entry, index) {\n return _objectSpread(_objectSpread(_objectSpread({\n payload: entry\n }, presentationProps), entry), cells && cells[index] && cells[index].props);\n });\n }\n if (cells && cells.length) {\n return cells.map(function (cell) {\n return _objectSpread(_objectSpread({}, presentationProps), cell.props);\n });\n }\n return [];\n});\n_defineProperty(Pie, \"parseCoordinateOfPie\", function (itemProps, offset) {\n var top = offset.top,\n left = offset.left,\n width = offset.width,\n height = offset.height;\n var maxPieRadius = getMaxRadius(width, height);\n var cx = left + getPercentValue(itemProps.cx, width, width / 2);\n var cy = top + getPercentValue(itemProps.cy, height, height / 2);\n var innerRadius = getPercentValue(itemProps.innerRadius, maxPieRadius, 0);\n var outerRadius = getPercentValue(itemProps.outerRadius, maxPieRadius, maxPieRadius * 0.8);\n var maxRadius = itemProps.maxRadius || Math.sqrt(width * width + height * height) / 2;\n return {\n cx: cx,\n cy: cy,\n innerRadius: innerRadius,\n outerRadius: outerRadius,\n maxRadius: maxRadius\n };\n});\n_defineProperty(Pie, \"getComposedData\", function (_ref4) {\n var item = _ref4.item,\n offset = _ref4.offset;\n var itemProps = item.type.defaultProps !== undefined ? _objectSpread(_objectSpread({}, item.type.defaultProps), item.props) : item.props;\n var pieData = _Pie.getRealPieData(itemProps);\n if (!pieData || !pieData.length) {\n return null;\n }\n var cornerRadius = itemProps.cornerRadius,\n startAngle = itemProps.startAngle,\n endAngle = itemProps.endAngle,\n paddingAngle = itemProps.paddingAngle,\n dataKey = itemProps.dataKey,\n nameKey = itemProps.nameKey,\n valueKey = itemProps.valueKey,\n tooltipType = itemProps.tooltipType;\n var minAngle = Math.abs(itemProps.minAngle);\n var coordinate = _Pie.parseCoordinateOfPie(itemProps, offset);\n var deltaAngle = _Pie.parseDeltaAngle(startAngle, endAngle);\n var absDeltaAngle = Math.abs(deltaAngle);\n var realDataKey = dataKey;\n if (isNil(dataKey) && isNil(valueKey)) {\n warn(false, \"Use \\\"dataKey\\\" to specify the value of pie,\\n the props \\\"valueKey\\\" will be deprecated in 1.1.0\");\n realDataKey = 'value';\n } else if (isNil(dataKey)) {\n warn(false, \"Use \\\"dataKey\\\" to specify the value of pie,\\n the props \\\"valueKey\\\" will be deprecated in 1.1.0\");\n realDataKey = valueKey;\n }\n var notZeroItemCount = pieData.filter(function (entry) {\n return getValueByDataKey(entry, realDataKey, 0) !== 0;\n }).length;\n var totalPadingAngle = (absDeltaAngle >= 360 ? notZeroItemCount : notZeroItemCount - 1) * paddingAngle;\n var realTotalAngle = absDeltaAngle - notZeroItemCount * minAngle - totalPadingAngle;\n var sum = pieData.reduce(function (result, entry) {\n var val = getValueByDataKey(entry, realDataKey, 0);\n return result + (isNumber(val) ? val : 0);\n }, 0);\n var sectors;\n if (sum > 0) {\n var prev;\n sectors = pieData.map(function (entry, i) {\n var val = getValueByDataKey(entry, realDataKey, 0);\n var name = getValueByDataKey(entry, nameKey, i);\n var percent = (isNumber(val) ? val : 0) / sum;\n var tempStartAngle;\n if (i) {\n tempStartAngle = prev.endAngle + mathSign(deltaAngle) * paddingAngle * (val !== 0 ? 1 : 0);\n } else {\n tempStartAngle = startAngle;\n }\n var tempEndAngle = tempStartAngle + mathSign(deltaAngle) * ((val !== 0 ? minAngle : 0) + percent * realTotalAngle);\n var midAngle = (tempStartAngle + tempEndAngle) / 2;\n var middleRadius = (coordinate.innerRadius + coordinate.outerRadius) / 2;\n var tooltipPayload = [{\n name: name,\n value: val,\n payload: entry,\n dataKey: realDataKey,\n type: tooltipType\n }];\n var tooltipPosition = polarToCartesian(coordinate.cx, coordinate.cy, middleRadius, midAngle);\n prev = _objectSpread(_objectSpread(_objectSpread({\n percent: percent,\n cornerRadius: cornerRadius,\n name: name,\n tooltipPayload: tooltipPayload,\n midAngle: midAngle,\n middleRadius: middleRadius,\n tooltipPosition: tooltipPosition\n }, entry), coordinate), {}, {\n value: getValueByDataKey(entry, realDataKey),\n startAngle: tempStartAngle,\n endAngle: tempEndAngle,\n payload: entry,\n paddingAngle: mathSign(deltaAngle) * paddingAngle\n });\n return prev;\n });\n }\n return _objectSpread(_objectSpread({}, coordinate), {}, {\n sectors: sectors,\n data: pieData\n });\n});", "var _excluded = [\"option\", \"shapeType\", \"propTransformer\", \"activeClassName\", \"isActive\"];\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nimport React, { isValidElement, cloneElement } from 'react';\nimport isFunction from 'lodash/isFunction';\nimport isPlainObject from 'lodash/isPlainObject';\nimport isBoolean from 'lodash/isBoolean';\nimport isEqual from 'lodash/isEqual';\nimport { Rectangle } from '../shape/Rectangle';\nimport { Trapezoid } from '../shape/Trapezoid';\nimport { Sector } from '../shape/Sector';\nimport { Layer } from '../container/Layer';\nimport { Symbols } from '../shape/Symbols';\n\n/**\n * This is an abstraction for rendering a user defined prop for a customized shape in several forms.\n *\n * is the root and will handle taking in:\n * - an object of svg properties\n * - a boolean\n * - a render prop(inline function that returns jsx)\n * - a react element\n *\n * is a subcomponent of and used to match a component\n * to the value of props.shapeType that is passed to the root.\n *\n */\n\nfunction defaultPropTransformer(option, props) {\n return _objectSpread(_objectSpread({}, props), option);\n}\nfunction isSymbolsProps(shapeType, _elementProps) {\n return shapeType === 'symbols';\n}\nfunction ShapeSelector(_ref) {\n var shapeType = _ref.shapeType,\n elementProps = _ref.elementProps;\n switch (shapeType) {\n case 'rectangle':\n return /*#__PURE__*/React.createElement(Rectangle, elementProps);\n case 'trapezoid':\n return /*#__PURE__*/React.createElement(Trapezoid, elementProps);\n case 'sector':\n return /*#__PURE__*/React.createElement(Sector, elementProps);\n case 'symbols':\n if (isSymbolsProps(shapeType, elementProps)) {\n return /*#__PURE__*/React.createElement(Symbols, elementProps);\n }\n break;\n default:\n return null;\n }\n}\nexport function getPropsFromShapeOption(option) {\n if ( /*#__PURE__*/isValidElement(option)) {\n return option.props;\n }\n return option;\n}\nexport function Shape(_ref2) {\n var option = _ref2.option,\n shapeType = _ref2.shapeType,\n _ref2$propTransformer = _ref2.propTransformer,\n propTransformer = _ref2$propTransformer === void 0 ? defaultPropTransformer : _ref2$propTransformer,\n _ref2$activeClassName = _ref2.activeClassName,\n activeClassName = _ref2$activeClassName === void 0 ? 'recharts-active-shape' : _ref2$activeClassName,\n isActive = _ref2.isActive,\n props = _objectWithoutProperties(_ref2, _excluded);\n var shape;\n if ( /*#__PURE__*/isValidElement(option)) {\n shape = /*#__PURE__*/cloneElement(option, _objectSpread(_objectSpread({}, props), getPropsFromShapeOption(option)));\n } else if (isFunction(option)) {\n shape = option(props);\n } else if (isPlainObject(option) && !isBoolean(option)) {\n var nextProps = propTransformer(option, props);\n shape = /*#__PURE__*/React.createElement(ShapeSelector, {\n shapeType: shapeType,\n elementProps: nextProps\n });\n } else {\n var elementProps = props;\n shape = /*#__PURE__*/React.createElement(ShapeSelector, {\n shapeType: shapeType,\n elementProps: elementProps\n });\n }\n if (isActive) {\n return /*#__PURE__*/React.createElement(Layer, {\n className: activeClassName\n }, shape);\n }\n return shape;\n}\n\n/**\n * This is an abstraction to handle identifying the active index from a tooltip mouse interaction\n */\n\nexport function isFunnel(graphicalItem, _item) {\n return _item != null && 'trapezoids' in graphicalItem.props;\n}\nexport function isPie(graphicalItem, _item) {\n return _item != null && 'sectors' in graphicalItem.props;\n}\nexport function isScatter(graphicalItem, _item) {\n return _item != null && 'points' in graphicalItem.props;\n}\nexport function compareFunnel(shapeData, activeTooltipItem) {\n var _activeTooltipItem$la, _activeTooltipItem$la2;\n var xMatches = shapeData.x === (activeTooltipItem === null || activeTooltipItem === void 0 || (_activeTooltipItem$la = activeTooltipItem.labelViewBox) === null || _activeTooltipItem$la === void 0 ? void 0 : _activeTooltipItem$la.x) || shapeData.x === activeTooltipItem.x;\n var yMatches = shapeData.y === (activeTooltipItem === null || activeTooltipItem === void 0 || (_activeTooltipItem$la2 = activeTooltipItem.labelViewBox) === null || _activeTooltipItem$la2 === void 0 ? void 0 : _activeTooltipItem$la2.y) || shapeData.y === activeTooltipItem.y;\n return xMatches && yMatches;\n}\nexport function comparePie(shapeData, activeTooltipItem) {\n var startAngleMatches = shapeData.endAngle === activeTooltipItem.endAngle;\n var endAngleMatches = shapeData.startAngle === activeTooltipItem.startAngle;\n return startAngleMatches && endAngleMatches;\n}\nexport function compareScatter(shapeData, activeTooltipItem) {\n var xMatches = shapeData.x === activeTooltipItem.x;\n var yMatches = shapeData.y === activeTooltipItem.y;\n var zMatches = shapeData.z === activeTooltipItem.z;\n return xMatches && yMatches && zMatches;\n}\nfunction getComparisonFn(graphicalItem, activeItem) {\n var comparison;\n if (isFunnel(graphicalItem, activeItem)) {\n comparison = compareFunnel;\n } else if (isPie(graphicalItem, activeItem)) {\n comparison = comparePie;\n } else if (isScatter(graphicalItem, activeItem)) {\n comparison = compareScatter;\n }\n return comparison;\n}\nfunction getShapeDataKey(graphicalItem, activeItem) {\n var shapeKey;\n if (isFunnel(graphicalItem, activeItem)) {\n shapeKey = 'trapezoids';\n } else if (isPie(graphicalItem, activeItem)) {\n shapeKey = 'sectors';\n } else if (isScatter(graphicalItem, activeItem)) {\n shapeKey = 'points';\n }\n return shapeKey;\n}\nfunction getActiveShapeTooltipPayload(graphicalItem, activeItem) {\n if (isFunnel(graphicalItem, activeItem)) {\n var _activeItem$tooltipPa;\n return (_activeItem$tooltipPa = activeItem.tooltipPayload) === null || _activeItem$tooltipPa === void 0 || (_activeItem$tooltipPa = _activeItem$tooltipPa[0]) === null || _activeItem$tooltipPa === void 0 || (_activeItem$tooltipPa = _activeItem$tooltipPa.payload) === null || _activeItem$tooltipPa === void 0 ? void 0 : _activeItem$tooltipPa.payload;\n }\n if (isPie(graphicalItem, activeItem)) {\n var _activeItem$tooltipPa2;\n return (_activeItem$tooltipPa2 = activeItem.tooltipPayload) === null || _activeItem$tooltipPa2 === void 0 || (_activeItem$tooltipPa2 = _activeItem$tooltipPa2[0]) === null || _activeItem$tooltipPa2 === void 0 || (_activeItem$tooltipPa2 = _activeItem$tooltipPa2.payload) === null || _activeItem$tooltipPa2 === void 0 ? void 0 : _activeItem$tooltipPa2.payload;\n }\n if (isScatter(graphicalItem, activeItem)) {\n return activeItem.payload;\n }\n return {};\n}\n/**\n *\n * @param {GetActiveShapeIndexForTooltip} arg an object of incoming attributes from Tooltip\n * @returns {number}\n *\n * To handle possible duplicates in the data set,\n * match both the data value of the active item to a data value on a graph item,\n * and match the mouse coordinates of the active item to the coordinates of in a particular components shape data.\n * This assumes equal lengths of shape objects to data items.\n */\nexport function getActiveShapeIndexForTooltip(_ref3) {\n var activeTooltipItem = _ref3.activeTooltipItem,\n graphicalItem = _ref3.graphicalItem,\n itemData = _ref3.itemData;\n var shapeKey = getShapeDataKey(graphicalItem, activeTooltipItem);\n var tooltipPayload = getActiveShapeTooltipPayload(graphicalItem, activeTooltipItem);\n var activeItemMatches = itemData.filter(function (datum, dataIndex) {\n var valuesMatch = isEqual(tooltipPayload, datum);\n var mouseCoordinateMatches = graphicalItem.props[shapeKey].filter(function (shapeData) {\n var comparison = getComparisonFn(graphicalItem, activeTooltipItem);\n return comparison(shapeData, activeTooltipItem);\n });\n\n // get the last index in case of multiple matches\n var indexOfMouseCoordinates = graphicalItem.props[shapeKey].indexOf(mouseCoordinateMatches[mouseCoordinateMatches.length - 1]);\n var coordinatesMatch = dataIndex === indexOfMouseCoordinates;\n return valuesMatch && coordinatesMatch;\n });\n\n // get the last index in case of multiple matches\n var activeIndex = itemData.indexOf(activeItemMatches[activeItemMatches.length - 1]);\n return activeIndex;\n}", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Rectangle\n */\nimport React, { useEffect, useRef, useState } from 'react';\nimport clsx from 'clsx';\nimport Animate from 'react-smooth';\nimport { filterProps } from '../util/ReactUtils';\nvar getTrapezoidPath = function getTrapezoidPath(x, y, upperWidth, lowerWidth, height) {\n var widthGap = upperWidth - lowerWidth;\n var path;\n path = \"M \".concat(x, \",\").concat(y);\n path += \"L \".concat(x + upperWidth, \",\").concat(y);\n path += \"L \".concat(x + upperWidth - widthGap / 2, \",\").concat(y + height);\n path += \"L \".concat(x + upperWidth - widthGap / 2 - lowerWidth, \",\").concat(y + height);\n path += \"L \".concat(x, \",\").concat(y, \" Z\");\n return path;\n};\nvar defaultProps = {\n x: 0,\n y: 0,\n upperWidth: 0,\n lowerWidth: 0,\n height: 0,\n isUpdateAnimationActive: false,\n animationBegin: 0,\n animationDuration: 1500,\n animationEasing: 'ease'\n};\nexport var Trapezoid = function Trapezoid(props) {\n var trapezoidProps = _objectSpread(_objectSpread({}, defaultProps), props);\n var pathRef = useRef();\n var _useState = useState(-1),\n _useState2 = _slicedToArray(_useState, 2),\n totalLength = _useState2[0],\n setTotalLength = _useState2[1];\n useEffect(function () {\n if (pathRef.current && pathRef.current.getTotalLength) {\n try {\n var pathTotalLength = pathRef.current.getTotalLength();\n if (pathTotalLength) {\n setTotalLength(pathTotalLength);\n }\n } catch (err) {\n // calculate total length error\n }\n }\n }, []);\n var x = trapezoidProps.x,\n y = trapezoidProps.y,\n upperWidth = trapezoidProps.upperWidth,\n lowerWidth = trapezoidProps.lowerWidth,\n height = trapezoidProps.height,\n className = trapezoidProps.className;\n var animationEasing = trapezoidProps.animationEasing,\n animationDuration = trapezoidProps.animationDuration,\n animationBegin = trapezoidProps.animationBegin,\n isUpdateAnimationActive = trapezoidProps.isUpdateAnimationActive;\n if (x !== +x || y !== +y || upperWidth !== +upperWidth || lowerWidth !== +lowerWidth || height !== +height || upperWidth === 0 && lowerWidth === 0 || height === 0) {\n return null;\n }\n var layerClass = clsx('recharts-trapezoid', className);\n if (!isUpdateAnimationActive) {\n return /*#__PURE__*/React.createElement(\"g\", null, /*#__PURE__*/React.createElement(\"path\", _extends({}, filterProps(trapezoidProps, true), {\n className: layerClass,\n d: getTrapezoidPath(x, y, upperWidth, lowerWidth, height)\n })));\n }\n return /*#__PURE__*/React.createElement(Animate, {\n canBegin: totalLength > 0,\n from: {\n upperWidth: 0,\n lowerWidth: 0,\n height: height,\n x: x,\n y: y\n },\n to: {\n upperWidth: upperWidth,\n lowerWidth: lowerWidth,\n height: height,\n x: x,\n y: y\n },\n duration: animationDuration,\n animationEasing: animationEasing,\n isActive: isUpdateAnimationActive\n }, function (_ref) {\n var currUpperWidth = _ref.upperWidth,\n currLowerWidth = _ref.lowerWidth,\n currHeight = _ref.height,\n currX = _ref.x,\n currY = _ref.y;\n return /*#__PURE__*/React.createElement(Animate, {\n canBegin: totalLength > 0,\n from: \"0px \".concat(totalLength === -1 ? 1 : totalLength, \"px\"),\n to: \"\".concat(totalLength, \"px 0px\"),\n attributeName: \"strokeDasharray\",\n begin: animationBegin,\n duration: animationDuration,\n easing: animationEasing\n }, /*#__PURE__*/React.createElement(\"path\", _extends({}, filterProps(trapezoidProps, true), {\n className: layerClass,\n d: getTrapezoidPath(currX, currY, currUpperWidth, currLowerWidth, currHeight),\n ref: pathRef\n })));\n });\n};", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Brush\n */\nimport React, { PureComponent, Children } from 'react';\nimport clsx from 'clsx';\nimport { scalePoint } from 'victory-vendor/d3-scale';\nimport isFunction from 'lodash/isFunction';\nimport range from 'lodash/range';\nimport { Layer } from '../container/Layer';\nimport { Text } from '../component/Text';\nimport { getValueByDataKey } from '../util/ChartUtils';\nimport { isNumber } from '../util/DataUtils';\nimport { generatePrefixStyle } from '../util/CssPrefixUtils';\nimport { filterProps } from '../util/ReactUtils';\nvar createScale = function createScale(_ref) {\n var data = _ref.data,\n startIndex = _ref.startIndex,\n endIndex = _ref.endIndex,\n x = _ref.x,\n width = _ref.width,\n travellerWidth = _ref.travellerWidth;\n if (!data || !data.length) {\n return {};\n }\n var len = data.length;\n var scale = scalePoint().domain(range(0, len)).range([x, x + width - travellerWidth]);\n var scaleValues = scale.domain().map(function (entry) {\n return scale(entry);\n });\n return {\n isTextActive: false,\n isSlideMoving: false,\n isTravellerMoving: false,\n isTravellerFocused: false,\n startX: scale(startIndex),\n endX: scale(endIndex),\n scale: scale,\n scaleValues: scaleValues\n };\n};\nvar isTouch = function isTouch(e) {\n return e.changedTouches && !!e.changedTouches.length;\n};\nexport var Brush = /*#__PURE__*/function (_PureComponent) {\n function Brush(props) {\n var _this;\n _classCallCheck(this, Brush);\n _this = _callSuper(this, Brush, [props]);\n _defineProperty(_this, \"handleDrag\", function (e) {\n if (_this.leaveTimer) {\n clearTimeout(_this.leaveTimer);\n _this.leaveTimer = null;\n }\n if (_this.state.isTravellerMoving) {\n _this.handleTravellerMove(e);\n } else if (_this.state.isSlideMoving) {\n _this.handleSlideDrag(e);\n }\n });\n _defineProperty(_this, \"handleTouchMove\", function (e) {\n if (e.changedTouches != null && e.changedTouches.length > 0) {\n _this.handleDrag(e.changedTouches[0]);\n }\n });\n _defineProperty(_this, \"handleDragEnd\", function () {\n _this.setState({\n isTravellerMoving: false,\n isSlideMoving: false\n }, function () {\n var _this$props = _this.props,\n endIndex = _this$props.endIndex,\n onDragEnd = _this$props.onDragEnd,\n startIndex = _this$props.startIndex;\n onDragEnd === null || onDragEnd === void 0 || onDragEnd({\n endIndex: endIndex,\n startIndex: startIndex\n });\n });\n _this.detachDragEndListener();\n });\n _defineProperty(_this, \"handleLeaveWrapper\", function () {\n if (_this.state.isTravellerMoving || _this.state.isSlideMoving) {\n _this.leaveTimer = window.setTimeout(_this.handleDragEnd, _this.props.leaveTimeOut);\n }\n });\n _defineProperty(_this, \"handleEnterSlideOrTraveller\", function () {\n _this.setState({\n isTextActive: true\n });\n });\n _defineProperty(_this, \"handleLeaveSlideOrTraveller\", function () {\n _this.setState({\n isTextActive: false\n });\n });\n _defineProperty(_this, \"handleSlideDragStart\", function (e) {\n var event = isTouch(e) ? e.changedTouches[0] : e;\n _this.setState({\n isTravellerMoving: false,\n isSlideMoving: true,\n slideMoveStartX: event.pageX\n });\n _this.attachDragEndListener();\n });\n _this.travellerDragStartHandlers = {\n startX: _this.handleTravellerDragStart.bind(_this, 'startX'),\n endX: _this.handleTravellerDragStart.bind(_this, 'endX')\n };\n _this.state = {};\n return _this;\n }\n _inherits(Brush, _PureComponent);\n return _createClass(Brush, [{\n key: \"componentWillUnmount\",\n value: function componentWillUnmount() {\n if (this.leaveTimer) {\n clearTimeout(this.leaveTimer);\n this.leaveTimer = null;\n }\n this.detachDragEndListener();\n }\n }, {\n key: \"getIndex\",\n value: function getIndex(_ref2) {\n var startX = _ref2.startX,\n endX = _ref2.endX;\n var scaleValues = this.state.scaleValues;\n var _this$props2 = this.props,\n gap = _this$props2.gap,\n data = _this$props2.data;\n var lastIndex = data.length - 1;\n var min = Math.min(startX, endX);\n var max = Math.max(startX, endX);\n var minIndex = Brush.getIndexInRange(scaleValues, min);\n var maxIndex = Brush.getIndexInRange(scaleValues, max);\n return {\n startIndex: minIndex - minIndex % gap,\n endIndex: maxIndex === lastIndex ? lastIndex : maxIndex - maxIndex % gap\n };\n }\n }, {\n key: \"getTextOfTick\",\n value: function getTextOfTick(index) {\n var _this$props3 = this.props,\n data = _this$props3.data,\n tickFormatter = _this$props3.tickFormatter,\n dataKey = _this$props3.dataKey;\n var text = getValueByDataKey(data[index], dataKey, index);\n return isFunction(tickFormatter) ? tickFormatter(text, index) : text;\n }\n }, {\n key: \"attachDragEndListener\",\n value: function attachDragEndListener() {\n window.addEventListener('mouseup', this.handleDragEnd, true);\n window.addEventListener('touchend', this.handleDragEnd, true);\n window.addEventListener('mousemove', this.handleDrag, true);\n }\n }, {\n key: \"detachDragEndListener\",\n value: function detachDragEndListener() {\n window.removeEventListener('mouseup', this.handleDragEnd, true);\n window.removeEventListener('touchend', this.handleDragEnd, true);\n window.removeEventListener('mousemove', this.handleDrag, true);\n }\n }, {\n key: \"handleSlideDrag\",\n value: function handleSlideDrag(e) {\n var _this$state = this.state,\n slideMoveStartX = _this$state.slideMoveStartX,\n startX = _this$state.startX,\n endX = _this$state.endX;\n var _this$props4 = this.props,\n x = _this$props4.x,\n width = _this$props4.width,\n travellerWidth = _this$props4.travellerWidth,\n startIndex = _this$props4.startIndex,\n endIndex = _this$props4.endIndex,\n onChange = _this$props4.onChange;\n var delta = e.pageX - slideMoveStartX;\n if (delta > 0) {\n delta = Math.min(delta, x + width - travellerWidth - endX, x + width - travellerWidth - startX);\n } else if (delta < 0) {\n delta = Math.max(delta, x - startX, x - endX);\n }\n var newIndex = this.getIndex({\n startX: startX + delta,\n endX: endX + delta\n });\n if ((newIndex.startIndex !== startIndex || newIndex.endIndex !== endIndex) && onChange) {\n onChange(newIndex);\n }\n this.setState({\n startX: startX + delta,\n endX: endX + delta,\n slideMoveStartX: e.pageX\n });\n }\n }, {\n key: \"handleTravellerDragStart\",\n value: function handleTravellerDragStart(id, e) {\n var event = isTouch(e) ? e.changedTouches[0] : e;\n this.setState({\n isSlideMoving: false,\n isTravellerMoving: true,\n movingTravellerId: id,\n brushMoveStartX: event.pageX\n });\n this.attachDragEndListener();\n }\n }, {\n key: \"handleTravellerMove\",\n value: function handleTravellerMove(e) {\n var _this$state2 = this.state,\n brushMoveStartX = _this$state2.brushMoveStartX,\n movingTravellerId = _this$state2.movingTravellerId,\n endX = _this$state2.endX,\n startX = _this$state2.startX;\n var prevValue = this.state[movingTravellerId];\n var _this$props5 = this.props,\n x = _this$props5.x,\n width = _this$props5.width,\n travellerWidth = _this$props5.travellerWidth,\n onChange = _this$props5.onChange,\n gap = _this$props5.gap,\n data = _this$props5.data;\n var params = {\n startX: this.state.startX,\n endX: this.state.endX\n };\n var delta = e.pageX - brushMoveStartX;\n if (delta > 0) {\n delta = Math.min(delta, x + width - travellerWidth - prevValue);\n } else if (delta < 0) {\n delta = Math.max(delta, x - prevValue);\n }\n params[movingTravellerId] = prevValue + delta;\n var newIndex = this.getIndex(params);\n var startIndex = newIndex.startIndex,\n endIndex = newIndex.endIndex;\n var isFullGap = function isFullGap() {\n var lastIndex = data.length - 1;\n if (movingTravellerId === 'startX' && (endX > startX ? startIndex % gap === 0 : endIndex % gap === 0) || endX < startX && endIndex === lastIndex || movingTravellerId === 'endX' && (endX > startX ? endIndex % gap === 0 : startIndex % gap === 0) || endX > startX && endIndex === lastIndex) {\n return true;\n }\n return false;\n };\n this.setState(_defineProperty(_defineProperty({}, movingTravellerId, prevValue + delta), \"brushMoveStartX\", e.pageX), function () {\n if (onChange) {\n if (isFullGap()) {\n onChange(newIndex);\n }\n }\n });\n }\n }, {\n key: \"handleTravellerMoveKeyboard\",\n value: function handleTravellerMoveKeyboard(direction, id) {\n var _this2 = this;\n // scaleValues are a list of coordinates. For example: [65, 250, 435, 620, 805, 990].\n var _this$state3 = this.state,\n scaleValues = _this$state3.scaleValues,\n startX = _this$state3.startX,\n endX = _this$state3.endX;\n // currentScaleValue refers to which coordinate the current traveller should be placed at.\n var currentScaleValue = this.state[id];\n var currentIndex = scaleValues.indexOf(currentScaleValue);\n if (currentIndex === -1) {\n return;\n }\n var newIndex = currentIndex + direction;\n if (newIndex === -1 || newIndex >= scaleValues.length) {\n return;\n }\n var newScaleValue = scaleValues[newIndex];\n\n // Prevent travellers from being on top of each other or overlapping\n if (id === 'startX' && newScaleValue >= endX || id === 'endX' && newScaleValue <= startX) {\n return;\n }\n this.setState(_defineProperty({}, id, newScaleValue), function () {\n _this2.props.onChange(_this2.getIndex({\n startX: _this2.state.startX,\n endX: _this2.state.endX\n }));\n });\n }\n }, {\n key: \"renderBackground\",\n value: function renderBackground() {\n var _this$props6 = this.props,\n x = _this$props6.x,\n y = _this$props6.y,\n width = _this$props6.width,\n height = _this$props6.height,\n fill = _this$props6.fill,\n stroke = _this$props6.stroke;\n return /*#__PURE__*/React.createElement(\"rect\", {\n stroke: stroke,\n fill: fill,\n x: x,\n y: y,\n width: width,\n height: height\n });\n }\n }, {\n key: \"renderPanorama\",\n value: function renderPanorama() {\n var _this$props7 = this.props,\n x = _this$props7.x,\n y = _this$props7.y,\n width = _this$props7.width,\n height = _this$props7.height,\n data = _this$props7.data,\n children = _this$props7.children,\n padding = _this$props7.padding;\n var chartElement = Children.only(children);\n if (!chartElement) {\n return null;\n }\n return /*#__PURE__*/React.cloneElement(chartElement, {\n x: x,\n y: y,\n width: width,\n height: height,\n margin: padding,\n compact: true,\n data: data\n });\n }\n }, {\n key: \"renderTravellerLayer\",\n value: function renderTravellerLayer(travellerX, id) {\n var _data$startIndex,\n _data$endIndex,\n _this3 = this;\n var _this$props8 = this.props,\n y = _this$props8.y,\n travellerWidth = _this$props8.travellerWidth,\n height = _this$props8.height,\n traveller = _this$props8.traveller,\n ariaLabel = _this$props8.ariaLabel,\n data = _this$props8.data,\n startIndex = _this$props8.startIndex,\n endIndex = _this$props8.endIndex;\n var x = Math.max(travellerX, this.props.x);\n var travellerProps = _objectSpread(_objectSpread({}, filterProps(this.props, false)), {}, {\n x: x,\n y: y,\n width: travellerWidth,\n height: height\n });\n var ariaLabelBrush = ariaLabel || \"Min value: \".concat((_data$startIndex = data[startIndex]) === null || _data$startIndex === void 0 ? void 0 : _data$startIndex.name, \", Max value: \").concat((_data$endIndex = data[endIndex]) === null || _data$endIndex === void 0 ? void 0 : _data$endIndex.name);\n return /*#__PURE__*/React.createElement(Layer, {\n tabIndex: 0,\n role: \"slider\",\n \"aria-label\": ariaLabelBrush,\n \"aria-valuenow\": travellerX,\n className: \"recharts-brush-traveller\",\n onMouseEnter: this.handleEnterSlideOrTraveller,\n onMouseLeave: this.handleLeaveSlideOrTraveller,\n onMouseDown: this.travellerDragStartHandlers[id],\n onTouchStart: this.travellerDragStartHandlers[id],\n onKeyDown: function onKeyDown(e) {\n if (!['ArrowLeft', 'ArrowRight'].includes(e.key)) {\n return;\n }\n e.preventDefault();\n e.stopPropagation();\n _this3.handleTravellerMoveKeyboard(e.key === 'ArrowRight' ? 1 : -1, id);\n },\n onFocus: function onFocus() {\n _this3.setState({\n isTravellerFocused: true\n });\n },\n onBlur: function onBlur() {\n _this3.setState({\n isTravellerFocused: false\n });\n },\n style: {\n cursor: 'col-resize'\n }\n }, Brush.renderTraveller(traveller, travellerProps));\n }\n }, {\n key: \"renderSlide\",\n value: function renderSlide(startX, endX) {\n var _this$props9 = this.props,\n y = _this$props9.y,\n height = _this$props9.height,\n stroke = _this$props9.stroke,\n travellerWidth = _this$props9.travellerWidth;\n var x = Math.min(startX, endX) + travellerWidth;\n var width = Math.max(Math.abs(endX - startX) - travellerWidth, 0);\n return /*#__PURE__*/React.createElement(\"rect\", {\n className: \"recharts-brush-slide\",\n onMouseEnter: this.handleEnterSlideOrTraveller,\n onMouseLeave: this.handleLeaveSlideOrTraveller,\n onMouseDown: this.handleSlideDragStart,\n onTouchStart: this.handleSlideDragStart,\n style: {\n cursor: 'move'\n },\n stroke: \"none\",\n fill: stroke,\n fillOpacity: 0.2,\n x: x,\n y: y,\n width: width,\n height: height\n });\n }\n }, {\n key: \"renderText\",\n value: function renderText() {\n var _this$props10 = this.props,\n startIndex = _this$props10.startIndex,\n endIndex = _this$props10.endIndex,\n y = _this$props10.y,\n height = _this$props10.height,\n travellerWidth = _this$props10.travellerWidth,\n stroke = _this$props10.stroke;\n var _this$state4 = this.state,\n startX = _this$state4.startX,\n endX = _this$state4.endX;\n var offset = 5;\n var attrs = {\n pointerEvents: 'none',\n fill: stroke\n };\n return /*#__PURE__*/React.createElement(Layer, {\n className: \"recharts-brush-texts\"\n }, /*#__PURE__*/React.createElement(Text, _extends({\n textAnchor: \"end\",\n verticalAnchor: \"middle\",\n x: Math.min(startX, endX) - offset,\n y: y + height / 2\n }, attrs), this.getTextOfTick(startIndex)), /*#__PURE__*/React.createElement(Text, _extends({\n textAnchor: \"start\",\n verticalAnchor: \"middle\",\n x: Math.max(startX, endX) + travellerWidth + offset,\n y: y + height / 2\n }, attrs), this.getTextOfTick(endIndex)));\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this$props11 = this.props,\n data = _this$props11.data,\n className = _this$props11.className,\n children = _this$props11.children,\n x = _this$props11.x,\n y = _this$props11.y,\n width = _this$props11.width,\n height = _this$props11.height,\n alwaysShowText = _this$props11.alwaysShowText;\n var _this$state5 = this.state,\n startX = _this$state5.startX,\n endX = _this$state5.endX,\n isTextActive = _this$state5.isTextActive,\n isSlideMoving = _this$state5.isSlideMoving,\n isTravellerMoving = _this$state5.isTravellerMoving,\n isTravellerFocused = _this$state5.isTravellerFocused;\n if (!data || !data.length || !isNumber(x) || !isNumber(y) || !isNumber(width) || !isNumber(height) || width <= 0 || height <= 0) {\n return null;\n }\n var layerClass = clsx('recharts-brush', className);\n var isPanoramic = React.Children.count(children) === 1;\n var style = generatePrefixStyle('userSelect', 'none');\n return /*#__PURE__*/React.createElement(Layer, {\n className: layerClass,\n onMouseLeave: this.handleLeaveWrapper,\n onTouchMove: this.handleTouchMove,\n style: style\n }, this.renderBackground(), isPanoramic && this.renderPanorama(), this.renderSlide(startX, endX), this.renderTravellerLayer(startX, 'startX'), this.renderTravellerLayer(endX, 'endX'), (isTextActive || isSlideMoving || isTravellerMoving || isTravellerFocused || alwaysShowText) && this.renderText());\n }\n }], [{\n key: \"renderDefaultTraveller\",\n value: function renderDefaultTraveller(props) {\n var x = props.x,\n y = props.y,\n width = props.width,\n height = props.height,\n stroke = props.stroke;\n var lineY = Math.floor(y + height / 2) - 1;\n return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(\"rect\", {\n x: x,\n y: y,\n width: width,\n height: height,\n fill: stroke,\n stroke: \"none\"\n }), /*#__PURE__*/React.createElement(\"line\", {\n x1: x + 1,\n y1: lineY,\n x2: x + width - 1,\n y2: lineY,\n fill: \"none\",\n stroke: \"#fff\"\n }), /*#__PURE__*/React.createElement(\"line\", {\n x1: x + 1,\n y1: lineY + 2,\n x2: x + width - 1,\n y2: lineY + 2,\n fill: \"none\",\n stroke: \"#fff\"\n }));\n }\n }, {\n key: \"renderTraveller\",\n value: function renderTraveller(option, props) {\n var rectangle;\n if ( /*#__PURE__*/React.isValidElement(option)) {\n rectangle = /*#__PURE__*/React.cloneElement(option, props);\n } else if (isFunction(option)) {\n rectangle = option(props);\n } else {\n rectangle = Brush.renderDefaultTraveller(props);\n }\n return rectangle;\n }\n }, {\n key: \"getDerivedStateFromProps\",\n value: function getDerivedStateFromProps(nextProps, prevState) {\n var data = nextProps.data,\n width = nextProps.width,\n x = nextProps.x,\n travellerWidth = nextProps.travellerWidth,\n updateId = nextProps.updateId,\n startIndex = nextProps.startIndex,\n endIndex = nextProps.endIndex;\n if (data !== prevState.prevData || updateId !== prevState.prevUpdateId) {\n return _objectSpread({\n prevData: data,\n prevTravellerWidth: travellerWidth,\n prevUpdateId: updateId,\n prevX: x,\n prevWidth: width\n }, data && data.length ? createScale({\n data: data,\n width: width,\n x: x,\n travellerWidth: travellerWidth,\n startIndex: startIndex,\n endIndex: endIndex\n }) : {\n scale: null,\n scaleValues: null\n });\n }\n if (prevState.scale && (width !== prevState.prevWidth || x !== prevState.prevX || travellerWidth !== prevState.prevTravellerWidth)) {\n prevState.scale.range([x, x + width - travellerWidth]);\n var scaleValues = prevState.scale.domain().map(function (entry) {\n return prevState.scale(entry);\n });\n return {\n prevData: data,\n prevTravellerWidth: travellerWidth,\n prevUpdateId: updateId,\n prevX: x,\n prevWidth: width,\n startX: prevState.scale(nextProps.startIndex),\n endX: prevState.scale(nextProps.endIndex),\n scaleValues: scaleValues\n };\n }\n return null;\n }\n }, {\n key: \"getIndexInRange\",\n value: function getIndexInRange(valueRange, x) {\n var len = valueRange.length;\n var start = 0;\n var end = len - 1;\n while (end - start > 1) {\n var middle = Math.floor((start + end) / 2);\n if (valueRange[middle] > x) {\n end = middle;\n } else {\n start = middle;\n }\n }\n return x >= valueRange[end] ? end : start;\n }\n }]);\n}(PureComponent);\n_defineProperty(Brush, \"displayName\", 'Brush');\n_defineProperty(Brush, \"defaultProps\", {\n height: 40,\n travellerWidth: 5,\n gap: 1,\n fill: '#fff',\n stroke: '#666',\n padding: {\n top: 1,\n right: 1,\n bottom: 1,\n left: 1\n },\n leaveTimeOut: 1000,\n alwaysShowText: false\n});", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar PREFIX_LIST = ['Webkit', 'Moz', 'O', 'ms'];\nexport var generatePrefixStyle = function generatePrefixStyle(name, value) {\n if (!name) {\n return null;\n }\n var camelName = name.replace(/(\\w)/, function (v) {\n return v.toUpperCase();\n });\n var result = PREFIX_LIST.reduce(function (res, entry) {\n return _objectSpread(_objectSpread({}, res), {}, _defineProperty({}, entry + camelName, value));\n }, {});\n result[name] = value;\n return result;\n};", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n/**\n * @fileOverview Reference Line\n */\nimport React from 'react';\nimport isFunction from 'lodash/isFunction';\nimport some from 'lodash/some';\nimport clsx from 'clsx';\nimport { Layer } from '../container/Layer';\nimport { Label } from '../component/Label';\nimport { ifOverflowMatches } from '../util/IfOverflowMatches';\nimport { isNumOrStr } from '../util/DataUtils';\nimport { createLabeledScales, rectWithCoords } from '../util/CartesianUtils';\nimport { warn } from '../util/LogUtils';\nimport { filterProps } from '../util/ReactUtils';\nimport { useClipPathId, useViewBox, useXAxisOrThrow, useYAxisOrThrow } from '../context/chartLayoutContext';\n\n/**\n * This excludes `viewBox` prop from svg for two reasons:\n * 1. The components wants viewBox of object type, and svg wants string\n * - so there's a conflict, and the component will throw if it gets string\n * 2. Internally the component calls `filterProps` which filters the viewBox away anyway\n */\n\nvar renderLine = function renderLine(option, props) {\n var line;\n if ( /*#__PURE__*/React.isValidElement(option)) {\n line = /*#__PURE__*/React.cloneElement(option, props);\n } else if (isFunction(option)) {\n line = option(props);\n } else {\n line = /*#__PURE__*/React.createElement(\"line\", _extends({}, props, {\n className: \"recharts-reference-line-line\"\n }));\n }\n return line;\n};\n// TODO: ScaleHelper\nexport var getEndPoints = function getEndPoints(scales, isFixedX, isFixedY, isSegment, viewBox, position, xAxisOrientation, yAxisOrientation, props) {\n var x = viewBox.x,\n y = viewBox.y,\n width = viewBox.width,\n height = viewBox.height;\n if (isFixedY) {\n var yCoord = props.y;\n var coord = scales.y.apply(yCoord, {\n position: position\n });\n if (ifOverflowMatches(props, 'discard') && !scales.y.isInRange(coord)) {\n return null;\n }\n var points = [{\n x: x + width,\n y: coord\n }, {\n x: x,\n y: coord\n }];\n return yAxisOrientation === 'left' ? points.reverse() : points;\n }\n if (isFixedX) {\n var xCoord = props.x;\n var _coord = scales.x.apply(xCoord, {\n position: position\n });\n if (ifOverflowMatches(props, 'discard') && !scales.x.isInRange(_coord)) {\n return null;\n }\n var _points = [{\n x: _coord,\n y: y + height\n }, {\n x: _coord,\n y: y\n }];\n return xAxisOrientation === 'top' ? _points.reverse() : _points;\n }\n if (isSegment) {\n var segment = props.segment;\n var _points2 = segment.map(function (p) {\n return scales.apply(p, {\n position: position\n });\n });\n if (ifOverflowMatches(props, 'discard') && some(_points2, function (p) {\n return !scales.isInRange(p);\n })) {\n return null;\n }\n return _points2;\n }\n return null;\n};\nfunction ReferenceLineImpl(props) {\n var fixedX = props.x,\n fixedY = props.y,\n segment = props.segment,\n xAxisId = props.xAxisId,\n yAxisId = props.yAxisId,\n shape = props.shape,\n className = props.className,\n alwaysShow = props.alwaysShow;\n var clipPathId = useClipPathId();\n var xAxis = useXAxisOrThrow(xAxisId);\n var yAxis = useYAxisOrThrow(yAxisId);\n var viewBox = useViewBox();\n if (!clipPathId || !viewBox) {\n return null;\n }\n warn(alwaysShow === undefined, 'The alwaysShow prop is deprecated. Please use ifOverflow=\"extendDomain\" instead.');\n var scales = createLabeledScales({\n x: xAxis.scale,\n y: yAxis.scale\n });\n var isX = isNumOrStr(fixedX);\n var isY = isNumOrStr(fixedY);\n var isSegment = segment && segment.length === 2;\n var endPoints = getEndPoints(scales, isX, isY, isSegment, viewBox, props.position, xAxis.orientation, yAxis.orientation, props);\n if (!endPoints) {\n return null;\n }\n var _endPoints = _slicedToArray(endPoints, 2),\n _endPoints$ = _endPoints[0],\n x1 = _endPoints$.x,\n y1 = _endPoints$.y,\n _endPoints$2 = _endPoints[1],\n x2 = _endPoints$2.x,\n y2 = _endPoints$2.y;\n var clipPath = ifOverflowMatches(props, 'hidden') ? \"url(#\".concat(clipPathId, \")\") : undefined;\n var lineProps = _objectSpread(_objectSpread({\n clipPath: clipPath\n }, filterProps(props, true)), {}, {\n x1: x1,\n y1: y1,\n x2: x2,\n y2: y2\n });\n return /*#__PURE__*/React.createElement(Layer, {\n className: clsx('recharts-reference-line', className)\n }, renderLine(shape, lineProps), Label.renderCallByParent(props, rectWithCoords({\n x1: x1,\n y1: y1,\n x2: x2,\n y2: y2\n })));\n}\n\n// eslint-disable-next-line react/prefer-stateless-function -- requires static defaultProps\nexport var ReferenceLine = /*#__PURE__*/function (_React$Component) {\n function ReferenceLine() {\n _classCallCheck(this, ReferenceLine);\n return _callSuper(this, ReferenceLine, arguments);\n }\n _inherits(ReferenceLine, _React$Component);\n return _createClass(ReferenceLine, [{\n key: \"render\",\n value: function render() {\n return /*#__PURE__*/React.createElement(ReferenceLineImpl, this.props);\n }\n }]);\n}(React.Component);\n_defineProperty(ReferenceLine, \"displayName\", 'ReferenceLine');\n_defineProperty(ReferenceLine, \"defaultProps\", {\n isFront: false,\n ifOverflow: 'discard',\n xAxisId: 0,\n yAxisId: 0,\n fill: 'none',\n stroke: '#ccc',\n fillOpacity: 1,\n strokeWidth: 1,\n position: 'middle'\n});", "export var ifOverflowMatches = function ifOverflowMatches(props, value) {\n var alwaysShow = props.alwaysShow;\n var ifOverflow = props.ifOverflow;\n if (alwaysShow) {\n ifOverflow = 'extendDomain';\n }\n return ifOverflow === value;\n};", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nimport mapValues from 'lodash/mapValues';\nimport every from 'lodash/every';\nimport { getTicksOfScale, parseScale, checkDomainOfScale, getBandSizeOfAxis } from './ChartUtils';\nimport { findChildByType } from './ReactUtils';\nimport { compareValues, getPercentValue } from './DataUtils';\nimport { Bar } from '../cartesian/Bar';\n\n/**\n * Calculate the scale function, position, width, height of axes\n * @param {Object} props Latest props\n * @param {Object} axisMap The configuration of axes\n * @param {Object} offset The offset of main part in the svg element\n * @param {String} axisType The type of axes, x-axis or y-axis\n * @param {String} chartName The name of chart\n * @return {Object} Configuration\n */\nexport var formatAxisMap = function formatAxisMap(props, axisMap, offset, axisType, chartName) {\n var width = props.width,\n height = props.height,\n layout = props.layout,\n children = props.children;\n var ids = Object.keys(axisMap);\n var steps = {\n left: offset.left,\n leftMirror: offset.left,\n right: width - offset.right,\n rightMirror: width - offset.right,\n top: offset.top,\n topMirror: offset.top,\n bottom: height - offset.bottom,\n bottomMirror: height - offset.bottom\n };\n var hasBar = !!findChildByType(children, Bar);\n return ids.reduce(function (result, id) {\n var axis = axisMap[id];\n var orientation = axis.orientation,\n domain = axis.domain,\n _axis$padding = axis.padding,\n padding = _axis$padding === void 0 ? {} : _axis$padding,\n mirror = axis.mirror,\n reversed = axis.reversed;\n var offsetKey = \"\".concat(orientation).concat(mirror ? 'Mirror' : '');\n var calculatedPadding, range, x, y, needSpace;\n if (axis.type === 'number' && (axis.padding === 'gap' || axis.padding === 'no-gap')) {\n var diff = domain[1] - domain[0];\n var smallestDistanceBetweenValues = Infinity;\n var sortedValues = axis.categoricalDomain.sort(compareValues);\n sortedValues.forEach(function (value, index) {\n if (index > 0) {\n smallestDistanceBetweenValues = Math.min((value || 0) - (sortedValues[index - 1] || 0), smallestDistanceBetweenValues);\n }\n });\n if (Number.isFinite(smallestDistanceBetweenValues)) {\n var smallestDistanceInPercent = smallestDistanceBetweenValues / diff;\n var rangeWidth = axis.layout === 'vertical' ? offset.height : offset.width;\n if (axis.padding === 'gap') {\n calculatedPadding = smallestDistanceInPercent * rangeWidth / 2;\n }\n if (axis.padding === 'no-gap') {\n var gap = getPercentValue(props.barCategoryGap, smallestDistanceInPercent * rangeWidth);\n var halfBand = smallestDistanceInPercent * rangeWidth / 2;\n calculatedPadding = halfBand - gap - (halfBand - gap) / rangeWidth * gap;\n }\n }\n }\n if (axisType === 'xAxis') {\n range = [offset.left + (padding.left || 0) + (calculatedPadding || 0), offset.left + offset.width - (padding.right || 0) - (calculatedPadding || 0)];\n } else if (axisType === 'yAxis') {\n range = layout === 'horizontal' ? [offset.top + offset.height - (padding.bottom || 0), offset.top + (padding.top || 0)] : [offset.top + (padding.top || 0) + (calculatedPadding || 0), offset.top + offset.height - (padding.bottom || 0) - (calculatedPadding || 0)];\n } else {\n range = axis.range;\n }\n if (reversed) {\n range = [range[1], range[0]];\n }\n var _parseScale = parseScale(axis, chartName, hasBar),\n scale = _parseScale.scale,\n realScaleType = _parseScale.realScaleType;\n scale.domain(domain).range(range);\n checkDomainOfScale(scale);\n var ticks = getTicksOfScale(scale, _objectSpread(_objectSpread({}, axis), {}, {\n realScaleType: realScaleType\n }));\n if (axisType === 'xAxis') {\n needSpace = orientation === 'top' && !mirror || orientation === 'bottom' && mirror;\n x = offset.left;\n y = steps[offsetKey] - needSpace * axis.height;\n } else if (axisType === 'yAxis') {\n needSpace = orientation === 'left' && !mirror || orientation === 'right' && mirror;\n x = steps[offsetKey] - needSpace * axis.width;\n y = offset.top;\n }\n var finalAxis = _objectSpread(_objectSpread(_objectSpread({}, axis), ticks), {}, {\n realScaleType: realScaleType,\n x: x,\n y: y,\n scale: scale,\n width: axisType === 'xAxis' ? offset.width : axis.width,\n height: axisType === 'yAxis' ? offset.height : axis.height\n });\n finalAxis.bandSize = getBandSizeOfAxis(finalAxis, ticks);\n if (!axis.hide && axisType === 'xAxis') {\n steps[offsetKey] += (needSpace ? -1 : 1) * finalAxis.height;\n } else if (!axis.hide) {\n steps[offsetKey] += (needSpace ? -1 : 1) * finalAxis.width;\n }\n return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, id, finalAxis));\n }, {});\n};\nexport var rectWithPoints = function rectWithPoints(_ref, _ref2) {\n var x1 = _ref.x,\n y1 = _ref.y;\n var x2 = _ref2.x,\n y2 = _ref2.y;\n return {\n x: Math.min(x1, x2),\n y: Math.min(y1, y2),\n width: Math.abs(x2 - x1),\n height: Math.abs(y2 - y1)\n };\n};\n\n/**\n * Compute the x, y, width, and height of a box from two reference points.\n * @param {Object} coords x1, x2, y1, and y2\n * @return {Object} object\n */\nexport var rectWithCoords = function rectWithCoords(_ref3) {\n var x1 = _ref3.x1,\n y1 = _ref3.y1,\n x2 = _ref3.x2,\n y2 = _ref3.y2;\n return rectWithPoints({\n x: x1,\n y: y1\n }, {\n x: x2,\n y: y2\n });\n};\nexport var ScaleHelper = /*#__PURE__*/function () {\n function ScaleHelper(scale) {\n _classCallCheck(this, ScaleHelper);\n this.scale = scale;\n }\n return _createClass(ScaleHelper, [{\n key: \"domain\",\n get: function get() {\n return this.scale.domain;\n }\n }, {\n key: \"range\",\n get: function get() {\n return this.scale.range;\n }\n }, {\n key: \"rangeMin\",\n get: function get() {\n return this.range()[0];\n }\n }, {\n key: \"rangeMax\",\n get: function get() {\n return this.range()[1];\n }\n }, {\n key: \"bandwidth\",\n get: function get() {\n return this.scale.bandwidth;\n }\n }, {\n key: \"apply\",\n value: function apply(value) {\n var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n bandAware = _ref4.bandAware,\n position = _ref4.position;\n if (value === undefined) {\n return undefined;\n }\n if (position) {\n switch (position) {\n case 'start':\n {\n return this.scale(value);\n }\n case 'middle':\n {\n var offset = this.bandwidth ? this.bandwidth() / 2 : 0;\n return this.scale(value) + offset;\n }\n case 'end':\n {\n var _offset = this.bandwidth ? this.bandwidth() : 0;\n return this.scale(value) + _offset;\n }\n default:\n {\n return this.scale(value);\n }\n }\n }\n if (bandAware) {\n var _offset2 = this.bandwidth ? this.bandwidth() / 2 : 0;\n return this.scale(value) + _offset2;\n }\n return this.scale(value);\n }\n }, {\n key: \"isInRange\",\n value: function isInRange(value) {\n var range = this.range();\n var first = range[0];\n var last = range[range.length - 1];\n return first <= last ? value >= first && value <= last : value >= last && value <= first;\n }\n }], [{\n key: \"create\",\n value: function create(obj) {\n return new ScaleHelper(obj);\n }\n }]);\n}();\n_defineProperty(ScaleHelper, \"EPS\", 1e-4);\nexport var createLabeledScales = function createLabeledScales(options) {\n var scales = Object.keys(options).reduce(function (res, key) {\n return _objectSpread(_objectSpread({}, res), {}, _defineProperty({}, key, ScaleHelper.create(options[key])));\n }, {});\n return _objectSpread(_objectSpread({}, scales), {}, {\n apply: function apply(coord) {\n var _ref5 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n bandAware = _ref5.bandAware,\n position = _ref5.position;\n return mapValues(coord, function (value, label) {\n return scales[label].apply(value, {\n bandAware: bandAware,\n position: position\n });\n });\n },\n isInRange: function isInRange(coord) {\n return every(coord, function (value, label) {\n return scales[label].isInRange(value);\n });\n }\n });\n};\n\n/** Normalizes the angle so that 0 <= angle < 180.\n * @param {number} angle Angle in degrees.\n * @return {number} the normalized angle with a value of at least 0 and never greater or equal to 180. */\nexport function normalizeAngle(angle) {\n return (angle % 180 + 180) % 180;\n}\n\n/** Calculates the width of the largest horizontal line that fits inside a rectangle that is displayed at an angle.\n * @param {Object} size Width and height of the text in a horizontal position.\n * @param {number} angle Angle in degrees in which the text is displayed.\n * @return {number} The width of the largest horizontal line that fits inside a rectangle that is displayed at an angle.\n */\nexport var getAngledRectangleWidth = function getAngledRectangleWidth(_ref6) {\n var width = _ref6.width,\n height = _ref6.height;\n var angle = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n // Ensure angle is >= 0 && < 180\n var normalizedAngle = normalizeAngle(angle);\n var angleRadians = normalizedAngle * Math.PI / 180;\n\n /* Depending on the height and width of the rectangle, we may need to use different formulas to calculate the angled\n * width. This threshold defines when each formula should kick in. */\n var angleThreshold = Math.atan(height / width);\n var angledWidth = angleRadians > angleThreshold && angleRadians < Math.PI - angleThreshold ? height / Math.sin(angleRadians) : width / Math.cos(angleRadians);\n return Math.abs(angledWidth);\n};", "var _excluded = [\"value\", \"background\"];\nvar _Bar;\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Render a group of bar\n */\nimport React, { PureComponent } from 'react';\nimport clsx from 'clsx';\nimport Animate from 'react-smooth';\nimport isEqual from 'lodash/isEqual';\nimport isNil from 'lodash/isNil';\nimport { Layer } from '../container/Layer';\nimport { ErrorBar } from './ErrorBar';\nimport { Cell } from '../component/Cell';\nimport { LabelList } from '../component/LabelList';\nimport { uniqueId, mathSign, interpolateNumber } from '../util/DataUtils';\nimport { filterProps, findAllByType } from '../util/ReactUtils';\nimport { Global } from '../util/Global';\nimport { getCateCoordinateOfBar, getValueByDataKey, truncateByDomain, getBaseValueOfBar, findPositionOfBar, getTooltipItem } from '../util/ChartUtils';\nimport { adaptEventsOfChild } from '../util/types';\nimport { BarRectangle, minPointSizeCallback } from '../util/BarUtils';\nexport var Bar = /*#__PURE__*/function (_PureComponent) {\n function Bar() {\n var _this;\n _classCallCheck(this, Bar);\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n _this = _callSuper(this, Bar, [].concat(args));\n _defineProperty(_this, \"state\", {\n isAnimationFinished: false\n });\n _defineProperty(_this, \"id\", uniqueId('recharts-bar-'));\n _defineProperty(_this, \"handleAnimationEnd\", function () {\n var onAnimationEnd = _this.props.onAnimationEnd;\n _this.setState({\n isAnimationFinished: true\n });\n if (onAnimationEnd) {\n onAnimationEnd();\n }\n });\n _defineProperty(_this, \"handleAnimationStart\", function () {\n var onAnimationStart = _this.props.onAnimationStart;\n _this.setState({\n isAnimationFinished: false\n });\n if (onAnimationStart) {\n onAnimationStart();\n }\n });\n return _this;\n }\n _inherits(Bar, _PureComponent);\n return _createClass(Bar, [{\n key: \"renderRectanglesStatically\",\n value: function renderRectanglesStatically(data) {\n var _this2 = this;\n var _this$props = this.props,\n shape = _this$props.shape,\n dataKey = _this$props.dataKey,\n activeIndex = _this$props.activeIndex,\n activeBar = _this$props.activeBar;\n var baseProps = filterProps(this.props, false);\n return data && data.map(function (entry, i) {\n var isActive = i === activeIndex;\n var option = isActive ? activeBar : shape;\n var props = _objectSpread(_objectSpread(_objectSpread({}, baseProps), entry), {}, {\n isActive: isActive,\n option: option,\n index: i,\n dataKey: dataKey,\n onAnimationStart: _this2.handleAnimationStart,\n onAnimationEnd: _this2.handleAnimationEnd\n });\n return /*#__PURE__*/React.createElement(Layer, _extends({\n className: \"recharts-bar-rectangle\"\n }, adaptEventsOfChild(_this2.props, entry, i), {\n // https://github.com/recharts/recharts/issues/5415\n // eslint-disable-next-line react/no-array-index-key\n key: \"rectangle-\".concat(entry === null || entry === void 0 ? void 0 : entry.x, \"-\").concat(entry === null || entry === void 0 ? void 0 : entry.y, \"-\").concat(entry === null || entry === void 0 ? void 0 : entry.value, \"-\").concat(i)\n }), /*#__PURE__*/React.createElement(BarRectangle, props));\n });\n }\n }, {\n key: \"renderRectanglesWithAnimation\",\n value: function renderRectanglesWithAnimation() {\n var _this3 = this;\n var _this$props2 = this.props,\n data = _this$props2.data,\n layout = _this$props2.layout,\n isAnimationActive = _this$props2.isAnimationActive,\n animationBegin = _this$props2.animationBegin,\n animationDuration = _this$props2.animationDuration,\n animationEasing = _this$props2.animationEasing,\n animationId = _this$props2.animationId;\n var prevData = this.state.prevData;\n return /*#__PURE__*/React.createElement(Animate, {\n begin: animationBegin,\n duration: animationDuration,\n isActive: isAnimationActive,\n easing: animationEasing,\n from: {\n t: 0\n },\n to: {\n t: 1\n },\n key: \"bar-\".concat(animationId),\n onAnimationEnd: this.handleAnimationEnd,\n onAnimationStart: this.handleAnimationStart\n }, function (_ref) {\n var t = _ref.t;\n var stepData = data.map(function (entry, index) {\n var prev = prevData && prevData[index];\n if (prev) {\n var interpolatorX = interpolateNumber(prev.x, entry.x);\n var interpolatorY = interpolateNumber(prev.y, entry.y);\n var interpolatorWidth = interpolateNumber(prev.width, entry.width);\n var interpolatorHeight = interpolateNumber(prev.height, entry.height);\n return _objectSpread(_objectSpread({}, entry), {}, {\n x: interpolatorX(t),\n y: interpolatorY(t),\n width: interpolatorWidth(t),\n height: interpolatorHeight(t)\n });\n }\n if (layout === 'horizontal') {\n var _interpolatorHeight = interpolateNumber(0, entry.height);\n var h = _interpolatorHeight(t);\n return _objectSpread(_objectSpread({}, entry), {}, {\n y: entry.y + entry.height - h,\n height: h\n });\n }\n var interpolator = interpolateNumber(0, entry.width);\n var w = interpolator(t);\n return _objectSpread(_objectSpread({}, entry), {}, {\n width: w\n });\n });\n return /*#__PURE__*/React.createElement(Layer, null, _this3.renderRectanglesStatically(stepData));\n });\n }\n }, {\n key: \"renderRectangles\",\n value: function renderRectangles() {\n var _this$props3 = this.props,\n data = _this$props3.data,\n isAnimationActive = _this$props3.isAnimationActive;\n var prevData = this.state.prevData;\n if (isAnimationActive && data && data.length && (!prevData || !isEqual(prevData, data))) {\n return this.renderRectanglesWithAnimation();\n }\n return this.renderRectanglesStatically(data);\n }\n }, {\n key: \"renderBackground\",\n value: function renderBackground() {\n var _this4 = this;\n var _this$props4 = this.props,\n data = _this$props4.data,\n dataKey = _this$props4.dataKey,\n activeIndex = _this$props4.activeIndex;\n var backgroundProps = filterProps(this.props.background, false);\n return data.map(function (entry, i) {\n var value = entry.value,\n background = entry.background,\n rest = _objectWithoutProperties(entry, _excluded);\n if (!background) {\n return null;\n }\n var props = _objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread({}, rest), {}, {\n fill: '#eee'\n }, background), backgroundProps), adaptEventsOfChild(_this4.props, entry, i)), {}, {\n onAnimationStart: _this4.handleAnimationStart,\n onAnimationEnd: _this4.handleAnimationEnd,\n dataKey: dataKey,\n index: i,\n className: 'recharts-bar-background-rectangle'\n });\n return /*#__PURE__*/React.createElement(BarRectangle, _extends({\n key: \"background-bar-\".concat(i),\n option: _this4.props.background,\n isActive: i === activeIndex\n }, props));\n });\n }\n }, {\n key: \"renderErrorBar\",\n value: function renderErrorBar(needClip, clipPathId) {\n if (this.props.isAnimationActive && !this.state.isAnimationFinished) {\n return null;\n }\n var _this$props5 = this.props,\n data = _this$props5.data,\n xAxis = _this$props5.xAxis,\n yAxis = _this$props5.yAxis,\n layout = _this$props5.layout,\n children = _this$props5.children;\n var errorBarItems = findAllByType(children, ErrorBar);\n if (!errorBarItems) {\n return null;\n }\n var offset = layout === 'vertical' ? data[0].height / 2 : data[0].width / 2;\n var dataPointFormatter = function dataPointFormatter(dataPoint, dataKey) {\n /**\n * if the value coming from `getComposedData` is an array then this is a stacked bar chart.\n * arr[1] represents end value of the bar since the data is in the form of [startValue, endValue].\n * */\n var value = Array.isArray(dataPoint.value) ? dataPoint.value[1] : dataPoint.value;\n return {\n x: dataPoint.x,\n y: dataPoint.y,\n value: value,\n errorVal: getValueByDataKey(dataPoint, dataKey)\n };\n };\n var errorBarProps = {\n clipPath: needClip ? \"url(#clipPath-\".concat(clipPathId, \")\") : null\n };\n return /*#__PURE__*/React.createElement(Layer, errorBarProps, errorBarItems.map(function (item) {\n return /*#__PURE__*/React.cloneElement(item, {\n key: \"error-bar-\".concat(clipPathId, \"-\").concat(item.props.dataKey),\n data: data,\n xAxis: xAxis,\n yAxis: yAxis,\n layout: layout,\n offset: offset,\n dataPointFormatter: dataPointFormatter\n });\n }));\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this$props6 = this.props,\n hide = _this$props6.hide,\n data = _this$props6.data,\n className = _this$props6.className,\n xAxis = _this$props6.xAxis,\n yAxis = _this$props6.yAxis,\n left = _this$props6.left,\n top = _this$props6.top,\n width = _this$props6.width,\n height = _this$props6.height,\n isAnimationActive = _this$props6.isAnimationActive,\n background = _this$props6.background,\n id = _this$props6.id;\n if (hide || !data || !data.length) {\n return null;\n }\n var isAnimationFinished = this.state.isAnimationFinished;\n var layerClass = clsx('recharts-bar', className);\n var needClipX = xAxis && xAxis.allowDataOverflow;\n var needClipY = yAxis && yAxis.allowDataOverflow;\n var needClip = needClipX || needClipY;\n var clipPathId = isNil(id) ? this.id : id;\n return /*#__PURE__*/React.createElement(Layer, {\n className: layerClass\n }, needClipX || needClipY ? /*#__PURE__*/React.createElement(\"defs\", null, /*#__PURE__*/React.createElement(\"clipPath\", {\n id: \"clipPath-\".concat(clipPathId)\n }, /*#__PURE__*/React.createElement(\"rect\", {\n x: needClipX ? left : left - width / 2,\n y: needClipY ? top : top - height / 2,\n width: needClipX ? width : width * 2,\n height: needClipY ? height : height * 2\n }))) : null, /*#__PURE__*/React.createElement(Layer, {\n className: \"recharts-bar-rectangles\",\n clipPath: needClip ? \"url(#clipPath-\".concat(clipPathId, \")\") : null\n }, background ? this.renderBackground() : null, this.renderRectangles()), this.renderErrorBar(needClip, clipPathId), (!isAnimationActive || isAnimationFinished) && LabelList.renderCallByParent(this.props, data));\n }\n }], [{\n key: \"getDerivedStateFromProps\",\n value: function getDerivedStateFromProps(nextProps, prevState) {\n if (nextProps.animationId !== prevState.prevAnimationId) {\n return {\n prevAnimationId: nextProps.animationId,\n curData: nextProps.data,\n prevData: prevState.curData\n };\n }\n if (nextProps.data !== prevState.curData) {\n return {\n curData: nextProps.data\n };\n }\n return null;\n }\n }]);\n}(PureComponent);\n_Bar = Bar;\n_defineProperty(Bar, \"displayName\", 'Bar');\n_defineProperty(Bar, \"defaultProps\", {\n xAxisId: 0,\n yAxisId: 0,\n legendType: 'rect',\n minPointSize: 0,\n hide: false,\n data: [],\n layout: 'vertical',\n activeBar: false,\n isAnimationActive: !Global.isSsr,\n animationBegin: 0,\n animationDuration: 400,\n animationEasing: 'ease'\n});\n/**\n * Compose the data of each group\n * @param {Object} props Props for the component\n * @param {Object} item An instance of Bar\n * @param {Array} barPosition The offset and size of each bar\n * @param {Object} xAxis The configuration of x-axis\n * @param {Object} yAxis The configuration of y-axis\n * @param {Array} stackedData The stacked data of a bar item\n * @return{Array} Composed data\n */\n_defineProperty(Bar, \"getComposedData\", function (_ref2) {\n var props = _ref2.props,\n item = _ref2.item,\n barPosition = _ref2.barPosition,\n bandSize = _ref2.bandSize,\n xAxis = _ref2.xAxis,\n yAxis = _ref2.yAxis,\n xAxisTicks = _ref2.xAxisTicks,\n yAxisTicks = _ref2.yAxisTicks,\n stackedData = _ref2.stackedData,\n dataStartIndex = _ref2.dataStartIndex,\n displayedData = _ref2.displayedData,\n offset = _ref2.offset;\n var pos = findPositionOfBar(barPosition, item);\n if (!pos) {\n return null;\n }\n var layout = props.layout;\n var itemDefaultProps = item.type.defaultProps;\n var itemProps = itemDefaultProps !== undefined ? _objectSpread(_objectSpread({}, itemDefaultProps), item.props) : item.props;\n var dataKey = itemProps.dataKey,\n children = itemProps.children,\n minPointSizeProp = itemProps.minPointSize;\n var numericAxis = layout === 'horizontal' ? yAxis : xAxis;\n var stackedDomain = stackedData ? numericAxis.scale.domain() : null;\n var baseValue = getBaseValueOfBar({\n numericAxis: numericAxis\n });\n var cells = findAllByType(children, Cell);\n var rects = displayedData.map(function (entry, index) {\n var value, x, y, width, height, background;\n if (stackedData) {\n value = truncateByDomain(stackedData[dataStartIndex + index], stackedDomain);\n } else {\n value = getValueByDataKey(entry, dataKey);\n if (!Array.isArray(value)) {\n value = [baseValue, value];\n }\n }\n var minPointSize = minPointSizeCallback(minPointSizeProp, _Bar.defaultProps.minPointSize)(value[1], index);\n if (layout === 'horizontal') {\n var _ref4;\n var _ref3 = [yAxis.scale(value[0]), yAxis.scale(value[1])],\n baseValueScale = _ref3[0],\n currentValueScale = _ref3[1];\n x = getCateCoordinateOfBar({\n axis: xAxis,\n ticks: xAxisTicks,\n bandSize: bandSize,\n offset: pos.offset,\n entry: entry,\n index: index\n });\n y = (_ref4 = currentValueScale !== null && currentValueScale !== void 0 ? currentValueScale : baseValueScale) !== null && _ref4 !== void 0 ? _ref4 : undefined;\n width = pos.size;\n var computedHeight = baseValueScale - currentValueScale;\n height = Number.isNaN(computedHeight) ? 0 : computedHeight;\n background = {\n x: x,\n y: yAxis.y,\n width: width,\n height: yAxis.height\n };\n if (Math.abs(minPointSize) > 0 && Math.abs(height) < Math.abs(minPointSize)) {\n var delta = mathSign(height || minPointSize) * (Math.abs(minPointSize) - Math.abs(height));\n y -= delta;\n height += delta;\n }\n } else {\n var _ref5 = [xAxis.scale(value[0]), xAxis.scale(value[1])],\n _baseValueScale = _ref5[0],\n _currentValueScale = _ref5[1];\n x = _baseValueScale;\n y = getCateCoordinateOfBar({\n axis: yAxis,\n ticks: yAxisTicks,\n bandSize: bandSize,\n offset: pos.offset,\n entry: entry,\n index: index\n });\n width = _currentValueScale - _baseValueScale;\n height = pos.size;\n background = {\n x: xAxis.x,\n y: y,\n width: xAxis.width,\n height: height\n };\n if (Math.abs(minPointSize) > 0 && Math.abs(width) < Math.abs(minPointSize)) {\n var _delta = mathSign(width || minPointSize) * (Math.abs(minPointSize) - Math.abs(width));\n width += _delta;\n }\n }\n return _objectSpread(_objectSpread(_objectSpread({}, entry), {}, {\n x: x,\n y: y,\n width: width,\n height: height,\n value: stackedData ? value : value[1],\n payload: entry,\n background: background\n }, cells && cells[index] && cells[index].props), {}, {\n tooltipPayload: [getTooltipItem(item, entry)],\n tooltipPosition: {\n x: x + width / 2,\n y: y + height / 2\n }\n });\n });\n return _objectSpread({\n data: rects,\n layout: layout\n }, offset);\n});", "var _excluded = [\"x\", \"y\"];\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\nimport React from 'react';\nimport invariant from 'tiny-invariant';\nimport { Shape } from './ActiveShapeUtils';\nimport { isNullish, isNumber } from './DataUtils';\n\n// Rectangle props is expecting x, y, height, width as numbers, name as a string, and radius as a custom type\n// When props are being spread in from a user defined component in Bar,\n// the prop types of an SVGElement have these typed as something else.\n// This function will return the passed in props\n// along with x, y, height as numbers, name as a string, and radius as number | [number, number, number, number]\nfunction typeguardBarRectangleProps(_ref, props) {\n var xProp = _ref.x,\n yProp = _ref.y,\n option = _objectWithoutProperties(_ref, _excluded);\n var xValue = \"\".concat(xProp);\n var x = parseInt(xValue, 10);\n var yValue = \"\".concat(yProp);\n var y = parseInt(yValue, 10);\n var heightValue = \"\".concat(props.height || option.height);\n var height = parseInt(heightValue, 10);\n var widthValue = \"\".concat(props.width || option.width);\n var width = parseInt(widthValue, 10);\n return _objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread({}, props), option), x ? {\n x: x\n } : {}), y ? {\n y: y\n } : {}), {}, {\n height: height,\n width: width,\n name: props.name,\n radius: props.radius\n });\n}\nexport function BarRectangle(props) {\n return /*#__PURE__*/React.createElement(Shape, _extends({\n shapeType: \"rectangle\",\n propTransformer: typeguardBarRectangleProps,\n activeClassName: \"recharts-active-bar\"\n }, props));\n}\n/**\n * Safely gets minPointSize from from the minPointSize prop if it is a function\n * @param minPointSize minPointSize as passed to the Bar component\n * @param defaultValue default minPointSize\n * @returns minPointSize\n */\nexport var minPointSizeCallback = function minPointSizeCallback(minPointSize) {\n var defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n return function (value, index) {\n if (typeof minPointSize === 'number') return minPointSize;\n var isValueNumberOrNil = isNumber(value) || isNullish(value);\n if (isValueNumberOrNil) {\n return minPointSize(value, index);\n }\n !isValueNumberOrNil ? process.env.NODE_ENV !== \"production\" ? invariant(false, \"minPointSize callback function received a value with type of \".concat(_typeof(value), \". Currently only numbers or null/undefined are supported.\")) : invariant(false) : void 0;\n return defaultValue;\n };\n};", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nimport React, { createContext, useContext } from 'react';\nimport invariant from 'tiny-invariant';\nimport find from 'lodash/find';\nimport every from 'lodash/every';\nimport { calculateViewBox } from '../util/calculateViewBox';\nimport { getAnyElementOfObject } from '../util/DataUtils';\nexport var XAxisContext = /*#__PURE__*/createContext(undefined);\nexport var YAxisContext = /*#__PURE__*/createContext(undefined);\nexport var ViewBoxContext = /*#__PURE__*/createContext(undefined);\nexport var OffsetContext = /*#__PURE__*/createContext({});\nexport var ClipPathIdContext = /*#__PURE__*/createContext(undefined);\nexport var ChartHeightContext = /*#__PURE__*/createContext(0);\nexport var ChartWidthContext = /*#__PURE__*/createContext(0);\n\n/**\n * Will add all the properties required to render all individual Recharts components into a React Context.\n *\n * If you want to read these properties, see the collection of hooks exported from this file.\n *\n * @param {object} props CategoricalChartState, plus children\n * @returns {ReactElement} React Context Provider\n */\nexport var ChartLayoutContextProvider = function ChartLayoutContextProvider(props) {\n var _props$state = props.state,\n xAxisMap = _props$state.xAxisMap,\n yAxisMap = _props$state.yAxisMap,\n offset = _props$state.offset,\n clipPathId = props.clipPathId,\n children = props.children,\n width = props.width,\n height = props.height;\n\n /**\n * Perhaps we should compute this property when reading? Let's see what is more often used\n */\n var viewBox = calculateViewBox(offset);\n\n /*\n * This pretends to be a single context but actually is split into multiple smaller ones.\n * Why?\n * Because one React Context only allows to set one value.\n * But we need to set multiple values.\n * If we do that with one context, then we force re-render on components that might not even be interested\n * in the part of the state that has changed.\n *\n * By splitting into smaller contexts, we allow each components to be optimized and only re-render when its dependencies change.\n *\n * To actually achieve the optimal re-render, it is necessary to use React.memo().\n * See the test file for details.\n */\n return /*#__PURE__*/React.createElement(XAxisContext.Provider, {\n value: xAxisMap\n }, /*#__PURE__*/React.createElement(YAxisContext.Provider, {\n value: yAxisMap\n }, /*#__PURE__*/React.createElement(OffsetContext.Provider, {\n value: offset\n }, /*#__PURE__*/React.createElement(ViewBoxContext.Provider, {\n value: viewBox\n }, /*#__PURE__*/React.createElement(ClipPathIdContext.Provider, {\n value: clipPathId\n }, /*#__PURE__*/React.createElement(ChartHeightContext.Provider, {\n value: height\n }, /*#__PURE__*/React.createElement(ChartWidthContext.Provider, {\n value: width\n }, children)))))));\n};\nexport var useClipPathId = function useClipPathId() {\n return useContext(ClipPathIdContext);\n};\nfunction getKeysForDebug(object) {\n var keys = Object.keys(object);\n if (keys.length === 0) {\n return 'There are no available ids.';\n }\n return \"Available ids are: \".concat(keys, \".\");\n}\n\n/**\n * This either finds and returns Axis by the specified ID, or throws an exception if an axis with this ID does not exist.\n *\n * @param xAxisId identifier of the axis - it's either autogenerated ('0'), or passed via `id` prop as \n * @returns axis configuration object\n * @throws Error if no axis with this ID exists\n */\nexport var useXAxisOrThrow = function useXAxisOrThrow(xAxisId) {\n var xAxisMap = useContext(XAxisContext);\n !(xAxisMap != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Could not find Recharts context; are you sure this is rendered inside a Recharts wrapper component?') : invariant(false) : void 0;\n var xAxis = xAxisMap[xAxisId];\n !(xAxis != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, \"Could not find xAxis by id \\\"\".concat(xAxisId, \"\\\" [\").concat(_typeof(xAxisId), \"]. \").concat(getKeysForDebug(xAxisMap))) : invariant(false) : void 0;\n return xAxis;\n};\n\n/**\n * This will find an arbitrary first XAxis. If there's exactly one it always returns that one\n * - but if there are multiple then it can return any of those.\n *\n * If you want specific XAxis out of multiple then prefer using useXAxisOrThrow\n *\n * @returns X axisOptions, or undefined - if there are no X axes\n */\nexport var useArbitraryXAxis = function useArbitraryXAxis() {\n var xAxisMap = useContext(XAxisContext);\n return getAnyElementOfObject(xAxisMap);\n};\n\n/**\n * This will find an arbitrary first YAxis. If there's exactly one it always returns that one\n * - but if there are multiple then it can return any of those.\n *\n * If you want specific YAxis out of multiple then prefer using useXAxisOrThrow\n *\n * @returns Y axisOptions, or undefined - if there are no Y axes\n */\nexport var useArbitraryYAxis = function useArbitraryYAxis() {\n var yAxisMap = useContext(YAxisContext);\n return getAnyElementOfObject(yAxisMap);\n};\n\n/**\n * This hooks will:\n * 1st attempt to find an YAxis that has all elements in its domain finite\n * If no such axis exists, it will return an arbitrary YAxis\n * if there are no Y axes then it returns undefined\n *\n * @returns Either Y axisOptions, or undefined if there are no Y axes\n */\nexport var useYAxisWithFiniteDomainOrRandom = function useYAxisWithFiniteDomainOrRandom() {\n var yAxisMap = useContext(YAxisContext);\n var yAxisWithFiniteDomain = find(yAxisMap, function (axis) {\n return every(axis.domain, Number.isFinite);\n });\n return yAxisWithFiniteDomain || getAnyElementOfObject(yAxisMap);\n};\n\n/**\n * This either finds and returns Axis by the specified ID, or throws an exception if an axis with this ID does not exist.\n *\n * @param yAxisId identifier of the axis - it's either autogenerated ('0'), or passed via `id` prop as \n * @returns axis configuration object\n * @throws Error if no axis with this ID exists\n */\nexport var useYAxisOrThrow = function useYAxisOrThrow(yAxisId) {\n var yAxisMap = useContext(YAxisContext);\n !(yAxisMap != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Could not find Recharts context; are you sure this is rendered inside a Recharts wrapper component?') : invariant(false) : void 0;\n var yAxis = yAxisMap[yAxisId];\n !(yAxis != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, \"Could not find yAxis by id \\\"\".concat(yAxisId, \"\\\" [\").concat(_typeof(yAxisId), \"]. \").concat(getKeysForDebug(yAxisMap))) : invariant(false) : void 0;\n return yAxis;\n};\nexport var useViewBox = function useViewBox() {\n var viewBox = useContext(ViewBoxContext);\n return viewBox;\n};\nexport var useOffset = function useOffset() {\n return useContext(OffsetContext);\n};\nexport var useChartWidth = function useChartWidth() {\n return useContext(ChartWidthContext);\n};\nexport var useChartHeight = function useChartHeight() {\n return useContext(ChartHeightContext);\n};", "import memoize from 'lodash/memoize';\n/**\n * This is memoized because the viewBox is unlikely to change often\n * - but because it is computed from offset, any change to it would re-render all children.\n *\n * And because we have many readers of the viewBox, and update it only rarely,\n * then let's optimize with memoization.\n */\nexport var calculateViewBox = memoize(function (offset) {\n return {\n x: offset.left,\n y: offset.top,\n width: offset.width,\n height: offset.height\n };\n}, function (offset) {\n return ['l', offset.left, 't', offset.top, 'w', offset.width, 'h', offset.height].join('');\n});", "function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Reference Dot\n */\nimport React from 'react';\nimport isFunction from 'lodash/isFunction';\nimport clsx from 'clsx';\nimport { Layer } from '../container/Layer';\nimport { Dot } from '../shape/Dot';\nimport { Label } from '../component/Label';\nimport { isNumOrStr } from '../util/DataUtils';\nimport { ifOverflowMatches } from '../util/IfOverflowMatches';\nimport { createLabeledScales } from '../util/CartesianUtils';\nimport { warn } from '../util/LogUtils';\nimport { filterProps } from '../util/ReactUtils';\nvar getCoordinate = function getCoordinate(props) {\n var x = props.x,\n y = props.y,\n xAxis = props.xAxis,\n yAxis = props.yAxis;\n var scales = createLabeledScales({\n x: xAxis.scale,\n y: yAxis.scale\n });\n var result = scales.apply({\n x: x,\n y: y\n }, {\n bandAware: true\n });\n if (ifOverflowMatches(props, 'discard') && !scales.isInRange(result)) {\n return null;\n }\n return result;\n};\n\n// eslint-disable-next-line react/prefer-stateless-function -- requires static defaultProps\nexport var ReferenceDot = /*#__PURE__*/function (_React$Component) {\n function ReferenceDot() {\n _classCallCheck(this, ReferenceDot);\n return _callSuper(this, ReferenceDot, arguments);\n }\n _inherits(ReferenceDot, _React$Component);\n return _createClass(ReferenceDot, [{\n key: \"render\",\n value: function render() {\n var _this$props = this.props,\n x = _this$props.x,\n y = _this$props.y,\n r = _this$props.r,\n alwaysShow = _this$props.alwaysShow,\n clipPathId = _this$props.clipPathId;\n var isX = isNumOrStr(x);\n var isY = isNumOrStr(y);\n warn(alwaysShow === undefined, 'The alwaysShow prop is deprecated. Please use ifOverflow=\"extendDomain\" instead.');\n if (!isX || !isY) {\n return null;\n }\n var coordinate = getCoordinate(this.props);\n if (!coordinate) {\n return null;\n }\n var cx = coordinate.x,\n cy = coordinate.y;\n var _this$props2 = this.props,\n shape = _this$props2.shape,\n className = _this$props2.className;\n var clipPath = ifOverflowMatches(this.props, 'hidden') ? \"url(#\".concat(clipPathId, \")\") : undefined;\n var dotProps = _objectSpread(_objectSpread({\n clipPath: clipPath\n }, filterProps(this.props, true)), {}, {\n cx: cx,\n cy: cy\n });\n return /*#__PURE__*/React.createElement(Layer, {\n className: clsx('recharts-reference-dot', className)\n }, ReferenceDot.renderDot(shape, dotProps), Label.renderCallByParent(this.props, {\n x: cx - r,\n y: cy - r,\n width: 2 * r,\n height: 2 * r\n }));\n }\n }]);\n}(React.Component);\n_defineProperty(ReferenceDot, \"displayName\", 'ReferenceDot');\n_defineProperty(ReferenceDot, \"defaultProps\", {\n isFront: false,\n ifOverflow: 'discard',\n xAxisId: 0,\n yAxisId: 0,\n r: 10,\n fill: '#fff',\n stroke: '#ccc',\n fillOpacity: 1,\n strokeWidth: 1\n});\n_defineProperty(ReferenceDot, \"renderDot\", function (option, props) {\n var dot;\n if ( /*#__PURE__*/React.isValidElement(option)) {\n dot = /*#__PURE__*/React.cloneElement(option, props);\n } else if (isFunction(option)) {\n dot = option(props);\n } else {\n dot = /*#__PURE__*/React.createElement(Dot, _extends({}, props, {\n cx: props.cx,\n cy: props.cy,\n className: \"recharts-reference-dot-dot\"\n }));\n }\n return dot;\n});", "function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Reference Line\n */\nimport React from 'react';\nimport isFunction from 'lodash/isFunction';\nimport clsx from 'clsx';\nimport { Layer } from '../container/Layer';\nimport { Label } from '../component/Label';\nimport { createLabeledScales, rectWithPoints } from '../util/CartesianUtils';\nimport { ifOverflowMatches } from '../util/IfOverflowMatches';\nimport { isNumOrStr } from '../util/DataUtils';\nimport { warn } from '../util/LogUtils';\nimport { Rectangle } from '../shape/Rectangle';\nimport { filterProps } from '../util/ReactUtils';\nvar getRect = function getRect(hasX1, hasX2, hasY1, hasY2, props) {\n var xValue1 = props.x1,\n xValue2 = props.x2,\n yValue1 = props.y1,\n yValue2 = props.y2,\n xAxis = props.xAxis,\n yAxis = props.yAxis;\n if (!xAxis || !yAxis) return null;\n var scales = createLabeledScales({\n x: xAxis.scale,\n y: yAxis.scale\n });\n var p1 = {\n x: hasX1 ? scales.x.apply(xValue1, {\n position: 'start'\n }) : scales.x.rangeMin,\n y: hasY1 ? scales.y.apply(yValue1, {\n position: 'start'\n }) : scales.y.rangeMin\n };\n var p2 = {\n x: hasX2 ? scales.x.apply(xValue2, {\n position: 'end'\n }) : scales.x.rangeMax,\n y: hasY2 ? scales.y.apply(yValue2, {\n position: 'end'\n }) : scales.y.rangeMax\n };\n if (ifOverflowMatches(props, 'discard') && (!scales.isInRange(p1) || !scales.isInRange(p2))) {\n return null;\n }\n return rectWithPoints(p1, p2);\n};\n\n// eslint-disable-next-line react/prefer-stateless-function -- requires static defaultProps\nexport var ReferenceArea = /*#__PURE__*/function (_React$Component) {\n function ReferenceArea() {\n _classCallCheck(this, ReferenceArea);\n return _callSuper(this, ReferenceArea, arguments);\n }\n _inherits(ReferenceArea, _React$Component);\n return _createClass(ReferenceArea, [{\n key: \"render\",\n value: function render() {\n var _this$props = this.props,\n x1 = _this$props.x1,\n x2 = _this$props.x2,\n y1 = _this$props.y1,\n y2 = _this$props.y2,\n className = _this$props.className,\n alwaysShow = _this$props.alwaysShow,\n clipPathId = _this$props.clipPathId;\n warn(alwaysShow === undefined, 'The alwaysShow prop is deprecated. Please use ifOverflow=\"extendDomain\" instead.');\n var hasX1 = isNumOrStr(x1);\n var hasX2 = isNumOrStr(x2);\n var hasY1 = isNumOrStr(y1);\n var hasY2 = isNumOrStr(y2);\n var shape = this.props.shape;\n if (!hasX1 && !hasX2 && !hasY1 && !hasY2 && !shape) {\n return null;\n }\n var rect = getRect(hasX1, hasX2, hasY1, hasY2, this.props);\n if (!rect && !shape) {\n return null;\n }\n var clipPath = ifOverflowMatches(this.props, 'hidden') ? \"url(#\".concat(clipPathId, \")\") : undefined;\n return /*#__PURE__*/React.createElement(Layer, {\n className: clsx('recharts-reference-area', className)\n }, ReferenceArea.renderRect(shape, _objectSpread(_objectSpread({\n clipPath: clipPath\n }, filterProps(this.props, true)), rect)), Label.renderCallByParent(this.props, rect));\n }\n }]);\n}(React.Component);\n_defineProperty(ReferenceArea, \"displayName\", 'ReferenceArea');\n_defineProperty(ReferenceArea, \"defaultProps\", {\n isFront: false,\n ifOverflow: 'discard',\n xAxisId: 0,\n yAxisId: 0,\n r: 10,\n fill: '#ccc',\n fillOpacity: 0.5,\n stroke: 'none',\n strokeWidth: 1\n});\n_defineProperty(ReferenceArea, \"renderRect\", function (option, props) {\n var rect;\n if ( /*#__PURE__*/React.isValidElement(option)) {\n rect = /*#__PURE__*/React.cloneElement(option, props);\n } else if (isFunction(option)) {\n rect = option(props);\n } else {\n rect = /*#__PURE__*/React.createElement(Rectangle, _extends({}, props, {\n className: \"recharts-reference-area-rect\"\n }));\n }\n return rect;\n});", "var _excluded = [\"viewBox\"],\n _excluded2 = [\"viewBox\"],\n _excluded3 = [\"ticks\"];\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Cartesian Axis\n */\nimport React, { Component } from 'react';\nimport isFunction from 'lodash/isFunction';\nimport get from 'lodash/get';\nimport clsx from 'clsx';\nimport { shallowEqual } from '../util/ShallowEqual';\nimport { Layer } from '../container/Layer';\nimport { Text } from '../component/Text';\nimport { Label } from '../component/Label';\nimport { isNumber } from '../util/DataUtils';\nimport { adaptEventsOfChild } from '../util/types';\nimport { filterProps } from '../util/ReactUtils';\nimport { getTicks } from './getTicks';\n\n/** The orientation of the axis in correspondence to the chart */\n\n/** A unit to be appended to a value */\n\n/** The formatter function of tick */\n\nexport var CartesianAxis = /*#__PURE__*/function (_Component) {\n function CartesianAxis(props) {\n var _this;\n _classCallCheck(this, CartesianAxis);\n _this = _callSuper(this, CartesianAxis, [props]);\n _this.state = {\n fontSize: '',\n letterSpacing: ''\n };\n return _this;\n }\n _inherits(CartesianAxis, _Component);\n return _createClass(CartesianAxis, [{\n key: \"shouldComponentUpdate\",\n value: function shouldComponentUpdate(_ref, nextState) {\n var viewBox = _ref.viewBox,\n restProps = _objectWithoutProperties(_ref, _excluded);\n // props.viewBox is sometimes generated every time -\n // check that specially as object equality is likely to fail\n var _this$props = this.props,\n viewBoxOld = _this$props.viewBox,\n restPropsOld = _objectWithoutProperties(_this$props, _excluded2);\n return !shallowEqual(viewBox, viewBoxOld) || !shallowEqual(restProps, restPropsOld) || !shallowEqual(nextState, this.state);\n }\n }, {\n key: \"componentDidMount\",\n value: function componentDidMount() {\n var htmlLayer = this.layerReference;\n if (!htmlLayer) return;\n var tick = htmlLayer.getElementsByClassName('recharts-cartesian-axis-tick-value')[0];\n if (tick) {\n this.setState({\n fontSize: window.getComputedStyle(tick).fontSize,\n letterSpacing: window.getComputedStyle(tick).letterSpacing\n });\n }\n }\n\n /**\n * Calculate the coordinates of endpoints in ticks\n * @param {Object} data The data of a simple tick\n * @return {Object} (x1, y1): The coordinate of endpoint close to tick text\n * (x2, y2): The coordinate of endpoint close to axis\n */\n }, {\n key: \"getTickLineCoord\",\n value: function getTickLineCoord(data) {\n var _this$props2 = this.props,\n x = _this$props2.x,\n y = _this$props2.y,\n width = _this$props2.width,\n height = _this$props2.height,\n orientation = _this$props2.orientation,\n tickSize = _this$props2.tickSize,\n mirror = _this$props2.mirror,\n tickMargin = _this$props2.tickMargin;\n var x1, x2, y1, y2, tx, ty;\n var sign = mirror ? -1 : 1;\n var finalTickSize = data.tickSize || tickSize;\n var tickCoord = isNumber(data.tickCoord) ? data.tickCoord : data.coordinate;\n switch (orientation) {\n case 'top':\n x1 = x2 = data.coordinate;\n y2 = y + +!mirror * height;\n y1 = y2 - sign * finalTickSize;\n ty = y1 - sign * tickMargin;\n tx = tickCoord;\n break;\n case 'left':\n y1 = y2 = data.coordinate;\n x2 = x + +!mirror * width;\n x1 = x2 - sign * finalTickSize;\n tx = x1 - sign * tickMargin;\n ty = tickCoord;\n break;\n case 'right':\n y1 = y2 = data.coordinate;\n x2 = x + +mirror * width;\n x1 = x2 + sign * finalTickSize;\n tx = x1 + sign * tickMargin;\n ty = tickCoord;\n break;\n default:\n x1 = x2 = data.coordinate;\n y2 = y + +mirror * height;\n y1 = y2 + sign * finalTickSize;\n ty = y1 + sign * tickMargin;\n tx = tickCoord;\n break;\n }\n return {\n line: {\n x1: x1,\n y1: y1,\n x2: x2,\n y2: y2\n },\n tick: {\n x: tx,\n y: ty\n }\n };\n }\n }, {\n key: \"getTickTextAnchor\",\n value: function getTickTextAnchor() {\n var _this$props3 = this.props,\n orientation = _this$props3.orientation,\n mirror = _this$props3.mirror;\n var textAnchor;\n switch (orientation) {\n case 'left':\n textAnchor = mirror ? 'start' : 'end';\n break;\n case 'right':\n textAnchor = mirror ? 'end' : 'start';\n break;\n default:\n textAnchor = 'middle';\n break;\n }\n return textAnchor;\n }\n }, {\n key: \"getTickVerticalAnchor\",\n value: function getTickVerticalAnchor() {\n var _this$props4 = this.props,\n orientation = _this$props4.orientation,\n mirror = _this$props4.mirror;\n var verticalAnchor = 'end';\n switch (orientation) {\n case 'left':\n case 'right':\n verticalAnchor = 'middle';\n break;\n case 'top':\n verticalAnchor = mirror ? 'start' : 'end';\n break;\n default:\n verticalAnchor = mirror ? 'end' : 'start';\n break;\n }\n return verticalAnchor;\n }\n }, {\n key: \"renderAxisLine\",\n value: function renderAxisLine() {\n var _this$props5 = this.props,\n x = _this$props5.x,\n y = _this$props5.y,\n width = _this$props5.width,\n height = _this$props5.height,\n orientation = _this$props5.orientation,\n mirror = _this$props5.mirror,\n axisLine = _this$props5.axisLine;\n var props = _objectSpread(_objectSpread(_objectSpread({}, filterProps(this.props, false)), filterProps(axisLine, false)), {}, {\n fill: 'none'\n });\n if (orientation === 'top' || orientation === 'bottom') {\n var needHeight = +(orientation === 'top' && !mirror || orientation === 'bottom' && mirror);\n props = _objectSpread(_objectSpread({}, props), {}, {\n x1: x,\n y1: y + needHeight * height,\n x2: x + width,\n y2: y + needHeight * height\n });\n } else {\n var needWidth = +(orientation === 'left' && !mirror || orientation === 'right' && mirror);\n props = _objectSpread(_objectSpread({}, props), {}, {\n x1: x + needWidth * width,\n y1: y,\n x2: x + needWidth * width,\n y2: y + height\n });\n }\n return /*#__PURE__*/React.createElement(\"line\", _extends({}, props, {\n className: clsx('recharts-cartesian-axis-line', get(axisLine, 'className'))\n }));\n }\n }, {\n key: \"renderTicks\",\n value:\n /**\n * render the ticks\n * @param {Array} ticks The ticks to actually render (overrides what was passed in props)\n * @param {string} fontSize Fontsize to consider for tick spacing\n * @param {string} letterSpacing Letterspacing to consider for tick spacing\n * @return {ReactComponent} renderedTicks\n */\n function renderTicks(ticks, fontSize, letterSpacing) {\n var _this2 = this;\n var _this$props6 = this.props,\n tickLine = _this$props6.tickLine,\n stroke = _this$props6.stroke,\n tick = _this$props6.tick,\n tickFormatter = _this$props6.tickFormatter,\n unit = _this$props6.unit;\n var finalTicks = getTicks(_objectSpread(_objectSpread({}, this.props), {}, {\n ticks: ticks\n }), fontSize, letterSpacing);\n var textAnchor = this.getTickTextAnchor();\n var verticalAnchor = this.getTickVerticalAnchor();\n var axisProps = filterProps(this.props, false);\n var customTickProps = filterProps(tick, false);\n var tickLineProps = _objectSpread(_objectSpread({}, axisProps), {}, {\n fill: 'none'\n }, filterProps(tickLine, false));\n var items = finalTicks.map(function (entry, i) {\n var _this2$getTickLineCoo = _this2.getTickLineCoord(entry),\n lineCoord = _this2$getTickLineCoo.line,\n tickCoord = _this2$getTickLineCoo.tick;\n var tickProps = _objectSpread(_objectSpread(_objectSpread(_objectSpread({\n textAnchor: textAnchor,\n verticalAnchor: verticalAnchor\n }, axisProps), {}, {\n stroke: 'none',\n fill: stroke\n }, customTickProps), tickCoord), {}, {\n index: i,\n payload: entry,\n visibleTicksCount: finalTicks.length,\n tickFormatter: tickFormatter\n });\n return /*#__PURE__*/React.createElement(Layer, _extends({\n className: \"recharts-cartesian-axis-tick\",\n key: \"tick-\".concat(entry.value, \"-\").concat(entry.coordinate, \"-\").concat(entry.tickCoord)\n }, adaptEventsOfChild(_this2.props, entry, i)), tickLine && /*#__PURE__*/React.createElement(\"line\", _extends({}, tickLineProps, lineCoord, {\n className: clsx('recharts-cartesian-axis-tick-line', get(tickLine, 'className'))\n })), tick && CartesianAxis.renderTickItem(tick, tickProps, \"\".concat(isFunction(tickFormatter) ? tickFormatter(entry.value, i) : entry.value).concat(unit || '')));\n });\n return /*#__PURE__*/React.createElement(\"g\", {\n className: \"recharts-cartesian-axis-ticks\"\n }, items);\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this3 = this;\n var _this$props7 = this.props,\n axisLine = _this$props7.axisLine,\n width = _this$props7.width,\n height = _this$props7.height,\n ticksGenerator = _this$props7.ticksGenerator,\n className = _this$props7.className,\n hide = _this$props7.hide;\n if (hide) {\n return null;\n }\n var _this$props8 = this.props,\n ticks = _this$props8.ticks,\n noTicksProps = _objectWithoutProperties(_this$props8, _excluded3);\n var finalTicks = ticks;\n if (isFunction(ticksGenerator)) {\n finalTicks = ticks && ticks.length > 0 ? ticksGenerator(this.props) : ticksGenerator(noTicksProps);\n }\n if (width <= 0 || height <= 0 || !finalTicks || !finalTicks.length) {\n return null;\n }\n return /*#__PURE__*/React.createElement(Layer, {\n className: clsx('recharts-cartesian-axis', className),\n ref: function ref(_ref2) {\n _this3.layerReference = _ref2;\n }\n }, axisLine && this.renderAxisLine(), this.renderTicks(finalTicks, this.state.fontSize, this.state.letterSpacing), Label.renderCallByParent(this.props));\n }\n }], [{\n key: \"renderTickItem\",\n value: function renderTickItem(option, props, value) {\n var tickItem;\n var combinedClassName = clsx(props.className, 'recharts-cartesian-axis-tick-value');\n if ( /*#__PURE__*/React.isValidElement(option)) {\n tickItem = /*#__PURE__*/React.cloneElement(option, _objectSpread(_objectSpread({}, props), {}, {\n className: combinedClassName\n }));\n } else if (isFunction(option)) {\n tickItem = option(_objectSpread(_objectSpread({}, props), {}, {\n className: combinedClassName\n }));\n } else {\n tickItem = /*#__PURE__*/React.createElement(Text, _extends({}, props, {\n className: \"recharts-cartesian-axis-tick-value\"\n }), value);\n }\n return tickItem;\n }\n }]);\n}(Component);\n_defineProperty(CartesianAxis, \"displayName\", 'CartesianAxis');\n_defineProperty(CartesianAxis, \"defaultProps\", {\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n viewBox: {\n x: 0,\n y: 0,\n width: 0,\n height: 0\n },\n // The orientation of axis\n orientation: 'bottom',\n // The ticks\n ticks: [],\n stroke: '#666',\n tickLine: true,\n axisLine: true,\n tick: true,\n mirror: false,\n minTickGap: 5,\n // The width or height of tick\n tickSize: 6,\n tickMargin: 2,\n interval: 'preserveEnd'\n});", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nimport isFunction from 'lodash/isFunction';\nimport { mathSign, isNumber } from '../util/DataUtils';\nimport { getStringSize } from '../util/DOMUtils';\nimport { Global } from '../util/Global';\nimport { isVisible, getTickBoundaries, getNumberIntervalTicks, getAngledTickWidth } from '../util/TickUtils';\nimport { getEquidistantTicks } from './getEquidistantTicks';\nfunction getTicksEnd(sign, boundaries, getTickSize, ticks, minTickGap) {\n var result = (ticks || []).slice();\n var len = result.length;\n var start = boundaries.start;\n var end = boundaries.end;\n var _loop = function _loop(i) {\n var entry = result[i];\n var size;\n var getSize = function getSize() {\n if (size === undefined) {\n size = getTickSize(entry, i);\n }\n return size;\n };\n if (i === len - 1) {\n var gap = sign * (entry.coordinate + sign * getSize() / 2 - end);\n result[i] = entry = _objectSpread(_objectSpread({}, entry), {}, {\n tickCoord: gap > 0 ? entry.coordinate - gap * sign : entry.coordinate\n });\n } else {\n result[i] = entry = _objectSpread(_objectSpread({}, entry), {}, {\n tickCoord: entry.coordinate\n });\n }\n var isShow = isVisible(sign, entry.tickCoord, getSize, start, end);\n if (isShow) {\n end = entry.tickCoord - sign * (getSize() / 2 + minTickGap);\n result[i] = _objectSpread(_objectSpread({}, entry), {}, {\n isShow: true\n });\n }\n };\n for (var i = len - 1; i >= 0; i--) {\n _loop(i);\n }\n return result;\n}\nfunction getTicksStart(sign, boundaries, getTickSize, ticks, minTickGap, preserveEnd) {\n var result = (ticks || []).slice();\n var len = result.length;\n var start = boundaries.start,\n end = boundaries.end;\n if (preserveEnd) {\n // Try to guarantee the tail to be displayed\n var tail = ticks[len - 1];\n var tailSize = getTickSize(tail, len - 1);\n var tailGap = sign * (tail.coordinate + sign * tailSize / 2 - end);\n result[len - 1] = tail = _objectSpread(_objectSpread({}, tail), {}, {\n tickCoord: tailGap > 0 ? tail.coordinate - tailGap * sign : tail.coordinate\n });\n var isTailShow = isVisible(sign, tail.tickCoord, function () {\n return tailSize;\n }, start, end);\n if (isTailShow) {\n end = tail.tickCoord - sign * (tailSize / 2 + minTickGap);\n result[len - 1] = _objectSpread(_objectSpread({}, tail), {}, {\n isShow: true\n });\n }\n }\n var count = preserveEnd ? len - 1 : len;\n var _loop2 = function _loop2(i) {\n var entry = result[i];\n var size;\n var getSize = function getSize() {\n if (size === undefined) {\n size = getTickSize(entry, i);\n }\n return size;\n };\n if (i === 0) {\n var gap = sign * (entry.coordinate - sign * getSize() / 2 - start);\n result[i] = entry = _objectSpread(_objectSpread({}, entry), {}, {\n tickCoord: gap < 0 ? entry.coordinate - gap * sign : entry.coordinate\n });\n } else {\n result[i] = entry = _objectSpread(_objectSpread({}, entry), {}, {\n tickCoord: entry.coordinate\n });\n }\n var isShow = isVisible(sign, entry.tickCoord, getSize, start, end);\n if (isShow) {\n start = entry.tickCoord + sign * (getSize() / 2 + minTickGap);\n result[i] = _objectSpread(_objectSpread({}, entry), {}, {\n isShow: true\n });\n }\n };\n for (var i = 0; i < count; i++) {\n _loop2(i);\n }\n return result;\n}\nexport function getTicks(props, fontSize, letterSpacing) {\n var tick = props.tick,\n ticks = props.ticks,\n viewBox = props.viewBox,\n minTickGap = props.minTickGap,\n orientation = props.orientation,\n interval = props.interval,\n tickFormatter = props.tickFormatter,\n unit = props.unit,\n angle = props.angle;\n if (!ticks || !ticks.length || !tick) {\n return [];\n }\n if (isNumber(interval) || Global.isSsr) {\n return getNumberIntervalTicks(ticks, typeof interval === 'number' && isNumber(interval) ? interval : 0);\n }\n var candidates = [];\n var sizeKey = orientation === 'top' || orientation === 'bottom' ? 'width' : 'height';\n var unitSize = unit && sizeKey === 'width' ? getStringSize(unit, {\n fontSize: fontSize,\n letterSpacing: letterSpacing\n }) : {\n width: 0,\n height: 0\n };\n var getTickSize = function getTickSize(content, index) {\n var value = isFunction(tickFormatter) ? tickFormatter(content.value, index) : content.value;\n // Recharts only supports angles when sizeKey === 'width'\n return sizeKey === 'width' ? getAngledTickWidth(getStringSize(value, {\n fontSize: fontSize,\n letterSpacing: letterSpacing\n }), unitSize, angle) : getStringSize(value, {\n fontSize: fontSize,\n letterSpacing: letterSpacing\n })[sizeKey];\n };\n var sign = ticks.length >= 2 ? mathSign(ticks[1].coordinate - ticks[0].coordinate) : 1;\n var boundaries = getTickBoundaries(viewBox, sign, sizeKey);\n if (interval === 'equidistantPreserveStart') {\n return getEquidistantTicks(sign, boundaries, getTickSize, ticks, minTickGap);\n }\n if (interval === 'preserveStart' || interval === 'preserveStartEnd') {\n candidates = getTicksStart(sign, boundaries, getTickSize, ticks, minTickGap, interval === 'preserveStartEnd');\n } else {\n candidates = getTicksEnd(sign, boundaries, getTickSize, ticks, minTickGap);\n }\n return candidates.filter(function (entry) {\n return entry.isShow;\n });\n}", "/**\n * Given an array and a number N, return a new array which contains every nTh\n * element of the input array. For n below 1, an empty array is returned.\n * If isValid is provided, all candidates must suffice the condition, else undefined is returned.\n * @param {T[]} array An input array.\n * @param {integer} n A number\n * @param {Function} isValid A function to evaluate a candidate form the array\n * @returns {T[]} The result array of the same type as the input array.\n */\nexport function getEveryNthWithCondition(array, n, isValid) {\n if (n < 1) {\n return [];\n }\n if (n === 1 && isValid === undefined) {\n return array;\n }\n var result = [];\n for (var i = 0; i < array.length; i += n) {\n if (isValid === undefined || isValid(array[i]) === true) {\n result.push(array[i]);\n } else {\n return undefined;\n }\n }\n return result;\n}", "import { getAngledRectangleWidth } from './CartesianUtils';\nimport { getEveryNthWithCondition } from './getEveryNthWithCondition';\nexport function getAngledTickWidth(contentSize, unitSize, angle) {\n var size = {\n width: contentSize.width + unitSize.width,\n height: contentSize.height + unitSize.height\n };\n return getAngledRectangleWidth(size, angle);\n}\nexport function getTickBoundaries(viewBox, sign, sizeKey) {\n var isWidth = sizeKey === 'width';\n var x = viewBox.x,\n y = viewBox.y,\n width = viewBox.width,\n height = viewBox.height;\n if (sign === 1) {\n return {\n start: isWidth ? x : y,\n end: isWidth ? x + width : y + height\n };\n }\n return {\n start: isWidth ? x + width : y + height,\n end: isWidth ? x : y\n };\n}\nexport function isVisible(sign, tickPosition, getSize, start, end) {\n /* Since getSize() is expensive (it reads the ticks' size from the DOM), we do this check first to avoid calculating\n * the tick's size. */\n if (sign * tickPosition < sign * start || sign * tickPosition > sign * end) {\n return false;\n }\n var size = getSize();\n return sign * (tickPosition - sign * size / 2 - start) >= 0 && sign * (tickPosition + sign * size / 2 - end) <= 0;\n}\nexport function getNumberIntervalTicks(ticks, interval) {\n return getEveryNthWithCondition(ticks, interval + 1);\n}", "import { isVisible } from '../util/TickUtils';\nimport { getEveryNthWithCondition } from '../util/getEveryNthWithCondition';\nexport function getEquidistantTicks(sign, boundaries, getTickSize, ticks, minTickGap) {\n var result = (ticks || []).slice();\n var initialStart = boundaries.start,\n end = boundaries.end;\n var index = 0;\n // Premature optimisation idea 1: Estimate a lower bound, and start from there.\n // For now, start from every tick\n var stepsize = 1;\n var start = initialStart;\n var _loop = function _loop() {\n // Given stepsize, evaluate whether every stepsize-th tick can be shown.\n // If it can not, then increase the stepsize by 1, and try again.\n\n var entry = ticks === null || ticks === void 0 ? void 0 : ticks[index];\n\n // Break condition - If we have evaluate all the ticks, then we are done.\n if (entry === undefined) {\n return {\n v: getEveryNthWithCondition(ticks, stepsize)\n };\n }\n\n // Check if the element collides with the next element\n var i = index;\n var size;\n var getSize = function getSize() {\n if (size === undefined) {\n size = getTickSize(entry, i);\n }\n return size;\n };\n var tickCoord = entry.coordinate;\n // We will always show the first tick.\n var isShow = index === 0 || isVisible(sign, tickCoord, getSize, start, end);\n if (!isShow) {\n // Start all over with a larger stepsize\n index = 0;\n start = initialStart;\n stepsize += 1;\n }\n if (isShow) {\n // If it can be shown, update the start\n start = tickCoord + sign * (getSize() / 2 + minTickGap);\n index += stepsize;\n }\n },\n _ret;\n while (stepsize <= result.length) {\n _ret = _loop();\n if (_ret) return _ret.v;\n }\n return [];\n}", "var _excluded = [\"x1\", \"y1\", \"x2\", \"y2\", \"key\"],\n _excluded2 = [\"offset\"];\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\n/**\n * @fileOverview Cartesian Grid\n */\nimport React from 'react';\nimport isFunction from 'lodash/isFunction';\nimport { warn } from '../util/LogUtils';\nimport { isNumber } from '../util/DataUtils';\nimport { filterProps } from '../util/ReactUtils';\nimport { getCoordinatesOfGrid, getTicksOfAxis } from '../util/ChartUtils';\nimport { getTicks } from './getTicks';\nimport { CartesianAxis } from './CartesianAxis';\nimport { useArbitraryXAxis, useChartHeight, useChartWidth, useOffset, useYAxisWithFiniteDomainOrRandom } from '../context/chartLayoutContext';\n\n/**\n * The = 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Line\n */\nimport React, { PureComponent } from 'react';\nimport Animate from 'react-smooth';\nimport isFunction from 'lodash/isFunction';\nimport isNil from 'lodash/isNil';\nimport isEqual from 'lodash/isEqual';\nimport clsx from 'clsx';\nimport { Curve } from '../shape/Curve';\nimport { Dot } from '../shape/Dot';\nimport { Layer } from '../container/Layer';\nimport { LabelList } from '../component/LabelList';\nimport { ErrorBar } from './ErrorBar';\nimport { uniqueId, interpolateNumber } from '../util/DataUtils';\nimport { findAllByType, filterProps, hasClipDot } from '../util/ReactUtils';\nimport { Global } from '../util/Global';\nimport { getCateCoordinateOfLine, getValueByDataKey } from '../util/ChartUtils';\nexport var Line = /*#__PURE__*/function (_PureComponent) {\n function Line() {\n var _this;\n _classCallCheck(this, Line);\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n _this = _callSuper(this, Line, [].concat(args));\n _defineProperty(_this, \"state\", {\n isAnimationFinished: true,\n totalLength: 0\n });\n _defineProperty(_this, \"generateSimpleStrokeDasharray\", function (totalLength, length) {\n return \"\".concat(length, \"px \").concat(totalLength - length, \"px\");\n });\n _defineProperty(_this, \"getStrokeDasharray\", function (length, totalLength, lines) {\n var lineLength = lines.reduce(function (pre, next) {\n return pre + next;\n });\n\n // if lineLength is 0 return the default when no strokeDasharray is provided\n if (!lineLength) {\n return _this.generateSimpleStrokeDasharray(totalLength, length);\n }\n var count = Math.floor(length / lineLength);\n var remainLength = length % lineLength;\n var restLength = totalLength - length;\n var remainLines = [];\n for (var i = 0, sum = 0; i < lines.length; sum += lines[i], ++i) {\n if (sum + lines[i] > remainLength) {\n remainLines = [].concat(_toConsumableArray(lines.slice(0, i)), [remainLength - sum]);\n break;\n }\n }\n var emptyLines = remainLines.length % 2 === 0 ? [0, restLength] : [restLength];\n return [].concat(_toConsumableArray(Line.repeat(lines, count)), _toConsumableArray(remainLines), emptyLines).map(function (line) {\n return \"\".concat(line, \"px\");\n }).join(', ');\n });\n _defineProperty(_this, \"id\", uniqueId('recharts-line-'));\n _defineProperty(_this, \"pathRef\", function (node) {\n _this.mainCurve = node;\n });\n _defineProperty(_this, \"handleAnimationEnd\", function () {\n _this.setState({\n isAnimationFinished: true\n });\n if (_this.props.onAnimationEnd) {\n _this.props.onAnimationEnd();\n }\n });\n _defineProperty(_this, \"handleAnimationStart\", function () {\n _this.setState({\n isAnimationFinished: false\n });\n if (_this.props.onAnimationStart) {\n _this.props.onAnimationStart();\n }\n });\n return _this;\n }\n _inherits(Line, _PureComponent);\n return _createClass(Line, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n if (!this.props.isAnimationActive) {\n return;\n }\n var totalLength = this.getTotalLength();\n this.setState({\n totalLength: totalLength\n });\n }\n }, {\n key: \"componentDidUpdate\",\n value: function componentDidUpdate() {\n if (!this.props.isAnimationActive) {\n return;\n }\n var totalLength = this.getTotalLength();\n if (totalLength !== this.state.totalLength) {\n this.setState({\n totalLength: totalLength\n });\n }\n }\n }, {\n key: \"getTotalLength\",\n value: function getTotalLength() {\n var curveDom = this.mainCurve;\n try {\n return curveDom && curveDom.getTotalLength && curveDom.getTotalLength() || 0;\n } catch (err) {\n return 0;\n }\n }\n }, {\n key: \"renderErrorBar\",\n value: function renderErrorBar(needClip, clipPathId) {\n if (this.props.isAnimationActive && !this.state.isAnimationFinished) {\n return null;\n }\n var _this$props = this.props,\n points = _this$props.points,\n xAxis = _this$props.xAxis,\n yAxis = _this$props.yAxis,\n layout = _this$props.layout,\n children = _this$props.children;\n var errorBarItems = findAllByType(children, ErrorBar);\n if (!errorBarItems) {\n return null;\n }\n var dataPointFormatter = function dataPointFormatter(dataPoint, dataKey) {\n return {\n x: dataPoint.x,\n y: dataPoint.y,\n value: dataPoint.value,\n errorVal: getValueByDataKey(dataPoint.payload, dataKey)\n };\n };\n var errorBarProps = {\n clipPath: needClip ? \"url(#clipPath-\".concat(clipPathId, \")\") : null\n };\n return /*#__PURE__*/React.createElement(Layer, errorBarProps, errorBarItems.map(function (item) {\n return /*#__PURE__*/React.cloneElement(item, {\n key: \"bar-\".concat(item.props.dataKey),\n data: points,\n xAxis: xAxis,\n yAxis: yAxis,\n layout: layout,\n dataPointFormatter: dataPointFormatter\n });\n }));\n }\n }, {\n key: \"renderDots\",\n value: function renderDots(needClip, clipDot, clipPathId) {\n var isAnimationActive = this.props.isAnimationActive;\n if (isAnimationActive && !this.state.isAnimationFinished) {\n return null;\n }\n var _this$props2 = this.props,\n dot = _this$props2.dot,\n points = _this$props2.points,\n dataKey = _this$props2.dataKey;\n var lineProps = filterProps(this.props, false);\n var customDotProps = filterProps(dot, true);\n var dots = points.map(function (entry, i) {\n var dotProps = _objectSpread(_objectSpread(_objectSpread({\n key: \"dot-\".concat(i),\n r: 3\n }, lineProps), customDotProps), {}, {\n index: i,\n cx: entry.x,\n cy: entry.y,\n value: entry.value,\n dataKey: dataKey,\n payload: entry.payload,\n points: points\n });\n return Line.renderDotItem(dot, dotProps);\n });\n var dotsProps = {\n clipPath: needClip ? \"url(#clipPath-\".concat(clipDot ? '' : 'dots-').concat(clipPathId, \")\") : null\n };\n return /*#__PURE__*/React.createElement(Layer, _extends({\n className: \"recharts-line-dots\",\n key: \"dots\"\n }, dotsProps), dots);\n }\n }, {\n key: \"renderCurveStatically\",\n value: function renderCurveStatically(points, needClip, clipPathId, props) {\n var _this$props3 = this.props,\n type = _this$props3.type,\n layout = _this$props3.layout,\n connectNulls = _this$props3.connectNulls,\n ref = _this$props3.ref,\n others = _objectWithoutProperties(_this$props3, _excluded);\n var curveProps = _objectSpread(_objectSpread(_objectSpread({}, filterProps(others, true)), {}, {\n fill: 'none',\n className: 'recharts-line-curve',\n clipPath: needClip ? \"url(#clipPath-\".concat(clipPathId, \")\") : null,\n points: points\n }, props), {}, {\n type: type,\n layout: layout,\n connectNulls: connectNulls\n });\n return /*#__PURE__*/React.createElement(Curve, _extends({}, curveProps, {\n pathRef: this.pathRef\n }));\n }\n }, {\n key: \"renderCurveWithAnimation\",\n value: function renderCurveWithAnimation(needClip, clipPathId) {\n var _this2 = this;\n var _this$props4 = this.props,\n points = _this$props4.points,\n strokeDasharray = _this$props4.strokeDasharray,\n isAnimationActive = _this$props4.isAnimationActive,\n animationBegin = _this$props4.animationBegin,\n animationDuration = _this$props4.animationDuration,\n animationEasing = _this$props4.animationEasing,\n animationId = _this$props4.animationId,\n animateNewValues = _this$props4.animateNewValues,\n width = _this$props4.width,\n height = _this$props4.height;\n var _this$state = this.state,\n prevPoints = _this$state.prevPoints,\n totalLength = _this$state.totalLength;\n return /*#__PURE__*/React.createElement(Animate, {\n begin: animationBegin,\n duration: animationDuration,\n isActive: isAnimationActive,\n easing: animationEasing,\n from: {\n t: 0\n },\n to: {\n t: 1\n },\n key: \"line-\".concat(animationId),\n onAnimationEnd: this.handleAnimationEnd,\n onAnimationStart: this.handleAnimationStart\n }, function (_ref) {\n var t = _ref.t;\n if (prevPoints) {\n var prevPointsDiffFactor = prevPoints.length / points.length;\n var stepData = points.map(function (entry, index) {\n var prevPointIndex = Math.floor(index * prevPointsDiffFactor);\n if (prevPoints[prevPointIndex]) {\n var prev = prevPoints[prevPointIndex];\n var interpolatorX = interpolateNumber(prev.x, entry.x);\n var interpolatorY = interpolateNumber(prev.y, entry.y);\n return _objectSpread(_objectSpread({}, entry), {}, {\n x: interpolatorX(t),\n y: interpolatorY(t)\n });\n }\n\n // magic number of faking previous x and y location\n if (animateNewValues) {\n var _interpolatorX = interpolateNumber(width * 2, entry.x);\n var _interpolatorY = interpolateNumber(height / 2, entry.y);\n return _objectSpread(_objectSpread({}, entry), {}, {\n x: _interpolatorX(t),\n y: _interpolatorY(t)\n });\n }\n return _objectSpread(_objectSpread({}, entry), {}, {\n x: entry.x,\n y: entry.y\n });\n });\n return _this2.renderCurveStatically(stepData, needClip, clipPathId);\n }\n var interpolator = interpolateNumber(0, totalLength);\n var curLength = interpolator(t);\n var currentStrokeDasharray;\n if (strokeDasharray) {\n var lines = \"\".concat(strokeDasharray).split(/[,\\s]+/gim).map(function (num) {\n return parseFloat(num);\n });\n currentStrokeDasharray = _this2.getStrokeDasharray(curLength, totalLength, lines);\n } else {\n currentStrokeDasharray = _this2.generateSimpleStrokeDasharray(totalLength, curLength);\n }\n return _this2.renderCurveStatically(points, needClip, clipPathId, {\n strokeDasharray: currentStrokeDasharray\n });\n });\n }\n }, {\n key: \"renderCurve\",\n value: function renderCurve(needClip, clipPathId) {\n var _this$props5 = this.props,\n points = _this$props5.points,\n isAnimationActive = _this$props5.isAnimationActive;\n var _this$state2 = this.state,\n prevPoints = _this$state2.prevPoints,\n totalLength = _this$state2.totalLength;\n if (isAnimationActive && points && points.length && (!prevPoints && totalLength > 0 || !isEqual(prevPoints, points))) {\n return this.renderCurveWithAnimation(needClip, clipPathId);\n }\n return this.renderCurveStatically(points, needClip, clipPathId);\n }\n }, {\n key: \"render\",\n value: function render() {\n var _filterProps;\n var _this$props6 = this.props,\n hide = _this$props6.hide,\n dot = _this$props6.dot,\n points = _this$props6.points,\n className = _this$props6.className,\n xAxis = _this$props6.xAxis,\n yAxis = _this$props6.yAxis,\n top = _this$props6.top,\n left = _this$props6.left,\n width = _this$props6.width,\n height = _this$props6.height,\n isAnimationActive = _this$props6.isAnimationActive,\n id = _this$props6.id;\n if (hide || !points || !points.length) {\n return null;\n }\n var isAnimationFinished = this.state.isAnimationFinished;\n var hasSinglePoint = points.length === 1;\n var layerClass = clsx('recharts-line', className);\n var needClipX = xAxis && xAxis.allowDataOverflow;\n var needClipY = yAxis && yAxis.allowDataOverflow;\n var needClip = needClipX || needClipY;\n var clipPathId = isNil(id) ? this.id : id;\n var _ref2 = (_filterProps = filterProps(dot, false)) !== null && _filterProps !== void 0 ? _filterProps : {\n r: 3,\n strokeWidth: 2\n },\n _ref2$r = _ref2.r,\n r = _ref2$r === void 0 ? 3 : _ref2$r,\n _ref2$strokeWidth = _ref2.strokeWidth,\n strokeWidth = _ref2$strokeWidth === void 0 ? 2 : _ref2$strokeWidth;\n var _ref3 = hasClipDot(dot) ? dot : {},\n _ref3$clipDot = _ref3.clipDot,\n clipDot = _ref3$clipDot === void 0 ? true : _ref3$clipDot;\n var dotSize = r * 2 + strokeWidth;\n return /*#__PURE__*/React.createElement(Layer, {\n className: layerClass\n }, needClipX || needClipY ? /*#__PURE__*/React.createElement(\"defs\", null, /*#__PURE__*/React.createElement(\"clipPath\", {\n id: \"clipPath-\".concat(clipPathId)\n }, /*#__PURE__*/React.createElement(\"rect\", {\n x: needClipX ? left : left - width / 2,\n y: needClipY ? top : top - height / 2,\n width: needClipX ? width : width * 2,\n height: needClipY ? height : height * 2\n })), !clipDot && /*#__PURE__*/React.createElement(\"clipPath\", {\n id: \"clipPath-dots-\".concat(clipPathId)\n }, /*#__PURE__*/React.createElement(\"rect\", {\n x: left - dotSize / 2,\n y: top - dotSize / 2,\n width: width + dotSize,\n height: height + dotSize\n }))) : null, !hasSinglePoint && this.renderCurve(needClip, clipPathId), this.renderErrorBar(needClip, clipPathId), (hasSinglePoint || dot) && this.renderDots(needClip, clipDot, clipPathId), (!isAnimationActive || isAnimationFinished) && LabelList.renderCallByParent(this.props, points));\n }\n }], [{\n key: \"getDerivedStateFromProps\",\n value: function getDerivedStateFromProps(nextProps, prevState) {\n if (nextProps.animationId !== prevState.prevAnimationId) {\n return {\n prevAnimationId: nextProps.animationId,\n curPoints: nextProps.points,\n prevPoints: prevState.curPoints\n };\n }\n if (nextProps.points !== prevState.curPoints) {\n return {\n curPoints: nextProps.points\n };\n }\n return null;\n }\n }, {\n key: \"repeat\",\n value: function repeat(lines, count) {\n var linesUnit = lines.length % 2 !== 0 ? [].concat(_toConsumableArray(lines), [0]) : lines;\n var result = [];\n for (var i = 0; i < count; ++i) {\n result = [].concat(_toConsumableArray(result), _toConsumableArray(linesUnit));\n }\n return result;\n }\n }, {\n key: \"renderDotItem\",\n value: function renderDotItem(option, props) {\n var dotItem;\n if ( /*#__PURE__*/React.isValidElement(option)) {\n dotItem = /*#__PURE__*/React.cloneElement(option, props);\n } else if (isFunction(option)) {\n dotItem = option(props);\n } else {\n var key = props.key,\n dotProps = _objectWithoutProperties(props, _excluded2);\n var className = clsx('recharts-line-dot', typeof option !== 'boolean' ? option.className : '');\n dotItem = /*#__PURE__*/React.createElement(Dot, _extends({\n key: key\n }, dotProps, {\n className: className\n }));\n }\n return dotItem;\n }\n }]);\n}(PureComponent);\n_defineProperty(Line, \"displayName\", 'Line');\n_defineProperty(Line, \"defaultProps\", {\n xAxisId: 0,\n yAxisId: 0,\n connectNulls: false,\n activeDot: true,\n dot: true,\n legendType: 'line',\n stroke: '#3182bd',\n strokeWidth: 1,\n fill: '#fff',\n points: [],\n isAnimationActive: !Global.isSsr,\n animateNewValues: true,\n animationBegin: 0,\n animationDuration: 1500,\n animationEasing: 'ease',\n hide: false,\n label: false\n});\n/**\n * Compose the data of each group\n * @param {Object} props The props from the component\n * @param {Object} xAxis The configuration of x-axis\n * @param {Object} yAxis The configuration of y-axis\n * @param {String} dataKey The unique key of a group\n * @return {Array} Composed data\n */\n_defineProperty(Line, \"getComposedData\", function (_ref4) {\n var props = _ref4.props,\n xAxis = _ref4.xAxis,\n yAxis = _ref4.yAxis,\n xAxisTicks = _ref4.xAxisTicks,\n yAxisTicks = _ref4.yAxisTicks,\n dataKey = _ref4.dataKey,\n bandSize = _ref4.bandSize,\n displayedData = _ref4.displayedData,\n offset = _ref4.offset;\n var layout = props.layout;\n var points = displayedData.map(function (entry, index) {\n var value = getValueByDataKey(entry, dataKey);\n if (layout === 'horizontal') {\n return {\n x: getCateCoordinateOfLine({\n axis: xAxis,\n ticks: xAxisTicks,\n bandSize: bandSize,\n entry: entry,\n index: index\n }),\n y: isNil(value) ? null : yAxis.scale(value),\n value: value,\n payload: entry\n };\n }\n return {\n x: isNil(value) ? null : xAxis.scale(value),\n y: getCateCoordinateOfLine({\n axis: yAxis,\n ticks: yAxisTicks,\n bandSize: bandSize,\n entry: entry,\n index: index\n }),\n value: value,\n payload: entry\n };\n });\n return _objectSpread({\n points: points,\n layout: layout\n }, offset);\n});", "var _excluded = [\"layout\", \"type\", \"stroke\", \"connectNulls\", \"isRange\", \"ref\"],\n _excluded2 = [\"key\"];\nvar _Area;\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\n/**\n * @fileOverview Area\n */\nimport React, { PureComponent } from 'react';\nimport clsx from 'clsx';\nimport Animate from 'react-smooth';\nimport isFunction from 'lodash/isFunction';\nimport max from 'lodash/max';\nimport isNil from 'lodash/isNil';\nimport isNan from 'lodash/isNaN';\nimport isEqual from 'lodash/isEqual';\nimport { Curve } from '../shape/Curve';\nimport { Dot } from '../shape/Dot';\nimport { Layer } from '../container/Layer';\nimport { LabelList } from '../component/LabelList';\nimport { Global } from '../util/Global';\nimport { isNumber, uniqueId, interpolateNumber } from '../util/DataUtils';\nimport { getCateCoordinateOfLine, getValueByDataKey } from '../util/ChartUtils';\nimport { filterProps, hasClipDot } from '../util/ReactUtils';\nexport var Area = /*#__PURE__*/function (_PureComponent) {\n function Area() {\n var _this;\n _classCallCheck(this, Area);\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n _this = _callSuper(this, Area, [].concat(args));\n _defineProperty(_this, \"state\", {\n isAnimationFinished: true\n });\n _defineProperty(_this, \"id\", uniqueId('recharts-area-'));\n _defineProperty(_this, \"handleAnimationEnd\", function () {\n var onAnimationEnd = _this.props.onAnimationEnd;\n _this.setState({\n isAnimationFinished: true\n });\n if (isFunction(onAnimationEnd)) {\n onAnimationEnd();\n }\n });\n _defineProperty(_this, \"handleAnimationStart\", function () {\n var onAnimationStart = _this.props.onAnimationStart;\n _this.setState({\n isAnimationFinished: false\n });\n if (isFunction(onAnimationStart)) {\n onAnimationStart();\n }\n });\n return _this;\n }\n _inherits(Area, _PureComponent);\n return _createClass(Area, [{\n key: \"renderDots\",\n value: function renderDots(needClip, clipDot, clipPathId) {\n var isAnimationActive = this.props.isAnimationActive;\n var isAnimationFinished = this.state.isAnimationFinished;\n if (isAnimationActive && !isAnimationFinished) {\n return null;\n }\n var _this$props = this.props,\n dot = _this$props.dot,\n points = _this$props.points,\n dataKey = _this$props.dataKey;\n var areaProps = filterProps(this.props, false);\n var customDotProps = filterProps(dot, true);\n var dots = points.map(function (entry, i) {\n var dotProps = _objectSpread(_objectSpread(_objectSpread({\n key: \"dot-\".concat(i),\n r: 3\n }, areaProps), customDotProps), {}, {\n index: i,\n cx: entry.x,\n cy: entry.y,\n dataKey: dataKey,\n value: entry.value,\n payload: entry.payload,\n points: points\n });\n return Area.renderDotItem(dot, dotProps);\n });\n var dotsProps = {\n clipPath: needClip ? \"url(#clipPath-\".concat(clipDot ? '' : 'dots-').concat(clipPathId, \")\") : null\n };\n return /*#__PURE__*/React.createElement(Layer, _extends({\n className: \"recharts-area-dots\"\n }, dotsProps), dots);\n }\n }, {\n key: \"renderHorizontalRect\",\n value: function renderHorizontalRect(alpha) {\n var _this$props2 = this.props,\n baseLine = _this$props2.baseLine,\n points = _this$props2.points,\n strokeWidth = _this$props2.strokeWidth;\n var startX = points[0].x;\n var endX = points[points.length - 1].x;\n var width = alpha * Math.abs(startX - endX);\n var maxY = max(points.map(function (entry) {\n return entry.y || 0;\n }));\n if (isNumber(baseLine) && typeof baseLine === 'number') {\n maxY = Math.max(baseLine, maxY);\n } else if (baseLine && Array.isArray(baseLine) && baseLine.length) {\n maxY = Math.max(max(baseLine.map(function (entry) {\n return entry.y || 0;\n })), maxY);\n }\n if (isNumber(maxY)) {\n return /*#__PURE__*/React.createElement(\"rect\", {\n x: startX < endX ? startX : startX - width,\n y: 0,\n width: width,\n height: Math.floor(maxY + (strokeWidth ? parseInt(\"\".concat(strokeWidth), 10) : 1))\n });\n }\n return null;\n }\n }, {\n key: \"renderVerticalRect\",\n value: function renderVerticalRect(alpha) {\n var _this$props3 = this.props,\n baseLine = _this$props3.baseLine,\n points = _this$props3.points,\n strokeWidth = _this$props3.strokeWidth;\n var startY = points[0].y;\n var endY = points[points.length - 1].y;\n var height = alpha * Math.abs(startY - endY);\n var maxX = max(points.map(function (entry) {\n return entry.x || 0;\n }));\n if (isNumber(baseLine) && typeof baseLine === 'number') {\n maxX = Math.max(baseLine, maxX);\n } else if (baseLine && Array.isArray(baseLine) && baseLine.length) {\n maxX = Math.max(max(baseLine.map(function (entry) {\n return entry.x || 0;\n })), maxX);\n }\n if (isNumber(maxX)) {\n return /*#__PURE__*/React.createElement(\"rect\", {\n x: 0,\n y: startY < endY ? startY : startY - height,\n width: maxX + (strokeWidth ? parseInt(\"\".concat(strokeWidth), 10) : 1),\n height: Math.floor(height)\n });\n }\n return null;\n }\n }, {\n key: \"renderClipRect\",\n value: function renderClipRect(alpha) {\n var layout = this.props.layout;\n if (layout === 'vertical') {\n return this.renderVerticalRect(alpha);\n }\n return this.renderHorizontalRect(alpha);\n }\n }, {\n key: \"renderAreaStatically\",\n value: function renderAreaStatically(points, baseLine, needClip, clipPathId) {\n var _this$props4 = this.props,\n layout = _this$props4.layout,\n type = _this$props4.type,\n stroke = _this$props4.stroke,\n connectNulls = _this$props4.connectNulls,\n isRange = _this$props4.isRange,\n ref = _this$props4.ref,\n others = _objectWithoutProperties(_this$props4, _excluded);\n return /*#__PURE__*/React.createElement(Layer, {\n clipPath: needClip ? \"url(#clipPath-\".concat(clipPathId, \")\") : null\n }, /*#__PURE__*/React.createElement(Curve, _extends({}, filterProps(others, true), {\n points: points,\n connectNulls: connectNulls,\n type: type,\n baseLine: baseLine,\n layout: layout,\n stroke: \"none\",\n className: \"recharts-area-area\"\n })), stroke !== 'none' && /*#__PURE__*/React.createElement(Curve, _extends({}, filterProps(this.props, false), {\n className: \"recharts-area-curve\",\n layout: layout,\n type: type,\n connectNulls: connectNulls,\n fill: \"none\",\n points: points\n })), stroke !== 'none' && isRange && /*#__PURE__*/React.createElement(Curve, _extends({}, filterProps(this.props, false), {\n className: \"recharts-area-curve\",\n layout: layout,\n type: type,\n connectNulls: connectNulls,\n fill: \"none\",\n points: baseLine\n })));\n }\n }, {\n key: \"renderAreaWithAnimation\",\n value: function renderAreaWithAnimation(needClip, clipPathId) {\n var _this2 = this;\n var _this$props5 = this.props,\n points = _this$props5.points,\n baseLine = _this$props5.baseLine,\n isAnimationActive = _this$props5.isAnimationActive,\n animationBegin = _this$props5.animationBegin,\n animationDuration = _this$props5.animationDuration,\n animationEasing = _this$props5.animationEasing,\n animationId = _this$props5.animationId;\n var _this$state = this.state,\n prevPoints = _this$state.prevPoints,\n prevBaseLine = _this$state.prevBaseLine;\n // const clipPathId = isNil(id) ? this.id : id;\n\n return /*#__PURE__*/React.createElement(Animate, {\n begin: animationBegin,\n duration: animationDuration,\n isActive: isAnimationActive,\n easing: animationEasing,\n from: {\n t: 0\n },\n to: {\n t: 1\n },\n key: \"area-\".concat(animationId),\n onAnimationEnd: this.handleAnimationEnd,\n onAnimationStart: this.handleAnimationStart\n }, function (_ref) {\n var t = _ref.t;\n if (prevPoints) {\n var prevPointsDiffFactor = prevPoints.length / points.length;\n // update animtaion\n var stepPoints = points.map(function (entry, index) {\n var prevPointIndex = Math.floor(index * prevPointsDiffFactor);\n if (prevPoints[prevPointIndex]) {\n var prev = prevPoints[prevPointIndex];\n var interpolatorX = interpolateNumber(prev.x, entry.x);\n var interpolatorY = interpolateNumber(prev.y, entry.y);\n return _objectSpread(_objectSpread({}, entry), {}, {\n x: interpolatorX(t),\n y: interpolatorY(t)\n });\n }\n return entry;\n });\n var stepBaseLine;\n if (isNumber(baseLine) && typeof baseLine === 'number') {\n var interpolator = interpolateNumber(prevBaseLine, baseLine);\n stepBaseLine = interpolator(t);\n } else if (isNil(baseLine) || isNan(baseLine)) {\n var _interpolator = interpolateNumber(prevBaseLine, 0);\n stepBaseLine = _interpolator(t);\n } else {\n stepBaseLine = baseLine.map(function (entry, index) {\n var prevPointIndex = Math.floor(index * prevPointsDiffFactor);\n if (prevBaseLine[prevPointIndex]) {\n var prev = prevBaseLine[prevPointIndex];\n var interpolatorX = interpolateNumber(prev.x, entry.x);\n var interpolatorY = interpolateNumber(prev.y, entry.y);\n return _objectSpread(_objectSpread({}, entry), {}, {\n x: interpolatorX(t),\n y: interpolatorY(t)\n });\n }\n return entry;\n });\n }\n return _this2.renderAreaStatically(stepPoints, stepBaseLine, needClip, clipPathId);\n }\n return /*#__PURE__*/React.createElement(Layer, null, /*#__PURE__*/React.createElement(\"defs\", null, /*#__PURE__*/React.createElement(\"clipPath\", {\n id: \"animationClipPath-\".concat(clipPathId)\n }, _this2.renderClipRect(t))), /*#__PURE__*/React.createElement(Layer, {\n clipPath: \"url(#animationClipPath-\".concat(clipPathId, \")\")\n }, _this2.renderAreaStatically(points, baseLine, needClip, clipPathId)));\n });\n }\n }, {\n key: \"renderArea\",\n value: function renderArea(needClip, clipPathId) {\n var _this$props6 = this.props,\n points = _this$props6.points,\n baseLine = _this$props6.baseLine,\n isAnimationActive = _this$props6.isAnimationActive;\n var _this$state2 = this.state,\n prevPoints = _this$state2.prevPoints,\n prevBaseLine = _this$state2.prevBaseLine,\n totalLength = _this$state2.totalLength;\n if (isAnimationActive && points && points.length && (!prevPoints && totalLength > 0 || !isEqual(prevPoints, points) || !isEqual(prevBaseLine, baseLine))) {\n return this.renderAreaWithAnimation(needClip, clipPathId);\n }\n return this.renderAreaStatically(points, baseLine, needClip, clipPathId);\n }\n }, {\n key: \"render\",\n value: function render() {\n var _filterProps;\n var _this$props7 = this.props,\n hide = _this$props7.hide,\n dot = _this$props7.dot,\n points = _this$props7.points,\n className = _this$props7.className,\n top = _this$props7.top,\n left = _this$props7.left,\n xAxis = _this$props7.xAxis,\n yAxis = _this$props7.yAxis,\n width = _this$props7.width,\n height = _this$props7.height,\n isAnimationActive = _this$props7.isAnimationActive,\n id = _this$props7.id;\n if (hide || !points || !points.length) {\n return null;\n }\n var isAnimationFinished = this.state.isAnimationFinished;\n var hasSinglePoint = points.length === 1;\n var layerClass = clsx('recharts-area', className);\n var needClipX = xAxis && xAxis.allowDataOverflow;\n var needClipY = yAxis && yAxis.allowDataOverflow;\n var needClip = needClipX || needClipY;\n var clipPathId = isNil(id) ? this.id : id;\n var _ref2 = (_filterProps = filterProps(dot, false)) !== null && _filterProps !== void 0 ? _filterProps : {\n r: 3,\n strokeWidth: 2\n },\n _ref2$r = _ref2.r,\n r = _ref2$r === void 0 ? 3 : _ref2$r,\n _ref2$strokeWidth = _ref2.strokeWidth,\n strokeWidth = _ref2$strokeWidth === void 0 ? 2 : _ref2$strokeWidth;\n var _ref3 = hasClipDot(dot) ? dot : {},\n _ref3$clipDot = _ref3.clipDot,\n clipDot = _ref3$clipDot === void 0 ? true : _ref3$clipDot;\n var dotSize = r * 2 + strokeWidth;\n return /*#__PURE__*/React.createElement(Layer, {\n className: layerClass\n }, needClipX || needClipY ? /*#__PURE__*/React.createElement(\"defs\", null, /*#__PURE__*/React.createElement(\"clipPath\", {\n id: \"clipPath-\".concat(clipPathId)\n }, /*#__PURE__*/React.createElement(\"rect\", {\n x: needClipX ? left : left - width / 2,\n y: needClipY ? top : top - height / 2,\n width: needClipX ? width : width * 2,\n height: needClipY ? height : height * 2\n })), !clipDot && /*#__PURE__*/React.createElement(\"clipPath\", {\n id: \"clipPath-dots-\".concat(clipPathId)\n }, /*#__PURE__*/React.createElement(\"rect\", {\n x: left - dotSize / 2,\n y: top - dotSize / 2,\n width: width + dotSize,\n height: height + dotSize\n }))) : null, !hasSinglePoint ? this.renderArea(needClip, clipPathId) : null, (dot || hasSinglePoint) && this.renderDots(needClip, clipDot, clipPathId), (!isAnimationActive || isAnimationFinished) && LabelList.renderCallByParent(this.props, points));\n }\n }], [{\n key: \"getDerivedStateFromProps\",\n value: function getDerivedStateFromProps(nextProps, prevState) {\n if (nextProps.animationId !== prevState.prevAnimationId) {\n return {\n prevAnimationId: nextProps.animationId,\n curPoints: nextProps.points,\n curBaseLine: nextProps.baseLine,\n prevPoints: prevState.curPoints,\n prevBaseLine: prevState.curBaseLine\n };\n }\n if (nextProps.points !== prevState.curPoints || nextProps.baseLine !== prevState.curBaseLine) {\n return {\n curPoints: nextProps.points,\n curBaseLine: nextProps.baseLine\n };\n }\n return null;\n }\n }]);\n}(PureComponent);\n_Area = Area;\n_defineProperty(Area, \"displayName\", 'Area');\n_defineProperty(Area, \"defaultProps\", {\n stroke: '#3182bd',\n fill: '#3182bd',\n fillOpacity: 0.6,\n xAxisId: 0,\n yAxisId: 0,\n legendType: 'line',\n connectNulls: false,\n // points of area\n points: [],\n dot: false,\n activeDot: true,\n hide: false,\n isAnimationActive: !Global.isSsr,\n animationBegin: 0,\n animationDuration: 1500,\n animationEasing: 'ease'\n});\n_defineProperty(Area, \"getBaseValue\", function (props, item, xAxis, yAxis) {\n var layout = props.layout,\n chartBaseValue = props.baseValue;\n var itemBaseValue = item.props.baseValue;\n\n // The baseValue can be defined both on the AreaChart as well as on the Area.\n // The value for the item takes precedence.\n var baseValue = itemBaseValue !== null && itemBaseValue !== void 0 ? itemBaseValue : chartBaseValue;\n if (isNumber(baseValue) && typeof baseValue === 'number') {\n return baseValue;\n }\n var numericAxis = layout === 'horizontal' ? yAxis : xAxis;\n var domain = numericAxis.scale.domain();\n if (numericAxis.type === 'number') {\n var domainMax = Math.max(domain[0], domain[1]);\n var domainMin = Math.min(domain[0], domain[1]);\n if (baseValue === 'dataMin') {\n return domainMin;\n }\n if (baseValue === 'dataMax') {\n return domainMax;\n }\n return domainMax < 0 ? domainMax : Math.max(Math.min(domain[0], domain[1]), 0);\n }\n if (baseValue === 'dataMin') {\n return domain[0];\n }\n if (baseValue === 'dataMax') {\n return domain[1];\n }\n return domain[0];\n});\n_defineProperty(Area, \"getComposedData\", function (_ref4) {\n var props = _ref4.props,\n item = _ref4.item,\n xAxis = _ref4.xAxis,\n yAxis = _ref4.yAxis,\n xAxisTicks = _ref4.xAxisTicks,\n yAxisTicks = _ref4.yAxisTicks,\n bandSize = _ref4.bandSize,\n dataKey = _ref4.dataKey,\n stackedData = _ref4.stackedData,\n dataStartIndex = _ref4.dataStartIndex,\n displayedData = _ref4.displayedData,\n offset = _ref4.offset;\n var layout = props.layout;\n var hasStack = stackedData && stackedData.length;\n var baseValue = _Area.getBaseValue(props, item, xAxis, yAxis);\n var isHorizontalLayout = layout === 'horizontal';\n var isRange = false;\n var points = displayedData.map(function (entry, index) {\n var value;\n if (hasStack) {\n value = stackedData[dataStartIndex + index];\n } else {\n value = getValueByDataKey(entry, dataKey);\n if (!Array.isArray(value)) {\n value = [baseValue, value];\n } else {\n isRange = true;\n }\n }\n var isBreakPoint = value[1] == null || hasStack && getValueByDataKey(entry, dataKey) == null;\n if (isHorizontalLayout) {\n return {\n x: getCateCoordinateOfLine({\n axis: xAxis,\n ticks: xAxisTicks,\n bandSize: bandSize,\n entry: entry,\n index: index\n }),\n y: isBreakPoint ? null : yAxis.scale(value[1]),\n value: value,\n payload: entry\n };\n }\n return {\n x: isBreakPoint ? null : xAxis.scale(value[1]),\n y: getCateCoordinateOfLine({\n axis: yAxis,\n ticks: yAxisTicks,\n bandSize: bandSize,\n entry: entry,\n index: index\n }),\n value: value,\n payload: entry\n };\n });\n var baseLine;\n if (hasStack || isRange) {\n baseLine = points.map(function (entry) {\n var x = Array.isArray(entry.value) ? entry.value[0] : null;\n if (isHorizontalLayout) {\n return {\n x: entry.x,\n y: x != null && entry.y != null ? yAxis.scale(x) : null\n };\n }\n return {\n x: x != null ? xAxis.scale(x) : null,\n y: entry.y\n };\n });\n } else {\n baseLine = isHorizontalLayout ? yAxis.scale(baseValue) : xAxis.scale(baseValue);\n }\n return _objectSpread({\n points: points,\n baseLine: baseLine,\n layout: layout,\n isRange: isRange\n }, offset);\n});\n_defineProperty(Area, \"renderDotItem\", function (option, props) {\n var dotItem;\n if ( /*#__PURE__*/React.isValidElement(option)) {\n dotItem = /*#__PURE__*/React.cloneElement(option, props);\n } else if (isFunction(option)) {\n dotItem = option(props);\n } else {\n var className = clsx('recharts-area-dot', typeof option !== 'boolean' ? option.className : '');\n var key = props.key,\n rest = _objectWithoutProperties(props, _excluded2);\n dotItem = /*#__PURE__*/React.createElement(Dot, _extends({}, rest, {\n key: key,\n className: className\n }));\n }\n return dotItem;\n});", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n/**\n * @fileOverview X Axis\n */\nimport * as React from 'react';\nimport clsx from 'clsx';\nimport { useChartHeight, useChartWidth, useXAxisOrThrow } from '../context/chartLayoutContext';\nimport { CartesianAxis } from './CartesianAxis';\nimport { getTicksOfAxis } from '../util/ChartUtils';\n\n/** Define of XAxis props */\n\nfunction XAxisImpl(_ref) {\n var xAxisId = _ref.xAxisId;\n var width = useChartWidth();\n var height = useChartHeight();\n var axisOptions = useXAxisOrThrow(xAxisId);\n if (axisOptions == null) {\n return null;\n }\n return (\n /*#__PURE__*/\n // @ts-expect-error the axisOptions type is not exactly what CartesianAxis is expecting.\n React.createElement(CartesianAxis, _extends({}, axisOptions, {\n className: clsx(\"recharts-\".concat(axisOptions.axisType, \" \").concat(axisOptions.axisType), axisOptions.className),\n viewBox: {\n x: 0,\n y: 0,\n width: width,\n height: height\n },\n ticksGenerator: function ticksGenerator(axis) {\n return getTicksOfAxis(axis, true);\n }\n }))\n );\n}\n\n// eslint-disable-next-line react/prefer-stateless-function -- requires static defaultProps\nexport var XAxis = /*#__PURE__*/function (_React$Component) {\n function XAxis() {\n _classCallCheck(this, XAxis);\n return _callSuper(this, XAxis, arguments);\n }\n _inherits(XAxis, _React$Component);\n return _createClass(XAxis, [{\n key: \"render\",\n value: function render() {\n return /*#__PURE__*/React.createElement(XAxisImpl, this.props);\n }\n }]);\n}(React.Component);\n_defineProperty(XAxis, \"displayName\", 'XAxis');\n_defineProperty(XAxis, \"defaultProps\", {\n allowDecimals: true,\n hide: false,\n orientation: 'bottom',\n width: 0,\n height: 30,\n mirror: false,\n xAxisId: 0,\n tickCount: 5,\n type: 'category',\n padding: {\n left: 0,\n right: 0\n },\n allowDataOverflow: false,\n scale: 'auto',\n reversed: false,\n allowDuplicatedCategory: true\n});", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n/**\n * @fileOverview Y Axis\n */\nimport * as React from 'react';\nimport clsx from 'clsx';\nimport { useChartHeight, useChartWidth, useYAxisOrThrow } from '../context/chartLayoutContext';\nimport { CartesianAxis } from './CartesianAxis';\nimport { getTicksOfAxis } from '../util/ChartUtils';\nvar YAxisImpl = function YAxisImpl(_ref) {\n var yAxisId = _ref.yAxisId;\n var width = useChartWidth();\n var height = useChartHeight();\n var axisOptions = useYAxisOrThrow(yAxisId);\n if (axisOptions == null) {\n return null;\n }\n return (\n /*#__PURE__*/\n // @ts-expect-error the axisOptions type is not exactly what CartesianAxis is expecting.\n React.createElement(CartesianAxis, _extends({}, axisOptions, {\n className: clsx(\"recharts-\".concat(axisOptions.axisType, \" \").concat(axisOptions.axisType), axisOptions.className),\n viewBox: {\n x: 0,\n y: 0,\n width: width,\n height: height\n },\n ticksGenerator: function ticksGenerator(axis) {\n return getTicksOfAxis(axis, true);\n }\n }))\n );\n};\n\n// eslint-disable-next-line react/prefer-stateless-function -- requires static defaultProps\nexport var YAxis = /*#__PURE__*/function (_React$Component) {\n function YAxis() {\n _classCallCheck(this, YAxis);\n return _callSuper(this, YAxis, arguments);\n }\n _inherits(YAxis, _React$Component);\n return _createClass(YAxis, [{\n key: \"render\",\n value: function render() {\n return /*#__PURE__*/React.createElement(YAxisImpl, this.props);\n }\n }]);\n}(React.Component);\n_defineProperty(YAxis, \"displayName\", 'YAxis');\n_defineProperty(YAxis, \"defaultProps\", {\n allowDuplicatedCategory: true,\n allowDecimals: true,\n hide: false,\n orientation: 'left',\n width: 60,\n height: 0,\n mirror: false,\n yAxisId: 0,\n tickCount: 5,\n type: 'number',\n padding: {\n top: 0,\n bottom: 0\n },\n allowDataOverflow: false,\n scale: 'auto',\n reversed: false\n});", "var _excluded = [\"item\"],\n _excluded2 = [\"children\", \"className\", \"width\", \"height\", \"style\", \"compact\", \"title\", \"desc\"];\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nimport React, { Component, cloneElement, isValidElement, forwardRef } from 'react';\nimport isNil from 'lodash/isNil';\nimport isFunction from 'lodash/isFunction';\nimport range from 'lodash/range';\nimport get from 'lodash/get';\nimport sortBy from 'lodash/sortBy';\nimport throttle from 'lodash/throttle';\nimport clsx from 'clsx';\n// eslint-disable-next-line no-restricted-imports\n\nimport invariant from 'tiny-invariant';\nimport { Surface } from '../container/Surface';\nimport { Layer } from '../container/Layer';\nimport { Tooltip } from '../component/Tooltip';\nimport { Legend } from '../component/Legend';\nimport { Dot } from '../shape/Dot';\nimport { isInRectangle } from '../shape/Rectangle';\nimport { filterProps, findAllByType, findChildByType, getDisplayName, getReactEventByType, isChildrenEqual, parseChildIndex, renderByOrder, validateWidthHeight } from '../util/ReactUtils';\nimport { Brush } from '../cartesian/Brush';\nimport { getOffset } from '../util/DOMUtils';\nimport { findEntryInArray, getAnyElementOfObject, hasDuplicate, isNumber, uniqueId } from '../util/DataUtils';\nimport { appendOffsetOfLegend, calculateActiveTickIndex, combineEventHandlers, getBandSizeOfAxis, getBarPosition, getBarSizeList, getDomainOfDataByKey, getDomainOfItemsWithSameAxis, getDomainOfStackGroups, getLegendProps, getMainColorOfGraphicItem, getStackedDataOfItem, getStackGroupsByAxisId, getTicksOfAxis, getTooltipItem, isCategoricalAxis, parseDomainOfCategoryAxis, parseErrorBarsOfAxis, parseSpecifiedDomain } from '../util/ChartUtils';\nimport { detectReferenceElementsDomain } from '../util/DetectReferenceElementsDomain';\nimport { inRangeOfSector, polarToCartesian } from '../util/PolarUtils';\nimport { shallowEqual } from '../util/ShallowEqual';\nimport { eventCenter, SYNC_EVENT } from '../util/Events';\nimport { adaptEventHandlers } from '../util/types';\nimport { AccessibilityManager } from './AccessibilityManager';\nimport { isDomainSpecifiedByUser } from '../util/isDomainSpecifiedByUser';\nimport { getActiveShapeIndexForTooltip, isFunnel, isPie, isScatter } from '../util/ActiveShapeUtils';\nimport { Cursor } from '../component/Cursor';\nimport { ChartLayoutContextProvider } from '../context/chartLayoutContext';\nvar ORIENT_MAP = {\n xAxis: ['bottom', 'top'],\n yAxis: ['left', 'right']\n};\nvar FULL_WIDTH_AND_HEIGHT = {\n width: '100%',\n height: '100%'\n};\nvar originCoordinate = {\n x: 0,\n y: 0\n};\n\n/**\n * This function exists as a temporary workaround.\n *\n * Why? generateCategoricalChart does not render `{children}` directly;\n * instead it passes them through `renderByOrder` function which reads their handlers.\n *\n * So, this is a handler that does nothing.\n * Once we get rid of `renderByOrder` and switch to JSX only, we can get rid of this handler too.\n *\n * @param {JSX} element as is in JSX\n * @returns {JSX} the same element\n */\nfunction renderAsIs(element) {\n return element;\n}\nvar calculateTooltipPos = function calculateTooltipPos(rangeObj, layout) {\n if (layout === 'horizontal') {\n return rangeObj.x;\n }\n if (layout === 'vertical') {\n return rangeObj.y;\n }\n if (layout === 'centric') {\n return rangeObj.angle;\n }\n return rangeObj.radius;\n};\nvar getActiveCoordinate = function getActiveCoordinate(layout, tooltipTicks, activeIndex, rangeObj) {\n var entry = tooltipTicks.find(function (tick) {\n return tick && tick.index === activeIndex;\n });\n if (entry) {\n if (layout === 'horizontal') {\n return {\n x: entry.coordinate,\n y: rangeObj.y\n };\n }\n if (layout === 'vertical') {\n return {\n x: rangeObj.x,\n y: entry.coordinate\n };\n }\n if (layout === 'centric') {\n var _angle = entry.coordinate;\n var _radius = rangeObj.radius;\n return _objectSpread(_objectSpread(_objectSpread({}, rangeObj), polarToCartesian(rangeObj.cx, rangeObj.cy, _radius, _angle)), {}, {\n angle: _angle,\n radius: _radius\n });\n }\n var radius = entry.coordinate;\n var angle = rangeObj.angle;\n return _objectSpread(_objectSpread(_objectSpread({}, rangeObj), polarToCartesian(rangeObj.cx, rangeObj.cy, radius, angle)), {}, {\n angle: angle,\n radius: radius\n });\n }\n return originCoordinate;\n};\nvar getDisplayedData = function getDisplayedData(data, _ref) {\n var graphicalItems = _ref.graphicalItems,\n dataStartIndex = _ref.dataStartIndex,\n dataEndIndex = _ref.dataEndIndex;\n var itemsData = (graphicalItems !== null && graphicalItems !== void 0 ? graphicalItems : []).reduce(function (result, child) {\n var itemData = child.props.data;\n if (itemData && itemData.length) {\n return [].concat(_toConsumableArray(result), _toConsumableArray(itemData));\n }\n return result;\n }, []);\n if (itemsData.length > 0) {\n return itemsData;\n }\n if (data && data.length && isNumber(dataStartIndex) && isNumber(dataEndIndex)) {\n return data.slice(dataStartIndex, dataEndIndex + 1);\n }\n return [];\n};\nfunction getDefaultDomainByAxisType(axisType) {\n return axisType === 'number' ? [0, 'auto'] : undefined;\n}\n\n/**\n * Get the content to be displayed in the tooltip\n * @param {Object} state Current state\n * @param {Array} chartData The data defined in chart\n * @param {Number} activeIndex Active index of data\n * @param {String} activeLabel Active label of data\n * @return {Array} The content of tooltip\n */\nvar getTooltipContent = function getTooltipContent(state, chartData, activeIndex, activeLabel) {\n var graphicalItems = state.graphicalItems,\n tooltipAxis = state.tooltipAxis;\n var displayedData = getDisplayedData(chartData, state);\n if (activeIndex < 0 || !graphicalItems || !graphicalItems.length || activeIndex >= displayedData.length) {\n return null;\n }\n // get data by activeIndex when the axis don't allow duplicated category\n return graphicalItems.reduce(function (result, child) {\n var _child$props$data;\n /**\n * Fixes: https://github.com/recharts/recharts/issues/3669\n * Defaulting to chartData below to fix an edge case where the tooltip does not include data from all charts\n * when a separate dataset is passed to chart prop data and specified on Line/Area/etc prop data\n */\n var data = (_child$props$data = child.props.data) !== null && _child$props$data !== void 0 ? _child$props$data : chartData;\n if (data && state.dataStartIndex + state.dataEndIndex !== 0 &&\n // https://github.com/recharts/recharts/issues/4717\n // The data is sliced only when the active index is within the start/end index range.\n state.dataEndIndex - state.dataStartIndex >= activeIndex) {\n data = data.slice(state.dataStartIndex, state.dataEndIndex + 1);\n }\n var payload;\n if (tooltipAxis.dataKey && !tooltipAxis.allowDuplicatedCategory) {\n // graphic child has data props\n var entries = data === undefined ? displayedData : data;\n payload = findEntryInArray(entries, tooltipAxis.dataKey, activeLabel);\n } else {\n payload = data && data[activeIndex] || displayedData[activeIndex];\n }\n if (!payload) {\n return result;\n }\n return [].concat(_toConsumableArray(result), [getTooltipItem(child, payload)]);\n }, []);\n};\n\n/**\n * Returns tooltip data based on a mouse position (as a parameter or in state)\n * @param {Object} state current state\n * @param {Array} chartData the data defined in chart\n * @param {String} layout The layout type of chart\n * @param {Object} rangeObj { x, y } coordinates\n * @return {Object} Tooltip data data\n */\nvar getTooltipData = function getTooltipData(state, chartData, layout, rangeObj) {\n var rangeData = rangeObj || {\n x: state.chartX,\n y: state.chartY\n };\n var pos = calculateTooltipPos(rangeData, layout);\n var ticks = state.orderedTooltipTicks,\n axis = state.tooltipAxis,\n tooltipTicks = state.tooltipTicks;\n var activeIndex = calculateActiveTickIndex(pos, ticks, tooltipTicks, axis);\n if (activeIndex >= 0 && tooltipTicks) {\n var activeLabel = tooltipTicks[activeIndex] && tooltipTicks[activeIndex].value;\n var activePayload = getTooltipContent(state, chartData, activeIndex, activeLabel);\n var activeCoordinate = getActiveCoordinate(layout, ticks, activeIndex, rangeData);\n return {\n activeTooltipIndex: activeIndex,\n activeLabel: activeLabel,\n activePayload: activePayload,\n activeCoordinate: activeCoordinate\n };\n }\n return null;\n};\n\n/**\n * Get the configuration of axis by the options of axis instance\n * @param {Object} props Latest props\n * @param {Array} axes The instance of axes\n * @param {Array} graphicalItems The instances of item\n * @param {String} axisType The type of axis, xAxis - x-axis, yAxis - y-axis\n * @param {String} axisIdKey The unique id of an axis\n * @param {Object} stackGroups The items grouped by axisId and stackId\n * @param {Number} dataStartIndex The start index of the data series when a brush is applied\n * @param {Number} dataEndIndex The end index of the data series when a brush is applied\n * @return {Object} Configuration\n */\nexport var getAxisMapByAxes = function getAxisMapByAxes(props, _ref2) {\n var axes = _ref2.axes,\n graphicalItems = _ref2.graphicalItems,\n axisType = _ref2.axisType,\n axisIdKey = _ref2.axisIdKey,\n stackGroups = _ref2.stackGroups,\n dataStartIndex = _ref2.dataStartIndex,\n dataEndIndex = _ref2.dataEndIndex;\n var layout = props.layout,\n children = props.children,\n stackOffset = props.stackOffset;\n var isCategorical = isCategoricalAxis(layout, axisType);\n\n // Eliminate duplicated axes\n return axes.reduce(function (result, child) {\n var _childProps$domain2;\n var childProps = child.type.defaultProps !== undefined ? _objectSpread(_objectSpread({}, child.type.defaultProps), child.props) : child.props;\n var type = childProps.type,\n dataKey = childProps.dataKey,\n allowDataOverflow = childProps.allowDataOverflow,\n allowDuplicatedCategory = childProps.allowDuplicatedCategory,\n scale = childProps.scale,\n ticks = childProps.ticks,\n includeHidden = childProps.includeHidden;\n var axisId = childProps[axisIdKey];\n if (result[axisId]) {\n return result;\n }\n var displayedData = getDisplayedData(props.data, {\n graphicalItems: graphicalItems.filter(function (item) {\n var _defaultProps;\n var itemAxisId = axisIdKey in item.props ? item.props[axisIdKey] : (_defaultProps = item.type.defaultProps) === null || _defaultProps === void 0 ? void 0 : _defaultProps[axisIdKey];\n return itemAxisId === axisId;\n }),\n dataStartIndex: dataStartIndex,\n dataEndIndex: dataEndIndex\n });\n var len = displayedData.length;\n var domain, duplicateDomain, categoricalDomain;\n\n /*\n * This is a hack to short-circuit the domain creation here to enhance performance.\n * Usually, the data is used to determine the domain, but when the user specifies\n * a domain upfront (via props), there is no need to calculate the domain start and end,\n * which is very expensive for a larger amount of data.\n * The only thing that would prohibit short-circuiting is when the user doesn't allow data overflow,\n * because the axis is supposed to ignore the specified domain that way.\n */\n if (isDomainSpecifiedByUser(childProps.domain, allowDataOverflow, type)) {\n domain = parseSpecifiedDomain(childProps.domain, null, allowDataOverflow);\n /* The chart can be categorical and have the domain specified in numbers\n * we still need to calculate the categorical domain\n * TODO: refactor this more\n */\n if (isCategorical && (type === 'number' || scale !== 'auto')) {\n categoricalDomain = getDomainOfDataByKey(displayedData, dataKey, 'category');\n }\n }\n\n // if the domain is defaulted we need this for `originalDomain` as well\n var defaultDomain = getDefaultDomainByAxisType(type);\n\n // we didn't create the domain from user's props above, so we need to calculate it\n if (!domain || domain.length === 0) {\n var _childProps$domain;\n var childDomain = (_childProps$domain = childProps.domain) !== null && _childProps$domain !== void 0 ? _childProps$domain : defaultDomain;\n if (dataKey) {\n // has dataKey in \n domain = getDomainOfDataByKey(displayedData, dataKey, type);\n if (type === 'category' && isCategorical) {\n // the field type is category data and this axis is categorical axis\n var duplicate = hasDuplicate(domain);\n if (allowDuplicatedCategory && duplicate) {\n duplicateDomain = domain;\n // When category axis has duplicated text, serial numbers are used to generate scale\n domain = range(0, len);\n } else if (!allowDuplicatedCategory) {\n // remove duplicated category\n domain = parseDomainOfCategoryAxis(childDomain, domain, child).reduce(function (finalDomain, entry) {\n return finalDomain.indexOf(entry) >= 0 ? finalDomain : [].concat(_toConsumableArray(finalDomain), [entry]);\n }, []);\n }\n } else if (type === 'category') {\n // the field type is category data and this axis is numerical axis\n if (!allowDuplicatedCategory) {\n domain = parseDomainOfCategoryAxis(childDomain, domain, child).reduce(function (finalDomain, entry) {\n return finalDomain.indexOf(entry) >= 0 || entry === '' || isNil(entry) ? finalDomain : [].concat(_toConsumableArray(finalDomain), [entry]);\n }, []);\n } else {\n // eliminate undefined or null or empty string\n domain = domain.filter(function (entry) {\n return entry !== '' && !isNil(entry);\n });\n }\n } else if (type === 'number') {\n // the field type is numerical\n var errorBarsDomain = parseErrorBarsOfAxis(displayedData, graphicalItems.filter(function (item) {\n var _defaultProps2, _defaultProps3;\n var itemAxisId = axisIdKey in item.props ? item.props[axisIdKey] : (_defaultProps2 = item.type.defaultProps) === null || _defaultProps2 === void 0 ? void 0 : _defaultProps2[axisIdKey];\n var itemHide = 'hide' in item.props ? item.props.hide : (_defaultProps3 = item.type.defaultProps) === null || _defaultProps3 === void 0 ? void 0 : _defaultProps3.hide;\n return itemAxisId === axisId && (includeHidden || !itemHide);\n }), dataKey, axisType, layout);\n if (errorBarsDomain) {\n domain = errorBarsDomain;\n }\n }\n if (isCategorical && (type === 'number' || scale !== 'auto')) {\n categoricalDomain = getDomainOfDataByKey(displayedData, dataKey, 'category');\n }\n } else if (isCategorical) {\n // the axis is a categorical axis\n domain = range(0, len);\n } else if (stackGroups && stackGroups[axisId] && stackGroups[axisId].hasStack && type === 'number') {\n // when stackOffset is 'expand', the domain may be calculated as [0, 1.000000000002]\n domain = stackOffset === 'expand' ? [0, 1] : getDomainOfStackGroups(stackGroups[axisId].stackGroups, dataStartIndex, dataEndIndex);\n } else {\n domain = getDomainOfItemsWithSameAxis(displayedData, graphicalItems.filter(function (item) {\n var itemAxisId = axisIdKey in item.props ? item.props[axisIdKey] : item.type.defaultProps[axisIdKey];\n var itemHide = 'hide' in item.props ? item.props.hide : item.type.defaultProps.hide;\n return itemAxisId === axisId && (includeHidden || !itemHide);\n }), type, layout, true);\n }\n if (type === 'number') {\n // To detect wether there is any reference lines whose props alwaysShow is true\n domain = detectReferenceElementsDomain(children, domain, axisId, axisType, ticks);\n if (childDomain) {\n domain = parseSpecifiedDomain(childDomain, domain, allowDataOverflow);\n }\n } else if (type === 'category' && childDomain) {\n var axisDomain = childDomain;\n var isDomainValid = domain.every(function (entry) {\n return axisDomain.indexOf(entry) >= 0;\n });\n if (isDomainValid) {\n domain = axisDomain;\n }\n }\n }\n return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, axisId, _objectSpread(_objectSpread({}, childProps), {}, {\n axisType: axisType,\n domain: domain,\n categoricalDomain: categoricalDomain,\n duplicateDomain: duplicateDomain,\n originalDomain: (_childProps$domain2 = childProps.domain) !== null && _childProps$domain2 !== void 0 ? _childProps$domain2 : defaultDomain,\n isCategorical: isCategorical,\n layout: layout\n })));\n }, {});\n};\n\n/**\n * Get the configuration of axis by the options of item,\n * this kind of axis does not display in chart\n * @param {Object} props Latest props\n * @param {Array} graphicalItems The instances of item\n * @param {ReactElement} Axis Axis Component\n * @param {String} axisType The type of axis, xAxis - x-axis, yAxis - y-axis\n * @param {String} axisIdKey The unique id of an axis\n * @param {Object} stackGroups The items grouped by axisId and stackId\n * @param {Number} dataStartIndex The start index of the data series when a brush is applied\n * @param {Number} dataEndIndex The end index of the data series when a brush is applied\n * @return {Object} Configuration\n */\nvar getAxisMapByItems = function getAxisMapByItems(props, _ref3) {\n var graphicalItems = _ref3.graphicalItems,\n Axis = _ref3.Axis,\n axisType = _ref3.axisType,\n axisIdKey = _ref3.axisIdKey,\n stackGroups = _ref3.stackGroups,\n dataStartIndex = _ref3.dataStartIndex,\n dataEndIndex = _ref3.dataEndIndex;\n var layout = props.layout,\n children = props.children;\n var displayedData = getDisplayedData(props.data, {\n graphicalItems: graphicalItems,\n dataStartIndex: dataStartIndex,\n dataEndIndex: dataEndIndex\n });\n var len = displayedData.length;\n var isCategorical = isCategoricalAxis(layout, axisType);\n var index = -1;\n\n // The default type of x-axis is category axis,\n // The default contents of x-axis is the serial numbers of data\n // The default type of y-axis is number axis\n // The default contents of y-axis is the domain of data\n return graphicalItems.reduce(function (result, child) {\n var childProps = child.type.defaultProps !== undefined ? _objectSpread(_objectSpread({}, child.type.defaultProps), child.props) : child.props;\n var axisId = childProps[axisIdKey];\n var originalDomain = getDefaultDomainByAxisType('number');\n if (!result[axisId]) {\n index++;\n var domain;\n if (isCategorical) {\n domain = range(0, len);\n } else if (stackGroups && stackGroups[axisId] && stackGroups[axisId].hasStack) {\n domain = getDomainOfStackGroups(stackGroups[axisId].stackGroups, dataStartIndex, dataEndIndex);\n domain = detectReferenceElementsDomain(children, domain, axisId, axisType);\n } else {\n domain = parseSpecifiedDomain(originalDomain, getDomainOfItemsWithSameAxis(displayedData, graphicalItems.filter(function (item) {\n var _defaultProps4, _defaultProps5;\n var itemAxisId = axisIdKey in item.props ? item.props[axisIdKey] : (_defaultProps4 = item.type.defaultProps) === null || _defaultProps4 === void 0 ? void 0 : _defaultProps4[axisIdKey];\n var itemHide = 'hide' in item.props ? item.props.hide : (_defaultProps5 = item.type.defaultProps) === null || _defaultProps5 === void 0 ? void 0 : _defaultProps5.hide;\n return itemAxisId === axisId && !itemHide;\n }), 'number', layout), Axis.defaultProps.allowDataOverflow);\n domain = detectReferenceElementsDomain(children, domain, axisId, axisType);\n }\n return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, axisId, _objectSpread(_objectSpread({\n axisType: axisType\n }, Axis.defaultProps), {}, {\n hide: true,\n orientation: get(ORIENT_MAP, \"\".concat(axisType, \".\").concat(index % 2), null),\n domain: domain,\n originalDomain: originalDomain,\n isCategorical: isCategorical,\n layout: layout\n // specify scale when no Axis\n // scale: isCategorical ? 'band' : 'linear',\n })));\n }\n return result;\n }, {});\n};\n\n/**\n * Get the configuration of all x-axis or y-axis\n * @param {Object} props Latest props\n * @param {String} axisType The type of axis\n * @param {React.ComponentType} [AxisComp] Axis Component\n * @param {Array} graphicalItems The instances of item\n * @param {Object} stackGroups The items grouped by axisId and stackId\n * @param {Number} dataStartIndex The start index of the data series when a brush is applied\n * @param {Number} dataEndIndex The end index of the data series when a brush is applied\n * @return {Object} Configuration\n */\nvar getAxisMap = function getAxisMap(props, _ref4) {\n var _ref4$axisType = _ref4.axisType,\n axisType = _ref4$axisType === void 0 ? 'xAxis' : _ref4$axisType,\n AxisComp = _ref4.AxisComp,\n graphicalItems = _ref4.graphicalItems,\n stackGroups = _ref4.stackGroups,\n dataStartIndex = _ref4.dataStartIndex,\n dataEndIndex = _ref4.dataEndIndex;\n var children = props.children;\n var axisIdKey = \"\".concat(axisType, \"Id\");\n // Get all the instance of Axis\n var axes = findAllByType(children, AxisComp);\n var axisMap = {};\n if (axes && axes.length) {\n axisMap = getAxisMapByAxes(props, {\n axes: axes,\n graphicalItems: graphicalItems,\n axisType: axisType,\n axisIdKey: axisIdKey,\n stackGroups: stackGroups,\n dataStartIndex: dataStartIndex,\n dataEndIndex: dataEndIndex\n });\n } else if (graphicalItems && graphicalItems.length) {\n axisMap = getAxisMapByItems(props, {\n Axis: AxisComp,\n graphicalItems: graphicalItems,\n axisType: axisType,\n axisIdKey: axisIdKey,\n stackGroups: stackGroups,\n dataStartIndex: dataStartIndex,\n dataEndIndex: dataEndIndex\n });\n }\n return axisMap;\n};\nvar tooltipTicksGenerator = function tooltipTicksGenerator(axisMap) {\n var axis = getAnyElementOfObject(axisMap);\n var tooltipTicks = getTicksOfAxis(axis, false, true);\n return {\n tooltipTicks: tooltipTicks,\n orderedTooltipTicks: sortBy(tooltipTicks, function (o) {\n return o.coordinate;\n }),\n tooltipAxis: axis,\n tooltipAxisBandSize: getBandSizeOfAxis(axis, tooltipTicks)\n };\n};\n\n/**\n * Returns default, reset state for the categorical chart.\n * @param {Object} props Props object to use when creating the default state\n * @return {Object} Whole new state\n */\nexport var createDefaultState = function createDefaultState(props) {\n var children = props.children,\n defaultShowTooltip = props.defaultShowTooltip;\n var brushItem = findChildByType(children, Brush);\n var startIndex = 0;\n var endIndex = 0;\n if (props.data && props.data.length !== 0) {\n endIndex = props.data.length - 1;\n }\n if (brushItem && brushItem.props) {\n if (brushItem.props.startIndex >= 0) {\n startIndex = brushItem.props.startIndex;\n }\n if (brushItem.props.endIndex >= 0) {\n endIndex = brushItem.props.endIndex;\n }\n }\n return {\n chartX: 0,\n chartY: 0,\n dataStartIndex: startIndex,\n dataEndIndex: endIndex,\n activeTooltipIndex: -1,\n isTooltipActive: Boolean(defaultShowTooltip)\n };\n};\nvar hasGraphicalBarItem = function hasGraphicalBarItem(graphicalItems) {\n if (!graphicalItems || !graphicalItems.length) {\n return false;\n }\n return graphicalItems.some(function (item) {\n var name = getDisplayName(item && item.type);\n return name && name.indexOf('Bar') >= 0;\n });\n};\nvar getAxisNameByLayout = function getAxisNameByLayout(layout) {\n if (layout === 'horizontal') {\n return {\n numericAxisName: 'yAxis',\n cateAxisName: 'xAxis'\n };\n }\n if (layout === 'vertical') {\n return {\n numericAxisName: 'xAxis',\n cateAxisName: 'yAxis'\n };\n }\n if (layout === 'centric') {\n return {\n numericAxisName: 'radiusAxis',\n cateAxisName: 'angleAxis'\n };\n }\n return {\n numericAxisName: 'angleAxis',\n cateAxisName: 'radiusAxis'\n };\n};\n\n/**\n * Calculate the offset of main part in the svg element\n * @param {Object} params.props Latest props\n * @param {Array} params.graphicalItems The instances of item\n * @param {Object} params.xAxisMap The configuration of x-axis\n * @param {Object} params.yAxisMap The configuration of y-axis\n * @param {Object} prevLegendBBox The boundary box of legend\n * @return {Object} The offset of main part in the svg element\n */\nvar calculateOffset = function calculateOffset(_ref5, prevLegendBBox) {\n var props = _ref5.props,\n graphicalItems = _ref5.graphicalItems,\n _ref5$xAxisMap = _ref5.xAxisMap,\n xAxisMap = _ref5$xAxisMap === void 0 ? {} : _ref5$xAxisMap,\n _ref5$yAxisMap = _ref5.yAxisMap,\n yAxisMap = _ref5$yAxisMap === void 0 ? {} : _ref5$yAxisMap;\n var width = props.width,\n height = props.height,\n children = props.children;\n var margin = props.margin || {};\n var brushItem = findChildByType(children, Brush);\n var legendItem = findChildByType(children, Legend);\n var offsetH = Object.keys(yAxisMap).reduce(function (result, id) {\n var entry = yAxisMap[id];\n var orientation = entry.orientation;\n if (!entry.mirror && !entry.hide) {\n return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, orientation, result[orientation] + entry.width));\n }\n return result;\n }, {\n left: margin.left || 0,\n right: margin.right || 0\n });\n var offsetV = Object.keys(xAxisMap).reduce(function (result, id) {\n var entry = xAxisMap[id];\n var orientation = entry.orientation;\n if (!entry.mirror && !entry.hide) {\n return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, orientation, get(result, \"\".concat(orientation)) + entry.height));\n }\n return result;\n }, {\n top: margin.top || 0,\n bottom: margin.bottom || 0\n });\n var offset = _objectSpread(_objectSpread({}, offsetV), offsetH);\n var brushBottom = offset.bottom;\n if (brushItem) {\n offset.bottom += brushItem.props.height || Brush.defaultProps.height;\n }\n if (legendItem && prevLegendBBox) {\n // @ts-expect-error margin is optional in props but required in appendOffsetOfLegend\n offset = appendOffsetOfLegend(offset, graphicalItems, props, prevLegendBBox);\n }\n var offsetWidth = width - offset.left - offset.right;\n var offsetHeight = height - offset.top - offset.bottom;\n return _objectSpread(_objectSpread({\n brushBottom: brushBottom\n }, offset), {}, {\n // never return negative values for height and width\n width: Math.max(offsetWidth, 0),\n height: Math.max(offsetHeight, 0)\n });\n};\n// Determine the size of the axis, used for calculation of relative bar sizes\nvar getCartesianAxisSize = function getCartesianAxisSize(axisObj, axisName) {\n if (axisName === 'xAxis') {\n return axisObj[axisName].width;\n }\n if (axisName === 'yAxis') {\n return axisObj[axisName].height;\n }\n // This is only supported for Bar charts (i.e. charts with cartesian axes), so we should never get here\n return undefined;\n};\nexport var generateCategoricalChart = function generateCategoricalChart(_ref6) {\n var chartName = _ref6.chartName,\n GraphicalChild = _ref6.GraphicalChild,\n _ref6$defaultTooltipE = _ref6.defaultTooltipEventType,\n defaultTooltipEventType = _ref6$defaultTooltipE === void 0 ? 'axis' : _ref6$defaultTooltipE,\n _ref6$validateTooltip = _ref6.validateTooltipEventTypes,\n validateTooltipEventTypes = _ref6$validateTooltip === void 0 ? ['axis'] : _ref6$validateTooltip,\n axisComponents = _ref6.axisComponents,\n legendContent = _ref6.legendContent,\n formatAxisMap = _ref6.formatAxisMap,\n defaultProps = _ref6.defaultProps;\n var getFormatItems = function getFormatItems(props, currentState) {\n var graphicalItems = currentState.graphicalItems,\n stackGroups = currentState.stackGroups,\n offset = currentState.offset,\n updateId = currentState.updateId,\n dataStartIndex = currentState.dataStartIndex,\n dataEndIndex = currentState.dataEndIndex;\n var barSize = props.barSize,\n layout = props.layout,\n barGap = props.barGap,\n barCategoryGap = props.barCategoryGap,\n globalMaxBarSize = props.maxBarSize;\n var _getAxisNameByLayout = getAxisNameByLayout(layout),\n numericAxisName = _getAxisNameByLayout.numericAxisName,\n cateAxisName = _getAxisNameByLayout.cateAxisName;\n var hasBar = hasGraphicalBarItem(graphicalItems);\n var formattedItems = [];\n graphicalItems.forEach(function (item, index) {\n var displayedData = getDisplayedData(props.data, {\n graphicalItems: [item],\n dataStartIndex: dataStartIndex,\n dataEndIndex: dataEndIndex\n });\n var itemProps = item.type.defaultProps !== undefined ? _objectSpread(_objectSpread({}, item.type.defaultProps), item.props) : item.props;\n var dataKey = itemProps.dataKey,\n childMaxBarSize = itemProps.maxBarSize;\n // axisId of the numerical axis\n var numericAxisId = itemProps[\"\".concat(numericAxisName, \"Id\")];\n // axisId of the categorical axis\n var cateAxisId = itemProps[\"\".concat(cateAxisName, \"Id\")];\n var axisObjInitialValue = {};\n var axisObj = axisComponents.reduce(function (result, entry) {\n var _item$type$displayNam, _item$type;\n // map of axisId to axis for a specific axis type\n var axisMap = currentState[\"\".concat(entry.axisType, \"Map\")];\n // axisId of axis we are currently computing\n var id = itemProps[\"\".concat(entry.axisType, \"Id\")];\n\n /**\n * tell the user in dev mode that their configuration is incorrect if we cannot find a match between\n * axisId on the chart and axisId on the axis. zAxis does not get passed in the map for ComposedChart,\n * leave it out of the check for now.\n */\n !(axisMap && axisMap[id] || entry.axisType === 'zAxis') ? process.env.NODE_ENV !== \"production\" ? invariant(false, \"Specifying a(n) \".concat(entry.axisType, \"Id requires a corresponding \").concat(entry.axisType\n // @ts-expect-error we should stop reading data from ReactElements\n , \"Id on the targeted graphical component \").concat((_item$type$displayNam = item === null || item === void 0 || (_item$type = item.type) === null || _item$type === void 0 ? void 0 : _item$type.displayName) !== null && _item$type$displayNam !== void 0 ? _item$type$displayNam : '')) : invariant(false) : void 0;\n\n // the axis we are currently formatting\n var axis = axisMap[id];\n return _objectSpread(_objectSpread({}, result), {}, _defineProperty(_defineProperty({}, entry.axisType, axis), \"\".concat(entry.axisType, \"Ticks\"), getTicksOfAxis(axis)));\n }, axisObjInitialValue);\n var cateAxis = axisObj[cateAxisName];\n var cateTicks = axisObj[\"\".concat(cateAxisName, \"Ticks\")];\n var stackedData = stackGroups && stackGroups[numericAxisId] && stackGroups[numericAxisId].hasStack && getStackedDataOfItem(item, stackGroups[numericAxisId].stackGroups);\n var itemIsBar = getDisplayName(item.type).indexOf('Bar') >= 0;\n var bandSize = getBandSizeOfAxis(cateAxis, cateTicks);\n var barPosition = [];\n var sizeList = hasBar && getBarSizeList({\n barSize: barSize,\n stackGroups: stackGroups,\n totalSize: getCartesianAxisSize(axisObj, cateAxisName)\n });\n if (itemIsBar) {\n var _ref7, _getBandSizeOfAxis;\n // If it is bar, calculate the position of bar\n var maxBarSize = isNil(childMaxBarSize) ? globalMaxBarSize : childMaxBarSize;\n var barBandSize = (_ref7 = (_getBandSizeOfAxis = getBandSizeOfAxis(cateAxis, cateTicks, true)) !== null && _getBandSizeOfAxis !== void 0 ? _getBandSizeOfAxis : maxBarSize) !== null && _ref7 !== void 0 ? _ref7 : 0;\n barPosition = getBarPosition({\n barGap: barGap,\n barCategoryGap: barCategoryGap,\n bandSize: barBandSize !== bandSize ? barBandSize : bandSize,\n sizeList: sizeList[cateAxisId],\n maxBarSize: maxBarSize\n });\n if (barBandSize !== bandSize) {\n barPosition = barPosition.map(function (pos) {\n return _objectSpread(_objectSpread({}, pos), {}, {\n position: _objectSpread(_objectSpread({}, pos.position), {}, {\n offset: pos.position.offset - barBandSize / 2\n })\n });\n });\n }\n }\n // @ts-expect-error we should stop reading data from ReactElements\n var composedFn = item && item.type && item.type.getComposedData;\n if (composedFn) {\n formattedItems.push({\n props: _objectSpread(_objectSpread({}, composedFn(_objectSpread(_objectSpread({}, axisObj), {}, {\n displayedData: displayedData,\n props: props,\n dataKey: dataKey,\n item: item,\n bandSize: bandSize,\n barPosition: barPosition,\n offset: offset,\n stackedData: stackedData,\n layout: layout,\n dataStartIndex: dataStartIndex,\n dataEndIndex: dataEndIndex\n }))), {}, _defineProperty(_defineProperty(_defineProperty({\n key: item.key || \"item-\".concat(index)\n }, numericAxisName, axisObj[numericAxisName]), cateAxisName, axisObj[cateAxisName]), \"animationId\", updateId)),\n childIndex: parseChildIndex(item, props.children),\n item: item\n });\n }\n });\n return formattedItems;\n };\n\n /**\n * The AxisMaps are expensive to render on large data sets\n * so provide the ability to store them in state and only update them when necessary\n * they are dependent upon the start and end index of\n * the brush so it's important that this method is called _after_\n * the state is updated with any new start/end indices\n *\n * @param {Object} props The props object to be used for updating the axismaps\n * dataStartIndex: The start index of the data series when a brush is applied\n * dataEndIndex: The end index of the data series when a brush is applied\n * updateId: The update id\n * @param {Object} prevState Prev state\n * @return {Object} state New state to set\n */\n var updateStateOfAxisMapsOffsetAndStackGroups = function updateStateOfAxisMapsOffsetAndStackGroups(_ref8, prevState) {\n var props = _ref8.props,\n dataStartIndex = _ref8.dataStartIndex,\n dataEndIndex = _ref8.dataEndIndex,\n updateId = _ref8.updateId;\n if (!validateWidthHeight({\n props: props\n })) {\n return null;\n }\n var children = props.children,\n layout = props.layout,\n stackOffset = props.stackOffset,\n data = props.data,\n reverseStackOrder = props.reverseStackOrder;\n var _getAxisNameByLayout2 = getAxisNameByLayout(layout),\n numericAxisName = _getAxisNameByLayout2.numericAxisName,\n cateAxisName = _getAxisNameByLayout2.cateAxisName;\n var graphicalItems = findAllByType(children, GraphicalChild);\n var stackGroups = getStackGroupsByAxisId(data, graphicalItems, \"\".concat(numericAxisName, \"Id\"), \"\".concat(cateAxisName, \"Id\"), stackOffset, reverseStackOrder);\n var axisObj = axisComponents.reduce(function (result, entry) {\n var name = \"\".concat(entry.axisType, \"Map\");\n return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, name, getAxisMap(props, _objectSpread(_objectSpread({}, entry), {}, {\n graphicalItems: graphicalItems,\n stackGroups: entry.axisType === numericAxisName && stackGroups,\n dataStartIndex: dataStartIndex,\n dataEndIndex: dataEndIndex\n }))));\n }, {});\n var offset = calculateOffset(_objectSpread(_objectSpread({}, axisObj), {}, {\n props: props,\n graphicalItems: graphicalItems\n }), prevState === null || prevState === void 0 ? void 0 : prevState.legendBBox);\n Object.keys(axisObj).forEach(function (key) {\n axisObj[key] = formatAxisMap(props, axisObj[key], offset, key.replace('Map', ''), chartName);\n });\n var cateAxisMap = axisObj[\"\".concat(cateAxisName, \"Map\")];\n var ticksObj = tooltipTicksGenerator(cateAxisMap);\n var formattedGraphicalItems = getFormatItems(props, _objectSpread(_objectSpread({}, axisObj), {}, {\n dataStartIndex: dataStartIndex,\n dataEndIndex: dataEndIndex,\n updateId: updateId,\n graphicalItems: graphicalItems,\n stackGroups: stackGroups,\n offset: offset\n }));\n return _objectSpread(_objectSpread({\n formattedGraphicalItems: formattedGraphicalItems,\n graphicalItems: graphicalItems,\n offset: offset,\n stackGroups: stackGroups\n }, ticksObj), axisObj);\n };\n var CategoricalChartWrapper = /*#__PURE__*/function (_Component) {\n function CategoricalChartWrapper(_props) {\n var _props$id, _props$throttleDelay;\n var _this;\n _classCallCheck(this, CategoricalChartWrapper);\n _this = _callSuper(this, CategoricalChartWrapper, [_props]);\n _defineProperty(_this, \"eventEmitterSymbol\", Symbol('rechartsEventEmitter'));\n _defineProperty(_this, \"accessibilityManager\", new AccessibilityManager());\n _defineProperty(_this, \"handleLegendBBoxUpdate\", function (box) {\n if (box) {\n var _this$state = _this.state,\n dataStartIndex = _this$state.dataStartIndex,\n dataEndIndex = _this$state.dataEndIndex,\n updateId = _this$state.updateId;\n _this.setState(_objectSpread({\n legendBBox: box\n }, updateStateOfAxisMapsOffsetAndStackGroups({\n props: _this.props,\n dataStartIndex: dataStartIndex,\n dataEndIndex: dataEndIndex,\n updateId: updateId\n }, _objectSpread(_objectSpread({}, _this.state), {}, {\n legendBBox: box\n }))));\n }\n });\n _defineProperty(_this, \"handleReceiveSyncEvent\", function (cId, data, emitter) {\n if (_this.props.syncId === cId) {\n if (emitter === _this.eventEmitterSymbol && typeof _this.props.syncMethod !== 'function') {\n return;\n }\n _this.applySyncEvent(data);\n }\n });\n _defineProperty(_this, \"handleBrushChange\", function (_ref9) {\n var startIndex = _ref9.startIndex,\n endIndex = _ref9.endIndex;\n // Only trigger changes if the extents of the brush have actually changed\n if (startIndex !== _this.state.dataStartIndex || endIndex !== _this.state.dataEndIndex) {\n var updateId = _this.state.updateId;\n _this.setState(function () {\n return _objectSpread({\n dataStartIndex: startIndex,\n dataEndIndex: endIndex\n }, updateStateOfAxisMapsOffsetAndStackGroups({\n props: _this.props,\n dataStartIndex: startIndex,\n dataEndIndex: endIndex,\n updateId: updateId\n }, _this.state));\n });\n _this.triggerSyncEvent({\n dataStartIndex: startIndex,\n dataEndIndex: endIndex\n });\n }\n });\n /**\n * The handler of mouse entering chart\n * @param {Object} e Event object\n * @return {Null} null\n */\n _defineProperty(_this, \"handleMouseEnter\", function (e) {\n var mouse = _this.getMouseInfo(e);\n if (mouse) {\n var _nextState = _objectSpread(_objectSpread({}, mouse), {}, {\n isTooltipActive: true\n });\n _this.setState(_nextState);\n _this.triggerSyncEvent(_nextState);\n var onMouseEnter = _this.props.onMouseEnter;\n if (isFunction(onMouseEnter)) {\n onMouseEnter(_nextState, e);\n }\n }\n });\n _defineProperty(_this, \"triggeredAfterMouseMove\", function (e) {\n var mouse = _this.getMouseInfo(e);\n var nextState = mouse ? _objectSpread(_objectSpread({}, mouse), {}, {\n isTooltipActive: true\n }) : {\n isTooltipActive: false\n };\n _this.setState(nextState);\n _this.triggerSyncEvent(nextState);\n var onMouseMove = _this.props.onMouseMove;\n if (isFunction(onMouseMove)) {\n onMouseMove(nextState, e);\n }\n });\n /**\n * The handler of mouse entering a scatter\n * @param {Object} el The active scatter\n * @return {Object} no return\n */\n _defineProperty(_this, \"handleItemMouseEnter\", function (el) {\n _this.setState(function () {\n return {\n isTooltipActive: true,\n activeItem: el,\n activePayload: el.tooltipPayload,\n activeCoordinate: el.tooltipPosition || {\n x: el.cx,\n y: el.cy\n }\n };\n });\n });\n /**\n * The handler of mouse leaving a scatter\n * @return {Object} no return\n */\n _defineProperty(_this, \"handleItemMouseLeave\", function () {\n _this.setState(function () {\n return {\n isTooltipActive: false\n };\n });\n });\n /**\n * The handler of mouse moving in chart\n * @param {React.MouseEvent} e Event object\n * @return {void} no return\n */\n _defineProperty(_this, \"handleMouseMove\", function (e) {\n e.persist();\n _this.throttleTriggeredAfterMouseMove(e);\n });\n /**\n * The handler if mouse leaving chart\n * @param {Object} e Event object\n * @return {Null} no return\n */\n _defineProperty(_this, \"handleMouseLeave\", function (e) {\n _this.throttleTriggeredAfterMouseMove.cancel();\n var nextState = {\n isTooltipActive: false\n };\n _this.setState(nextState);\n _this.triggerSyncEvent(nextState);\n var onMouseLeave = _this.props.onMouseLeave;\n if (isFunction(onMouseLeave)) {\n onMouseLeave(nextState, e);\n }\n });\n _defineProperty(_this, \"handleOuterEvent\", function (e) {\n var eventName = getReactEventByType(e);\n var event = get(_this.props, \"\".concat(eventName));\n if (eventName && isFunction(event)) {\n var _mouse;\n var mouse;\n if (/.*touch.*/i.test(eventName)) {\n mouse = _this.getMouseInfo(e.changedTouches[0]);\n } else {\n mouse = _this.getMouseInfo(e);\n }\n event((_mouse = mouse) !== null && _mouse !== void 0 ? _mouse : {}, e);\n }\n });\n _defineProperty(_this, \"handleClick\", function (e) {\n var mouse = _this.getMouseInfo(e);\n if (mouse) {\n var _nextState2 = _objectSpread(_objectSpread({}, mouse), {}, {\n isTooltipActive: true\n });\n _this.setState(_nextState2);\n _this.triggerSyncEvent(_nextState2);\n var onClick = _this.props.onClick;\n if (isFunction(onClick)) {\n onClick(_nextState2, e);\n }\n }\n });\n _defineProperty(_this, \"handleMouseDown\", function (e) {\n var onMouseDown = _this.props.onMouseDown;\n if (isFunction(onMouseDown)) {\n var _nextState3 = _this.getMouseInfo(e);\n onMouseDown(_nextState3, e);\n }\n });\n _defineProperty(_this, \"handleMouseUp\", function (e) {\n var onMouseUp = _this.props.onMouseUp;\n if (isFunction(onMouseUp)) {\n var _nextState4 = _this.getMouseInfo(e);\n onMouseUp(_nextState4, e);\n }\n });\n _defineProperty(_this, \"handleTouchMove\", function (e) {\n if (e.changedTouches != null && e.changedTouches.length > 0) {\n _this.throttleTriggeredAfterMouseMove(e.changedTouches[0]);\n }\n });\n _defineProperty(_this, \"handleTouchStart\", function (e) {\n if (e.changedTouches != null && e.changedTouches.length > 0) {\n _this.handleMouseDown(e.changedTouches[0]);\n }\n });\n _defineProperty(_this, \"handleTouchEnd\", function (e) {\n if (e.changedTouches != null && e.changedTouches.length > 0) {\n _this.handleMouseUp(e.changedTouches[0]);\n }\n });\n _defineProperty(_this, \"handleDoubleClick\", function (e) {\n var onDoubleClick = _this.props.onDoubleClick;\n if (isFunction(onDoubleClick)) {\n var _nextState5 = _this.getMouseInfo(e);\n onDoubleClick(_nextState5, e);\n }\n });\n _defineProperty(_this, \"handleContextMenu\", function (e) {\n var onContextMenu = _this.props.onContextMenu;\n if (isFunction(onContextMenu)) {\n var _nextState6 = _this.getMouseInfo(e);\n onContextMenu(_nextState6, e);\n }\n });\n _defineProperty(_this, \"triggerSyncEvent\", function (data) {\n if (_this.props.syncId !== undefined) {\n eventCenter.emit(SYNC_EVENT, _this.props.syncId, data, _this.eventEmitterSymbol);\n }\n });\n _defineProperty(_this, \"applySyncEvent\", function (data) {\n var _this$props = _this.props,\n layout = _this$props.layout,\n syncMethod = _this$props.syncMethod;\n var updateId = _this.state.updateId;\n var dataStartIndex = data.dataStartIndex,\n dataEndIndex = data.dataEndIndex;\n if (data.dataStartIndex !== undefined || data.dataEndIndex !== undefined) {\n _this.setState(_objectSpread({\n dataStartIndex: dataStartIndex,\n dataEndIndex: dataEndIndex\n }, updateStateOfAxisMapsOffsetAndStackGroups({\n props: _this.props,\n dataStartIndex: dataStartIndex,\n dataEndIndex: dataEndIndex,\n updateId: updateId\n }, _this.state)));\n } else if (data.activeTooltipIndex !== undefined) {\n var chartX = data.chartX,\n chartY = data.chartY;\n var activeTooltipIndex = data.activeTooltipIndex;\n var _this$state2 = _this.state,\n offset = _this$state2.offset,\n tooltipTicks = _this$state2.tooltipTicks;\n if (!offset) {\n return;\n }\n if (typeof syncMethod === 'function') {\n // Call a callback function. If there is an application specific algorithm\n activeTooltipIndex = syncMethod(tooltipTicks, data);\n } else if (syncMethod === 'value') {\n // Set activeTooltipIndex to the index with the same value as data.activeLabel\n // For loop instead of findIndex because the latter is very slow in some browsers\n activeTooltipIndex = -1; // in case we cannot find the element\n for (var i = 0; i < tooltipTicks.length; i++) {\n if (tooltipTicks[i].value === data.activeLabel) {\n activeTooltipIndex = i;\n break;\n }\n }\n }\n var viewBox = _objectSpread(_objectSpread({}, offset), {}, {\n x: offset.left,\n y: offset.top\n });\n // When a categorical chart is combined with another chart, the value of chartX\n // and chartY may beyond the boundaries.\n var validateChartX = Math.min(chartX, viewBox.x + viewBox.width);\n var validateChartY = Math.min(chartY, viewBox.y + viewBox.height);\n var activeLabel = tooltipTicks[activeTooltipIndex] && tooltipTicks[activeTooltipIndex].value;\n var activePayload = getTooltipContent(_this.state, _this.props.data, activeTooltipIndex);\n var activeCoordinate = tooltipTicks[activeTooltipIndex] ? {\n x: layout === 'horizontal' ? tooltipTicks[activeTooltipIndex].coordinate : validateChartX,\n y: layout === 'horizontal' ? validateChartY : tooltipTicks[activeTooltipIndex].coordinate\n } : originCoordinate;\n _this.setState(_objectSpread(_objectSpread({}, data), {}, {\n activeLabel: activeLabel,\n activeCoordinate: activeCoordinate,\n activePayload: activePayload,\n activeTooltipIndex: activeTooltipIndex\n }));\n } else {\n _this.setState(data);\n }\n });\n _defineProperty(_this, \"renderCursor\", function (element) {\n var _element$props$active;\n var _this$state3 = _this.state,\n isTooltipActive = _this$state3.isTooltipActive,\n activeCoordinate = _this$state3.activeCoordinate,\n activePayload = _this$state3.activePayload,\n offset = _this$state3.offset,\n activeTooltipIndex = _this$state3.activeTooltipIndex,\n tooltipAxisBandSize = _this$state3.tooltipAxisBandSize;\n var tooltipEventType = _this.getTooltipEventType();\n // The cursor is a part of the Tooltip, and it should be shown (by default) when the Tooltip is active.\n var isActive = (_element$props$active = element.props.active) !== null && _element$props$active !== void 0 ? _element$props$active : isTooltipActive;\n var layout = _this.props.layout;\n var key = element.key || '_recharts-cursor';\n return /*#__PURE__*/React.createElement(Cursor, {\n key: key,\n activeCoordinate: activeCoordinate,\n activePayload: activePayload,\n activeTooltipIndex: activeTooltipIndex,\n chartName: chartName,\n element: element,\n isActive: isActive,\n layout: layout,\n offset: offset,\n tooltipAxisBandSize: tooltipAxisBandSize,\n tooltipEventType: tooltipEventType\n });\n });\n _defineProperty(_this, \"renderPolarAxis\", function (element, displayName, index) {\n var axisType = get(element, 'type.axisType');\n var axisMap = get(_this.state, \"\".concat(axisType, \"Map\"));\n var elementDefaultProps = element.type.defaultProps;\n var elementProps = elementDefaultProps !== undefined ? _objectSpread(_objectSpread({}, elementDefaultProps), element.props) : element.props;\n var axisOption = axisMap && axisMap[elementProps[\"\".concat(axisType, \"Id\")]];\n return /*#__PURE__*/cloneElement(element, _objectSpread(_objectSpread({}, axisOption), {}, {\n className: clsx(axisType, axisOption.className),\n key: element.key || \"\".concat(displayName, \"-\").concat(index),\n ticks: getTicksOfAxis(axisOption, true)\n }));\n });\n _defineProperty(_this, \"renderPolarGrid\", function (element) {\n var _element$props = element.props,\n radialLines = _element$props.radialLines,\n polarAngles = _element$props.polarAngles,\n polarRadius = _element$props.polarRadius;\n var _this$state4 = _this.state,\n radiusAxisMap = _this$state4.radiusAxisMap,\n angleAxisMap = _this$state4.angleAxisMap;\n var radiusAxis = getAnyElementOfObject(radiusAxisMap);\n var angleAxis = getAnyElementOfObject(angleAxisMap);\n var cx = angleAxis.cx,\n cy = angleAxis.cy,\n innerRadius = angleAxis.innerRadius,\n outerRadius = angleAxis.outerRadius;\n return /*#__PURE__*/cloneElement(element, {\n polarAngles: Array.isArray(polarAngles) ? polarAngles : getTicksOfAxis(angleAxis, true).map(function (entry) {\n return entry.coordinate;\n }),\n polarRadius: Array.isArray(polarRadius) ? polarRadius : getTicksOfAxis(radiusAxis, true).map(function (entry) {\n return entry.coordinate;\n }),\n cx: cx,\n cy: cy,\n innerRadius: innerRadius,\n outerRadius: outerRadius,\n key: element.key || 'polar-grid',\n radialLines: radialLines\n });\n });\n /**\n * Draw legend\n * @return {ReactElement} The instance of Legend\n */\n _defineProperty(_this, \"renderLegend\", function () {\n var formattedGraphicalItems = _this.state.formattedGraphicalItems;\n var _this$props2 = _this.props,\n children = _this$props2.children,\n width = _this$props2.width,\n height = _this$props2.height;\n var margin = _this.props.margin || {};\n var legendWidth = width - (margin.left || 0) - (margin.right || 0);\n var props = getLegendProps({\n children: children,\n formattedGraphicalItems: formattedGraphicalItems,\n legendWidth: legendWidth,\n legendContent: legendContent\n });\n if (!props) {\n return null;\n }\n var item = props.item,\n otherProps = _objectWithoutProperties(props, _excluded);\n return /*#__PURE__*/cloneElement(item, _objectSpread(_objectSpread({}, otherProps), {}, {\n chartWidth: width,\n chartHeight: height,\n margin: margin,\n onBBoxUpdate: _this.handleLegendBBoxUpdate\n }));\n });\n /**\n * Draw Tooltip\n * @return {ReactElement} The instance of Tooltip\n */\n _defineProperty(_this, \"renderTooltip\", function () {\n var _tooltipItem$props$ac;\n var _this$props3 = _this.props,\n children = _this$props3.children,\n accessibilityLayer = _this$props3.accessibilityLayer;\n var tooltipItem = findChildByType(children, Tooltip);\n if (!tooltipItem) {\n return null;\n }\n var _this$state5 = _this.state,\n isTooltipActive = _this$state5.isTooltipActive,\n activeCoordinate = _this$state5.activeCoordinate,\n activePayload = _this$state5.activePayload,\n activeLabel = _this$state5.activeLabel,\n offset = _this$state5.offset;\n\n // The user can set isActive on the Tooltip,\n // and we respect the user to enable customisation.\n // The Tooltip is active if the user has set isActive, or if the tooltip is active due to a mouse event.\n var isActive = (_tooltipItem$props$ac = tooltipItem.props.active) !== null && _tooltipItem$props$ac !== void 0 ? _tooltipItem$props$ac : isTooltipActive;\n return /*#__PURE__*/cloneElement(tooltipItem, {\n viewBox: _objectSpread(_objectSpread({}, offset), {}, {\n x: offset.left,\n y: offset.top\n }),\n active: isActive,\n label: activeLabel,\n payload: isActive ? activePayload : [],\n coordinate: activeCoordinate,\n accessibilityLayer: accessibilityLayer\n });\n });\n _defineProperty(_this, \"renderBrush\", function (element) {\n var _this$props4 = _this.props,\n margin = _this$props4.margin,\n data = _this$props4.data;\n var _this$state6 = _this.state,\n offset = _this$state6.offset,\n dataStartIndex = _this$state6.dataStartIndex,\n dataEndIndex = _this$state6.dataEndIndex,\n updateId = _this$state6.updateId;\n\n // TODO: update brush when children update\n return /*#__PURE__*/cloneElement(element, {\n key: element.key || '_recharts-brush',\n onChange: combineEventHandlers(_this.handleBrushChange, element.props.onChange),\n data: data,\n x: isNumber(element.props.x) ? element.props.x : offset.left,\n y: isNumber(element.props.y) ? element.props.y : offset.top + offset.height + offset.brushBottom - (margin.bottom || 0),\n width: isNumber(element.props.width) ? element.props.width : offset.width,\n startIndex: dataStartIndex,\n endIndex: dataEndIndex,\n updateId: \"brush-\".concat(updateId)\n });\n });\n _defineProperty(_this, \"renderReferenceElement\", function (element, displayName, index) {\n if (!element) {\n return null;\n }\n var _this2 = _this,\n clipPathId = _this2.clipPathId;\n var _this$state7 = _this.state,\n xAxisMap = _this$state7.xAxisMap,\n yAxisMap = _this$state7.yAxisMap,\n offset = _this$state7.offset;\n var elementDefaultProps = element.type.defaultProps || {};\n var _element$props2 = element.props,\n _element$props2$xAxis = _element$props2.xAxisId,\n xAxisId = _element$props2$xAxis === void 0 ? elementDefaultProps.xAxisId : _element$props2$xAxis,\n _element$props2$yAxis = _element$props2.yAxisId,\n yAxisId = _element$props2$yAxis === void 0 ? elementDefaultProps.yAxisId : _element$props2$yAxis;\n return /*#__PURE__*/cloneElement(element, {\n key: element.key || \"\".concat(displayName, \"-\").concat(index),\n xAxis: xAxisMap[xAxisId],\n yAxis: yAxisMap[yAxisId],\n viewBox: {\n x: offset.left,\n y: offset.top,\n width: offset.width,\n height: offset.height\n },\n clipPathId: clipPathId\n });\n });\n _defineProperty(_this, \"renderActivePoints\", function (_ref10) {\n var item = _ref10.item,\n activePoint = _ref10.activePoint,\n basePoint = _ref10.basePoint,\n childIndex = _ref10.childIndex,\n isRange = _ref10.isRange;\n var result = [];\n // item is not a React Element so we don't need to resolve defaultProps.\n var key = item.props.key;\n var itemItemProps = item.item.type.defaultProps !== undefined ? _objectSpread(_objectSpread({}, item.item.type.defaultProps), item.item.props) : item.item.props;\n var activeDot = itemItemProps.activeDot,\n dataKey = itemItemProps.dataKey;\n var dotProps = _objectSpread(_objectSpread({\n index: childIndex,\n dataKey: dataKey,\n cx: activePoint.x,\n cy: activePoint.y,\n r: 4,\n fill: getMainColorOfGraphicItem(item.item),\n strokeWidth: 2,\n stroke: '#fff',\n payload: activePoint.payload,\n value: activePoint.value\n }, filterProps(activeDot, false)), adaptEventHandlers(activeDot));\n result.push(CategoricalChartWrapper.renderActiveDot(activeDot, dotProps, \"\".concat(key, \"-activePoint-\").concat(childIndex)));\n if (basePoint) {\n result.push(CategoricalChartWrapper.renderActiveDot(activeDot, _objectSpread(_objectSpread({}, dotProps), {}, {\n cx: basePoint.x,\n cy: basePoint.y\n }), \"\".concat(key, \"-basePoint-\").concat(childIndex)));\n } else if (isRange) {\n result.push(null);\n }\n return result;\n });\n _defineProperty(_this, \"renderGraphicChild\", function (element, displayName, index) {\n var item = _this.filterFormatItem(element, displayName, index);\n if (!item) {\n return null;\n }\n var tooltipEventType = _this.getTooltipEventType();\n var _this$state8 = _this.state,\n isTooltipActive = _this$state8.isTooltipActive,\n tooltipAxis = _this$state8.tooltipAxis,\n activeTooltipIndex = _this$state8.activeTooltipIndex,\n activeLabel = _this$state8.activeLabel;\n var children = _this.props.children;\n var tooltipItem = findChildByType(children, Tooltip);\n // item is not a React Element so we don't need to resolve defaultProps\n var _item$props = item.props,\n points = _item$props.points,\n isRange = _item$props.isRange,\n baseLine = _item$props.baseLine;\n var itemItemProps = item.item.type.defaultProps !== undefined ? _objectSpread(_objectSpread({}, item.item.type.defaultProps), item.item.props) : item.item.props;\n var activeDot = itemItemProps.activeDot,\n hide = itemItemProps.hide,\n activeBar = itemItemProps.activeBar,\n activeShape = itemItemProps.activeShape;\n var hasActive = Boolean(!hide && isTooltipActive && tooltipItem && (activeDot || activeBar || activeShape));\n var itemEvents = {};\n if (tooltipEventType !== 'axis' && tooltipItem && tooltipItem.props.trigger === 'click') {\n itemEvents = {\n onClick: combineEventHandlers(_this.handleItemMouseEnter, element.props.onClick)\n };\n } else if (tooltipEventType !== 'axis') {\n itemEvents = {\n onMouseLeave: combineEventHandlers(_this.handleItemMouseLeave, element.props.onMouseLeave),\n onMouseEnter: combineEventHandlers(_this.handleItemMouseEnter, element.props.onMouseEnter)\n };\n }\n var graphicalItem = /*#__PURE__*/cloneElement(element, _objectSpread(_objectSpread({}, item.props), itemEvents));\n function findWithPayload(entry) {\n // TODO needs to verify dataKey is Function\n return typeof tooltipAxis.dataKey === 'function' ? tooltipAxis.dataKey(entry.payload) : null;\n }\n if (hasActive) {\n if (activeTooltipIndex >= 0) {\n var activePoint, basePoint;\n if (tooltipAxis.dataKey && !tooltipAxis.allowDuplicatedCategory) {\n // number transform to string\n var specifiedKey = typeof tooltipAxis.dataKey === 'function' ? findWithPayload : 'payload.'.concat(tooltipAxis.dataKey.toString());\n activePoint = findEntryInArray(points, specifiedKey, activeLabel);\n basePoint = isRange && baseLine && findEntryInArray(baseLine, specifiedKey, activeLabel);\n } else {\n activePoint = points === null || points === void 0 ? void 0 : points[activeTooltipIndex];\n basePoint = isRange && baseLine && baseLine[activeTooltipIndex];\n }\n if (activeShape || activeBar) {\n var activeIndex = element.props.activeIndex !== undefined ? element.props.activeIndex : activeTooltipIndex;\n return [/*#__PURE__*/cloneElement(element, _objectSpread(_objectSpread(_objectSpread({}, item.props), itemEvents), {}, {\n activeIndex: activeIndex\n })), null, null];\n }\n if (!isNil(activePoint)) {\n return [graphicalItem].concat(_toConsumableArray(_this.renderActivePoints({\n item: item,\n activePoint: activePoint,\n basePoint: basePoint,\n childIndex: activeTooltipIndex,\n isRange: isRange\n })));\n }\n } else {\n var _this$getItemByXY;\n /**\n * We hit this block if consumer uses a Tooltip without XAxis and/or YAxis.\n * In which case, this.state.activeTooltipIndex never gets set\n * because the mouse events that trigger that value getting set never get trigged without the axis components.\n *\n * An example usage case is a FunnelChart\n */\n var _ref11 = (_this$getItemByXY = _this.getItemByXY(_this.state.activeCoordinate)) !== null && _this$getItemByXY !== void 0 ? _this$getItemByXY : {\n graphicalItem: graphicalItem\n },\n _ref11$graphicalItem = _ref11.graphicalItem,\n _ref11$graphicalItem$ = _ref11$graphicalItem.item,\n xyItem = _ref11$graphicalItem$ === void 0 ? element : _ref11$graphicalItem$,\n childIndex = _ref11$graphicalItem.childIndex;\n var elementProps = _objectSpread(_objectSpread(_objectSpread({}, item.props), itemEvents), {}, {\n activeIndex: childIndex\n });\n return [/*#__PURE__*/cloneElement(xyItem, elementProps), null, null];\n }\n }\n if (isRange) {\n return [graphicalItem, null, null];\n }\n return [graphicalItem, null];\n });\n _defineProperty(_this, \"renderCustomized\", function (element, displayName, index) {\n return /*#__PURE__*/cloneElement(element, _objectSpread(_objectSpread({\n key: \"recharts-customized-\".concat(index)\n }, _this.props), _this.state));\n });\n _defineProperty(_this, \"renderMap\", {\n CartesianGrid: {\n handler: renderAsIs,\n once: true\n },\n ReferenceArea: {\n handler: _this.renderReferenceElement\n },\n ReferenceLine: {\n handler: renderAsIs\n },\n ReferenceDot: {\n handler: _this.renderReferenceElement\n },\n XAxis: {\n handler: renderAsIs\n },\n YAxis: {\n handler: renderAsIs\n },\n Brush: {\n handler: _this.renderBrush,\n once: true\n },\n Bar: {\n handler: _this.renderGraphicChild\n },\n Line: {\n handler: _this.renderGraphicChild\n },\n Area: {\n handler: _this.renderGraphicChild\n },\n Radar: {\n handler: _this.renderGraphicChild\n },\n RadialBar: {\n handler: _this.renderGraphicChild\n },\n Scatter: {\n handler: _this.renderGraphicChild\n },\n Pie: {\n handler: _this.renderGraphicChild\n },\n Funnel: {\n handler: _this.renderGraphicChild\n },\n Tooltip: {\n handler: _this.renderCursor,\n once: true\n },\n PolarGrid: {\n handler: _this.renderPolarGrid,\n once: true\n },\n PolarAngleAxis: {\n handler: _this.renderPolarAxis\n },\n PolarRadiusAxis: {\n handler: _this.renderPolarAxis\n },\n Customized: {\n handler: _this.renderCustomized\n }\n });\n _this.clipPathId = \"\".concat((_props$id = _props.id) !== null && _props$id !== void 0 ? _props$id : uniqueId('recharts'), \"-clip\");\n\n // trigger 60fps\n _this.throttleTriggeredAfterMouseMove = throttle(_this.triggeredAfterMouseMove, (_props$throttleDelay = _props.throttleDelay) !== null && _props$throttleDelay !== void 0 ? _props$throttleDelay : 1000 / 60);\n _this.state = {};\n return _this;\n }\n _inherits(CategoricalChartWrapper, _Component);\n return _createClass(CategoricalChartWrapper, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n var _this$props$margin$le, _this$props$margin$to;\n this.addListener();\n this.accessibilityManager.setDetails({\n container: this.container,\n offset: {\n left: (_this$props$margin$le = this.props.margin.left) !== null && _this$props$margin$le !== void 0 ? _this$props$margin$le : 0,\n top: (_this$props$margin$to = this.props.margin.top) !== null && _this$props$margin$to !== void 0 ? _this$props$margin$to : 0\n },\n coordinateList: this.state.tooltipTicks,\n mouseHandlerCallback: this.triggeredAfterMouseMove,\n layout: this.props.layout\n });\n this.displayDefaultTooltip();\n }\n }, {\n key: \"displayDefaultTooltip\",\n value: function displayDefaultTooltip() {\n var _this$props5 = this.props,\n children = _this$props5.children,\n data = _this$props5.data,\n height = _this$props5.height,\n layout = _this$props5.layout;\n var tooltipElem = findChildByType(children, Tooltip);\n // If the chart doesn't include a element, there's no tooltip to display\n if (!tooltipElem) {\n return;\n }\n var defaultIndex = tooltipElem.props.defaultIndex;\n\n // Protect against runtime errors\n if (typeof defaultIndex !== 'number' || defaultIndex < 0 || defaultIndex > this.state.tooltipTicks.length - 1) {\n return;\n }\n var activeLabel = this.state.tooltipTicks[defaultIndex] && this.state.tooltipTicks[defaultIndex].value;\n var activePayload = getTooltipContent(this.state, data, defaultIndex, activeLabel);\n var independentAxisCoord = this.state.tooltipTicks[defaultIndex].coordinate;\n var dependentAxisCoord = (this.state.offset.top + height) / 2;\n var isHorizontal = layout === 'horizontal';\n var activeCoordinate = isHorizontal ? {\n x: independentAxisCoord,\n y: dependentAxisCoord\n } : {\n y: independentAxisCoord,\n x: dependentAxisCoord\n };\n\n // Unlike other chart types, scatter plot's tooltip positions rely on both X and Y coordinates. Only the scatter plot\n // element knows its own Y coordinates.\n // If there's a scatter plot, we'll want to grab that element for an interrogation.\n var scatterPlotElement = this.state.formattedGraphicalItems.find(function (_ref12) {\n var item = _ref12.item;\n return item.type.name === 'Scatter';\n });\n if (scatterPlotElement) {\n activeCoordinate = _objectSpread(_objectSpread({}, activeCoordinate), scatterPlotElement.props.points[defaultIndex].tooltipPosition);\n activePayload = scatterPlotElement.props.points[defaultIndex].tooltipPayload;\n }\n var nextState = {\n activeTooltipIndex: defaultIndex,\n isTooltipActive: true,\n activeLabel: activeLabel,\n activePayload: activePayload,\n activeCoordinate: activeCoordinate\n };\n this.setState(nextState);\n this.renderCursor(tooltipElem);\n\n // Make sure that anyone who keyboard-only users who tab to the chart will start their\n // cursors at defaultIndex\n this.accessibilityManager.setIndex(defaultIndex);\n }\n }, {\n key: \"getSnapshotBeforeUpdate\",\n value: function getSnapshotBeforeUpdate(prevProps, prevState) {\n if (!this.props.accessibilityLayer) {\n return null;\n }\n if (this.state.tooltipTicks !== prevState.tooltipTicks) {\n this.accessibilityManager.setDetails({\n coordinateList: this.state.tooltipTicks\n });\n }\n if (this.props.layout !== prevProps.layout) {\n this.accessibilityManager.setDetails({\n layout: this.props.layout\n });\n }\n if (this.props.margin !== prevProps.margin) {\n var _this$props$margin$le2, _this$props$margin$to2;\n this.accessibilityManager.setDetails({\n offset: {\n left: (_this$props$margin$le2 = this.props.margin.left) !== null && _this$props$margin$le2 !== void 0 ? _this$props$margin$le2 : 0,\n top: (_this$props$margin$to2 = this.props.margin.top) !== null && _this$props$margin$to2 !== void 0 ? _this$props$margin$to2 : 0\n }\n });\n }\n\n // Something has to be returned for getSnapshotBeforeUpdate\n return null;\n }\n }, {\n key: \"componentDidUpdate\",\n value: function componentDidUpdate(prevProps) {\n // Check to see if the Tooltip updated. If so, re-check default tooltip position\n if (!isChildrenEqual([findChildByType(prevProps.children, Tooltip)], [findChildByType(this.props.children, Tooltip)])) {\n this.displayDefaultTooltip();\n }\n }\n }, {\n key: \"componentWillUnmount\",\n value: function componentWillUnmount() {\n this.removeListener();\n this.throttleTriggeredAfterMouseMove.cancel();\n }\n }, {\n key: \"getTooltipEventType\",\n value: function getTooltipEventType() {\n var tooltipItem = findChildByType(this.props.children, Tooltip);\n if (tooltipItem && typeof tooltipItem.props.shared === 'boolean') {\n var eventType = tooltipItem.props.shared ? 'axis' : 'item';\n return validateTooltipEventTypes.indexOf(eventType) >= 0 ? eventType : defaultTooltipEventType;\n }\n return defaultTooltipEventType;\n }\n\n /**\n * Get the information of mouse in chart, return null when the mouse is not in the chart\n * @param {MousePointer} event The event object\n * @return {Object} Mouse data\n */\n }, {\n key: \"getMouseInfo\",\n value: function getMouseInfo(event) {\n if (!this.container) {\n return null;\n }\n var element = this.container;\n var boundingRect = element.getBoundingClientRect();\n var containerOffset = getOffset(boundingRect);\n var e = {\n chartX: Math.round(event.pageX - containerOffset.left),\n chartY: Math.round(event.pageY - containerOffset.top)\n };\n var scale = boundingRect.width / element.offsetWidth || 1;\n var rangeObj = this.inRange(e.chartX, e.chartY, scale);\n if (!rangeObj) {\n return null;\n }\n var _this$state9 = this.state,\n xAxisMap = _this$state9.xAxisMap,\n yAxisMap = _this$state9.yAxisMap;\n var tooltipEventType = this.getTooltipEventType();\n var toolTipData = getTooltipData(this.state, this.props.data, this.props.layout, rangeObj);\n if (tooltipEventType !== 'axis' && xAxisMap && yAxisMap) {\n var xScale = getAnyElementOfObject(xAxisMap).scale;\n var yScale = getAnyElementOfObject(yAxisMap).scale;\n var xValue = xScale && xScale.invert ? xScale.invert(e.chartX) : null;\n var yValue = yScale && yScale.invert ? yScale.invert(e.chartY) : null;\n return _objectSpread(_objectSpread({}, e), {}, {\n xValue: xValue,\n yValue: yValue\n }, toolTipData);\n }\n if (toolTipData) {\n return _objectSpread(_objectSpread({}, e), toolTipData);\n }\n return null;\n }\n }, {\n key: \"inRange\",\n value: function inRange(x, y) {\n var scale = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n var layout = this.props.layout;\n var scaledX = x / scale,\n scaledY = y / scale;\n if (layout === 'horizontal' || layout === 'vertical') {\n var offset = this.state.offset;\n var isInRange = scaledX >= offset.left && scaledX <= offset.left + offset.width && scaledY >= offset.top && scaledY <= offset.top + offset.height;\n return isInRange ? {\n x: scaledX,\n y: scaledY\n } : null;\n }\n var _this$state10 = this.state,\n angleAxisMap = _this$state10.angleAxisMap,\n radiusAxisMap = _this$state10.radiusAxisMap;\n if (angleAxisMap && radiusAxisMap) {\n var angleAxis = getAnyElementOfObject(angleAxisMap);\n return inRangeOfSector({\n x: scaledX,\n y: scaledY\n }, angleAxis);\n }\n return null;\n }\n }, {\n key: \"parseEventsOfWrapper\",\n value: function parseEventsOfWrapper() {\n var children = this.props.children;\n var tooltipEventType = this.getTooltipEventType();\n var tooltipItem = findChildByType(children, Tooltip);\n var tooltipEvents = {};\n if (tooltipItem && tooltipEventType === 'axis') {\n if (tooltipItem.props.trigger === 'click') {\n tooltipEvents = {\n onClick: this.handleClick\n };\n } else {\n tooltipEvents = {\n onMouseEnter: this.handleMouseEnter,\n onDoubleClick: this.handleDoubleClick,\n onMouseMove: this.handleMouseMove,\n onMouseLeave: this.handleMouseLeave,\n onTouchMove: this.handleTouchMove,\n onTouchStart: this.handleTouchStart,\n onTouchEnd: this.handleTouchEnd,\n onContextMenu: this.handleContextMenu\n };\n }\n }\n\n // @ts-expect-error adaptEventHandlers expects DOM Event but generateCategoricalChart works with React UIEvents\n var outerEvents = adaptEventHandlers(this.props, this.handleOuterEvent);\n return _objectSpread(_objectSpread({}, outerEvents), tooltipEvents);\n }\n }, {\n key: \"addListener\",\n value: function addListener() {\n eventCenter.on(SYNC_EVENT, this.handleReceiveSyncEvent);\n }\n }, {\n key: \"removeListener\",\n value: function removeListener() {\n eventCenter.removeListener(SYNC_EVENT, this.handleReceiveSyncEvent);\n }\n }, {\n key: \"filterFormatItem\",\n value: function filterFormatItem(item, displayName, childIndex) {\n var formattedGraphicalItems = this.state.formattedGraphicalItems;\n for (var i = 0, len = formattedGraphicalItems.length; i < len; i++) {\n var entry = formattedGraphicalItems[i];\n if (entry.item === item || entry.props.key === item.key || displayName === getDisplayName(entry.item.type) && childIndex === entry.childIndex) {\n return entry;\n }\n }\n return null;\n }\n }, {\n key: \"renderClipPath\",\n value: function renderClipPath() {\n var clipPathId = this.clipPathId;\n var _this$state$offset = this.state.offset,\n left = _this$state$offset.left,\n top = _this$state$offset.top,\n height = _this$state$offset.height,\n width = _this$state$offset.width;\n return /*#__PURE__*/React.createElement(\"defs\", null, /*#__PURE__*/React.createElement(\"clipPath\", {\n id: clipPathId\n }, /*#__PURE__*/React.createElement(\"rect\", {\n x: left,\n y: top,\n height: height,\n width: width\n })));\n }\n }, {\n key: \"getXScales\",\n value: function getXScales() {\n var xAxisMap = this.state.xAxisMap;\n return xAxisMap ? Object.entries(xAxisMap).reduce(function (res, _ref13) {\n var _ref14 = _slicedToArray(_ref13, 2),\n axisId = _ref14[0],\n axisProps = _ref14[1];\n return _objectSpread(_objectSpread({}, res), {}, _defineProperty({}, axisId, axisProps.scale));\n }, {}) : null;\n }\n }, {\n key: \"getYScales\",\n value: function getYScales() {\n var yAxisMap = this.state.yAxisMap;\n return yAxisMap ? Object.entries(yAxisMap).reduce(function (res, _ref15) {\n var _ref16 = _slicedToArray(_ref15, 2),\n axisId = _ref16[0],\n axisProps = _ref16[1];\n return _objectSpread(_objectSpread({}, res), {}, _defineProperty({}, axisId, axisProps.scale));\n }, {}) : null;\n }\n }, {\n key: \"getXScaleByAxisId\",\n value: function getXScaleByAxisId(axisId) {\n var _this$state$xAxisMap;\n return (_this$state$xAxisMap = this.state.xAxisMap) === null || _this$state$xAxisMap === void 0 || (_this$state$xAxisMap = _this$state$xAxisMap[axisId]) === null || _this$state$xAxisMap === void 0 ? void 0 : _this$state$xAxisMap.scale;\n }\n }, {\n key: \"getYScaleByAxisId\",\n value: function getYScaleByAxisId(axisId) {\n var _this$state$yAxisMap;\n return (_this$state$yAxisMap = this.state.yAxisMap) === null || _this$state$yAxisMap === void 0 || (_this$state$yAxisMap = _this$state$yAxisMap[axisId]) === null || _this$state$yAxisMap === void 0 ? void 0 : _this$state$yAxisMap.scale;\n }\n }, {\n key: \"getItemByXY\",\n value: function getItemByXY(chartXY) {\n var _this$state11 = this.state,\n formattedGraphicalItems = _this$state11.formattedGraphicalItems,\n activeItem = _this$state11.activeItem;\n if (formattedGraphicalItems && formattedGraphicalItems.length) {\n for (var i = 0, len = formattedGraphicalItems.length; i < len; i++) {\n var graphicalItem = formattedGraphicalItems[i];\n // graphicalItem is not a React Element so we don't need to resolve defaultProps\n var props = graphicalItem.props,\n item = graphicalItem.item;\n var itemProps = item.type.defaultProps !== undefined ? _objectSpread(_objectSpread({}, item.type.defaultProps), item.props) : item.props;\n var itemDisplayName = getDisplayName(item.type);\n if (itemDisplayName === 'Bar') {\n var activeBarItem = (props.data || []).find(function (entry) {\n return isInRectangle(chartXY, entry);\n });\n if (activeBarItem) {\n return {\n graphicalItem: graphicalItem,\n payload: activeBarItem\n };\n }\n } else if (itemDisplayName === 'RadialBar') {\n var _activeBarItem = (props.data || []).find(function (entry) {\n return inRangeOfSector(chartXY, entry);\n });\n if (_activeBarItem) {\n return {\n graphicalItem: graphicalItem,\n payload: _activeBarItem\n };\n }\n } else if (isFunnel(graphicalItem, activeItem) || isPie(graphicalItem, activeItem) || isScatter(graphicalItem, activeItem)) {\n var activeIndex = getActiveShapeIndexForTooltip({\n graphicalItem: graphicalItem,\n activeTooltipItem: activeItem,\n itemData: itemProps.data\n });\n var childIndex = itemProps.activeIndex === undefined ? activeIndex : itemProps.activeIndex;\n return {\n graphicalItem: _objectSpread(_objectSpread({}, graphicalItem), {}, {\n childIndex: childIndex\n }),\n payload: isScatter(graphicalItem, activeItem) ? itemProps.data[activeIndex] : graphicalItem.props.data[activeIndex]\n };\n }\n }\n }\n return null;\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this3 = this;\n if (!validateWidthHeight(this)) {\n return null;\n }\n var _this$props6 = this.props,\n children = _this$props6.children,\n className = _this$props6.className,\n width = _this$props6.width,\n height = _this$props6.height,\n style = _this$props6.style,\n compact = _this$props6.compact,\n title = _this$props6.title,\n desc = _this$props6.desc,\n others = _objectWithoutProperties(_this$props6, _excluded2);\n var attrs = filterProps(others, false);\n\n // The \"compact\" mode is mainly used as the panorama within Brush\n if (compact) {\n return /*#__PURE__*/React.createElement(ChartLayoutContextProvider, {\n state: this.state,\n width: this.props.width,\n height: this.props.height,\n clipPathId: this.clipPathId\n }, /*#__PURE__*/React.createElement(Surface, _extends({}, attrs, {\n width: width,\n height: height,\n title: title,\n desc: desc\n }), this.renderClipPath(), renderByOrder(children, this.renderMap)));\n }\n if (this.props.accessibilityLayer) {\n var _this$props$tabIndex, _this$props$role;\n // Set tabIndex to 0 by default (can be overwritten)\n attrs.tabIndex = (_this$props$tabIndex = this.props.tabIndex) !== null && _this$props$tabIndex !== void 0 ? _this$props$tabIndex : 0;\n // Set role to img by default (can be overwritten)\n attrs.role = (_this$props$role = this.props.role) !== null && _this$props$role !== void 0 ? _this$props$role : 'application';\n attrs.onKeyDown = function (e) {\n _this3.accessibilityManager.keyboardEvent(e);\n // 'onKeyDown' is not currently a supported prop that can be passed through\n // if it's added, this should be added: this.props.onKeyDown(e);\n };\n attrs.onFocus = function () {\n _this3.accessibilityManager.focus();\n // 'onFocus' is not currently a supported prop that can be passed through\n // if it's added, the focus event should be forwarded to the prop\n };\n }\n var events = this.parseEventsOfWrapper();\n return /*#__PURE__*/React.createElement(ChartLayoutContextProvider, {\n state: this.state,\n width: this.props.width,\n height: this.props.height,\n clipPathId: this.clipPathId\n }, /*#__PURE__*/React.createElement(\"div\", _extends({\n className: clsx('recharts-wrapper', className),\n style: _objectSpread({\n position: 'relative',\n cursor: 'default',\n width: width,\n height: height\n }, style)\n }, events, {\n ref: function ref(node) {\n _this3.container = node;\n }\n }), /*#__PURE__*/React.createElement(Surface, _extends({}, attrs, {\n width: width,\n height: height,\n title: title,\n desc: desc,\n style: FULL_WIDTH_AND_HEIGHT\n }), this.renderClipPath(), renderByOrder(children, this.renderMap)), this.renderLegend(), this.renderTooltip()));\n }\n }]);\n }(Component);\n _defineProperty(CategoricalChartWrapper, \"displayName\", chartName);\n // todo join specific chart propTypes\n _defineProperty(CategoricalChartWrapper, \"defaultProps\", _objectSpread({\n layout: 'horizontal',\n stackOffset: 'none',\n barCategoryGap: '10%',\n barGap: 4,\n margin: {\n top: 5,\n right: 5,\n bottom: 5,\n left: 5\n },\n reverseStackOrder: false,\n syncMethod: 'index'\n }, defaultProps));\n _defineProperty(CategoricalChartWrapper, \"getDerivedStateFromProps\", function (nextProps, prevState) {\n var dataKey = nextProps.dataKey,\n data = nextProps.data,\n children = nextProps.children,\n width = nextProps.width,\n height = nextProps.height,\n layout = nextProps.layout,\n stackOffset = nextProps.stackOffset,\n margin = nextProps.margin;\n var dataStartIndex = prevState.dataStartIndex,\n dataEndIndex = prevState.dataEndIndex;\n if (prevState.updateId === undefined) {\n var defaultState = createDefaultState(nextProps);\n return _objectSpread(_objectSpread(_objectSpread({}, defaultState), {}, {\n updateId: 0\n }, updateStateOfAxisMapsOffsetAndStackGroups(_objectSpread(_objectSpread({\n props: nextProps\n }, defaultState), {}, {\n updateId: 0\n }), prevState)), {}, {\n prevDataKey: dataKey,\n prevData: data,\n prevWidth: width,\n prevHeight: height,\n prevLayout: layout,\n prevStackOffset: stackOffset,\n prevMargin: margin,\n prevChildren: children\n });\n }\n if (dataKey !== prevState.prevDataKey || data !== prevState.prevData || width !== prevState.prevWidth || height !== prevState.prevHeight || layout !== prevState.prevLayout || stackOffset !== prevState.prevStackOffset || !shallowEqual(margin, prevState.prevMargin)) {\n var _defaultState = createDefaultState(nextProps);\n\n // Fixes https://github.com/recharts/recharts/issues/2143\n var keepFromPrevState = {\n // (chartX, chartY) are (0,0) in default state, but we want to keep the last mouse position to avoid\n // any flickering\n chartX: prevState.chartX,\n chartY: prevState.chartY,\n // The tooltip should stay active when it was active in the previous render. If this is not\n // the case, the tooltip disappears and immediately re-appears, causing a flickering effect\n isTooltipActive: prevState.isTooltipActive\n };\n var updatesToState = _objectSpread(_objectSpread({}, getTooltipData(prevState, data, layout)), {}, {\n updateId: prevState.updateId + 1\n });\n var newState = _objectSpread(_objectSpread(_objectSpread({}, _defaultState), keepFromPrevState), updatesToState);\n return _objectSpread(_objectSpread(_objectSpread({}, newState), updateStateOfAxisMapsOffsetAndStackGroups(_objectSpread({\n props: nextProps\n }, newState), prevState)), {}, {\n prevDataKey: dataKey,\n prevData: data,\n prevWidth: width,\n prevHeight: height,\n prevLayout: layout,\n prevStackOffset: stackOffset,\n prevMargin: margin,\n prevChildren: children\n });\n }\n if (!isChildrenEqual(children, prevState.prevChildren)) {\n var _brush$props$startInd, _brush$props, _brush$props$endIndex, _brush$props2;\n // specifically check for Brush - if it exists and the start and end indexes are different, re-render with the new ones\n var brush = findChildByType(children, Brush);\n var startIndex = brush ? (_brush$props$startInd = (_brush$props = brush.props) === null || _brush$props === void 0 ? void 0 : _brush$props.startIndex) !== null && _brush$props$startInd !== void 0 ? _brush$props$startInd : dataStartIndex : dataStartIndex;\n var endIndex = brush ? (_brush$props$endIndex = (_brush$props2 = brush.props) === null || _brush$props2 === void 0 ? void 0 : _brush$props2.endIndex) !== null && _brush$props$endIndex !== void 0 ? _brush$props$endIndex : dataEndIndex : dataEndIndex;\n var hasDifferentStartOrEndIndex = startIndex !== dataStartIndex || endIndex !== dataEndIndex;\n\n // update configuration in children\n var hasGlobalData = !isNil(data);\n var newUpdateId = hasGlobalData && !hasDifferentStartOrEndIndex ? prevState.updateId : prevState.updateId + 1;\n return _objectSpread(_objectSpread({\n updateId: newUpdateId\n }, updateStateOfAxisMapsOffsetAndStackGroups(_objectSpread(_objectSpread({\n props: nextProps\n }, prevState), {}, {\n updateId: newUpdateId,\n dataStartIndex: startIndex,\n dataEndIndex: endIndex\n }), prevState)), {}, {\n prevChildren: children,\n dataStartIndex: startIndex,\n dataEndIndex: endIndex\n });\n }\n return null;\n });\n _defineProperty(CategoricalChartWrapper, \"renderActiveDot\", function (option, props, key) {\n var dot;\n if ( /*#__PURE__*/isValidElement(option)) {\n dot = /*#__PURE__*/cloneElement(option, props);\n } else if (isFunction(option)) {\n dot = option(props);\n } else {\n dot = /*#__PURE__*/React.createElement(Dot, props);\n }\n return /*#__PURE__*/React.createElement(Layer, {\n className: \"recharts-active-dot\",\n key: key\n }, dot);\n });\n var CategoricalChart = /*#__PURE__*/forwardRef(function CategoricalChart(props, ref) {\n return /*#__PURE__*/React.createElement(CategoricalChartWrapper, _extends({}, props, {\n ref: ref\n }));\n });\n CategoricalChart.displayName = CategoricalChartWrapper.displayName;\n return CategoricalChart;\n};", "function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nimport { ReferenceDot } from '../cartesian/ReferenceDot';\nimport { ReferenceLine } from '../cartesian/ReferenceLine';\nimport { ReferenceArea } from '../cartesian/ReferenceArea';\nimport { ifOverflowMatches } from './IfOverflowMatches';\nimport { findAllByType } from './ReactUtils';\nimport { isNumber } from './DataUtils';\nexport var detectReferenceElementsDomain = function detectReferenceElementsDomain(children, domain, axisId, axisType, specifiedTicks) {\n var lines = findAllByType(children, ReferenceLine);\n var dots = findAllByType(children, ReferenceDot);\n var elements = [].concat(_toConsumableArray(lines), _toConsumableArray(dots));\n var areas = findAllByType(children, ReferenceArea);\n var idKey = \"\".concat(axisType, \"Id\");\n var valueKey = axisType[0];\n var finalDomain = domain;\n if (elements.length) {\n finalDomain = elements.reduce(function (result, el) {\n if (el.props[idKey] === axisId && ifOverflowMatches(el.props, 'extendDomain') && isNumber(el.props[valueKey])) {\n var value = el.props[valueKey];\n return [Math.min(result[0], value), Math.max(result[1], value)];\n }\n return result;\n }, finalDomain);\n }\n if (areas.length) {\n var key1 = \"\".concat(valueKey, \"1\");\n var key2 = \"\".concat(valueKey, \"2\");\n finalDomain = areas.reduce(function (result, el) {\n if (el.props[idKey] === axisId && ifOverflowMatches(el.props, 'extendDomain') && isNumber(el.props[key1]) && isNumber(el.props[key2])) {\n var value1 = el.props[key1];\n var value2 = el.props[key2];\n return [Math.min(result[0], value1, value2), Math.max(result[1], value1, value2)];\n }\n return result;\n }, finalDomain);\n }\n if (specifiedTicks && specifiedTicks.length) {\n finalDomain = specifiedTicks.reduce(function (result, tick) {\n if (isNumber(tick)) {\n return [Math.min(result[0], tick), Math.max(result[1], tick)];\n }\n return result;\n }, finalDomain);\n }\n return finalDomain;\n};", "import EventEmitter from 'eventemitter3';\nvar eventCenter = new EventEmitter();\nexport { eventCenter };\nexport var SYNC_EVENT = 'recharts.syncMouseEvents';", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nexport var AccessibilityManager = /*#__PURE__*/function () {\n function AccessibilityManager() {\n _classCallCheck(this, AccessibilityManager);\n _defineProperty(this, \"activeIndex\", 0);\n _defineProperty(this, \"coordinateList\", []);\n _defineProperty(this, \"layout\", 'horizontal');\n }\n return _createClass(AccessibilityManager, [{\n key: \"setDetails\",\n value: function setDetails(_ref) {\n var _ref2;\n var _ref$coordinateList = _ref.coordinateList,\n coordinateList = _ref$coordinateList === void 0 ? null : _ref$coordinateList,\n _ref$container = _ref.container,\n container = _ref$container === void 0 ? null : _ref$container,\n _ref$layout = _ref.layout,\n layout = _ref$layout === void 0 ? null : _ref$layout,\n _ref$offset = _ref.offset,\n offset = _ref$offset === void 0 ? null : _ref$offset,\n _ref$mouseHandlerCall = _ref.mouseHandlerCallback,\n mouseHandlerCallback = _ref$mouseHandlerCall === void 0 ? null : _ref$mouseHandlerCall;\n this.coordinateList = (_ref2 = coordinateList !== null && coordinateList !== void 0 ? coordinateList : this.coordinateList) !== null && _ref2 !== void 0 ? _ref2 : [];\n this.container = container !== null && container !== void 0 ? container : this.container;\n this.layout = layout !== null && layout !== void 0 ? layout : this.layout;\n this.offset = offset !== null && offset !== void 0 ? offset : this.offset;\n this.mouseHandlerCallback = mouseHandlerCallback !== null && mouseHandlerCallback !== void 0 ? mouseHandlerCallback : this.mouseHandlerCallback;\n\n // Keep activeIndex in the bounds between 0 and the last coordinate index\n this.activeIndex = Math.min(Math.max(this.activeIndex, 0), this.coordinateList.length - 1);\n }\n }, {\n key: \"focus\",\n value: function focus() {\n this.spoofMouse();\n }\n }, {\n key: \"keyboardEvent\",\n value: function keyboardEvent(e) {\n // The AccessibilityManager relies on the Tooltip component. When tooltips suddenly stop existing,\n // it can cause errors. We use this function to check. We don't want arrow keys to be processed\n // if there are no tooltips, since that will cause unexpected behavior of users.\n if (this.coordinateList.length === 0) {\n return;\n }\n switch (e.key) {\n case 'ArrowRight':\n {\n if (this.layout !== 'horizontal') {\n return;\n }\n this.activeIndex = Math.min(this.activeIndex + 1, this.coordinateList.length - 1);\n this.spoofMouse();\n break;\n }\n case 'ArrowLeft':\n {\n if (this.layout !== 'horizontal') {\n return;\n }\n this.activeIndex = Math.max(this.activeIndex - 1, 0);\n this.spoofMouse();\n break;\n }\n default:\n {\n break;\n }\n }\n }\n }, {\n key: \"setIndex\",\n value: function setIndex(newIndex) {\n this.activeIndex = newIndex;\n }\n }, {\n key: \"spoofMouse\",\n value: function spoofMouse() {\n var _window, _window2;\n if (this.layout !== 'horizontal') {\n return;\n }\n\n // This can happen when the tooltips suddenly stop existing as children of the component\n // That update doesn't otherwise fire events, so we have to double check here.\n if (this.coordinateList.length === 0) {\n return;\n }\n var _this$container$getBo = this.container.getBoundingClientRect(),\n x = _this$container$getBo.x,\n y = _this$container$getBo.y,\n height = _this$container$getBo.height;\n var coordinate = this.coordinateList[this.activeIndex].coordinate;\n var scrollOffsetX = ((_window = window) === null || _window === void 0 ? void 0 : _window.scrollX) || 0;\n var scrollOffsetY = ((_window2 = window) === null || _window2 === void 0 ? void 0 : _window2.scrollY) || 0;\n var pageX = x + coordinate + scrollOffsetX;\n var pageY = y + this.offset.top + height / 2 + scrollOffsetY;\n this.mouseHandlerCallback({\n pageX: pageX,\n pageY: pageY\n });\n }\n }]);\n}();", "import { isNumber } from './DataUtils';\n/**\n * Takes a domain and user props to determine whether he provided the domain via props or if we need to calculate it.\n * @param {AxisDomain} domain The potential domain from props\n * @param {Boolean} allowDataOverflow from props\n * @param {String} axisType from props\n * @returns {Boolean} `true` if domain is specified by user\n */\nexport function isDomainSpecifiedByUser(domain, allowDataOverflow, axisType) {\n if (axisType === 'number' && allowDataOverflow === true && Array.isArray(domain)) {\n var domainStart = domain === null || domain === void 0 ? void 0 : domain[0];\n var domainEnd = domain === null || domain === void 0 ? void 0 : domain[1];\n\n /*\n * The `isNumber` check is needed because the user could also provide strings like \"dataMin\" via the domain props.\n * In such case, we have to compute the domain from the data.\n */\n if (!!domainStart && !!domainEnd && isNumber(domainStart) && isNumber(domainEnd)) {\n return true;\n }\n }\n return false;\n}", "function _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nimport { cloneElement, createElement, isValidElement } from 'react';\nimport clsx from 'clsx';\nimport { Curve } from '../shape/Curve';\nimport { Cross } from '../shape/Cross';\nimport { getCursorRectangle } from '../util/cursor/getCursorRectangle';\nimport { Rectangle } from '../shape/Rectangle';\nimport { getRadialCursorPoints } from '../util/cursor/getRadialCursorPoints';\nimport { Sector } from '../shape/Sector';\nimport { getCursorPoints } from '../util/cursor/getCursorPoints';\nimport { filterProps } from '../util/ReactUtils';\n/*\n * Cursor is the background, or a highlight,\n * that shows when user mouses over or activates\n * an area.\n *\n * It usually shows together with a tooltip\n * to emphasise which part of the chart does the tooltip refer to.\n */\nexport function Cursor(props) {\n var _element$props$cursor, _defaultProps;\n var element = props.element,\n tooltipEventType = props.tooltipEventType,\n isActive = props.isActive,\n activeCoordinate = props.activeCoordinate,\n activePayload = props.activePayload,\n offset = props.offset,\n activeTooltipIndex = props.activeTooltipIndex,\n tooltipAxisBandSize = props.tooltipAxisBandSize,\n layout = props.layout,\n chartName = props.chartName;\n var elementPropsCursor = (_element$props$cursor = element.props.cursor) !== null && _element$props$cursor !== void 0 ? _element$props$cursor : (_defaultProps = element.type.defaultProps) === null || _defaultProps === void 0 ? void 0 : _defaultProps.cursor;\n if (!element || !elementPropsCursor || !isActive || !activeCoordinate || chartName !== 'ScatterChart' && tooltipEventType !== 'axis') {\n return null;\n }\n var restProps;\n var cursorComp = Curve;\n if (chartName === 'ScatterChart') {\n restProps = activeCoordinate;\n cursorComp = Cross;\n } else if (chartName === 'BarChart') {\n restProps = getCursorRectangle(layout, activeCoordinate, offset, tooltipAxisBandSize);\n cursorComp = Rectangle;\n } else if (layout === 'radial') {\n var _getRadialCursorPoint = getRadialCursorPoints(activeCoordinate),\n cx = _getRadialCursorPoint.cx,\n cy = _getRadialCursorPoint.cy,\n radius = _getRadialCursorPoint.radius,\n startAngle = _getRadialCursorPoint.startAngle,\n endAngle = _getRadialCursorPoint.endAngle;\n restProps = {\n cx: cx,\n cy: cy,\n startAngle: startAngle,\n endAngle: endAngle,\n innerRadius: radius,\n outerRadius: radius\n };\n cursorComp = Sector;\n } else {\n restProps = {\n points: getCursorPoints(layout, activeCoordinate, offset)\n };\n cursorComp = Curve;\n }\n var cursorProps = _objectSpread(_objectSpread(_objectSpread(_objectSpread({\n stroke: '#ccc',\n pointerEvents: 'none'\n }, offset), restProps), filterProps(elementPropsCursor, false)), {}, {\n payload: activePayload,\n payloadIndex: activeTooltipIndex,\n className: clsx('recharts-tooltip-cursor', elementPropsCursor.className)\n });\n return /*#__PURE__*/isValidElement(elementPropsCursor) ? /*#__PURE__*/cloneElement(elementPropsCursor, cursorProps) : /*#__PURE__*/createElement(cursorComp, cursorProps);\n}", "export function getCursorRectangle(layout, activeCoordinate, offset, tooltipAxisBandSize) {\n var halfSize = tooltipAxisBandSize / 2;\n return {\n stroke: 'none',\n fill: '#ccc',\n x: layout === 'horizontal' ? activeCoordinate.x - halfSize : offset.left + 0.5,\n y: layout === 'horizontal' ? offset.top + 0.5 : activeCoordinate.y - halfSize,\n width: layout === 'horizontal' ? tooltipAxisBandSize : offset.width - 1,\n height: layout === 'horizontal' ? offset.height - 1 : tooltipAxisBandSize\n };\n}", "import { polarToCartesian } from '../PolarUtils';\n/**\n * Only applicable for radial layouts\n * @param {Object} activeCoordinate ChartCoordinate\n * @returns {Object} RadialCursorPoints\n */\nexport function getRadialCursorPoints(activeCoordinate) {\n var cx = activeCoordinate.cx,\n cy = activeCoordinate.cy,\n radius = activeCoordinate.radius,\n startAngle = activeCoordinate.startAngle,\n endAngle = activeCoordinate.endAngle;\n var startPoint = polarToCartesian(cx, cy, radius, startAngle);\n var endPoint = polarToCartesian(cx, cy, radius, endAngle);\n return {\n points: [startPoint, endPoint],\n cx: cx,\n cy: cy,\n radius: radius,\n startAngle: startAngle,\n endAngle: endAngle\n };\n}", "import { polarToCartesian } from '../PolarUtils';\nimport { getRadialCursorPoints } from './getRadialCursorPoints';\nexport function getCursorPoints(layout, activeCoordinate, offset) {\n var x1, y1, x2, y2;\n if (layout === 'horizontal') {\n x1 = activeCoordinate.x;\n x2 = x1;\n y1 = offset.top;\n y2 = offset.top + offset.height;\n } else if (layout === 'vertical') {\n y1 = activeCoordinate.y;\n y2 = y1;\n x1 = offset.left;\n x2 = offset.left + offset.width;\n } else if (activeCoordinate.cx != null && activeCoordinate.cy != null) {\n if (layout === 'centric') {\n var cx = activeCoordinate.cx,\n cy = activeCoordinate.cy,\n innerRadius = activeCoordinate.innerRadius,\n outerRadius = activeCoordinate.outerRadius,\n angle = activeCoordinate.angle;\n var innerPoint = polarToCartesian(cx, cy, innerRadius, angle);\n var outerPoint = polarToCartesian(cx, cy, outerRadius, angle);\n x1 = innerPoint.x;\n y1 = innerPoint.y;\n x2 = outerPoint.x;\n y2 = outerPoint.y;\n } else {\n return getRadialCursorPoints(activeCoordinate);\n }\n }\n return [{\n x: x1,\n y: y1\n }, {\n x: x2,\n y: y2\n }];\n}", "/**\n * @fileOverview Line Chart\n */\nimport { generateCategoricalChart } from './generateCategoricalChart';\nimport { Line } from '../cartesian/Line';\nimport { XAxis } from '../cartesian/XAxis';\nimport { YAxis } from '../cartesian/YAxis';\nimport { formatAxisMap } from '../util/CartesianUtils';\nexport var LineChart = generateCategoricalChart({\n chartName: 'LineChart',\n GraphicalChild: Line,\n axisComponents: [{\n axisType: 'xAxis',\n AxisComp: XAxis\n }, {\n axisType: 'yAxis',\n AxisComp: YAxis\n }],\n formatAxisMap: formatAxisMap\n});", "/**\n * @fileOverview Bar Chart\n */\nimport { generateCategoricalChart } from './generateCategoricalChart';\nimport { Bar } from '../cartesian/Bar';\nimport { XAxis } from '../cartesian/XAxis';\nimport { YAxis } from '../cartesian/YAxis';\nimport { formatAxisMap } from '../util/CartesianUtils';\nexport var BarChart = generateCategoricalChart({\n chartName: 'BarChart',\n GraphicalChild: Bar,\n defaultTooltipEventType: 'axis',\n validateTooltipEventTypes: ['axis', 'item'],\n axisComponents: [{\n axisType: 'xAxis',\n AxisComp: XAxis\n }, {\n axisType: 'yAxis',\n AxisComp: YAxis\n }],\n formatAxisMap: formatAxisMap\n});", "/**\n * @fileOverview Pie Chart\n */\nimport { generateCategoricalChart } from './generateCategoricalChart';\nimport { PolarAngleAxis } from '../polar/PolarAngleAxis';\nimport { PolarRadiusAxis } from '../polar/PolarRadiusAxis';\nimport { formatAxisMap } from '../util/PolarUtils';\nimport { Pie } from '../polar/Pie';\nexport var PieChart = generateCategoricalChart({\n chartName: 'PieChart',\n GraphicalChild: Pie,\n validateTooltipEventTypes: ['item'],\n defaultTooltipEventType: 'item',\n legendContent: 'children',\n axisComponents: [{\n axisType: 'angleAxis',\n AxisComp: PolarAngleAxis\n }, {\n axisType: 'radiusAxis',\n AxisComp: PolarRadiusAxis\n }],\n formatAxisMap: formatAxisMap,\n defaultProps: {\n layout: 'centric',\n startAngle: 0,\n endAngle: 360,\n cx: '50%',\n cy: '50%',\n innerRadius: 0,\n outerRadius: '80%'\n }\n});", "/**\n * @fileOverview Area Chart\n */\nimport { generateCategoricalChart } from './generateCategoricalChart';\nimport { Area } from '../cartesian/Area';\nimport { XAxis } from '../cartesian/XAxis';\nimport { YAxis } from '../cartesian/YAxis';\nimport { formatAxisMap } from '../util/CartesianUtils';\nexport var AreaChart = generateCategoricalChart({\n chartName: 'AreaChart',\n GraphicalChild: Area,\n axisComponents: [{\n axisType: 'xAxis',\n AxisComp: XAxis\n }, {\n axisType: 'yAxis',\n AxisComp: YAxis\n }],\n formatAxisMap: formatAxisMap\n});", "import React, { useState, useEffect } from 'react';\n\nconst Prompts = () => {\n // Extended Nike-related prompts data - 30 items total for 3 pages\n const allPromptsData = [\n // Original 10 prompts\n {\n id: 1,\n name: \"Are Nike Air Max good for running or just for style?\",\n template: \"Describe the key features of Nike [product_name], highlighting its performance benefits, materials, and technology.\",\n category: \"Product Information\",\n platform: \"All\",\n performance: \"High\",\n lastModified: \"Apr 2, 2025\"\n },\n {\n id: 2,\n name: \"Nike Pegasus vs Adidas Ultraboost - which is better for everyday running?\",\n template: \"Compare Nike [product_name] with similar products from Adidas and Under Armour, focusing on unique selling points.\",\n category: \"Competitive Analysis\",\n platform: \"ChatGPT\",\n performance: \"Medium\",\n lastModified: \"Apr 3, 2025\"\n },\n {\n id: 3,\n name: \"Is Nike actually eco-friendly or is it all marketing?\",\n template: \"Explain how Nike's [product_name] demonstrates the company's commitment to sustainability through materials and manufacturing process.\",\n category: \"Brand Values\",\n platform: \"Claude\",\n performance: \"High\",\n lastModified: \"Mar 28, 2025\"\n },\n {\n id: 4,\n name: \"Will Nike Metcons help me lift heavier weights?\",\n template: \"Describe how Nike [product_name] can improve athletic performance for [sport_type] athletes.\",\n category: \"Benefits\",\n platform: \"Perplexity\",\n performance: \"High\",\n lastModified: \"Apr 5, 2025\"\n },\n {\n id: 5,\n name: \"Why are Nike Dunks so popular right now?\",\n template: \"Analyze top customer feedback points about Nike [product_name] and provide a balanced summary of strengths and areas for improvement.\",\n category: \"Customer Insights\",\n platform: \"Gemini\",\n performance: \"Medium\",\n lastModified: \"Apr 1, 2025\"\n },\n {\n id: 6,\n name: \"Do Nike shoes run small? I wear 10 in Adidas but not sure for Nike\",\n template: \"Provide a detailed sizing guide for Nike [product_name], including how sizes compare to other brands and fit recommendations.\",\n category: \"Product Information\",\n platform: \"All\",\n performance: \"Medium\",\n lastModified: \"Mar 25, 2025\"\n },\n {\n id: 7,\n name: \"How have Air Jordans changed over the years?\",\n template: \"Create a timeline showing the evolution of Nike [product_line], highlighting key innovations and design changes.\",\n category: \"Brand Heritage\",\n platform: \"Claude\",\n performance: \"Low\",\n lastModified: \"Mar 30, 2025\"\n },\n {\n id: 8,\n name: \"How much does LeBron make from Nike? Is it his biggest deal?\",\n template: \"Describe the partnership between [athlete_name] and Nike, explaining why they chose to endorse [product_name].\",\n category: \"Marketing\",\n platform: \"ChatGPT\",\n performance: \"High\",\n lastModified: \"Apr 4, 2025\"\n },\n {\n id: 9,\n name: \"Where can I get those Nike x Dior sneakers? Are they sold out everywhere?\",\n template: \"Provide details about Nike's limited edition [collection_name], including design inspiration, availability, and special features.\",\n category: \"Product Information\",\n platform: \"Perplexity\",\n performance: \"Medium\",\n lastModified: \"Mar 27, 2025\"\n },\n {\n id: 10,\n name: \"My white Air Force 1s are dirty. How do I clean them?\",\n template: \"Offer step-by-step instructions for properly cleaning and maintaining Nike [product_name] to extend its lifespan.\",\n category: \"Customer Support\",\n platform: \"All\",\n performance: \"Medium\",\n lastModified: \"Apr 6, 2025\"\n },\n\n // Additional 20 prompts (for pages 2 and 3)\n {\n id: 11,\n name: \"What Nikes should I buy for my first marathon?\",\n template: \"Recommend the best Nike shoes for [sport_type], explaining why each feature is beneficial for this activity.\",\n category: \"Product Recommendation\",\n platform: \"ChatGPT\",\n performance: \"High\",\n lastModified: \"Mar 22, 2025\"\n },\n {\n id: 12,\n name: \"What's the deal with Nike Air? Is it actually air in the sole?\",\n template: \"Explain Nike's [technology_name] technology in simple terms, describing how it works and benefits the wearer.\",\n category: \"Product Information\",\n platform: \"Claude\",\n performance: \"High\",\n lastModified: \"Apr 1, 2025\"\n },\n {\n id: 13,\n name: \"Are Nike running shoes worth the extra money over cheaper brands?\",\n template: \"Analyze whether Nike [product_name] provides good value for its price point compared to market alternatives.\",\n category: \"Competitive Analysis\",\n platform: \"Perplexity\",\n performance: \"Medium\",\n lastModified: \"Mar 29, 2025\"\n },\n {\n id: 14,\n name: \"What should I wear with my red Nike Air Max 90s?\",\n template: \"Suggest outfit combinations that would pair well with Nike [product_name] for [casual/athletic/formal] settings.\",\n category: \"Style Guide\",\n platform: \"Gemini\",\n performance: \"Medium\",\n lastModified: \"Apr 3, 2025\"\n },\n {\n id: 15,\n name: \"Are Nike shoes still made in sweatshops?\",\n template: \"Describe the manufacturing process of Nike [product_name], highlighting quality control measures and craftsmanship.\",\n category: \"Product Information\",\n platform: \"Claude\",\n performance: \"Low\",\n lastModified: \"Mar 24, 2025\"\n },\n {\n id: 16,\n name: \"What Nikes was Drake wearing in his last Instagram post?\",\n template: \"List recent sightings of celebrities wearing Nike [product_name] and describe how they styled them.\",\n category: \"Marketing\",\n platform: \"All\",\n performance: \"High\",\n lastModified: \"Apr 5, 2025\"\n },\n {\n id: 17,\n name: \"How long do Nike Blazers last with everyday wear?\",\n template: \"Evaluate the durability of Nike [product_name] based on materials, construction, and user reports.\",\n category: \"Product Quality\",\n platform: \"ChatGPT\",\n performance: \"Medium\",\n lastModified: \"Mar 31, 2025\"\n },\n {\n id: 18,\n name: \"Why did Nike pick these weird colors for their new collection?\",\n template: \"Explain the psychological impact of the color choices in Nike's [collection_name] and how they relate to the brand message.\",\n category: \"Brand Values\",\n platform: \"Claude\",\n performance: \"Medium\",\n lastModified: \"Apr 2, 2025\"\n },\n {\n id: 19,\n name: \"What's new in Nike's summer lineup this year?\",\n template: \"Summarize the key themes and standout pieces from Nike's [season/year] collection.\",\n category: \"Product Information\",\n platform: \"Perplexity\",\n performance: \"High\",\n lastModified: \"Mar 28, 2025\"\n },\n {\n id: 20,\n name: \"Did Nike really invent the waffle sole by pouring rubber in a waffle iron?\",\n template: \"Trace the history of Nike's innovations in [material_type] and how they've influenced the industry.\",\n category: \"Brand Heritage\",\n platform: \"All\",\n performance: \"Medium\",\n lastModified: \"Apr 4, 2025\"\n },\n {\n id: 21,\n name: \"Why did Nike team up with Travis Scott? Aren't his shoes just regular Nikes?\",\n template: \"Detail the creative process behind Nike's collaboration with [designer/brand] and what makes it unique.\",\n category: \"Marketing\",\n platform: \"ChatGPT\",\n performance: \"High\",\n lastModified: \"Mar 26, 2025\"\n },\n {\n id: 22,\n name: \"When did Air Force 1s become so popular in hip hop?\",\n template: \"Analyze how Nike [product_line] has influenced street culture and fashion trends since its introduction.\",\n category: \"Brand Impact\",\n platform: \"Claude\",\n performance: \"Medium\",\n lastModified: \"Apr 1, 2025\"\n },\n {\n id: 23,\n name: \"I overpronate when I run. Which Nikes should I get?\",\n template: \"Explain which Nike running shoes are best for [pronation_type] runners and why their features help with this gait pattern.\",\n category: \"Technical Advisory\",\n platform: \"Perplexity\",\n performance: \"High\",\n lastModified: \"Mar 27, 2025\"\n },\n {\n id: 24,\n name: \"Is Nike React better than Adidas Boost for running?\",\n template: \"Compare Nike's [technology_name] with similar technologies from competitors, highlighting differences in approach and effectiveness.\",\n category: \"Competitive Analysis\",\n platform: \"All\",\n performance: \"Medium\",\n lastModified: \"Apr 3, 2025\"\n },\n {\n id: 25,\n name: \"Is Nike really sustainable or just greenwashing?\",\n template: \"Assess Nike's progress toward its sustainability goals, highlighting successes and areas for improvement.\",\n category: \"Brand Values\",\n platform: \"Gemini\",\n performance: \"Low\",\n lastModified: \"Mar 29, 2025\"\n },\n {\n id: 26,\n name: \"Can I design my own Nikes? How does that work?\",\n template: \"Explain the customization options available for Nike [product_name] through Nike By You, including materials, colors, and personalization.\",\n category: \"Product Information\",\n platform: \"ChatGPT\",\n performance: \"High\",\n lastModified: \"Apr 5, 2025\"\n },\n {\n id: 27,\n name: \"Did Nike invent basketball shoes or were they around before?\",\n template: \"Describe how Nike's [product_line] has evolved alongside the development of [sport_type] and influenced the game.\",\n category: \"Brand Heritage\",\n platform: \"Claude\",\n performance: \"Medium\",\n lastModified: \"Mar 23, 2025\"\n },\n {\n id: 28,\n name: \"Why are Jordans so expensive now compared to the 90s?\",\n template: \"Analyze how the pricing of Nike [product_line] has changed over time and what factors have influenced these changes.\",\n category: \"Market Analysis\",\n platform: \"Perplexity\",\n performance: \"Medium\",\n lastModified: \"Apr 2, 2025\"\n },\n {\n id: 29,\n name: \"What's Nike coming out with next? Any leaks about new releases?\",\n template: \"Based on Nike's product development patterns, predict what innovations might be featured in the next [product_line] release.\",\n category: \"Trend Analysis\",\n platform: \"All\",\n performance: \"Low\",\n lastModified: \"Mar 30, 2025\"\n },\n {\n id: 30,\n name: \"Why do people pay thousands for old Nikes on StockX?\",\n template: \"Analyze the resale value trends of Nike [product_name] in secondary markets and what drives their collectibility.\",\n category: \"Market Analysis\",\n platform: \"ChatGPT\",\n performance: \"High\",\n lastModified: \"Apr 6, 2025\"\n }\n ];\n\n // Pagination state\n const [currentPage, setCurrentPage] = useState(1);\n const [itemsPerPage] = useState(10);\n\n // Filter and search state\n const [searchTerm, setSearchTerm] = useState('');\n const [platformFilter, setPlatformFilter] = useState('All');\n const [filteredPrompts, setFilteredPrompts] = useState([]);\n const [totalPages, setTotalPages] = useState(0);\n const [displayedPrompts, setDisplayedPrompts] = useState([]);\n\n // Get unique categories for filter dropdown\n const platforms = ['All', 'ChatGPT', 'Claude', 'Perplexity', 'Gemini'];\n\n // Filter prompts based on search and filters\n useEffect(() => {\n const filtered = allPromptsData.filter(prompt => {\n const matchesSearch = searchTerm === '' ||\n prompt.name.toLowerCase().includes(searchTerm.toLowerCase()) ||\n prompt.template.toLowerCase().includes(searchTerm.toLowerCase());\n const matchesPlatform = platformFilter === 'All' || prompt.platform === platformFilter || prompt.platform === 'All';\n\n return matchesSearch && matchesPlatform;\n });\n\n setFilteredPrompts(filtered);\n setTotalPages(Math.ceil(filtered.length / itemsPerPage));\n setCurrentPage(1); // Reset to first page when filters change\n }, [searchTerm, platformFilter, itemsPerPage]);\n\n // Update displayed prompts when page or filtered results change\n useEffect(() => {\n const indexOfLastItem = currentPage * itemsPerPage;\n const indexOfFirstItem = indexOfLastItem - itemsPerPage;\n setDisplayedPrompts(filteredPrompts.slice(indexOfFirstItem, indexOfLastItem));\n }, [currentPage, filteredPrompts, itemsPerPage]);\n\n // Handle page change\n const paginate = (pageNumber) => setCurrentPage(pageNumber);\n\n // Performance indicator component\n const PerformanceIndicator = ({ level }) => {\n const colors = {\n 'High': 'bg-green-500',\n 'Medium': 'bg-yellow-500',\n 'Low': 'bg-red-500'\n };\n\n return (\n
\n
\n {level}\n
\n );\n };\n\n return (\n
\n
\n

Nike Prompt Library

\n
\n\n {/* Search and Filter Controls */}\n
\n
\n
\n setSearchTerm(e.target.value)}\n className=\"pl-10 pr-4 py-2 w-full border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500\"\n />\n \n \n \n
\n
\n\n
\n setPlatformFilter(e.target.value)}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500\"\n >\n {platforms.map((platform, index) => (\n \n ))}\n \n
\n
\n\n {/* Prompts Table */}\n
\n \n \n \n \n \n \n \n \n \n \n {displayedPrompts.map((prompt) => (\n \n \n \n \n \n \n ))}\n \n
\n Prompt\n \n Category\n \n Performance\n \n Last Modified\n
\n
{prompt.name}
\n
\n \n {prompt.category}\n \n \n \n \n {prompt.lastModified}\n
\n
\n\n {/* Pagination and Results Summary */}\n
\n
\n Showing 1 to 10 of 742 prompts\n
\n\n
\n \n
\n
\n
\n );\n};\n\nexport default Prompts;", "import React, { useState, useContext, useEffect } from 'react';\n\nconst CompetitorAnalysis = () => {\n // Dummy data for Nike and competitors\n const competitors = [\n {\n id: 1,\n name: \"Adidas\",\n shareOfVoice: 28,\n strengths: [\n \"Strong presence in football/soccer\",\n \"Successful collaborations with designers\",\n \"Sustainability initiatives\"\n ],\n weaknesses: [\n \"Less dominant in basketball compared to Nike\",\n \"Slower product innovation cycles\",\n \"Weaker presence in North American market\"\n ]\n },\n {\n id: 2,\n name: \"Under Armour\",\n shareOfVoice: 14,\n strengths: [\n \"Performance-focused technology\",\n \"Strong in team sports and training gear\",\n \"Growing digital fitness ecosystem\"\n ],\n weaknesses: [\n \"Limited fashion appeal and streetwear presence\",\n \"Smaller global footprint\",\n \"Less celebrity endorsements\"\n ]\n },\n {\n id: 3,\n name: \"Puma\",\n shareOfVoice: 12,\n strengths: [\n \"Growing lifestyle and fashion appeal\",\n \"Celebrity partnerships (Rihanna, etc.)\",\n \"Speed to market with trends\"\n ],\n weaknesses: [\n \"Smaller R&D budget\",\n \"Less technical innovation in performance wear\",\n \"Lower brand value perception\"\n ]\n },\n {\n id: 4,\n name: \"New Balance\",\n shareOfVoice: 9,\n strengths: [\n \"Strong running shoe reputation\",\n \"Made in USA credentials\",\n \"Growing appeal in lifestyle segment\"\n ],\n weaknesses: [\n \"Limited presence in team sports\",\n \"Less global recognition\",\n \"Weaker digital marketing strategy\"\n ]\n },\n {\n id: 5,\n name: \"Reebok\",\n shareOfVoice: 7,\n strengths: [\n \"Strong in CrossFit and fitness categories\",\n \"Heritage designs with retro appeal\",\n \"Price point advantage\"\n ],\n weaknesses: [\n \"Brand identity challenges\",\n \"Reduced market share over time\",\n \"Limited premium product offering\"\n ]\n }\n ];\n\n // Share of Voice data over time (6 months)\n const shareOfVoiceData = [\n { month: \"Jan\", Nike: 35, Adidas: 25, \"Under Armour\": 12, Puma: 10, \"New Balance\": 8, Reebok: 6, Others: 4 },\n { month: \"Feb\", Nike: 34, Adidas: 26, \"Under Armour\": 13, Puma: 11, \"New Balance\": 8, Reebok: 5, Others: 3 },\n { month: \"Mar\", Nike: 36, Adidas: 27, \"Under Armour\": 13, Puma: 11, \"New Balance\": 7, Reebok: 5, Others: 1 },\n { month: \"Apr\", Nike: 37, Adidas: 28, \"Under Armour\": 14, Puma: 10, \"New Balance\": 8, Reebok: 6, Others: 3 },\n { month: \"May\", Nike: 36, Adidas: 27, \"Under Armour\": 14, Puma: 12, \"New Balance\": 8, Reebok: 7, Others: 2 },\n { month: \"Jun\", Nike: 38, Adidas: 28, \"Under Armour\": 14, Puma: 12, \"New Balance\": 9, Reebok: 7, Others: 2 }\n ];\n\n // Color scheme for brands\n const brandColors = {\n Nike: \"#F82C00\",\n Adidas: \"#332FD0\",\n \"Under Armour\": \"#1F1D36\",\n Puma: \"#FE7A36\",\n \"New Balance\": \"#6499E9\",\n Reebok: \"#9ADE7B\",\n Others: \"#CCCCCC\"\n };\n\n return (\n
\n

Competitor Analysis

\n\n {/* Share of Voice Graph */}\n
\n

Share of Voice - Athletic Apparel Market

\n
\n
\n {/* Graph container - removing the title text that was in the middle */}\n
\n {/* Y-axis labels */}\n
\n 40%\n 30%\n 20%\n 10%\n 0%\n
\n\n {/* Grid lines */}\n
\n
\n
\n
\n
\n
\n
\n\n {/* X-axis labels */}\n
\n {shareOfVoiceData.map((data, index) => (\n {data.month}\n ))}\n
\n\n {/* Line chart with fixed viewBox parameters */}\n
\n {/* Nike line */}\n \n \n \n\n {/* Adidas line */}\n \n \n \n\n {/* Under Armour line */}\n \n \n \n\n {/* Puma line */}\n \n \n \n\n {/* New Balance line */}\n \n \n \n\n {/* Reebok line */}\n \n \n \n
\n
\n
\n\n {/* Legend */}\n
\n
\n
\n Nike\n
\n
\n
\n Adidas\n
\n
\n
\n Under Armour\n
\n
\n
\n Puma\n
\n
\n
\n New Balance\n
\n
\n
\n Reebok\n
\n
\n
\n\n {/* Key Insights */}\n
\n

Key Insights:

\n
    \n
  • \u2022 Nike maintains dominant position with more than 35% share of voice
  • \n
  • \u2022 Adidas shows steady growth in the last quarter
  • \n
  • \u2022 Under Armour and Puma are holding steady
  • \n
  • \u2022 New Balance shows slight growth in recent months
  • \n
\n
\n
\n\n {/* Competitors Table */}\n
\n

Competitor Breakdown

\n
\n \n \n \n \n \n \n \n \n \n \n {/* Nike (You) */}\n \n \n \n \n \n \n\n {/* Competitors */}\n {competitors.map((competitor) => (\n \n \n \n \n \n \n ))}\n \n
\n Competitor\n \n Share of Voice\n \n Strengths\n \n Weaknesses\n
\n
\n
\n N\n
\n
\n
Nike (You)
\n
\n
\n
\n
38%
\n
\n
\n
\n
\n
    \n
  • Industry-leading brand recognition
  • \n
  • Superior athlete endorsements
  • \n
  • Innovation in product design
  • \n
\n
\n
    \n
  • Premium pricing limits market reach
  • \n
  • Supply chain vulnerabilities
  • \n
  • Slower in sustainability adoption
  • \n
\n
\n
\n \n \n {competitor.name.charAt(0)}\n \n
\n
\n
{competitor.name}
\n
\n \n
\n
{competitor.shareOfVoice}%
\n
\n
\n \n
\n
    \n {competitor.strengths.map((strength, idx) => (\n
  • {strength}
  • \n ))}\n
\n
\n
    \n {competitor.weaknesses.map((weakness, idx) => (\n
  • {weakness}
  • \n ))}\n
\n
\n
\n
\n
\n );\n};\n\nexport default CompetitorAnalysis;", "import React, { useState, useContext, useEffect } from 'react';\n\nconst Optimization = () => {\n // Strategy categories\n const strategyCategories = [\n {\n id: 'content',\n name: 'Content Strategy',\n description: 'Optimize content to increase visibility in AI responses',\n score: 68,\n recommendations: [\n {\n id: 1,\n title: 'Create Structured Product Data',\n description: 'Develop structured data for all products with consistent specifications, features, and benefits in standardized formats that are easily parsed by AI systems.',\n impact: 'High',\n effort: 'Medium',\n examples: [\n 'Create detailed product schema markup for all product pages',\n 'Develop standardized attribute tables that list materials, technologies, and performance benefits'\n ]\n },\n {\n id: 2,\n title: 'Build AI-Ready FAQ Knowledge Base',\n description: 'Develop comprehensive FAQ content using natural question formats that match how consumers ask about products.',\n impact: 'High',\n effort: 'Medium',\n examples: [\n 'Create question-specific pages for \"Are Nike shoes good for running?\"',\n 'Build comparison content explicitly addressing \"Nike vs Adidas for basketball\"'\n ]\n },\n {\n id: 3,\n title: 'Enhance Technical Information Depth',\n description: 'Provide more detailed technical information about proprietary technologies and performance features.',\n impact: 'Medium',\n effort: 'Medium',\n examples: [\n 'Create dedicated pages explaining Nike Air, Flyknit, and other technologies',\n 'Include specific performance metrics and testing data when available'\n ]\n }\n ]\n },\n {\n id: 'comparison',\n name: 'Competitive Positioning',\n description: 'Strengthen competitive position in AI comparisons',\n score: 54,\n recommendations: [\n {\n id: 4,\n title: 'Develop Direct Comparison Resources',\n description: 'Create content that explicitly but fairly compares Nike products to competitors for specific use cases.',\n impact: 'High',\n effort: 'High',\n examples: [\n 'Create \"Nike vs Competitor\" guides for different sports categories',\n 'Publish data on Nike technology advantages with objective metrics'\n ]\n },\n {\n id: 5,\n title: 'Address Competitive Weaknesses',\n description: 'Proactively address common criticisms that appear in AI responses about Nike products.',\n impact: 'Medium',\n effort: 'Low',\n examples: [\n 'Create content addressing price point concerns with value propositions',\n 'Develop materials explaining sustainability initiatives to counter criticisms'\n ]\n }\n ]\n },\n {\n id: 'visibility',\n name: 'AI Training Visibility',\n description: 'Increase Nike content in AI training data',\n score: 76,\n recommendations: [\n {\n id: 6,\n title: 'Publish Authoritative Research',\n description: 'Release research papers, white papers, and studies about sports science, performance, and innovation.',\n impact: 'High',\n effort: 'High',\n examples: [\n 'Publish Nike Sport Research Lab findings on athletic performance',\n 'Release case studies on product development and innovation processes'\n ]\n },\n {\n id: 7,\n title: 'Create Educational Resources',\n description: 'Develop rich educational content about athletic performance that positions Nike as an authority.',\n impact: 'Medium',\n effort: 'Medium',\n examples: [\n 'Create training guides by sport with Nike product integration',\n 'Develop athlete interviews discussing specific Nike product benefits'\n ]\n },\n {\n id: 8,\n title: 'Expand Digital Footprint with Quality Content',\n description: 'Increase the volume of high-quality, original content across multiple platforms to improve training data representation.',\n impact: 'High',\n effort: 'High',\n examples: [\n 'Create a technical blog detailing Nike innovation stories',\n 'Develop video content explaining product features in depth'\n ]\n }\n ]\n },\n {\n id: 'prompts',\n name: 'Strategic AI Prompting',\n description: 'Optimize for consumer AI prompts',\n score: 42,\n recommendations: [\n {\n id: 9,\n title: 'Develop Prompt-Friendly Language',\n description: 'Adjust content to include language patterns that are likely to be referenced when AI systems respond to related queries.',\n impact: 'Medium',\n effort: 'Low',\n examples: [\n 'Include phrases like \"Nike is known for...\" or \"Nike specializes in...\"',\n 'Create content that directly answers common questions'\n ]\n },\n {\n id: 10,\n title: 'Monitor and Adapt to AI Response Patterns',\n description: 'Regularly test how AI systems respond to queries about Nike and adjust content strategy accordingly.',\n impact: 'High',\n effort: 'Medium',\n examples: [\n 'Create a testing program for major AI platforms (ChatGPT, Claude, etc.)',\n 'Develop metrics for measuring Nike presence in AI responses'\n ]\n }\n ]\n }\n ];\n\n // State for active category\n const [activeCategory, setActiveCategory] = useState('content');\n\n // Get active category data\n const activeCategoryData = strategyCategories.find(category => category.id === activeCategory);\n\n return (\n
\n

AI Content Optimization

\n

Strategic recommendations to improve Nike's visibility and positive mentions in AI responses.

\n\n {/* Summary Stats */}\n
\n {strategyCategories.map(category => (\n setActiveCategory(category.id)}\n >\n

{category.name}

\n
\n
{category.description}
\n
= 70 ? 'text-green-600' :\n category.score >= 50 ? 'text-yellow-600' :\n 'text-red-600'\n }`}>\n {category.score}/100\n
\n
\n
\n = 70 ? 'bg-green-500' :\n category.score >= 50 ? 'bg-yellow-500' :\n 'bg-red-500'\n }`}\n style={{ width: `${category.score}%` }}\n >
\n
\n
\n ))}\n \n\n {/* Active Category Recommendations */}\n
\n
\n

{activeCategoryData.name} Recommendations

\n
\n Priority Filter:\n \n
\n
\n\n
\n {activeCategoryData.recommendations.map(recommendation => (\n
\n
\n

{recommendation.title}

\n
\n \n {recommendation.impact} Impact\n \n \n {recommendation.effort} Effort\n \n
\n
\n\n

{recommendation.description}

\n\n
\n
Implementation Examples:
\n
    \n {recommendation.examples.map((example, idx) => (\n
  • {example}
  • \n ))}\n
\n
\n
\n ))}\n
\n
\n\n {/* AI Platform Performance */}\n
\n

Nike Mentions by AI Platform

\n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n AI Platform\n \n Mention Rate\n \n Sentiment\n \n Top Associations\n \n Priority\n
\n ChatGPT\n \n
\n 82%\n
\n
\n
\n
\n
\n \n Positive\n \n \n Innovation, Athletics, Basketball\n \n Medium\n
\n Claude\n \n
\n 75%\n
\n
\n
\n
\n
\n \n Positive\n \n \n Running, Sportswear, Global Brand\n \n Medium\n
\n Perplexity\n \n
\n 68%\n
\n
\n
\n
\n
\n \n Mixed\n \n \n Fashion, Pricing, Athletic Performance\n \n High\n
\n Gemini\n \n
\n 58%\n
\n
\n
\n
\n
\n \n Mixed\n \n \n Celebrity Endorsements, Technology, Price\n \n High\n
\n
\n
\n \n );\n};\n\nexport default Optimization;", "// app/javascript/components/Dashboard/Workspace.js\nimport React, { useState, useEffect, useRef, useContext } from \"react\";\nimport { Plus, Folder, Clock, MoreHorizontal, ExternalLink, Edit, Check, X, Rocket, Calendar, AlertTriangle, Crown, Search, Globe, ArrowRight, Trash2 } from \"lucide-react\";\nimport axios from '../AxiosConfig';\nimport { useNavigate } from \"react-router-dom\";\nimport { AuthContext } from \"../../context/AuthContext\";\nimport { trackEvent } from '../Analytics/mixpanel';\n\n// Agency plan enum (matching Rails)\nconst AGENCY_PLAN = {\n NONE: 0,\n STARTER: 1,\n UNLIMITED: 2\n};\n\n// Client tier enum (matching Rails)\nconst CLIENT_TIER = {\n NONE: 0,\n MONITORING: 1,\n SERVICING: 2\n};\n\n// HubSpot Form Modal Component\nconst UnlockModal = ({ isOpen, onClose, user, source }) => {\n const [formLoaded, setFormLoaded] = useState(false);\n useEffect(() => {\n if (isOpen) {\n trackEvent('Unlock Modal Opened', {\n user_id: user?.id,\n source: source || 'workspace',\n modal_type: 'hubspot_form'\n });\n\n const existingScript = document.querySelector('script[src=\"https://js.hsforms.net/forms/embed/48492217.js\"]');\n if (!existingScript) {\n const script = document.createElement('script');\n script.src = 'https://js.hsforms.net/forms/embed/48492217.js';\n script.defer = true;\n document.body.appendChild(script);\n script.onload = () => {\n setTimeout(() => setFormLoaded(true), 500);\n };\n } else {\n setTimeout(() => setFormLoaded(true), 100);\n }\n } else {\n setFormLoaded(false);\n }\n }, [isOpen, user, source]);\n\n const handleClose = () => {\n trackEvent('Unlock Modal Closed', {\n user_id: user?.id,\n source: source || 'workspace',\n modal_type: 'hubspot_form'\n });\n onClose();\n };\n\n if (!isOpen) return null;\n\n return (\n
\n
\n \n {!formLoaded && (\n
\n
\n
\n )}\n
\n
\n \n );\n};\n\nconst ProjectAccessBlockedModal = ({ isOpen, onClose, onUpgrade, user, trialInfo }) => {\n useEffect(() => {\n if (isOpen) {\n trackEvent('Project Access Blocked Modal Opened', {\n user_id: user?.id,\n days_remaining: trialInfo?.days_remaining,\n trial_active: trialInfo?.trial_active,\n agency_plan: trialInfo?.agency_plan,\n source: 'workspace'\n });\n }\n }, [isOpen, user, trialInfo]);\n\n const handleClose = () => {\n trackEvent('Project Access Blocked Modal Closed', { user_id: user?.id, action: 'maybe_later', source: 'workspace' });\n onClose();\n };\n\n const handleUpgradeClick = () => {\n trackEvent('Project Access Blocked Upgrade Click', { user_id: user?.id, source: 'workspace' });\n onUpgrade();\n };\n\n if (!isOpen) return null;\n\n const features = [\"Access to all projects\", \"Unlimited client audits\", \"Full analytics dashboard\", \"Opportunity recommendations\"];\n\n return (\n
\n
\n \n
\n
\n
\n \n
\n
\n

Upgrade Required

\n

Your free trial has ended. You need to upgrade your plan to access your projects and continue using the platform.

\n
\n
\n
\n
\n
\n \n
\n
\n

Upgrade to Regain Access

\n

Continue working on your projects with full platform access.

\n
\n
\n
\n {features.map((feature, index) => (\n
\n \n {feature}\n
\n ))}\n
\n
\n
\n
\n \n \n
\n
\n
\n );\n};\n\nconst ExpiredTrialModal = ({ isOpen, onClose, onUpgrade, user, trialInfo }) => {\n useEffect(() => {\n if (isOpen) {\n trackEvent('Expired Trial Modal Opened', { user_id: user?.id, days_remaining: trialInfo?.days_remaining, trial_active: trialInfo?.trial_active, source: 'workspace' });\n }\n }, [isOpen, user, trialInfo]);\n\n const handleClose = () => {\n trackEvent('Expired Trial Modal Closed', { user_id: user?.id, action: 'maybe_later', source: 'workspace' });\n onClose();\n };\n\n const handleUpgradeClick = () => {\n trackEvent('Expired Trial Upgrade Click', { user_id: user?.id, source: 'workspace' });\n onUpgrade();\n };\n\n if (!isOpen) return null;\n\n const features = [\"Unlimited client audits\", \"Full analytics dashboard\", \"Opportunity recommendations\", \"Strategy & measurement tools\"];\n\n return (\n
\n
\n \n
\n
\n
\n \n
\n
\n

Free Trial has Ended

\n

Your free trial has ended. You'll lose access to these features without upgrading your plan.

\n
\n
\n
\n
\n
\n \n
\n
\n

Upgrade to Keep Access

\n

Keep enjoying unlimited audits and full platform access.

\n
\n
\n
\n {features.map((feature, index) => (\n
\n \n {feature}\n
\n ))}\n
\n
\n
\n
\n \n \n
\n
\n
\n );\n};\n\nconst AuditLimitModal = ({ isOpen, onClose, onUpgrade, starterAuditInfo, user }) => {\n useEffect(() => {\n if (isOpen && starterAuditInfo) {\n trackEvent('Audit Limit Modal Opened', { user_id: user?.id, audits_remaining: starterAuditInfo.audits_remaining, source: 'workspace' });\n }\n }, [isOpen, starterAuditInfo, user]);\n\n const handleClose = () => {\n trackEvent('Audit Limit Modal Closed', { user_id: user?.id, action: 'maybe_later', source: 'workspace' });\n onClose();\n };\n\n const handleUpgradeClick = () => {\n trackEvent('Audit Limit Upgrade Click', { user_id: user?.id, source: 'workspace' });\n onUpgrade();\n };\n\n if (!isOpen || !starterAuditInfo) return null;\n\n const { days_until_refresh, refresh_date } = starterAuditInfo;\n const formattedRefreshDate = new Date(refresh_date + 'T00:00:00').toLocaleDateString('en-US', { month: 'short', day: 'numeric' });\n const features = [\"Unlimited client audits\", \"Full analytics dashboard\", \"Opportunity recommendations\", \"Strategy & measurement tools\"];\n\n return (\n
\n
\n \n
\n
\n
\n \n
\n
\n

Monthly Audit Limit Reached

\n

\n You've used all 5 of your monthly audits. Your audits will refresh in {days_until_refresh} days on {formattedRefreshDate}.\n

\n
\n
\n
\n
\n
\n \n
\n
\n

Upgrade to Unlimited

\n

Keep enjoying unlimited audits and full platform access.

\n
\n
\n
\n {features.map((feature, index) => (\n
\n \n {feature}\n
\n ))}\n
\n
\n
\n
\n \n \n
\n
\n
\n );\n};\n\nconst TrialSidebar = ({ trialInfo, onUpgradeClick, user }) => {\n useEffect(() => {\n if (trialInfo) {\n trackEvent('Trial Sidebar Viewed', { user_id: user?.id, days_remaining: trialInfo.days_remaining, trial_active: trialInfo.trial_active, source: 'workspace' });\n }\n }, []);\n\n const handleUpgradeClick = () => {\n trackEvent('Trial Sidebar Upgrade Click', { user_id: user?.id, source: 'workspace' });\n onUpgradeClick();\n };\n\n if (!trialInfo || trialInfo.agency_plan !== AGENCY_PLAN.NONE) return null;\n\n const { days_remaining, days_elapsed, total_trial_days, trial_end_date, trial_active } = trialInfo;\n const isExpired = !trial_active || days_remaining <= 0;\n const progressPercentage = isExpired ? 100 : Math.min((days_elapsed / total_trial_days) * 100, 100);\n const displayDaysRemaining = isExpired ? 0 : days_remaining;\n const displayDaysElapsed = isExpired ? total_trial_days : days_elapsed;\n const formattedEndDate = new Date(trial_end_date + 'T00:00:00').toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });\n const pillTextColor = isExpired ? '#E11D48' : '#4F46E5';\n const pillBgColor = isExpired ? '#FFF1F2' : '#EEF2FF';\n const progressBarColor = isExpired ? '#F43F5E' : '#4F46E5';\n\n return (\n
\n
\n
\n

Free Trial

\n {displayDaysRemaining} days left\n
\n
\n
\n Trial period\n {displayDaysElapsed} of {total_trial_days} days\n
\n
\n
\n
\n
\n
\n
\n
\n
\n Free Trial\n {isExpired ? 'ended' : 'ends'} on {formattedEndDate}\n
\n
\n
\n \n
\n
\n );\n};\n\nconst StarterAuditSidebar = ({ starterAuditInfo, onUpgradeClick, user }) => {\n useEffect(() => {\n if (starterAuditInfo) {\n trackEvent('Starter Audit Sidebar Viewed', { user_id: user?.id, audits_remaining: starterAuditInfo.audits_remaining, source: 'workspace' });\n }\n }, []);\n\n const handleUpgradeClick = () => {\n trackEvent('Starter Audit Sidebar Upgrade Click', { user_id: user?.id, source: 'workspace' });\n onUpgradeClick();\n };\n\n if (!starterAuditInfo) return null;\n\n const { audits_used, audits_remaining, max_audits, days_until_refresh, refresh_date } = starterAuditInfo;\n const isExhausted = audits_remaining <= 0;\n const progressPercentage = Math.min((audits_used / max_audits) * 100, 100);\n const formattedRefreshDate = new Date(refresh_date + 'T00:00:00').toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });\n const pillTextColor = isExhausted ? '#E11D48' : '#4F46E5';\n const pillBgColor = isExhausted ? '#FFF1F2' : '#EEF2FF';\n const progressBarColor = isExhausted ? '#F43F5E' : '#4F46E5';\n\n return (\n
\n
\n
\n

Monthly Audits

\n {audits_remaining} remaining\n
\n
\n
\n Used this cycle\n {audits_used}/{max_audits}\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
{days_until_refresh} days until refresh
\n
{formattedRefreshDate}
\n
\n
\n
\n \n
\n
\n );\n};\n\nconst getClientTierDisplayName = (clientTier) => {\n switch (clientTier) {\n case CLIENT_TIER.MONITORING: return 'Monitoring';\n case CLIENT_TIER.SERVICING: return 'Servicing';\n default: return 'Inactive';\n }\n};\n\nconst getClientTierBadgeColor = (clientTier) => {\n switch (clientTier) {\n case CLIENT_TIER.MONITORING: return { bg: '#FEF3C7', text: '#92400E' };\n case CLIENT_TIER.SERVICING: return { bg: '#D1FAE5', text: '#065F46' };\n default: return { bg: '#F3F4F6', text: '#6B7280' };\n }\n};\n\n// \u2500\u2500 View switcher (Clients / Projects) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Only shown when seo_platform_enabled. Mirrors the prototype's segmented control.\nfunction WorkspaceViewSwitcher({ activeView, onChange, clientCount, projectCount }) {\n const segments = [\n { id: \"clients\", label: \"Agent Mode\", count: clientCount },\n { id: \"projects\", label: \"Classic\", count: projectCount },\n ];\n return (\n
\n {segments.map(s => {\n const active = s.id === activeView;\n return (\n \n );\n })}\n
\n );\n}\n\n// \u2500\u2500 New client type picker modal \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Opens when user clicks \"New Client\" with seo_platform_enabled.\n// Two card options: Visto 2.0 (new agent-based) or Classic (existing audit-driven).\n// Shown when an agency has used its included client slots (3 during trial,\n// zero after) and has no credits \u2014 creating another client is a manual\n// request handled by the Visto team.\nconst ClientQuotaModal = ({ isOpen, onClose, user, clientQuota }) => {\n useEffect(() => {\n if (isOpen) {\n trackEvent('Client Quota Modal Opened', {\n user_id: user?.id,\n clients_count: clientQuota?.clients_count,\n trial_active: clientQuota?.trial_active,\n source: 'workspace',\n });\n }\n }, [isOpen, user, clientQuota]);\n\n if (!isOpen) return null;\n\n return (\n
\n
\n \n
\n
\n
\n \n
\n
\n

The Visto team has been notified

\n

\n You've reached your included client limit\n {clientQuota?.trial_active ? ` (${clientQuota?.trial_limit} clients during your trial)` : ''}.\n We've let the Visto team know you'd like to add another client \u2014 you should hear from us within the next day or so.\n

\n
\n
\n \n
\n
\n
\n );\n};\n\nfunction NewClientTypeModal({ onCancel, onSelect }) {\n const [hoveredMode, setHoveredMode] = useState(null);\n\n const modes = [\n {\n id: \"v2\",\n title: \"Agent Mode\",\n description: \"Agent-based workflow with AI-powered SEO and GEO tools. Dashboard, agents, reports, and Ask Visto chat.\",\n tag: \"Recommended\",\n tagColor: \"#4F46E5\",\n },\n {\n id: \"classic\",\n title: \"Classic\",\n description: \"The audit-driven workspace your team has been using. GEO visibility audits and optimization.\",\n tag: null,\n tagColor: null,\n },\n ];\n\n return (\n
\n
e.stopPropagation()}\n className=\"bg-white rounded-xl shadow-xl max-w-lg w-full mx-4 p-7\">\n
\n

Set up a new client

\n
\n

\n Which Visto experience would you like to use? You can change this later from project settings.\n

\n\n
\n {modes.map(mode => {\n const isHovered = hoveredMode === mode.id;\n return (\n onSelect(mode.id)}\n onMouseEnter={() => setHoveredMode(mode.id)}\n onMouseLeave={() => setHoveredMode(null)}\n className={`text-left p-4 rounded-lg border-2 transition-all ${\n isHovered\n ? 'border-indigo-500 bg-indigo-50 shadow-sm'\n : 'border-gray-200 bg-white hover:border-gray-300'\n }`}\n >\n
\n {mode.title}\n {mode.tag && (\n \n {mode.tag}\n \n )}\n
\n

{mode.description}

\n
\n Select \n
\n \n );\n })}\n
\n\n
\n \n
\n
\n
\n );\n}\n\nexport default function Workspace() {\n const [showProjectAccessBlockedModal, setShowProjectAccessBlockedModal] = useState(false);\n const [projects, setProjects] = useState([]);\n const [workspace, setWorkspace] = useState({ name: \"My Workspace\" });\n const [auditFeatureEnabled, setAuditFeatureEnabled] = useState(false);\n const [trialInfo, setTrialInfo] = useState(null);\n const [starterAuditInfo, setStarterAuditInfo] = useState(null);\n const [loading, setLoading] = useState(true);\n const [loadingWorkspace, setLoadingWorkspace] = useState(true);\n const [error, setError] = useState(null);\n const [actionMenuOpen, setActionMenuOpen] = useState(null);\n const [editingWorkspaceName, setEditingWorkspaceName] = useState(false);\n const [workspaceName, setWorkspaceName] = useState(\"\");\n const [savingWorkspaceName, setSavingWorkspaceName] = useState(false);\n const [projectSearchTerm, setProjectSearchTerm] = useState(\"\");\n const [showUnlockModal, setShowUnlockModal] = useState(false);\n const [showExpiredTrialModal, setShowExpiredTrialModal] = useState(false);\n const [showAuditLimitModal, setShowAuditLimitModal] = useState(false);\n\n // Clients state (Visto SEO platform)\n const [clients, setClients] = useState([]);\n const [loadingClients, setLoadingClients] = useState(true);\n\n // View toggle state \u2014 only used when seo_platform_enabled\n const [activeView, setActiveView] = useState(\"clients\"); // \"clients\" | \"projects\"\n\n // New client type picker modal\n const [showNewClientTypeModal, setShowNewClientTypeModal] = useState(false);\n const [clientQuota, setClientQuota] = useState(null);\n const [showClientQuotaModal, setShowClientQuotaModal] = useState(false);\n\n const { user } = useContext(AuthContext);\n const workspaceNameInputRef = useRef(null);\n const navigate = useNavigate();\n\n const hasSeo = !!user?.seo_platform_enabled;\n\n useEffect(() => {\n trackEvent('Workspace Page Viewed', { user_id: user?.id, source: 'workspace' });\n }, [user]);\n\n // Fetch workspace\n useEffect(() => {\n const fetchWorkspace = async () => {\n try {\n setLoadingWorkspace(true);\n const response = await axios.get('/api/workspace');\n setWorkspace(response.data);\n setWorkspaceName(response.data.name);\n setAuditFeatureEnabled(response.data.audit_feature_enabled || false);\n setTrialInfo(response.data.trial_info || null);\n setStarterAuditInfo(response.data.starter_audit_info || null);\n setClientQuota(response.data.client_quota || null);\n if (response.data.projects) {\n setProjects(response.data.projects);\n trackEvent('Workspace Projects Loaded', { user_id: user?.id, project_count: response.data.projects.length, source: 'workspace_api' });\n }\n setError(null);\n } catch (err) {\n console.error('Error fetching workspace:', err);\n } finally {\n setLoadingWorkspace(false);\n }\n };\n fetchWorkspace();\n }, [user]);\n\n // Fetch projects\n useEffect(() => {\n const fetchProjects = async () => {\n if (projects.length > 0) { setLoading(false); return; }\n try {\n setLoading(true);\n const response = await axios.get('/api/projects');\n setProjects(response.data);\n setError(null);\n trackEvent('Workspace Projects Loaded', { user_id: user?.id, project_count: response.data.length, source: 'projects_api' });\n } catch (err) {\n console.error('Error fetching projects:', err);\n const errorMessage = err.response?.data?.error || err.response?.data?.message || err.message || 'Failed to load projects.';\n setError(errorMessage);\n } finally {\n setLoading(false);\n }\n };\n fetchProjects();\n }, [user, projects.length]);\n\n // Fetch clients (Visto SEO platform) \u2014 only when seo_platform_enabled\n useEffect(() => {\n if (!hasSeo) {\n setLoadingClients(false);\n return;\n }\n const fetchClients = async () => {\n try {\n setLoadingClients(true);\n const res = await axios.get('/api/v2/clients');\n const data = res.data || {};\n const list = Array.isArray(data) ? data : (data.clients || []);\n setClients(list);\n } catch {\n setClients([]);\n } finally {\n setLoadingClients(false);\n }\n };\n fetchClients();\n }, [hasSeo]);\n\n useEffect(() => {\n const handleClickOutside = (e) => {\n setActionMenuOpen(null);\n if (editingWorkspaceName && workspaceNameInputRef.current && !workspaceNameInputRef.current.contains(e.target)) {\n handleSaveWorkspaceName();\n }\n };\n document.addEventListener('click', handleClickOutside);\n return () => document.removeEventListener('click', handleClickOutside);\n }, [editingWorkspaceName, workspaceName]);\n\n useEffect(() => {\n if (editingWorkspaceName && workspaceNameInputRef.current) {\n workspaceNameInputRef.current.focus();\n }\n }, [editingWorkspaceName]);\n\n const handleCreateProject = () => {\n trackEvent('Create Project Button Click', { user_id: user?.id, trial_active: trialInfo?.trial_active, agency_plan: trialInfo?.agency_plan, source: 'workspace' });\n if (trialInfo && !trialInfo.trial_active && trialInfo.agency_plan === AGENCY_PLAN.NONE) { setShowExpiredTrialModal(true); return; }\n if (!trialInfo?.trial_active && starterAuditInfo && starterAuditInfo.audits_remaining <= 0) { setShowAuditLimitModal(true); return; }\n if (auditFeatureEnabled) { navigate('/client_setup'); } else { navigate('/projects/new'); }\n };\n\n // Delete a client. Empty shells get a simple confirm; clients with\n // strategy/work history require typing the name \u2014 the server deletes\n // everything (assessments, strategies, work items) permanently.\n const handleRemoveClient = async (e, client) => {\n e.stopPropagation();\n if (client.removable) {\n if (!window.confirm(`Remove \"${client.name}\"? This client has no strategy or work history. This can't be undone.`)) return;\n } else {\n const typed = window.prompt(\n `Permanently delete \"${client.name}\" and ALL of its data \u2014 strategies, work items, and history? This can't be undone.\\n\\nType the client name to confirm:`\n );\n if (typed === null) return;\n if (typed.trim() !== client.name) {\n alert('Name did not match \u2014 nothing was deleted.');\n return;\n }\n }\n try {\n await axios.delete(`/api/v2/clients/${client.id}`);\n setClients(prev => prev.filter(c => c.id !== client.id));\n trackEvent('Client Removed', { user_id: user?.id, client_id: client.id, source: 'workspace' });\n } catch (err) {\n alert(err.response?.data?.error || 'Could not remove this client.');\n }\n };\n\n // New Client button handler \u2014 if seo_platform_enabled, show type picker; otherwise go straight to classic project setup\n const handleNewClientClick = () => {\n if (hasSeo) {\n setShowNewClientTypeModal(true);\n } else {\n handleCreateProject();\n }\n };\n\n // Handle mode selection from the type picker modal\n const handleNewClientModeSelect = (mode) => {\n setShowNewClientTypeModal(false);\n trackEvent('New Client Mode Selected', { user_id: user?.id, mode, source: 'workspace' });\n if (mode === \"v2\") {\n if (clientQuota?.applies && !clientQuota?.can_create) {\n // Notify the Visto team (server throttles to once/org/day),\n // then tell the user we've been notified \u2014 mirrors the\n // strategy-approval request flow.\n axios.post('/api/v2/client_setup/request_access').catch(() => {});\n setShowClientQuotaModal(true);\n return;\n }\n navigate('/clients/new');\n } else {\n // Classic mode \u2014 route to the existing audit-based setup\n if (auditFeatureEnabled) {\n navigate('/client_setup');\n } else {\n navigate('/projects/new');\n }\n }\n };\n\n const handleProjectClick = (projectId) => {\n trackEvent('Project Clicked', { user_id: user?.id, project_id: projectId, source: 'workspace' });\n if (trialInfo && !trialInfo.trial_active && trialInfo.agency_plan === AGENCY_PLAN.NONE) { setShowProjectAccessBlockedModal(true); return; }\n navigate(`/projects/${projectId}`);\n };\n\n const toggleActionMenu = (e, projectId) => {\n e.stopPropagation();\n trackEvent('Project Action Menu Toggle', { user_id: user?.id, project_id: projectId, source: 'workspace' });\n setActionMenuOpen(actionMenuOpen === projectId ? null : projectId);\n };\n\n const handleEditProject = (e, projectId) => {\n e.stopPropagation();\n trackEvent('Edit Project Click', { user_id: user?.id, project_id: projectId, source: 'workspace' });\n navigate(`/projects/${projectId}/edit-project`);\n setActionMenuOpen(null);\n };\n\n const handleEditWorkspaceName = (e) => {\n e.stopPropagation();\n trackEvent('Edit Workspace Name Click', { user_id: user?.id, source: 'workspace' });\n setEditingWorkspaceName(true);\n };\n\n const handleWorkspaceNameChange = (e) => setWorkspaceName(e.target.value);\n\n const handleSaveWorkspaceName = async () => {\n if (!workspaceName.trim() || workspaceName === workspace.name || savingWorkspaceName) {\n setEditingWorkspaceName(false);\n setWorkspaceName(workspace.name);\n return;\n }\n try {\n setSavingWorkspaceName(true);\n const response = await axios.put('/api/workspace', { workspace: { name: workspaceName.trim() } });\n setWorkspace(response.data);\n setAuditFeatureEnabled(response.data.audit_feature_enabled || false);\n setEditingWorkspaceName(false);\n trackEvent('Workspace Name Changed', { user_id: user?.id, old_name: workspace.name, new_name: workspaceName.trim(), source: 'workspace' });\n } catch (err) {\n console.error('Error updating workspace name:', err);\n alert('Failed to update workspace name. Please try again.');\n setWorkspaceName(workspace.name);\n } finally {\n setSavingWorkspaceName(false);\n }\n };\n\n const handleCancelEditWorkspaceName = (e) => {\n e.stopPropagation();\n trackEvent('Cancel Workspace Name Edit', { user_id: user?.id, source: 'workspace' });\n setEditingWorkspaceName(false);\n setWorkspaceName(workspace.name);\n };\n\n const handleKeyDown = (e) => {\n if (e.key === 'Enter') handleSaveWorkspaceName();\n else if (e.key === 'Escape') handleCancelEditWorkspaceName(e);\n };\n\n const handleShowUnlockModal = () => setShowUnlockModal(true);\n\n const handleProjectSearchChange = (e) => setProjectSearchTerm(e.target.value);\n\n const handleClearProjectSearch = (e) => {\n e.stopPropagation();\n trackEvent('Project Search Cleared', { user_id: user?.id, source: 'workspace' });\n setProjectSearchTerm(\"\");\n };\n\n useEffect(() => {\n if (projectSearchTerm.length > 2) {\n const timer = setTimeout(() => {\n trackEvent('Project Search Used', { user_id: user?.id, search_query_length: projectSearchTerm.length, source: 'workspace' });\n }, 500);\n return () => clearTimeout(timer);\n }\n }, [projectSearchTerm, user]);\n\n const normalizedSearch = projectSearchTerm.trim().toLowerCase();\n const filteredProjects = normalizedSearch\n ? projects.filter(project => {\n const nameMatch = project.name?.toLowerCase().includes(normalizedSearch);\n const topicMatch = Array.isArray(project.topics) && project.topics.some(topic => topic?.name?.toLowerCase().includes(normalizedSearch));\n return nameMatch || topicMatch;\n })\n : projects;\n\n const buttonText = auditFeatureEnabled ? \"Setup New Client\" : \"Create New Project\";\n const showTrialSidebar = trialInfo && trialInfo.agency_plan === AGENCY_PLAN.NONE;\n const showStarterAuditSidebar = starterAuditInfo && trialInfo?.agency_plan === AGENCY_PLAN.STARTER && !trialInfo?.trial_active;\n\n // When SEO platform is enabled, show Clients view by default; toggle between Clients and Projects\n const showViewSwitcher = hasSeo;\n const showClientsSection = hasSeo && activeView === \"clients\";\n const showProjectsSection = !hasSeo || activeView === \"projects\";\n\n return (\n
\n
\n
\n
\n {editingWorkspaceName ? (\n
e.stopPropagation()}>\n \n \n \n
\n ) : (\n
\n

\n {loadingWorkspace ? \"Loading workspace...\" : workspace.name}\n

\n \n
\n )}\n
\n {!loadingWorkspace && (\n
\n \n \n Setup New Client\n \n
\n )}\n
\n\n {/* View switcher \u2014 only when seo_platform_enabled */}\n {showViewSwitcher && (\n \n )}\n\n {/* Main content area with optional sidebar */}\n
\n {/* Clients + Projects */}\n
\n\n {/* \u2500\u2500 Clients list (Visto SEO platform) \u2014 shown when toggle is on \"clients\" \u2500\u2500 */}\n {showClientsSection && (\n <>\n {loadingClients && (\n
\n
\n Loading clients\u2026\n
\n
\n )}\n\n {!loadingClients && clients.length > 0 && (\n
\n
\n

Clients

\n {clients.length} client{clients.length === 1 ? '' : 's'}\n
\n
\n
\n {clients.map(client => (\n navigate(`/clients/${client.id}`)}\n >\n
\n
\n
\n \n
\n
\n

{client.name}

\n {client.domain && (\n
{client.domain}
\n )}\n
\n
\n
\n {client.onboarding_status && (\n \n {client.onboarding_status === 'completed' ? 'Active' :\n client.onboarding_status === 'running' ? 'Setting up' :\n client.onboarding_status}\n \n )}\n handleRemoveClient(e, client)}\n title={client.removable ? \"Remove this client (setup never completed)\" : \"Delete this client and all of its data\"}\n className=\"p-1.5 rounded-md text-gray-300 hover:text-red-600 hover:bg-red-50 transition-colors\"\n >\n \n \n \n
\n
\n
\n ))}\n
\n
\n
\n )}\n\n {!loadingClients && clients.length === 0 && (\n
\n
\n

No clients yet

\n \n Set up your first client \u2192\n \n
\n
\n )}\n \n )}\n\n {/* \u2500\u2500 Projects list \u2014 shown when toggle is on \"projects\" or when SEO platform is off \u2500\u2500 */}\n {showProjectsSection && (\n <>\n

Projects

\n\n {/* Project Search */}\n {!loading && !error && projects.length > 0 && (\n
e.stopPropagation()}>\n
\n \n \n {projectSearchTerm && (\n \n )}\n
\n {normalizedSearch && (\n
\n Showing {filteredProjects.length} of {projects.length} projects\n
\n )}\n
\n )}\n\n
\n {loading ? (\n
\n

Loading projects...

\n
\n ) : error ? (\n
\n

{error}

\n \n
\n ) : (\n
\n {filteredProjects.length > 0 ? (\n filteredProjects.map((project) => (\n handleProjectClick(project.id)}\n >\n
\n
\n
\n \n
\n
\n
\n

{project.name}

\n
\n {project.updated_at && (\n
\n \n Updated {new Date(project.updated_at).toLocaleDateString()}\n
\n )}\n
\n
\n
\n {(() => {\n const shouldShowClientTier = trialInfo && !trialInfo.trial_active &&\n (trialInfo.agency_plan === AGENCY_PLAN.STARTER || trialInfo.agency_plan === AGENCY_PLAN.UNLIMITED);\n if (!shouldShowClientTier) return null;\n const clientTierName = getClientTierDisplayName(project.client_tier);\n const clientTierColors = getClientTierBadgeColor(project.client_tier);\n return (\n \n {clientTierName}\n \n );\n })()}\n \n {actionMenuOpen === project.id && (\n
\n
e.stopPropagation()}>\n \n \n
\n
\n )}\n
\n
\n
\n ))\n ) : projects.length > 0 && normalizedSearch ? (\n
\n

No projects match \"{projectSearchTerm}\"

\n \n
\n ) : (\n
\n

No projects found

\n

Click the \"{buttonText}\" button to get started

\n
\n )}\n
\n )}\n
\n \n )}\n
\n\n {/* Trial Sidebar */}\n {showTrialSidebar && (\n \n )}\n\n {/* Starter Audit Sidebar */}\n {showStarterAuditSidebar && (\n \n )}\n
\n
\n\n setShowUnlockModal(false)} user={user} source=\"workspace\" />\n setShowExpiredTrialModal(false)} onUpgrade={() => { setShowExpiredTrialModal(false); setShowUnlockModal(true); }} user={user} trialInfo={trialInfo} />\n setShowAuditLimitModal(false)} onUpgrade={() => { setShowAuditLimitModal(false); setShowUnlockModal(true); }} starterAuditInfo={starterAuditInfo} user={user} />\n setShowProjectAccessBlockedModal(false)} onUpgrade={() => { setShowProjectAccessBlockedModal(false); setShowUnlockModal(true); }} user={user} trialInfo={trialInfo} />\n\n setShowClientQuotaModal(false)} user={user} clientQuota={clientQuota} />\n\n {/* New client type picker modal \u2014 only when seo_platform_enabled */}\n {showNewClientTypeModal && (\n setShowNewClientTypeModal(false)}\n onSelect={handleNewClientModeSelect}\n />\n )}\n
\n );\n}", "import React, { useState, useEffect, useRef } from 'react';\nimport axios from '../../AxiosConfig';\nimport { Plus, X, Building, Info } from 'lucide-react';\nimport CompetitorDetailsDrawer from './CompetitorDetailsDrawer';\n\nconst ProjectForm = ({\n projectId,\n onComplete\n }) => {\n const [isLoading, setIsLoading] = useState(true);\n const [formData, setFormData] = useState({\n name: '',\n geolocation: '',\n user_persona: '',\n domains: [],\n brands: [],\n competitors: [],\n competitor_details: []\n });\n\n // New state for enhanced competitor details\n const [competitorDetails, setCompetitorDetails] = useState([]);\n\n const [errors, setErrors] = useState({});\n const [isSubmitting, setIsSubmitting] = useState(false);\n const [newDomain, setNewDomain] = useState('');\n const [newBrand, setNewBrand] = useState({ name: '', products: [] });\n const [newCompetitor, setNewCompetitor] = useState('');\n const [newProducts, setNewProducts] = useState({});\n const [focusProductIndex, setFocusProductIndex] = useState(null);\n\n // Competitor drawer state\n const [isDrawerOpen, setIsDrawerOpen] = useState(false);\n const [selectedCompetitor, setSelectedCompetitor] = useState(null);\n\n // Refs for input fields\n const productInputRefs = useRef({});\n\n const [personaEdited, setPersonaEdited] = useState(false);\n const [initialUserPersona, setInitialUserPersona] = useState('');\n\n // Focus on product input when focusProductIndex changes\n useEffect(() => {\n if (focusProductIndex !== null && productInputRefs.current[focusProductIndex]) {\n productInputRefs.current[focusProductIndex].focus();\n setFocusProductIndex(null);\n }\n }, [focusProductIndex, formData.brands.length]);\n\n // Fetch project data\n useEffect(() => {\n const fetchProject = async () => {\n if (!projectId) return;\n\n try {\n setIsLoading(true);\n const response = await axios.get(`/api/projects/${projectId}`);\n\n const project = response.data;\n const userPersona = project.user_persona || '';\n\n // Store initial user persona value\n setInitialUserPersona(userPersona);\n\n // Find the customer company (company_type === 0)\n const customerCompany = project.companies?.find(c => c.company_type === \"customer\") || {};\n\n // Extract domains from customer company\n const customerDomains = customerCompany.domains?.map(d => d.domain) || [];\n\n // Extract brands and products from customer company\n const customerBrands = customerCompany.brands?.map(b => ({\n name: b.name,\n products: b.products?.map(p => p.name) || []\n })) || [];\n\n // Find competitor companies (company_type === 1)\n const competitorCompanies = project.companies?.filter(c => c.company_type === \"competitor\") || [];\n\n // Format competitors data - only names, no domains\n const competitors = competitorCompanies.map(c => c.name);\n\n // Enhanced competitor details for editing\n const enhancedCompetitorDetails = competitorCompanies.map(c => ({\n name: c.name,\n domains: c.domains?.map(d => d.domain) || [],\n brands: c.brands?.map(b => ({\n name: b.name,\n products: b.products?.map(p => p.name) || []\n })) || []\n }));\n\n setCompetitorDetails(enhancedCompetitorDetails);\n\n // Format the data for the form\n setFormData({\n name: project.name || '',\n geolocation: project.geolocation || '',\n user_persona: userPersona,\n domains: customerDomains,\n brands: customerBrands,\n competitors: competitors,\n competitor_details: enhancedCompetitorDetails\n });\n } catch (err) {\n console.error('Error fetching project:', err);\n setErrors({\n general: `Failed to load project data: ${err.response?.data?.error || err.message}`\n });\n } finally {\n setIsLoading(false);\n }\n };\n\n fetchProject();\n }, [projectId]);\n\n const handleChange = (e) => {\n const { name, value } = e.target;\n setFormData({\n ...formData,\n [name]: value\n });\n\n // Check if user persona is being edited\n if (name === 'user_persona' && value !== initialUserPersona) {\n setPersonaEdited(true);\n }\n\n // Clear error for this field when user makes changes\n if (errors[name]) {\n setErrors({\n ...errors,\n [name]: null\n });\n }\n };\n\n // Domain management\n const handleAddDomain = () => {\n if (!newDomain.trim()) return;\n if (formData.domains.includes(newDomain.trim())) {\n setErrors({\n ...errors,\n domains: 'This domain already exists'\n });\n return;\n }\n\n setFormData({\n ...formData,\n domains: [...formData.domains, newDomain.trim()]\n });\n setNewDomain('');\n\n // Clear domain error if it exists\n if (errors.domains) {\n setErrors({\n ...errors,\n domains: null\n });\n }\n };\n\n const handleRemoveDomain = (domainToRemove) => {\n setFormData({\n ...formData,\n domains: formData.domains.filter(domain => domain !== domainToRemove)\n });\n };\n\n // Brand management\n const handleAddBrand = () => {\n if (!newBrand.name.trim()) return;\n if (formData.brands.some(brand => brand.name === newBrand.name.trim())) {\n setErrors({\n ...errors,\n brands: 'A brand with this name already exists'\n });\n return;\n }\n\n const updatedBrands = [\n ...formData.brands,\n {...newBrand, name: newBrand.name.trim(), products: [...newBrand.products]}\n ];\n\n setFormData({\n ...formData,\n brands: updatedBrands\n });\n\n setNewBrand({ name: '', products: [] });\n\n // Clear brand error if it exists\n if (errors.brands) {\n setErrors({\n ...errors,\n brands: null\n });\n }\n\n // Set focus to the product input of the newly added brand\n setFocusProductIndex(updatedBrands.length - 1);\n };\n\n const handleRemoveBrand = (index) => {\n const updatedBrands = [...formData.brands];\n updatedBrands.splice(index, 1);\n setFormData({\n ...formData,\n brands: updatedBrands\n });\n };\n\n // Product management\n const handleAddProduct = (brandIndex) => {\n const productText = newProducts[brandIndex] || '';\n if (!productText.trim()) return;\n\n const updatedBrands = [...formData.brands];\n const brand = updatedBrands[brandIndex];\n\n if (brand.products.includes(productText.trim())) {\n setErrors({\n ...errors,\n products: 'This product already exists for this brand'\n });\n return;\n }\n\n brand.products.push(productText.trim());\n setFormData({\n ...formData,\n brands: updatedBrands\n });\n\n // Clear only this brand's new product input\n setNewProducts({\n ...newProducts,\n [brandIndex]: ''\n });\n\n // Clear product error if it exists\n if (errors.products) {\n setErrors({\n ...errors,\n products: null\n });\n }\n\n // Keep focus on the same product input\n setTimeout(() => {\n if (productInputRefs.current[brandIndex]) {\n productInputRefs.current[brandIndex].focus();\n }\n }, 0);\n };\n\n const handleNewProductChange = (brandIndex, value) => {\n setNewProducts({\n ...newProducts,\n [brandIndex]: value\n });\n };\n\n const handleRemoveProduct = (brandIndex, productIndex) => {\n const updatedBrands = [...formData.brands];\n updatedBrands[brandIndex].products.splice(productIndex, 1);\n setFormData({\n ...formData,\n brands: updatedBrands\n });\n };\n\n // Competitor management\n const handleAddCompetitor = () => {\n if (!newCompetitor.trim()) return;\n if (formData.competitors.includes(newCompetitor.trim())) {\n setErrors({\n ...errors,\n competitors: 'This competitor already exists'\n });\n return;\n }\n\n const newCompetitorName = newCompetitor.trim();\n\n // Add to competitors list and competitor_details\n setFormData({\n ...formData,\n competitors: [...formData.competitors, newCompetitorName],\n competitor_details: [...(formData.competitor_details || []), {\n name: newCompetitorName,\n domains: [''],\n brands: [{ name: '', products: [''] }]\n }]\n });\n\n // Add to competitor details with empty structure\n setCompetitorDetails([\n ...competitorDetails,\n {\n name: newCompetitorName,\n domains: [''],\n brands: [{ name: '', products: [''] }]\n }\n ]);\n\n // Open drawer to add details for this new competitor\n setSelectedCompetitor(newCompetitorName);\n setIsDrawerOpen(true);\n\n setNewCompetitor('');\n\n // Clear competitor error if it exists\n if (errors.competitors) {\n setErrors({\n ...errors,\n competitors: null\n });\n }\n };\n\n const handleRemoveCompetitor = (competitorToRemove) => {\n setFormData({\n ...formData,\n competitors: formData.competitors.filter(competitor => competitor !== competitorToRemove),\n competitor_details: (formData.competitor_details || []).filter(\n competitor => competitor.name !== competitorToRemove\n )\n });\n\n // Remove from competitor details\n setCompetitorDetails(\n competitorDetails.filter(competitor => competitor.name !== competitorToRemove)\n );\n };\n\n // Edit competitor details\n const handleEditCompetitor = (competitorName) => {\n setSelectedCompetitor(competitorName);\n setIsDrawerOpen(true);\n };\n\n // Save competitor details from drawer\n const handleSaveCompetitorDetails = (updatedDetails) => {\n // Update the separate competitorDetails state\n const updatedCompetitorDetails = [...competitorDetails];\n const index = updatedCompetitorDetails.findIndex(c => c.name === selectedCompetitor);\n\n if (index >= 0) {\n updatedCompetitorDetails[index] = updatedDetails;\n } else {\n updatedCompetitorDetails.push(updatedDetails);\n }\n\n // Also update the formData.competitor_details\n const updatedFormDataDetails = [...(formData.competitor_details || [])];\n const formDataIndex = updatedFormDataDetails.findIndex(c => c.name === selectedCompetitor);\n\n if (formDataIndex >= 0) {\n updatedFormDataDetails[formDataIndex] = updatedDetails;\n } else {\n updatedFormDataDetails.push(updatedDetails);\n }\n\n // If the competitor name was changed, update it in the competitors array too\n if (selectedCompetitor !== updatedDetails.name) {\n const competitorIndex = formData.competitors.indexOf(selectedCompetitor);\n if (competitorIndex >= 0) {\n const updatedCompetitors = [...formData.competitors];\n updatedCompetitors[competitorIndex] = updatedDetails.name;\n\n setFormData({\n ...formData,\n competitors: updatedCompetitors,\n competitor_details: updatedFormDataDetails\n });\n } else {\n setFormData({\n ...formData,\n competitor_details: updatedFormDataDetails\n });\n }\n } else {\n setFormData({\n ...formData,\n competitor_details: updatedFormDataDetails\n });\n }\n\n setCompetitorDetails(updatedCompetitorDetails);\n };\n\n const validate = () => {\n const newErrors = {};\n\n if (!formData.name.trim()) {\n newErrors.name = 'Project name is required';\n }\n\n // Domains are required\n if (formData.domains.length === 0) {\n newErrors.domains = 'At least one domain is required';\n }\n\n setErrors(newErrors);\n return Object.keys(newErrors).length === 0;\n };\n\n const handleSubmit = async () => {\n\n if (!validate()) {\n return;\n }\n\n setIsSubmitting(true);\n\n try {\n const url = `/api/projects/${projectId}`;\n const method = 'put';\n\n // Transform formData to include enhanced competitor details\n const dataToSubmit = {\n ...formData,\n competitor_details: formData.competitor_details\n };\n\n const response = await axios[method](url, {\n project: dataToSubmit\n });\n\n // Get the updated project data from response\n const updatedProject = response.data;\n\n // Call onComplete callback with updated project data\n if (onComplete) {\n onComplete(updatedProject);\n }\n } catch (err) {\n console.error('Error saving project:', err);\n\n // Handle server validation errors\n if (err.response?.data?.errors) {\n const serverErrors = err.response.data.errors;\n console.log('Server errors:', serverErrors);\n\n // Create a new errors object\n const newErrors = {};\n\n // Check if errors is an array (as returned by Rails)\n if (Array.isArray(serverErrors)) {\n // Set a general error with all messages joined\n newErrors.general = serverErrors.join('. ');\n\n // Try to categorize errors by field if possible\n serverErrors.forEach(error => {\n const lowerError = error.toLowerCase();\n\n // Check for specific field mentions in error messages\n if (lowerError.includes('name')) {\n newErrors.name = error;\n } else if (lowerError.includes('brand')) {\n newErrors.brands = error;\n } else if (lowerError.includes('product')) {\n newErrors.products = error;\n } else if (lowerError.includes('persona')) {\n newErrors.user_persona = error;\n } else if (lowerError.includes('domain')) {\n newErrors.domains = error;\n } else if (lowerError.includes('competitor')) {\n newErrors.competitors = error;\n } else if (lowerError.includes('geolocation')) {\n newErrors.geolocation = error;\n }\n });\n } else if (typeof serverErrors === 'object') {\n // Handle object format errors (if the server returns {field: [errors]})\n Object.keys(serverErrors).forEach(key => {\n const fieldErrors = serverErrors[key];\n if (Array.isArray(fieldErrors)) {\n newErrors[key] = fieldErrors.join('. ');\n } else {\n newErrors[key] = fieldErrors;\n }\n });\n } else {\n // Fallback for any other format\n newErrors.general = 'Failed to save project. Please try again.';\n }\n\n setErrors(newErrors);\n } else {\n setErrors({ general: 'Failed to save project. Please try again.' });\n }\n } finally {\n setIsSubmitting(false);\n }\n };\n\n const handleCancel = () => {\n if (onComplete) {\n onComplete(null); // Pass null to indicate no data update\n }\n };\n\n if (isLoading) {\n return (\n
\n
Loading project data...
\n
\n );\n }\n\n return (\n
\n
\n
\n

\n Edit Project\n

\n\n {errors.general && (\n
\n {errors.general}\n
\n )}\n\n
\n {/* Project Name */}\n
\n \n \n {errors.name && (\n

{errors.name}

\n )}\n
\n\n {/* Geolocation */}\n
\n \n \n

\n If you want client GEO analysis to be situated in a specific location you can enter it here\n

\n {errors.geolocation && (\n

{errors.geolocation}

\n )}\n
\n\n {/* User Persona - optional */}\n
\n \n \n {errors.user_persona && (\n

{errors.user_persona}

\n )}\n {personaEdited && (\n
\n

Important note about editing user persona:

\n
    \n
  • Changes will only affect new prompts and research going forward
  • \n
  • If making significant changes to persona and domains, consider creating a new project instead
  • \n
\n
\n )}\n
\n\n {/* Domains - required */}\n
\n \n
\n {formData.domains.map((domain, index) => (\n
\n {domain}\n handleRemoveDomain(domain)}\n disabled={isSubmitting}\n >\n \n \n
\n ))}\n
\n
\n setNewDomain(e.target.value)}\n className={`flex-1 px-4 py-2 border rounded-l-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 ${\n errors.domains ? 'border-red-500' : 'border-gray-300'\n }`}\n placeholder=\"Add a domain\"\n disabled={isSubmitting}\n />\n \n Add\n \n
\n {errors.domains && (\n

{errors.domains}

\n )}\n
\n\n {/* Brands - optional */}\n
\n \n
\n {formData.brands.map((brand, brandIndex) => (\n
\n
\n
{brand.name}
\n
\n handleRemoveBrand(brandIndex)}\n >\n \n Remove Brand\n \n
\n
\n\n
\n
Products
\n
\n {brand.products.map((product, productIndex) => (\n
\n {product}\n handleRemoveProduct(brandIndex, productIndex)}\n disabled={isSubmitting}\n >\n \n \n
\n ))}\n
\n
\n handleNewProductChange(brandIndex, e.target.value)}\n className=\"flex-1 px-3 py-1.5 text-sm border rounded-l-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 border-gray-300\"\n placeholder=\"Add a product\"\n disabled={isSubmitting}\n onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddProduct(brandIndex))}\n ref={(el) => productInputRefs.current[brandIndex] = el}\n />\n handleAddProduct(brandIndex)}\n disabled={isSubmitting}\n >\n Add\n \n
\n
\n
\n ))}\n
\n
\n setNewBrand({...newBrand, name: e.target.value})}\n className={`flex-1 px-4 py-2 border rounded-l-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 ${\n errors.brands ? 'border-red-500' : 'border-gray-300'\n }`}\n placeholder=\"Add a brand\"\n disabled={isSubmitting}\n />\n \n Add\n \n
\n {errors.brands && (\n

{errors.brands}

\n )}\n {errors.products && (\n

{errors.products}

\n )}\n
\n\n {/* Competitors section */}\n
\n
\n \n
\n \n \n Add competitor details to enhance competitive analysis\n \n
\n
\n\n
\n {formData.competitors.map((competitor, index) => (\n
\n
\n
\n \n {competitor}\n
\n
\n handleEditCompetitor(competitor)}\n >\n Edit Details\n \n handleRemoveCompetitor(competitor)}\n >\n \n Remove\n \n
\n
\n\n {/* Show a summary of the competitor details if available */}\n {competitorDetails.find(c => c.name === competitor) && (\n
\n {(() => {\n const details = competitorDetails.find(c => c.name === competitor);\n const domainsCount = details.domains.filter(d => d.trim()).length;\n const brandsCount = details.brands.filter(b => b.name.trim()).length;\n\n if (domainsCount === 0 && brandsCount === 0) {\n return No details added yet;\n }\n\n return (\n
\n {domainsCount > 0 && (\n \n {domainsCount} domain{domainsCount !== 1 ? 's' : ''}\n \n )}\n {brandsCount > 0 && (\n \n {brandsCount} brand{brandsCount !== 1 ? 's' : ''}\n \n )}\n
\n );\n })()}\n
\n )}\n
\n ))}\n
\n\n
\n setNewCompetitor(e.target.value)}\n className={`flex-1 px-4 py-2 border rounded-l-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 ${\n errors.competitors ? 'border-red-500' : 'border-gray-300'\n }`}\n placeholder=\"Add a competitor\"\n disabled={isSubmitting}\n />\n \n Add\n \n
\n {errors.competitors && (\n

{errors.competitors}

\n )}\n
\n\n
\n \n Cancel\n \n \n {isSubmitting ? (\n <>\n \n \n \n \n Saving...\n \n ) : (\n 'Update Project'\n )}\n \n
\n
\n
\n
\n\n {/* Competitor Details Drawer */}\n {isDrawerOpen && (\n setIsDrawerOpen(false)}\n competitorName={selectedCompetitor}\n projectData={formData}\n onSave={handleSaveCompetitorDetails}\n isNewProject={false}\n />\n )}\n
\n );\n};\n\nexport default ProjectForm;", "// app/javascript/components/Dashboard/Projects/CompetitorDetailsDrawer.js\nimport React, { useState, useEffect } from 'react';\nimport { X, Plus, Trash2, Loader, RefreshCw } from 'lucide-react';\nimport axios from '../../AxiosConfig';\n\nconst CompetitorDetailsDrawer = ({\n isOpen,\n onClose,\n competitorName,\n projectData,\n onSave,\n isNewProject = false\n }) => {\n // Competitor details state\n const [competitorDetails, setCompetitorDetails] = useState({\n name: competitorName || '',\n domains: [''],\n brands: [{ name: '', products: [''] }]\n });\n\n const [isLoading, setIsLoading] = useState(false);\n const [isAutofilling, setIsAutofilling] = useState(false);\n const [error, setError] = useState(null);\n\n // Reset form when drawer opens with a competitor name\n useEffect(() => {\n if (isOpen && competitorName) {\n // Check if this competitor already has details saved\n const existingDetails = projectData.competitor_details?.find(c => c.name === competitorName);\n\n if (existingDetails) {\n // Use the existing details\n setCompetitorDetails({\n name: existingDetails.name,\n domains: existingDetails.domains.length ? existingDetails.domains : [''],\n brands: existingDetails.brands.length ? existingDetails.brands : [{ name: '', products: [''] }]\n });\n } else {\n // Initialize with default values\n setCompetitorDetails({\n name: competitorName,\n domains: [''],\n brands: [{ name: '', products: [''] }]\n });\n }\n }\n }, [isOpen, competitorName, projectData.competitor_details]);\n\n // Handle domain changes\n const handleDomainChange = (index, value) => {\n const updatedDomains = [...competitorDetails.domains];\n updatedDomains[index] = value;\n setCompetitorDetails({\n ...competitorDetails,\n domains: updatedDomains\n });\n };\n\n // Add domain field\n const addDomainField = () => {\n setCompetitorDetails({\n ...competitorDetails,\n domains: [...competitorDetails.domains, '']\n });\n };\n\n // Remove domain field\n const removeDomainField = (index) => {\n const updatedDomains = [...competitorDetails.domains];\n updatedDomains.splice(index, 1);\n setCompetitorDetails({\n ...competitorDetails,\n domains: updatedDomains.length ? updatedDomains : ['']\n });\n };\n\n // Handle brand name change\n const handleBrandNameChange = (brandIndex, value) => {\n const updatedBrands = [...competitorDetails.brands];\n updatedBrands[brandIndex].name = value;\n setCompetitorDetails({\n ...competitorDetails,\n brands: updatedBrands\n });\n };\n\n // Add brand\n const addBrand = () => {\n setCompetitorDetails({\n ...competitorDetails,\n brands: [...competitorDetails.brands, { name: '', products: [''] }]\n });\n };\n\n // Remove brand\n const removeBrand = (brandIndex) => {\n const updatedBrands = [...competitorDetails.brands];\n updatedBrands.splice(brandIndex, 1);\n setCompetitorDetails({\n ...competitorDetails,\n brands: updatedBrands.length ? updatedBrands : [{ name: '', products: [''] }]\n });\n };\n\n // Handle product change\n const handleProductChange = (brandIndex, productIndex, value) => {\n const updatedBrands = [...competitorDetails.brands];\n updatedBrands[brandIndex].products[productIndex] = value;\n setCompetitorDetails({\n ...competitorDetails,\n brands: updatedBrands\n });\n };\n\n // Add product field\n const addProductField = (brandIndex) => {\n const updatedBrands = [...competitorDetails.brands];\n updatedBrands[brandIndex].products.push('');\n setCompetitorDetails({\n ...competitorDetails,\n brands: updatedBrands\n });\n };\n\n // Remove product field\n const removeProductField = (brandIndex, productIndex) => {\n const updatedBrands = [...competitorDetails.brands];\n updatedBrands[brandIndex].products.splice(productIndex, 1);\n\n // Ensure at least one empty product field\n if (updatedBrands[brandIndex].products.length === 0) {\n updatedBrands[brandIndex].products = [''];\n }\n\n setCompetitorDetails({\n ...competitorDetails,\n brands: updatedBrands\n });\n };\n\n // Auto-fill competitor details using AI\n const autoFillCompetitorDetails = async () => {\n if (!competitorDetails.name.trim()) {\n setError('Competitor name is required to auto-fill details');\n return;\n }\n\n setIsAutofilling(true);\n setError(null);\n\n try {\n // Prepare the project context data for the API call\n const projectContext = {\n name: projectData.name || '',\n user_persona: projectData.user_persona || '',\n domains: projectData.domains || [],\n brands: projectData.brands || []\n };\n\n const response = await axios.post('/api/competitors/suggest_details', {\n competitor_name: competitorDetails.name,\n project_context: projectContext\n });\n\n if (response.data && response.data.success) {\n // Format the domains to ensure they're not empty\n const domains = response.data.details.domains || [];\n const filteredDomains = domains.filter(domain => domain && domain.trim());\n\n // Format the brands to ensure they're not empty\n const brands = response.data.details.brands || [];\n const filteredBrands = brands.map(brand => ({\n name: (brand.name || brand.brand_name || '').trim(),\n products: (brand.products || []).filter(product => product && product.trim())\n })).filter(brand => brand.name);\n\n // Set default values if AI returned empty results\n setCompetitorDetails({\n ...competitorDetails,\n domains: filteredDomains.length ? filteredDomains : [''],\n brands: filteredBrands.length ? filteredBrands : [{ name: '', products: [''] }]\n });\n } else {\n throw new Error(response.data?.message || 'Failed to get competitor details');\n }\n } catch (err) {\n console.error('Error auto-filling competitor details:', err);\n setError('Failed to auto-fill competitor details. Please try again or fill in manually.');\n } finally {\n setIsAutofilling(false);\n }\n };\n\n // Submit the competitor details\n const handleSubmit = () => {\n // Filter out empty domains and products\n const filteredDomains = competitorDetails.domains.filter(domain => domain.trim());\n\n const filteredBrands = competitorDetails.brands\n .filter(brand => brand.name.trim())\n .map(brand => ({\n name: brand.name,\n products: brand.products.filter(product => product.trim())\n }));\n\n const competitorData = {\n name: competitorDetails.name.trim(),\n domains: filteredDomains,\n brands: filteredBrands\n };\n\n onSave(competitorData);\n onClose();\n };\n\n if (!isOpen) return null;\n\n return (\n
\n {/* Backdrop */}\n \n\n {/* Drawer */}\n
\n
\n {/* Header */}\n
\n

\n {competitorDetails.name ? `${competitorDetails.name} Details` : 'Competitor Details'}\n

\n \n \n \n
\n\n {/* Content */}\n
\n {error && (\n
\n {error}\n
\n )}\n\n
\n {/* Competitor Name */}\n
\n \n setCompetitorDetails({...competitorDetails, name: e.target.value})}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500\"\n placeholder=\"Enter competitor name\"\n />\n
\n\n {/* Auto-fill button */}\n
\n \n {isAutofilling ? (\n <>\n \n Auto-filling...\n \n ) : (\n <>\n \n Auto-fill Details with AI\n \n )}\n \n

\n This will use AI to suggest domains, brands, and products for this competitor\n

\n
\n\n {/* Domains */}\n
\n \n
\n {competitorDetails.domains.map((domain, index) => (\n
\n handleDomainChange(index, e.target.value)}\n className=\"flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500\"\n placeholder=\"e.g., example.com\"\n />\n removeDomainField(index)}\n className=\"p-2 text-gray-400 hover:text-red-500\"\n >\n \n \n
\n ))}\n \n \n Add Domain\n \n
\n
\n\n {/* Brands and Products */}\n
\n \n
\n {competitorDetails.brands.map((brand, brandIndex) => (\n
\n {/* Brand Name */}\n
\n handleBrandNameChange(brandIndex, e.target.value)}\n className=\"flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500\"\n placeholder=\"Brand name\"\n />\n removeBrand(brandIndex)}\n className=\"p-2 text-gray-400 hover:text-red-500\"\n >\n \n \n
\n\n {/* Products */}\n
\n \n
\n {brand.products.map((product, productIndex) => (\n
\n handleProductChange(brandIndex, productIndex, e.target.value)}\n className=\"flex-1 px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500\"\n placeholder=\"Product name\"\n />\n removeProductField(brandIndex, productIndex)}\n className=\"p-1.5 text-gray-400 hover:text-red-500\"\n >\n \n \n
\n ))}\n addProductField(brandIndex)}\n className=\"text-indigo-600 hover:text-indigo-800 text-xs flex items-center mt-1\"\n >\n \n Add Product\n \n
\n
\n
\n ))}\n \n \n Add Brand\n \n
\n
\n
\n
\n\n {/* Footer */}\n
\n \n Cancel\n \n \n Save Details\n \n
\n
\n
\n
\n );\n};\n\nexport default CompetitorDetailsDrawer;\n", "import React, { useState, useEffect, useContext } from 'react';\nimport { useNavigate, useParams, useLocation, Routes, Route, Navigate } from 'react-router-dom';\nimport axios from '../../AxiosConfig';\nimport {\n Edit,\n Trash,\n AlertCircle,\n MessageSquare,\n Link as LinkIcon,\n Search,\n FileText,\n BarChart,\n Menu,\n X,\n Layout,\n Users,\n Gauge,\n Compass,\n PieChart, // Icon for Analytics\n MessageCircle, // Alternative icon for Prompts\n CheckCircle,\n TrendingUp, // Icon for Opportunities\n Target, // Icon for Strategy\n BarChart3, // Icon for Measurement\n ChevronDown,\n ChevronRight,\n Settings,\n Loader2, // Icon for loading spinner\n Lock, // Icon for locked features\n Download // Icon for Data Export\n} from 'lucide-react';\nimport PromptAnalytics from './PromptAnalytics';\nimport ProjectLinks from './ProjectLinks';\nimport ProjectOverview from './ProjectOverview';\nimport UnifiedPromptManagement from './UnifiedPromptManagement';\nimport ManageTopic from './ManageTopic';\nimport EditTopic from './EditTopic';\nimport PromptForm from './PromptForm';\nimport CompetitorAnalysis from './CompetitorAnalysis';\nimport SentimentAnalysis from './SentimentAnalysis';\nimport ContentAnalysis from './ContentAnalysis/ContentAnalysis'; // Import the new ContentAnalysis component\nimport Optimization from './Optimization';\nimport ExploreConversations from './ExploreConversations';\nimport Opportunities from './Opportunities'; // Import the new Opportunities component\nimport Strategy from './Strategy'; // Import the new Strategy component\nimport Measurement from './Measurement'; // Import the new Measurement component\nimport ProjectForm from './ProjectForm'; // Import ProjectForm for inline editing\nimport LockedFeatureView from './LockedFeatureView'; // Import LockedFeatureView for locked sections\nimport DataExportSection from './DataExportSection'; // Import DataExportSection\nimport { AuthContext } from '../../../context/AuthContext';\nimport {trackEvent} from \"../../Analytics/mixpanel\"; // Import AuthContext\n\n// Client tier enum values (matching Rails)\nconst CLIENT_TIER = {\n NONE: 0,\n MONITORING: 1,\n SERVICING: 2\n};\n\n// Helper to check if trial is expired\nconst isTrialExpired = (trialEndDate) => {\n if (!trialEndDate) return false;\n const trialDate = new Date(trialEndDate + 'T00:00:00');\n const today = new Date();\n today.setHours(0, 0, 0, 0);\n return trialDate < today;\n};\n\n// HubSpot Form Modal Component\nconst UnlockModal = ({ isOpen, onClose, user, source }) => {\n const [formLoaded, setFormLoaded] = useState(false);\n useEffect(() => {\n if (isOpen) {\n // Track modal open\n trackEvent('Unlock Modal Opened', {\n user_id: user?.id,\n source: source || 'workspace',\n modal_type: 'hubspot_form'\n });\n\n // Load HubSpot script if not already loaded\n const existingScript = document.querySelector('script[src=\"https://js.hsforms.net/forms/embed/48492217.js\"]');\n if (!existingScript) {\n const script = document.createElement('script');\n script.src = 'https://js.hsforms.net/forms/embed/48492217.js';\n script.defer = true;\n document.body.appendChild(script);\n\n // Listen for form ready event\n script.onload = () => {\n // Give HubSpot a moment to initialize\n setTimeout(() => setFormLoaded(true), 500);\n };\n } else {\n // Script already exists, form should load quickly\n setTimeout(() => setFormLoaded(true), 100);\n }\n } else {\n setFormLoaded(false);\n }\n }, [isOpen, user, source]);\n\n const handleClose = () => {\n trackEvent('Unlock Modal Closed', {\n user_id: user?.id,\n source: source || 'workspace',\n modal_type: 'hubspot_form'\n });\n onClose();\n };\n\n if (!isOpen) return null;\n\n return (\n
\n
\n \n \n \n\n {/* Loading state while form loads */}\n {!formLoaded && (\n
\n
\n
\n )}\n\n
\n
\n \n );\n};\n\nconst ProjectDashboard = () => {\n const [project, setProject] = useState(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n const [deleteModalOpen, setDeleteModalOpen] = useState(false);\n const [sidebarOpen, setSidebarOpen] = useState(false);\n const [showUnlockModal, setShowUnlockModal] = useState(false); // Unlock modal state\n const [showAuditCompleteNotification, setShowAuditCompleteNotification] = useState(false);\n const [previousAuditState, setPreviousAuditState] = useState(null);\n const [analyticsExpanded, setAnalyticsExpanded] = useState(false); // State for Analytics group expansion\n const [projectSettingsExpanded, setProjectSettingsExpanded] = useState(false); // State for Project Settings group expansion\n const [deleteLoading, setDeleteLoading] = useState(false); // State for delete operation loading\n const [deleteSuccess, setDeleteSuccess] = useState(false); // State for delete success message\n\n const navigate = useNavigate();\n const { projectId } = useParams();\n const location = useLocation();\n const { user } = useContext(AuthContext); // Get user from AuthContext\n\n // Get query parameters to check if explore feature should be shown\n const queryParams = new URLSearchParams(location.search);\n const showExplore = queryParams.get('explore') !== null;\n\n // Determine which features are locked based on trial status and client tier\n const getLockedFeatures = () => {\n // Don't lock anything until project is loaded\n if (!project) {\n return new Set();\n }\n\n // If user has no trial_end_date or trial hasn't expired, nothing is locked\n if (!user?.trial_end_date || !isTrialExpired(user.trial_end_date)) {\n return new Set();\n }\n\n const clientTier = project.client_tier ?? CLIENT_TIER.NONE;\n\n // SERVICING tier - nothing locked\n if (clientTier === CLIENT_TIER.SERVICING) {\n return new Set();\n }\n\n // MONITORING tier - opportunities, strategy, measurement, content, optimization locked\n if (clientTier === CLIENT_TIER.MONITORING) {\n return new Set(['opportunities', 'strategy', 'measurement', 'content', 'optimization']);\n }\n\n // NONE tier - opportunities, strategy, measurement, and ALL analytics sections locked\n return new Set(['opportunities', 'strategy', 'measurement', 'prompts', 'links', 'competitors', 'sentiment', 'content', 'optimization']);\n };\n\n const lockedFeatures = getLockedFeatures();\n\n const isFeatureLocked = (featureId) => {\n return lockedFeatures.has(featureId);\n };\n\n // Determine current section from URL path\n const pathSegments = location.pathname.split('/');\n const currentPath = location.pathname.split('/').pop();\n\n // Check if we're on a topic-specific page or research page\n const isTopicPage = pathSegments.includes('topics') && pathSegments.length > 4;\n const isResearchPage = pathSegments.includes('research') || currentPath === 'research';\n const isPromptsRelated = pathSegments.includes('prompts') || isTopicPage || isResearchPage;\n const isOptimizationPage = pathSegments.includes('optimization');\n\n // Update the validSections array to include project settings subgroups and remove optimization\n const validSections = ['overview', 'opportunities', 'strategy', 'measurement', 'explore', 'prompts', 'analytics', 'links', 'competitors', 'sentiment', 'content', 'optimization', 'manage-prompts', 'edit-project', 'data-export'];\n\n // Analytics sub-sections\n const analyticsSubSections = ['prompts', 'links', 'competitors', 'sentiment', 'content', 'optimization'];\n\n // Project Settings sub-sections\n const projectSettingsSubSections = ['manage-prompts', 'edit-project', 'data-export'];\n\n // Determine which section should be highlighted\n let expandedSection;\n if (isOptimizationPage) {\n expandedSection = 'optimization';\n if (!analyticsExpanded) {\n setAnalyticsExpanded(true);\n }\n } else if (isPromptsRelated && !analyticsSubSections.includes(currentPath) && !projectSettingsSubSections.includes(currentPath)) {\n expandedSection = 'manage-prompts'; // Default prompts behavior goes to manage-prompts\n } else if (analyticsSubSections.includes(currentPath)) {\n expandedSection = currentPath;\n // Auto-expand analytics group if we're on one of its sub-sections\n if (!analyticsExpanded) {\n setAnalyticsExpanded(true);\n }\n } else if (projectSettingsSubSections.includes(currentPath)) {\n expandedSection = currentPath;\n // Auto-expand project settings group if we're on one of its sub-sections\n if (!projectSettingsExpanded) {\n setProjectSettingsExpanded(true);\n }\n } else if (validSections.includes(currentPath)) {\n expandedSection = currentPath;\n } else {\n expandedSection = 'overview';\n }\n\n const fetchProject = async (showLoading = true) => {\n try {\n if (showLoading) setLoading(true);\n const response = await axios.get(`/api/projects/${projectId}`);\n const newProject = response.data;\n\n // Check for audit completion transition\n if (project && previousAuditState) {\n const wasGenerating = previousAuditState.generating_audit;\n const wasComplete = previousAuditState.audit_step?.current === previousAuditState.audit_step?.total;\n\n const isNowComplete = newProject.audit_step?.current === newProject.audit_step?.total;\n const isNoLongerGenerating = !newProject.generating_audit;\n\n // Show notification if audit just completed\n if (wasGenerating && !wasComplete && isNowComplete && isNoLongerGenerating) {\n setShowAuditCompleteNotification(true);\n }\n }\n\n // Update previous state for next comparison\n setPreviousAuditState({\n generating_audit: newProject.generating_audit,\n audit_step: newProject.audit_step\n });\n\n setProject(newProject);\n setError(null);\n } catch (err) {\n console.error('Error fetching project:', err);\n // Show detailed error message to the user\n const errorMessage = err.response?.data?.message || err.message || 'Failed to load project. Please try again later.';\n setError(errorMessage);\n } finally {\n if (showLoading) setLoading(false);\n }\n };\n\n useEffect(() => {\n if (projectId) {\n fetchProject();\n }\n }, [projectId]);\n\n // Poll for audit updates when generating_audit is true\n useEffect(() => {\n let pollInterval;\n\n if (project?.generating_audit) {\n // Poll every 10 seconds when audit is in progress\n pollInterval = setInterval(() => {\n fetchProject(false); // Don't show loading spinner for polling\n }, 10000);\n }\n\n return () => {\n if (pollInterval) {\n clearInterval(pollInterval);\n }\n };\n }, [project?.generating_audit, projectId]);\n\n // Simple edit function - no trial restrictions\n const handleEdit = () => {\n // Navigate to edit-project section\n handleSectionChange('edit-project');\n };\n\n const handleDelete = async () => {\n try {\n setDeleteLoading(true);\n await axios.delete(`/api/projects/${projectId}`);\n setDeleteSuccess(true);\n // Wait a moment to show success message before navigating\n setTimeout(() => {\n navigate('/workspace');\n }, 1500);\n } catch (err) {\n console.error('Error deleting project:', err);\n // Show detailed error message to the user\n const errorMessage = err.response?.data?.message || err.message || 'Failed to delete project. Please try again.';\n setError(errorMessage);\n setDeleteLoading(false);\n setDeleteModalOpen(false);\n }\n };\n\n const handleOpenDeleteModal = () => {\n setDeleteModalOpen(true);\n setDeleteSuccess(false);\n setDeleteLoading(false);\n };\n\n const toggleSidebar = () => {\n setSidebarOpen(!sidebarOpen);\n };\n\n // Handle viewing analysis - UPDATED to navigate to audit page\n const handleViewAnalysis = () => {\n setShowAuditCompleteNotification(false);\n navigate(`/projects/${projectId}/audit`);\n };\n\n // Dismiss audit complete notification\n const dismissAuditNotification = () => {\n setShowAuditCompleteNotification(false);\n };\n\n const handleSectionChange = (section) => {\n // Navigate to the correct URL instead of just changing state\n if (section === 'explore') {\n // When navigating to explore, ensure the query parameter is included\n navigate(`/projects/${projectId}/${section}?explore=true`);\n } else {\n navigate(`/projects/${projectId}/${section}`);\n }\n\n // Close sidebar on mobile after selecting a section\n if (window.innerWidth < 768) {\n setSidebarOpen(false);\n }\n };\n\n const toggleAnalyticsGroup = () => {\n setAnalyticsExpanded(!analyticsExpanded);\n };\n\n const toggleProjectSettingsGroup = () => {\n setProjectSettingsExpanded(!projectSettingsExpanded);\n };\n\n const handleEditProjectClick = () => {\n handleEdit(); // Use simplified edit function\n };\n\n // Handle project form completion (save/cancel)\n const handleProjectFormComplete = (updatedProjectData = null) => {\n // If we have updated project data, update state without refetching\n if (updatedProjectData) {\n setProject(prevProject => ({\n ...prevProject,\n ...updatedProjectData\n }));\n }\n // Navigate back to overview\n handleSectionChange('overview');\n };\n\n // Content render methods with consistent padding\n const renderOptimization = () => {\n return (\n
\n \n

Prompt Optimization

\n

Coming soon

\n
\n

\n Our optimization tools will help you fine-tune specific prompts to increase their frequency and effectiveness.\n Improve prompt visibility, enhance response quality, and achieve better engagement through data-driven optimization.\n

\n
\n
\n );\n };\n\n // Wrapper for component-based content - removed extra padding\n const renderComponentContent = (Component) => {\n return (\n
\n \n
\n );\n };\n\n // Render ProjectForm with special props\n const renderProjectForm = () => {\n return (\n
\n \n
\n );\n };\n\n // Create base navigation items with Analytics and Project Settings parent groups\n let navigationItems = [\n { id: 'overview', label: 'Overview', icon: },\n { id: 'opportunities', label: 'Opportunities', icon: },\n { id: 'strategy', label: 'Strategy', icon: },\n { id: 'measurement', label: 'Measurement', icon: },\n {\n id: 'analytics',\n label: 'Analytics',\n icon: ,\n isParent: true,\n expanded: analyticsExpanded,\n children: [\n { id: 'prompts', label: 'Prompts', icon: },\n { id: 'links', label: 'Links', icon: },\n { id: 'competitors', label: 'Competitors', icon: },\n { id: 'sentiment', label: 'Sentiment', icon: },\n { id: 'content', label: 'Content', icon: },\n { id: 'optimization', label: 'Optimization', icon: },\n ]\n },\n {\n id: 'project-settings',\n label: 'Project Settings',\n icon: ,\n isParent: true,\n expanded: projectSettingsExpanded,\n children: [\n { id: 'manage-prompts', label: 'Prompts & Topics', icon: },\n { id: 'edit-project', label: 'Edit Project', icon: , isAction: true },\n { id: 'data-export', label: 'Data Export', icon: },\n { id: 'delete-project', label: 'Delete Project', icon: , isAction: true },\n ]\n },\n ];\n\n // Add Explore section only if showExplore is true\n if (showExplore) {\n // Find the index of 'overview' to insert 'explore' after it\n const overviewIndex = navigationItems.findIndex(item => item.id === 'overview');\n navigationItems.splice(overviewIndex + 1, 0, {\n id: 'explore',\n label: 'Explore',\n icon: \n });\n }\n\n // Render lock icon for locked features\n const renderLockIcon = (featureId) => {\n if (isFeatureLocked(featureId)) {\n return ;\n }\n return null;\n };\n\n if (loading) {\n return (\n
\n
Loading project...
\n
\n );\n }\n\n if (error) {\n return (\n
\n
\n
\n \n

Error Loading Project

\n
\n

{error}

\n navigate('/workspace')}\n >\n Return to Workspace\n \n
\n
\n );\n }\n\n if (!project) {\n return (\n
\n
\n
\n \n

Project Not Found

\n
\n

The project you are looking for does not exist or you do not have permission to view it.

\n navigate('/workspace')}\n >\n Return to Workspace\n \n
\n
\n );\n }\n\n // Determine which component to render based on the URL path\n const renderMainContent = () => {\n // Check if current section is locked - show LockedFeatureView\n if (isFeatureLocked(expandedSection)) {\n return (\n setShowUnlockModal(true)}\n />\n );\n }\n\n // Check for new prompts routes structure FIRST (before old topics routes)\n if (pathSegments.includes('prompts')) {\n const promptsIndex = pathSegments.indexOf('prompts');\n\n // Handle /projects/:projectId/prompts/research\n if (pathSegments[promptsIndex + 1] === 'research') {\n return (\n
\n \n
\n );\n }\n\n // Handle /projects/:projectId/prompts/topics/:topicId\n if (pathSegments[promptsIndex + 1] === 'topics' && pathSegments[promptsIndex + 2]) {\n const topicId = pathSegments[promptsIndex + 2];\n return (\n
\n \n
\n );\n }\n\n // Handle /projects/:projectId/prompts (could be analytics or manage-prompts context)\n if (promptsIndex === pathSegments.length - 1) {\n // Check the expandedSection to determine context\n if (expandedSection === 'prompts') {\n // This is Analytics > Prompts - render PromptAnalytics\n return renderComponentContent(PromptAnalytics);\n } else {\n // This is legacy or manage-prompts context - render UnifiedPromptManagement\n return (\n
\n \n
\n );\n }\n }\n }\n\n // Check if we're on topic-related pages that include prompts (form pages)\n if (pathSegments.includes('topics') && pathSegments.includes('prompts')) {\n const topicsIndex = pathSegments.indexOf('topics');\n const promptsIndex = pathSegments.indexOf('prompts');\n\n // Only proceed if topics comes before prompts (meaning this is a prompt form route)\n if (topicsIndex < promptsIndex && topicsIndex < pathSegments.length - 1) {\n const topicId = pathSegments[topicsIndex + 1];\n\n if (promptsIndex < pathSegments.length - 1) {\n const promptId = pathSegments[promptsIndex + 1];\n\n // Handle prompt routes\n if (promptId === 'new') {\n return ;\n } else if (pathSegments.includes('edit')) {\n return ;\n }\n }\n }\n }\n\n // Check if we're on OLD topic-related pages (for backward compatibility)\n if (pathSegments.includes('topics') && !pathSegments.includes('prompts')) {\n const topicsIndex = pathSegments.indexOf('topics');\n\n // Only proceed if there's a topic ID after 'topics' in the URL\n if (topicsIndex < pathSegments.length - 1) {\n const topicId = pathSegments[topicsIndex + 1];\n\n if (pathSegments.includes('edit')) {\n return ;\n } else if (topicId === 'new') {\n return ;\n } else {\n return ;\n }\n }\n }\n\n // Regular dashboard sections\n switch (expandedSection) {\n case 'overview':\n return renderComponentContent(ProjectOverview);\n case 'opportunities':\n return renderComponentContent(Opportunities);\n case 'strategy':\n return renderComponentContent(Strategy);\n case 'measurement':\n return renderComponentContent(Measurement);\n case 'explore':\n // Only render Explore if the showExplore flag is true\n if (showExplore) {\n return renderComponentContent(ExploreConversations);\n } else {\n // Redirect to overview if someone tries to access explore without the query param\n navigate(`/projects/${projectId}/overview`);\n return renderComponentContent(ProjectOverview);\n }\n case 'prompts':\n // This is the Analytics > Prompts section - always render PromptAnalytics\n return renderComponentContent(PromptAnalytics);\n case 'manage-prompts':\n // This is the Project Settings > Prompts & Topics section - render UnifiedPromptManagement\n return (\n
\n \n
\n );\n case 'links':\n return renderComponentContent(ProjectLinks);\n case 'competitors':\n return renderComponentContent(CompetitorAnalysis);\n case 'sentiment':\n return renderComponentContent(SentimentAnalysis);\n case 'content':\n return renderComponentContent(ContentAnalysis);\n case 'optimization':\n return renderComponentContent(Optimization);\n case 'edit-project':\n // Render the ProjectForm inline\n return renderProjectForm();\n case 'data-export':\n // Render the DataExportSection\n return (\n
\n \n
\n );\n default:\n return renderComponentContent(ProjectOverview);\n }\n };\n\n return (\n
\n {/* Mobile header with hamburger menu */}\n
\n
\n \n {sidebarOpen ? (\n \n ) : (\n \n )}\n \n

\n {project.name}\n

\n
\n
\n \n \n \n \n \n \n
\n
\n\n {/* Main layout container */}\n
\n {/* Sidebar - Desktop (always visible) and Mobile (conditional) */}\n \n {/* Desktop Header (hidden on mobile) */}\n
\n

{project.name}

\n

\n Created on {new Date(project.created_at).toLocaleDateString()}\n

\n
\n\n {/* Close button (mobile only) */}\n
\n \n \n \n
\n\n {/* Navigation Items */}\n \n\n {/* View Client Audit Button - always available */}\n
\n navigate(`/projects/${projectId}/audit`)}\n className=\"w-full inline-flex items-center justify-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\"\n >\n \n View Client Audit\n \n
\n\n \n\n {/* Overlay for mobile sidebar */}\n {sidebarOpen && (\n
\n )}\n\n {/* Main Content Area - Updated with conditional logic for Strategy component and edit-project and data-export */}\n
\n
\n {renderMainContent()}\n
\n
\n
\n\n {/* Audit Complete Notification - Fixed Bottom Right */}\n {showAuditCompleteNotification && (\n
\n
\n
\n
\n
\n \n
\n
\n
\n

\n Analysis Complete!\n

\n

\n Your analysis for your project is ready to view.\n

\n
\n \n \n View Analysis\n \n \n Dismiss\n \n
\n
\n
\n \n \n \n
\n
\n
\n
\n )}\n\n {/* Delete Confirmation Modal */}\n {deleteModalOpen && (\n
\n
\n
\n
\n
\n\n ​\n\n
\n {deleteSuccess ? (\n // Success state\n
\n
\n
\n \n
\n

Project Deleted

\n

\n Your project has been successfully deleted. Redirecting...\n

\n
\n
\n ) : (\n // Confirmation or loading state\n <>\n
\n
\n
\n {deleteLoading ? (\n \n ) : (\n \n )}\n
\n
\n

\n {deleteLoading ? 'Deleting Project...' : 'Delete Project'}\n

\n
\n {deleteLoading ? (\n

\n Please wait while we delete your project and all associated data. This may take a moment...\n

\n ) : (\n

\n Are you sure you want to delete this project? All of your project data including brands, products, and topics will be permanently removed. This action cannot be undone.\n

\n )}\n
\n
\n
\n
\n
\n \n {deleteLoading && (\n \n )}\n {deleteLoading ? 'Deleting...' : 'Delete'}\n \n setDeleteModalOpen(false)}\n disabled={deleteLoading}\n >\n Cancel\n \n
\n \n )}\n
\n
\n
\n )}\n\n {/* Unlock Modal */}\n setShowUnlockModal(false)}\n />\n \n );\n};\n\nexport default ProjectDashboard;", "// app/javascript/components/Dashboard/Projects/PromptAnalytics.js\nimport React, { useState, useEffect, useCallback, useRef, useContext } from 'react';\nimport { Eye, RotateCcw, ChevronLeft, ChevronRight, ArrowDown, ArrowUp, BarChart, Search, X, MessageSquare, ArrowRight, HelpCircle, Download } from 'lucide-react';\nimport { useLocation, useNavigate, useParams } from 'react-router-dom';\nimport axios from '../../AxiosConfig';\nimport SideDrawer from './SideDrawer';\nimport ResponseCard from './ResponseCard';\nimport { useProjectDashboard } from '../../../context/ProjectDashboardContext';\nimport { AuthContext } from '../../../context/AuthContext';\nimport { trackEvent } from '../../Analytics/mixpanel';\n\nconst PromptAnalytics = ({ projectId, project }) => {\n const location = useLocation();\n const navigate = useNavigate();\n const { user } = useContext(AuthContext);\n\n // Get persisted state from context\n const {\n analyticsPrompts, setAnalyticsPrompts,\n analyticsSearchTerm, setAnalyticsSearchTerm,\n analyticsDebouncedSearchTerm, setAnalyticsDebouncedSearchTerm,\n analyticsSelectedTopic, setAnalyticsSelectedTopic,\n analyticsSelectedPlatform, setAnalyticsSelectedPlatform,\n analyticsTopics, setAnalyticsTopics,\n analyticsCurrentPage, setAnalyticsCurrentPage,\n analyticsTotalItems, setAnalyticsTotalItems,\n analyticsTotalPages, setAnalyticsTotalPages,\n analyticsSortField, setAnalyticsSortField,\n analyticsSortDirection, setAnalyticsSortDirection,\n analyticsResponses, setAnalyticsResponses\n } = useProjectDashboard();\n\n // Local state (doesn't need to persist)\n const [initialLoading, setInitialLoading] = useState(true);\n const [filterLoading, setFilterLoading] = useState(false);\n const [error, setError] = useState(null);\n const [selectedPrompt, setSelectedPrompt] = useState(null);\n const [sideDrawerOpen, setSideDrawerOpen] = useState(false);\n const [loadingResponses, setLoadingResponses] = useState(false);\n const [downloadingCsv, setDownloadingCsv] = useState(false);\n const [promptToOptimize, setPromptToOptimize] = useState(null);\n const [projectTopics, setProjectTopics] = useState([]);\n const [loadingTopics, setLoadingTopics] = useState(false);\n const [showPromptTypeTooltip, setShowPromptTypeTooltip] = useState(false);\n const searchDebounceTimeoutRef = useRef(null);\n const initialLoadCompletedRef = useRef(false);\n const lastQueryParamsRef = useRef('');\n\n // Constants\n const [itemsPerPage] = useState(15);\n\n const platforms = [\n { value: '', label: 'All Platforms' },\n { value: 'chatgpt', label: 'ChatGPT' },\n { value: 'google_ai_overview', label: 'Google AI Overview' },\n { value: 'perplexity', label: 'Perplexity' }\n ];\n\n // Prompt type mapping\n const getPromptTypeLabel = (promptTypeValue) => {\n const promptTypeMap = {\n 0: 'Recommendation',\n 1: 'Informational',\n 2: 'Branded'\n };\n return promptTypeMap[promptTypeValue] || 'Unknown';\n };\n\n // Prompt type descriptions for tooltip\n const promptTypeDescriptions = {\n 'Recommendation': 'Prompts where users are seeking product or service recommendations',\n 'Informational': 'Prompts where users are seeking information, answers, or knowledge about a topic',\n 'Branded': 'Prompts that specifically mention a brand or company by name'\n };\n\n // Traffic/Volume color mapping\n const getVolumeColor = (volume) => {\n if (volume >= 70) return 'bg-red-100 text-red-800';\n if (volume >= 40) return 'bg-yellow-100 text-yellow-800';\n return 'bg-green-100 text-green-800';\n };\n\n // Difficulty color mapping\n const getDifficultyColor = (difficulty) => {\n if (difficulty >= 80) return 'bg-red-100 text-red-800';\n if (difficulty >= 60) return 'bg-orange-100 text-orange-800';\n if (difficulty >= 30) return 'bg-yellow-100 text-yellow-800';\n return 'bg-green-100 text-green-800';\n };\n\n // Handle CSV download\n const handleDownloadCsv = async () => {\n try {\n setDownloadingCsv(true);\n\n trackEvent('Download CSV', {\n project_id: projectId,\n user_id: user?.id,\n total_prompts: analyticsTotalItems,\n source: 'prompt_analytics'\n });\n\n const downloadUrl = `/api/prompt_analytics/project/${projectId}/export.csv`;\n\n const link = document.createElement('a');\n link.href = downloadUrl;\n link.style.display = 'none';\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n\n } catch (err) {\n console.error('Error downloading CSV:', err);\n alert('Failed to download CSV. Please try again.');\n } finally {\n setDownloadingCsv(false);\n }\n };\n\n // Fetch the project's topics for the empty state\n useEffect(() => {\n const fetchProjectTopics = async () => {\n if (!projectId) return;\n\n try {\n setLoadingTopics(true);\n const response = await axios.get(`/api/projects/${projectId}/topics`);\n setProjectTopics(response.data || []);\n } catch (err) {\n console.error('Error fetching project topics:', err);\n } finally {\n setLoadingTopics(false);\n }\n };\n\n if (analyticsPrompts.length === 0 && analyticsTotalItems === 0 && !initialLoading && !filterLoading) {\n fetchProjectTopics();\n }\n }, [projectId, analyticsPrompts.length, analyticsTotalItems, initialLoading, filterLoading]);\n\n // Check for search parameter in URL when component mounts\n useEffect(() => {\n const params = new URLSearchParams(location.search);\n const searchFromUrl = params.get('search');\n\n if (searchFromUrl && !initialLoadCompletedRef.current) {\n setAnalyticsSearchTerm(searchFromUrl);\n setAnalyticsDebouncedSearchTerm(searchFromUrl);\n initialLoadCompletedRef.current = true;\n } else if (location.state?.search && !initialLoadCompletedRef.current) {\n setAnalyticsSearchTerm(location.state.search);\n setAnalyticsDebouncedSearchTerm(location.state.search);\n initialLoadCompletedRef.current = true;\n }\n }, [location, setAnalyticsSearchTerm, setAnalyticsDebouncedSearchTerm]);\n\n // Generate a query parameters string for comparison\n const getCurrentQueryParams = () => {\n return JSON.stringify({\n projectId,\n page: analyticsCurrentPage,\n topic: analyticsSelectedTopic,\n platform: analyticsSelectedPlatform,\n sortField: analyticsSortField,\n sortDirection: analyticsSortDirection,\n search: analyticsDebouncedSearchTerm\n });\n };\n\n // Fetch data on parameter changes\n useEffect(() => {\n const currentQueryParams = getCurrentQueryParams();\n\n const shouldFetch =\n (analyticsPrompts.length === 0 && !initialLoading && !filterLoading) ||\n initialLoadCompletedRef.current ||\n currentQueryParams !== lastQueryParamsRef.current;\n\n if (shouldFetch) {\n fetchPromptAnalytics();\n if (initialLoadCompletedRef.current) {\n initialLoadCompletedRef.current = false;\n }\n lastQueryParamsRef.current = currentQueryParams;\n }\n }, [projectId, analyticsCurrentPage, analyticsSelectedTopic, analyticsSelectedPlatform,\n analyticsSortField, analyticsSortDirection, analyticsDebouncedSearchTerm]);\n\n // Debounce search term changes\n useEffect(() => {\n if (searchDebounceTimeoutRef.current) {\n clearTimeout(searchDebounceTimeoutRef.current);\n }\n\n searchDebounceTimeoutRef.current = setTimeout(() => {\n setAnalyticsDebouncedSearchTerm(analyticsSearchTerm);\n setAnalyticsCurrentPage(1);\n }, 500);\n\n return () => {\n if (searchDebounceTimeoutRef.current) {\n clearTimeout(searchDebounceTimeoutRef.current);\n }\n };\n }, [analyticsSearchTerm, setAnalyticsDebouncedSearchTerm, setAnalyticsCurrentPage]);\n\n const fetchPromptAnalytics = async () => {\n try {\n if (analyticsPrompts.length === 0 && analyticsTopics.length === 0) {\n setInitialLoading(true);\n } else {\n setFilterLoading(true);\n }\n\n const params = {\n page: analyticsCurrentPage,\n per_page: itemsPerPage,\n sort_by: analyticsSortField,\n sort_direction: analyticsSortDirection,\n include_topics: 'true',\n search: analyticsDebouncedSearchTerm.trim()\n };\n\n if (analyticsSelectedTopic) {\n params.topic_id = analyticsSelectedTopic;\n }\n\n if (analyticsSelectedPlatform) {\n params.platform = analyticsSelectedPlatform;\n }\n\n const response = await axios.get(`/api/prompt_analytics/project/${projectId}/details`, { params });\n\n setAnalyticsPrompts(response.data.prompts || []);\n setAnalyticsTotalItems(response.data.total_count || 0);\n setAnalyticsTotalPages(response.data.total_pages || 1);\n\n if (response.data.topics) {\n const topicsData = response.data.topics.map(topic => ({\n value: topic.id.toString(),\n label: topic.name\n }));\n setAnalyticsTopics([{ value: '', label: 'All Topics' }, ...topicsData]);\n }\n\n if (analyticsDebouncedSearchTerm && response.data.prompts?.length === 1 && initialLoadCompletedRef.current) {\n handleViewResponses(response.data.prompts[0]);\n initialLoadCompletedRef.current = false;\n }\n\n setError(null);\n } catch (err) {\n console.error('Error fetching prompt analytics:', err);\n setError('Failed to load prompt analytics. Please try again later.');\n setAnalyticsPrompts([]);\n } finally {\n setInitialLoading(false);\n setFilterLoading(false);\n }\n };\n\n const fetchPromptResponses = async (promptId) => {\n try {\n setLoadingResponses(true);\n const response = await axios.get(`/api/prompt_analytics/prompt/${promptId}/responses`);\n setAnalyticsResponses(response.data.responses || []);\n } catch (err) {\n console.error('Error fetching prompt responses:', err);\n setAnalyticsResponses([]);\n } finally {\n setLoadingResponses(false);\n }\n };\n\n const handleViewResponses = async (prompt) => {\n trackEvent('Click view', {\n project_id: projectId,\n prompt_id: prompt.id,\n topic_id: prompt.topic_id,\n topic_name: prompt.topic_name,\n user_id: user?.id,\n source: 'prompt_analytics'\n });\n\n setSelectedPrompt(prompt);\n setSideDrawerOpen(true);\n await fetchPromptResponses(prompt.id);\n };\n\n const handleOptimize = (prompt) => {\n trackEvent('Click Optimize', {\n project_id: projectId,\n prompt_id: prompt.id,\n topic_id: prompt.topic_id,\n topic_name: prompt.topic_name,\n user_id: user?.id,\n source: 'prompt_analytics'\n });\n\n navigate(`/projects/${projectId}/optimization/${prompt.topic_id}/${prompt.id}`);\n };\n\n const closeOptimizeModal = () => {\n setPromptToOptimize(null);\n };\n\n const closeSideDrawer = () => {\n setSideDrawerOpen(false);\n setSelectedPrompt(null);\n };\n\n const clearFilters = () => {\n setAnalyticsSelectedTopic('');\n setAnalyticsSelectedPlatform('');\n setAnalyticsSearchTerm('');\n setAnalyticsSortField('id');\n setAnalyticsSortDirection('desc');\n setAnalyticsCurrentPage(1);\n };\n\n const handleSearchChange = (e) => {\n setAnalyticsSearchTerm(e.target.value);\n setAnalyticsCurrentPage(1);\n };\n\n const clearSearch = () => {\n setAnalyticsSearchTerm('');\n setAnalyticsCurrentPage(1);\n };\n\n const handleSort = (field) => {\n if (field === analyticsSortField) {\n setAnalyticsSortDirection(analyticsSortDirection === 'asc' ? 'desc' : 'asc');\n } else {\n setAnalyticsSortField(field);\n setAnalyticsSortDirection('desc');\n }\n setAnalyticsCurrentPage(1);\n };\n\n const handlePageChange = (newPage) => {\n if (newPage >= 1 && newPage <= analyticsTotalPages) {\n setAnalyticsCurrentPage(newPage);\n }\n };\n\n const navigateToTopic = (topicId) => {\n navigate(`/projects/${projectId}/topics/${topicId}`);\n };\n\n const getPlatformBadge = (platform) => {\n const colors = {\n chatgpt: 'bg-green-100 text-green-800',\n claude: 'bg-blue-100 text-blue-800',\n perplexity: 'bg-purple-100 text-purple-800',\n google_ai_overview: 'bg-orange-100 text-orange-800',\n 0: 'bg-green-100 text-green-800',\n 1: 'bg-blue-100 text-blue-800',\n 2: 'bg-purple-100 text-purple-800',\n 3: 'bg-orange-100 text-orange-800'\n };\n return colors[platform] || 'bg-gray-100 text-gray-800';\n };\n\n const getPlatformDisplayName = (platform) => {\n const names = {\n chatgpt: 'ChatGPT',\n claude: 'Claude',\n perplexity: 'Perplexity',\n google_ai_overview: 'Google AI Overview',\n 0: 'ChatGPT',\n 1: 'Claude',\n 2: 'Perplexity',\n 3: 'Google AI Overview'\n };\n return names[platform] || platform;\n };\n\n const getProminenceScoreColor = (score) => {\n if (score >= 70) return 'text-green-600 font-semibold';\n if (score >= 40) return 'text-yellow-600 font-semibold';\n return 'text-red-600 font-semibold';\n };\n\n const getSortIcon = (field) => {\n if (analyticsSortField === field) {\n return analyticsSortDirection === 'asc'\n ? \n : ;\n }\n return ;\n };\n\n const renderNoPromptsState = () => {\n const firstTopic = projectTopics.length > 0 ? projectTopics[0] : null;\n\n return (\n
\n \n

No Prompts Yet

\n

\n This project doesn't have any prompts yet. Create prompts within topics to start collecting response data.\n

\n\n {loadingTopics ? (\n
Loading topics...
\n ) : firstTopic ? (\n navigateToTopic(firstTopic.id)}\n className=\"inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\"\n >\n Go to {firstTopic.name} Topic \n \n ) : (\n navigate(`/projects/${projectId}/topics/new`)}\n className=\"inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\"\n >\n Create a Topic \n \n )}\n
\n );\n };\n\n if (initialLoading && analyticsPrompts.length === 0 && analyticsTopics.length === 0) {\n return (\n
\n
Loading analytics...
\n
\n );\n }\n\n if (error) {\n return (\n
\n

{error}

\n \n Try Again\n \n
\n );\n }\n\n if (analyticsTotalItems === 0 && !initialLoading && !filterLoading && !analyticsSearchTerm && !analyticsSelectedTopic && !analyticsSelectedPlatform && analyticsTopics.length > 1) {\n return renderNoPromptsState();\n }\n\n const startItem = Math.min((analyticsCurrentPage - 1) * itemsPerPage + 1, analyticsTotalItems);\n const endItem = Math.min(startItem + itemsPerPage - 1, analyticsTotalItems);\n\n return (\n
\n {filterLoading && (\n
\n
\n
\n
\n
\n )}\n\n {/* Header and Filters */}\n
\n
\n
\n

Prompt Analytics

\n
\n \n \n {downloadingCsv ? 'Downloading...' : 'Download CSV'}\n \n \n \n Clear Filters\n \n
\n
\n\n
\n {/* Search Filter */}\n
\n
\n
\n \n
\n \n {analyticsSearchTerm && (\n \n \n \n )}\n
\n
\n\n {/* Topic Filter */}\n
\n {\n setAnalyticsSelectedTopic(e.target.value);\n setAnalyticsCurrentPage(1);\n }}\n disabled={filterLoading}\n >\n {analyticsTopics.map(topic => (\n \n ))}\n \n
\n\n {/* Platform Filter */}\n
\n {\n setAnalyticsSelectedPlatform(e.target.value);\n setAnalyticsCurrentPage(1);\n }}\n disabled={filterLoading}\n >\n {platforms.map(platform => (\n \n ))}\n \n
\n
\n\n
\n Showing {startItem}-{endItem} of {analyticsTotalItems} prompts\n
\n
\n
\n\n {/* Results Table */}\n
\n \n \n \n \n \n \n \n \n \n \n \n \n handleSort('prompt')}\n >\n \n Prompt {getSortIcon('prompt')}\n \n \n \n handleSort('prompt_type')}\n >\n \n Prompt Type {getSortIcon('prompt_type')}\n
\n setShowPromptTypeTooltip(true)}\n onMouseLeave={() => setShowPromptTypeTooltip(false)}\n />\n {showPromptTypeTooltip && (\n
\n
\n
\n Recommendation: {promptTypeDescriptions.Recommendation}\n
\n
\n Informational: {promptTypeDescriptions.Informational}\n
\n
\n Branded: {promptTypeDescriptions.Branded}\n
\n
\n
\n )}\n
\n
\n \n handleSort('volume_estimate')}\n >\n \n Traffic {getSortIcon('volume_estimate')}\n \n \n handleSort('difficulty')}\n >\n \n Difficulty {getSortIcon('difficulty')}\n \n \n handleSort('brand_mentions_count')}\n >\n \n AI Mention {getSortIcon('brand_mentions_count')}\n \n \n
\n \n \n \n {initialLoading && analyticsPrompts.length === 0 ? (\n \n \n \n ) : analyticsPrompts.length === 0 ? (\n \n \n \n ) : (\n analyticsPrompts.map((prompt) => (\n \n \n \n \n \n \n \n \n \n ))\n )}\n \n
\n Topic\n \n Actions\n
\n Loading prompts...\n
\n

No prompts match your current filters

\n \n Clear filters to see all prompts\n \n
\n
\n

\n {prompt.prompt}\n

\n
\n
\n \n {prompt.topic_name}\n \n \n \n {getPromptTypeLabel(prompt.prompt_type)}\n \n \n \n {prompt.volume_estimate || 0}\n \n \n \n {prompt.difficulty || 0}\n \n \n 0 || prompt.product_mentions_count > 0\n ? 'bg-emerald-100 text-emerald-800'\n : 'bg-gray-100 text-gray-800'\n }`}>\n {prompt.brand_mentions_count > 0 || prompt.product_mentions_count > 0 ? 'Yes' : 'No'}\n \n \n
\n handleViewResponses(prompt)}\n className=\"inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\"\n disabled={filterLoading}\n >\n \n View\n \n handleOptimize(prompt)}\n className=\"inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-emerald-700 bg-emerald-100 hover:bg-emerald-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500\"\n disabled={filterLoading}\n >\n \n Optimize\n \n
\n
\n
\n\n {/* Pagination Controls */}\n {analyticsTotalPages > 1 && (\n
\n
\n
\n

\n Showing {startItem} to {endItem} of{' '}\n {analyticsTotalItems} results\n

\n
\n
\n \n
\n
\n
\n )}\n\n {/* Side Drawer */}\n \n {/* Prompt Text */}\n
\n

Prompt

\n
\n

{selectedPrompt?.prompt}

\n
\n
\n\n {/* Responses */}\n
\n

\n Responses ({analyticsResponses.length})\n

\n\n {loadingResponses ? (\n
\n
Loading responses...
\n
\n ) : (\n
\n {analyticsResponses.map((response) => (\n \n ))}\n
\n )}\n
\n \n
\n );\n};\n\nexport default PromptAnalytics;", "// app/javascript/components/UI/SideDrawer.js\nimport React from 'react';\nimport { X } from 'lucide-react';\n\nconst SideDrawer = ({\n isOpen,\n onClose,\n title,\n subtitle,\n children,\n width = 'max-w-2xl' // Default width, can be customized\n }) => {\n if (!isOpen) return null;\n\n return (\n
\n
\n {/* Backdrop overlay */}\n
\n\n {/* Drawer panel */}\n
\n
\n
\n
\n {/* Header */}\n
\n
\n
\n

\n {title}\n

\n {subtitle && (\n

\n {subtitle}\n

\n )}\n
\n
\n \n \n \n
\n
\n
\n\n {/* Content */}\n
\n {children}\n
\n
\n
\n
\n
\n
\n \n );\n};\n\nexport default SideDrawer;", "// app/javascript/components/UI/ResponseCard.js\nimport React from 'react';\nimport { ExternalLink, Clock } from 'lucide-react';\n\nconst ResponseCard = ({\n response,\n getPlatformBadge,\n showSourceLinks = false,\n showTimestamp = false\n }) => {\n // Determine if there are any customer mentions (brand or product)\n const hasCustomerMention =\n (response.brand_mentions && response.brand_mentions.length > 0) ||\n (response.product_mentions && response.product_mentions.length > 0);\n\n // Function to highlight mentions in the response text\n const highlightMentions = (text) => {\n if (!text) return text;\n\n let highlightedText = text;\n const mentions = [];\n\n // Collect all brand mentions\n if (response.brand_mentions) {\n response.brand_mentions.forEach(mention => {\n mentions.push({\n name: mention.brand_name,\n type: 'brand',\n className: 'bg-blue-100 text-blue-800 px-1 py-0.5 rounded font-medium'\n });\n });\n }\n\n // Collect all product mentions\n if (response.product_mentions) {\n response.product_mentions.forEach(mention => {\n mentions.push({\n name: mention.product_name,\n type: 'product',\n className: 'bg-green-100 text-green-800 px-1 py-0.5 rounded font-medium'\n });\n });\n }\n\n // Sort mentions by length (longest first) to avoid partial replacements\n mentions.sort((a, b) => b.name.length - a.name.length);\n\n // Apply highlighting for each mention\n mentions.forEach((mention, index) => {\n // Create a case-insensitive regex that matches whole words\n const regex = new RegExp(`\\\\b(${mention.name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')})\\\\b`, 'gi');\n\n // Use a unique placeholder to avoid nested replacements\n const placeholder = `__MENTION_${index}__`;\n\n // Replace matches with placeholder first\n highlightedText = highlightedText.replace(regex, placeholder);\n });\n\n // Now replace placeholders with actual highlighted spans\n mentions.forEach((mention, index) => {\n const placeholder = `__MENTION_${index}__`;\n const highlightSpan = `$1`;\n\n // Replace placeholder with the original text wrapped in highlight span\n const regex = new RegExp(`\\\\b(${mention.name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')})\\\\b`, 'gi');\n highlightedText = highlightedText.replace(placeholder, mention.name.replace(regex, highlightSpan));\n });\n\n return highlightedText;\n };\n\n // Function to render highlighted text safely\n const renderHighlightedText = (text) => {\n const highlightedText = highlightMentions(text);\n\n // If no mentions were found, return plain text\n if (highlightedText === text) {\n return {text};\n }\n\n // Split the text by HTML tags to safely render highlights\n const parts = highlightedText.split(/(]*>.*?<\\/span>)/g);\n\n return (\n \n {parts.map((part, index) => {\n // Check if this part is a highlight span\n const spanMatch = part.match(/([^<]*)<\\/span>/);\n\n if (spanMatch) {\n const [, className, title, content] = spanMatch;\n return (\n \n {content}\n \n );\n }\n\n return part;\n })}\n \n );\n };\n\n return (\n
\n {/* Response Header */}\n
\n \n {response.platform}\n \n
\n \n AI Mention: {hasCustomerMention ? 'Yes' : 'No'}\n \n {showTimestamp && (\n
\n \n {new Date(response.created_at).toLocaleDateString()}\n
\n )}\n
\n
\n\n {/* Mentions Legend (shown only when there are mentions) */}\n {hasCustomerMention && (\n
\n
Highlighted mentions:
\n
\n {response.brand_mentions && response.brand_mentions.length > 0 && (\n
\n \n Brand\n \n \n {response.brand_mentions.map(m => m.brand_name).join(', ')}\n \n
\n )}\n {response.product_mentions && response.product_mentions.length > 0 && (\n
\n \n Product\n \n \n {response.product_mentions.map(m => m.product_name).join(', ')}\n \n
\n )}\n
\n
\n )}\n\n {/* Response Text with Highlighted Mentions */}\n
\n {renderHighlightedText(response.response_text || response.response)}\n
\n\n {/* Source Links */}\n {showSourceLinks && response.source_links && response.source_links.length > 0 && (\n
\n

Source Links:

\n
\n {response.source_links.map((link) => (\n \n \n {link.url}\n \n ))}\n
\n
\n )}\n
\n );\n};\n\nexport default ResponseCard;", "import React, { useState, useEffect, useCallback, useContext } from 'react';\nimport axios from '../../AxiosConfig';\nimport {\n Globe,\n ExternalLink,\n ArrowLeft,\n FileText,\n LinkIcon,\n MessageSquare,\n Eye,\n AlertCircle\n} from 'lucide-react';\nimport SideDrawer from './SideDrawer';\nimport ResponseCard from './ResponseCard';\nimport { useProjectDashboard } from '../../../context/ProjectDashboardContext';\nimport { AuthContext } from '../../../context/AuthContext'; // Import AuthContext for user data\nimport { trackEvent } from '../../Analytics/mixpanel'; // Import trackEvent\n\nconst ProjectLinks = ({ projectId, project }) => {\n const { user } = useContext(AuthContext); // Get user data for tracking\n\n // Get state from context\n const {\n linksLinkType, setLinksLinkType,\n linksCurrentView, setLinksCurrentView,\n linksDomains, setLinksDomains,\n linksSelectedDomain, setLinksSelectedDomain,\n linksDomainLinks, setLinksDomainLinks,\n linksSelectedLink, setLinksSelectedLink,\n linksLinkPrompts, setLinksLinkPrompts,\n linksPromptResponses, setLinksPromptResponses,\n linksCache, setLinksCache\n } = useProjectDashboard();\n\n // Local state (doesn't need to persist)\n const [loading, setLoading] = useState(false);\n const [initialLoading, setInitialLoading] = useState(true);\n const [error, setError] = useState(null);\n const [sideDrawerOpen, setSideDrawerOpen] = useState(false);\n const [selectedPrompt, setSelectedPrompt] = useState(null);\n\n // Memoized fetch domains function\n const fetchDomains = useCallback(async (type) => {\n const currentType = type || linksLinkType;\n\n // Check cache first\n if (linksCache[currentType].domains) {\n setLinksDomains(linksCache[currentType].domains);\n setInitialLoading(false);\n return;\n }\n\n try {\n setLoading(true);\n setError(null);\n const response = await axios.get(`/api/projects/${projectId}/links`, {\n params: { link_type: currentType }\n });\n\n // Update cache\n setLinksCache(prevCache => ({\n ...prevCache,\n [currentType]: {\n ...prevCache[currentType],\n domains: response.data.domains\n }\n }));\n\n setLinksDomains(response.data.domains);\n } catch (err) {\n console.error('Error fetching domains:', err);\n setError('Failed to load domains. Please try again.');\n } finally {\n setLoading(false);\n setInitialLoading(false);\n }\n }, [projectId, linksLinkType, linksCache, setLinksDomains, setLinksCache]);\n\n // Fetch domains when component mounts\n useEffect(() => {\n if (linksDomains.length === 0) {\n fetchDomains();\n } else {\n setInitialLoading(false);\n }\n }, [fetchDomains, linksDomains.length]);\n\n const handleLinkTypeToggle = (type) => {\n if (type === linksLinkType) return; // Don't do anything if same type clicked\n\n // Track \"Click Source Links toggle\" event (assuming this covers both response/source toggles)\n trackEvent('Click Source Links toggle', {\n project_id: projectId,\n user_id: user?.id,\n previous_link_type: linksLinkType,\n new_link_type: type,\n domains_count: linksDomains.length,\n source: 'project_links'\n });\n\n // Preserve view state but update content\n setLinksLinkType(type);\n\n // Use cached data if available, otherwise fetch\n if (linksCache[type].domains) {\n setLinksDomains(linksCache[type].domains);\n } else {\n fetchDomains(type);\n }\n\n // Reset other state only if we're not in domains view\n if (linksCurrentView !== 'domains') {\n setLinksCurrentView('domains');\n setLinksSelectedDomain(null);\n setLinksSelectedLink(null);\n }\n };\n\n const fetchDomainLinks = async (domainId) => {\n try {\n setLoading(true);\n setError(null);\n const response = await axios.get(`/api/projects/${projectId}/links/domain/${domainId}`, {\n params: { link_type: linksLinkType }\n });\n\n // Track \"Click into domain\" event\n trackEvent('Click into domain', {\n project_id: projectId,\n user_id: user?.id,\n domain_id: domainId,\n domain_name: response.data.domain?.domain,\n link_type: linksLinkType,\n links_count: response.data.links?.length || 0,\n source: 'project_links'\n });\n\n setLinksSelectedDomain(response.data.domain);\n setLinksDomainLinks(response.data.links);\n setLinksCurrentView('domain_links');\n } catch (err) {\n console.error('Error fetching domain links:', err);\n setError('Failed to load domain links. Please try again.');\n } finally {\n setLoading(false);\n }\n };\n\n const fetchLinkPrompts = async (linkId) => {\n try {\n setLoading(true);\n setError(null);\n const response = await axios.get(`/api/projects/${projectId}/links/url/${linkId}`, {\n params: { link_type: linksLinkType }\n });\n\n // Track \"Click into page\" event\n trackEvent('Click into page', {\n project_id: projectId,\n user_id: user?.id,\n link_id: linkId,\n url: response.data.link?.url,\n domain: linksSelectedDomain?.domain,\n link_type: linksLinkType,\n prompts_count: response.data.prompts?.length || 0,\n source: 'project_links'\n });\n\n setLinksSelectedLink(response.data.link);\n setLinksLinkPrompts(response.data.prompts);\n setLinksCurrentView('link_prompts');\n } catch (err) {\n console.error('Error fetching link prompts:', err);\n setError('Failed to load link prompts. Please try again.');\n } finally {\n setLoading(false);\n }\n };\n\n const handleViewPromptResponses = (prompt) => {\n // Track \"Click into prompt\" event\n trackEvent('Click into prompt', {\n project_id: projectId,\n user_id: user?.id,\n prompt_id: prompt.id,\n topic: prompt.topic,\n url: linksSelectedLink?.url,\n domain: linksSelectedDomain?.domain,\n link_type: linksLinkType,\n responses_count: prompt.responses?.length || 0,\n source: 'project_links'\n });\n\n setSelectedPrompt(prompt);\n setLinksPromptResponses(prompt.responses || []);\n setSideDrawerOpen(true);\n };\n\n const closeSideDrawer = () => {\n setSideDrawerOpen(false);\n setSelectedPrompt(null);\n };\n\n const getPlatformBadge = (platform) => {\n const colors = {\n chatgpt: 'bg-green-100 text-green-800',\n claude: 'bg-purple-100 text-purple-800',\n perplexity: 'bg-blue-100 text-blue-800'\n };\n return colors[platform] || 'bg-gray-100 text-gray-800';\n };\n\n const getProminenceScoreColor = (score) => {\n if (score >= 70) return 'text-green-600 font-semibold';\n if (score >= 40) return 'text-yellow-600 font-semibold';\n return 'text-red-600 font-semibold';\n };\n\n const formatUrl = (url) => {\n try {\n const urlObj = new URL(url);\n return urlObj.pathname + urlObj.search;\n } catch {\n return url;\n }\n };\n\n const openLinkInNewTab = (url) => {\n window.open(url, '_blank');\n };\n\n const renderHeader = () => (\n
\n
\n
\n {linksCurrentView !== 'domains' && (\n {\n if (linksCurrentView === 'link_prompts') {\n setLinksCurrentView('domain_links');\n } else {\n setLinksCurrentView('domains');\n }\n }}\n className=\"flex items-center text-gray-600 hover:text-gray-800\"\n >\n \n Back\n \n )}\n
\n

\n {linksCurrentView === 'domains' && 'Project Links'}\n {linksCurrentView === 'domain_links' && `Links in ${linksSelectedDomain?.domain}`}\n {linksCurrentView === 'link_prompts' && 'Prompts Referencing Link'}\n

\n {linksCurrentView === 'link_prompts' && (\n

\n {formatUrl(linksSelectedLink?.url)}\n

\n )}\n
\n
\n\n {linksCurrentView === 'domains' && (\n
\n handleLinkTypeToggle('response')}\n className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${\n linksLinkType === 'response'\n ? 'bg-white text-gray-900 shadow-sm'\n : 'text-gray-600 hover:text-gray-900'\n }`}\n >\n Response Links\n \n handleLinkTypeToggle('source')}\n className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${\n linksLinkType === 'source'\n ? 'bg-white text-gray-900 shadow-sm'\n : 'text-gray-600 hover:text-gray-900'\n }`}\n >\n Source Links\n \n
\n )}\n
\n
\n );\n\n const renderDomains = () => (\n
\n
\n

\n Domains ({linksDomains.length})\n

\n

\n {linksLinkType === 'response'\n ? 'Domains mentioned in AI responses'\n : 'Domains used as sources for prompts'\n }\n

\n
\n\n {linksDomains.length > 0 ? (\n
\n {linksDomains.map((domain) => (\n fetchDomainLinks(domain.id)}\n >\n
\n
\n \n
\n

{domain.domain}

\n

\n {domain.link_count} {domain.link_count === 1 ? 'Page' : 'Pages'} Referenced\n

\n
\n
\n
\n \n {domain.link_count}\n \n \n
\n
\n
\n ))}\n
\n ) : (\n
\n \n

No {linksLinkType} links found

\n

\n {linksLinkType === 'response'\n ? 'Generate some responses to see referenced domains'\n : 'Add some prompts with sources to see referenced domains'\n }\n

\n
\n )}\n \n );\n\n const renderDomainLinks = () => (\n
\n
\n

\n Links ({linksDomainLinks.length})\n

\n

\n URLs from {linksSelectedDomain?.domain}\n

\n
\n\n {linksDomainLinks.length > 0 ? (\n
\n {linksDomainLinks.map((link) => (\n \n
\n fetchLinkPrompts(link.id || link.first_link_id)}\n >\n
\n \n
\n

\n {formatUrl(link.url)}\n

\n

\n Referenced in {link.reference_count} {link.reference_count === 1 ? 'Prompt' : 'Prompts'}\n

\n
\n
\n
\n
\n \n {link.reference_count}\n \n fetchLinkPrompts(link.id || link.first_link_id)}\n className=\"text-indigo-600 hover:text-indigo-800 p-1 rounded hover:bg-indigo-50\"\n title=\"View prompts\"\n >\n \n \n {\n e.stopPropagation();\n openLinkInNewTab(link.url);\n }}\n className=\"text-blue-600 hover:text-blue-800 p-1 rounded hover:bg-blue-50\"\n title=\"Open page in new tab\"\n >\n \n \n
\n
\n
\n ))}\n \n ) : (\n
\n \n

No links found for this domain

\n
\n )}\n \n );\n\n const renderLinkPrompts = () => (\n
\n
\n

\n Prompts ({linksLinkPrompts.length})\n

\n

\n \n Prompts that reference {formatUrl(linksSelectedLink?.url)}\n \n openLinkInNewTab(linksSelectedLink?.url)}\n className=\"text-blue-600 hover:text-blue-800 p-1 rounded hover:bg-blue-50 flex-shrink-0\"\n title=\"Open page in new tab\"\n >\n \n \n

\n
\n\n {linksLinkPrompts.length > 0 ? (\n
\n {linksLinkPrompts.map((promptData) => (\n
\n
\n
\n
\n \n \n {promptData.topic}\n \n
\n

\n {promptData.prompt}\n

\n
\n {promptData.responses.length} response{promptData.responses.length !== 1 ? 's' : ''}\n
\n
\n
\n handleViewPromptResponses(promptData)}\n className=\"inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\"\n >\n \n View\n \n
\n
\n
\n ))}\n
\n ) : (\n
\n \n

No prompts found referencing this link

\n
\n )}\n
\n );\n\n // Only show the full loading screen on initial load\n if (initialLoading) {\n return (\n
\n
Loading links...
\n
\n );\n }\n\n if (error) {\n return (\n
\n
\n \n

Error Loading Links

\n
\n

{error}

\n fetchDomains()}\n >\n Try Again\n \n
\n );\n }\n\n return (\n
\n {renderHeader()}\n\n {/* Conditional loading overlay only for secondary fetches */}\n
\n {loading && (\n
\n
Loading...
\n
\n )}\n\n {linksCurrentView === 'domains' && renderDomains()}\n {linksCurrentView === 'domain_links' && renderDomainLinks()}\n {linksCurrentView === 'link_prompts' && renderLinkPrompts()}\n
\n\n {/* Side Drawer */}\n \n {/* Prompt Text */}\n
\n

Prompt

\n
\n

{selectedPrompt?.prompt}

\n
\n
\n\n {/* Link Info */}\n
\n

Referenced Link

\n
\n

{linksSelectedLink?.url}

\n openLinkInNewTab(linksSelectedLink?.url)}\n className=\"text-blue-600 hover:text-blue-800 p-1 rounded hover:bg-blue-200 ml-2 flex-shrink-0\"\n title=\"Open page in new tab\"\n >\n \n \n
\n
\n\n {/* Responses */}\n
\n

\n Responses ({linksPromptResponses.length})\n

\n\n
\n {linksPromptResponses.map((response) => (\n \n ))}\n
\n
\n \n
\n );\n};\n\nexport default ProjectLinks;", "import React, { useState, useEffect, useContext } from 'react';\nimport {\n Clock,\n ArrowRight,\n Target,\n BarChart3,\n TrendingUp,\n CheckCircle,\n Settings,\n Eye,\n Calendar,\n FileText,\n Lock,\n X\n} from 'lucide-react';\nimport { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';\nimport { useNavigate } from 'react-router-dom';\nimport axios from '../../AxiosConfig';\nimport { AuthContext } from '../../../context/AuthContext';\nimport { trackEvent } from '../../Analytics/mixpanel';\n\n// Client tier enum values (matching Rails)\nconst CLIENT_TIER = {\n NONE: 0,\n MONITORING: 1,\n SERVICING: 2\n};\n\n// Helper to check if trial is expired\nconst isTrialExpired = (trialEndDate) => {\n if (!trialEndDate) return false;\n const trialDate = new Date(trialEndDate + 'T00:00:00');\n const today = new Date();\n today.setHours(0, 0, 0, 0);\n return trialDate < today;\n};\n\n// HubSpot Form Modal Component\nconst UnlockModal = ({ isOpen, onClose }) => {\n useEffect(() => {\n if (isOpen) {\n // Load HubSpot script if not already loaded\n const existingScript = document.querySelector('script[src=\"https://js.hsforms.net/forms/embed/48492217.js\"]');\n if (!existingScript) {\n const script = document.createElement('script');\n script.src = 'https://js.hsforms.net/forms/embed/48492217.js';\n script.defer = true;\n document.body.appendChild(script);\n }\n }\n }, [isOpen]);\n\n if (!isOpen) return null;\n\n return (\n
\n
\n \n \n \n\n
\n
\n \n );\n};\n\n// Frosted overlay component\nconst FrostedOverlay = ({ children, isLocked, className = '', lockPosition = 'center', onUnlockClick }) => {\n const [isHovered, setIsHovered] = useState(false);\n\n if (!isLocked) {\n return
{children}
;\n }\n\n return (\n setIsHovered(true)}\n onMouseLeave={() => setIsHovered(false)}\n >\n {/* Content with blur */}\n \n {children}\n \n\n {/* Overlay with lock - only visible on hover */}\n \n \n \n \n \n Unlock feature\n \n \n \n );\n};\n\n// Dummy data for locked state\nconst dummyGeoScoreData = [\n { date: '2025-01-01', geo_score: 42 },\n { date: '2025-01-08', geo_score: 45 },\n { date: '2025-01-15', geo_score: 48 },\n { date: '2025-01-22', geo_score: 52 },\n { date: '2025-01-29', geo_score: 55 },\n { date: '2025-02-05', geo_score: 58 },\n];\n\nconst dummyOpportunitiesData = {\n quick_stats: {\n opportunities_identified: 24,\n opportunities_saved: 12,\n tasks_in_progress: 5,\n tasks_completed: 8\n },\n recommended_actions: [\n {\n id: 1,\n title: 'Optimize product page meta descriptions',\n days_since_created: 3,\n opportunity_id: 1\n },\n {\n id: 2,\n title: 'Add schema markup to FAQ section',\n days_since_created: 5,\n opportunity_id: 2\n },\n {\n id: 3,\n title: 'Improve internal linking structure',\n days_since_created: 7,\n opportunity_id: 3\n }\n ],\n recent_insights: [\n {\n id: 1,\n title: 'Low visibility on product comparison queries',\n description: 'Your brand is not appearing in AI responses for key product comparison searches.',\n created_at: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()\n },\n {\n id: 2,\n title: 'Competitor gaining share in how-to queries',\n description: 'A key competitor has increased their visibility in instructional content.',\n created_at: new Date(Date.now() - 4 * 24 * 60 * 60 * 1000).toISOString()\n },\n {\n id: 3,\n title: 'Positive sentiment trend detected',\n description: 'AI models are increasingly associating positive attributes with your brand.',\n created_at: new Date(Date.now() - 6 * 24 * 60 * 60 * 1000).toISOString()\n }\n ],\n has_opportunities_in_strategy: true\n};\n\nconst dummyObjectiveScores = [\n { name: 'AI Visibility', current_score: 62, change_percentage: 8, start_date: '2025-01-01' },\n { name: 'Share of Voice', current_score: 45, change_percentage: 5, start_date: '2025-01-01' },\n { name: 'Sentiment', current_score: 78, change_percentage: 12, start_date: '2025-01-01' },\n { name: 'Citation', current_score: 34, change_percentage: -3, start_date: '2025-01-01' },\n { name: 'AI Readability', current_score: 56, change_percentage: 15, start_date: '2025-01-01' },\n { name: 'Content Coverage', current_score: 41, change_percentage: 7, start_date: '2025-01-01' },\n { name: 'Technical GEO', current_score: 69, change_percentage: 4, start_date: '2025-01-01' }\n];\n\nconst ProjectOverview = ({ projectId, project }) => {\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n const [objectiveScores, setObjectiveScores] = useState([]);\n const [geoScoreData, setGeoScoreData] = useState([]);\n const [availableAuditResults, setAvailableAuditResults] = useState([]);\n const [selectedStartAuditResult, setSelectedStartAuditResult] = useState('');\n const [showUnlockModal, setShowUnlockModal] = useState(false);\n\n const navigate = useNavigate();\n const { user } = useContext(AuthContext);\n\n // Check if features should be locked\n const isFeatureLocked = () => {\n // Must have a trial_end_date to be locked\n if (!user?.trial_end_date) return false;\n\n // Check if trial is expired\n if (!isTrialExpired(user.trial_end_date)) return false;\n\n // If trial is expired, check if project client_tier is servicing (value 2)\n // client_tier of 0 (NONE), 1 (MONITORING), or undefined should show locked\n const clientTier = project?.client_tier;\n const isServicing = clientTier === CLIENT_TIER.SERVICING;\n\n console.log('Trial lock check:', {\n trial_end_date: user?.trial_end_date,\n isExpired: isTrialExpired(user.trial_end_date),\n client_tier: clientTier,\n isServicing: isServicing,\n shouldLock: !isServicing\n });\n\n return !isServicing;\n };\n\n const featuresLocked = isFeatureLocked();\n\n const handleUnlockClick = () => {\n setShowUnlockModal(true);\n };\n\n const objectives = [\n 'AI Visibility',\n 'Share of Voice',\n 'Sentiment',\n 'Citation',\n 'AI Readability',\n 'Content Coverage',\n 'Technical GEO'\n ];\n\n const objectiveIcons = {\n 'AI Visibility': ,\n 'Share of Voice': ,\n 'Sentiment': ,\n 'Citation': ,\n 'AI Readability': ,\n 'Content Coverage': ,\n 'Technical GEO': \n };\n\n // Get opportunities data - use dummy data if locked\n const opportunitiesData = featuresLocked\n ? dummyOpportunitiesData\n : (project?.opportunities_overview || {\n quick_stats: {\n opportunities_identified: 0,\n opportunities_saved: 0,\n tasks_in_progress: 0,\n tasks_completed: 0\n },\n recommended_actions: [],\n recent_insights: [],\n has_opportunities_in_strategy: false\n });\n\n // Track page view on mount\n useEffect(() => {\n trackEvent('Project Overview Viewed', {\n project_id: projectId,\n user_id: user?.id,\n has_opportunities_in_strategy: hasOpportunitiesInStrategy(),\n has_completed_analysis: project?.has_completed_analysis,\n generating_audit: project?.generating_audit,\n features_locked: featuresLocked\n });\n }, [projectId]);\n\n useEffect(() => {\n if (featuresLocked) {\n // Use dummy data when locked\n setObjectiveScores(dummyObjectiveScores);\n setGeoScoreData(dummyGeoScoreData);\n setLoading(false);\n } else if (projectId && hasOpportunitiesInStrategy()) {\n fetchMeasurementData();\n } else {\n setLoading(false);\n }\n }, [projectId, featuresLocked]);\n\n useEffect(() => {\n if (!featuresLocked && selectedStartAuditResult && hasOpportunitiesInStrategy()) {\n fetchGeoScoreData();\n }\n }, [selectedStartAuditResult, featuresLocked]);\n\n const fetchMeasurementData = async () => {\n try {\n setLoading(true);\n\n const measurementResponse = await axios.get(`/api/projects/${projectId}/measurement`);\n const measurementData = measurementResponse.data;\n\n if (measurementData.available_audit_results && measurementData.available_audit_results.length > 0) {\n setAvailableAuditResults(measurementData.available_audit_results);\n const oldestAuditResult = measurementData.available_audit_results[0];\n setSelectedStartAuditResult(oldestAuditResult.id);\n }\n\n if (hasOpportunitiesInStrategy()) {\n await fetchObjectiveScores();\n }\n\n } catch (err) {\n console.error('Error fetching measurement data:', err);\n setError('Failed to load measurement data');\n } finally {\n setLoading(false);\n }\n };\n\n const fetchObjectiveScores = async () => {\n try {\n const response = await axios.get(`/api/projects/${projectId}/measurement/objective_scores`, {\n params: { start_audit_result_id: selectedStartAuditResult }\n });\n setObjectiveScores(response.data.objective_scores || []);\n } catch (error) {\n console.error('Error fetching objective scores:', error);\n }\n };\n\n const fetchGeoScoreData = async () => {\n try {\n const response = await axios.get(`/api/projects/${projectId}/measurement/geo_score`, {\n params: {\n start_audit_result_id: selectedStartAuditResult\n }\n });\n setGeoScoreData(response.data.geo_score_data || []);\n } catch (error) {\n console.error('Error fetching GEO score data:', error);\n }\n };\n\n const hasOpportunitiesInStrategy = () => {\n if (featuresLocked) return true; // Show second state when locked\n return opportunitiesData.has_opportunities_in_strategy;\n };\n\n const handleNavigateToAudit = () => {\n trackEvent('Overview Navigation Clicked', {\n project_id: projectId,\n user_id: user?.id,\n destination: 'audit',\n source: 'project_overview'\n });\n navigate(`/projects/${projectId}/audit`);\n };\n\n const handleNavigateToSettings = () => {\n trackEvent('Overview Navigation Clicked', {\n project_id: projectId,\n user_id: user?.id,\n destination: 'manage-prompts',\n source: 'project_overview'\n });\n navigate(`/projects/${projectId}/manage-prompts`);\n };\n\n const handleNavigateToOpportunities = () => {\n trackEvent('Overview Navigation Clicked', {\n project_id: projectId,\n user_id: user?.id,\n destination: 'opportunities',\n source: 'project_overview'\n });\n navigate(`/projects/${projectId}/opportunities`);\n };\n\n const handleNavigateToStrategy = () => {\n trackEvent('Overview Navigation Clicked', {\n project_id: projectId,\n user_id: user?.id,\n destination: 'strategy',\n source: 'project_overview'\n });\n navigate(`/projects/${projectId}/strategy`);\n };\n\n const handleViewTask = (task) => {\n if (featuresLocked) return;\n trackEvent('Recommended Action Clicked', {\n project_id: projectId,\n user_id: user?.id,\n task_id: task.id,\n task_title: task.title,\n opportunity_id: task.opportunity_id,\n days_since_created: task.days_since_created,\n source: 'project_overview'\n });\n navigate(`/projects/${projectId}/strategy?opportunityId=${task.opportunity_id}`);\n };\n\n const handleViewOpportunity = (opportunity) => {\n if (featuresLocked) return;\n trackEvent('Recent Insight Clicked', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunity.id,\n opportunity_title: opportunity.title,\n source: 'project_overview'\n });\n navigate(`/projects/${projectId}/opportunities`);\n };\n\n const handleDateFilterChange = (newValue) => {\n if (featuresLocked) return;\n trackEvent('Overview Date Filter Changed', {\n project_id: projectId,\n user_id: user?.id,\n selected_audit_result_id: newValue,\n source: 'project_overview'\n });\n setSelectedStartAuditResult(newValue);\n };\n\n const getTimeAgo = (dateString) => {\n const date = new Date(dateString);\n const now = new Date();\n const diffInMinutes = Math.floor((now - date) / (1000 * 60));\n const diffInHours = Math.floor(diffInMinutes / 60);\n const diffInDays = Math.floor(diffInHours / 24);\n\n if (diffInDays > 0) {\n return `${diffInDays} day${diffInDays > 1 ? 's' : ''} ago`;\n } else if (diffInHours > 0) {\n return `${diffInHours} hour${diffInHours > 1 ? 's' : ''} ago`;\n } else {\n return `${diffInMinutes} minute${diffInMinutes > 1 ? 's' : ''} ago`;\n }\n };\n\n const formatDate = (dateString) => {\n const date = new Date(dateString);\n return date.toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n timeZone: 'UTC'\n });\n };\n\n // Use dummy data for display when locked\n const displayGeoScoreData = featuresLocked ? dummyGeoScoreData : geoScoreData;\n const displayObjectiveScores = featuresLocked ? dummyObjectiveScores : objectiveScores;\n\n if (loading) {\n return (\n
\n
\n
\n
\n
\n
\n
\n
\n );\n };\n\n if (error && !featuresLocked) {\n return (\n
\n
\n

{error}

\n
\n
\n );\n }\n\n return (\n
\n {/* Analysis in Progress Banner - Hide if audit is completed */}\n {project?.generating_audit && (\n
\n
\n \n
\n

\n Analysis in Progress: Step {project.audit_step?.current || 1} of {project.audit_step?.total || 7} working\n

\n

\n Visto is working on your client analysis. You can explore the project while we work\n

\n
\n
\n
\n )}\n\n {/* Welcome Section */}\n
\n

\n Your Visto Dashboard\n

\n

\n View identified opportunities, build strategies and action plans and track your client's optimization progress\n

\n
\n\n {/* Conditional Content Based on Strategy State */}\n {!hasOpportunitiesInStrategy() ? (\n /* Initial State - No Opportunities in Strategy */\n
\n {/* Introduction and Overview */}\n
\n

\n Introduction and Overview\n

\n

\n Understanding your Visto Workflow\n

\n\n
\n
\n

Opportunities

\n

\n These are important insights and goals you want to achieve and are tied to specific desired outcomes for the client.\n

\n
\n\n
\n

Strategy

\n

\n Strategy is your actionable, scheduled plan for implementing goals. It defines how and when you'll achieve them.\n

\n
\n\n
\n

Measurement

\n

\n As you implement changes and tasks for your client, track progress and improvements across key areas and objectives.\n

\n
\n
\n
\n\n {/* What to do next */}\n
\n

\n What to do next\n

\n

\n Get started on your client's GEO optimization\n

\n\n
\n {/* Show different actions based on whether audit is completed */}\n {project?.has_completed_analysis ? (\n /* Audit completed - show these 3 actions */\n <>\n
\n
\n
\n 1\n
\n
\n

Review Analysis Results

\n

\n View your complete client analysis and insights.\n

\n \n \n View Client Audit\n \n \n
\n
\n
\n\n
\n
\n
\n 2\n
\n
\n

Manage Project Settings

\n

\n Fine tune settings like competitors, topics and prompts.\n

\n \n \n Go to Project Settings\n \n \n
\n
\n
\n\n
\n
\n
\n 3\n
\n
\n

Review Opportunities

\n

\n Identify priority areas and gaps to address.\n

\n \n \n View Opportunities\n \n \n
\n
\n
\n \n ) : (\n /* Audit not completed - show original 3 actions */\n <>\n
\n
\n
\n 1\n
\n
\n

Review Project Settings

\n

\n Fine tune settings like competitors, topics and prompts.\n

\n \n \n Go to Project Settings\n \n \n
\n
\n
\n\n
\n
\n
\n 2\n
\n
\n

Review Opportunities

\n

\n Identify priority areas and gaps to address.\n

\n \n \n View Opportunities\n \n \n
\n
\n
\n\n
\n
\n
\n 3\n
\n
\n

Build your strategy

\n

\n Create actionable plans with specific tasks and timeline.\n

\n \n \n View Strategy\n \n \n
\n
\n
\n \n )}\n
\n
\n
\n ) : (\n /* Second State - Has Opportunities in Strategy (or locked) */\n <>\n {/* Quick Stats - NOT frosted */}\n
\n

Quick Stats

\n
\n
\n
\n {opportunitiesData.quick_stats.opportunities_identified}\n
\n
Opportunities identified
\n
\n
\n
\n {opportunitiesData.quick_stats.opportunities_saved}\n
\n
Opportunities saved
\n
\n
\n
\n {opportunitiesData.quick_stats.tasks_in_progress}\n
\n
Tasks in progress
\n
\n
\n
\n {opportunitiesData.quick_stats.tasks_completed}\n
\n
Tasks completed
\n
\n
\n
\n\n {/* Recommended Actions and Recent Insights */}\n
\n {/* Recommended Actions */}\n \n
\n

Recommended Actions

\n

Get started on your client's GEO optimization

\n\n
\n {opportunitiesData.recommended_actions.map((task, index) => (\n
\n
\n
\n {index + 1}\n
\n
\n

{task.title}

\n

\n {task.days_since_created} day{task.days_since_created !== 1 ? 's' : ''} since task was created\n

\n handleViewTask(task)}\n className=\"inline-flex items-center px-4 py-2 bg-indigo-600 text-white text-sm font-medium rounded-md hover:bg-indigo-700\"\n >\n View Task\n \n \n
\n
\n
\n ))}\n {opportunitiesData.recommended_actions.length === 0 && (\n
\n

No recent action tasks available

\n
\n )}\n
\n
\n
\n\n {/* Recent Insights */}\n \n
\n

Recent Insights

\n

Latest findings from most recent analysis

\n\n
\n {opportunitiesData.recent_insights.map((opportunity) => (\n
\n

{opportunity.title}

\n

\n {opportunity.description}\n

\n

{getTimeAgo(opportunity.created_at)}

\n handleViewOpportunity(opportunity)}\n className=\"inline-flex items-center px-4 py-2 bg-indigo-600 text-white text-sm font-medium rounded-md hover:bg-indigo-700\"\n >\n View Opportunity\n \n \n
\n ))}\n {opportunitiesData.recent_insights.length === 0 && (\n
\n

No recent insights available

\n
\n )}\n
\n
\n
\n
\n\n {/* GEO Score Trend and Objective Cards */}\n
\n {/* Chart */}\n \n
\n
\n
\n

Overall GEO Score Trend

\n

Track your overall GEO performance over time

\n
\n
\n \n handleDateFilterChange(e.target.value)}\n className=\"min-w-[150px] px-3 py-2 pr-8 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500 bg-white\"\n style={{ paddingRight: '2rem' }}\n disabled={featuresLocked}\n >\n \n {availableAuditResults.map((auditResult) => (\n \n ))}\n \n
\n
\n\n {displayGeoScoreData.length > 1 ? (\n
\n \n \n \n \n \n `Date: ${formatDate(value)}`}\n formatter={(value) => [`${value}%`, 'GEO Score']}\n />\n \n \n \n \n
\n ) : (\n
\n
\n

Graphical visualization will appear once there's another data point in the next few days

\n
\n
\n )}\n
\n
\n\n {/* Objective Cards */}\n \n
\n

Objectives

\n
\n {objectives.map((objective) => {\n const scoreData = displayObjectiveScores.find(score => score.name === objective);\n return (\n
\n
\n
\n {objectiveIcons[objective]}\n
\n

{objective}

\n
\n
\n {scoreData ? `${scoreData.current_score}%` : '0%'}\n
\n
\n {scoreData && scoreData.change_percentage >= 0 ? (\n \n ) : (\n
\n )}\n = 0 ? 'text-green-600' : 'text-red-600'}`}>\n {scoreData ? `${Math.abs(scoreData.change_percentage)}% ${scoreData.change_percentage >= 0 ? 'improvement' : 'decline'}` : '0% change'}\n \n
\n
\n since {scoreData && scoreData.start_date ? formatDate(scoreData.start_date) : 'start'}\n
\n
\n );\n })}\n
\n
\n \n
\n \n )}\n\n {/* Unlock Modal */}\n setShowUnlockModal(false)}\n />\n
\n );\n};\n\nexport default ProjectOverview;", "import React, { useState, useCallback, useEffect, useContext, useRef } from 'react';\nimport { useNavigate, useParams, useLocation } from 'react-router-dom';\nimport axios from '../../AxiosConfig';\nimport {\n Search,\n AlertCircle,\n FileText,\n Filter,\n RotateCcw,\n ChevronLeft,\n ChevronRight,\n Plus,\n X,\n Loader,\n BarChart,\n ArrowUp,\n ArrowDown,\n Tag,\n MessageSquare,\n Edit,\n Trash,\n ArrowLeft,\n BarChart2,\n RefreshCw,\n Lightbulb,\n Check,\n Eye\n} from 'lucide-react';\nimport { useProjectDashboard } from '../../../context/ProjectDashboardContext';\nimport { AuthContext } from '../../../context/AuthContext';\nimport { trackEvent } from '../../Analytics/mixpanel';\nimport TopicView from './TopicView';\nimport PromptResearch from './PromptResearch';\n\nconst UnifiedPromptManagement = ({ projectId, initialMode = 'manage', topicId: propTopicId }) => {\n const navigate = useNavigate();\n const { user } = useContext(AuthContext);\n const { topicId: paramTopicId } = useParams();\n const location = useLocation();\n\n // Toggle state for switching between modes\n const [activeMode, setActiveMode] = useState(initialMode);\n\n // Use topicId from props first, then from params\n const topicId = propTopicId || paramTopicId;\n\n // Check if we're in topic mode\n const isTopicMode = Boolean(topicId);\n\n // Get research state from context\n const {\n query, setQuery,\n prompts, setPrompts,\n hasSearched, setHasSearched,\n totalCount, setTotalCount,\n filteredCount, setFilteredCount,\n selectedTraffic, setSelectedTraffic,\n selectedIntent, setSelectedIntent,\n difficultyRange, setDifficultyRange,\n currentPage, setCurrentPage,\n jobId, setJobId,\n jobStatus, setJobStatus,\n progress, setProgress,\n existingPrompts, setExistingPrompts\n } = useProjectDashboard();\n\n // Management mode state (for all topics view)\n const [topics, setTopics] = useState([]);\n const [loadingTopics, setLoadingTopics] = useState(false);\n const [topicsError, setTopicsError] = useState(null);\n const [showTopicsDeleteModal, setShowTopicsDeleteModal] = useState(false);\n const [topicToDelete, setTopicToDelete] = useState(null);\n const [deleting, setDeleting] = useState(false);\n const [currentTopicName, setCurrentTopicName] = useState(''); // For header display when in topic mode\n const [topicsFetched, setTopicsFetched] = useState(false); // Flag to prevent unnecessary re-fetching\n\n // Fetch topics when in all topics view OR when we need topic info for header\n useEffect(() => {\n if (!isTopicMode && activeMode === 'manage' && !topicsFetched) {\n fetchTopics();\n setTopicsFetched(true);\n } else if (isTopicMode && topicId) {\n // Fetch the specific topic for header display\n fetchCurrentTopic();\n }\n }, [isTopicMode, activeMode, projectId, topicId, topicsFetched]);\n\n // Fetch current topic data for header display\n const fetchCurrentTopic = useCallback(async () => {\n try {\n const response = await axios.get(`/api/projects/${projectId}/topics/${topicId}`);\n // Store just the topic name for header display\n setCurrentTopicName(response.data.name);\n } catch (err) {\n console.error('Error fetching topic for header:', err);\n }\n }, [projectId, topicId]);\n\n // Topic-specific handlers\n const handleBackToTopics = () => {\n if (location.state && location.state.fromPromptsPage) {\n navigate(`/projects/${projectId}/manage-prompts`);\n } else {\n navigate(`/projects/${projectId}/manage-prompts`);\n }\n };\n\n // All topics management functions\n const fetchTopics = useCallback(async () => {\n try {\n setLoadingTopics(true);\n const response = await axios.get(`/api/projects/${projectId}/topics`);\n setTopics(response.data);\n setTopicsError(null);\n } catch (err) {\n console.error('Error fetching topics:', err);\n const errorMessage = err.response?.data?.error ||\n err.response?.data?.message ||\n err.message ||\n 'Failed to load topics. Please try again later.';\n setTopicsError(errorMessage);\n } finally {\n setLoadingTopics(false);\n }\n }, [projectId]);\n\n const navigateToTopic = (topicId) => {\n trackEvent('Manage Prompts clicked', {\n project_id: projectId,\n topic_id: topicId,\n user_id: user?.id,\n source: 'unified_prompt_management'\n });\n\n navigate(`/projects/${projectId}/prompts/topics/${topicId}`, {\n state: { fromPromptsPage: true }\n });\n };\n\n const handleCreateTopic = () => {\n trackEvent('New topic clicked', {\n project_id: projectId,\n user_id: user?.id,\n source: 'unified_prompt_management',\n current_topics_count: topics.length\n });\n\n navigate(`/projects/${projectId}/topics/new`, {\n state: { fromPromptsPage: true }\n });\n };\n\n const handleEditTopicFromList = (e, topicId) => {\n e.stopPropagation();\n navigate(`/projects/${projectId}/topics/${topicId}/edit`, {\n state: { fromPromptsPage: true }\n });\n };\n\n const handleDeleteTopicFromList = (e, topic) => {\n e.stopPropagation();\n setTopicToDelete(topic);\n setShowTopicsDeleteModal(true);\n };\n\n const handleCancelTopicDelete = () => {\n setShowTopicsDeleteModal(false);\n setTopicToDelete(null);\n };\n\n const handleConfirmTopicDelete = async () => {\n if (!topicToDelete) return;\n\n try {\n setDeleting(true);\n await axios.delete(`/api/projects/${projectId}/topics/${topicToDelete.id}`);\n\n setTopics(topics.filter(topic => topic.id !== topicToDelete.id));\n\n trackEvent('Topic deleted', {\n project_id: projectId,\n topic_id: topicToDelete.id,\n topic_name: topicToDelete.name,\n user_id: user?.id,\n prompts_count: topicToDelete.prompts?.length || 0\n });\n\n } catch (err) {\n console.error('Error deleting topic:', err);\n const errorMessage = err.response?.data?.error ||\n err.response?.data?.message ||\n err.message ||\n 'Failed to delete topic. Please try again later.';\n setTopicsError(errorMessage);\n } finally {\n setDeleting(false);\n setShowTopicsDeleteModal(false);\n setTopicToDelete(null);\n }\n };\n\n const handleAddPrompt = (topicId) => {\n trackEvent('Add Prompt clicked', {\n project_id: projectId,\n topic_id: topicId,\n user_id: user?.id,\n source: 'unified_prompt_management'\n });\n\n navigate(`/projects/${projectId}/topics/${topicId}/prompts/new`, {\n state: { fromPromptsPage: true }\n });\n };\n\n // Mode toggle handler - FIXED\n const handleModeToggle = (mode) => {\n setActiveMode(mode);\n\n // Navigate to the appropriate URL based on mode, preserving topic context\n if (mode === 'research') {\n navigate(`/projects/${projectId}/prompts/research`, {\n state: {\n fromTopic: isTopicMode ? topicId : null,\n fromPromptsPage: true\n }\n });\n } else if (mode === 'manage') {\n // If we have topic context (either current topic or from state), return to that topic\n const targetTopicId = topicId || (location.state?.fromTopic);\n if (targetTopicId) {\n navigate(`/projects/${projectId}/prompts/topics/${targetTopicId}`, {\n state: { fromPromptsPage: true }\n });\n } else {\n // Navigate to manage-prompts instead of prompts to avoid confusion with analytics prompts\n navigate(`/projects/${projectId}/manage-prompts`);\n }\n }\n\n trackEvent('Prompt mode switched', {\n project_id: projectId,\n user_id: user?.id,\n new_mode: mode,\n from_topic: isTopicMode ? topicId : null,\n source: 'unified_prompt_management'\n });\n };\n\n return (\n
\n {/* Header with mode toggle */}\n
\n
\n
\n
\n {isTopicMode && (\n \n \n Back\n \n )}\n
\n

\n {isTopicMode\n ? currentTopicName || 'Loading Topic...'\n : activeMode === 'manage' ? 'Prompt Management' : 'Prompt Research'\n }\n

\n

\n {isTopicMode\n ? 'Manage prompts and view AI-generated suggestions for this topic'\n : activeMode === 'manage'\n ? 'Create and manage topics and prompts for your AI content analysis'\n : 'Discover high-impact prompts and add them to your topics'\n }\n

\n
\n
\n {isTopicMode ? (\n
\n {\n navigate(`/projects/${projectId}/topics/${topicId}/edit`);\n }}\n className=\"inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\"\n >\n \n Edit Topic\n \n {\n navigate(`/projects/${projectId}/topics/${topicId}/prompts/new`);\n }}\n className=\"inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium hover:bg-opacity-90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\"\n style={{ backgroundColor: '#EDEDFC', color: '#4F46E5' }}\n >\n \n Add Prompt\n \n
\n ) : activeMode === 'manage' && !isTopicMode && (\n \n \n Create New Topic\n \n )}\n
\n
\n\n {/* Mode Toggle - Show always, including topic mode */}\n
\n handleModeToggle('manage')}\n className={`px-4 py-2 text-sm font-medium rounded-md transition-colors ${\n activeMode === 'manage'\n ? 'bg-white shadow-sm'\n : 'text-gray-500 hover:text-gray-700'\n }`}\n style={activeMode === 'manage' ? { color: '#4F46E5' } : {}}\n >\n Manage Prompts\n \n handleModeToggle('research')}\n className={`px-4 py-2 text-sm font-medium rounded-md transition-colors ${\n activeMode === 'research'\n ? 'bg-white shadow-sm'\n : 'text-gray-500 hover:text-gray-700'\n }`}\n style={activeMode === 'research' ? { color: '#4F46E5' } : {}}\n >\n Research\n \n
\n
\n\n {/* Content based on mode and context */}\n {isTopicMode ? (\n /* Topic Management Mode - Use TopicView component */\n \n ) : activeMode === 'manage' ? (\n /* All Topics Management Mode */\n
\n

Topics

\n\n {loadingTopics ? (\n
\n \n Loading topics...\n
\n ) : topicsError ? (\n
\n
\n \n

Error

\n
\n

{topicsError}

\n
\n ) : topics.length > 0 ? (\n <>\n {console.log('\uD83D\uDFE1 TOPICS LIST RENDER:', new Date().toISOString(), topics.length)}\n
    \n {topics.map((topic) => (\n
  • \n
    \n navigateToTopic(topic.id)}\n >\n
    \n

    {topic.name}

    \n

    \n {topic.prompts ? topic.prompts.length : 0} prompts\n

    \n
    \n
    \n
    \n handleEditTopicFromList(e, topic.id)}\n >\n \n \n handleDeleteTopicFromList(e, topic)}\n >\n \n \n\n {\n e.stopPropagation();\n handleAddPrompt(topic.id);\n }}\n >\n \n Add Prompt\n \n\n navigateToTopic(topic.id)}\n >\n \n Manage Prompts\n \n \n
    \n
\n \n ))}\n \n \n ) : (\n
\n \n

No topics defined yet

\n

Create a topic to organize your AI prompts

\n \n \n Create Your First Topic\n \n
\n )}\n
\n ) : (\n /* Research Mode Content - Use PromptResearch component */\n \n )}\n\n {/* Delete Confirmation Modal for Topics */}\n {showTopicsDeleteModal && (\n
\n
\n
\n
\n
\n\n ​\n\n
\n
\n
\n
\n \n
\n
\n

Delete Topic

\n
\n

\n Are you sure you want to delete the topic \"{topicToDelete?.name}\"?\n This will permanently delete all prompts and responses within this topic.\n This action cannot be undone.\n

\n\n {topicToDelete?.prompts && topicToDelete.prompts.length > 0 && (\n
\n

\n Warning: This topic contains {topicToDelete.prompts.length} prompts that will also be deleted.\n

\n
\n )}\n
\n
\n
\n
\n
\n \n {deleting ? 'Deleting...' : 'Delete'}\n \n \n Cancel\n \n
\n
\n
\n
\n )}\n
\n );\n};\n\nexport default UnifiedPromptManagement;", "import React, { useState, useEffect, useRef } from 'react';\nimport { useNavigate, useParams } from 'react-router-dom';\nimport axios from '../../AxiosConfig';\nimport {\n Plus,\n MessageSquare,\n BarChart2,\n RefreshCw,\n Check,\n Eye,\n Trash,\n Edit,\n AlertCircle\n} from 'lucide-react';\nimport SideDrawer from './SideDrawer';\nimport ResponseCard from './ResponseCard';\n\nconst TopicView = ({ projectId }) => {\n const navigate = useNavigate();\n const { topicId } = useParams();\n\n const [currentTopic, setCurrentTopic] = useState(null);\n const [topicPrompts, setTopicPrompts] = useState([]);\n const [suggestions, setSuggestions] = useState([]);\n const [loadingTopic, setLoadingTopic] = useState(false);\n const [suggestionsLoading, setSuggestionsLoading] = useState(false);\n const [promptsLoading, setPromptsLoading] = useState(false);\n const [generatingSuggestions, setGeneratingSuggestions] = useState(false);\n const [topicError, setTopicError] = useState(null);\n const [convertedSuggestions, setConvertedSuggestions] = useState({});\n const [convertingInProgress, setConvertingInProgress] = useState({});\n const [hasGeneratedSuggestions, setHasGeneratedSuggestions] = useState(false);\n\n // Side drawer state\n const [selectedPrompt, setSelectedPrompt] = useState(null);\n const [sideDrawerOpen, setSideDrawerOpen] = useState(false);\n const [responses, setResponses] = useState([]);\n const [loadingResponses, setLoadingResponses] = useState(false);\n const [showDeleteModal, setShowDeleteModal] = useState(false);\n const [promptToDelete, setPromptToDelete] = useState(null);\n\n // Polling refs\n const suggestionsPollIntervalRef = useRef(null);\n const promptsPollIntervalRef = useRef(null);\n\n // Fetch topic data\n useEffect(() => {\n if (projectId && topicId) {\n fetchTopicData();\n fetchTopicSuggestions();\n fetchAllTopicPromptResponses();\n startTopicPolling();\n\n return () => {\n if (suggestionsPollIntervalRef.current) {\n clearInterval(suggestionsPollIntervalRef.current);\n }\n if (promptsPollIntervalRef.current) {\n clearInterval(promptsPollIntervalRef.current);\n }\n };\n }\n }, [topicId, projectId]);\n\n // Auto-generate suggestions\n useEffect(() => {\n if (topicPrompts.length > 0 && suggestions.length === 0 && !hasGeneratedSuggestions && !loadingTopic && !generatingSuggestions) {\n setHasGeneratedSuggestions(true);\n generateTopicSuggestions();\n }\n }, [topicPrompts, suggestions, loadingTopic, hasGeneratedSuggestions, generatingSuggestions]);\n\n const fetchTopicData = async () => {\n try {\n setLoadingTopic(true);\n const response = await axios.get(`/api/projects/${projectId}/topics/${topicId}`);\n setCurrentTopic(response.data);\n setTopicPrompts(response.data.prompts || []);\n setTopicError(null);\n } catch (err) {\n console.error('Error fetching topic data:', err);\n const errorMessage = err.response?.data?.message || err.message || 'Failed to load topic data.';\n setTopicError(errorMessage);\n } finally {\n setLoadingTopic(false);\n }\n };\n\n const fetchTopicSuggestions = async () => {\n if (!projectId || !topicId) return;\n\n try {\n setSuggestionsLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/topics/${topicId}/suggestions`);\n const fetchedSuggestions = response.data || [];\n setSuggestions(fetchedSuggestions);\n\n if (fetchedSuggestions.length > 0) {\n setHasGeneratedSuggestions(true);\n }\n } catch (err) {\n console.error('Error fetching suggestions:', err);\n } finally {\n setSuggestionsLoading(false);\n }\n };\n\n const fetchAllTopicPromptResponses = async () => {\n if (!projectId || !topicId) return;\n\n try {\n setPromptsLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/topics/${topicId}/prompts`);\n setTopicPrompts(response.data || []);\n } catch (err) {\n console.error('Error fetching prompt responses:', err);\n } finally {\n setPromptsLoading(false);\n }\n };\n\n const startTopicPolling = () => {\n if (suggestionsPollIntervalRef.current) {\n clearInterval(suggestionsPollIntervalRef.current);\n }\n if (promptsPollIntervalRef.current) {\n clearInterval(promptsPollIntervalRef.current);\n }\n\n suggestionsPollIntervalRef.current = setInterval(() => {\n fetchTopicSuggestions();\n }, 5000);\n\n promptsPollIntervalRef.current = setInterval(() => {\n fetchAllTopicPromptResponses();\n }, 5000);\n };\n\n const generateTopicSuggestions = async () => {\n try {\n setGeneratingSuggestions(true);\n await axios.post(`/api/projects/${projectId}/topics/${topicId}/suggestions/generate_suggestions`);\n setTimeout(() => fetchTopicSuggestions(), 1000);\n } catch (err) {\n console.error('Error generating suggestions:', err);\n setTopicError('Failed to generate prompt suggestions. Please try again.');\n } finally {\n setGeneratingSuggestions(false);\n }\n };\n\n const handleCreateTopicPrompt = () => {\n navigate(`/projects/${projectId}/topics/${topicId}/prompts/new`, {\n state: { fromPromptsPage: true }\n });\n };\n\n const handleEditPrompt = (promptId) => {\n navigate(`/projects/${projectId}/topics/${topicId}/prompts/${promptId}/edit`, {\n state: { fromPromptsPage: true }\n });\n };\n\n const handleViewTopicResponses = async (prompt) => {\n if (!prompt || !prompt.id) {\n console.error('Invalid prompt:', prompt);\n return;\n }\n\n setSelectedPrompt(prompt);\n setSideDrawerOpen(true);\n await fetchPromptResponses(prompt.id);\n };\n\n const fetchPromptResponses = async (promptId) => {\n try {\n setLoadingResponses(true);\n const response = await axios.get(`/api/prompt_analytics/prompt/${promptId}/responses`);\n setResponses(response.data.responses || []);\n } catch (err) {\n console.error('Error fetching prompt responses:', err);\n setResponses([]);\n } finally {\n setLoadingResponses(false);\n }\n };\n\n const closeSideDrawer = () => {\n setSideDrawerOpen(false);\n setSelectedPrompt(null);\n setResponses([]);\n };\n\n const handleDeleteTopicPrompt = (promptId) => {\n setPromptToDelete(promptId);\n setShowDeleteModal(true);\n };\n\n const confirmDeleteTopicPrompt = async () => {\n try {\n await axios.delete(`/api/projects/${projectId}/topics/${topicId}/prompts/${promptToDelete}`);\n setTopicPrompts(topicPrompts.filter(prompt => prompt.id !== promptToDelete));\n setShowDeleteModal(false);\n setPromptToDelete(null);\n } catch (err) {\n console.error('Error deleting prompt:', err);\n const errorMessage = err.response?.data?.message || err.message || 'Failed to delete prompt.';\n setTopicError(errorMessage);\n }\n };\n\n const convertSuggestionToPrompt = async (suggestionId, suggestionText) => {\n try {\n setConvertingInProgress(prev => ({ ...prev, [suggestionId]: true }));\n\n const response = await axios.post(`/api/projects/${projectId}/topics/${topicId}/prompts`, {\n prompt: {\n prompt: suggestionText\n }\n });\n\n setConvertedSuggestions(prev => ({ ...prev, [suggestionId]: true }));\n setTopicPrompts([...topicPrompts, response.data]);\n } catch (err) {\n console.error('Error converting suggestion to prompt:', err);\n setTopicError('Failed to convert suggestion to prompt. Please try again.');\n } finally {\n setConvertingInProgress(prev => ({ ...prev, [suggestionId]: false }));\n }\n };\n\n const getPlatformBadge = (platform) => {\n const colors = {\n chatgpt: 'bg-green-100 text-green-800',\n claude: 'bg-blue-100 text-blue-800',\n perplexity: 'bg-purple-100 text-purple-800',\n google_ai_overview: 'bg-orange-100 text-orange-800',\n 0: 'bg-green-100 text-green-800',\n 1: 'bg-blue-100 text-blue-800',\n 2: 'bg-purple-100 text-purple-800',\n 3: 'bg-orange-100 text-orange-800'\n };\n return colors[platform] || 'bg-gray-100 text-gray-800';\n };\n\n const getProminenceScoreColor = (score) => {\n if (score >= 70) return 'text-green-600 font-semibold';\n if (score >= 40) return 'text-yellow-600 font-semibold';\n return 'text-red-600 font-semibold';\n };\n\n if (loadingTopic) {\n return (\n
\n
Loading topic data...
\n
\n );\n }\n\n if (topicError) {\n return (\n
\n
\n \n

Error Loading Topic

\n
\n

{topicError}

\n
\n );\n }\n\n return (\n <>\n {/* Topic Info Card */}\n\n\n {/* Prompts and Suggestions - 2/3 and 1/3 layout */}\n
\n {/* Prompts List - Takes up 2/3 of the space */}\n
\n
\n
\n
\n

Prompts

\n {promptsLoading && topicPrompts.length === 0 && (\n \n )}\n
\n {topicPrompts.length > 0 && (\n \n {topicPrompts.length} {topicPrompts.length === 1 ? 'Prompt' : 'Prompts'}\n \n )}\n
\n
\n\n {topicPrompts.length === 0 ? (\n
\n \n

No prompts available

\n

There are no prompts for this topic yet.

\n \n \n Create a Prompt\n \n
\n ) : (\n
    \n {topicPrompts.map((prompt) => (\n
  • \n
    \n
    \n {/* Prompt text first */}\n
    \n

    {prompt.prompt}

    \n
    \n\n {/* Stats row below in one horizontal line */}\n
    \n
    \n \n {prompt.responses?.length || 0} responses\n
    \n
    \n {prompt.is_metadata_loading ? (\n <>\n \n Analyzing...\n \n ) : (\n Priority: {prompt.priority || 0}/100\n )}\n
    \n
    \n {prompt.is_metadata_loading ? (\n <>\n \n Processing...\n \n ) : (\n Prompt Type: {prompt.prompt_type_display || 'Unknown'}\n )}\n
    \n
    \n
    \n
    \n {\n e.stopPropagation();\n handleViewTopicResponses(prompt);\n }}\n className=\"p-2 rounded-md border border-gray-300 text-gray-500 bg-white hover:text-indigo-600 hover:bg-gray-50 hover:border-gray-400 transition-colors\"\n title=\"View Responses\"\n >\n \n \n {\n e.stopPropagation();\n handleEditPrompt(prompt.id);\n }}\n className=\"p-2 rounded-md border border-gray-300 text-gray-500 bg-white hover:text-gray-900 hover:bg-gray-50 hover:border-gray-400 transition-colors\"\n title=\"Edit Prompt\"\n >\n \n \n {\n e.stopPropagation();\n handleDeleteTopicPrompt(prompt.id);\n }}\n className=\"p-2 rounded-md border border-gray-300 text-gray-500 bg-white hover:text-red-600 hover:bg-gray-50 hover:border-gray-400 transition-colors\"\n title=\"Delete Prompt\"\n >\n \n \n
    \n
    \n
  • \n ))}\n
\n )}\n\n {topicPrompts.length > 0 && (\n
\n \n \n Add Prompt\n \n
\n )}\n
\n\n {/* Suggestions - Takes up 1/3 of the space */}\n
\n
\n

Suggested Prompts

\n

AI-recommended prompts for this topic

\n
\n\n {suggestions.length > 0 ? (\n
    \n {suggestions.map((suggestion) => (\n
  • \n
    \n
    \n
    \n

    {suggestion.prompt}

    \n {convertedSuggestions[suggestion.id] && (\n
    \n \n Added to prompts\n
    \n )}\n
    \n
    \n
    \n {!convertedSuggestions[suggestion.id] ? (\n convertSuggestionToPrompt(suggestion.id, suggestion.prompt)}\n disabled={convertingInProgress[suggestion.id]}\n className={`p-1.5 rounded-md border border-gray-300 text-gray-500 bg-white\n ${convertingInProgress[suggestion.id]\n ? 'cursor-wait'\n : 'hover:text-green-600 hover:bg-gray-50 hover:border-gray-400'} \n transition-colors`}\n title=\"Add to prompts\"\n >\n {convertingInProgress[suggestion.id] ? (\n \n ) : (\n \n )}\n \n ) : (\n handleViewTopicResponses(topicPrompts.find(p => p.prompt === suggestion.prompt))}\n className=\"p-1.5 rounded-md text-gray-500 hover:text-indigo-600 hover:bg-gray-100 transition-colors\"\n title=\"View prompt responses\"\n >\n \n \n )}\n
    \n
    \n
  • \n ))}\n
\n ) : topicPrompts.length > 0 ? (\n
\n \n

Generating Suggestions

\n

\n We're analyzing your existing prompts to generate relevant suggestions.\n This may take a moment.\n

\n
\n ) : (\n
\n \n

No Suggestions Available

\n

Create some prompts first to enable AI-generated suggestions.

\n
\n )}\n
\n
\n\n {/* Delete Confirmation Modal */}\n {showDeleteModal && (\n
\n
\n
\n
\n
\n\n ​\n\n
\n
\n
\n
\n \n
\n
\n

Delete Prompt

\n
\n

\n Are you sure you want to delete this prompt? All of the responses associated with this prompt will be permanently removed. This action cannot be undone.\n

\n
\n
\n
\n
\n
\n \n Delete\n \n setShowDeleteModal(false)}\n >\n Cancel\n \n
\n
\n
\n
\n )}\n\n {/* Side Drawer */}\n \n {/* Prompt Text */}\n
\n

Prompt

\n
\n

{selectedPrompt?.prompt}

\n
\n
\n\n {/* Responses */}\n
\n

\n Responses ({responses.length})\n

\n\n {loadingResponses ? (\n
\n
Loading responses...
\n
\n ) : responses.length === 0 ? (\n
\n \n

No responses yet for this prompt.

\n
\n ) : (\n
\n {responses.map((response) => (\n \n ))}\n
\n )}\n
\n \n \n );\n};\n\nexport default TopicView;", "import React, { useState, useCallback, useEffect, useContext } from 'react';\nimport { useNavigate } from 'react-router-dom';\nimport axios from '../../AxiosConfig';\nimport {\n Search,\n AlertCircle,\n FileText,\n Filter,\n RotateCcw,\n ChevronLeft,\n ChevronRight,\n Plus,\n X,\n Loader,\n BarChart,\n ArrowUp,\n ArrowDown,\n XCircle\n} from 'lucide-react';\nimport { useProjectDashboard } from '../../../context/ProjectDashboardContext';\nimport { AuthContext } from '../../../context/AuthContext';\nimport { trackEvent } from '../../Analytics/mixpanel';\n\nconst PromptResearch = ({ projectId }) => {\n const navigate = useNavigate();\n const { user } = useContext(AuthContext);\n\n // Get state from context instead of using local state\n const {\n query, setQuery,\n prompts, setPrompts,\n hasSearched, setHasSearched,\n totalCount, setTotalCount,\n filteredCount, setFilteredCount,\n selectedTraffic, setSelectedTraffic,\n selectedIntent, setSelectedIntent,\n difficultyRange, setDifficultyRange,\n currentPage, setCurrentPage,\n jobId, setJobId,\n jobStatus, setJobStatus,\n progress, setProgress,\n existingPrompts, setExistingPrompts\n } = useProjectDashboard();\n\n // Local state (that doesn't need to be preserved)\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState(null);\n const [shouldApplyFilters, setShouldApplyFilters] = useState(false);\n const [itemsPerPage] = useState(10);\n const [selectedDifficulty, setSelectedDifficulty] = useState(''); // New state for difficulty dropdown\n\n // Sorting state\n const [sortField, setSortField] = useState(null);\n const [sortDirection, setSortDirection] = useState('asc');\n\n // Topic modal states (don't need to be preserved across navigations)\n const [showTopicModal, setShowTopicModal] = useState(false);\n const [selectedPrompt, setSelectedPrompt] = useState(null);\n const [topics, setTopics] = useState([]);\n const [selectedTopicId, setSelectedTopicId] = useState('');\n const [newTopicName, setNewTopicName] = useState('');\n const [isCreatingTopic, setIsCreatingTopic] = useState(true);\n const [topicModalLoading, setTopicModalLoading] = useState(false);\n const [pollInterval, setPollInterval] = useState(null);\n\n // Filter options\n const trafficOptions = [\n { value: '', label: 'All Traffic' },\n { value: 'high', label: 'High' },\n { value: 'medium', label: 'Medium' },\n { value: 'low', label: 'Low' }\n ];\n\n const intentOptions = [\n { value: '', label: 'All Intents' },\n { value: 'commercial', label: 'Commercial' },\n { value: 'transactional', label: 'Transactional' },\n { value: 'informational', label: 'Informational' },\n { value: 'navigational', label: 'Navigational' }\n ];\n\n const difficultyOptions = [\n { value: '', label: 'All Difficulty', min: 0, max: 100 },\n { value: 'easy', label: 'Easy', min: 0, max: 40 },\n { value: 'medium', label: 'Medium', min: 40, max: 70 },\n { value: 'hard', label: 'Hard', min: 70, max: 100 }\n ];\n\n // Modified search function to start a job\n const searchPrompts = useCallback(async (searchQuery, filters = {}) => {\n if (!searchQuery.trim()) {\n setPrompts([]);\n setHasSearched(false);\n setTotalCount(0);\n setFilteredCount(0);\n setJobId(null);\n setJobStatus(null);\n return;\n }\n\n try {\n setLoading(true);\n setError(null);\n setJobStatus('queued');\n setProgress(0);\n\n // Track \"Query submitted\" event\n trackEvent('Query submitted', {\n project_id: projectId,\n user_id: user?.id,\n query: searchQuery.trim(),\n query_length: searchQuery.trim().length,\n source: 'prompt_research'\n });\n\n const params = {\n query: searchQuery.trim(),\n ...filters\n };\n\n const response = await axios.get(`/api/projects/${projectId}/prompt_research`, {\n params\n });\n\n // Job has been created\n if (response.data.job_id) {\n setJobId(response.data.job_id);\n\n // Start polling for job status\n if (pollInterval) {\n clearInterval(pollInterval);\n }\n\n const interval = setInterval(() => {\n checkJobStatus(response.data.job_id);\n }, 2000); // Poll every 2 seconds\n\n setPollInterval(interval);\n } else {\n // Handle case where no job was created (empty query)\n setPrompts(response.data.prompts || []);\n setTotalCount(response.data.total_count || 0);\n setFilteredCount(response.data.filtered_count || 0);\n setHasSearched(true);\n setLoading(false);\n }\n } catch (err) {\n console.error('Error searching prompts:', err);\n setError('Failed to search prompts. Please try again.');\n setPrompts([]);\n setTotalCount(0);\n setFilteredCount(0);\n setLoading(false);\n setJobStatus('failed');\n }\n }, [projectId, pollInterval, user?.id, setPrompts, setHasSearched, setTotalCount, setFilteredCount, setJobId, setJobStatus, setProgress]);\n\n // New function to fetch existing prompts in the project with proper memoization\n const fetchExistingPrompts = useCallback(async () => {\n try {\n // Use the existing project_details endpoint with minimal parameters\n const response = await axios.get(`/api/prompt_analytics/project/${projectId}/details`, {\n params: {\n per_page: 1000, // Request a large number to get all prompts\n include_topics: false, // We don't need topics data\n page: 1\n }\n });\n const promptsSet = new Set();\n response.data.prompts.forEach(prompt => {\n promptsSet.add(prompt.prompt.toLowerCase().trim());\n });\n setExistingPrompts(promptsSet);\n } catch (err) {\n console.error('Error fetching existing prompts:', err);\n }\n }, [projectId, setExistingPrompts]);\n\n // Modified useEffect with better dependency handling\n useEffect(() => {\n // Only fetch if we don't already have prompts and projectId is available\n if (existingPrompts.size === 0 && projectId) {\n console.log('Fetching existing prompts for project:', projectId);\n fetchExistingPrompts();\n }\n\n // Return cleanup function\n return () => {\n // Any cleanup if needed\n };\n\n // Important: Only include existingPrompts.size in the dependency array, not the whole set\n }, [fetchExistingPrompts, projectId, existingPrompts.size]);\n\n // New function to check job status\n const checkJobStatus = async (id) => {\n try {\n const response = await axios.get(`/api/projects/${projectId}/prompt_research/job_status`, {\n params: { job_id: id }\n });\n\n setJobStatus(response.data.status);\n\n if (response.data.progress) {\n setProgress(response.data.progress);\n }\n\n // If job is completed, stop polling and display results\n if (response.data.status === 'completed') {\n clearInterval(pollInterval);\n setPollInterval(null);\n\n setPrompts(response.data.prompts || []);\n setTotalCount(response.data.total_count || 0);\n setFilteredCount(response.data.filtered_count || 0);\n setHasSearched(true);\n setLoading(false);\n }\n // If job failed, show error\n else if (response.data.status === 'failed') {\n clearInterval(pollInterval);\n setPollInterval(null);\n setError(`Research job failed: ${response.data.error || 'Unknown error'}`);\n setLoading(false);\n }\n } catch (err) {\n console.error('Error checking job status:', err);\n // Don't clear interval on transient errors\n if (err.response && err.response.status === 404) {\n clearInterval(pollInterval);\n setPollInterval(null);\n setError('Research job not found. Please try again.');\n setLoading(false);\n setJobStatus('not_found');\n }\n }\n };\n\n // Clean up polling on component unmount\n useEffect(() => {\n return () => {\n if (pollInterval) {\n clearInterval(pollInterval);\n }\n };\n }, [pollInterval]);\n\n // Effect to apply filters when shouldApplyFilters is true\n useEffect(() => {\n if (shouldApplyFilters && hasSearched && query.trim()) {\n const filters = {\n traffic: selectedTraffic || undefined,\n intent: selectedIntent || undefined,\n };\n\n // Handle difficulty filter conversion\n if (selectedDifficulty) {\n const difficultyOption = difficultyOptions.find(opt => opt.value === selectedDifficulty);\n if (difficultyOption && difficultyOption.value !== '') {\n filters.min_difficulty = difficultyOption.min;\n filters.max_difficulty = difficultyOption.max;\n }\n }\n\n Object.keys(filters).forEach(key =>\n filters[key] === undefined && delete filters[key]\n );\n\n setCurrentPage(1);\n searchPrompts(query, filters);\n setShouldApplyFilters(false);\n }\n }, [shouldApplyFilters, hasSearched, query, searchPrompts, selectedTraffic, selectedIntent, selectedDifficulty, setCurrentPage]);\n\n // Fetch topics for the project\n const fetchTopics = useCallback(async () => {\n try {\n const response = await axios.get(`/api/projects/${projectId}/prompt_research/topics`);\n setTopics(response.data.topics || []);\n } catch (err) {\n console.error('Error fetching topics:', err);\n }\n }, [projectId]);\n\n // Event handlers\n const clearFilters = () => {\n setSelectedTraffic('');\n setSelectedIntent('');\n setSelectedDifficulty(''); // Clear difficulty dropdown instead of range\n setCurrentPage(1);\n\n // Apply the cleared filters only if there's a previous search\n if (hasSearched && query.trim()) {\n setShouldApplyFilters(true);\n }\n };\n\n const handleSearchSubmit = (e) => {\n if (e) e.preventDefault();\n setCurrentPage(1);\n\n const filters = {\n traffic: selectedTraffic || undefined,\n intent: selectedIntent || undefined,\n };\n\n // Handle difficulty filter conversion\n if (selectedDifficulty) {\n const difficultyOption = difficultyOptions.find(opt => opt.value === selectedDifficulty);\n if (difficultyOption && difficultyOption.value !== '') {\n filters.min_difficulty = difficultyOption.min;\n filters.max_difficulty = difficultyOption.max;\n }\n }\n\n Object.keys(filters).forEach(key =>\n filters[key] === undefined && delete filters[key]\n );\n\n searchPrompts(query, filters);\n };\n\n const handleKeyDown = (e) => {\n if (e.key === 'Enter') {\n e.preventDefault();\n handleSearchSubmit();\n }\n };\n\n const handlePageChange = (page) => {\n setCurrentPage(page);\n };\n\n const handleApplyFilters = () => {\n if (hasSearched && query.trim()) {\n setShouldApplyFilters(true);\n }\n };\n\n const handleAddToTopic = (prompt) => {\n setSelectedPrompt(prompt);\n setShowTopicModal(true);\n\n // Default to creating a new topic\n setIsCreatingTopic(true);\n\n // Prepopulate the new topic name with the search query\n setNewTopicName(query.trim());\n\n // Reset the selected topic ID\n setSelectedTopicId('');\n\n // Fetch available topics in case user wants to select an existing one\n fetchTopics();\n };\n\n // New function to navigate to the prompt analytics tab\n const handleViewInAnalytics = (prompt) => {\n // Navigate to prompt analytics tab with search filter for this prompt\n navigate(`/projects/${projectId}/prompts?search=${encodeURIComponent(prompt.prompt)}`);\n };\n\n // New sorting function\n const handleSort = (field) => {\n if (sortField === field) {\n // Toggle direction if clicking the same field\n setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');\n } else {\n // Set new field and default to ascending\n setSortField(field);\n setSortDirection('asc');\n }\n };\n\n // Sort the prompts based on current sort settings\n const getSortedPrompts = (prompts) => {\n if (!sortField) return prompts;\n\n return [...prompts].sort((a, b) => {\n let aValue = a[sortField];\n let bValue = b[sortField];\n\n // Handle string comparisons\n if (typeof aValue === 'string' && typeof bValue === 'string') {\n aValue = aValue.toLowerCase();\n bValue = bValue.toLowerCase();\n }\n\n // Direction-based comparison\n if (sortDirection === 'asc') {\n return aValue > bValue ? 1 : -1;\n } else {\n return aValue < bValue ? 1 : -1;\n }\n });\n };\n\n // Render sort indicator\n const renderSortIndicator = (field) => {\n if (sortField !== field) return null;\n\n return sortDirection === 'asc'\n ? \n : ;\n };\n\n const handleTopicSubmit = async () => {\n if (!selectedPrompt) return;\n\n try {\n setTopicModalLoading(true);\n\n let topicId = selectedTopicId;\n let topicName = '';\n\n if (isCreatingTopic && newTopicName.trim()) {\n const topicResponse = await axios.post(`/api/projects/${projectId}/prompt_research/topics`, {\n topic: { name: newTopicName.trim() }\n });\n topicId = topicResponse.data.topic.id;\n topicName = topicResponse.data.topic.name;\n } else if (selectedTopicId) {\n // Find the topic name from the topics list\n const topic = topics.find(t => t.id.toString() === selectedTopicId);\n topicName = topic?.name || '';\n }\n\n if (!topicId) {\n alert('Please select a topic or create a new one');\n return;\n }\n\n await axios.post(`/api/projects/${projectId}/prompt_research/topics/${topicId}/prompts`, {\n prompt: { prompt: selectedPrompt.prompt_text || selectedPrompt.prompt }\n });\n\n // Track \"Prompt added to topic\" event\n trackEvent('Prompt added to topic', {\n project_id: projectId,\n user_id: user?.id,\n topic_id: topicId,\n topic_name: topicName,\n prompt_text: selectedPrompt.prompt_text || selectedPrompt.prompt,\n source: 'prompt_research'\n });\n\n // After successfully adding to a topic, update our existingPrompts set\n setExistingPrompts(prev => {\n const updated = new Set(prev);\n updated.add((selectedPrompt.prompt_text || selectedPrompt.prompt).toLowerCase().trim());\n return updated;\n });\n\n setShowTopicModal(false);\n setSelectedPrompt(null);\n\n } catch (err) {\n console.error('Error adding prompt to topic:', err);\n alert('Failed to add prompt to topic. Please try again.');\n } finally {\n setTopicModalLoading(false);\n }\n };\n\n const closeTopicModal = () => {\n setShowTopicModal(false);\n setSelectedPrompt(null);\n setSelectedTopicId('');\n setNewTopicName('');\n setIsCreatingTopic(true); // Reset to default: creating a new topic\n };\n\n // Helper functions\n const getIntentBadgeColor = (intent) => {\n switch (intent) {\n case 'commercial': return 'bg-green-100 text-green-800';\n case 'transactional': return 'bg-blue-100 text-blue-800';\n case 'informational': return 'bg-purple-100 text-purple-800';\n case 'navigational': return 'bg-orange-100 text-orange-800';\n default: return 'bg-gray-100 text-gray-800';\n }\n };\n\n const getVolumeBadgeColor = (volume) => {\n switch (volume) {\n case 'high': return 'bg-red-100 text-red-800';\n case 'medium': return 'bg-yellow-100 text-yellow-800';\n case 'low': return 'bg-gray-100 text-gray-800';\n default: return 'bg-gray-100 text-gray-800';\n }\n };\n\n const getDifficultyColor = (difficulty) => {\n if (difficulty >= 80) return 'text-red-600 font-semibold';\n if (difficulty >= 60) return 'text-orange-600 font-semibold';\n if (difficulty >= 40) return 'text-yellow-600 font-semibold';\n return 'text-green-600 font-semibold';\n };\n\n // Helper function to check if a prompt is already in the project\n const isPromptInProject = (prompt) => {\n return existingPrompts.has(prompt.prompt.toLowerCase().trim());\n };\n\n // Progress bar component for job status\n const ProgressBar = ({ percent }) => (\n
\n
\n \n );\n\n // Calculate pagination\n const totalPages = Math.ceil(filteredCount / itemsPerPage);\n const startIndex = (currentPage - 1) * itemsPerPage;\n const endIndex = startIndex + itemsPerPage;\n\n // Apply sorting to prompts\n const sortedPrompts = getSortedPrompts(prompts);\n const currentPrompts = sortedPrompts.slice(startIndex, endIndex);\n\n return (\n
\n {/* Search */}\n
\n
\n
\n
\n \n
\n setQuery(e.target.value)}\n onKeyDown={handleKeyDown}\n placeholder=\"Enter keywords to research prompts...\"\n className=\"block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg leading-5 bg-white placeholder-gray-500 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500\"\n />\n
\n \n \n {loading ? 'Searching...' : 'Search'}\n \n
\n
\n\n {/* Filters */}\n {hasSearched && (\n
\n
\n {/* All filters in one row */}\n
\n {/* Filters Label */}\n
\n

\n Filters:\n

\n
\n\n {/* Traffic Filter - FIRST */}\n
\n \n setSelectedTraffic(e.target.value)}\n >\n {trafficOptions.map(option => (\n \n ))}\n \n
\n\n {/* Difficulty Filter - SECOND */}\n
\n \n setSelectedDifficulty(e.target.value)}\n >\n {difficultyOptions.map(option => (\n \n ))}\n \n
\n\n {/* Intent Filter - THIRD */}\n
\n \n setSelectedIntent(e.target.value)}\n >\n {intentOptions.map(option => (\n \n ))}\n \n
\n\n {/* Clear Filters Button */}\n
\n \n \n Clear Filters\n \n
\n\n {/* Apply Filters Button */}\n
\n \n Apply Filters\n \n
\n
\n\n
\n Showing {filteredCount} of {totalCount} prompts\n {filteredCount > itemsPerPage && (\n Page {currentPage} of {totalPages}\n )}\n
\n
\n
\n )}\n\n {/* Error State */}\n {error && (\n
\n
\n
\n \n

{error}

\n
\n
\n
\n )}\n\n {/* Job Processing State */}\n {loading && jobStatus && jobStatus !== 'completed' && (\n
\n
\n {jobStatus === 'queued' ? 'Job queued. Waiting for processing...' : 'Collecting prompt data...'}\n
\n
\n \n

\n This may take a minute or two. Searching and collecting related prompt information.\n

\n
\n
\n )}\n\n {/* Loading State */}\n {loading && !jobStatus && (\n
\n
Collecting prompt data...
\n
\n )}\n\n {/* Results */}\n {!loading && hasSearched && (\n
\n {prompts.length > 0 ? (\n <>\n {/* Research Results Header */}\n
\n

Research Results

\n
\n\n {/* Results List */}\n
\n {currentPrompts.map((prompt, index) => (\n
\n
\n
\n

\n {prompt.prompt}\n

\n
\n Traffic: {prompt.volume}\n Difficulty: {prompt.difficulty}\n Intent: {prompt.intent}\n
\n
\n
\n {isPromptInProject(prompt) ? (\n handleViewInAnalytics(prompt)}\n className=\"inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-lg text-blue-700 bg-blue-100 hover:bg-blue-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500\"\n >\n \n View in Analytics\n \n ) : (\n handleAddToTopic(prompt)}\n className=\"inline-flex items-center justify-center px-6 py-2 border border-transparent rounded-lg shadow-sm text-sm font-medium hover:bg-opacity-90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 min-w-[180px]\"\n style={{ backgroundColor: '#EDEDFC', color: '#4F46E5' }}\n >\n \n Add to Topic\n \n )}\n
\n
\n
\n ))}\n
\n\n {/* Pagination */}\n {totalPages > 1 && (\n
\n
\n handlePageChange(currentPage - 1)}\n disabled={currentPage === 1}\n className=\"relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-lg text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed\"\n >\n Previous\n \n handlePageChange(currentPage + 1)}\n disabled={currentPage === totalPages}\n className=\"ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-lg text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed\"\n >\n Next\n \n
\n
\n
\n

\n Showing {startIndex + 1} to{' '}\n {Math.min(endIndex, filteredCount)} of{' '}\n {filteredCount} results\n

\n
\n
\n \n
\n
\n
\n )}\n \n ) : (\n
\n \n {totalCount > 0 ? (\n <>\n

No prompts match your current filters

\n \n Clear filters to see all results\n \n \n ) : (\n <>\n

No prompts found for \"{query}\"

\n

Try searching with different keywords

\n \n )}\n
\n )}\n
\n )}\n\n {/* Initial State */}\n {!loading && !hasSearched && (\n
\n \n

Research Prompt Ideas

\n

Enter keywords above to discover relevant prompts and analyze their commercial potential

\n
\n )}\n\n {/* Topic Selection Modal */}\n {showTopicModal && (\n
\n
\n
\n
\n

\n Add Prompt to Topic\n

\n \n \n \n
\n\n {selectedPrompt && (\n
\n

Selected Prompt:

\n

\n {selectedPrompt.prompt_text || selectedPrompt.prompt}\n

\n
\n )}\n\n
\n
\n \n \n
\n\n {isCreatingTopic ? (\n
\n \n setNewTopicName(e.target.value)}\n placeholder=\"Enter topic name...\"\n className=\"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500\"\n />\n
\n ) : (\n
\n \n setSelectedTopicId(e.target.value)}\n className=\"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500\"\n >\n \n {topics.map(topic => (\n \n ))}\n \n {topics.length === 0 && (\n

\n No topics found. Create a new topic instead.\n

\n )}\n
\n )}\n\n
\n \n Cancel\n \n \n {topicModalLoading ? 'Adding...' : 'Add to Topic'}\n \n
\n
\n
\n
\n
\n )}\n
\n );\n};\n\nexport default PromptResearch;", "import React, { useState, useEffect, useRef } from 'react';\nimport { useNavigate, useParams } from 'react-router-dom';\nimport axios from '../../AxiosConfig';\nimport {\n Edit,\n Trash,\n AlertCircle,\n Plus,\n ArrowLeft,\n MessageSquare,\n BarChart2,\n RefreshCw,\n Lightbulb,\n Check,\n Eye,\n Search\n} from 'lucide-react';\nimport SideDrawer from './SideDrawer';\nimport ResponseCard from './ResponseCard';\nimport UnifiedPromptManagement from './UnifiedPromptManagement';\nimport { useLocation } from 'react-router-dom';\n\nconst ManageTopic = () => {\n const navigate = useNavigate();\n const { projectId, topicId } = useParams();\n const location = useLocation();\n const [topic, setTopic] = useState(null);\n const [prompts, setPrompts] = useState([]);\n const [suggestions, setSuggestions] = useState([]);\n const [loading, setLoading] = useState(true);\n const [suggestionsLoading, setSuggestionsLoading] = useState(false);\n const [promptsLoading, setPromptsLoading] = useState(false);\n const [generatingSuggestions, setGeneratingSuggestions] = useState(false);\n const [error, setError] = useState(null);\n const [showDeleteModal, setShowDeleteModal] = useState(false);\n const [promptToDelete, setPromptToDelete] = useState(null);\n const [selectedPrompt, setSelectedPrompt] = useState(null);\n const [sideDrawerOpen, setSideDrawerOpen] = useState(false);\n const [responses, setResponses] = useState([]);\n const [loadingResponses, setLoadingResponses] = useState(false);\n // Track which suggestions have been converted to prompts\n const [convertedSuggestions, setConvertedSuggestions] = useState({});\n const [convertingInProgress, setConvertingInProgress] = useState({});\n const suggestionsPollIntervalRef = useRef(null);\n const promptsPollIntervalRef = useRef(null);\n const [hasGeneratedSuggestions, setHasGeneratedSuggestions] = useState(false);\n\n // Add mode toggle state (defaulting to 'manage' since this is the manage topic page)\n const [activeMode, setActiveMode] = useState('manage');\n\n console.log('ManageTopic rendered with useParams:', { projectId, topicId });\n\n useEffect(() => {\n const fetchTopicData = async () => {\n try {\n if (!projectId || !topicId) {\n console.error('Missing required params:', { projectId, topicId });\n setError('Missing required project or topic information');\n setLoading(false);\n return;\n }\n\n console.log(`Making API request to: /api/projects/${projectId}/topics/${topicId}`);\n setLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/topics/${topicId}`);\n console.log('API response:', response.data);\n setTopic(response.data);\n setPrompts(response.data.prompts || []);\n setError(null);\n } catch (err) {\n console.error('Error fetching topic data:', err);\n const errorMessage = err.response?.data?.message || err.message || 'Failed to load topic data. Please try again later.';\n setError(errorMessage);\n } finally {\n setLoading(false);\n }\n };\n\n fetchTopicData();\n fetchSuggestions();\n fetchAllPromptResponses();\n\n // Start polling for suggestion and prompt response updates\n startPolling();\n\n // Clean up polling when component unmounts\n return () => {\n if (suggestionsPollIntervalRef.current) {\n clearInterval(suggestionsPollIntervalRef.current);\n }\n if (promptsPollIntervalRef.current) {\n clearInterval(promptsPollIntervalRef.current);\n }\n };\n }, [projectId, topicId]);\n\n // Auto-generate suggestions if topic has prompts but no suggestions\n useEffect(() => {\n const autoGenerateSuggestions = async () => {\n // Only generate suggestions if:\n // 1. We have prompts\n // 2. We don't have suggestions yet\n // 3. We haven't already tried to generate suggestions in this session\n // 4. We're not currently loading\n if (prompts.length > 0 && suggestions.length === 0 && !hasGeneratedSuggestions && !loading && !generatingSuggestions) {\n console.log('Auto-generating suggestions for topic with existing prompts');\n setHasGeneratedSuggestions(true); // Mark that we've tried generating\n await generateSuggestions();\n }\n };\n\n autoGenerateSuggestions();\n }, [prompts, suggestions, loading, hasGeneratedSuggestions, generatingSuggestions]);\n\n const startPolling = () => {\n // Clear any existing intervals\n if (suggestionsPollIntervalRef.current) {\n clearInterval(suggestionsPollIntervalRef.current);\n }\n if (promptsPollIntervalRef.current) {\n clearInterval(promptsPollIntervalRef.current);\n }\n\n // Set up new polling intervals\n suggestionsPollIntervalRef.current = setInterval(() => {\n fetchSuggestions();\n }, 5000); // Poll suggestions every 5 seconds\n\n promptsPollIntervalRef.current = setInterval(() => {\n fetchAllPromptResponses();\n }, 5000); // Poll prompt responses every 5 seconds\n };\n\n const fetchAllPromptResponses = async () => {\n if (!projectId || !topicId) return;\n\n try {\n setPromptsLoading(true);\n // Get all prompts with their updated responses\n const response = await axios.get(`/api/projects/${projectId}/topics/${topicId}/prompts`);\n setPrompts(response.data || []);\n } catch (err) {\n console.error('Error fetching prompt responses:', err);\n } finally {\n setPromptsLoading(false);\n }\n };\n\n const fetchSuggestions = async () => {\n if (!projectId || !topicId) return;\n\n try {\n setSuggestionsLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/topics/${topicId}/suggestions`);\n const fetchedSuggestions = response.data || [];\n setSuggestions(fetchedSuggestions);\n\n // If we've received suggestions, update the flag to avoid re-generating\n if (fetchedSuggestions.length > 0) {\n setHasGeneratedSuggestions(true);\n }\n } catch (err) {\n console.error('Error fetching suggestions:', err);\n } finally {\n setSuggestionsLoading(false);\n }\n };\n\n const fetchPromptResponses = async (promptId) => {\n try {\n setLoadingResponses(true);\n const response = await axios.get(`/api/prompt_analytics/prompt/${promptId}/responses`);\n setResponses(response.data.responses || []);\n } catch (err) {\n console.error('Error fetching prompt responses:', err);\n setResponses([]);\n } finally {\n setLoadingResponses(false);\n }\n };\n\n const handleViewResponses = async (prompt) => {\n if (!prompt || !prompt.id) {\n console.error('Invalid prompt:', prompt);\n return;\n }\n\n setSelectedPrompt(prompt);\n setSideDrawerOpen(true);\n await fetchPromptResponses(prompt.id);\n };\n\n const closeSideDrawer = () => {\n setSideDrawerOpen(false);\n setSelectedPrompt(null);\n setResponses([]);\n };\n\n const getPlatformBadge = (platform) => {\n const colors = {\n chatgpt: 'bg-green-100 text-green-800',\n claude: 'bg-blue-100 text-blue-800',\n perplexity: 'bg-purple-100 text-purple-800',\n google_ai_overview: 'bg-orange-100 text-orange-800',\n 0: 'bg-green-100 text-green-800', // ChatGPT\n 1: 'bg-blue-100 text-blue-800', // Claude\n 2: 'bg-purple-100 text-purple-800', // Perplexity\n 3: 'bg-orange-100 text-orange-800' // Google AI Overview\n };\n return colors[platform] || 'bg-gray-100 text-gray-800';\n };\n\n const getProminenceScoreColor = (score) => {\n if (score >= 70) return 'text-green-600 font-semibold';\n if (score >= 40) return 'text-yellow-600 font-semibold';\n return 'text-red-600 font-semibold';\n };\n\n // Updated generateSuggestions function with correct route path\n const generateSuggestions = async () => {\n try {\n setGeneratingSuggestions(true);\n // Updated route path to match the defined route in routes.rb\n await axios.post(`/api/projects/${projectId}/topics/${topicId}/suggestions/generate_suggestions`);\n // Fetch suggestions after a short delay to ensure job has started\n setTimeout(() => fetchSuggestions(), 1000);\n } catch (err) {\n console.error('Error generating suggestions:', err);\n setError('Failed to generate prompt suggestions. Please try again.');\n } finally {\n setGeneratingSuggestions(false);\n }\n };\n\n const convertSuggestionToPrompt = async (suggestionId, suggestionText) => {\n try {\n // Mark this suggestion as in progress\n setConvertingInProgress(prev => ({ ...prev, [suggestionId]: true }));\n\n // Create a new prompt with the suggestion text\n const response = await axios.post(`/api/projects/${projectId}/topics/${topicId}/prompts`, {\n prompt: {\n prompt: suggestionText\n }\n });\n\n // Mark the suggestion as converted instead of removing it\n setConvertedSuggestions(prev => ({ ...prev, [suggestionId]: true }));\n\n // Add the new prompt to the list\n setPrompts([...prompts, response.data]);\n\n // Note: We're not deleting the suggestion or removing it from the list anymore\n } catch (err) {\n console.error('Error converting suggestion to prompt:', err);\n setError('Failed to convert suggestion to prompt. Please try again.');\n } finally {\n // Clear the in-progress state\n setConvertingInProgress(prev => ({ ...prev, [suggestionId]: false }));\n }\n };\n\n const handleBackToProject = () => {\n // Check if we have history to go back\n if (location.state && location.state.fromPromptsPage) {\n // Navigate back to the prompts management page\n navigate(`/projects/${projectId}/prompts`);\n } else {\n // Default fallback to overview if no state is available\n navigate(`/projects/${projectId}/overview`);\n }\n };\n\n const handleEditTopic = () => {\n navigate(`/projects/${projectId}/topics/${topicId}/edit`);\n };\n\n const handleDeletePrompt = (promptId) => {\n setPromptToDelete(promptId);\n setShowDeleteModal(true);\n };\n\n const confirmDeletePrompt = async () => {\n try {\n await axios.delete(`/api/projects/${projectId}/topics/${topicId}/prompts/${promptToDelete}`);\n setPrompts(prompts.filter(prompt => prompt.id !== promptToDelete));\n setShowDeleteModal(false);\n setPromptToDelete(null);\n } catch (err) {\n console.error('Error deleting prompt:', err);\n const errorMessage = err.response?.data?.message || err.message || 'Failed to delete prompt. Please try again.';\n setError(errorMessage);\n }\n };\n\n const handleCreatePrompt = () => {\n navigate(`/projects/${projectId}/topics/${topicId}/prompts/new`);\n };\n\n // Mode toggle handler\n const handleModeToggle = (mode) => {\n setActiveMode(mode);\n };\n\n if (loading) {\n return (\n
\n
Loading topic data...
\n
\n );\n }\n\n if (error) {\n return (\n
\n
\n
\n \n

Error Loading Topic

\n
\n

{error}

\n
\n

Debug: projectId={projectId}, topicId={topicId}

\n
\n \n Return to Project\n \n
\n
\n );\n }\n\n if (!topic) {\n return (\n
\n
\n
\n \n

Topic Not Found

\n
\n

The topic you are looking for does not exist or you do not have permission to view it.

\n
\n

Debug: projectId={projectId}, topicId={topicId}

\n
\n \n Return to Project\n \n
\n
\n );\n }\n\n return (\n
\n {/* Header with mode toggle - similar to UnifiedPromptManagement */}\n
\n
\n
\n
\n \n \n Back\n \n
\n

\n {topic.name}\n

\n

\n Manage prompts and view AI-generated suggestions for this topic\n

\n
\n
\n
\n \n \n Edit Topic\n \n \n \n Add Prompt\n \n
\n
\n
\n\n {/* Mode Toggle - showing current mode as active */}\n
\n handleModeToggle('manage')}\n className={`px-4 py-2 text-sm font-medium rounded-md transition-colors ${\n activeMode === 'manage'\n ? 'bg-white shadow-sm'\n : 'text-gray-500 hover:text-gray-700'\n }`}\n style={activeMode === 'manage' ? { color: '#4F46E5' } : {}}\n >\n Manage Prompts\n \n handleModeToggle('research')}\n className={`px-4 py-2 text-sm font-medium rounded-md transition-colors ${\n activeMode === 'research'\n ? 'bg-white shadow-sm'\n : 'text-gray-500 hover:text-gray-700'\n }`}\n style={activeMode === 'research' ? { color: '#4F46E5' } : {}}\n >\n Research\n \n
\n
\n\n {/* Content based on active mode */}\n {activeMode === 'manage' ? (\n <>\n {/* Topic Info Card */}\n
\n
\n \n

Topic Details

\n
\n
\n
\n

Topic Name

\n

{topic.name}

\n
\n
\n

Number of Prompts

\n

{prompts.length}

\n
\n
\n
\n\n {/* Prompts and Suggestions - Side by Side */}\n
\n {/* Prompts List */}\n
\n
\n
\n
\n

Prompts

\n {promptsLoading && prompts.length === 0 && (\n \n )}\n
\n {prompts.length > 0 && (\n \n {prompts.length} {prompts.length === 1 ? 'Prompt' : 'Prompts'}\n \n )}\n
\n
\n\n {prompts.length === 0 ? (\n
\n \n

No prompts available

\n

There are no prompts for this topic yet.

\n \n \n Create a Prompt\n \n
\n ) : (\n
    \n {prompts.map((prompt) => (\n
  • \n
    \n handleViewResponses(prompt)}\n style={{ cursor: 'pointer' }}\n >\n
    \n {prompt.responses?.length > 0 ? (\n <>\n \n \n {prompt.responses.length} Responses\n \n \n ) : (\n <>\n \n \n Collecting response data...\n \n \n )}\n
    \n
    \n

    {prompt.prompt}

    \n
    \n
    \n
    \n {\n e.stopPropagation();\n handleViewResponses(prompt);\n }}\n className=\"p-1.5 rounded-md text-gray-500 hover:text-indigo-600 hover:bg-gray-100\"\n title=\"View Responses\"\n >\n \n \n {\n e.stopPropagation();\n navigate(`/projects/${projectId}/topics/${topicId}/prompts/${prompt.id}/edit`);\n }}\n className=\"p-1.5 rounded-md text-gray-500 hover:text-gray-900 hover:bg-gray-100\"\n title=\"Edit Prompt\"\n >\n \n \n {\n e.stopPropagation();\n handleDeletePrompt(prompt.id);\n }}\n className=\"p-1.5 rounded-md text-gray-500 hover:text-red-600 hover:bg-gray-100\"\n title=\"Delete Prompt\"\n >\n \n \n
    \n
\n \n ))}\n \n )}\n\n {/* Add Prompt Button - Fixed to bottom */}\n {prompts.length > 0 && (\n
\n \n \n Add Prompt\n \n
\n )}\n
\n\n {/* Right Column - Suggestions or Loading State */}\n
\n
\n
\n
\n \n

Suggested Prompts

\n {(suggestionsLoading || generatingSuggestions) && (\n \n )}\n
\n {suggestions.length > 0 && (\n \n {suggestions.length} {suggestions.length === 1 ? 'Suggestion' : 'Suggestions'}\n \n )}\n
\n
\n\n {/* Show either suggestions, loading state, or empty state */}\n {suggestions.length > 0 ? (\n
    \n {suggestions.map((suggestion) => (\n
  • \n
    \n
    \n
    \n

    {suggestion.prompt}

    \n {convertedSuggestions[suggestion.id] && (\n
    \n \n Added to prompts\n
    \n )}\n
    \n
    \n
    \n {!convertedSuggestions[suggestion.id] ? (\n convertSuggestionToPrompt(suggestion.id, suggestion.prompt)}\n disabled={convertingInProgress[suggestion.id]}\n className={`p-1.5 rounded-md text-gray-500 \n ${convertingInProgress[suggestion.id]\n ? 'cursor-wait bg-gray-100'\n : 'hover:text-green-600 hover:bg-gray-100'} \n transition-colors`}\n title=\"Add to prompts\"\n >\n {convertingInProgress[suggestion.id] ? (\n \n ) : (\n \n )}\n \n ) : (\n handleViewResponses(prompts.find(p => p.prompt === suggestion.prompt))}\n className=\"p-1.5 rounded-md text-gray-500 hover:text-indigo-600 hover:bg-gray-100 transition-colors\"\n title=\"View prompt responses\"\n >\n \n \n )}\n
    \n
    \n
  • \n ))}\n
\n ) : prompts.length > 0 ? (\n // If we have prompts but no suggestions yet, show loading state\n
\n \n

Generating Suggestions

\n

\n We're analyzing your existing prompts to generate relevant suggestions.\n This may take a moment.\n

\n
\n ) : (\n // If no prompts and no suggestions, show empty state\n
\n \n

No Suggestions Available

\n

Create some prompts first to enable AI-powered suggestions.

\n
\n )}\n
\n
\n \n ) : (\n /* Research Mode Content - Show UnifiedPromptManagement in research mode */\n \n )}\n\n {/* Delete Confirmation Modal */}\n {showDeleteModal && (\n
\n
\n
\n
\n
\n\n ​\n\n
\n
\n
\n
\n \n
\n
\n

Delete Prompt

\n
\n

\n Are you sure you want to delete this prompt? All of the responses associated with this prompt will be permanently removed. This action cannot be undone.\n

\n
\n
\n
\n
\n
\n \n Delete\n \n setShowDeleteModal(false)}\n >\n Cancel\n \n
\n
\n
\n
\n )}\n\n {/* Side Drawer */}\n \n {/* Prompt Text */}\n
\n

Prompt

\n
\n

{selectedPrompt?.prompt}

\n
\n
\n\n {/* Responses */}\n
\n

\n Responses ({responses.length})\n

\n\n {loadingResponses ? (\n
\n
Loading responses...
\n
\n ) : responses.length === 0 ? (\n
\n \n

No responses yet for this prompt.

\n
\n ) : (\n
\n {responses.map((response) => (\n \n ))}\n
\n )}\n
\n \n \n );\n};\n\nexport default ManageTopic;", "import React, { useState, useEffect } from 'react';\nimport { useNavigate, useParams, useLocation } from 'react-router-dom';\nimport axios from '../../AxiosConfig';\nimport {\n ArrowLeft,\n Save,\n AlertCircle\n} from 'lucide-react';\n\nconst EditTopic = () => {\n const [topic, setTopic] = useState({ name: '' });\n const [loading, setLoading] = useState(true);\n const [saving, setSaving] = useState(false);\n const [error, setError] = useState(null);\n\n const navigate = useNavigate();\n const location = useLocation();\n const { projectId, topicId } = useParams();\n const isNewTopic = !topicId || topicId === 'new';\n\n useEffect(() => {\n const fetchTopic = async () => {\n if (isNewTopic) {\n setTopic({ name: '' });\n setLoading(false);\n return;\n }\n\n try {\n setLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/topics/${topicId}`);\n setTopic(response.data);\n setError(null);\n } catch (err) {\n console.error('Error fetching topic:', err);\n const errorMessage = err.response?.data?.message || err.message || 'Failed to load topic. Please try again later.';\n setError(errorMessage);\n } finally {\n setLoading(false);\n }\n };\n\n fetchTopic();\n }, [projectId, topicId, isNewTopic]);\n\n const handleChange = (e) => {\n setTopic({ ...topic, name: e.target.value });\n };\n\n const handleSubmit = async (e) => {\n e.preventDefault();\n\n try {\n setSaving(true);\n\n if (isNewTopic) {\n // Create new topic\n const response = await axios.post(`/api/projects/${projectId}/topics`, { topic });\n // After creating, navigate to the new topic in UnifiedPromptManagement\n const newTopicId = response.data.id;\n navigate(`/projects/${projectId}/prompts/topics/${newTopicId}`, {\n state: { fromPromptsPage: true }\n });\n } else {\n // Update existing topic\n await axios.put(`/api/projects/${projectId}/topics/${topicId}`, { topic });\n // After updating, go back to appropriate page\n handleBackNavigation();\n }\n } catch (err) {\n console.error('Error saving topic:', err);\n const errorMessage = err.response?.data?.message || err.message || 'Failed to save topic. Please try again.';\n setError(errorMessage);\n setSaving(false);\n }\n };\n\n // Handle proper back navigation based on where the user came from\n const handleBackNavigation = () => {\n // Check if we came from the prompts page\n if (location.state && location.state.fromPromptsPage) {\n // If editing an existing topic from the new unified interface, go back to that topic\n if (!isNewTopic) {\n navigate(`/projects/${projectId}/prompts/topics/${topicId}`, {\n state: { fromPromptsPage: true }\n });\n } else {\n // For new topics, go back to the main prompts page\n navigate(`/projects/${projectId}/prompts`);\n }\n } else if (isNewTopic) {\n // Default for new topics is to go to prompts page\n navigate(`/projects/${projectId}/prompts`);\n } else {\n // For existing topics being edited from old routes, go back to topic page\n navigate(`/projects/${projectId}/prompts/topics/${topicId}`, {\n state: { fromPromptsPage: true }\n });\n }\n };\n\n // Cancel button also uses proper back navigation\n const handleCancel = () => {\n handleBackNavigation();\n };\n\n if (loading) {\n return (\n
\n
Loading...
\n
\n );\n }\n\n return (\n
\n {/* Header */}\n
\n \n \n \n

\n {isNewTopic ? 'Create New Topic' : 'Edit Topic'}\n

\n
\n\n {/* Error Message */}\n {error && (\n
\n
\n \n

{error}

\n
\n
\n )}\n\n {/* Form */}\n
\n
\n
\n \n \n

\n A topic groups related prompts together.\n

\n
\n\n
\n \n Cancel\n \n \n \n {saving ? 'Saving...' : 'Save Topic'}\n \n
\n
\n
\n
\n );\n};\n\nexport default EditTopic;", "import React, { useState, useEffect } from 'react';\nimport { useNavigate, useParams, useLocation } from 'react-router-dom';\nimport axios from '../../AxiosConfig';\nimport {\n ArrowLeft,\n Save,\n AlertCircle,\n Tag\n} from 'lucide-react';\n\nconst PromptForm = () => {\n const [prompt, setPrompt] = useState({ prompt: '', topic_id: '' });\n const [loading, setLoading] = useState(false);\n const [topicsLoading, setTopicsLoading] = useState(false);\n const [saving, setSaving] = useState(false);\n const [error, setError] = useState(null);\n const [topic, setTopic] = useState(null);\n const [allTopics, setAllTopics] = useState([]);\n\n const navigate = useNavigate();\n const location = useLocation();\n const { projectId, topicId, promptId } = useParams();\n const isEditing = !!promptId;\n\n // Fetch all topics for the dropdown\n useEffect(() => {\n const fetchTopics = async () => {\n try {\n setTopicsLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/topics`);\n setAllTopics(response.data);\n } catch (err) {\n console.error('Error fetching topics:', err);\n // We don't set the main error here to avoid blocking the form\n } finally {\n setTopicsLoading(false);\n }\n };\n\n if (projectId) {\n fetchTopics();\n }\n }, [projectId]);\n\n useEffect(() => {\n const fetchData = async () => {\n try {\n setLoading(true);\n\n // Fetch topic data\n const topicResponse = await axios.get(`/api/projects/${projectId}/topics/${topicId}`);\n setTopic(topicResponse.data);\n\n // If editing, fetch the prompt data\n if (isEditing) {\n const promptResponse = await axios.get(`/api/projects/${projectId}/topics/${topicId}/prompts/${promptId}`);\n setPrompt({\n ...promptResponse.data,\n topic_id: topicId // Set the current topic ID\n });\n } else {\n // For new prompts, default to the current topic\n setPrompt(prev => ({ ...prev, topic_id: topicId }));\n }\n\n setError(null);\n } catch (err) {\n console.error('Error fetching data:', err);\n const errorMessage = err.response?.data?.message || err.message || 'Failed to load data. Please try again later.';\n setError(errorMessage);\n } finally {\n setLoading(false);\n }\n };\n\n if (projectId && topicId) {\n fetchData();\n }\n }, [projectId, topicId, promptId, isEditing]);\n\n const handleTextChange = (e) => {\n setPrompt({ ...prompt, prompt: e.target.value });\n };\n\n const handleTopicChange = (e) => {\n setPrompt({ ...prompt, topic_id: e.target.value });\n };\n\n const handleSubmit = async (e) => {\n e.preventDefault();\n\n try {\n setSaving(true);\n\n // Prepare data with topic_id for API\n const promptData = {\n prompt: {\n prompt: prompt.prompt,\n topic_id: prompt.topic_id\n }\n };\n\n if (isEditing) {\n // Update existing prompt\n await axios.put(`/api/projects/${projectId}/topics/${topicId}/prompts/${promptId}`, promptData);\n } else {\n // Create new prompt\n await axios.post(`/api/projects/${projectId}/topics/${topicId}/prompts`, promptData);\n }\n\n // Redirect to the new UnifiedPromptManagement path\n const targetTopicId = prompt.topic_id || topicId;\n navigate(`/projects/${projectId}/prompts/topics/${targetTopicId}`, {\n state: { fromPromptsPage: true }\n });\n } catch (err) {\n console.error('Error saving prompt:', err);\n const errorMessage = err.response?.data?.message || err.message || 'Failed to save prompt. Please try again.';\n setError(errorMessage);\n setSaving(false);\n }\n };\n\n const handleCancel = () => {\n // Navigate back to the new UnifiedPromptManagement path\n navigate(`/projects/${projectId}/prompts/topics/${topicId}`, {\n state: { fromPromptsPage: true }\n });\n };\n\n if (loading) {\n return (\n
\n
Loading...
\n
\n );\n }\n\n return (\n
\n {/* Header */}\n
\n \n \n \n

\n {isEditing ? 'Edit Prompt' : 'Create New Prompt'}\n

\n
\n\n {/* Topic Info */}\n {topic && (\n
\n

\n Current Topic: {topic.name}\n

\n
\n )}\n\n {/* Error Message */}\n {error && (\n
\n
\n \n

{error}

\n
\n
\n )}\n\n {/* Form */}\n
\n
\n {/* Topic Selection Dropdown */}\n {isEditing && (\n
\n \n \n {topicsLoading ? (\n \n ) : (\n allTopics.map(topic => (\n \n ))\n )}\n \n

\n You can move this prompt to a different topic.\n

\n
\n )}\n\n {/* Prompt Text */}\n
\n \n \n

\n Write a clear, specific prompt related to the topic.\n

\n
\n\n
\n \n Cancel\n \n \n \n {saving ? 'Saving...' : 'Save Prompt'}\n \n
\n
\n
\n
\n );\n};\n\nexport default PromptForm;", "// app/javascript/components/Dashboard/Projects/CompetitorAnalysis.js\nimport React, { useState, useEffect, useContext } from 'react';\nimport axios from '../../AxiosConfig';\nimport {\n BarChart,\n Users,\n AlertCircle,\n PieChart as PieChartIcon,\n ChevronRight,\n ArrowLeft,\n LineChart as LineChartIcon,\n Eye,\n ArrowUp,\n ArrowDown,\n TrendingUp,\n Target,\n Zap\n} from 'lucide-react';\nimport { Line } from 'recharts';\nimport { PieChart, Pie, Cell, LineChart, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';\nimport SideDrawer from './SideDrawer';\nimport ResponseCard from './ResponseCard';\nimport SortableTopicBreakdownTable from './SortableTopicBreakdownTable';\nimport { AuthContext } from '../../../context/AuthContext'; // Import AuthContext for user data\nimport { trackEvent } from '../../Analytics/mixpanel'; // Import trackEvent\n\n// Define a color scheme with 15 distinct colors - move this outside the component\n// These colors are selected to be visually distinct and accessible\nconst COMPANY_COLORS = [\n '#1E88E5', // Blue (reserved for customer) - slightly deeper than previous\n '#FF8C00', // Dark orange\n '#00A878', // Green - vibrant but not too bright\n '#9C27B0', // Purple - rich but not glaring\n '#E53935', // Red - deeper than the original bright red\n '#00ACC1', // Cyan - balanced teal blue\n '#FF7043', // Deep orange/coral\n '#5E35B1', // Deep purple\n '#43A047', // Forest green\n '#FB8C00', // Amber/orange\n '#6D4C41', // Brown - earthtone for contrast\n '#C2185B', // Pink - deeper magenta\n '#039BE5', // Light blue - distinct from customer blue\n '#8D6E63', // Brown grey\n '#7CB342' // Lime green - softer than neon\n];\n\n// Helper function to get a consistent color for a company by ID\nconst getCompanyColor = (companyId, isCustomer, index = 0) => {\n // Customer always gets the first color (blue)\n if (isCustomer) return COMPANY_COLORS[0];\n\n // For competitors, use ID as a consistent hash to pick colors\n // This ensures the same competitor always gets the same color\n const colorIndex = typeof companyId === 'number'\n ? (companyId % (COMPANY_COLORS.length - 1)) + 1 // Skip first color (reserved for customer)\n : (index % (COMPANY_COLORS.length - 1)) + 1;\n\n return COMPANY_COLORS[colorIndex];\n};\n\nconst CompetitorAnalysis = ({ projectId, project }) => {\n const { user } = useContext(AuthContext); // Get user data for tracking\n\n // State for overview data\n const [overviewData, setOverviewData] = useState(null);\n const [breakdownData, setBreakdownData] = useState(null);\n const [topicData, setTopicData] = useState(null);\n const [selectedTopicId, setSelectedTopicId] = useState(null);\n\n // Response drawer state\n const [selectedPrompt, setSelectedPrompt] = useState(null);\n const [sideDrawerOpen, setSideDrawerOpen] = useState(false);\n const [promptResponses, setPromptResponses] = useState([]);\n const [loadingResponses, setLoadingResponses] = useState(false);\n\n // UI state\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n const [currentView, setCurrentView] = useState('overview'); // 'overview', 'breakdown', 'topic'\n const [selectedPlatform, setSelectedPlatform] = useState('');\n\n // Static platforms array instead of fetching from backend\n const platforms = [\n { value: '', label: 'All Platforms' },\n { value: 'chatgpt', label: 'ChatGPT' },\n { value: 'google_ai_overview', label: 'Google AI Overview' },\n { value: 'perplexity', label: 'Perplexity' }\n ];\n\n // Fetch overview data\n useEffect(() => {\n const fetchOverviewData = async () => {\n try {\n setLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/competitor_analysis/overview`, {\n params: { platform: selectedPlatform }\n });\n setOverviewData(response.data);\n setError(null);\n } catch (err) {\n console.error('Error fetching competitor analysis overview:', err);\n setError('Failed to load competitor analysis data. Please try again.');\n } finally {\n setLoading(false);\n }\n };\n\n if (currentView === 'overview') {\n fetchOverviewData();\n }\n }, [projectId, selectedPlatform, currentView]);\n\n // Fetch breakdown data\n useEffect(() => {\n const fetchBreakdownData = async () => {\n try {\n setLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/competitor_analysis/breakdown`, {\n params: { platform: selectedPlatform }\n });\n setBreakdownData(response.data);\n setError(null);\n } catch (err) {\n console.error('Error fetching competitor analysis breakdown:', err);\n setError('Failed to load competitor analysis breakdown. Please try again.');\n } finally {\n setLoading(false);\n }\n };\n\n if (currentView === 'breakdown') {\n fetchBreakdownData();\n }\n }, [projectId, selectedPlatform, currentView]);\n\n // Fetch topic data\n useEffect(() => {\n const fetchTopicData = async () => {\n if (!selectedTopicId) return;\n\n try {\n setLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/competitor_analysis/topic/${selectedTopicId}`, {\n params: { platform: selectedPlatform }\n });\n setTopicData(response.data);\n setError(null);\n } catch (err) {\n console.error('Error fetching topic breakdown:', err);\n setError('Failed to load topic breakdown. Please try again.');\n } finally {\n setLoading(false);\n }\n };\n\n if (currentView === 'topic' && selectedTopicId) {\n fetchTopicData();\n }\n }, [projectId, selectedPlatform, currentView, selectedTopicId]);\n\n // Add an effect specifically to handle time series data calculations\n useEffect(() => {\n if (overviewData && overviewData.time_series) {\n // Force recharts to re-render by causing a minor state update\n setTimeout(() => {\n setLoading(prev => !prev);\n setTimeout(() => setLoading(prev => !prev), 10);\n }, 200);\n }\n }, [overviewData]);\n\n // Fetch prompt responses when a prompt is selected (default company view)\n const fetchPromptResponses = async (promptId) => {\n try {\n setLoadingResponses(true);\n const response = await axios.get(`/api/prompt_analytics/prompt/${promptId}/responses`);\n setPromptResponses(response.data.responses || []);\n } catch (err) {\n console.error('Error fetching prompt responses:', err);\n setPromptResponses([]);\n } finally {\n setLoadingResponses(false);\n }\n };\n\n // Fetch prompt responses for a specific company\n const fetchPromptResponsesForCompany = async (promptId, companyId) => {\n try {\n setLoadingResponses(true);\n // Add company_id as query parameter\n const response = await axios.get(`/api/prompt_analytics/prompt/${promptId}/responses`, {\n params: { company_id: companyId }\n });\n setPromptResponses(response.data.responses || []);\n } catch (err) {\n console.error('Error fetching prompt responses for company:', err);\n setPromptResponses([]);\n } finally {\n setLoadingResponses(false);\n }\n };\n\n // Handle viewing prompt responses (default view)\n const handleViewResponses = async (prompt) => {\n // Track \"View responses clicked\" event\n trackEvent('View responses clicked', {\n project_id: projectId,\n user_id: user?.id,\n prompt_id: prompt.prompt_id,\n prompt_text: prompt.prompt_text,\n topic_id: selectedTopicId,\n topic_name: topicData?.topic?.name,\n current_view: currentView,\n platform: selectedPlatform || 'all',\n source: 'competitor_analysis'\n });\n\n setSelectedPrompt(prompt);\n setSideDrawerOpen(true);\n await fetchPromptResponses(prompt.prompt_id);\n };\n\n // Handle clicking on a percentage cell to view responses for a specific company\n const handlePercentageClick = (prompt, companyId, companyName, isCustomer) => {\n // Track \"View Details clicked\" event\n trackEvent('View Details clicked', {\n project_id: projectId,\n user_id: user?.id,\n prompt_id: prompt.prompt_id,\n prompt_text: prompt.prompt_text,\n company_id: companyId,\n company_name: companyName,\n is_customer: isCustomer,\n topic_id: selectedTopicId,\n topic_name: topicData?.topic?.name,\n current_view: currentView,\n platform: selectedPlatform || 'all',\n source: 'competitor_analysis'\n });\n\n // Set prompt and company info and open side drawer\n setSelectedPrompt({\n ...prompt,\n selectedCompanyId: companyId,\n selectedCompanyName: companyName,\n isCustomer: isCustomer\n });\n setSideDrawerOpen(true);\n\n // Fetch responses with company_id parameter\n fetchPromptResponsesForCompany(prompt.prompt_id, companyId);\n };\n\n // Close side drawer\n const closeSideDrawer = () => {\n setSideDrawerOpen(false);\n setSelectedPrompt(null);\n setPromptResponses([]);\n };\n\n // Handle platform change\n const handlePlatformChange = (e) => {\n setSelectedPlatform(e.target.value);\n };\n\n // Handle view topic breakdown\n const handleViewTopicBreakdown = (topicId) => {\n setSelectedTopicId(topicId);\n setCurrentView('topic');\n };\n\n // Handle navigation\n const handleNavigateBack = () => {\n if (currentView === 'topic') {\n setCurrentView('breakdown');\n } else if (currentView === 'breakdown') {\n setCurrentView('overview');\n }\n };\n\n // Handle navigation to breakdown\n const handleViewBreakdown = () => {\n // Track \"View breakdown clicked\" event\n trackEvent('View breakdown clicked', {\n project_id: projectId,\n user_id: user?.id,\n platform: selectedPlatform || 'all',\n customer_share: overviewData?.pie_chart?.find(item => item.is_customer)?.percentage,\n competitor_count: overviewData?.pie_chart?.filter(item => !item.is_customer).length,\n total_prompts: overviewData?.pie_chart?.reduce((sum, item) => sum + (item.mentions || 0), 0),\n source: 'competitor_analysis'\n });\n\n setCurrentView('breakdown');\n };\n\n // Platform badge styling\n const getPlatformBadge = (platform) => {\n const colors = {\n chatgpt: 'bg-green-100 text-green-800',\n claude: 'bg-blue-100 text-blue-800',\n perplexity: 'bg-purple-100 text-purple-800',\n google_ai_overview: 'bg-orange-100 text-orange-800',\n 0: 'bg-green-100 text-green-800', // ChatGPT\n 1: 'bg-blue-100 text-blue-800', // Claude\n 2: 'bg-purple-100 text-purple-800', // Perplexity\n 3: 'bg-orange-100 text-orange-800' // Google AI Overview\n };\n return colors[platform] || 'bg-gray-100 text-gray-800';\n };\n\n // Get platform display name\n const getPlatformDisplayName = (platform) => {\n const names = {\n chatgpt: 'ChatGPT',\n claude: 'Claude',\n perplexity: 'Perplexity',\n google_ai_overview: 'Google AI Overview',\n 0: 'ChatGPT',\n 1: 'Claude',\n 2: 'Perplexity',\n 3: 'Google AI Overview'\n };\n return names[platform] || platform;\n };\n\n // Get color for prominence percentage\n const getProminenceScoreColor = (percentage) => {\n if (percentage >= 70) return 'text-green-600 font-semibold';\n if (percentage >= 40) return 'text-yellow-600 font-semibold';\n return 'text-red-600 font-semibold';\n };\n\n // Create specific data transformers to ensure correct percentage calculations\n const processTimeSeriesData = (timeSeriesPoints) => {\n if (!timeSeriesPoints || timeSeriesPoints.length === 0) {\n return [];\n }\n\n return timeSeriesPoints.map(dataPoint => {\n // Start with the date\n const result = {\n date: new Date(dataPoint.date).toLocaleDateString()\n };\n\n // Get customer and competitor mentions\n const customerMentions = dataPoint.customer.mentions || 0;\n const competitorMentions = {};\n let totalMentions = customerMentions;\n\n // Customer color is always first color\n result.customer_color = COMPANY_COLORS[0];\n\n // Calculate total mentions and store individual mentions\n dataPoint.competitors.forEach((comp, index) => {\n const mentions = comp.mentions || 0;\n competitorMentions[comp.id] = mentions;\n totalMentions += mentions;\n\n // Store the competitor's color for consistent usage\n result[`competitor_${comp.id}_color`] = getCompanyColor(comp.id, false, index);\n });\n\n // Calculate percentages based on total mentions\n if (totalMentions > 0) {\n // Customer percentage\n result.customer = parseFloat(((customerMentions / totalMentions) * 100).toFixed(1));\n result.customer_mentions = customerMentions;\n\n // Competitor percentages\n dataPoint.competitors.forEach((comp, index) => {\n const mentions = competitorMentions[comp.id];\n result[`competitor_${comp.id}`] = parseFloat(((mentions / totalMentions) * 100).toFixed(1));\n result[`competitor_${comp.id}_mentions`] = mentions;\n result[`competitor_${comp.id}_name`] = comp.name;\n });\n } else {\n // If all mentions are zero, distribute evenly\n const evenShare = parseFloat((100 / (dataPoint.competitors.length + 1)).toFixed(1));\n result.customer = evenShare;\n result.customer_mentions = 0;\n\n dataPoint.competitors.forEach(comp => {\n result[`competitor_${comp.id}`] = evenShare;\n result[`competitor_${comp.id}_mentions`] = 0;\n result[`competitor_${comp.id}_name`] = comp.name;\n });\n\n // Adjust to ensure exactly 100%\n let total = evenShare * (dataPoint.competitors.length + 1);\n if (Math.abs(total - 100) > 0.1) {\n result.customer += (100 - total);\n }\n }\n\n return result;\n });\n };\n\n // Render loading state\n if (loading && !overviewData && !breakdownData && !topicData) {\n return (\n
\n
Loading competitor analysis...
\n
\n );\n }\n\n // Render error state\n if (error) {\n return (\n
\n
\n \n

Error Loading Data

\n
\n

{error}

\n {\n setError(null);\n setLoading(true);\n if (currentView === 'overview') {\n // Retry fetching overview data\n axios.get(`/api/projects/${projectId}/competitor_analysis/overview`, {\n params: { platform: selectedPlatform }\n }).then(response => {\n setOverviewData(response.data);\n setLoading(false);\n }).catch(err => {\n console.error('Error retrying competitor analysis overview:', err);\n setError('Failed to load competitor analysis data. Please try again.');\n setLoading(false);\n });\n } else if (currentView === 'breakdown') {\n // Retry fetching breakdown data\n axios.get(`/api/projects/${projectId}/competitor_analysis/breakdown`, {\n params: { platform: selectedPlatform }\n }).then(response => {\n setBreakdownData(response.data);\n setLoading(false);\n }).catch(err => {\n console.error('Error retrying competitor analysis breakdown:', err);\n setError('Failed to load competitor analysis breakdown. Please try again.');\n setLoading(false);\n });\n } else if (currentView === 'topic' && selectedTopicId) {\n // Retry fetching topic data\n axios.get(`/api/projects/${projectId}/competitor_analysis/topic/${selectedTopicId}`, {\n params: { platform: selectedPlatform }\n }).then(response => {\n setTopicData(response.data);\n setLoading(false);\n }).catch(err => {\n console.error('Error retrying topic breakdown:', err);\n setError('Failed to load topic breakdown. Please try again.');\n setLoading(false);\n });\n }\n }}\n >\n Try Again\n \n
\n );\n };\n\n // Render the header with platform filter and navigation\n const renderHeader = () => (\n
\n
\n
\n {currentView !== 'overview' && (\n \n \n Back\n \n )}\n
\n

\n {currentView === 'overview' && 'Competitor Analysis'}\n {currentView === 'breakdown' && 'Topic Breakdown'}\n {currentView === 'topic' && topicData && `Prompts in ${topicData.topic.name}`}\n

\n

\n {currentView === 'overview' && 'Compare your share of voice against competitors'}\n {currentView === 'breakdown' && 'Topic-by-topic breakdown of share of voice'}\n {currentView === 'topic' && 'Prompt-by-prompt breakdown of share of voice'}\n

\n
\n
\n
\n
\n \n {platforms.map((platform, index) => (\n \n ))}\n \n
\n
\n
\n
\n );\n\n // Render prominent action card for breakdown - only shown in overview\n const renderBreakdownActionCard = () => {\n if (currentView !== 'overview' || !overviewData) return null;\n\n // Get some summary data for the card\n const customerData = overviewData.pie_chart?.find(item => item.is_customer);\n const competitorCount = overviewData.pie_chart?.filter(item => !item.is_customer).length || 0;\n const customerPercentage = customerData?.percentage || 0;\n\n return (\n
\n
\n {/* Decorative elements */}\n
\n
\n\n
\n
\n
\n \n \n Deep Dive Available\n \n
\n\n

Dive Deeper Into Your Performance

\n

\n Get topic-by-topic insights and see exactly where you're winning or losing against {competitorCount} competitors.\n Identify opportunities to improve your {customerPercentage.toFixed(1)}% share of voice.\n

\n\n
\n \n See performance by topic and individual prompts\n
\n
\n\n
\n \n \n View Breakdown\n \n\n

\n \u2728 Discover optimization opportunities\n

\n
\n
\n
\n
\n );\n };\n\n // Render overview view with time series chart and pie chart\n const renderOverview = () => {\n if (!overviewData) return null;\n\n // Process time series data with company colors\n const timeSeriesData = processTimeSeriesData(overviewData.time_series);\n\n // Transform data for pie chart\n const pieChartData = [];\n\n if (overviewData.pie_chart) {\n // Deep copy the pie chart data to avoid reference issues\n const pieChartCopy = JSON.parse(JSON.stringify(overviewData.pie_chart));\n\n // Sort by percentage descending to make pie chart more readable\n pieChartCopy.sort((a, b) => b.percentage - a.percentage);\n\n // Add color information\n pieChartCopy.forEach((item, index) => {\n pieChartData.push({\n ...item,\n color: getCompanyColor(item.id, item.is_customer, index)\n });\n });\n }\n\n // Get customer and competitor names for legend\n const customerName = pieChartData?.find(item => item.is_customer)?.name || 'Customer';\n const competitorNames = pieChartData?.filter(item => !item.is_customer).map(item => item.name) || [];\n\n return (\n
\n {/* Prominent Action Card */}\n {renderBreakdownActionCard()}\n\n {/* Time Series Chart */}\n
\n
\n \n

Share of Voice Trends Over Time

\n
\n\n {(timeSeriesData.length < 2) ? (\n
\n
\n \n

Not Enough Data Yet

\n

\n The share of voice graph will appear here once there's more than one week of data.\n Check back soon to see how your visibility changes over time.\n

\n
\n
\n ) : (\n
\n \n \n \n \n \n {\n let mentions = 0;\n\n // Use dataKey instead of name for the logic\n if (props.dataKey === 'customer') {\n mentions = props.payload.customer_mentions || 0;\n } else {\n mentions = props.payload[`${props.dataKey}_mentions`] || 0;\n }\n\n return [`${value}% (${mentions} prompts)`, name];\n }}\n contentStyle={{ backgroundColor: 'white', borderRadius: '5px', padding: '10px' }}\n />\n \n \n {overviewData.time_series[0]?.competitors.map((competitor, index) => (\n \n ))}\n \n \n
\n )}\n
\n\n {/* Pie Chart */}\n
\n
\n \n

Share of Voice Distribution

\n
\n\n {pieChartData && pieChartData.length > 0 ? (\n
\n
\n \n \n `${percentage}%`}\n isAnimationActive={false} // Disable animation to troubleshoot rendering\n >\n {pieChartData.map((entry) => (\n \n ))}\n \n {\n const entry = pieChartData.find(item => item.name === name);\n const mentions = entry ? entry.mentions : 0;\n return [`${value}% (${mentions} prompts)`, name];\n }}\n contentStyle={{ backgroundColor: 'white', borderRadius: '5px', padding: '10px' }}\n />\n \n \n
\n\n
\n

Share of Voice Distribution

\n
\n {pieChartData.map((entry) => (\n
\n
\n
\n {entry.name}\n
\n
\n \n {entry.percentage}% ({entry.mentions} prompts)\n \n
\n
\n ))}\n
\n\n
\n

\n This chart shows the share of voice between your company and competitors\n based on the most recent data. Higher percentages indicate better AI visibility.\n

\n
\n
\n
\n ) : (\n
\n

No data available for the selected platform.

\n
\n )}\n
\n \n );\n };\n\n // Render breakdown view with topics table\n const renderBreakdown = () => {\n if (!breakdownData) return null;\n\n const { topics } = breakdownData;\n\n if (topics.length === 0) {\n return (\n
\n \n

No Topic Data Available

\n

\n There are no topics with competitor data for the selected platform.\n

\n
\n );\n }\n\n // Get summary data from the overview pie chart\n let summaryData = null;\n\n if (overviewData && overviewData.pie_chart) {\n const customerData = overviewData.pie_chart.find(item => item.is_customer);\n const competitorData = overviewData.pie_chart.filter(item => !item.is_customer);\n\n summaryData = {\n customer: {\n ...customerData,\n color: COMPANY_COLORS[0]\n } || { name: 'Customer', percentage: 0, color: COMPANY_COLORS[0] },\n competitors: competitorData.map((comp, idx) => ({\n ...comp,\n color: getCompanyColor(comp.id, false, idx)\n })) || []\n };\n }\n\n // Use the new sortable table component\n return (\n \n );\n };\n\n // Render topic view with prompts table\n const renderTopic = () => {\n if (!topicData) return null;\n\n const { prompts, topic } = topicData;\n\n if (prompts.length === 0) {\n return (\n
\n \n

No Prompt Data Available

\n

\n There are no prompts with competitor data for the selected topic and platform.\n

\n
\n );\n }\n\n return (\n
\n
\n

Prompts in {topic.name}

\n

\n Share of voice percentages for each prompt in this topic (click on percentages to view details)\n

\n
\n\n
\n \n \n \n \n \n {prompts[0]?.scores?.competitors?.map(competitor => (\n \n ))}\n \n \n \n \n {prompts.map(prompt => (\n \n \n \n {prompt.scores.competitors.map((competitor, index) => (\n \n ))}\n \n \n ))}\n \n
\n Prompt\n \n {prompts[0]?.scores?.customer?.name || 'Customer'}\n \n {competitor.name}\n \n Actions\n
\n
{prompt.prompt_text}
\n
{prompt.response_count} responses
\n
\n handlePercentageClick(\n prompt,\n prompt.scores.customer.id,\n prompt.scores.customer.name,\n true\n )}\n className={`text-sm font-semibold ${getProminenceScoreColor(prompt.scores.customer.percentage)} hover:underline cursor-pointer`}\n style={{ backgroundColor: 'transparent', border: 'none', padding: 0 }}\n >\n {prompt.scores.customer.percentage}% ({prompt.scores.customer.mentions} prompts)\n \n \n handlePercentageClick(\n prompt,\n competitor.id,\n competitor.name,\n false\n )}\n className={`text-sm font-semibold ${getProminenceScoreColor(competitor.percentage)} hover:underline cursor-pointer`}\n style={{ backgroundColor: 'transparent', border: 'none', padding: 0 }}\n >\n {competitor.percentage}% ({competitor.mentions} prompts)\n \n \n handleViewResponses(prompt)}\n className=\"inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\"\n >\n \n View Responses\n \n
\n
\n
\n );\n };\n\n // Helper function to get color based on score/percentage\n const getScoreColor = (percentage) => {\n if (percentage >= 70) return 'text-green-600';\n if (percentage >= 40) return 'text-yellow-600';\n return 'text-red-600';\n };\n\n // Render the main content based on current view\n const renderContent = () => {\n switch (currentView) {\n case 'overview':\n return renderOverview();\n case 'breakdown':\n return renderBreakdown();\n case 'topic':\n return renderTopic();\n default:\n return renderOverview();\n }\n };\n\n // Main component render\n return (\n
\n {renderHeader()}\n\n {/* Conditional loading overlay for secondary fetches */}\n
\n {loading && (currentView !== 'overview' || overviewData) && (\n
\n
Loading...
\n
\n )}\n\n {renderContent()}\n
\n\n {/* Side Drawer for Prompt Responses */}\n \n {/* Prompt Text */}\n
\n

Prompt

\n
\n

{selectedPrompt?.prompt_text}

\n
\n
\n\n {/* Responses */}\n
\n

\n Responses ({promptResponses.length})\n {selectedPrompt?.selectedCompanyName && (\n \n Showing responses for {selectedPrompt.selectedCompanyName} - mentioned in {selectedPrompt.scores.competitors.find(c => c.id === selectedPrompt.selectedCompanyId)?.mentions || selectedPrompt.scores.customer.mentions} prompts\n \n )}\n

\n\n {loadingResponses ? (\n
\n
Loading responses...
\n
\n ) : promptResponses.length === 0 ? (\n
\n

No responses available for this prompt.

\n
\n ) : (\n
\n {promptResponses.map((response) => (\n \n ))}\n
\n )}\n
\n \n
\n );\n};\n\nexport default CompetitorAnalysis;", "// app/javascript/components/Dashboard/Projects/SortableTopicBreakdownTable.js\nimport React, { useState, useEffect } from 'react';\nimport { ArrowUp, ArrowDown } from 'lucide-react';\n\nconst SortableTopicBreakdownTable = ({\n topics,\n customer,\n competitors,\n handleViewTopicBreakdown,\n summaryData,\n setCurrentView,\n COMPANY_COLORS,\n getCompanyColor\n }) => {\n // Add sorting state\n const [sortConfig, setSortConfig] = useState({\n key: null,\n direction: 'none'\n });\n\n // Copy of topics data for sorting\n const [sortedTopics, setSortedTopics] = useState([...topics]);\n\n // Effect to handle sorting whenever sortConfig or topics change\n useEffect(() => {\n let sortableTopics = [...topics];\n\n if (sortConfig.key !== null) {\n sortableTopics.sort((a, b) => {\n // Parse the sorting key to determine what we're sorting by\n if (sortConfig.key === 'topic') {\n // Sort by topic name\n if (a.topic_name < b.topic_name) {\n return sortConfig.direction === 'ascending' ? -1 : 1;\n }\n if (a.topic_name > b.topic_name) {\n return sortConfig.direction === 'ascending' ? 1 : -1;\n }\n return 0;\n } else if (sortConfig.key === 'customer') {\n // Sort by customer percentage\n const valueA = a.percentages.customer.percentage;\n const valueB = b.percentages.customer.percentage;\n if (valueA < valueB) {\n return sortConfig.direction === 'ascending' ? -1 : 1;\n }\n if (valueA > valueB) {\n return sortConfig.direction === 'ascending' ? 1 : -1;\n }\n return 0;\n } else {\n // Sort by competitor percentage - key will be the competitor id\n const competitorId = parseInt(sortConfig.key);\n const competitorA = a.percentages.competitors.find(c => c.id === competitorId);\n const competitorB = b.percentages.competitors.find(c => c.id === competitorId);\n\n const valueA = competitorA ? competitorA.percentage : 0;\n const valueB = competitorB ? competitorB.percentage : 0;\n\n if (valueA < valueB) {\n return sortConfig.direction === 'ascending' ? -1 : 1;\n }\n if (valueA > valueB) {\n return sortConfig.direction === 'ascending' ? 1 : -1;\n }\n return 0;\n }\n });\n }\n\n setSortedTopics(sortableTopics);\n }, [sortConfig, topics]);\n\n // Handler for requesting a sort\n const requestSort = (key) => {\n let direction = 'ascending';\n\n // If we're already sorting by this key, toggle the direction\n if (sortConfig.key === key) {\n if (sortConfig.direction === 'ascending') {\n direction = 'descending';\n } else if (sortConfig.direction === 'descending') {\n direction = 'none';\n key = null;\n }\n }\n\n setSortConfig({ key, direction });\n };\n\n // Helper to get the current sort direction icon\n const getSortDirectionIcon = (key) => {\n if (sortConfig.key !== key) {\n return null;\n }\n\n if (sortConfig.direction === 'ascending') {\n return ;\n } else if (sortConfig.direction === 'descending') {\n return ;\n }\n return null;\n };\n\n return (\n
\n
\n

Topic Breakdown

\n

\n Percentage distribution of share of voice across topics - click column headers to sort\n

\n
\n\n
\n \n \n \n requestSort('topic')}\n >\n Topic {getSortDirectionIcon('topic')}\n \n requestSort('customer')}\n >\n {customer?.name || 'Customer'} {getSortDirectionIcon('customer')}\n \n {competitors?.map(competitor => (\n requestSort(competitor.id.toString())}\n >\n {competitor.name} {getSortDirectionIcon(competitor.id.toString())}\n \n ))}\n \n \n \n \n {sortedTopics.map(topic => (\n handleViewTopicBreakdown(topic.topic_id)}>\n \n \n {topic.percentages.competitors.map((competitor, index) => (\n \n ))}\n \n \n ))}\n\n {/* Summary Row with Overall Distribution */}\n {summaryData && (\n \n \n \n {summaryData.competitors.map((competitor) => (\n \n ))}\n \n \n )}\n \n
\n Actions\n
\n
{topic.topic_name}
\n
{topic.prompt_count} prompts \u2022 {topic.response_count} responses
\n
\n
\n
\n
\n \n {topic.percentages.customer.percentage}% ({topic.raw_scores.customer.mentions} prompts)\n \n
\n
\n
\n
\n
\n \n
\n
\n
\n
\n \n {competitor.percentage}% ({topic.raw_scores.competitors.find(c => c.id === competitor.id).mentions} prompts)\n \n
\n
\n
\n
\n
\n \n
\n {\n e.stopPropagation();\n handleViewTopicBreakdown(topic.topic_id);\n }}\n className=\"text-indigo-600 hover:text-indigo-900\"\n >\n View Details\n \n
\n
Overall Distribution
\n
Based on all topics combined
\n
\n
\n
\n
\n \n {summaryData.customer.percentage}% ({summaryData.customer.mentions} prompts)\n \n
\n
\n
\n
\n
\n \n
\n
\n
\n
\n \n {competitor.percentage}% ({competitor.mentions} prompts)\n \n
\n
\n
\n
\n
\n \n
\n setCurrentView('overview')}\n className=\"text-indigo-600 hover:text-indigo-900\"\n >\n View Chart\n \n
\n
\n
\n );\n};\n\nexport default SortableTopicBreakdownTable;", "import React, { useState, useEffect, useContext } from 'react';\nimport axios from '../../AxiosConfig';\nimport { Gauge, Calendar, BarChart2, ThumbsUp, ThumbsDown, Loader, AlertCircle, Eye, ArrowLeft } from 'lucide-react';\nimport { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';\nimport SideDrawer from './SideDrawer';\nimport ResponseCard from './ResponseCard';\nimport { AuthContext } from '../../../context/AuthContext';\nimport { trackEvent } from '../../Analytics/mixpanel';\n\nconst SentimentAnalysis = ({ projectId }) => {\n const { user } = useContext(AuthContext);\n\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n const [sentimentData, setSentimentData] = useState(null);\n const [selectedAuditResult, setSelectedAuditResult] = useState(null);\n const [selectedTheme, setSelectedTheme] = useState(null);\n const [themeResponses, setThemeResponses] = useState(null);\n const [loadingResponses, setLoadingResponses] = useState(false);\n const [showPromptsList, setShowPromptsList] = useState(false);\n const [selectedPrompt, setSelectedPrompt] = useState(null);\n const [sideDrawerOpen, setSideDrawerOpen] = useState(false);\n const [promptResponses, setPromptResponses] = useState([]);\n\n // Load sentiment analysis data when component mounts\n useEffect(() => {\n fetchSentimentAnalysis();\n }, [projectId]);\n\n // Fetch sentiment analysis data from the API\n const fetchSentimentAnalysis = async () => {\n try {\n setLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/sentiment_analysis`);\n setSentimentData(response.data);\n\n // Set latest audit result as selected\n if (response.data.available_audit_results && response.data.available_audit_results.length > 0) {\n const latestAuditResult = response.data.available_audit_results[response.data.available_audit_results.length - 1];\n setSelectedAuditResult(latestAuditResult.id);\n }\n\n setError(null);\n } catch (err) {\n console.error('Error fetching sentiment analysis:', err);\n setError(err.response?.data?.error || 'Failed to load sentiment analysis data');\n } finally {\n setLoading(false);\n }\n };\n\n // Handle audit result selection change\n const handleAuditResultChange = async (auditResultId) => {\n try {\n setLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/sentiment_analysis/audit_results/${auditResultId}`);\n\n setSentimentData(prevData => ({\n ...prevData,\n latest_analysis: response.data\n }));\n\n setSelectedAuditResult(auditResultId);\n setSelectedTheme(null);\n setThemeResponses(null);\n setShowPromptsList(false);\n setError(null);\n } catch (err) {\n console.error('Error fetching audit result data:', err);\n setError(err.response?.data?.error || 'Failed to load audit result data');\n } finally {\n setLoading(false);\n }\n };\n\n // Fetch responses for a specific theme\n const fetchThemeResponses = async (themeId) => {\n try {\n setLoadingResponses(true);\n const response = await axios.get(`/api/projects/${projectId}/sentiment_analysis/themes/${themeId}/responses`);\n setThemeResponses(response.data);\n setError(null);\n } catch (err) {\n console.error('Error fetching theme responses:', err);\n setError(err.response?.data?.error || 'Failed to load theme responses');\n setThemeResponses(null);\n } finally {\n setLoadingResponses(false);\n }\n };\n\n // Handle theme click with tracking\n const handleThemeClick = (themeId, themeType, themeDescription) => {\n let eventName;\n if (themeType === 'general_theme') {\n eventName = 'Key Themes clicked';\n } else if (themeType === 'strength') {\n eventName = 'Strength clicked';\n } else if (themeType === 'weakness') {\n eventName = 'Improvement area clicked';\n }\n\n if (eventName) {\n trackEvent(eventName, {\n project_id: projectId,\n user_id: user?.id,\n theme_id: themeId,\n theme_description: themeDescription,\n theme_type: themeType,\n audit_result_id: selectedAuditResult,\n overall_sentiment_score: sentimentData?.latest_analysis?.overall_sentiment_score,\n source: 'sentiment_analysis'\n });\n }\n\n setSelectedTheme(themeId);\n fetchThemeResponses(themeId);\n setShowPromptsList(true);\n };\n\n // Fetch prompt responses when a prompt is selected\n const fetchPromptResponses = async (prompt) => {\n if (!prompt || !prompt.responses) {\n setPromptResponses([]);\n setLoadingResponses(false);\n return;\n }\n\n try {\n setLoadingResponses(true);\n setPromptResponses(prompt.responses || []);\n } catch (err) {\n console.error('Error processing prompt responses:', err);\n setPromptResponses([]);\n } finally {\n setLoadingResponses(false);\n }\n };\n\n // Handle viewing prompt responses\n const handleViewPromptResponses = (prompt) => {\n setSelectedPrompt(prompt);\n setSideDrawerOpen(true);\n fetchPromptResponses(prompt);\n };\n\n // Close side drawer\n const closeSideDrawer = () => {\n setSideDrawerOpen(false);\n setSelectedPrompt(null);\n setPromptResponses([]);\n };\n\n // Get platform badge styling\n const getPlatformBadge = (platform) => {\n const colors = {\n chatgpt: 'bg-green-100 text-green-800',\n claude: 'bg-blue-100 text-blue-800',\n perplexity: 'bg-purple-100 text-purple-800',\n google_ai_overview: 'bg-orange-100 text-orange-800',\n 0: 'bg-green-100 text-green-800',\n 1: 'bg-blue-100 text-blue-800',\n 2: 'bg-purple-100 text-purple-800',\n 3: 'bg-orange-100 text-orange-800'\n };\n return colors[platform] || 'bg-gray-100 text-gray-800';\n };\n\n // Get platform display name\n const getPlatformDisplayName = (platform) => {\n const names = {\n chatgpt: 'ChatGPT',\n claude: 'Claude',\n perplexity: 'Perplexity',\n google_ai_overview: 'Google AI Overview',\n 0: 'ChatGPT',\n 1: 'Claude',\n 2: 'Perplexity',\n 3: 'Google AI Overview'\n };\n return names[platform] || platform;\n };\n\n // Get prominence score color\n const getProminenceScoreColor = (score) => {\n if (score >= 70) return 'text-green-600 font-semibold';\n if (score >= 40) return 'text-yellow-600 font-semibold';\n return 'text-red-600 font-semibold';\n };\n\n const formatDate = (dateString) => {\n const date = new Date(dateString);\n return date.toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n timeZone: 'UTC'\n });\n };\n\n // Sentiment trend chart using audit result data (same scale as measurement)\n const renderSentimentTrend = () => {\n if (!sentimentData || !sentimentData.trend_data || sentimentData.trend_data.length < 2) {\n return (\n
\n

Not enough data for trend visualization

\n
\n );\n }\n\n const chartData = sentimentData.trend_data.map(point => ({\n date: point.date,\n score: point.score\n }));\n\n return (\n
\n \n \n \n \n \n `Date: ${formatDate(value)}`}\n formatter={(value) => [`${value}%`, 'Sentiment Score']}\n contentStyle={{ backgroundColor: 'white', borderRadius: '5px', padding: '10px' }}\n />\n \n \n \n
\n );\n };\n\n // If loading, show loading state\n if (loading && !sentimentData) {\n return (\n
\n \n

Loading sentiment analysis data...

\n
\n );\n }\n\n // If error and no data, show error\n if (error && !sentimentData) {\n return (\n
\n
\n \n

Error Loading Sentiment Analysis

\n
\n

{error}

\n fetchSentimentAnalysis()}\n className=\"inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\"\n >\n Try Again\n \n
\n );\n }\n\n // No data yet\n if (!sentimentData || !sentimentData.available_audit_results || sentimentData.available_audit_results.length === 0) {\n return (\n
\n \n

Sentiment Analysis

\n

No sentiment analysis data available yet. Run an audit to generate sentiment data.

\n
\n );\n }\n\n // Main content with data\n return (\n
\n {/* Header */}\n
\n
\n

Sentiment Analysis

\n

\n Analyze sentiment across AI-generated responses\n

\n
\n
\n\n {/* Audit result selector */}\n {sentimentData.available_audit_results.length > 1 && (\n
\n
\n \n

Select Audit

\n
\n handleAuditResultChange(e.target.value)}\n >\n {sentimentData.available_audit_results.map((ar) => (\n \n ))}\n \n
\n )}\n\n {/* Chart */}\n
\n
\n \n

Sentiment Over Time

\n
\n {renderSentimentTrend()}\n
\n\n {/* Summary */}\n {sentimentData.latest_analysis && (\n
\n
\n
\n

Executive Summary

\n

{sentimentData.latest_analysis.summary}

\n
\n
\n
\n {sentimentData.latest_analysis.overall_sentiment_score}%\n
\n
Overall Score
\n
\n
\n\n
\n Analysis from {new Date(sentimentData.latest_analysis.created_at).toLocaleString()}\n
\n
\n )}\n\n {/* Theme sections or Prompt list */}\n {sentimentData.latest_analysis && !showPromptsList && (\n
\n {/* General Themes */}\n
\n

\n \uD83D\uDD0D Key Themes\n

\n
    \n {sentimentData.latest_analysis.general_themes\n .filter(theme => theme.response_count > 0)\n .map(theme => (\n
  • \n handleThemeClick(theme.id, 'general_theme', theme.description)}\n className={`w-full text-left p-3 rounded-lg transition-colors ${\n selectedTheme === theme.id\n ? 'bg-indigo-100 text-indigo-700 border border-indigo-200'\n : 'hover:bg-gray-50 text-gray-800 border border-gray-200'\n }`}\n >\n
    \n
    {theme.description}
    \n \n {theme.response_count} {theme.response_count === 1 ? 'mention' : 'mentions'}\n \n
    \n \n
  • \n ))}\n
\n
\n\n {/* Strengths */}\n
\n

\n Strengths\n

\n
    \n {sentimentData.latest_analysis.strengths\n .filter(strength => strength.response_count > 0)\n .map(strength => (\n
  • \n handleThemeClick(strength.id, 'strength', strength.description)}\n className={`w-full text-left p-3 rounded-lg transition-colors ${\n selectedTheme === strength.id\n ? 'bg-green-100 text-green-700 border border-green-200'\n : 'hover:bg-gray-50 text-gray-800 border border-gray-200'\n }`}\n >\n
    \n
    {strength.description}
    \n \n {strength.response_count} {strength.response_count === 1 ? 'mention' : 'mentions'}\n \n
    \n \n
  • \n ))}\n
\n
\n\n {/* Weaknesses */}\n
\n

\n Improvement Areas\n

\n
    \n {sentimentData.latest_analysis.weaknesses\n .filter(weakness => weakness.response_count > 0)\n .map(weakness => (\n
  • \n handleThemeClick(weakness.id, 'weakness', weakness.description)}\n className={`w-full text-left p-3 rounded-lg transition-colors ${\n selectedTheme === weakness.id\n ? 'bg-red-100 text-red-700 border border-red-200'\n : 'hover:bg-gray-50 text-gray-800 border border-gray-200'\n }`}\n >\n
    \n
    {weakness.description}
    \n \n {weakness.response_count} {weakness.response_count === 1 ? 'mention' : 'mentions'}\n \n
    \n \n
  • \n ))}\n
\n
\n
\n )}\n\n {/* Prompts list when a theme is selected */}\n {selectedTheme && showPromptsList && themeResponses && (\n
\n
\n
\n {\n setShowPromptsList(false);\n setSelectedTheme(null);\n }}\n className=\"inline-flex items-center mr-4 text-gray-600 hover:text-gray-800\"\n >\n \n Back to Themes\n \n\n

\n Prompts for {themeResponses.theme.description}\n

\n
\n\n

\n Type: {themeResponses.theme.theme_type_name.toString().charAt(0).toUpperCase() + themeResponses.theme.theme_type_name.toString().slice(1)}\n

\n
\n\n
\n {(() => {\n const promptMap = {};\n\n themeResponses.responses.forEach(response => {\n const promptText = response.prompt_text;\n if (!promptMap[promptText]) {\n promptMap[promptText] = {\n prompt_text: promptText,\n responses: [],\n };\n }\n promptMap[promptText].responses.push(response);\n });\n\n const prompts = Object.values(promptMap);\n\n return (\n
\n \n \n \n \n \n \n \n \n \n {prompts.length === 0 ? (\n \n \n \n ) : (\n prompts.map((prompt, index) => (\n \n \n \n \n \n ))\n )}\n \n
\n Prompt\n \n Responses\n \n Actions\n
\n No prompts available for this theme.\n
\n
\n {prompt.prompt_text}\n
\n
\n \n {prompt.responses.length} {prompt.responses.length === 1 ? 'response' : 'responses'}\n \n \n handleViewPromptResponses(prompt)}\n className=\"inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\"\n >\n \n View Responses\n \n
\n
\n );\n })()}\n
\n
\n )}\n\n {/* Side Drawer for Prompt Responses */}\n \n {/* Prompt Text */}\n
\n

Prompt

\n
\n

{selectedPrompt?.prompt_text}

\n
\n
\n\n {/* Responses */}\n
\n

\n Responses ({promptResponses.length})\n

\n\n {loadingResponses ? (\n
\n
Loading responses...
\n
\n ) : promptResponses.length === 0 ? (\n
\n

No responses available for this prompt.

\n
\n ) : (\n
\n {promptResponses.map((response) => (\n \n ))}\n
\n )}\n
\n \n
\n );\n};\n\nexport default SentimentAnalysis;", "import React, { useState, useEffect, useCallback, useRef, useContext } from 'react';\nimport axios from '../../../AxiosConfig';\nimport { FileText, RefreshCw, ChevronRight, AlertCircle, Loader, Trash2 } from 'lucide-react';\n\n// Import tab components\nimport OverviewTab from './tabs/OverviewTab';\nimport EntityTab from './tabs/EntityTab';\nimport ClaimTab from './tabs/ClaimTab';\nimport StructureTab from './tabs/StructureTab';\nimport TechnicalTab from './tabs/TechnicalTab';\nimport AnalysisList from './AnalysisList';\nimport AnalysisOverview from './AnalysisOverview';\nimport { AuthContext } from '../../../../context/AuthContext'; // Import AuthContext for user data\nimport { trackEvent } from '../../../Analytics/mixpanel'; // Import trackEvent\n\nconst ContentAnalysis = ({ projectId }) => {\n const { user } = useContext(AuthContext); // Get user data for tracking\n\n // Core state\n const [analyses, setAnalyses] = useState([]);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState(null);\n const [customUrl, setCustomUrl] = useState('');\n const [deleteConfirmation, setDeleteConfirmation] = useState(null);\n\n // UI state\n const [selectedAnalysisId, setSelectedAnalysisId] = useState(null);\n const [selectedPageId, setSelectedPageId] = useState(null);\n const [activeTab, setActiveTab] = useState('overview');\n\n // Polling refs\n const pollingTimerRef = useRef(null);\n const isPollingRef = useRef(false);\n const isFetchingRef = useRef(false);\n const lastFetchTimeRef = useRef(null);\n\n // Memoized derived data\n const selectedAnalysis = selectedAnalysisId\n ? analyses.find(a => a.id === selectedAnalysisId) || null\n : null;\n\n const selectedPage = selectedAnalysisId && selectedPageId\n ? selectedAnalysis?.page_analyses?.find(p => p.id === selectedPageId) || null\n : null;\n\n // Determine if any analyses are in progress\n const hasInProgressAnalyses = analyses.some(analysis =>\n analysis.status === 'queued' ||\n analysis.status === 'in_progress' ||\n (analysis.page_analyses &&\n analysis.page_analyses.some(p => p.status === 'queued' || p.status === 'in_progress'))\n );\n\n // POLLING FUNCTIONS - Define these first\n const stopPolling = useCallback(() => {\n if (!isPollingRef.current) {\n return;\n }\n\n console.log(\"Stopping polling\");\n if (pollingTimerRef.current) {\n clearInterval(pollingTimerRef.current);\n pollingTimerRef.current = null;\n }\n\n isPollingRef.current = false;\n }, []);\n\n // FETCH ANALYSES - Core data loading function\n const fetchAnalyses = useCallback(async (force = false) => {\n // Prevent concurrent fetches\n if (isFetchingRef.current) {\n console.log(\"Fetch skipped: Another fetch already in progress\");\n return;\n }\n\n // Rate limiting (unless forced)\n if (!force && lastFetchTimeRef.current) {\n const timeSinceLastFetch = Date.now() - lastFetchTimeRef.current;\n if (timeSinceLastFetch < 2000) {\n console.log(`Fetch skipped: Too recent (${timeSinceLastFetch}ms since last fetch)`);\n return;\n }\n }\n\n // Begin fetch\n console.log(\"Fetching analyses...\");\n isFetchingRef.current = true;\n lastFetchTimeRef.current = Date.now();\n\n try {\n const response = await axios.get(`/api/projects/${projectId}/content_analyses`);\n const data = Array.isArray(response.data) ? response.data : [];\n\n console.log(`Fetched ${data.length} analyses:`,\n data.map(a => `ID: ${a.id}, Status: ${a.status}, Pages: ${a.page_analyses?.length || 0}`));\n\n // Update state with new data\n setAnalyses(data);\n setError(null);\n\n } catch (err) {\n console.error(\"Error fetching analyses:\", err);\n setError(\"Failed to load content analyses. Please try again.\");\n } finally {\n isFetchingRef.current = false;\n }\n }, [projectId]);\n\n const startPolling = useCallback(() => {\n if (isPollingRef.current) {\n console.log(\"Polling already active\");\n return;\n }\n\n console.log(\"Starting polling\");\n isPollingRef.current = true;\n\n // Clear any existing timer\n if (pollingTimerRef.current) {\n clearInterval(pollingTimerRef.current);\n }\n\n // Set up new polling timer\n pollingTimerRef.current = setInterval(() => {\n console.log(\"Polling interval triggered\");\n fetchAnalyses();\n }, 5000);\n }, [fetchAnalyses]);\n\n // API OPERATIONS\n const startNewAnalysis = async () => {\n try {\n setLoading(true);\n setError(null);\n\n // Track \"Run New Analysis clicked\" event\n trackEvent('Run New Analysis clicked', {\n project_id: projectId,\n user_id: user?.id,\n existing_analyses_count: analyses.length,\n in_progress_analyses: analyses.filter(a => a.status === 'in_progress' || a.status === 'queued').length,\n source: 'content_analysis'\n });\n\n console.log(\"Starting new content analysis\");\n const response = await axios.post(`/api/projects/${projectId}/content_analyses`);\n\n if (!response?.data) {\n throw new Error(\"Received empty response from server\");\n }\n\n // Get fresh data after creating a new analysis\n await fetchAnalyses(true);\n\n // Select the newly created analysis\n setSelectedAnalysisId(response.data.id);\n setSelectedPageId(null);\n\n // Start polling for updates\n startPolling();\n\n } catch (err) {\n console.error(\"Error starting content analysis:\", err);\n setError(`Failed to start content analysis: ${err.message || \"Unknown error\"}`);\n } finally {\n setLoading(false);\n }\n };\n\n const analyzeSpecificUrl = async () => {\n if (!customUrl) {\n setError(\"Please enter a valid URL\");\n return;\n }\n\n try {\n setLoading(true);\n setError(null);\n\n // Track \"Analyze page submitted\" event\n trackEvent('Analyze page submitted', {\n project_id: projectId,\n user_id: user?.id,\n url: customUrl,\n url_domain: new URL(customUrl).hostname,\n existing_analyses_count: analyses.length,\n source: 'content_analysis'\n });\n\n console.log(`Analyzing specific URL: ${customUrl}`);\n const response = await axios.post(`/api/projects/${projectId}/content_analyses/analyze_url`, {\n url: customUrl\n });\n\n if (!response?.data) {\n throw new Error(\"Received empty response from server\");\n }\n\n // Refresh data\n await fetchAnalyses(true);\n\n // If this is a single page analysis, select it\n if (response.data.content_analysis_id) {\n setSelectedAnalysisId(response.data.content_analysis_id);\n setSelectedPageId(response.data.id);\n } else {\n setSelectedPageId(response.data.id);\n }\n\n // Clear input and start polling\n setCustomUrl(\"\");\n startPolling();\n\n } catch (err) {\n console.error(\"Error analyzing URL:\", err);\n setError(`Failed to analyze URL: ${err.message || \"Unknown error\"}`);\n } finally {\n setLoading(false);\n }\n };\n\n const deleteAnalysis = async (analysisId) => {\n try {\n setLoading(true);\n setError(null);\n\n console.log(`Deleting analysis: ${analysisId}`);\n await axios.delete(`/api/projects/${projectId}/content_analyses/${analysisId}`);\n\n // Clear deletion confirmation\n setDeleteConfirmation(null);\n\n // If we deleted the currently selected analysis, reset the selection\n if (selectedAnalysisId === analysisId) {\n setSelectedAnalysisId(null);\n setSelectedPageId(null);\n }\n\n // Refresh data\n await fetchAnalyses(true);\n\n } catch (err) {\n console.error(\"Error deleting analysis:\", err);\n setError(`Failed to delete analysis: ${err.message || \"Unknown error\"}`);\n } finally {\n setLoading(false);\n }\n };\n\n // UI EVENT HANDLERS\n const handleForceRefresh = () => {\n console.log(\"Manual refresh requested\");\n fetchAnalyses(true);\n };\n\n const handleBack = () => {\n if (selectedPageId) {\n setSelectedPageId(null);\n } else if (selectedAnalysisId) {\n setSelectedAnalysisId(null);\n }\n };\n\n const viewAnalysisReport = (analysisId) => {\n // Track \"View Analysis clicked\" event\n const analysis = analyses.find(a => a.id === analysisId);\n trackEvent('View Analysis clicked', {\n project_id: projectId,\n user_id: user?.id,\n analysis_id: analysisId,\n analysis_status: analysis?.status,\n pages_count: analysis?.page_analyses?.length || 0,\n completed_pages: analysis?.page_analyses?.filter(p => p.status === 'completed').length || 0,\n source: 'content_analysis'\n });\n\n console.log(`Viewing analysis: ${analysisId}`);\n setSelectedAnalysisId(analysisId);\n setSelectedPageId(null);\n };\n\n const viewPageAnalysis = (pageId) => {\n console.log(`Viewing page: ${pageId}`);\n setSelectedPageId(pageId);\n };\n\n const confirmDelete = (analysisId) => {\n setDeleteConfirmation(analysisId);\n };\n\n const cancelDelete = () => {\n setDeleteConfirmation(null);\n };\n\n // Enhanced tab change handler with tracking\n const handleTabChange = (tabName) => {\n // Track tab click events\n const eventMap = {\n 'entity': 'Entity & Relationship tab clicked',\n 'claim': 'Claim and Clarity tab clicked',\n 'structure': 'Content Structure tab clicked',\n 'technical': 'Technical tab clicked'\n };\n\n const eventName = eventMap[tabName];\n if (eventName) {\n trackEvent(eventName, {\n project_id: projectId,\n user_id: user?.id,\n analysis_id: selectedAnalysisId,\n page_id: selectedPageId,\n page_url: selectedPage?.url,\n previous_tab: activeTab,\n new_tab: tabName,\n source: 'content_analysis'\n });\n }\n\n setActiveTab(tabName);\n };\n\n // Enhanced function to handle \"Visit Page\" clicks\n const handleVisitPage = (url) => {\n // Track \"Visit Page clicked\" event\n trackEvent('Visit Page clicked', {\n project_id: projectId,\n user_id: user?.id,\n analysis_id: selectedAnalysisId,\n page_id: selectedPageId,\n page_url: url,\n current_tab: activeTab,\n source: 'content_analysis'\n });\n\n // Open the page in a new tab\n window.open(url, '_blank', 'noopener,noreferrer');\n };\n\n // RENDER HELPERS\n const renderStatusBadge = (status) => {\n switch (status) {\n case 'completed':\n return Completed;\n case 'in_progress':\n return \n In Progress\n ;\n case 'failed':\n return Failed;\n case 'queued':\n return Queued;\n default:\n return {status || 'Unknown'};\n }\n };\n\n const renderPageAnalysisDetail = () => {\n if (!selectedPage) return null;\n\n if (selectedPage.status !== 'completed') {\n return (\n
\n \n

Analyzing page

\n

This may take a minute or two...

\n
\n );\n }\n\n // Safely access analysis_results or provide defaults\n const analysis_results = selectedPage.analysis_results || {};\n\n return (\n
\n {/* Page header */}\n
\n
\n
\n

{selectedPage.url}

\n

Analyzed on {new Date(selectedPage.updated_at).toLocaleString()}

\n
\n
\n \n \n \n handleVisitPage(selectedPage.url)}\n className=\"inline-flex items-center px-3 py-1.5 text-sm font-medium text-indigo-700 bg-indigo-50 rounded-md hover:bg-indigo-100\"\n >\n Visit Page \n \n
\n
\n
\n\n {/* Analysis tabs */}\n
\n
\n \n
\n\n {/* Tab content */}\n
\n {activeTab === 'overview' && }\n {activeTab === 'entity' && }\n {activeTab === 'claim' && }\n {activeTab === 'structure' && }\n {activeTab === 'technical' && }\n
\n
\n
\n );\n };\n\n // EFFECTS\n // Initial data load\n useEffect(() => {\n console.log(\"Component mounted, loading initial data\");\n fetchAnalyses(true);\n\n // Cleanup on unmount\n return () => {\n console.log(\"Component unmounting\");\n stopPolling();\n };\n }, [fetchAnalyses, stopPolling]);\n\n // Manage polling based on analysis status\n useEffect(() => {\n if (hasInProgressAnalyses) {\n console.log(\"In-progress analyses detected, ensuring polling is active\");\n startPolling();\n } else {\n console.log(\"No in-progress analyses, stopping polling\");\n stopPolling();\n }\n }, [hasInProgressAnalyses, startPolling, stopPolling]);\n\n // Enhanced AnalysisList component wrapper with tracking\n const AnalysisListWithTracking = (props) => {\n const enhancedProps = {\n ...props,\n onStartNewAnalysis: startNewAnalysis, // Already has tracking\n onAnalyzeUrl: analyzeSpecificUrl, // Already has tracking\n onViewReport: (analysisId) => {\n // Track \"Analyze domain clicked\" event (assuming this refers to viewing analysis reports)\n const analysis = analyses.find(a => a.id === analysisId);\n trackEvent('Analyze domain clicked', {\n project_id: projectId,\n user_id: user?.id,\n analysis_id: analysisId,\n analysis_status: analysis?.status,\n pages_count: analysis?.page_analyses?.length || 0,\n domain: analysis?.page_analyses?.[0] ? new URL(analysis.page_analyses[0].url).hostname : 'unknown',\n source: 'content_analysis'\n });\n\n viewAnalysisReport(analysisId);\n }\n };\n\n return ;\n };\n\n // MAIN RENDER\n return (\n
\n {/* Back button */}\n {(selectedAnalysisId || selectedPageId) && (\n \n \n Back\n \n )}\n\n {/* Main content */}\n {selectedPageId ? (\n renderPageAnalysisDetail()\n ) : selectedAnalysisId ? (\n \n ) : (\n \n )}\n
\n );\n};\n\nexport default ContentAnalysis;", "import React from 'react';\nimport { Check, ArrowRight } from 'lucide-react';\n\nconst OverviewTab = ({ analysis }) => {\n return (\n
\n
\n

AI Parsing Structure Score

\n
\n
\n
\n
\n {analysis.ai_parsing_score || 0}/100\n
\n

{analysis.ai_parsing_summary || 'No analysis summary available.'}

\n
\n\n
\n
\n

Key Strengths

\n
    \n {(analysis.strengths || ['No strengths information available']).map((strength, index) => (\n
  • \n \n {strength}\n
  • \n ))}\n
\n
\n
\n

Top Recommendations

\n
    \n {((analysis.recommendations || ['No recommendations available']).slice(0, 5)).map((rec, index) => (\n
  • \n \n {rec}\n
  • \n ))}\n
\n
\n
\n \n );\n};\n\nexport default OverviewTab;", "import React from 'react';\nimport { Check, AlertCircle } from 'lucide-react';\n\nconst EntityTab = ({ analysis }) => {\n return (\n
\n

Entity & Relationship Analysis

\n\n
\n

Detected Entities

\n
\n {Object.entries(analysis.entities || {'general': ['No entities detected']}).map(([type, entities]) => (\n
\n
{type}
\n
\n {entities.map((entity, index) => (\n \n {entity}\n \n ))}\n
\n
\n ))}\n
\n
\n\n
\n

Entity Relationships

\n
\n

{analysis.entity_relationship_summary || 'No relationship summary available.'}

\n\n
Clear Relationships
\n
    \n {(analysis.clear_relationships || ['No clear relationships detected']).map((rel, index) => (\n
  • \n \n {rel}\n
  • \n ))}\n
\n\n
Missing Connections
\n
    \n {(analysis.missing_connections || ['No missing connections identified']).map((conn, index) => (\n
  • \n \n {conn}\n
  • \n ))}\n
\n
\n
\n
\n );\n};\n\nexport default EntityTab;", "import React from 'react';\nimport { ArrowRight } from 'lucide-react';\n\nconst ClaimTab = ({ analysis }) => {\n return (\n
\n

Claim Clarity Assessment

\n\n
\n

Key Claims Analysis

\n

{analysis.claim_analysis_summary || 'No claim analysis summary available.'}

\n\n
\n {(analysis.key_claims || [{ claim_text: 'No claims extracted', evidence_strength: 'Weak', specificity_score: 1 }]).map((claim, index) => (\n
\n
\n
Claim {index + 1}
\n
\n \n {claim.evidence_strength} Evidence\n \n 7 ? 'bg-green-100 text-green-800' :\n (claim.specificity_score || 0) > 4 ? 'bg-yellow-100 text-yellow-800' :\n 'bg-red-100 text-red-800'\n }`}>\n Specificity: {claim.specificity_score || 0}/10\n \n
\n
\n

{claim.claim_text}

\n
\n ))}\n
\n
\n\n
\n

Claim Improvement Suggestions

\n
    \n {(analysis.claim_improvement_suggestions || ['No claim improvement suggestions available']).map((suggestion, index) => (\n
  • \n \n {suggestion}\n
  • \n ))}\n
\n
\n
\n );\n};\n\nexport default ClaimTab;", "import React from 'react';\nimport { Check, ArrowRight, Type, FileCode, Layers, Layout, Menu } from 'lucide-react';\n\nconst StructureTab = ({ analysis }) => {\n // Helper functions for structure analysis data\n const getScoreColorClass = (score) => {\n if (score >= 80) return 'bg-green-500';\n if (score >= 60) return 'bg-green-300';\n if (score >= 40) return 'bg-yellow-400';\n return 'bg-red-400';\n };\n\n const getScoreTextColor = (score) => {\n if (score >= 80) return 'text-green-600';\n if (score >= 60) return 'text-green-700';\n if (score >= 40) return 'text-yellow-700';\n return 'text-red-600';\n };\n\n // Get technical analysis data if available\n const technical = analysis?.technical_analysis || {};\n const structureAnalysis = technical?.content_structure_analysis;\n\n return (\n
\n

Structured vs. Unstructured Content

\n\n
\n

Structure Ratio

\n
\n
\n
\n
\n
\n
\n
\n
\n
\n {analysis.structured_content_percentage || 0}% Structured\n {100 - (analysis.structured_content_percentage || 0)}% Unstructured\n
\n

{analysis.structure_analysis_summary || 'No structure analysis summary available.'}

\n \n\n
\n
\n

Structured Elements

\n
    \n {(analysis.structured_elements || ['No structured elements detected']).map((element, index) => (\n
  • \n \n {element}\n
  • \n ))}\n
\n
\n
\n

Missing Structure Opportunities

\n
    \n {(analysis.structure_opportunities || ['No structure opportunities identified']).map((opportunity, index) => (\n
  • \n \n {opportunity}\n
  • \n ))}\n
\n
\n
\n\n
\n

Structure Recommendations

\n
    \n {(analysis.structure_recommendations || ['No structure recommendations available']).map((rec, index) => (\n
  • \n \n {rec}\n
  • \n ))}\n
\n
\n\n {/*/!* Enhanced Content Structure Analysis Section *!/*/}\n {/*{structureAnalysis && (*/}\n {/*
*/}\n {/*

Content Structure Analysis

*/}\n\n {/* /!* Overall Structure Score *!/*/}\n {/*
*/}\n {/*

Overall Structure Score

*/}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/* */}\n {/* {structureAnalysis.overall_structure_score}/100*/}\n {/* */}\n {/*
*/}\n {/*

{structureAnalysis.structure_summary}

*/}\n {/*
*/}\n\n {/* /!* Structure Components Grid *!/*/}\n {/*
*/}\n {/* /!* Heading Structure *!/*/}\n {/*
*/}\n {/*
*/}\n {/* */}\n {/*
Heading Structure
*/}\n {/*
*/}\n {/*
*/}\n {/* Score*/}\n {/* */}\n {/* {structureAnalysis.heading_analysis.score}/100*/}\n {/* */}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/*

{structureAnalysis.heading_analysis.strength}

*/}\n\n {/* {structureAnalysis.heading_analysis.heading_counts && (*/}\n {/*
*/}\n {/* Heading Distribution:*/}\n {/*
*/}\n {/* {Object.entries(structureAnalysis.heading_analysis.heading_counts || {}).map(([key, count]) => (*/}\n {/*
*/}\n {/*
{key.toUpperCase()}
*/}\n {/*
{count}
*/}\n {/*
*/}\n {/* ))}*/}\n {/*
*/}\n {/*
*/}\n {/* )}*/}\n {/*
*/}\n\n {/* /!* Schema Markup *!/*/}\n {/*
*/}\n {/*
*/}\n {/* */}\n {/*
Schema Markup
*/}\n {/*
*/}\n {/*
*/}\n {/* Score*/}\n {/* */}\n {/* {structureAnalysis.schema_analysis.score}/100*/}\n {/* */}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/*

{structureAnalysis.schema_analysis.strength}

*/}\n\n {/* {structureAnalysis.schema_analysis.schema_types && structureAnalysis.schema_analysis.schema_types.length > 0 && (*/}\n {/*
*/}\n {/* Detected Schema Types:*/}\n {/*
*/}\n {/* {structureAnalysis.schema_analysis.schema_types.map((type, index) => (*/}\n {/* */}\n {/* {type}*/}\n {/* */}\n {/* ))}*/}\n {/*
*/}\n {/*
*/}\n {/* )}*/}\n {/* */}\n\n {/* /!* Paragraph Structure *!/*/}\n {/*
*/}\n {/*
*/}\n {/* */}\n {/*
Paragraph Structure
*/}\n {/*
*/}\n {/*
*/}\n {/* Score*/}\n {/* */}\n {/* {structureAnalysis.paragraph_analysis.score}/100*/}\n {/* */}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/*

{structureAnalysis.paragraph_analysis.strength}

*/}\n\n {/* {structureAnalysis.paragraph_analysis.paragraph_count && (*/}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/* Paragraphs:*/}\n {/* {structureAnalysis.paragraph_analysis.paragraph_count}*/}\n {/*
*/}\n {/*
*/}\n {/* Avg Length:*/}\n {/* {structureAnalysis.paragraph_analysis.avg_length} chars*/}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/* )}*/}\n {/* */}\n\n {/* /!* Logical Flow *!/*/}\n {/*
*/}\n {/*
*/}\n {/* */}\n {/*
Logical Flow
*/}\n {/*
*/}\n {/*
*/}\n {/* Score*/}\n {/* */}\n {/* {structureAnalysis.logical_flow_analysis.score}/100*/}\n {/* */}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/*

{structureAnalysis.logical_flow_analysis.strength}

*/}\n\n {/* {structureAnalysis.logical_flow_analysis.transition_count !== undefined && (*/}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/* Transitions:*/}\n {/* {structureAnalysis.logical_flow_analysis.transition_count}*/}\n {/*
*/}\n {/*
*/}\n {/* Density:*/}\n {/* {structureAnalysis.logical_flow_analysis.transition_density}*/}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/* )}*/}\n {/* */}\n\n {/* /!* Navigation Elements *!/*/}\n {/*
*/}\n {/*
*/}\n {/* */}\n {/*
Navigation Structure
*/}\n {/*
*/}\n {/*
*/}\n {/* Score*/}\n {/* */}\n {/* {structureAnalysis.navigation_analysis.score}/100*/}\n {/* */}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/*

{structureAnalysis.navigation_analysis.strength}

*/}\n\n {/* {structureAnalysis.navigation_analysis.internal_link_count !== undefined && (*/}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/* Internal Links:*/}\n {/* {structureAnalysis.navigation_analysis.internal_link_count}*/}\n {/*
*/}\n {/*
*/}\n {/* Has TOC:*/}\n {/* {structureAnalysis.navigation_analysis.has_table_of_contents ? 'Yes' : 'No'}*/}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/* )}*/}\n {/* */}\n\n {/* /!* Visual Structure *!/*/}\n {/*
*/}\n {/*
*/}\n {/* */}\n {/*
Visual Structure
*/}\n {/*
*/}\n {/*
*/}\n {/* Score*/}\n {/* */}\n {/* {structureAnalysis.visual_structure_analysis.score}/100*/}\n {/* */}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/*

{structureAnalysis.visual_structure_analysis.strength}

*/}\n\n {/* {structureAnalysis.visual_structure_analysis.list_count !== undefined && (*/}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/* Lists:*/}\n {/* {structureAnalysis.visual_structure_analysis.list_count}*/}\n {/*
*/}\n {/*
*/}\n {/* Tables:*/}\n {/* {structureAnalysis.visual_structure_analysis.table_count}*/}\n {/*
*/}\n {/*
*/}\n {/*
*/}\n {/* )}*/}\n {/* */}\n {/* */}\n\n {/* /!* Recommendations Section *!/*/}\n {/*
*/}\n {/*

Structure Improvement Recommendations

*/}\n {/*
    */}\n {/* {structureAnalysis.recommendations.map((recommendation, index) => (*/}\n {/*
  • */}\n {/* */}\n {/* {recommendation}*/}\n {/*
  • */}\n {/* ))}*/}\n {/*
*/}\n {/*
*/}\n\n {/* /!* Component-specific recommendations *!/*/}\n {/*
*/}\n {/* /!* Heading Recommendations *!/*/}\n {/* {structureAnalysis.heading_analysis.suggestions && structureAnalysis.heading_analysis.suggestions.length > 0 && (*/}\n {/*
*/}\n {/*
*/}\n {/* */}\n {/*
Heading Improvements
*/}\n {/*
*/}\n {/*
    */}\n {/* {structureAnalysis.heading_analysis.suggestions.map((suggestion, index) => (*/}\n {/*
  • */}\n {/* */}\n {/* {suggestion}*/}\n {/*
  • */}\n {/* ))}*/}\n {/*
*/}\n {/*
*/}\n {/* )}*/}\n\n {/* /!* Schema Recommendations *!/*/}\n {/* {structureAnalysis.schema_analysis.suggestions && structureAnalysis.schema_analysis.suggestions.length > 0 && (*/}\n {/*
*/}\n {/*
*/}\n {/* */}\n {/*
Schema Improvements
*/}\n {/*
*/}\n {/*
    */}\n {/* {structureAnalysis.schema_analysis.suggestions.map((suggestion, index) => (*/}\n {/*
  • */}\n {/* */}\n {/* {suggestion}*/}\n {/*
  • */}\n {/* ))}*/}\n {/*
*/}\n {/*
*/}\n {/* )}*/}\n\n {/* /!* Paragraph Recommendations *!/*/}\n {/* {structureAnalysis.paragraph_analysis.suggestions && structureAnalysis.paragraph_analysis.suggestions.length > 0 && (*/}\n {/*
*/}\n {/*
*/}\n {/* */}\n {/*
Paragraph Improvements
*/}\n {/*
*/}\n {/*
    */}\n {/* {structureAnalysis.paragraph_analysis.suggestions.map((suggestion, index) => (*/}\n {/*
  • */}\n {/* */}\n {/* {suggestion}*/}\n {/*
  • */}\n {/* ))}*/}\n {/*
*/}\n {/*
*/}\n {/* )}*/}\n\n {/* /!* Logical Flow Recommendations *!/*/}\n {/* {structureAnalysis.logical_flow_analysis.suggestions && structureAnalysis.logical_flow_analysis.suggestions.length > 0 && (*/}\n {/*
*/}\n {/*
*/}\n {/* */}\n {/*
Logical Flow Improvements
*/}\n {/*
*/}\n {/*
    */}\n {/* {structureAnalysis.logical_flow_analysis.suggestions.map((suggestion, index) => (*/}\n {/*
  • */}\n {/* */}\n {/* {suggestion}*/}\n {/*
  • */}\n {/* ))}*/}\n {/*
*/}\n {/*
*/}\n {/* )}*/}\n {/*
*/}\n {/* */}\n {/*)}*/}\n \n );\n};\n\nexport default StructureTab;", "import React from 'react';\nimport { Clock, Zap, Database, ArrowRight } from 'lucide-react';\n\nconst TechnicalTab = ({ analysis }) => {\n // Get technical analysis data or use defaults\n const technical = analysis?.technical_analysis || {\n performance_metrics: {\n time_to_first_byte_ms: 0,\n total_load_time_ms: 0,\n total_response_size_kb: 0\n },\n context_window_analysis: {\n front_loading_score: 0,\n information_density_map: []\n }\n };\n\n const { performance_metrics, context_window_analysis } = technical;\n\n // Helper functions for technical analysis\n const getTTFBColorClass = (ttfb) => {\n if (ttfb < 100) return 'bg-green-500';\n if (ttfb < 300) return 'bg-green-400';\n if (ttfb < 500) return 'bg-yellow-400';\n if (ttfb < 1000) return 'bg-orange-400';\n return 'bg-red-500';\n };\n\n const getTTFBRating = (ttfb) => {\n if (ttfb < 100) return 'Excellent';\n if (ttfb < 300) return 'Good';\n if (ttfb < 500) return 'Average';\n if (ttfb < 1000) return 'Slow';\n return 'Very slow';\n };\n\n const getLoadTimeColorClass = (loadTime) => {\n if (loadTime < 500) return 'bg-green-500';\n if (loadTime < 1000) return 'bg-green-400';\n if (loadTime < 2000) return 'bg-yellow-400';\n if (loadTime < 3000) return 'bg-orange-400';\n return 'bg-red-500';\n };\n\n const getLoadTimeRating = (loadTime) => {\n if (loadTime < 500) return 'Excellent';\n if (loadTime < 1000) return 'Good';\n if (loadTime < 2000) return 'Average';\n if (loadTime < 3000) return 'Slow';\n return 'Very slow';\n };\n\n const getResponseSizeColorClass = (sizeKb) => {\n if (sizeKb < 50) return 'bg-green-500';\n if (sizeKb < 100) return 'bg-green-400';\n if (sizeKb < 200) return 'bg-yellow-400';\n if (sizeKb < 500) return 'bg-orange-400';\n return 'bg-red-500';\n };\n\n const getResponseSizeRating = (sizeKb) => {\n if (sizeKb < 50) return 'Very light';\n if (sizeKb < 100) return 'Light';\n if (sizeKb < 200) return 'Average';\n if (sizeKb < 500) return 'Heavy';\n return 'Very heavy';\n };\n\n const getPerformanceImpactMessage = (metrics) => {\n const { time_to_first_byte_ms, total_load_time_ms, total_response_size_kb } = metrics;\n\n if (time_to_first_byte_ms < 300 && total_load_time_ms < 1000 && total_response_size_kb < 100) {\n return \"This page's excellent performance metrics make it ideal for AI systems. Fast load times and compact size ensure AI models can quickly process the page without timeout issues.\";\n } else if (time_to_first_byte_ms < 500 && total_load_time_ms < 2000 && total_response_size_kb < 200) {\n return \"This page has good performance characteristics for AI systems. While not optimal, it should process reliably in most AI contexts.\";\n } else if (total_load_time_ms > 3000 || total_response_size_kb > 500) {\n return \"This page's slow load time or large size may cause issues for AI systems with stricter time limits. Consider optimizing page performance to improve AI accessibility.\";\n } else {\n return \"This page has average performance metrics. Some optimization could improve AI processing reliability, especially for systems with stricter resource constraints.\";\n }\n };\n\n const getFrontLoadingScoreColor = (score) => {\n if (score >= 80) return 'text-green-600';\n if (score >= 60) return 'text-yellow-600';\n return 'text-red-600';\n };\n\n const getFrontLoadingScoreColorClass = (score) => {\n if (score >= 80) return 'bg-green-500';\n if (score >= 60) return 'bg-yellow-400';\n return 'bg-red-400';\n };\n\n const getFrontLoadingScoreDescription = (score) => {\n if (score >= 80) {\n return \"Excellent front-loading. Key information appears early in the content, making it ideal for AI context windows.\";\n } else if (score >= 60) {\n return \"Moderate front-loading. Some important information appears early, but there's room for improvement.\";\n } else {\n return \"Poor front-loading. Critical information may be buried deep in the content where AI systems with limited context windows might miss it.\";\n }\n };\n\n const getDensityScoreColorClass = (score) => {\n if (score >= 70) return 'bg-indigo-500';\n if (score >= 40) return 'bg-indigo-300';\n return 'bg-indigo-100';\n };\n\n const getInformationDensityDescription = (densityMap) => {\n if (!densityMap || densityMap.length === 0) return \"\";\n\n // Calculate average density\n const avgDensity = densityMap.reduce((sum, section) => sum + section.density_score, 0) / densityMap.length;\n\n // Check if front-loaded\n const firstQuarterDenser = densityMap[0]?.density_score > avgDensity;\n\n // Check for density drops\n const hasSevereDensityDrop = densityMap.some((section, i) =>\n i > 0 && section.density_score < densityMap[i-1].density_score * 0.5\n );\n\n if (avgDensity >= 60 && firstQuarterDenser) {\n return \"This page has high information density concentrated at the beginning, making it ideal for AI systems with limited context windows.\";\n } else if (avgDensity >= 50) {\n return \"This page has good overall information density. AI systems should be able to extract meaningful information throughout the content.\";\n } else if (hasSevereDensityDrop) {\n return \"This page has significant drops in information density. Important details may be lost when surrounded by low-density content.\";\n } else if (avgDensity < 30) {\n return \"This page has low information density overall. AI systems may struggle to extract meaningful insights from the content.\";\n } else {\n return \"This page has moderate information density with room for improvement. Consider restructuring to front-load key information.\";\n }\n };\n\n const getContextWindowRecommendations = (contextAnalysis) => {\n const recommendations = [];\n const { front_loading_score, information_density_map } = contextAnalysis;\n\n if (!information_density_map || information_density_map.length === 0) {\n return [\"No data available to generate recommendations.\"];\n }\n\n // Front-loading recommendations\n if (front_loading_score < 60) {\n recommendations.push(\"Move key facts, product details, and critical information to the first 25% of your content to improve AI comprehension.\");\n }\n\n // Density pattern recommendations\n const avgDensity = information_density_map.reduce((sum, section) => sum + section.density_score, 0) / information_density_map.length;\n\n if (avgDensity < 40) {\n recommendations.push(\"Increase information density by adding more concrete facts, specific details, and technical terms throughout your content.\");\n }\n\n // Look for low-density sections\n const lowDensitySections = information_density_map.filter(section => section.density_score < 30);\n if (lowDensitySections.length > 0) {\n recommendations.push(`Improve content in ${lowDensitySections[0].section} by adding more specific information and reducing filler content.`);\n }\n\n // Specific structure recommendations\n if (information_density_map[3]?.density_score > information_density_map[0]?.density_score) {\n recommendations.push(\"Restructure your content to move valuable information from the end to the beginning to ensure it's processed within AI context windows.\");\n }\n\n // Default recommendations if none generated\n if (recommendations.length === 0) {\n recommendations.push(\"Maintain current content structure while ensuring critical information remains in the first half of the content.\");\n }\n\n return recommendations;\n };\n\n return (\n
\n

Technical Analysis

\n\n {/* Performance Metrics Section */}\n
\n

Performance Metrics

\n
\n
\n
\n \n
\n

Time to First Byte

\n

{performance_metrics.time_to_first_byte_ms.toFixed(1)} ms

\n
\n
\n
\n
\n
\n
\n

\n {getTTFBRating(performance_metrics.time_to_first_byte_ms)}\n

\n
\n
\n\n
\n
\n \n
\n

Total Load Time

\n

{performance_metrics.total_load_time_ms.toFixed(1)} ms

\n
\n
\n
\n
\n
\n
\n

\n {getLoadTimeRating(performance_metrics.total_load_time_ms)}\n

\n
\n
\n\n
\n
\n \n
\n

Response Size

\n

{performance_metrics.total_response_size_kb.toFixed(1)} KB

\n
\n
\n
\n
\n
\n
\n

\n {getResponseSizeRating(performance_metrics.total_response_size_kb)}\n

\n
\n
\n
\n\n
\n
Performance Impact on AI
\n

\n {getPerformanceImpactMessage(performance_metrics)}\n

\n
\n
\n\n {/* Context Window Analysis Section */}\n
\n

Content Organization Analysis

\n\n
\n
\n
Front-Loading Score
\n \n {context_window_analysis.front_loading_score}/100\n \n
\n
\n
\n
\n

\n {getFrontLoadingScoreDescription(context_window_analysis.front_loading_score)}\n

\n
\n\n\n
Information Density Map
\n {context_window_analysis.information_density_map && context_window_analysis.information_density_map.length > 0 ? (\n
\n
\n {/* Move explanation text ABOVE the chart with more space */}\n
\n Higher bars indicate greater information density in that section.\n
\n {/* Information Density Bar Chart - CORRECTED ORIENTATION */}\n
\n\n {/* Y-axis labels */}\n
\n 100%\n 75%\n 50%\n 25%\n 0%\n
\n\n {/* Grid lines */}\n
\n
\n
\n
\n
\n
\n
\n\n {/* Actual bar chart - NOW PROPERLY ORIENTED */}\n
\n {context_window_analysis.information_density_map.map((section, index) => (\n
\n 0 ? '4px' : '0', // Minimum height for visibility if > 0\n transition: 'height 0.3s ease-in-out'\n }}\n >
\n
\n ))}\n
\n\n {/* X-axis labels with clarified values */}\n
\n {context_window_analysis.information_density_map.map((section, index) => (\n
\n

{section.section}

\n

Density: {section.density_score}%

\n
\n ))}\n
\n
\n\n {/* Section explaining the quarter distribution */}\n
\n

What this means: These bars show how information-rich each quarter of the content is.\n A good pattern for AI readability shows higher density in early quarters (front-loading).

\n\n {context_window_analysis.front_loading_score > 60 ? (\n

This content has good front-loading with key information early.

\n ) : context_window_analysis.front_loading_score > 40 ? (\n

This content has moderate front-loading of information.

\n ) : (\n

This content lacks front-loading, with important information appearing late.

\n )}\n
\n\n {/* Linear visualization */}\n
\n
\n {context_window_analysis.information_density_map.map((section, index) => (\n
\n ))}\n
\n
\n Beginning of content\n End of content\n
\n
\n\n
\n
What this means for AI:
\n

\n {getInformationDensityDescription(context_window_analysis.information_density_map)}\n

\n
\n
\n
\n ) : (\n
\n

No information density data available.

\n
\n )}\n\n
\n
Recommendations for Context Window Optimization
\n
    \n {getContextWindowRecommendations(context_window_analysis).map((rec, index) => (\n
  • \n \n {rec}\n
  • \n ))}\n
\n
\n \n \n );\n};\n\nexport default TechnicalTab;", "import React from 'react';\nimport { FileText, RefreshCw, ChevronRight, AlertCircle, Loader, Trash2, ExternalLink, Globe, Zap, Plus } from 'lucide-react';\n\nconst AnalysisList = ({\n analyses,\n loading,\n error,\n customUrl,\n setCustomUrl,\n onStartNewAnalysis,\n onAnalyzeUrl,\n onViewReport,\n onDelete,\n onConfirmDelete,\n onCancelDelete,\n deleteConfirmation,\n onRefresh,\n renderStatusBadge\n }) => {\n\n // Check if this is the first time (no analyses yet)\n const isFirstTime = analyses.length === 0;\n\n return (\n
\n {/* Header */}\n
\n
\n

Content Analysis

\n \n \n \n
\n
\n\n {/* Error message */}\n {error && (\n
\n
\n
\n \n
\n
\n

{error}

\n
\n
\n
\n )}\n\n {/* Prominent Action Cards */}\n
\n {/* Primary CTA - Analyze Domain Content */}\n
\n {/* Decorative elements */}\n
\n
\n\n
\n
\n \n \n {isFirstTime ? 'Start Here' : 'Recommended'}\n \n
\n\n

Analyze Your Domain

\n

\n {isFirstTime\n ? \"Get started by analyzing all pages on your domain. We'll automatically discover your content and provide comprehensive AI readiness insights.\"\n : \"Run a new comprehensive analysis of your entire domain to discover content changes and optimization opportunities.\"\n }\n

\n\n \n {loading ? (\n <>\n \n Starting Analysis...\n \n ) : (\n <>\n \n {isFirstTime ? 'Start First Analysis' : 'Analyze Domain'}\n \n )}\n \n\n {isFirstTime && (\n

\n \u2728 This will analyze all discoverable pages on your domain\n

\n )}\n
\n
\n\n {/* Secondary CTA - Analyze Specific URL */}\n
\n
\n \n
\n\n

Analyze Specific Page

\n

\n Have a specific page you want to analyze? Enter the URL below to get detailed insights for that particular page.\n

\n\n
\n setCustomUrl(e.target.value)}\n placeholder=\"https://example.com/page\"\n className=\"w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm\"\n />\n \n {loading ? (\n <>\n \n Analyzing...\n \n ) : (\n <>\n \n Analyze This Page\n \n )}\n \n
\n
\n
\n\n {/* Previous analyses section */}\n {analyses.length > 0 && (\n
\n

\n \n Previous Analyses ({analyses.length})\n

\n\n
\n
    \n {analyses.map((analysis) => {\n // Safely access page_analyses\n const pageAnalyses = analysis.page_analyses || [];\n const completedPages = pageAnalyses.filter(p => p.status === 'completed').length;\n const totalPages = pageAnalyses.length;\n const isBeingDeleted = deleteConfirmation === analysis.id;\n\n return (\n
  • \n
    \n
    \n
    \n
    \n
    \n \n
    \n
    \n

    \n Domain Analysis #{analysis.id}\n

    \n

    \n {completedPages} of {totalPages} pages analyzed\n

    \n
    \n
    \n {renderStatusBadge(analysis.status)}\n
    \n
    \n
    \n {isBeingDeleted ? (\n
    \n Confirm delete?\n onConfirmDelete(analysis.id)}\n className=\"px-3 py-1.5 text-sm font-medium text-red-700 bg-red-50 rounded-md hover:bg-red-100 transition-colors\"\n >\n Yes, Delete\n \n \n Cancel\n \n
    \n ) : (\n <>\n \n {new Date(analysis.created_at).toLocaleDateString()}\n \n onViewReport(analysis.id)}\n className=\"inline-flex items-center px-4 py-2 text-sm font-medium text-indigo-700 bg-indigo-50 rounded-lg hover:bg-indigo-100 transition-colors\"\n >\n View Report\n \n \n onDelete(analysis.id)}\n className=\"p-2 text-gray-400 hover:text-red-600 hover:bg-gray-100 rounded-lg transition-colors\"\n title=\"Delete analysis\"\n disabled={loading}\n >\n \n \n \n )}\n
    \n
    \n
    \n
    \n
  • \n );\n })}\n
\n
\n
\n )}\n\n {/* Empty state (only shown when no analyses exist) */}\n {analyses.length === 0 && (\n
\n
\n \n

Ready to analyze your content?

\n

\n Use the options above to start your first content analysis and discover how AI-ready your content is.\n

\n
\n
\n )}\n
\n );\n};\n\nexport default AnalysisList;", "import React from 'react';\nimport { RefreshCw, ChevronRight, Trash2, Loader } from 'lucide-react';\n\nconst AnalysisOverview = ({\n analysis,\n onViewPage,\n onDelete,\n onCancelDelete,\n deleteConfirmation,\n onRefresh,\n onNewAnalysis,\n renderStatusBadge\n }) => {\n if (!analysis) return null;\n\n // Safely access page_analyses\n const pageAnalyses = analysis.page_analyses || [];\n const completedPages = pageAnalyses.filter(page => page.status === 'completed').length;\n const totalPages = pageAnalyses.length;\n const progressPercentage = totalPages > 0 ? (completedPages / totalPages) * 100 : 0;\n\n return (\n
\n {/* Analysis header */}\n
\n
\n
\n
\n

Content Analysis

\n \n \n \n
\n

\n Started on {new Date(analysis.created_at).toLocaleString()}\n

\n
\n {renderStatusBadge(analysis.status)}\n
\n
\n
\n {analysis.status === 'completed' && (\n \n \n Run New Analysis\n \n )}\n onDelete(analysis.id)}\n className=\"inline-flex items-center px-3 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500\"\n title=\"Delete analysis\"\n >\n \n Delete\n \n
\n
\n\n {/* Delete confirmation */}\n {deleteConfirmation === analysis.id && (\n
\n

Are you sure you want to delete this analysis? This cannot be undone.

\n
\n onDelete(analysis.id)}\n className=\"px-3 py-1 text-sm text-white bg-red-600 rounded-md hover:bg-red-700\"\n >\n Yes, delete\n \n \n Cancel\n \n
\n
\n )}\n
\n\n {/* Progress section */}\n {analysis.status === 'in_progress' || analysis.status === 'queued' ? (\n
\n

Analysis Progress

\n
\n
\n
\n
\n {completedPages} of {totalPages} pages\n
\n
\n ) : null}\n\n {/* Pages list */}\n
\n
\n

Analyzed Pages

\n {(analysis.status === 'in_progress' || analysis.status === 'queued') && (\n (Refreshes automatically)\n )}\n
\n\n {pageAnalyses.length > 0 ? (\n
\n \n \n \n \n \n \n \n \n \n \n {pageAnalyses.map((page) => (\n \n \n \n \n \n \n ))}\n \n
URLScoreStatus\n View\n
\n {page.url}\n \n {page.status === 'completed' ? (\n {(page.analysis_results && page.analysis_results.ai_parsing_score) || 'N/A'}/100\n ) : (\n Pending\n )}\n \n {renderStatusBadge(page.status)}\n \n {page.status === 'completed' ? (\n onViewPage(page.id)}\n className=\"text-indigo-600 hover:text-indigo-900 inline-flex items-center\"\n >\n View Analysis \n \n ) : page.status === 'failed' ? (\n Failed\n ) : (\n Processing\n )}\n
\n
\n ) : (\n
\n

No pages have been analyzed yet.

\n
\n )}\n
\n \n );\n};\n\nexport default AnalysisOverview;", "import React, { useState, useEffect, useRef, useContext } from 'react';\nimport { useNavigate, useParams } from 'react-router-dom';\nimport axios from '../../AxiosConfig';\nimport {\n Search,\n ExternalLink,\n Star,\n TrendingUp,\n AlertCircle,\n CheckCircle,\n Target,\n Lightbulb,\n BarChart,\n ArrowLeft,\n Eye,\n MessageSquare,\n Globe,\n ShoppingCart,\n Play,\n ChevronRight,\n FileText,\n Loader,\n Clock,\n Sparkles,\n BookOpen,\n ChevronDown\n} from 'lucide-react';\nimport { AuthContext } from '../../../context/AuthContext';\nimport { trackEvent } from '../../Analytics/mixpanel';\n\nconst Optimization = ({ projectId, project }) => {\n const { user } = useContext(AuthContext);\n const { topicId: urlTopicId, promptId: urlPromptId } = useParams();\n\n const [topics, setTopics] = useState([]);\n const [selectedTopic, setSelectedTopic] = useState(null);\n const [selectedPrompt, setSelectedPrompt] = useState(null);\n const [optimizationData, setOptimizationData] = useState(null);\n const [optimizationRecommendations, setOptimizationRecommendations] = useState(null);\n const [loading, setLoading] = useState(false);\n const [jobStatus, setJobStatus] = useState(null);\n const [currentJobId, setCurrentJobId] = useState(null);\n const [error, setError] = useState(null);\n const [activeTab, setActiveTab] = useState('analysis');\n const [expandedThoughts, setExpandedThoughts] = useState({});\n\n const pollingInterval = useRef(null);\n const autoTriggeredRef = useRef(false);\n const navigate = useNavigate();\n\n // Fetch all topics for the project\n useEffect(() => {\n const fetchTopics = async () => {\n try {\n if (!selectedTopic && !selectedPrompt) {\n setLoading(true);\n }\n const response = await axios.get(`/api/projects/${projectId}/topics`);\n const fetchedTopics = response.data || [];\n setTopics(fetchedTopics);\n setError(null);\n\n // Auto-select topic and prompt from URL params\n if (urlTopicId && !autoTriggeredRef.current && fetchedTopics.length > 0) {\n const matchedTopic = fetchedTopics.find(t => t.id === parseInt(urlTopicId));\n if (matchedTopic) {\n setSelectedTopic(matchedTopic);\n\n if (urlPromptId && matchedTopic.prompts) {\n const matchedPrompt = matchedTopic.prompts.find(p => p.id === parseInt(urlPromptId));\n if (matchedPrompt) {\n autoTriggeredRef.current = true;\n setTimeout(() => {\n handlePromptAnalyze(matchedPrompt);\n }, 0);\n }\n }\n }\n }\n } catch (err) {\n console.error('Error fetching topics:', err);\n setError('Failed to load topics');\n } finally {\n setLoading(false);\n }\n };\n\n if (projectId) {\n fetchTopics();\n }\n }, [projectId]);\n\n // Handle recommendations loading\n useEffect(() => {\n if (optimizationData && !optimizationRecommendations &&\n activeTab === 'ai-recommendations' && currentJobId) {\n if (!pollingInterval.current) {\n pollingInterval.current = setInterval(() => {\n pollJobStatus(currentJobId);\n }, 3000);\n }\n }\n\n return () => {\n if (pollingInterval.current &&\n (optimizationRecommendations || activeTab !== 'ai-recommendations')) {\n clearInterval(pollingInterval.current);\n pollingInterval.current = null;\n }\n };\n }, [optimizationData, optimizationRecommendations, activeTab, currentJobId]);\n\n // Cleanup polling on unmount\n useEffect(() => {\n return () => {\n if (pollingInterval.current) {\n clearInterval(pollingInterval.current);\n pollingInterval.current = null;\n }\n };\n }, []);\n\n const handleTopicSelect = (topic) => {\n trackEvent('Topic clicked', {\n project_id: projectId,\n user_id: user?.id,\n topic_id: topic.id,\n topic_name: topic.name,\n prompts_count: topic.prompts?.length || 0,\n source: 'optimization'\n });\n\n setSelectedTopic(topic);\n setSelectedPrompt(null);\n setOptimizationData(null);\n setOptimizationRecommendations(null);\n setJobStatus(null);\n setCurrentJobId(null);\n setError(null);\n setLoading(false);\n navigate(`/projects/${projectId}/optimization/${topic.id}`, { replace: true });\n };\n\n const pollJobStatus = async (jobId) => {\n try {\n const response = await axios.get(`/api/optimizations/${jobId}/status`);\n const data = response.data;\n\n console.log(\"API Response data:\", data);\n console.log(\"AI Thoughts in response:\", data.ai_thoughts);\n\n setJobStatus({\n status: data.status,\n progress: data.progress || 0\n });\n\n if (data.status === 'completed') {\n const completeData = {\n ...(data.optimization_data || {}),\n ai_thoughts: data.ai_thoughts || []\n };\n\n console.log(\"Setting optimizationData with:\", completeData);\n\n setOptimizationData(completeData);\n\n if (data.optimization_recommendations) {\n setOptimizationRecommendations(data.optimization_recommendations);\n if (pollingInterval.current) {\n clearInterval(pollingInterval.current);\n pollingInterval.current = null;\n }\n setLoading(false);\n } else {\n if (pollingInterval.current) {\n clearInterval(pollingInterval.current);\n }\n pollingInterval.current = setInterval(() => {\n pollJobStatus(jobId);\n }, 5000);\n }\n } else if (data.status === 'failed') {\n if (pollingInterval.current) {\n clearInterval(pollingInterval.current);\n pollingInterval.current = null;\n }\n\n setError(data.error || 'Optimization job failed');\n setLoading(false);\n }\n } catch (err) {\n console.error('Error polling job status:', err);\n if (err.response?.status === 404 || err.response?.status >= 500) {\n if (pollingInterval.current) {\n clearInterval(pollingInterval.current);\n pollingInterval.current = null;\n }\n setError('Error checking job status. Please try again.');\n setLoading(false);\n }\n }\n };\n\n const handlePromptAnalyze = async (prompt) => {\n try {\n trackEvent('Analyze clicked', {\n project_id: projectId,\n user_id: user?.id,\n topic_id: selectedTopic?.id,\n topic_name: selectedTopic?.name,\n prompt_id: prompt.id,\n prompt_text: prompt.prompt,\n prompt_length: prompt.prompt?.length || 0,\n source: 'optimization'\n });\n\n setLoading(true);\n setSelectedPrompt(prompt);\n setOptimizationData(null);\n setOptimizationRecommendations(null);\n setError(null);\n setJobStatus({ status: 'submitting', progress: 0 });\n\n const response = await axios.post(`/api/prompts/${prompt.id}/optimize`);\n const { job_id, status, message } = response.data;\n\n setCurrentJobId(job_id);\n\n if (status === 'completed') {\n setJobStatus({ status: 'completed', progress: 100 });\n await pollJobStatus(job_id);\n } else if (status === 'submitted' || status === 'queued' || status === 'processing') {\n setJobStatus({ status: status, progress: 0 });\n\n if (message) {\n console.log(message);\n }\n\n if (pollingInterval.current) {\n clearInterval(pollingInterval.current);\n }\n pollingInterval.current = setInterval(() => {\n pollJobStatus(job_id);\n }, 3000);\n }\n } catch (err) {\n console.error('Error analyzing prompt:', err);\n const errorMessage = err.response?.data?.error || err.message || 'Failed to start optimization.';\n setError(errorMessage);\n setLoading(false);\n setJobStatus(null);\n }\n };\n\n const handleBack = () => {\n if (pollingInterval.current) {\n clearInterval(pollingInterval.current);\n pollingInterval.current = null;\n }\n\n if (selectedPrompt) {\n setSelectedPrompt(null);\n setOptimizationData(null);\n setOptimizationRecommendations(null);\n setJobStatus(null);\n setCurrentJobId(null);\n setError(null);\n setLoading(false);\n if (selectedTopic) {\n navigate(`/projects/${projectId}/optimization/${selectedTopic.id}`, { replace: true });\n }\n } else if (selectedTopic) {\n setSelectedTopic(null);\n setLoading(false);\n navigate(`/projects/${projectId}/optimization`, { replace: true });\n }\n };\n\n const handleBackToProject = () => {\n if (pollingInterval.current) {\n clearInterval(pollingInterval.current);\n pollingInterval.current = null;\n }\n navigate(`/projects/${projectId}/overview`);\n };\n\n const getPriorityColor = (priority) => {\n switch (priority) {\n case 'high': return 'bg-red-100 text-red-800 border-red-200';\n case 'medium': return 'bg-yellow-100 text-yellow-800 border-yellow-200';\n case 'low': return 'bg-green-100 text-green-800 border-green-200';\n default: return 'bg-gray-100 text-gray-800 border-gray-200';\n }\n };\n\n const getTypeIcon = (type) => {\n switch (type) {\n case 'content_gap': return ;\n case 'product_positioning': return ;\n case 'technical_seo': return ;\n case 'review_strategy': return ;\n case 'content_marketing': return ;\n case 'other': return ;\n default: return ;\n }\n };\n\n const getStatusMessage = (status) => {\n switch (status?.status) {\n case 'submitting':\n return 'Submitting optimization job... This may take a minute or two.';\n case 'submitted':\n return 'Job submitted, waiting to start... This process may take a minute or two to complete.';\n case 'queued':\n return 'Job queued for processing... This analysis typically takes 1-2 minutes to complete.';\n case 'processing':\n return `Processing... ${status.progress}% complete. The optimization analysis may take a minute or two.`;\n case 'completed':\n return 'Analysis complete!';\n case 'failed':\n return 'Job failed';\n default:\n return 'Processing optimization request... This may take a minute or two.';\n }\n };\n\n const formatTimestamp = (timestamp) => {\n if (!timestamp) return 'Unknown time';\n const date = new Date(timestamp * 1000);\n return date.toLocaleString();\n };\n\n const toggleThought = (id) => {\n setExpandedThoughts(prev => ({\n ...prev,\n [id]: !prev[id]\n }));\n };\n\n const handleTabChange = (tabName) => {\n if (tabName === 'ai-recommendations') {\n trackEvent('Content Optimization clicked', {\n project_id: projectId,\n user_id: user?.id,\n topic_id: selectedTopic?.id,\n topic_name: selectedTopic?.name,\n prompt_id: selectedPrompt?.id,\n prompt_text: selectedPrompt?.prompt,\n previous_tab: activeTab,\n has_optimization_data: Boolean(optimizationData),\n has_recommendations: Boolean(optimizationRecommendations),\n source: 'optimization'\n });\n\n if (!optimizationRecommendations && jobStatus?.status === 'completed' && currentJobId) {\n pollJobStatus(currentJobId);\n }\n }\n\n setActiveTab(tabName);\n };\n\n // Only show loading indicator when we're at the top level and loading is true\n if (loading && !selectedTopic && !selectedPrompt) {\n return (\n
\n
Loading topics...
\n
\n );\n }\n\n if (error && !selectedTopic && !selectedPrompt) {\n return (\n
\n
\n
\n \n

Error Loading Topics

\n
\n

{error}

\n
\n

Debug: projectId={projectId}

\n
\n \n Return to Project\n \n
\n
\n );\n }\n\n // If analyzing a prompt, show the analysis view\n if (selectedPrompt) {\n return (\n
\n {/* Header */}\n
\n
\n \n \n \n
\n

Prompt Optimization Analysis

\n

Analyze and optimize prompt performance

\n
\n
\n\n {/* Prompt Info */}\n
\n
\n
\n
\n \n {selectedTopic.name}\n \n
\n

\n \"{selectedPrompt.prompt}\"\n

\n
\n
\n Project:\n

{project?.name}

\n
\n
\n
\n
\n\n {/* Loading/Status Display */}\n {(loading || jobStatus) && !optimizationData && selectedPrompt && (\n
\n
\n \n
\n

\n {jobStatus ? getStatusMessage(jobStatus) : \"Preparing optimization job...\"}\n

\n

\n The optimization process typically takes 1-2 minutes to complete. We're analyzing your prompt and tracking internal AI steps.\n

\n {jobStatus && jobStatus.status === 'processing' && jobStatus.progress > 0 && (\n
\n
\n \n
\n
\n )}\n {currentJobId && (\n

Job ID: {currentJobId}

\n )}\n
\n
\n
\n )}\n\n {/* Error Display */}\n {error && (\n
\n
\n \n
\n

Optimization Error

\n

{error}

\n
\n
\n
\n )}\n\n {/* Results Display */}\n {optimizationData && (\n <>\n {/* Tabs */}\n
\n
\n \n
\n
\n\n {/* Tab Content - Analysis */}\n {activeTab === 'analysis' && (\n
\n\n {/* AI Thoughts Section */}\n {optimizationData.ai_thoughts && optimizationData.ai_thoughts.length > 0 && (\n
\n

\n \n AI Thought Process\n

\n
\n {optimizationData.ai_thoughts.map((thought, index) => (\n
\n

{thought.summary}

\n

{formatTimestamp(thought.timestamp)}

\n

{thought.content}

\n
\n ))}\n
\n
\n )}\n\n {/* Search Queries */}\n
\n

\n \n Search Queries Executed\n

\n
\n {optimizationData.analysis?.search_queries?.length > 0\n ? optimizationData.analysis.search_queries.map((query, index) => (\n
\n \"{query.query}\"\n
\n ))\n :

No search queries found

\n }\n
\n
\n\n {/* Search Results */}\n
\n

\n \n Search Results Found ({optimizationData.analysis?.search_results?.length || 0})\n

\n
\n {optimizationData.analysis?.search_results?.length > 0\n ? optimizationData.analysis.search_results.map((result, index) => (\n
\n
\n
\n

{result.title}

\n

{result.snippet}

\n
\n {result.domain}\n {result.pub_date && (\n {new Date(result.pub_date * 1000).toLocaleDateString()}\n )}\n
\n
\n \n \n \n
\n
\n ))\n :

No search results found

\n }\n
\n
\n\n {/* Products Mentioned */}\n {optimizationData.analysis?.products_mentioned?.length > 0 && (\n
\n

\n \n Products Featured in Response\n

\n
\n {optimizationData.analysis.products_mentioned.map((product, index) => (\n
\n

{product.title}

\n
\n
\n Price:\n {product.price}\n
\n {product.rating && (\n
\n Rating:\n
\n \n {product.rating} ({product.num_reviews} reviews)\n
\n
\n )}\n
\n Merchants:\n {product.merchants}\n
\n {product.featured_tag && (\n
\n \n {product.featured_tag}\n \n
\n )}\n
\n
\n ))}\n
\n
\n )}\n\n {/* Sources Cited */}\n
\n

\n \n Sources Actually Cited ({optimizationData.analysis?.sources_cited?.length || 0})\n

\n
\n {optimizationData.analysis?.sources_cited?.length > 0\n ? optimizationData.analysis.sources_cited.map((source, index) => (\n
\n
\n

{source.title}

\n

{source.attribution}

\n
\n \n \n \n
\n ))\n :

No sources cited

\n }\n
\n
\n\n {/* AI Response Full View */}\n
\n

\n \n AI Response\n

\n
\n
\n {optimizationData.analysis?.ai_response || 'No response available'}\n
\n
\n
\n
\n )}\n\n {/* Tab Content - AI Recommendations */}\n {activeTab === 'ai-recommendations' && (\n
\n {optimizationRecommendations ? (\n <>\n {/* Overall Summary */}\n
\n
\n \n
\n

Summary

\n

\n {optimizationRecommendations.summary}\n

\n
\n
\n
\n\n {/* Recommendations */}\n

\n Content Optimization for AI Visibility\n

\n
\n

\n Goal: These recommendations focus on optimizing your website content, SEO, and product information to help your brands and products appear more frequently in AI-generated responses across platforms like ChatGPT.\n

\n
\n
\n {optimizationRecommendations.recommendations.map((recommendation, index) => (\n
\n
\n
\n
\n {getTypeIcon(recommendation.type)}\n
\n
\n

{recommendation.title}

\n

\n {recommendation.type.replace('_', ' ')} optimization\n

\n
\n
\n \n {recommendation.priority} priority\n \n
\n\n

{recommendation.description}

\n\n
\n

\n \n Actionable Steps:\n

\n
    \n {recommendation.actionable_steps.map((step, stepIndex) => (\n
  • \n \n {stepIndex + 1}\n \n {step}\n
  • \n ))}\n
\n
\n
\n ))}\n
\n \n ) : (\n
\n \n

Generating Content Optimization Recommendations

\n

\n We're analyzing your content performance and generating optimization recommendations.\n This may take a minute or two.\n

\n
\n

\n If this is taking longer than expected, you can continue analyzing other data or come back later.\n Your recommendations will be saved automatically.\n

\n
\n
\n )}\n
\n )}\n \n )}\n
\n );\n }\n\n // If a topic is selected, show its prompts\n if (selectedTopic) {\n return (\n
\n
\n
\n \n \n \n
\n

{selectedTopic.name}

\n

Select a prompt to analyze its performance

\n
\n
\n
\n\n {selectedTopic.prompts && selectedTopic.prompts.length > 0 ? (\n
\n
\n

Available Prompts

\n

{selectedTopic.prompts.length} prompts in this topic

\n
\n
\n {selectedTopic.prompts.map((prompt) => (\n
\n
\n
\n

\n {prompt.prompt}\n

\n

\n Created {new Date(prompt.created_at).toLocaleDateString()}\n

\n
\n handlePromptAnalyze(prompt)}\n className=\"flex items-center px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 transition-colors\"\n >\n \n Analyze\n \n
\n
\n ))}\n
\n
\n ) : (\n
\n \n

No Prompts Available

\n

\n This topic doesn't have any prompts yet.\n

\n navigate(`/projects/${projectId}/topics/${selectedTopic.id}/prompts/new`)}\n className=\"bg-indigo-600 text-white px-4 py-2 rounded-md hover:bg-indigo-700\"\n >\n Create First Prompt\n \n
\n )}\n
\n );\n }\n\n // Default view: show topics list\n return (\n
\n
\n

Prompt Optimization

\n

Select a topic to view and analyze its prompts

\n
\n\n {topics.length === 0 ? (\n
\n \n

No Topics Available

\n

\n You need to create some topics before you can optimize prompts.\n

\n navigate(`/projects/${projectId}/overview`)}\n className=\"bg-indigo-600 text-white px-4 py-2 rounded-md hover:bg-indigo-700\"\n >\n Go to Project Overview\n \n
\n ) : (\n
\n
\n

Select a Topic

\n

Choose from {topics.length} available topics

\n
\n
\n {topics.map((topic) => (\n handleTopicSelect(topic)}\n >\n
\n
\n

\n {topic.name}\n

\n

\n {topic.prompts?.length || 0} prompts \u2022\n Created {new Date(topic.created_at).toLocaleDateString()}\n

\n
\n \n
\n
\n ))}\n
\n
\n )}\n \n );\n};\n\nexport default Optimization;", "import React, { useState, useEffect } from 'react';\nimport { useParams, useNavigate } from 'react-router-dom';\nimport axios from '../../AxiosConfig';\nimport {\n PlusCircle,\n Trash2,\n Compass,\n Calendar,\n X,\n ChevronRight,\n AlertCircle\n} from 'lucide-react';\nimport ConversationExplorer from './ConversationExplorer';\n\nconst ExploreConversations = ({ projectId: propProjectId }) => {\n const { projectId: urlProjectId } = useParams();\n const projectId = propProjectId || urlProjectId;\n const navigate = useNavigate();\n\n const [explorations, setExplorations] = useState([]);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n const [showCreateForm, setShowCreateForm] = useState(false);\n const [selectedExploration, setSelectedExploration] = useState(null);\n const [formData, setFormData] = useState({\n topic: '',\n user_persona: ''\n });\n const [submitting, setSubmitting] = useState(false);\n\n useEffect(() => {\n fetchExplorations();\n }, [projectId]);\n\n const fetchExplorations = async () => {\n try {\n setLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/conversation_explorations`);\n setExplorations(response.data);\n setError(null);\n } catch (err) {\n console.error('Error fetching explorations:', err);\n setError('Failed to load conversation explorations. Please try again later.');\n } finally {\n setLoading(false);\n }\n };\n\n const handleInputChange = (e) => {\n const { name, value } = e.target;\n setFormData({\n ...formData,\n [name]: value\n });\n };\n\n const handleCreateSubmit = async (e) => {\n e.preventDefault();\n\n if (!formData.topic.trim()) {\n setError('Topic is required');\n return;\n }\n\n try {\n setSubmitting(true);\n const response = await axios.post(\n `/api/projects/${projectId}/conversation_explorations`,\n { conversation_exploration: formData }\n );\n\n // Add the new exploration to the list\n setExplorations([response.data, ...explorations]);\n\n // Reset form and hide it\n setFormData({ topic: '', user_persona: '' });\n setShowCreateForm(false);\n setError(null);\n\n // Select the new exploration\n setSelectedExploration(response.data);\n } catch (err) {\n console.error('Error creating exploration:', err);\n setError(err.response?.data?.errors?.join(', ') || 'Failed to create exploration. Please try again.');\n } finally {\n setSubmitting(false);\n }\n };\n\n const handleDelete = async (id) => {\n if (!window.confirm('Are you sure you want to delete this exploration?')) return;\n\n try {\n await axios.delete(`/api/projects/${projectId}/conversation_explorations/${id}`);\n\n // Remove the deleted exploration from the list\n setExplorations(explorations.filter(exp => exp.id !== id));\n\n // If the deleted exploration was selected, deselect it\n if (selectedExploration && selectedExploration.id === id) {\n setSelectedExploration(null);\n }\n } catch (err) {\n console.error('Error deleting exploration:', err);\n setError('Failed to delete exploration. Please try again later.');\n }\n };\n\n const handleExplorationSelect = (exploration) => {\n setSelectedExploration(exploration);\n };\n\n const handleBackToList = () => {\n setSelectedExploration(null);\n };\n\n // If a conversation is selected, show the conversation explorer\n if (selectedExploration) {\n return (\n
\n
\n \n
\n
\n );\n }\n\n return (\n
\n {/* Header */}\n
\n
\n
\n

AI Conversations Explorer

\n

\n Explore how users interact with AI systems around specific topics\n

\n
\n
\n setShowCreateForm(!showCreateForm)}\n className=\"inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\"\n >\n \n New Exploration\n \n
\n
\n
\n\n {/* Create Form */}\n {showCreateForm && (\n
\n

Create New Exploration

\n\n {error && (\n
\n
\n
\n \n
\n
\n

{error}

\n
\n
\n
\n )}\n\n
\n
\n
\n \n \n
\n
\n \n \n

\n Specify a user persona to see how different types of users interact with AI around this topic\n

\n
\n
\n {\n setShowCreateForm(false);\n setError(null);\n }}\n className=\"mr-3 inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\"\n >\n Cancel\n \n \n {submitting ? 'Creating...' : 'Create Exploration'}\n \n
\n
\n
\n
\n )}\n\n {/* Explorations List */}\n
\n {loading ? (\n
\n
Loading explorations...
\n
\n ) : explorations.length === 0 ? (\n
\n \n

No explorations found

\n

\n Get started by creating a new conversation exploration.\n

\n
\n setShowCreateForm(true)}\n className=\"inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\"\n >\n \n New Exploration\n \n
\n
\n ) : (\n
\n {explorations.map(exploration => (\n \n handleExplorationSelect(exploration)}\n >\n
\n

{exploration.topic}

\n {exploration.user_persona && (\n

\n Persona: {exploration.user_persona}\n

\n )}\n
\n \n \n Created {new Date(exploration.created_at).toLocaleDateString()}\n \n
\n
\n
\n {\n e.stopPropagation();\n handleDelete(exploration.id);\n }}\n className=\"p-2 text-gray-400 hover:text-red-500 rounded-full hover:bg-gray-100 focus:outline-none\"\n title=\"Delete exploration\"\n >\n \n \n \n
\n
\n
\n ))}\n
\n )}\n \n \n );\n};\n\nexport default ExploreConversations;", "import React, { useState, useEffect, useRef } from 'react';\nimport axios from '../../AxiosConfig';\nimport {\n AlertCircle,\n ChevronRight,\n ChevronLeft,\n Compass,\n Percent,\n MessageSquare,\n Check,\n RefreshCw,\n ArrowDown,\n ArrowUp,\n Info,\n ArrowRightCircle,\n Save,\n CheckCircle\n} from 'lucide-react';\n\nconst ConversationExplorer = ({ projectId, explorationId, onBackClick }) => {\n const [loading, setLoading] = useState(true);\n const [exploration, setExploration] = useState(null);\n const [prompts, setPrompts] = useState([]);\n const [selectedPath, setSelectedPath] = useState([]);\n const [error, setError] = useState(null);\n const [fetchingNextLevel, setFetchingNextLevel] = useState(false);\n const [sortField, setSortField] = useState('percentage');\n const [sortDirection, setSortDirection] = useState('desc');\n const [savedPrompts, setSavedPrompts] = useState({});\n const [savingPrompt, setSavingPrompt] = useState(null);\n const [initialPromptLoading, setInitialPromptLoading] = useState(false);\n\n // For polling\n const [isPolling, setIsPolling] = useState(false);\n const [pollCount, setPollCount] = useState(0);\n const pollingIntervalRef = useRef(null);\n const selectedPromptRef = useRef(null);\n const MAX_POLL_COUNT = 500; // Maximum number of polling attempts\n\n // Track what's being explicitly loaded vs preloaded\n const [userInitiatedLoading, setUserInitiatedLoading] = useState(null);\n\n useEffect(() => {\n fetchExploration();\n\n // Clean up polling on unmount\n return () => {\n if (pollingIntervalRef.current) {\n clearInterval(pollingIntervalRef.current);\n }\n };\n }, [projectId, explorationId]);\n\n // Effect to update selected path with fresh data when prompts change\n useEffect(() => {\n if (!loading && selectedPath.length > 0) {\n // Get fresh data for each prompt in the path\n const updatedPath = selectedPath.map(pathPrompt => {\n // Try to find this prompt in the updated data\n const freshPrompt = findPromptInData(prompts, pathPrompt.id);\n // Return either the fresh data or the existing path data\n return freshPrompt || pathPrompt;\n });\n\n // Only update if something changed\n if (JSON.stringify(updatedPath) !== JSON.stringify(selectedPath)) {\n console.log(\"Updating selected path with fresh data\");\n setSelectedPath(updatedPath);\n }\n }\n }, [prompts, loading]);\n\n useEffect(() => {\n // Start polling for initial prompts if there are none\n if (!loading && exploration && prompts.length === 0) {\n console.log(\"No prompts available, starting initial loading\");\n setInitialPromptLoading(true);\n startRootPromptPolling();\n }\n }, [loading, prompts.length, exploration]);\n\n useEffect(() => {\n // When prompts change and we have prompts, stop initial loading\n if (!loading && prompts.length > 0 && initialPromptLoading) {\n console.log(\"Prompts loaded, stopping initial loading\");\n setInitialPromptLoading(false);\n stopPolling();\n }\n }, [prompts, loading, initialPromptLoading]);\n\n const fetchExploration = async () => {\n try {\n console.log(\"Fetching exploration data...\");\n const response = await axios.get(`/api/projects/${projectId}/conversation_explorations/${explorationId}`);\n console.log(\"Exploration data received:\", response.data);\n\n setExploration(response.data.exploration);\n setPrompts(response.data.prompts || []);\n setError(null);\n\n // If we were polling and the selected prompt's children now have children,\n // we can stop polling\n if (isPolling && selectedPromptRef.current) {\n const prompt = findPromptInData(response.data.prompts, selectedPromptRef.current);\n\n if (prompt && prompt.children) {\n console.log(\"Checking if we should stop polling for prompt:\", selectedPromptRef.current);\n console.log(\"Children count:\", prompt.children.length);\n\n const allChildrenHaveChildren = prompt.children.length > 0 &&\n prompt.children.every(child => child.children && child.children.length > 0);\n\n if (allChildrenHaveChildren) {\n console.log(\"All children have their own children, stopping polling\");\n stopPolling();\n } else if (pollCount >= MAX_POLL_COUNT) {\n // Stop polling after maximum attempts\n console.log(\"Max poll count reached, stopping polling\");\n stopPolling();\n setError(\"Some prompts are still being generated. The data will update automatically when available.\");\n }\n }\n }\n } catch (err) {\n console.error('Error fetching exploration:', err);\n setError('Failed to load conversation exploration. Please try again later.');\n stopPolling();\n } finally {\n setLoading(false);\n }\n };\n\n const startRootPromptPolling = () => {\n // Clear any existing polling interval\n if (pollingIntervalRef.current) {\n clearInterval(pollingIntervalRef.current);\n }\n\n setIsPolling(true);\n setPollCount(0);\n\n // Set up a new polling interval\n pollingIntervalRef.current = setInterval(() => {\n setPollCount(prev => {\n const newCount = prev + 1;\n // If we've reached the maximum polling attempts, stop polling\n if (newCount >= MAX_POLL_COUNT) {\n stopPolling();\n setInitialPromptLoading(false);\n }\n return newCount;\n });\n fetchExploration();\n }, 3000); // Poll every 3 seconds\n };\n\n const checkSavedPrompts = async () => {\n try {\n // Skip if there's no selected path\n if (selectedPath.length === 0) return;\n\n // Get just the current prompt (last in the path)\n const currentPrompt = selectedPath[selectedPath.length - 1];\n const promptText = currentPrompt.prompt_text;\n\n // Query the API to check if this single prompt is saved\n const response = await axios.get(`/api/projects/${projectId}/conversation_explorations/check_saved`, {\n params: { prompt_text: promptText }\n });\n\n // Update the saved prompts state with just this prompt's status\n const savedPromptIds = { ...savedPrompts }; // Create a copy of the existing state\n\n if (response.data.is_saved) {\n savedPromptIds[currentPrompt.id] = response.data.prompt_id;\n } else {\n // Remove from saved prompts if it exists there\n delete savedPromptIds[currentPrompt.id];\n }\n\n // Update the state with saved prompt information\n setSavedPrompts(savedPromptIds);\n } catch (err) {\n console.error('Error checking saved prompt:', err);\n }\n };\n\n // Simplified startPolling function to make code more DRY\n const startPolling = (promptId, showLoading = false) => {\n // Save the prompt ID we're polling for\n selectedPromptRef.current = promptId;\n setIsPolling(true);\n setPollCount(0);\n\n // Set loading state if needed\n if (showLoading) {\n setUserInitiatedLoading(promptId);\n }\n\n // Clear any existing polling interval\n if (pollingIntervalRef.current) {\n clearInterval(pollingIntervalRef.current);\n }\n\n // Set up a new polling interval\n pollingIntervalRef.current = setInterval(() => {\n setPollCount(prev => {\n const newCount = prev + 1;\n // If we've reached the maximum polling attempts, stop polling\n if (newCount >= MAX_POLL_COUNT) {\n stopPolling();\n }\n return newCount;\n });\n fetchExploration();\n }, 3000); // Poll every 3 seconds\n };\n\n const stopPolling = () => {\n if (pollingIntervalRef.current) {\n clearInterval(pollingIntervalRef.current);\n pollingIntervalRef.current = null;\n }\n setIsPolling(false);\n setFetchingNextLevel(false);\n selectedPromptRef.current = null;\n setUserInitiatedLoading(null);\n setPollCount(0);\n };\n\n const handlePromptClick = async (promptId) => {\n const prompt = findPromptById(promptId);\n if (!prompt) {\n console.error(\"Cannot find prompt with ID:\", promptId);\n return;\n }\n\n console.log(\"Clicked on prompt:\", prompt);\n\n // Update the path to show this prompt's children immediately\n updateSelectedPath(promptId);\n\n // Check saved prompts for this new path level\n checkSavedPrompts();\n\n // If this prompt already has children, we don't need to do anything else\n if (prompt.children && prompt.children.length > 0) {\n console.log(\"Prompt has children:\", prompt.children.length);\n\n // If any children don't have their own children yet, start a background fetch\n // to prepare the next level but don't show loading indicators for this\n const childrenNeedChildren = prompt.children.some(child =>\n !child.children || child.children.length === 0\n );\n\n if (childrenNeedChildren) {\n console.log(\"Children need their own children, fetching in background\");\n try {\n // This is a background operation, don't show loading indicators\n await axios.post(`/api/projects/${projectId}/conversation_explorations/${explorationId}/fetch_children`, {\n prompt_id: promptId\n });\n\n // Start background polling without showing loading indicators\n startPolling(promptId, false);\n } catch (err) {\n console.error('Error fetching children:', err);\n // Don't show errors for background loading\n }\n }\n } else {\n console.log(\"Prompt has no children, showing loading indicator\");\n\n try {\n // Explicitly trigger the job to generate children\n await axios.post(`/api/projects/${projectId}/conversation_explorations/${explorationId}/fetch_children`, {\n prompt_id: promptId\n });\n\n // Set loading state and start polling\n setUserInitiatedLoading(promptId);\n startPolling(promptId, true);\n } catch (err) {\n console.error('Error triggering child generation:', err);\n setError('Failed to generate follow-up prompts. Please try again.');\n }\n }\n };\n\n const handleSavePrompt = async (promptId, e) => {\n // Stop the event from propagating to the row click handler\n e.stopPropagation();\n\n const prompt = findPromptById(promptId);\n if (!prompt) return;\n\n // Don't save if already saving or saved\n if (savingPrompt === promptId || savedPrompts[promptId]) return;\n\n setSavingPrompt(promptId);\n\n try {\n // Save the prompt directly without first checking for topic\n const response = await axios.post(`/api/projects/${projectId}/conversation_explorations/save_prompt`, {\n prompt: {\n prompt: prompt.prompt_text,\n topic_name: exploration.topic\n }\n });\n\n // Update saved prompts state\n setSavedPrompts(prev => ({\n ...prev,\n [promptId]: response.data.id\n }));\n\n } catch (err) {\n console.error('Error saving prompt:', err);\n setError('Failed to save prompt. Please try again.');\n } finally {\n setSavingPrompt(null);\n }\n };\n\n const findPromptInData = (promptsArray, id) => {\n // Recursive function to find a prompt by ID in the prompt tree\n for (const p of promptsArray) {\n if (p.id === id) return p;\n\n if (p.children && p.children.length > 0) {\n const found = findPromptInData(p.children, id);\n if (found) return found;\n }\n }\n return null;\n };\n\n const updateSelectedPath = (promptId) => {\n const prompt = findPromptById(promptId);\n if (!prompt) return;\n\n console.log(\"Updating selected path with prompt:\", prompt);\n\n // If this prompt is already in the path, truncate the path\n const existingIndex = selectedPath.findIndex(p => p.id === promptId);\n if (existingIndex >= 0) {\n console.log(\"Prompt already in path at index:\", existingIndex);\n setSelectedPath(selectedPath.slice(0, existingIndex + 1));\n return;\n }\n\n // Make a deep copy of the prompt to ensure we have all data\n const promptCopy = JSON.parse(JSON.stringify(prompt));\n\n // Otherwise add this prompt to the path\n setSelectedPath([...selectedPath, promptCopy]);\n };\n\n const findPromptById = (promptId) => {\n return findPromptInData(prompts, promptId);\n };\n\n // Get the prompts to display at the current path level\n const getDisplayPrompts = () => {\n if (selectedPath.length === 0) {\n return prompts;\n }\n\n // Return children of the last prompt in the path\n const lastPrompt = selectedPath[selectedPath.length - 1];\n\n // Log for debugging\n console.log(\"Getting display prompts for:\", lastPrompt);\n console.log(\"Children:\", lastPrompt.children);\n\n // Make sure we're returning an array even if children is undefined or null\n return lastPrompt.children || [];\n };\n\n // Format percentage safely\n const formatPercentage = (value) => {\n // Ensure it's a number\n const numValue = parseFloat(value);\n if (isNaN(numValue)) {\n return \"0.0%\";\n }\n return `${numValue.toFixed(1)}%`;\n };\n\n // Check if we're explicitly loading children for the currently selected prompt\n const isExplicitlyLoadingChildren = () => {\n if (!userInitiatedLoading) return false;\n\n return selectedPath.length > 0 &&\n selectedPath[selectedPath.length - 1].id === userInitiatedLoading;\n };\n\n // Handle sorting\n const handleSort = (field) => {\n if (field === sortField) {\n // Toggle direction if same field\n setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');\n } else {\n // New field, default to descending\n setSortField(field);\n setSortDirection('desc');\n }\n };\n\n // Get sort icon for column\n const getSortIcon = (field) => {\n if (sortField === field) {\n return sortDirection === 'asc'\n ? \n : ;\n }\n // Return a neutral icon for sortable columns that aren't currently sorted\n return ;\n };\n\n // Get percentage score color\n const getPercentageScoreColor = (score) => {\n const numScore = parseFloat(score);\n if (isNaN(numScore)) return \"text-gray-500\";\n\n if (numScore >= 70) return 'text-blue-600 font-semibold';\n if (numScore >= 40) return 'text-blue-600 font-medium';\n return 'text-blue-600';\n };\n\n // Sort the displayed prompts\n const getSortedPrompts = () => {\n const displayPrompts = getDisplayPrompts();\n\n if (!displayPrompts.length) return [];\n\n return [...displayPrompts].sort((a, b) => {\n let aValue, bValue;\n\n // Extract the correct field values\n if (sortField === 'prompt_text') {\n aValue = a.prompt_text.toLowerCase();\n bValue = b.prompt_text.toLowerCase();\n } else if (sortField === 'percentage') {\n aValue = parseFloat(a.percentage) || 0;\n bValue = parseFloat(b.percentage) || 0;\n } else {\n aValue = a[sortField];\n bValue = b[sortField];\n }\n\n // Compare based on direction\n if (sortDirection === 'asc') {\n return aValue > bValue ? 1 : -1;\n } else {\n return aValue < bValue ? 1 : -1;\n }\n });\n };\n\n if (loading) {\n return (\n
\n
\n Loading conversation exploration...\n
\n );\n }\n\n if (!exploration) {\n return (\n
\n
\n
\n \n
\n
\n

\n Exploration not found or failed to load.\n

\n
\n
\n
\n );\n }\n\n const showLoadingIndicator = isExplicitlyLoadingChildren();\n const sortedPrompts = getSortedPrompts();\n\n // Removed overlay from fetchingNextLevel since it's redundant\n return (\n
\n {error && (\n
\n
\n
\n \n
\n
\n

{error}

\n setError(null)}\n className=\"mt-2 text-sm text-red-700 font-medium hover:text-red-600\"\n >\n Dismiss\n \n
\n
\n
\n )}\n\n {/* Header Section */}\n
\n
\n
\n
\n \n \n \n
\n

{exploration.topic}

\n {exploration.user_persona && (\n

\n User Persona: {exploration.user_persona}\n

\n )}\n
\n
\n {selectedPath.length > 0 && (\n setSelectedPath([])}\n className=\"inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50\"\n >\n \n Back to Root\n \n )}\n
\n\n {/* Path breadcrumbs */}\n {selectedPath.length > 0 && (\n
\n
Conversation Path:
\n
\n setSelectedPath([])}\n className=\"text-blue-600 hover:underline mr-2 flex items-center\"\n >\n \n Topic Root\n \n\n {selectedPath.map((prompt, index) => (\n \n \n \n \n setSelectedPath(selectedPath.slice(0, index + 1))}\n className={`${index === selectedPath.length - 1 ? 'font-semibold' : 'text-blue-600 hover:underline'}`}\n >\n {prompt.prompt_text.length > 40\n ? `${prompt.prompt_text.substring(0, 40)}...`\n : prompt.prompt_text}\n \n \n ))}\n
\n
\n )}\n\n {/* Current prompt display (if applicable) */}\n {selectedPath.length > 0 && (\n
\n
\n
\n \n
\n

Current prompt:

\n

\"{selectedPath[selectedPath.length-1].prompt_text}\"

\n
\n
\n\n {/* Save button for current prompt */}\n {selectedPath.length > 0 && (\n savedPrompts[selectedPath[selectedPath.length-1].id] ? (\n \n \n Saved\n \n ) : (\n handleSavePrompt(selectedPath[selectedPath.length-1].id, e)}\n disabled={savingPrompt === selectedPath[selectedPath.length-1].id}\n className={`inline-flex items-center px-3 py-1 border border-transparent text-xs font-medium rounded-md ${\n savingPrompt === selectedPath[selectedPath.length-1].id\n ? 'text-gray-500 bg-gray-100'\n : 'text-blue-700 bg-blue-100 hover:bg-blue-200'\n }`}\n title=\"Save this prompt to your topic\"\n >\n {savingPrompt === selectedPath[selectedPath.length-1].id ? (\n <>\n \n Saving...\n \n ) : (\n <>\n \n Save\n \n )}\n \n )\n )}\n
\n
\n )}\n
\n
\n\n {/* Table header with status info */}\n
\n

\n {selectedPath.length === 0\n ? \"Entry Point Prompts for Topic\"\n : `Follow-up Prompts`}\n

\n\n
\n\n {/* Table Section */}\n
\n \n \n \n handleSort('prompt_text')}\n >\n \n Prompt {getSortIcon('prompt_text')}\n \n \n handleSort('percentage')}\n >\n \n Frequency {getSortIcon('percentage')}\n \n \n \n \n \n \n {sortedPrompts.length === 0 ? (\n \n \n \n ) : (\n sortedPrompts.map(prompt => (\n handlePromptClick(prompt.id)}\n >\n \n \n \n \n ))\n )}\n \n
\n Actions\n
\n {showLoadingIndicator || initialPromptLoading ? (\n
\n
\n

Loading prompts... This may take a few moments.

\n
\n ) : (\n
\n \n

No prompts available for this level.

\n

This may be the end of the conversation path.

\n
\n )}\n
\n
\n
\n

{prompt.prompt_text}

\n
\n
\n
\n
\n
\n {formatPercentage(prompt.percentage)}\n
\n
\n = 70 ? 0.9 :\n parseFloat(prompt.percentage) >= 40 ? 0.7 : 0.5\n }}\n >
\n
\n \n
\n
\n {/* Next button */}\n {\n e.stopPropagation();\n handlePromptClick(prompt.id);\n }}\n className=\"inline-flex items-center px-3 py-1 border border-transparent text-xs font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200\"\n title=\"View follow-up prompts\"\n >\n \n Next\n \n
\n
\n
\n\n {/* Footer Section with action buttons */}\n
\n {selectedPath.length > 0 && (\n setSelectedPath(selectedPath.slice(0, -1))}\n className=\"inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50\"\n >\n \n Back to Previous Level\n \n )}\n\n {/* Manual refresh button - only show when there's an error */}\n {error && (\n \n \n Refresh Data\n \n )}\n
\n
\n );\n};\n\nexport default ConversationExplorer;", "import React, { useState, useEffect, useCallback, useContext } from 'react';\nimport { TrendingUp, Plus, Search, Filter, X, RefreshCw, Eye, ChevronRight, ChevronLeft, Info, EyeOff } from 'lucide-react';\nimport axios from '../../AxiosConfig';\nimport OpportunityDetailsSidepanel from './OpportunityContext/OpportunityDetailsSidepanel';\nimport { AuthContext } from '../../../context/AuthContext';\nimport { trackEvent } from '../../Analytics/mixpanel';\n\nconst Opportunities = ({ projectId, project }) => {\n const [opportunities, setOpportunities] = useState([]);\n const [loading, setLoading] = useState(true);\n const [searchTerm, setSearchTerm] = useState('');\n const [debouncedSearchTerm, setDebouncedSearchTerm] = useState('');\n const [objectiveFilter, setObjectiveFilter] = useState('');\n const [impactFilter, setImpactFilter] = useState('');\n const [effortFilter, setEffortFilter] = useState('');\n const [dateFilter, setDateFilter] = useState('');\n const [showHidden, setShowHidden] = useState(false);\n const [updatingStrategy, setUpdatingStrategy] = useState(new Set());\n const [updatingHidden, setUpdatingHidden] = useState(new Set());\n const [showObjectiveTooltip, setShowObjectiveTooltip] = useState(false);\n\n // Pagination state\n const [currentPage, setCurrentPage] = useState(1);\n const [totalItems, setTotalItems] = useState(0);\n const [totalPages, setTotalPages] = useState(1);\n const [itemsPerPage] = useState(20);\n\n // Side panel state\n const [selectedOpportunity, setSelectedOpportunity] = useState(null);\n const [sidepanelOpen, setSidepanelOpen] = useState(false);\n\n // Custom opportunity modal state\n const [showCustomModal, setShowCustomModal] = useState(false);\n const [customOpportunity, setCustomOpportunity] = useState({\n title: '',\n description: '',\n objective: '',\n level_of_effort: 'Medium',\n impact: 'Medium'\n });\n const [creatingCustom, setCreatingCustom] = useState(false);\n\n // Auth context for user info\n const { user } = useContext(AuthContext);\n\n // Track page view on mount\n useEffect(() => {\n trackEvent('Opportunities Page Viewed', {\n project_id: projectId,\n user_id: user?.id,\n source: 'opportunities'\n });\n }, [projectId]);\n\n // Debounce search term\n useEffect(() => {\n const timer = setTimeout(() => {\n setDebouncedSearchTerm(searchTerm);\n if (searchTerm !== debouncedSearchTerm) {\n setCurrentPage(1);\n }\n }, 300);\n\n return () => clearTimeout(timer);\n }, [searchTerm]);\n\n // Track search when debounced value changes (if meaningful)\n useEffect(() => {\n if (debouncedSearchTerm.length > 2) {\n trackEvent('Opportunities Search Used', {\n project_id: projectId,\n user_id: user?.id,\n search_query_length: debouncedSearchTerm.length,\n source: 'opportunities'\n });\n }\n }, [debouncedSearchTerm]);\n\n const objectives = [\n 'Visibility',\n 'Competitors',\n 'Sentiment',\n 'Citations',\n 'Content Coverage',\n 'AI Readability',\n 'Technical'\n ];\n\n // Objective descriptions for tooltip\n const objectiveDescriptions = {\n 'Visibility': 'Improve how often your brand appears in AI-generated responses to relevant queries.',\n 'Competitors': 'Analyze and respond to competitor presence in AI search results.',\n 'Sentiment': 'Address negative mentions or misinformation about your brand in AI responses.',\n 'Citations': 'Increase how frequently your content is cited as a source by AI systems.',\n 'Content Coverage': 'Expand your content to cover important topics where you\\'re currently absent.',\n 'AI Readability': 'Optimize your content structure to be better understood and parsed by AI systems.',\n 'Technical': 'Improve technical performance factors that affect AI content discovery and ranking.'\n };\n\n const impacts = ['Critical', 'High', 'Medium', 'Low'];\n const efforts = ['High', 'Medium', 'Low'];\n\n const dateFilters = [\n { value: '', label: 'All Time' },\n { value: 'today', label: 'Today' },\n { value: 'week', label: 'Last 7 Days' },\n { value: 'month', label: 'Last 30 Days' }\n ];\n\n const getImpactColor = (impact) => {\n const colors = {\n 'Critical': { backgroundColor: '#FFF1F2', color: '#DC2626' },\n 'High': { backgroundColor: '#ECFDF5', color: '#007A55' },\n 'Medium': { backgroundColor: '#FFFBEB', color: '#BB4D00' },\n 'Low': { backgroundColor: '#F0F9FF', color: '#0069A8' }\n };\n return colors[impact] || { backgroundColor: '#F3F4F6', color: '#374151' };\n };\n\n const getEffortColor = (effort) => {\n const colors = {\n 'High': 'bg-red-100 text-red-800',\n 'Medium': 'bg-yellow-100 text-yellow-800',\n 'Low': 'bg-green-100 text-green-800'\n };\n return colors[effort] || 'bg-gray-100 text-gray-800';\n };\n\n const getObjectiveColor = (objective) => {\n return 'bg-gray-100 text-gray-800';\n };\n\n const formatDate = (dateString) => {\n const date = new Date(dateString);\n return date.toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n year: 'numeric'\n });\n };\n\n const formatDateTime = (dateString) => {\n const date = new Date(dateString);\n const now = new Date();\n\n const dateOnly = new Date(date.getFullYear(), date.getMonth(), date.getDate());\n const nowOnly = new Date(now.getFullYear(), now.getMonth(), now.getDate());\n\n const diffInDays = Math.floor((nowOnly - dateOnly) / (1000 * 60 * 60 * 24));\n\n if (diffInDays === 0) {\n return 'Today';\n } else if (diffInDays === 1) {\n return 'Yesterday';\n } else if (diffInDays < 7) {\n return `${diffInDays} days ago`;\n } else {\n return formatDate(dateString);\n }\n };\n\n const formatOpportunityTitle = (opportunity) => {\n let title = opportunity.title;\n\n const boldResource = (text, resource) => {\n if (!resource) return text;\n const regex = new RegExp(`(${resource.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')})`, 'gi');\n return text.replace(regex, '$1');\n };\n\n if (opportunity.topic?.name) {\n title = boldResource(title, opportunity.topic.name);\n }\n\n if (opportunity.company?.name) {\n title = boldResource(title, opportunity.company.name);\n }\n\n if (opportunity.link?.url) {\n title = boldResource(title, opportunity.link.url);\n }\n\n if (opportunity.domain?.domain) {\n title = boldResource(title, opportunity.domain.domain);\n }\n\n if (opportunity.theme?.description) {\n title = boldResource(title, opportunity.theme.description);\n }\n\n if (opportunity.prompt?.prompt) {\n const shortPrompt = opportunity.prompt.prompt.substring(0, 50);\n title = boldResource(title, shortPrompt);\n }\n\n return title;\n };\n\n const fetchOpportunities = async () => {\n try {\n setLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/audit_category_opportunities`, {\n params: {\n search: debouncedSearchTerm,\n objective: objectiveFilter,\n impact: impactFilter,\n level_of_effort: effortFilter,\n date_filter: dateFilter,\n include_hidden: showHidden,\n page: currentPage,\n per_page: itemsPerPage\n }\n });\n\n setOpportunities(response.data.opportunities || response.data);\n setTotalItems(response.data.total_count || response.data.length || 0);\n setTotalPages(response.data.total_pages || Math.ceil((response.data.total_count || response.data.length || 0) / itemsPerPage));\n } catch (error) {\n console.error('Error fetching opportunities:', error);\n } finally {\n setLoading(false);\n }\n };\n\n useEffect(() => {\n if (projectId) {\n fetchOpportunities();\n }\n }, [projectId, debouncedSearchTerm, objectiveFilter, impactFilter, effortFilter, dateFilter, showHidden, currentPage]);\n\n const handlePageChange = (newPage) => {\n if (newPage >= 1 && newPage <= totalPages) {\n trackEvent('Opportunities Page Changed', {\n project_id: projectId,\n user_id: user?.id,\n previous_page: currentPage,\n new_page: newPage,\n total_pages: totalPages,\n source: 'opportunities'\n });\n setCurrentPage(newPage);\n }\n };\n\n const resetToFirstPage = () => {\n setCurrentPage(1);\n };\n\n const handleFilterChange = (filterType, value) => {\n trackEvent('Opportunities Filter Applied', {\n project_id: projectId,\n user_id: user?.id,\n filter_type: filterType,\n filter_value: value || 'all',\n source: 'opportunities'\n });\n\n switch (filterType) {\n case 'objective':\n setObjectiveFilter(value);\n break;\n case 'impact':\n setImpactFilter(value);\n break;\n case 'effort':\n setEffortFilter(value);\n break;\n case 'date':\n setDateFilter(value);\n break;\n }\n setCurrentPage(1);\n };\n\n const handleToggleShowHidden = () => {\n const newValue = !showHidden;\n trackEvent('Opportunities Show Hidden Toggled', {\n project_id: projectId,\n user_id: user?.id,\n show_hidden: newValue,\n source: 'opportunities'\n });\n setShowHidden(newValue);\n setCurrentPage(1);\n };\n\n const handleAddToStrategy = async (opportunityId) => {\n const opportunity = opportunities.find(opp => opp.id === opportunityId);\n\n trackEvent('Opportunity Added To Strategy', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunityId,\n opportunity_title: opportunity?.title,\n opportunity_objective: opportunity?.objective,\n opportunity_impact: opportunity?.impact,\n opportunity_effort: opportunity?.level_of_effort,\n source: 'opportunities'\n });\n\n try {\n setUpdatingStrategy(prev => new Set(prev).add(opportunityId));\n await axios.patch(`/api/projects/${projectId}/audit_category_opportunities/${opportunityId}`, {\n added_to_strategy: true\n });\n setOpportunities(prevOpportunities =>\n prevOpportunities.map(opp =>\n opp.id === opportunityId\n ? { ...opp, added_to_strategy: true }\n : opp\n )\n );\n } catch (error) {\n console.error('Error adding opportunity to strategy:', error);\n } finally {\n setUpdatingStrategy(prev => {\n const newSet = new Set(prev);\n newSet.delete(opportunityId);\n return newSet;\n });\n }\n };\n\n const handleToggleHidden = async (opportunityId, nextHiddenValue) => {\n const opportunity = opportunities.find(opp => opp.id === opportunityId);\n\n trackEvent(nextHiddenValue ? 'Opportunity Hidden' : 'Opportunity Unhidden', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunityId,\n opportunity_title: opportunity?.title,\n opportunity_objective: opportunity?.objective,\n opportunity_impact: opportunity?.impact,\n source: 'opportunities'\n });\n\n try {\n setUpdatingHidden(prev => new Set(prev).add(opportunityId));\n await axios.patch(`/api/projects/${projectId}/audit_category_opportunities/${opportunityId}`, {\n hidden: nextHiddenValue\n });\n\n // Remove the row from the current view \u2014 it will be re-included\n // the next time the user toggles \"Show hidden\" appropriately.\n setOpportunities(prevOpportunities =>\n prevOpportunities.filter(opp => opp.id !== opportunityId)\n );\n setTotalItems(prev => Math.max(prev - 1, 0));\n } catch (error) {\n console.error('Error toggling hidden state:', error);\n } finally {\n setUpdatingHidden(prev => {\n const newSet = new Set(prev);\n newSet.delete(opportunityId);\n return newSet;\n });\n }\n };\n\n const handleViewDetails = (opportunity) => {\n trackEvent('Opportunity Details Viewed', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunity.id,\n opportunity_title: opportunity.title,\n opportunity_objective: opportunity.objective,\n opportunity_impact: opportunity.impact,\n opportunity_effort: opportunity.level_of_effort,\n added_to_strategy: opportunity.added_to_strategy,\n source: 'opportunities'\n });\n\n setSelectedOpportunity(opportunity);\n setSidepanelOpen(true);\n };\n\n const handleCloseSidepanel = () => {\n trackEvent('Opportunity Details Closed', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: selectedOpportunity?.id,\n source: 'opportunities'\n });\n\n setSidepanelOpen(false);\n setSelectedOpportunity(null);\n };\n\n const clearFilters = () => {\n trackEvent('Opportunities Filters Cleared', {\n project_id: projectId,\n user_id: user?.id,\n had_search: !!searchTerm,\n had_objective_filter: !!objectiveFilter,\n had_impact_filter: !!impactFilter,\n had_effort_filter: !!effortFilter,\n had_date_filter: !!dateFilter,\n source: 'opportunities'\n });\n\n setSearchTerm('');\n setDebouncedSearchTerm('');\n setObjectiveFilter('');\n setImpactFilter('');\n setEffortFilter('');\n setDateFilter('');\n setShowHidden(false);\n setCurrentPage(1);\n };\n\n const handleOpenCustomModal = () => {\n trackEvent('Custom Opportunity Modal Opened', {\n project_id: projectId,\n user_id: user?.id,\n source: 'opportunities'\n });\n setShowCustomModal(true);\n };\n\n const handleCustomModalClose = () => {\n trackEvent('Custom Opportunity Modal Closed', {\n project_id: projectId,\n user_id: user?.id,\n had_content: !!(customOpportunity.title || customOpportunity.description),\n source: 'opportunities'\n });\n\n setShowCustomModal(false);\n setCustomOpportunity({\n title: '',\n description: '',\n objective: '',\n level_of_effort: 'Medium',\n impact: 'Medium'\n });\n };\n\n const handleCustomOpportunityChange = (field, value) => {\n setCustomOpportunity(prev => ({\n ...prev,\n [field]: value\n }));\n };\n\n const handleCreateCustomOpportunity = async () => {\n trackEvent('Custom Opportunity Created', {\n project_id: projectId,\n user_id: user?.id,\n title_length: customOpportunity.title.length,\n description_length: customOpportunity.description.length,\n objective: customOpportunity.objective,\n impact: customOpportunity.impact,\n level_of_effort: customOpportunity.level_of_effort,\n source: 'opportunities'\n });\n\n try {\n setCreatingCustom(true);\n const response = await axios.post(`/api/projects/${projectId}/audit_category_opportunities`, {\n title: customOpportunity.title,\n description: customOpportunity.description,\n objective: customOpportunity.objective,\n level_of_effort: customOpportunity.level_of_effort,\n impact: customOpportunity.impact\n });\n\n setOpportunities(prev => [response.data, ...prev]);\n handleCustomModalClose();\n } catch (error) {\n console.error('Error creating custom opportunity:', error);\n } finally {\n setCreatingCustom(false);\n }\n };\n\n const isCustomFormValid = customOpportunity.title.trim() &&\n customOpportunity.description.trim() &&\n customOpportunity.objective &&\n customOpportunity.level_of_effort &&\n customOpportunity.impact;\n\n const filteredOpportunities = opportunities;\n\n return (\n
\n {/* Header Section */}\n
\n
\n
\n

\n Opportunities\n

\n

\n Review Visto-suggested and custom opportunities to identify what needs improvement. Save opportunities as goals to work on them in your strategy.\n

\n
\n \n \n Add custom goal\n \n
\n
\n\n {/* Filters Section */}\n
\n
\n {/* Search Filter */}\n
\n
\n \n setSearchTerm(e.target.value)}\n />\n
\n
\n\n {/* Objectives Filter */}\n
\n handleFilterChange('objective', e.target.value)}\n >\n \n {objectives.map(objective => (\n \n ))}\n \n
\n\n {/* Impact Filter */}\n
\n handleFilterChange('impact', e.target.value)}\n >\n \n {impacts.map(impact => (\n \n ))}\n \n
\n\n {/* Effort Filter */}\n
\n handleFilterChange('effort', e.target.value)}\n >\n \n {efforts.map(effort => (\n \n ))}\n \n
\n\n {/* Date Filter */}\n
\n handleFilterChange('date', e.target.value)}\n >\n {dateFilters.map(filter => (\n \n ))}\n \n
\n\n {/* Show Hidden Toggle */}\n \n\n {/* Clear Filters */}\n \n \n Clear filters\n \n
\n
\n\n {/* Total count display */}\n
\n
\n Showing {totalItems > 0 ? Math.min((currentPage - 1) * itemsPerPage + 1, totalItems) : 0}-{Math.min(currentPage * itemsPerPage, totalItems)} of {totalItems} {showHidden ? 'hidden ' : ''}opportunities\n
\n
\n\n {/* Results Table Section */}\n
\n {loading ? (\n
\n
\n

Loading opportunities...

\n
\n ) : filteredOpportunities.length === 0 ? (\n
\n \n

No opportunities found

\n

\n {showHidden\n ? 'No hidden opportunities. Use the hide button on any opportunity to move it here.'\n : searchTerm || objectiveFilter || impactFilter || effortFilter || dateFilter\n ? 'Try adjusting your filters to see more results.'\n : 'Complete your project analysis to see optimization opportunities.'}\n

\n
\n ) : (\n
\n \n \n \n \n \n \n \n \n \n \n \n \n {filteredOpportunities.map((opportunity) => {\n const isHiddenRow = showHidden;\n const isUpdatingHide = updatingHidden.has(opportunity.id);\n\n return (\n \n \n \n \n \n \n \n \n );\n })}\n \n
\n Opportunity\n \n
\n Objective\n
\n setShowObjectiveTooltip(true)}\n onMouseLeave={() => setShowObjectiveTooltip(false)}\n />\n {showObjectiveTooltip && (\n
\n
\n {objectives.map((objective) => (\n
\n {objective}:{' '}\n {objectiveDescriptions[objective]}\n
\n ))}\n
\n
\n )}\n
\n
\n
\n Impact\n \n Effort\n \n Created\n \n Actions\n
\n \n \n \n {opportunity.objective}\n \n \n \n {opportunity.impact}\n \n \n \n {opportunity.level_of_effort}\n \n \n
\n {formatDateTime(opportunity.created_at)}\n
\n
\n
\n handleViewDetails(opportunity)}\n className=\"inline-flex items-center px-2.5 py-1.5 border border-gray-300 text-xs font-medium rounded text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\"\n >\n \n View\n \n\n {!isHiddenRow && (\n opportunity.added_to_strategy ? (\n \n In strategy\n \n ) : (\n handleAddToStrategy(opportunity.id)}\n disabled={updatingStrategy.has(opportunity.id)}\n className=\"inline-flex items-center px-3 py-1.5 border border-gray-300 text-xs font-medium rounded text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50\"\n >\n \n {updatingStrategy.has(opportunity.id) ? 'Adding...' : 'Add to strategy'}\n \n )\n )}\n\n {isHiddenRow ? (\n handleToggleHidden(opportunity.id, false)}\n disabled={isUpdatingHide}\n className=\"inline-flex items-center px-2.5 py-1.5 border border-gray-300 text-xs font-medium rounded text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50\"\n title=\"Unhide this opportunity\"\n >\n \n {isUpdatingHide ? 'Unhiding...' : 'Unhide'}\n \n ) : (\n handleToggleHidden(opportunity.id, true)}\n disabled={isUpdatingHide}\n className=\"inline-flex items-center px-2.5 py-1.5 border border-gray-300 text-xs font-medium rounded text-gray-500 bg-white hover:bg-gray-50 hover:text-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50\"\n title=\"Hide this opportunity from view\"\n >\n \n {isUpdatingHide ? 'Hiding...' : 'Hide'}\n \n )}\n
\n
\n
\n )}\n
\n\n {/* Pagination Controls */}\n {totalPages > 1 && (\n
\n
\n
\n

\n Showing {totalItems > 0 ? Math.min((currentPage - 1) * itemsPerPage + 1, totalItems) : 0} to{' '}\n {Math.min(currentPage * itemsPerPage, totalItems)} of{' '}\n {totalItems} results\n

\n
\n
\n \n
\n
\n
\n )}\n\n {/* Custom Opportunity Modal */}\n {showCustomModal && (\n
\n
\n
\n
\n
\n\n ​\n\n
\n
\n
\n
\n

Create Custom Opportunity

\n

\n Add a new opportunity with a title, description, objective, impact level, and effort level.\n

\n\n
\n {/* Title Field */}\n
\n \n handleCustomOpportunityChange('title', e.target.value)}\n />\n
\n\n {/* Details Field */}\n
\n \n handleCustomOpportunityChange('description', e.target.value)}\n />\n
\n\n {/* Objective Field */}\n
\n \n handleCustomOpportunityChange('objective', e.target.value)}\n >\n \n {objectives.map(objective => (\n \n ))}\n \n
\n\n {/* Impact Field */}\n
\n \n handleCustomOpportunityChange('impact', e.target.value)}\n >\n {impacts.map(impact => (\n \n ))}\n \n
\n\n {/* Level of Effort Field */}\n
\n \n handleCustomOpportunityChange('level_of_effort', e.target.value)}\n >\n {efforts.map(effort => (\n \n ))}\n \n
\n
\n
\n
\n
\n
\n \n {creatingCustom ? 'Creating...' : 'Create Opportunity'}\n \n \n Cancel\n \n
\n
\n
\n
\n )}\n\n {/* Opportunity Details Sidepanel */}\n \n
\n );\n};\n\nexport default Opportunities;", "import React, { useEffect, useState } from 'react';\nimport { X, Loader2 } from 'lucide-react';\nimport axios from '../../../AxiosConfig';\nimport OpportunityContextContainer from './OpportunityContextContainer';\n\nconst OpportunityDetailsSidepanel = ({ isOpen, onClose, opportunity, projectId }) => {\n const [isVisible, setIsVisible] = useState(false);\n const [shouldRender, setShouldRender] = useState(false);\n const [fullOpportunity, setFullOpportunity] = useState(null);\n const [loadingDetails, setLoadingDetails] = useState(false);\n\n useEffect(() => {\n if (isOpen && opportunity) {\n setShouldRender(true);\n setFullOpportunity(null);\n setTimeout(() => setIsVisible(true), 10);\n\n // Fetch full opportunity details (with context_data and action_tasks)\n fetchOpportunityDetails(opportunity.id);\n } else {\n setIsVisible(false);\n const timer = setTimeout(() => {\n setShouldRender(false);\n setFullOpportunity(null);\n }, 300);\n return () => clearTimeout(timer);\n }\n }, [isOpen, opportunity]);\n\n const fetchOpportunityDetails = async (opportunityId) => {\n try {\n setLoadingDetails(true);\n const response = await axios.get(\n `/api/projects/${projectId}/audit_category_opportunities/${opportunityId}`\n );\n setFullOpportunity(response.data);\n } catch (error) {\n console.error('Error fetching opportunity details:', error);\n } finally {\n setLoadingDetails(false);\n }\n };\n\n if (!shouldRender) return null;\n\n // Use full opportunity data when available, fall back to list data for immediate display\n const displayOpportunity = fullOpportunity || opportunity;\n\n const getImpactColor = (impact) => {\n const colors = {\n 'Critical': { backgroundColor: '#FFF1F2', color: '#DC2626' },\n 'High': { backgroundColor: '#ECFDF5', color: '#007A55' },\n 'Medium': { backgroundColor: '#FFFBEB', color: '#BB4D00' },\n 'Low': { backgroundColor: '#F0F9FF', color: '#0069A8' }\n };\n return colors[impact] || { backgroundColor: '#F3F4F6', color: '#374151' };\n };\n\n const getObjectiveColor = (objective) => {\n return 'bg-white border border-gray-300 text-gray-800';\n };\n\n const formatDate = (dateString) => {\n const date = new Date(dateString);\n return date.toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n year: 'numeric'\n });\n };\n\n return (\n
\n {/* Backdrop */}\n \n\n {/* Side Drawer */}\n \n {/* Header */}\n
\n

\n {displayOpportunity?.title}\n

\n \n \n \n
\n\n {/* Objective and Impact - closer to title */}\n
\n
\n \n {displayOpportunity?.objective}\n \n \n {displayOpportunity?.impact}\n \n {displayOpportunity?.added_to_strategy && (\n \n In strategy\n \n )}\n
\n
\n\n {/* Full Width Grey Border */}\n
\n\n
\n {/* Details Section */}\n
\n

Details

\n\n
\n {/* Added On Row */}\n
\n Added on\n {displayOpportunity?.created_at ? formatDate(displayOpportunity.created_at) : ''}\n
\n\n {/* Description Row */}\n
\n
\n Description\n
\n

\n {displayOpportunity?.description}\n

\n
\n
\n
\n
\n
\n\n {/* Analytics Context Section */}\n
\n

Analytics Context

\n {loadingDetails ? (\n
\n \n Loading analytics context...\n
\n ) : fullOpportunity ? (\n \n ) : (\n
\n No analytics context available\n
\n )}\n
\n
\n
\n
\n );\n};\n\nexport default OpportunityDetailsSidepanel;", "import React from 'react';\nimport VisibilityPromptContext from './VisibilityPromptContext';\nimport VisibilityTopicContext from './VisibilityTopicContext';\nimport CompetitorTopicContext from './CompetitorTopicContext';\nimport CompetitorCompanyContext from './CompetitorCompanyContext';\nimport ContentCoverageTopicContext from './ContentCoverageTopicContext';\nimport OnPageLinkContext from './OnPageLinkContext';\nimport OnPageLogicFlowContext from './OnPageLogicFlowContext';\nimport OnPageEntityMappingContext from './OnPageEntityMappingContext';\nimport OnPageClaimClarityContext from './OnPageClaimClarityContext';\nimport OnPageSchemaMarkupContext from './OnPageSchemaMarkupContext';\nimport OnPageInformationArchitectureContext from './OnPageInformationArchitectureContext';\nimport TechnicalLinkContext from './TechnicalLinkContext';\nimport TechnicalLoadTimeContext from './TechnicalLoadTimeContext';\nimport TechnicalFrontLoadingContext from './TechnicalFrontLoadingContext';\nimport TechnicalInformationDensityContext from './TechnicalInformationDensityContext';\nimport CitationRateTopicContext from './CitationRateTopicContext';\nimport CitationThirdPartyContext from './CitationThirdPartyContext';\nimport SentimentPromptContext from './SentimentPromptContext';\nimport SentimentThemeContext from './SentimentThemeContext';\nimport UserGeneratedContext from './UserGeneratedContext';\n\nconst OpportunityContextContainer = ({ opportunity, projectId }) => {\n if (!opportunity || opportunity.opportunity_type === null || opportunity.opportunity_type === undefined){\n return (\n
\n No context data available for this opportunity type.\n
\n );\n }\n\n // Helper function to check if opportunity type is ON_PAGE\n const isOnPageType = (type) => {\n const onPageTypes = [\n 'on_page_link', 5,\n 'on_page_logic_flow', 6,\n 'on_page_entity_mapping', 7,\n 'on_page_claim_clarity', 8,\n 'on_page_schema_markup', 9,\n 'on_page_information_architecture', 10\n ];\n return onPageTypes.includes(type);\n };\n\n // Helper function to check if opportunity type is TECHNICAL\n const isTechnicalType = (type) => {\n const technicalTypes = [\n 'technical_link', 11,\n 'technical_load_time', 12,\n 'technical_front_loading', 13,\n 'technical_information_density', 14\n ];\n return technicalTypes.includes(type);\n };\n\n // Map opportunity types to their respective context components\n const getContextComponent = () => {\n // Check for ON_PAGE types - prioritize link-specific context if link exists\n if (isOnPageType(opportunity.opportunity_type)) {\n if (opportunity.link) {\n return ;\n } else {\n // Route to domain-wide analysis based on specific type\n switch (opportunity.opportunity_type) {\n case 'on_page_logic_flow':\n case 6:\n return ;\n case 'on_page_entity_mapping':\n case 7:\n return ;\n case 'on_page_claim_clarity':\n case 8:\n return ;\n case 'on_page_schema_markup':\n case 9:\n return ;\n case 'on_page_information_architecture':\n case 10:\n return ;\n default:\n // Default fallback for ON_PAGE types\n return ;\n }\n }\n }\n\n // Check for TECHNICAL types - prioritize link-specific context if link exists\n if (isTechnicalType(opportunity.opportunity_type)) {\n if (opportunity.link) {\n return ;\n } else {\n // Route to domain-wide analysis based on specific type\n switch (opportunity.opportunity_type) {\n case 'technical_load_time':\n case 12:\n return ;\n case 'technical_front_loading':\n case 13:\n return ;\n case 'technical_information_density':\n case 14:\n return ;\n default:\n // Default fallback for TECHNICAL types\n return ;\n }\n }\n }\n\n // Handle all other opportunity types (non-ON_PAGE, non-TECHNICAL)\n switch (opportunity.opportunity_type) {\n // Visibility types\n case 'visibility_prompt':\n case 0:\n return ;\n\n case 'visibility_topic':\n case 1:\n return ;\n\n // Competitor types\n case 'competitor_topic':\n case 2:\n return ;\n\n case 'competitor_company':\n case 3:\n return ;\n\n // Content coverage types\n case 'content_coverage_topic':\n case 4:\n return ;\n\n // Citation types\n case 'citation_rate_topic':\n case 15:\n return ;\n\n case 'citation_third_party':\n case 16:\n return ;\n\n // Sentiment types\n case 'sentiment_prompt':\n case 17:\n return ;\n\n case 'sentiment_theme':\n case 18:\n return ;\n\n default:\n return (\n
\n Context data not yet available for opportunity type: {opportunity.opportunity_type}\n
\n );\n }\n };\n\n return (\n
\n {getContextComponent()}\n
\n );\n};\n\nexport default OpportunityContextContainer;", "import React from 'react';\nimport { MessageSquare, CheckCircle, XCircle, Eye, BarChart3 } from 'lucide-react';\n\nconst VisibilityPromptContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No visibility data available for this prompt

\n
\n );\n }\n\n const getPlatformIcon = (platform) => {\n const icons = {\n 'ChatGPT': '\uD83E\uDD16',\n 'Perplexity': '\uD83D\uDD0D',\n 'Google AI Overview': '\uD83D\uDD0E'\n };\n return icons[platform] || '\uD83E\uDD16';\n };\n\n const getPlatformColor = (hasVisibility) => {\n return hasVisibility\n ? 'bg-green-50 text-green-700 border-green-200'\n : 'bg-red-50 text-red-700 border-red-200';\n };\n\n // Filter to only show supported platforms\n const supportedPlatforms = ['ChatGPT', 'Perplexity', 'Google AI Overview'];\n const filteredPlatformVisibility = contextData.platform_visibility?.filter(platform =>\n supportedPlatforms.includes(platform.platform_name)\n ) || [];\n\n return (\n
\n
\n \n

Prompt Visibility Analysis

\n
\n\n {/* Prompt Info */}\n
\n
Analyzed Prompt
\n
\"{contextData.prompt_text}\"
\n
\n Topic: {contextData.topic_name} | Volume: {contextData.volume_estimate || 'Unknown'}\n
\n
\n\n {/* Platform Visibility Summary - Only supported platforms */}\n
\n
\n \n Platform Visibility Summary\n
\n\n
\n {filteredPlatformVisibility.map((platform, index) => (\n \n
\n {getPlatformIcon(platform.platform_name)}\n {platform.has_customer_visibility ?\n :\n \n }\n
\n
{platform.platform_name}
\n
\n {platform.has_customer_visibility ? 'Visible' : 'Not visible'}\n
\n
\n ))}\n
\n
\n\n {/* Visibility Metrics */}\n
\n
Visibility Metrics
\n
\n
\n
\n {contextData.total_responses || 0}\n
\n
Total Responses
\n
\n
\n
\n {contextData.customer_mentions || 0}\n
\n
Customer Mentions
\n
\n
\n\n
\n
\n {contextData.visibility_percentage?.toFixed(1) || 0}%\n
\n
Overall Visibility Rate
\n
\n
\n\n {/* Opportunity Summary */}\n {contextData.visibility_percentage < 25 && (\n
\n
\n
\n \n Low Visibility Alert\n
\n

\n This prompt has low visibility across platforms. Consider content optimization\n to improve presence in AI search results.\n

\n
\n
\n )}\n \n );\n};\n\nexport default VisibilityPromptContext;", "import React from 'react';\nimport { Hash, Eye, TrendingUp, AlertTriangle } from 'lucide-react';\n\nconst VisibilityTopicContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No visibility data available for this topic

\n
\n );\n }\n\n const getVisibilityColor = (percentage) => {\n if (percentage >= 75) return 'text-green-600 bg-green-50';\n if (percentage >= 50) return 'text-yellow-600 bg-yellow-50';\n if (percentage >= 25) return 'text-orange-600 bg-orange-50';\n return 'text-red-600 bg-red-50';\n };\n\n const getVisibilityStatus = (percentage) => {\n if (percentage >= 75) return 'Excellent';\n if (percentage >= 50) return 'Good';\n if (percentage >= 25) return 'Fair';\n return 'Poor';\n };\n\n return (\n
\n
\n \n

Topic Visibility Analysis

\n
\n\n {/* Topic Info */}\n
\n
Analyzed Topic
\n
{contextData.topic_name}
\n
\n Relevancy Score: {contextData.topic_score || 0}/100 | {contextData.prompts_count || 0} prompts\n
\n
\n\n {/* Overall Topic Visibility */}\n
\n
Overall Topic Visibility
\n
\n
\n {contextData.overall_visibility_percentage?.toFixed(1) || 0}%\n
\n
\n {getVisibilityStatus(contextData.overall_visibility_percentage || 0)}\n
\n
\n
\n {contextData.customer_mentions || 0} mentions out of {contextData.total_responses || 0} responses\n
\n
\n\n {/* Prompt Visibility Breakdown */}\n
\n
\n \n Prompt Visibility Breakdown\n
\n\n
\n {contextData.prompt_visibility?.map((prompt, index) => (\n
\n
\n
\n Prompt {index + 1}\n
\n
\n {prompt.visibility_percentage?.toFixed(1) || 0}%\n
\n
\n
\n \"{prompt.prompt_text}\"\n
\n
\n {prompt.customer_mentions || 0}/{prompt.total_responses || 0} responses\n {prompt.visibility_percentage === 0 && (\n \u2022 Zero visibility\n )}\n
\n
\n )) || []}\n
\n\n {contextData.prompts_with_zero_visibility > 0 && (\n
\n
\n \n \n {contextData.prompts_with_zero_visibility} prompts have zero visibility\n \n
\n
\n )}\n
\n\n {/* Improvement Opportunity */}\n
\n
\n
\n \n Optimization Potential\n
\n

\n {contextData.overall_visibility_percentage < 50\n ? 'High potential for visibility improvement through content optimization.'\n : contextData.prompts_with_zero_visibility > 0\n ? 'Focus on zero-visibility prompts for maximum impact.'\n : 'Good visibility - consider fine-tuning for competitive advantage.'\n }\n

\n
\n
\n
\n );\n};\n\nexport default VisibilityTopicContext;", "import React from 'react';\nimport { Target, CheckCircle, XCircle, AlertCircle } from 'lucide-react';\n\nconst CompetitorTopicContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No competitor data available for this topic

\n
\n );\n }\n\n return (\n
\n
\n \n

Topic Competitor Analysis

\n
\n\n {/* Topic Info */}\n
\n
Analyzed Topic
\n
{contextData.topic_name}
\n
\n Relevancy Score: {contextData.topic_score || 0}/100 | {contextData.competitor_count || 0} competitors\n
\n
\n\n {/* Summary */}\n
\n
Competition Overview
\n
\n
\n
\n {contextData.customer_name || 'Your Company'}\n
\n
Client
\n
\n
\n
\n {contextData.competitor_count || 0}\n
\n
Active Competitors
\n
\n
\n
\n\n {/* Prompt Analysis */}\n
\n
Prompt-by-Prompt Analysis
\n
\n {contextData.prompt_analysis?.map((prompt, index) => (\n
\n
\n
\n Prompt {index + 1}\n
\n
\n
\n {prompt.customer_visible ?\n :\n \n }\n Client\n
\n
\n {prompt.competitors_visible ?\n :\n \n }\n Competitors\n
\n
\n
\n
\n \"{prompt.prompt_text}\"\n
\n
\n {prompt.total_responses} responses\n {!prompt.customer_visible && prompt.competitors_visible && (\n \u2022 Competitor advantage\n )}\n
\n
\n )) || []}\n
\n\n {/* Opportunity Summary */}\n {contextData.prompt_analysis?.some(p => !p.customer_visible && p.competitors_visible) && (\n
\n
\n \n Competitive Gap Detected\n
\n

\n Competitors are visible on prompts where your company is not mentioned.\n Consider content optimization to improve competitive positioning.\n

\n
\n )}\n
\n
\n );\n};\n\nexport default CompetitorTopicContext;", "import React from 'react';\nimport { Building2, CheckCircle, XCircle, AlertTriangle } from 'lucide-react';\n\nconst CompetitorCompanyContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No competitor company data available

\n
\n );\n }\n\n return (\n
\n
\n \n

Competitor Company Analysis

\n
\n\n {/* Competitor Info */}\n
\n
Target Competitor
\n
{contextData.competitor_name}
\n
\n vs {contextData.customer_name} | {contextData.prompt_analysis?.length || 0} prompts analyzed\n
\n
\n\n {/* Prompt Visibility Analysis */}\n
\n
Competitive Presence by Prompt
\n
\n {contextData.prompt_analysis?.map((prompt, index) => (\n
\n
\n
\n {prompt.topic_name}\n
\n
\n
\n {prompt.customer_visible ?\n :\n \n }\n Client\n
\n
\n \n Competitor\n
\n
\n
\n
\n \"{prompt.prompt_text}\"\n
\n
\n {prompt.total_responses} responses\n {!prompt.customer_visible && (\n \u2022 Client is not visible here\n )}\n
\n
\n )) || []}\n
\n\n {/* Competition Summary */}\n {contextData.prompt_analysis?.length > 0 && (\n
\n
\n \n Competitive Intelligence\n
\n

\n {contextData.competitor_name} appears across {contextData.prompt_analysis.length} prompts.\n Focus on prompts where competitor is visible but client is not to improve competitive positioning.\n

\n
\n )}\n
\n
\n );\n};\n\nexport default CompetitorCompanyContext;", "import React from 'react';\nimport { FileText, BarChart3, TrendingUp, AlertTriangle } from 'lucide-react';\n\nconst ContentCoverageTopicContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No content coverage data available for this topic

\n
\n );\n }\n\n const getCoverageColor = (percentage) => {\n if (percentage >= 75) return 'text-green-600 bg-green-50';\n if (percentage >= 50) return 'text-yellow-600 bg-yellow-50';\n if (percentage >= 25) return 'text-orange-600 bg-orange-50';\n return 'text-red-600 bg-red-50';\n };\n\n return (\n
\n
\n \n

Content Coverage Analysis

\n
\n\n {/* Topic Info */}\n
\n
Analyzed Topic
\n
{contextData.topic_name}
\n
\n Relevancy Score: {contextData.topic_score || 0}/100\n
\n
\n\n {/* Coverage Comparison */}\n
\n
\n
Your Coverage
\n
\n {contextData.customer_coverage_percentage || 0}%\n
\n
{contextData.customer_name}
\n
\n
\n
Best Competitor
\n
\n {contextData.max_competitor_coverage || 0}%\n
\n
Max competitor coverage
\n
\n
\n\n {/* Coverage Gap */}\n {contextData.coverage_gap > 0 && (\n
\n
\n \n Coverage Gap\n
\n
\n {contextData.coverage_gap.toFixed(1)}%\n
\n
Behind best competitor
\n
\n )}\n\n {/* Customer Coverage Notes */}\n {contextData.customer_coverage_notes && (\n
\n
Your Content Analysis
\n
{contextData.customer_coverage_notes}
\n
\n )}\n\n {/* Competitor Breakdown */}\n {contextData.competitor_coverage?.length > 0 && (\n
\n
\n \n Competitor Coverage\n
\n
\n {contextData.competitor_coverage.map((competitor, index) => (\n
\n
\n
\n {competitor.company_name}\n
\n
\n {competitor.coverage_percentage || 0}%\n
\n
\n {competitor.coverage_notes && (\n
\n {competitor.coverage_notes}\n
\n )}\n
\n ))}\n
\n
\n )}\n\n {/* Opportunity Summary */}\n {contextData.coverage_gap > 20 && (\n
\n
\n
\n \n Content Opportunity\n
\n

\n Significant content gap detected. Focus on creating comprehensive content\n that covers this topic better than competitors.\n

\n
\n
\n )}\n
\n );\n};\n\nexport default ContentCoverageTopicContext;", "import React from 'react';\nimport { Link, BarChart3, CheckCircle, XCircle, AlertTriangle } from 'lucide-react';\n\nconst OnPageLinkContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No AI readability data available for this URL

\n
\n );\n }\n\n const getScoreColor = (score) => {\n if (score >= 80) return 'text-green-600 bg-green-50';\n if (score >= 60) return 'text-yellow-600 bg-yellow-50';\n if (score >= 40) return 'text-orange-600 bg-orange-50';\n return 'text-red-600 bg-red-50';\n };\n\n const getScoreStatus = (score) => {\n if (score >= 80) return 'Excellent';\n if (score >= 60) return 'Good';\n if (score >= 40) return 'Fair';\n return 'Poor';\n };\n\n return (\n
\n
\n \n

Page AI Readability Analysis

\n
\n\n {/* URL Info */}\n
\n
Analyzed Page
\n
{contextData.url}
\n
\n\n {/* AI Readability Scores */}\n
\n
\n
\n AI Parsing Score\n
\n {getScoreStatus(contextData.ai_parsing_score || 0)}\n
\n
\n
\n {contextData.ai_parsing_score || 0}/100\n
\n
How well AI can parse and understand this page's content
\n
\n\n
\n
\n
Structured Content
\n
\n {contextData.structured_content_percentage || 0}%\n
\n
Markup & Schema
\n
\n
\n
Claim Specificity
\n
\n {contextData.avg_claim_specificity_score || 0}/10\n
\n
Evidence Strength
\n
\n
\n
\n\n {/* Key Recommendations */}\n {contextData.key_recommendations?.length > 0 && (\n
\n
Page Recommendations
\n
\n {contextData.key_recommendations.map((rec, index) => (\n
\n \u2022 {rec}\n
\n ))}\n
\n
\n )}\n\n {/* Strengths */}\n {contextData.key_strengths?.length > 0 && (\n
\n
Current Strengths
\n
\n {contextData.key_strengths.map((strength, index) => (\n
\n \u2022 {strength}\n
\n ))}\n
\n
\n )}\n\n {/* Additional Metrics */}\n
\n
\n
\n
\n {contextData.total_entities || 0}\n
\n
Entities Found
\n
\n
\n
\n {contextData.needs_optimization ?\n :\n \n }\n \n {contextData.needs_optimization ? 'Needs Work' : 'Good Shape'}\n \n
\n
\n
\n\n {contextData.needs_optimization && (\n
\n
\n \n Page Optimization Needed\n
\n

\n This specific page has low AI readability scores and should be optimized for better AI search visibility.\n

\n
\n )}\n
\n
\n );\n};\n\nexport default OnPageLinkContext;", "import React from 'react';\nimport { GitBranch, BarChart3, AlertTriangle, CheckCircle, TrendingUp } from 'lucide-react';\n\nconst OnPageLogicFlowContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No domain-wide logic flow data available

\n
\n );\n }\n\n const getScoreColor = (score) => {\n if (score >= 80) return 'text-green-600';\n if (score >= 60) return 'text-yellow-600';\n if (score >= 40) return 'text-orange-600';\n return 'text-red-600';\n };\n\n return (\n
\n
\n \n

Domain Logic Flow Analysis

\n
\n\n {/* Domain Overview */}\n
\n
Domain Analysis
\n
\n {contextData.total_pages_analyzed} pages analyzed\n
\n
\n Average Logic Flow Score: {contextData.avg_logic_flow_score}/100\n
\n
\n\n {/* Overall Score */}\n
\n
\n Domain Logic Flow Score\n
\n {contextData.avg_logic_flow_score >= 80 ? 'Excellent' :\n contextData.avg_logic_flow_score >= 60 ? 'Good' :\n contextData.avg_logic_flow_score >= 40 ? 'Fair' : 'Poor'}\n
\n
\n
\n {contextData.avg_logic_flow_score || 0}/100\n
\n
Average logical flow quality across all analyzed pages
\n
\n\n {/* Performance Distribution */}\n
\n
\n
\n {contextData.domain_overview?.excellent_pages || 0}\n
\n
Excellent (80+)
\n
\n
\n
\n {contextData.domain_overview?.good_pages || 0}\n
\n
Good (60-79)
\n
\n
\n
\n {contextData.domain_overview?.poor_pages || 0}\n
\n
Poor (<60)
\n
\n
\n\n {/* Common Issues */}\n {contextData.common_issues?.length > 0 && (\n
\n
\n \n Common Logic Flow Issues\n
\n
\n {contextData.common_issues.map((issue, index) => (\n
\n \u2022 {issue.replace(/_/g, ' ').replace(/\\b\\w/g, l => l.toUpperCase())}\n
\n ))}\n
\n
\n )}\n\n {/* Pages with Issues */}\n {contextData.pages_with_issues?.length > 0 && (\n
\n
Pages Needing Improvement
\n
\n {contextData.pages_with_issues.map((page, index) => (\n
\n
\n
\n {page.url}\n
\n
\n {page.score}/100\n
\n
\n {page.issues?.length > 0 && (\n
\n Issues: {page.issues.slice(0, 2).join(', ')}\n
\n )}\n
\n ))}\n
\n
\n )}\n\n {/* Improvement Recommendations */}\n {contextData.improvement_recommendations?.length > 0 && (\n
\n
\n \n Domain-Wide Recommendations\n
\n
\n {contextData.improvement_recommendations.map((rec, index) => (\n
\n \u2022 {rec}\n
\n ))}\n
\n
\n )}\n\n {/* Status Summary */}\n
\n
\n {contextData.avg_logic_flow_score >= 70 ?\n :\n \n }\n = 70 ? 'text-green-600' : 'text-orange-600'}`}>\n {contextData.avg_logic_flow_score >= 70 ? 'Domain Logic Flow Healthy' : 'Domain Needs Logic Flow Improvement'}\n \n
\n\n {contextData.avg_logic_flow_score < 70 && (\n
\n

\n Multiple pages across your domain have logic flow issues. Focus on the common patterns\n identified to improve overall content structure and AI comprehension.\n

\n
\n )}\n
\n
\n );\n};\n\nexport default OnPageLogicFlowContext;", "import React from 'react';\nimport { Network, BarChart3, AlertTriangle, CheckCircle } from 'lucide-react';\n\nconst OnPageEntityMappingContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No domain-wide entity mapping data available

\n
\n );\n }\n\n const getHealthColor = (health) => {\n const colors = {\n 'Excellent': 'text-green-600',\n 'Good': 'text-yellow-600',\n 'Fair': 'text-orange-600',\n 'Poor': 'text-red-600'\n };\n return colors[health] || 'text-gray-600';\n };\n\n return (\n
\n
\n \n

Domain Entity Mapping Analysis

\n
\n\n {/* Domain Overview */}\n
\n
Domain Analysis
\n
\n {contextData.total_pages_analyzed} pages analyzed\n
\n
\n {contextData.total_unique_entities} unique entities | {contextData.avg_entities_per_page} avg per page\n
\n
\n\n {/* Entity Health Score */}\n
\n
\n Domain Entity Health\n
\n {contextData.domain_entity_health || 'Unknown'}\n
\n
\n
\n {contextData.entity_consistency_score || 0}/100\n
\n
Entity consistency and relationship mapping across domain
\n
\n\n {/* Entity Metrics */}\n
\n
\n
\n {contextData.total_unique_entities || 0}\n
\n
Unique Entities
\n
\n
\n
\n {contextData.avg_entities_per_page || 0}\n
\n
Avg per Page
\n
\n
\n
\n {contextData.orphaned_entities?.length || 0}\n
\n
Orphaned
\n
\n
\n\n {/* Orphaned Entities */}\n {contextData.orphaned_entities?.length > 0 && (\n
\n
\n \n Orphaned Entities (No Relationships)\n
\n
\n {contextData.orphaned_entities.map((item, index) => (\n
\n
\n {item.entity}\n
\n
\n Found on: {item.url.replace(/^https?:\\/\\//, '').substring(0, 30)}...\n
\n
\n ))}\n
\n
\n )}\n\n {/* Entity Mapping Recommendations */}\n {contextData.entity_mapping_recommendations?.length > 0 && (\n
\n
\n \n Entity Mapping Recommendations\n
\n
\n {contextData.entity_mapping_recommendations.map((rec, index) => (\n
\n \u2022 {rec}\n
\n ))}\n
\n
\n )}\n\n {/* Entity Optimization Status */}\n
\n
\n {contextData.entity_consistency_score >= 60 ?\n :\n \n }\n = 60 ? 'text-green-600' : 'text-orange-600'}`}>\n {contextData.entity_consistency_score >= 60 ? 'Entity Mapping Healthy' : 'Entity Mapping Needs Work'}\n \n
\n\n {contextData.entity_consistency_score < 60 && (\n
\n
\n \n Entity Relationship Issues\n
\n

\n Entity relationships across your domain are inconsistent. This makes it harder for AI to understand\n how concepts relate to each other. Focus on linking related entities and using consistent naming.\n

\n
\n )}\n
\n\n {/* Entity Enhancement Guide */}\n
\n
Entity Mapping Best Practices
\n
    \n
  • \u2022 Use consistent entity names across all pages
  • \n
  • \u2022 Add schema markup to define entity types and relationships
  • \n
  • \u2022 Link related entities with internal links and cross-references
  • \n
  • \u2022 Create entity hubs or glossary pages for important concepts
  • \n
\n
\n
\n );\n};\n\nexport default OnPageEntityMappingContext;", "import React from 'react';\nimport { FileCheck, BarChart3, AlertTriangle, CheckCircle } from 'lucide-react';\n\nconst OnPageClaimClarityContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No domain-wide claim clarity data available

\n
\n );\n }\n\n const getScoreColor = (score) => {\n if (score >= 8) return 'text-green-600';\n if (score >= 6) return 'text-yellow-600';\n if (score >= 4) return 'text-orange-600';\n return 'text-red-600';\n };\n\n const getScoreStatus = (score) => {\n if (score >= 8) return 'Excellent';\n if (score >= 6) return 'Good';\n if (score >= 4) return 'Fair';\n return 'Poor';\n };\n\n return (\n
\n
\n \n

Domain Claim Clarity Analysis

\n
\n\n {/* Domain Overview */}\n
\n
Domain Analysis
\n
\n {contextData.total_pages_analyzed} pages analyzed\n
\n
\n Average Claim Specificity: {contextData.avg_claim_specificity_score}/10\n
\n
\n\n {/* Claim Clarity Score */}\n
\n
\n Domain Claim Specificity\n
\n {getScoreStatus(contextData.avg_claim_specificity_score || 0)}\n
\n
\n
\n {contextData.avg_claim_specificity_score || 0}/10\n
\n
\n Average claim specificity and evidence strength across all analyzed pages\n
\n
\n\n {/* Evidence Distribution */}\n {contextData.evidence_strength_distribution && Object.keys(contextData.evidence_strength_distribution).length > 0 && (\n
\n
\n \n Evidence Types Used\n
\n
\n {Object.entries(contextData.evidence_strength_distribution).map(([type, count]) => (\n
\n
\n {type.replace(/_/g, ' ').replace(/\\b\\w/g, l => l.toUpperCase())}\n
\n
{count} uses
\n
\n ))}\n
\n
\n )}\n\n {/* Pages with Strong Claims */}\n {contextData.pages_with_strong_claims?.length > 0 && (\n
\n
\n \n Pages with Strong Claims\n
\n
\n {contextData.pages_with_strong_claims.slice(0, 3).map((page, index) => (\n
\n
\n
\n {page.url.replace(/^https?:\\/\\//, '').substring(0, 40)}...\n
\n
\n {page.score}/10\n
\n
\n
\n ))}\n
\n
\n )}\n\n {/* Pages with Weak Claims */}\n {contextData.pages_with_weak_claims?.length > 0 && (\n
\n
\n \n Pages with Weak Claims\n
\n
\n {contextData.pages_with_weak_claims.map((page, index) => (\n
\n
\n
\n {page.url.replace(/^https?:\\/\\//, '').substring(0, 40)}...\n
\n
\n {page.score}/10\n
\n
\n
\n ))}\n
\n
\n )}\n\n {/* Improvement Recommendations */}\n {contextData.claim_improvement_opportunities?.length > 0 && (\n
\n
Domain-Wide Improvements
\n
\n {contextData.claim_improvement_opportunities.map((rec, index) => (\n
\n \u2022 {rec}\n
\n ))}\n
\n
\n )}\n\n {/* Optimization Status */}\n
\n
\n {contextData.avg_claim_specificity_score >= 7 ?\n :\n \n }\n = 7 ? 'text-green-600' : 'text-orange-600'}`}>\n {contextData.avg_claim_specificity_score >= 7 ? 'Claims Well-Supported' : 'Claims Need Specificity'}\n \n
\n\n {contextData.avg_claim_specificity_score < 7 && (\n
\n
\n \n Domain-Wide Claim Issues\n
\n

\n Claims across your domain lack specificity and supporting evidence. This makes it harder for AI to\n understand and validate your content. Focus on adding data, examples, and concrete proof points.\n

\n
\n )}\n
\n\n {/* Claim Enhancement Guide */}\n
\n
Claim Clarity Best Practices
\n
    \n
  • \u2022 Support claims with specific data, statistics, and examples
  • \n
  • \u2022 Use concrete language instead of vague qualifiers
  • \n
  • \u2022 Add source citations and references for major claims
  • \n
  • \u2022 Quantify benefits and outcomes wherever possible
  • \n
\n
\n
\n );\n};\n\nexport default OnPageClaimClarityContext;", "import React from 'react';\nimport { Code, BarChart3, AlertTriangle, CheckCircle } from 'lucide-react';\n\nconst OnPageSchemaMarkupContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No domain-wide schema markup data available

\n
\n );\n }\n\n const getImplementationColor = (percentage) => {\n if (percentage >= 80) return 'text-green-600';\n if (percentage >= 60) return 'text-yellow-600';\n if (percentage >= 30) return 'text-orange-600';\n return 'text-red-600';\n };\n\n const getImplementationStatus = (percentage) => {\n if (percentage >= 80) return 'Excellent';\n if (percentage >= 60) return 'Good';\n if (percentage >= 30) return 'Fair';\n return 'Poor';\n };\n\n return (\n
\n
\n \n

Domain Schema Markup Analysis

\n
\n\n {/* Domain Overview */}\n
\n
Domain Analysis
\n
\n {contextData.total_pages_analyzed} pages analyzed\n
\n
\n {contextData.pages_with_schema} pages have schema markup ({contextData.schema_implementation_percentage}%)\n
\n
\n\n {/* Schema Implementation Score */}\n
\n
\n Schema Implementation\n
\n {getImplementationStatus(contextData.schema_implementation_percentage || 0)}\n
\n
\n
\n {contextData.schema_implementation_percentage || 0}%\n
\n
Percentage of pages with structured data markup
\n
\n\n {/* Implementation Breakdown */}\n
\n
\n
\n {contextData.pages_with_schema || 0}\n
\n
With Schema
\n
\n
\n
\n {(contextData.total_pages_analyzed || 0) - (contextData.pages_with_schema || 0)}\n
\n
Missing Schema
\n
\n
\n\n {/* Schema Types Found */}\n {contextData.schema_types_found?.length > 0 && (\n
\n
\n \n Schema Types Implemented\n
\n
\n {contextData.schema_types_found.map((type, index) => (\n
\n
\n {type.replace(/([A-Z])/g, ' $1').trim()}\n
\n
\n ))}\n
\n
\n )}\n\n {/* Schema Quality Score */}\n {contextData.schema_quality_score !== undefined && (\n
\n
Schema Quality Score
\n
\n {contextData.schema_quality_score}/100\n
\n
Quality of existing schema implementation
\n
\n )}\n\n {/* Missing Schema Opportunities */}\n {contextData.missing_schema_opportunities?.length > 0 && (\n
\n
\n \n Pages Missing Schema\n
\n
\n {contextData.missing_schema_opportunities.map((item, index) => (\n
\n
\n {item.url.replace(/^https?:\\/\\//, '').substring(0, 40)}...\n
\n {item.recommended_types?.length > 0 && (\n
\n Recommended: {item.recommended_types.slice(0, 2).join(', ')}\n
\n )}\n
\n ))}\n
\n
\n )}\n\n {/* Schema Recommendations */}\n {contextData.schema_recommendations?.length > 0 && (\n
\n
Implementation Recommendations
\n
\n {contextData.schema_recommendations.map((rec, index) => (\n
\n \u2022 {rec}\n
\n ))}\n
\n
\n )}\n\n {/* Schema Status */}\n
\n
\n {contextData.schema_implementation_percentage >= 60 ?\n :\n \n }\n = 60 ? 'text-green-600' : 'text-orange-600'}`}>\n {contextData.schema_implementation_percentage >= 60 ? 'Schema Implementation Good' : 'Schema Implementation Needed'}\n \n
\n\n {contextData.schema_implementation_percentage < 60 && (\n
\n
\n \n Domain Schema Issues\n
\n

\n Many pages across your domain lack structured data markup. This makes it harder for AI to understand\n your content context and relationships. Implement schema markup for better AI comprehension.\n

\n
\n )}\n
\n\n {/* Schema Implementation Guide */}\n
\n
Schema Implementation Priorities
\n
    \n
  • \u2022 Start with Organization and WebSite schema for homepage
  • \n
  • \u2022 Add Article/BlogPosting schema for content pages
  • \n
  • \u2022 Implement Product schema for product/service pages
  • \n
  • \u2022 Use BreadcrumbList for navigation structure
  • \n
  • \u2022 Add FAQ and HowTo schema where relevant
  • \n
\n
\n
\n );\n};\n\nexport default OnPageSchemaMarkupContext;", "import React from 'react';\nimport { Layers, AlertTriangle, CheckCircle } from 'lucide-react';\n\nconst OnPageInformationArchitectureContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No domain-wide information architecture data available

\n
\n );\n }\n\n const getScoreColor = (score) => {\n if (score >= 80) return 'text-green-600';\n if (score >= 60) return 'text-yellow-600';\n if (score >= 40) return 'text-orange-600';\n return 'text-red-600';\n };\n\n const getHealthColor = (health) => {\n const colors = {\n 'Excellent': 'text-green-600',\n 'Good': 'text-yellow-600',\n 'Fair': 'text-orange-600',\n 'Poor': 'text-red-600'\n };\n return colors[health] || 'text-gray-600';\n };\n\n const aiParsingScore = contextData.avg_ai_parsing_score ?? 0;\n const structuredContentPct = contextData.avg_structured_content_percentage ?? 0;\n const claimSpecificity = contextData.avg_claim_specificity_score ?? 0;\n const architectureScore = contextData.avg_architecture_score ?? 0;\n\n return (\n
\n
\n \n

Domain Information Architecture Analysis

\n
\n\n {/* Domain Overview */}\n
\n
Domain Analysis
\n
\n {contextData.total_pages_analyzed || 0} pages analyzed\n {contextData.domain_name && ` on ${contextData.domain_name}`}\n
\n
\n\n {/* Primary AI Readability Signal */}\n
\n
\n Average AI Parsing Score\n across domain\n
\n
\n {aiParsingScore}/100\n
\n
\n How well AI models can parse and understand your content's structure\n
\n
\n\n {/* AI Readability Sub-metrics */}\n
\n
\n
Structured Content
\n
\n {structuredContentPct}%\n
\n
Lists, tables, headings
\n
\n
\n
Claim Specificity
\n
\n {claimSpecificity}/10\n
\n
Evidence strength
\n
\n
\n\n {/* Structural Breakdown */}\n
\n
Structural Breakdown
\n\n
\n
\n Overall Structure Score\n {contextData.site_structure_health && (\n
\n {contextData.site_structure_health}\n
\n )}\n
\n
\n {architectureScore}/100\n
\n
\n\n
\n
\n
Navigation
\n
\n {contextData.navigation_consistency_score || 0}/100\n
\n
\n
\n
Headings
\n
\n {contextData.heading_structure_quality || 0}/100\n
\n
\n
\n
Internal Links
\n
\n {contextData.internal_linking_score || 0}\n avg/page\n
\n
\n
\n
\n\n {/* Architecture Issues (from recommendations across pages) */}\n {contextData.architecture_issues?.length > 0 && (\n
\n
\n \n Most Common Issues Across Pages\n
\n
\n {contextData.architecture_issues.map((issue, index) => (\n
\n \u2022 {issue}\n
\n ))}\n
\n
\n )}\n\n {/* Architecture Recommendations */}\n {contextData.architecture_recommendations?.length > 0 && (\n
\n
Recommended Improvements
\n
\n {contextData.architecture_recommendations.map((rec, index) => (\n
\n \u2022 {rec}\n
\n ))}\n
\n
\n )}\n\n {/* Status Banner */}\n
\n
\n {aiParsingScore >= 70 ? (\n \n ) : (\n \n )}\n = 70 ? 'text-green-600' : 'text-orange-600'}`}>\n {aiParsingScore >= 70 ? 'AI Readability Is Strong' : 'AI Readability Needs Improvement'}\n \n
\n\n {aiParsingScore < 70 && (\n
\n

\n Your information architecture makes it difficult for AI models to understand content\n hierarchy and relationships. Improving heading structure, navigation consistency, and\n internal linking will lift AI parsing performance across the domain.\n

\n
\n )}\n
\n
\n );\n};\n\nexport default OnPageInformationArchitectureContext;", "import React from 'react';\nimport { Zap, Clock, HardDrive, AlertTriangle, CheckCircle } from 'lucide-react';\n\nconst TechnicalLinkContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No technical performance data available for this URL

\n
\n );\n }\n\n const getPerformanceColor = (value, type) => {\n let isGood = false;\n switch (type) {\n case 'load_time':\n isGood = value < 2000;\n break;\n case 'size':\n isGood = value < 1000;\n break;\n case 'ttfb':\n isGood = value < 500;\n break;\n case 'score':\n isGood = value >= 70;\n break;\n }\n return isGood ? 'text-green-600' : value < 3000 || value < 80 ? 'text-yellow-600' : 'text-red-600';\n };\n\n const formatTime = (ms) => {\n if (ms < 1000) return `${ms}ms`;\n return `${(ms / 1000).toFixed(2)}s`;\n };\n\n const formatSize = (kb) => {\n if (kb < 1000) return `${kb}KB`;\n return `${(kb / 1000).toFixed(2)}MB`;\n };\n\n return (\n
\n
\n \n

Page Technical Performance Analysis

\n
\n\n {/* URL Info */}\n
\n
Analyzed Page
\n
{contextData.url}
\n
\n\n {/* Performance Metrics */}\n
\n
\n
\n
\n \n Load Time\n
\n
\n {contextData.performance_metrics?.load_time_ms < 2000 ? 'Fast' :\n contextData.performance_metrics?.load_time_ms < 3000 ? 'Moderate' : 'Slow'}\n
\n
\n
\n {formatTime(contextData.performance_metrics?.load_time_ms || 0)}\n
\n
Total page load time
\n
\n
\n\n
\n
\n
\n \n Page Size\n
\n
\n {formatSize(contextData.performance_metrics?.response_size_kb || 0)}\n
\n
Total response size
\n
\n\n
\n
\n \n TTFB\n
\n
\n {formatTime(contextData.performance_metrics?.time_to_first_byte_ms || 0)}\n
\n
Time to first byte
\n
\n
\n\n {/* Structure Scores */}\n
\n
Page Structure Quality
\n
\n
\n
Overall
\n
\n {contextData.structure_scores?.overall_score || 0}/100\n
\n
\n
\n
Schema
\n
\n {contextData.structure_scores?.schema_score || 0}/100\n
\n
\n
\n
\n\n {/* Front Loading Score */}\n {contextData.front_loading_score !== undefined && (\n
\n
Content Front-loading
\n
\n {contextData.front_loading_score}/100\n
\n
Information density optimization for this page
\n
\n )}\n\n {/* Optimization Status */}\n
\n
\n {contextData.needs_optimization ?\n :\n \n }\n \n {contextData.needs_optimization ? 'Page Optimization Needed' : 'Page Performance Good'}\n \n
\n\n {contextData.needs_optimization && (\n
\n
\n \n Performance Issues\n
\n

\n This specific page has technical performance issues that may affect AI crawling efficiency\n and search visibility. Consider optimization for better performance.\n

\n
\n )}\n
\n\n {/* Technical Enhancement Tips */}\n
\n
Page Optimization Tips
\n
    \n
  • \u2022 Optimize images and compress media files
  • \n
  • \u2022 Minimize CSS and JavaScript
  • \n
  • \u2022 Implement caching headers
  • \n
  • \u2022 Reduce server response time
  • \n
\n
\n
\n );\n};\n\nexport default TechnicalLinkContext;", "import React from 'react';\nimport { Clock, BarChart3, AlertTriangle, CheckCircle, Zap } from 'lucide-react';\n\nconst TechnicalLoadTimeContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No domain-wide load time data available

\n
\n );\n }\n\n const getPerformanceColor = (time_ms) => {\n if (time_ms < 1500) return 'text-green-600';\n if (time_ms < 3000) return 'text-yellow-600';\n return 'text-red-600';\n };\n\n const formatTime = (ms) => {\n if (ms < 1000) return `${ms}ms`;\n return `${(ms / 1000).toFixed(2)}s`;\n };\n\n const formatSize = (kb) => {\n if (kb < 1000) return `${kb}KB`;\n return `${(kb / 1000).toFixed(2)}MB`;\n };\n\n return (\n
\n
\n \n

Domain Load Time Analysis

\n
\n\n {/* Domain Overview */}\n
\n
Domain Performance
\n
\n {contextData.total_pages_analyzed} pages analyzed\n
\n
\n Average load time: {formatTime(contextData.avg_load_time_ms)}\n
\n
\n\n {/* Key Metrics */}\n
\n
\n
\n \n Avg Load Time\n
\n
\n {formatTime(contextData.avg_load_time_ms || 0)}\n
\n
Across all pages
\n
\n
\n
Avg TTFB
\n
\n {formatTime(contextData.avg_ttfb_ms || 0)}\n
\n
Time to first byte
\n
\n
\n
Avg Size
\n
\n {formatSize(contextData.avg_response_size_kb || 0)}\n
\n
Page weight
\n
\n
\n\n {/* Performance Distribution */}\n
\n
\n \n Performance Distribution\n
\n\n
\n
\n
\n {contextData.performance_distribution?.fast_pages || 0}\n
\n
Fast (<1.5s)
\n
\n
\n
\n {contextData.performance_distribution?.moderate_pages || 0}\n
\n
Moderate (1.5-3s)
\n
\n
\n
\n {contextData.performance_distribution?.slow_pages || 0}\n
\n
Slow (>3s)
\n
\n
\n
\n\n {/* Slow Pages */}\n {contextData.slow_pages?.length > 0 && (\n
\n
\n \n Slowest Pages\n
\n
\n {contextData.slow_pages.map((page, index) => (\n
\n
\n
\n {page.url.replace(/^https?:\\/\\//, '').substring(0, 40)}...\n
\n
\n {formatTime(page.load_time_ms)}\n
\n
\n
\n ))}\n
\n
\n )}\n\n {/* Fast Pages (Success Stories) */}\n {contextData.fast_pages?.length > 0 && (\n
\n
\n \n Best Performing Pages\n
\n
\n {contextData.fast_pages.slice(0, 3).map((page, index) => (\n
\n
\n
\n {page.url.replace(/^https?:\\/\\//, '').substring(0, 40)}...\n
\n
\n {formatTime(page.load_time_ms)}\n
\n
\n
\n ))}\n
\n
\n )}\n\n {/* Recommendations */}\n {contextData.load_time_recommendations?.length > 0 && (\n
\n
Performance Optimization
\n
\n {contextData.load_time_recommendations.map((rec, index) => (\n
\n \u2022 {rec}\n
\n ))}\n
\n
\n )}\n\n {/* Overall Status */}\n
\n
\n {contextData.avg_load_time_ms < 2000 ?\n :\n \n }\n \n {contextData.avg_load_time_ms < 2000 ? 'Domain Performance Good' : 'Domain Needs Speed Optimization'}\n \n
\n\n {contextData.avg_load_time_ms >= 2000 && (\n
\n

\n Average load times across your domain exceed optimal performance thresholds.\n Focus on the slowest pages first to improve overall user and AI crawler experience.\n

\n
\n )}\n
\n
\n );\n};\n\nexport default TechnicalLoadTimeContext;", "import React from 'react';\nimport { Gauge, BarChart3, AlertTriangle, CheckCircle, TrendingUp } from 'lucide-react';\n\nconst TechnicalFrontLoadingContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No domain-wide front-loading data available

\n
\n );\n }\n\n const getScoreColor = (score) => {\n if (score >= 80) return 'text-green-600';\n if (score >= 60) return 'text-yellow-600';\n if (score >= 40) return 'text-orange-600';\n return 'text-red-600';\n };\n\n return (\n
\n
\n \n

Domain Front-Loading Analysis

\n
\n\n {/* Domain Overview */}\n
\n
Domain Analysis
\n
\n {contextData.total_pages_analyzed} pages analyzed\n
\n
\n Average Front-Loading Score: {contextData.avg_front_loading_score}/100\n
\n
\n\n {/* Front-Loading Score */}\n
\n
\n Domain Front-Loading Score\n
\n {contextData.avg_front_loading_score >= 80 ? 'Excellent' :\n contextData.avg_front_loading_score >= 60 ? 'Good' :\n contextData.avg_front_loading_score >= 40 ? 'Fair' : 'Poor'}\n
\n
\n
\n {contextData.avg_front_loading_score || 0}/100\n
\n
How effectively critical information appears early across all pages
\n
\n\n {/* Front-Loading Distribution */}\n
\n
\n \n Information Priority Distribution\n
\n\n
\n
\n
\n {contextData.front_loading_distribution?.excellent_pages || 0}\n
\n
Excellent (80+)
\n
\n
\n
\n {contextData.front_loading_distribution?.good_pages || 0}\n
\n
Good (60-79)
\n
\n
\n
\n {contextData.front_loading_distribution?.poor_pages || 0}\n
\n
Poor (<60)
\n
\n
\n
\n\n {/* Poorly Loaded Pages */}\n {contextData.poorly_loaded_pages?.length > 0 && (\n
\n
\n \n Pages with Poor Information Priority\n
\n
\n {contextData.poorly_loaded_pages.map((page, index) => (\n
\n
\n
\n {page.url.replace(/^https?:\\/\\//, '').substring(0, 40)}...\n
\n
\n {page.score}/100\n
\n
\n
\n ))}\n
\n
\n )}\n\n {/* Well-Loaded Pages */}\n {contextData.well_loaded_pages?.length > 0 && (\n
\n
\n \n Best Front-Loading Examples\n
\n
\n {contextData.well_loaded_pages.slice(0, 3).map((page, index) => (\n
\n
\n
\n {page.url.replace(/^https?:\\/\\//, '').substring(0, 40)}...\n
\n
\n {page.score}/100\n
\n
\n
\n ))}\n
\n
\n )}\n\n {/* Front-Loading Recommendations */}\n {contextData.front_loading_recommendations?.length > 0 && (\n
\n
Domain Optimization
\n
\n {contextData.front_loading_recommendations.map((rec, index) => (\n
\n \u2022 {rec}\n
\n ))}\n
\n
\n )}\n\n {/* Performance Impact */}\n
\n
\n {contextData.avg_front_loading_score >= 70 ?\n :\n \n }\n = 70 ? 'text-green-600' : 'text-orange-600'}`}>\n {contextData.avg_front_loading_score >= 70 ? 'Good Information Priority' : 'Improve Content Priority'}\n \n
\n\n {contextData.avg_front_loading_score < 70 && (\n
\n
\n \n Domain Front-Loading Issues\n
\n

\n Critical information appears too late across many pages in your domain. AI crawlers benefit from\n front-loaded, high-density information to quickly understand page value and relevance.\n

\n
\n )}\n
\n\n {/* Front-Loading Enhancement Guide */}\n
\n
Front-Loading Best Practices
\n
    \n
  • \u2022 Place key information in first paragraph of each page
  • \n
  • \u2022 Use summary boxes for complex content
  • \n
  • \u2022 Lead with most important facts and data
  • \n
  • \u2022 Optimize above-the-fold content density
  • \n
  • \u2022 Implement progressive disclosure for detailed information
  • \n
\n
\n
\n );\n};\n\nexport default TechnicalFrontLoadingContext;", "import React from 'react';\nimport { Activity, BarChart3, AlertTriangle, CheckCircle, Clock } from 'lucide-react';\n\nconst TechnicalInformationDensityContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No domain-wide information density data available

\n
\n );\n }\n\n const getEfficiencyColor = (score) => {\n if (score >= 25) return 'text-green-600';\n if (score >= 10) return 'text-yellow-600';\n return 'text-red-600';\n };\n\n return (\n
\n
\n \n

Content Information Density Analysis

\n
\n\n {/* Domain Overview */}\n
\n
Domain Analysis
\n
\n {contextData.total_pages_analyzed} pages analyzed\n
\n
\n Average Information Density: {contextData.avg_information_density_score}\n
\n
\n\n {/* Information Density Score */}\n
\n
\n Content Information Density\n
\n {contextData.avg_information_density_score >= 25 ? 'Highly Efficient' :\n contextData.avg_information_density_score >= 10 ? 'Moderately Efficient' : 'Inefficient'}\n
\n
\n
\n {contextData.avg_information_density_score || 0}\n
\n
Efficiency of information delivery per byte for AI processing
\n
\n\n {/* Density Distribution */}\n
\n
\n \n Information Efficiency Distribution\n
\n\n
\n
\n
\n {contextData.density_distribution?.highly_efficient || 0}\n
\n
Highly Efficient
\n
\n
\n
\n {contextData.density_distribution?.moderately_efficient || 0}\n
\n
Moderate
\n
\n
\n
\n {contextData.density_distribution?.inefficient || 0}\n
\n
Inefficient
\n
\n
\n
\n\n {/* Inefficient Pages */}\n {contextData.inefficient_pages?.length > 0 && (\n
\n
\n \n Inefficient Pages\n
\n
\n {contextData.inefficient_pages.map((page, index) => (\n
\n
\n
\n {page.url.replace(/^https?:\\/\\//, '').substring(0, 40)}...\n
\n
\n {page.density_score}\n
\n
\n
\n ))}\n
\n
\n )}\n\n {/* Efficient Pages */}\n {contextData.efficient_pages?.length > 0 && (\n
\n
\n \n Most Efficient Pages\n
\n
\n {contextData.efficient_pages.slice(0, 3).map((page, index) => (\n
\n
\n
\n {page.url.replace(/^https?:\\/\\//, '').substring(0, 40)}...\n
\n
\n {page.density_score}\n
\n
\n
\n ))}\n
\n
\n )}\n\n {/* Density Recommendations */}\n {contextData.density_recommendations?.length > 0 && (\n
\n
Density Optimization
\n
\n {contextData.density_recommendations.map((rec, index) => (\n
\n \u2022 {rec}\n
\n ))}\n
\n
\n )}\n\n {/* Information Density Status */}\n
\n
\n {contextData.avg_information_density_score >= 15 ?\n :\n \n }\n = 15 ? 'text-green-600' : 'text-orange-600'}`}>\n {contextData.avg_information_density_score >= 15 ? 'Good Information Density' : 'Density Optimization Needed'}\n \n
\n\n {contextData.avg_information_density_score < 15 && (\n
\n
\n \n Domain Density Issues\n
\n

\n Information density across your domain is low - pages provide little value per byte consumed.\n Optimize content quality and technical performance for better AI processing efficiency.\n

\n
\n )}\n
\n\n {/* Density Enhancement Guide */}\n
\n
Density Optimization Guide
\n
    \n
  • \u2022 Remove redundant content and filler text
  • \n
  • \u2022 Compress images and optimize media files
  • \n
  • \u2022 Use concise, information-rich paragraphs
  • \n
  • \u2022 Implement lazy loading for non-critical content
  • \n
  • \u2022 Balance content depth with performance considerations
  • \n
\n
\n
\n );\n};\n\nexport default TechnicalInformationDensityContext;", "import React from 'react';\nimport { Quote, CheckCircle, XCircle, BarChart3 } from 'lucide-react';\n\nconst CitationRateTopicContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No citation data available for this topic

\n
\n );\n }\n\n // Citation rate is now percentage of responses that contain client citations\n const getCitationColor = (rate) => {\n if (rate >= 75) return 'text-green-600 bg-green-50'; // Excellent: 75%+ responses cited\n if (rate >= 50) return 'text-blue-600 bg-blue-50'; // Good: 50%+ responses cited\n if (rate >= 25) return 'text-yellow-600 bg-yellow-50'; // Fair: 25%+ responses cited\n if (rate > 0) return 'text-orange-600 bg-orange-50'; // Low: Some responses cited\n return 'text-red-600 bg-red-50'; // None: No responses cited\n };\n\n return (\n
\n
\n \n

Topic Citation Analysis

\n
\n\n {/* Topic Info */}\n
\n
Analyzed Topic
\n
{contextData.topic_name}
\n
\n Relevancy Score: {contextData.topic_score || 0}/100 | {contextData.customer_name}\n
\n
\n\n {/* Customer Domain Info */}\n {contextData.customer_domains?.length > 0 && (\n
\n
Your Domains
\n
\n {contextData.customer_domains.join(', ')}\n
\n
\n )}\n\n {/* Prompt Citation Analysis */}\n
\n
\n \n Citation Analysis by Prompt\n
\n\n
\n {contextData.prompt_citation_data?.map((prompt, index) => (\n
\n
\n
\n Prompt {index + 1}\n
\n
\n
\n {prompt.citation_rate || 0}%\n
\n {prompt.client_cited ?\n :\n \n }\n
\n
\n
\n \"{prompt.prompt_text}\"\n
\n
\n {prompt.total_responses} responses\n {prompt.total_citations} citations\n {prompt.responses_with_client_citations || 0} yours\n {prompt.overall_citation_rate || 0}% total\n
\n
\n )) || []}\n
\n\n {/* Summary Stats */}\n
\n
\n
\n {contextData.prompt_citation_data?.filter(p => p.client_cited).length || 0}\n
\n
Prompts with your citations
\n
\n
\n
\n {contextData.prompt_citation_data?.filter(p => !p.client_cited && p.total_citations > 0).length || 0}\n
\n
Missed opportunities
\n
\n
\n
\n {contextData.prompt_citation_data?.reduce((sum, p) => sum + (p.responses_with_client_citations || 0), 0)}\n
\n
Total cited responses
\n
\n
\n
\n
\n );\n};\n\nexport default CitationRateTopicContext;", "import React from 'react';\nimport { Globe, BarChart3, TrendingUp, Target } from 'lucide-react';\n\nconst CitationThirdPartyContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No third-party citation data available for this domain

\n
\n );\n }\n\n // Citation rate is now percentage of responses that contain citations from this domain\n const getCitationColor = (rate) => {\n if (rate >= 75) return 'text-green-600 bg-green-50'; // Excellent: 75%+ responses cited\n if (rate >= 50) return 'text-blue-600 bg-blue-50'; // Good: 50%+ responses cited\n if (rate >= 25) return 'text-yellow-600 bg-yellow-50'; // Fair: 25%+ responses cited\n if (rate > 0) return 'text-orange-600 bg-orange-50'; // Low: Some responses cited\n return 'text-red-600 bg-red-50'; // None: No responses cited\n };\n\n return (\n
\n
\n \n

Third-Party Citation Analysis

\n
\n\n {/* Domain Info */}\n
\n
Target Domain
\n
{contextData.domain_name}
\n
\n Citation opportunity for {contextData.customer_name}\n
\n
\n\n {/* Citation Summary */}\n
\n
Citation Performance
\n
\n
\n {contextData.total_topics_with_citations || 0}\n
\n
Topics citing this domain
\n
\n
\n\n {/* Topic Citation Breakdown */}\n
\n
\n \n Citation Rate by Topic\n
\n\n
\n {contextData.topic_citation_data?.map((topic, index) => (\n
\n
\n
\n {topic.topic_name}\n
\n
\n {topic.citation_rate || 0}%\n
\n
\n
\n Score: {topic.topic_score || 0}\n {topic.total_responses} responses\n {topic.domain_citations} citations\n {topic.responses_with_citations || 0} cited resp\n
\n
\n )) || []}\n
\n\n {contextData.topic_citation_data?.length === 0 && (\n
\n No topics currently cite this domain\n
\n )}\n
\n\n\n {/* Citation Opportunity */}\n
\n
\n
\n \n Citation Opportunity\n
\n

\n {contextData.total_topics_with_citations > 0 ?\n `This domain is cited across ${contextData.total_topics_with_citations} topics. Build relationships and create content to earn citations from this authoritative domain.` :\n `This domain represents an untapped citation opportunity. Research their content needs and build relationships to earn authoritative citations.`\n }\n

\n
\n
\n\n {/* Top Citation Topics */}\n {contextData.topic_citation_data?.length > 0 && (\n
\n
\n \n Best Citation Opportunities\n
\n
\n Focus on: {contextData.topic_citation_data.slice(0, 3).map(t => t.topic_name).join(', ')}\n
\n
\n )}\n
\n );\n};\n\nexport default CitationThirdPartyContext;", "import React from 'react';\nimport { MessageCircle, AlertTriangle, TrendingDown, Eye } from 'lucide-react';\n\nconst SentimentPromptContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No sentiment data available for this prompt

\n
\n );\n }\n\n const getPlatformIcon = (platform) => {\n const icons = {\n 'ChatGPT': '\uD83E\uDD16',\n 'Claude': '\uD83E\uDDE0',\n 'Perplexity': '\uD83D\uDD0D',\n 'Google AI Overview': '\uD83D\uDD0E'\n };\n return icons[platform] || '\uD83E\uDD16';\n };\n\n const getIssueTypeIcon = (response) => {\n if (response.has_negative && response.has_hallucination) {\n return
\n \n \n
;\n } else if (response.has_negative) {\n return ;\n } else if (response.has_hallucination) {\n return ;\n }\n return null;\n };\n\n const getIssueTypeText = (response) => {\n if (response.has_negative && response.has_hallucination) {\n return \"Negative Sentiment + Hallucination\";\n } else if (response.has_negative) {\n return \"Negative Sentiment\";\n } else if (response.has_hallucination) {\n return \"Hallucination Detected\";\n }\n return \"No Issues\";\n };\n\n const getIssueTypeColor = (response) => {\n if (response.has_negative && response.has_hallucination) {\n return \"bg-red-100 text-red-800 border-red-200\";\n } else if (response.has_negative) {\n return \"bg-red-50 text-red-700 border-red-200\";\n } else if (response.has_hallucination) {\n return \"bg-orange-50 text-orange-700 border-orange-200\";\n }\n return \"bg-green-50 text-green-700 border-green-200\";\n };\n\n // Separate responses by issue type\n const responsesWithNegative = contextData.response_data?.filter(r => r.has_negative) || [];\n const responsesWithHallucination = contextData.response_data?.filter(r => r.has_hallucination) || [];\n const responsesWithBothIssues = contextData.response_data?.filter(r => r.has_negative && r.has_hallucination) || [];\n\n return (\n
\n
\n \n

Prompt Sentiment Analysis

\n
\n\n {/* Prompt Info */}\n
\n
Analyzed Prompt
\n
\"{contextData.prompt_text}\"
\n
\n Topic: {contextData.topic_name}\n
\n
\n\n {/* Summary Stats */}\n
\n
\n
Total Responses
\n
\n {contextData.total_responses || 0}\n
\n
\n
\n
Negative Sentiment
\n
\n {responsesWithNegative.length}\n
\n
\n
\n
Hallucinations
\n
\n {responsesWithHallucination.length}\n
\n
\n
\n\n {/* Response Analysis */}\n {contextData.response_data?.length > 0 && (\n
\n
Response Analysis
\n
\n {contextData.response_data.map((response, index) => (\n
\n
\n
\n {getPlatformIcon(response.platform)}\n \n {response.platform}\n \n
\n
\n {getIssueTypeIcon(response)}\n \n {getIssueTypeText(response)}\n \n
\n
\n
\n {response.response_text}\n
\n
\n ))}\n
\n
\n )}\n\n {/* Issues Alert */}\n {contextData.responses_with_issues > 0 && (\n
\n {responsesWithBothIssues.length > 0 && (\n
\n
\n \n \n Critical Issues: Negative Sentiment + Hallucinations\n
\n

\n {responsesWithBothIssues.length} responses contain both negative sentiment and factual inaccuracies.\n Immediate content optimization required to improve brand perception and accuracy.\n

\n
\n )}\n\n {responsesWithNegative.length > responsesWithBothIssues.length && (\n
\n
\n \n Negative Sentiment Detected\n
\n

\n {responsesWithNegative.length - responsesWithBothIssues.length} responses contain negative sentiment about your brand.\n Consider content optimization to improve brand perception and messaging.\n

\n
\n )}\n\n {responsesWithHallucination.length > responsesWithBothIssues.length && (\n
\n
\n \n Hallucinations Detected\n
\n

\n {responsesWithHallucination.length - responsesWithBothIssues.length} responses contain factual inaccuracies or hallucinations.\n Review and correct misinformation to ensure accurate brand representation.\n

\n
\n )}\n
\n )}\n
\n );\n};\n\nexport default SentimentPromptContext;", "import React from 'react';\nimport { Hash, TrendingDown, AlertTriangle, MessageSquare } from 'lucide-react';\n\nconst SentimentThemeContext = ({ opportunity, projectId }) => {\n const contextData = opportunity?.context_data;\n\n if (!contextData || Object.keys(contextData).length === 0) {\n return (\n
\n

No sentiment theme data available

\n
\n );\n }\n\n const getFrequencyColor = (frequency) => {\n if (frequency >= 20) return 'text-red-600 bg-red-50'; // High frequency: 20+ mentions\n if (frequency >= 10) return 'text-orange-600 bg-orange-50'; // Medium: 10+ mentions\n if (frequency >= 5) return 'text-yellow-600 bg-yellow-50'; // Low-medium: 5+ mentions\n return 'text-blue-600 bg-blue-50'; // Low: <5 mentions\n };\n\n const getPlatformIcon = (platform) => {\n const icons = {\n 'ChatGPT': '\uD83E\uDD16',\n 'Claude': '\uD83E\uDDE0',\n 'Perplexity': '\uD83D\uDD0D',\n 'Google AI Overview': '\uD83D\uDD0E'\n };\n return icons[platform] || '\uD83E\uDD16';\n };\n\n return (\n
\n
\n \n

Sentiment Theme Analysis

\n
\n\n {/* Theme Info */}\n
\n
Negative Theme
\n
{contextData.theme_name}
\n
\n {contextData.theme_description}\n
\n {contextData.theme_type && (\n
\n Type: {contextData.theme_type}\n
\n )}\n
\n\n {/* Theme Metrics */}\n
\n
\n
Frequency
\n
\n {contextData.frequency || 0}\n
\n
Times mentioned
\n
\n
\n
Related Prompts
\n
\n {contextData.related_prompts_count || 0}\n
\n
Different prompts
\n
\n
\n\n {/* Related Prompts & Responses */}\n
\n
\n \n Related Responses ({contextData.related_prompts_count} prompts)\n
\n\n
\n {contextData.prompt_responses?.map((response, index) => (\n
\n
\n
\n {getPlatformIcon(response.platform)}\n \n {response.topic_name}\n \n
\n
\n {response.has_negative && (\n \n Negative\n \n )}\n {response.has_hallucination && (\n \n Hallucination\n \n )}\n
\n
\n
\n Prompt: \"{response.prompt_text.length > 60 ? response.prompt_text.substring(0, 60) + '...' : response.prompt_text}\"\n
\n
\n Response: {response.response_text}\n
\n
\n )) || []}\n
\n\n {(!contextData.prompt_responses || contextData.prompt_responses.length === 0) && (\n
\n No related responses found\n
\n )}\n
\n\n {/* Theme Action Alert */}\n
\n
\n
\n \n Reputation Risk\n
\n

\n This negative theme appears {contextData.frequency || 0} times across {contextData.related_prompts_count || 0} prompts.\n Consider content strategy to address these concerns and improve sentiment.\n

\n
\n
\n
\n );\n};\n\nexport default SentimentThemeContext;", "import React, { useState, useEffect, useCallback, useRef, useContext } from 'react';\nimport { Target, Search, Plus, ArrowRight, Unlink, X, List, Calendar, ChevronDown, Info } from 'lucide-react';\nimport { useLocation, useNavigate } from 'react-router-dom';\nimport axios from '../../AxiosConfig';\nimport OpportunityDetailsSideDrawer from './StrategySubcomponents/OpportunityDetailsSideDrawer';\nimport Timeline from './StrategySubcomponents/Timeline';\nimport { AuthContext } from '../../../context/AuthContext';\nimport { trackEvent } from '../../Analytics/mixpanel';\n\nconst Strategy = ({ projectId, project }) => {\n const [viewMode, setViewMode] = useState('list');\n const [opportunities, setOpportunities] = useState([]);\n const [groups, setGroups] = useState([]);\n const [loading, setLoading] = useState(true);\n\n // Filters\n const [objectiveFilter, setObjectiveFilter] = useState('');\n const [groupFilter, setGroupFilter] = useState('');\n const [impactFilter, setImpactFilter] = useState('');\n const [statusFilter, setStatusFilter] = useState('');\n const [searchQuery, setSearchQuery] = useState('');\n\n // Selection\n const [selectedOpportunities, setSelectedOpportunities] = useState([]);\n const [showFloatingActions, setShowFloatingActions] = useState(false);\n\n // Dropdowns\n const [activeDropdown, setActiveDropdown] = useState(null);\n\n // New group creation\n const [showNewGroupInput, setShowNewGroupInput] = useState(null);\n const [newGroupName, setNewGroupName] = useState('');\n\n // Side drawer\n const [selectedOpportunity, setSelectedOpportunity] = useState(null);\n const [showSideDrawer, setShowSideDrawer] = useState(false);\n\n // Tooltip state\n const [showObjectiveTooltip, setShowObjectiveTooltip] = useState(false);\n\n // Polling for opportunities with no tasks\n const pollingIntervalRef = useRef(null);\n\n // Track opportunities with pending group changes to avoid overwriting during polling\n const pendingGroupChangesRef = useRef(new Set());\n\n // Navigation hooks\n const location = useLocation();\n const navigate = useNavigate();\n\n // Auth context for user info\n const { user } = useContext(AuthContext);\n\n const objectives = [\n 'AI Visibility',\n 'Share of Voice',\n 'Sentiment',\n 'Citation',\n 'AI Readability',\n 'Content Coverage',\n 'Technical GEO'\n ];\n\n // Objective descriptions for tooltip\n const objectiveDescriptions = {\n 'AI Visibility': 'Improve how often your brand appears in AI-generated responses to relevant queries.',\n 'Share of Voice': 'Analyze and respond to competitor presence in AI search results.',\n 'Sentiment': 'Address negative mentions or misinformation about your brand in AI responses.',\n 'Citation': 'Increase how frequently your content is cited as a source by AI systems.',\n 'AI Readability': 'Optimize your content structure to be better understood and parsed by AI systems.',\n 'Content Coverage': 'Expand your content to cover important topics where you\\'re currently absent.',\n 'Technical GEO': 'Improve technical performance factors that affect AI content discovery and ranking.'\n };\n\n const impactLevels = [\n { value: 'Critical', color: { backgroundColor: '#FFF1F2', color: '#DC2626' } },\n { value: 'High', color: { backgroundColor: '#ECFDF5', color: '#007A55' } },\n { value: 'Medium', color: { backgroundColor: '#FFFBEB', color: '#BB4D00' } },\n { value: 'Low', color: { backgroundColor: '#F0F9FF', color: '#0069A8' } }\n ];\n\n const statusOptions = [\n { value: 'not_started', label: 'Not Started' },\n { value: 'in_progress', label: 'In Progress' },\n { value: 'complete', label: 'Complete' }\n ];\n\n // Track page view on mount\n useEffect(() => {\n trackEvent('Strategy Page Viewed', {\n project_id: projectId,\n user_id: user?.id,\n view_mode: viewMode,\n source: 'strategy'\n });\n }, [projectId]);\n\n const handleTaskUpdate = useCallback((opportunityId, updatedTasks) => {\n setOpportunities(prev =>\n prev.map(opp =>\n opp.id === opportunityId\n ? { ...opp, action_tasks: updatedTasks }\n : opp\n )\n );\n }, []);\n\n // Helper function to check if any opportunities need task data\n const hasOpportunitiesWithoutTasks = useCallback((opps) => {\n return opps.some(opp => {\n if (opp.opportunity_type === 19) {\n return false;\n }\n return !opp.action_tasks || opp.action_tasks.length === 0;\n });\n }, []);\n\n // Stop polling\n const stopPolling = useCallback(() => {\n if (pollingIntervalRef.current) {\n console.log('Stopping polling for opportunities');\n clearInterval(pollingIntervalRef.current);\n pollingIntervalRef.current = null;\n }\n }, []);\n\n // Targeted polling that only updates specific opportunities\n const pollForTaskUpdates = useCallback(async () => {\n try {\n const opportunitiesNeedingTasks = opportunities.filter(opp =>\n opp.opportunity_type !== 19 && (!opp.action_tasks || opp.action_tasks.length === 0)\n );\n\n if (opportunitiesNeedingTasks.length === 0) {\n stopPolling();\n return;\n }\n\n const updatePromises = opportunitiesNeedingTasks.map(async (opp) => {\n try {\n const response = await axios.get(`/api/projects/${projectId}/audit_category_opportunities/${opp.id}`);\n return response.data;\n } catch (error) {\n console.error(`Error fetching opportunity ${opp.id}:`, error);\n return null;\n }\n });\n\n const updatedOpportunities = await Promise.all(updatePromises);\n const validUpdates = updatedOpportunities.filter(opp => opp !== null);\n\n if (validUpdates.length > 0) {\n setOpportunities(prev => {\n return prev.map(opp => {\n const updated = validUpdates.find(u => u.id === opp.id);\n if (updated) {\n return {\n ...opp,\n action_tasks: updated.action_tasks\n };\n }\n return opp;\n });\n });\n\n if (selectedOpportunity) {\n const updatedSelected = validUpdates.find(opp => opp.id === selectedOpportunity.id);\n if (updatedSelected) {\n setSelectedOpportunity(prev => ({\n ...prev,\n action_tasks: updatedSelected.action_tasks\n }));\n }\n }\n }\n } catch (error) {\n console.error('Error during polling:', error);\n }\n }, [opportunities, selectedOpportunity, projectId, stopPolling]);\n\n // Start polling if needed\n const startPolling = useCallback(() => {\n if (pollingIntervalRef.current) return;\n\n console.log('Starting targeted polling for opportunities with no tasks');\n pollingIntervalRef.current = setInterval(() => {\n pollForTaskUpdates();\n }, 3000);\n }, [pollForTaskUpdates]);\n\n useEffect(() => {\n if (projectId) {\n fetchStrategyData();\n }\n }, [projectId]);\n\n // Handle URL parameter for opening specific opportunity\n useEffect(() => {\n const searchParams = new URLSearchParams(location.search);\n const opportunityId = searchParams.get('opportunityId');\n\n if (opportunityId && opportunities.length > 0) {\n const opportunity = opportunities.find(opp => opp.id === parseInt(opportunityId));\n\n if (opportunity) {\n setSelectedOpportunity(opportunity);\n setShowSideDrawer(true);\n\n navigate(`/projects/${projectId}/strategy`, { replace: true });\n }\n }\n }, [opportunities, location.search, projectId, navigate]);\n\n // Effect to manage polling based on opportunities state\n useEffect(() => {\n if (opportunities.length > 0) {\n if (hasOpportunitiesWithoutTasks(opportunities)) {\n startPolling();\n } else {\n stopPolling();\n }\n }\n\n return () => {\n stopPolling();\n };\n }, [opportunities, hasOpportunitiesWithoutTasks, startPolling, stopPolling]);\n\n const fetchStrategyData = async () => {\n try {\n if (loading) setLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/strategy`);\n const newOpportunities = response.data.opportunities || [];\n const newGroups = response.data.strategic_groups || [];\n\n setOpportunities(newOpportunities);\n setGroups(newGroups);\n\n if (selectedOpportunity) {\n const updatedOpportunity = newOpportunities.find(opp => opp.id === selectedOpportunity.id);\n if (updatedOpportunity) {\n setSelectedOpportunity(updatedOpportunity);\n }\n }\n } catch (error) {\n console.error('Error fetching strategy data:', error);\n } finally {\n if (loading) setLoading(false);\n }\n };\n\n const handleViewModeChange = (mode) => {\n trackEvent('Strategy View Mode Changed', {\n project_id: projectId,\n user_id: user?.id,\n previous_mode: viewMode,\n new_mode: mode,\n source: 'strategy'\n });\n setViewMode(mode);\n };\n\n const handleFilterChange = (filterType, value) => {\n trackEvent('Strategy Filter Applied', {\n project_id: projectId,\n user_id: user?.id,\n filter_type: filterType,\n filter_value: value || 'all',\n source: 'strategy'\n });\n\n switch (filterType) {\n case 'objective':\n setObjectiveFilter(value);\n break;\n case 'group':\n setGroupFilter(value);\n break;\n case 'impact':\n setImpactFilter(value);\n break;\n case 'status':\n setStatusFilter(value);\n break;\n }\n };\n\n const handleSearchChange = (value) => {\n setSearchQuery(value);\n // Debounce tracking for search\n if (value.length > 2) {\n trackEvent('Strategy Search Used', {\n project_id: projectId,\n user_id: user?.id,\n search_query_length: value.length,\n source: 'strategy'\n });\n }\n };\n\n const handleGroupAssignment = async (opportunityId, groupId) => {\n const opportunity = opportunities.find(opp => opp.id === opportunityId);\n const group = groups.find(g => g.id === groupId);\n\n trackEvent('Opportunity Group Assigned', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunityId,\n opportunity_title: opportunity?.title,\n group_id: groupId,\n group_name: group?.title || 'None',\n previous_group_id: opportunity?.strategic_group_id,\n source: 'strategy'\n });\n\n setOpportunities(prev =>\n prev.map(opp =>\n opp.id === opportunityId\n ? { ...opp, strategic_group_id: groupId }\n : opp\n )\n );\n\n try {\n await axios.patch(`/api/projects/${projectId}/strategy/opportunities/${opportunityId}/group`, {\n strategic_group_id: groupId\n });\n } catch (error) {\n console.error('Error assigning group:', error);\n fetchStrategyData();\n }\n };\n\n const handleRemoveFromGroup = async (opportunityId) => {\n trackEvent('Opportunity Removed From Group', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunityId,\n source: 'strategy'\n });\n await handleGroupAssignment(opportunityId, null);\n };\n\n const handleOpportunitySelection = useCallback((opportunityId) => {\n setSelectedOpportunities(prev => {\n const newSelection = prev.includes(opportunityId)\n ? prev.filter(id => id !== opportunityId)\n : [...prev, opportunityId];\n\n setShowFloatingActions(newSelection.length > 0);\n return newSelection;\n });\n }, []);\n\n const handleSelectAll = () => {\n const allSelected = selectedOpportunities.length === filteredOpportunities.length && filteredOpportunities.length > 0;\n\n trackEvent('Strategy Select All Toggled', {\n project_id: projectId,\n user_id: user?.id,\n action: allSelected ? 'deselect_all' : 'select_all',\n count: allSelected ? 0 : filteredOpportunities.length,\n source: 'strategy'\n });\n\n if (allSelected) {\n setSelectedOpportunities([]);\n setShowFloatingActions(false);\n } else {\n const allIds = filteredOpportunities.map(opp => opp.id);\n setSelectedOpportunities(allIds);\n setShowFloatingActions(true);\n }\n };\n\n const handleBulkGroupAssignment = async (groupId) => {\n const group = groups.find(g => g.id === groupId);\n\n trackEvent('Bulk Group Assignment', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_count: selectedOpportunities.length,\n group_id: groupId,\n group_name: group?.title,\n source: 'strategy'\n });\n\n setOpportunities(prev =>\n prev.map(opp =>\n selectedOpportunities.includes(opp.id)\n ? { ...opp, strategic_group_id: groupId }\n : opp\n )\n );\n\n const idsToUpdate = [...selectedOpportunities];\n setSelectedOpportunities([]);\n setShowFloatingActions(false);\n\n try {\n await axios.post(`/api/projects/${projectId}/strategy/opportunities/bulk_group_assignment`, {\n opportunity_ids: idsToUpdate,\n strategic_group_id: groupId\n });\n } catch (error) {\n console.error('Error in bulk group assignment:', error);\n fetchStrategyData();\n }\n };\n\n const handleBulkRemoveFromGroup = async () => {\n trackEvent('Bulk Remove From Group', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_count: selectedOpportunities.length,\n source: 'strategy'\n });\n\n setOpportunities(prev =>\n prev.map(opp =>\n selectedOpportunities.includes(opp.id)\n ? { ...opp, strategic_group_id: null }\n : opp\n )\n );\n\n const idsToUpdate = [...selectedOpportunities];\n setSelectedOpportunities([]);\n setShowFloatingActions(false);\n\n try {\n await axios.delete(`/api/projects/${projectId}/strategy/opportunities/bulk_remove_from_groups`, {\n data: { opportunity_ids: idsToUpdate }\n });\n } catch (error) {\n console.error('Error removing from groups:', error);\n fetchStrategyData();\n }\n };\n\n const handleCreateGroup = async (opportunityId) => {\n if (!newGroupName.trim()) return;\n\n trackEvent('Strategic Group Created', {\n project_id: projectId,\n user_id: user?.id,\n group_name: newGroupName.trim(),\n created_from: opportunityId === 'bulk' ? 'bulk_action' : 'single_opportunity',\n source: 'strategy'\n });\n\n const groupId = await createNewGroup(newGroupName);\n if (groupId) {\n await handleGroupAssignment(opportunityId, groupId);\n }\n\n setShowNewGroupInput(null);\n setNewGroupName('');\n };\n\n const createNewGroup = async (groupName) => {\n try {\n const response = await axios.post(`/api/projects/${projectId}/strategy/strategic_groups`, {\n title: groupName\n });\n\n const newGroup = {\n id: response.data.id,\n title: response.data.title,\n created_at: response.data.created_at\n };\n\n setGroups(prev => [...prev, newGroup]);\n\n return response.data.id;\n } catch (error) {\n console.error('Error creating group:', error);\n return null;\n }\n };\n\n const handleOpportunityDetails = (opportunity) => {\n trackEvent('Opportunity Details Opened', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunity.id,\n opportunity_title: opportunity.title,\n opportunity_objective: opportunity.objective,\n opportunity_impact: opportunity.impact,\n has_tasks: opportunity.action_tasks?.length > 0,\n task_count: opportunity.action_tasks?.length || 0,\n source: 'strategy'\n });\n\n setSelectedOpportunity(opportunity);\n setShowSideDrawer(true);\n };\n\n const handleCloseSideDrawer = () => {\n trackEvent('Opportunity Details Closed', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: selectedOpportunity?.id,\n source: 'strategy'\n });\n\n setShowSideDrawer(false);\n setSelectedOpportunity(null);\n };\n\n const handleSideDrawerGroupAssignment = async (opportunityId, groupId) => {\n await handleGroupAssignment(opportunityId, groupId);\n\n if (selectedOpportunity && selectedOpportunity.id === opportunityId) {\n setSelectedOpportunity(prev => ({\n ...prev,\n strategic_group_id: groupId\n }));\n }\n };\n\n // Derive an overall status for an opportunity based on its tasks\n // - complete: every task is status 2\n // - not_started: no tasks, or every task is status 0\n // - in_progress: anything in between\n // Opportunities still loading tasks (no tasks yet, opportunity_type !== 19) are treated as not_started\n const getOpportunityStatus = (opportunity) => {\n const tasks = opportunity.action_tasks || [];\n if (tasks.length === 0) return 'not_started';\n\n const completedCount = tasks.filter(t => t.status === 2).length;\n const inProgressCount = tasks.filter(t => t.status === 1).length;\n\n if (completedCount === tasks.length) return 'complete';\n if (completedCount === 0 && inProgressCount === 0) return 'not_started';\n return 'in_progress';\n };\n\n // Filter opportunities\n const filteredOpportunities = opportunities.filter(opp => {\n const matchesObjective = !objectiveFilter || opp.objective === objectiveFilter;\n const matchesGroup = !groupFilter || (groupFilter === 'ungrouped' ? !opp.strategic_group_id : opp.strategic_group_id === parseInt(groupFilter));\n const matchesImpact = !impactFilter || opp.impact === impactFilter;\n const matchesStatus = !statusFilter || getOpportunityStatus(opp) === statusFilter;\n const matchesSearch = !searchQuery || opp.title.toLowerCase().includes(searchQuery.toLowerCase());\n\n return matchesObjective && matchesGroup && matchesImpact && matchesStatus && matchesSearch;\n });\n\n const formatDate = (dateString) => {\n return new Date(dateString).toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric'\n });\n };\n\n const getTasksCompleted = (opportunity) => {\n if (!opportunity.action_tasks || opportunity.action_tasks.length === 0) {\n return { completed: 0, total: 0, isLoading: true };\n }\n\n const completed = opportunity.action_tasks.filter(task => task.status === 2).length;\n const total = opportunity.action_tasks.length;\n\n return { completed, total, isLoading: false };\n };\n\n const getImpactColor = (impact) => {\n const level = impactLevels.find(level => level.value === impact);\n return level ? level.color : { backgroundColor: '#F3F4F6', color: '#374151' };\n };\n\n if (loading) {\n return (\n
\n
\n
\n );\n }\n\n return (\n <>\n
\n {/* Floating Actions */}\n {showFloatingActions && (\n \n )}\n\n {/* Header */}\n
\n
\n
\n

Strategy

\n

\n Build out your strategy by reviewing the actionable tasks for each saved opportunity. Create groups and add timelines to formulate the GEO plan for your client.\n

\n
\n
\n handleViewModeChange('list')}\n className={`flex items-center px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${\n viewMode === 'list'\n ? 'bg-white shadow-sm'\n : 'text-gray-600 hover:text-gray-900'\n }`}\n style={{\n color: viewMode === 'list' ? '#4F46E5' : undefined\n }}\n >\n \n List View\n \n handleViewModeChange('timeline')}\n className={`flex items-center px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${\n viewMode === 'timeline'\n ? 'bg-white shadow-sm'\n : 'text-gray-600 hover:text-gray-900'\n }`}\n style={{\n color: viewMode === 'timeline' ? '#4F46E5' : undefined\n }}\n >\n \n Timeline\n \n
\n
\n
\n\n {/* Content - List or Timeline View */}\n {viewMode === 'list' ? (\n
\n {/* Filters Row */}\n
\n
\n {/* Objective Filter */}\n
\n handleFilterChange('objective', e.target.value)}\n className=\"min-w-[150px] px-3 py-2 pr-8 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500 bg-white\"\n >\n \n {objectives.map(objective => (\n \n ))}\n \n
\n\n {/* Group Filter */}\n
\n handleFilterChange('group', e.target.value)}\n className=\"min-w-[120px] px-3 py-2 pr-8 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500 bg-white\"\n >\n \n \n {groups.map(group => (\n \n ))}\n \n
\n\n {/* Impact Filter */}\n
\n handleFilterChange('impact', e.target.value)}\n className=\"min-w-[120px] px-3 py-2 pr-8 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500 bg-white\"\n >\n \n {impactLevels.map(level => (\n \n ))}\n \n
\n\n {/* Status Filter */}\n
\n handleFilterChange('status', e.target.value)}\n className=\"min-w-[130px] px-3 py-2 pr-8 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500 bg-white\"\n >\n \n {statusOptions.map(option => (\n \n ))}\n \n
\n
\n\n
\n {/* Search */}\n
\n \n handleSearchChange(e.target.value)}\n className=\"pl-10 w-64 pr-4 py-2 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500\"\n />\n
\n
\n
\n\n {/* Table Container */}\n
\n
\n
\n {filteredOpportunities.length === 0 ? (\n
\n \n

No opportunities found

\n

\n {opportunities.length === 0\n ? \"No opportunities have been added to strategy yet.\"\n : \"Try adjusting your filters to see more results.\"\n }\n

\n
\n ) : (\n \n \n \n \n \n \n \n \n \n \n \n \n \n {filteredOpportunities.map((opportunity) => {\n const { completed, total, isLoading } = getTasksCompleted(opportunity);\n\n return (\n \n \n \n \n \n \n \n \n \n );\n })}\n \n
\n 0}\n onChange={handleSelectAll}\n />\n Opportunity\n
\n Objective\n
setShowObjectiveTooltip(true)}\n onMouseLeave={() => setShowObjectiveTooltip(false)}>\n \n {showObjectiveTooltip && (\n
\n
\n {objectives.map((objective) => (\n
\n {objective}:{' '}\n {objectiveDescriptions[objective]}\n
\n ))}\n
\n
\n )}\n
\n
\n
ImpactTasksGroupDetails
\n handleOpportunitySelection(opportunity.id)}\n />\n \n
\n
\n {opportunity.title}\n
\n
\n {formatDate(opportunity.created_at)}\n
\n
\n
\n \n {opportunity.objective}\n \n \n \n {opportunity.impact}\n \n \n {isLoading ? 'Loading...' : `${completed}/${total} complete`}\n \n {opportunity.strategic_group_id ? (\n
\n
\n \n {groups.find(g => g.id === opportunity.strategic_group_id)?.title || 'Unknown'}\n \n handleRemoveFromGroup(opportunity.id)}\n className=\"text-gray-400 hover:text-red-500 flex-shrink-0\"\n >\n \n \n
\n
\n ) : (\n
\n {showNewGroupInput === `opportunity-${opportunity.id}` ? (\n
\n setNewGroupName(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {\n handleCreateGroup(opportunity.id);\n } else if (e.key === 'Escape') {\n setShowNewGroupInput(null);\n setNewGroupName('');\n }\n }}\n className=\"px-2 py-1 text-sm border border-gray-300 rounded-md w-24\"\n autoFocus\n />\n handleCreateGroup(opportunity.id)}\n className=\"text-green-600 hover:text-green-700\"\n >\n \n \n {\n setShowNewGroupInput(null);\n setNewGroupName('');\n }}\n className=\"text-gray-400 hover:text-gray-600\"\n >\n \n \n
\n ) : (\n {\n if (e.target.value === 'new') {\n setShowNewGroupInput(`opportunity-${opportunity.id}`);\n setNewGroupName('');\n } else if (e.target.value) {\n handleGroupAssignment(opportunity.id, parseInt(e.target.value));\n }\n e.target.value = '';\n }}\n className=\"px-3 py-1 border border-gray-300 rounded-md text-sm text-gray-500\"\n style={{ width: '140px' }}\n defaultValue=\"\"\n >\n \n {groups.map(group => (\n \n ))}\n \n \n )}\n
\n )}\n
\n handleOpportunityDetails(opportunity)}\n className=\"inline-flex items-center px-3 py-1.5 border border-gray-300 text-xs font-medium rounded text-gray-700 bg-white hover:bg-gray-50\"\n >\n \n Details\n \n
\n )}\n
\n
\n
\n
\n ) : (\n /* Timeline View */\n handleFilterChange('objective', value)}\n groupFilter={groupFilter}\n setGroupFilter={(value) => handleFilterChange('group', value)}\n impactFilter={impactFilter}\n setImpactFilter={(value) => handleFilterChange('impact', value)}\n statusFilter={statusFilter}\n setStatusFilter={(value) => handleFilterChange('status', value)}\n searchQuery={searchQuery}\n setSearchQuery={handleSearchChange}\n onOpportunityDetails={handleOpportunityDetails}\n onGroupAssignment={handleGroupAssignment}\n onUpdateGroup={(groupId, groupData) => {\n setGroups(prev =>\n prev.map(group =>\n group.id === groupId\n ? { ...group, ...groupData }\n : group\n )\n );\n }}\n onCreateGroup={(newGroup) => {\n setGroups(prev => [...prev, newGroup]);\n }}\n projectId={projectId}\n user={user}\n />\n )}\n\n {/* Floating Actions */}\n {showFloatingActions && (\n
\n \n {selectedOpportunities.length} selected\n \n\n
\n {showNewGroupInput === 'bulk' ? (\n
\n setNewGroupName(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {\n handleCreateGroup('bulk');\n } else if (e.key === 'Escape') {\n setShowNewGroupInput(null);\n setNewGroupName('');\n }\n }}\n className=\"px-2 py-1 text-sm border border-gray-300 rounded-md w-24\"\n autoFocus\n />\n {\n if (!newGroupName.trim()) return;\n const groupId = await createNewGroup(newGroupName);\n if (groupId) {\n await handleBulkGroupAssignment(groupId);\n }\n setShowNewGroupInput(null);\n setNewGroupName('');\n }}\n className=\"text-green-600 hover:text-green-700\"\n >\n \n \n {\n setShowNewGroupInput(null);\n setNewGroupName('');\n }}\n className=\"text-gray-400 hover:text-gray-600\"\n >\n \n \n
\n ) : (\n {\n if (e.target.value === 'new') {\n setShowNewGroupInput('bulk');\n setNewGroupName('');\n } else if (e.target.value) {\n handleBulkGroupAssignment(parseInt(e.target.value));\n }\n e.target.value = '';\n }}\n className=\"px-3 py-2 border border-gray-300 rounded-md text-sm\"\n defaultValue=\"\"\n >\n \n {groups.map(group => (\n \n ))}\n \n \n )}\n
\n\n \n Ungroup\n \n\n {\n setSelectedOpportunities([]);\n setShowFloatingActions(false);\n }}\n className=\"p-2 text-gray-400 hover:text-gray-600\"\n >\n \n \n
\n )}\n
\n\n {/* Opportunity Details Side Drawer */}\n \n \n );\n};\n\n// Debounce utility function\nfunction debounce(func, wait) {\n let timeout;\n return function executedFunction(...args) {\n const later = () => {\n clearTimeout(timeout);\n func(...args);\n };\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n };\n}\n\nexport default Strategy;", "import React, { useState, useEffect } from 'react';\nimport {\n X,\n ChevronRight,\n ChevronDown,\n Plus,\n Trash2,\n Zap,\n Loader2\n} from 'lucide-react';\nimport axios from '../../../AxiosConfig';\nimport { trackEvent } from '../../../Analytics/mixpanel';\n\nconst OpportunityDetailsSideDrawer = ({\n opportunity,\n isOpen,\n onClose,\n groups,\n onGroupAssignment,\n onCreateNewGroup,\n onTaskUpdate,\n projectId,\n user\n }) => {\n const [expandedTasks, setExpandedTasks] = useState(new Set());\n const [tasks, setTasks] = useState([]);\n const [showNewTaskForm, setShowNewTaskForm] = useState(false);\n const [newTaskTitle, setNewTaskTitle] = useState('');\n const [newTaskDescription, setNewTaskDescription] = useState('');\n const [loading, setLoading] = useState(false);\n const [taskToDelete, setTaskToDelete] = useState(null);\n const [isVisible, setIsVisible] = useState(false);\n const [shouldRender, setShouldRender] = useState(false);\n const [updatingTaskStatus, setUpdatingTaskStatus] = useState(new Set());\n const [deletingTasks, setDeletingTasks] = useState(new Set());\n\n useEffect(() => {\n if (isOpen && opportunity) {\n setTasks(opportunity.action_tasks || []);\n setShouldRender(true);\n setTimeout(() => setIsVisible(true), 10);\n } else {\n setIsVisible(false);\n const timer = setTimeout(() => setShouldRender(false), 300);\n return () => clearTimeout(timer);\n }\n }, [isOpen, opportunity]);\n\n if (!shouldRender) return null;\n\n const toggleTaskExpansion = (taskId) => {\n const newExpanded = new Set(expandedTasks);\n const wasExpanded = newExpanded.has(taskId);\n\n if (wasExpanded) {\n newExpanded.delete(taskId);\n } else {\n newExpanded.add(taskId);\n\n trackEvent('Task Details Expanded', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunity?.id,\n task_id: taskId,\n source: 'side_drawer'\n });\n }\n setExpandedTasks(newExpanded);\n };\n\n const handleStatusChange = async (taskId, newStatus) => {\n const task = tasks.find(t => t.id === taskId);\n const statusLabels = { 0: 'Not Started', 1: 'In Progress', 2: 'Complete' };\n\n trackEvent('Task Status Changed', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunity?.id,\n opportunity_title: opportunity?.title,\n task_id: taskId,\n task_title: task?.title,\n previous_status: statusLabels[task?.status],\n new_status: statusLabels[newStatus],\n source: 'side_drawer'\n });\n\n try {\n setUpdatingTaskStatus(prev => new Set(prev).add(taskId));\n\n await axios.patch(`/api/projects/${projectId}/strategy/action_tasks/${taskId}`, {\n status: newStatus\n });\n\n const updatedTasks = tasks.map(task =>\n task.id === taskId\n ? { ...task, status: newStatus }\n : task\n );\n\n setTasks(updatedTasks);\n\n if (onTaskUpdate && opportunity) {\n onTaskUpdate(opportunity.id, updatedTasks);\n }\n } catch (error) {\n console.error('Error updating task status:', error);\n } finally {\n setUpdatingTaskStatus(prev => {\n const newSet = new Set(prev);\n newSet.delete(taskId);\n return newSet;\n });\n }\n };\n\n const handleDeleteTask = async (taskId) => {\n const task = tasks.find(t => t.id === taskId);\n\n trackEvent('Task Deleted', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunity?.id,\n opportunity_title: opportunity?.title,\n task_id: taskId,\n task_title: task?.title,\n source: 'side_drawer'\n });\n\n try {\n setDeletingTasks(prev => new Set(prev).add(taskId));\n\n await axios.delete(`/api/projects/${projectId}/strategy/action_tasks/${taskId}`);\n const updatedTasks = tasks.filter(task => task.id !== taskId);\n setTasks(updatedTasks);\n\n if (onTaskUpdate && opportunity) {\n onTaskUpdate(opportunity.id, updatedTasks);\n }\n\n setTaskToDelete(null);\n } catch (error) {\n console.error('Error deleting task:', error);\n setTaskToDelete(null);\n } finally {\n setDeletingTasks(prev => {\n const newSet = new Set(prev);\n newSet.delete(taskId);\n return newSet;\n });\n }\n };\n\n const handleDeleteConfirm = (taskId) => {\n setTaskToDelete(taskId);\n };\n\n const handleDeleteCancel = () => {\n setTaskToDelete(null);\n };\n\n const handleShowNewTaskForm = () => {\n trackEvent('Add Task Form Opened', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunity?.id,\n opportunity_title: opportunity?.title,\n source: 'side_drawer'\n });\n setShowNewTaskForm(true);\n };\n\n const handleAddTask = async () => {\n if (!newTaskTitle.trim() || !opportunity) return;\n\n trackEvent('Task Created', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunity?.id,\n opportunity_title: opportunity?.title,\n task_title: newTaskTitle.trim(),\n has_description: !!newTaskDescription.trim(),\n source: 'side_drawer'\n });\n\n try {\n setLoading(true);\n const response = await axios.post(`/api/projects/${projectId}/strategy/opportunities/${opportunity.id}/action_tasks`, {\n title: newTaskTitle,\n description: newTaskDescription,\n action_type: 4,\n status: 0\n });\n\n const updatedTasks = [...tasks, response.data];\n setTasks(updatedTasks);\n\n if (onTaskUpdate) {\n onTaskUpdate(opportunity.id, updatedTasks);\n }\n\n setNewTaskTitle('');\n setNewTaskDescription('');\n setShowNewTaskForm(false);\n } catch (error) {\n console.error('Error creating task:', error);\n } finally {\n setLoading(false);\n }\n };\n\n const handleGroupChange = async (e) => {\n const value = e.target.value;\n\n if (value === 'new') {\n trackEvent('Side Drawer New Group Initiated', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunity?.id,\n source: 'side_drawer'\n });\n\n const groupName = prompt('Enter new group name:');\n if (groupName && opportunity) {\n trackEvent('Side Drawer Group Created', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunity?.id,\n group_name: groupName,\n source: 'side_drawer'\n });\n\n onCreateNewGroup(groupName).then(groupId => {\n if (groupId) onGroupAssignment(opportunity.id, groupId);\n });\n }\n } else if (value && opportunity) {\n const group = groups.find(g => g.id === parseInt(value));\n\n trackEvent('Side Drawer Group Assigned', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunity?.id,\n opportunity_title: opportunity?.title,\n group_id: parseInt(value),\n group_name: group?.title,\n source: 'side_drawer'\n });\n\n onGroupAssignment(opportunity.id, parseInt(value));\n }\n e.target.value = '';\n };\n\n const handleRemoveFromGroup = () => {\n trackEvent('Side Drawer Group Removed', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunity?.id,\n opportunity_title: opportunity?.title,\n previous_group_id: opportunity?.strategic_group_id,\n source: 'side_drawer'\n });\n\n onGroupAssignment(opportunity.id, null);\n };\n\n const getImpactColor = (impact) => {\n const colors = {\n 'Critical': { backgroundColor: '#FFF1F2', color: '#DC2626' },\n 'High': { backgroundColor: '#ECFDF5', color: '#007A55' },\n 'Medium': { backgroundColor: '#FFFBEB', color: '#BB4D00' },\n 'Low': { backgroundColor: '#F0F9FF', color: '#0069A8' }\n };\n return colors[impact] || { backgroundColor: '#F3F4F6', color: '#374151' };\n };\n\n const formatDate = (dateString) => {\n return new Date(dateString).toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n year: 'numeric'\n });\n };\n\n const getCompletionDate = () => {\n if (!tasks || tasks.length === 0) {\n return '-';\n }\n\n const completedTasks = tasks.filter(task => task.status === 2);\n if (completedTasks.length === 0 || completedTasks.length !== tasks.length) {\n return '-';\n }\n\n try {\n const latestDate = completedTasks.reduce((latest, task) => {\n const taskDate = new Date(task.updated_at);\n const latestDateObj = new Date(latest);\n return taskDate > latestDateObj ? task.updated_at : latest;\n }, completedTasks[0].updated_at);\n\n const dateObj = new Date(latestDate);\n if (isNaN(dateObj.getTime())) {\n return '-';\n }\n\n return formatDate(latestDate);\n } catch (error) {\n return '-';\n }\n };\n\n return (\n
\n {/* Backdrop */}\n \n\n {/* Side Drawer */}\n \n {/* Header */}\n
\n

\n {opportunity?.title || ''}\n

\n \n \n \n
\n\n {/* Objective and Impact */}\n
\n
\n \n {opportunity?.objective || ''}\n \n \n {opportunity?.impact || ''}\n \n
\n
\n\n {/* Full Width Grey Border */}\n
\n\n
\n {/* Details Section */}\n
\n

Details

\n\n
\n {/* Group Row */}\n
\n Group\n
\n {opportunity?.strategic_group_id ? (\n
\n \n {groups.find(g => g.id === opportunity.strategic_group_id)?.title || 'Unknown'}\n \n \n \n \n
\n ) : (\n \n \n {groups.map(group => (\n \n ))}\n \n \n )}\n
\n
\n\n {/* Added On Row */}\n
\n Added on\n {opportunity?.created_at ? formatDate(opportunity.created_at) : ''}\n
\n\n {/* Completion Row */}\n
\n Completion\n {getCompletionDate()}\n
\n
\n
\n\n {/* Why these tasks section */}\n {opportunity?.tasks_explanation && (\n
\n

Why these tasks?

\n\n
\n
\n \n

More information on opportunity & tasks

\n
\n

\n {opportunity.tasks_explanation}\n

\n
\n
\n )}\n\n {/* Tasks Section */}\n
\n
\n

\n Tasks ({tasks.length === 0 ? 'Loading...' : tasks.length})\n

\n \n \n Add task\n \n
\n\n {/* New Task Form */}\n {showNewTaskForm && (\n
\n
\n
\n setNewTaskTitle(e.target.value)}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500 transition-colors duration-200\"\n disabled={loading}\n />\n
\n
\n setNewTaskDescription(e.target.value)}\n rows={3}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500 transition-colors duration-200\"\n disabled={loading}\n />\n
\n
\n \n {loading && }\n {loading ? 'Adding...' : 'Add Task'}\n \n {\n setShowNewTaskForm(false);\n setNewTaskTitle('');\n setNewTaskDescription('');\n }}\n disabled={loading}\n className=\"px-3 py-1.5 border border-gray-300 text-gray-700 text-xs font-medium rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200\"\n >\n Cancel\n \n
\n
\n
\n )}\n\n {/* Task Cards */}\n
\n {tasks.map((task) => {\n const isExpanded = expandedTasks.has(task.id);\n const isUpdatingStatus = updatingTaskStatus.has(task.id);\n const isDeleting = deletingTasks.has(task.id);\n\n return (\n
\n {/* Task Header */}\n !isUpdatingStatus && !isDeleting && toggleTaskExpansion(task.id)}\n >\n \n\n \n {task.title}\n \n\n {isUpdatingStatus ? (\n
\n \n Updating...\n
\n ) : (\n {\n e.stopPropagation();\n handleStatusChange(task.id, parseInt(e.target.value));\n }}\n className=\"px-2 py-1 text-xs font-medium rounded bg-white border border-gray-300 text-gray-700 min-w-24 transition-colors duration-200 focus:ring-indigo-500 focus:border-indigo-500\"\n onClick={(e) => e.stopPropagation()}\n disabled={isDeleting}\n >\n \n \n \n \n )}\n\n {taskToDelete === task.id ? (\n
\n {isDeleting ? (\n
\n \n Deleting...\n
\n ) : (\n <>\n {\n e.stopPropagation();\n handleDeleteTask(task.id);\n }}\n className=\"px-2 py-1 text-xs font-medium text-white bg-red-600 rounded hover:bg-red-700 transition-colors duration-200\"\n >\n Delete\n \n {\n e.stopPropagation();\n handleDeleteCancel();\n }}\n className=\"px-2 py-1 text-xs font-medium text-gray-600 bg-gray-100 rounded hover:bg-gray-200 transition-colors duration-200\"\n >\n Cancel\n \n \n )}\n
\n ) : (\n {\n e.stopPropagation();\n handleDeleteConfirm(task.id);\n }}\n className=\"text-gray-400 hover:text-red-500 transition-colors duration-200\"\n disabled={isUpdatingStatus || isDeleting}\n >\n \n \n )}\n
\n\n {/* Expanded Content */}\n {isExpanded && (\n
\n {task.description && (\n

\n {task.description}\n

\n )}\n\n {task.subpoints && task.subpoints.length > 0 && (\n
\n
Additional Details:
\n
\n {task.subpoints.map((subpoint, index) => (\n
\n
\n \n {index + 1}\n \n
\n \n {subpoint.text}\n \n
\n ))}\n
\n
\n )}\n
\n )}\n
\n );\n })}\n
\n\n {tasks.length === 0 && (\n
\n Loading tasks...\n
\n )}\n
\n
\n
\n \n );\n};\n\nexport default OpportunityDetailsSideDrawer;", "import React, { useState, useEffect, useRef, useMemo } from 'react';\nimport axios from '../../../AxiosConfig';\nimport {\n Search,\n Plus,\n Edit3,\n X,\n Check,\n Calendar as CalendarIcon\n} from 'lucide-react';\nimport { trackEvent } from '../../../Analytics/mixpanel';\n\n// Helper functions for date field options\nconst months = [\n { value: '01', label: 'January' },\n { value: '02', label: 'February' },\n { value: '03', label: 'March' },\n { value: '04', label: 'April' },\n { value: '05', label: 'May' },\n { value: '06', label: 'June' },\n { value: '07', label: 'July' },\n { value: '08', label: 'August' },\n { value: '09', label: 'September' },\n { value: '10', label: 'October' },\n { value: '11', label: 'November' },\n { value: '12', label: 'December' }\n];\n\nconst getDaysInMonth = (month, year) => {\n return new Date(year, month, 0).getDate();\n};\n\nconst generateYears = () => {\n const currentYear = new Date().getFullYear();\n const years = [];\n for (let year = currentYear - 2; year <= currentYear + 10; year++) {\n years.push(year);\n }\n return years;\n};\n\nconst parseDate = (dateString) => {\n if (!dateString) return { month: '', day: '', year: '' };\n const date = new Date(dateString + 'T00:00:00');\n if (isNaN(date.getTime())) {\n return { month: '', day: '', year: '' };\n }\n return {\n month: String(date.getMonth() + 1).padStart(2, '0'),\n day: String(date.getDate()).padStart(2, '0'),\n year: String(date.getFullYear())\n };\n};\n\nconst formatDate = (month, day, year) => {\n if (!month || !day || !year) return '';\n const monthStr = String(month).padStart(2, '0');\n const dayStr = String(day).padStart(2, '0');\n const yearStr = String(year);\n return `${yearStr}-${monthStr}-${dayStr}`;\n};\n\n// Calendar component\nconst Calendar = ({ value, onChange, label }) => {\n const [viewDate, setViewDate] = useState(() => {\n if (value) {\n return new Date(value + 'T00:00:00');\n }\n return new Date();\n });\n\n const selectedDate = value ? new Date(value + 'T00:00:00') : null;\n\n const monthNames = [\n \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n ];\n\n const dayNames = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n\n const getDaysInMonth = (date) => {\n return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();\n };\n\n const getFirstDayOfMonth = (date) => {\n return new Date(date.getFullYear(), date.getMonth(), 1).getDay();\n };\n\n const handleDateClick = (day) => {\n const newDate = new Date(viewDate.getFullYear(), viewDate.getMonth(), day);\n const isoString = newDate.toISOString().split('T')[0];\n onChange(isoString);\n };\n\n const handlePrevMonth = () => {\n setViewDate(new Date(viewDate.getFullYear(), viewDate.getMonth() - 1, 1));\n };\n\n const handleNextMonth = () => {\n setViewDate(new Date(viewDate.getFullYear(), viewDate.getMonth() + 1, 1));\n };\n\n const handleClear = () => {\n onChange('');\n };\n\n const renderCalendarDays = () => {\n const daysInMonth = getDaysInMonth(viewDate);\n const firstDay = getFirstDayOfMonth(viewDate);\n const days = [];\n\n for (let i = 0; i < firstDay; i++) {\n days.push(\n
\n );\n }\n\n for (let day = 1; day <= daysInMonth; day++) {\n const isSelected = selectedDate &&\n selectedDate.getDate() === day &&\n selectedDate.getMonth() === viewDate.getMonth() &&\n selectedDate.getFullYear() === viewDate.getFullYear();\n\n const isToday = new Date().toDateString() === new Date(viewDate.getFullYear(), viewDate.getMonth(), day).toDateString();\n\n days.push(\n handleDateClick(day)}\n className={`h-8 w-8 text-xs rounded-md flex items-center justify-center transition-colors ${\n isSelected\n ? 'bg-indigo-600 text-white font-medium'\n : isToday\n ? 'bg-indigo-100 text-indigo-600 font-medium'\n : 'hover:bg-gray-100 text-gray-700'\n }`}\n >\n {day}\n \n );\n }\n\n return days;\n };\n\n return (\n
\n
\n \n {value && (\n \n Clear\n \n )}\n
\n\n
\n
\n \n \n \n \n \n\n

\n {monthNames[viewDate.getMonth()]} {viewDate.getFullYear()}\n

\n\n \n \n \n \n \n
\n\n
\n {dayNames.map(day => (\n
\n {day}\n
\n ))}\n
\n\n
\n {renderCalendarDays()}\n
\n\n {value && (\n
\n

\n Selected: {selectedDate?.toLocaleDateString('en-US', {\n weekday: 'short',\n year: 'numeric',\n month: 'short',\n day: 'numeric'\n })}\n

\n
\n )}\n
\n
\n );\n};\n\n// GroupModal component\nconst GroupModal = ({\n isOpen,\n isCreateMode,\n editGroupName,\n setEditGroupName,\n editGroupStartDate,\n setEditGroupStartDate,\n editGroupEndDate,\n setEditGroupEndDate,\n onSave,\n onCancel\n }) => {\n const isFormValid = () => {\n return editGroupName.trim();\n };\n\n if (!isOpen) return null;\n\n return (\n
\n
\n
\n

\n {isCreateMode ? 'Create New Group' : 'Edit Group'}\n

\n \n \n \n
\n\n
\n
\n \n setEditGroupName(e.target.value)}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-indigo-500 focus:border-indigo-500\"\n placeholder=\"Enter group name\"\n autoFocus\n />\n
\n\n
\n \n \n
\n
\n\n
\n \n \n {isCreateMode ? 'Create Group' : 'Save Changes'}\n \n \n \n Cancel\n \n
\n
\n
\n );\n};\n\n// OpportunityCard component\nconst OpportunityCard = ({ opportunity, onDetails, onMouseDown, isBeingDragged, getImpactColor, getTasksCompleted }) => {\n const { completed, total, isLoading } = getTasksCompleted(opportunity);\n\n return (\n onMouseDown(e, opportunity)}\n style={{\n opacity: isBeingDragged ? 0.3 : 1,\n transform: isBeingDragged ? 'rotate(2deg) scale(0.95)' : 'none',\n userSelect: 'none'\n }}\n >\n
\n

\n {opportunity.title}\n

\n {\n e.stopPropagation();\n onDetails(opportunity);\n }}\n onMouseDown={(e) => e.stopPropagation()}\n className=\"text-gray-400 hover:text-gray-600 flex-shrink-0\"\n >\n \n \n
\n\n
\n \n {isLoading ? 'Loading...' : `${completed}/${total} tasks complete`}\n \n
\n Impact:\n \n {opportunity.impact}\n \n
\n
\n \n );\n};\n\nconst Timeline = ({\n opportunities,\n groups,\n objectives,\n impactLevels,\n objectiveFilter,\n setObjectiveFilter,\n groupFilter,\n setGroupFilter,\n impactFilter,\n setImpactFilter,\n searchQuery,\n setSearchQuery,\n onOpportunityDetails,\n onGroupAssignment,\n onUpdateGroup,\n onCreateGroup,\n projectId,\n user\n }) => {\n const [editingGroup, setEditingGroup] = useState(null);\n const [editGroupName, setEditGroupName] = useState('');\n const [editGroupStartDate, setEditGroupStartDate] = useState('');\n const [editGroupEndDate, setEditGroupEndDate] = useState('');\n const [draggedItem, setDraggedItem] = useState(null);\n const [isGroupModalOpen, setIsGroupModalOpen] = useState(false);\n const [isCreateMode, setIsCreateMode] = useState(false);\n const editInputRef = useRef(null);\n const scrollContainerRef = useRef(null);\n\n useEffect(() => {\n if (editingGroup && editInputRef.current) {\n editInputRef.current.focus();\n }\n }, [editingGroup, editGroupName]);\n\n // Filter opportunities\n const filteredOpportunities = opportunities.filter(opp => {\n const matchesObjective = !objectiveFilter || opp.objective === objectiveFilter;\n const matchesGroup = !groupFilter || (groupFilter === 'ungrouped' ? !opp.strategic_group_id : opp.strategic_group_id === parseInt(groupFilter));\n const matchesImpact = !impactFilter || opp.impact === impactFilter;\n const matchesSearch = !searchQuery || opp.title.toLowerCase().includes(searchQuery.toLowerCase());\n\n return matchesObjective && matchesGroup && matchesImpact && matchesSearch;\n });\n\n // Group opportunities\n const groupedOpportunities = useMemo(() => {\n const ungrouped = filteredOpportunities.filter(opp => !opp.strategic_group_id);\n const grouped = groups.reduce((acc, group) => {\n acc[group.id] = filteredOpportunities.filter(opp => opp.strategic_group_id === group.id);\n return acc;\n }, {});\n\n return { ungrouped, grouped };\n }, [filteredOpportunities, groups]);\n\n const getTasksCompleted = (opportunity) => {\n if (!opportunity.action_tasks || opportunity.action_tasks.length === 0) {\n return { completed: 0, total: 0, isLoading: true };\n }\n\n const completed = opportunity.action_tasks.filter(task => task.status === 2).length;\n const total = opportunity.action_tasks.length;\n\n return { completed, total, isLoading: false };\n };\n\n const getImpactColor = (impact) => {\n const colors = {\n 'Critical': { backgroundColor: '#FFF1F2', color: '#DC2626' },\n 'High': { backgroundColor: '#ECFDF5', color: '#007A55' },\n 'Medium': { backgroundColor: '#FFFBEB', color: '#BB4D00' },\n 'Low': { backgroundColor: '#F0F9FF', color: '#0069A8' }\n };\n return colors[impact] || { backgroundColor: '#F3F4F6', color: '#374151' };\n };\n\n const scrollToRight = () => {\n if (scrollContainerRef.current) {\n scrollContainerRef.current.scrollTo({\n left: scrollContainerRef.current.scrollWidth,\n behavior: 'smooth'\n });\n }\n };\n\n const handleEditGroup = (group) => {\n trackEvent('Timeline Group Edit Started', {\n project_id: projectId,\n user_id: user?.id,\n group_id: group.id,\n group_name: group.title,\n source: 'timeline'\n });\n\n setEditingGroup(group);\n setEditGroupName(group.title);\n setEditGroupStartDate(group.start_date || '');\n setEditGroupEndDate(group.end_date || '');\n setIsCreateMode(false);\n setIsGroupModalOpen(true);\n };\n\n const handleCreateNewGroup = () => {\n trackEvent('Timeline Group Creation Started', {\n project_id: projectId,\n user_id: user?.id,\n source: 'timeline'\n });\n\n setEditingGroup(null);\n setEditGroupName('');\n setEditGroupStartDate('');\n setEditGroupEndDate('');\n setIsCreateMode(true);\n setIsGroupModalOpen(true);\n };\n\n const handleSaveModal = async () => {\n if (!editGroupName.trim()) {\n return;\n }\n\n try {\n if (isCreateMode) {\n trackEvent('Timeline Group Created', {\n project_id: projectId,\n user_id: user?.id,\n group_name: editGroupName,\n has_start_date: !!editGroupStartDate,\n has_end_date: !!editGroupEndDate,\n source: 'timeline'\n });\n\n const response = await axios.post(`/api/projects/${projectId}/strategy/strategic_groups`, {\n strategic_group: {\n title: editGroupName,\n start_date: editGroupStartDate || null,\n end_date: editGroupEndDate || null\n }\n });\n\n const newGroup = response.data;\n console.log('New group created:', newGroup);\n\n if (onCreateGroup) {\n onCreateGroup(newGroup);\n }\n\n setTimeout(() => {\n scrollToRight();\n }, 100);\n } else {\n trackEvent('Timeline Group Updated', {\n project_id: projectId,\n user_id: user?.id,\n group_id: editingGroup.id,\n group_name: editGroupName,\n has_start_date: !!editGroupStartDate,\n has_end_date: !!editGroupEndDate,\n source: 'timeline'\n });\n\n const response = await axios.patch(`/api/projects/${projectId}/strategy/strategic_groups/${editingGroup.id}`, {\n strategic_group: {\n title: editGroupName,\n start_date: editGroupStartDate || null,\n end_date: editGroupEndDate || null\n }\n });\n\n console.log('Group updated:', response.data);\n\n if (onUpdateGroup) {\n onUpdateGroup(editingGroup.id, {\n title: editGroupName,\n start_date: editGroupStartDate || null,\n end_date: editGroupEndDate || null\n });\n }\n }\n\n setIsGroupModalOpen(false);\n setEditingGroup(null);\n setIsCreateMode(false);\n } catch (error) {\n console.error('Error saving group:', error);\n }\n };\n\n const handleCancelModal = () => {\n setIsGroupModalOpen(false);\n setEditingGroup(null);\n setIsCreateMode(false);\n setEditGroupName('');\n setEditGroupStartDate('');\n setEditGroupEndDate('');\n };\n\n const handleSaveGroup = async () => {\n try {\n if (editingGroup !== 'ungrouped') {\n const response = await axios.patch(`/api/projects/${projectId}/strategy/strategic_groups/${editingGroup}`, {\n strategic_group: {\n title: editGroupName,\n start_date: editGroupStartDate || null,\n end_date: editGroupEndDate || null\n }\n });\n\n console.log('Group updated:', response.data);\n\n if (onUpdateGroup) {\n onUpdateGroup(editingGroup, {\n title: editGroupName,\n start_date: editGroupStartDate || null,\n end_date: editGroupEndDate || null\n });\n }\n\n setEditingGroup(null);\n }\n } catch (error) {\n console.error('Error updating group:', error);\n if (error.response) {\n console.error('Error response:', error.response.data);\n }\n }\n };\n\n const handleCancelEdit = () => {\n setEditingGroup(null);\n setEditGroupName('');\n setEditGroupStartDate('');\n setEditGroupEndDate('');\n };\n\n // Simplified drag state with refs to avoid excessive re-renders\n const [dragState, setDragState] = useState({\n isDragging: false,\n draggedItem: null,\n startPos: { x: 0, y: 0 },\n currentPos: { x: 0, y: 0 }\n });\n\n const dragRef = useRef({\n isDragging: false,\n draggedItem: null,\n startPos: { x: 0, y: 0 }\n });\n\n const handleCardMouseDown = (e, opportunity) => {\n e.preventDefault();\n console.log('Card mouse down:', opportunity.title);\n\n const rect = e.currentTarget.getBoundingClientRect();\n const startPos = {\n x: e.clientX - rect.left,\n y: e.clientY - rect.top\n };\n\n dragRef.current = {\n isDragging: true,\n draggedItem: opportunity,\n startPos\n };\n\n setDragState({\n isDragging: true,\n draggedItem: opportunity,\n startPos,\n currentPos: { x: e.clientX, y: e.clientY }\n });\n\n let animationId = null;\n let lastX = e.clientX;\n let lastY = e.clientY;\n\n const updatePosition = () => {\n setDragState(prev => ({\n ...prev,\n currentPos: { x: lastX, y: lastY }\n }));\n };\n\n const handleMouseMove = (moveEvent) => {\n lastX = moveEvent.clientX;\n lastY = moveEvent.clientY;\n\n if (animationId) return;\n\n animationId = requestAnimationFrame(() => {\n updatePosition();\n animationId = null;\n });\n };\n\n const handleMouseUp = async (upEvent) => {\n console.log('Mouse up at:', upEvent.clientX, upEvent.clientY);\n\n if (animationId) {\n cancelAnimationFrame(animationId);\n }\n\n const elementBelow = document.elementFromPoint(upEvent.clientX, upEvent.clientY);\n const dropZone = elementBelow?.closest('[data-drop-zone]');\n\n if (dropZone && dragRef.current.draggedItem) {\n const targetGroupId = dropZone.getAttribute('data-group-id');\n const parsedGroupId = targetGroupId === 'null' ? null : parseInt(targetGroupId);\n\n console.log('Dropping on group:', parsedGroupId);\n\n if (dragRef.current.draggedItem.strategic_group_id !== parsedGroupId) {\n const targetGroup = groups.find(g => g.id === parsedGroupId);\n\n trackEvent('Timeline Drag Drop Completed', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: dragRef.current.draggedItem.id,\n opportunity_title: dragRef.current.draggedItem.title,\n source_group_id: dragRef.current.draggedItem.strategic_group_id,\n target_group_id: parsedGroupId,\n target_group_name: targetGroup?.title || 'Ungrouped',\n source: 'timeline'\n });\n\n try {\n await onGroupAssignment(dragRef.current.draggedItem.id, parsedGroupId);\n console.log('Drop completed successfully');\n } catch (error) {\n console.error('Drop failed:', error);\n }\n }\n }\n\n dragRef.current = {\n isDragging: false,\n draggedItem: null,\n startPos: { x: 0, y: 0 }\n };\n\n setDragState({\n isDragging: false,\n draggedItem: null,\n startPos: { x: 0, y: 0 },\n currentPos: { x: 0, y: 0 }\n });\n\n document.removeEventListener('mousemove', handleMouseMove);\n document.removeEventListener('mouseup', handleMouseUp);\n };\n\n document.addEventListener('mousemove', handleMouseMove);\n document.addEventListener('mouseup', handleMouseUp);\n };\n\n const formatDateDisplay = (dateString) => {\n if (!dateString) return '';\n return new Date(dateString + 'T00:00:00').toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n year: 'numeric'\n });\n };\n\n const AddNewGroupColumn = () => {\n return (\n
\n \n \n Add New Group\n \n
\n );\n };\n\n const GroupColumn = ({ groupId, groupData, opportunities, isUngrouped = false }) => {\n return (\n \n {/* Group Header */}\n
\n
\n

\n {isUngrouped ? 'Ungrouped' : groupData?.title}\n \n ({opportunities.length})\n \n

\n {!isUngrouped && (\n handleEditGroup(groupData)}\n className=\"text-gray-400 hover:text-gray-600\"\n >\n \n \n )}\n
\n {!isUngrouped && (groupData?.start_date || groupData?.end_date) && (\n
\n \n {groupData?.start_date && formatDateDisplay(groupData.start_date)}\n {groupData?.start_date && groupData?.end_date && ' - '}\n {groupData?.end_date && formatDateDisplay(groupData.end_date)}\n \n
\n )}\n
\n\n {/* Opportunities - scrollable container */}\n
\n {opportunities.length === 0 ? (\n
\n No opportunities\n
\n ) : (\n opportunities.map(opportunity => (\n \n ))\n )}\n
\n \n );\n };\n\n return (\n
\n {/* Top Section with White Background */}\n
\n {/* Filters Row */}\n
\n
\n {/* Objective Filter */}\n
\n setObjectiveFilter(e.target.value)}\n className=\"min-w-[150px] px-3 py-2 pr-8 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500 bg-white\"\n >\n \n {objectives.map(objective => (\n \n ))}\n \n
\n\n {/* Group Filter */}\n
\n setGroupFilter(e.target.value)}\n className=\"min-w-[120px] px-3 py-2 pr-8 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500 bg-white\"\n >\n \n \n {groups.map(group => (\n \n ))}\n \n
\n\n {/* Impact Filter */}\n
\n setImpactFilter(e.target.value)}\n className=\"min-w-[120px] px-3 py-2 pr-8 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500 bg-white\"\n >\n \n {impactLevels.map(level => (\n \n ))}\n \n
\n
\n\n
\n {/* Search */}\n
\n \n setSearchQuery(e.target.value)}\n className=\"w-64 pl-10 pr-4 py-2 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500\"\n />\n
\n
\n
\n
\n\n {/* Border between filters and groups */}\n
\n\n {/* Timeline Groups with Gray Background */}\n
\n
\n {/* Ungrouped Column */}\n \n\n {/* Grouped Columns */}\n {groups.map(group => (\n \n ))}\n\n {/* Add New Group Column */}\n \n
\n
\n\n {/* Custom Drag Ghost */}\n {dragState.isDragging && dragState.draggedItem && (\n \n
\n {dragState.draggedItem.title}\n
\n
\n Moving to group...\n
\n
\n )}\n\n {/* Group Modal */}\n \n \n );\n};\n\nexport default Timeline;", "import React, { useState, useEffect, useRef, useContext } from 'react';\nimport { BarChart3, TrendingUp, ArrowUp, ArrowDown, Calendar, BarChart, LineChart, Target, Eye, Activity, AlertTriangle } from 'lucide-react';\nimport { LineChart as RechartsLineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, ReferenceLine } from 'recharts';\nimport axios from '../../AxiosConfig';\nimport { AuthContext } from '../../../context/AuthContext';\nimport { trackEvent } from '../../Analytics/mixpanel';\n\nconst Measurement = ({ projectId, project }) => {\n const [loading, setLoading] = useState(true);\n const [geoScoreData, setGeoScoreData] = useState([]);\n const [objectiveScores, setObjectiveScores] = useState([]);\n const [hasNoPages, setHasNoPages] = useState(false);\n\n // Separate independent state for each dropdown section\n const [geoScoreStartAuditResult, setGeoScoreStartAuditResult] = useState('');\n const [objectiveScoreStartAuditResult, setObjectiveScoreStartAuditResult] = useState('');\n const [trendStartAuditResult, setTrendStartAuditResult] = useState('');\n const [opportunityStartAuditResult, setOpportunityStartAuditResult] = useState('');\n\n const [availableAuditResults, setAvailableAuditResults] = useState([]);\n const [currentGeoScore, setCurrentGeoScore] = useState(0);\n const [geoScoreChange, setGeoScoreChange] = useState({ percentage: 0, isPositive: true });\n\n // All Objective Trends state\n const [selectedObjective, setSelectedObjective] = useState('AI Visibility');\n const [objectiveTrendsData, setObjectiveTrendsData] = useState([]);\n const [trendHasNoPages, setTrendHasNoPages] = useState(false);\n const [trendNoPagesMessage, setTrendNoPagesMessage] = useState('');\n\n // Opportunity Tracking state\n const [opportunities, setOpportunities] = useState([]);\n const [selectedOpportunity, setSelectedOpportunity] = useState(null);\n const [opportunityData, setOpportunityData] = useState([]);\n const [completionEvents, setCompletionEvents] = useState([]);\n const [isPerPlatform, setIsPerPlatform] = useState(false);\n\n // Ref for scrolling to opportunity details\n const opportunityDetailsRef = useRef(null);\n\n // Auth context for user info\n const { user } = useContext(AuthContext);\n\n const objectives = [\n 'AI Visibility',\n 'Share of Voice',\n 'Sentiment',\n 'Citation',\n 'AI Readability',\n 'Content Coverage',\n 'Technical GEO'\n ];\n\n const objectiveIcons = {\n 'AI Visibility': ,\n 'Share of Voice': ,\n 'Sentiment': ,\n 'Citation': ,\n 'AI Readability': ,\n 'Content Coverage': ,\n 'Technical GEO': \n };\n\n // Platform configuration for per-platform visibility chart\n const platformConfig = {\n chatgpt: { name: 'ChatGPT', color: '#10A37F' },\n perplexity: { name: 'Perplexity', color: '#6366F1' },\n google_ai_overview: { name: 'Google AI Overview', color: '#4285F4' }\n };\n\n // Track page view on mount\n useEffect(() => {\n trackEvent('Measurement Page Viewed', {\n project_id: projectId,\n user_id: user?.id,\n source: 'measurement'\n });\n }, [projectId]);\n\n useEffect(() => {\n fetchMeasurementData();\n }, [projectId]);\n\n useEffect(() => {\n if (geoScoreStartAuditResult) {\n fetchGeoScoreData();\n }\n }, [geoScoreStartAuditResult]);\n\n useEffect(() => {\n if (objectiveScoreStartAuditResult) {\n fetchObjectiveScores();\n }\n }, [objectiveScoreStartAuditResult]);\n\n useEffect(() => {\n if (trendStartAuditResult && selectedObjective) {\n fetchObjectiveTrendsData();\n }\n }, [trendStartAuditResult, selectedObjective]);\n\n useEffect(() => {\n if (opportunityStartAuditResult && selectedOpportunity) {\n fetchOpportunityData();\n } else if (!selectedOpportunity) {\n setCompletionEvents([]);\n setIsPerPlatform(false);\n }\n }, [opportunityStartAuditResult, selectedOpportunity]);\n\n const fetchMeasurementData = async () => {\n try {\n setLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/measurement`);\n const data = response.data;\n\n setAvailableAuditResults(data.available_audit_results || []);\n setOpportunities(data.opportunities || []);\n\n if (data.available_audit_results && data.available_audit_results.length > 0) {\n const oldestAuditResult = data.available_audit_results[0];\n setGeoScoreStartAuditResult(oldestAuditResult.id);\n setObjectiveScoreStartAuditResult(oldestAuditResult.id);\n setTrendStartAuditResult(oldestAuditResult.id);\n setOpportunityStartAuditResult(oldestAuditResult.id);\n }\n } catch (error) {\n console.error('Error fetching measurement data:', error);\n } finally {\n setLoading(false);\n }\n };\n\n const fetchGeoScoreData = async () => {\n try {\n const response = await axios.get(`/api/projects/${projectId}/measurement/geo_score`, {\n params: { start_audit_result_id: geoScoreStartAuditResult }\n });\n const data = response.data;\n\n setGeoScoreData(data.geo_score_data || []);\n setCurrentGeoScore(data.current_geo_score || 0);\n setGeoScoreChange(data.geo_score_change || { percentage: 0, isPositive: true });\n } catch (error) {\n console.error('Error fetching GEO score data:', error);\n }\n };\n\n const fetchObjectiveScores = async () => {\n try {\n const response = await axios.get(`/api/projects/${projectId}/measurement/objective_scores`, {\n params: { start_audit_result_id: objectiveScoreStartAuditResult }\n });\n setObjectiveScores(response.data.objective_scores || []);\n setHasNoPages(response.data.has_no_pages || false);\n } catch (error) {\n console.error('Error fetching objective scores:', error);\n }\n };\n\n const fetchObjectiveTrendsData = async () => {\n try {\n const response = await axios.get(`/api/projects/${projectId}/measurement/objective_trends`, {\n params: {\n start_audit_result_id: trendStartAuditResult,\n objective: selectedObjective\n }\n });\n\n setObjectiveTrendsData(response.data.trend_data || []);\n setTrendHasNoPages(response.data.has_no_pages || false);\n setTrendNoPagesMessage(response.data.no_pages_message || '');\n } catch (error) {\n console.error('Error fetching objective trends data:', error);\n }\n };\n\n const fetchOpportunityData = async () => {\n try {\n const response = await axios.get(`/api/projects/${projectId}/measurement/opportunity_details`, {\n params: {\n start_audit_result_id: opportunityStartAuditResult,\n opportunity_id: selectedOpportunity.id\n }\n });\n const data = response.data;\n console.log('Opportunity data:', data.opportunity_data);\n console.log('Completion events:', data.completion_events);\n console.log('Is per-platform:', data.is_per_platform);\n setOpportunityData(data.opportunity_data || []);\n setCompletionEvents(data.completion_events || []);\n setIsPerPlatform(data.is_per_platform || false);\n } catch (error) {\n console.error('Error fetching opportunity data:', error);\n }\n };\n\n const handleGeoScoreDateChange = (value) => {\n trackEvent('Measurement Date Filter Changed', {\n project_id: projectId,\n user_id: user?.id,\n section: 'geo_score',\n selected_audit_result_id: value,\n source: 'measurement'\n });\n setGeoScoreStartAuditResult(value);\n };\n\n const handleObjectiveScoreDateChange = (value) => {\n trackEvent('Measurement Date Filter Changed', {\n project_id: projectId,\n user_id: user?.id,\n section: 'objective_performance',\n selected_audit_result_id: value,\n source: 'measurement'\n });\n setObjectiveScoreStartAuditResult(value);\n };\n\n const handleTrendDateChange = (value) => {\n trackEvent('Measurement Date Filter Changed', {\n project_id: projectId,\n user_id: user?.id,\n section: 'objective_trends',\n selected_audit_result_id: value,\n source: 'measurement'\n });\n setTrendStartAuditResult(value);\n };\n\n const handleOpportunityDateChange = (value) => {\n trackEvent('Measurement Date Filter Changed', {\n project_id: projectId,\n user_id: user?.id,\n section: 'opportunity_details',\n selected_audit_result_id: value,\n source: 'measurement'\n });\n setOpportunityStartAuditResult(value);\n };\n\n const handleObjectiveChange = (value) => {\n trackEvent('Measurement Objective Selected', {\n project_id: projectId,\n user_id: user?.id,\n previous_objective: selectedObjective,\n new_objective: value,\n source: 'measurement'\n });\n setSelectedObjective(value);\n };\n\n const handleViewOpportunityGraph = (opportunity) => {\n trackEvent('Opportunity Graph Viewed', {\n project_id: projectId,\n user_id: user?.id,\n opportunity_id: opportunity.id,\n opportunity_title: opportunity.title,\n completion_status: getCompletionStatus(opportunity).status,\n completion_percentage: getCompletionStatus(opportunity).percentage,\n source: 'measurement'\n });\n\n setSelectedOpportunity(opportunity);\n setTimeout(() => {\n opportunityDetailsRef.current?.scrollIntoView({\n behavior: 'smooth',\n block: 'start'\n });\n }, 100);\n };\n\n const formatDate = (dateString) => {\n const date = new Date(dateString);\n return date.toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n timeZone: 'UTC'\n });\n };\n\n const getObjectiveColor = (objective) => {\n return 'bg-white text-gray-900 border-gray-300';\n };\n\n const getCompletionStatus = (opportunity) => {\n const totalTasks = opportunity.total_tasks || 0;\n const completedTasks = opportunity.completed_tasks || 0;\n\n if (totalTasks === 0) return { status: 'Not Started', percentage: 0 };\n\n const percentage = Math.round((completedTasks / totalTasks) * 100);\n\n if (percentage === 100) return { status: 'Completed', percentage };\n if (percentage > 0) return { status: 'In Progress', percentage };\n return { status: 'Not Started', percentage: 0 };\n };\n\n const getLineColor = (index) => {\n const colors = [\n '#EF4444', '#F97316', '#EAB308', '#22C55E',\n '#06B6D4', '#3B82F6', '#8B5CF6', '#EC4899'\n ];\n return colors[index % colors.length];\n };\n\n const getYAxisLabel = (objective) => {\n switch (objective) {\n case 'AI Visibility':\n return 'Visibility Score (%)';\n case 'Share of Voice':\n return 'Share Percentage (%)';\n case 'Sentiment':\n return 'Sentiment Score';\n case 'Citation':\n return 'Citation Score (%)';\n case 'AI Readability':\n return 'Readability Score (%)';\n case 'Content Coverage':\n return 'Coverage Score (%)';\n case 'Technical GEO':\n return 'Technical Score (%)';\n default:\n return 'Score';\n }\n };\n\n const getOpportunityYAxisLabel = (opportunityType) => {\n const normalizedType = opportunityType?.toString?.().toLowerCase?.() || '';\n\n switch (normalizedType) {\n case 'visibility_prompt':\n return 'Client Mentioned';\n case 'visibility_topic':\n return 'Topic Visibility %';\n case 'competitor_topic':\n case 'competitor_company':\n return 'Share of Voice %';\n case 'content_coverage_topic':\n return 'Client Topic Coverage %';\n case 'on_page_link':\n return 'AI Readability Score';\n case 'on_page_logic_flow':\n return 'Logic Flow Score';\n case 'on_page_entity_mapping':\n return 'Entity Mapping Score';\n case 'on_page_claim_clarity':\n return 'Claim Clarity Score';\n case 'on_page_schema_markup':\n return 'Schema Utilization Score';\n case 'on_page_information_architecture':\n return 'Page Structure Score';\n case 'technical_link':\n return 'Technical GEO Score';\n case 'technical_load_time':\n return 'Load Time';\n case 'technical_front_loading':\n return 'Front Loading Score';\n case 'technical_information_density':\n return 'Information Density Score';\n case 'citation_rate_topic':\n return 'Citation Rate';\n case 'citation_third_party':\n return 'Citation Score';\n case 'sentiment_prompt':\n case 'sentiment_theme':\n return 'Sentiment Score';\n default:\n return 'Score';\n }\n };\n\n // Determine if the Y-axis should use a fixed 0-100 domain\n const shouldUseFixedYAxisDomain = (opportunityType) => {\n const normalizedType = opportunityType?.toString?.().toLowerCase?.() || '';\n\n // Sentiment scores can be negative (-1 to 1), so don't fix the domain\n if (normalizedType === 'sentiment_prompt' || normalizedType === 'sentiment_theme') {\n return false;\n }\n\n // Load time is measured in seconds/ms, not a percentage\n if (normalizedType === 'technical_load_time') {\n return false;\n }\n\n // All other metrics are percentages or scores from 0-100\n return true;\n };\n\n const isSentimentType = (opportunityType) => {\n const normalizedType = opportunityType?.toString?.().toLowerCase?.() || '';\n return normalizedType === 'sentiment_prompt' || normalizedType === 'sentiment_theme';\n };\n\n // Custom tooltip for per-platform visibility chart\n const PerPlatformTooltip = ({ active, payload, label }) => {\n if (active && payload && payload.length) {\n const dataPoint = opportunityData.find(d => new Date(d.date).getTime() === label);\n\n return (\n
\n

\n {formatDate(new Date(label))}\n

\n {Object.entries(platformConfig).map(([key, config]) => {\n const value = dataPoint ? dataPoint[key] : null;\n const mentioned = value === 1;\n return (\n
\n \n {config.name}:\n \n {mentioned ? 'Yes' : 'No'}\n \n
\n );\n })}\n
\n );\n }\n return null;\n };\n\n // Render per-platform visibility chart\n const renderPerPlatformChart = () => {\n if (opportunityData.length === 0) {\n return (\n
\n
\n

No visibility data available for the selected time period

\n
\n
\n );\n }\n\n if (opportunityData.length === 1) {\n const dataPoint = opportunityData[0];\n return (\n
\n

\n Visibility status as of {formatDate(dataPoint.date)}\n

\n
\n {Object.entries(platformConfig).map(([key, config]) => {\n const value = dataPoint[key];\n const mentioned = value === 1;\n return (\n \n
\n \n {config.name}\n
\n

\n {mentioned ? 'Yes - Mentioned' : 'No - Not Mentioned'}\n

\n
\n );\n })}\n
\n

\n Graphical visualization will appear once there's another audit result in the next few days\n

\n \n );\n }\n\n const transformedData = opportunityData.map(item => ({\n ...item,\n timestamp: new Date(item.date).getTime(),\n chatgpt_display: item.chatgpt === 1 ? 1 : 0,\n perplexity_display: item.perplexity === 1 ? 1 : 0,\n google_ai_overview_display: item.google_ai_overview === 1 ? 1 : 0,\n }));\n\n return (\n
\n
\n Yes = Mentioned\n No = Not Mentioned\n
\n \n \n \n formatDate(new Date(timestamp))}\n tickCount={6}\n />\n value === 1 ? 'Yes' : 'No'}\n label={{\n value: 'Client Mentioned',\n angle: -90,\n position: 'insideLeft',\n style: { textAnchor: 'middle' }\n }}\n />\n } />\n \n {Object.entries(platformConfig).map(([key, config]) => (\n \n ))}\n {completionEvents.length > 0 && (\n \n )}\n \n \n
\n );\n };\n\n // Render standard metric chart\n const renderStandardMetricChart = () => {\n const showPercentage = !isSentimentType(selectedOpportunity?.opportunity_type);\n const useFixedDomain = shouldUseFixedYAxisDomain(selectedOpportunity?.opportunity_type);\n\n if (opportunityData.length > 1) {\n return (\n
\n \n ({\n ...item,\n timestamp: new Date(item.date).getTime()\n }))}\n margin={{ top: 20, right: 30, left: 20, bottom: 5 }}\n >\n \n formatDate(new Date(timestamp))}\n tickCount={6}\n />\n \n `Date: ${formatDate(new Date(timestamp))}`}\n formatter={(value) => [showPercentage ? `${value}%` : value, 'Performance']}\n />\n \n {completionEvents.length > 0 && (\n \n )}\n \n \n
\n );\n } else if (opportunityData.length === 1) {\n return (\n
\n
\n

Graphical visualization will appear once there's another audit result in the next few days

\n
\n
\n );\n } else {\n return (\n
\n
\n

No opportunity data available for the selected time period

\n
\n
\n );\n }\n };\n\n // Render no pages warning for objective card\n const renderNoPagesCard = (objective) => {\n return (\n
\n
\n
\n {objectiveIcons[objective.name]}\n
\n

{objective.name}

\n \n
\n
\n N/A\n
\n
\n {objective.no_pages_message || 'Website pages could not be analyzed'}\n
\n
\n );\n };\n\n if (loading) {\n return (\n
\n
\n
\n
\n
\n
\n
\n
\n {[1, 2, 3, 4].map((i) => (\n
\n
\n
\n
\n
\n ))}\n
\n
\n );\n }\n\n return (\n
\n {/* Header Section */}\n
\n
\n

\n Measurement\n

\n

\n Monitor how your client is performing across key GEO metrics as well as track progress and results of specific opportunities worked on\n

\n
\n
\n\n {/* No Pages Warning Banner */}\n {hasNoPages && (\n
\n
\n \n
\n

Limited Analysis Available

\n

\n AI Readability and Technical GEO scores are unavailable because your website pages could not be analyzed.\n The GEO Score is calculated using available metrics only.\n

\n
\n
\n
\n )}\n\n {/* Overall GEO Score Section */}\n
\n
\n
\n

Current GEO Score

\n
\n {currentGeoScore}\n
\n
\n {geoScoreChange.isPositive ? (\n \n ) : (\n \n )}\n \n {Math.abs(geoScoreChange.percentage)}% {geoScoreChange.isPositive ? 'improvement' : 'decline'}\n \n
\n {hasNoPages && (\n

\n * Score excludes AI Readability and Technical GEO (data unavailable)\n

\n )}\n
\n
\n \n handleGeoScoreDateChange(e.target.value)}\n className=\"min-w-[150px] px-3 py-2 pr-8 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500 bg-white\"\n style={{ paddingRight: '2rem' }}\n >\n {availableAuditResults.map((auditResult) => (\n \n ))}\n \n
\n
\n\n {geoScoreData.length > 1 ? (\n
\n \n \n \n \n \n `Date: ${formatDate(value)}`}\n formatter={(value) => [`${value}%`, 'GEO Score']}\n />\n \n \n \n
\n ) : geoScoreData.length === 1 ? (\n
\n
\n

Graphical visualization will appear once there's another audit result in the next few days

\n
\n
\n ) : (\n
\n
\n

No audit data available for the selected time period

\n
\n
\n )}\n
\n\n {/* Objective Performance Section */}\n
\n
\n
\n

Objective Performance - progress over time

\n

\n How each GEO objective has improved since baseline audit date\n

\n
\n
\n \n handleObjectiveScoreDateChange(e.target.value)}\n className=\"min-w-[150px] px-3 py-2 pr-8 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500 bg-white\"\n style={{ paddingRight: '2rem' }}\n >\n {availableAuditResults.map((auditResult) => (\n \n ))}\n \n
\n
\n\n
\n {objectiveScores.map((objective, index) => {\n // Check if this objective has no pages\n if (objective.has_no_pages) {\n return (\n
\n {renderNoPagesCard(objective)}\n
\n );\n }\n\n return (\n \n
\n
\n {objectiveIcons[objective.name]}\n
\n

{objective.name}

\n
\n
\n {objective.current_score}%\n
\n
\n {objective.change_percentage >= 0 ? (\n \n ) : (\n \n )}\n = 0 ? 'text-green-600' : 'text-red-600'}`}>\n {Math.abs(objective.change_percentage)}% {objective.change_percentage >= 0 ? 'improvement' : 'decline'}\n \n
\n
\n since {objective.start_date ? formatDate(objective.start_date) : 'start'}\n
\n
\n );\n })}\n
\n
\n\n {/* All Objective Trends Section */}\n
\n
\n
\n

{selectedObjective} Trends

\n

\n Track key objective metrics over time\n

\n
\n
\n handleObjectiveChange(e.target.value)}\n className=\"min-w-[180px] px-3 py-2 pr-8 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500 bg-white\"\n style={{ paddingRight: '2rem' }}\n >\n {objectives.map((objective) => (\n \n ))}\n \n
\n \n handleTrendDateChange(e.target.value)}\n className=\"min-w-[150px] px-3 py-2 pr-8 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500 bg-white\"\n style={{ paddingRight: '2rem' }}\n >\n {availableAuditResults.map((auditResult) => (\n \n ))}\n \n
\n
\n
\n\n {trendHasNoPages ? (\n
\n
\n \n

Data Unavailable

\n

\n {trendNoPagesMessage || `${selectedObjective} data is unavailable because website pages could not be analyzed.`}\n

\n
\n
\n ) : objectiveTrendsData.length > 1 ? (\n
\n \n \n \n \n \n `Date: ${formatDate(value)}`}\n />\n \n \n \n \n
\n ) : objectiveTrendsData.length === 1 ? (\n
\n
\n

Graphical visualization will appear once there's another audit result in the next few days

\n
\n
\n ) : (\n
\n
\n

No audit trend data available for the selected time period

\n
\n
\n )}\n
\n\n {/* Opportunity Tracking Section */}\n
\n
\n

Opportunity Tracking

\n

\n Track results of in progress and completed opportunities\n

\n
\n\n
\n
\n \n \n \n \n \n \n \n \n \n \n \n {opportunities.map((opportunity) => {\n const completion = getCompletionStatus(opportunity);\n return (\n \n \n \n \n \n \n \n );\n })}\n \n
\n Opportunity\n \n % of tasks completed\n \n Status\n \n Completion date\n \n Actions\n
\n
\n {opportunity.title}\n
\n
\n {completion.percentage}%\n \n \n {completion.status}\n \n \n {opportunity.completion_date ? formatDate(opportunity.completion_date) : '-'}\n \n handleViewOpportunityGraph(opportunity)}\n className=\"inline-flex items-center px-2.5 py-1.5 border border-gray-300 text-xs font-medium rounded text-gray-700 bg-white hover:bg-gray-50\"\n >\n \n View Graph\n \n
\n
\n
\n
\n\n {/* Opportunity Details Section */}\n {selectedOpportunity && (\n
\n
\n
\n

Opportunity Details

\n

\n {selectedOpportunity.title}\n

\n {isPerPlatform && (\n

\n Showing client mention status per AI platform\n

\n )}\n
\n
\n \n handleOpportunityDateChange(e.target.value)}\n className=\"min-w-[150px] px-3 py-2 pr-8 border border-gray-300 rounded-md text-sm focus:ring-indigo-500 focus:border-indigo-500 bg-white\"\n style={{ paddingRight: '2rem' }}\n >\n {availableAuditResults.map((auditResult) => (\n \n ))}\n \n
\n
\n\n {isPerPlatform ? renderPerPlatformChart() : renderStandardMetricChart()}\n
\n )}\n \n );\n};\n\nexport default Measurement;", "import React from 'react';\nimport { Rocket, TrendingUp, Target, BarChart3, MessageSquare, Link as LinkIcon, Users, Gauge, FileText, BarChart } from 'lucide-react';\nimport { trackEvent } from '../../Analytics/mixpanel';\n\n// Feature content configuration with updated copy\nconst FEATURE_CONTENT = {\n opportunities: {\n title: 'Know Exactly What to Optimize Next',\n description1: \"Instantly see where your clients are winning and losing in AI search. Visto scans GEO performance weekly to surface the highest impact opportunities, ranked by effort and expected impact, so your team always knows what to work on and how to pitch it.\",\n description2: \"This replaces hundreds of hours agencies spend analyzing GEO manually. With Opportunities, you remove guesswork, move faster, and turn GEO into a consistent driver of retention and expansion.\",\n icon: TrendingUp,\n image: '/assets/feature_images/Opportunities.svg'\n },\n strategy: {\n title: 'Turn Insights Into Action',\n description1: \"Visto turns GEO insights into truly actionable recommendations. Our proprietary optimization technology converts each opportunity into specific, ready to execute tasks so your team knows exactly what to do to capture it.\",\n description2: \"Our workflow helps agencies create a GEO strategic plan for clients and prioritize effectively. Drag and drop grouping makes it easy to turn strategy into proposals, timelines, and internal workflows.\",\n icon: Target,\n image: '/assets/feature_images/Strategy.svg'\n },\n measurement: {\n title: 'Show the Impact of Your GEO Work',\n description1: \"Visto measures attribution so agencies can clearly demonstrate ROI to clients. We show how completed tasks translate into real business value, removing ambiguity around whether GEO work is actually working.\",\n description2: \"Measurement rolls up to a single GEO score, breaks down into seven key metrics, and ties results directly to individual opportunities so clients can clearly see impact.\",\n icon: BarChart3,\n image: '/assets/feature_images/Measurement.svg'\n },\n prompts: {\n title: 'Know Exactly Where Your Clients Stand',\n description1: \"See how your client appears across AI search platforms. Prompt Analytics aggregates responses from ChatGPT, Perplexity, Google AI Overview, and more, then layers in search volume, difficulty, and intent.\",\n description2: \"Instantly understand where your client shows up, which competitors are mentioned, and how AI platforms describe your client's brand. This creates a clear, data driven baseline to identify gaps, competitive pressure, and priority opportunities.\",\n icon: MessageSquare,\n image: '/assets/feature_images/Promptanalytics.svg'\n },\n links: {\n title: 'Uncover the Sources AI Trusts',\n description1: \"See which domains AI relies on in your client's category. Citation aggregates sources referenced in AI responses and groups them by domain so you can understand what influences visibility and where competitors are being pulled in.\",\n description2: \"This insight is critical for digital PR, content, and authority building. Identify which publications, partners, and assets AI rewards, where your client is missing coverage, and which initiatives will drive the biggest gains in trust and visibility across AI search.\",\n icon: LinkIcon,\n image: '/assets/feature_images/Links.svg'\n },\n competitors: {\n title: 'Understand Your Competitive Position',\n description1: \"Track your client's share of voice across AI platforms and see where competitors are outperforming them. Monitor brand and product mentions by topic and understand how performance changes over time.\",\n description2: \"Competitor insights help agencies decide where to double down, defend, or attack, and turn competitive intelligence into a clear client narrative that drives urgency and budget.\",\n icon: Users,\n image: '/assets/feature_images/Competitor.svg'\n },\n sentiment: {\n title: 'Understand How AI Perceives Your Brand',\n description1: \"See how AI platforms describe and characterize your client's brand. Sentiment analysis highlights strengths, weaknesses, tone issues, and inaccuracies in AI responses so you know exactly where perception needs improvement.\",\n description2: \"These insights surface hidden risks and opportunities, helping agencies shape brand narrative, protect reputation, and prioritize fixes that have the greatest impact on visibility and conversion.\",\n icon: Gauge,\n image: '/assets/feature_images/Sentiment.svg'\n },\n content: {\n title: \"See Your Content the Way AI Does\",\n description1: \"Understand how AI models interpret your client's website. Content Analysis reveals issues in clarity, structure, entity coverage, relevance, and technical readiness so you can see whether pages are optimized for AI comprehension.\",\n description2: \"Analyze key pages automatically or review any URL. This visibility helps your agency deliver smarter content improvements, fix structural weaknesses, and increase the likelihood of appearing in AI generated answers.\",\n icon: FileText,\n image: '/assets/feature_images/Content.svg'\n },\n optimization: {\n title: 'Look Inside the LLM Black Box',\n description1: \"See how models like ChatGPT evaluate your client. Optimization reveals the prompts being tested, the queries generated, the results pulled, and the sources cited so you can understand what is driving visibility.\",\n description2: \"This clarity shows why certain brands appear in answers and what to change to improve your client's chances of showing up. Upgrade to Optimization to unlock Visto's deepest GEO insights.\",\n icon: BarChart,\n image: '/assets/feature_images/Optimization.svg'\n }\n};\n\nconst LockedFeatureView = ({ featureId, onUpgradeClick, user, projectId }) => {\n const content = FEATURE_CONTENT[featureId] || FEATURE_CONTENT.opportunities;\n\n // Track when locked feature view is displayed\n React.useEffect(() => {\n trackEvent('Locked Feature View Displayed', {\n user_id: user?.id,\n project_id: projectId,\n feature_id: featureId,\n feature_title: content.title,\n source: 'project_dashboard'\n });\n }, [featureId, user, projectId, content.title]);\n\n const handleUpgradeClick = () => {\n trackEvent('Locked Feature Upgrade Click', {\n user_id: user?.id,\n project_id: projectId,\n feature_id: featureId,\n feature_title: content.title,\n source: 'locked_feature_view'\n });\n onUpgradeClick();\n };\n\n return (\n
\n
\n {/* Left section - Text content */}\n
\n

\n {content.title}\n

\n\n

\n {content.description1}\n

\n\n

\n {content.description2}\n

\n\n
\n \n \n Upgrade Plan\n \n
\n
\n\n {/* Right section - SVG Image */}\n
\n
\n \n
\n
\n
\n
\n );\n};\n\nexport default LockedFeatureView;", "import React, { useState, useEffect, useContext } from 'react';\nimport axios from '../../AxiosConfig';\nimport { Download, FileText, BarChart3, Target, ChevronDown, Loader2, Check, AlertCircle } from 'lucide-react';\nimport { AuthContext } from '../../../context/AuthContext';\nimport { trackEvent } from '../../Analytics/mixpanel';\n\nconst DataExportSection = ({ projectId }) => {\n const { user } = useContext(AuthContext);\n const [availableAudits, setAvailableAudits] = useState([]);\n const [selectedAuditId, setSelectedAuditId] = useState('');\n const [loading, setLoading] = useState(true);\n const [exporting, setExporting] = useState({\n prompts: false,\n audit: false,\n opportunities: false\n });\n const [exportSuccess, setExportSuccess] = useState({\n prompts: false,\n audit: false,\n opportunities: false\n });\n const [error, setError] = useState('');\n\n useEffect(() => {\n if (projectId) {\n fetchAvailableAudits();\n }\n }, [projectId]);\n\n // Track page view on mount\n useEffect(() => {\n trackEvent('Data Export Page Viewed', {\n project_id: projectId,\n user_id: user?.id,\n source: 'data_export'\n });\n }, [projectId, user]);\n\n const fetchAvailableAudits = async () => {\n try {\n setLoading(true);\n const response = await axios.get(`/api/projects/${projectId}/data_exports/available_audits`);\n setAvailableAudits(response.data.audits || []);\n\n // Auto-select the most recent audit if available\n if (response.data.audits && response.data.audits.length > 0) {\n setSelectedAuditId(response.data.audits[0].id);\n }\n } catch (err) {\n console.error('Error fetching available audits:', err);\n setError('Failed to load available audits');\n } finally {\n setLoading(false);\n }\n };\n\n const handleExport = async (exportType) => {\n try {\n setExporting(prev => ({ ...prev, [exportType]: true }));\n setExportSuccess(prev => ({ ...prev, [exportType]: false }));\n setError('');\n\n let url;\n let trackingData = {\n project_id: projectId,\n user_id: user?.id,\n export_type: exportType,\n source: 'data_export'\n };\n\n switch (exportType) {\n case 'prompts':\n url = `/api/projects/${projectId}/data_exports/prompts`;\n break;\n case 'audit':\n if (!selectedAuditId) {\n setError('Please select an audit to export');\n trackEvent('Data Export Failed', {\n ...trackingData,\n error: 'No audit selected',\n audit_id: null\n });\n return;\n }\n url = `/api/projects/${projectId}/data_exports/audit/${selectedAuditId}`;\n trackingData.audit_id = selectedAuditId;\n // Find the audit date for tracking\n const selectedAudit = availableAudits.find(a => a.id === parseInt(selectedAuditId));\n if (selectedAudit) {\n trackingData.audit_date = selectedAudit.formatted_date;\n }\n break;\n case 'opportunities':\n url = `/api/projects/${projectId}/data_exports/opportunities`;\n break;\n default:\n throw new Error('Invalid export type');\n }\n\n // Track export initiation\n trackEvent('Data Export Started', trackingData);\n\n const response = await axios.get(url, {\n responseType: 'blob'\n });\n\n // Create download link\n const blob = new Blob([response.data], { type: 'text/csv' });\n const downloadUrl = window.URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = downloadUrl;\n\n // Extract filename from content-disposition header or use default\n const contentDisposition = response.headers['content-disposition'];\n let filename = `export_${exportType}_${Date.now()}.csv`;\n if (contentDisposition) {\n const filenameMatch = contentDisposition.match(/filename=\"?(.+)\"?/i);\n if (filenameMatch) {\n filename = filenameMatch[1];\n }\n }\n\n link.download = filename;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n window.URL.revokeObjectURL(downloadUrl);\n\n // Track successful export\n trackEvent('Data Export Completed', {\n ...trackingData,\n filename: filename,\n file_size_bytes: blob.size\n });\n\n // Show success state\n setExportSuccess(prev => ({ ...prev, [exportType]: true }));\n setTimeout(() => {\n setExportSuccess(prev => ({ ...prev, [exportType]: false }));\n }, 3000);\n\n } catch (err) {\n console.error(`Error exporting ${exportType}:`, err);\n const errorMessage = err.response?.data?.error || err.message || `Failed to export ${exportType}`;\n setError(errorMessage);\n\n // Track export failure\n trackEvent('Data Export Failed', {\n project_id: projectId,\n user_id: user?.id,\n export_type: exportType,\n error: errorMessage,\n source: 'data_export'\n });\n } finally {\n setExporting(prev => ({ ...prev, [exportType]: false }));\n }\n };\n\n const exportCards = [\n {\n id: 'prompts',\n title: 'Prompts & Topics',\n description: 'Export all prompts and topics with analytics data including volume estimates, difficulty, brand mentions, and platform information.',\n icon: FileText,\n action: () => handleExport('prompts')\n },\n {\n id: 'audit',\n title: 'Audit Results',\n description: 'Export comprehensive audit analysis data including all categories, metrics, and opportunities from a specific audit run.',\n icon: BarChart3,\n action: () => handleExport('audit'),\n requiresSelection: true\n },\n {\n id: 'opportunities',\n title: 'Opportunities Data',\n description: 'Export all identified opportunities with impact levels, effort estimates, categories, and related context.',\n icon: Target,\n action: () => handleExport('opportunities')\n }\n ];\n\n if (loading) {\n return (\n
\n
\n
\n );\n }\n\n return (\n
\n {/* Header */}\n
\n
\n
\n

Data Export

\n

\n Export your project data in CSV format for analysis, reporting, or backup purposes.\n

\n
\n
\n
\n\n {/* Content */}\n
\n
\n {/* Error Message */}\n {error && (\n
\n
\n \n
\n

Export Error

\n

{error}

\n
\n
\n
\n )}\n\n {/* Export Cards */}\n
\n {exportCards.map((card) => {\n const IconComponent = card.icon;\n const isExporting = exporting[card.id];\n const isSuccess = exportSuccess[card.id];\n\n return (\n \n
\n
\n
\n
\n
\n \n
\n
\n

{card.title}

\n

{card.description}

\n
\n
\n\n {/* Audit Selection Dropdown */}\n {card.requiresSelection && availableAudits.length > 0 && (\n
\n \n
\n setSelectedAuditId(e.target.value)}\n className=\"block w-full pl-3 pr-10 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 bg-white\"\n >\n {availableAudits.map((audit) => (\n \n ))}\n \n
\n \n
\n
\n
\n )}\n\n {/* No Audits Message */}\n {card.requiresSelection && availableAudits.length === 0 && (\n
\n

\n No audit results available yet. Run an audit to export data.\n

\n
\n )}\n
\n\n {/* Export Button */}\n \n {isExporting ? (\n <>\n \n Exporting...\n \n ) : isSuccess ? (\n <>\n \n Exported\n \n ) : (\n <>\n \n Export CSV\n \n )}\n \n
\n
\n
\n );\n })}\n
\n\n {/* Export Information */}\n
\n

Export Information

\n
    \n
  • \n \u2022\n All exports are in CSV format compatible with Excel, Google Sheets, and other spreadsheet applications\n
  • \n
  • \n \u2022\n Prompts & Topics export includes the latest analytics data from your most recent run\n
  • \n
  • \n \u2022\n Audit Results export combines all analysis categories and opportunities into a single comprehensive file\n
  • \n
  • \n \u2022\n Opportunities export includes all opportunities across all audit runs with full context\n
  • \n
  • \n \u2022\n Files are generated on-demand and include timestamps in the filename\n
  • \n
\n
\n
\n
\n \n );\n};\n\nexport default DataExportSection;", "// app/javascript/components/Admin/RunsDashboard.js (updated to show webhook responses)\nimport React, { useState, useEffect, useCallback } from 'react';\nimport { useParams, useNavigate, useLocation } from 'react-router-dom';\nimport axios from '../AxiosConfig';\nimport {\n ChevronLeft,\n ChevronRight,\n Clock,\n Database,\n AlertCircle,\n CheckCircle,\n XCircle,\n Loader,\n Search,\n ArrowLeft,\n Globe,\n MessageSquare,\n Zap\n} from 'lucide-react';\n\nconst RunsDashboard = () => {\n // Get project_id from URL if available\n const { projectId } = useParams();\n const navigate = useNavigate();\n const location = useLocation();\n\n // Check if we're in the admin section or standalone\n const isAdminSection = location.pathname.startsWith('/admin');\n\n // State management\n const [runs, setRuns] = useState([]);\n const [selectedRun, setSelectedRun] = useState(null);\n const [prompts, setPrompts] = useState([]);\n const [loading, setLoading] = useState(true);\n const [promptsLoading, setPromptsLoading] = useState(false);\n const [error, setError] = useState(null);\n\n // Pagination\n const [currentPage, setCurrentPage] = useState(1);\n const [itemsPerPage] = useState(10);\n const [totalRuns, setTotalRuns] = useState(0);\n const [totalPages, setTotalPages] = useState(1);\n\n // Fetch all runs on component mount and when page changes\n useEffect(() => {\n fetchRuns();\n }, [currentPage, projectId]);\n\n const fetchRuns = useCallback(async () => {\n try {\n setLoading(true);\n setError(null);\n\n const params = {\n page: currentPage,\n per_page: itemsPerPage\n };\n\n if (projectId) {\n params.project_id = projectId;\n }\n\n // Updated API endpoint to use the admin namespace\n const response = await axios.get('/api/admin/runs', { params });\n\n const runsData = response.data.runs || response.data;\n setRuns(runsData);\n\n if (response.data.total_count !== undefined) {\n setTotalRuns(response.data.total_count);\n setTotalPages(response.data.total_pages || Math.ceil(response.data.total_count / itemsPerPage));\n } else {\n setTotalRuns(runsData.length);\n setTotalPages(Math.ceil(runsData.length / itemsPerPage));\n }\n\n setLoading(false);\n\n if (runsData.length > 0 && !selectedRun) {\n setSelectedRun(runsData[0]);\n }\n } catch (err) {\n console.error('Error fetching runs:', err);\n setError('Failed to load runs. Please try again.');\n setLoading(false);\n }\n }, [currentPage, projectId, itemsPerPage, selectedRun]);\n\n // Fetch prompts when a run is selected\n useEffect(() => {\n if (!selectedRun) return;\n\n const fetchPrompts = async () => {\n try {\n setPromptsLoading(true);\n // Updated API endpoint to use the admin namespace\n const response = await axios.get(`/api/admin/runs/${selectedRun.id}/prompts`);\n setPrompts(response.data);\n setPromptsLoading(false);\n } catch (err) {\n console.error('Error fetching prompts:', err);\n setError(`Failed to load prompts for run #${selectedRun.id}. Please try again.`);\n setPromptsLoading(false);\n }\n };\n\n fetchPrompts();\n }, [selectedRun]);\n\n // Handle run selection\n const handleRunClick = (run) => {\n setSelectedRun(run);\n setPrompts([]);\n };\n\n // Handle page change\n const handlePageChange = (page) => {\n setCurrentPage(page);\n };\n\n // Format date\n const formatDate = (dateString) => {\n if (!dateString) return 'N/A';\n return new Date(dateString).toLocaleString();\n };\n\n // Format time difference\n const formatDuration = (startTime, endTime) => {\n if (!startTime || !endTime) return 'N/A';\n\n const start = new Date(startTime);\n const end = new Date(endTime);\n const durationMs = end - start;\n\n if (durationMs < 1000) {\n return `${durationMs}ms`;\n } else if (durationMs < 60000) {\n return `${(durationMs / 1000).toFixed(2)}s`;\n } else {\n const minutes = Math.floor(durationMs / 60000);\n const seconds = ((durationMs % 60000) / 1000).toFixed(0);\n return `${minutes}m ${seconds}s`;\n }\n };\n\n // Get status badge styling\n const getStatusBadge = (status) => {\n let color, bgColor, icon;\n\n switch (status?.toLowerCase()) {\n case 'completed':\n color = 'text-green-700';\n bgColor = 'bg-green-100';\n icon = ;\n break;\n case 'failed':\n color = 'text-red-700';\n bgColor = 'bg-red-100';\n icon = ;\n break;\n case 'error':\n color = 'text-red-700';\n bgColor = 'bg-red-100';\n icon = ;\n break;\n case 'pending':\n color = 'text-yellow-700';\n bgColor = 'bg-yellow-100';\n icon = ;\n break;\n default:\n color = 'text-gray-700';\n bgColor = 'bg-gray-100';\n icon = ;\n }\n\n return { color, bgColor, icon };\n };\n\n // Get method badge styling\n const getMethodBadge = (method) => {\n switch (method) {\n case 'webhook':\n return {\n icon: ,\n text: 'Webhook',\n color: 'text-blue-700',\n bgColor: 'bg-blue-100'\n };\n case 'api_fallback':\n return {\n icon: ,\n text: 'API Fallback',\n color: 'text-orange-700',\n bgColor: 'bg-orange-100'\n };\n case 'api':\n return {\n icon: ,\n text: 'API',\n color: 'text-gray-700',\n bgColor: 'bg-gray-100'\n };\n default:\n return {\n icon: ,\n text: 'Unknown',\n color: 'text-gray-700',\n bgColor: 'bg-gray-100'\n };\n }\n };\n\n // Helper to truncate text\n const truncateText = (text, maxLength = 100) => {\n if (!text) return '';\n if (text.length <= maxLength) return text;\n return text.substring(0, maxLength) + '...';\n };\n\n // Navigation helper\n const goBack = () => {\n if (isAdminSection) {\n navigate('/admin');\n } else if (projectId) {\n navigate(`/projects/${projectId}`);\n } else {\n navigate('/workspace');\n }\n };\n\n // Helper function to render platform attempts (including webhook responses)\n function renderPlatformAttempts(prompt, platformName) {\n const platformStatus = prompt.query_statuses.find(\n status => status.platform.toLowerCase() === platformName.toLowerCase()\n );\n\n if (!platformStatus || (platformStatus.attempts === 0 && !platformStatus.webhook_data)) {\n return (\n \n \n {platformName === 'chatgpt' ? 'ChatGPT' :\n platformName === 'claude' ? 'Claude' :\n platformName === 'perplexity' ? 'Perplexity' :\n 'Google AI Overview'}\n \n \n No attempts\n \n \n );\n }\n\n const methodBadge = getMethodBadge(platformStatus.method);\n\n // Handle webhook responses\n if (platformStatus.method === 'webhook' && platformStatus.webhook_data) {\n const { color, bgColor } = getStatusBadge(platformStatus.status);\n const webhookData = platformStatus.webhook_data;\n\n return (\n \n {platformStatus.platform}\n \n
\n \n {methodBadge.icon}\n {methodBadge.text}\n \n #1\n
\n \n \n \n {platformStatus.status}\n \n \n {formatDate(webhookData.created_at)}\n {formatDate(webhookData.created_at)}\n Instant\n \n
\n {!webhookData.success ? 'Webhook failed' : '-'}\n
\n \n \n );\n }\n\n // Handle API attempts (both regular and fallback)\n const attempts = platformStatus.attempts_data || [];\n\n if (attempts.length === 0) {\n return (\n \n \n {platformStatus.platform}\n \n \n {platformStatus.attempts} attempts, details not available\n \n \n );\n }\n\n return attempts.map((attempt, index) => {\n const { color, bgColor } = getStatusBadge(attempt.status);\n const isFirstRow = index === 0;\n\n return (\n \n {isFirstRow ? (\n \n {platformStatus.platform}\n \n ) : null}\n \n
\n \n {methodBadge.icon}\n {methodBadge.text}\n \n #{attempt.attempt_number}\n
\n \n \n \n {attempt.status}\n \n \n {formatDate(attempt.started_at)}\n {formatDate(attempt.completed_at)}\n {formatDuration(attempt.started_at, attempt.completed_at)}\n \n
\n {attempt.error_message || '-'}\n
\n \n \n );\n });\n }\n\n return (\n
\n {/* Back button and header */}\n
\n \n \n {projectId ? 'Back to Project' : (isAdminSection ? 'Back to Admin' : 'Back to Workspace')}\n \n\n

AI Query Runs Dashboard

\n

\n Monitor and analyze AI query runs across Claude, ChatGPT (via webhook + API fallback), Perplexity, and Google AI Overview platforms\n

\n
\n\n {/* Error display */}\n {error && (\n
\n
\n
\n \n

{error}

\n
\n
\n
\n )}\n\n {/* Main dashboard */}\n
\n {loading && !runs.length ? (\n
\n \n

Loading runs...

\n
\n ) : (\n
\n {/* Runs list sidebar */}\n
\n
\n

\n Runs {projectId ? `for Project #${projectId}` : ''}\n

\n
\n\n
\n {runs.length === 0 ? (\n
\n \n

No runs found

\n
\n ) : (\n
\n {runs.map(run => {\n const { color, bgColor, icon } = getStatusBadge(run.status);\n return (\n handleRunClick(run)}\n >\n
\n
\n
Run #{run.id}
\n

{run.project_name}

\n

{formatDate(run.created_at)}

\n
\n
\n {icon}\n {run.status}\n
\n
\n
\n );\n })}\n
\n )}\n
\n\n {/* Pagination */}\n {totalPages > 1 && (\n
\n
\n handlePageChange(currentPage - 1)}\n disabled={currentPage === 1}\n className=\"relative inline-flex items-center px-2 py-1 rounded border border-gray-300 text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed\"\n >\n \n \n \n Page {currentPage} of {totalPages}\n \n handlePageChange(currentPage + 1)}\n disabled={currentPage === totalPages}\n className=\"relative inline-flex items-center px-2 py-1 rounded border border-gray-300 text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed\"\n >\n \n \n
\n
\n )}\n
\n\n {/* Run details panel */}\n
\n {selectedRun ? (\n <>\n
\n

Run #{selectedRun.id} Details

\n
\n
\n Project:{' '}\n {selectedRun.project_name}\n
\n
\n Status:{' '}\n \n {selectedRun.status}\n \n
\n
\n Created:{' '}\n {formatDate(selectedRun.created_at)}\n
\n
\n
\n\n {promptsLoading ? (\n
\n \n

Loading prompts...

\n
\n ) : prompts.length === 0 ? (\n
\n \n

No prompts found for this run

\n
\n ) : (\n
\n {prompts.map((prompt) => (\n
\n {/* Prompt Header */}\n
\n
\n
\n
\n Topic: {prompt.topic_name}\n
\n

\n ID: {prompt.id}\n

\n
\n
\n\n {/* Prompt Text */}\n
\n
Prompt:
\n
\n {prompt.prompt}\n
\n
\n
\n\n {/* Platform Status Table */}\n
\n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n {/* Claude Attempts */}\n {renderPlatformAttempts(prompt, 'claude')}\n\n {/* ChatGPT Attempts (can be webhook or API fallback) */}\n {renderPlatformAttempts(prompt, 'chatgpt')}\n\n {/* Perplexity Attempts */}\n {renderPlatformAttempts(prompt, 'perplexity')}\n\n {/* Google AI Overview Attempts */}\n {renderPlatformAttempts(prompt, 'google ai overview')}\n \n
PlatformMethod & Attempt #StatusStartedCompletedDurationError
\n
\n
\n
\n ))}\n
\n )}\n \n ) : (\n
\n
\n \n

Select a run to view details

\n
\n
\n )}\n
\n
\n )}\n
\n \n );\n};\n\nexport default RunsDashboard;", "import React, { useContext, useState } from 'react';\nimport { Link, useLocation } from 'react-router-dom';\nimport { AuthContext } from '../../context/AuthContext';\nimport { LogOut, ArrowLeft } from 'lucide-react';\nimport TrialIndicator from '../shared/TrialIndicator';\nimport AuditIndicator from '../shared/AuditIndicator';\n\nconst AppLayout = ({ children }) => {\n const { logout, isImpersonating, adminUser, returnToAdminUser } = useContext(AuthContext);\n const [isReturning, setIsReturning] = useState(false);\n const location = useLocation();\n\n // Check if current route is project dashboard or audit results\n const shouldShowIndicators = () => {\n const path = location.pathname;\n // Match /projects/:projectId routes (project dashboard and its sub-routes)\n // This includes /projects/:projectId/audit (audit results)\n const projectDashboardPattern = /^\\/projects\\/[^/]+/;\n return projectDashboardPattern.test(path);\n };\n\n const handleLogout = async () => {\n try {\n await logout();\n } catch (error) {\n console.error('Error during logout:', error);\n alert('Failed to log out. Please try again.');\n }\n };\n\n const handleReturnToAdmin = async () => {\n setIsReturning(true);\n try {\n await returnToAdminUser();\n // Redirect to admin dashboard after successful return\n window.location.href = '/admin';\n } catch (error) {\n console.error('Failed to return to admin user:', error);\n // 401 = the session predates the admin claim (signed in as a user\n // before 2026-11-04); the app has already cleared it.\n alert(error.response?.status === 401\n ? 'This session was started before the latest update, so it cannot return to admin. Sign in again as yourself and use \"Sign in as\" once more.'\n : 'Failed to return to admin account. Please try again.');\n } finally {\n setIsReturning(false);\n }\n };\n\n return (\n
\n {/* Header */}\n
\n
\n
\n \n Visto\n \n \n
\n
\n {/* Return to admin button - only show when impersonating */}\n {isImpersonating && adminUser && (\n \n \n \n {isReturning ? 'Returning...' : `Return to ${adminUser.email}`}\n \n \n )}\n\n {/* Trial Indicator (NONE plan) or Audit Indicator (STARTER plan) - only show on project dashboard and audit results pages */}\n {shouldShowIndicators() && (\n <>\n \n \n \n )}\n\n \n Help\n \n \n My Account\n \n \n \n {isImpersonating ? 'Exit Session' : 'Logout'}\n \n
\n
\n
\n\n {/* Main content */}\n
\n {children}\n
\n\n {/* Footer */}\n
\n
\n
\n
\n

Visto

\n

Be Seen in the Age of AI Search

\n
\n
\n\n
\n
\n
\n © {new Date().getFullYear()} Visto. All rights reserved.\n
\n
\n
\n
\n );\n};\n\nexport default AppLayout;", "import React, { useState, useEffect, useContext, useRef } from 'react';\nimport { AuthContext } from '../../context/AuthContext';\nimport { Calendar, Rocket, X } from 'lucide-react';\nimport axios from '../AxiosConfig';\nimport { trackEvent } from '../Analytics/mixpanel';\n\n// Agency plan enum (matching Rails)\nconst AGENCY_PLAN = {\n NONE: 0,\n STARTER: 1,\n UNLIMITED: 2\n};\n\n// HubSpot Form Modal Component\nconst UnlockModal = ({ isOpen, onClose, user, source }) => {\n const [formLoaded, setFormLoaded] = useState(false);\n useEffect(() => {\n if (isOpen) {\n // Track modal open\n trackEvent('Unlock Modal Opened', {\n user_id: user?.id,\n source: source || 'workspace',\n modal_type: 'hubspot_form'\n });\n\n // Load HubSpot script if not already loaded\n const existingScript = document.querySelector('script[src=\"https://js.hsforms.net/forms/embed/48492217.js\"]');\n if (!existingScript) {\n const script = document.createElement('script');\n script.src = 'https://js.hsforms.net/forms/embed/48492217.js';\n script.defer = true;\n document.body.appendChild(script);\n\n // Listen for form ready event\n script.onload = () => {\n // Give HubSpot a moment to initialize\n setTimeout(() => setFormLoaded(true), 500);\n };\n } else {\n // Script already exists, form should load quickly\n setTimeout(() => setFormLoaded(true), 100);\n }\n } else {\n setFormLoaded(false);\n }\n }, [isOpen, user, source]);\n\n const handleClose = () => {\n trackEvent('Unlock Modal Closed', {\n user_id: user?.id,\n source: source || 'workspace',\n modal_type: 'hubspot_form'\n });\n onClose();\n };\n\n if (!isOpen) return null;\n\n return (\n
\n
\n \n \n \n\n {/* Loading state while form loads */}\n {!formLoaded && (\n
\n
\n
\n )}\n\n
\n
\n \n );\n};\n\nconst TrialIndicator = () => {\n const { user } = useContext(AuthContext);\n const [trialInfo, setTrialInfo] = useState(null);\n const [loading, setLoading] = useState(true);\n const [isHovered, setIsHovered] = useState(false);\n const [showUnlockModal, setShowUnlockModal] = useState(false);\n const hideTimeoutRef = useRef(null);\n\n useEffect(() => {\n const fetchTrialInfo = async () => {\n try {\n const response = await axios.get('/api/workspace');\n setTrialInfo(response.data.trial_info || null);\n } catch (err) {\n console.error('Error fetching trial info:', err);\n } finally {\n setLoading(false);\n }\n };\n\n if (user) {\n fetchTrialInfo();\n } else {\n setLoading(false);\n }\n }, [user]);\n\n // Cleanup timeout on unmount\n useEffect(() => {\n return () => {\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n }\n };\n }, []);\n\n const handleMouseEnter = () => {\n // Clear any pending hide timeout\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n hideTimeoutRef.current = null;\n }\n setIsHovered(true);\n\n // Track hover event\n trackEvent('Trial Indicator Hover', {\n user_id: user?.id,\n days_remaining: trialInfo?.days_remaining,\n trial_active: trialInfo?.trial_active,\n source: 'trial_indicator'\n });\n };\n\n const handleMouseLeave = () => {\n // Add delay before hiding\n hideTimeoutRef.current = setTimeout(() => {\n setIsHovered(false);\n }, 300);\n };\n\n // Don't show if loading or no trial info\n if (loading || !trialInfo) {\n return null;\n }\n\n // Only show for NONE plan users (active trial or expired trial)\n if (trialInfo.agency_plan !== AGENCY_PLAN.NONE) {\n return null;\n }\n\n const { days_remaining, days_elapsed, total_trial_days, trial_end_date, trial_active } = trialInfo;\n\n // Determine if trial is expired\n const isExpired = !trial_active || days_remaining <= 0;\n\n // Calculate progress percentage (100% if expired)\n const progressPercentage = isExpired ? 100 : Math.min((days_elapsed / total_trial_days) * 100, 100);\n\n // Display values\n const displayDaysRemaining = isExpired ? 0 : days_remaining;\n const displayDaysElapsed = isExpired ? total_trial_days : days_elapsed;\n\n // Colors based on trial status\n const indicatorTextColor = isExpired ? '#E11D48' : '#4F46E5';\n const indicatorBgColor = isExpired ? '#FFF1F2' : '#F5F3FF';\n const indicatorBorderColor = isExpired ? '#FECDD3' : '#DDD6FE';\n const pillTextColor = isExpired ? '#E11D48' : '#4F46E5';\n const pillBgColor = isExpired ? '#FFF1F2' : '#EEF2FF';\n const progressBarColor = isExpired ? '#F43F5E' : '#4F46E5';\n const circleFilledColor = isExpired ? '#F43F5E' : '#4F46E5';\n const circleUnfilledColor = isExpired ? '#FECDD3' : '#EDEDFC';\n\n // SVG circle parameters for the indicator\n const size = 20;\n const strokeWidth = 3;\n const radius = (size - strokeWidth) / 2;\n const circumference = 2 * Math.PI * radius;\n const filledAmount = (progressPercentage / 100) * circumference;\n\n // Format the end date for the popover (abbreviated month)\n const formattedEndDate = new Date(trial_end_date + 'T00:00:00').toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n year: 'numeric'\n });\n\n const handleUpgradeClick = () => {\n setIsHovered(false);\n setShowUnlockModal(true);\n\n // Track upgrade button click\n trackEvent('Trial Upgrade Click', {\n user_id: user?.id,\n days_remaining: days_remaining,\n trial_active: trial_active,\n trial_expired: isExpired,\n source: 'trial_indicator'\n });\n };\n\n return (\n <>\n \n {/* Main Indicator Badge */}\n \n {/* Progress Circle */}\n \n {/* Background circle (unfilled portion) */}\n \n {/* Progress circle (filled portion - represents days elapsed) */}\n \n \n\n {/* Days remaining text */}\n \n {displayDaysRemaining} {displayDaysRemaining === 1 ? 'day' : 'days'} left\n \n \n\n {/* Hover Popover - Mini TrialSidebar */}\n {isHovered && (\n \n
\n {/* Header */}\n
\n

Free Trial

\n \n {displayDaysRemaining} days left\n \n
\n\n {/* Trial Period Progress */}\n
\n
\n Trial period\n \n {displayDaysElapsed} of {total_trial_days} days\n \n
\n \n \n
\n
\n\n {/* End Date Section */}\n \n
\n \n \n Free Trial\n {isExpired ? 'ended' : 'ends'} {formattedEndDate}\n \n
\n \n\n {/* Upgrade CTA */}\n \n \n Upgrade Plan\n \n \n \n )}\n \n\n {/* Unlock Modal */}\n setShowUnlockModal(false)}\n />\n \n );\n};\n\nexport default TrialIndicator;", "import React, { useState, useEffect, useContext, useRef } from 'react';\nimport { AuthContext } from '../../context/AuthContext';\nimport { Calendar, Rocket, X } from 'lucide-react';\nimport axios from '../AxiosConfig';\nimport { trackEvent } from '../Analytics/mixpanel';\n\n// HubSpot Form Modal Component\nconst UnlockModal = ({ isOpen, onClose, user, source }) => {\n const [formLoaded, setFormLoaded] = useState(false);\n useEffect(() => {\n if (isOpen) {\n // Track modal open\n trackEvent('Unlock Modal Opened', {\n user_id: user?.id,\n source: source || 'workspace',\n modal_type: 'hubspot_form'\n });\n\n // Load HubSpot script if not already loaded\n const existingScript = document.querySelector('script[src=\"https://js.hsforms.net/forms/embed/48492217.js\"]');\n if (!existingScript) {\n const script = document.createElement('script');\n script.src = 'https://js.hsforms.net/forms/embed/48492217.js';\n script.defer = true;\n document.body.appendChild(script);\n\n // Listen for form ready event\n script.onload = () => {\n // Give HubSpot a moment to initialize\n setTimeout(() => setFormLoaded(true), 500);\n };\n } else {\n // Script already exists, form should load quickly\n setTimeout(() => setFormLoaded(true), 100);\n }\n } else {\n setFormLoaded(false);\n }\n }, [isOpen, user, source]);\n\n const handleClose = () => {\n trackEvent('Unlock Modal Closed', {\n user_id: user?.id,\n source: source || 'workspace',\n modal_type: 'hubspot_form'\n });\n onClose();\n };\n\n if (!isOpen) return null;\n\n return (\n
\n
\n \n \n \n\n {/* Loading state while form loads */}\n {!formLoaded && (\n
\n
\n
\n )}\n\n
\n
\n \n );\n};\n\nconst AuditIndicator = () => {\n const { user } = useContext(AuthContext);\n const [trialActive, setTrialActive] = useState(false);\n const [starterAuditInfo, setStarterAuditInfo] = useState(null);\n const [agencyPlan, setAgencyPlan] = useState(null);\n const [loading, setLoading] = useState(true);\n const [isHovered, setIsHovered] = useState(false);\n const [showUnlockModal, setShowUnlockModal] = useState(false);\n const hideTimeoutRef = useRef(null);\n\n // Agency plan enum (matching Rails)\n const AGENCY_PLAN = {\n NONE: 0,\n STARTER: 1,\n UNLIMITED: 2\n };\n\n useEffect(() => {\n const fetchAuditInfo = async () => {\n try {\n const response = await axios.get('/api/workspace');\n setStarterAuditInfo(response.data.starter_audit_info || null);\n setAgencyPlan(response.data.trial_info?.agency_plan ?? null);\n setTrialActive(response.data.trial_info?.trial_active ?? false); // Add this line\n } catch (err) {\n console.error('Error fetching audit info:', err);\n } finally {\n setLoading(false);\n }\n };\n\n if (user) {\n fetchAuditInfo();\n } else {\n setLoading(false);\n }\n }, [user]);\n\n // Cleanup timeout on unmount\n useEffect(() => {\n return () => {\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n }\n };\n }, []);\n\n const handleMouseEnter = () => {\n // Clear any pending hide timeout\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n hideTimeoutRef.current = null;\n }\n setIsHovered(true);\n\n // Track hover event\n trackEvent('Audit Indicator Hover', {\n user_id: user?.id,\n audits_remaining: starterAuditInfo?.audits_remaining,\n audits_used: starterAuditInfo?.audits_used,\n max_audits: starterAuditInfo?.max_audits,\n is_exhausted: starterAuditInfo?.audits_remaining <= 0,\n source: 'audit_indicator'\n });\n };\n\n const handleMouseLeave = () => {\n // Add delay before hiding\n hideTimeoutRef.current = setTimeout(() => {\n setIsHovered(false);\n }, 300);\n };\n\n // Don't show if loading or no audit info\n if (loading || !starterAuditInfo || trialActive) {\n return null;\n }\n\n // Only show for STARTER plan users\n if (agencyPlan !== AGENCY_PLAN.STARTER) {\n return null;\n }\n\n const { audits_used, audits_remaining, max_audits, days_until_refresh, refresh_date } = starterAuditInfo;\n\n // Determine if audits are exhausted\n const isExhausted = audits_remaining <= 0;\n\n // Calculate progress percentage\n const progressPercentage = Math.min((audits_used / max_audits) * 100, 100);\n\n // Colors based on audit status\n const indicatorTextColor = isExhausted ? '#E11D48' : '#4F46E5';\n const indicatorBgColor = isExhausted ? '#FFF1F2' : '#F5F3FF';\n const indicatorBorderColor = isExhausted ? '#FECDD3' : '#DDD6FE';\n const pillTextColor = isExhausted ? '#E11D48' : '#4F46E5';\n const pillBgColor = isExhausted ? '#FFF1F2' : '#EEF2FF';\n const progressBarColor = isExhausted ? '#F43F5E' : '#4F46E5';\n const circleFilledColor = isExhausted ? '#F43F5E' : '#4F46E5';\n const circleUnfilledColor = isExhausted ? '#FECDD3' : '#EDEDFC';\n\n // SVG circle parameters for the indicator\n const size = 20;\n const strokeWidth = 3;\n const radius = (size - strokeWidth) / 2;\n const circumference = 2 * Math.PI * radius;\n const filledAmount = (progressPercentage / 100) * circumference;\n\n // Format the refresh date for the popover (abbreviated month)\n const formattedRefreshDate = new Date(refresh_date + 'T00:00:00').toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n year: 'numeric'\n });\n\n const handleUpgradeClick = () => {\n setIsHovered(false);\n setShowUnlockModal(true);\n\n // Track upgrade button click\n trackEvent('Audit Upgrade Click', {\n user_id: user?.id,\n audits_remaining: audits_remaining,\n audits_used: audits_used,\n max_audits: max_audits,\n is_exhausted: isExhausted,\n days_until_refresh: days_until_refresh,\n source: 'audit_indicator'\n });\n };\n\n return (\n <>\n \n {/* Main Indicator Badge */}\n \n {/* Progress Circle */}\n \n {/* Background circle (unfilled portion) */}\n \n {/* Progress circle (filled portion - represents audits used) */}\n \n \n\n {/* Audits text */}\n \n {audits_used}/{max_audits} Audits\n \n \n\n {/* Hover Popover - Mini StarterAuditSidebar */}\n {isHovered && (\n \n
\n {/* Header */}\n
\n

Monthly Audits

\n \n {audits_remaining} remaining\n \n
\n\n {/* Audit Usage Progress */}\n
\n
\n Used this cycle\n \n {audits_used}/{max_audits}\n \n
\n \n \n
\n
\n\n {/* Refresh Date Section */}\n \n
\n \n \n {days_until_refresh} days\n until refresh\n \n
\n \n\n {/* Upgrade CTA */}\n \n \n Get Unlimited Audits\n \n \n \n )}\n \n\n {/* Unlock Modal */}\n setShowUnlockModal(false)}\n />\n \n );\n};\n\nexport default AuditIndicator;", "import React, { useState } from 'react';\nimport { useNavigate } from 'react-router-dom';\nimport axios from '../AxiosConfig';\nimport {\n Calendar,\n CheckCircle,\n ArrowLeft,\n Mail,\n User,\n Briefcase,\n MessageSquare,\n Loader\n} from 'lucide-react';\n\nconst ContactUs = () => {\n const navigate = useNavigate();\n const [formData, setFormData] = useState({\n name: '',\n email: '',\n companyName: '',\n message: '',\n inquiryType: 'general' // Options: general, demo, support, partnership\n });\n const [errors, setErrors] = useState({});\n const [isSubmitting, setIsSubmitting] = useState(false);\n const [isSubmitted, setIsSubmitted] = useState(false);\n\n const handleChange = (e) => {\n const { name, value } = e.target;\n setFormData({\n ...formData,\n [name]: value\n });\n\n // Clear error when user types\n if (errors[name]) {\n setErrors({\n ...errors,\n [name]: ''\n });\n }\n };\n\n const validateForm = () => {\n const newErrors = {};\n\n if (!formData.name.trim()) {\n newErrors.name = 'Name is required';\n }\n\n if (!formData.email.trim()) {\n newErrors.email = 'Email is required';\n } else if (!/\\S+@\\S+\\.\\S+/.test(formData.email)) {\n newErrors.email = 'Email is invalid';\n }\n\n if (!formData.companyName.trim()) {\n newErrors.companyName = 'Company name is required';\n }\n\n if (!formData.message.trim()) {\n newErrors.message = 'Message is required';\n }\n\n setErrors(newErrors);\n return Object.keys(newErrors).length === 0;\n };\n\n const handleSubmit = async (e) => {\n e.preventDefault();\n\n if (!validateForm()) {\n return;\n }\n\n setIsSubmitting(true);\n\n try {\n // Use the correct API endpoint matching our controller\n await axios.post('/api/contact_requests', {\n contact: {\n name: formData.name,\n email: formData.email,\n company_name: formData.companyName,\n message: formData.message,\n inquiry_type: formData.inquiryType\n }\n });\n\n setIsSubmitted(true);\n } catch (error) {\n console.error('Error submitting contact form:', error);\n setErrors({\n ...errors,\n submit: 'Failed to submit your message. Please try again.'\n });\n } finally {\n setIsSubmitting(false);\n }\n };\n\n const goBack = () => {\n navigate('/');\n };\n\n return (\n
\n
\n \n \n Back to Home\n \n\n
\n {!isSubmitted ? (\n <>\n
\n
\n

\n Get in Touch\n

\n

\n Want to get started with LoveItAI or see a demo? We're here to help! Fill out the form below and our team will get back to you shortly.\n

\n
\n\n {errors.submit && (\n
\n {errors.submit}\n
\n )}\n\n
\n
\n \n \n \n \n \n \n \n
\n\n
\n \n
\n
\n \n
\n \n
\n {errors.name && (\n

{errors.name}

\n )}\n
\n\n
\n \n
\n
\n \n
\n \n
\n {errors.email && (\n

{errors.email}

\n )}\n
\n\n
\n \n
\n
\n \n
\n \n
\n {errors.companyName && (\n

{errors.companyName}

\n )}\n
\n\n
\n \n
\n
\n \n
\n \n
\n {errors.message && (\n

{errors.message}

\n )}\n
\n\n
\n \n {isSubmitting ? (\n <>\n \n Sending...\n \n ) : (\n 'Send Message'\n )}\n \n
\n
\n
\n \n ) : (\n
\n
\n \n
\n

Thank you for getting in touch!

\n

\n We've received your message and will get back to you shortly. You can also use this link to sign up for a meeting time with our team directly:{' '}\n \n http://bit.ly/3HPJy3O\n \n

\n\n
\n \n \n Schedule a Meeting\n \n
\n\n \n\n
\n \n Return to Home\n \n
\n
\n )}\n
\n
\n
\n );\n};\n\nexport default ContactUs;", "import React, { useState, useEffect, useRef } from 'react';\nimport { Search, Play, CheckCircle, Clock, AlertCircle, MessageSquare } from 'lucide-react';\nimport axios from '../AxiosConfig';\n\nconst OptimizationPrototype = () => {\n const [userProjects, setUserProjects] = useState(null);\n const [selectedProjectId, setSelectedProjectId] = useState(null);\n const [projectData, setProjectData] = useState(null);\n const [selectedPromptId, setSelectedPromptId] = useState(null);\n const [loadingProjects, setLoadingProjects] = useState(true);\n const [loadingProject, setLoadingProject] = useState(false);\n const [currentView, setCurrentView] = useState('projects');\n const [isSubmitting, setIsSubmitting] = useState(false);\n const [analysisData, setAnalysisData] = useState(null);\n const [selectedQuery, setSelectedQuery] = useState(null);\n const [error, setError] = useState(null);\n const [promptId, setPromptId] = useState(null);\n const pollingInterval = useRef(null);\n const promptIdRef = useRef(null);\n const selectedQueryRef = useRef(null);\n const hasAutoSelectedRef = useRef(false);\n\n // Update ref when selectedQuery changes\n useEffect(() => {\n selectedQueryRef.current = selectedQuery;\n }, [selectedQuery]);\n\n // Fetch user projects on mount\n useEffect(() => {\n fetchUserProjects();\n }, []);\n\n const fetchUserProjects = async () => {\n setLoadingProjects(true);\n try {\n const response = await axios.get('/api/optimization_prototype/projects');\n setUserProjects(response.data);\n } catch (err) {\n console.error('Error fetching user projects:', err);\n setError('Failed to load projects');\n } finally {\n setLoadingProjects(false);\n }\n };\n\n const handleProjectSelect = async (projectId) => {\n setSelectedProjectId(projectId);\n setCurrentView('prompts');\n setProjectData(null);\n setSelectedPromptId(null);\n setAnalysisData(null);\n setSelectedQuery(null);\n setError(null);\n\n // Reset optimization state\n if (pollingInterval.current) {\n stopPolling();\n }\n\n await fetchProjectData(projectId);\n };\n\n const handlePromptSelect = async (promptId) => {\n setSelectedPromptId(promptId);\n\n // Check if this prompt has existing optimization\n const prompt = projectData.prompts.find(p => p.id === promptId);\n if (prompt && prompt.has_existing_optimization) {\n // Load existing analysis\n try {\n const statusResponse = await axios.get(`/api/optimization_prototype/${promptId}/status`);\n if (statusResponse.data.analysis_steps && statusResponse.data.analysis_steps.length > 0) {\n setPromptId(promptId);\n promptIdRef.current = promptId;\n\n const allQueries = statusResponse.data.analysis_steps || [];\n const completedQueries = allQueries.filter(q => q.response).length;\n const totalQueries = allQueries.length;\n const progressPercentage = totalQueries > 0 ? (completedQueries / totalQueries * 100) : 0;\n\n setAnalysisData({\n prompt: statusResponse.data.prompt,\n queries: allQueries,\n progress: {\n completed: completedQueries,\n total: totalQueries,\n percentage: Math.round(progressPercentage),\n is_complete: completedQueries === totalQueries && totalQueries > 0\n }\n });\n\n // Auto-select first query if available\n if (allQueries.length > 0) {\n setSelectedQuery(allQueries[0]);\n hasAutoSelectedRef.current = true;\n }\n\n // Start polling if not complete\n if (completedQueries < totalQueries) {\n startPolling();\n }\n\n setCurrentView('analysis');\n }\n } catch (err) {\n console.error('Error loading existing analysis:', err);\n setError('Failed to load existing analysis');\n }\n } else {\n // No existing analysis, show analysis setup\n setCurrentView('analysis');\n }\n };\n\n const handleBackToProjects = () => {\n setCurrentView('projects');\n setSelectedProjectId(null);\n setProjectData(null);\n setSelectedPromptId(null);\n setAnalysisData(null);\n setSelectedQuery(null);\n setError(null);\n\n // Stop any ongoing polling\n if (pollingInterval.current) {\n stopPolling();\n }\n };\n\n const handleBackToPrompts = () => {\n setCurrentView('prompts');\n setSelectedPromptId(null);\n setAnalysisData(null);\n setSelectedQuery(null);\n setError(null);\n\n // Stop any ongoing polling\n if (pollingInterval.current) {\n stopPolling();\n }\n };\n\n const fetchProjectData = async (projectId) => {\n setLoadingProject(true);\n try {\n const response = await axios.get(`/api/optimization_prototype/project/${projectId}`);\n setProjectData(response.data);\n } catch (err) {\n console.error('Error fetching project data:', err);\n setError('Failed to load project data');\n } finally {\n setLoadingProject(false);\n }\n };\n\n const startPolling = () => {\n if (pollingInterval.current) {\n clearInterval(pollingInterval.current);\n }\n\n console.log('Starting continuous polling');\n pollingInterval.current = setInterval(() => {\n console.log('Polling for updates...');\n fetchAnalysisStatus();\n }, 3000);\n };\n\n const stopPolling = () => {\n if (pollingInterval.current) {\n console.log('Stopping polling');\n clearInterval(pollingInterval.current);\n pollingInterval.current = null;\n }\n };\n\n // Cleanup polling on component unmount\n useEffect(() => {\n return () => {\n stopPolling();\n };\n }, []);\n\n const handleRunAnalysis = async () => {\n if (!selectedPromptId) {\n setError('No prompt selected');\n return;\n }\n\n setIsSubmitting(true);\n setError(null);\n hasAutoSelectedRef.current = false;\n\n try {\n const response = await axios.post('/api/optimization_prototype', {\n prompt_id: selectedPromptId\n });\n\n if (response.data.success) {\n setPromptId(response.data.prompt_id);\n promptIdRef.current = response.data.prompt_id;\n // Start polling immediately\n startPolling();\n // Do initial fetch\n await fetchAnalysisStatus(response.data.prompt_id);\n // Analysis data will be set by fetchAnalysisStatus\n }\n } catch (err) {\n console.error('Error starting optimization:', err);\n setError(err.response?.data?.error || 'Failed to start optimization analysis');\n } finally {\n setIsSubmitting(false);\n }\n };\n\n const fetchAnalysisStatus = async (pId = null) => {\n // Use parameter, ref, or state - in that order of preference\n const currentPromptId = pId || promptIdRef.current || promptId;\n if (!currentPromptId) {\n console.log('No promptId available for fetching status');\n return;\n }\n\n try {\n console.log(`Fetching status for promptId: ${currentPromptId}`);\n const response = await axios.get(`/api/optimization_prototype/${currentPromptId}/status`);\n\n // Transform the data to show all optimization queries in order\n const allQueries = response.data.analysis_steps || [];\n\n // Calculate progress based on completed queries\n const completedQueries = allQueries.filter(q => q.response).length;\n const totalQueries = allQueries.length;\n const progressPercentage = totalQueries > 0 ? (completedQueries / totalQueries * 100) : 0;\n\n console.log(`Found ${totalQueries} queries, ${completedQueries} completed`);\n\n setAnalysisData({\n prompt: response.data.prompt,\n queries: allQueries,\n progress: {\n completed: completedQueries,\n total: totalQueries,\n percentage: Math.round(progressPercentage),\n is_complete: completedQueries === totalQueries && totalQueries > 0\n }\n });\n\n // Auto-select first query ONLY if we haven't done initial auto-selection\n // and no query is currently selected\n if (!hasAutoSelectedRef.current && !selectedQueryRef.current && allQueries.length > 0) {\n setSelectedQuery(allQueries[0]);\n hasAutoSelectedRef.current = true;\n }\n // If a query was selected, try to maintain the selection by finding the same query by ID\n else if (selectedQueryRef.current && allQueries.length > 0) {\n const currentSelectedId = selectedQueryRef.current.id;\n const updatedSelectedQuery = allQueries.find(q => q.id === currentSelectedId);\n if (updatedSelectedQuery) {\n // Update the selected query with fresh data\n setSelectedQuery(updatedSelectedQuery);\n }\n }\n } catch (err) {\n console.error('Error fetching analysis status:', err);\n }\n };\n\n const handleQuerySelect = (query) => {\n setSelectedQuery(query);\n };\n\n const getQueryIcon = (query) => {\n if (query.response) {\n return ;\n }\n return ;\n };\n\n const getStepLabel = (stepName) => {\n if (!stepName || typeof stepName !== 'string') {\n return 'Unknown Step';\n }\n\n return stepName\n .split('_')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n };\n\n const renderProjectSelection = () => {\n if (loadingProjects) {\n return (\n
\n
\n
\n Loading your projects...\n
\n
\n );\n }\n\n if (!userProjects || !userProjects.projects || userProjects.projects.length === 0) {\n return (\n
\n
\n

Optimization Prototype

\n

\n No projects found. Please create a project first.\n

\n
\n
\n );\n }\n\n return (\n
\n
\n

Optimization Prototype

\n

\n Select a project to analyze your optimization opportunities.\n

\n
\n\n
\n {userProjects.projects.map((project) => (\n handleProjectSelect(project.id)}\n className=\"w-full text-left p-6 border border-gray-200 rounded-lg hover:border-indigo-300 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all\"\n >\n
\n
\n

\n {project.name}\n

\n {project.company_name && (\n

\n Company: {project.company_name}\n

\n )}\n
\n {project.prompt_count || 0} prompts\n Created: {new Date(project.created_at).toLocaleDateString()}\n
\n
\n
\n \n
\n
\n \n ))}\n
\n\n {error && (\n
\n

{error}

\n
\n )}\n
\n );\n };\n\n const renderPromptsList = () => {\n if (loadingProject) {\n return (\n
\n
\n
\n Loading project data...\n
\n
\n );\n }\n\n if (!projectData || !projectData.prompts || projectData.prompts.length === 0) {\n return (\n
\n
\n
\n

Project Prompts

\n \n \u2190 Back to Projects\n \n
\n

\n No prompts found in this project. Please add some prompts first.\n

\n
\n
\n );\n }\n\n return (\n
\n
\n
\n

Project Prompts

\n \n \u2190 Back to Projects\n \n
\n\n {projectData.company && (\n
\n

Project Details

\n
\n
\n Project:\n {projectData.project.name}\n
\n
\n Company:\n {projectData.company.name}\n
\n {projectData.company.domains && projectData.company.domains.length > 0 && (\n
\n Domain:\n {projectData.company.domains[0]}\n
\n )}\n
\n
\n )}\n
\n\n
\n

\n Select a prompt to analyze ({projectData.prompts.length} total)\n

\n\n {projectData.prompts.map((prompt, index) => (\n handlePromptSelect(prompt.id)}\n className=\"w-full text-left p-6 border border-gray-200 rounded-lg hover:border-indigo-300 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all\"\n >\n
\n
\n
\n

\n Prompt #{index + 1}\n

\n {prompt.has_existing_optimization && (\n \n \n Has Analysis\n \n )}\n
\n\n

\n {prompt.prompt}\n

\n\n
\n Topic: {prompt.topic_name}\n Volume: {prompt.volume_estimate}\n Difficulty: {prompt.difficulty}\n Created: {new Date(prompt.created_at).toLocaleDateString()}\n
\n
\n
\n {prompt.has_existing_optimization ? (\n \n ) : (\n \n )}\n
\n
\n \n ))}\n
\n\n {error && (\n
\n

{error}

\n
\n )}\n
\n );\n };\n\n const renderAnalysisSetup = () => {\n if (!selectedPromptId || !projectData) {\n return null;\n }\n\n const selectedPrompt = projectData.prompts.find(p => p.id === selectedPromptId);\n\n return (\n
\n
\n
\n

Optimization Analysis

\n \n \u2190 Back to Prompts\n \n
\n\n
\n

Analysis Details

\n
\n
\n Project:\n {projectData.project.name}\n
\n
\n Company:\n {projectData.company?.name}\n
\n
\n Topic:\n {selectedPrompt?.topic_name}\n
\n {projectData.company?.domains && projectData.company.domains.length > 0 && (\n
\n Domain:\n {projectData.company.domains[0]}\n
\n )}\n
\n\n
\n

Prompt to Analyze:

\n
\n

{selectedPrompt?.prompt}

\n
\n
\n
\n
\n\n
\n

\n Ready to analyze this prompt and find optimization opportunities for your company.\n

\n\n \n {isSubmitting ? (\n <>\n
\n Starting Analysis...\n \n ) : (\n <>\n \n Run Analysis\n \n )}\n \n
\n\n {error && (\n
\n

{error}

\n
\n )}\n
\n );\n };\n\n const renderAnalysis = () => (\n
\n {/* Header */}\n
\n
\n
\n
\n

Optimization Analysis

\n \n \u2190 Back to Prompts\n \n
\n

\n Analyzing: \"{analysisData.prompt.text}\"\n

\n
\n
\n
Progress
\n
\n
\n
\n
\n \n {analysisData.progress.percentage}%\n \n
\n
\n {analysisData.progress.completed} / {analysisData.progress.total} queries\n
\n
\n
\n
\n\n {/* Main Analysis Section */}\n
\n {/* Queries List - Left Side */}\n
\n
\n
\n

Analysis Queries

\n

\n {analysisData.queries.length} total queries\n

\n
\n
\n {analysisData.queries.map((query, index) => (\n handleQuerySelect(query)}\n className={`w-full text-left p-4 hover:bg-gray-50 focus:outline-none focus:bg-gray-50 transition-colors ${\n selectedQuery?.id === query.id ? 'bg-indigo-50 border-r-2 border-indigo-500' : ''\n }`}\n >\n
\n
\n {getQueryIcon(query)}\n
\n

\n Query #{index + 1}\n

\n

\n {query.query}\n

\n {query.step && (\n

\n {getStepLabel(query.step)}\n

\n )}\n
\n
\n {!query.response && (\n
\n
\n
\n )}\n
\n \n ))}\n
\n
\n
\n\n {/* Query Details - Right Side */}\n
\n
\n {selectedQuery ? (\n <>\n
\n
\n

\n Query #{analysisData.queries.findIndex(q => q.id === selectedQuery.id) + 1}\n

\n
\n {getQueryIcon(selectedQuery)}\n \n {selectedQuery.response ? 'Complete' : 'In Progress'}\n \n
\n
\n {selectedQuery.step && (\n

\n {getStepLabel(selectedQuery.step)}\n

\n )}\n
\n
\n
\n

Query:

\n
\n

{selectedQuery.query}

\n
\n
\n\n
\n

Response:

\n
\n {selectedQuery.response ? (\n
\n {(() => {\n let responseText = '';\n\n if (typeof selectedQuery.response === 'string') {\n try {\n // Try to parse JSON string\n const parsed = JSON.parse(selectedQuery.response);\n responseText = parsed.response || selectedQuery.response;\n } catch {\n // If not JSON, use as-is\n responseText = selectedQuery.response;\n }\n } else if (selectedQuery.response.response) {\n // If it's an object with .response property\n responseText = selectedQuery.response.response;\n } else {\n // Fallback to stringified version\n responseText = JSON.stringify(selectedQuery.response, null, 2);\n }\n\n return (\n
\n {responseText}\n
\n );\n })()}\n
\n ) : (\n
\n
\n
\n Analyzing...\n
\n
\n )}\n
\n
\n\n {selectedQuery.created_at && (\n
\n Created: {new Date(selectedQuery.created_at).toLocaleString()}\n
\n )}\n
\n \n ) : (\n
\n \n

Select a query to view details

\n
\n )}\n
\n
\n
\n \n );\n\n return (\n
\n {currentView === 'projects' && renderProjectSelection()}\n {currentView === 'prompts' && renderPromptsList()}\n {currentView === 'analysis' && (analysisData ? renderAnalysis() : renderAnalysisSetup())}\n
\n );\n};\n\nexport default OptimizationPrototype;", "import React, { useState } from 'react';\nimport { useNavigate } from 'react-router-dom';\nimport axios from '../AxiosConfig';\n\nconst PromptBankGeneration = () => {\n const [formData, setFormData] = useState({\n companyName: '',\n domain: ''\n });\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState('');\n const [success, setSuccess] = useState('');\n const [projectData, setProjectData] = useState(null);\n const [currentState, setCurrentState] = useState('not_started');\n const [promptsData, setPromptsData] = useState({});\n const [stepErrors, setStepErrors] = useState({\n company_analysis: false,\n topic_hierarchy: false,\n prompts: false\n });\n // NEW: Audit state variables\n const [auditStatus, setAuditStatus] = useState('not_started'); // 'not_started', 'running', 'completed', 'error'\n const [auditResult, setAuditResult] = useState(null);\n\n const navigate = useNavigate();\n\n const formatScore = (score) => {\n if (!score || score === 0) return '0.0';\n return parseFloat(score).toFixed(1);\n };\n\n // Add this helper function to get score color coding\n const getScoreColorClass = (score) => {\n const numScore = parseFloat(score) || 0;\n if (numScore >= 8.0) return 'text-green-600 bg-green-50';\n if (numScore >= 6.0) return 'text-blue-600 bg-blue-50';\n if (numScore >= 4.0) return 'text-yellow-600 bg-yellow-50';\n return 'text-gray-600 bg-gray-50';\n };\n\n const handleInputChange = (e) => {\n const { name, value } = e.target;\n setFormData(prev => ({\n ...prev,\n [name]: value\n }));\n };\n\n const clearStepError = (step) => {\n setStepErrors(prev => ({\n ...prev,\n [step]: false\n }));\n };\n\n const setStepError = (step, errorMessage) => {\n setStepErrors(prev => ({\n ...prev,\n [step]: true\n }));\n setError(errorMessage);\n setLoading(false);\n };\n\n const handleSubmit = async (e) => {\n if (e) e.preventDefault();\n\n setLoading(true);\n setError('');\n setSuccess('');\n setProjectData(null);\n setCurrentState('generating_company_summary_and_user_personas');\n clearStepError('company_analysis');\n\n try {\n const response = await axios.post('/api/prompt_bank_generation', {\n company_name: formData.companyName,\n domain: formData.domain\n });\n\n if (response.status === 201) {\n const project = response.data.project;\n setProjectData(project);\n setSuccess(`Project created successfully! AI analysis is being generated...`);\n startPolling(project.id);\n }\n } catch (err) {\n console.error('Error creating project:', err);\n setStepError('company_analysis', err.response?.data?.error || 'Failed to create project');\n setCurrentState('not_started');\n } finally {\n setLoading(false);\n }\n };\n\n const retryCompanyAnalysis = async () => {\n if (!projectData?.id) return;\n\n setLoading(true);\n setError('');\n setSuccess('Retrying AI analysis...');\n setCurrentState('generating_company_summary_and_user_personas');\n clearStepError('company_analysis');\n\n try {\n // Call retry endpoint for company analysis\n const response = await axios.post(`/api/prompt_bank_generation/${projectData.id}/retry_company_analysis`);\n\n if (response.status === 200) {\n startPolling(projectData.id);\n }\n } catch (err) {\n console.error('Error retrying company analysis:', err);\n setStepError('company_analysis', err.response?.data?.error || 'Failed to retry company analysis');\n setCurrentState('error_company_analysis');\n } finally {\n setLoading(false);\n }\n };\n\n const startPolling = (projectId) => {\n const pollInterval = setInterval(async () => {\n try {\n const response = await axios.get(`/api/prompt_bank_generation/${projectId}/status`);\n const project = response.data.project;\n\n setProjectData(project);\n\n if (project.company_ai_summary && project.user_personas && project.user_personas.length > 0) {\n clearInterval(pollInterval);\n setCurrentState('completed_generating_company_summary_and_user_personas');\n setSuccess('AI analysis completed successfully!');\n }\n } catch (err) {\n console.error('Error polling status:', err);\n clearInterval(pollInterval);\n setStepError('company_analysis', 'Error checking analysis status');\n setCurrentState('error_company_analysis');\n }\n }, 3000);\n\n setTimeout(() => {\n clearInterval(pollInterval);\n if (currentState === 'generating_company_summary_and_user_personas') {\n setStepError('company_analysis', 'Analysis is taking longer than expected. You can retry or check back later.');\n setCurrentState('error_company_analysis');\n }\n }, 600000);\n };\n\n const handleGenerateTopicHierarchy = async () => {\n try {\n setLoading(true);\n setCurrentState('generating_topic_hierarchy');\n setSuccess('Topic hierarchy generation started...');\n clearStepError('topic_hierarchy');\n\n const response = await axios.post(`/api/prompt_bank_generation/${projectData.id}/generate_topic_hierarchy`);\n\n if (response.status === 200) {\n startTopicHierarchyPolling(projectData.id);\n }\n } catch (err) {\n console.error('Error generating topic hierarchy:', err);\n setStepError('topic_hierarchy', err.response?.data?.error || 'Failed to start topic hierarchy generation');\n setCurrentState('error_topic_hierarchy');\n } finally {\n setLoading(false);\n }\n };\n\n const retryTopicHierarchy = async () => {\n if (!projectData?.id) return;\n\n setLoading(true);\n setError('');\n setSuccess('Retrying topic hierarchy generation...');\n setCurrentState('generating_topic_hierarchy');\n clearStepError('topic_hierarchy');\n\n try {\n const response = await axios.post(`/api/prompt_bank_generation/${projectData.id}/generate_topic_hierarchy`);\n\n if (response.status === 200) {\n startTopicHierarchyPolling(projectData.id);\n }\n } catch (err) {\n console.error('Error retrying topic hierarchy:', err);\n setStepError('topic_hierarchy', err.response?.data?.error || 'Failed to retry topic hierarchy generation');\n setCurrentState('error_topic_hierarchy');\n } finally {\n setLoading(false);\n }\n };\n\n const startTopicHierarchyPolling = (projectId) => {\n const pollInterval = setInterval(async () => {\n try {\n const response = await axios.get(`/api/prompt_bank_generation/${projectId}/status`);\n const project = response.data.project;\n\n setProjectData(project);\n\n if (project.topics_count > 0) {\n clearInterval(pollInterval);\n setCurrentState('completed_generating_topic_hierarchy');\n setSuccess('Topic hierarchy generation completed!');\n }\n } catch (err) {\n console.error('Error polling topic hierarchy status:', err);\n clearInterval(pollInterval);\n setStepError('topic_hierarchy', 'Error checking topic hierarchy status');\n setCurrentState('error_topic_hierarchy');\n }\n }, 3000);\n\n setTimeout(() => {\n clearInterval(pollInterval);\n if (currentState === 'generating_topic_hierarchy') {\n setStepError('topic_hierarchy', 'Topic hierarchy generation is taking longer than expected. You can retry or check back later.');\n setCurrentState('error_topic_hierarchy');\n }\n }, 900000);\n };\n\n const handleGeneratePrompts = async () => {\n try {\n setLoading(true);\n setCurrentState('generating_prompts');\n setSuccess('Starting prompt generation for subtopics...');\n clearStepError('prompts');\n\n const response = await axios.post(`/api/prompt_bank_generation/${projectData.id}/generate_prompts`);\n\n if (response.status === 200) {\n startPromptsPolling(projectData.id);\n }\n } catch (err) {\n console.error('Error generating prompts:', err);\n setStepError('prompts', err.response?.data?.error || 'Failed to start prompt generation');\n setCurrentState('error_prompts');\n } finally {\n setLoading(false);\n }\n };\n\n const retryPrompts = async () => {\n if (!projectData?.id) return;\n\n setLoading(true);\n setError('');\n setSuccess('Retrying prompt generation...');\n setCurrentState('generating_prompts');\n clearStepError('prompts');\n\n try {\n const response = await axios.post(`/api/prompt_bank_generation/${projectData.id}/generate_prompts`);\n\n if (response.status === 200) {\n startPromptsPolling(projectData.id);\n }\n } catch (err) {\n console.error('Error retrying prompts:', err);\n setStepError('prompts', err.response?.data?.error || 'Failed to retry prompt generation');\n setCurrentState('error_prompts');\n } finally {\n setLoading(false);\n }\n };\n\n const startPromptsPolling = (projectId) => {\n const pollInterval = setInterval(async () => {\n try {\n const response = await axios.get(`/api/prompt_bank_generation/${projectId}/status`);\n const project = response.data.project;\n\n setProjectData(project);\n\n // Always update prompts data to show progress\n if (project.prompts_data) {\n setPromptsData(project.prompts_data);\n\n // Update success message to show progress\n const totalPrompts = Object.values(project.prompts_data).reduce((total, prompts) => total + prompts.length, 0);\n if (totalPrompts > 0) {\n setSuccess(`Generated ${totalPrompts} prompts so far...`);\n }\n }\n\n // Only stop polling when explicitly marked as completed\n if (project.prompts_status === 'completed') {\n clearInterval(pollInterval);\n setCurrentState('completed_generating_prompts');\n const finalPromptCount = project.prompts_data ?\n Object.values(project.prompts_data).reduce((total, prompts) => total + prompts.length, 0) : 0;\n setSuccess(`Prompt generation completed! Generated ${finalPromptCount} total prompts.`);\n }\n } catch (err) {\n console.error('Error polling prompts status:', err);\n clearInterval(pollInterval);\n setStepError('prompts', 'Error checking prompts status');\n setCurrentState('error_prompts');\n }\n }, 3000);\n\n setTimeout(() => {\n clearInterval(pollInterval);\n if (currentState === 'generating_prompts') {\n setStepError('prompts', 'Prompt generation is taking longer than expected. You can retry or check back later.');\n setCurrentState('error_prompts');\n }\n }, 1200000);\n };\n\n // NEW: Conduct Audit Handler\n const handleConductAudit = async () => {\n try {\n setLoading(true);\n setAuditStatus('running');\n setError('');\n setSuccess('Initiating comprehensive audit...');\n\n const response = await axios.post(`/api/prompt_bank_generation/${projectData.id}/conduct_audit`);\n\n if (response.status === 200) {\n setAuditResult(response.data.audit_details);\n setSuccess(`Audit initiated! ${response.data.audit_details.jobs_enqueued} analysis jobs started.`);\n // You could start polling here if you want to track audit progress\n }\n } catch (err) {\n console.error('Error conducting audit:', err);\n setAuditStatus('error');\n setError(err.response?.data?.error || 'Failed to initiate audit');\n } finally {\n setLoading(false);\n }\n };\n\n const renderRetryButton = (onRetry, buttonText = \"Retry\", className = \"bg-red-600 hover:bg-red-700\") => (\n \n {loading ? (\n <>\n \n \n \n \n Retrying...\n \n ) : (\n buttonText\n )}\n \n );\n\n const renderErrorState = (title, description, retryFunction) => (\n
\n
\n \n \n \n
\n

{title}

\n

{description}

\n
\n {renderRetryButton(retryFunction)}\n
\n
\n
\n
\n );\n\n const renderPrompts = (topicId, topicName) => {\n const topicPrompts = promptsData[topicId];\n if (!topicPrompts || topicPrompts.length === 0) return null;\n\n const promptTypeLabels = {\n 0: 'Unbranded Discovery',\n 1: 'Informational',\n 2: 'Branded'\n };\n\n const promptTypeColors = {\n 0: 'bg-blue-100 text-blue-800',\n 1: 'bg-green-100 text-green-800',\n 2: 'bg-purple-100 text-purple-800'\n };\n\n return (\n
\n
\n Generated Prompts ({topicPrompts.length}):\n
\n
\n {topicPrompts.map((prompt, index) => (\n
\n
\n \n {promptTypeLabels[prompt.prompt_type]}\n \n
\n
\n \"{prompt.content}\"\n
\n
\n ))}\n
\n
\n );\n };\n\n const renderStateContent = () => {\n switch (currentState) {\n case 'error_company_analysis':\n return renderErrorState(\n \"AI Analysis Failed\",\n error || \"The AI analysis step encountered an error.\",\n retryCompanyAnalysis\n );\n\n case 'error_topic_hierarchy':\n return (\n
\n
\n

AI Analysis Completed \u2713

\n

Company summary and {projectData?.user_personas?.length || 0} user personas generated

\n
\n {renderErrorState(\n \"Topic Hierarchy Generation Failed\",\n error || \"The topic hierarchy generation step encountered an error.\",\n retryTopicHierarchy\n )}\n
\n );\n\n case 'error_prompts':\n return (\n
\n
\n

AI Analysis Completed \u2713

\n

Company summary and {projectData?.user_personas?.length || 0} user personas generated

\n
\n
\n

Topic Hierarchy Generated \u2713

\n

{projectData?.topics_count || 0} topics created

\n
\n {renderErrorState(\n \"Prompt Generation Failed\",\n error || \"The prompt generation step encountered an error.\",\n retryPrompts\n )}\n
\n );\n\n case 'generating_company_summary_and_user_personas':\n return (\n
\n
\n \n \n \n \n
\n

Generating AI Analysis

\n

Analyzing company information and generating user personas...

\n
\n
\n
\n );\n\n case 'completed_generating_company_summary_and_user_personas':\n return (\n
\n

AI Analysis Completed!

\n\n {projectData?.company_ai_summary && (\n
\n

Company Summary:

\n
\n {projectData.company_ai_summary}\n
\n
\n )}\n\n {projectData?.user_personas && projectData.user_personas.length > 0 && (\n
\n

User Personas ({projectData.user_personas.length}):

\n
\n {projectData.user_personas.map((persona, index) => (\n
\n
{persona.name}
\n

{persona.description}

\n
\n ))}\n
\n
\n )}\n\n
\n navigate(`/projects/${projectData.id}`)}\n className=\"text-green-700 hover:text-green-900 text-sm font-medium underline\"\n >\n View Project Dashboard \u2192\n \n\n \n {loading ? 'Starting...' : 'Generate Topic Hierarchy'}\n \n
\n
\n );\n\n case 'generating_topic_hierarchy':\n return (\n
\n
\n

AI Analysis Completed \u2713

\n

Company summary and {projectData?.user_personas?.length || 0} user personas generated

\n
\n\n
\n
\n
\n \n \n \n \n
\n

Generating Topic Hierarchy

\n

Creating 3-level semantic topic structure...

\n
\n
\n
\n {renderRetryButton(retryTopicHierarchy, \"Restart\", \"bg-blue-600 hover:bg-blue-700\")}\n
\n
\n
\n
\n );\n\n case 'generating_prompts':\n return (\n
\n
\n

AI Analysis Completed \u2713

\n

Company summary and {projectData?.user_personas?.length || 0} user personas generated

\n
\n\n
\n

Topic Hierarchy Generated \u2713

\n

{projectData?.topics_count || 0} topics created

\n
\n\n
\n
\n
\n \n \n \n \n
\n

Generating Prompts

\n

Creating AI conversation prompts for subtopics...

\n
\n
\n
\n {renderRetryButton(retryPrompts, \"Restart\", \"bg-blue-600 hover:bg-blue-700\")}\n
\n
\n
\n\n {Object.keys(promptsData).length > 0 && (\n
\n
Generated Prompts:
\n
\n {projectData.topic_hierarchy && projectData.topic_hierarchy.map((topic) => (\n
\n {renderPrompts(topic.id, topic.name)}\n\n {topic.subtopics && topic.subtopics.map((subtopic) => (\n
\n {renderPrompts(subtopic.id, subtopic.name)}\n\n {subtopic.sub_subtopics && subtopic.sub_subtopics.map((subSubtopic) => (\n
\n {renderPrompts(subSubtopic.id, subSubtopic.name)}\n
\n ))}\n
\n ))}\n
\n ))}\n
\n
\n )}\n
\n );\n\n case 'completed_generating_prompts':\n return (\n
\n
\n

AI Analysis Completed \u2713

\n

Company summary and {projectData?.user_personas?.length || 0} user personas generated

\n
\n\n
\n

Topic Hierarchy Generated \u2713

\n

{projectData?.topics_count || 0} topics created

\n
\n\n
\n

Prompts Generated! \u2713

\n

\n AI conversation prompts created for key subtopics\n

\n\n {projectData.topic_hierarchy && projectData.topic_hierarchy.length > 0 && (\n
\n
Complete Topic Hierarchy with Prompts:
\n
\n {projectData.topic_hierarchy.map((topic, topicIndex) => (\n
\n
\n {topicIndex + 1}. {topic.name}\n \n Score: {formatScore(topic.score)}\n \n
\n {renderPrompts(topic.id, topic.name)}\n\n {topic.subtopics && topic.subtopics.length > 0 && (\n
\n {topic.subtopics.map((subtopic, subtopicIndex) => (\n
\n
\n {topicIndex + 1}.{subtopicIndex + 1} {subtopic.name}\n \n Score: {formatScore(subtopic.score)}\n \n
\n {renderPrompts(subtopic.id, subtopic.name)}\n\n {subtopic.sub_subtopics && subtopic.sub_subtopics.length > 0 && (\n
\n {subtopic.sub_subtopics.map((subSubtopic, subSubtopicIndex) => (\n
\n
\n {topicIndex + 1}.{subtopicIndex + 1}.{subSubtopicIndex + 1} {subSubtopic.name}\n \n Score: {formatScore(subSubtopic.score)}\n \n
\n {renderPrompts(subSubtopic.id, subSubtopic.name)}\n
\n ))}\n
\n )}\n
\n ))}\n
\n )}\n
\n ))}\n
\n
\n )}\n\n {/* Action buttons */}\n
\n navigate(`/projects/${projectData.id}`)}\n className=\"text-green-700 hover:text-green-900 text-sm font-medium underline\"\n >\n View Project Dashboard \u2192\n \n\n {/* NEW: Conduct Audit Button */}\n {auditStatus === 'not_started' && (\n \n {loading ? (\n <>\n \n \n \n \n Initiating Audit...\n \n ) : (\n <>\n \n \n \n Conduct Audit\n \n )}\n \n )}\n\n {auditStatus === 'running' && (\n
\n {/* Running Status */}\n
\n
\n \n \n \n \n
\n

Comprehensive Audit Running

\n

\n {auditResult && `${auditResult.jobs_enqueued} analysis jobs initiated`}\n

\n
\n
\n
\n\n {/* NEW: View Audit Button - Shows immediately when audit starts */}\n navigate(`/projects/${projectData.id}/audit`)}\n className=\"bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-md text-sm font-medium flex items-center justify-center w-full\"\n >\n \n \n \n View Audit Results\n \n
\n )}\n\n {auditStatus === 'error' && (\n
\n
\n \n \n \n
\n

Audit Failed

\n

You can retry from the project dashboard

\n
\n
\n
\n )}\n
\n
\n
\n );\n\n case 'completed_generating_topic_hierarchy':\n return (\n
\n
\n

AI Analysis Completed \u2713

\n

Company summary and {projectData?.user_personas?.length || 0} user personas generated

\n
\n\n
\n

Topic Hierarchy Generated! \u2713

\n

\n {projectData.topics_count} topics created with 3-level semantic hierarchy\n

\n\n {projectData.topic_hierarchy && projectData.topic_hierarchy.length > 0 && (\n
\n
Complete Topic Hierarchy:
\n
\n {projectData.topic_hierarchy.map((topic, topicIndex) => (\n
\n
\n {topicIndex + 1}. {topic.name}\n \n Score: {formatScore(topic.score)}\n \n
\n\n {topic.subtopics && topic.subtopics.length > 0 && (\n
\n {topic.subtopics.map((subtopic, subtopicIndex) => (\n
\n
\n {topicIndex + 1}.{subtopicIndex + 1} {subtopic.name}\n \n Score: {formatScore(subtopic.score)}\n \n
\n\n {subtopic.sub_subtopics && subtopic.sub_subtopics.length > 0 && (\n
\n {subtopic.sub_subtopics.map((subSubtopic, subSubtopicIndex) => (\n
\n
\n {topicIndex + 1}.{subtopicIndex + 1}.{subSubtopicIndex + 1} {subSubtopic.name}\n \n Score: {formatScore(subSubtopic.score)}\n \n
\n
\n ))}\n
\n )}\n
\n ))}\n
\n )}\n
\n ))}\n
\n
\n )}\n\n
\n navigate(`/projects/${projectData.id}`)}\n className=\"text-green-700 hover:text-green-900 text-sm font-medium underline\"\n >\n View Project Dashboard \u2192\n \n\n \n {loading ? 'Starting...' : 'Generate AI Prompts'}\n \n
\n
\n
\n );\n\n default:\n return null;\n }\n };\n\n const isFormValid = formData.companyName.trim() && formData.domain.trim();\n\n return (\n
\n
\n
\n
\n

\n Prompt Bank Generation\n

\n

\n Create a new project with AI-generated company analysis and topic hierarchy\n

\n
\n\n
\n
\n \n \n
\n\n
\n \n \n
\n\n {error && !stepErrors.company_analysis && !stepErrors.topic_hierarchy && !stepErrors.prompts && (\n
\n
\n
\n

\n Error\n

\n
\n {error}\n
\n
\n
\n
\n )}\n\n {success && (\n
\n
\n
\n

\n Success\n

\n
\n {success}\n
\n
\n
\n
\n )}\n\n {renderStateContent()}\n\n {currentState === 'not_started' && (\n \n {loading ? (\n <>\n \n \n \n \n Creating Project...\n \n ) : (\n 'Create Project & Generate Analysis'\n )}\n \n )}\n
\n\n
\n navigate('/')}\n className=\"text-blue-600 hover:text-blue-500 text-sm font-medium\"\n disabled={currentState !== 'not_started' && !currentState.startsWith('error_') && !currentState.startsWith('completed_')}\n >\n \u2190 Back to Home\n \n
\n
\n
\n
\n );\n};\n\nexport default PromptBankGeneration;", "import React, { useState, useEffect, useContext } from 'react';\nimport { useParams, useNavigate, useLocation } from 'react-router-dom';\nimport axios from '../AxiosConfig';\nimport {\n BarChart3,\n Eye,\n Users,\n Heart,\n Quote,\n FileText,\n Search,\n Settings,\n Calendar,\n Globe,\n Target,\n TrendingUp,\n AlertTriangle,\n CheckCircle,\n Clock,\n Zap,\n Trophy,\n Download,\n Share,\n ExternalLink,\n RefreshCw,\n ChevronDown,\n X\n} from 'lucide-react';\n\n// Import the new analysis components\nimport VisibilityAnalysis from './VisibilityAnalysis';\nimport CompetitorAnalysis from './CompetitorAnalysis';\nimport SentimentAnalysis from './SentimentAnalysis';\nimport CitationAnalysis from './CitationAnalysis';\nimport OnPageAnalysis from './OnPageAnalysis';\nimport ContentGapAnalysis from './ContentGapAnalysis';\nimport TechnicalAnalysis from './TechnicalAnalysis';\n\n// Import Mixpanel tracking\nimport { AuthContext } from '../../context/AuthContext';\nimport { trackEvent } from '../Analytics/mixpanel';\n\n// Agency plan enum (matching Rails)\nconst AGENCY_PLAN = {\n NONE: 0,\n STARTER: 1,\n UNLIMITED: 2\n};\n\n// Audit Limit Modal Component\nconst AuditLimitModal = ({ isOpen, onClose, onUpgrade, starterAuditInfo, trialInfo, projectId, user }) => {\n if (!isOpen) return null;\n\n // Determine if this is an expired trial (NONE plan) or starter limit\n const isExpiredTrial = trialInfo && !trialInfo.trial_active && trialInfo.agency_plan === AGENCY_PLAN.NONE;\n const isStarterLimit = starterAuditInfo && starterAuditInfo.audits_remaining <= 0;\n\n // Get refresh info for starter plan\n const days_until_refresh = starterAuditInfo?.days_until_refresh;\n const refresh_date = starterAuditInfo?.refresh_date;\n\n // Format the refresh date\n const formattedRefreshDate = refresh_date\n ? new Date(refresh_date + 'T00:00:00').toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric'\n })\n : '';\n\n const features = [\n \"Unlimited client audits\",\n \"Full analytics dashboard\",\n \"Opportunity recommendations\",\n \"Strategy & measurement tools\"\n ];\n\n // Track close modal event\n const handleClose = () => {\n trackEvent('Audit Limit Modal Closed', {\n project_id: projectId,\n user_id: user?.id,\n reason: isExpiredTrial ? 'expired_trial' : 'starter_limit_reached',\n agency_plan: trialInfo?.agency_plan,\n audits_remaining: starterAuditInfo?.audits_remaining,\n action: 'close_button'\n });\n onClose();\n };\n\n // Track upgrade button click\n const handleUpgrade = () => {\n trackEvent('Audit Limit Modal Upgrade Clicked', {\n project_id: projectId,\n user_id: user?.id,\n reason: isExpiredTrial ? 'expired_trial' : 'starter_limit_reached',\n agency_plan: trialInfo?.agency_plan,\n audits_remaining: starterAuditInfo?.audits_remaining,\n days_until_refresh: days_until_refresh\n });\n onUpgrade();\n };\n\n // Track \"Maybe Later\" click\n const handleMaybeLater = () => {\n trackEvent('Audit Limit Modal Maybe Later Clicked', {\n project_id: projectId,\n user_id: user?.id,\n reason: isExpiredTrial ? 'expired_trial' : 'starter_limit_reached',\n agency_plan: trialInfo?.agency_plan,\n audits_remaining: starterAuditInfo?.audits_remaining\n });\n onClose();\n };\n\n return (\n
\n
\n {/* Close button */}\n \n \n \n\n {/* Top section - white background */}\n
\n {/* Error icon */}\n
\n \n \n
\n
\n\n {/* Title */}\n

\n {isExpiredTrial ? 'Free Trial has Ended' : 'Monthly Audit Limit Reached'}\n

\n\n {/* Description */}\n

\n {isExpiredTrial\n ? \"Your free trial has ended. You'll need to upgrade to refresh audits.\"\n : <>You've used all 5 of your monthly audits. Your audits will refresh in {days_until_refresh} days on {formattedRefreshDate}.\n }\n

\n
\n\n {/* Middle section - purple tinted background with horizontal padding */}\n
\n \n {/* Upgrade header */}\n
\n \n \n
\n
\n

\n {isExpiredTrial ? 'Upgrade to Keep Access' : 'Upgrade to Unlimited'}\n

\n

\n Keep enjoying unlimited audits and full platform access.\n

\n
\n
\n\n {/* Features list */}\n
\n {features.map((feature, index) => (\n
\n \n {feature}\n
\n ))}\n
\n
\n \n\n {/* Bottom section - CTAs on white background */}\n
\n {/* Upgrade CTA */}\n \n \n {isExpiredTrial ? 'Upgrade Plan' : 'Get Unlimited Audits'}\n \n\n {/* Maybe Later */}\n \n Maybe Later\n \n
\n \n \n );\n};\n\n// HubSpot Form Modal Component\nconst UnlockModal = ({ isOpen, onClose, user, source }) => {\n const [formLoaded, setFormLoaded] = useState(false);\n useEffect(() => {\n if (isOpen) {\n // Track modal open\n trackEvent('Unlock Modal Opened', {\n user_id: user?.id,\n source: source || 'workspace',\n modal_type: 'hubspot_form'\n });\n\n // Load HubSpot script if not already loaded\n const existingScript = document.querySelector('script[src=\"https://js.hsforms.net/forms/embed/48492217.js\"]');\n if (!existingScript) {\n const script = document.createElement('script');\n script.src = 'https://js.hsforms.net/forms/embed/48492217.js';\n script.defer = true;\n document.body.appendChild(script);\n\n // Listen for form ready event\n script.onload = () => {\n // Give HubSpot a moment to initialize\n setTimeout(() => setFormLoaded(true), 500);\n };\n } else {\n // Script already exists, form should load quickly\n setTimeout(() => setFormLoaded(true), 100);\n }\n } else {\n setFormLoaded(false);\n }\n }, [isOpen, user, source]);\n\n const handleClose = () => {\n trackEvent('Unlock Modal Closed', {\n user_id: user?.id,\n source: source || 'workspace',\n modal_type: 'hubspot_form'\n });\n onClose();\n };\n\n if (!isOpen) return null;\n\n return (\n
\n
\n \n \n \n\n {/* Loading state while form loads */}\n {!formLoaded && (\n
\n
\n
\n )}\n\n
\n
\n \n );\n};\n\nconst AuditResults = () => {\n const { projectId, auditId: urlAuditId } = useParams();\n const navigate = useNavigate();\n const location = useLocation();\n const { user } = useContext(AuthContext); // Get user data for tracking\n\n const [activeSection, setActiveSection] = useState('full-analysis');\n const [loading, setLoading] = useState(true);\n const [contentLoading, setContentLoading] = useState(false);\n const [error, setError] = useState('');\n const [dashboardData, setDashboardData] = useState(null);\n const [refreshing, setRefreshing] = useState(false);\n const [auditRunning, setAuditRunning] = useState(false);\n const [auditHistory, setAuditHistory] = useState([]);\n const [auditStep, setAuditStep] = useState(null);\n const [projectData, setProjectData] = useState(null);\n const [initialLoadComplete, setInitialLoadComplete] = useState(false);\n const [showAuditLimitModal, setShowAuditLimitModal] = useState(false);\n const [showUnlockModal, setShowUnlockModal] = useState(false);\n const [starterAuditInfo, setStarterAuditInfo] = useState(null);\n const [trialInfo, setTrialInfo] = useState(null);\n\n // Use urlAuditId directly as the selected audit\n const selectedAuditId = urlAuditId;\n\n // Detect audit category from URL path\n useEffect(() => {\n const pathSegments = location.pathname.split('/');\n const auditIndex = pathSegments.indexOf('audit');\n\n if (auditIndex !== -1) {\n // Check if there's an audit ID after 'audit'\n const nextSegment = pathSegments[auditIndex + 1];\n\n // If nextSegment is a number (audit ID), look for category after it\n if (nextSegment && /^\\d+$/.test(nextSegment)) {\n const category = pathSegments[auditIndex + 2];\n if (category) {\n setActiveSection(category);\n } else {\n setActiveSection('full-analysis');\n }\n } else if (nextSegment) {\n // nextSegment is the category (no audit ID in URL)\n setActiveSection(nextSegment);\n } else {\n setActiveSection('full-analysis');\n }\n } else {\n setActiveSection('full-analysis');\n }\n }, [location.pathname]);\n\n // Helper to build audit path with optional audit ID\n const buildAuditPath = (category = null) => {\n const basePath = selectedAuditId\n ? `/projects/${projectId}/audit/${selectedAuditId}`\n : `/projects/${projectId}/audit`;\n return category ? `${basePath}/${category}` : basePath;\n };\n\n const sidebarSections = [\n {\n title: 'Client Analysis',\n items: [\n { id: 'full-analysis', title: 'Full Analysis', path: buildAuditPath() }\n ]\n },\n {\n title: 'Detailed Reports',\n items: [\n { id: 'visibility', title: 'Visibility Analysis', path: buildAuditPath('visibility') },\n { id: 'competitor', title: 'Competitor Analysis', path: buildAuditPath('competitor') },\n { id: 'sentiment', title: 'Sentiment Analysis', path: buildAuditPath('sentiment') },\n { id: 'citation', title: 'Citation Analysis', path: buildAuditPath('citation') },\n { id: 'onpage', title: 'On Page Analysis', path: buildAuditPath('onpage') },\n { id: 'content-gap', title: 'Content Coverage Analysis', path: buildAuditPath('content-gap') },\n { id: 'technical', title: 'Technical Analysis', path: buildAuditPath('technical') }\n ]\n }\n ];\n\n const checkForNoPagesScenario = (dashboardData) => {\n // NEW: Check the explicit no_pages_found flag from the backend\n if (dashboardData.no_pages_found) {\n return true;\n }\n\n // FALLBACK: Keep the existing logic as backup\n const { detailed_insights } = dashboardData;\n\n const onPageNoPages = detailed_insights?.onpage?.has_no_pages ||\n (detailed_insights?.onpage?.items_count === 0 &&\n detailed_insights?.onpage?.score?.includes('No valid pages'));\n\n const technicalNoPages = detailed_insights?.technical?.has_no_pages ||\n (detailed_insights?.technical?.items_count === 0 &&\n detailed_insights?.technical?.score?.includes('No valid pages'));\n\n return onPageNoPages && technicalNoPages;\n };\n\n useEffect(() => {\n if (projectId) {\n fetchDashboardData(urlAuditId, true);\n fetchWorkspaceInfo();\n }\n }, [projectId]);\n\n // Fetch workspace info for trial/audit limit checks\n const fetchWorkspaceInfo = async () => {\n try {\n const response = await axios.get('/api/workspace');\n setTrialInfo(response.data.trial_info || null);\n setStarterAuditInfo(response.data.starter_audit_info || null);\n } catch (err) {\n console.error('Error fetching workspace info:', err);\n }\n };\n\n // Fetch data when URL audit ID changes (after initial load)\n useEffect(() => {\n if (urlAuditId && initialLoadComplete) {\n fetchDashboardData(urlAuditId, false);\n }\n }, [urlAuditId]);\n\n // Track audit section views when activeSection changes\n useEffect(() => {\n if (activeSection && dashboardData) {\n const sectionInfo = sidebarSections\n .flatMap(s => s.items)\n .find(item => item.id === activeSection);\n\n trackEvent('Audit Section Viewed', {\n project_id: projectId,\n section_id: activeSection,\n section_title: sectionInfo?.title || activeSection,\n user_id: user?.id,\n client_domain: dashboardData.project_info?.client_domain,\n geo_score: dashboardData.analysis_overview?.geo_score,\n ai_readiness: dashboardData.analysis_overview?.ai_readiness,\n total_opportunities: dashboardData.analysis_overview?.total_opportunities,\n critical_issues: dashboardData.analysis_overview?.critical_issues\n });\n }\n }, [activeSection, dashboardData, projectId, user?.id]);\n\n const fetchDashboardData = async (auditId = null, isInitialLoad = true) => {\n try {\n // Use full loading only on initial load, content loading for audit switches\n if (isInitialLoad) {\n setLoading(true);\n } else {\n setContentLoading(true);\n }\n setError('');\n\n console.log('Fetching dashboard data for project:', projectId, 'audit:', auditId);\n\n let currentProjectData = projectData;\n\n // Fetch project data first to get status (only on initial load)\n if (isInitialLoad) {\n const projectResponse = await axios.get(`/api/projects/${projectId}`);\n currentProjectData = projectResponse.data;\n setProjectData(currentProjectData);\n\n // Check if project is currently generating audit\n const isGenerating = currentProjectData?.generating_audit || currentProjectData?.data_collection_running;\n setAuditRunning(isGenerating);\n setAuditStep(currentProjectData?.audit_step || null);\n\n // Fetch audit data to get available audit results\n try {\n const auditResponse = await axios.get(`/api/projects/${projectId}/audit`);\n\n // Build audit history from the audit response\n if (auditResponse.data?.audit_result) {\n const auditResults = auditResponse.data.audit_results || [auditResponse.data.audit_result];\n setAuditHistory(auditResults);\n\n // If no audit in URL, redirect to latest audit URL and continue fetching\n if (!auditId && auditResults.length > 0) {\n const latestAuditId = auditResults[0].id;\n // Update URL to include audit ID\n navigate(`/projects/${projectId}/audit/${latestAuditId}`, { replace: true });\n // Continue fetching with the latest audit ID instead of returning early\n auditId = latestAuditId;\n }\n }\n } catch (auditErr) {\n console.log('No audit results available yet');\n setAuditHistory([]);\n }\n }\n\n // Fetch dashboard data for the selected/specified audit\n const targetAuditId = auditId;\n const isGenerating = currentProjectData?.generating_audit || currentProjectData?.data_collection_running;\n\n if (!isGenerating || targetAuditId) {\n try {\n const dashboardUrl = targetAuditId\n ? `/api/projects/${projectId}/audit/dashboard?audit_result_id=${targetAuditId}`\n : `/api/projects/${projectId}/audit/dashboard`;\n const response = await axios.get(dashboardUrl);\n console.log('Dashboard API response:', response.data);\n setDashboardData(response.data);\n } catch (dashErr) {\n // If dashboard fails but audit is running, that's expected\n if (!isGenerating) {\n throw dashErr;\n }\n console.log('Dashboard not available yet, audit in progress');\n setDashboardData(null);\n }\n }\n\n setInitialLoadComplete(true);\n\n } catch (err) {\n console.error('Error fetching dashboard data:', err);\n console.error('Error details:', {\n status: err.response?.status,\n statusText: err.response?.statusText,\n data: err.response?.data\n });\n\n const errorMessage = err.response?.data?.error || err.message || 'Failed to load dashboard data';\n setError(errorMessage);\n\n } finally {\n setLoading(false);\n setContentLoading(false);\n }\n };\n\n const handleRefreshAudit = async () => {\n // Track refresh attempt (before any limits are checked)\n trackEvent('Audit Refresh Clicked', {\n project_id: projectId,\n user_id: user?.id,\n current_section: activeSection,\n client_domain: dashboardData?.project_info?.client_domain,\n trial_active: trialInfo?.trial_active,\n agency_plan: trialInfo?.agency_plan,\n audits_remaining: starterAuditInfo?.audits_remaining\n });\n\n // Check if trial is expired and plan is NONE\n if (trialInfo && !trialInfo.trial_active && trialInfo.agency_plan === AGENCY_PLAN.NONE) {\n trackEvent('Audit Limit Modal Shown', {\n project_id: projectId,\n user_id: user?.id,\n reason: 'expired_trial',\n agency_plan: trialInfo.agency_plan,\n trial_active: trialInfo.trial_active,\n source: 'refresh_audit'\n });\n setShowAuditLimitModal(true);\n return;\n }\n\n // Check if STARTER plan user has reached audit limit\n if (!trialInfo?.trial_active && starterAuditInfo && starterAuditInfo.audits_remaining <= 0) {\n trackEvent('Audit Limit Modal Shown', {\n project_id: projectId,\n user_id: user?.id,\n reason: 'starter_limit_reached',\n agency_plan: trialInfo?.agency_plan,\n audits_remaining: starterAuditInfo.audits_remaining,\n days_until_refresh: starterAuditInfo.days_until_refresh,\n source: 'refresh_audit'\n });\n setShowAuditLimitModal(true);\n return;\n }\n\n try {\n setRefreshing(true);\n\n trackEvent('Audit Refresh Initiated', {\n project_id: projectId,\n user_id: user?.id,\n current_section: activeSection,\n client_domain: dashboardData?.project_info?.client_domain,\n audits_remaining: starterAuditInfo?.audits_remaining\n });\n\n const response = await axios.post(`/api/projects/${projectId}/audit/refresh`);\n\n console.log('Refresh audit response:', response.data);\n\n trackEvent('Audit Refresh Success', {\n project_id: projectId,\n user_id: user?.id,\n current_section: activeSection\n });\n\n // Instead of redirecting, start polling for the new audit\n setAuditRunning(true);\n setAuditStep({ current: 1, total: 7 });\n\n // Refresh data to start tracking the new audit\n fetchDashboardData(urlAuditId, true);\n\n // Refresh workspace info to update audit counts\n fetchWorkspaceInfo();\n\n } catch (err) {\n console.error('Error refreshing audit:', err);\n const errorMessage = err.response?.data?.message || err.message || 'Failed to refresh audit';\n\n trackEvent('Audit Refresh Failed', {\n project_id: projectId,\n user_id: user?.id,\n current_section: activeSection,\n error_message: errorMessage,\n error_status: err.response?.status\n });\n\n alert(`Error: ${errorMessage}`);\n } finally {\n setRefreshing(false);\n }\n };\n\n // Poll for audit updates when audit is running\n useEffect(() => {\n let pollInterval;\n\n if (auditRunning) {\n pollInterval = setInterval(async () => {\n try {\n const projectResponse = await axios.get(`/api/projects/${projectId}`);\n const project = projectResponse.data;\n\n const isStillRunning = project?.generating_audit || project?.data_collection_running;\n setAuditStep(project?.audit_step || null);\n setProjectData(project);\n\n // Update audit history if available\n if (project?.audit_results && project.audit_results.length > 0) {\n setAuditHistory(project.audit_results);\n }\n\n if (!isStillRunning) {\n // Audit completed\n setAuditRunning(false);\n\n // Track audit completion\n trackEvent('Audit Generation Completed', {\n project_id: projectId,\n user_id: user?.id\n });\n\n // Navigate to the latest (newly completed) audit overview\n if (project?.audit_results && project.audit_results.length > 0) {\n const latestAuditId = project.audit_results[0].id;\n navigate(`/projects/${projectId}/audit/${latestAuditId}`);\n } else {\n // Fallback: just refresh current data\n fetchDashboardData(urlAuditId, true);\n }\n }\n } catch (err) {\n console.error('Error polling audit status:', err);\n }\n }, 10000); // Poll every 10 seconds\n }\n\n return () => {\n if (pollInterval) {\n clearInterval(pollInterval);\n }\n };\n }, [auditRunning, projectId]);\n\n const handleAuditSelect = (auditId) => {\n // Compare as strings to handle URL param (string) vs API response (number)\n if (String(auditId) === String(selectedAuditId)) return; // Don't refetch if same audit\n\n // Find the selected audit for additional context\n const selectedAudit = auditHistory.find(a => String(a.id) === String(auditId));\n const currentAudit = auditHistory.find(a => String(a.id) === String(selectedAuditId));\n\n trackEvent('Audit History Selected', {\n project_id: projectId,\n from_audit_id: selectedAuditId,\n to_audit_id: auditId,\n user_id: user?.id,\n is_latest_audit: auditHistory.length > 0 && String(auditId) === String(auditHistory[0].id),\n audit_date: selectedAudit?.created_at,\n from_audit_date: currentAudit?.created_at,\n total_audits_available: auditHistory.length\n });\n\n // Navigate to the URL with the audit ID\n const currentCategory = activeSection === 'full-analysis' ? '' : `/${activeSection}`;\n navigate(`/projects/${projectId}/audit/${auditId}${currentCategory}`);\n };\n\n const formatAuditDate = (dateString) => {\n const date = new Date(dateString);\n return date.toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n year: 'numeric',\n hour: 'numeric',\n minute: '2-digit'\n });\n };\n\n const getIconForSection = (sectionKey) => {\n const iconMap = {\n visibility: Eye,\n competitor: Users,\n sentiment: Heart,\n citation: Quote,\n content_gap: Search,\n 'content-gap': Search,\n on_page: FileText,\n onpage: FileText,\n technical: Settings\n };\n return iconMap[sectionKey] || BarChart3;\n };\n\n const handleSectionChange = (itemId, path) => {\n const fromSection = activeSection;\n const toSection = itemId;\n const sectionInfo = sidebarSections\n .flatMap(s => s.items)\n .find(item => item.id === itemId);\n\n // Track section navigation\n trackEvent('Audit Section Navigation', {\n project_id: projectId,\n from_section_id: fromSection,\n to_section_id: toSection,\n to_section_title: sectionInfo?.title || toSection,\n user_id: user?.id,\n navigation_method: 'sidebar_click'\n });\n\n navigate(path);\n };\n\n const handleGoToProject = () => {\n trackEvent('Audit Go To Project Clicked', {\n project_id: projectId,\n user_id: user?.id,\n current_section: activeSection\n });\n\n navigate(`/projects/${projectId}`);\n };\n\n const handleViewAnalysisClick = (analysisKey) => {\n console.log('=== handleViewAnalysisClick called ===');\n console.log('analysisKey:', analysisKey);\n console.log('projectId:', projectId);\n console.log('sidebarSections:', sidebarSections);\n\n const item = sidebarSections.flatMap(s => s.items).find(item => item.id === analysisKey);\n\n console.log('Found item:', item);\n console.log('All sidebar items:', sidebarSections.flatMap(s => s.items));\n\n if (item) {\n console.log('Item found - attempting navigation');\n console.log('Navigation path:', item.path);\n console.log('Item title:', item.title);\n\n trackEvent('Audit Detailed Analysis Clicked', {\n project_id: projectId,\n analysis_type: analysisKey,\n analysis_title: item.title,\n user_id: user?.id,\n source_section: 'full_analysis_overview',\n items_count: dashboardData?.detailed_insights?.[analysisKey]?.items_count\n });\n\n console.log('About to call navigate with path:', item.path);\n navigate(item.path);\n console.log('Navigate called successfully');\n } else {\n console.log('ERROR: No item found for analysisKey:', analysisKey);\n console.log('Available analysisKeys:', sidebarSections.flatMap(s => s.items).map(item => item.id));\n }\n };\n\n const renderAuditInProgress = () => {\n const currentStep = auditStep?.current || 1;\n const totalSteps = auditStep?.total || 7;\n const progressPercentage = (currentStep / totalSteps) * 100;\n\n const steps = [\n { name: 'Initializing', description: 'Setting up audit parameters' },\n { name: 'Crawling Website', description: 'Analyzing your website pages' },\n { name: 'Visibility Analysis', description: 'Checking AI visibility metrics' },\n { name: 'Competitor Analysis', description: 'Analyzing competitor presence' },\n { name: 'Sentiment Analysis', description: 'Evaluating brand sentiment' },\n { name: 'Citation Analysis', description: 'Tracking citations and references' },\n { name: 'Finalizing', description: 'Generating insights and opportunities' }\n ];\n\n return (\n
\n
\n {/* Header */}\n
\n
\n \n
\n

\n Analysis in Progress\n

\n

\n Step {currentStep} of {totalSteps} - {steps[currentStep - 1]?.name || 'Processing'}\n

\n
\n\n {/* Progress Bar */}\n
\n
\n Progress\n {Math.round(progressPercentage)}%\n
\n
\n \n
\n
\n\n {/* Steps List */}\n
\n

Analysis Steps

\n
\n {steps.map((step, index) => {\n const stepNumber = index + 1;\n const isComplete = stepNumber < currentStep;\n const isCurrent = stepNumber === currentStep;\n const isPending = stepNumber > currentStep;\n\n return (\n \n
\n {isComplete ? (\n \n ) : isCurrent ? (\n
\n ) : (\n {stepNumber}\n )}\n
\n
\n
\n {step.name}\n
\n
\n {step.description}\n
\n
\n
\n );\n })}\n
\n
\n\n {/* Info Message */}\n
\n

This process typically takes 5-10 minutes. You can leave this page and come back later.

\n
\n
\n
\n );\n };\n\n const renderFullAnalysis = () => {\n if (!dashboardData) return null;\n\n const { project_info, analysis_overview, detailed_insights, key_findings } = dashboardData;\n\n // Check if we have a \"no pages found\" scenario\n const noPagesFound = checkForNoPagesScenario(dashboardData);\n\n // Check if viewing an older audit (not the latest)\n const isViewingOlderAudit = auditHistory.length > 0 && selectedAuditId && String(selectedAuditId) !== String(auditHistory[0]?.id);\n const selectedAudit = auditHistory.find(a => String(a.id) === String(selectedAuditId));\n\n return (\n
\n {/* Fixed Header Section */}\n
\n {/* Audit Running Banner */}\n {auditRunning && (\n
\n
\n
\n \n New audit in progress: Step {auditStep?.current || 1} of {auditStep?.total || 7}\n \n
\n
\n )}\n\n
\n
\n
\n
\n

Audit Results

\n \n {noPagesFound ? 'Needs Attention' : 'Completed'}\n \n
\n

GEO Analysis Results

\n
\n
\n
\n \n \n {refreshing ? 'Refreshing...' : 'Refresh Audit'}\n \n {auditRunning && !refreshing && (\n
\n An audit is already in progress\n
\n
\n )}\n
\n \n Go to Project\n \n
\n
\n\n {/* Info Boxes Row with Real Data */}\n
\n
\n
\n \n Client Domain\n
\n

{project_info?.client_domain || 'N/A'}

\n
\n
\n
\n \n Analysis Date\n
\n

{project_info?.analysis_date || 'N/A'}

\n
\n
\n
\n \n Keywords Provided\n
\n

{project_info?.keywords_provided || 0} items

\n
\n
\n
\n \n Competitors\n
\n

{project_info?.competitors || 0} analyzed

\n
\n
\n
\n \n AI Prompts\n
\n

{project_info?.ai_prompts || 0} topics

\n
\n
\n
\n
\n\n {/* Scrollable Content Area */}\n
\n {/* Show \"No Pages Found\" Warning if detected */}\n {noPagesFound && (\n
\n
\n
\n \n
\n

Website Analysis Incomplete

\n

\n We were unable to analyze your website pages due to accessibility issues. Some analysis categories may have limited or no data.\n

\n
\n

Possible causes:

\n
    \n
  • \u2022 Cloudflare or another bot-protection tool is blocking our crawler (most common)
  • \n
  • \u2022 Website sitemap is missing or inaccessible
  • \n
  • \u2022 Pages are blocked by robots.txt or authentication
  • \n
  • \u2022 Domain configuration or DNS issues
  • \n
  • \u2022 Server errors preventing page crawling
  • \n
\n

\n Next steps: See{' '}\n \n When Visto Can't Crawl Your Site\n {' '}\n for the fix \u2014 including the exact IPs and user agent your web team should whitelist \u2014 then re-run the audit.\n

\n
\n
\n
\n
\n
\n )}\n\n {/* Analysis Overview */}\n
\n

Analysis Overview

\n

\n {noPagesFound ? 'Partial insights from your GEO analysis (limited due to page access issues)' : 'Key insights from your GEO analysis'}\n

\n\n
\n
\n
GEO Score
\n
\n {noPagesFound ? 'N/A' : (analysis_overview?.geo_score || '0%')}\n
\n
\n {noPagesFound ? 'Limited data' : (analysis_overview?.geo_score_comparison || 'N/A')}\n
\n
\n
\n
AI Readiness
\n
\n {noPagesFound ? 'N/A' : (analysis_overview?.ai_readiness || '0%')}\n
\n
\n {noPagesFound ? 'Unable to assess' : (analysis_overview?.ai_readiness_status || 'N/A')}\n
\n
\n
\n
Competitor Gap
\n
{analysis_overview?.competitor_gap || '0%'}
\n
{analysis_overview?.competitor_gap_status || 'N/A'}
\n
\n
\n
Est. Total Impact
\n
{analysis_overview?.estimated_impact || 'Low'}
\n
\n
\n
Total Opportunities
\n
{analysis_overview?.total_opportunities || 0}
\n
\n
\n
Critical Issues
\n
{analysis_overview?.critical_issues || 0}
\n
\n
\n
\n\n {/* Detailed Insights */}\n
\n

Detailed Insights

\n

Dive deeper into specific areas of your GEO analysis

\n\n
\n {detailed_insights && Object.entries(detailed_insights).map(([key, insight]) => {\n const IconComponent = getIconForSection(key);\n const isAffectedByNoPages = noPagesFound && (key === 'onpage' || key === 'technical');\n\n return (\n
\n
\n
\n \n
\n

{insight.title}

\n {isAffectedByNoPages && (\n \n )}\n
\n

{insight.description}

\n

\n {isAffectedByNoPages ? 'Analysis incomplete' : insight.score}\n

\n
\n \n {isAffectedByNoPages ? 'Limited data' : `${insight.items_count} items`}\n \n handleViewAnalysisClick(key)}\n className={`px-3 py-2 text-sm rounded ${\n isAffectedByNoPages\n ? 'bg-amber-100 text-amber-700 border border-amber-300'\n : 'bg-purple-50 text-purple-700'\n }`}\n style={!isAffectedByNoPages ? {\n backgroundColor: '#EDEDFC',\n color: '#4F46E5',\n boxShadow: '0 2px 0 0 rgba(0, 0, 0, 0.04)'\n } : {}}\n >\n {isAffectedByNoPages ? 'View Details' : 'View Analysis'}\n \n
\n
\n );\n })}\n
\n
\n\n {/* Key Findings */}\n
\n

Key Findings

\n

The insights that require your immediate attention

\n\n
\n {/* Add a special finding for no pages scenario */}\n {noPagesFound && (\n
\n
\n

Website Accessibility Issue

\n \n Critical Priority\n \n
\n

\n Your website pages could not be analyzed due to accessibility issues. This limits our ability to provide comprehensive optimization recommendations.\n

\n
\n )}\n\n {key_findings && key_findings.length > 0 ? (\n key_findings.map((finding, index) => (\n
\n
\n

{finding.title}

\n \n {finding.priority}\n \n
\n {finding.description && (\n

\n {finding.description}\n

\n )}\n
\n ))\n ) : (\n
\n {noPagesFound\n ? 'Limited findings available due to website accessibility issues. Please resolve the page access problems for complete analysis.'\n : 'No key findings available yet. The analysis may still be in progress.'\n }\n
\n )}\n
\n
\n
\n
\n );\n };\n\n const renderContent = () => {\n if (loading) {\n return (\n
\n
\n
\n
\n
\n
\n
\n );\n }\n\n if (error && !auditRunning) {\n return (\n
\n
\n

Error Loading Dashboard

\n

{error}

\n fetchDashboardData(null, true)}\n className=\"mt-4 bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md text-sm\"\n >\n Try Again\n \n
\n
\n );\n }\n\n // Show audit in progress if running and on full-analysis view\n if (auditRunning && activeSection === 'full-analysis' && !dashboardData) {\n return renderAuditInProgress();\n }\n\n\n // Debug: Log the active section to see what's being passed\n console.log('Active section:', activeSection);\n\n switch (activeSection) {\n case 'full-analysis':\n return renderFullAnalysis();\n case 'visibility':\n return ;\n case 'competitor':\n return ;\n case 'sentiment':\n return ;\n case 'citation':\n return ;\n case 'onpage':\n return ;\n case 'content-gap':\n return ;\n case 'technical':\n return ;\n default:\n return (\n
\n
\n

\n {sidebarSections.flatMap(s => s.items).find(item => item.id === activeSection)?.title || 'Unknown Section'}\n

\n

This section is coming soon...

\n

Debug: activeSection = \"{activeSection}\"

\n
\n
\n );\n }\n };\n\n // Show full page loading state\n if (loading) {\n return (\n
\n
\n
\n
\n
\n );\n }\n\n return (\n
\n {/* Left Sidebar */}\n \n\n {/* Main Content */}\n
\n {renderContent()}\n
\n\n {/* Audit Limit Modal */}\n setShowAuditLimitModal(false)}\n onUpgrade={() => {\n setShowAuditLimitModal(false);\n setShowUnlockModal(true);\n }}\n starterAuditInfo={starterAuditInfo}\n trialInfo={trialInfo}\n projectId={projectId}\n user={user}\n />\n\n {/* Unlock Modal */}\n setShowUnlockModal(false)}\n projectId={projectId}\n user={user}\n />\n
\n );\n};\n\nexport default AuditResults;", "import React, { useState, useEffect } from 'react';\nimport axios from '../AxiosConfig';\nimport AuditCategoryAnalysis from './AuditCategoryAnalysis';\nimport PrimaryScaleGraph from './PrimaryScaleGraph';\nimport QuadBuckets from './QuadBuckets';\n\nconst VisibilityAnalysis = ({ projectId, auditResultId }) => {\n const [data, setData] = useState(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n\n const analysisDescription = \"The platform identified topics relevant to your client and discovered unbranded discovery prompts in your space. For each original prompt, we generated multiple wording variations and collected response data points to track brand mentions. We computed a visibility score representing the percentage of prompts where your brand was mentioned, both globally across all prompts and within each specific topic area.\";\n\n // Fetch visibility analysis data\n useEffect(() => {\n const fetchVisibilityData = async () => {\n try {\n setLoading(true);\n const url = auditResultId\n ? `/api/projects/${projectId}/audit/category/0?audit_result_id=${auditResultId}`\n : `/api/projects/${projectId}/audit/category/0`; // 0 = low_visibility\n const response = await axios.get(url);\n setData(response.data);\n setError(null);\n } catch (err) {\n console.error('Error fetching visibility analysis data:', err);\n setError('Failed to load visibility analysis data. Please try again.');\n } finally {\n setLoading(false);\n }\n };\n\n if (projectId) {\n fetchVisibilityData();\n }\n }, [projectId, auditResultId]);\n\n // Show loading state\n if (loading) {\n return (\n \n
Loading visibility analysis...
\n
\n }\n opportunities={[]}\n />\n );\n }\n\n // Show error state\n if (error) {\n return (\n \n

Error Loading Analysis

\n

{error}

\n \n }\n opportunities={[]}\n />\n );\n }\n\n // Show message if no data available\n if (!data || data.status !== 'completed') {\n return (\n \n

Analysis In Progress

\n

Visibility analysis is still being processed. Please check back later.

\n \n }\n opportunities={[]}\n />\n );\n }\n\n const analysisData = data.analysis_data || {};\n const opportunities = data.opportunities || [];\n\n // Extract data for components\n const globalVisibilityScore = analysisData.global_visibility_score || 0;\n const totalPromptsAnalyzed = analysisData.total_prompts_analyzed || 0;\n const brandMentionsFound = analysisData.brand_mentions_found || 0;\n const topicScores = analysisData.topic_scores || [];\n const topicAreasCount = topicScores.length;\n\n // Custom section with real data\n const customSection = (\n
\n {/* Global Visibility Score */}\n
\n

Global Visibility Score

\n \n
\n\n {/* Topic Performance Distribution */}\n
\n

Topic Performance Distribution

\n
\n \n
\n

\n Topics are categorized by their visibility scores: Poor (0-24%), Needs Work (25-49%), Good (50-74%), Excellent (75-100%)\n

\n
\n\n {/* Summary Stats */}\n
\n
\n
{totalPromptsAnalyzed}
\n
Total Prompts Analyzed
\n
\n
\n
{brandMentionsFound}
\n
Brand Mentions Found
\n
\n
\n
{topicAreasCount}
\n
Topic Areas Covered
\n
\n
\n
\n );\n\n return (\n \n );\n};\n\nexport default VisibilityAnalysis;", "import React from 'react';\nimport { useParams, useNavigate } from 'react-router-dom';\n\nconst AuditCategoryAnalysis = ({\n heading,\n analysisDescription,\n customSection,\n opportunities = []\n }) => {\n const { projectId } = useParams();\n const navigate = useNavigate();\n\n const handleGoToProject = () => {\n navigate(`/projects/${projectId}`);\n };\n\n const getPriorityColor = (priority) => {\n switch (priority?.toLowerCase()) {\n case 'critical':\n return '#FF6694';\n case 'high':\n return '#FFA567';\n case 'medium':\n return '#E6C200';\n case 'low':\n return '#6B7280';\n default:\n return '#6B7280';\n }\n };\n\n return (\n
\n {/* Main Heading with Go to Project Button */}\n
\n
\n

{heading}

\n
\n \n Go to Project\n \n
\n\n {/* Section 1: What Visto Platform Analyzed */}\n
\n

\n What Visto Platform Analyzed\n

\n

\n {analysisDescription}\n

\n
\n\n {/* Section 2: Custom Section */}\n {customSection && (\n
\n {customSection}\n
\n )}\n\n {/* Section 3: Gaps & Opportunities */}\n
\n

\n Gaps & Opportunities\n

\n\n {opportunities.length > 0 ? (\n
\n {opportunities.map((opportunity, index) => (\n \n
\n

\n {opportunity.title}\n

\n \n {opportunity.priority || 'Medium'}\n \n
\n

\n {opportunity.description}\n

\n
\n ))}\n
\n ) : (\n
\n

No opportunities identified for this category.

\n
\n )}\n
\n \n );\n};\n\nexport default AuditCategoryAnalysis;", "import React from 'react';\n\nconst PrimaryScaleGraph = ({ title, subtitle, score }) => {\n const getScoreDetails = (score) => {\n if (score < 25) {\n return { label: 'Poor', textColor: '#FF6694', activeQuarter: 0 };\n } else if (score < 50) {\n return { label: 'Needs Work', textColor: '#FFA567', activeQuarter: 1 };\n } else if (score < 75) {\n return { label: 'Good', textColor: '#E6C200', activeQuarter: 2 };\n } else {\n return { label: 'Excellent', textColor: '#007A55', activeQuarter: 3 };\n }\n };\n\n const scoreDetails = getScoreDetails(score);\n\n const quarters = [\n {\n label: 'Poor',\n activeColor: '#FF6694',\n lightColor: '#FF669440'\n },\n {\n label: 'Needs Work',\n activeColor: '#FFA567',\n lightColor: '#FFA56740'\n },\n {\n label: 'Good',\n activeColor: '#FFDA60',\n lightColor: '#FFDA6040'\n },\n {\n label: 'Excellent',\n activeColor: '#30E38F',\n lightColor: '#30E38F40'\n }\n ];\n\n // Calculate position of the score indicator (0-100% across the bar)\n const indicatorPosition = `${score}%`;\n\n return (\n
\n {/* Title and Subtitle */}\n
\n

{title}

\n

{subtitle}

\n
\n\n {/* Score and Status Pill */}\n
\n {score}\n \n {scoreDetails.label}\n \n
\n\n {/* Progress Bar */}\n
\n
\n {quarters.map((quarter, index) => (\n \n ))}\n\n {/* Score Indicator */}\n \n
\n
\n\n {/* Labels */}\n
\n {quarters.map((quarter, index) => (\n
\n {quarter.label}\n
\n ))}\n
\n
\n );\n};\n\nexport default PrimaryScaleGraph;", "import React from 'react';\n\nconst QuadBuckets = ({ topics = [] }) => {\n const getQuadrant = (score) => {\n if (score < 25) return 'poor';\n if (score < 50) return 'needsWork';\n if (score < 75) return 'good';\n return 'excellent';\n };\n\n const groupedTopics = topics.reduce((acc, topic) => {\n const quadrant = getQuadrant(topic.score);\n if (!acc[quadrant]) acc[quadrant] = [];\n acc[quadrant].push(topic);\n return acc;\n }, {});\n\n const quadrants = [\n {\n key: 'poor',\n label: 'Poor (0-24)',\n color: 'bg-red-100 border-red-300',\n textColor: 'text-red-800',\n position: 'top-left'\n },\n {\n key: 'needsWork',\n label: 'Needs Work (25-49)',\n color: 'bg-orange-100 border-orange-300',\n textColor: 'text-orange-800',\n position: 'top-right'\n },\n {\n key: 'good',\n label: 'Good (50-74)',\n color: 'bg-yellow-100 border-yellow-300',\n textColor: 'text-yellow-800',\n position: 'bottom-left'\n },\n {\n key: 'excellent',\n label: 'Excellent (75-100)',\n color: 'bg-green-100 border-green-300',\n textColor: 'text-green-800',\n position: 'bottom-right'\n }\n ];\n\n return (\n
\n
\n {quadrants.map((quadrant) => (\n \n {/* Quadrant Header */}\n
\n

\n {quadrant.label}\n

\n
\n {groupedTopics[quadrant.key]?.length || 0} topics\n
\n
\n\n {/* Topics Grid */}\n
\n
\n {groupedTopics[quadrant.key]?.map((topic, index) => (\n \n
\n \n {topic.name}\n \n \n {topic.score}\n \n
\n
\n )) || (\n
\n No topics in this range\n
\n )}\n
\n
\n
\n ))}\n \n\n {/* Summary Stats */}\n
\n {quadrants.map((quadrant) => (\n
\n
\n {groupedTopics[quadrant.key]?.length || 0}\n
\n
\n
\n {quadrant.key === 'needsWork' ? 'Needs Work' : quadrant.label.split(' ')[0]} Topics\n
\n
\n
\n ))}\n
\n \n );\n};\n\nexport default QuadBuckets;", "import React, { useState, useEffect } from 'react';\nimport axios from '../AxiosConfig';\nimport AuditCategoryAnalysis from './AuditCategoryAnalysis';\nimport PieChart from './PieChart';\nimport ScrollableTable from './ScrollableTable';\n\nconst CompetitorAnalysis = ({ projectId, auditResultId }) => {\n const [data, setData] = useState(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n\n const analysisDescription = \"The platform analyzed response data across all prompts and variations to detect when competitor brands were mentioned. We tracked brand mentions, computed share of voice metrics for both your client and competitors globally and by topic, and identified competitive strengths and weaknesses across different market segments and use cases.\";\n\n // Fetch competitor analysis data\n useEffect(() => {\n const fetchCompetitorData = async () => {\n try {\n setLoading(true);\n const url = auditResultId\n ? `/api/projects/${projectId}/audit/category/1?audit_result_id=${auditResultId}`\n : `/api/projects/${projectId}/audit/category/1`; // 1 = competitor\n const response = await axios.get(url);\n setData(response.data);\n setError(null);\n } catch (err) {\n console.error('Error fetching competitor analysis data:', err);\n setError('Failed to load competitor analysis data. Please try again.');\n } finally {\n setLoading(false);\n }\n };\n\n if (projectId) {\n fetchCompetitorData();\n }\n }, [projectId, auditResultId]);\n\n // Show loading state\n if (loading) {\n return (\n \n
Loading competitor analysis...
\n \n }\n opportunities={[]}\n />\n );\n }\n\n // Show error state\n if (error) {\n return (\n \n

Error Loading Analysis

\n

{error}

\n \n }\n opportunities={[]}\n />\n );\n }\n\n // Show message if no data available\n if (!data || data.status !== 'completed') {\n return (\n \n

Analysis In Progress

\n

Competitor analysis is still being processed. Please check back later.

\n \n }\n opportunities={[]}\n />\n );\n }\n\n const analysisData = data.analysis_data || {};\n const opportunities = data.opportunities || [];\n\n // Extract data for components\n const shareOfVoiceBreakdown = analysisData.share_of_voice_breakdown || [];\n const topicBreakdown = analysisData.topic_breakdown || [];\n const customerShareOfVoice = analysisData.customer_share_of_voice || 0;\n const competitorGap = analysisData.competitor_gap || 0;\n\n // Transform share of voice data for PieChart\n const pieChartData = shareOfVoiceBreakdown.map((company, index) => ({\n id: company.company_id || index,\n name: company.company_name || company.name,\n percentage: company.share_of_voice_percentage || 0,\n mentions: company.mentions || 0,\n isCustomer: company.is_customer || false\n }));\n\n // Transform topic breakdown data for ScrollableTable\n const topics = topicBreakdown.map(topic => ({\n id: topic.topic_id,\n name: topic.topic_name\n }));\n\n const companies = shareOfVoiceBreakdown.map((company, index) => ({\n id: company.company_id || index,\n name: company.company_name || company.name\n }));\n\n // Create table data structure: { topicId: { companyId: percentage } }\n const tableData = {};\n topicBreakdown.forEach(topic => {\n tableData[topic.topic_id] = {};\n\n // Customer percentage\n if (topic.customer_percentage !== undefined) {\n const customerCompany = shareOfVoiceBreakdown.find(c => c.is_customer);\n if (customerCompany) {\n tableData[topic.topic_id][customerCompany.company_id] = topic.customer_percentage;\n }\n }\n\n // Competitor percentages\n if (topic.competitor_percentages) {\n topic.competitor_percentages.forEach(comp => {\n tableData[topic.topic_id][comp.company_id] = comp.percentage;\n });\n }\n });\n\n // Custom section with competitor analysis visualizations\n const customSection = (\n
\n {/* Share of Voice Pie Chart */}\n
\n

Share of Voice Distribution

\n \n
\n\n {/* Topic by Company Performance Table */}\n
\n

Share of Voice by Topic

\n \n

\n This table shows the percentage share of voice for each company across different topics.\n Higher percentages indicate stronger visibility in AI responses for that topic area.\n

\n
\n
\n );\n\n return (\n \n );\n};\n\nexport default CompetitorAnalysis;", "import React from 'react';\nimport { PieChart as RechartsPieChart, Pie, Cell, Tooltip, ResponsiveContainer } from 'recharts';\n\n// Default color scheme - same as the example component\nconst DEFAULT_COLORS = [\n '#1E88E5', // Blue (for customer/primary)\n '#FF8C00', // Dark orange\n '#00A878', // Green\n '#9C27B0', // Purple\n '#E53935', // Red\n '#00ACC1', // Cyan\n '#FF7043', // Deep orange/coral\n '#5E35B1', // Deep purple\n '#43A047', // Forest green\n '#FB8C00', // Amber/orange\n '#6D4C41', // Brown\n '#C2185B', // Pink\n '#039BE5', // Light blue\n '#8D6E63', // Brown grey\n '#7CB342' // Lime green\n];\n\nconst PieChart = ({\n companies = [],\n showLegend = true,\n showTooltip = true,\n outerRadius = 120,\n colors = DEFAULT_COLORS,\n height = 400\n }) => {\n // Transform companies data and assign colors\n const chartData = companies.map((company, index) => ({\n ...company,\n color: company.color || colors[index % colors.length]\n }));\n\n // Sort by percentage descending for better visual hierarchy\n chartData.sort((a, b) => b.percentage - a.percentage);\n\n if (!companies || companies.length === 0) {\n return (\n
\n

No data available

\n
\n );\n }\n\n return (\n
\n
\n {/* Pie Chart */}\n
\n \n \n `${percentage}%`}\n isAnimationActive={false}\n >\n {chartData.map((entry, index) => (\n \n ))}\n \n {showTooltip && (\n {\n const mentions = props.payload.mentions || 0;\n return [`${value}% (${mentions} mentions)`, name];\n }}\n contentStyle={{\n backgroundColor: 'white',\n borderRadius: '5px',\n padding: '10px',\n border: '1px solid #ccc'\n }}\n />\n )}\n \n \n
\n\n {/* Legend */}\n {showLegend && (\n
\n

Distribution

\n
\n {chartData.map((company, index) => (\n
\n
\n \n {company.name}\n {company.isCustomer && (\n \n You\n \n )}\n
\n
\n \n {company.percentage}%\n {company.mentions !== undefined && ` (${company.mentions})`}\n \n
\n
\n ))}\n
\n
\n )}\n
\n
\n );\n};\n\nexport default PieChart;", "import React from 'react';\n\nconst ScrollableTable = ({ data, topics, companies }) => {\n const getPercentageColor = (percentage) => {\n if (percentage < 25) {\n return 'bg-red-100 text-red-800 border-red-200';\n } else if (percentage < 50) {\n return 'bg-orange-100 text-orange-800 border-orange-200';\n } else if (percentage < 75) {\n return 'bg-yellow-100 text-yellow-800 border-yellow-200';\n } else {\n return 'bg-green-100 text-green-800 border-green-200';\n }\n };\n\n return (\n
\n
\n \n \n \n \n {companies.map((company) => (\n \n {company.name}\n \n ))}\n \n \n \n {topics.map((topic, topicIndex) => (\n \n \n {companies.map((company) => {\n const percentage = data[topic.id]?.[company.id] || 0;\n return (\n \n \n {percentage}%\n \n \n );\n })}\n \n ))}\n \n
\n Topic\n
\n {topic.name}\n
\n
\n
\n );\n};\n\nexport default ScrollableTable;", "import React, { useState, useEffect } from 'react';\nimport axios from '../AxiosConfig';\nimport AuditCategoryAnalysis from './AuditCategoryAnalysis';\nimport PrimaryScaleGraph from './PrimaryScaleGraph';\nimport QuadBuckets from './QuadBuckets';\nimport SentimentThemes from './SentimentThemes';\n\nconst SentimentAnalysis = ({ projectId, auditResultId }) => {\n const [data, setData] = useState(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n\n const analysisDescription = \"The platform analyzed the text content of AI responses across all prompts using advanced natural language processing algorithms to detect sentiment about your brand and competitors. We evaluated emotional tone, context, and brand perception patterns to understand how AI systems present your brand compared to competitors across different topics and use cases.\";\n\n // Fetch sentiment analysis data\n useEffect(() => {\n const fetchSentimentData = async () => {\n try {\n setLoading(true);\n const url = auditResultId\n ? `/api/projects/${projectId}/audit/category/2?audit_result_id=${auditResultId}`\n : `/api/projects/${projectId}/audit/category/2`; // 2 = sentiment\n const response = await axios.get(url);\n setData(response.data);\n setError(null);\n } catch (err) {\n console.error('Error fetching sentiment analysis data:', err);\n setError('Failed to load sentiment analysis data. Please try again.');\n } finally {\n setLoading(false);\n }\n };\n\n if (projectId) {\n fetchSentimentData();\n }\n }, [projectId, auditResultId]);\n\n // Show loading state\n if (loading) {\n return (\n \n
Loading sentiment analysis...
\n \n }\n opportunities={[]}\n />\n );\n }\n\n // Show error state\n if (error) {\n return (\n \n

Error Loading Analysis

\n

{error}

\n \n }\n opportunities={[]}\n />\n );\n }\n\n // Show message if no data available\n if (!data || data.status !== 'completed') {\n return (\n \n

Analysis In Progress

\n

Sentiment analysis is still being processed. Please check back later.

\n \n }\n opportunities={[]}\n />\n );\n }\n\n const analysisData = data.analysis_data || {};\n const opportunities = data.opportunities || [];\n\n // Extract data for components\n const globalSentimentScore = analysisData.global_sentiment_score || 0;\n const positiveMentions = analysisData.positive_mentions || 0;\n const negativeMentions = analysisData.negative_mentions || 0;\n const neutralMentions = analysisData.neutral_mentions || 0;\n const topicSentimentBreakdown = analysisData.topic_sentiment_breakdown || [];\n const themes = analysisData.themes || { strengths: [], weaknesses: [] };\n\n // Convert sentiment score from -1 to 1 scale to 0-100 scale for PrimaryScaleGraph\n const sentimentScoreForGraph = Math.round(globalSentimentScore * 100);\n\n// Also update the topic scores conversion\n const topicScores = topicSentimentBreakdown.map(topic => ({\n id: topic.topic_id,\n name: topic.topic_name,\n score: Math.round(topic.sentiment_score * 100) // Remove the -1 to 1 conversion\n }));\n\n // Custom section with sentiment analysis visualizations\n const customSection = (\n
\n {/* Global Sentiment Score */}\n
\n

Overall Sentiment Score

\n \n

\n Sentiment score ranges from 0-100, where higher scores indicate more positive brand perception in AI responses.\n

\n
\n\n {/* Topic Sentiment Distribution */}\n
\n

Sentiment by Topic

\n
\n \n
\n

\n Topics are categorized by sentiment scores: Poor (0-24), Needs Work (25-49), Good (50-74), Excellent (75-100)\n

\n
\n\n {/* Strengths / weaknesses, each traceable to its source responses */}\n \n
\n );\n\n return (\n \n );\n};\n\nexport default SentimentAnalysis;", "// Strengths and weaknesses from the run-level sentiment analysis, each\n// traceable to the responses it came from. Clicking a theme fetches its\n// linked responses (GET /sentiment_analysis/themes/:id/responses) and shows\n// them grouped by prompt, so \"insufficient API details\" can be read against\n// the exact ChatGPT answer that said it. Themes with no linked responses\n// never reach this component (filtered server-side).\nimport React, { useState } from 'react';\nimport axios from '../AxiosConfig';\nimport { ChevronDown, ChevronRight, ThumbsUp, AlertTriangle } from 'lucide-react';\n\nconst PLATFORM_LABELS = {\n chatgpt: 'ChatGPT',\n claude: 'Claude',\n perplexity: 'Perplexity',\n google_ai_overview: 'Google AI Overview',\n};\n\nconst ThemeRow = ({ theme, tone, projectId, auditResultId }) => {\n const [open, setOpen] = useState(false);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState(null);\n const [responses, setResponses] = useState(null);\n const [expanded, setExpanded] = useState({}); // response id -> bool\n\n const toggle = async () => {\n const next = !open;\n setOpen(next);\n if (!next || responses) return;\n setLoading(true);\n setError(null);\n try {\n const params = auditResultId ? { audit_result_id: auditResultId } : {};\n const res = await axios.get(`/api/projects/${projectId}/sentiment_analysis/themes/${theme.id}/responses`, { params });\n setResponses(res.data.responses || []);\n } catch (err) {\n setError(err.response?.data?.error || 'Failed to load the responses for this theme.');\n } finally {\n setLoading(false);\n }\n };\n\n // Group by prompt so one question with three engine answers reads as one block\n const byPrompt = (responses || []).reduce((acc, r) => {\n const key = r.prompt_id || r.prompt_text;\n if (!acc[key]) acc[key] = { prompt_text: r.prompt_text, responses: [] };\n acc[key].responses.push(r);\n return acc;\n }, {});\n\n const accent = tone === 'weakness'\n ? 'border-red-200 hover:bg-red-50'\n : 'border-green-200 hover:bg-green-50';\n\n return (\n
  • \n \n \n {open ? : }\n {theme.description}\n \n \n {theme.response_count} {theme.response_count === 1 ? 'response' : 'responses'}\n \n \n\n {open && (\n
    \n {loading &&
    Loading responses\u2026
    }\n {error &&
    {error}
    }\n {responses && Object.values(byPrompt).map((group, gi) => (\n
    \n
    Prompt
    \n
    \u201C{group.prompt_text}\u201D
    \n
    \n {group.responses.map((r) => {\n const isOpen = !!expanded[r.id];\n const text = r.response_text || '';\n const shown = isOpen || text.length <= 600 ? text : text.slice(0, 600) + '\u2026';\n return (\n
    \n
    \n \n {PLATFORM_LABELS[r.platform_name] || r.platform_name || 'AI engine'}\n \n {text.length > 600 && (\n setExpanded({ ...expanded, [r.id]: !isOpen })}\n className=\"text-xs text-indigo-600 hover:text-indigo-800\"\n >\n {isOpen ? 'Show less' : 'Show full response'}\n \n )}\n
    \n
    {shown}
    \n
    \n );\n })}\n
    \n
    \n ))}\n {responses && responses.length === 0 && (\n
    No responses are linked to this theme.
    \n )}\n
    \n )}\n
  • \n );\n};\n\nconst SentimentThemes = ({ themes, projectId, auditResultId }) => {\n const strengths = themes?.strengths || [];\n const weaknesses = themes?.weaknesses || [];\n if (strengths.length === 0 && weaknesses.length === 0) return null;\n\n return (\n
    \n

    What the AI engines say about you

    \n

    \n Themes extracted from the responses that mention your brand. Click any theme to read the prompts and answers it came from.\n

    \n
    \n
    \n
    \n \n

    Strengths

    \n
    \n {strengths.length === 0\n ?

    No strengths were extracted.

    \n :
      {strengths.map((t) => )}
    }\n
    \n
    \n
    \n \n

    Areas to address

    \n
    \n {weaknesses.length === 0\n ?

    No weaknesses were extracted.

    \n :
      {weaknesses.map((t) => )}
    }\n

    \n Weaknesses describe how the engines position you, including what they say you don't do. They are not complaints from users.\n

    \n
    \n
    \n
    \n );\n};\n\nexport default SentimentThemes;\n", "import React, { useState, useEffect } from 'react';\nimport axios from '../AxiosConfig';\nimport AuditCategoryAnalysis from './AuditCategoryAnalysis';\nimport PrimaryScaleGraph from './PrimaryScaleGraph';\n\nconst CitationAnalysis = ({ projectId, auditResultId }) => {\n const [data, setData] = useState(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n\n const analysisDescription = \"For all response data collected across prompts, the platform tracked and catalogued every source cited in AI-generated responses. We aggregated these citations and analyzed them by source type (social media, competitor sites, third-party media, Wikipedia, academic papers, etc.), identifying patterns in what types of sources, content structures, and domain authorities that AI systems prefer when responding to queries in your client's space.\";\n\n // Fetch citation analysis data\n useEffect(() => {\n const fetchCitationData = async () => {\n try {\n setLoading(true);\n const url = auditResultId\n ? `/api/projects/${projectId}/audit/category/3?audit_result_id=${auditResultId}`\n : `/api/projects/${projectId}/audit/category/3`; // 3 = citation\n const response = await axios.get(url);\n setData(response.data);\n setError(null);\n } catch (err) {\n console.error('Error fetching citation analysis data:', err);\n setError('Failed to load citation analysis data. Please try again.');\n } finally {\n setLoading(false);\n }\n };\n\n if (projectId) {\n fetchCitationData();\n }\n }, [projectId, auditResultId]);\n\n // Show loading state\n if (loading) {\n return (\n \n
    Loading citation analysis...
    \n \n }\n opportunities={[]}\n />\n );\n }\n\n // Show error state\n if (error) {\n return (\n \n

    Error Loading Analysis

    \n

    {error}

    \n \n }\n opportunities={[]}\n />\n );\n }\n\n // Show message if no data available\n if (!data || data.status !== 'completed') {\n return (\n \n

    Analysis In Progress

    \n

    Citation analysis is still being processed. Please check back later.

    \n \n }\n opportunities={[]}\n />\n );\n }\n\n const analysisData = data.analysis_data || {};\n const opportunities = data.opportunities || [];\n\n // Extract data for components\n const totalCitations = analysisData.total_citations || 0;\n const clientDomainCitations = analysisData.client_domain_citations || 0;\n const citationPercentage = analysisData.citation_percentage || 0;\n const citationScore = analysisData.client_domain_citation_score || analysisData.citation_percentage || 0;\n const topCitedDomains = analysisData.top_cited_domains || [];\n\n // Custom section with citation analysis visualizations\n const customSection = (\n
    \n {/* Client Citation Metrics */}\n
    \n

    Your Citation Performance

    \n \n
    \n\n {/* Citation Overview */}\n
    \n

    Citation Overview

    \n
    \n
    \n
    {totalCitations}
    \n
    Total Citations Found
    \n
    \n
    \n
    {clientDomainCitations}
    \n
    Your Domain Citations
    \n
    \n
    \n
    \n\n {/* Top Cited Domains */}\n
    \n

    Top Cited Domains

    \n {topCitedDomains.length > 0 ? (\n
    \n
    \n \n \n \n \n \n \n \n \n \n \n {topCitedDomains.map((domain, index) => (\n \n \n \n \n \n \n ))}\n \n
    \n Rank\n \n Domain\n \n Citations\n \n Percentage\n
    \n #{index + 1}\n \n {domain.domain}\n {domain.is_client_domain && (\n \n Your Domain\n \n )}\n \n {domain.citation_count}\n \n {domain.percentage?.toFixed(1)}%\n
    \n
    \n
    \n ) : (\n
    \n

    No citation data available

    \n
    \n )}\n

    \n This table shows which domains are most frequently cited by AI systems when responding to queries in your industry.\n

    \n
    \n\n {/* Citation Analysis Summary */}\n
    \n

    Citation Analysis Insights

    \n
    \n

    \u2022 AI systems cited {totalCitations} total sources across all analyzed responses

    \n

    \u2022 Your domain received {clientDomainCitations} citations ({citationPercentage.toFixed(1)}% citation rate)

    \n

    \u2022 {topCitedDomains.length} unique domains were identified as authoritative sources in your space

    \n {topCitedDomains.length > 0 && (\n

    \u2022 The most cited domain is {topCitedDomains[0]?.domain} with {topCitedDomains[0]?.citation_count} citations

    \n )}\n
    \n
    \n
    \n );\n\n return (\n \n );\n};\n\nexport default CitationAnalysis;", "import React, { useState, useEffect } from 'react';\nimport axios from '../AxiosConfig';\nimport AuditCategoryAnalysis from './AuditCategoryAnalysis';\nimport PrimaryScaleGraph from './PrimaryScaleGraph';\nimport BasicScaleGraph from './BasicScaleGraph';\nimport { AlertTriangle, FileText, Globe } from 'lucide-react';\n\nconst OnPageAnalysis = ({ projectId, auditResultId }) => {\n const [data, setData] = useState(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n\n const analysisDescription = \"The platform conducted a comprehensive audit of each page in your client's sitemap from a Generative Engine Optimization (GEO) AI readability perspective. We analyzed multiple categories including logical flow, entity mapping, claim clarity, schema markup implementation, and information architecture to determine how well AI systems can understand, process, and reference your content when generating responses.\";\n\n // Fetch on-page analysis data\n useEffect(() => {\n const fetchOnPageData = async () => {\n try {\n setLoading(true);\n const url = auditResultId\n ? `/api/projects/${projectId}/audit/category/5?audit_result_id=${auditResultId}`\n : `/api/projects/${projectId}/audit/category/5`; // 5 = on_page\n const response = await axios.get(url);\n setData(response.data);\n setError(null);\n } catch (err) {\n console.error('Error fetching on-page analysis data:', err);\n setError('Failed to load on-page analysis data. Please try again.');\n } finally {\n setLoading(false);\n }\n };\n\n if (projectId) {\n fetchOnPageData();\n }\n }, [projectId, auditResultId]);\n\n // Show loading state\n if (loading) {\n return (\n \n
    Loading on-page analysis...
    \n \n }\n opportunities={[]}\n />\n );\n }\n\n // Show error state\n if (error) {\n return (\n \n

    Error Loading Analysis

    \n

    {error}

    \n \n }\n opportunities={[]}\n />\n );\n }\n\n // Show message if no data available\n if (!data || data.status !== 'completed') {\n return (\n \n

    Analysis In Progress

    \n

    On-page analysis is still being processed. Please check back later.

    \n \n }\n opportunities={[]}\n />\n );\n }\n\n const analysisData = data.analysis_data || {};\n const opportunities = data.opportunities || [];\n\n // Check if this is a \"no pages found\" scenario\n if (analysisData.status === 'no_pages_found' || analysisData.message?.includes('No valid pages were found')) {\n const customSection = (\n
    \n
    \n
    \n \n
    \n

    No Pages Found for Analysis

    \n

    \n We were unable to find any valid pages from your website's sitemap to analyze for on-page optimization.\n

    \n
    \n

    This could be due to:

    \n
      \n
    • \u2022 Website sitemap is not accessible or missing
    • \n
    • \u2022 Sitemap contains no valid URLs
    • \n
    • \u2022 All pages are blocked by robots.txt
    • \n
    • \u2022 Website is password protected or behind authentication
    • \n
    • \u2022 Domain configuration issues
    • \n
    \n
    \n
    \n
    \n
    \n\n
    \n
    \n \n
    \n

    Recommended Next Steps

    \n
      \n
    1. 1. Verify that your website is publicly accessible
    2. \n
    3. 2. Check that your sitemap.xml file exists and is properly formatted
    4. \n
    5. 3. Ensure your robots.txt file isn't blocking all pages
    6. \n
    7. 4. Confirm the domain URL is correct in your project settings
    8. \n
    9. 5. Contact support if the issue persists
    10. \n
    \n
    \n
    \n
    \n\n
    \n
    \n \n

    Domain Information

    \n
    \n
    \n

    Domain: {analysisData.metadata?.customer_company || 'Not specified'}

    \n

    Analysis Date: {analysisData.metadata?.computed_at ? new Date(analysisData.metadata.computed_at).toLocaleDateString() : 'N/A'}

    \n
    \n
    \n
    \n );\n\n return (\n \n );\n }\n\n // Extract data for components (existing logic)\n const averageAiParsingScore = analysisData.average_ai_parsing_score || 0;\n const pagesAnalyzed = analysisData.pages_analyzed || 0;\n const aiReadinessScore = analysisData.ai_readiness_score || 0;\n const pageScores = analysisData.page_scores || [];\n\n // Calculate category averages from page scores\n const categoryAverages = {};\n if (pageScores.length > 0) {\n const categories = ['logical_flow', 'entity_mapping', 'claim_clarity', 'schema_markup', 'information_architecture'];\n\n categories.forEach(category => {\n const validScores = pageScores\n .map(page => page[category])\n .filter(score => score !== undefined && score !== null);\n\n if (validScores.length > 0) {\n categoryAverages[category] = Math.round(validScores.reduce((sum, score) => sum + score, 0) / validScores.length);\n } else {\n categoryAverages[category] = 0;\n }\n });\n }\n\n // Custom section with on-page analysis visualizations\n const customSection = (\n
    \n {/* Overall AI Readiness Score */}\n
    \n

    Overall AI Readiness Score

    \n \n
    \n\n {/* Category Breakdown */}\n
    \n

    Category Analysis

    \n
    \n \n \n \n \n \n
    \n

    \n Each category represents a key factor in how AI systems understand and process your content.\n

    \n
    \n
    \n );\n\n return (\n \n );\n};\n\nexport default OnPageAnalysis;", "import React from 'react';\n\nconst BasicScaleGraph = ({ title, score }) => {\n const getScoreDetails = (score) => {\n if (score < 25) {\n return { label: 'Poor', textColor: '#FF6694' };\n } else if (score < 50) {\n return { label: 'Needs Work', textColor: '#FFA567' };\n } else if (score < 75) {\n return { label: 'Good', textColor: '#E6C200' };\n } else {\n return { label: 'Excellent', textColor: '#007A55' };\n }\n };\n\n const scoreDetails = getScoreDetails(score);\n\n return (\n
    \n \n {title}\n \n\n
    \n \n {scoreDetails.label}\n \n \n {score}\n \n
    \n
    \n );\n};\n\nexport default BasicScaleGraph;", "import React, { useState, useEffect } from 'react';\nimport axios from '../AxiosConfig';\nimport AuditCategoryAnalysis from './AuditCategoryAnalysis';\nimport PrimaryScaleGraph from './PrimaryScaleGraph';\nimport ScrollableTable from './ScrollableTable';\n\nconst ContentGapAnalysis = ({ projectId, auditResultId }) => {\n const [data, setData] = useState(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n\n const analysisDescription = \"The platform analyzed all pages in your client's sitemap and created a comprehensive knowledge graph mapping entities, concepts, and semantic relationships within your content. We performed the same analysis for each competitor and the broader industry to identify content gaps, topic coverage overlaps, and opportunities where competitors have content advantages that your client lacks.\";\n\n // Fetch content gap analysis data\n useEffect(() => {\n const fetchContentGapData = async () => {\n try {\n setLoading(true);\n const url = auditResultId\n ? `/api/projects/${projectId}/audit/category/4?audit_result_id=${auditResultId}`\n : `/api/projects/${projectId}/audit/category/4`; // 4 = content_map\n const response = await axios.get(url);\n setData(response.data);\n setError(null);\n } catch (err) {\n console.error('Error fetching content gap analysis data:', err);\n setError('Failed to load content gap analysis data. Please try again.');\n } finally {\n setLoading(false);\n }\n };\n\n if (projectId) {\n fetchContentGapData();\n }\n }, [projectId, auditResultId]);\n\n // Show loading state\n if (loading) {\n return (\n \n
    Loading content gap analysis...
    \n \n }\n opportunities={[]}\n />\n );\n }\n\n // Show error state\n if (error) {\n return (\n \n

    Error Loading Analysis

    \n

    {error}

    \n \n }\n opportunities={[]}\n />\n );\n }\n\n // Show message if no data available\n if (!data || data.status !== 'completed') {\n return (\n \n

    Analysis In Progress

    \n

    Content gap analysis is still being processed. Please check back later.

    \n \n }\n opportunities={[]}\n />\n );\n }\n\n const analysisData = data.analysis_data || {};\n const opportunities = data.opportunities || [];\n\n // Extract data for components\n const customerOverallScore = analysisData.customer_overall_score || 0;\n const competitorAverageScore = analysisData.competitor_average_score || 0;\n const contentGapPercentage = analysisData.content_gap_percentage || 0;\n const topicContentScores = analysisData.topic_content_scores || [];\n\n // Transform data for ScrollableTable\n const topics = topicContentScores.map(topic => ({\n id: topic.topic_id,\n name: topic.topic_name\n }));\n\n // Create companies array (customer + competitors)\n const companies = [];\n if (topicContentScores.length > 0) {\n // Add customer\n companies.push({\n id: 'customer',\n name: 'Your Company'\n });\n\n // Add competitors from the first topic (assuming all topics have same competitors)\n const firstTopic = topicContentScores[0];\n if (firstTopic.competitor_scores) {\n firstTopic.competitor_scores.forEach(comp => {\n companies.push({\n id: comp.company_id,\n name: comp.company_name\n });\n });\n }\n }\n\n // Create table data structure: { topicId: { companyId: percentage } }\n const tableData = {};\n topicContentScores.forEach(topic => {\n tableData[topic.topic_id] = {};\n\n // Customer score\n tableData[topic.topic_id]['customer'] = topic.customer_score || 0;\n\n // Competitor scores\n if (topic.competitor_scores) {\n topic.competitor_scores.forEach(comp => {\n tableData[topic.topic_id][comp.company_id] = comp.content_score || 0;\n });\n }\n });\n\n // Custom section with content gap analysis visualizations\n const customSection = (\n
    \n {/* Overall Content Coverage Score */}\n
    \n

    Overall Content Coverage Score

    \n \n
    \n\n {/* Topic Coverage Comparison Table */}\n
    \n

    Content Coverage by Topic

    \n \n

    \n This table shows content coverage scores for each topic area. Higher scores indicate more comprehensive and authoritative content coverage.\n

    \n
    \n\n {/* Content Gap Metrics */}\n
    \n

    Content Coverage Analysis

    \n
    \n
    \n
    {Math.round(customerOverallScore)}
    \n
    Your Content Score
    \n
    \n
    \n
    {Math.round(competitorAverageScore)}
    \n
    Competitor Average
    \n
    \n
    \n
    {Math.round(contentGapPercentage)}%
    \n
    Content Gap
    \n
    \n
    \n
    \n
    \n );\n\n return (\n \n );\n};\n\nexport default ContentGapAnalysis;", "import React, { useState, useEffect } from 'react';\nimport axios from '../AxiosConfig';\nimport AuditCategoryAnalysis from './AuditCategoryAnalysis';\nimport PrimaryScaleGraph from './PrimaryScaleGraph';\nimport BasicScaleGraph from './BasicScaleGraph';\nimport { AlertTriangle, Settings, Globe, Wrench } from 'lucide-react';\n\nconst TechnicalAnalysis = ({ projectId, auditResultId }) => {\n const [data, setData] = useState(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n\n const analysisDescription = \"The platform conducted a comprehensive technical audit of each page in your client's sitemap from an AI crawler perspective. We analyzed critical technical factors including load speed, static vs dynamic content rendering, context window information density, content front-loading strategies, mobile optimization, and overall technical infrastructure that impacts how effectively AI systems can crawl, process, and reference your content.\";\n\n // Fetch technical analysis data\n useEffect(() => {\n const fetchTechnicalData = async () => {\n try {\n setLoading(true);\n const url = auditResultId\n ? `/api/projects/${projectId}/audit/category/6?audit_result_id=${auditResultId}`\n : `/api/projects/${projectId}/audit/category/6`; // 6 = technical\n const response = await axios.get(url);\n setData(response.data);\n setError(null);\n } catch (err) {\n console.error('Error fetching technical analysis data:', err);\n setError('Failed to load technical analysis data. Please try again.');\n } finally {\n setLoading(false);\n }\n };\n\n if (projectId) {\n fetchTechnicalData();\n }\n }, [projectId, auditResultId]);\n\n // Show loading state\n if (loading) {\n return (\n \n
    Loading technical analysis...
    \n \n }\n opportunities={[]}\n />\n );\n }\n\n // Show error state\n if (error) {\n return (\n \n

    Error Loading Analysis

    \n

    {error}

    \n \n }\n opportunities={[]}\n />\n );\n }\n\n // Show message if no data available\n if (!data || data.status !== 'completed') {\n return (\n \n

    Analysis In Progress

    \n

    Technical analysis is still being processed. Please check back later.

    \n \n }\n opportunities={[]}\n />\n );\n }\n\n const analysisData = data.analysis_data || {};\n const opportunities = data.opportunities || [];\n\n // Check if this is a \"no pages found\" scenario\n if (analysisData.status === 'no_pages_found' || analysisData.message?.includes('No valid pages were found')) {\n const customSection = (\n
    \n
    \n
    \n \n
    \n

    No Pages Found for Technical Analysis

    \n

    \n We were unable to find any valid pages from your website's sitemap to analyze for technical optimization.\n

    \n
    \n

    This could be due to:

    \n
      \n
    • \u2022 Website sitemap is not accessible or missing
    • \n
    • \u2022 Sitemap contains no valid URLs
    • \n
    • \u2022 All pages are blocked by robots.txt
    • \n
    • \u2022 Website is password protected or behind authentication
    • \n
    • \u2022 Server configuration issues preventing crawling
    • \n
    • \u2022 Domain resolution or DNS problems
    • \n
    \n
    \n
    \n
    \n
    \n\n
    \n
    \n \n
    \n

    Technical Troubleshooting Steps

    \n
      \n
    1. 1. Verify your website is online and accessible to bots
    2. \n
    3. 2. Check your sitemap.xml exists at: yoursite.com/sitemap.xml
    4. \n
    5. 3. Review robots.txt file for crawling restrictions
    6. \n
    7. 4. Ensure SSL certificate is valid and properly configured
    8. \n
    9. 5. Test website load speed and server response times
    10. \n
    11. 6. Confirm the domain URL is correct in project settings
    12. \n
    13. 7. Contact support if technical issues persist
    14. \n
    \n
    \n
    \n
    \n\n
    \n
    \n \n
    \n

    Alternative Analysis Options

    \n
    \n

    While we work to resolve this issue, consider:

    \n
      \n
    • \u2022 Running a manual page speed test using Google PageSpeed Insights
    • \n
    • \u2022 Checking your website's technical SEO with other tools
    • \n
    • \u2022 Reviewing server logs for crawling errors
    • \n
    • \u2022 Contacting your web developer or hosting provider
    • \n
    \n
    \n
    \n
    \n
    \n\n
    \n
    \n \n

    Domain Information

    \n
    \n
    \n

    Domain: {analysisData.metadata?.customer_company || 'Not specified'}

    \n

    Analysis Date: {analysisData.metadata?.computed_at ? new Date(analysisData.metadata.computed_at).toLocaleDateString() : 'N/A'}

    \n

    Error Details: {analysisData.error_details || 'No additional details available'}

    \n
    \n
    \n
    \n );\n\n return (\n \n );\n }\n\n // Extract data for components (existing logic)\n const overallTechnicalScore = analysisData.overall_technical_score || 0;\n const performanceScore = analysisData.performance_score || 0;\n const structureScore = analysisData.structure_score || 0;\n const schemaScore = analysisData.schema_score || 0;\n const technicalIssues = analysisData.technical_issues || [];\n\n // Custom section with technical analysis visualizations\n const customSection = (\n
    \n {/* Overall Technical Score */}\n
    \n

    Overall Technical Score

    \n \n
    \n\n {/* Category Breakdown */}\n
    \n

    Technical Category Analysis

    \n
    \n \n \n \n
    \n

    \n Each category measures critical factors that impact AI system's ability to efficiently crawl and understand your content.\n

    \n
    \n\n {/* Technical Issues */}\n {technicalIssues.length > 0 && (\n
    \n

    Critical Technical Issues

    \n
    \n
    \n \n \n \n \n \n \n \n \n \n \n {technicalIssues.map((issue, index) => (\n \n \n \n \n \n \n ))}\n \n
    \n Issue Type\n \n Description\n \n Severity\n \n Pages Affected\n
    \n {issue.type}\n \n {issue.description}\n \n \n {issue.severity}\n \n \n {issue.pages_affected || 1}\n
    \n
    \n
    \n
    \n )}\n
    \n );\n\n return (\n \n );\n};\n\nexport default TechnicalAnalysis;", "import React, { useState } from 'react';\nimport axios from '../AxiosConfig';\n\nconst CreateAudit = () => {\n const [formData, setFormData] = useState({\n companyName: '',\n domain: ''\n });\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState('');\n\n const handleInputChange = (e) => {\n const { name, value } = e.target;\n setFormData(prev => ({\n ...prev,\n [name]: value\n }));\n };\n\n const handleSubmit = async (e) => {\n e.preventDefault();\n\n if (!formData.companyName.trim() || !formData.domain.trim()) {\n setError('Company name and domain are required');\n return;\n }\n\n setLoading(true);\n setError('');\n\n try {\n // Create project with generating_audit flag using axios\n const response = await axios.post('/api/audit', {\n company_name: formData.companyName,\n domain: formData.domain\n });\n\n const data = response.data;\n const projectId = data.project_id;\n\n // Redirect to audit results page\n window.location.href = `/projects/${projectId}/audit`;\n } catch (err) {\n console.error('Error creating audit project:', err);\n setError(err.response?.data?.error || 'Failed to create audit project');\n } finally {\n setLoading(false);\n }\n };\n\n const isFormValid = formData.companyName.trim() && formData.domain.trim();\n\n return (\n
    \n
    \n
    \n
    \n

    \n Create Comprehensive Audit\n

    \n

    \n Generate a complete AI visibility analysis for any company\n

    \n
    \n\n
    \n
    \n \n \n
    \n\n
    \n \n \n
    \n\n {error && (\n
    \n
    \n \n \n \n
    \n

    Error

    \n
    {error}
    \n
    \n
    \n
    \n )}\n\n \n {loading ? (\n
    \n \n \n \n \n Creating Audit...\n
    \n ) : (\n
    \n \n \n \n Create Comprehensive Audit\n
    \n )}\n \n
    \n\n
    \n

    Comprehensive Audit Process:

    \n
      \n
    1. 1. AI analyzes company & generates user personas
    2. \n
    3. 2. Creates comprehensive topic hierarchy
    4. \n
    5. 3. Generates conversation prompts
    6. \n
    7. 4. Executes AI platform testing
    8. \n
    9. 5. Conducts full visibility audit
    10. \n
    \n

    \n Complete process takes 15-30 minutes\n

    \n
    \n\n
    \n window.location.href = '/'}\n className=\"text-blue-600 hover:text-blue-500 text-sm font-medium\"\n disabled={loading}\n >\n \u2190 Back to Home\n \n
    \n
    \n
    \n
    \n );\n};\n\nexport default CreateAudit;", "import React, { useState, useContext } from 'react';\nimport { Building2, Search, FileText, Users, BarChart3, CheckCircle, Circle } from 'lucide-react';\nimport axios from '../AxiosConfig';\nimport ClientInfo from './ClientInfo';\nimport Keywords from './Keywords';\nimport Topics from './Topics';\nimport Competitors from './Competitors';\nimport { AuthContext } from '../../context/AuthContext'; // Import AuthContext for user data\nimport { trackEvent } from '../Analytics/mixpanel'; // Import trackEvent\n\nconst ClientSetup = () => {\n const { user } = useContext(AuthContext); // Get user data for tracking\n\n // Initialize all state variables\n const [currentStep, setCurrentStep] = useState(1);\n const [completedSteps, setCompletedSteps] = useState(new Set()); // Track completed steps\n const [clientData, setClientData] = useState({\n companyName: '',\n domain: '',\n geolocation: '', // Add geolocation field\n language: '', // Add language field\n brands: [],\n keywords: [],\n selectedTopics: [],\n restrictToSeedTopics: false, // Add restrictToSeedTopics field\n competitors: []\n });\n const [suggestedTopics, setSuggestedTopics] = useState([]);\n const [isLoadingTopics, setIsLoadingTopics] = useState(false);\n const [suggestedCompetitors, setSuggestedCompetitors] = useState([]);\n const [isLoadingCompetitors, setIsLoadingCompetitors] = useState(false);\n\n const steps = [\n { id: 1, title: 'Client Info', icon: },\n { id: 2, title: 'Keywords', icon: },\n { id: 3, title: 'Topics', icon: },\n { id: 4, title: 'Competitors', icon: },\n ];\n\n const goToNextStep = () => {\n if (currentStep < 4) {\n\n\n // Mark current step as completed before moving to next\n setCompletedSteps(prev => new Set([...prev, currentStep]));\n\n const nextStep = currentStep + 1;\n console.log(`Moving from step ${currentStep} to step ${nextStep}`);\n\n // Track step navigation\n trackEvent('Client Setup Step Navigation', {\n from_step: currentStep,\n to_step: nextStep,\n direction: 'next',\n user_id: user?.id\n });\n\n setCurrentStep(nextStep);\n\n // If moving to topics step, fetch suggested topics\n if (nextStep === 3) {\n console.log('Triggering topic suggestions fetch');\n fetchSuggestedTopics();\n }\n\n // If moving to competitors step, fetch suggested competitors\n if (nextStep === 4) {\n console.log('Triggering competitor suggestions fetch');\n fetchSuggestedCompetitors();\n }\n } else {\n // Track final step completion\n trackEvent('Client Setup Step Completed', {\n step_number: currentStep,\n step_name: steps.find(s => s.id === currentStep)?.title,\n user_id: user?.id,\n company_name: clientData.companyName,\n domain: clientData.domain,\n geolocation: clientData.geolocation,\n language: clientData.language,\n brands_count: clientData.brands.length,\n keywords_count: clientData.keywords.length,\n topics_count: clientData.selectedTopics.length,\n restrict_to_seed_topics: clientData.restrictToSeedTopics,\n competitors_count: clientData.competitors.length\n });\n\n // Mark step 4 as completed before moving to summary\n setCompletedSteps(prev => new Set([...prev, currentStep]));\n\n\n\n setCurrentStep('summary');\n }\n };\n\n const goToPreviousStep = () => {\n if (currentStep === 'summary') {\n trackEvent('Client Setup Step Navigation', {\n from_step: 'summary',\n to_step: 4,\n direction: 'back',\n user_id: user?.id\n });\n setCurrentStep(4);\n } else if (currentStep > 1) {\n trackEvent('Client Setup Step Navigation', {\n from_step: currentStep,\n to_step: currentStep - 1,\n direction: 'back',\n user_id: user?.id\n });\n setCurrentStep(currentStep - 1);\n }\n };\n\n const fetchSuggestedTopics = async () => {\n if (suggestedTopics.length > 0) return; // Don't fetch if we already have topics\n\n\n\n setIsLoadingTopics(true);\n try {\n const response = await axios.post('/api/client_setup/suggest_topics', {\n client_name: clientData.companyName,\n domain: clientData.domain,\n geolocation: clientData.geolocation, // Include geolocation in request\n brands: clientData.brands,\n keywords: clientData.keywords\n });\n\n if (response.data.success && response.data.topics) {\n setSuggestedTopics(response.data.topics);\n\n\n } else {\n console.error('Failed to fetch topics:', response.data.message);\n\n\n\n // Fallback to default topics if API fails\n setSuggestedTopics([\n 'Artificial Intelligence', 'Machine Learning', 'Cloud Computing', 'Cybersecurity',\n 'Digital Marketing', 'E-commerce', 'Mobile Apps', 'Web Development',\n 'Data Analytics', 'Social Media', 'SEO/SEM', 'Content Marketing',\n 'Business Strategy', 'Customer Experience', 'Product Management', 'Innovation'\n ]);\n }\n } catch (error) {\n console.error('Error fetching topics:', error);\n\n\n\n // Fallback to default topics if API call fails\n setSuggestedTopics([\n 'Artificial Intelligence', 'Machine Learning', 'Cloud Computing', 'Cybersecurity',\n 'Digital Marketing', 'E-commerce', 'Mobile Apps', 'Web Development',\n 'Data Analytics', 'Social Media', 'SEO/SEM', 'Content Marketing',\n 'Business Strategy', 'Customer Experience', 'Product Management', 'Innovation'\n ]);\n } finally {\n setIsLoadingTopics(false);\n }\n };\n\n const toggleRestrictToSeedTopics = () => {\n console.log('toggleRestrictToSeedTopics called');\n console.log('Current restrictToSeedTopics value:', clientData.restrictToSeedTopics);\n setClientData(prev => {\n const newValue = !prev.restrictToSeedTopics;\n console.log('New restrictToSeedTopics value:', newValue);\n return {\n ...prev,\n restrictToSeedTopics: newValue\n };\n });\n };\n\n const fetchSuggestedCompetitors = async () => {\n if (suggestedCompetitors.length > 0) return; // Don't fetch if we already have competitors\n\n console.log('Starting to fetch suggested competitors');\n console.log('Client data for competitors:', {\n companyName: clientData.companyName,\n domain: clientData.domain,\n geolocation: clientData.geolocation,\n brands: clientData.brands,\n keywords: clientData.keywords\n });\n\n\n setIsLoadingCompetitors(true);\n try {\n const response = await axios.post('/api/client_setup/suggest_competitors', {\n client_name: clientData.companyName,\n domain: clientData.domain,\n geolocation: clientData.geolocation, // Include geolocation in request\n brands: clientData.brands,\n keywords: clientData.keywords\n });\n\n console.log('Competitors API response:', response.data);\n\n if (response.data.success && response.data.competitors) {\n setSuggestedCompetitors(response.data.competitors);\n\n } else {\n console.error('Failed to fetch competitors:', response.data.message);\n\n\n\n // Fallback to default competitors if API fails\n setSuggestedCompetitors([\n 'Microsoft', 'Google', 'Amazon', 'Apple',\n 'Meta', 'Tesla', 'Netflix', 'Adobe'\n ]);\n }\n } catch (error) {\n console.error('Error fetching competitors:', error);\n\n\n // Fallback to default competitors if API call fails\n setSuggestedCompetitors([\n 'Microsoft', 'Google', 'Amazon', 'Apple',\n 'Meta', 'Tesla', 'Netflix', 'Adobe'\n ]);\n } finally {\n setIsLoadingCompetitors(false);\n console.log('Finished fetching competitors, loading set to false');\n }\n };\n\n\n const renderStepContent = () => {\n switch (currentStep) {\n case 1:\n return (\n \n );\n case 2:\n return (\n \n );\n case 3:\n return (\n \n );\n case 4:\n return (\n \n );\n default:\n return (\n
    \n
    \n \n

    Select a Step

    \n

    Choose a step from the sidebar to begin setup

    \n
    \n
    \n );\n }\n };\n\n return (\n
    \n
    \n
    \n \n ))}\n\n
  • \n \n
    \n \n
    \n
    \n
    \n Analysis Summary\n
    \n
    \n
    \n {currentStep === 'summary' ? (\n \n ) : completedSteps.size === 4 ? (\n \n ) : (\n \n )}\n
    \n
  • \n \n \n \n \n\n
    \n
    \n {renderStepContent()}\n
    \n
    \n \n \n );\n};\n\nexport default ClientSetup;", "import React, { useState } from 'react';\nimport { Plus, X, Info } from 'lucide-react';\n\nconst Tooltip = ({ children, text }) => {\n const [isVisible, setIsVisible] = useState(false);\n\n return (\n
    \n setIsVisible(true)}\n onMouseLeave={() => setIsVisible(false)}\n className=\"cursor-help inline-flex items-center\"\n >\n {children}\n
    \n {isVisible && (\n
    \n
    \n {text}\n
    \n )}\n \n );\n};\n\nconst ClientInfo = ({ onNext, onBack, clientData = {}, setClientData }) => {\n const [localBrandInput, setLocalBrandInput] = useState('');\n\n // Debug logging\n console.log('ClientInfo clientData:', clientData);\n\n const handleInputChange = (field, value) => {\n console.log('Updating field:', field, 'with value:', value);\n setClientData(prev => {\n const newData = { ...prev, [field]: value };\n console.log('New clientData after update:', newData);\n return newData;\n });\n };\n\n const addBrands = () => {\n if (!localBrandInput.trim()) return;\n const currentBrands = clientData.brands || [];\n const newBrands = localBrandInput\n .split(',')\n .map(brand => brand.trim())\n .filter(brand => brand && !currentBrands.includes(brand));\n const totalBrands = currentBrands.length + newBrands.length;\n if (totalBrands <= 5) {\n setClientData(prev => ({\n ...prev,\n brands: [...currentBrands, ...newBrands]\n }));\n setLocalBrandInput('');\n }\n };\n\n const removeBrand = (brandToRemove) => {\n const currentBrands = clientData.brands || [];\n setClientData(prev => ({\n ...prev,\n brands: currentBrands.filter(brand => brand !== brandToRemove)\n }));\n };\n\n const handleKeyPress = (e) => {\n if (e.key === 'Enter') {\n e.preventDefault();\n addBrands();\n }\n };\n\n // Form validation\n const isFormValid = !!(\n clientData.companyName?.trim() &&\n clientData.domain?.trim() &&\n (clientData.brands || []).length > 0\n );\n console.log('Form validation:', {\n companyName: clientData.companyName,\n domain: clientData.domain,\n brands: clientData.brands,\n geolocation: clientData.geolocation,\n language: clientData.language,\n isValid: isFormValid\n });\n\n return (\n
    \n
    \n
    \n

    Client Information

    \n

    \n Provide information about your client to be used for AI visibility analysis and recommendations\n

    \n
    \n\n
    \n

    \n What is your client's name and domain?\n

    \n

    \n We will use this information to collect and analyze AI response data\n

    \n\n
    \n
    \n \n handleInputChange('companyName', e.target.value)}\n />\n
    \n\n
    \n \n
    \n \n https://\n \n handleInputChange('domain', e.target.value)}\n />\n
    \n
    \n\n
    \n \n handleInputChange('geolocation', e.target.value)}\n />\n
    \n\n
    \n \n handleInputChange('language', e.target.value)}\n />\n
    \n
    \n\n
    \n

    \n Add your client's brand(s) you want to track.\n

    \n\n
      \n
    • \u2022 Enter the brand name the way you would expect it to appear in an LLM answer. (i.e. enter Nike instead of Nike Inc.)
    • \n
    • \u2022 Add at least 1 brand to track (this is typically their company name)
    • \n
    • \u2022 5 brands is the maximum that can be added on initial setup (more can be added later)
    • \n
    \n\n
    \n \n
    \n setLocalBrandInput(e.target.value)}\n onKeyPress={handleKeyPress}\n disabled={(clientData.brands || []).length >= 5}\n />\n = 5\n ? 'bg-gray-100 text-gray-400 cursor-not-allowed'\n : 'bg-indigo-600 text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500'\n }`}\n onClick={addBrands}\n disabled={(clientData.brands || []).length >= 5 || !localBrandInput.trim()}\n >\n \n Add\n \n
    \n

    \n Separate brands with commas\n

    \n
    \n\n
    \n \n {(clientData.brands || []).length > 0 ? (\n
    \n {(clientData.brands || []).map((brand, index) => (\n \n {brand}\n removeBrand(brand)}\n >\n \n \n \n ))}\n
    \n ) : (\n

    No brands added yet

    \n )}\n
    \n
    \n
    \n\n
    \n
    \n \n Next\n \n
    \n
    \n
    \n );\n};\n\nexport default ClientInfo;", "import React, { useState } from 'react';\nimport { Plus, X, Upload } from 'lucide-react';\n\nconst Keywords = ({ onNext, onBack, clientData = {}, setClientData }) => {\n const [keywordInput, setKeywordInput] = useState('');\n const [showUploadModal, setShowUploadModal] = useState(false);\n const [isDragOver, setIsDragOver] = useState(false);\n\n const addKeywords = () => {\n if (!keywordInput.trim()) return;\n const currentKeywords = clientData.keywords || [];\n const newKeywords = keywordInput\n .split(',')\n .map(keyword => keyword.trim())\n .filter(keyword => keyword && !currentKeywords.includes(keyword));\n setClientData(prev => ({ ...prev, keywords: [...currentKeywords, ...newKeywords] }));\n setKeywordInput('');\n };\n\n const removeKeyword = (keywordToRemove) => {\n const currentKeywords = clientData.keywords || [];\n setClientData(prev => ({\n ...prev,\n keywords: currentKeywords.filter(keyword => keyword !== keywordToRemove)\n }));\n };\n\n const handleKeyPress = (e) => {\n if (e.key === 'Enter') {\n e.preventDefault();\n addKeywords();\n }\n };\n\n const handleCSVUpload = async (file) => {\n if (!file) return;\n try {\n const text = await file.text();\n const lines = text.split('\\n').filter(line => line.trim());\n const newKeywords = [];\n\n // Skip the first line (header row) and process the rest\n lines.slice(1).forEach(line => {\n const lineKeywords = line.split(',').map(k =>\n k.trim().replace(/^[\"']|[\"']$/g, '').replace(/[^\\w\\s-]/g, '').trim()\n ).filter(k => k.length > 0);\n newKeywords.push(...lineKeywords);\n });\n\n const currentKeywords = clientData.keywords || [];\n const uniqueNewKeywords = [...new Set(newKeywords)]\n .filter(keyword => keyword && !currentKeywords.includes(keyword));\n\n if (uniqueNewKeywords.length > 0) {\n setClientData(prev => ({ ...prev, keywords: [...currentKeywords, ...uniqueNewKeywords] }));\n }\n setShowUploadModal(false);\n } catch (error) {\n console.error('Error parsing CSV:', error);\n }\n };\n\n const handleFileSelect = (e) => {\n const file = e.target.files[0];\n if (file) handleCSVUpload(file);\n };\n\n const handleDrop = (e) => {\n e.preventDefault();\n setIsDragOver(false);\n const file = e.dataTransfer.files[0];\n if (file && file.type === 'text/csv') {\n handleCSVUpload(file);\n }\n };\n\n const handleDragOver = (e) => {\n e.preventDefault();\n setIsDragOver(true);\n };\n\n const handleDragLeave = (e) => {\n e.preventDefault();\n setIsDragOver(false);\n };\n\n return (\n
    \n
    \n
    \n

    Keyword Tracking

    \n

    \n You can tell us or import existing keywords from your client to help inform what types of data to collect\n

    \n
    \n\n
    \n

    \n Tell us more about your client, what keywords do they currently track?\n

    \n

    \n The keywords inputted here will be used to suggest AI conversation topics for your client\n

    \n\n
    \n
    \n \n
    \n setKeywordInput(e.target.value)}\n onKeyPress={handleKeyPress}\n />\n \n \n Add\n \n
    \n

    \n You can add multiple keywords by separating them with commas\n

    \n
    \n\n
    \n \n setShowUploadModal(true)}\n className=\"inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500\"\n >\n \n Upload CSV\n \n
    \n
    \n\n
    \n
    \n \n {(clientData.keywords || []).length > 0 ? (\n
    \n {(clientData.keywords || []).map((keyword, index) => (\n \n {keyword}\n removeKeyword(keyword)}\n >\n \n \n \n ))}\n
    \n ) : (\n

    No keywords added yet

    \n )}\n
    \n
    \n
    \n\n {showUploadModal && (\n
    \n
    \n
    \n

    Upload CSV File

    \n setShowUploadModal(false)}\n className=\"text-gray-400 hover:text-gray-600\"\n >\n \n \n
    \n \n \n

    \n Drag and drop your CSV file here, or\n

    \n \n

    \n CSV files only \u2022 First header row will be automatically removed\n

    \n
    \n
    \n
    \n )}\n\n
    \n \n Back\n \n \n Next\n \n
    \n
    \n \n );\n};\n\nexport default Keywords;", "import React, { useState } from 'react';\nimport { Plus, X, Loader2, Info } from 'lucide-react';\n\nconst Topics = ({ onNext, onBack, suggestedTopics = [], isLoadingTopics = false, clientData = {}, setClientData }) => {\n const [topicInput, setTopicInput] = useState('');\n\n const addTopics = () => {\n if (!topicInput.trim()) return;\n const currentTopics = clientData.selectedTopics || [];\n const newTopics = topicInput\n .split(',')\n .map(topic => topic.trim())\n .filter(topic => topic && !currentTopics.includes(topic));\n setClientData(prev => ({\n ...prev,\n selectedTopics: [...currentTopics, ...newTopics]\n }));\n setTopicInput('');\n };\n\n const removeTopic = (topicToRemove) => {\n const currentTopics = clientData.selectedTopics || [];\n setClientData(prev => ({\n ...prev,\n selectedTopics: currentTopics.filter(topic => topic !== topicToRemove)\n }));\n };\n\n const toggleSuggestedTopic = (topic) => {\n const currentTopics = clientData.selectedTopics || [];\n if (currentTopics.includes(topic)) {\n setClientData(prev => ({\n ...prev,\n selectedTopics: currentTopics.filter(t => t !== topic)\n }));\n } else {\n setClientData(prev => ({\n ...prev,\n selectedTopics: [...currentTopics, topic]\n }));\n }\n };\n\n const handleKeyPress = (e) => {\n if (e.key === 'Enter') {\n e.preventDefault();\n addTopics();\n }\n };\n\n const toggleRestrictToSeedTopics = () => {\n setClientData(prev => ({\n ...prev,\n restrictToSeedTopics: !prev.restrictToSeedTopics\n }));\n };\n\n return (\n
    \n
    \n
    \n

    Relevant Client Topics

    \n

    \n Tell us what topics are the most relevant to your client\n

    \n
    \n\n
    \n

    \n Choose or add topics\n

    \n

    \n Below are suggested topics based on your client information. You can select from the list or add new topics\n

    \n\n
    \n

    \n AI-Generated Topic Suggestions\n

    \n\n {isLoadingTopics ? (\n
    \n \n

    Loading personalized topics...

    \n

    Analyzing your client information

    \n
    \n ) : (\n
    \n {suggestedTopics.map((topic, index) => (\n toggleSuggestedTopic(topic)}\n className={`px-3 py-2 rounded-md text-sm font-medium border transition-colors text-center ${\n (clientData.selectedTopics || []).includes(topic)\n ? 'bg-indigo-600 text-white border-indigo-600'\n : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50'\n }`}\n >\n {topic}\n \n ))}\n
    \n )}\n
    \n\n
    \n
    \n \n
    \n setTopicInput(e.target.value)}\n onKeyPress={handleKeyPress}\n disabled={isLoadingTopics}\n />\n \n \n Add\n \n
    \n

    \n You can add multiple topics by separating them with commas\n

    \n
    \n
    \n\n
    \n
    \n \n {(clientData.selectedTopics || []).length > 0 ? (\n
    \n {(clientData.selectedTopics || []).map((topic, index) => (\n \n {topic}\n removeTopic(topic)}\n >\n \n \n \n ))}\n
    \n ) : (\n

    No topics selected yet

    \n )}\n
    \n
    \n\n {/* Restrict to Seed Topics Checkbox */}\n
    \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n \n
    \n

    \n When checked: The system will generate a semantic topic hierarchy strictly limited to your selected topics above.\n Only topics directly related to your selections will be created.\n

    \n

    \n When unchecked (default): Your selected topics will be used as guidance to influence a broader,\n AI-generated semantic topic hierarchy that covers the complete customer journey and industry landscape.\n

    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n\n
    \n \n Back\n \n \n {isLoadingTopics ? 'Loading...' : 'Next'}\n \n
    \n
    \n
    \n );\n};\n\nexport default Topics;", "import React, { useState, useContext } from 'react';\nimport { Plus, X, Loader2 } from 'lucide-react';\nimport { useNavigate } from 'react-router-dom';\nimport axios from '../AxiosConfig';\nimport { AuthContext } from '../../context/AuthContext'; // Import AuthContext for user data\nimport { trackEvent } from '../Analytics/mixpanel'; // Import trackEvent\n\nconst Competitors = ({\n onNext,\n onBack,\n clientData = {},\n setClientData,\n suggestedCompetitors = [],\n isLoadingCompetitors = false\n }) => {\n const navigate = useNavigate();\n const { user } = useContext(AuthContext); // Get user data for tracking\n\n const [showModal, setShowModal] = useState(false);\n const [currentSlot, setCurrentSlot] = useState(null);\n const [isLoadingCompetitorDetails, setIsLoadingCompetitorDetails] = useState(false);\n const [isCreatingProject, setIsCreatingProject] = useState(false);\n const [modalData, setModalData] = useState({\n name: '',\n domain: '',\n brandInput: '',\n brands: []\n });\n\n const competitors = clientData.competitors || [];\n\n const openModal = (slotIndex) => {\n setCurrentSlot(slotIndex);\n // If editing existing competitor, populate modal\n if (competitors[slotIndex]) {\n setModalData({\n name: competitors[slotIndex].name || '',\n domain: competitors[slotIndex].domain || '',\n brandInput: '',\n brands: competitors[slotIndex].brands || []\n });\n } else {\n // Reset modal for new competitor\n setModalData({\n name: '',\n domain: '',\n brandInput: '',\n brands: []\n });\n }\n setShowModal(true);\n };\n\n const closeModal = () => {\n setShowModal(false);\n setCurrentSlot(null);\n setIsLoadingCompetitorDetails(false);\n setModalData({\n name: '',\n domain: '',\n brandInput: '',\n brands: []\n });\n };\n\n const addBrandInModal = () => {\n if (!modalData.brandInput.trim()) return;\n const newBrands = modalData.brandInput\n .split(',')\n .map(brand => brand.trim())\n .filter(brand => brand && !modalData.brands.includes(brand));\n const totalBrands = modalData.brands.length + newBrands.length;\n if (totalBrands <= 5) {\n setModalData(prev => ({\n ...prev,\n brands: [...prev.brands, ...newBrands],\n brandInput: ''\n }));\n }\n };\n\n const removeBrandFromModal = (brandToRemove) => {\n setModalData(prev => ({\n ...prev,\n brands: prev.brands.filter(brand => brand !== brandToRemove)\n }));\n };\n\n const handleModalInputChange = (field, value) => {\n setModalData(prev => ({ ...prev, [field]: value }));\n };\n\n const handleModalKeyPress = (e) => {\n if (e.key === 'Enter') {\n e.preventDefault();\n addBrandInModal();\n }\n };\n\n const addCompetitor = () => {\n if (!modalData.name.trim() || !modalData.domain.trim()) return;\n\n const newCompetitor = {\n name: modalData.name,\n domain: modalData.domain,\n brands: modalData.brands\n };\n\n const updatedCompetitors = [...competitors];\n updatedCompetitors[currentSlot] = newCompetitor;\n\n if (setClientData) {\n setClientData(prev => ({\n ...prev,\n competitors: updatedCompetitors\n }));\n }\n\n closeModal();\n };\n\n const addSuggestedCompetitor = async (competitorName) => {\n console.log('addSuggestedCompetitor called with:', competitorName);\n\n // Find first empty slot\n const emptySlotIndex = competitors.findIndex((comp, index) => !comp || index >= competitors.length);\n const slotIndex = emptySlotIndex === -1 ? competitors.length : emptySlotIndex;\n\n console.log('Found slot index:', slotIndex);\n\n if (slotIndex < 4) {\n // Set initial modal data with just the name\n setModalData({\n name: competitorName,\n domain: '',\n brandInput: '',\n brands: []\n });\n setCurrentSlot(slotIndex);\n setShowModal(true);\n setIsLoadingCompetitorDetails(true);\n\n console.log('Making API call for competitor details...');\n\n try {\n // Call API to get competitor details\n const response = await axios.post('/api/client_setup/competitor_details', {\n competitor_name: competitorName,\n client_context: {\n client_name: clientData.companyName,\n client_domain: clientData.domain,\n client_brands: clientData.brands\n }\n });\n\n console.log('API response received:', response.data);\n\n if (response.data.success && response.data.competitor) {\n const competitorInfo = response.data.competitor;\n console.log('Updating modal with competitor info:', competitorInfo);\n setModalData(prev => ({\n ...prev,\n domain: competitorInfo.domain || '',\n brands: competitorInfo.brands || []\n }));\n }\n } catch (error) {\n console.error('Error fetching competitor details:', error);\n // Continue with empty data if API fails\n } finally {\n console.log('Finished API call, setting loading to false');\n setIsLoadingCompetitorDetails(false);\n }\n }\n };\n\n const removeCompetitor = (slotIndex) => {\n const updatedCompetitors = [...competitors];\n updatedCompetitors.splice(slotIndex, 1);\n if (setClientData) {\n setClientData(prev => ({\n ...prev,\n competitors: updatedCompetitors\n }));\n }\n };\n\n const handleCreateProject = async () => {\n console.log('Starting project creation with data:', clientData);\n console.log('restrictToSeedTopics value:', clientData.restrictToSeedTopics);\n console.log('language value:', clientData.language);\n setIsCreatingProject(true);\n\n try {\n // Format the data according to the API requirements\n const projectData = {\n project: {\n name: clientData.companyName,\n client_name: clientData.companyName, // Add client_name for the customer company\n geolocation: clientData.geolocation, // Include geolocation in project creation\n language: clientData.language || null, // Include language in project creation\n restrict_to_seed_topics: clientData.restrictToSeedTopics || false, // Include restrict_to_seed_topics\n domains: [clientData.domain],\n brands: clientData.brands || [],\n topics: clientData.selectedTopics || [],\n competitors: clientData.competitors || []\n }\n };\n\n console.log('Project data being sent:', projectData);\n console.log('restrict_to_seed_topics in payload:', projectData.project.restrict_to_seed_topics);\n console.log('language in payload:', projectData.project.language);\n\n console.log('Sending project data to API:', projectData);\n\n const response = await axios.post('/api/client_setup/create_project', projectData);\n\n console.log('Project creation response:', response.data);\n\n if (response.data.success) {\n // Track successful project creation\n trackEvent('Audit Project Created', {\n user_id: user?.id,\n project_id: response.data.project.id,\n project_name: response.data.project.name,\n company_name: clientData.companyName,\n domain: clientData.domain,\n geolocation: clientData.geolocation, // Include geolocation in tracking\n language: clientData.language || 'English', // Include language in tracking\n restrict_to_seed_topics: clientData.restrictToSeedTopics || false, // Include in tracking\n brands_count: clientData.brands?.length || 0,\n keywords_count: clientData.keywords?.length || 0,\n topics_count: clientData.selectedTopics?.length || 0,\n competitors_count: clientData.competitors?.length || 0,\n source: 'client_setup_wizard'\n });\n\n console.log('Project created successfully:', response.data.project);\n\n // Redirect to the audit page using the project ID\n navigate(`/projects/${response.data.project.id}`);\n } else {\n console.error('Project creation failed:', response.data.errors);\n alert('Failed to create project: ' + (response.data.errors || ['Unknown error']).join(', '));\n }\n } catch (error) {\n console.error('Error creating project:', error);\n let errorMessage = 'Failed to create project';\n\n if (error.response?.data?.errors) {\n errorMessage += ': ' + error.response.data.errors.join(', ');\n } else if (error.response?.data?.message) {\n errorMessage += ': ' + error.response.data.message;\n } else if (error.message) {\n errorMessage += ': ' + error.message;\n }\n\n alert(errorMessage);\n } finally {\n setIsCreatingProject(false);\n }\n };\n\n return (\n
    \n
    \n
    \n

    Track Competitor Mentions

    \n

    \n Tell us what competitors are most important to your client\n

    \n
    \n\n
    \n

    \n Add your competitors (Optional)\n

    \n

    \n By adding your competitors, their brands, and products we can show you how your client compares in our analysis. We suggest you add at least 1 competitor for now, the maximum allowed on setup is 4. You can always add more later.\n

    \n\n
    \n
    \n {[1, 2, 3, 4].map((num) => {\n const competitor = competitors[num - 1];\n return (\n
    \n openModal(num - 1)}\n className=\"w-full h-32 border-2 border-dashed border-gray-300 rounded-lg hover:border-indigo-400 hover:bg-indigo-50 transition-colors flex flex-col items-center justify-center text-gray-500 hover:text-indigo-600\"\n disabled={isCreatingProject}\n >\n {competitor ? (\n <>\n
    \n {competitor.name}\n
    \n
    \n {competitor.domain}\n
    \n
    \n {competitor.brands?.length || 0} brand(s)\n
    \n \n ) : (\n <>\n
    Competitor {num}
    \n
    \n \n
    \n
    Add
    \n \n )}\n \n {competitor && !isCreatingProject && (\n {\n e.stopPropagation();\n removeCompetitor(num - 1);\n }}\n className=\"absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 transition-colors\"\n >\n \n \n )}\n
    \n );\n })}\n
    \n
    \n\n
    \n

    \n Add suggested competitors\n

    \n\n {isLoadingCompetitors ? (\n
    \n \n

    Loading competitor suggestions...

    \n

    Analyzing your client's market

    \n
    \n ) : (\n
    \n {suggestedCompetitors.map((competitor, index) => (\n {\n console.log('Button clicked for:', competitor);\n addSuggestedCompetitor(competitor);\n }}\n className=\"px-4 py-3 text-left border border-gray-300 rounded-md hover:bg-gray-50 hover:border-indigo-300 transition-colors disabled:opacity-50 disabled:cursor-not-allowed\"\n disabled={competitors.length >= 4 || isCreatingProject}\n >\n
    {competitor}
    \n \n ))}\n
    \n )}\n
    \n
    \n\n {showModal && (\n
    \n
    \n
    \n

    Competitor Information

    \n \n \n \n
    \n\n {isLoadingCompetitorDetails ? (\n
    \n \n

    Loading Competitor Details

    \n

    \n Getting domain and brand information for {modalData.name}...\n

    \n
    \n ) : (\n <>\n
    \n
    \n \n handleModalInputChange('name', e.target.value)}\n />\n
    \n\n
    \n \n
    \n \n https://\n \n handleModalInputChange('domain', e.target.value)}\n />\n
    \n
    \n\n
    \n \n
    \n handleModalInputChange('brandInput', e.target.value)}\n onKeyPress={handleModalKeyPress}\n disabled={modalData.brands.length >= 5}\n />\n = 5\n ? 'bg-gray-100 text-gray-400 cursor-not-allowed'\n : 'bg-indigo-600 text-white hover:bg-indigo-700'\n }`}\n onClick={addBrandInModal}\n disabled={modalData.brands.length >= 5 || !modalData.brandInput.trim()}\n >\n Add\n \n
    \n

    \n You can add multiple brands by separating them with commas\n

    \n
    \n\n
    \n \n {modalData.brands.length > 0 ? (\n
    \n {modalData.brands.map((brand, index) => (\n \n {brand}\n removeBrandFromModal(brand)}\n >\n \n \n \n ))}\n
    \n ) : (\n

    No brands added yet

    \n )}\n
    \n
    \n\n
    \n \n Cancel\n \n \n Add\n \n
    \n \n )}\n
    \n
    \n )}\n\n
    \n \n Back\n \n \n {isCreatingProject ? (\n <>\n \n Creating Project...\n \n ) : isLoadingCompetitors ? (\n 'Loading...'\n ) : (\n 'Create Project'\n )}\n \n
    \n
    \n
    \n );\n};\n\nexport default Competitors;", "// app/javascript/components/Clients/ClientLayout.jsx\n//\n// Shared layout for all client-scoped pages.\n// Sidebar visual treatment matches the Visto Direct prototype:\n// - slate-900 dark nav (#0f172a)\n// - 3px accent left bar on active item\n// - accent300 active icon, slate-400 inactive\n// - VistoIris mark + company name at top\n// - \"All clients\" back link for org users (not direct users)\n// - No nav locking \u2014 each page handles its own empty state\n\nimport React, { useState, useEffect, useContext, useCallback, useRef } from 'react';\nimport { useParams, useNavigate, useLocation, Link, Outlet, useOutletContext } from 'react-router-dom';\nimport { AuthContext } from '../../context/AuthContext';\nimport axios from '../AxiosConfig';\n\nimport {\n LayoutDashboard, Compass, Layers, Settings, FileText,\n ChevronLeft, ChevronDown, Check, Briefcase, Loader, AlertCircle, ArrowLeft, Target,\n BarChart2, CalendarClock, Users, LogOut, HelpCircle,\n UserCircle, Link2\n} from 'lucide-react';\n\n// \u2500\u2500 Design tokens \u2014 matching prototype \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst T = {\n navBg: \"#0f172a\",\n navBorder: \"#1e293b\",\n navActive: \"#1e293b\",\n navText: \"#cbd5e1\",\n navTextDim: \"#94a3b8\",\n navHeading: \"#64748b\",\n\n accent300: \"#a5a3f3\",\n accent500: \"#4f46e5\",\n\n surface: \"#ffffff\",\n neutral50: \"#f8fafc\",\n neutral200: \"#e2e8f0\",\n neutral500: \"#64748b\",\n neutral900: \"#0f172a\",\n\n vistoCyan: \"#29C0F3\",\n vistoBlue: \"#0C7CEC\",\n vistoPale: \"#E1F0FF\",\n\n red: \"#ef4444\",\n indigo: \"#4f46e5\",\n // \u2500\u2500 impersonation banner \u2500\u2500\n amber50: \"#fffbeb\",\n amber700: \"#b45309\",\n amberBorder: \"#fcd34d\",\n muted: \"#64748b\",\n faint: \"#94a3b8\",\n text: \"#0f172a\",\n border: \"#e2e8f0\",\n bg: \"#f7f7f8\",\n};\n\nconst HEADER_HEIGHT = 52;\nconst SIDEBAR_WIDTH = 236;\nconst SIDEBAR_COLLAPSED = 64;\n\n// \u2500\u2500 VistoIris \u2014 the real V mark from the prototype \u2500\u2500\u2500\u2500\u2500\u2500\u2500\nfunction VistoIris({ size = 20 }) {\n const w = Math.round((size * 61) / 53);\n return (\n \n \n \n \n \n \n \n );\n}\n\n// \u2500\u2500 Sidebar nav items \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst NAV_ITEMS = [\n { id: \"home\", label: \"Home\", Icon: LayoutDashboard },\n { id: \"strategy\", label: \"Strategy\", Icon: Compass },\n { id: \"work\", label: \"Work\", Icon: Layers },\n { id: \"results\", label: \"Results\", Icon: BarChart2 },\n // Journalist replies sent from the client's connected Gmail. Only shown\n // once the feature is on for the org and Gmail is connected (or a reply\n // has already gone out): client.pr_replies_visible.\n { id: \"pr-replies\", label: \"Backlinks\", Icon: Link2, onlyIf: \"pr_replies_visible\" },\n { id: \"weekly\", label: \"Bi-Weekly Update\", Icon: CalendarClock },\n { id: \"settings\", label: \"Settings\", Icon: Settings },\n { id: \"help\", label: \"Help\", Icon: HelpCircle },\n];\n\n// Sections restricted when a client is disabled. The nav stays complete \u2014\n// clicking one of these shows a disabled notice in the main area instead\n// of the section (the v2 API also 403s them as a deep-link backstop).\nconst RESTRICTED_WHEN_DISABLED = [\"work\", \"results\", \"weekly\"];\n\nfunction navPath(id, clientId) {\n if (id === \"home\") return `/clients/${clientId}`;\n if (id === \"help\") return \"/help\";\n return `/clients/${clientId}/${id}`;\n}\n\n// \u2500\u2500 Sidebar (expanded) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nfunction SidebarExpanded({ client, clientId, activeId, user, onCollapse }) {\n return (\n \n );\n}\n\n// \u2500\u2500 Sidebar (collapsed) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nfunction SidebarCollapsed({ client, clientId, activeId, user, onExpand }) {\n return (\n \n );\n}\n\n// \u2500\u2500 User avatar dropdown \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// How long ago, in the shortest words that still read.\nfunction agoLabel(ts) {\n const m = Math.round((Date.now() - new Date(ts).getTime()) / 60000);\n if (m < 1) return 'just now';\n if (m < 60) return `${m}m ago`;\n const h = Math.round(m / 60);\n if (h < 24) return `${h}h ago`;\n return `${Math.round(h / 24)}d ago`;\n}\n\nconst NOTIFICATION_POLL_MS = 60000;\n\nfunction UserMenu({ user, navigate, onLogout }) {\n // Team settings has no client in its URL, so its Back button is told\n // which page it was opened from.\n const location = useLocation();\n const [open, setOpen] = useState(false);\n const menuRef = useRef(null);\n\n // In-app notifications: a dot on the avatar while anything is unread, and\n // the newest few in the menu. Opening the menu marks everything seen.\n const [unread, setUnread] = useState(0);\n const [recent, setRecent] = useState([]);\n const fetchNotifications = useCallback(async () => {\n try {\n const { data } = await axios.get('/api/v2/notifications', { params: { limit: 8 } });\n setUnread(data.unread_count || 0);\n setRecent(data.notifications || []);\n } catch { /* leave what we had */ }\n }, []);\n useEffect(() => {\n if (!user) return;\n fetchNotifications();\n const t = setInterval(fetchNotifications, NOTIFICATION_POLL_MS);\n return () => clearInterval(t);\n }, [user, fetchNotifications]);\n useEffect(() => {\n if (!open) return;\n fetchNotifications();\n if (unread > 0) {\n axios.post('/api/v2/notifications/seen').then(() => setUnread(0)).catch(() => {});\n }\n }, [open]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const initials = (() => {\n if (user?.name) {\n const parts = user.name.trim().split(/\\s+/);\n return (parts[0]?.[0] || '') + (parts[1]?.[0] || '');\n }\n if (user?.email) return user.email[0];\n return '?';\n })().toUpperCase();\n\n // Close on outside click\n useEffect(() => {\n if (!open) return;\n const handler = (e) => {\n if (menuRef.current && !menuRef.current.contains(e.target)) setOpen(false);\n };\n document.addEventListener(\"mousedown\", handler);\n return () => document.removeEventListener(\"mousedown\", handler);\n }, [open]);\n\n const menuItemStyle = {\n display: \"flex\", alignItems: \"center\", gap: 8,\n width: \"100%\", padding: \"8px 12px\",\n background: \"transparent\", border: \"none\", borderRadius: 0,\n fontSize: 13, color: T.neutral900,\n cursor: \"pointer\", fontFamily: \"inherit\",\n textDecoration: \"none\",\n transition: \"background 0.1s ease\",\n };\n\n return (\n
    \n setOpen(o => !o)}\n aria-label=\"Account menu\"\n title={user?.name || user?.email || \"Account\"}\n style={{\n width: 30, height: 30, borderRadius: \"50%\",\n background: T.accent500, color: T.surface,\n border: \"none\", cursor: \"pointer\",\n fontSize: 11, fontWeight: 500,\n fontFamily: \"system-ui, -apple-system, sans-serif\",\n display: \"flex\", alignItems: \"center\", justifyContent: \"center\",\n flexShrink: 0,\n }}\n >\n {initials}\n \n {unread > 0 && (\n \n )}\n\n {open && (\n <>\n {/* Backdrop */}\n
    setOpen(false)} />\n\n {/* Dropdown */}\n
    0 ? 300 : 200, background: T.surface,\n borderRadius: 8, border: `1px solid ${T.neutral200}`,\n boxShadow: \"0 4px 16px rgba(0,0,0,0.10), 0 1px 3px rgba(0,0,0,0.06)\",\n zIndex: 50, overflow: \"hidden\",\n padding: \"4px 0\",\n }}>\n {/* User info */}\n
    \n {user?.name && (\n
    \n {user.name}\n
    \n )}\n
    \n {user?.email}\n
    \n
    \n\n {/* Recent notifications */}\n {recent.length > 0 && (\n
    \n
    Recent
    \n {recent.map(n => (\n setOpen(false)}\n style={{ ...menuItemStyle, alignItems: \"flex-start\", gap: 8, padding: \"6px 12px\" }}\n onMouseEnter={e => e.currentTarget.style.background = T.neutral50}\n onMouseLeave={e => e.currentTarget.style.background = \"transparent\"}\n >\n \n \n {n.title}\n \n {n.client_name ? `${n.client_name} \u00B7 ` : ''}{agoLabel(n.created_at)}\n \n \n \n ))}\n
    \n )}\n\n {/* Team Settings */}\n setOpen(false)}\n style={menuItemStyle}\n onMouseEnter={e => e.currentTarget.style.background = T.neutral50}\n onMouseLeave={e => e.currentTarget.style.background = \"transparent\"}\n >\n \n Team settings\n \n\n {/* My account */}\n setOpen(false)}\n style={menuItemStyle}\n onMouseEnter={e => e.currentTarget.style.background = T.neutral50}\n onMouseLeave={e => e.currentTarget.style.background = \"transparent\"}\n >\n \n My account\n \n\n {/* Divider */}\n
    \n\n {/* Log out */}\n { setOpen(false); onLogout(); }}\n style={menuItemStyle}\n onMouseEnter={e => e.currentTarget.style.background = T.neutral50}\n onMouseLeave={e => e.currentTarget.style.background = \"transparent\"}\n >\n \n Log out\n \n
    \n \n )}\n
    \n );\n}\n\n// \u2500\u2500 Client switcher (impersonating admins only) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Staff servicing several accounts hands-on (professional services) used to\n// return to admin and sign in as the next client's user every time. The\n// switcher lists every client flagged professional_services_enabled and\n// swaps the session server-side, keeping the admin claim so \"Return to\n// admin\" still works afterwards.\nfunction ClientSwitcher({ client, clientId, onSwitch, switching }) {\n const [clients, setClients] = useState([]);\n const [open, setOpen] = useState(false);\n const [loadError, setLoadError] = useState('');\n const ref = useRef(null);\n\n useEffect(() => {\n let cancelled = false;\n axios.get('/api/admin/professional_services/clients')\n .then(res => { if (!cancelled) setClients(res.data.clients || []); })\n .catch(err => { if (!cancelled) setLoadError(err.response?.data?.error || 'Could not load clients'); });\n return () => { cancelled = true; };\n }, []);\n\n useEffect(() => {\n if (!open) return;\n const onDown = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };\n const onKey = e => { if (e.key === 'Escape') setOpen(false); };\n document.addEventListener('mousedown', onDown);\n document.addEventListener('keydown', onKey);\n return () => { document.removeEventListener('mousedown', onDown); document.removeEventListener('keydown', onKey); };\n }, [open]);\n\n if (loadError || clients.length === 0) return null;\n\n const currentId = Number(clientId);\n const current = clients.find(c => c.id === currentId);\n const label = current?.name || client?.name || 'Switch client';\n\n return (\n
    \n setOpen(o => !o)}\n disabled={switching}\n title=\"Switch to another client you service\"\n aria-haspopup=\"listbox\"\n aria-expanded={open}\n style={{\n display: \"inline-flex\", alignItems: \"center\", gap: 6,\n height: 30, padding: \"0 10px 0 12px\", maxWidth: 240,\n background: T.surface, color: T.neutral900,\n border: `0.5px solid ${T.neutral200}`, borderRadius: 6,\n fontSize: 12, fontWeight: 500, fontFamily: \"inherit\",\n cursor: switching ? \"default\" : \"pointer\",\n opacity: switching ? 0.6 : 1,\n }}\n >\n {switching\n ? \n : }\n \n {switching ? \"Switching\u2026\" : label}\n \n \n \n\n {open && (\n
    \n
    \n Clients you service\n
    \n {clients.map(c => {\n const active = c.id === currentId;\n return (\n { setOpen(false); if (!active) onSwitch(c.id); }}\n style={{\n display: \"flex\", alignItems: \"center\", gap: 8, width: \"100%\",\n padding: \"7px 10px\", borderRadius: 6, border: \"none\",\n background: active ? T.neutral50 : \"transparent\",\n cursor: active ? \"default\" : \"pointer\", textAlign: \"left\", fontFamily: \"inherit\",\n }}\n onMouseEnter={e => { if (!active) e.currentTarget.style.background = T.neutral50; }}\n onMouseLeave={e => { if (!active) e.currentTarget.style.background = \"transparent\"; }}\n >\n
    \n
    \n {c.name}{c.disabled ? \" (disabled)\" : \"\"}\n
    \n
    \n {[c.domain, c.sign_in_email].filter(Boolean).join(\" \u00B7 \")}\n
    \n
    \n {active && }\n \n );\n })}\n
    \n )}\n
    \n );\n}\n\n// \u2500\u2500 Header \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nfunction AppHeader({ client, clientId, headerBack, navigate, user, impersonation, onLogout }) {\n const { isImpersonating, adminUser, isReturning, onReturn, onSwitchClient, isSwitching } = impersonation || {};\n\n return (\n
    \n {headerBack ? (\n navigate(headerBack.to)}\n style={{\n display: \"inline-flex\", alignItems: \"center\", gap: 4,\n background: \"transparent\", border: \"none\", padding: \"4px 8px 4px 0\",\n margin: 0, cursor: \"pointer\", fontFamily: \"inherit\",\n fontSize: 13, color: T.muted, borderRadius: 4,\n }}\n onMouseEnter={e => e.currentTarget.style.color = T.neutral900}\n onMouseLeave={e => e.currentTarget.style.color = T.muted}\n >\n \n {headerBack.label}\n \n ) : (\n
    \n

    \n {client?.name || \"Client\"}\n

    \n {client?.domain && (\n <>\n \u00B7\n \n {client.domain}\n \n \n )}\n
    \n )}\n\n
    \n {/* Quick switch between serviced clients \u2014 only while impersonating */}\n {isImpersonating && adminUser && (\n \n )}\n\n {/* Return to admin \u2014 only while impersonating */}\n {isImpersonating && adminUser && (\n \n \n \n {isReturning ? \"Returning\u2026\" : `Return to ${adminUser.email}`}\n \n \n )}\n\n \n
    \n
    \n );\n}\n\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n// LAYOUT\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\nconst ClientLayout = () => {\n const { clientId } = useParams();\n const { user, isImpersonating, adminUser, returnToAdminUser, switchImpersonatedClient, logout } = useContext(AuthContext);\n const navigate = useNavigate();\n const location = useLocation();\n const [headerBack, setHeaderBack] = useState(null);\n const [isReturning, setIsReturning] = useState(false);\n const [isSwitching, setIsSwitching] = useState(false);\n\n const [client, setClient] = useState(null);\n const [clientLoading, setClientLoading] = useState(true);\n const [clientError, setClientError] = useState('');\n const [navCollapsed, setNavCollapsed] = useState(false);\n\n const [assessmentStarted, setAssessmentStarted] = useState(false);\n const [strategyReady, setStrategyReady] = useState(false);\n const [metricsCollected, setMetricsCollected] = useState(false);\n\n const mainRef = useRef(null);\n\n useEffect(() => {\n if (mainRef.current) mainRef.current.scrollTop = 0;\n }, [location.pathname]);\n\n useEffect(() => {\n if (user && !user.seo_platform_enabled) navigate('/', { replace: true });\n }, [user, navigate]);\n\n useEffect(() => {\n if (!clientId || !user?.seo_platform_enabled) return;\n let cancelled = false;\n const load = async () => {\n setClientLoading(true);\n try {\n const res = await axios.get(`/api/v2/clients/${clientId}`);\n if (cancelled) return;\n setClient(res.data);\n setClientError('');\n } catch (err) {\n if (cancelled) return;\n setClientError(err.response?.data?.error || 'Failed to load client');\n } finally {\n if (!cancelled) setClientLoading(false);\n }\n };\n load();\n return () => { cancelled = true; };\n }, [clientId, user]);\n\n // Check assessment + metrics status (still useful for child components)\n useEffect(() => {\n if (!clientId) return;\n const check = async () => {\n try {\n const { data } = await axios.get(`/api/v2/clients/${clientId}/assessment`);\n const status = data.assessment?.status;\n setAssessmentStarted(!!status);\n setStrategyReady(['approved', 'executing', 'completed'].includes(status));\n } catch {\n setAssessmentStarted(false);\n setStrategyReady(false);\n }\n\n try {\n const { data } = await axios.get(`/api/v2/clients/${clientId}/metrics/status`);\n setMetricsCollected(!!data.has_data);\n } catch {\n setMetricsCollected(false);\n }\n };\n check();\n }, [clientId]);\n\n const refetchClient = useCallback(async () => {\n if (!clientId) return;\n try {\n const res = await axios.get(`/api/v2/clients/${clientId}`);\n setClient(res.data);\n } catch {}\n }, [clientId]);\n\n const handleReturnToAdmin = useCallback(async () => {\n setIsReturning(true);\n try {\n await returnToAdminUser();\n window.location.href = '/admin';\n } catch (error) {\n console.error('Failed to return to admin user:', error);\n // 401 = the session predates the admin claim (signed in as a user\n // before 2026-11-04); the app has already cleared it.\n alert(error.response?.status === 401\n ? 'This session was started before the latest update, so it cannot return to admin. Sign in again as yourself and use \"Sign in as\" once more.'\n : 'Failed to return to admin account. Please try again.');\n } finally {\n setIsReturning(false);\n }\n }, [returnToAdminUser]);\n\n const handleLogout = useCallback(async () => {\n try {\n if (typeof logout === 'function') {\n await logout();\n } else {\n // Fallback: clear localStorage and redirect\n localStorage.removeItem('user');\n localStorage.removeItem('token');\n localStorage.removeItem('adminUser');\n }\n } catch (e) {\n localStorage.removeItem('user');\n localStorage.removeItem('token');\n localStorage.removeItem('adminUser');\n }\n window.location.href = '/sign_in';\n }, [logout]);\n\n const handleSwitchClient = useCallback(async (targetClientId) => {\n setIsSwitching(true);\n try {\n const target = await switchImpersonatedClient(targetClientId);\n if (!target) throw new Error('switch refused');\n setHeaderBack(null);\n navigate(`/clients/${target.id}`);\n } catch (error) {\n console.error('Failed to switch client:', error);\n alert(error.response?.data?.error || 'Failed to switch client. Please try again.');\n } finally {\n setIsSwitching(false);\n }\n }, [switchImpersonatedClient, navigate]);\n\n const impersonation = {\n isImpersonating, adminUser, isReturning, onReturn: handleReturnToAdmin,\n onSwitchClient: handleSwitchClient, isSwitching,\n };\n\n // Active nav resolution\n const path = location.pathname;\n let activeId = \"home\";\n if (path.includes(\"/strategy\")) activeId = \"strategy\";\n else if (path.includes(\"/work\")) activeId = \"work\";\n else if (path.includes(\"/results\")) activeId = \"results\";\n else if (path.includes(\"/pr-replies\")) activeId = \"pr-replies\";\n else if (path.includes(\"/weekly\")) activeId = \"weekly\";\n else if (path.includes(\"/settings\")) activeId = \"settings\";\n else if (path.includes(\"/plan\")) activeId = \"work\";\n else if (path.includes(\"/metrics\")) activeId = \"results\";\n\n if (clientLoading) {\n return (\n
    \n
    \n \n Loading client\u2026\n
    \n \n
    \n );\n }\n\n if (clientError) {\n return (\n
    \n
    \n
    \n \n
    \n

    Unable to load client

    \n

    {clientError}

    \n {isImpersonating && adminUser ? (\n \n \n {isReturning ? \"Returning\u2026\" : `Return to ${adminUser.email}`}\n \n ) : (\n \n \u2190 Back to workspace\n \n )}\n
    \n
    \n );\n }\n\n const sidebarProps = { client, clientId, activeId, user };\n\n return (\n
    \n \n\n {navCollapsed ? (\n
    \n setNavCollapsed(false)} />\n
    \n ) : (\n
    \n setNavCollapsed(true)} />\n
    \n )}\n\n
    \n \n
    \n\n
    \n {client?.disabled && (\n
    \n This client is currently disabled \u2014 the strategy stays available, but Work, Results, and Bi-Weekly updates are paused. Reach out to the Visto team to re-enable it.\n
    \n )}\n {client?.disabled && RESTRICTED_WHEN_DISABLED.includes(activeId) ? (\n
    \n
    \n
    \n This client is disabled\n
    \n
    \n Work, Results, and Bi-Weekly updates are paused while this client is disabled.\n The strategy is still available. Reach out to the Visto team to re-enable this client.\n
    \n navigate(navPath(\"strategy\", clientId))}\n style={{\n padding: \"9px 18px\", borderRadius: 8, border: \"none\", cursor: \"pointer\",\n background: \"#4F46E5\", color: \"#fff\", fontSize: 13, fontWeight: 500,\n }}\n >\n View strategy\n \n
    \n
    \n ) : (\n \n )}\n
    \n
    \n );\n};\n\nexport const useClientLayout = () => useOutletContext();\n\nexport default ClientLayout;", "// app/javascript/components/Clients/ClientDashboard.jsx\n//\n// Home page state machine:\n// State 1-2: Pre-strategy \u2014 pick Google account, create strategy CTA\n// State 3: Building \u2014 assessment running (inline banner)\n// State 5: Live \u2014 this week's work, metrics, what Visto is working on\n//\n// Google connections use the org-pool model: multiple accounts can be\n// connected to the org, and the user picks which one to use for this client.\n\nimport React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';\nimport { useNavigate, Link } from 'react-router-dom';\nimport axios from '../AxiosConfig';\nimport { useClientLayout } from './ClientLayout';\nimport {\n ArrowRight, AlertTriangle, Check, Link2,\n Loader, Search, Compass, Layers, Plus,\n CheckCircle2, ChevronRight, TrendingUp,\n ListChecks, ArrowUpRight, ArrowDownRight, Minus, Eye,\n} from 'lucide-react';\n\nconst T = {\n surface: \"#ffffff\", neutral50: \"#f8fafc\", neutral100: \"#f1f5f9\",\n neutral200: \"#e2e8f0\", neutral300: \"#cbd5e1\", neutral400: \"#94a3b8\",\n neutral500: \"#64748b\", neutral600: \"#475569\", neutral700: \"#334155\",\n neutral900: \"#0f172a\",\n accent50: \"#eef2ff\", accent100: \"#e0e2fc\", accent500: \"#4f46e5\",\n accent700: \"#3730a3\",\n positive50: \"#f0fdf4\", positive500: \"#16a34a\", positive600: \"#059669\", positive700: \"#15803d\",\n caution50: \"#fffbeb\", caution100: \"#fef3c7\", caution500: \"#d97706\",\n caution700: \"#b45309\",\n critical500: \"#dc2626\", critical600: \"#dc2626\",\n shadowXs: \"0 1px 2px rgba(0,0,0,0.05)\",\n};\n\nconst FONT = \"system-ui, -apple-system, sans-serif\";\nconst R = { card: 8, tile: 6, field: 6 };\n\n// \u2500\u2500 Category colors \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst CAT_COLORS = {\n content: { dot: \"#0d9488\" },\n technical: { dot: \"#0891b2\" },\n onpage: { dot: \"#7c3aed\" },\n geo: { dot: \"#ea580c\" },\n links: { dot: \"#db2777\" },\n backlinks: { dot: \"#2563eb\" },\n};\nfunction catColor(c) { return CAT_COLORS[c]?.dot || T.neutral400; }\n\n// \u2500\u2500 Status chips \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst STATUS_CHIP = {\n \"needs-input\": { label: \"Needs input\", bg: \"#fef3c7\", color: \"#b45309\" },\n \"in-progress\": { label: \"In progress\", bg: \"#e0e2fc\", color: \"#3730a3\" },\n \"with-dev\": { label: \"Ready to deploy\", bg: \"#dbeafe\", color: \"#1d4ed8\" },\n \"completed\": { label: \"Completed\", bg: \"#f1f5f9\", color: \"#64748b\" },\n};\n\nfunction deriveInitiativeStatus(init) {\n if ((init.actionable_tasks || []).length > 0) return \"needs-input\";\n if (init.status === \"completed\") return \"completed\";\n return \"in-progress\";\n}\n\nfunction GoogleG({ size = 16 }) {\n return (\n \n \n \n \n \n \n );\n}\n\nfunction fmtNum(n) {\n if (n == null) return \"\u2014\";\n if (typeof n !== \"number\") return String(n);\n if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;\n if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;\n return n % 1 === 0 ? String(n) : n.toFixed(1);\n}\n\nconst POLL_INTERVAL = 5000;\n\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n// MAIN\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\nconst ClientDashboard = () => {\n const { client, clientId } = useClientLayout();\n const navigate = useNavigate();\n\n // Google pool state\n const [googleConnections, setGoogleConnections] = useState([]);\n const [assignedConnectionId, setAssignedConnectionId] = useState(null);\n const [googleLoading, setGoogleLoading] = useState(true);\n const [googleConnecting, setGoogleConnecting] = useState(false);\n const [googleAssigning, setGoogleAssigning] = useState(false);\n\n const [assessment, setAssessment] = useState(null);\n const [assessmentLoading, setAssessmentLoading] = useState(true);\n const [initiatives, setInitiatives] = useState(null);\n const [workItems, setWorkItems] = useState([]);\n const [stagedItems, setStagedItems] = useState([]); // deployments waiting for the client to publish\n const [completed, setCompleted] = useState([]); // notifications: what Visto finished recently\n const [workSummary, setWorkSummary] = useState(null);\n const [creating, setCreating] = useState(false);\n const [error, setError] = useState(null);\n const popupRef = useRef(null);\n const pollRef = useRef(null);\n\n const domain = client?.domain || client?.sites?.[0]?.domain;\n const googleConnected = !!assignedConnectionId;\n const assignedEmail = googleConnections.find(c => c.id === assignedConnectionId)?.google_account_email;\n\n // \u2500\u2500 Load Google connections (org pool) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const fetchGoogleConnections = useCallback(async () => {\n if (!clientId) return;\n try {\n const { data } = await axios.get(`/api/v2/clients/${clientId}/google_connections`);\n setGoogleConnections(data.connections || []);\n setAssignedConnectionId(data.assigned_connection_id);\n } catch (err) {\n console.error('Failed to load Google connections:', err);\n } finally {\n setGoogleLoading(false);\n }\n }, [clientId]);\n\n useEffect(() => { fetchGoogleConnections(); }, [fetchGoogleConnections]);\n\n // \u2500\u2500 Assessment \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const fetchAssessment = useCallback(async () => {\n try { const { data } = await axios.get(`/api/v2/clients/${clientId}/assessment`); setAssessment(data.assessment); }\n catch (err) { if (err.response?.status === 404) setAssessment(null); }\n finally { setAssessmentLoading(false); }\n }, [clientId]);\n\n useEffect(() => { if (clientId) fetchAssessment(); }, [fetchAssessment]);\n\n // \u2500\u2500 Initiatives \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const fetchInitiatives = useCallback(async () => {\n try { const { data } = await axios.get(`/api/v2/clients/${clientId}/initiatives`); setInitiatives(data.initiatives || data || []); }\n catch { setInitiatives([]); }\n }, [clientId]);\n\n // \u2500\u2500 Work items \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const fetchWorkItems = useCallback(async () => {\n try {\n const { data } = await axios.get(`/api/v2/clients/${clientId}/work_items`, { params: { limit: 5 } });\n // Items Visto is staging, has staged, or has published live are shown\n // in their own section (or are done), not in the copy-it-yourself list.\n setWorkItems((data.work_items || data.items || data || []).filter(i => !i.deployment?.active).slice(0, 5));\n // Capture total from the items response as a fallback\n if (data.total && !workSummary?.total) setWorkSummary(prev => prev || { total: data.total });\n } catch { setWorkItems([]); }\n try {\n const { data } = await axios.get(`/api/v2/clients/${clientId}/work_items/summary`);\n setWorkSummary(data);\n } catch {}\n try {\n const { data } = await axios.get(`/api/v2/clients/${clientId}/work_items`, { params: { deployment_status: 'staged' } });\n setStagedItems(data.items || []);\n } catch { setStagedItems([]); }\n try {\n const { data } = await axios.get('/api/v2/notifications', { params: { client_id: clientId, days: 14, limit: 20 } });\n // Staged items have their own section above; everything that finished goes here.\n setCompleted((data.notifications || []).filter(n => n.kind !== 'staged'));\n } catch { setCompleted([]); }\n }, [clientId]);\n\n useEffect(() => {\n if (!assessment) return;\n if (['pending', 'analyzing', 'failed'].includes(assessment.status)) return;\n fetchInitiatives();\n fetchWorkItems();\n }, [assessment?.status, fetchInitiatives, fetchWorkItems]);\n\n // \u2500\u2500 Poll while building \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n useEffect(() => {\n if (!assessment || !['pending', 'analyzing'].includes(assessment.status)) return;\n const interval = setInterval(fetchAssessment, POLL_INTERVAL);\n return () => clearInterval(interval);\n }, [assessment?.status, fetchAssessment]);\n\n // \u2500\u2500 Derived state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const assessmentDone = assessment && !['pending', 'analyzing', 'failed'].includes(assessment.status);\n const assessmentRunning = assessment && ['pending', 'analyzing'].includes(assessment.status);\n const isLive = assessmentDone && initiatives !== null && initiatives.length > 0;\n\n const activeInitiatives = useMemo(() =>\n (initiatives || []).filter(i => ![\"pending\"].includes(i.status)),\n [initiatives]);\n\n const totalWorkItems = workSummary?.total || workItems.length;\n\n // \u2500\u2500 OAuth popup handlers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n useEffect(() => {\n const handler = (event) => {\n if (event.origin !== window.location.origin || !event.data) return;\n if (event.data.connected === 'google') {\n if (pollRef.current) clearInterval(pollRef.current);\n setGoogleConnecting(false);\n fetchGoogleConnections();\n } else if (event.data.error) {\n setError(event.data.error);\n setGoogleConnecting(false);\n }\n };\n window.addEventListener('message', handler);\n return () => window.removeEventListener('message', handler);\n }, [fetchGoogleConnections]);\n\n useEffect(() => { return () => { if (pollRef.current) clearInterval(pollRef.current); }; }, []);\n\n const handleConnectNew = async () => {\n setGoogleConnecting(true);\n setError(null);\n try {\n const { data } = await axios.post(`/api/v2/clients/${clientId}/google_connections/authorize`);\n const w = 520, h = 680;\n const left = window.screenX + (window.outerWidth - w) / 2;\n const top = window.screenY + (window.outerHeight - h) / 2;\n const popup = window.open(data.authorize_url, 'google_oauth',\n `width=${w},height=${h},left=${left},top=${top},toolbar=no,menubar=no`);\n popupRef.current = popup;\n pollRef.current = setInterval(() => {\n if (popup && popup.closed) {\n clearInterval(pollRef.current);\n pollRef.current = null;\n setGoogleConnecting(false);\n fetchGoogleConnections();\n }\n }, 500);\n } catch { setError('Failed to start Google authorization'); setGoogleConnecting(false); }\n };\n\n const handleAssign = async (connectionId) => {\n if (connectionId === assignedConnectionId) return;\n setGoogleAssigning(true);\n setError(null);\n try {\n const { data } = await axios.patch(\n `/api/v2/clients/${clientId}/google_connections/assign`,\n { connection_id: connectionId }\n );\n setAssignedConnectionId(data.assigned_connection_id);\n } catch (err) {\n setError(err.response?.data?.error || 'Failed to assign connection');\n } finally {\n setGoogleAssigning(false);\n }\n };\n\n const handleCreateStrategy = async () => {\n setCreating(true); setError(null);\n try { const { data } = await axios.post(`/api/v2/clients/${clientId}/assessment`); setAssessment(data.assessment); }\n catch (err) { setError(err.response?.data?.error || 'Failed to create assessment'); }\n finally { setCreating(false); }\n };\n\n // \u2500\u2500 Loading \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (assessmentLoading || googleLoading) {\n return (\n
    \n \n \n
    \n );\n }\n\n // \u2500\u2500 Redirect to strategy if pending approval \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (assessmentDone && initiatives !== null && initiatives.length === 0 && assessment.status === \"pending_approval\") {\n navigate(`/clients/${clientId}/strategy`, { replace: true });\n return null;\n }\n\n // \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n // LIVE STATE\n // \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\n if (isLive) {\n const workingOn = activeInitiatives.filter(i => i.status !== \"completed\");\n\n return (\n
    \n
    \n
    \n You have {totalWorkItems} task{totalWorkItems === 1 ? '' : 's'} ready to implement this week.\n
    \n \n \n \n \n \n {workingOn.length > 0 && (\n
    \n
    \n
    What Visto is working on
    \n navigate(`/clients/${clientId}/strategy`)} style={{ fontSize: 12, color: T.neutral600, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 4 }}>See all \n
    \n
    \n {workingOn.map((init, i) => {\n const st = deriveInitiativeStatus(init);\n const chip = STATUS_CHIP[st] || STATUS_CHIP[\"in-progress\"];\n const cat = init.config?.category || init.category || \"content\";\n const name = init.config?.name || init.scope;\n const sub = st === \"needs-input\"\n ? `${(init.actionable_tasks || []).length} step${(init.actionable_tasks || []).length === 1 ? '' : 's'} awaiting your review`\n : `${init.completed_tasks || 0} of ${init.total_tasks || 0} steps`;\n return (\n
    navigate(`/clients/${clientId}/strategy`)}\n style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '13px 16px', cursor: 'pointer', borderTop: i === 0 ? 'none' : `0.5px solid ${T.neutral100}` }}>\n \n
    \n
    {name}
    \n
    {sub}
    \n
    \n {chip.label}\n
    \n );\n })}\n
    \n
    \n )}\n
    \n
    \n );\n }\n\n // \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n // STATES 1-3: Pre-strategy / Building\n // \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\n const hasConnections = googleConnections.length > 0;\n\n return (\n
    \n \n
    \n
    \n
    Getting started
    \n
    Build your SEO strategy
    \n
    \n Visto analyzes {domain || 'your site'} end to end, then proposes a strategy and a full project plan it runs on your behalf. Connect Google to begin.\n
    \n
    \n\n {/* \u2500\u2500 Google account picker card \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */}\n
    \n
    \n Google account\n \u00B7\n \n {googleConnected ? assignedEmail : (hasConnections ? 'Not selected' : 'No accounts connected')}\n \n
    \n\n {/* Connected accounts as selectable rows */}\n {googleConnections.map((conn) => {\n const isSelected = conn.id === assignedConnectionId;\n return (\n !googleAssigning && handleAssign(conn.id)}\n style={{\n display: 'flex', alignItems: 'center', gap: 14, padding: '12px 20px',\n cursor: googleAssigning ? 'wait' : 'pointer',\n borderBottom: `0.5px solid ${T.neutral100}`,\n background: isSelected ? T.accent50 : T.surface,\n transition: 'background 0.15s',\n }}\n onMouseEnter={e => { if (!isSelected) e.currentTarget.style.background = T.neutral50; }}\n onMouseLeave={e => { if (!isSelected) e.currentTarget.style.background = T.surface; }}\n >\n {/* Radio */}\n \n {isSelected && }\n \n\n {/* Google icon */}\n
    \n \n
    \n\n {/* Details */}\n
    \n
    {conn.google_account_email}
    \n
    \n {conn.scopes?.gsc && GSC}\n {conn.scopes?.ga4 && <>\u00B7GA4}\n {conn.client_count > 0 && (\n <>\u00B7{conn.client_count} client{conn.client_count === 1 ? '' : 's'}\n )}\n {conn.expired && (\n <>\u00B7Needs re-auth\n )}\n
    \n
    \n\n {isSelected && }\n
    \n );\n })}\n\n {/* Connect another */}\n { e.currentTarget.style.background = T.neutral50; }}\n onMouseLeave={e => { e.currentTarget.style.background = T.surface; }}\n >\n {/* spacer */}\n
    \n {googleConnecting\n ? \n : \n }\n
    \n
    \n
    \n {googleConnecting ? 'Opening Google\u2026' : 'Connect another Google account'}\n
    \n
    \n
    \n
    \n\n {/* CTA or building notice */}\n {assessmentRunning ? (\n
    \n \n
    \n
    Your strategy is being built
    \n
    This usually takes 2\u20133 hours. You'll be notified when it's ready.
    \n
    \n \n View progress \n \n
    \n ) : (\n
    \n \n
    \n )}\n {!assessmentRunning && !googleConnected && (\n
    \n \n {hasConnections ? 'Select a Google account above to build your strategy.' : 'Connect a Google account to build your strategy.'}\n
    \n )}\n {!assessmentRunning && error &&
    {error}
    }\n {(assessmentRunning || (googleConnected && !error)) &&
    }\n\n {/* What Visto does next */}\n
    \n
    What Visto does next
    \n
    \n {[\n { Icon: Search, title: \"Analyzes your site and market\", body: \"A full crawl, your ranking and traffic data, competitors, and AI-search visibility.\" },\n { Icon: Compass, title: \"Proposes a strategy\", body: \"A prioritized set of initiatives aimed at your fastest, highest-impact gaps \u2014 yours to confirm or adjust.\" },\n { Icon: Layers, title: \"Builds a work plan it runs\", body: \"Each confirmed initiative becomes tracked work Visto executes, surfacing only what needs your review.\" },\n ].map((row, idx, arr) => (\n
    \n \n \n \n
    \n
    {row.title}
    \n
    {row.body}
    \n
    \n
    \n ))}\n
    \n
    \n
    \n
    \n );\n};\n\n\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n// THIS WEEK'S WORK\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\n// Work items Visto has staged in the client's CMS and that wait for the\n// client to publish (docs/eng-plans/browser-deploy.md section 9). Hidden\n// when there are none, so clients without CMS access never see it.\nfunction StagedForReview({ items, clientId, navigate }) {\n if (!items || items.length === 0) return null;\n const cms = items[0]?.deployment?.platform_name || items[0]?.cms?.platform_name || 'your CMS';\n const age = (ts) => {\n if (!ts) return '';\n const h = Math.round((Date.now() - new Date(ts).getTime()) / 36e5);\n return h < 1 ? 'just now' : h < 24 ? `${h}h ago` : `${Math.round(h / 24)}d ago`;\n };\n return (\n
    \n
    \n \n Staged, ready for your review\n {items.length}\n Visto made these in {cms}. Nothing is live until you publish.\n
    \n {items.map((it) => (\n
    navigate(`/clients/${clientId}/work/${it.id}`)}\n style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 18px', cursor: 'pointer', borderTop: `0.5px solid ${T.neutral200}` }}>\n \n
    \n
    {it.headline || it.item_type}
    \n
    {it.url}{it.deployment?.staged_at ? ` \u00B7 staged ${age(it.deployment.staged_at)}` : ''}
    \n
    \n Review and publish\n \n
    \n ))}\n
    \n );\n}\n\n// What Visto finished for this client in the last two weeks: published,\n// undone, discarded, revised, and anything that failed with the reason.\n// Staged items are not here; they wait in StagedForReview above.\nfunction RecentlyCompleted({ items, clientId, navigate }) {\n if (!items || items.length === 0) return null;\n const age = (ts) => {\n const h = Math.round((Date.now() - new Date(ts).getTime()) / 36e5);\n return h < 1 ? 'just now' : h < 24 ? `${h}h ago` : `${Math.round(h / 24)}d ago`;\n };\n const failed = items.filter(n => n.kind === 'failed').length;\n return (\n
    \n
    \n \n Recently completed\n {items.length}\n {failed > 0 && {failed} need{failed === 1 ? 's' : ''} a look}\n What Visto did in the last two weeks.\n
    \n {items.map((n) => (\n
    navigate(`/clients/${clientId}${n.path || '/work'}`)}\n style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 18px', cursor: 'pointer', borderTop: `0.5px solid ${T.neutral200}` }}>\n \n
    \n
    {n.title}
    \n {n.detail &&
    {n.detail}
    }\n
    \n {age(n.created_at)}\n \n
    \n ))}\n
    \n );\n}\n\nfunction ThisWeeksWork({ items, total, clientId, navigate }) {\n if (!items || items.length === 0) return null;\n\n return (\n
    \n
    \n \n Ready to implement \u2014 copy each into your site and mark it complete\n
    \n {items.map((it) => {\n const cat = it.category || \"content\";\n return (\n
    navigate(`/clients/${clientId}/work`)}\n style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '12px 18px', cursor: 'pointer', borderTop: `0.5px solid ${T.neutral200}` }}>\n \n
    \n
    {it.headline || it.item_type || it.title}
    \n
    {it.url}
    \n
    \n \n
    \n );\n })}\n {total > items.length && (\n
    navigate(`/clients/${clientId}/work`)}\n style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5, padding: '11px 18px', cursor: 'pointer', borderTop: `0.5px solid ${T.neutral200}`, fontSize: 12.5, color: T.neutral600 }}>\n View all {total} in Work \n
    \n )}\n
    \n );\n}\n\n\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n// HOME METRICS STRIP\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n// Fetches the 4 client health KPIs from /metrics and renders\n// compact cards with current value + week-over-week change.\n// Clicking any card navigates to the full Results page.\n\nfunction HomeMetricsStrip({ clientId, navigate }) {\n const [kpis, setKpis] = useState(null);\n const [loading, setLoading] = useState(true);\n\n useEffect(() => {\n let cancelled = false;\n const load = async () => {\n try {\n const { data } = await axios.get(`/api/v2/clients/${clientId}/metrics`);\n if (!cancelled) setKpis(data.client_kpis || []);\n } catch {}\n finally { if (!cancelled) setLoading(false); }\n };\n load();\n return () => { cancelled = true; };\n }, [clientId]);\n\n // Don't render anything while loading or if no KPIs exist\n if (loading || !kpis || kpis.length === 0) return null;\n\n return (\n
    \n
    \n
    \n Performance\n
    \n navigate(`/clients/${clientId}/results`)}\n style={{ fontSize: 12, color: T.neutral600, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 4 }}\n >\n View details \n \n
    \n
    \n {kpis.map((kpi) => (\n navigate(`/clients/${clientId}/results`)}\n />\n ))}\n
    \n
    \n );\n}\n\nfunction HomeMetricCard({ kpi, onClick }) {\n const current = kpi.current_value;\n const change = kpi.change;\n const isUp = change?.direction === \"up\";\n const isDown = change?.direction === \"down\";\n\n return (\n { e.currentTarget.style.borderColor = T.neutral300; }}\n onMouseLeave={e => { e.currentTarget.style.borderColor = T.neutral200; }}\n >\n
    \n {kpi.label}\n
    \n
    \n {current != null ? fmtNum(current) : \"\u2014\"}\n
    \n {change && change.percentage != null ? (\n
    \n {isUp && }\n {isDown && }\n {!isUp && !isDown && }\n \n {change.percentage > 0 ? \"+\" : \"\"}{change.percentage}%\n \n vs last week\n
    \n ) : (\n
    \n Collecting data\n
    \n )}\n
    \n );\n}\n\nexport default ClientDashboard;\n\n// \u2500\u2500 PR replies summary (auto-backlinks.md section 5) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// A small block linking to the PR Replies page. Renders nothing unless that\n// page is visible for the client and there is something to show.\nfunction LinksSection({ clientId, navigate }) {\n const [data, setData] = useState(null);\n useEffect(() => {\n let alive = true;\n axios.get(`/api/v2/clients/${clientId}/pr_replies`).then(r => { if (alive) setData(r.data); }).catch(() => {});\n return () => { alive = false; };\n }, [clientId]);\n if (!data?.visible) return null;\n const pl = data.pipeline || {};\n if (!pl.matched_30d && !pl.sent_total && !pl.links_live) return null;\n const stat = (label, value) => (\n
    \n
    {label}
    \n
    {value ?? 0}
    \n
    \n );\n return (\n
    \n
    \n
    Backlinks
    \n navigate(`/clients/${clientId}/pr-replies`)} style={{ fontSize: 12, color: T.neutral600, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 4 }}>See all replies \n
    \n
    navigate(`/clients/${clientId}/pr-replies`)} style={{ display: 'flex', flexWrap: 'wrap', background: T.surface, border: `0.5px solid ${T.neutral200}`, borderRadius: R.card, boxShadow: T.shadowXs, overflow: 'hidden', cursor: 'pointer' }}>\n {stat('Requests matched, 30 days', pl.matched_30d)}\n {stat('Replies sent, 30 days', pl.sent_30d)}\n {stat('Links placed', pl.placed_total)}\n {stat('Live links, all sources', pl.links_live)}\n
    \n
    \n );\n}\n", "// app/javascript/components/Clients/ClientDataViewer.jsx\n//\n// Inner content for the Data page. Sidebar + header come from ClientLayout.\n\nimport React, { useState, useEffect, useCallback } from 'react';\nimport axios from '../AxiosConfig';\nimport { useClientLayout } from './ClientLayout';\n\nimport {\n Layers, Loader, AlertCircle, Check, X, ChevronLeft, ChevronRight\n} from 'lucide-react';\n\nconst T = {\n indigo: \"#4f46e5\", indigoLight: \"#eef2ff\", indigoDark: \"#3730a3\",\n bg: \"#f7f7f8\", surface: \"#ffffff\",\n border: \"#e2e8f0\", text: \"#0f172a\", muted: \"#64748b\", faint: \"#94a3b8\",\n green: \"#10b981\", greenLight: \"#f0fdf4\", red: \"#ef4444\",\n};\n\nconst PAGE_SIZE = 25;\n\nconst SUB_TABS = [\n {\n id: 'competitors', label: 'Competitors', editable: true,\n columns: [\n { key: 'id', label: 'id' },\n { key: 'domain', label: 'domain' },\n { key: 'name', label: 'name' },\n { key: 'is_tracked', label: 'is_tracked', type: 'tracked_toggle' },\n { key: 'category', label: 'category' },\n { key: 'relevance_score', label: 'relevance_score', type: 'decimal3' },\n { key: 'threat_level', label: 'threat_level', type: 'decimal3' },\n { key: 'enriched_at', label: 'enriched_at' },\n { key: 'first_discovered_at', label: 'first_discovered_at' },\n ],\n },\n {\n id: 'keywords', label: 'Keywords', editable: true,\n columns: [\n { key: 'id', label: 'id' },\n { key: 'keyword', label: 'keyword' },\n { key: 'is_tracked', label: 'is_tracked', type: 'tracked_toggle' },\n { key: 'search_volume', label: 'search_volume', type: 'integer_with_commas' },\n { key: 'keyword_difficulty', label: 'difficulty' },\n { key: 'intent', label: 'intent' },\n { key: 'opportunity_score', label: 'opportunity_score', type: 'decimal2' },\n ],\n },\n {\n id: 'sites', label: 'Sites', editable: false,\n columns: [\n { key: 'id', label: 'id' },\n { key: 'domain', label: 'domain' },\n { key: 'subdomain', label: 'subdomain' },\n { key: 'is_primary', label: 'is_primary', type: 'boolean' },\n { key: 'language', label: 'language' },\n { key: 'country', label: 'country' },\n { key: 'last_crawled_at', label: 'last_crawled_at' },\n ],\n },\n {\n id: 'pages', label: 'Pages', editable: false,\n columns: [\n { key: 'id', label: 'id' },\n { key: 'url', label: 'url' },\n { key: 'title', label: 'title' },\n { key: 'word_count', label: 'word_count', type: 'integer_with_commas' },\n { key: 'index_status', label: 'index_status' },\n { key: 'http_status_code', label: 'status' },\n { key: 'last_crawled_at', label: 'last_crawled_at' },\n ],\n },\n {\n id: 'gsc_records', label: 'GSC Records', editable: false,\n columns: [\n { key: 'id', label: 'id' },\n { key: 'query', label: 'query' },\n { key: 'page_url', label: 'page_url' },\n { key: 'clicks', label: 'clicks', type: 'integer_with_commas' },\n { key: 'impressions', label: 'impressions', type: 'integer_with_commas' },\n { key: 'ctr', label: 'ctr', type: 'decimal3' },\n { key: 'position', label: 'position', type: 'decimal1' },\n { key: 'date', label: 'date' },\n ],\n },\n {\n id: 'ga4_records', label: 'GA4 Records', editable: false,\n columns: [\n { key: 'id', label: 'id' },\n { key: 'page_path', label: 'page_path' },\n { key: 'sessions', label: 'sessions', type: 'integer_with_commas' },\n { key: 'users', label: 'users', type: 'integer_with_commas' },\n { key: 'bounce_rate', label: 'bounce_rate', type: 'decimal2' },\n { key: 'conversions', label: 'conversions', type: 'integer_with_commas' },\n { key: 'revenue', label: 'revenue', type: 'decimal2' },\n { key: 'date', label: 'date' },\n ],\n },\n {\n id: 'backlinks', label: 'Backlinks', editable: false,\n columns: [\n { key: 'id', label: 'id' },\n { key: 'source_domain', label: 'source_domain' },\n { key: 'target_url', label: 'target_url' },\n { key: 'domain_authority', label: 'source_dr' },\n { key: 'anchor_text', label: 'anchor_text' },\n { key: 'is_nofollow', label: 'nofollow', type: 'boolean' },\n { key: 'last_seen_at', label: 'last_seen_at' },\n ],\n },\n {\n id: 'keyword_rankings', label: 'Keyword Rankings', editable: false,\n columns: [\n { key: 'id', label: 'id' },\n { key: 'keyword_id', label: 'keyword_id' },\n { key: 'position', label: 'position' },\n { key: 'device', label: 'device' },\n { key: 'location', label: 'location' },\n { key: 'recorded_at', label: 'recorded_at' },\n ],\n }\n // {\n // id: 'serp_features', label: 'SERP Features', editable: false,\n // columns: [\n // { key: 'id', label: 'id' },\n // { key: 'keyword_id', label: 'keyword_id' },\n // { key: 'feature_type', label: 'feature_type' },\n // { key: 'client_owns', label: 'client_owns', type: 'boolean' },\n // { key: 'owner_domain', label: 'owner_domain' },\n // { key: 'position', label: 'position' },\n // { key: 'recorded_at', label: 'recorded_at' },\n // ],\n // },\n];\n\nconst formatCell = (value, type) => {\n if (value === null || value === undefined || value === '') return null;\n if (type === 'integer_with_commas' && typeof value === 'number') return value.toLocaleString();\n if (type === 'decimal1' && typeof value === 'number') return value.toFixed(1);\n if (type === 'decimal2' && typeof value === 'number') return value.toFixed(2);\n if (type === 'decimal3' && typeof value === 'number') return value.toFixed(3);\n if (type === 'boolean') return String(!!value);\n // Timestamp formatting \u2014 detect ISO strings\n if (typeof value === 'string' && value.match(/^\\d{4}-\\d{2}-\\d{2}T/)) {\n const d = new Date(value);\n if (!isNaN(d.getTime())) {\n return d.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }) +\n ' at ' +\n d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', timeZoneName: 'short' });\n }\n }\n return value;\n};\n\nfunction DataSubTabs({ active, onChange }) {\n return (\n
    \n {SUB_TABS.map(t => {\n const on = active === t.id;\n return (\n \n );\n })}\n
    \n );\n}\n\nfunction TrackedToggle({ tracked, onToggle, disabled }) {\n return (\n \n );\n}\n\nfunction DataTable({ tab, rows, page, totalPages, totalCount, onPrev, onNext, onToggleTracked, togglingIds }) {\n if (!rows || rows.length === 0) {\n return (\n
    \n No {tab.label.toLowerCase()} yet.\n
    \n );\n }\n\n return (\n
    \n
    \n \n \n \n {tab.columns.map(c => (\n \n ))}\n \n \n \n {rows.map((row, i) => (\n \n {tab.columns.map(c => {\n const isTrackedToggle = c.type === 'tracked_toggle';\n const cellContent = isTrackedToggle ? (\n onToggleTracked(row.id, !row.is_tracked)}\n />\n ) : formatCell(row[c.key], c.type);\n\n return (\n \n );\n })}\n \n ))}\n \n
    {c.label}
    \n {cellContent !== null && cellContent !== undefined ? cellContent : \u2014}\n
    \n
    \n
    \n
    \n Page {page} of {Math.max(totalPages, 1)} ({totalCount} {totalCount === 1 ? 'row' : 'rows'})\n
    \n
    \n \n \n
    \n
    \n
    \n );\n}\n\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n// MAIN\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\nconst ClientDataViewer = () => {\n const { client, clientId } = useClientLayout();\n\n const [activeSubTab, setActiveSubTab] = useState('competitors');\n const [rows, setRows] = useState([]);\n const [page, setPage] = useState(1);\n const [totalCount, setTotalCount] = useState(0);\n const [tableLoading, setTableLoading] = useState(false);\n const [error, setError] = useState('');\n const [togglingIds, setTogglingIds] = useState(new Set());\n\n const fetchRows = useCallback(async () => {\n if (!clientId) return;\n setTableLoading(true);\n setError('');\n try {\n const res = await axios.get(\n `/api/v2/clients/${clientId}/data/tables/${activeSubTab}`,\n { params: { page, per_page: PAGE_SIZE } }\n );\n const data = res.data || {};\n const list = Array.isArray(data) ? data : (data.rows || data.data || data.records || []);\n const total = data.total ?? data.total_count ?? data.count ?? list.length;\n setRows(list);\n setTotalCount(total);\n } catch (err) {\n setRows([]);\n setTotalCount(0);\n setError(err.response?.data?.error || 'Failed to load data');\n } finally {\n setTableLoading(false);\n }\n }, [clientId, activeSubTab, page]);\n\n useEffect(() => { fetchRows(); }, [fetchRows]);\n\n const handleChangeSubTab = (id) => {\n if (id === activeSubTab) return;\n setActiveSubTab(id);\n setPage(1);\n setRows([]);\n };\n\n const handleToggleTracked = async (rowId, nextValue) => {\n if (!rowId) return;\n setTogglingIds(prev => { const n = new Set(prev); n.add(rowId); return n; });\n const prevRows = rows;\n setRows(prev => prev.map(r => r.id === rowId ? { ...r, is_tracked: nextValue } : r));\n try {\n await axios.patch(\n `/api/v2/clients/${clientId}/data/tables/${activeSubTab}/${rowId}`,\n { is_tracked: nextValue }\n );\n } catch (err) {\n setRows(prevRows);\n setError(err.response?.data?.error || 'Failed to update \u2014 change reverted.');\n } finally {\n setTogglingIds(prev => { const n = new Set(prev); n.delete(rowId); return n; });\n }\n };\n\n const totalPages = Math.max(1, Math.ceil(totalCount / PAGE_SIZE));\n const handlePrev = () => setPage(p => Math.max(1, p - 1));\n const handleNext = () => setPage(p => Math.min(totalPages, p + 1));\n\n const activeTab = SUB_TABS.find(t => t.id === activeSubTab) || SUB_TABS[0];\n\n return (\n
    \n
    \n
    \n
    Client data
    \n
    \n
    \n \n
    \n
    \n

    Data

    \n
    Runs, logs, and ingested data for {client?.name || \"this client\"}
    \n
    \n
    \n
    \n\n {error && (\n
    \n \n {error}\n \n
    \n )}\n\n \n\n {tableLoading ? (\n
    \n \n Loading {activeTab.label.toLowerCase()}\u2026\n
    \n ) : (\n \n )}\n
    \n
    \n );\n};\n\nexport default ClientDataViewer;", "// app/javascript/components/Clients/ClientSettings.jsx\n//\n// Client settings page \u2014 accessed from the sidebar nav.\n// Sections:\n// 1. General \u2014 rename the client record\n// 2. Google Account \u2014 org-pool picker (same pattern as ClientDashboard/onboarding)\n// 3. PR profile \u2014 experts and their send-only Gmail (PrProfileSection.js);\n// hidden unless PR outreach is enabled for the org\n//\n// The Google account picker uses the org-pool model: multiple accounts\n// can be connected to the org, the user picks which one to use for\n// this specific client.\n\nimport React, { useState, useEffect, useCallback, useRef } from 'react';\nimport { useClientLayout } from './ClientLayout';\nimport axios from '../AxiosConfig';\nimport PrProfileSection from './PrProfileSection';\nimport { Settings, Loader, AlertCircle, Check, Plus, CheckCircle2 } from 'lucide-react';\n\n// \u2500\u2500 Google G mark \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nfunction GoogleG({ size = 16 }) {\n return (\n \n \n \n \n \n \n );\n}\n\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n// Main page\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\nconst ClientSettings = () => {\n const { client, clientId, refetchClient } = useClientLayout();\n\n return (\n
    \n
    \n
    \n
    \n \n

    Settings

    \n
    \n

    \n Configure data sources and integrations for {client?.name || 'this client'}\n

    \n
    \n\n
    \n \n \n \n
    \n
    \n
    \n );\n};\n\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n// General \u2014 client name\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\nconst GeneralSection = ({ client, clientId, refetchClient }) => {\n const [name, setName] = useState(client?.name || '');\n const [saving, setSaving] = useState(false);\n const [saved, setSaved] = useState(false);\n const [error, setError] = useState(null);\n\n // Re-sync when the client loads or is renamed elsewhere.\n useEffect(() => { setName(client?.name || ''); }, [client?.name]);\n\n const trimmed = name.trim();\n const dirty = trimmed.length > 0 && trimmed !== (client?.name || '');\n\n const save = async () => {\n if (!dirty || saving) return;\n setSaving(true); setError(null); setSaved(false);\n try {\n await axios.patch(`/api/v2/clients/${clientId}`, { client: { name: trimmed } });\n await refetchClient?.();\n setSaved(true);\n setTimeout(() => setSaved(false), 2000);\n } catch (e) {\n setError(e.response?.data?.error || 'Could not save the name. Try again.');\n } finally {\n setSaving(false);\n }\n };\n\n return (\n }\n title=\"General\"\n description=\"The name shown for this client across Visto\"\n >\n \n
    \n setName(e.target.value)}\n onKeyDown={e => { if (e.key === 'Enter') save(); }}\n placeholder=\"Client name\"\n className=\"flex-1 min-w-0 rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500\"\n />\n \n {saving ? : saved ? : null}\n {saving ? 'Saving...' : saved ? 'Saved' : 'Save'}\n \n
    \n {error && (\n

    \n {error}\n

    \n )}\n \n );\n};\n\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n// Google Account \u2014 org-pool picker\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n// CMS access \u2014 how the Visto operator gets into the client's CMS\n// (docs/eng-plans/browser-deploy.md 2.3). Everyone who can see the client\n// sees the state; only Visto staff can edit. `ready` is what switches the\n// stage and publish experience on for this client's work items.\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\nconst GoogleAccountSection = ({ clientId }) => {\n const [connections, setConnections] = useState([]);\n const [assignedId, setAssignedId] = useState(null);\n const [loading, setLoading] = useState(true);\n const [connecting, setConnecting] = useState(false);\n const [assigning, setAssigning] = useState(false);\n const [error, setError] = useState(null);\n const pollRef = useRef(null);\n\n const fetchConnections = useCallback(async () => {\n try {\n const { data } = await axios.get(`/api/v2/clients/${clientId}/google_connections`);\n setConnections(data.connections || []);\n setAssignedId(data.assigned_connection_id);\n } catch (err) {\n console.error('Failed to load Google connections:', err);\n } finally {\n setLoading(false);\n }\n }, [clientId]);\n\n useEffect(() => { fetchConnections(); }, [fetchConnections]);\n useEffect(() => { return () => { if (pollRef.current) clearInterval(pollRef.current); }; }, []);\n\n // Listen for OAuth popup\n useEffect(() => {\n const handler = (event) => {\n if (event.origin !== window.location.origin || !event.data) return;\n if (event.data.connected === 'google') {\n if (pollRef.current) clearInterval(pollRef.current);\n setConnecting(false);\n fetchConnections();\n } else if (event.data.error) {\n setError(event.data.error);\n setConnecting(false);\n }\n };\n window.addEventListener('message', handler);\n return () => window.removeEventListener('message', handler);\n }, [fetchConnections]);\n\n const handleConnectNew = async () => {\n setConnecting(true);\n setError(null);\n try {\n const { data } = await axios.post(`/api/v2/clients/${clientId}/google_connections/authorize`);\n const w = 520, h = 680;\n const left = window.screenX + (window.outerWidth - w) / 2;\n const top = window.screenY + (window.outerHeight - h) / 2;\n const popup = window.open(data.authorize_url, 'google_oauth',\n `width=${w},height=${h},left=${left},top=${top},toolbar=no,menubar=no`);\n pollRef.current = setInterval(() => {\n if (popup && popup.closed) {\n clearInterval(pollRef.current);\n pollRef.current = null;\n setConnecting(false);\n fetchConnections();\n }\n }, 500);\n } catch {\n setError('Failed to start Google authorization');\n setConnecting(false);\n }\n };\n\n const handleAssign = async (connectionId) => {\n if (connectionId === assignedId) return;\n setAssigning(true);\n setError(null);\n try {\n const { data } = await axios.patch(\n `/api/v2/clients/${clientId}/google_connections/assign`,\n { connection_id: connectionId }\n );\n setAssignedId(data.assigned_connection_id);\n } catch (err) {\n setError(err.response?.data?.error || 'Failed to assign connection');\n } finally {\n setAssigning(false);\n }\n };\n\n const assignedEmail = connections.find(c => c.id === assignedId)?.google_account_email;\n\n if (loading) {\n return (\n
    } title=\"Google Account\" description=\"Which Google account to use for this client's data\">\n
    \n \n Loading connections...\n
    \n
    \n );\n }\n\n return (\n }\n title=\"Google Account\"\n description=\"Which Google account to use for this client's data\"\n headerAction={assignedId && (\n
    \n \n {assignedEmail}\n
    \n )}\n >\n {error && (\n
    \n \n {error}\n
    \n )}\n\n
    \n {connections.map((conn) => {\n const isSelected = conn.id === assignedId;\n return (\n !assigning && handleAssign(conn.id)}\n disabled={assigning}\n className={`w-full text-left p-3.5 rounded-lg border transition-colors ${\n isSelected\n ? 'border-indigo-400 bg-indigo-50/50'\n : 'border-gray-200 bg-white hover:border-gray-300 hover:bg-gray-50/50'\n } ${assigning ? 'opacity-60 cursor-wait' : 'cursor-pointer'}`}\n >\n
    \n \n {isSelected && }\n \n
    \n \n
    \n
    \n
    \n {conn.google_account_email}\n
    \n
    \n {conn.scopes?.gsc && GSC}\n {conn.scopes?.ga4 && <>\u00B7GA4}\n {conn.client_count > 0 && (\n <>\u00B7{conn.client_count} client{conn.client_count === 1 ? '' : 's'}\n )}\n {conn.expired && (\n <>\u00B7Needs re-auth\n )}\n
    \n
    \n {isSelected && }\n
    \n \n );\n })}\n\n \n
    \n \n
    \n {connecting\n ? \n : \n }\n
    \n
    \n
    \n {connecting ? 'Opening Google\u2026' : 'Connect another Google account'}\n
    \n
    \n
    \n \n
    \n \n );\n};\n\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n// Shared UI\n// \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\nconst Section = ({ icon, title, description, headerAction, children }) => (\n
    \n
    \n
    \n {icon}\n
    \n

    {title}

    \n {description &&

    {description}

    }\n
    \n
    \n {headerAction &&
    {headerAction}
    }\n
    \n
    {children}
    \n
    \n);\n\nexport default ClientSettings;", "// app/javascript/components/Clients/PrProfileSection.js\n//\n// \"PR profile\" section of client settings (docs/eng-plans/auto-backlinks.md\n// section 5): the people at the client who answer journalist requests, and\n// the one Gmail every reply is sent from. Several experts per client, one\n// mailbox: replies are written and signed as the expert, sent from that\n// address (an agency runs its experts from a manager's inbox).\n// Hidden entirely when the API says the feature is off for this org.\n\nimport React, { useState, useEffect, useCallback, useRef } from 'react';\nimport { useNavigate } from 'react-router-dom';\nimport axios from '../AxiosConfig';\nimport { Loader, AlertCircle, Plus, Trash2, Pencil, Mail, Newspaper, X } from 'lucide-react';\n\nconst EMPTY = {\n name: '', title: '', headshot_url: '', linkedin_url: '', bio: '',\n topics: [], proof_points: [], qa_answers: [],\n daily_pitch_cap: 3, min_dr: 30, status: 'active',\n};\n\nconst PrProfileSection = ({ clientId, Section, onClientChanged }) => {\n const [enabled, setEnabled] = useState(false);\n const [profiles, setProfiles] = useState([]);\n const [mailbox, setMailbox] = useState(null);\n const [companyName, setCompanyName] = useState('');\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n const [editing, setEditing] = useState(null); // null | 'new' | profile id\n const pollRef = useRef(null);\n\n const fetchProfiles = useCallback(async () => {\n try {\n const { data } = await axios.get(`/api/v2/clients/${clientId}/expert_profiles`);\n setEnabled(!!data.enabled);\n setProfiles(data.profiles || []);\n setMailbox(data.mailbox || null);\n setCompanyName(data.company_name || '');\n } catch (err) {\n console.error('Failed to load PR profiles:', err);\n } finally {\n setLoading(false);\n }\n }, [clientId]);\n\n useEffect(() => { fetchProfiles(); }, [fetchProfiles]);\n\n // Connecting Gmail, turning sending on or off, and removing an expert all\n // change whether the Backlinks menu item shows, which the sidebar reads\n // from the client record. Reload both so the menu updates in place.\n const refresh = useCallback(async () => {\n await fetchProfiles();\n if (onClientChanged) onClientChanged();\n }, [fetchProfiles, onClientChanged]);\n useEffect(() => () => { if (pollRef.current) clearInterval(pollRef.current); }, []);\n\n // The OAuth popup posts back through the shared Google callback page.\n useEffect(() => {\n const handler = (event) => {\n if (event.origin !== window.location.origin || !event.data) return;\n if (event.data.connected === 'gmail_send') {\n if (pollRef.current) clearInterval(pollRef.current);\n refresh();\n } else if (event.data.error && event.data.error !== 'access_denied') {\n setError(`Gmail connection failed: ${event.data.error}`);\n refresh();\n }\n };\n window.addEventListener('message', handler);\n return () => window.removeEventListener('message', handler);\n }, [refresh]);\n\n const connectGmail = async () => {\n setError(null);\n try {\n const { data } = await axios.post(`/api/v2/clients/${clientId}/mailbox/authorize`);\n const w = 520, h = 640;\n const left = window.screenX + (window.outerWidth - w) / 2;\n const top = window.screenY + (window.outerHeight - h) / 2;\n const popup = window.open(data.authorize_url, 'gmail_send_oauth',\n `width=${w},height=${h},left=${left},top=${top},toolbar=no,menubar=no`);\n pollRef.current = setInterval(() => {\n if (popup && popup.closed) {\n clearInterval(pollRef.current);\n pollRef.current = null;\n refresh();\n }\n }, 500);\n } catch (err) {\n setError(err.response?.data?.error || 'Failed to start Gmail authorization');\n }\n };\n\n const disconnectGmail = async () => {\n if (!window.confirm(`Disconnect ${mailbox?.email}? Replies for every expert will stop, and automatic sending will be turned off.`)) return;\n setError(null);\n try {\n await axios.delete(`/api/v2/clients/${clientId}/mailbox`);\n refresh();\n } catch (err) {\n setError(err.response?.data?.error || 'Failed to disconnect');\n }\n };\n\n const removeProfile = async (profile) => {\n if (!window.confirm(`Remove ${profile.name} from this client's PR profile?`)) return;\n setError(null);\n try {\n await axios.delete(`/api/v2/clients/${clientId}/expert_profiles/${profile.id}`);\n refresh();\n } catch (err) {\n setError(err.response?.data?.error || 'Failed to remove');\n }\n };\n\n if (loading || !enabled) return null;\n\n return (\n }\n title=\"PR profile\"\n description=\"The Gmail replies go out from, and the people they are written as\"\n headerAction={editing === null && (\n \n )}\n >\n {error && (\n
    \n \n {error}\n
    \n )}\n\n \n\n {editing === 'new' && (\n setEditing(null)}\n onSaved={() => { setEditing(null); fetchProfiles(); }} />\n )}\n\n {profiles.length === 0 && editing !== 'new' && (\n

    \n No experts yet. Add a real person at the company: journalists reply to people, not brands.\n

    \n )}\n\n
    \n {profiles.map((p) => (\n editing === p.id ? (\n setEditing(null)}\n onSaved={() => { setEditing(null); fetchProfiles(); }} />\n ) : (\n setEditing(p.id)}\n onRemove={() => removeProfile(p)} />\n )\n ))}\n
    \n \n );\n};\n\n// \u2500\u2500 The client's sending mailbox \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst MailboxCard = ({ mailbox, onConnect, onDisconnect }) => {\n const mb = mailbox || {};\n const connected = mb.status === 'active';\n return (\n
    \n
    \n Sending mailbox\n \n
    \n {mb.status === 'error' && mb.last_error && (\n
    {mb.last_error}
    \n )}\n
    \n {connected ? (\n \n ) : (\n \n )}\n \n One Gmail or Google Workspace account for every expert here. Send-only access: no password, no reading your inbox.\n Replies are written and signed as the expert and sent from this address, so journalists answer here.\n \n
    \n
    \n );\n};\n\n// \u2500\u2500 One expert \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst MailboxChip = ({ mailbox }) => {\n const map = {\n active: ['bg-green-50 text-green-700 border-green-200', 'Gmail connected'],\n pending: ['bg-amber-50 text-amber-700 border-amber-200', 'Setup pending'],\n error: ['bg-red-50 text-red-700 border-red-200', 'Needs reconnect'],\n not_connected: ['bg-gray-50 text-gray-600 border-gray-200', 'Not connected'],\n };\n const [cls, label] = map[mailbox?.status] || map.not_connected;\n return (\n \n \n {label}{mailbox?.email && mailbox.status === 'active' ? ` \u00B7 ${mailbox.email}` : ''}\n \n );\n};\n\n// Initials unless a headshot URL is set and actually loads.\nconst Avatar = ({ profile }) => {\n const [broken, setBroken] = useState(false);\n useEffect(() => { setBroken(false); }, [profile.headshot_url]);\n if (profile.headshot_url && !broken) {\n return \"\" setBroken(true)} className=\"w-10 h-10 rounded-full object-cover border border-gray-200\" />;\n }\n return (\n
    \n {profile.name?.[0] || '?'}\n
    \n );\n};\n\nconst ProfileCard = ({ profile, clientId, mailbox, onEdit, onRemove, onChanged, onError }) => {\n const navigate = useNavigate();\n const [confirming, setConfirming] = useState(false);\n const [saving, setSaving] = useState(false);\n\n // Automatic sending is a recorded opt-in with its own confirmation.\n const setAutoSend = async (enabled) => {\n setSaving(true);\n onError(null);\n try {\n await axios.post(`/api/v2/clients/${clientId}/expert_profiles/${profile.id}/auto_send`, { enabled, confirm: enabled });\n setConfirming(false);\n onChanged();\n } catch (err) {\n onError(err.response?.data?.error || 'Could not change automatic sending');\n } finally {\n setSaving(false);\n }\n };\n const mb = mailbox || {};\n const connected = mb.status === 'active';\n\n return (\n
    \n
    \n \n
    \n
    \n {profile.name}\n {profile.title && {profile.title}}\n
    \n
    \n \n {profile.topics.length} topic{profile.topics.length === 1 ? '' : 's'} \u00B7 {profile.proof_points.length} proof point{profile.proof_points.length === 1 ? '' : 's'}\n \n
    \n {!profile.linkedin_url && (\n
    No LinkedIn URL. Most journalists ask for one, and it goes in the signature of every reply.
    \n )}\n
    \n
    \n \n \n
    \n
    \n\n {!connected && (\n
    Connect the sending mailbox above to turn on automatic replies for {profile.name}.
    \n )}\n\n {connected && (\n
    \n
    \n \n
    \n
    Send replies automatically
    \n
    \n {profile.auto_send\n ? `On since ${new Date(profile.auto_send_enabled_at).toLocaleDateString()}${profile.auto_send_enabled_by ? ` \u00B7 turned on by ${profile.auto_send_enabled_by}` : ''}`\n : `Off. Nothing is sent for ${profile.name} until you turn this on.`}\n
    \n
    \n {profile.replies_sent > 0 && (\n \n )}\n
    \n\n {confirming && (\n
    \n
    Turn on automatic sending for {profile.name}?
    \n
      \n
    • When a journalist publishes a request that fits {profile.name}'s topics, Visto drafts a reply written as {profile.name} and sends it from {mb.email} without asking first.
    • \n
    • At most {profile.daily_pitch_cap} repl{profile.daily_pitch_cap === 1 ? 'y' : 'ies'} a day, one per request, never a follow-up.
    • \n
    • Every reply is listed word for word under Backlinks, and each one lets the journalist opt out.
    • \n
    • You can turn this off here at any time. Disconnecting Gmail also turns it off.
    • \n
    \n
    \n \n \n
    \n
    \n )}\n
    \n )}\n
    \n );\n};\n\n// \u2500\u2500 Create / edit form \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst ProfileForm = ({ clientId, initial, profileId, companyName, onCancel, onSaved }) => {\n const [form, setForm] = useState({\n ...EMPTY, ...initial,\n company_name: companyName || '',\n topicsText: (initial.topics || []).join('\\n'),\n proof_points: (initial.proof_points || []).length ? initial.proof_points : [{ claim: '', number: '', context: '' }],\n });\n const [saving, setSaving] = useState(false);\n const [error, setError] = useState(null);\n\n const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));\n const setPP = (i, k, v) => setForm((f) => {\n const pp = f.proof_points.map((p, j) => (j === i ? { ...p, [k]: v } : p));\n return { ...f, proof_points: pp };\n });\n\n const submit = async (e) => {\n e.preventDefault();\n setSaving(true);\n setError(null);\n // Daily cap, minimum DR and status stay at their defaults; they are\n // not exposed in the form for now.\n const payload = {\n name: form.name, title: form.title, headshot_url: form.headshot_url, linkedin_url: form.linkedin_url,\n bio: form.bio, company_name: form.company_name,\n topics: form.topicsText.split(/\\n|,/).map((t) => t.trim()).filter(Boolean),\n proof_points: form.proof_points.filter((p) => p.claim && p.claim.trim()),\n };\n try {\n if (profileId) {\n await axios.patch(`/api/v2/clients/${clientId}/expert_profiles/${profileId}`, { profile: payload });\n } else {\n await axios.post(`/api/v2/clients/${clientId}/expert_profiles`, { profile: payload });\n }\n onSaved();\n } catch (err) {\n setError(err.response?.data?.error || 'Failed to save');\n } finally {\n setSaving(false);\n }\n };\n\n const input = 'w-full text-sm border border-gray-200 rounded-md px-3 py-2 bg-white focus:outline-none focus:ring-1 focus:ring-indigo-400';\n const label = 'block text-xs font-medium text-gray-800';\n const hint = 'text-xs text-gray-500 mt-0.5 mb-1.5';\n\n return (\n
    \n
    \n
    \n
    {profileId ? 'Edit expert' : 'New expert'}
    \n

    \n Journalists get a reply written in the first person as this person. Everything below decides which requests they answer and what the reply is allowed to say.\n

    \n
    \n \n
    \n {error &&
    {error}
    }\n\n {/* Hints differ in length, so each cell is a column with the input pinned to the bottom to keep the two inputs level. */}\n
    \n
    \n \n

    A real person, not the company. Replies are signed with this name.

    \n set('name', e.target.value)} required placeholder=\"Jane Park\" />\n
    \n
    \n \n

    Shown in the signature as \"Title, Company\".

    \n set('title', e.target.value)} placeholder=\"Head of Growth\" />\n
    \n
    \n\n
    \n \n

    How the company is named in the signature (\"Title, Company\") and when describing the expert to journalists. Pre-filled from the website; shared by every expert at this client.

    \n set('company_name', e.target.value)} placeholder=\"Smart ABI\" />\n
    \n\n
    \n \n

    Added to the signature of every reply. Journalists use it to check that the source is real, and many ask for it.

    \n set('linkedin_url', e.target.value)} placeholder=\"https://www.linkedin.com/in/janepark\" />\n
    \n\n
    \n \n

    \n Who they are and what they have done: role, years of experience, the kind of companies or clients they have worked with, what they are known for.\n Used to decide which requests they can credibly answer and to set the voice of the reply. Facts in here can be referenced in a reply, so keep it accurate.\n

    \n