@dr.pogodin/react-utils 1.47.4 → 1.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/development/client/getInj.js +4 -0
- package/build/development/client/getInj.js.map +1 -1
- package/build/development/index.js +1 -1
- package/build/development/index.js.map +1 -1
- package/build/development/server/server.js +0 -1
- package/build/development/server/server.js.map +1 -1
- package/build/development/shared/components/Button/index.js +13 -9
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +8 -7
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +14 -12
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +15 -3
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/PageLayout/index.js +18 -15
- package/build/development/shared/components/PageLayout/index.js.map +1 -1
- package/build/development/shared/components/TextArea/index.js +9 -8
- package/build/development/shared/components/TextArea/index.js.map +1 -1
- package/build/development/shared/components/Throbber/index.js +15 -12
- package/build/development/shared/components/Throbber/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +6 -6
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js +6 -5
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js +13 -12
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js +11 -10
- package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/Switch/index.js +9 -9
- package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/development/shared/components/selectors/common.js.map +1 -1
- package/build/development/shared/components/selectors/index.js +1 -1
- package/build/development/shared/components/selectors/index.js.map +1 -1
- package/build/development/shared/utils/index.js +2 -5
- package/build/development/shared/utils/index.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv.js +0 -1
- package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/production/client/getInj.js +2 -2
- package/build/production/client/getInj.js.map +1 -1
- package/build/production/index.js +1 -1
- package/build/production/index.js.map +1 -1
- package/build/production/server/server.js +1 -1
- package/build/production/server/server.js.map +1 -1
- package/build/production/shared/components/Button/index.js +3 -8
- package/build/production/shared/components/Button/index.js.map +1 -1
- package/build/production/shared/components/Checkbox/index.js +1 -1
- package/build/production/shared/components/Checkbox/index.js.map +1 -1
- package/build/production/shared/components/Input/index.js +6 -6
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +3 -2
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/PageLayout/index.js +2 -2
- package/build/production/shared/components/PageLayout/index.js.map +1 -1
- package/build/production/shared/components/TextArea/index.js +4 -4
- package/build/production/shared/components/TextArea/index.js.map +1 -1
- package/build/production/shared/components/Throbber/index.js +2 -2
- package/build/production/shared/components/Throbber/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +3 -3
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js +4 -4
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js +2 -2
- package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/NativeDropdown/index.js +3 -3
- package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/Switch/index.js +1 -1
- package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/production/shared/components/selectors/common.js.map +1 -1
- package/build/production/shared/components/selectors/index.js +1 -1
- package/build/production/shared/components/selectors/index.js.map +1 -1
- package/build/production/shared/utils/index.js +1 -1
- package/build/production/shared/utils/index.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/types-code/index.d.ts +1 -1
- package/build/types-code/shared/components/Button/index.d.ts +6 -10
- package/build/types-code/shared/components/Checkbox/index.d.ts +4 -3
- package/build/types-code/shared/components/Input/index.d.ts +12 -4
- package/build/types-code/shared/components/Modal/index.d.ts +6 -3
- package/build/types-code/shared/components/PageLayout/index.d.ts +19 -4
- package/build/types-code/shared/components/TextArea/index.d.ts +4 -4
- package/build/types-code/shared/components/Throbber/index.d.ts +13 -3
- package/build/types-code/shared/components/WithTooltip/index.d.ts +18 -4
- package/build/types-code/shared/components/YouTubeVideo/index.d.ts +20 -4
- package/build/types-code/shared/components/selectors/CustomDropdown/index.d.ts +3 -2
- package/build/types-code/shared/components/selectors/NativeDropdown/index.d.ts +22 -2
- package/build/types-code/shared/components/selectors/Switch/index.d.ts +7 -6
- package/build/types-code/shared/components/selectors/common.d.ts +2 -3
- package/build/types-code/shared/components/selectors/index.d.ts +2 -2
- package/build/types-code/shared/utils/index.d.ts +2 -7
- package/build/web/client/getInj.js +3 -0
- package/build/web/client/getInj.js.map +1 -1
- package/build/web/index.js +1 -1
- package/build/web/index.js.map +1 -1
- package/build/web/server/server.js +0 -1
- package/build/web/server/server.js.map +1 -1
- package/build/web/shared/components/Button/index.js +13 -9
- package/build/web/shared/components/Button/index.js.map +1 -1
- package/build/web/shared/components/Checkbox/index.js +8 -7
- package/build/web/shared/components/Checkbox/index.js.map +1 -1
- package/build/web/shared/components/Input/index.js +14 -12
- package/build/web/shared/components/Input/index.js.map +1 -1
- package/build/web/shared/components/Modal/index.js +15 -3
- package/build/web/shared/components/Modal/index.js.map +1 -1
- package/build/web/shared/components/PageLayout/index.js +18 -15
- package/build/web/shared/components/PageLayout/index.js.map +1 -1
- package/build/web/shared/components/TextArea/index.js +9 -8
- package/build/web/shared/components/TextArea/index.js.map +1 -1
- package/build/web/shared/components/Throbber/index.js +15 -12
- package/build/web/shared/components/Throbber/index.js.map +1 -1
- package/build/web/shared/components/WithTooltip/index.js +6 -6
- package/build/web/shared/components/WithTooltip/index.js.map +1 -1
- package/build/web/shared/components/YouTubeVideo/index.js +6 -5
- package/build/web/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js +13 -12
- package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/NativeDropdown/index.js +11 -10
- package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/Switch/index.js +9 -9
- package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/web/shared/components/selectors/common.js.map +1 -1
- package/build/web/shared/components/selectors/index.js +1 -1
- package/build/web/shared/components/selectors/index.js.map +1 -1
- package/build/web/shared/utils/index.js +2 -5
- package/build/web/shared/utils/index.js.map +1 -1
- package/build/web/shared/utils/jest/E2eSsrEnv.js +0 -1
- package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/config/babel/webpack.js +1 -1
- package/package.json +15 -15
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["
|
|
1
|
+
{"version":3,"file":"index.js","names":["useTheme","optionValueName","defaultTheme","jsx","_jsx","jsxs","_jsxs","Switch","label","onChange","options","theme","value","composed","option","Error","optionNodes","iValue","iName","className","onPress","selected","push","onClick","onKeyDown","e","key","role","tabIndex","children","container"],"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":";AAEA,SAAqBA,QAAQ,QAAQ,0BAA0B;AAAA,SAK7DC,eAAe;AAAA,MAAAC,YAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;AAAA;AAGuB,SAAAC,GAAA,IAAAC,IAAA,EAAAC,IAAA,IAAAC,KAAA;AAYxC,OAAO,MAAMC,MAAiC,GAAGA,CAAC;EAChDC,KAAK;EACLC,QAAQ;EACRC,OAAO;EACPC,KAAK;EACLC;AACF,CAAC,KAAK;EACJ,MAAMC,QAAQ,GAAGb,QAAQ,CAAC,QAAQ,EAAEE,YAAY,EAAES,KAAK,CAAC;EAExD,IAAI,CAACD,OAAO,IAAI,CAACG,QAAQ,CAACC,MAAM,EAAE,MAAMC,KAAK,CAAC,gBAAgB,CAAC;EAE/D,MAAMC,WAA8B,GAAG,EAAE;EACzC,KAAK,MAAMF,MAAM,IAAIJ,OAAO,EAAE;IAC5B,MAAM,CAACO,MAAM,EAAEC,KAAK,CAAC,GAAGjB,eAAe,CAACa,MAAM,CAAC;IAE/C,IAAIK,SAAiB,GAAGN,QAAQ,CAACC,MAAM;IACvC,IAAIM,OAAiC;IACrC,IAAIH,MAAM,KAAKL,KAAK,EAAEO,SAAS,IAAI,IAAIN,QAAQ,CAACQ,QAAQ,EAAE,CAAC,KACtD,IAAIZ,QAAQ,EAAE;MACjBW,OAAO,GAAGA,CAAA,KAAM;QACdX,QAAQ,CAACQ,MAAM,CAAC;MAClB,CAAC;IACH;IAEAD,WAAW,CAACM,IAAI,CACdF,OAAO,gBAEHhB,IAAA;MACEe,SAAS,EAAEA,SAAU;MAErBI,OAAO,EAAEH,OAAQ;MACjBI,SAAS,EAAGC,CAAC,IAAK;QAChB,IAAIA,CAAC,CAACC,GAAG,KAAK,OAAO,EAAEN,OAAO,CAAC,CAAC;MAClC,CAAE;MACFO,IAAI,EAAC,QAAQ;MACbC,QAAQ,EAAE,CAAE;MAAAC,QAAA,EAEXX;IAAK,GARDD,MASF,CAAC,gBAENb,IAAA;MAAKe,SAAS,EAAEA,SAAU;MAAAU,QAAA,EAAeX;IAAK,GAAdD,MAAoB,CAC1D,CAAC;EACH;EAEA,oBACEX,KAAA;IAAKa,SAAS,EAAEN,QAAQ,CAACiB,SAAU;IAAAD,QAAA,GAChCrB,KAAK,gBAAGJ,IAAA;MAAKe,SAAS,EAAEN,QAAQ,CAACL,KAAM;MAAAqB,QAAA,EAAErB;IAAK,CAAM,CAAC,GAAG,IAAI,eAE7DJ,IAAA;MAAKe,SAAS,EAAEN,QAAQ,CAACH,OAAQ;MAAAmB,QAAA,EAC9Bb;IAAW,CACT,CAAC;EAAA,CACH,CAAC;AAEV,CAAC","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common.js","names":["isValue","x","type","optionValueName","option","value","name"],"sources":["../../../../../src/shared/components/selectors/common.ts"],"sourcesContent":["// The stuff common between different dropdown implementations.\n\nimport type { Theme } from '@dr.pogodin/react-themes';\n\
|
|
1
|
+
{"version":3,"file":"common.js","names":["isValue","x","type","optionValueName","option","value","name"],"sources":["../../../../../src/shared/components/selectors/common.ts"],"sourcesContent":["// The stuff common between different dropdown implementations.\n\nimport type { Theme } from '@dr.pogodin/react-themes';\n\nexport type ThemeT = Theme<\n | 'active'\n | 'arrow'\n | 'container'\n | 'dropdown'\n | 'hiddenOption'\n | 'label'\n | 'option'\n | 'select'\n\n // TODO: This is currently only valid for (native) <Dropdown>,\n // other kinds of selectors should be evaluated, and aligned with this\n // feature, if appropriate.\n | 'invalid'\n\n // TODO: This is only valid for <CustomDropdown>, thus we need to re-factor it\n // into a separate theme spec for that component.\n | 'upward'\n>;\n\nexport type ValueT = number | string;\n\nexport type OptionT<NameT> = {\n name?: NameT | null;\n value: ValueT;\n};\n\nexport type OptionsT<NameT> = Readonly<Array<OptionT<NameT> | ValueT>>;\n\nexport type PropsT<\n NameT,\n OnChangeT = React.ChangeEventHandler<HTMLSelectElement>,\n> = {\n filter?: (item: OptionT<NameT> | ValueT) => boolean;\n label?: React.ReactNode;\n onChange?: OnChangeT;\n options: Readonly<OptionsT<NameT>>;\n testId?: string;\n theme: ThemeT;\n value?: ValueT;\n};\n\nfunction isValue<T>(x: OptionT<T> | ValueT): x is ValueT {\n const type = typeof x;\n return type === 'number' || type === 'string';\n}\n\n/** Returns option value and name as a tuple. */\nexport function optionValueName<NameT>(\n option: OptionT<NameT> | ValueT,\n): [ValueT, NameT | ValueT] {\n return isValue(option)\n ? [option, option]\n : [option.value, option.name ?? option.value];\n}\n"],"mappings":"AAAA;;AA8CA,SAASA,OAAOA,CAAIC,CAAsB,EAAe;EACvD,MAAMC,IAAI,GAAG,OAAOD,CAAC;EACrB,OAAOC,IAAI,KAAK,QAAQ,IAAIA,IAAI,KAAK,QAAQ;AAC/C;;AAEA;AACA,OAAO,SAASC,eAAeA,CAC7BC,MAA+B,EACL;EAC1B,OAAOJ,OAAO,CAACI,MAAM,CAAC,GAClB,CAACA,MAAM,EAAEA,MAAM,CAAC,GAChB,CAACA,MAAM,CAACC,KAAK,EAAED,MAAM,CAACE,IAAI,IAAIF,MAAM,CAACC,KAAK,CAAC;AACjD","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { default as CustomDropdown } from "./CustomDropdown/index.js";
|
|
2
2
|
export { default as Dropdown } from "./NativeDropdown/index.js";
|
|
3
|
-
export {
|
|
3
|
+
export { Switch } from "./Switch/index.js";
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["default","CustomDropdown","Dropdown","Switch"],"sources":["../../../../../src/shared/components/selectors/index.ts"],"sourcesContent":["export { default as CustomDropdown } from './CustomDropdown';\nexport { default as Dropdown } from './NativeDropdown';\nexport {
|
|
1
|
+
{"version":3,"file":"index.js","names":["default","CustomDropdown","Dropdown","Switch"],"sources":["../../../../../src/shared/components/selectors/index.ts"],"sourcesContent":["export { default as CustomDropdown } from './CustomDropdown';\nexport { default as Dropdown } from './NativeDropdown';\nexport { Switch } from './Switch';\n\nexport type { OptionT, OptionsT } from './common';\n"],"mappings":"SAASA,OAAO,IAAIC,cAAc;AAAA,SACzBD,OAAO,IAAIE,QAAQ;AAAA,SACnBC,MAAM","ignoreList":[]}
|
|
@@ -1,13 +1,10 @@
|
|
|
1
|
-
import themedImpl, { COMPOSE, PRIORITY, ThemeProvider } from '@dr.pogodin/react-themes';
|
|
2
1
|
import { getConfig } from "./config.js";
|
|
3
2
|
import * as isomorphy from "./isomorphy/index.js";
|
|
4
3
|
import time from "./time.js";
|
|
5
4
|
import * as webpack from "./webpack.js";
|
|
6
5
|
export { assertEmptyObject, Barrier, Cached, Emitter, Semaphore, withRetries } from '@dr.pogodin/js-utils';
|
|
6
|
+
export { COMPOSE as THEME_COMPOSE, PRIORITY as THEME_PRIORITY, ThemeProvider, useTheme } from '@dr.pogodin/react-themes';
|
|
7
7
|
export { getSsrContext } from "./globalState.js";
|
|
8
8
|
export { default as splitComponent } from "./splitComponent.js";
|
|
9
|
-
|
|
10
|
-
themed.COMPOSE = COMPOSE;
|
|
11
|
-
themed.PRIORITY = PRIORITY;
|
|
12
|
-
export { getConfig, isomorphy, themed, ThemeProvider, time, webpack };
|
|
9
|
+
export { getConfig, isomorphy, time, webpack };
|
|
13
10
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["
|
|
1
|
+
{"version":3,"file":"index.js","names":["getConfig","isomorphy","time","webpack","assertEmptyObject","Barrier","Cached","Emitter","Semaphore","withRetries","COMPOSE","THEME_COMPOSE","PRIORITY","THEME_PRIORITY","ThemeProvider","useTheme","getSsrContext","default","splitComponent"],"sources":["../../../../src/shared/utils/index.ts"],"sourcesContent":["import { getConfig } from './config';\nimport * as isomorphy from './isomorphy';\nimport time from './time';\nimport * as webpack from './webpack';\n\nexport {\n assertEmptyObject,\n type Listener,\n type ObjectKey,\n Barrier,\n Cached,\n Emitter,\n Semaphore,\n withRetries,\n} from '@dr.pogodin/js-utils';\n\nexport {\n COMPOSE as THEME_COMPOSE,\n PRIORITY as THEME_PRIORITY,\n type Theme,\n ThemeProvider,\n useTheme,\n} from '@dr.pogodin/react-themes';\n\nexport { getSsrContext } from './globalState';\nexport { default as splitComponent } from './splitComponent';\n\nexport {\n getConfig,\n isomorphy,\n time,\n webpack,\n};\n"],"mappings":"SAASA,SAAS;AAAA,OACX,KAAKC,SAAS;AAAA,OACdC,IAAI;AAAA,OACJ,KAAKC,OAAO;AAEnB,SACEC,iBAAiB,EAGjBC,OAAO,EACPC,MAAM,EACNC,OAAO,EACPC,SAAS,EACTC,WAAW,QACN,sBAAsB;AAE7B,SACEC,OAAO,IAAIC,aAAa,EACxBC,QAAQ,IAAIC,cAAc,EAE1BC,aAAa,EACbC,QAAQ,QACH,0BAA0B;AAAA,SAExBC,aAAa;AAAA,SACbC,OAAO,IAAIC,cAAc;AAElC,SACElB,SAAS,EACTC,SAAS,EACTC,IAAI,EACJC,OAAO","ignoreList":[]}
|
|
@@ -66,7 +66,6 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
66
66
|
await this.loadWebpackConfig();
|
|
67
67
|
if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');
|
|
68
68
|
const compiler = webpack(this.global.webpackConfig);
|
|
69
|
-
if (!compiler) throw Error('Failed to construct Webpack compiler');
|
|
70
69
|
|
|
71
70
|
// TODO: The "as typeof compiler.outputFileSystem" piece below is
|
|
72
71
|
// a workaround for the Webpack regression:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"E2eSsrEnv.js","names":["path","defaults","set","register","JsdomEnv","Volume","createFsFromVolume","webpack","noop","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","Error","compiler","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","logger","debug","info","log","warn","cleanup","entry","p","module","exportName","entryExportName","Application","ssrFactory","renderer","status","markup","ssrRequest","cookie","send","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","dirname","testPath","withSsr","root","process","cwd","envName","babelEnv","extensions","setup","require","cache","setBuildInfo","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","forEach","key","revert"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\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\nimport path from 'node:path';\n\nimport type { Request, Response } from 'express';\n\nimport { defaults, set } from 'lodash-es';\n\nimport type { ReactNode } from 'react';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register/experimental-worker';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration } from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nfunction noop() {\n // NOOP\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?: webpack.StatsCompilation;\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 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 if (!compiler) throw Error('Failed to construct Webpack compiler');\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 const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n options.logger ??= {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n\n options.buildInfo ??= this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry as string);\n const module = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n p\n ) as NodeJS.Module;\n\n if ('cleanup' in module) cleanup = module.cleanup as () => void;\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n }\n }\n\n const { default: ssrFactory } = await import(/* webpackChunkName: \"not-a-valid-chunk\" */ 'server/renderer');\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url 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 // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n let root;\n switch (options.root) {\n case 'TEST':\n root = this.testFolder;\n break;\n default: root = process.cwd();\n }\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 register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // NOTE: It is possible that the Webpack run above, and the SSR run below\n // load different versions of the same module (CommonJS, and ES), and it may\n // cause very confusing problems (e.g. see:\n // https://github.com/birdofpreyru/react-utils/issues/413).\n // It seems we can't reset the cache of ES modules, and Jest's module reset\n // does not reset modules loaded in this enviroment module, and also only\n // replacing entire cache object by and empty {} seems to help (in contrast\n // to deleting all entries by their keys, as it is done within .teardown()\n // method below). Thus, for now we do this as a hotfix, and we also reset\n // build info to undefined, because ES module version not beeing reset\n // triggers an error on the subsequent test using the environment.\n // TODO: Look for a cleaner solution.\n require.cache = {};\n\n const { setBuildInfo } = await import(/* webpackChunkName: \"not-a-valid-chunk\" */'../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 // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n await super.teardown();\n }\n}\n"],"mappings":";;;AAAA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA,OAAOA,IAAI,MAAM,WAAW;AAI5B,SAASC,QAAQ,EAAEC,GAAG,QAAQ,WAAW;AAIzC;AACA;AACA;AACA,OAAOC,QAAQ,MAAM,qCAAqC;AAE1D,OAAOC,QAAQ,MAAM,wBAAwB;AAC7C,SAASC,MAAM,EAAEC,kBAAkB,QAAQ,OAAO;AAClD,OAAOC,O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AACO,OAAO,CAAEC,GAAG,IAAK;MAC1C,OAAOT,OAAO,CAACC,KAAK,CAACQ,GAAG,CAAC;IAC3B,CAAC,CAAC;IACFjG,QAAQ,CAACkG,MAAM,CAAC,CAAC;IACjB,MAAM,KAAK,CAACL,QAAQ,CAAC,CAAC;EACxB;AACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"E2eSsrEnv.js","names":["path","defaults","set","register","JsdomEnv","Volume","createFsFromVolume","webpack","noop","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","Error","compiler","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","logger","debug","info","log","warn","cleanup","entry","p","module","exportName","entryExportName","Application","ssrFactory","renderer","status","markup","ssrRequest","cookie","send","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","dirname","testPath","withSsr","root","process","cwd","envName","babelEnv","extensions","setup","require","cache","setBuildInfo","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","forEach","key","revert"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\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\nimport path from 'node:path';\n\nimport type { Request, Response } from 'express';\n\nimport { defaults, set } from 'lodash-es';\n\nimport type { ReactNode } from 'react';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register/experimental-worker';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration } from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nfunction noop() {\n // NOOP\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?: webpack.StatsCompilation;\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 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 const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n options.logger ??= {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n\n options.buildInfo ??= this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry as string);\n const module = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n p\n ) as NodeJS.Module;\n\n if ('cleanup' in module) cleanup = module.cleanup as () => void;\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n }\n }\n\n const { default: ssrFactory } = await import(/* webpackChunkName: \"not-a-valid-chunk\" */ 'server/renderer');\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url 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 // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n let root;\n switch (options.root) {\n case 'TEST':\n root = this.testFolder;\n break;\n default: root = process.cwd();\n }\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 register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // NOTE: It is possible that the Webpack run above, and the SSR run below\n // load different versions of the same module (CommonJS, and ES), and it may\n // cause very confusing problems (e.g. see:\n // https://github.com/birdofpreyru/react-utils/issues/413).\n // It seems we can't reset the cache of ES modules, and Jest's module reset\n // does not reset modules loaded in this enviroment module, and also only\n // replacing entire cache object by and empty {} seems to help (in contrast\n // to deleting all entries by their keys, as it is done within .teardown()\n // method below). Thus, for now we do this as a hotfix, and we also reset\n // build info to undefined, because ES module version not beeing reset\n // triggers an error on the subsequent test using the environment.\n // TODO: Look for a cleaner solution.\n require.cache = {};\n\n const { setBuildInfo } = await import(/* webpackChunkName: \"not-a-valid-chunk\" */'../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 // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n await super.teardown();\n }\n}\n"],"mappings":";;;AAAA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA,OAAOA,IAAI,MAAM,WAAW;AAI5B,SAASC,QAAQ,EAAEC,GAAG,QAAQ,WAAW;AAIzC;AACA;AACA;AACA,OAAOC,QAAQ,MAAM,qCAAqC;AAE1D,OAAOC,QAAQ,MAAM,wBAAwB;AAC7C,SAASC,MAAM,EAAEC,kBAAkB,QAAQ,OAAO;AAClD,OAAOC,OAAO,MAA8B,SAAS;AACrD;;AAOA,SAASC,IAAIA,CAAA,EAAG;EACd;AAAA;AAGF,eAAe,MAAMC,SAAS,SAASL,QAAQ,CAAC;EAa9C;AACF;AACA;AACA;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oreList":[]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import"core-js/modules/es.array-buffer.detached.js";import"core-js/modules/es.array-buffer.transfer.js";import"core-js/modules/es.array-buffer.transfer-to-fixed-length.js";import"core-js/modules/es.typed-array.to-reversed.js";import"core-js/modules/es.typed-array.to-sorted.js";import"core-js/modules/es.typed-array.with.js";import"core-js/modules/web.dom-exception.stack.js";// Encapsulates retrieval of server-side data injection into HTML template.
|
|
2
|
-
/* global document */import{getBuildInfo}from"../shared/utils/isomorphy/buildInfo.js";let inj;export default function getInj(){inj??=(async()=>{const metaElement=typeof document==="undefined"?null:document.querySelector("meta[itemprop=\"drpruinj\"]");if(metaElement){metaElement.remove();// NOTE: Since 2025 there is Uint8Array.fromBase64(), which should be
|
|
2
|
+
/* global document */import{SEC_MS,timer}from"@dr.pogodin/js-utils";import{getBuildInfo}from"../shared/utils/isomorphy/buildInfo.js";let inj;export default function getInj(){inj??=(async()=>{const metaElement=typeof document==="undefined"?null:document.querySelector("meta[itemprop=\"drpruinj\"]");if(metaElement){metaElement.remove();// NOTE: Since 2025 there is Uint8Array.fromBase64(), which should be
|
|
3
3
|
// preferred, but it is not supported by older environments yet.
|
|
4
|
-
const data=atob(metaElement.content);if(!window.isSecureContext){if(window.location.protocol==="https:"){throw Error("Loaded via HTTPS, but it is not considered a secure context")}else if(window.location.protocol!=="http:"){throw Error("Unexpected protocol")}const target=window.location.href.replace(/^http:/,"https:");window.location.replace(target)}const{key}=getBuildInfo();const code=x=>x.charCodeAt(0);const dataBuffer=Uint8Array.from(data.slice(16),code);const ivBuffer=Uint8Array.from(data.slice(0,16),code);const keyBuffer=Uint8Array.from(atob(key),code);const cKey=await window.crypto.subtle.importKey("raw",keyBuffer,{name:"AES-CBC"},false,["decrypt"]);const buffer=await window.crypto.subtle.decrypt({iv:ivBuffer,name:"AES-CBC"},cKey,dataBuffer);const decoder=new TextDecoder;// eslint-disable-next-line no-eval
|
|
4
|
+
const data=atob(metaElement.content);if(!window.isSecureContext){if(window.location.protocol==="https:"){throw Error("Loaded via HTTPS, but it is not considered a secure context")}else if(window.location.protocol!=="http:"){throw Error("Unexpected protocol")}const target=window.location.href.replace(/^http:/,"https:");window.location.replace(target);await timer(3*SEC_MS);throw Error("Failed to move into secure context")}const{key}=getBuildInfo();const code=x=>x.charCodeAt(0);const dataBuffer=Uint8Array.from(data.slice(16),code);const ivBuffer=Uint8Array.from(data.slice(0,16),code);const keyBuffer=Uint8Array.from(atob(key),code);const cKey=await window.crypto.subtle.importKey("raw",keyBuffer,{name:"AES-CBC"},false,["decrypt"]);const buffer=await window.crypto.subtle.decrypt({iv:ivBuffer,name:"AES-CBC"},cKey,dataBuffer);const decoder=new TextDecoder;// eslint-disable-next-line no-eval
|
|
5
5
|
const res=eval(`(${decoder.decode(buffer)})`);// NOTE: This is important, to be able to return the injection
|
|
6
6
|
// synchronously once it is initialized.
|
|
7
7
|
inj=res;return res}else if(typeof window!=="undefined"&&window.REACT_UTILS_INJECTION){const res=window.REACT_UTILS_INJECTION;delete window.REACT_UTILS_INJECTION;return res}// Otherwise, a bunch of dependent stuff will easily fail in non-standard
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getInj.js","names":["getBuildInfo","inj","getInj","metaElement","document","querySelector","remove","data","atob","content","window","isSecureContext","location","protocol","Error","target","href","replace","key","code","x","charCodeAt","dataBuffer","Uint8Array","from","slice","ivBuffer","keyBuffer","cKey","crypto","subtle","importKey","name","buffer","decrypt","iv","decoder","TextDecoder","res","eval","decode","REACT_UTILS_INJECTION"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nlet inj: InjT | Promise<InjT> | undefined;\n\nexport default function getInj(): InjT | Promise<InjT> {\n inj ??= (async () => {\n const metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\n if (metaElement) {\n metaElement.remove();\n\n // NOTE: Since 2025 there is Uint8Array.fromBase64(), which should be\n // preferred, but it is not supported by older environments yet.\n const data = atob(metaElement.content);\n\n if (!window.isSecureContext) {\n if (window.location.protocol === 'https:') {\n throw Error('Loaded via HTTPS, but it is not considered a secure context');\n } else if (window.location.protocol !== 'http:') {\n throw Error('Unexpected protocol');\n }\n\n const target = window.location.href.replace(/^http:/, 'https:');\n window.location.replace(target);\n }\n\n const { key } = getBuildInfo();\n\n const code = (x: string) => x.charCodeAt(0);\n const dataBuffer = Uint8Array.from(data.slice(16), code);\n const ivBuffer = Uint8Array.from(data.slice(0, 16), code);\n const keyBuffer = Uint8Array.from(atob(key), code);\n\n const cKey = await window.crypto.subtle.importKey(\n 'raw',\n keyBuffer,\n { name: 'AES-CBC' },\n false,\n ['decrypt'],\n );\n\n const buffer = await window.crypto.subtle.decrypt({\n iv: ivBuffer,\n name: 'AES-CBC',\n }, cKey, dataBuffer);\n\n const decoder = new TextDecoder();\n\n // eslint-disable-next-line no-eval\n const res = eval(`(${decoder.decode(buffer)})`) as InjT;\n\n // NOTE: This is important, to be able to return the injection\n // synchronously once it is initialized.\n inj = res;\n\n return res;\n } else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n const res = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n return res;\n }\n\n // Otherwise, a bunch of dependent stuff will easily fail in non-standard\n // environments, where no client-side initialization is performed. Like tests,\n // Docusaurus examples, etc.\n return {};\n })();\n\n return inj;\n}\n"],"mappings":"wXAAA;AAEA,
|
|
1
|
+
{"version":3,"file":"getInj.js","names":["SEC_MS","timer","getBuildInfo","inj","getInj","metaElement","document","querySelector","remove","data","atob","content","window","isSecureContext","location","protocol","Error","target","href","replace","key","code","x","charCodeAt","dataBuffer","Uint8Array","from","slice","ivBuffer","keyBuffer","cKey","crypto","subtle","importKey","name","buffer","decrypt","iv","decoder","TextDecoder","res","eval","decode","REACT_UTILS_INJECTION"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\nimport { SEC_MS, timer } from '@dr.pogodin/js-utils';\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nlet inj: InjT | Promise<InjT> | undefined;\n\nexport default function getInj(): InjT | Promise<InjT> {\n inj ??= (async () => {\n const metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\n if (metaElement) {\n metaElement.remove();\n\n // NOTE: Since 2025 there is Uint8Array.fromBase64(), which should be\n // preferred, but it is not supported by older environments yet.\n const data = atob(metaElement.content);\n\n if (!window.isSecureContext) {\n if (window.location.protocol === 'https:') {\n throw Error('Loaded via HTTPS, but it is not considered a secure context');\n } else if (window.location.protocol !== 'http:') {\n throw Error('Unexpected protocol');\n }\n\n const target = window.location.href.replace(/^http:/, 'https:');\n window.location.replace(target);\n\n await timer(3 * SEC_MS);\n throw Error('Failed to move into secure context');\n }\n\n const { key } = getBuildInfo();\n\n const code = (x: string) => x.charCodeAt(0);\n const dataBuffer = Uint8Array.from(data.slice(16), code);\n const ivBuffer = Uint8Array.from(data.slice(0, 16), code);\n const keyBuffer = Uint8Array.from(atob(key), code);\n\n const cKey = await window.crypto.subtle.importKey(\n 'raw',\n keyBuffer,\n { name: 'AES-CBC' },\n false,\n ['decrypt'],\n );\n\n const buffer = await window.crypto.subtle.decrypt({\n iv: ivBuffer,\n name: 'AES-CBC',\n }, cKey, dataBuffer);\n\n const decoder = new TextDecoder();\n\n // eslint-disable-next-line no-eval\n const res = eval(`(${decoder.decode(buffer)})`) as InjT;\n\n // NOTE: This is important, to be able to return the injection\n // synchronously once it is initialized.\n inj = res;\n\n return res;\n } else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n const res = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n return res;\n }\n\n // Otherwise, a bunch of dependent stuff will easily fail in non-standard\n // environments, where no client-side initialization is performed. Like tests,\n // Docusaurus examples, etc.\n return {};\n })();\n\n return inj;\n}\n"],"mappings":"wXAAA;AAEA,qBAEA,OAASA,MAAM,CAAEC,KAAK,KAAQ,sBAAsB,QAI3CC,YAAY,8CAErB,GAAI,CAAAC,GAAqC,CAEzC,cAAe,SAAS,CAAAC,MAAMA,CAAA,CAAyB,CACrDD,GAAG,GAAK,CAAC,SAAY,CACnB,KAAM,CAAAE,WAAmC,CAAG,MAAO,CAAAC,QAAQ,GAAK,WAAW,CACvE,IAAI,CAAGA,QAAQ,CAACC,aAAa,CAAC,6BAA2B,CAAC,CAE9D,GAAIF,WAAW,CAAE,CACfA,WAAW,CAACG,MAAM,CAAC,CAAC,CAEpB;AACA;AACA,KAAM,CAAAC,IAAI,CAAGC,IAAI,CAACL,WAAW,CAACM,OAAO,CAAC,CAEtC,GAAI,CAACC,MAAM,CAACC,eAAe,CAAE,CAC3B,GAAID,MAAM,CAACE,QAAQ,CAACC,QAAQ,GAAK,QAAQ,CAAE,CACzC,KAAM,CAAAC,KAAK,CAAC,6DAA6D,CAC3E,CAAC,IAAM,IAAIJ,MAAM,CAACE,QAAQ,CAACC,QAAQ,GAAK,OAAO,CAAE,CAC/C,KAAM,CAAAC,KAAK,CAAC,qBAAqB,CACnC,CAEA,KAAM,CAAAC,MAAM,CAAGL,MAAM,CAACE,QAAQ,CAACI,IAAI,CAACC,OAAO,CAAC,QAAQ,CAAE,QAAQ,CAAC,CAC/DP,MAAM,CAACE,QAAQ,CAACK,OAAO,CAACF,MAAM,CAAC,CAE/B,KAAM,CAAAhB,KAAK,CAAC,CAAC,CAAGD,MAAM,CAAC,CACvB,KAAM,CAAAgB,KAAK,CAAC,oCAAoC,CAClD,CAEA,KAAM,CAAEI,GAAI,CAAC,CAAGlB,YAAY,CAAC,CAAC,CAE9B,KAAM,CAAAmB,IAAI,CAAIC,CAAS,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,CAAC,EAAE,CAAC,CAEJ,MAAO,CAAArC,GACT","ignoreList":[]}
|
|
@@ -2,5 +2,5 @@
|
|
|
2
2
|
// being loaded into environment by mistake (e.g. because of different
|
|
3
3
|
// packages pinning down different exact versions of the lib, thus preventing
|
|
4
4
|
// a proper dedupe and using a single common library version).
|
|
5
|
-
if(global.REACT_UTILS_LIBRARY_LOADED){throw Error("React utils library is already loaded")}else global.REACT_UTILS_LIBRARY_LOADED=true;export{getGlobalState,GlobalStateProvider,newAsyncDataEnvelope,useAsyncCollection,useAsyncData,useGlobalState,withGlobalStateType}from"@dr.pogodin/react-global-state";export*from"./shared/components/index.js";export{assertEmptyObject,Barrier,Cached,Emitter,getConfig,isomorphy,getSsrContext,Semaphore,splitComponent,
|
|
5
|
+
if(global.REACT_UTILS_LIBRARY_LOADED){throw Error("React utils library is already loaded")}else global.REACT_UTILS_LIBRARY_LOADED=true;export{getGlobalState,GlobalStateProvider,newAsyncDataEnvelope,useAsyncCollection,useAsyncData,useGlobalState,withGlobalStateType}from"@dr.pogodin/react-global-state";export*from"./shared/components/index.js";export{assertEmptyObject,Barrier,Cached,Emitter,getConfig,isomorphy,getSsrContext,Semaphore,splitComponent,THEME_COMPOSE,THEME_PRIORITY,ThemeProvider,time,useTheme,webpack,withRetries}from"./shared/utils/index.js";
|
|
6
6
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["global","REACT_UTILS_LIBRARY_LOADED","Error","getGlobalState","GlobalStateProvider","newAsyncDataEnvelope","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType","assertEmptyObject","Barrier","Cached","Emitter","getConfig","isomorphy","getSsrContext","Semaphore","splitComponent","
|
|
1
|
+
{"version":3,"file":"index.js","names":["global","REACT_UTILS_LIBRARY_LOADED","Error","getGlobalState","GlobalStateProvider","newAsyncDataEnvelope","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType","assertEmptyObject","Barrier","Cached","Emitter","getConfig","isomorphy","getSsrContext","Semaphore","splitComponent","THEME_COMPOSE","THEME_PRIORITY","ThemeProvider","time","useTheme","webpack","withRetries"],"sources":["../../src/index.ts"],"sourcesContent":["// It is a safeguard against multiple instances / versions of the library\n// being loaded into environment by mistake (e.g. because of different\n// packages pinning down different exact versions of the lib, thus preventing\n// a proper dedupe and using a single common library version).\nif (global.REACT_UTILS_LIBRARY_LOADED) {\n throw Error('React utils library is already loaded');\n} else global.REACT_UTILS_LIBRARY_LOADED = true;\n\nexport {\n type AsyncCollectionT,\n type AsyncCollectionLoaderT,\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type ForceT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateResT,\n type ValueOrInitializerT,\n getGlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n withGlobalStateType,\n} from '@dr.pogodin/react-global-state';\n\nexport * from 'components';\n\nexport {\n type BeforeRenderResT,\n type BeforeRenderT,\n type ConfigT,\n type ServerSsrContext,\n type ServerT,\n} from './server';\n\nexport {\n assertEmptyObject,\n Barrier,\n Cached,\n Emitter,\n getConfig,\n isomorphy,\n getSsrContext,\n type Listener,\n type ObjectKey,\n Semaphore,\n splitComponent,\n type Theme,\n THEME_COMPOSE,\n THEME_PRIORITY,\n ThemeProvider,\n time,\n useTheme,\n webpack,\n withRetries,\n} from 'utils';\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA,GAAIA,MAAM,CAACC,0BAA0B,CAAE,CACrC,KAAM,CAAAC,KAAK,CAAC,uCAAuC,CACrD,CAAC,IAAM,CAAAF,MAAM,CAACC,0BAA0B,CAAG,IAAI,CAE/C,OAUEE,cAAc,CACdC,mBAAmB,CACnBC,oBAAoB,CACpBC,kBAAkB,CAClBC,YAAY,CACZC,cAAc,CACdC,mBAAmB,KACd,gCAAgC,kDAarCC,iBAAiB,CACjBC,OAAO,CACPC,MAAM,CACNC,OAAO,CACPC,SAAS,CACTC,SAAS,CACTC,aAAa,CAGbC,SAAS,CACTC,cAAc,CAEdC,aAAa,CACbC,cAAc,CACdC,aAAa,CACbC,IAAI,CACJC,QAAQ,CACRC,OAAO,CACPC,WAAW","ignoreList":[]}
|
|
@@ -45,7 +45,7 @@ server.get("/__service-worker.js",express.static(webpackConfig.output?.path??"",
|
|
|
45
45
|
// (in dev mode), and app modules are imported in some unfortunate ways.
|
|
46
46
|
// TODO: Double-check, what is going on here.
|
|
47
47
|
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
48
|
-
if(!global.location){global.location={href:`${pathToFileURL(process.cwd()).href}${sep}`}}const{default:webpack}=await import(/* webpackChunkName: "server-side-code" */"webpack");const{default:webpackDevMiddleware}=await import(/* webpackChunkName: "server-side-code" */"webpack-dev-middleware");const{default:webpackHotMiddleware}=await import(/* webpackChunkName: "server-side-code" */"webpack-hot-middleware");const compiler=webpack(webpackConfig);
|
|
48
|
+
if(!global.location){global.location={href:`${pathToFileURL(process.cwd()).href}${sep}`}}const{default:webpack}=await import(/* webpackChunkName: "server-side-code" */"webpack");const{default:webpackDevMiddleware}=await import(/* webpackChunkName: "server-side-code" */"webpack-dev-middleware");const{default:webpackHotMiddleware}=await import(/* webpackChunkName: "server-side-code" */"webpack-hot-middleware");const compiler=webpack(webpackConfig);server.use(webpackDevMiddleware(compiler,{publicPath,serverSideRender:true}));server.use(webpackHotMiddleware(compiler))}/* eslint-enable import/no-extraneous-dependencies */server.use(publicPath,express.static(webpackConfig.output.path));if(options.onExpressJsSetup){await options.onExpressJsSetup(server)}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use((req,res,next)=>{next(newError(ERRORS.NOT_FOUND,CODES.NOT_FOUND))});let dontAttachDefaultErrorHandler;if(options.beforeExpressJsError){dontAttachDefaultErrorHandler=await options.beforeExpressJsError(server)}/* Error handler. */if(!dontAttachDefaultErrorHandler){// TODO: Do we need this error handler at all? It actually seems to do
|
|
49
49
|
// what the default ExpressJS error handler does anyway, see:
|
|
50
50
|
// https://expressjs.com/en/guide/error-handling.html
|
|
51
51
|
//
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","names":["sep","pathToFileURL","cloneDeep","mapValues","pick","compression","cookieParser","csrf","express","favicon","helmet","loggerMiddleware","requestIp","v4","uuid","rendererFactory","CODES","ERRORS","getErrorForCode","newError","defaultCspSettings","directives","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","factory","webpackConfig","options","rendererOps","renderer","publicPath","output","server","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","cspNonce","cspSettings","cspSettingsHook","send","json","limit","urlencoded","extended","cookieSignatureSecret","mw","cookie","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","process","cwd","default","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","Error","serverSideRender","onExpressJsSetup","NOT_FOUND","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport { cloneDeep, mapValues, pick } from 'lodash-es';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\n\nimport express, {\n type Express,\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\n\nimport favicon from 'serve-favicon';\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport type { Configuration } from 'webpack';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT = Exclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => boolean | Promise<boolean>;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cookieSignatureSecret?: string;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser(options.cookieSignatureSecret));\n server.use(requestIp.mw());\n\n server.use(csrf({ cookie: true }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n const { default: webpack } = await import(/* webpackChunkName: \"server-side-code\" */ 'webpack');\n\n const { default: webpackDevMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-dev-middleware'\n );\n\n const { default: webpackHotMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-hot-middleware'\n );\n\n const compiler = webpack(webpackConfig);\n if (!compiler) throw Error('Internal error');\n\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":"wLAAA;AACA;AACA,GAEA,OAASA,GAAG,KAAQ,WAAW,CAC/B,OAASC,aAAa,KAAQ,UAAU,CAExC,OAASC,SAAS,CAAEC,SAAS,CAAEC,IAAI,KAAQ,WAAW,CAEtD,MAAO,CAAAC,WAAW,KAAM,aAAa,CACrC,MAAO,CAAAC,YAAY,KAAM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,GAAG,CAACuD,WAAW,CAAE,CACnBtD,IAAI,CAACqD,KAAK,CAAC,CACX,MACF,CAEA,KAAM,CAAAE,MAAM,CAAGF,KAAK,CAACE,MAAM,EAAIlF,KAAK,CAACmF,qBAAqB,CAC1D,KAAM,CAAAC,UAAU,CAAGF,MAAM,EAAKlF,KAAK,CAACmF,qBAAgC,CAEpE;AACApE,OAAO,CAACO,MAAM,CAAE+D,GAAG,CAACD,UAAU,CAAG,OAAO,CAAG,OAAO,CAAEJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC,CAErE,GAAI,CAAAC,OAAO,CAAGP,KAAK,CAACO,OAAO,EAAIrF,eAAe,CAACgF,MAAM,CAAC,CACtD,GAAIE,UAAU,EAAIjB,OAAO,CAACqB,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACvDF,OAAO,CAAGtF,MAAM,CAACkF,qBACnB,CAEAzD,GAAG,CAACwD,MAAM,CAACA,MAAM,CAAC,CAACvC,IAAI,CAAC4C,OAAO,CACjC,CAAC,CACH,CAEA,MAAO,CAAAnE,MACT","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"server.js","names":["sep","pathToFileURL","cloneDeep","mapValues","pick","compression","cookieParser","csrf","express","favicon","helmet","loggerMiddleware","requestIp","v4","uuid","rendererFactory","CODES","ERRORS","getErrorForCode","newError","defaultCspSettings","directives","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","factory","webpackConfig","options","rendererOps","renderer","publicPath","output","server","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","cspNonce","cspSettings","cspSettingsHook","send","json","limit","urlencoded","extended","cookieSignatureSecret","mw","cookie","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","process","cwd","default","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","NOT_FOUND","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport { cloneDeep, mapValues, pick } from 'lodash-es';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\n\nimport express, {\n type Express,\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\n\nimport favicon from 'serve-favicon';\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport type { Configuration } from 'webpack';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT = Exclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => boolean | Promise<boolean>;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cookieSignatureSecret?: string;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser(options.cookieSignatureSecret));\n server.use(requestIp.mw());\n\n server.use(csrf({ cookie: true }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n const { default: webpack } = await import(/* webpackChunkName: \"server-side-code\" */ 'webpack');\n\n const { default: webpackDevMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-dev-middleware'\n );\n\n const { default: webpackHotMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-hot-middleware'\n );\n\n const compiler = webpack(webpackConfig);\n\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":"wLAAA;AACA;AACA,GAEA,OAASA,GAAG,KAAQ,WAAW,CAC/B,OAASC,aAAa,KAAQ,UAAU,CAExC,OAASC,SAAS,CAAEC,SAAS,CAAEC,IAAI,KAAQ,WAAW,CAEtD,MAAO,CAAAC,WAAW,KAAM,aAAa,CACrC,MAAO,CAAAC,YAAY,KAAM,eAAe,CACxC,MAAO,CAAAC,IAAI,KAAM,mBAAmB,CAEpC,MAAO,CAAAC,OAAO,KAKP,SAAS,CAEhB,MAAO,CAAAC,OAAO,KAAM,eAAe,CACnC,MAAO,CAAAC,MAAM,KAA8B,QAAQ,CACnD,MAAO,CAAAC,gBAAgB,KAAM,QAAQ,CACrC,MAAO,CAAAC,SAAS,KAAM,YAAY,CAClC,OAASC,EAAE,GAAI,CAAAC,IAAI,KAAQ,MAAM,OAI1B,CAAAC,eAAe,4BAMpBC,KAAK,CACLC,MAAM,CACNC,eAAe,CACfC,QAAQ,yBAKV;AAMA;AACA;AACA;AACA,GACA,KAAM,CAAAC,kBAAkB,CAAG,CACzBC,UAAU,CAAElB,SAAS,CACnBO,MAAM,CAACY,qBAAqB,CAACC,oBAAoB,CAAC,CAAC,CAEnD;AACA;AACA;AACA;AACCC,KAAK,EAAMA,KAAK,CAAcC,MAAM,CAAEC,IAAY,EAAKA,IAAI,GAAK,QAAQ,CAC3E,CACF,CAAC,CACDN,kBAAkB,CAACC,UAAU,CAAC,WAAW,CAAC,CAAG,CAC3C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AAEC,GAAG,CAAEC,IAAI,GAAK,CAC7BA,IAAI,CAACxB,QAAQ,CAACF,MAAM,CAAC2E,SAAS,CAAE5E,KAAK,CAAC4E,SAAS,CAAC,CAClD,CAAC,CAAC,CAEF,GAAI,CAAAC,6BAA6B,CACjC,GAAI9D,OAAO,CAAC+D,oBAAoB,CAAE,CAChCD,6BAA6B,CAAG,KAAM,CAAA9D,OAAO,CAAC+D,oBAAoB,CAAC1D,MAAM,CAC3E,CAEA,oBACA,GAAI,CAACyD,6BAA6B,CAAE,CAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAzD,MAAM,CAACI,GAAG,CAAC,CACTuD,KAEC,CACDtD,GAAY,CACZC,GAAa,CACbC,IAAkB,GACf,CACH;AACA;AACA,GAAID,GAAG,CAACsD,WAAW,CAAE,CACnBrD,IAAI,CAACoD,KAAK,CAAC,CACX,MACF,CAEA,KAAM,CAAAE,MAAM,CAAGF,KAAK,CAACE,MAAM,EAAIjF,KAAK,CAACkF,qBAAqB,CAC1D,KAAM,CAAAC,UAAU,CAAGF,MAAM,EAAKjF,KAAK,CAACkF,qBAAgC,CAEpE;AACAnE,OAAO,CAACO,MAAM,CAAE8D,GAAG,CAACD,UAAU,CAAG,OAAO,CAAG,OAAO,CAAEJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC,CAErE,GAAI,CAAAC,OAAO,CAAGP,KAAK,CAACO,OAAO,EAAIpF,eAAe,CAAC+E,MAAM,CAAC,CACtD,GAAIE,UAAU,EAAIhB,OAAO,CAACoB,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACvDF,OAAO,CAAGrF,MAAM,CAACiF,qBACnB,CAEAxD,GAAG,CAACuD,MAAM,CAACA,MAAM,CAAC,CAACtC,IAAI,CAAC2C,OAAO,CACjC,CAAC,CACH,CAEA,MAAO,CAAAlE,MACT","ignoreList":[]}
|
|
@@ -1,14 +1,9 @@
|
|
|
1
1
|
// The <Button> component implements a standard button / button-like link.
|
|
2
|
-
import
|
|
2
|
+
import{useTheme}from"@dr.pogodin/react-themes";import Link from"../Link.js";const defaultTheme={"context":"_0S7CYa","ad":"YFXz0-","hoc":"BElFuo","button":"hXiBOw","active":"biX-UA","disabled":"_-6CH9q"};import{jsx as _jsx}from"react/jsx-runtime";export const BaseButton=({active,children,disabled,enforceA,onClick,onKeyDown:onKeyDownProp,onKeyUp,onMouseDown,onMouseUp,onPointerDown,onPointerUp,openNewTab,replace,testId,theme,to})=>{let className=theme.button;if(active&&theme.active)className+=` ${theme.active}`;if(disabled){if(theme.disabled)className+=` ${theme.disabled}`;return/*#__PURE__*/_jsx("div",{className:className,"data-testid":process.env.NODE_ENV==="production"?undefined:testId,children:children})}let onKeyDown=onKeyDownProp;if(!onKeyDown&&onClick){onKeyDown=e=>{if(e.key==="Enter")onClick(e)}}if(to){return/*#__PURE__*/_jsx(Link,{className:className,"data-testid":process.env.NODE_ENV==="production"?undefined:testId,enforceA:enforceA,onClick:onClick// TODO: For now, the `onKeyDown` handler is not passed to the <Link>,
|
|
3
3
|
// as <Link> component does not call it anyway, presumably due to
|
|
4
4
|
// the inner implementation details. We should look into supporting it:
|
|
5
5
|
// https://github.com/birdofpreyru/react-utils/issues/444
|
|
6
6
|
// onKeyDown={onKeyDown}
|
|
7
|
-
,onKeyUp:onKeyUp,onMouseDown:onMouseDown,onMouseUp:onMouseUp,onPointerDown:onPointerDown,onPointerUp:onPointerUp,openNewTab:openNewTab,replace:replace,to:to,children:children})}return/*#__PURE__*/_jsx("div",{className:className,"data-testid":process.env.NODE_ENV==="production"?undefined:testId,onClick:onClick,onKeyDown:onKeyDown,onKeyUp:onKeyUp,onMouseDown:onMouseDown,onMouseUp:onMouseUp,onPointerDown:onPointerDown,onPointerUp:onPointerUp,role:"button",tabIndex:0,children:children})}
|
|
8
|
-
|
|
9
|
-
* class names to append to button elements:
|
|
10
|
-
* @prop {string} [active] to the root element of active button.
|
|
11
|
-
* @prop {string} [button] to the root element of any button.
|
|
12
|
-
* @prop {string} [disabled] to the root element of disabled button.
|
|
13
|
-
*/export default/* #__PURE__ */themed(BaseButton,"Button",defaultTheme);
|
|
7
|
+
,onKeyUp:onKeyUp,onMouseDown:onMouseDown,onMouseUp:onMouseUp,onPointerDown:onPointerDown,onPointerUp:onPointerUp,openNewTab:openNewTab,replace:replace,to:to,children:children})}return/*#__PURE__*/_jsx("div",{className:className,"data-testid":process.env.NODE_ENV==="production"?undefined:testId,onClick:onClick,onKeyDown:onKeyDown,onKeyUp:onKeyUp,onMouseDown:onMouseDown,onMouseUp:onMouseUp,onPointerDown:onPointerDown,onPointerUp:onPointerUp,role:"button",tabIndex:0,children:children})};const Button=({theme,...rest})=>{const composed=useTheme("Button",defaultTheme,theme);// eslint-disable-next-line react/jsx-props-no-spreading
|
|
8
|
+
return/*#__PURE__*/_jsx(BaseButton,{...rest,theme:composed})};export default Button;
|
|
14
9
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["
|
|
1
|
+
{"version":3,"file":"index.js","names":["useTheme","Link","defaultTheme","jsx","_jsx","BaseButton","active","children","disabled","enforceA","onClick","onKeyDown","onKeyDownProp","onKeyUp","onMouseDown","onMouseUp","onPointerDown","onPointerUp","openNewTab","replace","testId","theme","to","className","button","process","env","NODE_ENV","undefined","e","key","role","tabIndex","Button","rest","composed"],"sources":["../../../../../src/shared/components/Button/index.tsx"],"sourcesContent":["// The <Button> component implements a standard button / button-like link.\n\nimport type {\n FunctionComponent,\n KeyboardEventHandler,\n MouseEventHandler,\n PointerEventHandler,\n ReactNode,\n} from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport Link from 'components/Link';\n\nimport defaultTheme from './style.scss';\n\ntype ThemeT = Theme<'active' | 'button' | 'disabled'>;\n\ntype PropsT = {\n active?: boolean;\n children?: ReactNode;\n disabled?: boolean;\n enforceA?: boolean;\n onClick?: MouseEventHandler & KeyboardEventHandler;\n onKeyDown?: KeyboardEventHandler;\n onKeyUp?: KeyboardEventHandler;\n onMouseDown?: MouseEventHandler;\n onMouseUp?: MouseEventHandler;\n onPointerDown?: PointerEventHandler;\n onPointerUp?: PointerEventHandler;\n openNewTab?: boolean;\n replace?: boolean;\n testId?: string;\n theme: ThemeT;\n\n // TODO: It needs a more precise typing of the object option.\n to?: object | string;\n};\n\nexport const BaseButton: FunctionComponent<PropsT> = ({\n active,\n children,\n disabled,\n enforceA,\n onClick,\n onKeyDown: onKeyDownProp,\n onKeyUp,\n onMouseDown,\n onMouseUp,\n onPointerDown,\n onPointerUp,\n openNewTab,\n replace,\n testId,\n theme,\n to,\n}) => {\n let className = theme.button;\n if (active && theme.active) className += ` ${theme.active}`;\n if (disabled) {\n if (theme.disabled) className += ` ${theme.disabled}`;\n return (\n <div\n className={className}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n >\n {children}\n </div>\n );\n }\n\n let onKeyDown = onKeyDownProp;\n if (!onKeyDown && onClick) {\n onKeyDown = (e) => {\n if (e.key === 'Enter') onClick(e);\n };\n }\n\n if (to) {\n return (\n <Link\n className={className}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n enforceA={enforceA}\n onClick={onClick}\n\n // TODO: For now, the `onKeyDown` handler is not passed to the <Link>,\n // as <Link> component does not call it anyway, presumably due to\n // the inner implementation details. We should look into supporting it:\n // https://github.com/birdofpreyru/react-utils/issues/444\n // onKeyDown={onKeyDown}\n\n onKeyUp={onKeyUp}\n onMouseDown={onMouseDown}\n onMouseUp={onMouseUp}\n onPointerDown={onPointerDown}\n onPointerUp={onPointerUp}\n openNewTab={openNewTab}\n replace={replace}\n to={to}\n >\n {children}\n </Link>\n );\n }\n\n return (\n <div\n className={className}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onClick={onClick}\n onKeyDown={onKeyDown}\n onKeyUp={onKeyUp}\n onMouseDown={onMouseDown}\n onMouseUp={onMouseUp}\n onPointerDown={onPointerDown}\n onPointerUp={onPointerUp}\n role=\"button\"\n tabIndex={0}\n >\n {children}\n </div>\n );\n};\n\nconst Button: FunctionComponent<\n Omit<PropsT, 'theme'> & { theme?: ThemeT }\n> = ({ theme, ...rest }) => {\n const composed = useTheme('Button', defaultTheme, theme);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return <BaseButton {...rest} theme={composed} />;\n};\n\nexport default Button;\n"],"mappings":"AAAA;AAUA,OAAqBA,QAAQ,KAAQ,0BAA0B,OAExD,CAAAC,IAAI,wBAAAC,YAAA,6GAE6B,OAAAC,GAAA,IAAAC,IAAA,yBAyBxC,MAAO,MAAM,CAAAC,UAAqC,CAAGA,CAAC,CACpDC,MAAM,CACNC,QAAQ,CACRC,QAAQ,CACRC,QAAQ,CACRC,OAAO,CACPC,SAAS,CAAEC,aAAa,CACxBC,OAAO,CACPC,WAAW,CACXC,SAAS,CACTC,aAAa,CACbC,WAAW,CACXC,UAAU,CACVC,OAAO,CACPC,MAAM,CACNC,KAAK,CACLC,EACF,CAAC,GAAK,CACJ,GAAI,CAAAC,SAAS,CAAGF,KAAK,CAACG,MAAM,CAC5B,GAAIlB,MAAM,EAAIe,KAAK,CAACf,MAAM,CAAEiB,SAAS,EAAI,IAAIF,KAAK,CAACf,MAAM,EAAE,CAC3D,GAAIE,QAAQ,CAAE,CACZ,GAAIa,KAAK,CAACb,QAAQ,CAAEe,SAAS,EAAI,IAAIF,KAAK,CAACb,QAAQ,EAAE,CACrD,mBACEJ,IAAA,QACEmB,SAAS,CAAEA,SAAU,CACrB,cAAaE,OAAO,CAACC,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAGC,SAAS,CAAGR,MAAO,CAAAb,QAAA,CAEvEA,QAAQ,CACN,CAET,CAEA,GAAI,CAAAI,SAAS,CAAGC,aAAa,CAC7B,GAAI,CAACD,SAAS,EAAID,OAAO,CAAE,CACzBC,SAAS,CAAIkB,CAAC,EAAK,CACjB,GAAIA,CAAC,CAACC,GAAG,GAAK,OAAO,CAAEpB,OAAO,CAACm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[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import
|
|
1
|
+
import{useTheme}from"@dr.pogodin/react-themes";const defaultTheme={"context":"_08mmmo","ad":"Hc06MV","hoc":"toOtOd","checkbox":"v4DmWM","indeterminate":"ckSC8W","container":"g7wee9","label":"XQ57WS","disabled":"baVvQA"};import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const Checkbox=({checked,disabled,label,onChange,testId,theme})=>{const composed=useTheme("Checkbox",defaultTheme,theme);let containerClassName=composed.container;if(disabled)containerClassName+=` ${composed.disabled}`;let checkboxClassName=composed.checkbox;if(checked==="indeterminate")checkboxClassName+=` ${composed.indeterminate}`;return/*#__PURE__*/_jsxs("div",{className:containerClassName,children:[label===undefined?null:/*#__PURE__*/_jsx("div",{className:composed.label,children:label}),/*#__PURE__*/_jsx("input",{checked:checked===undefined?undefined:checked===true,className:checkboxClassName,"data-testid":process.env.NODE_ENV==="production"?undefined:testId,disabled:disabled,onChange:onChange,onClick:e=>{e.stopPropagation()},type:"checkbox"})]})};export default Checkbox;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["
|
|
1
|
+
{"version":3,"file":"index.js","names":["useTheme","defaultTheme","jsx","_jsx","jsxs","_jsxs","Checkbox","checked","disabled","label","onChange","testId","theme","composed","containerClassName","container","checkboxClassName","checkbox","indeterminate","className","children","undefined","process","env","NODE_ENV","onClick","e","stopPropagation","type"],"sources":["../../../../../src/shared/components/Checkbox/index.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './theme.scss';\n\ntype PropT<ValueT> = {\n checked?: ValueT;\n disabled?: boolean;\n label?: React.ReactNode;\n onChange?: React.ChangeEventHandler<HTMLInputElement>;\n testId?: string;\n theme?: Theme<\n | 'checkbox'\n | 'container'\n | 'disabled'\n | 'indeterminate'\n | 'label'\n >;\n};\n\nconst Checkbox = <ValueT extends boolean | 'indeterminate' = boolean>({\n checked,\n disabled,\n label,\n onChange,\n testId,\n theme,\n}: PropT<ValueT>): ReactNode => {\n const composed = useTheme('Checkbox', defaultTheme, theme);\n\n let containerClassName = composed.container;\n if (disabled) containerClassName += ` ${composed.disabled}`;\n\n let checkboxClassName = composed.checkbox;\n if (checked === 'indeterminate') checkboxClassName += ` ${composed.indeterminate}`;\n\n return (\n <div className={containerClassName}>\n { label === undefined\n ? null : <div className={composed.label}>{label}</div> }\n <input\n checked={checked === undefined ? undefined : checked === true}\n className={checkboxClassName}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n disabled={disabled}\n onChange={onChange}\n onClick={(e) => {\n e.stopPropagation();\n }}\n type=\"checkbox\"\n />\n </div>\n );\n};\n\nexport default Checkbox;\n"],"mappings":"AAEA,OAAqBA,QAAQ,KAAQ,0BAA0B,OAAAC,YAAA,2JAEvB,OAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBAiBxC,KAAM,CAAAC,QAAQ,CAAGA,CAAqD,CACpEC,OAAO,CACPC,QAAQ,CACRC,KAAK,CACLC,QAAQ,CACRC,MAAM,CACNC,KACa,CAAC,GAAgB,CAC9B,KAAM,CAAAC,QAAQ,CAAGb,QAAQ,CAAC,UAAU,CAAEC,YAAY,CAAEW,KAAK,CAAC,CAE1D,GAAI,CAAAE,kBAAkB,CAAGD,QAAQ,CAACE,SAAS,CAC3C,GAAIP,QAAQ,CAAEM,kBAAkB,EAAI,IAAID,QAAQ,CAACL,QAAQ,EAAE,CAE3D,GAAI,CAAAQ,iBAAiB,CAAGH,QAAQ,CAACI,QAAQ,CACzC,GAAIV,OAAO,GAAK,eAAe,CAAES,iBAAiB,EAAI,IAAIH,QAAQ,CAACK,aAAa,EAAE,CAElF,mBACEb,KAAA,QAAKc,SAAS,CAAEL,kBAAmB,CAAAM,QAAA,EAC/BX,KAAK,GAAKY,SAAS,CACjB,IAAI,cAAGlB,IAAA,QAAKgB,SAAS,CAAEN,QAAQ,CAACJ,KAAM,CAAAW,QAAA,CAAEX,KAAK,CAAM,CAAC,cACxDN,IAAA,UACEI,OAAO,CAAEA,OAAO,GAAKc,SAAS,CAAGA,SAAS,CAAGd,OAAO,GAAK,IAAK,CAC9DY,SAAS,CAAEH,iBAAkB,CAC7B,cAAaM,OAAO,CAACC,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAGH,SAAS,CAAGV,MAAO,CACxEH,QAAQ,CAAEA,QAAS,CACnBE,QAAQ,CAAEA,QAAS,CACnBe,OAAO,CAAGC,CAAC,EAAK,CACdA,CAAC,CAACC,eAAe,CAAC,CACpB,CAAE,CACFC,IAAI,CAAC,UAAU,CAChB,CAAC,EACC,CAET,CAAC,CAED,cAAe,CAAAtB,QAAQ","ignoreList":[]}
|
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import{useRef,useState}from"react";import
|
|
1
|
+
import{useRef,useState}from"react";import{useTheme}from"@dr.pogodin/react-themes";const defaultTheme={"context":"-Jj9Dp","ad":"IOZUc8","hoc":"nSzLXc","container":"wW08uK","children":"hCuQWP","input":"oYQ-Uo","label":"OTmX5n","error":"_7jrZ-X","errorMessage":"qjYbwz"};import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";/**
|
|
2
2
|
* Themeable input field, based on the standard HTML `<input>` element.
|
|
3
3
|
* @param [props.label] Input label.
|
|
4
4
|
* @param [props.theme] _Ad hoc_ theme.
|
|
5
5
|
* @param [props...] [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)
|
|
6
6
|
* @param [props...] Any other properties are passed to the underlying
|
|
7
7
|
* `<input>` element.
|
|
8
|
-
*/const Input=({children,error,label,ref,testId,theme,...rest})=>{
|
|
8
|
+
*/const Input=({children,error,label,ref,testId,theme,...rest})=>{const composed=useTheme("Input",defaultTheme,theme);// NOTE: As of now, it is only updated when "theme.focused" is defined,
|
|
9
9
|
// as otherwise its value is not used.
|
|
10
|
-
const[focused,setFocused]=useState(false);const localRef=useRef(null);let containerClassName=
|
|
10
|
+
const[focused,setFocused]=useState(false);const localRef=useRef(null);let containerClassName=composed.container;// NOTE: As of now, "focused" can be true only when "theme.focused"
|
|
11
11
|
// is provided.
|
|
12
|
-
if(focused/* && theme.focused */)containerClassName+=` ${
|
|
12
|
+
if(focused/* && theme.focused */)containerClassName+=` ${composed.focused}`;if(!rest.value&&composed.empty)containerClassName+=` ${composed.empty}`;if(error)containerClassName+=` ${composed.error}`;return/*#__PURE__*/_jsxs("div",{className:containerClassName,onFocus:()=>{// TODO: It does not really work if a callback-style `ref` is passed in,
|
|
13
13
|
// we need a more complex logic to cover that case, but for now this serves
|
|
14
14
|
// the case we need it for.
|
|
15
|
-
if(typeof ref==="object")ref?.current?.focus();else localRef.current?.focus()},children:[label===undefined?null:/*#__PURE__*/_jsx("div",{className:
|
|
15
|
+
if(typeof ref==="object")ref?.current?.focus();else localRef.current?.focus()},children:[label===undefined?null:/*#__PURE__*/_jsx("div",{className:composed.label,children:label}),/*#__PURE__*/_jsx("input",{className:composed.input,"data-testid":process.env.NODE_ENV==="production"?undefined:testId,ref:ref??localRef// TODO: Avoid the spreading later.
|
|
16
16
|
// eslint-disable-next-line react/jsx-props-no-spreading
|
|
17
|
-
,...rest,onBlur:
|
|
17
|
+
,...rest,onBlur:composed.focused?e=>{setFocused(false);rest.onBlur?.(e)}:rest.onBlur,onFocus:composed.focused?e=>{setFocused(true);rest.onFocus?.(e)}:rest.onFocus}),error&&error!==true?/*#__PURE__*/_jsx("div",{className:composed.errorMessage,children:error}):null,children?/*#__PURE__*/_jsx("div",{className:composed.children,children:children}):null]})};export default Input;
|
|
18
18
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["useRef","useState","
|
|
1
|
+
{"version":3,"file":"index.js","names":["useRef","useState","useTheme","defaultTheme","jsx","_jsx","jsxs","_jsxs","Input","children","error","label","ref","testId","theme","rest","composed","focused","setFocused","localRef","containerClassName","container","value","empty","className","onFocus","current","focus","undefined","input","process","env","NODE_ENV","onBlur","e","errorMessage"],"sources":["../../../../../src/shared/components/Input/index.tsx"],"sourcesContent":["import {\n type FunctionComponent,\n type ReactNode,\n type Ref,\n useRef,\n useState,\n} from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './theme.scss';\n\ntype ThemeKeyT = 'children' | 'container' | 'empty' | 'error' | 'errorMessage'\n | 'focused' | 'input' | 'label';\n\ntype PropsT = React.InputHTMLAttributes<HTMLInputElement> & {\n children?: ReactNode;\n error?: ReactNode;\n label?: React.ReactNode;\n ref?: Ref<HTMLInputElement>;\n testId?: string;\n theme?: Theme<ThemeKeyT>;\n};\n\n/**\n * Themeable input field, based on the standard HTML `<input>` element.\n * @param [props.label] Input label.\n * @param [props.theme] _Ad hoc_ theme.\n * @param [props...] [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n * @param [props...] Any other properties are passed to the underlying\n * `<input>` element.\n */\nconst Input: FunctionComponent<PropsT> = ({\n children,\n error,\n label,\n ref,\n testId,\n theme,\n ...rest\n}) => {\n const composed = useTheme('Input', defaultTheme, theme);\n\n // NOTE: As of now, it is only updated when \"theme.focused\" is defined,\n // as otherwise its value is not used.\n const [focused, setFocused] = useState(false);\n\n const localRef = useRef<HTMLInputElement>(null);\n\n let containerClassName = composed.container;\n\n // NOTE: As of now, \"focused\" can be true only when \"theme.focused\"\n // is provided.\n if (focused /* && theme.focused */) containerClassName += ` ${composed.focused}`;\n\n if (!rest.value && composed.empty) containerClassName += ` ${composed.empty}`;\n\n if (error) containerClassName += ` ${composed.error}`;\n\n return (\n <div\n className={containerClassName}\n onFocus={() => {\n // TODO: It does not really work if a callback-style `ref` is passed in,\n // we need a more complex logic to cover that case, but for now this serves\n // the case we need it for.\n if (typeof ref === 'object') ref?.current?.focus();\n else localRef.current?.focus();\n }}\n >\n {label === undefined\n ? null : <div className={composed.label}>{label}</div>}\n <input\n className={composed.input}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n ref={ref ?? localRef}\n\n // TODO: Avoid the spreading later.\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest}\n\n onBlur={composed.focused ? (e) => {\n setFocused(false);\n rest.onBlur?.(e);\n } : rest.onBlur}\n onFocus={composed.focused ? (e) => {\n setFocused(true);\n rest.onFocus?.(e);\n } : rest.onFocus}\n />\n {error && error !== true\n ? <div className={composed.errorMessage}>{error}</div>\n : null}\n {children ? <div className={composed.children}>{children}</div> : null}\n </div>\n );\n};\n\nexport default Input;\n"],"mappings":"AAAA,OAIEA,MAAM,CACNC,QAAQ,KACH,OAAO,CAEd,OAAqBC,QAAQ,KAAQ,0BAA0B,OAAAC,YAAA,wKAEvB,OAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBAcxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAM,CAAAC,KAAgC,CAAGA,CAAC,CACxCC,QAAQ,CACRC,KAAK,CACLC,KAAK,CACLC,GAAG,CACHC,MAAM,CACNC,KAAK,CACL,GAAGC,IACL,CAAC,GAAK,CACJ,KAAM,CAAAC,QAAQ,CAAGd,QAAQ,CAAC,OAAO,CAAEC,YAAY,CAAEW,KAAK,CAAC,CAEvD;AACA;AACA,KAAM,CAACG,OAAO,CAAEC,UAAU,CAAC,CAAGjB,QAAQ,CAAC,KAAK,CAAC,CAE7C,KAAM,CAAAkB,QAAQ,CAAGnB,MAAM,CAAmB,IAAI,CAAC,CAE/C,GAAI,CAAAoB,kBAAkB,CAAGJ,QAAQ,CAACK,SAAS,CAE3C;AACA;AACA,GAAIJ,OAAQ,uBAAwBG,kBAAkB,EAAI,IAAIJ,QAAQ,CAACC,OAAO,EAAE,CAEhF,GAAI,CAACF,IAAI,CAACO,KAAK,EAAIN,QAAQ,CAACO,KAAK,CAAEH,kBAAkB,EAAI,IAAIJ,QA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A,QAAKmB,SAAS,CAAER,QAAQ,CAACP,QAAS,CAAAA,QAAA,CAAEA,QAAQ,CAAM,CAAC,CAAG,IAAI,EACnE,CAET,CAAC,CAED,cAAe,CAAAD,KAAK","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{useEffect,useMemo,useRef}from"react";import{createPortal}from"react-dom";import
|
|
1
|
+
import{useEffect,useMemo,useRef}from"react";import{createPortal}from"react-dom";import{useTheme}from"@dr.pogodin/react-themes";const defaultTheme={"context":"sCYXfW","ad":"e0BH-f","hoc":"vqUuSP","overlay":"uAH4as","container":"zqpc6q"};const S={"scrollingDisabledByModal":"yfvOIZ"};import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";/**
|
|
2
2
|
* The `<Modal>` component implements a simple themeable modal window, wrapped
|
|
3
3
|
* into the default theme. `<BaseModal>` exposes the base non-themed component.
|
|
4
4
|
* **Children:** Component children are rendered as the modal content.
|
|
@@ -15,5 +15,6 @@ useEffect(()=>{if(!dontDisableScrolling){document.body.classList.add(S.scrolling
|
|
|
15
15
|
,tabIndex:0}),[]);return/*#__PURE__*/createPortal(/*#__PURE__*/_jsxs("div",{children:[focusLast,/*#__PURE__*/_jsx("div",{"aria-label":"Cancel",className:theme.overlay,"data-testid":process.env.NODE_ENV==="production"?undefined:testIdForOverlay,onClick:e=>{if(onCancel){onCancel();e.stopPropagation()}},onKeyDown:e=>{if(e.key==="Escape"&&onCancel){onCancel();e.stopPropagation()}},ref:node=>{if(node&&node!==overlayRef.current){overlayRef.current=node;node.focus()}},role:"button",style:overlayStyle,tabIndex:0}),/*#__PURE__*/_jsx("div",{// eslint-disable-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions
|
|
16
16
|
"aria-modal":"true",className:theme.container,"data-testid":process.env.NODE_ENV==="production"?undefined:testId,onClick:e=>{e.stopPropagation()},onWheel:event=>{event.stopPropagation()},ref:containerRef,role:"dialog",style:style??containerStyle,children:children}),/*#__PURE__*/_jsx("div",{onFocus:()=>{overlayRef.current?.focus()}// TODO: Have a look at this later.
|
|
17
17
|
// eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex
|
|
18
|
-
,tabIndex:0}),focusLast]}),document.body)}
|
|
18
|
+
,tabIndex:0}),focusLast]}),document.body)};/* Non-themed version of the Modal. */export{BaseModal};const Modal=({theme,...rest})=>{const composed=useTheme("Modal",defaultTheme,theme);// eslint-disable-next-line react/jsx-props-no-spreading
|
|
19
|
+
return/*#__PURE__*/_jsx(BaseModal,{...rest,theme:composed})};export default Modal;
|
|
19
20
|
//# sourceMappingURL=index.js.map
|