@dr.pogodin/react-utils 1.58.0 → 1.58.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.
Files changed (94) hide show
  1. package/__type_tests__/shared/utils/config.ts +9 -0
  2. package/build/development/client/getInj.js +17 -2
  3. package/build/development/client/getInj.js.map +1 -1
  4. package/build/development/server/Cache.js +35 -3
  5. package/build/development/server/Cache.js.map +1 -1
  6. package/build/development/server/renderer.js +53 -7
  7. package/build/development/server/renderer.js.map +1 -1
  8. package/build/development/server/server.js +8 -6
  9. package/build/development/server/server.js.map +1 -1
  10. package/build/development/server/utils/errors.js +11 -11
  11. package/build/development/server/utils/errors.js.map +1 -1
  12. package/build/development/server/utils/modules.js +35 -1
  13. package/build/development/server/utils/modules.js.map +1 -1
  14. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +5 -2
  15. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  16. package/build/development/shared/components/selectors/CustomDropdown/index.js +3 -0
  17. package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  18. package/build/development/shared/components/selectors/NativeDropdown/index.js +5 -2
  19. package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  20. package/build/development/shared/components/selectors/Switch/index.js +2 -2
  21. package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
  22. package/build/development/shared/utils/config.js +3 -1
  23. package/build/development/shared/utils/config.js.map +1 -1
  24. package/build/development/shared/utils/jest/E2eSsrEnv/index.js +10 -10
  25. package/build/development/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
  26. package/build/development/shared/utils/jest/index.js +3 -3
  27. package/build/development/shared/utils/jest/index.js.map +1 -1
  28. package/build/development/shared/utils/splitComponent.js +77 -3
  29. package/build/development/shared/utils/splitComponent.js.map +1 -1
  30. package/build/development/shared/utils/webpack.js +3 -1
  31. package/build/development/shared/utils/webpack.js.map +1 -1
  32. package/build/production/client/getInj.js +1 -1
  33. package/build/production/client/getInj.js.map +1 -1
  34. package/build/production/server/Cache.js +1 -1
  35. package/build/production/server/Cache.js.map +1 -1
  36. package/build/production/server/renderer.js +4 -4
  37. package/build/production/server/renderer.js.map +1 -1
  38. package/build/production/server/server.js +4 -4
  39. package/build/production/server/server.js.map +1 -1
  40. package/build/production/server/utils/errors.js +2 -2
  41. package/build/production/server/utils/errors.js.map +1 -1
  42. package/build/production/server/utils/modules.js +1 -1
  43. package/build/production/server/utils/modules.js.map +1 -1
  44. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
  45. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  46. package/build/production/shared/components/selectors/CustomDropdown/index.js +1 -1
  47. package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  48. package/build/production/shared/components/selectors/NativeDropdown/index.js +2 -2
  49. package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  50. package/build/production/shared/components/selectors/Switch/index.js +1 -1
  51. package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
  52. package/build/production/shared/utils/config.js +4 -1
  53. package/build/production/shared/utils/config.js.map +1 -1
  54. package/build/production/shared/utils/jest/E2eSsrEnv/index.js +3 -3
  55. package/build/production/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
  56. package/build/production/shared/utils/jest/index.js +3 -3
  57. package/build/production/shared/utils/jest/index.js.map +1 -1
  58. package/build/production/shared/utils/splitComponent.js +3 -3
  59. package/build/production/shared/utils/splitComponent.js.map +1 -1
  60. package/build/production/shared/utils/webpack.js +1 -1
  61. package/build/production/shared/utils/webpack.js.map +1 -1
  62. package/build/types-code/shared/utils/config.d.ts +1 -1
  63. package/build/web/client/getInj.js +1 -1
  64. package/build/web/client/getInj.js.map +1 -1
  65. package/build/web/server/Cache.js +1 -1
  66. package/build/web/server/Cache.js.map +1 -1
  67. package/build/web/server/renderer.js +4 -4
  68. package/build/web/server/renderer.js.map +1 -1
  69. package/build/web/server/server.js +4 -4
  70. package/build/web/server/server.js.map +1 -1
  71. package/build/web/server/utils/errors.js +2 -2
  72. package/build/web/server/utils/errors.js.map +1 -1
  73. package/build/web/server/utils/modules.js +1 -1
  74. package/build/web/server/utils/modules.js.map +1 -1
  75. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
  76. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  77. package/build/web/shared/components/selectors/CustomDropdown/index.js +1 -1
  78. package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  79. package/build/web/shared/components/selectors/NativeDropdown/index.js +2 -2
  80. package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  81. package/build/web/shared/components/selectors/Switch/index.js +1 -1
  82. package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
  83. package/build/web/shared/utils/config.js +4 -1
  84. package/build/web/shared/utils/config.js.map +1 -1
  85. package/build/web/shared/utils/jest/E2eSsrEnv/index.js +3 -3
  86. package/build/web/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
  87. package/build/web/shared/utils/jest/index.js +3 -3
  88. package/build/web/shared/utils/jest/index.js.map +1 -1
  89. package/build/web/shared/utils/splitComponent.js +3 -3
  90. package/build/web/shared/utils/splitComponent.js.map +1 -1
  91. package/build/web/shared/utils/webpack.js +1 -1
  92. package/build/web/shared/utils/webpack.js.map +1 -1
  93. package/config/babel/webpack.js +11 -2
  94. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"modules.js","names":[],"sources":["../../../../src/server/utils/modules.ts"],"sourcesContent":["// TODO: It makes sense to move these to more generic JS Utils,\n// but it will probably require some rework of exports there, as these\n// are strictly for NodeJS environment, while current JS Utils are\n// generic JavaScript, environment-agnostic... thus, for now let's\n// keep it here, until we really need these outside a React app.\n\nimport { existsSync, readFileSync, statSync } from 'node:fs';\nimport { type LoadFnOutput, createRequire, registerHooks } from 'node:module';\nimport { basename, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type * as BabelCore from '@babel/core';\n\nconst require = createRequire(import.meta.url);\n\ntype RegisterBabelLoaderArgT = {\n envName?: string;\n root?: string;\n};\n\n/**\n * It looks like, as of Babel v8, @babel/node does not quite work with ES module\n * codebase. This function registers a Node module API hook that customizes ES\n * module loading, to run Babel transformation on them.\n *{(\n * BEWARE: It is intended for development environments only.\n */\nexport function registerBabelLoader({\n envName = 'development',\n root = process.cwd(),\n}: RegisterBabelLoaderArgT = {}): void {\n // eslint-disable-next-line import/no-extraneous-dependencies\n const { transformSync } = require('@babel/core') as typeof BabelCore;\n\n const cache = new Map<string, LoadFnOutput>();\n\n registerHooks({\n load(url, context, next) {\n const cached = cache.get(url);\n if (cached !== undefined) return cached;\n\n if (\n url.startsWith('file://')\n && !url.includes('/node_modules/')\n && !url.includes('/config/babel/')\n && url.match(/.(js|jsx|svg|ts|tsx)$/)\n ) {\n const path = fileURLToPath(url);\n const source = readFileSync(path, 'utf8');\n\n const transformed = transformSync(source, {\n cwd: dirname(path),\n envName,\n filename: basename(path),\n root,\n });\n\n const res: LoadFnOutput = {\n format: 'module',\n shortCircuit: true,\n source: transformed?.code ?? '',\n };\n\n cache.set(url, res);\n return res;\n }\n\n return next(url, context);\n },\n });\n}\n\nconst CANDIDATE_EXTENSIONS = [\n '.js',\n '.jsx',\n '.ts',\n '.tsx',\n];\n\nfunction resolveExtension(base: string): null | string {\n for (const ext of CANDIDATE_EXTENSIONS) {\n const path = base + ext;\n if (existsSync(path)) return path;\n }\n\n return null;\n}\n\n/**\n * Registers a Node module API hook that customizes ES module resolution\n * to make mandatory file extensions optional.\n */\nexport function registerResolver(): void {\n registerHooks({\n resolve(specifier, context, next) {\n let path = specifier;\n\n const isAbsolute = path.startsWith('/');\n const isRelative = path.startsWith('.');\n\n if (isAbsolute || isRelative) {\n if (isRelative) path = new URL(path, context.parentURL).pathname;\n const stat = statSync(path, { throwIfNoEntry: false });\n if (!stat?.isFile()) {\n path = resolveExtension(path)\n ?? (stat?.isDirectory() ? resolveExtension(`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AAI,EAAE,WAAW,CAAC,CAAC,CAAG,gBAAgB,CAAC,GAAG,IAAI,QAAQ,CAAC,CAAG,IAAI,CAAC,EAChE,SAAS,CAChB,CACF,CAEA,MAAO,KAAI,CAAC,IAAI,CAAE,OAAO,CAAC,CAC5B,CACF,CAAC,CAAC,CACJ","ignoreList":[]}
