dinocollab-core 2.2.44 → 2.2.45
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/dist/_virtual/_rollupPluginBabelHelpers.js +2 -2
- package/dist/src/components/create.multi-select-dropdown.js +1 -1
- package/dist/src/components/create.multi-select-dropdown.js.map +1 -1
- package/dist/src/data-view/create.active-filters-panel.js +1 -1
- package/dist/src/data-view/create.active-filters-panel.js.map +1 -1
- package/dist/src/data-view/dino.js +1 -1
- package/dist/src/data-view/dino.js.map +1 -1
- package/dist/src/data-view/filter-store.js +1 -1
- package/dist/src/data-view/filter-store.js.map +1 -1
- package/dist/src/data-view/query-param-url.js +1 -1
- package/dist/src/data-view/query-param-url.js.map +1 -1
- package/dist/src/form/create.date-expired.js +1 -1
- package/dist/src/form/create.date-expired.js.map +1 -1
- package/dist/src/form/create.date-picker.js +1 -1
- package/dist/src/form/create.date-picker.js.map +1 -1
- package/dist/src/form/create.form-base.js +1 -1
- package/dist/src/form/create.form-base.js.map +1 -1
- package/dist/src/form/create.form-comfirm.js +1 -1
- package/dist/src/form/create.form-comfirm.js.map +1 -1
- package/dist/src/form/create.form-grid-layout.js +1 -1
- package/dist/src/form/create.form-grid-layout.js.map +1 -1
- package/dist/src/form/create.input-file.csv-local-parser.js +1 -1
- package/dist/src/form/create.input-file.csv-local-parser.js.map +1 -1
- package/dist/src/form/create.input.js +1 -1
- package/dist/src/form/create.input.js.map +1 -1
- package/dist/src/form/create.text-editor.js +1 -1
- package/dist/src/form/create.text-editor.js.map +1 -1
- package/dist/src/form/decorator.form.js +1 -1
- package/dist/src/form/decorator.form.js.map +1 -1
- package/dist/src/form/decorator.units.js +1 -1
- package/dist/src/form/decorator.units.js.map +1 -1
- package/dist/src/form/error-handler.js +2 -0
- package/dist/src/form/error-handler.js.map +1 -0
- package/dist/src/form/helpers.js +1 -1
- package/dist/src/form/helpers.js.map +1 -1
- package/dist/src/form/modal-wrapper.js +1 -1
- package/dist/src/form/modal-wrapper.js.map +1 -1
- package/dist/src/form/validator.js +1 -1
- package/dist/src/form/validator.js.map +1 -1
- package/dist/src/table/create.action-row.js +1 -1
- package/dist/src/table/create.action-row.js.map +1 -1
- package/dist/src/table/create.table.js +1 -1
- package/dist/src/table/create.table.js.map +1 -1
- package/dist/src/table/dino.js +1 -1
- package/dist/src/table/dino.js.map +1 -1
- package/dist/src/table/helpers.js +1 -1
- package/dist/src/table/helpers.js.map +1 -1
- package/dist/src/table/toolbar-pannel.js +1 -1
- package/dist/src/table/toolbar-pannel.js.map +1 -1
- package/dist/src/table/ui.units.js +1 -1
- package/dist/src/table/ui.units.js.map +1 -1
- package/dist/src/table-grid/create.table-grid.js +1 -1
- package/dist/src/table-grid/create.table-grid.js.map +1 -1
- package/dist/src/table-grid/toolbar-pannel.js +1 -1
- package/dist/src/table-grid/toolbar-pannel.js.map +1 -1
- package/dist/src/table-grid/url-query-param.js +1 -1
- package/dist/src/table-grid/url-query-param.js.map +1 -1
- package/dist/table/index.js +1 -1
- package/dist/types/form/create.form-base.d.ts +11 -9
- package/dist/types/form/decorator.form.d.ts +6 -6
- package/dist/types/form/decorator.units.d.ts +0 -1
- package/dist/types/form/dino-form.d.ts +2 -2
- package/dist/types/form/error-handler.d.ts +10 -0
- package/dist/types/form/helpers.d.ts +5 -8
- package/dist/types/form/validator.d.ts +15 -15
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.input-file.csv-local-parser.js","sources":["../../../src/form/create.input-file.csv-local-parser.tsx"],"sourcesContent":["import React, { Component, ComponentType } from 'react'\r\nimport { Box, BoxProps, styled, TextField, TextFieldProps, Typography, TypographyProps } from '@mui/material'\r\nimport DownloadIcon from '@mui/icons-material/Download'\r\nimport { getErrorMessage } from './helpers'\r\nimport { tryParseCsvFileToArray } from '../utils'\r\nimport { IFormBase, IFormInputBase } from './types'\r\n\r\nexport interface IInputFileCsvLocalParserSlots {\r\n /**\r\n * The URL of the sample CSV file that users can download.\r\n * If provided, a \"Download sample\" link will be displayed.\r\n * Example: '/sample.csv' or 'https://example.com/sample.csv'\r\n */\r\n downloadSampleUrl?: string\r\n /**\r\n * Instructional text displayed alongside the download link or file input.\r\n * Useful for guiding users on how to use or fill out the CSV file.\r\n */\r\n instructionalText?: string\r\n /**\r\n * The title text displayed at the top.\r\n */\r\n titleText?: string\r\n /**\r\n * Optional sub text displayed below the title or above the download link.\r\n */\r\n subText?: string\r\n /**\r\n * Props to customize the TextField used for uploading the CSV file.\r\n * Allows customization of appearance and behavior (e.g., placeholder, onChange, disabled).\r\n */\r\n textFieldProps?: TextFieldProps\r\n /**\r\n * Props passed to the wrapper element (typically a Box).\r\n * Useful for customizing layout styles such as margin, padding, or display.\r\n */\r\n wrapProps?: BoxProps\r\n /**\r\n * Whether the label should shrink when displayed.\r\n * Defaults to `true` if a label is present to prevent overlap.\r\n * @default true\r\n */\r\n labelShrink?: boolean\r\n}\r\n\r\nexport interface IInputFileCsvLocalParserParams extends IInputFileCsvLocalParserSlots {\r\n /** Optional sub name for the input field. */\r\n subName?: string\r\n /**\r\n * Optional suffix name for the input field. When `subName` is provided, `suffixName` will be not used.\r\n * @default '_file'\r\n * */\r\n suffixName?: string\r\n}\r\n\r\nexport interface IInputFileCsvLocalParserProps<T, C> extends IFormInputBase<T, IInputFileCsvLocalParserSlots> {\r\n onChange?: (value: C[]) => void\r\n}\r\n\r\nexport interface IInputFileCsvLocalParserState<C> {\r\n parsedData: C[]\r\n}\r\n\r\ntype IPickConfigs<T> = Required<Pick<IFormBase<T>, 'onBlur' | 'messageErrors'>>\r\n\r\ninterface IMergeConfigs<T> extends IPickConfigs<T>, IInputFileCsvLocalParserSlots {\r\n name: keyof T\r\n}\r\n\r\n/**\r\n * Creates a React component that renders a file input specifically for CSV files,\r\n * parses the selected file locally into a structured array, and integrates with a form system.\r\n *\r\n * @template T - The main data model used in the form. Represents the shape of the overall form data.\r\n * @template C - The type of each individual item parsed from the CSV file.\r\n *\r\n * @param params - Optional slot parameters to customize the appearance or behavior of the text field.\r\n * @returns A React component configured for uploading and parsing local CSV files.\r\n */\r\nexport function createInputFileCsvLocalParser<T, C>(params?: IInputFileCsvLocalParserParams): ComponentType<IInputFileCsvLocalParserProps<T, C>> {\r\n class InputFileCsvLocalParser extends Component<IInputFileCsvLocalParserProps<T, C>, IInputFileCsvLocalParserState<C>> {\r\n private mergeConfigsCache: IMergeConfigs<T> = { name: '' as keyof T, onBlur: () => {}, messageErrors: {} }\r\n constructor(props: IInputFileCsvLocalParserProps<T, C>) {\r\n super(props)\r\n this.mergeConfigsCache = this.upgradeMergeConfigs(props)\r\n this.state = { parsedData: [] }\r\n }\r\n\r\n get mergeConfigs(): IMergeConfigs<T> {\r\n return this.mergeConfigsCache\r\n }\r\n\r\n get inputValue() {\r\n return this.state.parsedData.length > 0 ? JSON.stringify(this.state.parsedData) : ''\r\n }\r\n\r\n shouldComponentUpdate(nextProps: Readonly<IInputFileCsvLocalParserProps<T, C>>): boolean {\r\n if (nextProps !== this.props) this.mergeConfigsCache = this.upgradeMergeConfigs(nextProps)\r\n return true\r\n }\r\n\r\n refInput: HTMLInputElement | null = null\r\n refTextFiled: HTMLInputElement | null = null\r\n render() {\r\n return (\r\n <Box {...this.mergeConfigs.wrapProps}>\r\n {this.mergeConfigs.titleText && (\r\n <Typography variant='subtitle1' component='h6' sx={{ fontWeight: 600, mb: 0.5 }}>\r\n {this.mergeConfigs.titleText}\r\n </Typography>\r\n )}\r\n {this.mergeConfigs.downloadSampleUrl && (\r\n <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>\r\n <Typography variant='subtitle2' component='span'>\r\n {this.mergeConfigs.instructionalText ?? 'Metadata file, please fill out the form we provide.'}\r\n </Typography>\r\n <DownloadButton href={this.mergeConfigs.downloadSampleUrl}>\r\n <span> Download sample</span>\r\n <DownloadIcon fontSize='small' />\r\n </DownloadButton>\r\n </Box>\r\n )}\r\n {this.mergeConfigs.subText && (\r\n <Typography variant='body2' component='span' sx={{ display: 'block', mb: 1 }}>\r\n {this.mergeConfigs.subText}\r\n </Typography>\r\n )}\r\n <input hidden name={this.props.name?.toString()} type='text' ref={(ref) => (this.refInput = ref)} defaultValue='' />\r\n <TextField {...this.getTextFieldProps()} inputRef={(ref) => (this.refTextFiled = ref)} />\r\n </Box>\r\n )\r\n }\r\n\r\n getTextFieldProps = (): TextFieldProps => {\r\n const { label, name } = this.props\r\n const eMessage = getErrorMessage(this.mergeConfigs.messageErrors, this.mergeConfigs.name)\r\n const subName = params?.subName ? params.subName : `${name?.toString()}${params?.suffixName ?? '_file'}`\r\n const mergedProps: TextFieldProps = {\r\n label,\r\n error: eMessage.error,\r\n helperText: eMessage.message,\r\n name: name ? subName : undefined,\r\n type: 'file',\r\n variant: 'outlined',\r\n fullWidth: true,\r\n onChange: this.handleChange,\r\n inputProps: { accept: 'text/csv' },\r\n InputLabelProps: { shrink: this.mergeConfigs.labelShrink },\r\n ...this.mergeConfigs.textFieldProps\r\n }\r\n return mergedProps\r\n }\r\n\r\n upgradeMergeConfigs = (currentProps: IInputFileCsvLocalParserProps<T, C>): IMergeConfigs<T> => {\r\n const { name, label, onBlur, messageErrors } = currentProps\r\n return {\r\n textFieldProps: Object.assign({}, params?.textFieldProps, currentProps.slots?.textFieldProps),\r\n wrapProps: Object.assign({}, params?.wrapProps, currentProps.slots?.wrapProps),\r\n name: name as keyof T,\r\n onBlur: onBlur || (() => {}),\r\n messageErrors: messageErrors || {},\r\n downloadSampleUrl: currentProps.slots?.downloadSampleUrl ?? params?.downloadSampleUrl,\r\n titleText: currentProps.slots?.titleText ?? params?.titleText,\r\n subText: currentProps.slots?.subText ?? params?.subText,\r\n instructionalText: currentProps.slots?.instructionalText ?? params?.instructionalText,\r\n labelShrink: (currentProps.slots?.labelShrink ?? params?.labelShrink) !== false && !!label\r\n }\r\n }\r\n\r\n handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {\r\n const file = e.target.files?.[0]\r\n if (!file) return\r\n try {\r\n const result = await tryParseCsvFileToArray(file)\r\n if (this.refInput) this.refInput.value = JSON.stringify(result)\r\n this.setState({ parsedData: result as C[] }, () => {\r\n this.props.onChange && this.props.onChange(result as C[])\r\n this.mergeConfigs.onBlur(this.mergeConfigs.name)\r\n })\r\n } catch (err) {\r\n console.error('Error parsing CSV:', err)\r\n this.mergeConfigs.onBlur(this.mergeConfigs.name)\r\n }\r\n }\r\n }\r\n return InputFileCsvLocalParser\r\n}\r\n\r\nconst DownloadButton = styled((p: TypographyProps & { href: string }) => (\r\n <Typography variant='subtitle2' component='a' target='_blank' download {...p} />\r\n))(({ theme }) => ({\r\n display: 'flex',\r\n alignItems: 'center',\r\n color: theme.palette.primary.light,\r\n cursor: 'pointer',\r\n fontWeight: 600,\r\n marginLeft: '6px',\r\n gap: '4px',\r\n transition: 'all 0.3s ease',\r\n '&:hover': {\r\n textDecoration: 'underline',\r\n color: theme.palette.primary.dark\r\n }\r\n}))\r\n"],"names":["createInputFileCsvLocalParser","params","InputFileCsvLocalParser","props","_this","_classCallCheck","_callSuper","_defineProperty","name","onBlur","messageErrors","_params$suffixName","_this$props","label","eMessage","getErrorMessage","mergeConfigs","subName","concat","toString","suffixName","_objectSpread","error","helperText","message","undefined","type","variant","fullWidth","onChange","handleChange","inputProps","accept","InputLabelProps","shrink","labelShrink","textFieldProps","currentProps","_currentProps$slots","_currentProps$slots2","_currentProps$slots$d","_currentProps$slots3","_currentProps$slots$t","_currentProps$slots4","_currentProps$slots$s","_currentProps$slots5","_currentProps$slots$i","_currentProps$slots6","_currentProps$slots$l","_currentProps$slots7","Object","assign","slots","wrapProps","downloadSampleUrl","titleText","subText","instructionalText","_ref","_asyncToGenerator","_regenerator","m","_callee","e","_e$target$files","file","result","_t","w","_context","p","n","target","files","a","tryParseCsvFileToArray","v","refInput","value","JSON","stringify","setState","parsedData","console","_x","apply","this","arguments","mergeConfigsCache","upgradeMergeConfigs","state","_inherits","Component","_createClass","key","get","length","nextProps","_this$mergeConfigs$in","_this$props$name","_this2","_jsxs","Box","children","_jsx","Typography","component","sx","fontWeight","mb","display","alignItems","DownloadButton","href","DownloadIcon","fontSize","hidden","ref","defaultValue","TextField","getTextFieldProps","inputRef","refTextFiled","styled","download","_ref3","theme","color","palette","primary","light","cursor","marginLeft","gap","transition","textDecoration","dark"],"mappings":"qkBA+EM,SAAUA,EAAoCC,GAAuC,IACnFC,aAEJ,SAAAA,EAAYC,GAA0C,IAAAC,EAGrB,OAHqBC,OAAAH,GACpDE,EAAAE,EAAAJ,KAAAA,GAAMC,IAAMI,EAAAH,EAFgC,oBAAA,CAAEI,KAAM,GAAeC,OAAQ,WAAQ,EAAEC,cAAe,CAAA,IAAIH,EAAAH,EAAA,WAoBtE,MAAIG,EAAAH,EAAA,eACA,MAAIG,EAAAH,EAAA,oBA+BxB,WAAqB,IAAAO,EACvCC,EAAwBR,EAAKD,MAArBU,EAAKD,EAALC,MAAOL,EAAII,EAAJJ,KACTM,EAAWC,EAAgBX,EAAKY,aAAaN,cAAeN,EAAKY,aAAaR,MAC9ES,EAAUhB,SAAAA,EAAQgB,QAAUhB,EAAOgB,QAAOC,GAAAA,OAAMV,aAAAA,EAAAA,EAAMW,YAAUD,OAAqBP,QAArBA,EAAGV,eAAAA,EAAQmB,sBAAUT,EAAAA,EAAI,SAc/F,OAbiBU,EAAA,CACfR,MAAAA,EACAS,MAAOR,EAASQ,MAChBC,WAAYT,EAASU,QACrBhB,KAAMA,EAAOS,OAAUQ,EACvBC,KAAM,OACNC,QAAS,WACTC,WAAW,EACXC,SAAUzB,EAAK0B,aACfC,WAAY,CAAEC,OAAQ,YACtBC,gBAAiB,CAAEC,OAAQ9B,EAAKY,aAAamB,cAC1C/B,EAAKY,aAAaoB,kBAGxB7B,EAAAH,EAEqB,sBAAA,SAACiC,GAAuE,IAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EACpFzC,EAAuC6B,EAAvC7B,KAAMK,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,GAAA,CAAEC,SAAU,SAACJ,GAAG,OAAMjB,EAAKsB,aAAeL,CAAG,QAG1F,IAAC,IAsDH,OAAOnH,CACT,CAEA,IAAM8G,EAAiBW,EAAO,SAACrD,GAAqC,OAClEkC,EAACC,EAAUpF,EAAA,CAACM,QAAQ,YAAY+E,UAAU,IAAIlC,OAAO,SAASoD,UAAQ,GAAKtD,GAAK,EAD3DqD,CAEpB,SAAAE,GAAA,IAAGC,EAAKD,EAALC,MAAK,MAAQ,CACjBhB,QAAS,OACTC,WAAY,SACZgB,MAAOD,EAAME,QAAQC,QAAQC,MAC7BC,OAAQ,UACRvB,WAAY,IACZwB,WAAY,MACZC,IAAK,MACLC,WAAY,gBACZ,UAAW,CACTC,eAAgB,YAChBR,MAAOD,EAAME,QAAQC,QAAQO,MAEhC"}
|
|
1
|
+
{"version":3,"file":"create.input-file.csv-local-parser.js","sources":["../../../src/form/create.input-file.csv-local-parser.tsx"],"sourcesContent":["import React, { Component, ComponentType } from 'react'\r\nimport { Box, BoxProps, styled, TextField, TextFieldProps, Typography, TypographyProps } from '@mui/material'\r\nimport DownloadIcon from '@mui/icons-material/Download'\r\nimport { getErrorMessage } from './helpers'\r\nimport { tryParseCsvFileToArray } from '../utils'\r\nimport { IFormBase, IFormInputBase } from './types'\r\n\r\nexport interface IInputFileCsvLocalParserSlots {\r\n /**\r\n * The URL of the sample CSV file that users can download.\r\n * If provided, a \"Download sample\" link will be displayed.\r\n * Example: '/sample.csv' or 'https://example.com/sample.csv'\r\n */\r\n downloadSampleUrl?: string\r\n /**\r\n * Instructional text displayed alongside the download link or file input.\r\n * Useful for guiding users on how to use or fill out the CSV file.\r\n */\r\n instructionalText?: string\r\n /**\r\n * The title text displayed at the top.\r\n */\r\n titleText?: string\r\n /**\r\n * Optional sub text displayed below the title or above the download link.\r\n */\r\n subText?: string\r\n /**\r\n * Props to customize the TextField used for uploading the CSV file.\r\n * Allows customization of appearance and behavior (e.g., placeholder, onChange, disabled).\r\n */\r\n textFieldProps?: TextFieldProps\r\n /**\r\n * Props passed to the wrapper element (typically a Box).\r\n * Useful for customizing layout styles such as margin, padding, or display.\r\n */\r\n wrapProps?: BoxProps\r\n /**\r\n * Whether the label should shrink when displayed.\r\n * Defaults to `true` if a label is present to prevent overlap.\r\n * @default true\r\n */\r\n labelShrink?: boolean\r\n}\r\n\r\nexport interface IInputFileCsvLocalParserParams extends IInputFileCsvLocalParserSlots {\r\n /** Optional sub name for the input field. */\r\n subName?: string\r\n /**\r\n * Optional suffix name for the input field. When `subName` is provided, `suffixName` will be not used.\r\n * @default '_file'\r\n * */\r\n suffixName?: string\r\n}\r\n\r\nexport interface IInputFileCsvLocalParserProps<T, C> extends IFormInputBase<T, IInputFileCsvLocalParserSlots> {\r\n onChange?: (value: C[]) => void\r\n}\r\n\r\nexport interface IInputFileCsvLocalParserState<C> {\r\n parsedData: C[]\r\n}\r\n\r\ntype IPickConfigs<T> = Required<Pick<IFormBase<T>, 'onBlur' | 'messageErrors'>>\r\n\r\ninterface IMergeConfigs<T> extends IPickConfigs<T>, IInputFileCsvLocalParserSlots {\r\n name: keyof T\r\n}\r\n\r\n/**\r\n * Creates a React component that renders a file input specifically for CSV files,\r\n * parses the selected file locally into a structured array, and integrates with a form system.\r\n *\r\n * @template T - The main data model used in the form. Represents the shape of the overall form data.\r\n * @template C - The type of each individual item parsed from the CSV file.\r\n *\r\n * @param params - Optional slot parameters to customize the appearance or behavior of the text field.\r\n * @returns A React component configured for uploading and parsing local CSV files.\r\n */\r\nexport function createInputFileCsvLocalParser<T, C>(params?: IInputFileCsvLocalParserParams): ComponentType<IInputFileCsvLocalParserProps<T, C>> {\r\n class InputFileCsvLocalParser extends Component<IInputFileCsvLocalParserProps<T, C>, IInputFileCsvLocalParserState<C>> {\r\n private mergeConfigsCache: IMergeConfigs<T> = { name: '' as keyof T, onBlur: () => {}, messageErrors: {} }\r\n constructor(props: IInputFileCsvLocalParserProps<T, C>) {\r\n super(props)\r\n this.mergeConfigsCache = this.upgradeMergeConfigs(props)\r\n this.state = { parsedData: [] }\r\n }\r\n\r\n get mergeConfigs(): IMergeConfigs<T> {\r\n return this.mergeConfigsCache\r\n }\r\n\r\n get inputValue() {\r\n return this.state.parsedData.length > 0 ? JSON.stringify(this.state.parsedData) : ''\r\n }\r\n\r\n shouldComponentUpdate(nextProps: Readonly<IInputFileCsvLocalParserProps<T, C>>): boolean {\r\n if (nextProps !== this.props) this.mergeConfigsCache = this.upgradeMergeConfigs(nextProps)\r\n return true\r\n }\r\n\r\n refInput: HTMLInputElement | null = null\r\n refTextFiled: HTMLInputElement | null = null\r\n render() {\r\n return (\r\n <Box {...this.mergeConfigs.wrapProps}>\r\n {this.mergeConfigs.titleText && (\r\n <Typography variant='subtitle1' component='h6' sx={{ fontWeight: 600, mb: 0.5 }}>\r\n {this.mergeConfigs.titleText}\r\n </Typography>\r\n )}\r\n {this.mergeConfigs.downloadSampleUrl && (\r\n <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>\r\n <Typography variant='subtitle2' component='span'>\r\n {this.mergeConfigs.instructionalText ?? 'Metadata file, please fill out the form we provide.'}\r\n </Typography>\r\n <DownloadButton href={this.mergeConfigs.downloadSampleUrl}>\r\n <span> Download sample</span>\r\n <DownloadIcon fontSize='small' />\r\n </DownloadButton>\r\n </Box>\r\n )}\r\n {this.mergeConfigs.subText && (\r\n <Typography variant='body2' component='span' sx={{ display: 'block', mb: 1 }}>\r\n {this.mergeConfigs.subText}\r\n </Typography>\r\n )}\r\n <input hidden name={this.props.name?.toString()} type='text' ref={(ref) => (this.refInput = ref)} defaultValue='' />\r\n <TextField {...this.getTextFieldProps()} inputRef={(ref) => (this.refTextFiled = ref)} />\r\n </Box>\r\n )\r\n }\r\n\r\n getTextFieldProps = (): TextFieldProps => {\r\n const { label, name } = this.props\r\n const eMessage = getErrorMessage(this.mergeConfigs.messageErrors, this.mergeConfigs.name)\r\n const subName = params?.subName ? params.subName : `${name?.toString()}${params?.suffixName ?? '_file'}`\r\n const mergedProps: TextFieldProps = {\r\n label,\r\n error: eMessage.error,\r\n helperText: eMessage.message,\r\n name: name ? subName : undefined,\r\n type: 'file',\r\n variant: 'outlined',\r\n fullWidth: true,\r\n onChange: this.handleChange,\r\n inputProps: { accept: 'text/csv' },\r\n InputLabelProps: { shrink: this.mergeConfigs.labelShrink },\r\n ...this.mergeConfigs.textFieldProps\r\n }\r\n return mergedProps\r\n }\r\n\r\n upgradeMergeConfigs = (currentProps: IInputFileCsvLocalParserProps<T, C>): IMergeConfigs<T> => {\r\n const { name, label, onBlur, messageErrors } = currentProps\r\n return {\r\n textFieldProps: Object.assign({}, params?.textFieldProps, currentProps.slots?.textFieldProps),\r\n wrapProps: Object.assign({}, params?.wrapProps, currentProps.slots?.wrapProps),\r\n name: name as keyof T,\r\n onBlur: onBlur || (() => {}),\r\n messageErrors: messageErrors || {},\r\n downloadSampleUrl: currentProps.slots?.downloadSampleUrl ?? params?.downloadSampleUrl,\r\n titleText: currentProps.slots?.titleText ?? params?.titleText,\r\n subText: currentProps.slots?.subText ?? params?.subText,\r\n instructionalText: currentProps.slots?.instructionalText ?? params?.instructionalText,\r\n labelShrink: (currentProps.slots?.labelShrink ?? params?.labelShrink) !== false && !!label\r\n }\r\n }\r\n\r\n handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {\r\n const file = e.target.files?.[0]\r\n if (!file) return\r\n try {\r\n const result = await tryParseCsvFileToArray(file)\r\n if (this.refInput) this.refInput.value = JSON.stringify(result)\r\n this.setState({ parsedData: result as C[] }, () => {\r\n this.props.onChange && this.props.onChange(result as C[])\r\n this.mergeConfigs.onBlur(this.mergeConfigs.name)\r\n })\r\n } catch (err) {\r\n console.error('Error parsing CSV:', err)\r\n this.mergeConfigs.onBlur(this.mergeConfigs.name)\r\n }\r\n }\r\n }\r\n return InputFileCsvLocalParser\r\n}\r\n\r\nconst DownloadButton = styled((p: TypographyProps & { href: string }) => (\r\n <Typography variant='subtitle2' component='a' target='_blank' download {...p} />\r\n))(({ theme }) => ({\r\n display: 'flex',\r\n alignItems: 'center',\r\n color: theme.palette.primary.light,\r\n cursor: 'pointer',\r\n fontWeight: 600,\r\n marginLeft: '6px',\r\n gap: '4px',\r\n transition: 'all 0.3s ease',\r\n '&:hover': {\r\n textDecoration: 'underline',\r\n color: theme.palette.primary.dark\r\n }\r\n}))\r\n"],"names":["createInputFileCsvLocalParser","params","InputFileCsvLocalParser","props","_this","_classCallCheck","_callSuper","_defineProperty","name","onBlur","messageErrors","_params$suffixName","_this$props","label","eMessage","getErrorMessage","mergeConfigs","subName","concat","toString","suffixName","_objectSpread","error","helperText","message","undefined","type","variant","fullWidth","onChange","handleChange","inputProps","accept","InputLabelProps","shrink","labelShrink","textFieldProps","currentProps","_currentProps$slots","_currentProps$slots2","_currentProps$slots$d","_currentProps$slots3","_currentProps$slots$t","_currentProps$slots4","_currentProps$slots$s","_currentProps$slots5","_currentProps$slots$i","_currentProps$slots6","_currentProps$slots$l","_currentProps$slots7","Object","assign","slots","wrapProps","downloadSampleUrl","titleText","subText","instructionalText","_ref","_asyncToGenerator","_regenerator","m","_callee","e","_e$target$files","file","result","_t","w","_context","p","n","target","files","a","tryParseCsvFileToArray","v","refInput","value","JSON","stringify","setState","parsedData","console","_x","apply","this","arguments","mergeConfigsCache","upgradeMergeConfigs","state","_inherits","Component","_createClass","key","get","length","nextProps","_this$mergeConfigs$in","_this$props$name","_this2","_jsxs","Box","children","_jsx","Typography","component","sx","fontWeight","mb","display","alignItems","DownloadButton","href","DownloadIcon","fontSize","hidden","ref","defaultValue","TextField","getTextFieldProps","inputRef","refTextFiled","styled","download","_ref3","theme","color","palette","primary","light","cursor","marginLeft","gap","transition","textDecoration","dark"],"mappings":"ogBA+EM,SAAUA,EAAoCC,GAAuC,IACnFC,aAEJ,SAAAA,EAAYC,GAA0C,IAAAC,EAGrB,OAHqBC,OAAAH,GACpDE,EAAAE,EAAAJ,KAAAA,GAAMC,IAAMI,EAAAH,EAFgC,oBAAA,CAAEI,KAAM,GA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Q,UACRvB,WAAY,IACZwB,WAAY,MACZC,IAAK,MACLC,WAAY,gBACZ,UAAW,CACTC,eAAgB,YAChBR,MAAOD,EAAME,QAAQC,QAAQO,MAEhC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{inherits as e,createClass as t,objectSpread2 as r,classCallCheck as o,callSuper as a,defineProperty as l,objectWithoutProperties as
|
|
1
|
+
import{inherits as e,createClass as t,objectSpread2 as r,classCallCheck as o,callSuper as a,defineProperty as l,objectWithoutProperties as n,asyncToGenerator as i,regenerator as s}from"../../_virtual/_rollupPluginBabelHelpers.js";import{jsxs as u,jsx as p,Fragment as d}from"react/jsx-runtime";import{Component as c}from"react";import{styled as m,Box as h,TextField as v,InputAdornment as f,IconButton as g,Collapse as b,CircularProgress as x}from"@mui/material";import S from"@mui/icons-material/ContentPaste";import{getErrorMessage as k}from"./helpers.js";import{ImageWithFallback as P}from"../components/image-with-fallback.js";import{RichTooltip as y,HelpOutlinePulseIcon as L}from"../components/rich-tooltip.js";import{mergeObjects as j}from"../utils/helpers.js";var C=["src","element","alt","fallbackSrc","debounceDelay"],I=function(m){return function(){function x(e){var t,c;return o(this,x),c=a(this,x,[e]),l(c,"_cachedSlots",{}),l(c,"mapTextFieldProps",function(){var e,t,o,a,l=k(c.props.messageErrors,c.props.name),n={fullWidth:!0,variant:"outlined",name:null===(e=c.props.name)||void 0===e?void 0:e.toString(),error:l.error,helperText:l.message,disabled:c.props.disabled,onBlur:function(){c.props.name&&c.props.onBlur&&c.props.onBlur(c.props.name)},label:c.getLabel(),placeholder:c.props.placeholder,InputLabelProps:c.state.value?{shrink:!0}:{},value:null!==(t=c.state.value)&&void 0!==t?t:"",onChange:c.handleChange};return n.InputProps||(n.InputProps={}),n.InputProps.endAdornment=u(f,{position:"end",children:[c.slots.pastenable&&p(g,{onClick:c.handlePaste,edge:"end",children:p(S,{})}),c.slots.tooltip&&p(y,{panel:c.slots.tooltip,children:p(L,{fontSize:"small"})})]}),null!==(o=c.slots)&&void 0!==o&&o.maxLength&&(n.inputProps=r(r({},n.inputProps),{},{maxLength:c.slots.maxLength})),j({},n,null===(a=c.slots)||void 0===a?void 0:a.textFieldProps)}),l(c,"renderImageSide",function(e){var t="left"===e?c.slots.imageLeft:c.slots.imageRight;if(!t)return p(d,{});var o=t.src,a=t.element,l=t.alt,i=void 0===l?"input-image":l,s=t.fallbackSrc,u=void 0===s?"":s,m=t.debounceDelay,h=void 0===m?700:m,v=n(t,C);if(a)return p(z,{children:p(a,{value:c.state.value,model:c.props.data})});var f="function"==typeof o?o(c.state.value,c.props.data):null!=o?o:c.state.value,g={src:f,alt:i,fallbackSrc:u,debounceDelay:h};return p(b,{sx:{mx:"10px"},in:!!f,unmountOnExit:!0,orientation:"horizontal",children:p(z,{children:p(P,r(r(r({},v),g),{},{loading:p(w,{})}))})})}),l(c,"mergeSlots",function(e){var t=j({},m,e),o=t.imageLeft,a=t.imageRight;return null!=o&&o.mirror&&!a?(t.imageRight=r({},o),delete t.imageRight.mirror):null!=a&&a.mirror&&!o&&(t.imageLeft=r({},a),delete t.imageLeft.mirror),t}),l(c,"getLabel",function(){var e,t,r;if(c.props.label)return null!==(e=c.slots)&&void 0!==e&&e.maxLength?"".concat(c.props.label," (").concat(null!==(t=null===(r=c.state.value)||void 0===r?void 0:r.length)&&void 0!==t?t:0,"/").concat(c.slots.maxLength,")"):c.props.label}),l(c,"handleChange",function(e){c.setState({value:e.target.value})}),l(c,"handlePaste",i(s().m(function e(){var t,r;return s().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,e.n=1,navigator.clipboard.readText();case 1:t=e.v,c.setState({value:t}),e.n=3;break;case 2:e.p=2,r=e.v,console.error("Error clipboard:",r);case 3:return e.a(2)}},e,null,[[0,2]])}))),c._cachedSlots=null!==(t=c.mergeSlots(e.slots))&&void 0!==t?t:{},c.state={value:c.defaulValue},c}return e(x,c),t(x,[{key:"slots",get:function(){return this._cachedSlots}},{key:"defaulValue",get:function(){var e,t,r=this.props,o=r.data,a=r.name;return null!==(e=o&&a?null===(t=o[a])||void 0===t?void 0:t.toString():void 0)&&void 0!==e?e:this.props.defaultValue}},{key:"componentDidUpdate",value:function(e){e.slots!==this.props.slots&&(this._cachedSlots=this.mergeSlots(this.props.slots))}},{key:"shouldComponentUpdate",value:function(e){var t=this.props,r=t.name;t.slots;if(r){var o,a,l,n,i=null!==(o=null===(a=this.props.data)||void 0===a||null===(a=a[r])||void 0===a?void 0:a.toString())&&void 0!==o?o:"",s=null!==(l=null===(n=e.data)||void 0===n||null===(n=n[r])||void 0===n?void 0:n.toString())&&void 0!==l?l:"";if(i!==s)return this.setState({value:s}),!1}return e.slots,!0}},{key:"render",value:function(){var e;return u(h,{sx:{display:"flex",alignItems:"flex-start"},children:[!!this.props.disabled&&p("input",{hidden:!0,name:null===(e=this.props.name)||void 0===e?void 0:e.toString(),defaultValue:this.defaulValue}),this.renderImageSide("left"),p(v,r({},this.mapTextFieldProps())),this.renderImageSide("right")]})}}])}()},w=function(){return p("div",{children:p(x,{size:24})})},z=m(h)({fontSize:"1rem",height:"var(--input-base-image-size, 54px)",width:"var(--input-base-image-size, 54px)",position:"relative",borderRadius:"8px",boxShadow:"rgba(0, 0, 0, 0.16) 0px 1px 4px",overflow:"hidden","& > img":{position:"absolute",top:0,left:0,backgroundRepeat:"no-repeat",height:"100%",width:"100%",backgroundSize:"contain"},"& > div":{position:"absolute",top:0,left:0,height:"100%",width:"100%",background:"#fafafa",zIndex:1,display:"flex",alignItems:"center",justifyContent:"center"}});export{I as default};
|
|
2
2
|
//# sourceMappingURL=create.input.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.input.js","sources":["../../../src/form/create.input.tsx"],"sourcesContent":["import React, { Component, ComponentType, FC } from 'react'\r\nimport { Box, CircularProgress, Collapse, IconButton, InputAdornment, styled, TextField, TextFieldProps } from '@mui/material'\r\nimport ContentPasteIcon from '@mui/icons-material/ContentPaste'\r\nimport { mergeObjects } from '../utils'\r\nimport { IFormInputBase } from './types'\r\nimport { getErrorMessage } from './helpers'\r\nimport { ImageWithFallback, IImageWithFallbackPropsOwner } from '../components/image-with-fallback'\r\nimport { IRichTooltipPanelConfig, RichTooltip, HelpOutlinePulseIcon } from '../components/rich-tooltip'\r\n\r\nexport interface InputBaseImage<T> extends Omit<Partial<IImageWithFallbackPropsOwner>, 'src'> {\r\n src?: string | ((value: any, model?: Partial<T>) => string | undefined)\r\n element?: React.ComponentType<{ value: any; model?: Partial<T> }>\r\n mirror?: boolean\r\n}\r\n\r\nexport interface IInputSlots<T> {\r\n maxLength?: number\r\n textFieldProps?: TextFieldProps\r\n pastenable?: boolean\r\n imageLeft?: InputBaseImage<T>\r\n imageRight?: InputBaseImage<T>\r\n tooltip?: IRichTooltipPanelConfig\r\n}\r\n\r\nexport interface IInputProps<T> extends IFormInputBase<T, IInputSlots<T>> {}\r\n\r\nexport interface IInputState {\r\n value?: string\r\n}\r\n\r\nexport interface IInputParams<T> extends IInputSlots<T> {}\r\n\r\nconst createInput = function <T>(params?: IInputParams<T>): ComponentType<IInputProps<T>> {\r\n class InputBase extends Component<IInputProps<T>, IInputState> {\r\n private _cachedSlots: IInputSlots<T> = {}\r\n constructor(props: IInputProps<T>) {\r\n super(props)\r\n this._cachedSlots = this.mergeSlots(props.slots) ?? {}\r\n this.state = { value: this.defaulValue }\r\n }\r\n\r\n get slots() {\r\n return this._cachedSlots\r\n }\r\n\r\n get defaulValue(): string {\r\n const { data, name } = this.props\r\n return (!!data && !!name ? data[name]?.toString() : undefined) ?? this.props.defaultValue\r\n }\r\n\r\n componentDidUpdate(prevProps: IInputProps<T>) {\r\n if (prevProps.slots !== this.props.slots) {\r\n this._cachedSlots = this.mergeSlots(this.props.slots)\r\n }\r\n }\r\n\r\n shouldComponentUpdate(nextProps: Readonly<IInputProps<T>>): boolean {\r\n const { name, slots } = this.props\r\n if (!!name) {\r\n const currentDataValue = this.props.data?.[name]?.toString() ?? ''\r\n const nextDataValue = nextProps.data?.[name]?.toString() ?? ''\r\n if (currentDataValue !== nextDataValue) {\r\n this.setState({ value: nextDataValue })\r\n return false\r\n }\r\n }\r\n\r\n if (slots !== nextProps.slots) {\r\n return true\r\n }\r\n return true\r\n }\r\n\r\n mapTextFieldProps = (): TextFieldProps => {\r\n const errorMessage = getErrorMessage(this.props.messageErrors, this.props.name)\r\n const tfp: TextFieldProps = {\r\n fullWidth: true,\r\n variant: 'outlined',\r\n name: this.props.name?.toString(),\r\n error: errorMessage.error,\r\n helperText: errorMessage.message,\r\n disabled: this.props.disabled,\r\n onBlur: () => {\r\n if (!this.props.name) return\r\n this.props.onBlur && this.props.onBlur(this.props.name)\r\n },\r\n label: this.getLabel(),\r\n placeholder: this.props.placeholder,\r\n InputLabelProps: !!this.state.value ? { shrink: true } : {},\r\n value: this.state.value ?? '',\r\n onChange: this.handleChange\r\n }\r\n if (!tfp.InputProps) tfp.InputProps = {}\r\n tfp.InputProps.endAdornment = (\r\n <InputAdornment position='end'>\r\n {this.slots.pastenable && (\r\n <IconButton onClick={this.handlePaste} edge='end'>\r\n <ContentPasteIcon />\r\n </IconButton>\r\n )}\r\n {this.slots.tooltip && (\r\n <RichTooltip panel={this.slots.tooltip}>\r\n <HelpOutlinePulseIcon fontSize='small' />\r\n </RichTooltip>\r\n )}\r\n </InputAdornment>\r\n )\r\n if (this.slots?.maxLength) tfp.inputProps = { ...tfp.inputProps, maxLength: this.slots.maxLength }\r\n return mergeObjects<TextFieldProps>({}, tfp, this.slots?.textFieldProps)\r\n }\r\n\r\n //#region Render\r\n render() {\r\n return (\r\n <Box sx={{ display: 'flex', alignItems: 'flex-start' }}>\r\n {!!this.props.disabled && <input hidden name={this.props.name?.toString()} defaultValue={this.defaulValue} />}\r\n {this.renderImageSide('left')}\r\n <TextField {...this.mapTextFieldProps()} />\r\n {this.renderImageSide('right')}\r\n </Box>\r\n )\r\n }\r\n\r\n renderImageSide = (side: 'left' | 'right') => {\r\n const image = side === 'left' ? this.slots.imageLeft : this.slots.imageRight\r\n if (!image) return <></>\r\n const { src, element, alt = 'input-image', fallbackSrc = '', debounceDelay = 700, ...imageOther } = image\r\n if (element) {\r\n const Element = element\r\n return (\r\n <WrapImage>\r\n <Element value={this.state.value} model={this.props.data} />\r\n </WrapImage>\r\n )\r\n }\r\n const finalSrc = typeof src === 'function' ? src(this.state.value, this.props.data) : (src ?? this.state.value)\r\n const imageProps: IImageWithFallbackPropsOwner = { src: finalSrc, alt, fallbackSrc, debounceDelay }\r\n return (\r\n <Collapse sx={{ mx: '10px' }} in={!!finalSrc} unmountOnExit orientation='horizontal'>\r\n <WrapImage>\r\n <ImageWithFallback {...imageOther} {...imageProps} loading={<LoadingCircularProgress />} />\r\n </WrapImage>\r\n </Collapse>\r\n )\r\n }\r\n //#endregion\r\n\r\n private mergeSlots = (currentSlots?: IInputSlots<T>): IInputSlots<T> => {\r\n const base = mergeObjects<IInputSlots<T>>({}, params, currentSlots)\r\n const { imageLeft, imageRight } = base\r\n\r\n // mirror from left to right\r\n if (imageLeft?.mirror && !imageRight) {\r\n base.imageRight = { ...imageLeft }\r\n delete base.imageRight.mirror\r\n }\r\n // mirror from right to left\r\n else if (imageRight?.mirror && !imageLeft) {\r\n base.imageLeft = { ...imageRight }\r\n delete base.imageLeft.mirror\r\n }\r\n\r\n return base\r\n }\r\n\r\n getLabel = () => {\r\n if (!this.props.label) return\r\n if (!this.slots?.maxLength) return this.props.label\r\n return `${this.props.label} (${this.state.value?.length ?? 0}/${this.slots.maxLength})`\r\n }\r\n\r\n handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {\r\n this.setState({ value: event.target.value })\r\n }\r\n\r\n handlePaste = async () => {\r\n try {\r\n const clipboardText = await navigator.clipboard.readText()\r\n this.setState({ value: clipboardText })\r\n } catch (error) {\r\n console.error('Error clipboard:', error)\r\n }\r\n }\r\n }\r\n return InputBase\r\n}\r\n\r\nexport default createInput\r\n\r\n// export type InputTextType<T> = ReturnType<typeof CreateInputBase<T>>\r\n\r\nconst LoadingCircularProgress: FC = () => (\r\n <div>\r\n <CircularProgress size={24} />\r\n </div>\r\n)\r\n\r\nconst WrapImage = styled(Box)({\r\n fontSize: '1rem',\r\n height: 'var(--input-base-image-size, 54px)',\r\n width: 'var(--input-base-image-size, 54px)',\r\n position: 'relative',\r\n borderRadius: '8px',\r\n boxShadow: 'rgba(0, 0, 0, 0.16) 0px 1px 4px',\r\n overflow: 'hidden',\r\n '& > img': {\r\n position: 'absolute',\r\n top: 0,\r\n left: 0,\r\n backgroundRepeat: 'no-repeat',\r\n height: '100%',\r\n width: '100%',\r\n backgroundSize: 'contain'\r\n },\r\n '& > div': {\r\n position: 'absolute',\r\n top: 0,\r\n left: 0,\r\n height: '100%',\r\n width: '100%',\r\n background: '#fafafa',\r\n zIndex: 1,\r\n display: 'flex',\r\n alignItems: 'center',\r\n justifyContent: 'center'\r\n }\r\n})\r\n"],"names":["createInput","params","InputBase","props","_this$mergeSlots","_this","_classCallCheck","_callSuper","_defineProperty","_this$props$name","_this$state$value","_this$slots","_this$slots2","errorMessage","getErrorMessage","messageErrors","name","tfp","fullWidth","variant","toString","error","helperText","message","disabled","onBlur","label","getLabel","placeholder","InputLabelProps","state","value","shrink","onChange","handleChange","InputProps","endAdornment","_jsxs","InputAdornment","position","children","slots","pastenable","_jsx","IconButton","onClick","handlePaste","edge","ContentPasteIcon","tooltip","RichTooltip","panel","HelpOutlinePulseIcon","fontSize","maxLength","inputProps","_objectSpread","mergeObjects","textFieldProps","side","image","imageLeft","imageRight","src","element","_image$alt","alt","_image$fallbackSrc","fallbackSrc","_image$debounceDelay","debounceDelay","imageOther","_objectWithoutProperties","_excluded","WrapImage","model","data","finalSrc","imageProps","Collapse","sx","mx","in","unmountOnExit","orientation","ImageWithFallback","loading","LoadingCircularProgress","currentSlots","base","mirror","_this$slots3","_this$state$value$len","_this$state$value2","concat","length","event","setState","target","_asyncToGenerator","_regenerator","m","_callee","clipboardText","_t","w","_context","p","n","navigator","clipboard","readText","v","console","a","_cachedSlots","mergeSlots","defaulValue","_inherits","Component","_createClass","key","get","this","_ref2","_data$name","_this$props","undefined","defaultValue","prevProps","nextProps","_this$props2","_this$props$data$name","_this$props$data","_nextProps$data$name$","_nextProps$data","currentDataValue","nextDataValue","_this$props$name2","Box","display","alignItems","hidden","renderImageSide","TextField","mapTextFieldProps","CircularProgress","size","styled","height","width","borderRadius","boxShadow","overflow","top","left","backgroundRepeat","backgroundSize","background","zIndex","justifyContent"],"mappings":"63BAgCMA,EAAc,SAAaC,GAwJ/B,kBArJE,SAAAC,EAAYC,GAAqB,IAAAC,EAAAC,EAGS,OAHTC,OAAAJ,GAC/BG,EAAAE,EAAAL,KAAAA,GAAMC,IAAMK,EAAAH,EAFyB,eAAA,IAAEG,EAAAH,EAAA,oBAuCrB,WAAqB,IAAAI,EAAAC,EAAAC,EAAAC,EACjCC,EAAeC,EAAgBT,EAAKF,MAAMY,cAAeV,EAAKF,MAAMa,MACpEC,EAAsB,CAC1BC,WAAW,EACXC,QAAS,WACTH,KAAqB,QAAjBP,EAAEJ,EAAKF,MAAMa,YAAXP,IAAeA,OAAfA,EAAAA,EAAiBW,WACvBC,MAAOR,EAAaQ,MACpBC,WAAYT,EAAaU,QACzBC,SAAUnB,EAAKF,MAAMqB,SACrBC,OAAQ,WACDpB,EAAKF,MAAMa,MAChBX,EAAKF,MAAMsB,QAAUpB,EAAKF,MAAMsB,OAAOpB,EAAKF,MAAMa,KACnD,EACDU,MAAOrB,EAAKsB,WACZC,YAAavB,EAAKF,MAAMyB,YACxBC,gBAAmBxB,EAAKyB,MAAMC,MAAQ,CAAEC,QAAQ,GAAS,CAAE,EAC3DD,MAAuBrB,QAAlBA,EAAEL,EAAKyB,MAAMC,aAAKrB,IAAAA,EAAAA,EAAI,GAC3BuB,SAAU5B,EAAK6B,cAkBjB,OAhBKjB,EAAIkB,aAAYlB,EAAIkB,WAAa,CAAE,GACxClB,EAAIkB,WAAWC,aACbC,EAACC,EAAc,CAACC,SAAS,MAAKC,SAAA,CA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WAAY,UACZC,OAAQ,EACRnB,QAAS,OACTC,WAAY,SACZmB,eAAgB"}
|
|
1
|
+
{"version":3,"file":"create.input.js","sources":["../../../src/form/create.input.tsx"],"sourcesContent":["import React, { Component, ComponentType, FC } from 'react'\r\nimport { Box, CircularProgress, Collapse, IconButton, InputAdornment, styled, TextField, TextFieldProps } from '@mui/material'\r\nimport ContentPasteIcon from '@mui/icons-material/ContentPaste'\r\nimport { mergeObjects } from '../utils'\r\nimport { IFormInputBase } from './types'\r\nimport { getErrorMessage } from './helpers'\r\nimport { ImageWithFallback, IImageWithFallbackPropsOwner } from '../components/image-with-fallback'\r\nimport { IRichTooltipPanelConfig, RichTooltip, HelpOutlinePulseIcon } from '../components/rich-tooltip'\r\n\r\nexport interface InputBaseImage<T> extends Omit<Partial<IImageWithFallbackPropsOwner>, 'src'> {\r\n src?: string | ((value: any, model?: Partial<T>) => string | undefined)\r\n element?: React.ComponentType<{ value: any; model?: Partial<T> }>\r\n mirror?: boolean\r\n}\r\n\r\nexport interface IInputSlots<T> {\r\n maxLength?: number\r\n textFieldProps?: TextFieldProps\r\n pastenable?: boolean\r\n imageLeft?: InputBaseImage<T>\r\n imageRight?: InputBaseImage<T>\r\n tooltip?: IRichTooltipPanelConfig\r\n}\r\n\r\nexport interface IInputProps<T> extends IFormInputBase<T, IInputSlots<T>> {}\r\n\r\nexport interface IInputState {\r\n value?: string\r\n}\r\n\r\nexport interface IInputParams<T> extends IInputSlots<T> {}\r\n\r\nconst createInput = function <T>(params?: IInputParams<T>): ComponentType<IInputProps<T>> {\r\n class InputBase extends Component<IInputProps<T>, IInputState> {\r\n private _cachedSlots: IInputSlots<T> = {}\r\n constructor(props: IInputProps<T>) {\r\n super(props)\r\n this._cachedSlots = this.mergeSlots(props.slots) ?? {}\r\n this.state = { value: this.defaulValue }\r\n }\r\n\r\n get slots() {\r\n return this._cachedSlots\r\n }\r\n\r\n get defaulValue(): string {\r\n const { data, name } = this.props\r\n return (!!data && !!name ? data[name]?.toString() : undefined) ?? this.props.defaultValue\r\n }\r\n\r\n componentDidUpdate(prevProps: IInputProps<T>) {\r\n if (prevProps.slots !== this.props.slots) {\r\n this._cachedSlots = this.mergeSlots(this.props.slots)\r\n }\r\n }\r\n\r\n shouldComponentUpdate(nextProps: Readonly<IInputProps<T>>): boolean {\r\n const { name, slots } = this.props\r\n if (!!name) {\r\n const currentDataValue = this.props.data?.[name]?.toString() ?? ''\r\n const nextDataValue = nextProps.data?.[name]?.toString() ?? ''\r\n if (currentDataValue !== nextDataValue) {\r\n this.setState({ value: nextDataValue })\r\n return false\r\n }\r\n }\r\n\r\n if (slots !== nextProps.slots) {\r\n return true\r\n }\r\n return true\r\n }\r\n\r\n mapTextFieldProps = (): TextFieldProps => {\r\n const errorMessage = getErrorMessage(this.props.messageErrors, this.props.name)\r\n const tfp: TextFieldProps = {\r\n fullWidth: true,\r\n variant: 'outlined',\r\n name: this.props.name?.toString(),\r\n error: errorMessage.error,\r\n helperText: errorMessage.message,\r\n disabled: this.props.disabled,\r\n onBlur: () => {\r\n if (!this.props.name) return\r\n this.props.onBlur && this.props.onBlur(this.props.name)\r\n },\r\n label: this.getLabel(),\r\n placeholder: this.props.placeholder,\r\n InputLabelProps: !!this.state.value ? { shrink: true } : {},\r\n value: this.state.value ?? '',\r\n onChange: this.handleChange\r\n }\r\n if (!tfp.InputProps) tfp.InputProps = {}\r\n tfp.InputProps.endAdornment = (\r\n <InputAdornment position='end'>\r\n {this.slots.pastenable && (\r\n <IconButton onClick={this.handlePaste} edge='end'>\r\n <ContentPasteIcon />\r\n </IconButton>\r\n )}\r\n {this.slots.tooltip && (\r\n <RichTooltip panel={this.slots.tooltip}>\r\n <HelpOutlinePulseIcon fontSize='small' />\r\n </RichTooltip>\r\n )}\r\n </InputAdornment>\r\n )\r\n if (this.slots?.maxLength) tfp.inputProps = { ...tfp.inputProps, maxLength: this.slots.maxLength }\r\n return mergeObjects<TextFieldProps>({}, tfp, this.slots?.textFieldProps)\r\n }\r\n\r\n //#region Render\r\n render() {\r\n return (\r\n <Box sx={{ display: 'flex', alignItems: 'flex-start' }}>\r\n {!!this.props.disabled && <input hidden name={this.props.name?.toString()} defaultValue={this.defaulValue} />}\r\n {this.renderImageSide('left')}\r\n <TextField {...this.mapTextFieldProps()} />\r\n {this.renderImageSide('right')}\r\n </Box>\r\n )\r\n }\r\n\r\n renderImageSide = (side: 'left' | 'right') => {\r\n const image = side === 'left' ? this.slots.imageLeft : this.slots.imageRight\r\n if (!image) return <></>\r\n const { src, element, alt = 'input-image', fallbackSrc = '', debounceDelay = 700, ...imageOther } = image\r\n if (element) {\r\n const Element = element\r\n return (\r\n <WrapImage>\r\n <Element value={this.state.value} model={this.props.data} />\r\n </WrapImage>\r\n )\r\n }\r\n const finalSrc = typeof src === 'function' ? src(this.state.value, this.props.data) : (src ?? this.state.value)\r\n const imageProps: IImageWithFallbackPropsOwner = { src: finalSrc, alt, fallbackSrc, debounceDelay }\r\n return (\r\n <Collapse sx={{ mx: '10px' }} in={!!finalSrc} unmountOnExit orientation='horizontal'>\r\n <WrapImage>\r\n <ImageWithFallback {...imageOther} {...imageProps} loading={<LoadingCircularProgress />} />\r\n </WrapImage>\r\n </Collapse>\r\n )\r\n }\r\n //#endregion\r\n\r\n private mergeSlots = (currentSlots?: IInputSlots<T>): IInputSlots<T> => {\r\n const base = mergeObjects<IInputSlots<T>>({}, params, currentSlots)\r\n const { imageLeft, imageRight } = base\r\n\r\n // mirror from left to right\r\n if (imageLeft?.mirror && !imageRight) {\r\n base.imageRight = { ...imageLeft }\r\n delete base.imageRight.mirror\r\n }\r\n // mirror from right to left\r\n else if (imageRight?.mirror && !imageLeft) {\r\n base.imageLeft = { ...imageRight }\r\n delete base.imageLeft.mirror\r\n }\r\n\r\n return base\r\n }\r\n\r\n getLabel = () => {\r\n if (!this.props.label) return\r\n if (!this.slots?.maxLength) return this.props.label\r\n return `${this.props.label} (${this.state.value?.length ?? 0}/${this.slots.maxLength})`\r\n }\r\n\r\n handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {\r\n this.setState({ value: event.target.value })\r\n }\r\n\r\n handlePaste = async () => {\r\n try {\r\n const clipboardText = await navigator.clipboard.readText()\r\n this.setState({ value: clipboardText })\r\n } catch (error) {\r\n console.error('Error clipboard:', error)\r\n }\r\n }\r\n }\r\n return InputBase\r\n}\r\n\r\nexport default createInput\r\n\r\n// export type InputTextType<T> = ReturnType<typeof CreateInputBase<T>>\r\n\r\nconst LoadingCircularProgress: FC = () => (\r\n <div>\r\n <CircularProgress size={24} />\r\n </div>\r\n)\r\n\r\nconst WrapImage = styled(Box)({\r\n fontSize: '1rem',\r\n height: 'var(--input-base-image-size, 54px)',\r\n width: 'var(--input-base-image-size, 54px)',\r\n position: 'relative',\r\n borderRadius: '8px',\r\n boxShadow: 'rgba(0, 0, 0, 0.16) 0px 1px 4px',\r\n overflow: 'hidden',\r\n '& > img': {\r\n position: 'absolute',\r\n top: 0,\r\n left: 0,\r\n backgroundRepeat: 'no-repeat',\r\n height: '100%',\r\n width: '100%',\r\n backgroundSize: 'contain'\r\n },\r\n '& > div': {\r\n position: 'absolute',\r\n top: 0,\r\n left: 0,\r\n height: '100%',\r\n width: '100%',\r\n background: '#fafafa',\r\n zIndex: 1,\r\n display: 'flex',\r\n alignItems: 'center',\r\n justifyContent: 'center'\r\n }\r\n})\r\n"],"names":["createInput","params","InputBase","props","_this$mergeSlots","_this","_classCallCheck","_callSuper","_defineProperty","_this$props$name","_this$state$value","_this$slots","_this$slots2","errorMessage","getErrorMessage","messageErrors","name","tfp","fullWidth","variant","toString","error","helperText","message","disabled","onBlur","label","getLabel","placeholder","InputLabelProps","state","value","shrink","onChange","handleChange","InputProps","endAdornment","_jsxs","InputAdornment","position","children","slots","pastenable","_jsx","IconButton","onClick","handlePaste","edge","ContentPasteIcon","tooltip","RichTooltip","panel","HelpOutlinePulseIcon","fontSize","maxLength","inputProps","_objectSpread","mergeObjects","textFieldProps","side","image","imageLeft","imageRight","src","element","_image$alt","alt","_image$fallbackSrc","fallbackSrc","_image$debounceDelay","debounceDelay","imageOther","_objectWithoutProperties","_excluded","WrapImage","model","data","finalSrc","imageProps","Collapse","sx","mx","in","unmountOnExit","orientation","ImageWithFallback","loading","LoadingCircularProgress","currentSlots","base","mirror","_this$slots3","_this$state$value$len","_this$state$value2","concat","length","event","setState","target","_asyncToGenerator","_regenerator","m","_callee","clipboardText","_t","w","_context","p","n","navigator","clipboard","readText","v","console","a","_cachedSlots","mergeSlots","defaulValue","_inherits","Component","_createClass","key","get","this","_ref2","_data$name","_this$props","undefined","defaultValue","prevProps","nextProps","_this$props2","_this$props$data$name","_this$props$data","_nextProps$data$name$","_nextProps$data","currentDataValue","nextDataValue","_this$props$name2","Box","display","alignItems","hidden","renderImageSide","TextField","mapTextFieldProps","CircularProgress","size","styled","height","width","borderRadius","boxShadow","overflow","top","left","backgroundRepeat","backgroundSize","background","zIndex","justifyContent"],"mappings":"4zBAgCMA,EAAc,SAAaC,GAwJ/B,kBArJE,SAAAC,EAAYC,GAAqB,IAAAC,EAAAC,EAGS,OAHTC,OAAAJ,GAC/BG,EAAAE,EAAAL,KAAAA,GAAMC,IAAMK,EAAAH,EAFyB,eAAA,IAAEG,EAAAH,EAAA,oBAuCrB,WAAqB,IAAAI,EAAAC,EAAAC,EAAAC,EACjCC,EAAeC,EAAgBT,EAAKF,MAAMY,cAAeV,EAAKF,MAAMa,MACpEC,EAAsB,CAC1BC,WAAW,EACXC,QAAS,WACTH,KAAqB,QAAjBP,EAAEJ,EAAKF,MAAMa,YAAXP,IAAeA,OAAfA,EAAAA,EAAiBW,WACvBC,MAAOR,EAAaQ,MACpBC,WAAYT,EAAaU,QACzBC,SAAUnB,EAAKF,MAAMqB,SACrBC,OAAQ,WACDpB,EAAKF,MAAMa,MAChBX,EAAKF,MAAMsB,QAAUpB,EAAKF,MAAMsB,OAAOpB,EAAKF,MAAMa,KACnD,EACDU,MAAOrB,EAAKsB,WACZC,YAAavB,EAAKF,MAAMyB,YACxBC,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CAAY,CAC5B/F,SAAU,OACVgG,OAAQ,qCACRC,MAAO,qCACP/G,SAAU,WACVgH,aAAc,MACdC,UAAW,kCACXC,SAAU,SACV,UAAW,CACTlH,SAAU,WACVmH,IAAK,EACLC,KAAM,EACNC,iBAAkB,YAClBP,OAAQ,OACRC,MAAO,OACPO,eAAgB,WAElB,UAAW,CACTtH,SAAU,WACVmH,IAAK,EACLC,KAAM,EACNN,OAAQ,OACRC,MAAO,OACPQ,WAAY,UACZC,OAAQ,EACRnB,QAAS,OACTC,WAAY,SACZmB,eAAgB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{defineProperty as e,objectWithoutProperties as t,objectSpread2 as n,inherits as r,createClass as
|
|
1
|
+
import{defineProperty as e,objectWithoutProperties as t,objectSpread2 as n,inherits as r,createClass as l,classCallCheck as o,callSuper as i}from"../../_virtual/_rollupPluginBabelHelpers.js";import{jsx as s,jsxs as c}from"react/jsx-runtime";import{createRef as a,Component as u}from"react";import{styled as h,Box as p,IconButton as d,Typography as f,Tooltip as m}from"@mui/material";import g from"@mui/icons-material/Fullscreen";import v from"@mui/icons-material/FullscreenExit";import{getErrorMessage as x}from"./helpers.js";import F,{textEditorClasses as C}from"../components/text-editor.js";var y=["children"];function b(t){return function(){function n(t){var r;return o(this,n),r=i(this,n,[t]),e(r,"handleFullscreenChange",function(){r.setState({isFullscreen:!!document.fullscreenElement})}),e(r,"handleFullscreenToggle",function(){r.contentRef.current&&(document.fullscreenElement?document.exitFullscreen():r.contentRef.current.requestFullscreen().catch(function(e){console.error("Error attempting to enable full-screen mode: ".concat(e.message))}))}),e(r,"getWrapClasses",function(){var e=[];return r.state.isFullscreen&&e.push(C.fullscreen),e.join(" ")}),r.state={isFullscreen:!1},r.contentRef=a(),r}return r(n,u),l(n,[{key:"componentDidMount",value:function(){document.addEventListener("fullscreenchange",this.handleFullscreenChange)}},{key:"componentWillUnmount",value:function(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange)}},{key:"render",value:function(){var e,n,r,l,o,i=this,a=x(this.props.messageErrors,this.props.name),u=null!==(e=null===(n=this.props.name?null===(r=this.props.data)||void 0===r?void 0:r[this.props.name]:"")||void 0===n?void 0:n.toString())&&void 0!==e?e:"";return c(p,{id:t.id,ref:this.contentRef,sx:{backgroundColor:"#fff"},children:[this.state.isFullscreen&&s(j,{children:s(f,{variant:"h4",sx:{fontWeight:600,flex:1,textAlign:"center"},children:t.title})}),c(k,{className:this.getWrapClasses(),children:[s(E,{children:s(m,{title:this.state.isFullscreen?"Exit Fullscreen":"Fullscreen",arrow:!0,children:s(S,{sx:{color:"#06c"},onClick:this.handleFullscreenToggle,children:this.state.isFullscreen?s(v,{}):s(g,{})})})}),s(W,{children:s(F,{defautValue:u,name:null!==(l=null===(o=this.props.name)||void 0===o?void 0:o.toString())&&void 0!==l?l:"",readOnly:this.props.disabled,error:a.error,onBlur:function(){var e,t;i.props.name&&(null===(e=(t=i.props).onBlur)||void 0===e||e.call(t,i.props.name))}})})]})]})}}])}()}var k=h(p)(function(t){var n=t.theme;return e(e({maxWidth:n.breakpoints.values.xl,margin:"0 auto",position:"relative"},"&.".concat(C.fullscreen," .").concat(C.root),{height:"calc(100vh - ".concat(74,"px)")}),"&.".concat(C.fullscreen),{width:"871px"})}),j=h(p)({height:"".concat(64,"px"),display:"flex",justifyContent:"center",alignItems:"center"}),E=h(function(e){var r=e.children,l=t(e,y);return s(p,n(n({},l),{},{children:s(p,{children:r})}))})({position:"sticky",top:"-1px",zIndex:2,"& > div":{height:0,display:"flex",justifyContent:"right",padding:"0 6px"}}),S=h(d)({flex:"0 0 auto",marginTop:"1px",width:"40px",height:"40px"}),W=h(p)({backgroundColor:"#fff",width:"100%","& .ql-container":{fontFamily:'"Roboto", serif',fontSize:"14px"},"& .ql-toolbar":{position:"sticky",top:"-1px",backgroundColor:"#fff",zIndex:1}});export{b as default};
|
|
2
2
|
//# sourceMappingURL=create.text-editor.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.text-editor.js","sources":["../../../src/form/create.text-editor.tsx"],"sourcesContent":["import React, { Component, createRef } from 'react'\r\nimport { Box, BoxProps, IconButton, styled, Tooltip, Typography } from '@mui/material'\r\nimport FullscreenIcon from '@mui/icons-material/Fullscreen'\r\nimport FullscreenExitIcon from '@mui/icons-material/FullscreenExit'\r\nimport { IFormInputBase } from './types'\r\nimport { getErrorMessage } from './helpers'\r\nimport { TextEditor as TextEditorBase, textEditorClasses } from '../components'\r\n\r\nexport interface ITextEditorParams {\r\n id: string\r\n title: string\r\n}\r\n\r\nexport interface ITextEditorProps<T> extends IFormInputBase<T> {}\r\n\r\nexport interface ITextEditorState {\r\n isFullscreen: boolean\r\n}\r\n\r\nfunction CreateTextEditor<T>(params: ITextEditorParams) {\r\n class TextEditor extends Component<ITextEditorProps<T>, ITextEditorState> {\r\n contentRef\r\n constructor(props: ITextEditorProps<T>) {\r\n super(props)\r\n this.state = {\r\n isFullscreen: false\r\n }\r\n this.contentRef = createRef<HTMLDivElement | null>()\r\n }\r\n\r\n componentDidMount() {\r\n document.addEventListener('fullscreenchange', this.handleFullscreenChange)\r\n }\r\n\r\n componentWillUnmount() {\r\n document.removeEventListener('fullscreenchange', this.handleFullscreenChange)\r\n }\r\n\r\n handleFullscreenChange = () => {\r\n this.setState({ isFullscreen: !!document.fullscreenElement })\r\n }\r\n\r\n handleFullscreenToggle = () => {\r\n if (this.contentRef.current) {\r\n if (!document.fullscreenElement) {\r\n this.contentRef.current.requestFullscreen().catch((err) => {\r\n console.error(`Error attempting to enable full-screen mode: ${err.message}`)\r\n })\r\n } else {\r\n document.exitFullscreen()\r\n }\r\n }\r\n }\r\n\r\n getWrapClasses = () => {\r\n const classes = []\r\n if (this.state.isFullscreen) classes.push(textEditorClasses.fullscreen)\r\n return classes.join(' ')\r\n }\r\n\r\n render() {\r\n const errorMessage = getErrorMessage(this.props.messageErrors, this.props.name)\r\n const dValue = (this.props.name ? this.props.data?.[this.props.name] : '')?.toString() ?? ''\r\n\r\n return (\r\n <Box id={params.id} ref={this.contentRef} sx={{ backgroundColor: '#fff' }}>\r\n {this.state.isFullscreen && (\r\n <WrapTitle>\r\n <Typography variant='h4' sx={{ fontWeight: 600, flex: 1, textAlign: 'center' }}>\r\n {params.title}\r\n </Typography>\r\n </WrapTitle>\r\n )}\r\n <Wrap className={this.getWrapClasses()}>\r\n <WrapActions>\r\n <Tooltip title={this.state.isFullscreen ? 'Exit Fullscreen' : 'Fullscreen'} arrow>\r\n <CustomButton sx={{ color: '#06c' }} onClick={this.handleFullscreenToggle}>\r\n {this.state.isFullscreen ? <FullscreenExitIcon /> : <FullscreenIcon />}\r\n </CustomButton>\r\n </Tooltip>\r\n </WrapActions>\r\n <WrapTextEditor>\r\n <TextEditorBase\r\n defautValue={dValue}\r\n name={this.props.name?.toString() ?? ''}\r\n readOnly={this.props.disabled}\r\n error={errorMessage.error}\r\n onBlur={() => {\r\n if (!this.props.name) return\r\n this.props.onBlur?.(this.props.name)\r\n }}\r\n />\r\n </WrapTextEditor>\r\n </Wrap>\r\n </Box>\r\n )\r\n }\r\n }\r\n return TextEditor\r\n}\r\nexport default CreateTextEditor\r\n\r\nconst editorHeight = 64\r\n\r\nconst Wrap = styled(Box)(({ theme }) => ({\r\n maxWidth: theme.breakpoints.values.xl,\r\n margin: '0 auto',\r\n position: 'relative',\r\n [`&.${textEditorClasses.fullscreen} .${textEditorClasses.root}`]: {\r\n height: `calc(100vh - ${editorHeight + 10}px)`\r\n },\r\n [`&.${textEditorClasses.fullscreen}`]: {\r\n width: '871px'\r\n }\r\n}))\r\n\r\nconst WrapTitle = styled(Box)({\r\n height: `${editorHeight}px`,\r\n display: 'flex',\r\n justifyContent: 'center',\r\n alignItems: 'center'\r\n})\r\n\r\nconst WrapActions = styled(({ children, ...props }: BoxProps) => (\r\n <Box {...props}>\r\n <Box>{children}</Box>\r\n </Box>\r\n))({\r\n position: 'sticky',\r\n top: '-1px',\r\n zIndex: 2,\r\n '& > div': {\r\n height: 0,\r\n display: 'flex',\r\n justifyContent: 'right',\r\n padding: '0 6px'\r\n }\r\n})\r\n\r\nconst CustomButton = styled(IconButton)({\r\n flex: '0 0 auto',\r\n marginTop: '1px',\r\n width: '40px',\r\n height: '40px'\r\n})\r\n\r\nconst WrapTextEditor = styled(Box)({\r\n backgroundColor: '#fff',\r\n width: '100%',\r\n '& .ql-container': {\r\n fontFamily: '\"Roboto\", serif',\r\n fontSize: '14px'\r\n },\r\n '& .ql-toolbar': {\r\n position: 'sticky',\r\n top: '-1px',\r\n backgroundColor: '#fff',\r\n zIndex: 1\r\n }\r\n})\r\n"],"names":["CreateTextEditor","params","TextEditor","props","_this","_classCallCheck","_callSuper","_defineProperty","setState","isFullscreen","document","fullscreenElement","contentRef","current","exitFullscreen","requestFullscreen","err","console","error","concat","message","classes","state","push","textEditorClasses","fullscreen","join","createRef","_inherits","Component","_createClass","key","value","addEventListener","this","handleFullscreenChange","removeEventListener","_toString","_ref","_this$props$data","_this$props$name$toSt","_this$props$name","_this2","errorMessage","getErrorMessage","messageErrors","name","dValue","data","toString","_jsxs","Box","id","ref","sx","backgroundColor","children","_jsx","WrapTitle","Typography","variant","fontWeight","flex","textAlign","title","Wrap","className","getWrapClasses","WrapActions","Tooltip","arrow","CustomButton","color","onClick","handleFullscreenToggle","FullscreenExitIcon","FullscreenIcon","WrapTextEditor","TextEditorBase","defautValue","readOnly","disabled","onBlur","_this2$props$onBlur","_this2$props","call","styled","_ref2","theme","maxWidth","breakpoints","values","xl","margin","position","root","height","editorHeight","width","display","justifyContent","alignItems","_ref4","_objectWithoutProperties","_excluded","_objectSpread","top","zIndex","padding","IconButton","marginTop","fontFamily","fontSize"],"mappings":"
|
|
1
|
+
{"version":3,"file":"create.text-editor.js","sources":["../../../src/form/create.text-editor.tsx"],"sourcesContent":["import React, { Component, createRef } from 'react'\r\nimport { Box, BoxProps, IconButton, styled, Tooltip, Typography } from '@mui/material'\r\nimport FullscreenIcon from '@mui/icons-material/Fullscreen'\r\nimport FullscreenExitIcon from '@mui/icons-material/FullscreenExit'\r\nimport { IFormInputBase } from './types'\r\nimport { getErrorMessage } from './helpers'\r\nimport { TextEditor as TextEditorBase, textEditorClasses } from '../components'\r\n\r\nexport interface ITextEditorParams {\r\n id: string\r\n title: string\r\n}\r\n\r\nexport interface ITextEditorProps<T> extends IFormInputBase<T> {}\r\n\r\nexport interface ITextEditorState {\r\n isFullscreen: boolean\r\n}\r\n\r\nfunction CreateTextEditor<T>(params: ITextEditorParams) {\r\n class TextEditor extends Component<ITextEditorProps<T>, ITextEditorState> {\r\n contentRef\r\n constructor(props: ITextEditorProps<T>) {\r\n super(props)\r\n this.state = {\r\n isFullscreen: false\r\n }\r\n this.contentRef = createRef<HTMLDivElement | null>()\r\n }\r\n\r\n componentDidMount() {\r\n document.addEventListener('fullscreenchange', this.handleFullscreenChange)\r\n }\r\n\r\n componentWillUnmount() {\r\n document.removeEventListener('fullscreenchange', this.handleFullscreenChange)\r\n }\r\n\r\n handleFullscreenChange = () => {\r\n this.setState({ isFullscreen: !!document.fullscreenElement })\r\n }\r\n\r\n handleFullscreenToggle = () => {\r\n if (this.contentRef.current) {\r\n if (!document.fullscreenElement) {\r\n this.contentRef.current.requestFullscreen().catch((err) => {\r\n console.error(`Error attempting to enable full-screen mode: ${err.message}`)\r\n })\r\n } else {\r\n document.exitFullscreen()\r\n }\r\n }\r\n }\r\n\r\n getWrapClasses = () => {\r\n const classes = []\r\n if (this.state.isFullscreen) classes.push(textEditorClasses.fullscreen)\r\n return classes.join(' ')\r\n }\r\n\r\n render() {\r\n const errorMessage = getErrorMessage(this.props.messageErrors, this.props.name)\r\n const dValue = (this.props.name ? this.props.data?.[this.props.name] : '')?.toString() ?? ''\r\n\r\n return (\r\n <Box id={params.id} ref={this.contentRef} sx={{ backgroundColor: '#fff' }}>\r\n {this.state.isFullscreen && (\r\n <WrapTitle>\r\n <Typography variant='h4' sx={{ fontWeight: 600, flex: 1, textAlign: 'center' }}>\r\n {params.title}\r\n </Typography>\r\n </WrapTitle>\r\n )}\r\n <Wrap className={this.getWrapClasses()}>\r\n <WrapActions>\r\n <Tooltip title={this.state.isFullscreen ? 'Exit Fullscreen' : 'Fullscreen'} arrow>\r\n <CustomButton sx={{ color: '#06c' }} onClick={this.handleFullscreenToggle}>\r\n {this.state.isFullscreen ? <FullscreenExitIcon /> : <FullscreenIcon />}\r\n </CustomButton>\r\n </Tooltip>\r\n </WrapActions>\r\n <WrapTextEditor>\r\n <TextEditorBase\r\n defautValue={dValue}\r\n name={this.props.name?.toString() ?? ''}\r\n readOnly={this.props.disabled}\r\n error={errorMessage.error}\r\n onBlur={() => {\r\n if (!this.props.name) return\r\n this.props.onBlur?.(this.props.name)\r\n }}\r\n />\r\n </WrapTextEditor>\r\n </Wrap>\r\n </Box>\r\n )\r\n }\r\n }\r\n return TextEditor\r\n}\r\nexport default CreateTextEditor\r\n\r\nconst editorHeight = 64\r\n\r\nconst Wrap = styled(Box)(({ theme }) => ({\r\n maxWidth: theme.breakpoints.values.xl,\r\n margin: '0 auto',\r\n position: 'relative',\r\n [`&.${textEditorClasses.fullscreen} .${textEditorClasses.root}`]: {\r\n height: `calc(100vh - ${editorHeight + 10}px)`\r\n },\r\n [`&.${textEditorClasses.fullscreen}`]: {\r\n width: '871px'\r\n }\r\n}))\r\n\r\nconst WrapTitle = styled(Box)({\r\n height: `${editorHeight}px`,\r\n display: 'flex',\r\n justifyContent: 'center',\r\n alignItems: 'center'\r\n})\r\n\r\nconst WrapActions = styled(({ children, ...props }: BoxProps) => (\r\n <Box {...props}>\r\n <Box>{children}</Box>\r\n </Box>\r\n))({\r\n position: 'sticky',\r\n top: '-1px',\r\n zIndex: 2,\r\n '& > div': {\r\n height: 0,\r\n display: 'flex',\r\n justifyContent: 'right',\r\n padding: '0 6px'\r\n }\r\n})\r\n\r\nconst CustomButton = styled(IconButton)({\r\n flex: '0 0 auto',\r\n marginTop: '1px',\r\n width: '40px',\r\n height: '40px'\r\n})\r\n\r\nconst WrapTextEditor = styled(Box)({\r\n backgroundColor: '#fff',\r\n width: '100%',\r\n '& .ql-container': {\r\n fontFamily: '\"Roboto\", serif',\r\n fontSize: '14px'\r\n },\r\n '& .ql-toolbar': {\r\n position: 'sticky',\r\n top: '-1px',\r\n backgroundColor: '#fff',\r\n zIndex: 1\r\n }\r\n})\r\n"],"names":["CreateTextEditor","params","TextEditor","props","_this","_classCallCheck","_callSuper","_defineProperty","setState","isFullscreen","document","fullscreenElement","contentRef","current","exitFullscreen","requestFullscreen","err","console","error","concat","message","classes","state","push","textEditorClasses","fullscreen","join","createRef","_inherits","Component","_createClass","key","value","addEventListener","this","handleFullscreenChange","removeEventListener","_toString","_ref","_this$props$data","_this$props$name$toSt","_this$props$name","_this2","errorMessage","getErrorMessage","messageErrors","name","dValue","data","toString","_jsxs","Box","id","ref","sx","backgroundColor","children","_jsx","WrapTitle","Typography","variant","fontWeight","flex","textAlign","title","Wrap","className","getWrapClasses","WrapActions","Tooltip","arrow","CustomButton","color","onClick","handleFullscreenToggle","FullscreenExitIcon","FullscreenIcon","WrapTextEditor","TextEditorBase","defautValue","readOnly","disabled","onBlur","_this2$props$onBlur","_this2$props","call","styled","_ref2","theme","maxWidth","breakpoints","values","xl","margin","position","root","height","editorHeight","width","display","justifyContent","alignItems","_ref4","_objectWithoutProperties","_excluded","_objectSpread","top","zIndex","padding","IconButton","marginTop","fontFamily","fontSize"],"mappings":"qmBAmBA,SAASA,EAAoBC,GA+E3B,kBA5EE,SAAAC,EAAYC,GAA0B,IAAAC,EAKgB,OALhBC,OAAAH,GACpCE,EAAAE,EAAAJ,KAAAA,GAAMC,IAAMI,EAAAH,EAAA,yBAeW,WACvBA,EAAKI,SAAS,CAAEC,eAAgBC,SAASC,sBAC1CJ,EAAAH,EAAA,yBAEwB,WACnBA,EAAKQ,WAAWC,UACbH,SAASC,kBAKZD,SAASI,iBAJTV,EAAKQ,WAAWC,QAAQE,oBAAyB,MAAC,SAACC,GACjDC,QAAQC,MAAKC,gDAAAA,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R,UAAW,CACTX,OAAQ,EACRG,QAAS,OACTC,eAAgB,QAChBQ,QAAS,WAIPrC,EAAee,EAAOuB,EAAPvB,CAAmB,CACtCxB,KAAM,WACNgD,UAAW,MACXZ,MAAO,OACPF,OAAQ,SAGJnB,EAAiBS,EAAOnC,EAAPmC,CAAY,CACjC/B,gBAAiB,OACjB2C,MAAO,OACP,kBAAmB,CACjBa,WAAY,kBACZC,SAAU,QAEZ,gBAAiB,CACflB,SAAU,SACVY,IAAK,OACLnD,gBAAiB,OACjBoD,OAAQ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{defineProperty as r,objectSpread2 as e,slicedToArray as o,objectWithoutProperties as t,asyncToGenerator as n,regenerator as i}from"../../_virtual/_rollupPluginBabelHelpers.js";import{jsx as a,jsxs as s,Fragment as l}from"react/jsx-runtime";import{useRef as u,useState as c,useEffect as d,useMemo as f,Fragment as m}from"react";import{styled as p,Stack as v,Box as g,Typography as h,Grid as b,CircularProgress as x}from"@mui/material";import{getErrorMessage as y}from"./helpers.js";import{FormFooter as C}from"./decorator.units.js";import{getFormFields as S,getFormValidators as j,getFormPreSubmit as E,isFormRegistered as G}from"./decorator.js";import{FormValidator as k}from"./validator.js";import w from"./create.form-base.js";import B from"./create.input.js";import{fetchDelay as F}from"../utils/helpers.js";var D=["type","renderInput","formContext"],P=["disabled","visible","sizes"];var z=function(r,p){var v,z=w({errorGetter:null==p?void 0:p.errorGetter,errorCommonGetter:null==p?void 0:p.errorCommonGetter}),H=(v=B({}),function(r){var o,n,i=r.type,l=r.renderInput,u=r.formContext,c=t(r,D),d=c.name,f=null!==(o=d?null===(n=c.data)||void 0===n?void 0:n[d]:c.defaultValue)&&void 0!==o?o:"",m=null!=u?u:{},p=m.messageErrors,g=m.onBlur,h=y(null==u?void 0:u.messageErrors,c.name);if(l)return a(l,e(e({},c),{},{messageErrors:p,onBlur:g,formContext:u}));switch(i){case String:return a(v,e(e({},c),{},{messageErrors:p,onBlur:g,formContext:u}));case Number:return a(v,e(e({},c),{},{slots:e({textFieldProps:{type:"number"}},c.slots),messageErrors:p,onBlur:g,formContext:u}));case Boolean:return s("div",{children:[s("label",{children:[c.label||(null==d?void 0:d.toString()),": "]}),a("input",{name:null==d?void 0:d.toString(),type:"checkbox",defaultChecked:f}),a("span",{style:{color:"red"},children:h.error?h.message:""})]});default:return s("div",{children:["Unsupported field type for ",null==d?void 0:d.toString()]})}}),T=function(r){var p,v,y=r.slots,w=S(r.configClass),B=j(r.configClass),D=E(r.configClass),T=u(null),U=c(!1),W=o(U,2),_=W[0],M=W[1];if(!G(r.configClass)){var O,R=(null===(O=r.configClass)||void 0===O?void 0:O.name)||"Unknown";return s(g,{sx:{border:"1px dashed #ccc",padding:12,borderRadius:4,color:"#333",background:"#fafafa"},children:[a(h,{variant:"subtitle1",sx:{fontWeight:600,marginBottom:6},children:"Form configuration not registered"}),s(h,{variant:"body1",children:['Configuration for "',R,'" was not found. Did you forget to add ',a("code",{children:"@registerForm"})," to the class?"]})]})}var V=function(){var e=n(i().m(function e(o){var t,n,a,s;return i().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t=new AbortController,T.current=t,n=t.signal,a=o,e.p=1,null==D||!D.handler){e.n=3;break}return e.n=2,D.handler(o,r.data);case 2:null==(a=e.v)&&(a=o);case 3:if(M(!0),!r.onSubmit){e.n=5;break}return e.n=4,F(function(){return r.onSubmit(a,n)},500);case 4:r.onSuccess&&r.onSuccess(a);case 5:M(!1),e.n=7;break;case 6:throw e.p=6,s=e.v,r.onError&&r.onError(s),M(!1),s;case 7:return e.a(2)}},e,null,[[1,6]])}));return function(r){return e.apply(this,arguments)}}();d(function(){return function(){var r;null===(r=T.current)||void 0===r||r.abort()}},[]);var Y=f(function(){return new k(B)},[B]),q=f(function(){var e=[I.root];return r.disableGutters&&e.push(I.disableGutters),e.join(" ")},[r.disableGutters]);return a(z.Form,{flexBox:!0,onSubmit:V,validate:Y,onError:r.onSubmitError,slots:null==y?void 0:y.formBase,children:s(N,{className:q,children:[null===(p=r.slots)||void 0===p?void 0:p.top,a("div",{className:I.content,children:a(b,e(e({container:!0,spacing:2},null==y?void 0:y.contentProps),{},{children:w.map(function(o){var n=o.disabled,i=o.visible,s=o.sizes,u=t(o,P);return a(m,{children:z.mapContext(function(o){if(!("function"==typeof i?i(r.data,o.modelState):!1!==i))return a(l,{});var t="function"==typeof n?n(r.data,o.modelState):!0===n,c="function"==typeof s?s(r.data,o.modelState):s;return a(b,e(e({item:!0,xs:12},c),{},{children:a(H,e(e({data:r.data},u),{},{disabled:t,formContext:o}))}))})},o.name.toString())})}))}),z.mapContext(function(r){var o,t;if(!1===(null==y?void 0:y.isFooter))return a(l,{});if(null!=y&&y.footer){var n=y.footer;return a(n,{formContext:r})}var i=Object.values(r.messageErrors).filter(Boolean),s="";if(i.length>0&&(s=null!==(o=null===(t=i[0])||void 0===t||null===(t=t[0])||void 0===t?void 0:t.message)&&void 0!==o?o:"An error has occurred, please check the form again"),i.length>1){var u=i.length-1;s+=" (and ".concat(u," more error").concat(u>1?"s":"",")")}return a(C,e({slots:null==y?void 0:y.footerSlots,errorMessage:s},null==y?void 0:y.footerProps))}),a(A,{className:_?"loading":"",children:a(x,{size:40,thickness:4,color:"primary"})}),null===(v=r.slots)||void 0===v?void 0:v.bottom]})})};return function(o){return a(T,e(e({configClass:r},p),o))}},I={root:"DinoDecoratorForm-root",content:"DinoDecoratorForm-content",disableGutters:"DinoDecoratorForm-disableGutters"},N=p(v)(function(e){var o=e.theme;return r(r({flex:1,minHeight:0},"& .".concat(I.content),{flex:1,minHeight:0,padding:o.spacing(2,1.5),overflowY:"auto"}),"&.".concat(I.disableGutters," .").concat(I.content),{padding:0})}),A=p(g)({position:"absolute",top:0,left:0,width:"100%",height:"100%",backgroundColor:"rgba(0, 0, 0, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:10,opacity:0,visibility:"hidden",transition:"opacity 0.3s ease-in-out",pointerEvents:"none","&.loading":{opacity:1,visibility:"visible",pointerEvents:"auto"}});export{z as createDecoratorForm,z as default};
|
|
2
2
|
//# sourceMappingURL=decorator.form.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decorator.form.js","sources":["../../../src/form/decorator.form.tsx"],"sourcesContent":["import { ComponentType, FC, Fragment, useEffect, useMemo, useRef, useState } from 'react'\r\nimport { Box, BoxProps, Button, CircularProgress, Grid, GridProps, styled, Typography } from '@mui/material'\r\nimport { IFormInputBase } from './types'\r\nimport { getErrorMessage } from './helpers'\r\nimport { getFormFields, getFormPreSubmit, getFormValidators, isFormRegistered } from './decorator'\r\nimport FormValidator, { IPartialError } from './validator'\r\nimport createFormBase, { IFormBaseSlots } from './create.form-base'\r\nimport createInput from './create.input'\r\nimport { FormFooter, IFormFooterProps, IFormFooterSlots } from './decorator.units'\r\nimport { fetchDelay } from '../utils'\r\n\r\nexport interface IDecoratorFieldProps<T = any> extends IFormInputBase<T> {\r\n type?: any\r\n visible?: boolean | ((data: T) => boolean)\r\n renderInput?: ComponentType<IFormInputBase<T>>\r\n}\r\n\r\nfunction createDecoratorField<T>() {\r\n const InputInstance = createInput<T>({})\r\n\r\n const DecoratorField: FC<IDecoratorFieldProps<T>> = ({ type: inputType, renderInput, formContext, ...props }) => {\r\n const name = props.name\r\n const defaultValue = (name ? props.data?.[name] : props.defaultValue) ?? ''\r\n\r\n const { messageErrors, onBlur } = formContext ?? {}\r\n const err = getErrorMessage(formContext?.messageErrors, props.name as any)\r\n if (renderInput) {\r\n const InputComp = renderInput\r\n return <InputComp {...props} messageErrors={messageErrors} onBlur={onBlur} formContext={formContext} />\r\n }\r\n switch (inputType) {\r\n case String:\r\n return <InputInstance {...props} messageErrors={messageErrors} onBlur={onBlur} formContext={formContext} />\r\n case Number:\r\n return (\r\n <InputInstance\r\n {...props}\r\n slots={{ textFieldProps: { type: 'number' }, ...props.slots }}\r\n messageErrors={messageErrors}\r\n onBlur={onBlur}\r\n formContext={formContext}\r\n />\r\n )\r\n case Boolean:\r\n return (\r\n <div>\r\n <label>{props.label || name?.toString()}: </label>\r\n <input name={name?.toString()} type='checkbox' defaultChecked={defaultValue} />\r\n <span style={{ color: 'red' }}>{err.error ? err.message : ''}</span>\r\n </div>\r\n )\r\n default:\r\n return <div>Unsupported field type for {name?.toString()}</div>\r\n }\r\n }\r\n\r\n return DecoratorField\r\n}\r\n\r\nexport interface IDecoratorFormSlots<T> {\r\n top?: React.ReactNode\r\n bottom?: React.ReactNode\r\n isFooter?: React.ReactNode | boolean\r\n contentProps?: GridProps\r\n formBase?: IFormBaseSlots\r\n footer?: ComponentType<IFormFooterProps<T>>\r\n footerProps?: Omit<BoxProps, 'slots'>\r\n footerSlots?: IFormFooterSlots\r\n}\r\n\r\nexport interface IDecoratorFormProps<T = any> {\r\n configClass?: any\r\n data?: T\r\n onSubmit?: (data: Partial<T>, signal?: AbortSignal) => Promise<void>\r\n onError?: (error: any) => void\r\n onSubmitError?: (error: IPartialError<T>) => void\r\n onSuccess?: (data: Partial<T>) => void\r\n enableStickyFooter?: boolean\r\n slots?: IDecoratorFormSlots<T>\r\n}\r\n\r\ntype IDecoratorFormParam<T> = Partial<Omit<IDecoratorFormProps<T>, 'configClass'>>\r\n\r\nexport const createDecoratorForm = function <T>(configClass: any, param?: IDecoratorFormParam<T>): ComponentType<IDecoratorFormProps<T>> {\r\n const FormBase = createFormBase<T>({})\r\n const DecoratorField = createDecoratorField<T>()\r\n\r\n const DecoratorForm: FC<IDecoratorFormProps<T>> = (props) => {\r\n const { slots } = props\r\n const fields = getFormFields<T>(props.configClass)\r\n const validators = getFormValidators<Partial<T>>(props.configClass)\r\n const preSubmitConfig = getFormPreSubmit<T>(props.configClass)\r\n const abortControllerRef = useRef<AbortController | null>(null)\r\n\r\n const [loading, setLoading] = useState(false)\r\n\r\n // If the provided configClass isn't registered via @registerForm,\r\n // show a simple, friendly error UI instead of throwing.\r\n if (!isFormRegistered(props.configClass)) {\r\n const name = props.configClass?.name || 'Unknown'\r\n return (\r\n <Box sx={{ border: '1px dashed #ccc', padding: 12, borderRadius: 4, color: '#333', background: '#fafafa' }}>\r\n <Typography variant='subtitle1' sx={{ fontWeight: 600, marginBottom: 6 }}>\r\n Form configuration not registered\r\n </Typography>\r\n <Typography variant='body1'>\r\n Configuration for \"{name}\" was not found. Did you forget to add <code>@registerForm</code> to the class?\r\n </Typography>\r\n </Box>\r\n )\r\n }\r\n\r\n const handleSubmit = async (data: any) => {\r\n // Create new AbortController for this submit\r\n const abortController = new AbortController()\r\n abortControllerRef.current = abortController\r\n const signal = abortController.signal\r\n\r\n let processedData = data\r\n try {\r\n // Execute presubmit handler if exists\r\n if (preSubmitConfig?.handler) {\r\n processedData = await preSubmitConfig.handler(data, props.data)\r\n // If handler returns null/undefined, use original data\r\n if (processedData === null || processedData === undefined) {\r\n processedData = data\r\n }\r\n }\r\n\r\n // Set loading state to true before calling onSubmit\r\n setLoading(true)\r\n\r\n // Call the original onSubmit with processed data and abort signal\r\n if (props.onSubmit) {\r\n await fetchDelay(() => props.onSubmit!(processedData, signal), 500) // Optional delay for UX purposes\r\n if (props.onSuccess) {\r\n props.onSuccess(processedData)\r\n }\r\n }\r\n setLoading(false) // Reset loading state after successful submit\r\n } catch (error) {\r\n if (props.onError) {\r\n props.onError(error)\r\n }\r\n setLoading(false) // Reset loading state on error\r\n throw error\r\n }\r\n }\r\n\r\n const renderFooter = () => {\r\n return FormBase.mapContext((context) => {\r\n if (slots?.isFooter === false) return <></>\r\n if (slots?.footer) {\r\n const FooterComponent = slots.footer\r\n return <FooterComponent formContext={context} />\r\n }\r\n\r\n const errorList = Object.values(context.messageErrors).filter(Boolean)\r\n const errorMessage = errorList.length > 0 ? 'An error has occurred, please check the form again' : undefined\r\n return <FormFooter isSticky={props.enableStickyFooter} slots={slots?.footerSlots} errorMessage={errorMessage} {...slots?.footerProps} />\r\n })\r\n }\r\n\r\n useEffect(() => {\r\n return () => {\r\n // Abort any pending request when component unmounts\r\n abortControllerRef.current?.abort()\r\n }\r\n }, [])\r\n\r\n const validate = useMemo(() => new FormValidator<Partial<T>>(validators), [validators])\r\n\r\n return (\r\n <FormBase.Form onSubmit={handleSubmit} validate={validate} onError={props.onSubmitError} slots={slots?.formBase}>\r\n {props.slots?.top}\r\n <Grid container spacing={2} {...slots?.contentProps}>\r\n {fields.map((field) => {\r\n const { disabled, visible, sizes, ...fieldOther } = field\r\n return (\r\n <Fragment key={field.name.toString()}>\r\n {FormBase.mapContext((context) => {\r\n // Check visibility, default is visible (true or undefined)\r\n const isVisible = typeof visible === 'function' ? visible(props.data, context.modelState) : visible !== false\r\n if (!isVisible) return <></>\r\n // Check disabled state, default is enabled (false or undefined)\r\n const isDisabled = typeof disabled === 'function' ? disabled(props.data, context.modelState) : disabled === true\r\n // Determine sizes, default is full width (undefined)\r\n const finalSizes = typeof sizes === 'function' ? sizes(props.data, context.modelState) : sizes\r\n return (\r\n <Grid item xs={12} {...finalSizes}>\r\n <DecoratorField data={props.data} {...fieldOther} disabled={isDisabled} formContext={context} />\r\n </Grid>\r\n )\r\n })}\r\n </Fragment>\r\n )\r\n })}\r\n </Grid>\r\n {renderFooter()}\r\n <Overlay className={loading ? 'loading' : ''}>\r\n <CircularProgress size={40} thickness={4} color='primary' />\r\n </Overlay>\r\n {props.slots?.bottom}\r\n </FormBase.Form>\r\n )\r\n }\r\n\r\n const DecoratorFormComp: FC<IDecoratorFormProps<T>> = (props) => {\r\n return <DecoratorForm configClass={configClass} {...param} {...props} />\r\n }\r\n return DecoratorFormComp\r\n}\r\nexport default createDecoratorForm\r\n\r\nconst Overlay = styled(Box)(({ theme }) => ({\r\n position: 'absolute',\r\n top: 0,\r\n left: 0,\r\n width: '100%',\r\n height: '100%',\r\n backgroundColor: 'rgba(0, 0, 0, 0.3)',\r\n display: 'flex',\r\n alignItems: 'center',\r\n justifyContent: 'center',\r\n zIndex: 10,\r\n opacity: 0,\r\n visibility: 'hidden',\r\n transition: 'opacity 0.3s ease-in-out',\r\n pointerEvents: 'none',\r\n '&.loading': {\r\n opacity: 1,\r\n visibility: 'visible',\r\n pointerEvents: 'auto'\r\n }\r\n}))\r\n"],"names":["createDecoratorForm","configClass","param","InputInstance","FormBase","createFormBase","DecoratorField","createInput","_ref","_ref2","_props$data","inputType","type","renderInput","formContext","props","_objectWithoutProperties","_excluded","name","defaultValue","data","_ref3","messageErrors","onBlur","err","getErrorMessage","_jsx","_objectSpread","String","Number","slots","textFieldProps","Boolean","_jsxs","children","label","toString","defaultChecked","style","color","error","message","DecoratorForm","_props$slots","_props$slots2","fields","getFormFields","validators","getFormValidators","preSubmitConfig","getFormPreSubmit","abortControllerRef","useRef","_useState","useState","_useState2","_slicedToArray","loading","setLoading","isFormRegistered","_props$configClass","Box","sx","border","padding","borderRadius","background","Typography","variant","fontWeight","marginBottom","handleSubmit","_ref4","_asyncToGenerator","_regenerator","m","_callee","abortController","signal","processedData","_t","w","_context","p","n","AbortController","current","handler","v","onSubmit","fetchDelay","onSuccess","onError","a","_x","apply","this","arguments","useEffect","_abortControllerRef$c","abort","validate","useMemo","FormValidator","Form","onSubmitError","formBase","top","Grid","container","spacing","contentProps","map","field","disabled","visible","sizes","fieldOther","_excluded2","Fragment","mapContext","context","modelState","isDisabled","finalSizes","item","xs","isFooter","footer","FooterComponent","errorMessage","Object","values","filter","length","undefined","FormFooter","isSticky","enableStickyFooter","footerSlots","footerProps","Overlay","className","CircularProgress","size","thickness","bottom","styled","_ref5","theme","position","left","width","height","backgroundColor","display","alignItems","justifyContent","zIndex","opacity","visibility","transition","pointerEvents"],"mappings":"g6BAmFO,IAAMA,EAAsB,SAAaC,EAAkBC,GAChE,IAlEMC,EAkEAC,EAAWC,EAAkB,IAC7BC,GAnEAH,EAAgBI,EAAe,IAEe,SAAhCC,GAA4F,IAAAC,EAAAC,EAAnDC,EAASH,EAAfI,KAAiBC,EAAWL,EAAXK,YAAaC,EAAWN,EAAXM,YAAgBC,EAAKC,EAAAR,EAAAS,GAClGC,EAAOH,EAAMG,KACbC,EA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OAAQ,OACRC,gBAAiB,qBACjBC,QAAS,OACTC,WAAY,SACZC,eAAgB,SAChBC,OAAQ,GACRC,QAAS,EACTC,WAAY,SACZC,WAAY,2BACZC,cAAe,OACf,YAAa,CACXH,QAAS,EACTC,WAAY,UACZE,cAAe,QAElB"}
|
|
1
|
+
{"version":3,"file":"decorator.form.js","sources":["../../../src/form/decorator.form.tsx"],"sourcesContent":["import { ComponentType, FC, Fragment, useEffect, useMemo, useRef, useState } from 'react'\r\nimport { Box, BoxProps, CircularProgress, Grid, GridProps, Stack, styled, Typography } from '@mui/material'\r\nimport { fetchDelay } from '../utils'\r\nimport { IFormInputBase } from './types'\r\nimport { getErrorMessage } from './helpers'\r\nimport { FormFooter, IFormFooterProps, IFormFooterSlots } from './decorator.units'\r\nimport { getFormFields, getFormPreSubmit, getFormValidators, isFormRegistered } from './decorator'\r\nimport FormValidator, { IPartialError, IRuleOption } from './validator'\r\nimport createFormBase, { IFormBaseErrorHandlers, IFormBaseSlots } from './create.form-base'\r\nimport createInput from './create.input'\r\n\r\nexport interface IDecoratorFieldProps<T = any> extends IFormInputBase<T> {\r\n type?: any\r\n visible?: boolean | ((data: T) => boolean)\r\n renderInput?: ComponentType<IFormInputBase<T>>\r\n}\r\n\r\nfunction createDecoratorField<T>() {\r\n const InputInstance = createInput<T>({})\r\n\r\n const DecoratorField: FC<IDecoratorFieldProps<T>> = ({ type: inputType, renderInput, formContext, ...props }) => {\r\n const name = props.name\r\n const defaultValue = (name ? props.data?.[name] : props.defaultValue) ?? ''\r\n\r\n const { messageErrors, onBlur } = formContext ?? {}\r\n const err = getErrorMessage(formContext?.messageErrors, props.name as any)\r\n if (renderInput) {\r\n const InputComp = renderInput\r\n return <InputComp {...props} messageErrors={messageErrors} onBlur={onBlur} formContext={formContext} />\r\n }\r\n switch (inputType) {\r\n case String:\r\n return <InputInstance {...props} messageErrors={messageErrors} onBlur={onBlur} formContext={formContext} />\r\n case Number:\r\n return (\r\n <InputInstance\r\n {...props}\r\n slots={{ textFieldProps: { type: 'number' }, ...props.slots }}\r\n messageErrors={messageErrors}\r\n onBlur={onBlur}\r\n formContext={formContext}\r\n />\r\n )\r\n case Boolean:\r\n return (\r\n <div>\r\n <label>{props.label || name?.toString()}: </label>\r\n <input name={name?.toString()} type='checkbox' defaultChecked={defaultValue} />\r\n <span style={{ color: 'red' }}>{err.error ? err.message : ''}</span>\r\n </div>\r\n )\r\n default:\r\n return <div>Unsupported field type for {name?.toString()}</div>\r\n }\r\n }\r\n\r\n return DecoratorField\r\n}\r\n\r\nexport interface IDecoratorFormSlots<T> {\r\n top?: React.ReactNode\r\n bottom?: React.ReactNode\r\n isFooter?: React.ReactNode | boolean\r\n contentProps?: GridProps\r\n formBase?: IFormBaseSlots\r\n footer?: ComponentType<IFormFooterProps<T>>\r\n footerProps?: Omit<BoxProps, 'slots'>\r\n footerSlots?: IFormFooterSlots\r\n}\r\n\r\nexport interface IDecoratorFormProps<T = any> extends IFormBaseErrorHandlers<T> {\r\n configClass?: any\r\n data?: T\r\n onSubmit?: (data: Partial<T>, signal?: AbortSignal) => Promise<void>\r\n onError?: (error: any) => void\r\n onSubmitError?: (error: IPartialError<T>) => void\r\n onSuccess?: (data: Partial<T>) => void\r\n slots?: IDecoratorFormSlots<T>\r\n disableGutters?: boolean\r\n}\r\n\r\nexport type IDecoratorFormConfig<T> = Partial<Omit<IDecoratorFormProps<T>, 'configClass'>>\r\n\r\nexport const createDecoratorForm = function <T>(configClass: any, config?: IDecoratorFormConfig<T>): ComponentType<IDecoratorFormProps<T>> {\r\n const FormBase = createFormBase<T>({\r\n errorGetter: config?.errorGetter,\r\n errorCommonGetter: config?.errorCommonGetter\r\n })\r\n const DecoratorField = createDecoratorField<T>()\r\n\r\n const DecoratorForm: FC<IDecoratorFormProps<T>> = (props) => {\r\n const { slots } = props\r\n const fields = getFormFields<T>(props.configClass)\r\n const validators = getFormValidators<Partial<T>>(props.configClass)\r\n const preSubmitConfig = getFormPreSubmit<T>(props.configClass)\r\n const abortControllerRef = useRef<AbortController | null>(null)\r\n\r\n const [loading, setLoading] = useState(false)\r\n\r\n // If the provided configClass isn't registered via @registerForm,\r\n // show a simple, friendly error UI instead of throwing.\r\n if (!isFormRegistered(props.configClass)) {\r\n const name = props.configClass?.name || 'Unknown'\r\n return (\r\n <Box sx={{ border: '1px dashed #ccc', padding: 12, borderRadius: 4, color: '#333', background: '#fafafa' }}>\r\n <Typography variant='subtitle1' sx={{ fontWeight: 600, marginBottom: 6 }}>\r\n Form configuration not registered\r\n </Typography>\r\n <Typography variant='body1'>\r\n Configuration for \"{name}\" was not found. Did you forget to add <code>@registerForm</code> to the class?\r\n </Typography>\r\n </Box>\r\n )\r\n }\r\n\r\n const handleSubmit = async (data: any) => {\r\n // Create new AbortController for this submit\r\n const abortController = new AbortController()\r\n abortControllerRef.current = abortController\r\n const signal = abortController.signal\r\n\r\n let processedData = data\r\n try {\r\n // Execute presubmit handler if exists\r\n if (preSubmitConfig?.handler) {\r\n processedData = await preSubmitConfig.handler(data, props.data)\r\n // If handler returns null/undefined, use original data\r\n if (processedData === null || processedData === undefined) {\r\n processedData = data\r\n }\r\n }\r\n\r\n // Set loading state to true before calling onSubmit\r\n setLoading(true)\r\n\r\n // Call the original onSubmit with processed data and abort signal\r\n if (props.onSubmit) {\r\n await fetchDelay(() => props.onSubmit!(processedData, signal), 500) // Optional delay for UX purposes\r\n if (props.onSuccess) {\r\n props.onSuccess(processedData)\r\n }\r\n }\r\n setLoading(false) // Reset loading state after successful submit\r\n } catch (error) {\r\n if (props.onError) {\r\n props.onError(error)\r\n }\r\n setLoading(false) // Reset loading state on error\r\n throw error\r\n }\r\n }\r\n\r\n const renderFooter = () => {\r\n return FormBase.mapContext((context) => {\r\n if (slots?.isFooter === false) return <></>\r\n if (slots?.footer) {\r\n const FooterComponent = slots.footer\r\n return <FooterComponent formContext={context} />\r\n }\r\n\r\n const errorList = Object.values(context.messageErrors).filter(Boolean) as IRuleOption<T>[][]\r\n let message: string = ''\r\n if (errorList.length > 0) message = errorList[0]?.[0]?.message ?? 'An error has occurred, please check the form again'\r\n if (errorList.length > 1) {\r\n const remaining = errorList.length - 1\r\n message += ` (and ${remaining} more error${remaining > 1 ? 's' : ''})`\r\n }\r\n\r\n return <FormFooter slots={slots?.footerSlots} errorMessage={message} {...slots?.footerProps} />\r\n })\r\n }\r\n\r\n useEffect(() => {\r\n return () => {\r\n // Abort any pending request when component unmounts\r\n abortControllerRef.current?.abort()\r\n }\r\n }, [])\r\n\r\n const validate = useMemo(() => new FormValidator<Partial<T>>(validators), [validators])\r\n\r\n const rootClasses = useMemo(() => {\r\n const classes = [formClasses.root]\r\n if (props.disableGutters) classes.push(formClasses.disableGutters)\r\n return classes.join(' ')\r\n }, [props.disableGutters])\r\n\r\n return (\r\n <FormBase.Form flexBox onSubmit={handleSubmit} validate={validate} onError={props.onSubmitError} slots={slots?.formBase}>\r\n <DecoratorFormStyled className={rootClasses}>\r\n {props.slots?.top}\r\n <div className={formClasses.content}>\r\n <Grid container spacing={2} {...slots?.contentProps}>\r\n {fields.map((field) => {\r\n const { disabled, visible, sizes, ...fieldOther } = field\r\n return (\r\n <Fragment key={field.name.toString()}>\r\n {FormBase.mapContext((context) => {\r\n // Check visibility, default is visible (true or undefined)\r\n const isVisible = typeof visible === 'function' ? visible(props.data, context.modelState) : visible !== false\r\n if (!isVisible) return <></>\r\n // Check disabled state, default is enabled (false or undefined)\r\n const isDisabled = typeof disabled === 'function' ? disabled(props.data, context.modelState) : disabled === true\r\n // Determine sizes, default is full width (undefined)\r\n const finalSizes = typeof sizes === 'function' ? sizes(props.data, context.modelState) : sizes\r\n return (\r\n <Grid item xs={12} {...finalSizes}>\r\n <DecoratorField data={props.data} {...fieldOther} disabled={isDisabled} formContext={context} />\r\n </Grid>\r\n )\r\n })}\r\n </Fragment>\r\n )\r\n })}\r\n </Grid>\r\n </div>\r\n {renderFooter()}\r\n <Overlay className={loading ? 'loading' : ''}>\r\n <CircularProgress size={40} thickness={4} color='primary' />\r\n </Overlay>\r\n {props.slots?.bottom}\r\n </DecoratorFormStyled>\r\n </FormBase.Form>\r\n )\r\n }\r\n\r\n const DecoratorFormComp: FC<IDecoratorFormProps<T>> = (props) => {\r\n return <DecoratorForm configClass={configClass} {...config} {...props} />\r\n }\r\n return DecoratorFormComp\r\n}\r\nexport default createDecoratorForm\r\n\r\nconst formClasses = {\r\n root: 'DinoDecoratorForm-root',\r\n content: 'DinoDecoratorForm-content',\r\n disableGutters: 'DinoDecoratorForm-disableGutters'\r\n}\r\n\r\nconst DecoratorFormStyled = styled(Stack)(({ theme }) => ({\r\n flex: 1,\r\n minHeight: 0,\r\n [`& .${formClasses.content}`]: {\r\n flex: 1,\r\n minHeight: 0,\r\n padding: theme.spacing(2, 1.5),\r\n overflowY: 'auto'\r\n },\r\n [`&.${formClasses.disableGutters} .${formClasses.content}`]: { padding: 0 }\r\n}))\r\n\r\nconst Overlay = styled(Box)({\r\n position: 'absolute',\r\n top: 0,\r\n left: 0,\r\n width: '100%',\r\n height: '100%',\r\n backgroundColor: 'rgba(0, 0, 0, 0.3)',\r\n display: 'flex',\r\n alignItems: 'center',\r\n justifyContent: 'center',\r\n zIndex: 10,\r\n opacity: 0,\r\n visibility: 'hidden',\r\n transition: 'opacity 0.3s ease-in-out',\r\n pointerEvents: 'none',\r\n '&.loading': {\r\n opacity: 1,\r\n visibility: 'visible',\r\n pointerEvents: 'auto'\r\n }\r\n})\r\n"],"names":["createDecoratorForm","configClass","config","InputInstance","FormBase","createFormBase","errorGetter","errorCommonGetter","DecoratorField","createInput","_ref","_ref2","_props$data","inputType","type","renderInput","formContext","props","_objectWithoutProperties","_excluded","name","defaultValue","data","_ref3","messageErrors","onBlur","err","getErrorMessage","_jsx","_objectSpread","String","Number","slots","textFieldProps","Boolean","_jsxs","children","label","toString","defaultChecked","style","color","error","message","DecoratorForm","_props$slots","_props$slots2","fields","getFormFields","validators","getFormValidators","preSubmitConfig","getFormPreSubmit","abortControllerRef","useRef","_useState","useState","_useState2","_slicedToArray","loading","setLoading","isFormRegistered","_props$configClass","Box","sx","border","padding","borderRadius","background","Typography","variant","fontWeight","marginBottom","handleSubmit","_ref4","_asyncToGenerator","_regenerator","m","_callee","abortController","signal","processedData","_t","w","_context","p","n","AbortController","current","handler","v","onSubmit","fetchDelay","onSuccess","onError","a","_x","apply","this","arguments","useEffect","_abortControllerRef$c","abort","validate","useMemo","FormValidator","rootClasses","classes","formClasses","root","disableGutters","push","join","Form","flexBox","onSubmitError","formBase","DecoratorFormStyled","className","top","content","Grid","container","spacing","contentProps","map","field","disabled","visible","sizes","fieldOther","_excluded2","Fragment","mapContext","context","modelState","isDisabled","finalSizes","item","xs","_errorList$0$0$messag","_errorList$","isFooter","footer","FooterComponent","errorList","Object","values","filter","length","remaining","concat","FormFooter","footerSlots","errorMessage","footerProps","Overlay","CircularProgress","size","thickness","bottom","styled","Stack","_ref5","theme","_defineProperty","flex","minHeight","overflowY","position","left","width","height","backgroundColor","display","alignItems","justifyContent","zIndex","opacity","visibility","transition","pointerEvents"],"mappings":"83BAmFO,IAAMA,EAAsB,SAAaC,EAAkBC,GAChE,IAlEMC,EAkEAC,EAAWC,EAAkB,CACjCC,YAAaJ,aAAAA,EAAAA,EAAQI,YACrBC,kBAAmBL,aAAM,EAANA,EAAQK,oBAEvBC,GAtEAL,EAAgBM,EAAe,IAEe,SAAhCC,GAA4F,IAAAC,EAAAC,EAAnDC,EAASH,EAAfI,KAAiBC,EAAWL,EAAXK,YAAaC,EAAWN,EAAXM,YAAgBC,EAAKC,EAAAR,EAAAS,GAClGC,EAAOH,EAAMG,KACbC,EAA8D,QAAlDV,EAAIS,EAAiBR,QAAbA,EAAGK,EAAMK,YAANV,IAAUA,OAAVA,EAAAA,EAAaQ,GAAQH,EAAMI,oBAAY,IAAAV,EAAAA,EAAK,GAEzEY,EAAkCP,QAAAA,EAAe,CAAE,EAA3CQ,EAAaD,EAAbC,cAAeC,EAAMF,EAANE,OACjBC,EAAMC,EAAgBX,aAAAA,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iI,EAAiB,CAAAC,KAAM,GAAIC,UAAW,EAAGtH,MAAM,cAEtC,QADFK,EACT7B,EAAMe,aAAK,IAAAc,OAAA,EAAXA,EAAakH,WAIrB,EAKD,OAHsD,SAAC/I,GACrD,OAAOW,EAACgB,EAAaf,EAAAA,EAAA,CAAC5B,YAAaA,GAAiBC,GAAYe,GACjE,CAEH,EAGM2F,EAAc,CAClBC,KAAM,yBACNW,QAAS,4BACTV,eAAgB,oCAGZO,EAAsB4C,EAAOC,EAAPD,CAAc,SAAAE,GAAA,IAAGC,EAAKD,EAALC,MAAK,OAAAC,EAAAA,EAAA,CAChDC,KAAM,EACNC,UAAW,GAAC,MAAAhB,OACL3C,EAAYY,SAAY,CAC7B8C,KAAM,EACNC,UAAW,EACXrG,QAASkG,EAAMzC,QAAQ,EAAG,KAC1B6C,UAAW,SACZjB,KAAAA,OACK3C,EAAYE,eAAcyC,MAAAA,OAAK3C,EAAYY,SAAY,CAAEtD,QAAS,GAAG,GAGvE0F,EAAUK,EAAOlG,EAAPkG,CAAY,CAC1BQ,SAAU,WACVlD,IAAK,EACLmD,KAAM,EACNC,MAAO,OACPC,OAAQ,OACRC,gBAAiB,qBACjBC,QAAS,OACTC,WAAY,SACZC,eAAgB,SAChBC,OAAQ,GACRC,QAAS,EACTC,WAAY,SACZC,WAAY,2BACZC,cAAe,OACf,YAAa,CACXH,QAAS,EACTC,WAAY,UACZE,cAAe"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{objectWithoutProperties as
|
|
1
|
+
import{objectWithoutProperties as e,objectSpread2 as r}from"../../_virtual/_rollupPluginBabelHelpers.js";import{jsxs as a,jsx as t}from"react/jsx-runtime";import{styled as o,Box as i,Typography as l,Button as n}from"@mui/material";var s=["slots","className","errorMessage"],p=function(o){var i=o.slots,p=o.className,m=o.errorMessage,x=e(o,s);return a(c,r(r({className:[p].filter(Boolean).join(" ")},x),{},{children:[null==i?void 0:i.before,m&&t(l,{variant:"caption",color:"error",noWrap:!0,title:m,sx:{flex:1,fontWeight:600},children:m}),t(n,{variant:"contained",color:"primary",type:"submit",size:"small",sx:{flex:"0 0 auto"},children:"Submit"}),null==i?void 0:i.after]}))},c=o(i)(function(e){var r=e.theme;return{display:"flex",justifyContent:"flex-end",alignItems:"center",padding:r.spacing(1,1.5),boxShadow:"rgba(145, 158, 171, 0.1) 0px 0px 2px 0px, rgba(145, 158, 171, 0.12) 0px 0px 24px -4px",gap:r.spacing(2)}});export{p as FormFooter};
|
|
2
2
|
//# sourceMappingURL=decorator.units.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decorator.units.js","sources":["../../../src/form/decorator.units.tsx"],"sourcesContent":["import { FC } from 'react'\r\nimport { Box, BoxProps, Button, styled, Typography } from '@mui/material'\r\nimport { IFormBaseContext } from './types'\r\n\r\nexport interface IFormFooterSlots {\r\n after?: React.ReactNode\r\n before?: React.ReactNode\r\n}\r\n\r\nexport interface IFormFooterProps<T = any> extends Omit<BoxProps, 'slots'> {\r\n formContext?: IFormBaseContext<T>\r\n}\r\n\r\ninterface IInternalFormFooterProps<T = any> extends IFormFooterProps<T> {\r\n
|
|
1
|
+
{"version":3,"file":"decorator.units.js","sources":["../../../src/form/decorator.units.tsx"],"sourcesContent":["import { FC } from 'react'\r\nimport { Box, BoxProps, Button, styled, Typography } from '@mui/material'\r\nimport { IFormBaseContext } from './types'\r\n\r\nexport interface IFormFooterSlots {\r\n after?: React.ReactNode\r\n before?: React.ReactNode\r\n}\r\n\r\nexport interface IFormFooterProps<T = any> extends Omit<BoxProps, 'slots'> {\r\n formContext?: IFormBaseContext<T>\r\n}\r\n\r\ninterface IInternalFormFooterProps<T = any> extends IFormFooterProps<T> {\r\n slots?: IFormFooterSlots\r\n errorMessage?: string\r\n}\r\n\r\nexport const FormFooter: FC<IInternalFormFooterProps<any>> = (props) => {\r\n const { slots, className, errorMessage, ...boxProps } = props\r\n const classNames = [className]\r\n return (\r\n <FooterStyled className={classNames.filter(Boolean).join(' ')} {...boxProps}>\r\n {slots?.before}\r\n {errorMessage && (\r\n <Typography variant='caption' color='error' noWrap title={errorMessage} sx={{ flex: 1, fontWeight: 600 }}>\r\n {errorMessage}\r\n </Typography>\r\n )}\r\n <Button variant='contained' color='primary' type='submit' size='small' sx={{ flex: '0 0 auto' }}>\r\n Submit\r\n </Button>\r\n {slots?.after}\r\n </FooterStyled>\r\n )\r\n}\r\n\r\nconst FooterStyled = styled(Box)(({ theme }) => ({\r\n display: 'flex',\r\n justifyContent: 'flex-end',\r\n alignItems: 'center',\r\n padding: theme.spacing(1, 1.5),\r\n boxShadow: 'rgba(145, 158, 171, 0.1) 0px 0px 2px 0px, rgba(145, 158, 171, 0.12) 0px 0px 24px -4px',\r\n gap: theme.spacing(2)\r\n}))\r\n"],"names":["FormFooter","props","slots","className","errorMessage","boxProps","_objectWithoutProperties","_excluded","_jsxs","FooterStyled","_objectSpread","filter","Boolean","join","before","_jsx","Typography","variant","color","noWrap","title","sx","flex","fontWeight","Button","type","size","children","after","styled","Box","_ref","theme","display","justifyContent","alignItems","padding","spacing","boxShadow","gap"],"mappings":"kRAkBaA,EAAgD,SAACC,GAC5D,IAAQC,EAAgDD,EAAhDC,MAAOC,EAAyCF,EAAzCE,UAAWC,EAA8BH,EAA9BG,aAAiBC,EAAQC,EAAKL,EAAKM,GAE7D,OACEC,EAACC,EAAYC,EAAAA,EAAA,CAACP,UAFG,CAACA,GAEkBQ,OAAOC,SAASC,KAAK,MAAUR,GAAQ,GAAA,WACxEH,aAAAA,EAAAA,EAAOY,OACPV,GACCW,EAACC,EAAW,CAAAC,QAAQ,UAAUC,MAAM,QAAQC,QAAM,EAACC,MAAOhB,EAAciB,GAAI,CAAEC,KAAM,EAAGC,WAAY,cAChGnB,IAGLW,EAACS,EAAO,CAAAP,QAAQ,YAAYC,MAAM,UAAUO,KAAK,SAASC,KAAK,QAAQL,GAAI,CAAEC,KAAM,YAE1EK,SAAA,WACRzB,aAAAA,EAAAA,EAAO0B,SAGd,EAEMnB,EAAeoB,EAAOC,EAAPD,CAAY,SAAAE,GAAA,IAAGC,EAAKD,EAALC,MAAK,MAAQ,CAC/CC,QAAS,OACTC,eAAgB,WAChBC,WAAY,SACZC,QAASJ,EAAMK,QAAQ,EAAG,KAC1BC,UAAW,wFACXC,IAAKP,EAAMK,QAAQ,GACpB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createClass as r,classCallCheck as t,defineProperty as e}from"../../_virtual/_rollupPluginBabelHelpers.js";import{SingleRuleValidate as i}from"./validator.js";var n=r(function r(){t(this,r),e(this,"getError",function(r,t){var e,i=null===(e=r.response)||void 0===e?void 0:e.data,n=(null==i?void 0:i.errors)||i;if(n){var o=Object.keys(null!=t?t:{}),a={};return o.forEach(function(r){var t=n[r],e=[];Array.isArray(t)?e=t.filter(function(r){return r&&"string"==typeof r&&""!==r.trim()}):"string"==typeof t&&""!==t.trim()&&(e=[t]),Array.isArray(e)&&e.length>0&&(a[r]=e[0])}),a}return{}}),e(this,"errorToPartialError",function(r){var t,e={},n=Object.keys(r),o=function(r){return Array.isArray(r)?r.map(function(r){return{rule:i.Custom,message:r}}):"string"==typeof r&&""!==r.trim()?[{rule:i.Custom,message:r}]:[]};n.forEach(function(t){var i,n=null!==(i=r[t])&&void 0!==i?i:[];e[t]=o(n)});var a=null!==(t=r[""])&&void 0!==t?t:[],s=o(a);return s.length>0&&(e[""]=s),e}),e(this,"getErrorCommon",function(r){var t,e=null===(t=r.response)||void 0===t?void 0:t.data,i=[],n=(null==e?void 0:e.errors)||e;if(n&&n[""]){var o=n[""];Array.isArray(o)&&(i=o.filter(function(r){return r&&"string"==typeof r&&""!==r.trim()}))}else"string"==typeof n&&""!==n.trim()&&(i=[n]);return i})});export{n as ErrorHandler};
|
|
2
|
+
//# sourceMappingURL=error-handler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-handler.js","sources":["../../../src/form/error-handler.ts"],"sourcesContent":["import { IPartialError, SingleRuleValidate } from './validator'\r\n\r\nexport type IErrorGetter<T> = (error: any, modelRender?: Partial<T>) => { [key in keyof T]?: string | string[] } | undefined\r\n\r\nexport type IErrorCommonGetter = (error: any) => string | string[] | undefined\r\n\r\nexport class ErrorHandler<T> {\r\n getError: IErrorGetter<T> = (error, modelRender) => {\r\n const data = error.response?.data as any\r\n const dataRaw = data?.errors || data\r\n if (dataRaw) {\r\n const keys = Object.keys(modelRender ?? {}) as (keyof T)[]\r\n const obj: { [key in keyof T]?: string } = {}\r\n keys.forEach((key) => {\r\n const itemRaw = dataRaw[key]\r\n let messages: string[] = []\r\n if (Array.isArray(itemRaw)) {\r\n messages = itemRaw.filter((msg) => msg && typeof msg === 'string' && msg.trim() !== '')\r\n } else if (typeof itemRaw === 'string' && itemRaw.trim() !== '') {\r\n messages = [itemRaw]\r\n }\r\n if (Array.isArray(messages) && messages.length > 0) {\r\n obj[key] = messages[0]\r\n }\r\n })\r\n return obj\r\n }\r\n return {}\r\n }\r\n\r\n errorToPartialError = (errors: { [key in keyof T]?: string | string[] }): IPartialError<T> => {\r\n const obj: IPartialError<T> = {}\r\n const keys = Object.keys(errors) as (keyof T)[]\r\n\r\n const stringToRuleOptions = (message: string | string[]): { rule: SingleRuleValidate; message: string }[] => {\r\n if (Array.isArray(message)) {\r\n return message.map((msg) => ({ rule: SingleRuleValidate.Custom, message: msg }))\r\n } else if (typeof message === 'string' && message.trim() !== '') {\r\n return [{ rule: SingleRuleValidate.Custom, message }]\r\n }\r\n return []\r\n }\r\n\r\n keys.forEach((key) => {\r\n const messages: string | string[] | undefined = errors[key] ?? []\r\n obj[key] = stringToRuleOptions(messages)\r\n })\r\n\r\n const commonMessages = ((errors as any)[''] as string | string[] | undefined) ?? []\r\n const commonRuleOptions = stringToRuleOptions(commonMessages)\r\n if (commonRuleOptions.length > 0) {\r\n ;(obj as any)[''] = commonRuleOptions\r\n }\r\n return obj\r\n }\r\n\r\n getErrorCommon: IErrorCommonGetter = (error) => {\r\n const data = error.response?.data as any\r\n let messages: string[] = []\r\n const dataRaw = data?.errors || data\r\n if (dataRaw && dataRaw['']) {\r\n const itemRaw = dataRaw['']\r\n if (Array.isArray(itemRaw)) {\r\n messages = itemRaw.filter((msg) => msg && typeof msg === 'string' && msg.trim() !== '')\r\n }\r\n } else if (typeof dataRaw === 'string' && dataRaw.trim() !== '') {\r\n messages = [dataRaw]\r\n }\r\n return messages\r\n }\r\n}\r\n"],"names":["ErrorHandler","_createClass","_classCallCheck","_defineProperty","this","error","modelRender","_error$response","data","response","dataRaw","errors","keys","Object","obj","forEach","key","itemRaw","messages","Array","isArray","filter","msg","trim","length","_errors$","stringToRuleOptions","message","map","rule","SingleRuleValidate","Custom","_errors$key","commonMessages","commonRuleOptions","_error$response2"],"mappings":"sKAMA,IAAaA,EAAYC,EAAA,SAAAD,IAAAE,OAAAF,GAAAG,EACKC,KAAA,WAAA,SAACC,EAAOC,GAAe,IAAAC,EAC3CC,EAAqB,QAAjBD,EAAGF,EAAMI,gBAAQ,IAAAF,OAAA,EAAdA,EAAgBC,KACvBE,GAAUF,aAAI,EAAJA,EAAMG,SAAUH,EAChC,GAAIE,EAAS,CACX,IAAME,EAAOC,OAAOD,KAAKN,QAAAA,EAAe,IAClCQ,EAAqC,CAAE,EAa7C,OAZAF,EAAKG,QAAQ,SAACC,GACZ,IAAMC,EAAUP,EAAQM,GACpBE,EAAqB,GACrBC,MAAMC,QAAQH,GAChBC,EAAWD,EAAQI,OAAO,SAACC,GAAG,OAAKA,GAAsB,iBAARA,GAAmC,KAAfA,EAAIC,SAC7C,iBAAZN,GAA2C,KAAnBA,EAAQM,SAChDL,EAAW,CAACD,IAEVE,MAAMC,QAAQF,IAAaA,EAASM,OAAS,IAC/CV,EAAIE,GAAOE,EAAS,GAExB,GACOJ,CACR,CACD,MAAO,CAAE,IACVX,EAAAC,KAAA,sBAEqB,SAACO,GAAsE,IAAAc,EACrFX,EAAwB,CAAE,EAC1BF,EAAOC,OAAOD,KAAKD,GAEnBe,EAAsB,SAACC,GAC3B,OAAIR,MAAMC,QAAQO,GACTA,EAAQC,IAAI,SAACN,GAAG,MAAM,CAAEO,KAAMC,EAAmBC,OAAQJ,QAASL,EAAK,GAClD,iBAAZK,GAA2C,KAAnBA,EAAQJ,OACzC,CAAC,CAAEM,KAAMC,EAAmBC,OAAQJ,QAAAA,IAEtC,EACR,EAEDf,EAAKG,QAAQ,SAACC,GAAO,IAAAgB,EACbd,EAAqDc,QAA7CA,EAAkCrB,EAAOK,UAAIgB,IAAAA,EAAAA,EAAI,GAC/DlB,EAAIE,GAAOU,EAAoBR,EACjC,GAEA,IAAMe,EAAuER,QAAzDA,EAAKd,EAAe,WAAqCc,IAAAA,EAAAA,EAAI,GAC3ES,EAAoBR,EAAoBO,GAI9C,OAHIC,EAAkBV,OAAS,IAC3BV,EAAY,IAAMoB,GAEfpB,IACRX,EAAAC,KAAA,iBAEoC,SAACC,GAAS,IAAA8B,EACvC3B,EAAqB,QAAjB2B,EAAG9B,EAAMI,gBAAQ,IAAA0B,OAAA,EAAdA,EAAgB3B,KACzBU,EAAqB,GACnBR,GAAUF,aAAI,EAAJA,EAAMG,SAAUH,EAChC,GAAIE,GAAWA,EAAQ,IAAK,CAC1B,IAAMO,EAAUP,EAAQ,IACpBS,MAAMC,QAAQH,KAChBC,EAAWD,EAAQI,OAAO,SAACC,GAAG,OAAKA,GAAsB,iBAARA,GAAmC,KAAfA,EAAIC,SAE5E,KAA6B,iBAAZb,GAA2C,KAAnBA,EAAQa,SAChDL,EAAW,CAACR,IAEd,OAAOQ,GACR"}
|
package/dist/src/form/helpers.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{toConsumableArray as r,typeof as e,objectSpread2 as
|
|
1
|
+
import{toConsumableArray as r,typeof as e,objectSpread2 as t,createForOfIteratorHelper as n}from"../../_virtual/_rollupPluginBabelHelpers.js";import{FormValidator as a}from"./validator.js";var o=function(r){for(var t=arguments.length,a=new Array(t>1?t-1:0),i=1;i<t;i++)a[i-1]=arguments[i];var u=a.filter(function(r){return!!r});if(u.length<1)return r;var f,l=Object.assign({},r),s=n(u);try{for(s.s();!(f=s.n()).done;)for(var c=f.value,v=0,y=Object.keys(c);v<y.length;v++){var m=y[v],p=c[m],g=l[m];null===p||"object"!==e(p)||Array.isArray(p)||null===g||"object"!==e(g)||Array.isArray(g)?l[m]=p:l[m]=o(g,p)}}catch(r){s.e(r)}finally{s.f()}return l},i=function(r,e){return r&&r[e]?t(t({},r[e][0]),{},{error:!0}):{error:!1,message:""}},u=function(r){var e=Array.from(r).reduce(function(r,e){return r[e[0]]?Array.isArray(r[e[0]])?r[e[0]].push(e[1]):r[e[0]]=[r[e[0]],e[1]]:r[e[0]]=e[1],r},{});return Object.keys(e).forEach(function(r){var t=e[r];"string"!=typeof t||"true"!==t.toString().toLocaleLowerCase()&&"false"!==t.toString().toLocaleLowerCase()||(e[r]="true"===t.toString().toLocaleLowerCase())}),e},f=function(r){if("string"==typeof r)return r.startsWith("#")&&/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(r)?r:r.trim();if(Array.isArray(r))return r.map(function(r){return f(r)});if(r instanceof File)return r;if(r instanceof FileList)return r;if(r instanceof Date)return r;if("number"==typeof r||"boolean"==typeof r||null==r)return r;if(r instanceof HTMLElement)return r;if("function"==typeof r)return r;if(r&&"object"===e(r)){var t={};return Object.keys(r).forEach(function(e){t[e]=f(r[e])}),t}return r},l=function(r,e,t,n){var a=n.run(e);if(a){var o=t||{},i=Object.keys(e).filter(function(r){return!!e[r]}).filter(function(r){return e[r]instanceof File&&!!e[r].size});return i.push(r),i.forEach(function(r){a[r]?o[r]=a[r]:delete o[r]}),o}return null},s=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var i=t.map(function(r){return null==r?void 0:r.configs}).filter(function(r){return!!r}),u=Object.assign.apply(Object,[{}].concat(r(i))),f=function(){var e=Object.keys(u)[l];u[e]=o.apply(void 0,[{}].concat(r(i.map(function(r){return r?r[e]:{Rules:[]}})))),u[e].Rules=i.map(function(r){return r?r[e]:{Rules:[]}}).reduce(function(e,t){var n;return e.push.apply(e,r(null!==(n=null==t?void 0:t.Rules)&&void 0!==n?n:[])),e},[])},l=0;l<Object.keys(u).length;l++)f();return new a(u)},c=function(r,e,t){if(0===r.length)return{valid:!1,message:"File is empty or cannot be parsed"};var a=Object.keys(r[0]),o=e.filter(function(r){return!a.includes(r)});if(o.length>0)return{valid:!1,message:"Missing required columns: ".concat(o.join(", "))};if(null!=t&&t.maxRows&&r.length>t.maxRows)return{valid:!1,message:"File exceeds maximum row limit of ".concat(t.maxRows)};for(var i=0;i<r.length;i++){var u,f=r[i],l=n(e);try{for(l.s();!(u=l.n()).done;){var s=u.value,c=f[s];if("string"!=typeof c||""===c.trim())return{valid:!1,message:'Invalid or missing value for "'.concat(s.toString(),'" at row ').concat(i+2)}}}catch(r){l.e(r)}finally{l.f()}}return{valid:!0}};export{u as convertFormDataToJson,i as getErrorMessage,l as singleValidate,f as trimAllStrings,c as validateCsvModel,s as validateMerge};
|
|
2
2
|
//# sourceMappingURL=helpers.js.map
|