@dr.pogodin/react-utils 1.35.0 → 1.35.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/development/client/getInj.js.map +1 -1
- package/build/development/index.js.map +1 -1
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js.map +1 -1
- package/build/development/shared/components/Button/index.js +2 -1
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/MetaTags.js.map +1 -1
- package/build/development/shared/components/TextArea/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/components/index.js +8 -1
- package/build/development/shared/components/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/development/shared/utils/index.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/development/shared/utils/jest/index.js +7 -2
- package/build/development/shared/utils/jest/index.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/web.bundle.js +3 -3
- package/build/production/client/getInj.js.map +1 -1
- package/build/production/index.js.map +1 -1
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js.map +1 -1
- package/build/production/shared/components/Button/index.js +2 -2
- package/build/production/shared/components/Button/index.js.map +1 -1
- package/build/production/shared/components/MetaTags.js.map +1 -1
- package/build/production/shared/components/TextArea/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/components/index.js +1 -1
- package/build/production/shared/components/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/production/shared/utils/index.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/production/shared/utils/jest/index.js +1 -1
- package/build/production/shared/utils/jest/index.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/web.bundle.js +1 -1
- package/build/production/web.bundle.js.map +1 -1
- package/build/types-code/index.d.ts +1 -1
- package/build/types-code/shared/components/Button/index.d.ts +1 -0
- package/build/types-code/shared/components/index.d.ts +1 -1
- package/build/types-code/shared/utils/index.d.ts +1 -1
- package/build/types-code/shared/utils/jest/index.d.ts +2 -1
- package/package.json +32 -33
- package/src/index.ts +1 -0
- package/src/shared/components/Button/index.tsx +1 -1
- package/src/shared/components/index.ts +1 -1
- package/src/shared/utils/index.ts +1 -0
- package/src/shared/utils/jest/index.tsx +9 -3
- package/tsconfig.types.json +1 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MetaTags.js","names":["_propTypes","_interopRequireDefault","require","_react","_reactHelmet","_jsxRuntime","Context","createContext","description","title","MetaTags","children","image","siteName","socialDescription","socialTitle","url","socTitle","socDesc","context","useMemo","jsxs","Fragment","Helmet","jsx","name","content","Provider","value","propTypes","PT","node","string","isRequired","_default","exports","default"],"sources":["../../../../src/shared/components/MetaTags.tsx"],"sourcesContent":["import PT from 'prop-types';\nimport { type ReactNode, createContext, useMemo } from 'react';\nimport { Helmet } from 'react-helmet';\n\ntype PropsT = {\n children?: ReactNode;\n description: string;\n image?: string;\n siteName?: string;\n socialDescription?: string;\n socialTitle?: string;\n title: string;\n url?: string;\n};\n\nconst Context = createContext<PropsT>({\n description: '',\n title: '',\n});\n\n/**\n * The `<MetaTags>` component is an auxiliary wrapper around `react-helmet`,\n * which helps to inject meta tags (page title, a brief content description,\n * and social media thumbnails) into generated pages.\n *\n * When `<MetaTags>` are nested within the app's component tree, meta tags\n * content injected by components encountered down the tree overrides tags\n * injected by previously encountered `<MetaTags>` components.\n *\n * **Children:** `<MetaTags>` children, if any, are rendered at the component's\n * location. The context passes down all meta tag properties of parent\n * `<MetaTag>` instances. These properties can fetched within children\n * hierarchy in the following way, thus facilitating tags modification by\n * children:\n * ```jsx\n * import { useContext } from 'react';\n * import { MetaTags } from '@dr.pogodin/react-utils';\n * export default function SampleComponent() {\n * const { title, description, ...rest } = useContext(MetaTags.Context);\n * // Do something with these props here, e.g. prefix the page title with\n * // the component name:\n * return (\n * <MetaTags title={`Sample component - ${title}`} />\n * );\n * }\n * ```\n * @param [props]\n * @param [props.description] Page description to use in\n * the `description` meta tag, and as a default description of Open Graph Tags.\n * @param [props.image] The absolute URL of thumbnail image to use\n * in Open Graph Tags (`twitter:image`, and `og:image`). By default these tags\n * are not injected.\n *\n * **BEWARE:** It must be a complete, absolute URL, including the correct\n * website domain and HTTP schema.\n *\n * @param [props.siteName]: The site name to use in `twitter:site`,\n * and `og:sitename` tags. By default these tags are not injected.\n *\n * @param [props.socialDescription] The site description to use in\n * `twitter:description` and `og:description` meta tags. By default the value of\n * `description` prop is used.\n * @param [props.socialTitle] The page title to use in\n * `twitter:title`, `og:title`, and `og:image:alt` tags. By default the value of\n * `title` prop is used. Also the `og:image:alt` tag is only injected if `image`\n * prop is present.\n *\n * @param props.title: The page name to use in the `<title>` tag.\n * It is also used as the default value of `socialTitle` prop.\n *\n * @param [props.url] The page URL to use in `og:url` tag.\n * By default the tag is not injected.\n */\nconst MetaTags: React.FunctionComponent<PropsT> & {\n Context: React.Context<PropsT>;\n} = ({\n children,\n description,\n image,\n siteName,\n socialDescription,\n socialTitle,\n title,\n url,\n}) => {\n const socTitle = socialTitle || title;\n const socDesc = socialDescription || description;\n\n const context = useMemo(() => ({\n description,\n image,\n siteName,\n socialDescription,\n socialTitle,\n title,\n url,\n }), [\n description,\n image,\n siteName,\n socialDescription,\n socialTitle,\n title,\n url,\n ]);\n\n return (\n <>\n <Helmet>\n {/* General tags. */}\n <title>\n {title}\n </title>\n <meta name=\"description\" content={description} />\n\n {/* Twitter cards. */}\n <meta name=\"twitter:card\" content=\"summary_large_image\" />\n <meta name=\"twitter:title\" content={socTitle} />\n <meta name=\"twitter:description\" content={socDesc} />\n { image ? <meta name=\"twitter:image\" content={image} /> : null }\n {\n siteName ? (\n <meta name=\"twitter:site\" content={`@${siteName}`} />\n ) : null\n }\n\n {/* Open Graph data. */}\n <meta name=\"og:title\" content={socTitle} />\n { image ? <meta name=\"og:image\" content={image} /> : null }\n { image ? <meta name=\"og:image:alt\" content={socTitle} /> : null }\n <meta name=\"og:description\" content={socDesc} />\n {\n siteName ? (<meta name=\"og:sitename\" content={siteName} />) : null\n }\n { url ? (<meta name=\"og:url\" content={url} />) : null }\n </Helmet>\n {\n children ? (\n <Context.Provider value={context}>\n {children}\n </Context.Provider>\n ) : null\n }\n </>\n );\n};\n\nMetaTags.Context = Context;\n\nMetaTags.propTypes = {\n children: PT.node,\n description: PT.string.isRequired,\n image: PT.string,\n siteName: PT.string,\n socialDescription: PT.string,\n socialTitle: PT.string,\n title: PT.string.isRequired,\n url: PT.string,\n};\n\nexport default MetaTags;\n"],"mappings":"gLAAA,IAAAA,UAAA,CAAAC,sBAAA,CAAAC,OAAA,gBACA,IAAAC,MAAA,CAAAD,OAAA,UACA,IAAAE,YAAA,CAAAF,OAAA,iBAAsC,IAAAG,WAAA,CAAAH,OAAA,sBAatC,KAAM,CAAAI,OAAO,cAAG,GAAAC,oBAAa,EAAS,CACpCC,WAAW,CAAE,EAAE,CACfC,KAAK,CAAE,EACT,CAAC,CAAC,CAEF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAM,CAAAC,QAEL,CAAGA,CAAC,CACHC,QAAQ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cACN,GAAAR,WAAA,CAAAmB,GAAA,UAAMC,IAAI,CAAC,cAAc,CAACC,OAAO,
|
|
1
|
+
{"version":3,"file":"MetaTags.js","names":["_propTypes","_interopRequireDefault","require","_react","_reactHelmet","_jsxRuntime","Context","createContext","description","title","MetaTags","children","image","siteName","socialDescription","socialTitle","url","socTitle","socDesc","context","useMemo","jsxs","Fragment","Helmet","jsx","name","content","Provider","value","propTypes","PT","node","string","isRequired","_default","exports","default"],"sources":["../../../../src/shared/components/MetaTags.tsx"],"sourcesContent":["import PT from 'prop-types';\nimport { type ReactNode, createContext, useMemo } from 'react';\nimport { Helmet } from 'react-helmet';\n\ntype PropsT = {\n children?: ReactNode;\n description: string;\n image?: string;\n siteName?: string;\n socialDescription?: string;\n socialTitle?: string;\n title: string;\n url?: string;\n};\n\nconst Context = createContext<PropsT>({\n description: '',\n title: '',\n});\n\n/**\n * The `<MetaTags>` component is an auxiliary wrapper around `react-helmet`,\n * which helps to inject meta tags (page title, a brief content description,\n * and social media thumbnails) into generated pages.\n *\n * When `<MetaTags>` are nested within the app's component tree, meta tags\n * content injected by components encountered down the tree overrides tags\n * injected by previously encountered `<MetaTags>` components.\n *\n * **Children:** `<MetaTags>` children, if any, are rendered at the component's\n * location. The context passes down all meta tag properties of parent\n * `<MetaTag>` instances. These properties can fetched within children\n * hierarchy in the following way, thus facilitating tags modification by\n * children:\n * ```jsx\n * import { useContext } from 'react';\n * import { MetaTags } from '@dr.pogodin/react-utils';\n * export default function SampleComponent() {\n * const { title, description, ...rest } = useContext(MetaTags.Context);\n * // Do something with these props here, e.g. prefix the page title with\n * // the component name:\n * return (\n * <MetaTags title={`Sample component - ${title}`} />\n * );\n * }\n * ```\n * @param [props]\n * @param [props.description] Page description to use in\n * the `description` meta tag, and as a default description of Open Graph Tags.\n * @param [props.image] The absolute URL of thumbnail image to use\n * in Open Graph Tags (`twitter:image`, and `og:image`). By default these tags\n * are not injected.\n *\n * **BEWARE:** It must be a complete, absolute URL, including the correct\n * website domain and HTTP schema.\n *\n * @param [props.siteName]: The site name to use in `twitter:site`,\n * and `og:sitename` tags. By default these tags are not injected.\n *\n * @param [props.socialDescription] The site description to use in\n * `twitter:description` and `og:description` meta tags. By default the value of\n * `description` prop is used.\n * @param [props.socialTitle] The page title to use in\n * `twitter:title`, `og:title`, and `og:image:alt` tags. By default the value of\n * `title` prop is used. Also the `og:image:alt` tag is only injected if `image`\n * prop is present.\n *\n * @param props.title: The page name to use in the `<title>` tag.\n * It is also used as the default value of `socialTitle` prop.\n *\n * @param [props.url] The page URL to use in `og:url` tag.\n * By default the tag is not injected.\n */\nconst MetaTags: React.FunctionComponent<PropsT> & {\n Context: React.Context<PropsT>;\n} = ({\n children,\n description,\n image,\n siteName,\n socialDescription,\n socialTitle,\n title,\n url,\n}) => {\n const socTitle = socialTitle || title;\n const socDesc = socialDescription || description;\n\n const context = useMemo(() => ({\n description,\n image,\n siteName,\n socialDescription,\n socialTitle,\n title,\n url,\n }), [\n description,\n image,\n siteName,\n socialDescription,\n socialTitle,\n title,\n url,\n ]);\n\n return (\n <>\n <Helmet>\n {/* General tags. */}\n <title>\n {title}\n </title>\n <meta name=\"description\" content={description} />\n\n {/* Twitter cards. */}\n <meta name=\"twitter:card\" content=\"summary_large_image\" />\n <meta name=\"twitter:title\" content={socTitle} />\n <meta name=\"twitter:description\" content={socDesc} />\n { image ? <meta name=\"twitter:image\" content={image} /> : null }\n {\n siteName ? (\n <meta name=\"twitter:site\" content={`@${siteName}`} />\n ) : null\n }\n\n {/* Open Graph data. */}\n <meta name=\"og:title\" content={socTitle} />\n { image ? <meta name=\"og:image\" content={image} /> : null }\n { image ? <meta name=\"og:image:alt\" content={socTitle} /> : null }\n <meta name=\"og:description\" content={socDesc} />\n {\n siteName ? (<meta name=\"og:sitename\" content={siteName} />) : null\n }\n { url ? (<meta name=\"og:url\" content={url} />) : null }\n </Helmet>\n {\n children ? (\n <Context.Provider value={context}>\n {children}\n </Context.Provider>\n ) : null\n }\n </>\n );\n};\n\nMetaTags.Context = Context;\n\nMetaTags.propTypes = {\n children: PT.node,\n description: PT.string.isRequired,\n image: PT.string,\n siteName: PT.string,\n socialDescription: PT.string,\n socialTitle: PT.string,\n title: PT.string.isRequired,\n url: PT.string,\n};\n\nexport default MetaTags;\n"],"mappings":"gLAAA,IAAAA,UAAA,CAAAC,sBAAA,CAAAC,OAAA,gBACA,IAAAC,MAAA,CAAAD,OAAA,UACA,IAAAE,YAAA,CAAAF,OAAA,iBAAsC,IAAAG,WAAA,CAAAH,OAAA,sBAatC,KAAM,CAAAI,OAAO,cAAG,GAAAC,oBAAa,EAAS,CACpCC,WAAW,CAAE,EAAE,CACfC,KAAK,CAAE,EACT,CAAC,CAAC,CAEF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAM,CAAAC,QAEL,CAAGA,CAAC,CACHC,QAAQ,CACRH,WAAW,CACXI,KAAK,CACLC,QAAQ,CACRC,iBAAiB,CACjBC,WAAW,CACXN,KAAK,CACLO,GACF,CAAC,GAAK,CACJ,KAAM,CAAAC,QAAQ,CAAGF,WAAW,EAAIN,KAAK,CACrC,KAAM,CAAAS,OAAO,CAAGJ,iBAAiB,EAAIN,WAAW,CAEhD,KAAM,CAAAW,OAAO,CAAG,GAAAC,cAAO,EAAC,KAAO,CAC7BZ,WAAW,CACXI,KAAK,CACLC,QAAQ,CACRC,iBAAiB,CACjBC,WAAW,CACXN,KAAK,CACLO,GACF,CAAC,CAAC,CAAE,CACFR,WAAW,CACXI,KAAK,CACLC,QAAQ,CACRC,iBAAiB,CACjBC,WAAW,CACXN,KAAK,CACLO,GAAG,CACJ,CAAC,CAEF,mB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GAAA,UAAMC,IAAI,CAAC,gBAAgB,CAACC,OAAO,CAAER,OAAQ,CAAE,CAAC,CAE9CL,QAAQ,cAAI,GAAAR,WAAA,CAAAmB,GAAA,UAAMC,IAAI,CAAC,aAAa,CAACC,OAAO,CAAEb,QAAS,CAAE,CAAC,CAAI,IAAI,CAElEG,GAAG,cAAI,GAAAX,WAAA,CAAAmB,GAAA,UAAMC,IAAI,CAAC,QAAQ,CAACC,OAAO,CAAEV,GAAI,CAAE,CAAC,CAAI,IAAI,EAC/C,CAAC,CAEPL,QAAQ,cACN,GAAAN,WAAA,CAAAmB,GAAA,EAAClB,OAAO,CAACqB,QAAQ,EAACC,KAAK,CAAET,OAAQ,CAAAR,QAAA,CAC9BA,QAAQ,CACO,CAAC,CACjB,IAAI,EAEV,CAEN,CAAC,CAEDD,QAAQ,CAACJ,OAAO,CAAGA,OAAO,CAE1BI,QAAQ,CAACmB,SAAS,CAAG,CACnBlB,QAAQ,CAAEmB,kBAAE,CAACC,IAAI,CACjBvB,WAAW,CAAEsB,kBAAE,CAACE,MAAM,CAACC,UAAU,CACjCrB,KAAK,CAAEkB,kBAAE,CAACE,MAAM,CAChBnB,QAAQ,CAAEiB,kBAAE,CAACE,MAAM,CACnBlB,iBAAiB,CAAEgB,kBAAE,CAACE,MAAM,CAC5BjB,WAAW,CAAEe,kBAAE,CAACE,MAAM,CACtBvB,KAAK,CAAEqB,kBAAE,CAACE,MAAM,CAACC,UAAU,CAC3BjB,GAAG,CAAEc,kBAAE,CAACE,MACV,CAAC,CAAC,IAAAE,QAAA,CAAAC,OAAA,CAAAC,OAAA,CAEa1B,QAAQ","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_react","require","_propTypes","_interopRequireDefault","_reactThemes","_jsxRuntime","defaultTheme","validThemeKeys","TextArea","disabled","onChange","onKeyDown","placeholder","theme","value","hiddenAreaRef","useRef","height","setHeight","useState","localValue","setLocalValue","undefined","useEffect","el","current","cb","scrollHeight","observer","ResizeObserver","observe","disconnect","jsxs","className","container","children","jsx","readOnly","ref","textarea","hidden","e","target","style","ThemedTextArea","themed","propTypes","PT","bool","func","string","themeType","isRequired","_default","exports","default"],"sources":["../../../../../src/shared/components/TextArea/index.tsx"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\nimport PT from 'prop-types';\n\nimport themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './style.scss';\n\nconst validThemeKeys = [\n 'container',\n 'hidden',\n 'textarea',\n] as const;\n\ntype Props = {\n disabled?: boolean;\n onChange?: React.ChangeEventHandler<HTMLTextAreaElement>;\n onKeyDown?: React.KeyboardEventHandler<HTMLTextAreaElement>;\n placeholder?: string;\n theme: Theme<typeof validThemeKeys>;\n value?: string;\n};\n\nconst TextArea: React.FunctionComponent<Props> = ({\n disabled,\n onChange,\n onKeyDown,\n placeholder,\n theme,\n value,\n}) => {\n const hiddenAreaRef = useRef<HTMLTextAreaElement>(null);\n const [height, setHeight] = useState<number | undefined>();\n\n const [localValue, setLocalValue] = useState(value || '');\n if (value !== undefined && localValue !== value) setLocalValue(value);\n\n // This resizes text area's height when its width is changed for any reason.\n useEffect(() => {\n const el = hiddenAreaRef.current;\n if (!el) return undefined;\n\n const cb = () => {\n setHeight(el.scrollHeight);\n };\n const observer = new ResizeObserver(cb);\n observer.observe(el);\n\n return () => {\n observer.disconnect();\n };\n }, []);\n\n // This resizes the text area when its content is modified.\n useEffect(() => {\n const el = hiddenAreaRef.current;\n if (el) setHeight(el.scrollHeight);\n }, [localValue]);\n\n return (\n <div className={theme.container}>\n <textarea\n // This text area is hidden underneath the primary one below,\n // and it is used for text measurements, to implement auto-scaling\n // of the primary textarea's height.\n readOnly\n ref={hiddenAreaRef}\n className={`${theme.textarea} ${theme.hidden}`}\n value={localValue}\n />\n <textarea\n disabled={disabled}\n // When value is \"undefined\" the text area is not-managed, and we should\n // manage it internally for the measurement / resizing functionality\n // to work.\n onChange={value === undefined ? ((e) => {\n setLocalValue(e.target.value);\n }) : onChange}\n onKeyDown={onKeyDown}\n placeholder={placeholder}\n style={{ height }}\n className={theme.textarea}\n value={localValue}\n />\n </div>\n );\n};\n\nconst ThemedTextArea = themed(\n TextArea,\n 'TextArea',\n validThemeKeys,\n defaultTheme,\n);\n\nTextArea.propTypes = {\n disabled: PT.bool,\n onChange: PT.func,\n onKeyDown: PT.func,\n placeholder: PT.string,\n theme: ThemedTextArea.themeType.isRequired,\n value: PT.string,\n};\n\nexport default ThemedTextArea;\n"],"mappings":"gLAAA,IAAAA,MAAA,CAAAC,OAAA,UACA,IAAAC,UAAA,CAAAC,sBAAA,CAAAF,OAAA,gBAEA,IAAAG,YAAA,CAAAD,sBAAA,CAAAF,OAAA,8BAA8D,IAAAI,WAAA,CAAAJ,OAAA,4BAAAK,YAAA,+GAI9D,KAAM,CAAAC,cAAc,CAAG,CACrB,WAAW,CACX,QAAQ,CACR,UAAU,CACF,CAWV,KAAM,CAAAC,QAAwC,CAAGA,CAAC,CAChDC,QAAQ,CACRC,QAAQ,CACRC,SAAS,CACTC,WAAW,CACXC,KAAK,CACLC,KACF,CAAC,GAAK,CACJ,KAAM,CAAAC,aAAa,CAAG,GAAAC,aAAM,EAAsB,IAAI,CAAC,CACvD,KAAM,CAACC,MAAM,CAAEC,SAAS,CAAC,CAAG,GAAAC,eAAQ,EAAqB,CAAC,CAE1D,KAAM,CAACC,UAAU,CAAEC,aAAa,CAAC,CAAG,GAAAF,eAAQ,EAACL,KAAK,EAAI,EAAE,CAAC,CACzD,GAAIA,KAAK,GAAKQ,SAAS,EAAIF,UAAU,GAAKN,KAAK,CAAEO,aAAa,CAACP,KAAK,CAAC,CAErE;AACA,GAAAS,gBAAS,EAAC,IAAM,CACd,KAAM,CAAAC,EAAE,CAAGT,aAAa,CAACU,OAAO,CAChC,GAAI,CAACD,EAAE,CAAE,MAAO,CAAAF,SAAS,CAEzB,KAAM,CAAAI,EAAE,CAAGA,CAAA,GAAM,CACfR,SAAS,CAACM,EAAE,CAACG,YAAY,CAC3B,CAAC,CACD,KAAM,CAAAC,QAAQ,CAAG,GAAI,CAAAC,cAAc,CAACH,EAAE,CAAC,CACvCE,QAAQ,CAACE,OAAO,CAACN,EAAE,CAAC,CAEpB,MAAO,IAAM,CACXI,QAAQ,CAACG,UAAU,CAAC,CACtB,CACF,CAAC,CAAE,EAAE,CAAC,CAEN;AACA,GAAAR,gBAAS,EAAC,IAAM,CACd,KAAM,CAAAC,EAAE,CAAGT,aAAa,CAACU,OAAO,CAChC,GAAID,EAAE,CAAEN,SAAS,CAACM,EAAE,CAACG,YAAY,CACnC,CAAC,CAAE,CAACP,UAAU,CAAC,CAAC,CAEhB,mBACE,GAAAf,WAAA,CAAA2B,IAAA,SAAKC,SAAS,CAAEpB,KAAK,CAACqB,SAAU,CAAAC,QAAA,eAC9B,GAAA9B,WAAA,CAAA+B,GAAA,cACE;AACA;AACA;AACAC,QAAQ,MACRC,GAAG,CAAEvB,aAAc,CACnBkB,SAAS,
|
|
1
|
+
{"version":3,"file":"index.js","names":["_react","require","_propTypes","_interopRequireDefault","_reactThemes","_jsxRuntime","defaultTheme","validThemeKeys","TextArea","disabled","onChange","onKeyDown","placeholder","theme","value","hiddenAreaRef","useRef","height","setHeight","useState","localValue","setLocalValue","undefined","useEffect","el","current","cb","scrollHeight","observer","ResizeObserver","observe","disconnect","jsxs","className","container","children","jsx","readOnly","ref","textarea","hidden","e","target","style","ThemedTextArea","themed","propTypes","PT","bool","func","string","themeType","isRequired","_default","exports","default"],"sources":["../../../../../src/shared/components/TextArea/index.tsx"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\nimport PT from 'prop-types';\n\nimport themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './style.scss';\n\nconst validThemeKeys = [\n 'container',\n 'hidden',\n 'textarea',\n] as const;\n\ntype Props = {\n disabled?: boolean;\n onChange?: React.ChangeEventHandler<HTMLTextAreaElement>;\n onKeyDown?: React.KeyboardEventHandler<HTMLTextAreaElement>;\n placeholder?: string;\n theme: Theme<typeof validThemeKeys>;\n value?: string;\n};\n\nconst TextArea: React.FunctionComponent<Props> = ({\n disabled,\n onChange,\n onKeyDown,\n placeholder,\n theme,\n value,\n}) => {\n const hiddenAreaRef = useRef<HTMLTextAreaElement>(null);\n const [height, setHeight] = useState<number | undefined>();\n\n const [localValue, setLocalValue] = useState(value || '');\n if (value !== undefined && localValue !== value) setLocalValue(value);\n\n // This resizes text area's height when its width is changed for any reason.\n useEffect(() => {\n const el = hiddenAreaRef.current;\n if (!el) return undefined;\n\n const cb = () => {\n setHeight(el.scrollHeight);\n };\n const observer = new ResizeObserver(cb);\n observer.observe(el);\n\n return () => {\n observer.disconnect();\n };\n }, []);\n\n // This resizes the text area when its content is modified.\n useEffect(() => {\n const el = hiddenAreaRef.current;\n if (el) setHeight(el.scrollHeight);\n }, [localValue]);\n\n return (\n <div className={theme.container}>\n <textarea\n // This text area is hidden underneath the primary one below,\n // and it is used for text measurements, to implement auto-scaling\n // of the primary textarea's height.\n readOnly\n ref={hiddenAreaRef}\n className={`${theme.textarea} ${theme.hidden}`}\n value={localValue}\n />\n <textarea\n disabled={disabled}\n // When value is \"undefined\" the text area is not-managed, and we should\n // manage it internally for the measurement / resizing functionality\n // to work.\n onChange={value === undefined ? ((e) => {\n setLocalValue(e.target.value);\n }) : onChange}\n onKeyDown={onKeyDown}\n placeholder={placeholder}\n style={{ height }}\n className={theme.textarea}\n value={localValue}\n />\n </div>\n );\n};\n\nconst ThemedTextArea = themed(\n TextArea,\n 'TextArea',\n validThemeKeys,\n defaultTheme,\n);\n\nTextArea.propTypes = {\n disabled: PT.bool,\n onChange: PT.func,\n onKeyDown: PT.func,\n placeholder: PT.string,\n theme: ThemedTextArea.themeType.isRequired,\n value: PT.string,\n};\n\nexport default ThemedTextArea;\n"],"mappings":"gLAAA,IAAAA,MAAA,CAAAC,OAAA,UACA,IAAAC,UAAA,CAAAC,sBAAA,CAAAF,OAAA,gBAEA,IAAAG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version":3,"file":"Tooltip.js","names":["_react","require","_reactDom","_propTypes","_interopRequireDefault","PLACEMENTS","exports","ARROW_STYLE_DOWN","join","ARROW_STYLE_UP","validThemeKeys","createTooltipComponents","theme","arrow","document","createElement","setAttribute","content","container","appendChild","body","calcTooltipRects","tooltip","getBoundingClientRect","calcViewportRect","scrollX","scrollY","window","documentElement","clientHeight","clientWidth","left","right","top","bottom","calcPositionAboveXY","x","y","tooltipRects","arrowX","width","arrowY","height","containerX","containerY","baseArrowStyle","setComponentPositions","pageX","pageY","placement","element","viewportRect","pos","Math","max","maxX","min","containerStyle","arrowStyle","Tooltip","forwardRef","children","ref","current","heap","useRef","lastElement","undefined","lastPageX","lastPageY","lastPlacement","components","setComponents","useState","pointTo","useImperativeHandle","useEffect","removeChild","createPortal","propTypes","PT","node","shape","isRequired","_default","default"],"sources":["../../../../../src/shared/components/WithTooltip/Tooltip.tsx"],"sourcesContent":["/**\n * The actual tooltip component. It is rendered outside the regular document\n * hierarchy, and with sub-components managed without React to achieve the best\n * performance during animation.\n */\n/* global document, window */\n\nimport {\n type ReactNode,\n forwardRef,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from 'react';\n\nimport { createPortal } from 'react-dom';\n\nimport PT from 'prop-types';\n\nimport type { Theme } from '@dr.pogodin/react-themes';\n\n/* Valid placements of the rendered tooltip. They will be overriden when\n * necessary to fit the tooltip within the viewport. */\nexport enum PLACEMENTS {\n ABOVE_CURSOR = 'ABOVE_CURSOR',\n ABOVE_ELEMENT = 'ABOVE_ELEMENT',\n BELOW_CURSOR = 'BELOW_CURSOR',\n BELOW_ELEMENT = 'BELOW_ELEMENT',\n}\n\nconst ARROW_STYLE_DOWN = [\n 'border-bottom-color:transparent',\n 'border-left-color:transparent',\n 'border-right-color:transparent',\n].join(';');\n\nconst ARROW_STYLE_UP = [\n 'border-top-color:transparent',\n 'border-left-color:transparent',\n 'border-right-color:transparent',\n].join(';');\n\ntype ComponentsT = {\n container: HTMLDivElement;\n arrow: HTMLDivElement;\n content: HTMLDivElement;\n};\n\ntype HeapT = {\n lastElement?: HTMLElement;\n lastPageX: number;\n lastPageY: number;\n lastPlacement?: PLACEMENTS | undefined;\n};\n\nexport const validThemeKeys = [\n 'appearance',\n 'arrow',\n 'content',\n 'container',\n] as const;\n\ntype TooltipThemeT = Theme<typeof validThemeKeys>;\n\n/**\n * Creates tooltip components.\n * @ignore\n * @param {object} theme Themes to use for tooltip container, arrow,\n * and content.\n * @return {object} Object with DOM references to the container components:\n * container, arrow, content.\n */\nfunction createTooltipComponents(theme: TooltipThemeT): ComponentsT {\n const arrow = document.createElement('div');\n if (theme.arrow) arrow.setAttribute('class', theme.arrow);\n\n const content = document.createElement('div');\n if (theme.content) content.setAttribute('class', theme.content);\n\n const container = document.createElement('div');\n if (theme.container) container.setAttribute('class', theme.container);\n\n container.appendChild(arrow);\n container.appendChild(content);\n document.body.appendChild(container);\n\n return { container, arrow, content };\n}\n\ntype TooltipRectsT = {\n arrow: DOMRect;\n container: DOMRect;\n};\n\n/**\n * Generates bounding client rectangles for tooltip components.\n * @ignore\n * @param tooltip DOM references to the tooltip components.\n * @param tooltip.arrow\n * @param tooltip.container\n * @return Object holding tooltip rectangles in\n * two fields.\n */\nfunction calcTooltipRects(tooltip: ComponentsT): TooltipRectsT {\n return {\n arrow: tooltip.arrow.getBoundingClientRect(),\n container: tooltip.container.getBoundingClientRect(),\n };\n}\n\n/**\n * Calculates the document viewport size.\n * @ignore\n * @return {{x, y, width, height}}\n */\nfunction calcViewportRect() {\n const { scrollX, scrollY } = window;\n const { documentElement: { clientHeight, clientWidth } } = document;\n return {\n left: scrollX,\n right: scrollX + clientWidth,\n top: scrollY,\n bottom: scrollY + clientHeight,\n };\n}\n\n/**\n * Calculates tooltip and arrow positions for the placement just above\n * the cursor.\n * @ignore\n * @param {number} x Cursor page-x position.\n * @param {number} y Cursor page-y position.\n * @param {object} tooltipRects Bounding client rectangles of tooltip parts.\n * @param {object} tooltipRects.arrow\n * @param {object} tooltipRects.container\n * @return {object} Contains the following fields:\n * - {number} arrowX\n * - {number} arrowY\n * - {number} containerX\n * - {number} containerY\n * - {string} baseArrowStyle\n */\nfunction calcPositionAboveXY(\n x: number,\n y: number,\n tooltipRects: TooltipRectsT,\n) {\n const { arrow, container } = tooltipRects;\n return {\n arrowX: 0.5 * (container.width - arrow.width),\n arrowY: container.height,\n containerX: x - container.width / 2,\n containerY: y - container.height - arrow.height / 1.5,\n\n // TODO: Instead of already setting the base style here, we should\n // introduce a set of constants for arrow directions, which will help\n // to do checks dependant on the arrow direction.\n baseArrowStyle: ARROW_STYLE_DOWN,\n };\n}\n\n/*\nconst HIT = {\n NONE: false,\n LEFT: 'LEFT',\n RIGHT: 'RIGHT',\n TOP: 'TOP',\n BOTTOM: 'BOTTOM',\n};\n*/\n\n/**\n * Checks whether\n * @param {object} pos\n * @param {object} tooltipRects\n * @param {object} viewportRect\n * @return {HIT}\n */\n/*\nfunction checkViewportFit(pos, tooltipRects, viewportRect) {\n const { containerX, containerY } = pos;\n if (containerX < viewportRect.left + 6) return HIT.LEFT;\n if (containerX > viewportRect.right - 6) return HIT.RIGHT;\n return HIT.NONE;\n}\n*/\n\n/**\n * Shifts tooltip horizontally to fit into the viewport, while keeping\n * the arrow pointed to the XY point.\n * @param {number} x\n * @param {number} y\n * @param {object} pos\n * @param {number} pageXOffset\n * @param {number} pageXWidth\n */\n/*\nfunction xPageFitCorrection(x, y, pos, pageXOffset, pageXWidth) {\n if (pos.containerX < pageXOffset + 6) {\n pos.containerX = pageXOffset + 6;\n pos.arrowX = Math.max(6, pageX - containerX - arrowRect.width / 2);\n } else {\n const maxX = pageXOffset + docRect.width - containerRect.width - 6;\n if (containerX > maxX) {\n containerX = maxX;\n arrowX = Math.min(\n containerRect.width - 6,\n pageX - containerX - arrowRect.width / 2,\n );\n }\n }\n}\n*/\n\n/**\n * Sets positions of tooltip components to point the tooltip to the specified\n * page point.\n * @ignore\n * @param pageX\n * @param pageY\n * @param placement\n * @param element DOM reference to the element wrapped by the tooltip.\n * @param tooltip\n * @param tooltip.arrow DOM reference to the tooltip arrow.\n * @param tooltip.container DOM reference to the tooltip container.\n */\nfunction setComponentPositions(\n pageX: number,\n pageY: number,\n placement: PLACEMENTS | undefined,\n element: HTMLElement | undefined,\n tooltip: ComponentsT,\n) {\n const tooltipRects = calcTooltipRects(tooltip);\n const viewportRect = calcViewportRect();\n\n /* Default container coords: tooltip at the top. */\n const pos = calcPositionAboveXY(pageX, pageY, tooltipRects);\n\n if (pos.containerX < viewportRect.left + 6) {\n pos.containerX = viewportRect.left + 6;\n pos.arrowX = Math.max(\n 6,\n pageX - pos.containerX - tooltipRects.arrow.width / 2,\n );\n } else {\n const maxX = viewportRect.right - 6 - tooltipRects.container.width;\n if (pos.containerX > maxX) {\n pos.containerX = maxX;\n pos.arrowX = Math.min(\n tooltipRects.container.width - 6,\n pageX - pos.containerX - tooltipRects.arrow.width / 2,\n );\n }\n }\n\n /* If tooltip has not enough space on top - make it bottom tooltip. */\n if (pos.containerY < viewportRect.top + 6) {\n pos.containerY += tooltipRects.container.height\n + 2 * tooltipRects.arrow.height;\n pos.arrowY -= tooltipRects.container.height\n + tooltipRects.arrow.height;\n pos.baseArrowStyle = ARROW_STYLE_UP;\n }\n\n const containerStyle = `left:${pos.containerX}px;top:${pos.containerY}px`;\n tooltip.container.setAttribute('style', containerStyle);\n\n const arrowStyle = `${pos.baseArrowStyle};left:${pos.arrowX}px;top:${pos.arrowY}px`;\n tooltip.arrow.setAttribute('style', arrowStyle);\n}\n\n/* The Tooltip component itself. */\nconst Tooltip = forwardRef<unknown, {\n children?: ReactNode;\n theme: any;\n}>(({ children, theme }, ref) => {\n // NOTE: The way it has to be implemented, for clean mounting and unmounting\n // at the client side, the <Tooltip> is fully mounted into DOM in the next\n // rendering cycles, and only then it can be correctly measured and positioned.\n // Thus, when we create the <Tooltip> we have to record its target positioning\n // details, and then apply them when it is created.\n\n const { current: heap } = useRef<HeapT>({\n lastElement: undefined,\n lastPageX: 0,\n lastPageY: 0,\n lastPlacement: undefined,\n });\n\n const [components, setComponents] = useState<ComponentsT | null>(null);\n\n const pointTo = (\n pageX: number,\n pageY: number,\n placement: PLACEMENTS,\n element: HTMLElement,\n ) => {\n heap.lastElement = element;\n heap.lastPageX = pageX;\n heap.lastPageY = pageY;\n heap.lastPlacement = placement;\n\n if (components) {\n setComponentPositions(pageX, pageY, placement, element, components);\n }\n };\n useImperativeHandle(ref, () => ({ pointTo }));\n\n /* Inits and destroys tooltip components. */\n useEffect(() => {\n const x = createTooltipComponents(theme);\n setComponents(x);\n return () => {\n document.body.removeChild(x.container);\n setComponents(null);\n };\n }, [theme]);\n\n useEffect(() => {\n if (components) {\n setComponentPositions(\n heap.lastPageX,\n heap.lastPageY,\n heap.lastPlacement,\n heap.lastElement,\n components,\n );\n }\n }, [\n components,\n // BEWARE: Careful about these dependencies - they are updated when mouse\n // is moved over the tool-tipped element, thus potentially may cause\n // unnecessary firing of this effect on each mouse event. It does not\n // happen now just because the mouse movements themselves are not causing\n // the component re-rendering, thus dependencies of this effect are not\n // really re-evaluated.\n heap.lastPageX,\n heap.lastPageY,\n heap.lastPlacement,\n heap.lastElement,\n ]);\n\n return components ? createPortal(children, components.content) : null;\n});\n\nTooltip.propTypes = {\n children: PT.node,\n theme: PT.shape({}).isRequired,\n};\n\nexport default Tooltip;\n"],"mappings":"0NAOA,IAAAA,MAAA,CAAAC,OAAA,UASA,IAAAC,SAAA,CAAAD,OAAA,cAEA,IAAAE,UAAA,CAAAC,sBAAA,CAAAH,OAAA,gBAlBA;AACA;AACA;AACA;AACA,GAJA,CAKA,8BAiBA;AACA,uDADA,GAEY,CAAAI,UAAU,CAAAC,OAAA,CAAAD,UAAA,uBAAVA,UAAU,EAAVA,UAAU,gCAAVA,UAAU,kCAAVA,UAAU,gCAAVA,UAAU,wCAAV,CAAAA,UAAU,MAOtB,KAAM,CAAAE,gBAAgB,CAAG,CACvB,iCAAiC,CACjC,+BAA+B,CAC/B,gCAAg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OAAO","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"Tooltip.js","names":["_react","require","_reactDom","_propTypes","_interopRequireDefault","PLACEMENTS","exports","ARROW_STYLE_DOWN","join","ARROW_STYLE_UP","validThemeKeys","createTooltipComponents","theme","arrow","document","createElement","setAttribute","content","container","appendChild","body","calcTooltipRects","tooltip","getBoundingClientRect","calcViewportRect","scrollX","scrollY","window","documentElement","clientHeight","clientWidth","left","right","top","bottom","calcPositionAboveXY","x","y","tooltipRects","arrowX","width","arrowY","height","containerX","containerY","baseArrowStyle","setComponentPositions","pageX","pageY","placement","element","viewportRect","pos","Math","max","maxX","min","containerStyle","arrowStyle","Tooltip","forwardRef","children","ref","current","heap","useRef","lastElement","undefined","lastPageX","lastPageY","lastPlacement","components","setComponents","useState","pointTo","useImperativeHandle","useEffect","removeChild","createPortal","propTypes","PT","node","shape","isRequired","_default","default"],"sources":["../../../../../src/shared/components/WithTooltip/Tooltip.tsx"],"sourcesContent":["/**\n * The actual tooltip component. It is rendered outside the regular document\n * hierarchy, and with sub-components managed without React to achieve the best\n * performance during animation.\n */\n/* global document, window */\n\nimport {\n type ReactNode,\n forwardRef,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from 'react';\n\nimport { createPortal } from 'react-dom';\n\nimport PT from 'prop-types';\n\nimport type { Theme } from '@dr.pogodin/react-themes';\n\n/* Valid placements of the rendered tooltip. They will be overriden when\n * necessary to fit the tooltip within the viewport. */\nexport enum PLACEMENTS {\n ABOVE_CURSOR = 'ABOVE_CURSOR',\n ABOVE_ELEMENT = 'ABOVE_ELEMENT',\n BELOW_CURSOR = 'BELOW_CURSOR',\n BELOW_ELEMENT = 'BELOW_ELEMENT',\n}\n\nconst ARROW_STYLE_DOWN = [\n 'border-bottom-color:transparent',\n 'border-left-color:transparent',\n 'border-right-color:transparent',\n].join(';');\n\nconst ARROW_STYLE_UP = [\n 'border-top-color:transparent',\n 'border-left-color:transparent',\n 'border-right-color:transparent',\n].join(';');\n\ntype ComponentsT = {\n container: HTMLDivElement;\n arrow: HTMLDivElement;\n content: HTMLDivElement;\n};\n\ntype HeapT = {\n lastElement?: HTMLElement;\n lastPageX: number;\n lastPageY: number;\n lastPlacement?: PLACEMENTS | undefined;\n};\n\nexport const validThemeKeys = [\n 'appearance',\n 'arrow',\n 'content',\n 'container',\n] as const;\n\ntype TooltipThemeT = Theme<typeof validThemeKeys>;\n\n/**\n * Creates tooltip components.\n * @ignore\n * @param {object} theme Themes to use for tooltip container, arrow,\n * and content.\n * @return {object} Object with DOM references to the container components:\n * container, arrow, content.\n */\nfunction createTooltipComponents(theme: TooltipThemeT): ComponentsT {\n const arrow = document.createElement('div');\n if (theme.arrow) arrow.setAttribute('class', theme.arrow);\n\n const content = document.createElement('div');\n if (theme.content) content.setAttribute('class', theme.content);\n\n const container = document.createElement('div');\n if (theme.container) container.setAttribute('class', theme.container);\n\n container.appendChild(arrow);\n container.appendChild(content);\n document.body.appendChild(container);\n\n return { container, arrow, content };\n}\n\ntype TooltipRectsT = {\n arrow: DOMRect;\n container: DOMRect;\n};\n\n/**\n * Generates bounding client rectangles for tooltip components.\n * @ignore\n * @param tooltip DOM references to the tooltip components.\n * @param tooltip.arrow\n * @param tooltip.container\n * @return Object holding tooltip rectangles in\n * two fields.\n */\nfunction calcTooltipRects(tooltip: ComponentsT): TooltipRectsT {\n return {\n arrow: tooltip.arrow.getBoundingClientRect(),\n container: tooltip.container.getBoundingClientRect(),\n };\n}\n\n/**\n * Calculates the document viewport size.\n * @ignore\n * @return {{x, y, width, height}}\n */\nfunction calcViewportRect() {\n const { scrollX, scrollY } = window;\n const { documentElement: { clientHeight, clientWidth } } = document;\n return {\n left: scrollX,\n right: scrollX + clientWidth,\n top: scrollY,\n bottom: scrollY + clientHeight,\n };\n}\n\n/**\n * Calculates tooltip and arrow positions for the placement just above\n * the cursor.\n * @ignore\n * @param {number} x Cursor page-x position.\n * @param {number} y Cursor page-y position.\n * @param {object} tooltipRects Bounding client rectangles of tooltip parts.\n * @param {object} tooltipRects.arrow\n * @param {object} tooltipRects.container\n * @return {object} Contains the following fields:\n * - {number} arrowX\n * - {number} arrowY\n * - {number} containerX\n * - {number} containerY\n * - {string} baseArrowStyle\n */\nfunction calcPositionAboveXY(\n x: number,\n y: number,\n tooltipRects: TooltipRectsT,\n) {\n const { arrow, container } = tooltipRects;\n return {\n arrowX: 0.5 * (container.width - arrow.width),\n arrowY: container.height,\n containerX: x - container.width / 2,\n containerY: y - container.height - arrow.height / 1.5,\n\n // TODO: Instead of already setting the base style here, we should\n // introduce a set of constants for arrow directions, which will help\n // to do checks dependant on the arrow direction.\n baseArrowStyle: ARROW_STYLE_DOWN,\n };\n}\n\n/*\nconst HIT = {\n NONE: false,\n LEFT: 'LEFT',\n RIGHT: 'RIGHT',\n TOP: 'TOP',\n BOTTOM: 'BOTTOM',\n};\n*/\n\n/**\n * Checks whether\n * @param {object} pos\n * @param {object} tooltipRects\n * @param {object} viewportRect\n * @return {HIT}\n */\n/*\nfunction checkViewportFit(pos, tooltipRects, viewportRect) {\n const { containerX, containerY } = pos;\n if (containerX < viewportRect.left + 6) return HIT.LEFT;\n if (containerX > viewportRect.right - 6) return HIT.RIGHT;\n return HIT.NONE;\n}\n*/\n\n/**\n * Shifts tooltip horizontally to fit into the viewport, while keeping\n * the arrow pointed to the XY point.\n * @param {number} x\n * @param {number} y\n * @param {object} pos\n * @param {number} pageXOffset\n * @param {number} pageXWidth\n */\n/*\nfunction xPageFitCorrection(x, y, pos, pageXOffset, pageXWidth) {\n if (pos.containerX < pageXOffset + 6) {\n pos.containerX = pageXOffset + 6;\n pos.arrowX = Math.max(6, pageX - containerX - arrowRect.width / 2);\n } else {\n const maxX = pageXOffset + docRect.width - containerRect.width - 6;\n if (containerX > maxX) {\n containerX = maxX;\n arrowX = Math.min(\n containerRect.width - 6,\n pageX - containerX - arrowRect.width / 2,\n );\n }\n }\n}\n*/\n\n/**\n * Sets positions of tooltip components to point the tooltip to the specified\n * page point.\n * @ignore\n * @param pageX\n * @param pageY\n * @param placement\n * @param element DOM reference to the element wrapped by the tooltip.\n * @param tooltip\n * @param tooltip.arrow DOM reference to the tooltip arrow.\n * @param tooltip.container DOM reference to the tooltip container.\n */\nfunction setComponentPositions(\n pageX: number,\n pageY: number,\n placement: PLACEMENTS | undefined,\n element: HTMLElement | undefined,\n tooltip: ComponentsT,\n) {\n const tooltipRects = calcTooltipRects(tooltip);\n const viewportRect = calcViewportRect();\n\n /* Default container coords: tooltip at the top. */\n const pos = calcPositionAboveXY(pageX, pageY, tooltipRects);\n\n if (pos.containerX < viewportRect.left + 6) {\n pos.containerX = viewportRect.left + 6;\n pos.arrowX = Math.max(\n 6,\n pageX - pos.containerX - tooltipRects.arrow.width / 2,\n );\n } else {\n const maxX = viewportRect.right - 6 - tooltipRects.container.width;\n if (pos.containerX > maxX) {\n pos.containerX = maxX;\n pos.arrowX = Math.min(\n tooltipRects.container.width - 6,\n pageX - pos.containerX - tooltipRects.arrow.width / 2,\n );\n }\n }\n\n /* If tooltip has not enough space on top - make it bottom tooltip. */\n if (pos.containerY < viewportRect.top + 6) {\n pos.containerY += tooltipRects.container.height\n + 2 * tooltipRects.arrow.height;\n pos.arrowY -= tooltipRects.container.height\n + tooltipRects.arrow.height;\n pos.baseArrowStyle = ARROW_STYLE_UP;\n }\n\n const containerStyle = `left:${pos.containerX}px;top:${pos.containerY}px`;\n tooltip.container.setAttribute('style', containerStyle);\n\n const arrowStyle = `${pos.baseArrowStyle};left:${pos.arrowX}px;top:${pos.arrowY}px`;\n tooltip.arrow.setAttribute('style', arrowStyle);\n}\n\n/* The Tooltip component itself. */\nconst Tooltip = forwardRef<unknown, {\n children?: ReactNode;\n theme: any;\n}>(({ children, theme }, ref) => {\n // NOTE: The way it has to be implemented, for clean mounting and unmounting\n // at the client side, the <Tooltip> is fully mounted into DOM in the next\n // rendering cycles, and only then it can be correctly measured and positioned.\n // Thus, when we create the <Tooltip> we have to record its target positioning\n // details, and then apply them when it is created.\n\n const { current: heap } = useRef<HeapT>({\n lastElement: undefined,\n lastPageX: 0,\n lastPageY: 0,\n lastPlacement: undefined,\n });\n\n const [components, setComponents] = useState<ComponentsT | null>(null);\n\n const pointTo = (\n pageX: number,\n pageY: number,\n placement: PLACEMENTS,\n element: HTMLElement,\n ) => {\n heap.lastElement = element;\n heap.lastPageX = pageX;\n heap.lastPageY = pageY;\n heap.lastPlacement = placement;\n\n if (components) {\n setComponentPositions(pageX, pageY, placement, element, components);\n }\n };\n useImperativeHandle(ref, () => ({ pointTo }));\n\n /* Inits and destroys tooltip components. */\n useEffect(() => {\n const x = createTooltipComponents(theme);\n setComponents(x);\n return () => {\n document.body.removeChild(x.container);\n setComponents(null);\n };\n }, [theme]);\n\n useEffect(() => {\n if (components) {\n setComponentPositions(\n heap.lastPageX,\n heap.lastPageY,\n heap.lastPlacement,\n heap.lastElement,\n components,\n );\n }\n }, [\n components,\n // BEWARE: Careful about these dependencies - they are updated when mouse\n // is moved over the tool-tipped element, thus potentially may cause\n // unnecessary firing of this effect on each mouse event. It does not\n // happen now just because the mouse movements themselves are not causing\n // the component re-rendering, thus dependencies of this effect are not\n // really re-evaluated.\n heap.lastPageX,\n heap.lastPageY,\n heap.lastPlacement,\n heap.lastElement,\n ]);\n\n return components ? createPortal(children, components.content) : null;\n});\n\nTooltip.propTypes = {\n children: PT.node,\n theme: PT.shape({}).isRequired,\n};\n\nexport default Tooltip;\n"],"mappings":"0NAOA,IAAAA,MAAA,CAAAC,OAAA,UASA,IAAAC,SAAA,CAAAD,OAAA,cAEA,IAAAE,UAAA,CAAAC,sBAAA,CAAAH,OAAA,gBAlBA;AACA;AACA;AACA;AACA,GAJA,CAKA,8BAiBA;AACA,uDADA,GAEY,CAAAI,UAAU,CAAAC,OAAA,CAAAD,UAAA,uBAAVA,UAAU,EAAVA,UAAU,gCAAVA,UAAU,kCAAVA,UAAU,gCAAVA,UAAU,wCAAV,CAAAA,UAAU,MAOtB,KAAM,CAAAE,gBAAgB,CAAG,CACvB,iCA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A9E,OAAA,CAAA+E,OAAA,CAEa1B,OAAO","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_propTypes","_interopRequireDefault","require","_qs","_reactThemes","_Throbber","_jsxRuntime","baseTheme","throbberTheme","validThemeKeys","YouTubeVideo","autoplay","src","theme","title","srcParts","split","url","queryString","query","qs","parse","videoId","v","match","stringify","jsxs","className","container","children","jsx","default","allow","allowFullScreen","video","ThemedYouTubeVideo","themed","propTypes","PT","bool","string","isRequired","themeType","_default","exports"],"sources":["../../../../../src/shared/components/YouTubeVideo/index.tsx"],"sourcesContent":["import PT from 'prop-types';\nimport qs from 'qs';\n\nimport themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport Throbber from 'components/Throbber';\n\nimport baseTheme from './base.scss';\nimport throbberTheme from './throbber.scss';\n\nconst validThemeKeys = ['container', 'video'] as const;\n\ntype ComponentThemeT = Theme<typeof validThemeKeys>;\n\ntype PropsT = {\n autoplay?: boolean;\n src: string;\n theme: ComponentThemeT,\n title?: string;\n};\n\n/**\n * A component for embeding a YouTube video.\n * @param [props] Component properties.\n * @param [props.autoplay] If `true` the video will start to play\n * automatically once loaded.\n * @param [props.src] URL of the video to play. Can be in any of\n * the following formats, and keeps any additional query parameters understood\n * by the YouTube IFrame player:\n * - `https://www.youtube.com/watch?v=NdF6Rmt6Ado`\n * - `https://youtu.be/NdF6Rmt6Ado`\n * - `https://www.youtube.com/embed/NdF6Rmt6Ado`\n * @param [props.theme] _Ad hoc_ theme.\n * @param [props.title] The `title` attribute to add to the player\n * IFrame.\n */\nconst YouTubeVideo: React.FunctionComponent<PropsT> = ({\n autoplay,\n src,\n theme,\n title,\n}) => {\n const srcParts = src.split('?');\n let url = srcParts[0];\n const queryString = srcParts[1];\n const query = queryString ? qs.parse(queryString) : {};\n\n const videoId = query.v || url.match(/\\/([a-zA-Z0-9-_]*)$/)?.[1];\n url = `https://www.youtube.com/embed/${videoId}`;\n\n delete query.v;\n query.autoplay = autoplay ? '1' : '0';\n url += `?${qs.stringify(query)}`;\n\n // TODO: https://developers.google.com/youtube/player_parameters\n // More query parameters can be exposed via the component props.\n\n return (\n <div className={theme.container}>\n <Throbber theme={throbberTheme} />\n <iframe\n allow=\"autoplay\"\n allowFullScreen\n className={theme.video}\n src={url}\n title={title}\n />\n </div>\n );\n};\n\nconst ThemedYouTubeVideo = themed(\n YouTubeVideo,\n 'YouTubeVideo',\n validThemeKeys,\n baseTheme,\n);\n\nYouTubeVideo.propTypes = {\n autoplay: PT.bool,\n src: PT.string.isRequired,\n theme: ThemedYouTubeVideo.themeType.isRequired,\n title: PT.string,\n};\n\nexport default ThemedYouTubeVideo;\n"],"mappings":"gLAAA,IAAAA,UAAA,CAAAC,sBAAA,CAAAC,OAAA,gBACA,IAAAC,GAAA,CAAAF,sBAAA,CAAAC,OAAA,QAEA,IAAAE,YAAA,CAAAH,sBAAA,CAAAC,OAAA,8BAEA,IAAAG,SAAA,CAAAJ,sBAAA,CAAAC,OAAA,iBAA2C,IAAAI,WAAA,CAAAJ,OAAA,4BAAAK,SAAA,+FAAAC,aAAA,0EAK3C,KAAM,CAAAC,cAAc,CAAG,CAAC,WAAW,CAAE,OAAO,CAAU,CAWtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAM,CAAAC,YAA6C,CAAGA,CAAC,CACrDC,QAAQ,CACRC,GAAG,CACHC,KAAK,CACLC,KACF,CAAC,GAAK,CACJ,KAAM,CAAAC,QAAQ,CAAGH,GAAG,CAACI,KAAK,CAAC,GAAG,CAAC,CAC/B,GAAI,CAAAC,GAAG,CAAGF,QAAQ,CAAC,CAAC,CAAC,CACrB,KAAM,CAAAG,WAAW,CAAGH,QAAQ,CAAC,CAAC,CAAC,CAC/B,KAAM,CAAAI,KAAK,CAAGD,WAAW,CAAGE,WAAE,CAACC,KAAK,CAACH,WAAW,CAAC,CAAG,CAAC,CAAC,CAEtD,KAAM,CAAAI,OAAO,CAAGH,KAAK,CAACI,CAAC,EAAIN,GAAG,CAACO,KAAK,CAAC,qBAAqB,CAAC,GAAG,CAAC,CAAC,CAChEP,GAAG,
|
|
1
|
+
{"version":3,"file":"index.js","names":["_propTypes","_interopRequireDefault","require","_qs","_reactThemes","_Throbber","_jsxRuntime","baseTheme","throbberTheme","validThemeKeys","YouTubeVideo","autoplay","src","theme","title","srcParts","split","url","queryString","query","qs","parse","videoId","v","match","stringify","jsxs","className","container","children","jsx","default","allow","allowFullScreen","video","ThemedYouTubeVideo","themed","propTypes","PT","bool","string","isRequired","themeType","_default","exports"],"sources":["../../../../../src/shared/components/YouTubeVideo/index.tsx"],"sourcesContent":["import PT from 'prop-types';\nimport qs from 'qs';\n\nimport themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport Throbber from 'components/Throbber';\n\nimport baseTheme from './base.scss';\nimport throbberTheme from './throbber.scss';\n\nconst validThemeKeys = ['container', 'video'] as const;\n\ntype ComponentThemeT = Theme<typeof validThemeKeys>;\n\ntype PropsT = {\n autoplay?: boolean;\n src: string;\n theme: ComponentThemeT,\n title?: string;\n};\n\n/**\n * A component for embeding a YouTube video.\n * @param [props] Component properties.\n * @param [props.autoplay] If `true` the video will start to play\n * automatically once loaded.\n * @param [props.src] URL of the video to play. Can be in any of\n * the following formats, and keeps any additional query parameters understood\n * by the YouTube IFrame player:\n * - `https://www.youtube.com/watch?v=NdF6Rmt6Ado`\n * - `https://youtu.be/NdF6Rmt6Ado`\n * - `https://www.youtube.com/embed/NdF6Rmt6Ado`\n * @param [props.theme] _Ad hoc_ theme.\n * @param [props.title] The `title` attribute to add to the player\n * IFrame.\n */\nconst YouTubeVideo: React.FunctionComponent<PropsT> = ({\n autoplay,\n src,\n theme,\n title,\n}) => {\n const srcParts = src.split('?');\n let url = srcParts[0];\n const queryString = srcParts[1];\n const query = queryString ? qs.parse(queryString) : {};\n\n const videoId = query.v || url.match(/\\/([a-zA-Z0-9-_]*)$/)?.[1];\n url = `https://www.youtube.com/embed/${videoId}`;\n\n delete query.v;\n query.autoplay = autoplay ? '1' : '0';\n url += `?${qs.stringify(query)}`;\n\n // TODO: https://developers.google.com/youtube/player_parameters\n // More query parameters can be exposed via the component props.\n\n return (\n <div className={theme.container}>\n <Throbber theme={throbberTheme} />\n <iframe\n allow=\"autoplay\"\n allowFullScreen\n className={theme.video}\n src={url}\n title={title}\n />\n </div>\n );\n};\n\nconst ThemedYouTubeVideo = themed(\n YouTubeVideo,\n 'YouTubeVideo',\n validThemeKeys,\n baseTheme,\n);\n\nYouTubeVideo.propTypes = {\n autoplay: PT.bool,\n src: PT.string.isRequired,\n theme: ThemedYouTubeVideo.themeType.isRequired,\n title: PT.string,\n};\n\nexport default ThemedYouTubeVideo;\n"],"mappings":"gLAAA,IAAAA,UAAA,CAAAC,sBAAA,CAAAC,OAAA,gBACA,IAAAC,GAAA,CAAAF,sBAAA,CAAAC,OAAA,QAEA,IAAAE,YAAA,CAAAH,sBAAA,CAAAC,OAAA,8BAEA,IAAAG,SAAA,CAAAJ,sBAAA,CAAAC,OAAA,iBAA2C,IAAAI,WAAA,CAAAJ,OAAA,4BAAAK,SAAA,+FAAAC,aAAA,0EAK3C,KAAM,CAAAC,cAAc,CAAG,CAAC,WAAW,CAAE,OAAO,CAAU,CAWtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAM,CAAAC,YAA6C,CAAGA,CAAC,CACrDC,QAAQ,CACRC,GAAG,CACHC,KAAK,CACLC,KACF,CAAC,GAAK,CACJ,KAAM,CAAAC,QAAQ,CAAGH,GAAG,CAACI,KAAK,CAAC,GAAG,CAAC,CAC/B,GAAI,CAAAC,GAAG,CAAGF,QAAQ,CAAC,CAAC,CAAC,CACrB,KAAM,CAAAG,WAAW,CAAGH,QAAQ,CAAC,CAAC,CAAC,CAC/B,KAAM,CAAAI,KAAK,CAAGD,WAAW,CAAGE,WAAE,CAACC,KAAK,CAAC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babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});var _exportNames={Button:true,Checkbox:true,Input:true,Link:true,PageLayout:true,MetaTags:true,Modal:true,BaseModal:true,NavLink:true,Throbber:true,WithTooltip:true,YouTubeVideo:true,TextArea:true};Object.defineProperty(exports,"BaseModal",{enumerable:true,get:function(){return _Modal.BaseModal}});Object.defineProperty(exports,"Button",{enumerable:true,get:function(){return _Button.default}});Object.defineProperty(exports,"Checkbox",{enumerable:true,get:function(){return _Checkbox.default}});Object.defineProperty(exports,"Input",{enumerable:true,get:function(){return _Input.default}});Object.defineProperty(exports,"Link",{enumerable:true,get:function(){return _Link.default}});Object.defineProperty(exports,"MetaTags",{enumerable:true,get:function(){return _MetaTags.default}});Object.defineProperty(exports,"Modal",{enumerable:true,get:function(){return _Modal.default}});Object.defineProperty(exports,"NavLink",{enumerable:true,get:function(){return _NavLink.default}});Object.defineProperty(exports,"PageLayout",{enumerable:true,get:function(){return _PageLayout.default}});Object.defineProperty(exports,"TextArea",{enumerable:true,get:function(){return _TextArea.default}});Object.defineProperty(exports,"Throbber",{enumerable:true,get:function(){return _Throbber.default}});Object.defineProperty(exports,"WithTooltip",{enumerable:true,get:function(){return _WithTooltip.default}});Object.defineProperty(exports,"YouTubeVideo",{enumerable:true,get:function(){return _YouTubeVideo.default}});var _selectors=require("./selectors");Object.keys(_selectors).forEach(function(key){if(key==="default"||key==="__esModule")return;if(Object.prototype.hasOwnProperty.call(_exportNames,key))return;if(key in exports&&exports[key]===_selectors[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _selectors[key]}})});var _Button=
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});var _exportNames={Button:true,BaseButton:true,Checkbox:true,Input:true,Link:true,PageLayout:true,MetaTags:true,Modal:true,BaseModal:true,NavLink:true,Throbber:true,WithTooltip:true,YouTubeVideo:true,TextArea:true};Object.defineProperty(exports,"BaseButton",{enumerable:true,get:function(){return _Button.BaseButton}});Object.defineProperty(exports,"BaseModal",{enumerable:true,get:function(){return _Modal.BaseModal}});Object.defineProperty(exports,"Button",{enumerable:true,get:function(){return _Button.default}});Object.defineProperty(exports,"Checkbox",{enumerable:true,get:function(){return _Checkbox.default}});Object.defineProperty(exports,"Input",{enumerable:true,get:function(){return _Input.default}});Object.defineProperty(exports,"Link",{enumerable:true,get:function(){return _Link.default}});Object.defineProperty(exports,"MetaTags",{enumerable:true,get:function(){return _MetaTags.default}});Object.defineProperty(exports,"Modal",{enumerable:true,get:function(){return _Modal.default}});Object.defineProperty(exports,"NavLink",{enumerable:true,get:function(){return _NavLink.default}});Object.defineProperty(exports,"PageLayout",{enumerable:true,get:function(){return _PageLayout.default}});Object.defineProperty(exports,"TextArea",{enumerable:true,get:function(){return _TextArea.default}});Object.defineProperty(exports,"Throbber",{enumerable:true,get:function(){return _Throbber.default}});Object.defineProperty(exports,"WithTooltip",{enumerable:true,get:function(){return _WithTooltip.default}});Object.defineProperty(exports,"YouTubeVideo",{enumerable:true,get:function(){return _YouTubeVideo.default}});var _selectors=require("./selectors");Object.keys(_selectors).forEach(function(key){if(key==="default"||key==="__esModule")return;if(Object.prototype.hasOwnProperty.call(_exportNames,key))return;if(key in exports&&exports[key]===_selectors[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _selectors[key]}})});var _Button=_interopRequireWildcard(require("./Button"));var _Checkbox=_interopRequireDefault(require("./Checkbox"));var _Input=_interopRequireDefault(require("./Input"));var _Link=_interopRequireDefault(require("./Link"));var _PageLayout=_interopRequireDefault(require("./PageLayout"));var _MetaTags=_interopRequireDefault(require("./MetaTags"));var _Modal=_interopRequireWildcard(require("./Modal"));var _NavLink=_interopRequireDefault(require("./NavLink"));var _Throbber=_interopRequireDefault(require("./Throbber"));var _WithTooltip=_interopRequireDefault(require("./WithTooltip"));var _YouTubeVideo=_interopRequireDefault(require("./YouTubeVideo"));var _TextArea=_interopRequireDefault(require("./TextArea"));function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var r=new WeakMap,t=new WeakMap;return(_getRequireWildcardCache=function(e){return e?t:r})(e)}function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var t=_getRequireWildcardCache(r);if(t&&t.has(e))return t.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in e)if("default"!==u&&{}.hasOwnProperty.call(e,u)){var i=a?Object.getOwnPropertyDescriptor(e,u):null;i&&(i.get||i.set)?Object.defineProperty(n,u,i):n[u]=e[u]}return n.default=e,t&&t.set(e,n),n}
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_selectors","require","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_Button","
|
|
1
|
+
{"version":3,"file":"index.js","names":["_selectors","require","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_Button","_interopRequireWildcard","_Checkbox","_interopRequireDefault","_Input","_Link","_PageLayout","_MetaTags","_Modal","_NavLink","_Throbber","_WithTooltip","_YouTubeVideo","_TextArea","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","n","__proto__","a","getOwnPropertyDescriptor","u","i","set"],"sources":["../../../../src/shared/components/index.ts"],"sourcesContent":["/**\n * Just an aggregation of all exported components into a single module.\n */\n\nexport * from 'components/selectors';\n\nexport { default as Button, BaseButton } from 'components/Button';\nexport { default as Checkbox } from 'components/Checkbox';\nexport { default as Input } from 'components/Input';\nexport { default as Link } from 'components/Link';\nexport { default as PageLayout } from 'components/PageLayout';\nexport { default as MetaTags } from 'components/MetaTags';\nexport { default as Modal, BaseModal } from 'components/Modal';\nexport { default as NavLink } from 'components/NavLink';\nexport { default as Throbber } from 'components/Throbber';\nexport { default as WithTooltip } from 'components/W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A,CAAAD,CAAA,GAAAF,CAAA,WAAAd,wBAAAc,CAAA,CAAAE,CAAA,MAAAA,CAAA,EAAAF,CAAA,EAAAA,CAAA,CAAAI,UAAA,QAAAJ,CAAA,WAAAA,CAAA,mBAAAA,CAAA,qBAAAA,CAAA,QAAAK,OAAA,CAAAL,CAAA,MAAAG,CAAA,CAAAJ,wBAAA,CAAAG,CAAA,KAAAC,CAAA,EAAAA,CAAA,CAAAG,GAAA,CAAAN,CAAA,SAAAG,CAAA,CAAAnB,GAAA,CAAAgB,CAAA,MAAAO,CAAA,EAAAC,SAAA,OAAAC,CAAA,CAAApC,MAAA,CAAAS,cAAA,EAAAT,MAAA,CAAAqC,wBAAA,SAAAC,CAAA,IAAAX,CAAA,gBAAAW,CAAA,KAAAjC,cAAA,CAAAC,IAAA,CAAAqB,CAAA,CAAAW,CAAA,OAAAC,CAAA,CAAAH,CAAA,CAAApC,MAAA,CAAAqC,wBAAA,CAAAV,CAAA,CAAAW,CAAA,OAAAC,CAAA,GAAAA,CAAA,CAAA5B,GAAA,EAAA4B,CAAA,CAAAC,GAAA,EAAAxC,MAAA,CAAAS,cAAA,CAAAyB,CAAA,CAAAI,CAAA,CAAAC,CAAA,EAAAL,CAAA,CAAAI,CAAA,EAAAX,CAAA,CAAAW,CAAA,SAAAJ,CAAA,CAAAF,OAAA,CAAAL,CAAA,CAAAG,CAAA,EAAAA,CAAA,CAAAU,GAAA,CAAAb,CAAA,CAAAO,CAAA,EAAAA,CAAA","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_propTypes","_interopRequireDefault","require","_react","_reactThemes","_Options","_interopRequireWildcard","_common","_jsxRuntime","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","defaultTheme","BaseCustomDropdown","filter","label","onChange","options","theme","value","Error","active","setActive","useState","dropdownRef","useRef","opsRef","opsPos","setOpsPos","upward","setUpward","useEffect","undefined","id","cb","anchor","current","getBoundingClientRect","opsRect","measure","fitsDown","bottom","height","window","visualViewport","fitsUp","top","up","pos","left","width","now","areEqual","requestAnimationFrame","cancelAnimationFrame","openList","view","rect","stopPropagation","selected","jsx","Fragment","children","length","option","iValue","iName","optionValueName","containerClassName","container","opsContainerClass","select","jsxs","className","dropdown","onClick","onKeyDown","key","ref","role","tabIndex","arrow","containerClass","containerStyle","onCancel","newValue","optionClass","ThemedCustomDropdown","themed","validThemeKeys","propTypes","PT","func","node","arrayOf","optionValidator","isRequired","themeType","valueValidator","_default","exports"],"sources":["../../../../../../src/shared/components/selectors/CustomDropdown/index.tsx"],"sourcesContent":["import PT from 'prop-types';\nimport { useEffect, useRef, useState } from 'react';\n\nimport themed from '@dr.pogodin/react-themes';\n\nimport Options, { type ContainerPosT, type RefT, areEqual } from './Options';\n\nimport defaultTheme from './theme.scss';\n\nimport {\n type PropsT,\n type ValueT,\n optionValidator,\n optionValueName,\n validThemeKeys,\n valueValidator,\n} from '../common';\n\nconst BaseCustomDropdown: React.FunctionComponent<\nPropsT<React.ReactNode, (value: ValueT) => void>\n> = ({\n filter,\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n if (!options) throw Error('Internal error');\n\n const [active, setActive] = useState(false);\n\n const dropdownRef = useRef<HTMLDivElement>(null);\n const opsRef = useRef<RefT>(null);\n\n const [opsPos, setOpsPos] = useState<ContainerPosT>();\n const [upward, setUpward] = useState(false);\n\n useEffect(() => {\n if (!active) return undefined;\n\n let id: number;\n const cb = () => {\n const anchor = dropdownRef.current?.getBoundingClientRect();\n const opsRect = opsRef.current?.measure();\n if (anchor && opsRect) {\n const fitsDown = anchor.bottom + opsRect.height\n < (window.visualViewport?.height ?? 0);\n const fitsUp = anchor.top - opsRect.height > 0;\n\n const up = !fitsDown && fitsUp;\n setUpward(up);\n\n const pos = up ? {\n top: anchor.top - opsRect.height - 1,\n left: anchor.left,\n width: anchor.width,\n } : {\n left: anchor.left,\n top: anchor.bottom,\n width: anchor.width,\n };\n\n setOpsPos((now) => (areEqual(now, pos) ? now : pos));\n }\n id = requestAnimationFrame(cb);\n };\n requestAnimationFrame(cb);\n\n return () => {\n cancelAnimationFrame(id);\n };\n }, [active]);\n\n const openList = (\n e: React.KeyboardEvent<HTMLDivElement> | React.MouseEvent<HTMLDivElement>,\n ) => {\n const view = window.visualViewport;\n const rect = dropdownRef.current!.getBoundingClientRect();\n setActive(true);\n\n // NOTE: This first opens the dropdown off-screen, where it is measured\n // by an effect declared above, and then positioned below, or above\n // the original dropdown element, depending where it fits best\n // (if we first open it downward, it would flick if we immediately\n // move it above, at least with the current position update via local\n // react state, and not imperatively).\n setOpsPos({\n left: view?.width || 0,\n top: view?.height || 0,\n width: rect.width,\n });\n\n e.stopPropagation();\n };\n\n let selected: React.ReactNode = <>‌</>;\n for (let i = 0; i < options.length; ++i) {\n const option = options[i];\n if (!filter || filter(option)) {\n const [iValue, iName] = optionValueName(option);\n if (iValue === value) {\n selected = iName;\n break;\n }\n }\n }\n\n let containerClassName = theme.container;\n if (active) containerClassName += ` ${theme.active}`;\n\n let opsContainerClass = theme.select || '';\n if (upward) {\n containerClassName += ` ${theme.upward}`;\n opsContainerClass += ` ${theme.upward}`;\n }\n\n return (\n <div className={containerClassName}>\n {label === undefined ? null : (\n <div className={theme.label}>{label}</div>\n )}\n <div\n className={theme.dropdown}\n onClick={openList}\n onKeyDown={(e) => {\n if (e.key === 'Enter') openList(e);\n }}\n ref={dropdownRef}\n role=\"listbox\"\n tabIndex={0}\n >\n {selected}\n <div className={theme.arrow} />\n </div>\n {\n active ? (\n <Options\n containerClass={opsContainerClass}\n containerStyle={opsPos}\n onCancel={() => {\n setActive(false);\n }}\n onChange={(newValue) => {\n setActive(false);\n if (onChange) onChange(newValue);\n }}\n optionClass={theme.option || ''}\n options={options}\n ref={opsRef}\n />\n ) : null\n }\n </div>\n );\n};\n\nconst ThemedCustomDropdown = themed(\n BaseCustomDropdown,\n 'CustomDropdown',\n validThemeKeys,\n defaultTheme,\n);\n\nBaseCustomDropdown.propTypes = {\n filter: PT.func,\n label: PT.node,\n onChange: PT.func,\n options: PT.arrayOf(optionValidator.isRequired),\n theme: ThemedCustomDropdown.themeType.isRequired,\n value: valueValidator,\n};\n\nexport default ThemedCustomDropdown;\n"],"mappings":"gLAAA,IAAAA,UAAA,CAAAC,sBAAA,CAAAC,OAAA,gBACA,IAAAC,MAAA,CAAAD,OAAA,UAEA,IAAAE,YAAA,CAAAH,sBAAA,CAAAC,OAAA,8BAEA,IAAAG,QAAA,CAAAC,uBAAA,CAAAJ,OAAA,eAIA,IAAAK,OAAA,CAAAL,OAAA,cAOmB,IAAAM,WAAA,CAAAN,OAAA,+BAAAO,yBAAAC,CAAA,wBAAAC,OAAA,iBAAAC,CAAA,KAAAD,OAAA,CAAAE,CAAA,KAAAF,OAAA,QAAAF,wBAAA,SAAAA,CAAAC,CAAA,SAAAA,CAAA,CAAAG,CAAA,CAAAD,CAAA,GAAAF,CAAA,WAAAJ,wBAAAI,CAAA,CAAAE,CAAA,MAAAA,CAAA,EAAAF,CAAA,EAAAA,CAAA,CAAAI,UAAA,QAAAJ,CAAA,WAAAA,CAAA,mBAAAA,CAAA,qBAAAA,CAAA,QAAAK,OAAA,CAAAL,CAAA,MAAAG,CAAA,CAAAJ,wBAAA,CAAAG,CAAA,KAAAC,CAAA,EAAAA,CAAA,CAAAG,GAAA,CAAAN,CAAA,SAAAG,CAAA,CAAAI,GAAA,CAAAP,CAAA,MAAAQ,CAAA,EAAAC,SAAA,OAAAC,CAAA,CAAAC,MAAA,CAAAC,cAAA,EAAAD,MAAA,CAAAE,wBAAA,SAAAC,CAAA,IAAAd,CAAA,gBAAAc,CAAA,KAAAC,cAAA,CAAAC,IAAA,CAAAhB,CAAA,CAAAc,CAAA,OAAAG,CAAA,CAAAP,CAAA,CAAAC,MAAA,CAAAE,wBAAA,CAAAb,CAAA,CAAAc,CAAA,OAAAG,CAAA,GAAAA,CA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AO,CAAE0E,kBAAE,CAACG,OAAO,CAACC,uBAAe,CAACC,UAAU,CAAC,CAC/C9E,KAAK,CAAEqE,oBAAoB,CAACU,SAAS,CAACD,UAAU,CAChD7E,KAAK,CAAE+E,sBACT,CAAC,CAAC,IAAAC,QAAA,CAAAC,OAAA,CAAAtG,OAAA,CAEayF,oBAAoB","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":["_propTypes","_interopRequireDefault","require","_react","_reactThemes","_Options","_interopRequireWildcard","_common","_jsxRuntime","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","defaultTheme","BaseCustomDropdown","filter","label","onChange","options","theme","value","Error","active","setActive","useState","dropdownRef","useRef","opsRef","opsPos","setOpsPos","upward","setUpward","useEffect","undefined","id","cb","anchor","current","getBoundingClientRect","opsRect","measure","fitsDown","bottom","height","window","visualViewport","fitsUp","top","up","pos","left","width","now","areEqual","requestAnimationFrame","cancelAnimationFrame","openList","view","rect","stopPropagation","selected","jsx","Fragment","children","length","option","iValue","iName","optionValueName","containerClassName","container","opsContainerClass","select","jsxs","className","dropdown","onClick","onKeyDown","key","ref","role","tabIndex","arrow","containerClass","containerStyle","onCancel","newValue","optionClass","ThemedCustomDropdown","themed","validThemeKeys","propTypes","PT","func","node","arrayOf","optionValidator","isRequired","themeType","valueValidator","_default","exports"],"sources":["../../../../../../src/shared/components/selectors/CustomDropdown/index.tsx"],"sourcesContent":["import PT from 'prop-types';\nimport { useEffect, useRef, useState } from 'react';\n\nimport themed from '@dr.pogodin/react-themes';\n\nimport Options, { type ContainerPosT, type RefT, areEqual } from './Options';\n\nimport defaultTheme from './theme.scss';\n\nimport {\n type PropsT,\n type ValueT,\n optionValidator,\n optionValueName,\n validThemeKeys,\n valueValidator,\n} from '../common';\n\nconst BaseCustomDropdown: React.FunctionComponent<\nPropsT<React.ReactNode, (value: ValueT) => void>\n> = ({\n filter,\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n if (!options) throw Error('Internal error');\n\n const [active, setActive] = useState(false);\n\n const dropdownRef = useRef<HTMLDivElement>(null);\n const opsRef = useRef<RefT>(null);\n\n const [opsPos, setOpsPos] = useState<ContainerPosT>();\n const [upward, setUpward] = useState(false);\n\n useEffect(() => {\n if (!active) return undefined;\n\n let id: number;\n const cb = () => {\n const anchor = dropdownRef.current?.getBoundingClientRect();\n const opsRect = opsRef.current?.measure();\n if (anchor && opsRect) {\n const fitsDown = anchor.bottom + opsRect.height\n < (window.visualViewport?.height ?? 0);\n const fitsUp = anchor.top - opsRect.height > 0;\n\n const up = !fitsDown && fitsUp;\n setUpward(up);\n\n const pos = up ? {\n top: anchor.top - opsRect.height - 1,\n left: anchor.left,\n width: anchor.width,\n } : {\n left: anchor.left,\n top: anchor.bottom,\n width: anchor.width,\n };\n\n setOpsPos((now) => (areEqual(now, pos) ? now : pos));\n }\n id = requestAnimationFrame(cb);\n };\n requestAnimationFrame(cb);\n\n return () => {\n cancelAnimationFrame(id);\n };\n }, [active]);\n\n const openList = (\n e: React.KeyboardEvent<HTMLDivElement> | React.MouseEvent<HTMLDivElement>,\n ) => {\n const view = window.visualViewport;\n const rect = dropdownRef.current!.getBoundingClientRect();\n setActive(true);\n\n // NOTE: This first opens the dropdown off-screen, where it is measured\n // by an effect declared above, and then positioned below, or above\n // the original dropdown element, depending where it fits best\n // (if we first open it downward, it would flick if we immediately\n // move it above, at least with the current position update via local\n // react state, and not imperatively).\n setOpsPos({\n left: view?.width || 0,\n top: view?.height || 0,\n width: rect.width,\n });\n\n e.stopPropagation();\n };\n\n let selected: React.ReactNode = <>‌</>;\n for (let i = 0; i < options.length; ++i) {\n const option = options[i];\n if (!filter || filter(option)) {\n const [iValue, iName] = optionValueName(option);\n if (iValue === value) {\n selected = iName;\n break;\n }\n }\n }\n\n let containerClassName = theme.container;\n if (active) containerClassName += ` ${theme.active}`;\n\n let opsContainerClass = theme.select || '';\n if (upward) {\n containerClassName += ` ${theme.upward}`;\n opsContainerClass += ` ${theme.upward}`;\n }\n\n return (\n <div className={containerClassName}>\n {label === undefined ? null : (\n <div className={theme.label}>{label}</div>\n )}\n <div\n className={theme.dropdown}\n onClick={openList}\n onKeyDown={(e) => {\n if (e.key === 'Enter') openList(e);\n }}\n ref={dropdownRef}\n role=\"listbox\"\n tabIndex={0}\n >\n {selected}\n <div className={theme.arrow} />\n </div>\n {\n active ? (\n <Options\n containerClass={opsContainerClass}\n containerStyle={opsPos}\n onCancel={() => {\n setActive(false);\n }}\n onChange={(newValue) => {\n setActive(false);\n if (onChange) onChange(newValue);\n }}\n optionClass={theme.option || ''}\n options={options}\n ref={opsRef}\n />\n ) : null\n }\n </div>\n );\n};\n\nconst ThemedCustomDropdown = themed(\n BaseCustomDropdown,\n 'CustomDropdown',\n validThemeKeys,\n defaultTheme,\n);\n\nBaseCustomDropdown.propTypes = {\n filter: PT.func,\n label: PT.node,\n onChange: PT.func,\n options: PT.arrayOf(optionValidator.isRequired),\n theme: ThemedCustomDropdown.themeType.isRequired,\n value: valueValidator,\n};\n\nexport default ThemedCustomDropdown;\n"],"mappings":"gLAAA,IAAAA,UAAA,CAAAC,sBAAA,CAAAC,OAAA,gBACA,IAAAC,MAAA,CAAAD,OAAA,UAEA,IAAAE,YAAA,CAAAH,sBAAA,CAAAC,OAAA,8BAEA,IAAAG,QAAA,CAAAC,uBAAA,CAAAJ,OAAA,eAIA,IAAAK,OAAA,CAAAL,OAAA,cAOmB,IAAAM,WAAA,CAAAN,OAAA,+BAAAO,yBAAAC,CAAA,wBAAAC,OAAA,iBAAAC,CAAA,KAAAD,OAAA,CAAAE,CAAA,KAAAF,OAAA,QAAAF,wBAAA,SAAAA,CAAAC,CAAA,SAAAA,CAAA,CAAAG,CAAA,CAAAD,CAAA,GAAAF,CAAA,WAAAJ,wBAAAI,CAAA,CAAAE,CAAA,MAAAA,CAAA,EAAAF,CAAA,EAAAA,CAAA,CAAAI,UAAA,QAAA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AK,CAAC,CAChB,GAAIN,QAAQ,CAAEA,QAAQ,CAACqE,QAAQ,CACjC,CAAE,CACFC,WAAW,CAAEpE,KAAK,CAAC8C,MAAM,EAAI,EAAG,CAChC/C,OAAO,CAAEA,OAAQ,CACjB6D,GAAG,CAAEpD,MAAO,CACb,CAAC,CACA,IAAI,EAEP,CAET,CAAC,CAED,KAAM,CAAA6D,oBAAoB,CAAG,GAAAC,oBAAM,EACjC3E,kBAAkB,CAClB,gBAAgB,CAChB4E,sBAAc,CACd7E,YACF,CAAC,CAEDC,kBAAkB,CAAC6E,SAAS,CAAG,CAC7B5E,MAAM,CAAE6E,kBAAE,CAACC,IAAI,CACf7E,KAAK,CAAE4E,kBAAE,CAACE,IAAI,CACd7E,QAAQ,CAAE2E,kBAAE,CAACC,IAAI,CACjB3E,OAAO,CAAE0E,kBAAE,CAACG,OAAO,CAACC,uBAAe,CAACC,UAAU,CAAC,CAC/C9E,KAAK,CAAEqE,oBAAoB,CAACU,SAAS,CAACD,UAAU,CAChD7E,KAAK,CAAE+E,sBACT,CAAC,CAAC,IAAAC,QAAA,CAAAC,OAAA,CAAAtG,OAAA,CAEayF,oBAAoB","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_propTypes","_interopRequireDefault","require","_reactThemes","_common","_jsxRuntime","defaultTheme","validThemeKeys","BaseSwitch","label","onChange","options","theme","value","option","Error","optionNodes","i","length","iValue","iName","optionValueName","className","onPress","selected","push","jsx","onClick","onKeyDown","e","key","role","tabIndex","children","jsxs","container","ThemedSwitch","themed","propTypes","PT","node","func","optionsValidator","themeType","isRequired","valueValidator","_default","exports","default"],"sources":["../../../../../../src/shared/components/selectors/Switch/index.tsx"],"sourcesContent":["import PT from 'prop-types';\nimport themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport {\n type OptionsT,\n type ValueT,\n optionsValidator,\n optionValueName,\n valueValidator,\n} from '../common';\n\nimport defaultTheme from './theme.scss';\n\nconst validThemeKeys = [\n 'container',\n 'label',\n 'option',\n 'options',\n 'selected',\n] as const;\n\ntype PropsT = {\n label?: React.ReactNode;\n onChange?: (value: ValueT) => void;\n options?: Readonly<OptionsT<React.ReactNode>>;\n theme: Theme<typeof validThemeKeys>;\n value?: ValueT;\n};\n\nconst BaseSwitch: React.FunctionComponent<PropsT> = ({\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n if (!options || !theme.option) throw Error('Internal error');\n\n const optionNodes: React.ReactNode[] = [];\n for (let i = 0; i < options?.length; ++i) {\n const [iValue, iName] = optionValueName(options[i]);\n\n let className: string = theme.option;\n let onPress: (() => void) | undefined;\n if (iValue === value) className += ` ${theme.selected}`;\n else if (onChange) onPress = () => onChange(iValue);\n\n optionNodes.push(\n onPress ? (\n <div\n className={className}\n onClick={onPress}\n onKeyDown={(e) => {\n if (onPress && e.key === 'Enter') onPress();\n }}\n key={iValue}\n role=\"button\"\n tabIndex={0}\n >\n {iName}\n </div>\n ) : (\n <div className={className} key={iValue}>{iName}</div>\n ),\n );\n }\n\n return (\n <div className={theme.container}>\n {label ? <div className={theme.label}>{label}</div> : null}\n <div className={theme.options}>\n {optionNodes}\n </div>\n </div>\n );\n};\n\nconst ThemedSwitch = themed(\n BaseSwitch,\n 'Switch',\n validThemeKeys,\n defaultTheme,\n);\n\nBaseSwitch.propTypes = {\n label: PT.node,\n onChange: PT.func,\n options: optionsValidator,\n theme: ThemedSwitch.themeType.isRequired,\n value: valueValidator,\n};\n\nexport default ThemedSwitch;\n"],"mappings":"gLAAA,IAAAA,UAAA,CAAAC,sBAAA,CAAAC,OAAA,gBACA,IAAAC,YAAA,CAAAF,sBAAA,CAAAC,OAAA,8BAEA,IAAAE,OAAA,CAAAF,OAAA,cAMmB,IAAAG,WAAA,CAAAH,OAAA,4BAAAI,YAAA,kIAInB,KAAM,CAAAC,cAAc,CAAG,CACrB,WAAW,CACX,OAAO,CACP,QAAQ,CACR,SAAS,CACT,UAAU,CACF,CAUV,KAAM,CAAAC,UAA2C,CAAGA,CAAC,CACnDC,KAAK,CACLC,QAAQ,CACRC,OAAO,CACPC,KAAK,CACLC,KACF,CAAC,GAAK,CACJ,GAAI,CAACF,OAAO,EAAI,CAACC,KAAK,CAACE,MAAM,CAAE,KAAM,CAAAC,KAAK,CAAC,gBAAgB,CAAC,CAE5D,KAAM,CAAAC,WAA8B,CAAG,EAAE,CACzC,IAAK,GAAI,CAAAC,CAAC,CAAG,CAAC,CAAEA,CAAC,CAAGN,OAAO,EAAEO,MAAM,CAAE,EAAED,CAAC,CAAE,CACxC,KAAM,CAACE,MAAM,CAAEC,KAAK,CAAC,CAAG,GAAAC,uBAAe,EAACV,OAAO,CAACM,CAAC,CAAC,CAAC,CAEnD,GAAI,CAAAK,SAAiB,CAAGV,KAAK,CAACE,MAAM,CACpC,GAAI,CAAAS,OAAiC,CACrC,GAAIJ,MAAM,GAAKN,KAAK,CAAES,SAAS,
|
|
1
|
+
{"version":3,"file":"index.js","names":["_propTypes","_interopRequireDefault","require","_reactThemes","_common","_jsxRuntime","defaultTheme","validThemeKeys","BaseSwitch","label","onChange","options","theme","value","option","Error","optionNodes","i","length","iValue","iName","optionValueName","className","onPress","selected","push","jsx","onClick","onKeyDown","e","key","role","tabIndex","children","jsxs","container","ThemedSwitch","themed","propTypes","PT","node","func","optionsValidator","themeType","isRequired","valueValidator","_default","exports","default"],"sources":["../../../../../../src/shared/components/selectors/Switch/index.tsx"],"sourcesContent":["import PT from 'prop-types';\nimport themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport {\n type OptionsT,\n type ValueT,\n optionsValidator,\n optionValueName,\n valueValidator,\n} from '../common';\n\nimport defaultTheme from './theme.scss';\n\nconst validThemeKeys = [\n 'container',\n 'label',\n 'option',\n 'options',\n 'selected',\n] as const;\n\ntype PropsT = {\n label?: React.ReactNode;\n onChange?: (value: ValueT) => void;\n options?: Readonly<OptionsT<React.ReactNode>>;\n theme: Theme<typeof validThemeKeys>;\n value?: ValueT;\n};\n\nconst BaseSwitch: React.FunctionComponent<PropsT> = ({\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n if (!options || !theme.option) throw Error('Internal error');\n\n const optionNodes: React.ReactNode[] = [];\n for (let i = 0; i < options?.length; ++i) {\n const [iValue, iName] = optionValueName(options[i]);\n\n let className: string = theme.option;\n let onPress: (() => void) | undefined;\n if (iValue === value) className += ` ${theme.selected}`;\n else if (onChange) onPress = () => onChange(iValue);\n\n optionNodes.push(\n onPress ? (\n <div\n className={className}\n onClick={onPress}\n onKeyDown={(e) => {\n if (onPress && e.key === 'Enter') onPress();\n }}\n key={iValue}\n role=\"button\"\n tabIndex={0}\n >\n {iName}\n </div>\n ) : (\n <div className={className} key={iValue}>{iName}</div>\n ),\n );\n }\n\n return (\n <div className={theme.container}>\n {label ? <div className={theme.label}>{label}</div> : null}\n <div className={theme.options}>\n {optionNodes}\n </div>\n </div>\n );\n};\n\nconst ThemedSwitch = themed(\n BaseSwitch,\n 'Switch',\n validThemeKeys,\n defaultTheme,\n);\n\nBaseSwitch.propTypes = {\n label: PT.node,\n onChange: PT.func,\n options: optionsValidator,\n theme: ThemedSwitch.themeType.isRequired,\n value: valueValidator,\n};\n\nexport default ThemedSwitch;\n"],"mappings":"gLAAA,IAAAA,UAAA,CAAAC,sBAAA,CAAAC,OAAA,gBACA,IAAAC,YAAA,CAAAF,sBAAA,CAAAC,OAAA,8BAEA,IAAAE,OAAA,CAAAF,OAAA,cAMmB,IAAAG,WAAA,CAAAH,OAAA,4BAAAI,YAAA,kIAInB,KAAM,CAAAC,cAAc,CAAG,CACrB,WAAW,CACX,OAAO,CACP,QAAQ,CACR,SAAS,CACT,UAAU,CACF,CAUV,KAAM,CAAAC,UAA2C,CAAGA,CAAC,CACnDC,KAAK,CACLC,QAAQ,CACRC,OAAO,CACPC,KAAK,CACLC,KACF,CAAC,GAAK,CACJ,GAAI,CAACF,OAAO,EAAI,CAACC,KAAK,CAACE,MAAM,CAAE,KAAM,CAAAC,KAAK,CAAC,g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B,GAAA,SAAKJ,SAAS,CAAEV,KAAK,CAACD,OAAQ,CAAAsB,QAAA,CAC3BjB,WAAW,CACT,CAAC,EACH,CAET,CAAC,CAED,KAAM,CAAAoB,YAAY,CAAG,GAAAC,oBAAM,EACzB7B,UAAU,CACV,QAAQ,CACRD,cAAc,CACdD,YACF,CAAC,CAEDE,UAAU,CAAC8B,SAAS,CAAG,CACrB7B,KAAK,CAAE8B,kBAAE,CAACC,IAAI,CACd9B,QAAQ,CAAE6B,kBAAE,CAACE,IAAI,CACjB9B,OAAO,CAAE+B,wBAAgB,CACzB9B,KAAK,CAAEwB,YAAY,CAACO,SAAS,CAACC,UAAU,CACxC/B,KAAK,CAAEgC,sBACT,CAAC,CAAC,IAAAC,QAAA,CAAAC,OAAA,CAAAC,OAAA,CAEaZ,YAAY","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_reactThemes","_interopRequireWildcard","require","_config","_interopRequireDefault","isomorphy","exports","_time","webpack","_jsUtils","_globalState","_splitComponent","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","themed","themedImpl","COMPOSE","PRIORITY"],"sources":["../../../../src/shared/utils/index.ts"],"sourcesContent":["import themedImpl, {\n type Theme,\n COMPOSE,\n PRIORITY,\n ThemeProvider,\n} from '@dr.pogodin/react-themes';\n\nimport config from './config';\nimport * as isomorphy from './isomorphy';\nimport time from './time';\nimport * as webpack from './webpack';\n\nexport {\n Barrier,\n Emitter,\n Semaphore,\n withRetries,\n} from '@dr.pogodin/js-utils';\n\nexport { getSsrContext } from './globalState';\nexport { default as splitComponent } from './splitComponent';\n\ntype ThemedT = typeof themedImpl & {\n COMPOSE: typeof COMPOSE;\n PRIORITY: typeof PRIORITY;\n};\n\nconst themed: ThemedT = themedImpl as ThemedT;\n\nthemed.COMPOSE = COMPOSE;\nthemed.PRIORITY = PRIORITY;\n\nexport {\n type Theme,\n config,\n isomorphy,\n themed,\n ThemeProvider,\n time,\n webpack,\n};\n"],"mappings":"4oCAAA,IAAAA,YAAA,CAAAC,uBAAA,CAAAC,OAAA,8BAOA,IAAAC,OAAA,CAAAC,sBAAA,CAAAF,OAAA,cACA,IAAAG,SAAA,CAAAJ,uBAAA,CAAAC,OAAA,iBAAyCI,OAAA,CAAAD,SAAA,CAAAA,SAAA,CACzC,IAAAE,KAAA,CAAAH,sBAAA,CAAAF,OAAA,YACA,IAAAM,OAAA,CAAAP,uBAAA,CAAAC,OAAA,eAAqCI,OAAA,CAAAE,OAAA,CAAAA,OAAA,CAErC,IAAAC,QAAA,CAAAP,OAAA,
|
|
1
|
+
{"version":3,"file":"index.js","names":["_reactThemes","_interopRequireWildcard","require","_config","_interopRequireDefault","isomorphy","exports","_time","webpack","_jsUtils","_globalState","_splitComponent","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","themed","themedImpl","COMPOSE","PRIORITY"],"sources":["../../../../src/shared/utils/index.ts"],"sourcesContent":["import themedImpl, {\n type Theme,\n COMPOSE,\n PRIORITY,\n ThemeProvider,\n} from '@dr.pogodin/react-themes';\n\nimport config from './config';\nimport * as isomorphy from './isomorphy';\nimport time from './time';\nimport * as webpack from './webpack';\n\nexport {\n type Listener,\n Barrier,\n Emitter,\n Semaphore,\n withRetries,\n} from '@dr.pogodin/js-utils';\n\nexport { getSsrContext } from './globalState';\nexport { default as splitComponent } from './splitComponent';\n\ntype ThemedT = typeof themedImpl & {\n COMPOSE: typeof COMPOSE;\n PRIORITY: typeof PRIORITY;\n};\n\nconst themed: ThemedT = themedImpl as ThemedT;\n\nthemed.COMPOSE = COMPOSE;\nthemed.PRIORITY = PRIORITY;\n\nexport {\n type Theme,\n config,\n isomorphy,\n themed,\n ThemeProvider,\n time,\n webpack,\n};\n"],"mappings":"4oCAAA,IAAAA,Y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A,CAAAC,GAAA,EAAAP,MAAA,CAAAC,cAAA,CAAAJ,CAAA,CAAAM,CAAA,CAAAG,CAAA,EAAAT,CAAA,CAAAM,CAAA,EAAAd,CAAA,CAAAc,CAAA,SAAAN,CAAA,CAAAH,OAAA,CAAAL,CAAA,CAAAG,CAAA,EAAAA,CAAA,CAAAe,GAAA,CAAAlB,CAAA,CAAAQ,CAAA,EAAAA,CAAA,CAO7D,KAAM,CAAAW,MAAe,CAAA1B,OAAA,CAAA0B,MAAA,CAAGC,oBAAqB,CAE7CD,MAAM,CAACE,OAAO,CAAGA,oBAAO,CACxBF,MAAM,CAACG,QAAQ,CAAGA,qBAAQ","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"E2eSsrEnv.js","names":["_path","_interopRequireDefault","require","_lodash","_experimentalWorker","_jestEnvironmentJsdom","_memfs","_webpack","_renderer","E2eSsrEnv","JsdomEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","defaults","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","path","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","compiler","webpack","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","Error","webpackStats","runSsr","logger","undefined","debug","noop","info","log","warn","cleanup","entry","p","module","Application","entryExportName","renderer","ssrFactory","status","markup","ssrRequest","cookie","send","set","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","createFsFromVolume","Volume","dirname","testPath","withSsr","root","process","cwd","register","envName","babelEnv","extensions","setup","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","cache","forEach","key","revert","exports"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n/* eslint-disable global-require, import/no-dynamic-require */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\nimport path from 'path';\n\nimport type { Request, Response } from 'express';\nimport { defaults, noop, set } from 'lodash';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register/experimental-worker';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { type IFs, createFsFromVolume, Volume } from 'memfs';\nimport webpack from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nimport ssrFactory from 'server/renderer';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: webpack.StatsCompilation;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString\n ? JSON.parse(optionsString) : {}) as webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n let factory = require(path.resolve(this.rootDir, factoryPath));\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs as IFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack() {\n this.loadWebpackConfig();\n\n const compiler = webpack(this.global.webpackConfig as webpack.Configuration);\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is a workaround\n // for the Webpack regression: https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr() {\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString ? JSON.parse(optionsString) : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n if (options.logger === undefined) {\n options.logger = {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n }\n\n if (!options.buildInfo) options.buildInfo = this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry);\n const module = require(p);\n cleanup = module.cleanup;\n options.Application = module[options.entryExportName || 'default'];\n }\n\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n if (error) fail(error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString ? JSON.parse(requestString) : {};\n\n if (!request.url) request.url = '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString ? JSON.parse(optionsString) : {};\n let root;\n switch (options.root) {\n case 'TEST': root = this.testFolder; break;\n default: root = process.cwd();\n }\n register({\n envName: options.babelEnv,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup() {\n await super.setup();\n await this.runWebpack();\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown() {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n super.teardown();\n }\n}\n"],"mappings":"gLAiBA,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AACE,GAAG,CAC1B,CAAC,CAAC,CACFX,2BAAQ,CAACY,MAAM,CAAC,CAAC,CACjB,KAAK,CAACN,QAAQ,CAAC,CACjB,CACF,CAACO,OAAA,CAAAhF,OAAA,CAAAnB,SAAA","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"E2eSsrEnv.js","names":["_path","_interopRequireDefault","require","_lodash","_experimentalWorker","_jestEnvironmentJsdom","_memfs","_webpack","_renderer","E2eSsrEnv","JsdomEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","defaults","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","path","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","compiler","webpack","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","Error","webpackStats","runSsr","logger","undefined","debug","noop","info","log","warn","cleanup","entry","p","module","Application","entryExportName","renderer","ssrFactory","status","markup","ssrRequest","cookie","send","set","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","createFsFromVolume","Volume","dirname","testPath","withSsr","root","process","cwd","register","envName","babelEnv","extensions","setup","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","cache","forEach","key","revert","exports"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n/* eslint-disable global-require, import/no-dynamic-require */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\nimport path from 'path';\n\nimport type { Request, Response } from 'express';\nimport { defaults, noop, set } from 'lodash';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register/experimental-worker';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { type IFs, createFsFromVolume, Volume } from 'memfs';\nimport webpack from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nimport ssrFactory from 'server/renderer';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: webpack.StatsCompilation;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString\n ? JSON.parse(optionsString) : {}) as webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n let factory = require(path.resolve(this.rootDir, factoryPath));\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs as IFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack() {\n this.loadWebpackConfig();\n\n const compiler = webpack(this.global.webpackConfig as webpack.Configuration);\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is a workaround\n // for the Webpack regression: https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr() {\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString ? JSON.parse(optionsString) : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n if (options.logger === undefined) {\n options.logger = {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n }\n\n if (!options.buildInfo) options.buildInfo = this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry);\n const module = require(p);\n cleanup = module.cleanup;\n options.Application = module[options.entryExportName || 'default'];\n }\n\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n if (error) fail(error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString ? JSON.parse(requestString) : {};\n\n if (!request.url) request.url = '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString ? JSON.parse(optionsString) : {};\n let root;\n switch (options.root) {\n case 'TEST': root = this.testFolder; break;\n default: root = process.cwd();\n }\n register({\n envName: options.babelEnv,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup() {\n await super.setup();\n await this.runWebpack();\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown() {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n super.teardown();\n }\n}\n"],"mappings":"gLAiBA,IAAAA,KAAA,CAAAC,sBAAA,CAAAC,OAAA,UAGA,IAAAC,OAAA,CAAAD,OAAA,WAKA,IAAAE,mBAAA,CAAAH,sBAAA,CAAAC,OAAA,yCAEA,IAAAG,qBAAA,CAAAJ,sBAAA,CAAAC,OAAA,4BACA,IAAAI,MAAA,CAAAJ,OAAA,UACA,IAAAK,QAAA,CAAAN,sBAAA,CAAAC,OAAA,aAGA,IAAAM,SAAA,CAAAP,sBA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CAAAC,OAAO,CAAGF,aAAa,CAAGG,IAAI,CAACC,KAAK,CAACJ,aAAa,CAAC,CAAG,CAAC,CAAC,CAC9D,GAAI,CAAAgF,IAAI,CACR,OAAQ9E,OAAO,CAAC8E,IAAI,EAClB,IAAK,MAAM,CAAEA,IAAI,CAAG,IAAI,CAACzE,UAAU,CAAE,MACrC,QAASyE,IAAI,CAAGC,OAAO,CAACC,GAAG,CAAC,CAC9B,CACA,GAAAC,2BAAQ,EAAC,CACPC,OAAO,CAAElF,OAAO,CAACmF,QAAQ,CACzBC,UAAU,CAAE,CAAC,KAAK,CAAE,MAAM,CAAE,KAAK,CAAE,MAAM,CAAE,MAAM,CAAC,CAClDN,IACF,CAAC,CACH,CAEA,KAAM,CAAAO,KAAKA,CAAA,CAAG,CACZ,KAAM,MAAK,CAACA,KAAK,CAAC,CAAC,CACnB,KAAM,KAAI,CAAClE,UAAU,CAAC,CAAC,CACvB,GAAI,IAAI,CAAC0D,OAAO,CAAE,KAAM,KAAI,CAACzC,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC7B,MAAM,CAAC+E,6BAA6B,CAAG,IAC9C,CAEA,KAAM,CAAAC,QAAQA,CAAA,CAAG,CACf,MAAO,KAAI,CAAChF,MAAM,CAAC+E,6BAA6B,CAEhD;AACA;AACA;AACA;AACA;AACA;AACAE,MAAM,CAACC,IAAI,CAACrG,OAAO,CAACsG,KAAK,CAAC,CAACC,OAAO,CAAEC,GAAG,EAAK,CAC1C,MAAO,CAAAxG,OAAO,CAACsG,KAAK,CAACE,GAAG,CAC1B,CAAC,CAAC,CACFX,2BAAQ,CAACY,MAAM,CAAC,CAAC,CACjB,KAAK,CAACN,QAAQ,CAAC,CACjB,CACF,CAACO,OAAA,CAAAhF,OAAA,CAAAnB,SAAA","ignoreList":[]}
|
|
@@ -25,5 +25,5 @@
|
|
|
25
25
|
// when it is simulating user events.
|
|
26
26
|
global.IS_REACT_ACT_ENVIRONMENT=true;(0,_react.act)(()=>root.unmount());res.remove()};// NOTE: As it seems @testing-library may reset this flag to false
|
|
27
27
|
// when it is simulating user events.
|
|
28
|
-
global.IS_REACT_ACT_ENVIRONMENT=true;(0,_react.act)(()=>{root=(0,_client.createRoot)(res);root.render(scene)});return res}function snapshot(element){
|
|
28
|
+
global.IS_REACT_ACT_ENVIRONMENT=true;(0,_react.act)(()=>{root=(0,_client.createRoot)(res);root.render(scene)});return res}function snapshot(element){let res;(0,_react.act)(()=>{res=(0,_react2.render)(element)});if(res===undefined)throw Error("Render failed");const nodes=res.asFragment().childNodes;expect(nodes.length>1?[...nodes]:nodes[0]).toMatchSnapshot();return res}
|
|
29
29
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_mockdate","_interopRequireDefault","require","_react","_client","_react2","_global","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockTimer","time","mockdate","set","Date","now","jest","advanceTimersByTime","mount","scene","root","element","document","createElement","body","appendChild","res","destroy","act","unmount","remove","createRoot","render","snapshot","asFragment","
|
|
1
|
+
{"version":3,"file":"index.js","names":["_mockdate","_interopRequireDefault","require","_react","_client","_react2","_global","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockTimer","time","mockdate","set","Date","now","jest","advanceTimersByTime","mount","scene","root","element","document","createElement","body","appendChild","res","destroy","act","unmount","remove","createRoot","render","snapshot","undefined","Error","nodes","asFragment","childNodes","expect","length","toMatchSnapshot"],"sources":["../../../../../src/shared/utils/jest/index.tsx"],"sourcesContent":["/* global jest, document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport mockdate from 'mockdate';\nimport { type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\ndeclare global {\n // eslint-disable-next-line no-var, vars-on-top\n var IS_REACT_ACT_ENVIRONMENT: boolean | undefined;\n}\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide() {\n Object.defineProperty(process, 'versions', { value: null });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide() {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0) {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number) {\n mockdate.set(time + Date.now());\n jest.advanceTimersByTime(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => root.unmount());\n res.remove();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\nexport function snapshot(element: React.ReactElement) {\n let res: RenderResult | undefined;\n act(() => {\n res = render(element);\n });\n if (res === undefined) throw Error('Render failed');\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"ghBAGA,IAAAA,SAAA,CAAAC,sBAAA,CAAAC,OAAA,cACA,IAAAC,MAAA,CAAAD,OAAA,UACA,IAAAE,OAAA,CAAAF,OAAA,qBAEA,IAAAG,OAAA,CAAAH,OAAA,2BAQA,IAAAI,OAAA,CAAAL,sBAAA,CAAAC,OAAA,cAfA,4BACA,uDAQA;AACA;AACA;AACA,GAUAK,MAAM,CAACC,wBAAwB,CAAG,IAAI,CAEtC,KAAM,CAAAC,uBAAuB,CAAGC,OAAO,CAACC,QAAQ,CAEhD;AACA;AACA;AACA,GACO,QAAS,CAAAC,cAAcA,CAAA,CAAG,CAC/BC,MAAM,CAACC,cAAc,CAACJ,OAAO,CAAE,UAAU,CAAE,CAAEK,KAAK,CAAE,IAAK,CAAC,CAC5D,CAEA;AACA;AACA,GACO,QAAS,CAAAC,gBAAgBA,CAAA,CAAG,CACjCH,MAAM,CAACC,cAAc,CAACJ,OAAO,CAAE,UAAU,CAAE,CACzCK,KAAK,CAAEN,uBAAuB,CAC9BQ,QAAQ,CAAE,KACZ,CAAC,CACH,CAEA;AACA;AACA;AACA;AACA;AACA,GACO,QAAS,CAAAC,WAAWA,CAACC,IAAI,CAAG,CAAC,CAAE,CACpC,KAAM,CAAAC,CAAC,CAAGD,IAAI,CAACE,QAAQ,CAAC,EAAE,CAAC,CAACC,QAAQ,CAAC,EAAE,CAAE,GAAG,CAAC,CAC7C,MAAO,GAAGF,CAAC,CAACG,KAAK,CAAC,CAAC,CAAE,CAAC,CAAC,IAAIH,CAAC,CAACG,KAAK,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AC,CAAC,CACF,GAAIK,GAAG,GAAKQ,SAAS,CAAE,KAAM,CAAAC,KAAK,CAAC,eAAe,CAAC,CAEnD,KAAM,CAAAC,KAAK,CAAGV,GAAG,CAACW,UAAU,CAAC,CAAC,CAACC,UAAU,CACzCC,MAAM,CAACH,KAAK,CAACI,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGJ,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACK,eAAe,CAAC,CAAC,CAClE,MAAO,CAAAf,GACT","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"splitComponent.js","names":["_propTypes","_interopRequireDefault","require","_react","_jsUtils","_globalState","_isomorphy","_jsxRuntime","clientChunkGroups","IS_CLIENT_SIDE","default","CHUNK_GROUPS","refCounts","getPublicPath","getBuildInfo","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","Barrier","addEventListener","resolve","current","getLoadedStyleSheets","Set","styleSheets","i","length","href","add","assertChunkName","chunkName","chunkGroups","Error","bookStyleSheets","promises","assets","asset","endsWith","promise","push","Promise","allSettled","then","freeStyleSheets","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","resolved","Component","Wrapper","forwardRef","children","rest","ref","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","jsx","CodeSplit","Suspense","fallback","propTypes","PT","node"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* eslint-disable react/jsx-props-no-spreading */\n/* global document */\n\nimport PT from 'prop-types';\n\nimport {\n type ComponentType,\n type ReactNode,\n forwardRef,\n lazy,\n Suspense,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\n// Note: At the client side we can get chunk groups immediately when loading\n// the module; at the server-side we only can get them within React render flow.\n// Thus, we set and use the following variable at the client-side, and then when\n// needed on the server side, we'll fetch it differently.\nlet clientChunkGroups: ChunkGroupsT;\n\nif (IS_CLIENT_SIDE) {\n // eslint-disable-next-line global-require\n clientChunkGroups = require('client/getInj').default().CHUNK_GROUPS || {};\n}\n\nconst refCounts: { [path: string]: number } = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => res!.resolve());\n link.addEventListener('error', () => res!.resolve());\n }\n\n if (refCount) {\n const current = refCounts[path] || 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (let i = 0; i < styleSheets.length; ++i) {\n const { href } = styleSheets[i];\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n const loadedSheets = getLoadedStyleSheets();\n\n for (let i = 0; i < assets.length; ++i) {\n const asset = assets[i];\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n const assets = chunkGroups[chunkName];\n for (let i = 0; i < assets.length; ++i) {\n const asset = assets[i];\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n if (--refCounts[path] <= 0) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>,\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends { children?: ReactNode },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>,\n placeholder?: ReactNode,\n}) {\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) assertChunkName(chunkName, clientChunkGroups);\n\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper = forwardRef((\n { children, ...rest }: ComponentPropsT,\n ref,\n ) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => freeStyleSheets(chunkName, clientChunkGroups);\n }, []);\n\n return (\n <Component ref={ref} {...rest as ComponentPropsT}>\n {children}\n </Component>\n );\n });\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent {...rest as Parameters<typeof LazyComponent>[0]}>\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n CodeSplit.propTypes = {\n children: PT.node,\n } as PT.WeakValidationMap<ComponentPropsT>;\n\n return CodeSplit;\n}\n"],"mappings":"wQAGA,IAAAA,UAAA,CAAAC,sBAAA,CAAAC,OAAA,gBAEA,IAAAC,MAAA,CAAAD,OAAA,UASA,IAAAE,QAAA,CAAAF,OAAA,yBAEA,IAAAG,YAAA,CAAAH,OAAA,kBAEA,IAAAI,UAAA,CAAAJ,OAAA,gBAIqB,I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,GAAI,IAAKD,IAAI,CAAAD,QAAA,CAC1BA,QAAQ,CACA,CAEf,CAAC,CAAC,CAEF,MAAO,CAAE5D,OAAO,CAAE0D,OAAQ,CAC5B,CAAC,CAAC,CAEF,KAAM,CAAAW,SAAmD,CAAGA,CAAC,CAC3DT,QAAQ,CACR,GAAGC,IACY,CAAC,gBAChB,GAAAhE,WAAA,CAAAuE,GAAA,EAAC3E,MAAA,CAAA6E,QAAQ,EAACC,QAAQ,CAAElB,WAAY,CAAAO,QAAA,cAC9B,GAAA/D,WAAA,CAAAuE,GAAA,EAACd,aAAa,KAAKO,IAAI,CAAAD,QAAA,CACpBA,QAAQ,CACI,CAAC,CACR,CACX,CAEDS,SAAS,CAACG,SAAS,CAAG,CACpBZ,QAAQ,CAAEa,kBAAE,CAACC,IACf,CAA0C,CAE1C,MAAO,CAAAL,SACT","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"splitComponent.js","names":["_propTypes","_interopRequireDefault","require","_react","_jsUtils","_globalState","_isomorphy","_jsxRuntime","clientChunkGroups","IS_CLIENT_SIDE","default","CHUNK_GROUPS","refCounts","getPublicPath","getBuildInfo","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","Barrier","addEventListener","resolve","current","getLoadedStyleSheets","Set","styleSheets","i","length","href","add","assertChunkName","chunkName","chunkGroups","Error","bookStyleSheets","promises","assets","asset","endsWith","promise","push","Promise","allSettled","then","freeStyleSheets","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","resolved","Component","Wrapper","forwardRef","children","rest","ref","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","jsx","CodeSplit","Suspense","fallback","propTypes","PT","node"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* eslint-disable react/jsx-props-no-spreading */\n/* global document */\n\nimport PT from 'prop-types';\n\nimport {\n type ComponentType,\n type ReactNode,\n forwardRef,\n lazy,\n Suspense,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\n// Note: At the client side we can get chunk groups immediately when loading\n// the module; at the server-side we only can get them within React render flow.\n// Thus, we set and use the following variable at the client-side, and then when\n// needed on the server side, we'll fetch it differently.\nlet clientChunkGroups: ChunkGroupsT;\n\nif (IS_CLIENT_SIDE) {\n // eslint-disable-next-line global-require\n clientChunkGroups = require('client/getInj').default().CHUNK_GROUPS || {};\n}\n\nconst refCounts: { [path: string]: number } = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => res!.resolve());\n link.addEventListener('error', () => res!.resolve());\n }\n\n if (refCount) {\n const current = refCounts[path] || 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (let i = 0; i < styleSheets.length; ++i) {\n const { href } = styleSheets[i];\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n const loadedSheets = getLoadedStyleSheets();\n\n for (let i = 0; i < assets.length; ++i) {\n const asset = assets[i];\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n const assets = chunkGroups[chunkName];\n for (let i = 0; i < assets.length; ++i) {\n const asset = assets[i];\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n if (--refCounts[path] <= 0) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>,\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends { children?: ReactNode },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>,\n placeholder?: ReactNode,\n}) {\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) assertChunkName(chunkName, clientChunkGroups);\n\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper = forwardRef((\n { children, ...rest }: ComponentPropsT,\n ref,\n ) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => freeStyleSheets(chunkName, clientChunkGroups);\n }, []);\n\n return (\n <Component ref={ref} {...rest as ComponentPropsT}>\n {children}\n </Component>\n );\n });\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent {...rest as Parameters<typeof LazyComponent>[0]}>\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n CodeSplit.propTypes = {\n children: PT.node,\n } as PT.WeakValidationMap<ComponentPropsT>;\n\n return CodeSplit;\n}\n"],"mappings":"wQAGA,IA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