1
+ {"version":3,"file":"modules.js","names":[],"sources":["../../../../src/server/utils/modules.ts"],"sourcesContent":["// TODO: It makes sense to move these to more generic JS Utils,\n// but it will probably require some rework of exports there, as these\n// are strictly for NodeJS environment, while current JS Utils are\n// generic JavaScript, environment-agnostic... thus, for now let's\n// keep it here, until we really need these outside a React app.\n\nimport { existsSync, readFileSync, statSync } from 'node:fs';\nimport { type LoadFnOutput, createRequire, registerHooks } from 'node:module';\nimport { basename, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type * as BabelCore from '@babel/core';\n\nconst require = createRequire(import.meta.url);\n\ntype RegisterBabelLoaderArgT = {\n envName?: string;\n root?: string;\n};\n\n/**\n * It looks like, as of Babel v8, @babel/node does not quite work with ES module\n * codebase. This function registers a Node module API hook that customizes ES\n * module loading, to run Babel transformation on them.\n *{(\n * BEWARE: It is intended for development environments only.\n */\nexport function registerBabelLoader({\n envName = 'development',\n root = process.cwd(),\n}: RegisterBabelLoaderArgT = {}): void {\n // eslint-disable-next-line import/no-extraneous-dependencies\n const { transformSync } = require('@babel/core') as typeof BabelCore;\n\n const cache = new Map<string, LoadFnOutput>();\n\n registerHooks({\n load(url, context, next) {\n const cached = cache.get(url);\n if (cached !== undefined) return cached;\n\n if (\n url.startsWith('file://')\n && !url.includes('/node_modules/')\n && !url.includes('/config/babel/')\n && url.match(/.(js|jsx|svg|ts|tsx)$/)\n ) {\n const path = fileURLToPath(url);\n const source = readFileSync(path, 'utf8');\n\n const transformed = transformSync(source, {\n cwd: dirname(path),\n envName,\n filename: basename(path),\n root,\n });\n\n const res: LoadFnOutput = {\n format: 'module',\n shortCircuit: true,\n source: transformed?.code ?? '',\n };\n\n cache.set(url, res);\n return res;\n }\n\n return next(url, context);\n },\n });\n}\n\nconst CANDIDATE_EXTENSIONS = [\n '.js',\n '.jsx',\n '.ts',\n '.tsx',\n];\n\nfunction resolveExtension(base: string): null | string {\n for (const ext of CANDIDATE_EXTENSIONS) {\n const path = base + ext;\n if (existsSync(path)) return path;\n }\n\n return null;\n}\n\n/**\n * Registers a Node module API hook that customizes ES module resolution\n * to make mandatory file extensions optional.\n */\nexport function registerResolver(): void {\n registerHooks({\n resolve(specifier, context, next) {\n let path = specifier;\n\n const isAbsolute = path.startsWith('/');\n const isRelative = path.startsWith('.');\n\n if (isAbsolute || isRelative) {\n if (isRelative) path = new URL(path, context.parentURL).pathname;\n const stat = statSync(path, { throwIfNoEntry: false });\n if (!stat?.isFile()) {\n path = resolveExtension(path)\n ?? (stat?.isDirectory() ? resolveExtension(`${path}/index`) : null)\n ?? specifier;\n }\n }\n\n return next(path, context);\n },\n });\n}\n"],"mappings":"mnDAAA;AACA;AACA;AACA;AACA;AAEA,OAAS,UAAU,CAAE,YAAY,CAAE,QAAQ,KAAQ,SAAS,CAC5D,OAA4B,aAAa,CAAE,aAAa,KAAQ,aAAa,CAC7E,OAAS,QAAQ,CAAE,OAAO,KAAQ,WAAW,CAC7C,OAAS,aAAa,KAAQ,UAAU,CAIxC,KAAM,QAAO,CAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAO9C;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,oBAAmB,CAAC,CAClC,OAAO,CAAG,aAAa,CACvB,IAAI,CAAG,OAAO,CAAC,GAAG,CAAC,CACI,CAAC,CAAG,CAAC,CAAC,CAAQ,CACrC;AACA,KAAM,CAAE,aAAc,CAAC,CAAG,OAAO,CAAC,aAAa,CAAqB,CAEpE,KAAM,MAAK,CAAG,GAAI,IAA2B,CAE7C,aAAa,CAAC,CACZ,IAAI,CAAC,GAAG,CAAE,OAAO,CAAE,IAAI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,CAAC,CACZ,OAAO,CAAC,SAAS,CAAE,OAAO,CAAE,IAAI,CAAE,CAChC,GAAI,KAAI,CAAG,SAAS,CAEpB,KAAM,WAAU,CAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CACvC,KAAM,WAAU,CAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAEvC,GAAI,UAAU,EAAI,UAAU,CAAE,CAC5B,GAAI,UAAU,CAAE,IAAI,CAAG,GAAI,IAAG,CAAC,IAAI,CAAE,OAAO,CAAC,SAAS,CAAC,CAAC,QAAQ,CAChE,KAAM,KAAI,CAAG,QAAQ,CAAC,IAAI,CAAE,CAAE,cAAc,CAAE,KAAM,CAAC,CAAC,CACtD,GAAI,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAE,CACnB,IAAI,CAAG,gBAAgB,CAAC,IAAI,CAAC,GACvB,IAAI,EAAE,WAAW,CAAC,CAAC,CAAG,gBAAgB,CAAC,GAAG,IAAI,QAAQ,CAAC,CAAG,IAAI,CAAC,EAChE,SAAS,CAChB,CACF,CAEA,MAAO,KAAI,CAAC,IAAI,CAAE,OAAO,CAAC,CAC5B,CACF,CAAC,CAAC,CACJ","ignoreList":[]}
@@ -1,2 +1,2 @@
1
- import _pushInstanceProperty from"core-js-pure/features/instance/push.js";import{c as _c}from"react/compiler-runtime";import{useImperativeHandle,useRef}from"react";import{BaseModal}from"../../../Modal/index.js";import{optionValueName}from"../../common.js";const S={"overlay":"ntZ5My"};import{jsx as _jsx}from"react/jsx-runtime";export function areEqual(a,b){return a?.left===b?.left&&a?.top===b?.top&&a?.width===b?.width;}const Options=t0=>{const $=_c(16);const{containerClass,containerStyle,filter,onCancel,onChange,optionClass,options,ref}=t0;const opsRef=useRef(null);let t1;let t2;if($[0]===Symbol.for("react.memo_cache_sentinel")){t1=()=>({measure:()=>{const e=opsRef.current?.parentElement;if(!e){return;}if(!opsRef.current){throw Error("Missing reference");}const rect=opsRef.current.getBoundingClientRect();const style=window.getComputedStyle(e);const mBottom=parseFloat(style.marginBottom);const mTop=parseFloat(style.marginTop);rect.height=rect.height+(mBottom+mTop);return rect;}});t2=[];$[0]=t1;$[1]=t2;}else{t1=$[0];t2=$[1];}useImperativeHandle(ref,t1,t2);let optionNodes;if($[2]!==filter||$[3]!==onChange||$[4]!==optionClass||$[5]!==options){optionNodes=[];for(const option of options){if(!filter||filter(option)){const[iValue,iName]=optionValueName(option);_pushInstanceProperty(optionNodes).call(optionNodes,/*#__PURE__*/_jsx("div",{className:optionClass,onClick:e_0=>{onChange(iValue);e_0.stopPropagation();},onKeyDown:e_1=>{if(e_1.key==="Enter"){onChange(iValue);e_1.stopPropagation();}},role:"button",tabIndex:0,children:iName},iValue));}}$[2]=filter;$[3]=onChange;$[4]=optionClass;$[5]=options;$[6]=optionNodes;}else{optionNodes=$[6];}let t3;if($[7]!==containerClass){t3={ad:"",container:containerClass,context:"",hoc:"",overlay:S.overlay};$[7]=containerClass;$[8]=t3;}else{t3=$[8];}let t4;if($[9]!==optionNodes){t4=/*#__PURE__*/_jsx("div",{ref:opsRef,children:optionNodes});$[9]=optionNodes;$[10]=t4;}else{t4=$[10];}let t5;if($[11]!==containerStyle||$[12]!==onCancel||$[13]!==t3||$[14]!==t4){t5=/*#__PURE__*/_jsx(BaseModal,{cancelOnScrolling:true,dontDisableScrolling:true,onCancel:onCancel,style:containerStyle,theme:t3,children:t4});$[11]=containerStyle;$[12]=onCancel;$[13]=t3;$[14]=t4;$[15]=t5;}else{t5=$[15];}return t5;};export default Options;
1
+ import"core-js/modules/es.iterator.filter.js";import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";import{c as _c}from"react/compiler-runtime";import{useImperativeHandle,useRef}from"react";import{BaseModal}from"../../../Modal/index.js";import{optionValueName}from"../../common.js";const S={"overlay":"ntZ5My"};import{jsx as _jsx}from"react/jsx-runtime";export function areEqual(a,b){return a?.left===b?.left&&a?.top===b?.top&&a?.width===b?.width;}const Options=t0=>{const $=_c(16);const{containerClass,containerStyle,filter,onCancel,onChange,optionClass,options,ref}=t0;const opsRef=useRef(null);let t1;let t2;if($[0]===Symbol.for("react.memo_cache_sentinel")){t1=()=>({measure:()=>{const e=opsRef.current?.parentElement;if(!e){return;}if(!opsRef.current){throw Error("Missing reference");}const rect=opsRef.current.getBoundingClientRect();const style=window.getComputedStyle(e);const mBottom=parseFloat(style.marginBottom);const mTop=parseFloat(style.marginTop);rect.height=rect.height+(mBottom+mTop);return rect;}});t2=[];$[0]=t1;$[1]=t2;}else{t1=$[0];t2=$[1];}useImperativeHandle(ref,t1,t2);let optionNodes;if($[2]!==filter||$[3]!==onChange||$[4]!==optionClass||$[5]!==options){optionNodes=[];for(const option of options){if(!filter||filter(option)){const[iValue,iName]=optionValueName(option);optionNodes.push(/*#__PURE__*/_jsx("div",{className:optionClass,onClick:e_0=>{onChange(iValue);e_0.stopPropagation();},onKeyDown:e_1=>{if(e_1.key==="Enter"){onChange(iValue);e_1.stopPropagation();}},role:"button",tabIndex:0,children:iName},iValue));}}$[2]=filter;$[3]=onChange;$[4]=optionClass;$[5]=options;$[6]=optionNodes;}else{optionNodes=$[6];}let t3;if($[7]!==containerClass){t3={ad:"",container:containerClass,context:"",hoc:"",overlay:S.overlay};$[7]=containerClass;$[8]=t3;}else{t3=$[8];}let t4;if($[9]!==optionNodes){t4=/*#__PURE__*/_jsx("div",{ref:opsRef,children:optionNodes});$[9]=optionNodes;$[10]=t4;}else{t4=$[10];}let t5;if($[11]!==containerStyle||$[12]!==onCancel||$[13]!==t3||$[14]!==t4){t5=/*#__PURE__*/_jsx(BaseModal,{cancelOnScrolling:true,dontDisableScrolling:true,onCancel:onCancel,style:containerStyle,theme:t3,children:t4});$[11]=containerStyle;$[12]=onCancel;$[13]=t3;$[14]=t4;$[15]=t5;}else{t5=$[15];}return t5;};export default Options;
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../../../../src/shared/components/selectors/CustomDropdown/Options/index.tsx"],"sourcesContent":["import {\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n useImperativeHandle,\n useRef,\n} from 'react';\n\nimport { BaseModal } from 'components/Modal';\n\nimport {\n type OptionT,\n type OptionsT,\n type ValueT,\n optionValueName,\n} from '../../common';\n\nimport S from './style.scss';\n\nexport type ContainerPosT = {\n left: number;\n top: number;\n width: number;\n};\n\nexport function areEqual(a?: ContainerPosT, b?: ContainerPosT): boolean {\n return a?.left === b?.left && a?.top === b?.top && a?.width === b?.width;\n}\n\nexport type RefT = {\n measure: () => DOMRect | undefined;\n};\n\ntype PropsT = {\n containerClass: string;\n containerStyle?: ContainerPosT;\n filter?: (item: OptionT<ReactNode> | ValueT) => boolean;\n onCancel: () => void;\n onChange: (value: ValueT) => void;\n optionClass: string;\n options: Readonly<OptionsT<ReactNode>>;\n ref?: RefObject<RefT | null>;\n};\n\nconst Options: FunctionComponent<PropsT> = ({\n containerClass,\n containerStyle,\n filter,\n onCancel,\n onChange,\n optionClass,\n options,\n ref,\n}) => {\n const opsRef = useRef<HTMLDivElement>(null);\n\n useImperativeHandle(ref, () => ({\n measure: () => {\n const e = opsRef.current?.parentElement;\n if (!e) return undefined;\n\n if (!opsRef.current) throw Error('Missing reference');\n const rect = opsRef.current.getBoundingClientRect();\n const style = window.getComputedStyle(e);\n const mBottom = parseFloat(style.marginBottom);\n const mTop = parseFloat(style.marginTop);\n\n rect.height += mBottom + mTop;\n\n return rect;\n },\n }), []);\n\n const optionNodes: ReactNode[] = [];\n for (const option of options) {\n if (!filter || filter(option)) {\n const [iValue, iName] = optionValueName(option);\n optionNodes.push(\n <div\n className={optionClass}\n key={iValue}\n onClick={(e) => {\n onChange(iValue);\n e.stopPropagation();\n }}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {\n onChange(iValue);\n e.stopPropagation();\n }\n }}\n role=\"button\"\n tabIndex={0}\n >\n {iName}\n </div>,\n );\n }\n }\n\n return (\n <BaseModal\n // Closes the dropdown (cancels the selection) on any page scrolling attempt.\n // This is the same native <select> elements do on scrolling, and at least for\n // now we have no reason to deal with complications needed to support open\n // dropdowns during the scrolling (that would need to re-position it in\n // response to the position changes of the root dropdown element).\n cancelOnScrolling\n dontDisableScrolling\n onCancel={onCancel}\n style={containerStyle}\n theme={{\n ad: '',\n container: containerClass,\n context: '',\n hoc: '',\n overlay: S.overlay,\n }}\n >\n <div ref={opsRef}>{optionNodes}</div>\n </BaseModal>\n );\n};\n\nexport default Options;\n"],"mappings":"sHAAA,OAIE,mBAAmB,CACnB,MAAM,KACD,OAAO,CAAC,OAEN,SAAS,sCAMhB,eAAe,uBAGjB,6BAA6B,2CAQ7B,MAAO,SAAS,SAAQ,CAAC,CAAiB,CAAE,CAAiB,CAAW,CACtE,MAAO,EAAC,EAAE,IAAI,GAAK,CAAC,EAAE,IAAI,EAAI,CAAC,EAAE,GAAG,GAAK,CAAC,EAAE,GAAG,EAAI,CAAC,EAAE,KAAK,GAAK,CAAC,EAAE,KAAK,CAC1E,CAiBA,KAAM,QAAkC,CAAG,oBAAC,wFAS3C,CACC,aAAe,MAAM,CAAiB,IAAI,CAAC,CAAC,iEAEnB,QAAO,SACrB,KACP,QAAU,MAAM,QAAuB,gBACvC,GAAI,CAAC,CAAC,UAEN,GAAI,CAAC,MAAM,QAAQ,EAAE,KAAM,MAAK,CAAC,mBAAmB,CAAC,CAAC,CACtD,WAAa,MAAM,QAAQ,sBAAsB,CAAC,CAAC,CACnD,YAAc,MAAM,iBAAiB,CAAC,CAAC,CAAC,CACxC,cAAgB,UAAU,CAAC,KAAK,aAAa,CAAC,CAC9C,WAAa,UAAU,CAAC,KAAK,UAAU,CAAC,CAExC,IAAI,QAAJ,IAAI,OAAO,EAAI,OAAO,CAAG,IAAI,CAAlB,OAEJ,KAAI,EAEf,CAAC,CAAC,CAAE,KAAE,wCAfN,mBAAmB,CAAC,GAAG,CAAE,EAevB,CAAE,EAAE,CAAC,wFAEP,YAAiC,EAAE,CACnC,IAAK,YAAY,GAAI,QAAO,EAC1B,GAAI,CAAC,MAAwB,EAAd,MAAM,CAAC,MAAM,CAAC,EAC3B,oBAAwB,eAAe,CAAC,MAAM,CAAC,CAC/C,iCAAW,OAAX,WAAW,cACT,YACa,SAAW,CAAX,WAAW,CAEb,OAGR,CAHQ,MACP,QAAQ,CAAC,MAAM,CAAC,CAChB,GAAC,gBAAgB,CAAC,CAAC,EACpB,CACU,SAKV,CALU,MACT,GAAI,GAAC,IAAI,GAAK,OAAO,EACnB,QAAQ,CAAC,MAAM,CAAC,CAChB,GAAC,gBAAgB,CAAC,CAAC,EACpB,CACF,CACI,IAAQ,CAAR,QAAQ,CACH,QAAC,CAAD,CAAC,UAEV,KAAK,EAdD,MAeF,CACP,CAAC,EACF,CACF,kIAaU,OACD,EAAE,WACK,cAAc,SAChB,EAAE,KACN,EAAE,SACE,CAAC,QACZ,CAAC,0EAED,4BAAU,GAAM,CAAN,MAAM,UAAG,WAAW,CAAM,CAAC,uHAlBvC,qBAAC,SAAS,EAMR,iBAAiB,CAAjB,IAAiB,CACjB,oBAAoB,CAApB,IAAoB,CACV,QAAQ,CAAR,QAAQ,CACX,KAAc,CAAd,cAAc,CACd,KAMN,CANM,EAMN,UAED,EAAqC,CAC5B,CAAC,sFAnBZ,GAmBY,EAEf,CAED,cAAe,QAAO","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../../../../src/shared/components/selectors/CustomDropdown/Options/index.tsx"],"sourcesContent":["import {\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n useImperativeHandle,\n useRef,\n} from 'react';\n\nimport { BaseModal } from 'components/Modal';\n\nimport {\n type OptionT,\n type OptionsT,\n type ValueT,\n optionValueName,\n} from '../../common';\n\nimport S from './style.scss';\n\nexport type ContainerPosT = {\n left: number;\n top: number;\n width: number;\n};\n\nexport function areEqual(a?: ContainerPosT, b?: ContainerPosT): boolean {\n return a?.left === b?.left && a?.top === b?.top && a?.width === b?.width;\n}\n\nexport type RefT = {\n measure: () => DOMRect | undefined;\n};\n\ntype PropsT = {\n containerClass: string;\n containerStyle?: ContainerPosT;\n filter?: (item: OptionT<ReactNode> | ValueT) => boolean;\n onCancel: () => void;\n onChange: (value: ValueT) => void;\n optionClass: string;\n options: Readonly<OptionsT<ReactNode>>;\n ref?: RefObject<RefT | null>;\n};\n\nconst Options: FunctionComponent<PropsT> = ({\n containerClass,\n containerStyle,\n filter,\n onCancel,\n onChange,\n optionClass,\n options,\n ref,\n}) => {\n const opsRef = useRef<HTMLDivElement>(null);\n\n useImperativeHandle(ref, () => ({\n measure: () => {\n const e = opsRef.current?.parentElement;\n if (!e) return undefined;\n\n if (!opsRef.current) throw Error('Missing reference');\n const rect = opsRef.current.getBoundingClientRect();\n const style = window.getComputedStyle(e);\n const mBottom = parseFloat(style.marginBottom);\n const mTop = parseFloat(style.marginTop);\n\n rect.height += mBottom + mTop;\n\n return rect;\n },\n }), []);\n\n const optionNodes: ReactNode[] = [];\n for (const option of options) {\n if (!filter || filter(option)) {\n const [iValue, iName] = optionValueName(option);\n optionNodes.push(\n <div\n className={optionClass}\n key={iValue}\n onClick={(e) => {\n onChange(iValue);\n e.stopPropagation();\n }}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {\n onChange(iValue);\n e.stopPropagation();\n }\n }}\n role=\"button\"\n tabIndex={0}\n >\n {iName}\n </div>,\n );\n }\n }\n\n return (\n <BaseModal\n // Closes the dropdown (cancels the selection) on any page scrolling attempt.\n // This is the same native <select> elements do on scrolling, and at least for\n // now we have no reason to deal with complications needed to support open\n // dropdowns during the scrolling (that would need to re-position it in\n // response to the position changes of the root dropdown element).\n cancelOnScrolling\n dontDisableScrolling\n onCancel={onCancel}\n style={containerStyle}\n theme={{\n ad: '',\n container: containerClass,\n context: '',\n hoc: '',\n overlay: S.overlay,\n }}\n >\n <div ref={opsRef}>{optionNodes}</div>\n </BaseModal>\n );\n};\n\nexport default Options;\n"],"mappings":"oOAAA,OAIE,mBA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ChB,GAAC,gBAAgB,CAAC,CAAC,EACpB,CACF,CACI,IAAQ,CAAR,QAAQ,CACH,QAAC,CAAD,CAAC,UAEV,KAAK,EAdD,MAeF,CACP,CAAC,EACF,CACF,kIAaU,OACD,EAAE,WACK,cAAc,SAChB,EAAE,KACN,EAAE,SACE,CAAC,QACZ,CAAC,0EAED,4BAAU,GAAM,CAAN,MAAM,UAAG,WAAW,CAAM,CAAC,uHAlBvC,qBAAC,SAAS,EAMR,iBAAiB,CAAjB,IAAiB,CACjB,oBAAoB,CAApB,IAAoB,CACV,QAAQ,CAAR,QAAQ,CACX,KAAc,CAAd,cAAc,CACd,KAMN,CANM,EAMN,UAED,EAAqC,CAC5B,CAAC,sFAnBZ,GAmBY,EAEf,CAED,cAAe,QAAO","ignoreList":[]}
@@ -1,2 +1,2 @@
1
- import{c as _c}from"react/compiler-runtime";import{useEffect,useRef,useState}from"react";import{useTheme}from"@dr.pogodin/react-themes";import{optionValueName}from"../common.js";import Options,{areEqual}from"./Options/index.js";const defaultTheme={"context":"SNj3wp","ad":"T6eOJ-","hoc":"KG-OKN","container":"SzHHPE","label":"KTG4ai","dropdown":"xdotm7","option":"y-WCDM","select":"PP5Siy","arrow":"_7-A7Lh","active":"RoOAZK","upward":"_--5Xpy"};import{Fragment as _Fragment,jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const CustomDropdown=t0=>{const $=_c(31);const{filter,label,onChange,options,theme,value}=t0;const custom=useTheme("CustomDropdown",defaultTheme,theme);const[active,setActive]=useState(false);const dropdownRef=useRef(null);const opsRef=useRef(null);const[opsPos,setOpsPos]=useState();const[upward,setUpward]=useState(false);let t1;let t2;if($[0]!==active){t1=()=>{if(!active){return;}let id;const cb=()=>{const anchor=dropdownRef.current?.getBoundingClientRect();const opsRect=opsRef.current?.measure();if(anchor&&opsRect){const fitsDown=anchor.bottom+opsRect.height<(window.visualViewport?.height??0);const fitsUp=anchor.top-opsRect.height>0;const up=!fitsDown&&fitsUp;setUpward(up);const pos=up?{left:anchor.left,top:anchor.top-opsRect.height-1,width:anchor.width}:{left:anchor.left,top:anchor.bottom,width:anchor.width};setOpsPos(now=>areEqual(now,pos)?now:pos);}id=requestAnimationFrame(cb);};requestAnimationFrame(cb);return()=>{cancelAnimationFrame(id);};};t2=[active];$[0]=active;$[1]=t1;$[2]=t2;}else{t1=$[1];t2=$[2];}useEffect(t1,t2);let t3;if($[3]===Symbol.for("react.memo_cache_sentinel")){t3=e=>{const view=window.visualViewport;if(!dropdownRef.current){throw Error("Missing dropdown reference");}const rect=dropdownRef.current.getBoundingClientRect();setActive(true);setOpsPos({left:view?.width??0,top:view?.height??0,width:rect.width});e.stopPropagation();};$[3]=t3;}else{t3=$[3];}const openList=t3;let t4;if($[4]===Symbol.for("react.memo_cache_sentinel")){t4=/*#__PURE__*/_jsx(_Fragment,{children:"‌"});$[4]=t4;}else{t4=$[4];}let selected=t4;if($[5]!==filter||$[6]!==options||$[7]!==value){for(const option of options){if(!filter||filter(option)){const[iValue,iName]=optionValueName(option);if(iValue===value){selected=iName;break;}}}$[5]=filter;$[6]=options;$[7]=value;$[8]=selected;}else{selected=$[8];}let containerClassName=custom.container??"";if(active){containerClassName=containerClassName+` ${custom.active??""}`;}let opsContainerClass=custom.select??"";if(upward){containerClassName=containerClassName+` ${custom.upward??""}`;opsContainerClass=opsContainerClass+` ${custom.upward??""}`;}let t5;if($[9]!==custom.label||$[10]!==label){t5=label===undefined?null:/*#__PURE__*/_jsx("div",{className:custom.label,children:label});$[9]=custom.label;$[10]=label;$[11]=t5;}else{t5=$[11];}let t6;if($[12]===Symbol.for("react.memo_cache_sentinel")){t6=e_0=>{if(e_0.key==="Enter"){openList(e_0);}};$[12]=t6;}else{t6=$[12];}let t7;if($[13]!==custom.arrow){t7=/*#__PURE__*/_jsx("div",{className:custom.arrow});$[13]=custom.arrow;$[14]=t7;}else{t7=$[14];}let t8;if($[15]!==custom.dropdown||$[16]!==selected||$[17]!==t7){t8=/*#__PURE__*/_jsxs("div",{className:custom.dropdown,onClick:openList,onKeyDown:t6,ref:dropdownRef,role:"listbox",tabIndex:0,children:[selected,t7]});$[15]=custom.dropdown;$[16]=selected;$[17]=t7;$[18]=t8;}else{t8=$[18];}let t9;if($[19]!==active||$[20]!==custom.option||$[21]!==onChange||$[22]!==opsContainerClass||$[23]!==opsPos||$[24]!==options){t9=active?/*#__PURE__*/_jsx(Options,{containerClass:opsContainerClass,containerStyle:opsPos,onCancel:()=>{setActive(false);},onChange:newValue=>{setActive(false);if(onChange){onChange(newValue);}},optionClass:custom.option??"",options:options,ref:opsRef}):null;$[19]=active;$[20]=custom.option;$[21]=onChange;$[22]=opsContainerClass;$[23]=opsPos;$[24]=options;$[25]=t9;}else{t9=$[25];}let t10;if($[26]!==containerClassName||$[27]!==t5||$[28]!==t8||$[29]!==t9){t10=/*#__PURE__*/_jsxs("div",{className:containerClassName,children:[t5,t8,t9]});$[26]=containerClassName;$[27]=t5;$[28]=t8;$[29]=t9;$[30]=t10;}else{t10=$[30];}return t10;};export default CustomDropdown;
1
+ import"core-js/modules/es.iterator.filter.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";import{c as _c}from"react/compiler-runtime";import{useEffect,useRef,useState}from"react";import{useTheme}from"@dr.pogodin/react-themes";import{optionValueName}from"../common.js";import Options,{areEqual}from"./Options/index.js";const defaultTheme={"context":"SNj3wp","ad":"T6eOJ-","hoc":"KG-OKN","container":"SzHHPE","label":"KTG4ai","dropdown":"xdotm7","option":"y-WCDM","select":"PP5Siy","arrow":"_7-A7Lh","active":"RoOAZK","upward":"_--5Xpy"};import{Fragment as _Fragment,jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const CustomDropdown=t0=>{const $=_c(31);const{filter,label,onChange,options,theme,value}=t0;const custom=useTheme("CustomDropdown",defaultTheme,theme);const[active,setActive]=useState(false);const dropdownRef=useRef(null);const opsRef=useRef(null);const[opsPos,setOpsPos]=useState();const[upward,setUpward]=useState(false);let t1;let t2;if($[0]!==active){t1=()=>{if(!active){return;}let id;const cb=()=>{const anchor=dropdownRef.current?.getBoundingClientRect();const opsRect=opsRef.current?.measure();if(anchor&&opsRect){const fitsDown=anchor.bottom+opsRect.height<(window.visualViewport?.height??0);const fitsUp=anchor.top-opsRect.height>0;const up=!fitsDown&&fitsUp;setUpward(up);const pos=up?{left:anchor.left,top:anchor.top-opsRect.height-1,width:anchor.width}:{left:anchor.left,top:anchor.bottom,width:anchor.width};setOpsPos(now=>areEqual(now,pos)?now:pos);}id=requestAnimationFrame(cb);};requestAnimationFrame(cb);return()=>{cancelAnimationFrame(id);};};t2=[active];$[0]=active;$[1]=t1;$[2]=t2;}else{t1=$[1];t2=$[2];}useEffect(t1,t2);let t3;if($[3]===Symbol.for("react.memo_cache_sentinel")){t3=e=>{const view=window.visualViewport;if(!dropdownRef.current){throw Error("Missing dropdown reference");}const rect=dropdownRef.current.getBoundingClientRect();setActive(true);setOpsPos({left:view?.width??0,top:view?.height??0,width:rect.width});e.stopPropagation();};$[3]=t3;}else{t3=$[3];}const openList=t3;let t4;if($[4]===Symbol.for("react.memo_cache_sentinel")){t4=/*#__PURE__*/_jsx(_Fragment,{children:"‌"});$[4]=t4;}else{t4=$[4];}let selected=t4;if($[5]!==filter||$[6]!==options||$[7]!==value){for(const option of options){if(!filter||filter(option)){const[iValue,iName]=optionValueName(option);if(iValue===value){selected=iName;break;}}}$[5]=filter;$[6]=options;$[7]=value;$[8]=selected;}else{selected=$[8];}let containerClassName=custom.container??"";if(active){containerClassName=containerClassName+` ${custom.active??""}`;}let opsContainerClass=custom.select??"";if(upward){containerClassName=containerClassName+` ${custom.upward??""}`;opsContainerClass=opsContainerClass+` ${custom.upward??""}`;}let t5;if($[9]!==custom.label||$[10]!==label){t5=label===undefined?null:/*#__PURE__*/_jsx("div",{className:custom.label,children:label});$[9]=custom.label;$[10]=label;$[11]=t5;}else{t5=$[11];}let t6;if($[12]===Symbol.for("react.memo_cache_sentinel")){t6=e_0=>{if(e_0.key==="Enter"){openList(e_0);}};$[12]=t6;}else{t6=$[12];}let t7;if($[13]!==custom.arrow){t7=/*#__PURE__*/_jsx("div",{className:custom.arrow});$[13]=custom.arrow;$[14]=t7;}else{t7=$[14];}let t8;if($[15]!==custom.dropdown||$[16]!==selected||$[17]!==t7){t8=/*#__PURE__*/_jsxs("div",{className:custom.dropdown,onClick:openList,onKeyDown:t6,ref:dropdownRef,role:"listbox",tabIndex:0,children:[selected,t7]});$[15]=custom.dropdown;$[16]=selected;$[17]=t7;$[18]=t8;}else{t8=$[18];}let t9;if($[19]!==active||$[20]!==custom.option||$[21]!==onChange||$[22]!==opsContainerClass||$[23]!==opsPos||$[24]!==options){t9=active?/*#__PURE__*/_jsx(Options,{containerClass:opsContainerClass,containerStyle:opsPos,onCancel:()=>{setActive(false);},onChange:newValue=>{setActive(false);if(onChange){onChange(newValue);}},optionClass:custom.option??"",options:options,ref:opsRef}):null;$[19]=active;$[20]=custom.option;$[21]=onChange;$[22]=opsContainerClass;$[23]=opsPos;$[24]=options;$[25]=t9;}else{t9=$[25];}let t10;if($[26]!==containerClassName||$[27]!==t5||$[28]!==t8||$[29]!==t9){t10=/*#__PURE__*/_jsxs("div",{className:containerClassName,children:[t5,t8,t9]});$[26]=containerClassName;$[27]=t5;$[28]=t8;$[29]=t9;$[30]=t10;}else{t10=$[30];}return t10;};export default CustomDropdown;
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/components/selectors/CustomDropdown/index.tsx"],"sourcesContent":["import {\n type FunctionComponent,\n type ReactNode,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { useTheme } from '@dr.pogodin/react-themes';\n\nimport { type PropsT, type ValueT, optionValueName } from '../common';\n\nimport Options, { type ContainerPosT, type RefT, areEqual } from './Options';\n\nimport defaultTheme from './theme.scss';\n\nconst CustomDropdown: FunctionComponent<\n PropsT<ReactNode, (value: ValueT) => void>\n> = ({\n filter,\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n const custom = useTheme('CustomDropdown', defaultTheme, theme);\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 left: anchor.left,\n top: anchor.top - opsRect.height - 1,\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 if (!dropdownRef.current) throw Error('Missing dropdown reference');\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 = <>&zwnj;</>;\n for (const option of options) {\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 = custom.container ?? '';\n if (active) containerClassName += ` ${custom.active ?? ''}`;\n\n let opsContainerClass = custom.select ?? '';\n if (upward) {\n containerClassName += ` ${custom.upward ?? ''}`;\n opsContainerClass += ` ${custom.upward ?? ''}`;\n }\n\n return (\n <div className={containerClassName}>\n {label === undefined ? null\n : <div className={custom.label}>{label}</div>}\n <div\n className={custom.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={custom.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={custom.option ?? ''}\n options={options}\n ref={opsRef}\n />\n ) : null\n }\n </div>\n );\n};\n\nexport default CustomDropdown;\n"],"mappings":"4CAAA,OAGE,SAAS,CACT,MAAM,CACN,QAAQ,KACH,OAAO,CAEd,OAAS,QAAQ,KAAQ,0BAA0B,CAAC,OAEjB,eAAe,0BAE3C,QAAO,EAAmC,QAAQ,0BAEzD,0NAAwC,+EAExC,KAAM,eAEL,CAAG,oBAAC,mDAOJ,CACC,aAAe,QAAQ,CAAC,gBAAgB,CAAE,YAAY,CAAE,KAAK,CAAC,CAE9D,wBAA4B,QAAQ,CAAC,KAAK,CAAC,CAE3C,kBAAoB,MAAM,CAAiB,IAAI,CAAC,CAChD,aAAe,MAAM,CAAO,IAAI,CAAC,CAEjC,wBAA4B,QAAQ,CAAgB,CAAC,CACrD,wBAA4B,QAAQ,CAAC,KAAK,CAAC,CAAC,gCAElC,QACR,GAAI,CAAC,MAAM,UAEP,OACJ,SAAW,KACT,aAAe,WAAW,QAA+B,uBAAE,CAAD,CAAC,CAC3D,cAAgB,MAAM,QAAiB,SAAE,CAAD,CAAC,CACzC,GAAI,MAAiB,EAAjB,OAAiB,EACnB,eAAiB,MAAM,OAAO,CAAG,OAAO,OAAO,EAC1C,MAAM,eA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CN,IAkCM,EAET,CAED,cAAe,eAAc","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/components/selectors/CustomDropdown/index.tsx"],"sourcesContent":["import {\n type FunctionComponent,\n type ReactNode,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { useTheme } from '@dr.pogodin/react-themes';\n\nimport { type PropsT, type ValueT, optionValueName } from '../common';\n\nimport Options, { type ContainerPosT, type RefT, areEqual } from './Options';\n\nimport defaultTheme from './theme.scss';\n\nconst CustomDropdown: FunctionComponent<\n PropsT<ReactNode, (value: ValueT) => void>\n> = ({\n filter,\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n const custom = useTheme('CustomDropdown', defaultTheme, theme);\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 left: anchor.left,\n top: anchor.top - opsRect.height - 1,\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 if (!dropdownRef.current) throw Error('Missing dropdown reference');\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 = <>&zwnj;</>;\n for (const option of options) {\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 = custom.container ?? '';\n if (active) containerClassName += ` ${custom.active ?? ''}`;\n\n let opsContainerClass = custom.select ?? '';\n if (upward) {\n containerClassName += ` ${custom.upward ?? ''}`;\n opsContainerClass += ` ${custom.upward ?? ''}`;\n }\n\n return (\n <div className={containerClassName}>\n {label === undefined ? null\n : <div className={custom.label}>{label}</div>}\n <div\n className={custom.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={custom.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={custom.option ?? ''}\n options={options}\n ref={opsRef}\n />\n ) : null\n }\n </div>\n );\n};\n\nexport default CustomDropdown;\n"],"mappings":"2LAAA,OAGE,SAAS,CACT,MAAM,CACN,QAAQ,KACH,OAAO,CAEd,OAAS,QAAQ,KAAQ,0BAA0B,CAAC,OAEjB,eAAe,0BAE3C,QAAO,EAAmC,QAAQ,0BAEzD,0NAAwC,+EAExC,KAAM,eAEL,CAAG,oBAAC,mDAOJ,CACC,aAAe,QAAQ,CAAC,gBAAgB,CAAE,YAAY,CAAE,KAAK,CAAC,CAE9D,wBAA4B,QAAQ,CAAC,KAAK,CAAC,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AAN,MAAM,CACZ,QAET,CAFS,KACR,SAAS,CAAC,KAAK,CAAC,EACjB,CACS,QAGT,CAHS,WACR,SAAS,CAAC,KAAK,CAAC,CAChB,GAAI,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,EAAC,CAClC,CACY,WAAmB,CAAnB,MAAM,OAAa,EAAnB,EAAmB,CACvB,OAAO,CAAP,OAAO,CACX,GAAM,CAAN,MAAM,CAER,CAAC,CAfR,IAeQ,wMAhCZ,8BAAgB,SAAkB,CAAlB,kBAAkB,WAC/B,EAC8C,CAC/C,EAYM,CAEJ,EAeQ,EAEP,CAAC,sFAlCN,IAkCM,EAET,CAED,cAAe,eAAc","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- import _pushInstanceProperty from"core-js-pure/features/instance/push.js";// Implements dropdown based on the native HTML <select> element.
1
+ import"core-js/modules/es.iterator.filter.js";import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";// Implements dropdown based on the native HTML <select> element.
2
2
  import{useTheme}from"@dr.pogodin/react-themes";import{optionValueName}from"../common.js";const defaultTheme={"context":"WbwY1Y","ad":"AP5hsY","hoc":"ODAJeW","dropdown":"wabw76","arrow":"WFSB9z","container":"vE9M8Z","active":"sfLSJA","label":"bQLBhS","option":"wgCtdC","hiddenOption":"ty19C2","select":"ntbzPR","invalid":"_3CzMM4"};/**
3
3
  * Implements a themeable dropdown list. Internally it is rendered with help of
4
4
  * the standard HTML `<select>` element, thus the styling support is somewhat
@@ -17,7 +17,7 @@ import{useTheme}from"@dr.pogodin/react-themes";import{optionValueName}from"../co
17
17
  * @param [props.value] Currently selected value.
18
18
  * @param [props....]
19
19
  * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)
20
- */import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const Dropdown=({filter,label,onChange,onClick,options,testId,theme,value})=>{let isValidValue=false;const optionElements=[];const composed=useTheme("Dropdown",defaultTheme,theme);for(const option of options){if(!filter||filter(option)){const[iValue,iName]=optionValueName(option);isValidValue||=iValue===value;_pushInstanceProperty(optionElements).call(optionElements,/*#__PURE__*/_jsx("option",{className:composed.option,value:iValue,children:iName},iValue));}}// NOTE: This element represents the current `value` when it does not match
20
+ */import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const Dropdown=({filter,label,onChange,onClick,options,testId,theme,value})=>{let isValidValue=false;const optionElements=[];const composed=useTheme("Dropdown",defaultTheme,theme);for(const option of options){if(!filter||filter(option)){const[iValue,iName]=optionValueName(option);isValidValue||=iValue===value;optionElements.push(/*#__PURE__*/_jsx("option",{className:composed.option,value:iValue,children:iName},iValue));}}// NOTE: This element represents the current `value` when it does not match
21
21
  // any valid option. In Chrome, and some other browsers, we are able to hide
22
22
  // it from the opened dropdown; in others, e.g. Safari, the best we can do is
23
23
  // to show it as disabled.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/components/selectors/NativeDropdown/index.tsx"],"sourcesContent":["// Implements dropdown based on the native HTML <select> element.\n\nimport type { FunctionComponent } from 'react';\n\nimport { useTheme } from '@dr.pogodin/react-themes';\n\nimport { type PropsT, optionValueName } from '../common';\n\nimport defaultTheme from './theme.scss';\n\n/**\n * Implements a themeable dropdown list. Internally it is rendered with help of\n * the standard HTML `<select>` element, thus the styling support is somewhat\n * limited.\n * @param [props] Component properties.\n * @param [props.filter] Options filter function. If provided, only\n * those elements of `options` list will be used by the dropdown, for which this\n * filter returns `true`.\n * @param [props.label] Dropdown label.\n * @param [props.onChange] Selection event handler.\n * @param [props.options=[]] Array of dropdown\n * options. For string elements the option value and name will be the same.\n * It is allowed to mix DropdownOption and string elements in the same option\n * list.\n * @param [props.theme] _Ad hoc_ theme.\n * @param [props.value] Currently selected value.\n * @param [props....]\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nconst Dropdown: FunctionComponent<PropsT<string>> = ({\n filter,\n label,\n onChange,\n onClick,\n options,\n testId,\n theme,\n value,\n}) => {\n let isValidValue = false;\n const optionElements = [];\n\n const composed = useTheme('Dropdown', defaultTheme, theme);\n\n for (const option of options) {\n if (!filter || filter(option)) {\n const [iValue, iName] = optionValueName(option);\n isValidValue ||= iValue === value;\n optionElements.push(\n <option className={composed.option} key={iValue} value={iValue}>\n {iName}\n </option>,\n );\n }\n }\n\n // NOTE: This element represents the current `value` when it does not match\n // any valid option. In Chrome, and some other browsers, we are able to hide\n // it from the opened dropdown; in others, e.g. Safari, the best we can do is\n // to show it as disabled.\n const hiddenOption = isValidValue ? null : (\n <option\n className={composed.hiddenOption}\n disabled\n key=\"__reactUtilsHiddenOption\"\n value={value}\n >\n {value}\n </option>\n );\n\n let selectClassName = composed.select ?? '';\n if (!isValidValue) selectClassName += ` ${composed.invalid ?? ''}`;\n\n return (\n <div className={composed.container}>\n { label === undefined\n ? null : <div className={composed.label}>{label}</div> }\n <div className={composed.dropdown}>\n <select\n className={selectClassName}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onChange={onChange}\n onClick={onClick}\n value={value}\n >\n {hiddenOption}\n {optionElements}\n </select>\n <div className={composed.arrow} />\n </div>\n </div>\n );\n};\n\nexport default Dropdown;\n"],"mappings":"0EAAA;AAIA,OAAS,QAAQ,KAAQ,0BAA0B,CAAC,OAE9B,eAAe,oBAErC,kPAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAlBA,yDAmBA,KAAM,SAA2C,CAAG,CAAC,CACnD,MAAM,CACN,KAAK,CACL,QAAQ,CACR,OAAO,CACP,OAAO,CACP,MAAM,CACN,KAAK,CACL,KACF,CAAC,GAAK,CACJ,GAAI,aAAY,CAAG,KAAK,CACxB,KAAM,eAAc,CAAG,EAAE,CAEzB,KAAM,SAAQ,CAAG,QAAQ,CAAC,UAAU,CAAE,YAAY,CAAE,KAAK,CAAC,C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":[],"sources":["../../../../../../src/shared/components/selectors/NativeDropdown/index.tsx"],"sourcesContent":["// Implements dropdown based on the native HTML <select> element.\n\nimport type { FunctionComponent } from 'react';\n\nimport { useTheme } from '@dr.pogodin/react-themes';\n\nimport { type PropsT, optionValueName } from '../common';\n\nimport defaultTheme from './theme.scss';\n\n/**\n * Implements a themeable dropdown list. Internally it is rendered with help of\n * the standard HTML `<select>` element, thus the styling support is somewhat\n * limited.\n * @param [props] Component properties.\n * @param [props.filter] Options filter function. If provided, only\n * those elements of `options` list will be used by the dropdown, for which this\n * filter returns `true`.\n * @param [props.label] Dropdown label.\n * @param [props.onChange] Selection event handler.\n * @param [props.options=[]] Array of dropdown\n * options. For string elements the option value and name will be the same.\n * It is allowed to mix DropdownOption and string elements in the same option\n * list.\n * @param [props.theme] _Ad hoc_ theme.\n * @param [props.value] Currently selected value.\n * @param [props....]\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nconst Dropdown: FunctionComponent<PropsT<string>> = ({\n filter,\n label,\n onChange,\n onClick,\n options,\n testId,\n theme,\n value,\n}) => {\n let isValidValue = false;\n const optionElements = [];\n\n const composed = useTheme('Dropdown', defaultTheme, theme);\n\n for (const option of options) {\n if (!filter || filter(option)) {\n const [iValue, iName] = optionValueName(option);\n isValidValue ||= iValue === value;\n optionElements.push(\n <option className={composed.option} key={iValue} value={iValue}>\n {iName}\n </option>,\n );\n }\n }\n\n // NOTE: This element represents the current `value` when it does not match\n // any valid option. In Chrome, and some other browsers, we are able to hide\n // it from the opened dropdown; in others, e.g. Safari, the best we can do is\n // to show it as disabled.\n const hiddenOption = isValidValue ? null : (\n <option\n className={composed.hiddenOption}\n disabled\n key=\"__reactUtilsHiddenOption\"\n value={value}\n >\n {value}\n </option>\n );\n\n let selectClassName = composed.select ?? '';\n if (!isValidValue) selectClassName += ` ${composed.invalid ?? ''}`;\n\n return (\n <div className={composed.container}>\n { label === undefined\n ? null : <div className={composed.label}>{label}</div> }\n <div className={composed.dropdown}>\n <select\n className={selectClassName}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onChange={onChange}\n onClick={onClick}\n value={value}\n >\n {hiddenOption}\n {optionElements}\n </select>\n <div className={composed.arrow} />\n </div>\n </div>\n );\n};\n\nexport default Dropdown;\n"],"mappings":"wLAAA;AAIA,OAAS,QAAQ,KAAQ,0BAA0B,CAAC,OAE9B,eAAe,oBAErC,kPAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAlBA,yDAmBA,KAAM,SAA2C,CAAG,CAAC,CACnD,MAAM,CACN,KAAK,CACL,QAAQ,CACR,OAAO,CACP,OAAO,CACP,MAAM,CACN,KAAK,CACL,KACF,CAAC,GAAK,CACJ,GAAI,aAAY,CAAG,KAAK,CACxB,KAAM,eAAc,CAAG,EAAE,CAEzB,KAAM,SAAQ,CAAG,QAAQ,CAAC,UAAU,CAAE,YAAY,CAAE,KAAK,CAAC,CAE1D,IAAK,KAAM,OAAM,GAAI,QAAO,CAAE,CAC5B,GAAI,CAAC,MAAM,EAAI,MAAM,CAAC,MAAM,CAAC,CAAE,CAC7B,KAAM,CAAC,MAAM,CAAE,KAAK,CAAC,CAAG,eAAe,CAAC,MAAM,CAAC,CAC/C,YAAY,GAAK,MAAM,GAAK,KAAK,CACjC,cAAc,CAAC,IAAI,cACjB,eAAQ,SAAS,CAAE,QAAQ,CAAC,MAAO,CAAc,KAAK,CAAE,MAAO,UAC5D,KAAK,EADiC,MAEjC,CACV,CAAC,CACH,CACF,CAEA;AACA;AACA;AACA;AACA,KAAM,aAAY,CAAG,YAAY,CAAG,IAAI,cACtC,eACE,SAAS,CAAE,QAAQ,CAAC,YAAa,CACjC,QAAQ,MAER,KAAK,CAAE,KAAM,UAEZ,KAAK,EAHF,0BAIE,CACT,CAED,GAAI,gBAAe,CAAG,QAAQ,CAAC,MAAM,EAAI,EAAE,CAC3C,GAAI,CAAC,YAAY,CAAE,eAAe,EAAI,IAAI,QAAQ,CAAC,OAAO,EAAI,EAAE,EAAE,CAElE,mBACE,aAAK,SAAS,CAAE,QAAQ,CAAC,SAAU,WAC/B,KAAK,GAAK,SAAS,CACjB,IAAI,cAAG,YAAK,SAAS,CAAE,QAAQ,CAAC,KAAM,UAAE,KAAK,CAAM,CAAC,cACxD,aAAK,SAAS,CAAE,QAAQ,CAAC,QAAS,wBAChC,gBACE,SAAS,CAAE,eAAgB,CAC3B,cAAa,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAK,YAAY,CAAG,SAAS,CAAG,MAAO,CACxE,QAAQ,CAAE,QAAS,CACnB,OAAO,CAAE,OAAQ,CACjB,KAAK,CAAE,KAAM,WAEZ,YAAY,CACZ,cAAc,EACT,CAAC,cACT,YAAK,SAAS,CAAE,QAAQ,CAAC,KAAM,CAAE,CAAC,EAC/B,CAAC,EACH,CAAC,CAEV,CAAC,CAED,cAAe,SAAQ","ignoreList":[]}
@@ -1,2 +1,2 @@
1
- import _pushInstanceProperty from"core-js-pure/features/instance/push.js";import{c as _c}from"react/compiler-runtime";import{useTheme}from"@dr.pogodin/react-themes";import{optionValueName}from"../common.js";const defaultTheme={"context":"akD3dQ","ad":"xcXtdE","hoc":"N3iziJ","container":"BYeWyJ","option":"_7MFXEN","selected":"CDbWAd","options":"_9-eOZo"};import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";export const Switch=t0=>{const $=_c(16);const{label,onChange,options,theme,value}=t0;const composed=useTheme("Switch",defaultTheme,theme);if(!options||!composed.option){throw Error("Internal error");}let optionNodes;if($[0]!==composed.option||$[1]!==composed.selected||$[2]!==onChange||$[3]!==options||$[4]!==value){optionNodes=[];for(const option of options){const[iValue,iName]=optionValueName(option);let className=composed.option;let onPress;if(iValue===value){className=className+` ${composed.selected??""}`;}else{if(onChange){onPress=()=>{onChange(iValue);};}}_pushInstanceProperty(optionNodes).call(optionNodes,onPress?/*#__PURE__*/_jsx("div",{className:className,onClick:onPress,onKeyDown:e=>{if(e.key==="Enter"){onPress();}},role:"button",tabIndex:0,children:iName},iValue):/*#__PURE__*/_jsx("div",{className:className,children:iName},iValue));}$[0]=composed.option;$[1]=composed.selected;$[2]=onChange;$[3]=options;$[4]=value;$[5]=optionNodes;}else{optionNodes=$[5];}let t1;if($[6]!==composed.label||$[7]!==label){t1=label?/*#__PURE__*/_jsx("div",{className:composed.label,children:label}):null;$[6]=composed.label;$[7]=label;$[8]=t1;}else{t1=$[8];}let t2;if($[9]!==composed.options||$[10]!==optionNodes){t2=/*#__PURE__*/_jsx("div",{className:composed.options,children:optionNodes});$[9]=composed.options;$[10]=optionNodes;$[11]=t2;}else{t2=$[11];}let t3;if($[12]!==composed.container||$[13]!==t1||$[14]!==t2){t3=/*#__PURE__*/_jsxs("div",{className:composed.container,children:[t1,t2]});$[12]=composed.container;$[13]=t1;$[14]=t2;$[15]=t3;}else{t3=$[15];}return t3;};
1
+ import"core-js/modules/es.array.push.js";import{c as _c}from"react/compiler-runtime";import{useTheme}from"@dr.pogodin/react-themes";import{optionValueName}from"../common.js";const defaultTheme={"context":"akD3dQ","ad":"xcXtdE","hoc":"N3iziJ","container":"BYeWyJ","option":"_7MFXEN","selected":"CDbWAd","options":"_9-eOZo"};import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";export const Switch=t0=>{const $=_c(16);const{label,onChange,options,theme,value}=t0;const composed=useTheme("Switch",defaultTheme,theme);if(!options||!composed.option){throw Error("Internal error");}let optionNodes;if($[0]!==composed.option||$[1]!==composed.selected||$[2]!==onChange||$[3]!==options||$[4]!==value){optionNodes=[];for(const option of options){const[iValue,iName]=optionValueName(option);let className=composed.option;let onPress;if(iValue===value){className=className+` ${composed.selected??""}`;}else{if(onChange){onPress=()=>{onChange(iValue);};}}optionNodes.push(onPress?/*#__PURE__*/_jsx("div",{className:className,onClick:onPress,onKeyDown:e=>{if(e.key==="Enter"){onPress();}},role:"button",tabIndex:0,children:iName},iValue):/*#__PURE__*/_jsx("div",{className:className,children:iName},iValue));}$[0]=composed.option;$[1]=composed.selected;$[2]=onChange;$[3]=options;$[4]=value;$[5]=optionNodes;}else{optionNodes=$[5];}let t1;if($[6]!==composed.label||$[7]!==label){t1=label?/*#__PURE__*/_jsx("div",{className:composed.label,children:label}):null;$[6]=composed.label;$[7]=label;$[8]=t1;}else{t1=$[8];}let t2;if($[9]!==composed.options||$[10]!==optionNodes){t2=/*#__PURE__*/_jsx("div",{className:composed.options,children:optionNodes});$[9]=composed.options;$[10]=optionNodes;$[11]=t2;}else{t2=$[11];}let t3;if($[12]!==composed.container||$[13]!==t1||$[14]!==t2){t3=/*#__PURE__*/_jsxs("div",{className:composed.container,children:[t1,t2]});$[12]=composed.container;$[13]=t1;$[14]=t2;$[15]=t3;}else{t3=$[15];}return t3;};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/components/selectors/Switch/index.tsx"],"sourcesContent":["import type { FunctionComponent, ReactNode } from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport {\n type OptionsT,\n type ValueT,\n optionValueName,\n} from '../common';\n\nimport defaultTheme from './theme.scss';\n\ntype ThemeT = Theme<'container' | 'label' | 'option' | 'options' | 'selected'>;\n\ntype PropsT = {\n label?: ReactNode;\n onChange?: (value: ValueT) => void;\n options?: Readonly<OptionsT<ReactNode>>;\n theme?: ThemeT;\n value?: ValueT;\n};\n\nexport const Switch: FunctionComponent<PropsT> = ({\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n const composed = useTheme('Switch', defaultTheme, theme);\n\n if (!options || !composed.option) throw Error('Internal error');\n\n const optionNodes: React.ReactNode[] = [];\n for (const option of options) {\n const [iValue, iName] = optionValueName(option);\n\n let className: string = composed.option;\n let onPress: (() => void) | undefined;\n if (iValue === value) className += ` ${composed.selected ?? ''}`;\n else if (onChange) {\n onPress = () => {\n onChange(iValue);\n };\n }\n\n optionNodes.push(\n onPress\n ? (\n <div\n className={className}\n key={iValue}\n onClick={onPress}\n onKeyDown={(e) => {\n if (e.key === 'Enter') onPress();\n }}\n role=\"button\"\n tabIndex={0}\n >\n {iName}\n </div>\n )\n : <div className={className} key={iValue}>{iName}</div>,\n );\n }\n\n return (\n <div className={composed.container}>\n {label ? <div className={composed.label}>{label}</div> : null}\n\n <div className={composed.options}>\n {optionNodes}\n </div>\n </div>\n );\n};\n"],"mappings":"sHAEA,OAAqB,QAAQ,KAAQ,0BAA0B,CAAC,OAK9D,eAAe,oBAGjB,qJAAwC,yDAYxC,MAAO,MAAM,OAAiC,CAAG,oBAAC,4CAMjD,CACC,eAAiB,QAAQ,CAAC,QAAQ,CAAE,YAAY,CAAE,KAAK,CAAC,CAExD,GAAI,CAAC,OAA2B,EAA5B,CAAa,QAAQ,OAAO,EAAE,KAAM,MAAK,CAAC,gBAAgB,CAAC,CAAC,qHAEhE,YAAuC,EAAE,CACzC,IAAK,YAAY,GAAI,QAAO,EAC1B,oBAAwB,eAAe,CAAC,MAAM,CAAC,CAE/C,cAAwB,QAAQ,OAAO,CACnC,YACJ,GAAI,MAAM,GAAK,KAAK,EAAE,mBAAS,CAAI,IAAI,QAAQ,SAAe,EAAvB,EAAuB,EAAE,OAC3D,GAAI,QAAQ,EACf,QAAU,KACR,QAAQ,CAAC,MAAM,CAAC,EACjB,CAFM,CAGR,CAED,iCAAW,OAAX,WAAW,CACT,OAAO,cAAP,YAGiB,SAAS,CAAT,SAAS,CAEX,OAAO,CAAP,OAAO,CACL,SAEV,CAFU,IACT,GAAI,CAAC,IAAI,GAAK,OAAO,EAAE,OAAO,CAAC,CAAC,EAAC,CAClC,CACI,IAAQ,CAAR,QAAQ,CACH,QAAC,CAAD,CAAC,UAEV,KAAK,EARD,MAW6C,CAAC,cAfzD,YAeoB,SAAS,CAAT,SAAS,UAAgB,KAAK,EAAd,MAAoB,CAC1D,CAAC,EACF,0KAII,QAAK,cAAL,YAAwB,SAAc,CAAd,QAAQ,MAAM,UAAG,KAAK,CAAa,CAAC,CAA5D,IAA4D,+GAE7D,4BAAgB,SAAgB,CAAhB,QAAQ,QAAQ,UAC7B,WAAW,CACT,CAAC,gIALR,6BAAgB,SAAkB,CAAlB,QAAQ,UAAU,WAC/B,EAA4D,CAE7D,EAEM,EACH,CAAC,2EANN,GAMM,EAET","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/components/selectors/Switch/index.tsx"],"sourcesContent":["import type { FunctionComponent, ReactNode } from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport {\n type OptionsT,\n type ValueT,\n optionValueName,\n} from '../common';\n\nimport defaultTheme from './theme.scss';\n\ntype ThemeT = Theme<'container' | 'label' | 'option' | 'options' | 'selected'>;\n\ntype PropsT = {\n label?: ReactNode;\n onChange?: (value: ValueT) => void;\n options?: Readonly<OptionsT<ReactNode>>;\n theme?: ThemeT;\n value?: ValueT;\n};\n\nexport const Switch: FunctionComponent<PropsT> = ({\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n const composed = useTheme('Switch', defaultTheme, theme);\n\n if (!options || !composed.option) throw Error('Internal error');\n\n const optionNodes: React.ReactNode[] = [];\n for (const option of options) {\n const [iValue, iName] = optionValueName(option);\n\n let className: string = composed.option;\n let onPress: (() => void) | undefined;\n if (iValue === value) className += ` ${composed.selected ?? ''}`;\n else if (onChange) {\n onPress = () => {\n onChange(iValue);\n };\n }\n\n optionNodes.push(\n onPress\n ? (\n <div\n className={className}\n key={iValue}\n onClick={onPress}\n onKeyDown={(e) => {\n if (e.key === 'Enter') onPress();\n }}\n role=\"button\"\n tabIndex={0}\n >\n {iName}\n </div>\n )\n : <div className={className} key={iValue}>{iName}</div>,\n );\n }\n\n return (\n <div className={composed.container}>\n {label ? <div className={composed.label}>{label}</div> : null}\n\n <div className={composed.options}>\n {optionNodes}\n </div>\n </div>\n );\n};\n"],"mappings":"qFAEA,OAAqB,QAAQ,KAAQ,0BAA0B,CAAC,OAK9D,eAAe,oBAGjB,qJAAwC,yDAYxC,MAAO,MAAM,OAAiC,CAAG,oBAAC,4CAMjD,CACC,eAAiB,QAAQ,CAAC,QAAQ,CAAE,YAAY,CAAE,KAAK,CAAC,CAExD,GAAI,CAAC,OAA2B,EAA5B,CAAa,QAAQ,OAAO,EAAE,KAAM,MAAK,CAAC,gBAAgB,CAAC,CAAC,qHAEhE,YAAuC,EAAE,CACzC,IAAK,YAAY,GAAI,QAAO,EAC1B,oBAAwB,eAAe,CAAC,MAAM,CAAC,CAE/C,cAAwB,QAAQ,OAAO,CACnC,YACJ,GAAI,MAAM,GAAK,KAAK,EAAE,mBAAS,CAAI,IAAI,QAAQ,SAAe,EAAvB,EAAuB,EAAE,OAC3D,GAAI,QAAQ,EACf,QAAU,KACR,QAAQ,CAAC,MAAM,CAAC,EACjB,CAFM,CAGR,CAED,WAAW,KAAK,CACd,OAAO,cAAP,YAGiB,SAAS,CAAT,SAAS,CAEX,OAAO,CAAP,OAAO,CACL,SAEV,CAFU,IACT,GAAI,CAAC,IAAI,GAAK,OAAO,EAAE,OAAO,CAAC,CAAC,EAAC,CAClC,CACI,IAAQ,CAAR,QAAQ,CACH,QAAC,CAAD,CAAC,UAEV,KAAK,EARD,MAW6C,CAAC,cAfzD,YAeoB,SAAS,CAAT,SAAS,UAAgB,KAAK,EAAd,MAAoB,CAC1D,CAAC,EACF,0KAII,QAAK,cAAL,YAAwB,SAAc,CAAd,QAAQ,MAAM,UAAG,KAAK,CAAa,CAAC,CAA5D,IAA4D,+GAE7D,4BAAgB,SAAgB,CAAhB,QAAQ,QAAQ,UAC7B,WAAW,CACT,CAAC,gIALR,6BAAgB,SAAkB,CAAlB,QAAQ,UAAU,WAC/B,EAA4D,CAE7D,EAEM,EACH,CAAC,2EANN,GAMM,EAET","ignoreList":[]}
@@ -7,5 +7,8 @@
7
7
  // like React Native, IS_CLIENT_SIDE is "true", however "document" and a bunch
8
8
  // of other browser-world features are not available.
9
9
  if(IS_CLIENT_SIDE&&typeof document!=="undefined"){// eslint-disable-next-line no-param-reassign
10
- cfg.CSRF=parseCookie(document.cookie).csrfToken;}return cfg;}export function getConfig(sync){if(!config){if(IS_CLIENT_SIDE){const inj=clientGetInj();config=inj instanceof Promise?inj.then(injection=>{const res=injectCsrfToken(injection.CONFIG??{});config=res;return res;}):injectCsrfToken(inj.CONFIG??{});}else{const weak=requireWeak("config");if(!weak)throw Error("Internal error");config=weak;}}if(sync&&config instanceof Promise){throw Error("The config is not available yet");}return config;}
10
+ cfg.CSRF=parseCookie(document.cookie).csrfToken;}return cfg;}// BEWARE: Removing generic type from this override messes up
11
+ // type resolution in the host code in some scenarios.
12
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
13
+ export function getConfig(sync){if(!config){if(IS_CLIENT_SIDE){const inj=clientGetInj();config=inj instanceof Promise?inj.then(injection=>{const res=injectCsrfToken(injection.CONFIG??{});config=res;return res;}):injectCsrfToken(inj.CONFIG??{});}else{const weak=requireWeak("config");if(!weak)throw Error("Internal error");config=weak;}}if(sync&&config instanceof Promise){throw Error("The config is not available yet");}return config;}
11
14
  //# sourceMappingURL=config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","names":[],"sources":["../../../../src/shared/utils/config.ts"],"sourcesContent":["/* global document */\n\nimport { parseCookie } from 'cookie';\n\nimport clientGetInj from '../../client/getInj';\n\nimport { IS_CLIENT_SIDE } from './isomorphy/environment-check';\nimport { requireWeak } from './webpack';\n\ntype ConfigT = Record<string, unknown>;\n\nlet config: ConfigT | Promise<ConfigT> | undefined;\n\n/**\n * Injects CSRF token into config (on client-side only).\n *\n * BEWARE: It mutates the argument, and also returns it as the result,\n * for chaining.\n */\nfunction injectCsrfToken(cfg: ConfigT): ConfigT {\n // The safeguard for \"document\" is necessary because in non-Node environments,\n // like React Native, IS_CLIENT_SIDE is \"true\", however \"document\" and a bunch\n // of other browser-world features are not available.\n if (IS_CLIENT_SIDE && typeof document !== 'undefined') {\n // eslint-disable-next-line no-param-reassign\n cfg.CSRF = parseCookie(document.cookie).csrfToken;\n }\n\n return cfg;\n}\n\nexport function getConfig(sync: true): ConfigT;\n\nexport function getConfig<T extends ConfigT>(sync?: boolean): Promise<T> | T;\n\nexport function getConfig<T extends ConfigT>(sync?: boolean): Promise<T> | T {\n if (!config) {\n if (IS_CLIENT_SIDE) {\n const inj = clientGetInj();\n config = inj instanceof Promise\n ? inj.then((injection) => {\n const res = injectCsrfToken(injection.CONFIG ?? {});\n config = res;\n return res;\n })\n : injectCsrfToken(inj.CONFIG ?? {});\n } else {\n const weak = requireWeak<ConfigT>('config');\n if (!weak) throw Error('Internal error');\n config = weak;\n }\n }\n\n if (sync && (config instanceof Promise)) {\n throw Error('The config is not available yet');\n }\n\n return config as T;\n}\n"],"mappings":"AAAA,qBAEA,OAAS,WAAW,KAAQ,QAAQ,CAAC,MAE9B,aAAY,qCAEV,cAAc,+CACd,WAAW,oBAIpB,GAAI,OAA8C,CAElD;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,gBAAe,CAAC,GAAY,CAAW,CAC9C;AACA;AACA;AACA,GAAI,cAAc,EAAI,MAAO,SAAQ,GAAK,WAAW,CAAE,CACrD;AACA,GAAG,CAAC,IAAI,CAAG,WAAW,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,SAAS,CACnD,CAEA,MAAO,IAAG,CACZ,CAMA,MAAO,SAAS,UAAS,CAAoB,IAAc,CAAkB,CAC3E,GAAI,CAAC,MAAM,CAAE,CACX,GAAI,cAAc,CAAE,CAClB,KAAM,IAAG,CAAG,YAAY,CAAC,CAAC,CAC1B,MAAM,CAAG,GAAG,WAAY,QAAO,CAC3B,GAAG,CAAC,IAAI,CAAE,SAAS,EAAK,CACxB,KAAM,IAAG,CAAG,eAAe,CAAC,SAAS,CAAC,MAAM,EAAI,CAAC,CAAC,CAAC,CACnD,MAAM,CAAG,GAAG,CACZ,MAAO,IAAG,CACZ,CAAC,CAAC,CACA,eAAe,CAAC,GAAG,CAAC,MAAM,EAAI,CAAC,CAAC,CAAC,CACvC,CAAC,IAAM,CACL,KAAM,KAAI,CAAG,WAAW,CAAU,QAAQ,CAAC,CAC3C,GAAI,CAAC,IAAI,CAAE,KAAM,MAAK,CAAC,gBAAgB,CAAC,CACxC,MAAM,CAAG,IAAI,CACf,CACF,CAEA,GAAI,IAAI,EAAK,MAAM,WAAY,QAAQ,CAAE,CACvC,KAAM,MAAK,CAAC,iCAAiC,CAAC,CAChD,CAEA,MAAO,OAAM,CACf","ignoreList":[]}
1
+ {"version":3,"file":"config.js","names":[],"sources":["../../../../src/shared/utils/config.ts"],"sourcesContent":["/* global document */\n\nimport { parseCookie } from 'cookie';\n\nimport clientGetInj from '../../client/getInj';\n\nimport { IS_CLIENT_SIDE } from './isomorphy/environment-check';\nimport { requireWeak } from './webpack';\n\ntype ConfigT = Record<string, unknown>;\n\nlet config: ConfigT | Promise<ConfigT> | undefined;\n\n/**\n * Injects CSRF token into config (on client-side only).\n *\n * BEWARE: It mutates the argument, and also returns it as the result,\n * for chaining.\n */\nfunction injectCsrfToken(cfg: ConfigT): ConfigT {\n // The safeguard for \"document\" is necessary because in non-Node environments,\n // like React Native, IS_CLIENT_SIDE is \"true\", however \"document\" and a bunch\n // of other browser-world features are not available.\n if (IS_CLIENT_SIDE && typeof document !== 'undefined') {\n // eslint-disable-next-line no-param-reassign\n cfg.CSRF = parseCookie(document.cookie).csrfToken;\n }\n\n return cfg;\n}\n\n// BEWARE: Removing generic type from this override messes up\n// type resolution in the host code in some scenarios.\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters\nexport function getConfig<T extends ConfigT>(sync: true): T;\n\nexport function getConfig<T extends ConfigT>(sync?: boolean): Promise<T> | T;\n\nexport function getConfig<T extends ConfigT>(sync?: boolean): Promise<T> | T {\n if (!config) {\n if (IS_CLIENT_SIDE) {\n const inj = clientGetInj();\n config = inj instanceof Promise\n ? inj.then((injection) => {\n const res = injectCsrfToken(injection.CONFIG ?? {});\n config = res;\n return res;\n })\n : injectCsrfToken(inj.CONFIG ?? {});\n } else {\n const weak = requireWeak<ConfigT>('config');\n if (!weak) throw Error('Internal error');\n config = weak;\n }\n }\n\n if (sync && (config instanceof Promise)) {\n throw Error('The config is not available yet');\n }\n\n return config as T;\n}\n"],"mappings":"AAAA,qBAEA,OAAS,WAAW,KAAQ,QAAQ,CAAC,MAE9B,aAAY,qCAEV,cAAc,+CACd,WAAW,oBAIpB,GAAI,OAA8C,CAElD;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,gBAAe,CAAC,GAAY,CAAW,CAC9C;AACA;AACA;AACA,GAAI,cAAc,EAAI,MAAO,SAAQ,GAAK,WAAW,CAAE,CACrD;AACA,GAAG,CAAC,IAAI,CAAG,WAAW,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,SAAS,CACnD,CAEA,MAAO,IAAG,CACZ,CAEA;AACA;AACA;AAKA,MAAO,SAAS,UAAS,CAAoB,IAAc,CAAkB,CAC3E,GAAI,CAAC,MAAM,CAAE,CACX,GAAI,cAAc,CAAE,CAClB,KAAM,IAAG,CAAG,YAAY,CAAC,CAAC,CAC1B,MAAM,CAAG,GAAG,WAAY,QAAO,CAC3B,GAAG,CAAC,IAAI,CAAE,SAAS,EAAK,CACxB,KAAM,IAAG,CAAG,eAAe,CAAC,SAAS,CAAC,MAAM,EAAI,CAAC,CAAC,CAAC,CACnD,MAAM,CAAG,GAAG,CACZ,MAAO,IAAG,CACZ,CAAC,CAAC,CACA,eAAe,CAAC,GAAG,CAAC,MAAM,EAAI,CAAC,CAAC,CAAC,CACvC,CAAC,IAAM,CACL,KAAM,KAAI,CAAG,WAAW,CAAU,QAAQ,CAAC,CAC3C,GAAI,CAAC,IAAI,CAAE,KAAM,MAAK,CAAC,gBAAgB,CAAC,CACxC,MAAM,CAAG,IAAI,CACf,CACF,CAEA,GAAI,IAAI,EAAK,MAAM,WAAY,QAAQ,CAAE,CACvC,KAAM,MAAK,CAAC,iCAAiC,CAAC,CAChD,CAEA,MAAO,OAAM,CACf","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- import _JSON$parse from"core-js-pure/features/json/parse.js";/**
1
+ import"core-js/modules/es.json.parse.js";/**
2
2
  * Jest environment for end-to-end SSR and client-side testing. It relies on
3
3
  * the standard react-utils mechanics to execute SSR of given scene, and also
4
4
  * Webpack build of the code for client-side execution, it further exposes
@@ -19,7 +19,7 @@ import _JSON$parse from"core-js-pure/features/json/parse.js";/**
19
19
  }throw Error(`Module "${module}" was not found, neither as TS, nor as JS`);}export default class E2eSsrEnv extends JsdomEnv{pragmas;ssrRequest;rootDir;testFolder;withSsr;webpackStats;/**
20
20
  * Loads Webpack config, and exposes it to the environment via global
21
21
  * webpackConfig object.
22
- */async loadWebpackConfig(){const optionsString=this.pragmas["webpack-config-options"];const options=optionsString?_JSON$parse(optionsString):{};defaults(options,{context:this.testFolder,fs:this.global.webpackOutputFs});const factoryPath=this.pragmas["webpack-config-factory"];let factory=await import(/* webpackChunkName: "not-a-valid-chunk" */path.resolve(this.rootDir,factoryPath));factory="default"in factory?factory.default:factory;this.global.webpackConfig=factory(options);const fs=this.global.webpackOutputFs;if(!options.context)throw Error("Missing context");let buildInfo=`${options.context}/.build-info`;if(fs.existsSync(buildInfo)){buildInfo=fs.readFileSync(buildInfo,"utf8");this.global.buildInfo=_JSON$parse(buildInfo);}}/**
22
+ */async loadWebpackConfig(){const optionsString=this.pragmas["webpack-config-options"];const options=optionsString?JSON.parse(optionsString):{};defaults(options,{context:this.testFolder,fs:this.global.webpackOutputFs});const factoryPath=this.pragmas["webpack-config-factory"];let factory=await import(/* webpackChunkName: "not-a-valid-chunk" */path.resolve(this.rootDir,factoryPath));factory="default"in factory?factory.default:factory;this.global.webpackConfig=factory(options);const fs=this.global.webpackOutputFs;if(!options.context)throw Error("Missing context");let buildInfo=`${options.context}/.build-info`;if(fs.existsSync(buildInfo)){buildInfo=fs.readFileSync(buildInfo,"utf8");this.global.buildInfo=JSON.parse(buildInfo);}}/**
23
23
  * Executes Webpack build.
24
24
  * @return {Promise}
25
25
  */async runWebpack(){await this.loadWebpackConfig();if(!this.global.webpackConfig)throw Error("Failed to load Webpack config");const compiler=webpack(this.global.webpackConfig);// TODO: The "as typeof compiler.outputFileSystem" piece below is
@@ -34,7 +34,7 @@ this.webpackStats=stats;done();});});}async runSsr(){// NOTE: This is a TS modul
34
34
  // on it for the forked NodeJS process, we need to resolve the correct
35
35
  // extention ourselves (as NodeJS will hit the given path, without any
36
36
  // additional resolutions / transformations).
37
- const ssrModulePath=await findModule(`${import.meta.dirname}/ssr-preload`);const cp=fork(ssrModulePath);const optionsString=this.pragmas["ssr-options"];const options=optionsString?_JSON$parse(optionsString):{};options.buildInfo??=this.global.buildInfo;if(!this.webpackStats)throw Error("Missing Webpack stats");options.chunkGroups=deduceChunkGroups(this.webpackStats);return new Promise((resolve,reject)=>{cp.on("exit",code=>{if(code)reject(Error("SSR process crashed"));});cp.on("message",message=>{this.global.ssrMarkup=message.markup;this.global.ssrOptions=options;this.global.ssrStatus=message.status;cp.kill();resolve();});if(!this.global.webpackConfig)throw Error("Missing Webpack config");cp.send({options,root:options.root==="TEST"?this.testFolder:process.cwd(),ssrRequest:this.ssrRequest,testFolder:this.testFolder,webpackConfig:this.global.webpackConfig});});}constructor(config,context){const pragmas=context.docblockPragmas;const requestString=pragmas["ssr-request"];const request=requestString?_JSON$parse(requestString):{};request.url??="/";// This ensures the initial JsDom URL matches the value we use for SSR.
37
+ const ssrModulePath=await findModule(`${import.meta.dirname}/ssr-preload`);const cp=fork(ssrModulePath);const optionsString=this.pragmas["ssr-options"];const options=optionsString?JSON.parse(optionsString):{};options.buildInfo??=this.global.buildInfo;if(!this.webpackStats)throw Error("Missing Webpack stats");options.chunkGroups=deduceChunkGroups(this.webpackStats);return new Promise((resolve,reject)=>{cp.on("exit",code=>{if(code)reject(Error("SSR process crashed"));});cp.on("message",message=>{this.global.ssrMarkup=message.markup;this.global.ssrOptions=options;this.global.ssrStatus=message.status;cp.kill();resolve();});if(!this.global.webpackConfig)throw Error("Missing Webpack config");cp.send({options,root:options.root==="TEST"?this.testFolder:process.cwd(),ssrRequest:this.ssrRequest,testFolder:this.testFolder,webpackConfig:this.global.webpackConfig});});}constructor(config,context){const pragmas=context.docblockPragmas;const requestString=pragmas["ssr-request"];const request=requestString?JSON.parse(requestString):{};request.url??="/";// This ensures the initial JsDom URL matches the value we use for SSR.
38
38
  set(config.projectConfig,"testEnvironmentOptions.url",`http://localhost${request.url}`);super(config,context);this.global.dom=this.dom;this.global.webpackOutputFs=createFsFromVolume(new Volume);// Extracts necessary settings from config and context.
39
39
  const{projectConfig}=config;this.rootDir=projectConfig.rootDir;this.testFolder=path.dirname(context.testPath);this.withSsr=!pragmas["no-ssr"];this.ssrRequest=request;this.pragmas=pragmas;// BEWARE: Anything imported prior to this register() call seems to be
40
40
  // transpiled again by Babel if loaded after this call. This causes very
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/index.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\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\n// TODO: We need to add correct typing for environment options.\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 */\n\nimport { fork } from 'node:child_process';\nimport { access } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { defaults, set } from 'lodash-es';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration, type Stats } from 'webpack';\n\nimport register, { revert } from '@babel/register';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport { deduceChunkGroups } from 'server/renderer';\n\nimport type { LaunchT, ResultT } from './ssr';\n\nasync function findModule(module: string): Promise<string> {\n try {\n const res = `${module}.ts`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n try {\n const res = `${module}.js`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n throw Error(`Module \"${module}\" was not found, neither as TS, nor as JS`);\n}\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?: Stats;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private async loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n 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\n let factory = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n path.resolve(this.rootDir, factoryPath)\n ) as (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n if (!options.context) throw Error('Missing context');\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(): Promise<void> {\n await this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n 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(): Promise<void> {\n // NOTE: This is a TS module in the source code, and it turn into JS\n // module in the distributed code, after Babel compilation. As we rely\n // on it for the forked NodeJS process, we need to resolve the correct\n // extention ourselves (as NodeJS will hit the given path, without any\n // additional resolutions / transformations).\n const ssrModulePath = await findModule(`${import.meta.dirname}/ssr-preload`);\n\n const cp = fork(ssrModulePath);\n\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n options.buildInfo ??= this.global.buildInfo;\n\n if (!this.webpackStats) throw Error('Missing Webpack stats');\n\n options.chunkGroups = deduceChunkGroups(this.webpackStats);\n\n return new Promise((resolve, reject) => {\n cp.on('exit', (code) => {\n if (code) reject(Error('SSR process crashed'));\n });\n\n cp.on('message', (message: ResultT) => {\n this.global.ssrMarkup = message.markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = message.status;\n cp.kill();\n resolve();\n });\n\n if (!this.global.webpackConfig) throw Error('Missing Webpack config');\n\n cp.send({\n options,\n root: options.root === 'TEST' ? this.testFolder : process.cwd(),\n ssrRequest: this.ssrRequest,\n testFolder: this.testFolder,\n webpackConfig: this.global.webpackConfig,\n } satisfies LaunchT);\n });\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\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\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 as string}`,\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 // BEWARE: Anything imported prior to this register() call seems to be\n // transpiled again by Babel if loaded after this call. This causes very\n // confusing errors when testing the code dependent on some sort of contexts\n // (because loading a module again effectively creates a new context object,\n // which is not recognized by the code expecting another context instance).\n // That's why below we prefer dynamic imports for some React Utils methods.\n // BEWARE: Although we also do the registration inside SSR testing code,\n // we still need it here to correctly process imported Webpack configurations\n // (which are imported directly from this module).\n register({\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // eslint-disable-next-line import/dynamic-import-chunkname\n const { setBuildInfo } = await import('../../isomorphy/buildInfo');\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n revert();\n\n await super.teardown();\n }\n}\n"],"mappings":"6DAAA;AACA;AACA;AACA;AACA;AACA,GAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA,sDAEA,OAAS,IAAI,KAAQ,oBAAoB,CACzC,OAAS,MAAM,KAAQ,kBAAkB,CACzC,MAAO,KAAI,KAAM,WAAW,CAE5B,MAAO,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AAC,KAAK,CAAE,MAAM,CAAE,KAAK,CAAE,MAAM,CAAE,MAAM,CACnD,CAAC,CAAC,CACJ,CAEA,KAAM,MAAK,EAAkB,CAC3B,KAAM,MAAK,CAAC,KAAK,CAAC,CAAC,CACnB,KAAM,KAAI,CAAC,UAAU,CAAC,CAAC,CAEvB;AACA,KAAM,CAAE,YAAa,CAAC,CAAG,KAAM,OAAM,gCAA6B,CAClE,YAAY,CAAC,SAAS,CAAE,IAAI,CAAC,CAE7B,GAAI,IAAI,CAAC,OAAO,CAAE,KAAM,KAAI,CAAC,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC,MAAM,CAAC,6BAA6B,CAAG,IAAI,CAClD,CAEA,KAAM,SAAQ,EAAkB,CAC9B,MAAO,KAAI,CAAC,MAAM,CAAC,6BAA6B,CAEhD,MAAM,CAAC,CAAC,CAER,KAAM,MAAK,CAAC,QAAQ,CAAC,CAAC,CACxB,CACF","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/index.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\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\n// TODO: We need to add correct typing for environment options.\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 */\n\nimport { fork } from 'node:child_process';\nimport { access } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { defaults, set } from 'lodash-es';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration, type Stats } from 'webpack';\n\nimport register, { revert } from '@babel/register';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport { deduceChunkGroups } from 'server/renderer';\n\nimport type { LaunchT, ResultT } from './ssr';\n\nasync function findModule(module: string): Promise<string> {\n try {\n const res = `${module}.ts`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n try {\n const res = `${module}.js`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n throw Error(`Module \"${module}\" was not found, neither as TS, nor as JS`);\n}\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?: Stats;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private async loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n 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\n let factory = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n path.resolve(this.rootDir, factoryPath)\n ) as (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n if (!options.context) throw Error('Missing context');\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(): Promise<void> {\n await this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n 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(): Promise<void> {\n // NOTE: This is a TS module in the source code, and it turn into JS\n // module in the distributed code, after Babel compilation. As we rely\n // on it for the forked NodeJS process, we need to resolve the correct\n // extention ourselves (as NodeJS will hit the given path, without any\n // additional resolutions / transformations).\n const ssrModulePath = await findModule(`${import.meta.dirname}/ssr-preload`);\n\n const cp = fork(ssrModulePath);\n\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n options.buildInfo ??= this.global.buildInfo;\n\n if (!this.webpackStats) throw Error('Missing Webpack stats');\n\n options.chunkGroups = deduceChunkGroups(this.webpackStats);\n\n return new Promise((resolve, reject) => {\n cp.on('exit', (code) => {\n if (code) reject(Error('SSR process crashed'));\n });\n\n cp.on('message', (message: ResultT) => {\n this.global.ssrMarkup = message.markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = message.status;\n cp.kill();\n resolve();\n });\n\n if (!this.global.webpackConfig) throw Error('Missing Webpack config');\n\n cp.send({\n options,\n root: options.root === 'TEST' ? this.testFolder : process.cwd(),\n ssrRequest: this.ssrRequest,\n testFolder: this.testFolder,\n webpackConfig: this.global.webpackConfig,\n } satisfies LaunchT);\n });\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\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\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 as string}`,\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 // BEWARE: Anything imported prior to this register() call seems to be\n // transpiled again by Babel if loaded after this call. This causes very\n // confusing errors when testing the code dependent on some sort of contexts\n // (because loading a module again effectively creates a new context object,\n // which is not recognized by the code expecting another context instance).\n // That's why below we prefer dynamic imports for some React Utils methods.\n // BEWARE: Although we also do the registration inside SSR testing code,\n // we still need it here to correctly process imported Webpack configurations\n // (which are imported directly from this module).\n register({\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // eslint-disable-next-line import/dynamic-import-chunkname\n const { setBuildInfo } = await import('../../isomorphy/buildInfo');\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n revert();\n\n await super.teardown();\n }\n}\n"],"mappings":"yCAAA;AACA;AACA;AACA;AACA;AACA,GAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA,sDAEA,OAAS,IAAI,KAAQ,oBAAoB,CACzC,OAAS,MAAM,KAAQ,kBAAkB,CACzC,MAAO,KAAI,KAAM,WAAW,CAE5B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EtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,CAAC,CACP,UAAU,CAAE,CAAC,KAAK,CAAE,MAAM,CAAE,KAAK,CAAE,MAAM,CAAE,MAAM,CACnD,CAAC,CAAC,CACJ,CAEA,KAAM,MAAK,EAAkB,CAC3B,KAAM,MAAK,CAAC,KAAK,CAAC,CAAC,CACnB,KAAM,KAAI,CAAC,UAAU,CAAC,CAAC,CAEvB;AACA,KAAM,CAAE,YAAa,CAAC,CAAG,KAAM,OAAM,gCAA6B,CAClE,YAAY,CAAC,SAAS,CAAE,IAAI,CAAC,CAE7B,GAAI,IAAI,CAAC,OAAO,CAAE,KAAM,KAAI,CAAC,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC,MAAM,CAAC,6BAA6B,CAAG,IAAI,CAClD,CAEA,KAAM,SAAQ,EAAkB,CAC9B,MAAO,KAAI,CAAC,MAAM,CAAC,6BAA6B,CAEhD,MAAM,CAAC,CAAC,CAER,KAAM,MAAK,CAAC,QAAQ,CAAC,CAAC,CACxB,CACF","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- import _JSON$stringify from"core-js-pure/features/json/stringify.js";/* global document *//* eslint-disable import/no-extraneous-dependencies */import mockdate from"mockdate";import{act}from"react";import{createRoot}from"react-dom/client";import{expect,jest}from"@jest/globals";import{render}from"@testing-library/react";/**
1
+ import"core-js/modules/es.json.stringify.js";/* global document *//* eslint-disable import/no-extraneous-dependencies */import mockdate from"mockdate";import{act}from"react";import{createRoot}from"react-dom/client";import{expect,jest}from"@jest/globals";import{render}from"@testing-library/react";/**
2
2
  * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)
3
3
  * from `react`.
4
4
  */export{act};export{default as getGlobal}from"./global.js";global.IS_REACT_ACT_ENVIRONMENT=true;const originalProcessVersions=process.versions;/**
@@ -13,8 +13,8 @@ import _JSON$stringify from"core-js-pure/features/json/stringify.js";/* global d
13
13
  * @return {string}
14
14
  */export function getMockUuid(seed=0){const x=seed.toString(16).padStart(32,"0");return`${x.slice(0,8)}-${x.slice(8,12)}-${x.slice(12,16)}-${x.slice(16,20)}-${x.slice(20)}`;}export function mockAxios(handlers){const axios=jest.requireActual("axios");axios.defaults.adapter=async config=>{for(const handler of handlers){const res=handler(config);if(res){return{config:config,data:null,headers:{},status:200,statusText:"OK",...res};}}// Fallback to the regular network request.
15
15
  let res;try{res=await axios({...config,adapter:["xhr","http","fetch"]});// eslint-disable-next-line no-console
16
- console.warn("Network request has not been mocked for a test.\n\nConfig:\n",config,"\n\nResult:\n",_JSON$stringify(res,null,2));}catch(e){// eslint-disable-next-line no-console
17
- console.warn("Network request has not been mocked for a test, and failed.\n\nConfig:\n",config,"\n\nError\n",_JSON$stringify(e,null,2));throw e;}return res;};return axios;}/**
16
+ console.warn("Network request has not been mocked for a test.\n\nConfig:\n",config,"\n\nResult:\n",JSON.stringify(res,null,2));}catch(e){// eslint-disable-next-line no-console
17
+ console.warn("Network request has not been mocked for a test, and failed.\n\nConfig:\n",config,"\n\nError\n",JSON.stringify(e,null,2));throw e;}return res;};return axios;}/**
18
18
  * Advances mock timers, and mock date by the specified time.
19
19
  * @param {number} time Time step [ms].
20
20
  * @returns {Promise} Wait for this to "jump after" any async code which should
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { expect, jest } from '@jest/globals';\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\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(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\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): `${string}-${string}-${string}-${string}-${string}` {\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\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\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): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => 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(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\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\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve, reject) => {\n let rejected = false;\n\n // BEWARE: The \"promise\" returned by act() does not behave as a regular\n // Promise instance:\n // 1. In case of errors its .then() method both calls its \"reject\"\n // callback (first), and then its \"resolve\" callback second.\n // 2. It errors out if a rendering error happens, and there is no\n // \"reject\" argument provided.\n void promise.then(() => {\n if (!rejected) {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n if (!res) throw Error('Missing render result');\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res);\n }\n }, (error: unknown) => {\n rejected = true;\n\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(error);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"qEAAA,qBACA,sDASA,MAAO,SAAQ,KAAM,UAAU,CAC/B,OAA4C,GAAG,KAAQ,OAAO,CAC9D,OAAoB,UAAU,KAAQ,kBAAkB,CAExD,OAAS,MAAM,CAAE,IAAI,KAAQ,eAAe,CAC5C,OAA4B,MAAM,KAAQ,wBAAwB,CAElE;AACA;AACA;AACA,GACA,OAAS,GAAG,EAAG,OAEN,OAAO,GAAI,UAAS,mBAE7B,MAAM,CAAC,wBAAwB,CAAG,IAAI,CAEtC,KAAM,wBAAuB,CAAG,OAAO,CAAC,QAAQ,CAEhD;AACA;AACA;AACA,GACA,MAAO,SAAS,eAAc,EAAS,CACrC,MAAM,CAAC,cAAc,CAAC,OAAO,CAAE,UAAU,CAAE,CAAE,KAAK,CAAE,SAAU,CAAC,CAAC,CAClE,CAEA;AACA;AACA,GACA,MAAO,SAAS,iBAAgB,EAAS,CACvC,MAA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AC,CAAC,eAAe,CAAC,CAAC,CAClE,MAAO,IAAG,CACZ","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { expect, jest } from '@jest/globals';\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\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(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\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): `${string}-${string}-${string}-${string}-${string}` {\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\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\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): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => 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(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\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\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve, reject) => {\n let rejected = false;\n\n // BEWARE: The \"promise\" returned by act() does not behave as a regular\n // Promise instance:\n // 1. In case of errors its .then() method both calls its \"reject\"\n // callback (first), and then its \"resolve\" callback second.\n // 2. It errors out if a rendering error happens, and there is no\n // \"reject\" argument provided.\n void promise.then(() => {\n if (!rejected) {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n if (!res) throw Error('Missing render result');\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res);\n }\n }, (error: unknown) => {\n rejected = true;\n\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(error);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"6CAAA,qBACA,sDASA,MAAO,SAAQ,KAA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C,CAC9C,KAAM,MAAK,CAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,UAAU,CACzC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAG,CAAC,CAAG,CAAC,GAAG,KAAK,CAAC,CAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAClE,OAAO,CAAC,GAAG,CAAC,CACd,CACF,CAAC,CAAG,KAAc,EAAK,CACrB,QAAQ,CAAG,IAAI,CAEf;AACA,MAAM,CAAC,KAAK,CAAC,CACf,CAAC,CAAC,CACJ,CAAC,CAAC,CACJ,CAEA,KAAM,MAAK,CAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,UAAU,CACzC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAG,CAAC,CAAG,CAAC,GAAG,KAAK,CAAC,CAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAClE,MAAO,IAAG,CACZ","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- import _pushInstanceProperty from"core-js-pure/features/instance/push.js";import{c as _c}from"react/compiler-runtime";/* global document */import{Suspense,lazy,useInsertionEffect}from"react";import{Barrier}from"@dr.pogodin/js-utils";import{useSsrContext}from"./globalState.js";import{IS_CLIENT_SIDE,IS_SERVER_SIDE,assertClientSide,getBuildInfo}from"./isomorphy/index.js";import{jsx as _jsx}from"react/jsx-runtime";let clientChunkGroups;export function setClientChunkGroups(groups){assertClientSide();clientChunkGroups=groups;}const refCounts=new Map;function getPublicPath(){return getBuildInfo().publicPath;}/**
1
+ import"core-js/modules/es.map.get-or-insert.js";import"core-js/modules/es.map.get-or-insert-computed.js";import"core-js/modules/esnext.iterator.chunks.js";import"core-js/modules/esnext.map.delete-all.js";import"core-js/modules/esnext.map.emplace.js";import"core-js/modules/esnext.map.every.js";import"core-js/modules/esnext.map.filter.js";import"core-js/modules/esnext.map.find.js";import"core-js/modules/esnext.map.find-key.js";import"core-js/modules/esnext.map.includes.js";import"core-js/modules/esnext.map.key-of.js";import"core-js/modules/esnext.map.map-keys.js";import"core-js/modules/esnext.map.map-values.js";import"core-js/modules/esnext.map.merge.js";import"core-js/modules/esnext.map.reduce.js";import"core-js/modules/esnext.map.some.js";import"core-js/modules/esnext.map.update.js";import"core-js/modules/esnext.set.add-all.js";import"core-js/modules/esnext.set.delete-all.js";import"core-js/modules/esnext.set.difference.js";import"core-js/modules/esnext.set.every.js";import"core-js/modules/esnext.set.filter.js";import"core-js/modules/esnext.set.find.js";import"core-js/modules/esnext.set.intersection.js";import"core-js/modules/esnext.set.is-disjoint-from.js";import"core-js/modules/esnext.set.is-subset-of.js";import"core-js/modules/esnext.set.is-superset-of.js";import"core-js/modules/esnext.set.join.js";import"core-js/modules/esnext.set.map.js";import"core-js/modules/esnext.set.reduce.js";import"core-js/modules/esnext.set.some.js";import"core-js/modules/esnext.set.symmetric-difference.js";import"core-js/modules/esnext.set.union.js";import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.map.get-or-insert.js";import"core-js/modules/es.map.get-or-insert-computed.js";import"core-js/modules/es.set.difference.v2.js";import"core-js/modules/es.set.intersection.v2.js";import"core-js/modules/es.set.is-disjoint-from.v2.js";import"core-js/modules/es.set.is-subset-of.v2.js";import"core-js/modules/es.set.is-superset-of.v2.js";import"core-js/modules/es.set.symmetric-difference.v2.js";import"core-js/modules/es.set.union.v2.js";import"core-js/modules/esnext.iterator.chunks.js";import"core-js/modules/esnext.map.delete-all.js";import"core-js/modules/esnext.map.emplace.js";import"core-js/modules/esnext.map.every.js";import"core-js/modules/esnext.map.filter.js";import"core-js/modules/esnext.map.find.js";import"core-js/modules/esnext.map.find-key.js";import"core-js/modules/esnext.map.includes.js";import"core-js/modules/esnext.map.key-of.js";import"core-js/modules/esnext.map.map-keys.js";import"core-js/modules/esnext.map.map-values.js";import"core-js/modules/esnext.map.merge.js";import"core-js/modules/esnext.map.reduce.js";import"core-js/modules/esnext.map.some.js";import"core-js/modules/esnext.map.update.js";import"core-js/modules/esnext.set.add-all.js";import"core-js/modules/esnext.set.delete-all.js";import"core-js/modules/esnext.set.difference.js";import"core-js/modules/esnext.set.every.js";import"core-js/modules/esnext.set.filter.js";import"core-js/modules/esnext.set.find.js";import"core-js/modules/esnext.set.intersection.js";import"core-js/modules/esnext.set.is-disjoint-from.js";import"core-js/modules/esnext.set.is-subset-of.js";import"core-js/modules/esnext.set.is-superset-of.js";import"core-js/modules/esnext.set.join.js";import"core-js/modules/esnext.set.map.js";import"core-js/modules/esnext.set.reduce.js";import"core-js/modules/esnext.set.some.js";import"core-js/modules/esnext.set.symmetric-difference.js";import"core-js/modules/esnext.set.union.js";import{c as _c}from"react/compiler-runtime";/* global document */import{Suspense,lazy,useInsertionEffect}from"react";import{Barrier}from"@dr.pogodin/js-utils";import{useSsrContext}from"./globalState.js";import{IS_CLIENT_SIDE,IS_SERVER_SIDE,assertClientSide,getBuildInfo}from"./isomorphy/index.js";import{jsx as _jsx}from"react/jsx-runtime";let clientChunkGroups;export function setClientChunkGroups(groups){assertClientSide();clientChunkGroups=groups;}const refCounts=new Map;function getPublicPath(){return getBuildInfo().publicPath;}/**
2
2
  * Client-side only! Ensures the specified CSS stylesheet is loaded into
3
3
  * the document; loads if it is missing; and does simple reference counting
4
4
  * to facilitate future clean-up.
@@ -17,7 +17,7 @@ import _pushInstanceProperty from"core-js-pure/features/instance/push.js";import
17
17
  * @param refCount
18
18
  * @return Resolves once all pending stylesheets, necessary for
19
19
  * the chunk, are either loaded, or failed to load.
20
- */export async function bookStyleSheets(chunkName,chunkGroups,refCount){const promises=[];const assets=chunkGroups[chunkName];if(!assets)return Promise.resolve();const loadedSheets=getLoadedStyleSheets();for(const asset of assets){if(asset.endsWith(".css")){const promise=bookStyleSheet(asset,loadedSheets,refCount);if(promise)_pushInstanceProperty(promises).call(promises,promise);}}return promises.length?Promise.allSettled(promises).then():Promise.resolve();}/**
20
+ */export async function bookStyleSheets(chunkName,chunkGroups,refCount){const promises=[];const assets=chunkGroups[chunkName];if(!assets)return Promise.resolve();const loadedSheets=getLoadedStyleSheets();for(const asset of assets){if(asset.endsWith(".css")){const promise=bookStyleSheet(asset,loadedSheets,refCount);if(promise)promises.push(promise);}}return promises.length?Promise.allSettled(promises).then():Promise.resolve();}/**
21
21
  * Client-side only! Frees from the document all CSS stylesheets that are
22
22
  * required by the specified chunk, and have reference counter equal to one
23
23
  * (for chunks with larger reference counter values, it just decrements
@@ -41,5 +41,5 @@ if(usedChunkNames.has(chunkName)// When HMR happens splitComponent() ends up get
41
41
  &&!import.meta.webpackHot){throw Error(`Repeated splitComponent() call for the chunk "${chunkName}"`);}else usedChunkNames.add(chunkName);const LazyComponent=/*#__PURE__*/lazy(async()=>{const resolved=await getComponent();const Component="default"in resolved?resolved.default:resolved;// This pre-loads necessary stylesheets prior to the first mount of
42
42
  // the component (the lazy load function is executed by React one at
43
43
  // the frist mount).
44
- if(IS_CLIENT_SIDE){if(!clientChunkGroups)throw Error("Internal error");await bookStyleSheets(chunkName,clientChunkGroups,false);}const Wrapper=t0=>{const $=_c(12);let children;let chunkGroups;let ref;let rest;if($[0]!==t0){({children,chunkGroups,ref,...rest}=t0);$[0]=t0;$[1]=children;$[2]=chunkGroups;$[3]=ref;$[4]=rest;}else{children=$[1];chunkGroups=$[2];ref=$[3];rest=$[4];}let t1;let t2;if($[5]!==chunkGroups){t1=()=>{if(!clientChunkGroups){throw Error("Internal error");}bookStyleSheets(chunkName,chunkGroups,true);return()=>{freeStyleSheets(chunkName,chunkGroups);};};t2=[chunkGroups];$[5]=chunkGroups;$[6]=t1;$[7]=t2;}else{t1=$[6];t2=$[7];}useInsertionEffect(t1,t2);const t3=rest;let t4;if($[8]!==children||$[9]!==ref||$[10]!==t3){t4=/*#__PURE__*/_jsx(Component,{...t3,ref:ref,children:children});$[8]=children;$[9]=ref;$[10]=t3;$[11]=t4;}else{t4=$[11];}return t4;};return{default:Wrapper};});const CodeSplit=t0=>{const $=_c(7);let children;let rest;if($[0]!==t0){({children,...rest}=t0);$[0]=t0;$[1]=children;$[2]=rest;}else{children=$[1];rest=$[2];}let chunkGroups;const ssrContext=useSsrContext(false);if(IS_SERVER_SIDE){if(!ssrContext){throw Error("Internal error");}({chunkGroups}=ssrContext);const{chunks}=ssrContext;if(!chunks.includes(chunkName)){_pushInstanceProperty(chunks).call(chunks,chunkName);}}else{if(!clientChunkGroups){throw Error("Missing client-side chunk groups data");}chunkGroups=clientChunkGroups;}assertChunkName(chunkName,chunkGroups);const t1=rest;let t2;if($[3]!==children||$[4]!==chunkGroups||$[5]!==t1){t2=/*#__PURE__*/_jsx(Suspense,{fallback:placeholder,children:/*#__PURE__*/_jsx(LazyComponent,{...t1,chunkGroups:chunkGroups,children:children})});$[3]=children;$[4]=chunkGroups;$[5]=t1;$[6]=t2;}else{t2=$[6];}return t2;};return CodeSplit;}
44
+ if(IS_CLIENT_SIDE){if(!clientChunkGroups)throw Error("Internal error");await bookStyleSheets(chunkName,clientChunkGroups,false);}const Wrapper=t0=>{const $=_c(12);let children;let chunkGroups;let ref;let rest;if($[0]!==t0){({children,chunkGroups,ref,...rest}=t0);$[0]=t0;$[1]=children;$[2]=chunkGroups;$[3]=ref;$[4]=rest;}else{children=$[1];chunkGroups=$[2];ref=$[3];rest=$[4];}let t1;let t2;if($[5]!==chunkGroups){t1=()=>{if(!clientChunkGroups){throw Error("Internal error");}bookStyleSheets(chunkName,chunkGroups,true);return()=>{freeStyleSheets(chunkName,chunkGroups);};};t2=[chunkGroups];$[5]=chunkGroups;$[6]=t1;$[7]=t2;}else{t1=$[6];t2=$[7];}useInsertionEffect(t1,t2);const t3=rest;let t4;if($[8]!==children||$[9]!==ref||$[10]!==t3){t4=/*#__PURE__*/_jsx(Component,{...t3,ref:ref,children:children});$[8]=children;$[9]=ref;$[10]=t3;$[11]=t4;}else{t4=$[11];}return t4;};return{default:Wrapper};});const CodeSplit=t0=>{const $=_c(7);let children;let rest;if($[0]!==t0){({children,...rest}=t0);$[0]=t0;$[1]=children;$[2]=rest;}else{children=$[1];rest=$[2];}let chunkGroups;const ssrContext=useSsrContext(false);if(IS_SERVER_SIDE){if(!ssrContext){throw Error("Internal error");}({chunkGroups}=ssrContext);const{chunks}=ssrContext;if(!chunks.includes(chunkName)){chunks.push(chunkName);}}else{if(!clientChunkGroups){throw Error("Missing client-side chunk groups data");}chunkGroups=clientChunkGroups;}assertChunkName(chunkName,chunkGroups);const t1=rest;let t2;if($[3]!==children||$[4]!==chunkGroups||$[5]!==t1){t2=/*#__PURE__*/_jsx(Suspense,{fallback:placeholder,children:/*#__PURE__*/_jsx(LazyComponent,{...t1,chunkGroups:chunkGroups,children:children})});$[3]=children;$[4]=chunkGroups;$[5]=t1;$[6]=t2;}else{t2=$[6];}return t2;};return CodeSplit;}
45
45
  //# sourceMappingURL=splitComponent.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"splitComponent.js","names":[],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, useSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n assertClientSide,\n getBuildInfo,\n} from './isomorphy';\n\nlet clientChunkGroups: ChunkGroupsT | undefined;\n\nexport function setClientChunkGroups(groups: ChunkGroupsT): void {\n assertClientSide();\n clientChunkGroups = groups;\n}\n\nconst refCounts = new Map<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', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts.get(path) ?? 0;\n refCounts.set(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 (const { href } of styleSheets) {\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 async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\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): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts.get(path);\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n const node = document.head.querySelector(`link[href=\"${path}\"]`);\n if (!node) throw Error('Missing node');\n node.remove();\n refCounts.delete(path);\n } else refCounts.set(path, pathRefCount - 1);\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\ntype GenericComponentPropsT = {\n children?: ReactNode;\n ref?: RefObject<unknown>;\n\n // NOTE: This is necessary, as without it this type (with only optional\n // fields) will be conisdered as \"weak\" by TypeScript, and it will be\n // a error to assign to it any type that does not use \"children\", or \"ref\".\n [propName: string]: unknown;\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 GenericComponentPropsT,\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)\n\n // When HMR happens splitComponent() ends up getting called again for some\n // chunks, thus we should not throw this error. Not sure, if we need to do\n // some additional handling in that case, or just not throwing is all we\n // need.\n && !import.meta.webpackHot\n ) {\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 if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT & {\n chunkGroups: ChunkGroupsT;\n }> = ({\n children,\n chunkGroups,\n ref,\n ...rest\n }) => {\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n if (!clientChunkGroups) throw Error('Internal error');\n void bookStyleSheets(chunkName, chunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, chunkGroups);\n };\n }, [chunkGroups]);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => {\n let chunkGroups: ChunkGroupsT;\n\n const ssrContext = useSsrContext(false);\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 if (!ssrContext) throw Error('Internal error');\n ({ chunkGroups } = ssrContext);\n const { chunks } = ssrContext;\n\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n } else {\n if (!clientChunkGroups) {\n throw Error('Missing client-side chunk groups data');\n }\n chunkGroups = clientChunkGroups;\n }\n\n assertChunkName(chunkName, chunkGroups);\n\n return (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n\n chunkGroups={chunkGroups}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n };\n\n return CodeSplit;\n}\n"],"mapp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K,CAAC,gBAAgB,CAAC,CAAC,CAC9C,eAAkB,UAAU,EAC7B,cAAmB,UAAU,CAE7B,GAAI,CAAC,MAAM,SAAS,CAAC,SAAS,CAAC,EAAE,4BAAM,OAAN,MAAM,CAAM,SAAS,CAAC,EAAC,MAExD,GAAI,CAAC,iBAAiB,EACpB,KAAM,MAAK,CAAC,uCAAuC,CAAC,CAAC,CAEvD,YAAc,iBAAiB,CAApB,CAGb,eAAe,CAAC,SAAS,CAAE,WAAW,CAAC,CAM7B,aAAI,CAAuC,0DAHnD,qBAAC,QAAQ,EAAW,QAAW,CAAX,WAAW,uBAC7B,KAAC,aAAa,KAER,EAA2C,CAElC,WAAW,CAAX,WAAW,UAEvB,QAAQ,CACI,CAAC,CACR,CAAC,qEATX,GASW,EAEd,CAED,MAAO,UAAS,CAClB","ignoreList":[]}
1
+ {"version":3,"file":"splitComponent.js","names":[],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, useSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n assertClientSide,\n getBuildInfo,\n} from './isomorphy';\n\nlet clientChunkGroups: ChunkGroupsT | undefined;\n\nexport function setClientChunkGroups(groups: ChunkGroupsT): void {\n assertClientSide();\n clientChunkGroups = groups;\n}\n\nconst refCounts = new Map<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', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts.get(path) ?? 0;\n refCounts.set(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 (const { href } of styleSheets) {\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 async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\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): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts.get(path);\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n const node = document.head.querySelector(`link[href=\"${path}\"]`);\n if (!node) throw Error('Missing node');\n node.remove();\n refCounts.delete(path);\n } else refCounts.set(path, pathRefCount - 1);\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\ntype GenericComponentPropsT = {\n children?: ReactNode;\n ref?: RefObject<unknown>;\n\n // NOTE: This is necessary, as without it this type (with only optional\n // fields) will be conisdered as \"weak\" by TypeScript, and it will be\n // a error to assign to it any type that does not use \"children\", or \"ref\".\n [propName: string]: unknown;\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 GenericComponentPropsT,\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)\n\n // When HMR happens splitComponent() ends up getting called again for some\n // chunks, thus we should not throw this error. Not sure, if we need to do\n // some additional handling in that case, or just not throwing is all we\n // need.\n && !import.meta.webpackHot\n ) {\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 if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT & {\n chunkGroups: ChunkGroupsT;\n }> = ({\n children,\n chunkGroups,\n ref,\n ...rest\n }) => {\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n if (!clientChunkGroups) throw Error('Internal error');\n void bookStyleSheets(chunkName, chunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, chunkGroups);\n };\n }, [chunkGroups]);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => {\n let chunkGroups: ChunkGroupsT;\n\n const ssrContext = useSsrContext(false);\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 if (!ssrContext) throw Error('Internal error');\n ({ chunkGroups } = ssrContext);\n const { chunks } = ssrContext;\n\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n } else {\n if (!clientChunkGroups) {\n throw Error('Missing client-side chunk groups data');\n }\n chunkGroups = clientChunkGroups;\n }\n\n assertChunkName(chunkName, chunkGroups);\n\n return (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n\n chunkGroups={chunkGroups}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n };\n\n return CodeSplit;\n}\n"],"mappings":"mhHAAA,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gB,CAAC,CAAC,CAC9C,eAAkB,UAAU,EAC7B,cAAmB,UAAU,CAE7B,GAAI,CAAC,MAAM,SAAS,CAAC,SAAS,CAAC,EAAE,MAAM,KAAK,CAAC,SAAS,CAAC,EAAC,MAExD,GAAI,CAAC,iBAAiB,EACpB,KAAM,MAAK,CAAC,uCAAuC,CAAC,CAAC,CAEvD,YAAc,iBAAiB,CAApB,CAGb,eAAe,CAAC,SAAS,CAAE,WAAW,CAAC,CAM7B,aAAI,CAAuC,0DAHnD,qBAAC,QAAQ,EAAW,QAAW,CAAX,WAAW,uBAC7B,KAAC,aAAa,KAER,EAA2C,CAElC,WAAW,CAAX,WAAW,UAEvB,QAAQ,CACI,CAAC,CACR,CAAC,qEATX,GASW,EAEd,CAED,MAAO,UAAS,CAClB","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- // eslint-disable-next-line import/enforce-node-protocol-usage, perfectionist/sort-imports
1
+ import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.for-each.js";// eslint-disable-next-line import/enforce-node-protocol-usage, perfectionist/sort-imports
2
2
  import{createRequire}from"module";import{IS_CLIENT_SIDE,IS_SERVER_SIDE}from"./isomorphy/index.js";let require;if(IS_SERVER_SIDE)require=createRequire(import.meta.url);/**
3
3
  * Requires the specified module without including it into the bundle during
4
4
  * Webpack build.