dinocollab-core 2.2.43 → 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/bin/codegen.js +2 -1
- package/dist/_virtual/_rollupPluginBabelHelpers.js +2 -2
- package/dist/form/index.js +1 -1
- package/dist/src/api-context/alert-global.js +1 -1
- package/dist/src/api-context/alert-global.js.map +1 -1
- 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/components/text-editor.js +1 -1
- package/dist/src/components/text-editor.js.map +1 -1
- package/dist/src/data-surface/view-list/styled.js +1 -1
- package/dist/src/data-surface/view-list/styled.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/filter-bar/components/filter-summary.js +1 -1
- package/dist/src/filter-bar/components/filter-summary.js.map +1 -1
- package/dist/src/filter-bar/menu/create-form-field-select-multiple.js +1 -1
- package/dist/src/filter-bar/menu/create-form-field-select-multiple.js.map +1 -1
- package/dist/src/filter-bar/menu/create-form-field-select.js +1 -1
- package/dist/src/filter-bar/menu/create-form-field-select.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/decorator.form.js +1 -1
- package/dist/src/form/decorator.form.js.map +1 -1
- package/dist/src/form/decorator.js +1 -1
- package/dist/src/form/decorator.js.map +1 -1
- package/dist/src/form/decorator.units.js +2 -0
- package/dist/src/form/decorator.units.js.map +1 -0
- package/dist/src/form/dino-form.js +1 -1
- package/dist/src/form/dino-form.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/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/url-query-param.js +1 -1
- package/dist/src/table-grid/url-query-param.js.map +1 -1
- package/dist/src/utils/query-param.js +1 -1
- package/dist/src/utils/query-param.js.map +1 -1
- package/dist/table/index.js +1 -1
- package/dist/types/api-context/alert-global.d.ts +1 -1
- package/dist/types/components/text-editor.d.ts +0 -1
- package/dist/types/filter-bar/menu/create-form-field-select-multiple.d.ts +1 -1
- package/dist/types/filter-bar/menu/create-form-field-select.d.ts +1 -1
- package/dist/types/form/create.form-base.d.ts +11 -9
- package/dist/types/form/create.input-file.csv-local-parser.d.ts +15 -0
- package/dist/types/form/decorator.d.ts +9 -8
- package/dist/types/form/decorator.form.d.ts +14 -20
- package/dist/types/form/decorator.units.d.ts +16 -0
- package/dist/types/form/dino-form.d.ts +2 -3
- package/dist/types/form/error-handler.d.ts +10 -0
- package/dist/types/form/helpers.d.ts +9 -9
- package/dist/types/form/types.d.ts +1 -1
- package/dist/types/form/validator.d.ts +15 -15
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.form-grid-layout.js","sources":["../../../src/form/create.form-grid-layout.tsx"],"sourcesContent":["import { Component, Fragment } from 'react'\r\nimport { BoxProps, Grid, RegularBreakpoints, SxProps, Theme } from '@mui/material'\r\nimport type { ComponentType } from 'react'\r\nimport { cleanObject } from '../utils'\r\nimport { mapGlobalModalContext } from '../api-context'\r\nimport { IFormBase, IFormBaseContext, IFormInputBase } from './types'\r\nimport { FormGridLayoutStyled, CreateFormBottomBar, formGridLayoutClasses } from './create.form-grid-layout.units'\r\nimport FormValidator, { IPartialError } from './validator'\r\nimport createFormBase, { IFormBaseSlots } from './create.form-base'\r\nimport createInput from './create.input'\r\n\r\nexport interface IFormGridLayoutConfig<T> {\r\n key: keyof T\r\n label?: string\r\n placeholder?: string\r\n sizes?: RegularBreakpoints\r\n defaultValue?: any\r\n className?: string\r\n inputElement?: ComponentType<IFormInputBase<T>>\r\n}\r\n\r\nexport type IPreSubmitEvent<T> = (value: Partial<T>, oldValue?: T) => Partial<T>\r\n\r\nexport interface IFormGridLayoutMergedConfigs<T> {\r\n hiddenFields?: Partial<Record<keyof T, boolean>> | ((state: Partial<T>, model?: Partial<T>) => Partial<Record<keyof T, boolean>>)\r\n disabledFields?: Partial<Record<keyof T, boolean>> | ((state: Partial<T>, model?: Partial<T>) => Partial<Record<keyof T, boolean>>)\r\n}\r\n\r\nexport interface IFormGridLayoutSlots<T> extends IFormGridLayoutMergedConfigs<T> {\r\n action?: ComponentType<IFormBase<T>>\r\n actionBefore?: JSX.Element\r\n contentBefore?: JSX.Element\r\n contentAfter?: JSX.Element\r\n // getDisabledFields?: (value: Partial<T>) => Partial<Record<keyof T, boolean>>\r\n closeState?: { Success?: boolean; Fail?: boolean }\r\n rootProps?: BoxProps\r\n preSubmit?: IPreSubmitEvent<T>\r\n formSlots?: IFormBaseSlots\r\n}\r\n\r\nexport interface IFormGridLayoutParams<T> extends IFormGridLayoutSlots<T> {\r\n configs: IFormGridLayoutConfig<T>[]\r\n validate: FormValidator<Partial<T>>\r\n autoHeight?: boolean\r\n}\r\n\r\nexport interface IFormGridLayoutProps<T> {\r\n data?: T\r\n onSubmit: (value: Partial<T>, signal?: AbortSignal) => Promise<void>\r\n onError?: (error: any) => void\r\n onSubmitError?: (error: IPartialError<T>) => void\r\n onClose?: () => void\r\n sx?: SxProps<Theme>\r\n slots?: IFormGridLayoutSlots<T>\r\n autoHeight?: boolean\r\n}\r\n\r\nexport interface IFormGridLayoutState {\r\n loadding?: boolean\r\n}\r\n\r\nconst CreateFormGridLayout = function <T>(params: IFormGridLayoutParams<T>): ComponentType<IFormGridLayoutProps<T>> {\r\n const FormBaseInstance = createFormBase<T>()\r\n const BottomBarInstance = CreateFormBottomBar<T>()\r\n const InputBaseInstance = createInput<T>({ maxLength: 250 })\r\n\r\n class FormGridLayout extends Component<IFormGridLayoutProps<T>, IFormGridLayoutState> {\r\n private abortController?: AbortController\r\n constructor(props: IFormGridLayoutProps<T>) {\r\n super(props)\r\n this.state = { loadding: false }\r\n }\r\n\r\n get configMerged() {\r\n const { slots = {} } = this.props\r\n return {\r\n hiddenFields: slots.hiddenFields ?? params.hiddenFields ?? (() => ({}) as Partial<Record<keyof T, boolean>>),\r\n disabledFields: slots.disabledFields ?? params.disabledFields ?? (() => ({}) as Partial<Record<keyof T, boolean>>)\r\n }\r\n }\r\n\r\n render() {\r\n const { slots, data, autoHeight } = this.props\r\n const BottomBar = params?.action ?? slots?.action ?? BottomBarInstance\r\n\r\n const rootClasses = [formGridLayoutClasses.root, slots?.rootProps?.className]\r\n if (autoHeight ?? params.autoHeight) rootClasses.push(formGridLayoutClasses.autoHeight)\r\n\r\n return mapGlobalModalContext(({ close }) => (\r\n <FormGridLayoutStyled {...slots?.rootProps} className={rootClasses.filter(Boolean).join(' ')}>\r\n <FormBaseInstance.Form\r\n className={formGridLayoutClasses.form}\r\n validate={params.validate}\r\n onSubmit={(v) => this.onSubmit(v, close)}\r\n slots={this.getFormSlots()}\r\n onError={this.props.onSubmitError}\r\n >\r\n {slots?.contentBefore && slots?.contentBefore}\r\n {params?.contentBefore}\r\n {FormBaseInstance.mapContext((context) => {\r\n const { hiddenFields } = this.configMerged\r\n const mState = context.modelState || {}\r\n const finalHiddenFields = typeof hiddenFields === 'function' ? hiddenFields(mState, data) : hiddenFields || {}\r\n return (\r\n <Grid container spacing={2}>\r\n {params.configs.map((config, index) => {\r\n const isHidden: boolean | undefined = finalHiddenFields[config.key] ? true : undefined\r\n if (isHidden) return <Fragment key={config.key.toString() + index} />\r\n return (\r\n <Fragment key={config.key.toString() + index}>\r\n <Grid item xs={12} {...config.sizes} className={config.className}>\r\n {this.renderFormFieldElement(context, config)}\r\n </Grid>\r\n </Fragment>\r\n )\r\n })}\r\n </Grid>\r\n )\r\n })}\r\n {params?.contentAfter}\r\n {slots?.contentAfter && slots?.contentAfter}\r\n {FormBaseInstance.mapContext((context) => (\r\n <BottomBar data={data} onBlur={context.onBlur} messageErrors={context.messageErrors} before={slots?.actionBefore} />\r\n ))}\r\n </FormBaseInstance.Form>\r\n </FormGridLayoutStyled>\r\n ))\r\n }\r\n\r\n renderFormFieldElement = (context: IFormBaseContext<T>, config: IFormGridLayoutConfig<T>) => {\r\n const { data } = this.props\r\n const ElementComponent = config.inputElement ?? InputBaseInstance\r\n const mState = context.modelState || {}\r\n const { disabledFields } = this.configMerged\r\n const finalDisabledFields = typeof disabledFields === 'function' ? disabledFields(mState, data) : disabledFields || {}\r\n const obj: IFormInputBase<T, any> = {\r\n data,\r\n onBlur: context.onBlur,\r\n messageErrors: context.messageErrors,\r\n name: config.key,\r\n label: config.label,\r\n placeholder: config.placeholder,\r\n disabled: finalDisabledFields[config.key] ? true : undefined,\r\n defaultValue: data?.[config.key] ?? config?.defaultValue,\r\n formContext: context\r\n }\r\n return <ElementComponent {...cleanObject(obj)} />\r\n }\r\n\r\n loading = () => this.setState({ loadding: true })\r\n\r\n unloading = () => this.setState({ loadding: false })\r\n\r\n componentWillUnmount(): void {\r\n this.abortController?.abort()\r\n }\r\n\r\n onSubmit = async (value: Partial<T>, close?: () => void) => {\r\n const { slots } = this.props\r\n const mapping = this.props.slots?.preSubmit ?? params.preSubmit ?? this.preSubmit\r\n const data = mapping(value, this.props.data)\r\n try {\r\n this.loading()\r\n this.abortController?.abort()\r\n this.abortController = new AbortController()\r\n await this.props.onSubmit(data, this.abortController?.signal)\r\n if (!slots?.closeState || slots.closeState.Success !== false) {\r\n close && close()\r\n this.props.onClose && this.props.onClose()\r\n }\r\n } catch (error) {\r\n if (slots?.closeState && slots.closeState.Fail === true) {\r\n close && close()\r\n this.props.onClose && this.props.onClose()\r\n }\r\n if (this.props.onError) this.props.onError(error)\r\n throw error\r\n } finally {\r\n this.unloading()\r\n }\r\n }\r\n\r\n preSubmit: IPreSubmitEvent<T> = (value) => value\r\n\r\n getFormSlots = (): IFormBaseSlots => {\r\n const isLoading = this.state.loadding\r\n const { formProps } = this.props.slots?.formSlots || {}\r\n return {\r\n formProps: {\r\n ...formProps,\r\n sx: {\r\n ...this.props.sx,\r\n opacity: isLoading ? 0.7 : 1,\r\n pointerEvents: isLoading ? 'none' : 'auto'\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return FormGridLayout\r\n}\r\n\r\nexport default CreateFormGridLayout\r\n"],"names":["CreateFormGridLayout","params","FormBaseInstance","createFormBase","BottomBarInstance","CreateFormBottomBar","InputBaseInstance","createInput","maxLength","FormGridLayout","props","_this","_classCallCheck","_callSuper","_defineProperty","context","config","_config$inputElement","_data$config$key","data","ElementComponent","inputElement","mState","modelState","disabledFields","configMerged","finalDisabledFields","obj","onBlur","messageErrors","name","key","label","placeholder","disabled","undefined","defaultValue","formContext","_jsx","_objectSpread","cleanObject","setState","loadding","_ref","_asyncToGenerator","_regenerator","m","_callee","value","close","_ref2","_this$props$slots$pre","_this$props$slots","slots","mapping","_this$abortController","_this$abortController2","_t","w","_context","p","n","preSubmit","loading","abortController","abort","AbortController","onSubmit","signal","closeState","Success","onClose","v","Fail","onError","unloading","f","a","_x","_x2","apply","this","arguments","_this$props$slots2","isLoading","state","formProps","formSlots","sx","opacity","pointerEvents","_inherits","Component","_createClass","get","_ref4","_slots$hiddenFields","_ref5","_slots$disabledFields","_this$props$slots3","hiddenFields","_ref6","_params$action","_slots$rootProps","_this2","_this$props","autoHeight","BottomBar","action","rootClasses","formGridLayoutClasses","root","rootProps","className","push","mapGlobalModalContext","_ref7","FormGridLayoutStyled","filter","Boolean","join","children","_jsxs","Form","form","validate","getFormSlots","onSubmitError","contentBefore","mapContext","finalHiddenFields","Grid","container","spacing","configs","map","index","isHidden","Fragment","item","xs","sizes","renderFormFieldElement","toString","contentAfter","before","actionBefore","_this$abortController3"],"mappings":"8sBA6DA,IAAMA,EAAuB,SAAaC,GACxC,IAAMC,EAAmBC,IACnBC,EAAoBC,IACpBC,EAAoBC,EAAe,CAAEC,UAAW,MAEhDC,aAEJ,SAAAA,EAAYC,GAA8B,IAAAC,EAER,OAFQC,OAAAH,GACxCE,EAAAE,EAAAJ,KAAAA,GAAMC,IAAMI,EAAAH,EAAA,yBA4DW,SAACI,EAA8BC,GAAoC,IAAAC,EAAAC,EAClFC,EAASR,EAAKD,MAAdS,KACFC,EAAsC,QAAtBH,EAAGD,EAAOK,oBAAY,IAAAJ,EAAAA,EAAIX,EAC1CgB,EAASP,EAAQQ,YAAc,CAAE,EAC/BC,EAAmBb,EAAKc,aAAxBD,eACFE,EAAgD,mBAAnBF,EAAgCA,EAAeF,EAAQ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,CACT"}
|
|
1
|
+
{"version":3,"file":"create.form-grid-layout.js","sources":["../../../src/form/create.form-grid-layout.tsx"],"sourcesContent":["import { Component, Fragment } from 'react'\r\nimport { BoxProps, Grid, RegularBreakpoints, SxProps, Theme } from '@mui/material'\r\nimport type { ComponentType } from 'react'\r\nimport { cleanObject } from '../utils'\r\nimport { mapGlobalModalContext } from '../api-context'\r\nimport { IFormBase, IFormBaseContext, IFormInputBase } from './types'\r\nimport { FormGridLayoutStyled, CreateFormBottomBar, formGridLayoutClasses } from './create.form-grid-layout.units'\r\nimport FormValidator, { IPartialError } from './validator'\r\nimport createFormBase, { IFormBaseSlots } from './create.form-base'\r\nimport createInput from './create.input'\r\n\r\nexport interface IFormGridLayoutConfig<T> {\r\n key: keyof T\r\n label?: string\r\n placeholder?: string\r\n sizes?: RegularBreakpoints\r\n defaultValue?: any\r\n className?: string\r\n inputElement?: ComponentType<IFormInputBase<T>>\r\n}\r\n\r\nexport type IPreSubmitEvent<T> = (value: Partial<T>, oldValue?: T) => Partial<T>\r\n\r\nexport interface IFormGridLayoutMergedConfigs<T> {\r\n hiddenFields?: Partial<Record<keyof T, boolean>> | ((state: Partial<T>, model?: Partial<T>) => Partial<Record<keyof T, boolean>>)\r\n disabledFields?: Partial<Record<keyof T, boolean>> | ((state: Partial<T>, model?: Partial<T>) => Partial<Record<keyof T, boolean>>)\r\n}\r\n\r\nexport interface IFormGridLayoutSlots<T> extends IFormGridLayoutMergedConfigs<T> {\r\n action?: ComponentType<IFormBase<T>>\r\n actionBefore?: JSX.Element\r\n contentBefore?: JSX.Element\r\n contentAfter?: JSX.Element\r\n // getDisabledFields?: (value: Partial<T>) => Partial<Record<keyof T, boolean>>\r\n closeState?: { Success?: boolean; Fail?: boolean }\r\n rootProps?: BoxProps\r\n preSubmit?: IPreSubmitEvent<T>\r\n formSlots?: IFormBaseSlots\r\n}\r\n\r\nexport interface IFormGridLayoutParams<T> extends IFormGridLayoutSlots<T> {\r\n configs: IFormGridLayoutConfig<T>[]\r\n validate: FormValidator<Partial<T>>\r\n autoHeight?: boolean\r\n}\r\n\r\nexport interface IFormGridLayoutProps<T> {\r\n data?: T\r\n onSubmit: (value: Partial<T>, signal?: AbortSignal) => Promise<void>\r\n onError?: (error: any) => void\r\n onSubmitError?: (error: IPartialError<T>) => void\r\n onClose?: () => void\r\n sx?: SxProps<Theme>\r\n slots?: IFormGridLayoutSlots<T>\r\n autoHeight?: boolean\r\n}\r\n\r\nexport interface IFormGridLayoutState {\r\n loadding?: boolean\r\n}\r\n\r\nconst CreateFormGridLayout = function <T>(params: IFormGridLayoutParams<T>): ComponentType<IFormGridLayoutProps<T>> {\r\n const FormBaseInstance = createFormBase<T>()\r\n const BottomBarInstance = CreateFormBottomBar<T>()\r\n const InputBaseInstance = createInput<T>({ maxLength: 250 })\r\n\r\n class FormGridLayout extends Component<IFormGridLayoutProps<T>, IFormGridLayoutState> {\r\n private abortController?: AbortController\r\n constructor(props: IFormGridLayoutProps<T>) {\r\n super(props)\r\n this.state = { loadding: false }\r\n }\r\n\r\n get configMerged() {\r\n const { slots = {} } = this.props\r\n return {\r\n hiddenFields: slots.hiddenFields ?? params.hiddenFields ?? (() => ({}) as Partial<Record<keyof T, boolean>>),\r\n disabledFields: slots.disabledFields ?? params.disabledFields ?? (() => ({}) as Partial<Record<keyof T, boolean>>)\r\n }\r\n }\r\n\r\n render() {\r\n const { slots, data, autoHeight } = this.props\r\n const BottomBar = params?.action ?? slots?.action ?? BottomBarInstance\r\n\r\n const rootClasses = [formGridLayoutClasses.root, slots?.rootProps?.className]\r\n if (autoHeight ?? params.autoHeight) rootClasses.push(formGridLayoutClasses.autoHeight)\r\n\r\n return mapGlobalModalContext(({ close }) => (\r\n <FormGridLayoutStyled {...slots?.rootProps} className={rootClasses.filter(Boolean).join(' ')}>\r\n <FormBaseInstance.Form\r\n className={formGridLayoutClasses.form}\r\n validate={params.validate}\r\n onSubmit={(v) => this.onSubmit(v, close)}\r\n slots={this.getFormSlots()}\r\n onError={this.props.onSubmitError}\r\n >\r\n {slots?.contentBefore && slots?.contentBefore}\r\n {params?.contentBefore}\r\n {FormBaseInstance.mapContext((context) => {\r\n const { hiddenFields } = this.configMerged\r\n const mState = context.modelState || {}\r\n const finalHiddenFields = typeof hiddenFields === 'function' ? hiddenFields(mState, data) : hiddenFields || {}\r\n return (\r\n <Grid container spacing={2}>\r\n {params.configs.map((config, index) => {\r\n const isHidden: boolean | undefined = finalHiddenFields[config.key] ? true : undefined\r\n if (isHidden) return <Fragment key={config.key.toString() + index} />\r\n return (\r\n <Fragment key={config.key.toString() + index}>\r\n <Grid item xs={12} {...config.sizes} className={config.className}>\r\n {this.renderFormFieldElement(context, config)}\r\n </Grid>\r\n </Fragment>\r\n )\r\n })}\r\n </Grid>\r\n )\r\n })}\r\n {params?.contentAfter}\r\n {slots?.contentAfter && slots?.contentAfter}\r\n {FormBaseInstance.mapContext((context) => (\r\n <BottomBar data={data} onBlur={context.onBlur} messageErrors={context.messageErrors} before={slots?.actionBefore} />\r\n ))}\r\n </FormBaseInstance.Form>\r\n </FormGridLayoutStyled>\r\n ))\r\n }\r\n\r\n renderFormFieldElement = (context: IFormBaseContext<T>, config: IFormGridLayoutConfig<T>) => {\r\n const { data } = this.props\r\n const ElementComponent = config.inputElement ?? InputBaseInstance\r\n const mState = context.modelState || {}\r\n const { disabledFields } = this.configMerged\r\n const finalDisabledFields = typeof disabledFields === 'function' ? disabledFields(mState, data) : disabledFields || {}\r\n const obj: IFormInputBase<T, any> = {\r\n data,\r\n onBlur: context.onBlur,\r\n messageErrors: context.messageErrors,\r\n name: config.key,\r\n label: config.label,\r\n placeholder: config.placeholder,\r\n disabled: finalDisabledFields[config.key] ? true : undefined,\r\n defaultValue: data?.[config.key] ?? config?.defaultValue,\r\n formContext: context\r\n }\r\n return <ElementComponent {...cleanObject(obj)} />\r\n }\r\n\r\n loading = () => this.setState({ loadding: true })\r\n\r\n unloading = () => this.setState({ loadding: false })\r\n\r\n componentWillUnmount(): void {\r\n this.abortController?.abort()\r\n }\r\n\r\n onSubmit = async (value: Partial<T>, close?: () => void) => {\r\n const { slots } = this.props\r\n const mapping = this.props.slots?.preSubmit ?? params.preSubmit ?? this.preSubmit\r\n const data = mapping(value, this.props.data)\r\n try {\r\n this.loading()\r\n this.abortController?.abort()\r\n this.abortController = new AbortController()\r\n await this.props.onSubmit(data, this.abortController?.signal)\r\n if (!slots?.closeState || slots.closeState.Success !== false) {\r\n close && close()\r\n this.props.onClose && this.props.onClose()\r\n }\r\n } catch (error) {\r\n if (slots?.closeState && slots.closeState.Fail === true) {\r\n close && close()\r\n this.props.onClose && this.props.onClose()\r\n }\r\n if (this.props.onError) this.props.onError(error)\r\n throw error\r\n } finally {\r\n this.unloading()\r\n }\r\n }\r\n\r\n preSubmit: IPreSubmitEvent<T> = (value) => value\r\n\r\n getFormSlots = (): IFormBaseSlots => {\r\n const isLoading = this.state.loadding\r\n const { formProps } = this.props.slots?.formSlots || {}\r\n return {\r\n formProps: {\r\n ...formProps,\r\n sx: {\r\n ...this.props.sx,\r\n opacity: isLoading ? 0.7 : 1,\r\n pointerEvents: isLoading ? 'none' : 'auto'\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return FormGridLayout\r\n}\r\n\r\nexport default CreateFormGridLayout\r\n"],"names":["CreateFormGridLayout","params","FormBaseInstance","createFormBase","BottomBarInstance","CreateFormBottomBar","InputBaseInstance","createInput","maxLength","FormGridLayout","props","_this","_classCallCheck","_callSuper","_defineProperty","context","config","_config$inputElement","_data$config$key","data","ElementComponent","inputElement","mState","modelState","disabledFields","configMerged","finalDisabledFields","obj","onBlur","messageErrors","name","key","label","placeholder","disabled","undefined","defaultValue","formContext","_jsx","_objectSpread","cleanObject","setState","loadding","_ref","_asyncToGenerator","_regenerator","m","_callee","value","close","_ref2","_this$props$slots$pre","_this$props$slots","slots","mapping","_this$abortController","_this$abortController2","_t","w","_context","p","n","preSubmit","loading","abortController","abort","AbortController","onSubmit","signal","closeState","Success","onClose","v","Fail","onError","unloading","f","a","_x","_x2","apply","this","arguments","_this$props$slots2","isLoading","state","formProps","formSlots","sx","opacity","pointerEvents","_inherits","Component","_createClass","get","_ref4","_slots$hiddenFields","_ref5","_slots$disabledFields","_this$props$slots3","hiddenFields","_ref6","_params$action","_slots$rootProps","_this2","_this$props","autoHeight","BottomBar","action","rootClasses","formGridLayoutClasses","root","rootProps","className","push","mapGlobalModalContext","_ref7","FormGridLayoutStyled","filter","Boolean","join","children","_jsxs","Form","form","validate","getFormSlots","onSubmitError","contentBefore","mapContext","finalHiddenFields","Grid","container","spacing","configs","map","index","isHidden","Fragment","item","xs","sizes","renderFormFieldElement","toString","contentAfter","before","actionBefore","_this$abortController3"],"mappings":"6oBA6DA,IAAMA,EAAuB,SAAaC,GACxC,IAAMC,EAAmBC,IACnBC,EAAoBC,IACpBC,EAAoBC,EAAe,CAAEC,UAAW,MAEhDC,aAEJ,SAAAA,EAAYC,GAA8B,IAAAC,EAER,OAFQC,OAAAH,GACxCE,EAAAE,EAAAJ,KAAAA,GAAMC,IAAMI,EAAAH,EAAA,yBA4DW,SAACI,EAA8BC,GAAoC,IAAAC,EAAAC,EAClFC,EAASR,EAAKD,MAAdS,KACFC,EAAsC,QAAtBH,EAAGD,EAAOK,oBAAY,IAAAJ,EAAAA,EAAIX,EAC1CgB,EAASP,EAAQQ,YAAc,CAAE,EAC/BC,EAAmBb,EAAKc,aAAxBD,eACFE,EAAgD,mBAAnBF,EAAgCA,EAAeF,EAAQH,GAAQK,GAAkB,CAAE,EAChHG,EAA8B,CAClCR,KAAAA,EACAS,OAAQb,EAAQa,OAChBC,cAAed,EAAQc,cACvBC,KAAMd,EAAOe,IACbC,MAAOhB,EAAOgB,MACdC,YAAajB,EAAOiB,YACpBC,WAAUR,EAAoBV,EAAOe,WAAcI,EACnDC,aAAgClB,QAApBA,EAAEC,aAAAA,EAAAA,EAAOH,EAAOe,YAAIb,IAAAA,EAAAA,EAAIF,aAAM,EAANA,EAAQoB,aAC5CC,YAAatB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F9E,EAASP,EAAQQ,YAAc,CAAE,EACjC2G,EAA4C,mBAAjB9B,EAA8BA,EAAa9E,EAAQH,GAAQiF,GAAgB,CAAE,EAC9G,OACE9D,EAAC6F,EAAI,CAACC,WAAU,EAAAC,QAAS,EAACZ,SACvBxH,EAAOqI,QAAQC,IAAI,SAACvH,EAAQwH,GAC3B,IAAMC,IAAgCP,EAAkBlH,EAAOe,WAAcI,EAC7E,OAAqBG,EAACoG,EAAlBD,EAAgC,CAAA,YAGhCnG,EAAC6F,EAAI5F,EAAAA,EAAA,CAACoG,MAAI,EAACC,GAAI,IAAQ5H,EAAO6H,OAAK,GAAA,CAAE5B,UAAWjG,EAAOiG,UACpDQ,SAAAjB,EAAKsC,uBAAuB/H,EAASC,OAJRA,EAAOe,IAAIgH,WAAaP,EAQ7D,IAGN,GACAvI,aAAAA,EAAAA,EAAQ+I,cACR3F,aAAAA,EAAAA,EAAO2F,gBAAgB3F,eAAAA,EAAO2F,cAC9B9I,EAAiB+H,WAAW,SAAClH,GAAO,OACnCuB,EAACqE,EAAS,CAACxF,KAAMA,EAAMS,OAAQb,EAAQa,OAAQC,cAAed,EAAQc,cAAeoH,OAAQ5F,aAAK,EAALA,EAAO6F,cAAgB,QAGnG,EAE3B,GAAC,CAAAnH,IAAA,uBAAAiB,MA0BD,WAAoB,IAAAmG,EACE,QAApBA,EAAIlE,KAACjB,uBAAe,IAAAmF,GAApBA,EAAsBlF,OACxB,IAAC,IA4CH,OAAOxD,CACT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{objectSpread2 as e,inherits as
|
|
1
|
+
import{objectSpread2 as e,inherits as n,createClass as r,classCallCheck as t,callSuper as i,defineProperty as o,asyncToGenerator as l,regenerator as a}from"../../_virtual/_rollupPluginBabelHelpers.js";import{jsx as s,jsxs as u}from"react/jsx-runtime";import{Component as p}from"react";import{styled as d,Typography as g,Box as f,TextField as m}from"@mui/material";import c from"@mui/icons-material/Download";import{getErrorMessage as h}from"./helpers.js";import{tryParseCsvFileToArray as v}from"../utils/helpers.js";function C(d){var C=function(){function C(n){var r;return t(this,C),r=i(this,C,[n]),o(r,"mergeConfigsCache",{name:"",onBlur:function(){},messageErrors:{}}),o(r,"refInput",null),o(r,"refTextFiled",null),o(r,"getTextFieldProps",function(){var n,t=r.props,i=t.label,o=t.name,l=h(r.mergeConfigs.messageErrors,r.mergeConfigs.name),a=null!=d&&d.subName?d.subName:"".concat(null==o?void 0:o.toString()).concat(null!==(n=null==d?void 0:d.suffixName)&&void 0!==n?n:"_file");return e({label:i,error:l.error,helperText:l.message,name:o?a:void 0,type:"file",variant:"outlined",fullWidth:!0,onChange:r.handleChange,inputProps:{accept:"text/csv"},InputLabelProps:{shrink:r.mergeConfigs.labelShrink}},r.mergeConfigs.textFieldProps)}),o(r,"upgradeMergeConfigs",function(e){var n,r,t,i,o,l,a,s,u,p,g,f,m=e.name,c=e.label,h=e.onBlur,v=e.messageErrors;return{textFieldProps:Object.assign({},null==d?void 0:d.textFieldProps,null===(n=e.slots)||void 0===n?void 0:n.textFieldProps),wrapProps:Object.assign({},null==d?void 0:d.wrapProps,null===(r=e.slots)||void 0===r?void 0:r.wrapProps),name:m,onBlur:h||function(){},messageErrors:v||{},downloadSampleUrl:null!==(t=null===(i=e.slots)||void 0===i?void 0:i.downloadSampleUrl)&&void 0!==t?t:null==d?void 0:d.downloadSampleUrl,titleText:null!==(o=null===(l=e.slots)||void 0===l?void 0:l.titleText)&&void 0!==o?o:null==d?void 0:d.titleText,subText:null!==(a=null===(s=e.slots)||void 0===s?void 0:s.subText)&&void 0!==a?a:null==d?void 0:d.subText,instructionalText:null!==(u=null===(p=e.slots)||void 0===p?void 0:p.instructionalText)&&void 0!==u?u:null==d?void 0:d.instructionalText,labelShrink:!1!==(null!==(g=null===(f=e.slots)||void 0===f?void 0:f.labelShrink)&&void 0!==g?g:null==d?void 0:d.labelShrink)&&!!c}}),o(r,"handleChange",function(){var e=l(a().m(function e(n){var t,i,o,l;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:if(i=null===(t=n.target.files)||void 0===t?void 0:t[0]){e.n=1;break}return e.a(2);case 1:return e.p=1,e.n=2,v(i);case 2:o=e.v,r.refInput&&(r.refInput.value=JSON.stringify(o)),r.setState({parsedData:o},function(){r.props.onChange&&r.props.onChange(o),r.mergeConfigs.onBlur(r.mergeConfigs.name)}),e.n=4;break;case 3:e.p=3,l=e.v,console.error("Error parsing CSV:",l),r.mergeConfigs.onBlur(r.mergeConfigs.name);case 4:return e.a(2)}},e,null,[[1,3]])}));return function(n){return e.apply(this,arguments)}}()),r.mergeConfigsCache=r.upgradeMergeConfigs(n),r.state={parsedData:[]},r}return n(C,p),r(C,[{key:"mergeConfigs",get:function(){return this.mergeConfigsCache}},{key:"inputValue",get:function(){return this.state.parsedData.length>0?JSON.stringify(this.state.parsedData):""}},{key:"shouldComponentUpdate",value:function(e){return e!==this.props&&(this.mergeConfigsCache=this.upgradeMergeConfigs(e)),!0}},{key:"render",value:function(){var n,r,t=this;return u(f,e(e({},this.mergeConfigs.wrapProps),{},{children:[this.mergeConfigs.titleText&&s(g,{variant:"subtitle1",component:"h6",sx:{fontWeight:600,mb:.5},children:this.mergeConfigs.titleText}),this.mergeConfigs.downloadSampleUrl&&u(f,{sx:{display:"flex",alignItems:"center",mb:1},children:[s(g,{variant:"subtitle2",component:"span",children:null!==(n=this.mergeConfigs.instructionalText)&&void 0!==n?n:"Metadata file, please fill out the form we provide."}),u(x,{href:this.mergeConfigs.downloadSampleUrl,children:[s("span",{children:" Download sample"}),s(c,{fontSize:"small"})]})]}),this.mergeConfigs.subText&&s(g,{variant:"body2",component:"span",sx:{display:"block",mb:1},children:this.mergeConfigs.subText}),s("input",{hidden:!0,name:null===(r=this.props.name)||void 0===r?void 0:r.toString(),type:"text",ref:function(e){return t.refInput=e},defaultValue:""}),s(m,e(e({},this.getTextFieldProps()),{},{inputRef:function(e){return t.refTextFiled=e}}))]}))}}])}();return C}var x=d(function(n){return s(g,e({variant:"subtitle2",component:"a",target:"_blank",download:!0},n))})(function(e){var n=e.theme;return{display:"flex",alignItems:"center",color:n.palette.primary.light,cursor:"pointer",fontWeight:600,marginLeft:"6px",gap:"4px",transition:"all 0.3s ease","&:hover":{textDecoration:"underline",color:n.palette.primary.dark}}});export{C as createInputFileCsvLocalParser};
|
|
2
2
|
//# sourceMappingURL=create.input-file.csv-local-parser.js.map
|
|
@@ -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 * 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\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.downloadSampleUrl && (\r\n <Box sx={{ display: 'flex', alignItems: 'center', mb: '10px' }}>\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 <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 } = this.props\r\n const eMessage = getErrorMessage(this.mergeConfigs.messageErrors, this.mergeConfigs.name)\r\n const mergedProps: TextFieldProps = {\r\n label,\r\n error: eMessage.error,\r\n helperText: eMessage.message,\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 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","label","eMessage","getErrorMessage","mergeConfigs","_objectSpread","error","helperText","message","type","variant","fullWidth","onChange","handleChange","inputProps","accept","InputLabelProps","shrink","labelShrink","textFieldProps","currentProps","_currentProps$slots","_currentProps$slots2","_currentProps$slots$d","_currentProps$slots3","_currentProps$slots$i","_currentProps$slots4","_currentProps$slots$l","_currentProps$slots5","Object","assign","slots","wrapProps","downloadSampleUrl","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","sx","display","alignItems","mb","_jsx","Typography","component","DownloadButton","href","DownloadIcon","fontSize","hidden","toString","ref","defaultValue","TextField","getTextFieldProps","inputRef","refTextFiled","styled","download","_ref3","theme","color","palette","primary","light","cursor","fontWeight","marginLeft","gap","transition","textDecoration","dark"],"mappings":"qkBA+DM,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,oBAqBxB,WAClB,IAAQO,EAAUP,EAAKD,MAAfQ,MACFC,EAAWC,EAAgBT,EAAKU,aAAaJ,cAAeN,EAAKU,aAAaN,MAapF,OAZiBO,EAAA,CACfJ,MAAAA,EACAK,MAAOJ,EAASI,MAChBC,WAAYL,EAASM,QACrBC,KAAM,OACNC,QAAS,WACTC,WAAW,EACXC,SAAUlB,EAAKmB,aACfC,WAAY,CAAEC,OAAQ,YACtBC,gBAAiB,CAAEC,OAAQvB,EAAKU,aAAac,cAC1CxB,EAAKU,aAAae,kBAGxBtB,EAAAH,EAEqB,sBAAA,SAAC0B,GAAuE,IAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EACpF9B,EAAuCsB,EAAvCtB,KAAMG,EAAiCmB,EAAjCnB,MAAOF,EAA0BqB,EAA1BrB,OAAQC,EAAkBoB,EAAlBpB,cAC7B,MAAO,CACLmB,eAAgBU,OAAOC,OAAO,GAAIvC,aAAAA,EAAAA,EAAQ4B,eAAkCE,QAApBA,EAAED,EAAaW,aAAbV,IAAkBA,OAAlBA,EAAAA,EAAoBF,gBAC9Ea,UAAWH,OAAOC,OAAO,GAAIvC,aAAAA,EAAAA,EAAQyC,UAA6BV,QAApBA,EAAEF,EAAaW,aAAbT,IAAkBA,OAAlBA,EAA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EAAA,OAAA,CAAAL,SAAA,qBACAK,EAACK,EAAa,CAAAC,SAAS,gBAI7BN,EAAO,QAAA,CAAAO,QAAO,EAAA9F,KAAqB,QAAjB8E,EAAEb,KAAKtE,MAAMK,YAAX8E,IAAeA,OAAfA,EAAAA,EAAiBiB,WAAYpF,KAAK,OAAOqF,IAAK,SAACA,GAAG,OAAMjB,EAAKvB,SAAWwC,CAAI,EAAEC,aAAa,KAC/GV,EAACW,EAAS3F,EAAAA,EAAK,CAAA,EAAA0D,KAAKkC,qBAAmB,GAAA,CAAEC,SAAU,SAACJ,GAAG,OAAMjB,EAAKsB,aAAeL,CAAG,QAG1F,IAAC,IAkDH,OAAOtG,CACT,CAEA,IAAMgG,EAAiBY,EAAO,SAACrD,GAAqC,OAClEsC,EAACC,EAAUjF,EAAA,CAACK,QAAQ,YAAY6E,UAAU,IAAItC,OAAO,SAASoD,UAAQ,GAAKtD,GAAK,EAD3DqD,CAEpB,SAAAE,GAAA,IAAGC,EAAKD,EAALC,MAAK,MAAQ,CACjBrB,QAAS,OACTC,WAAY,SACZqB,MAAOD,EAAME,QAAQC,QAAQC,MAC7BC,OAAQ,UACRC,WAAY,IACZC,WAAY,MACZC,IAAK,MACLC,WAAY,gBACZ,UAAW,CACTC,eAAgB,YAChBT,MAAOD,EAAME,QAAQC,QAAQQ,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,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,EAAiCwB,EAAjCxB,MAAOJ,EAA0B4B,EAA1B5B,O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B,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,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,EAA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AM,MACpB,EAGFzE,EAAY0E,EAAOT,EAAPS,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
|
+
{"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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EAAEf,KAAKxH,MAAMa,YAAX0H,IAAeA,OAAfA,EAAAA,EAAiBtH,WAAY4G,aAAcL,KAAKN,cAC7FM,KAAKoB,gBAAgB,QACtBpG,EAACqG,EAASxF,EAAK,CAAA,EAAAmE,KAAKsB,sBACnBtB,KAAKoB,gBAAgB,WAG5B,IAAC,GAgEL,EAMMxD,EAA8B,WAAP,OAC3B5C,EACE,MAAA,CAAAH,SAAAG,EAACuG,EAAgB,CAACC,KAAM,MACpB,EAGFzE,EAAY0E,EAAOT,EAAPS,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{
|
|
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, useEffect, useRef } from 'react'\r\nimport { Box, BoxProps, Button, 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\n\r\nconst FormBase = createFormBase<any>({})\r\nconst InputInstance = createInput<any>({})\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\nexport const DecoratorField: FC<IDecoratorFieldProps> = ({ type: inputType, renderInput, ...props }) => {\r\n const name = props.name?.toString() || ''\r\n const defaultValue = props.data?.[name] || props.defaultValue\r\n\r\n return FormBase.mapContext((context) => {\r\n const { messageErrors, onBlur } = context\r\n const err = getErrorMessage(context.messageErrors, props.name as any)\r\n if (renderInput) {\r\n const InputComp = renderInput\r\n return <InputComp {...props} messageErrors={messageErrors} onBlur={onBlur} formContext={context} />\r\n }\r\n switch (inputType) {\r\n case String:\r\n return <InputInstance {...props} messageErrors={messageErrors} onBlur={onBlur} formContext={context} />\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={context}\r\n />\r\n )\r\n case Boolean:\r\n return (\r\n <div>\r\n <label>{props.label || name}: </label>\r\n <input name={name} 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}</div>\r\n }\r\n })\r\n}\r\n\r\nexport interface IDecoratorFormSlots {\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<any>\r\n footerProps?: BoxProps & { [key: string]: any }\r\n footerSlots?: { after?: React.ReactNode; before?: React.ReactNode }\r\n}\r\n\r\nexport interface IDecoratorFormProps<T = any> {\r\n configClass?: any\r\n data?: Partial<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\r\n}\r\n\r\nexport const DecoratorForm: FC<IDecoratorFormProps> = (props) => {\r\n const { slots } = props\r\n const fields = getFormFields(props.configClass)\r\n const validators = getFormValidators(props.configClass)\r\n const preSubmitConfig = getFormPreSubmit(props.configClass)\r\n const abortControllerRef = useRef<AbortController | null>(null)\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 // Call the original onSubmit with processed data and abort signal\r\n if (props.onSubmit) {\r\n await props.onSubmit(processedData, signal)\r\n if (props.onSuccess) {\r\n props.onSuccess(processedData)\r\n }\r\n }\r\n } catch (error) {\r\n if (props.onError) {\r\n props.onError(error)\r\n }\r\n throw error\r\n }\r\n }\r\n\r\n const renderFooter = () => {\r\n if (slots?.isFooter === false) return null\r\n if (slots?.footer) {\r\n const FooterComponent = slots.footer\r\n return <FooterComponent />\r\n }\r\n const footerClassName = [slots?.footerProps?.className]\r\n if (props.enableStickyFooter) footerClassName.push('sticky-footer')\r\n return (\r\n <FooterStyled {...slots?.footerProps} className={footerClassName.filter(Boolean).join(' ')}>\r\n {slots?.footerSlots?.before}\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?.footerSlots?.after}\r\n </FooterStyled>\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 return (\r\n <FormBase.Form onSubmit={handleSubmit} validate={new FormValidator(validators)} 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, size, ...fieldOther } = field\r\n // Check visibility, default is visible (true or undefined)\r\n const isVisible = typeof visible === 'function' ? visible(props.data) : visible !== false\r\n if (!isVisible) return null\r\n // Check disabled state, default is enabled (false or undefined)\r\n const isDisabled = typeof disabled === 'function' ? disabled(props.data) : disabled === true\r\n return (\r\n <Grid item key={field.name.toString()} xs={12} {...size}>\r\n <DecoratorField data={props.data} {...fieldOther} disabled={isDisabled} />\r\n </Grid>\r\n )\r\n })}\r\n </Grid>\r\n {renderFooter()}\r\n {props.slots?.bottom}\r\n </FormBase.Form>\r\n )\r\n}\r\nexport default DecoratorForm\r\n\r\ntype IDecoratorFormOptions<T> = Partial<Omit<IDecoratorFormProps<T>, 'configClass'>>\r\n\r\nexport const createDecoratorForm = function <T>(configClass: any, params?: IDecoratorFormOptions<T>): ComponentType<IDecoratorFormProps<T>> {\r\n const DecoratorFormComp: FC<IDecoratorFormProps<T>> = (props) => {\r\n return <DecoratorForm configClass={configClass} {...params} {...props} />\r\n }\r\n return DecoratorFormComp\r\n}\r\n\r\nconst FooterStyled = styled(Box)(({ theme }) => ({\r\n display: 'flex',\r\n justifyContent: 'flex-end',\r\n padding: theme.spacing(1),\r\n '&.sticky-footer': {\r\n position: 'sticky',\r\n bottom: 0,\r\n backgroundColor: theme.palette.background.paper,\r\n zIndex: theme.zIndex.appBar,\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 }\r\n}))\r\n"],"names":["FormBase","createFormBase","InputInstance","createInput","DecoratorField","_ref","_props$name","_props$data","inputType","type","renderInput","props","_objectWithoutProperties","_excluded","name","toString","defaultValue","data","mapContext","context","messageErrors","onBlur","err","getErrorMessage","_jsx","_objectSpread","formContext","String","Number","slots","textFieldProps","Boolean","_jsxs","children","label","defaultChecked","style","color","error","message","DecoratorForm","_props$slots","_props$slots2","fields","getFormFields","configClass","validators","getFormValidators","preSubmitConfig","getFormPreSubmit","abortControllerRef","useRef","isFormRegistered","_props$configClass","Box","sx","border","padding","borderRadius","background","Typography","variant","fontWeight","marginBottom","handleSubmit","_ref2","_asyncToGenerator","_regenerator","m","_callee","abortController","signal","processedData","_t","w","_context","p","n","AbortController","current","handler","v","onSubmit","onSuccess","onError","a","_x","apply","this","arguments","useEffect","_abortControllerRef$c","abort","Form","validate","FormValidator","onSubmitError","formBase","top","Grid","container","spacing","contentProps","map","field","disabled","visible","size","fieldOther","_excluded2","isDisabled","item","xs","_slots$footerProps","_slots$footerSlots","_slots$footerSlots2","isFooter","footer","FooterComponent","footerClassName","footerProps","className","enableStickyFooter","push","FooterStyled","filter","join","footerSlots","before","Button","flex","after","renderFooter","bottom","createDecoratorForm","params","styled","_ref3","theme","display","justifyContent","position","backgroundColor","palette","paper","zIndex","appBar","boxShadow"],"mappings":"ypBASMA,EAAWC,EAAoB,IAC/BC,EAAgBC,EAAiB,IAQ1BC,EAA2C,SAA7BC,GAA4E,IAAAC,EAAAC,EAAtCC,EAASH,EAAfI,KAAiBC,EAAWL,EAAXK,YAAgBC,EAAKC,EAAAP,EAAAQ,GACzFC,GAAiBR,QAAVA,EAAAK,EAAMG,gBAAIR,SAAVA,EAAYS,aAAc,GACjCC,GAAyB,QAAVT,EAAAI,EAAMM,YAAI,IAAAV,OAAA,EAAVA,EAAaO,KAASH,EAAMK,aAEjD,OAAOhB,EAASkB,WAAW,SAACC,GAC1B,IAAQC,EAA0BD,EAA1BC,cAAeC,EAAWF,EAAXE,OACjBC,EAAMC,EAAgBJ,EAAQC,cAAeT,EAAMG,MACzD,GAAIJ,EAEF,OAAOc,EADWd,EACDe,EAAAA,KAAKd,GAAK,GAAA,CAAES,cAAeA,EAAeC,OAAQA,EAAQK,YAAaP,KAE1F,OAAQX,GACN,KAAKmB,OACH,OAAOH,EAACtB,EAAauB,EAAAA,KAAKd,GAAK,GAAA,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EAAM,CAACpE,QAAQ,YAAYxB,MAAM,UAAU5B,KAAK,SAASkG,KAAK,QAAQpD,GAAI,CAAE2E,KAAM,YAE1EjG,SAAA,WACRJ,SAAkBsF,QAAbA,EAALtF,EAAOkG,mBAAPZ,IAAkBA,OAAlBA,EAAAA,EAAoBgB,SAG1B,CA2BIC,GACW1F,QADGA,EACd/B,EAAMkB,aAANa,IAAWA,OAAXA,EAAAA,EAAa2F,SAGpB,EAKaC,EAAsB,SAAazF,EAAkB0F,GAIhE,OAHsD,SAAC5H,GACrD,OAAOa,EAACgB,EAAaf,EAAAA,EAAA,CAACoB,YAAaA,GAAiB0F,GAAY5H,GACjE,CAEH,EAEMiH,EAAeY,EAAOlF,EAAPkF,CAAY,SAAAC,GAAA,IAAGC,EAAKD,EAALC,MAAK,MAAQ,CAC/CC,QAAS,OACTC,eAAgB,WAChBnF,QAASiF,EAAMrC,QAAQ,GACvB,kBAAmB,CACjBwC,SAAU,SACVR,OAAQ,EACRS,gBAAiBJ,EAAMK,QAAQpF,WAAWqF,MAC1CC,OAAQP,EAAMO,OAAOC,OACrBC,UAAW,yFAEd"}
|
|
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,EAAW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ACRC,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{toConsumableArray as e,objectSpread2 as t,inherits as r,createClass as
|
|
1
|
+
import{toConsumableArray as e,objectSpread2 as t,inherits as r,createClass as n,classCallCheck as a,callSuper as o,defineProperty as c}from"../../_virtual/_rollupPluginBabelHelpers.js";import"../../_virtual/Reflect.js";var f=new Map;function u(e){return function(t){var u=e||t.name;f.set(u,t);var i=function(e){function t(){var e;a(this,t);for(var r=arguments.length,n=new Array(r),f=0;f<r;f++)n[f]=arguments[f];return e=o(this,t,[].concat(n)),c(e,"__class",u),e.__class=u,e}return r(t,e),n(t)}(t);return Object.defineProperty(i,"name",{value:t.name}),Object.defineProperty(i,"__class",{value:u}),i}}function i(e){if(!e)return!1;var t="function"==typeof e?e:null==e?void 0:e.constructor;if(!t)return!1;var r=t.__class||t.name;return!!r&&f.has(r)}function l(e){return function(t){return Reflect.defineMetadata("form:presubmit",{handler:e},t),t}}function s(e){return Reflect.getMetadata("form:presubmit",e)}function d(r){return function(n,a){var o=Reflect.getMetadata("design:type",n,a),c=r.type||o,f=Reflect.hasOwnMetadata("form:fields",n.constructor)?Reflect.getOwnMetadata("form:fields",n.constructor):[],u=f.findIndex(function(e){return e.name===a}),i=r.defaultValue;if(void 0===i)try{i=(new n.constructor)[a]}catch(e){i=void 0}var l=t(t({name:a,type:c,label:r.label||a},r),{},{defaultValue:i});if(u>=0)f[u]=l,Reflect.defineMetadata("form:fields",f,n.constructor);else{var s=[].concat(e(f),[l]);Reflect.defineMetadata("form:fields",s,n.constructor)}}}function m(t){var r=Object.getPrototypeOf(t),n=r&&r!==Function.prototype?m(r):[],a=Reflect.getMetadata("form:fields",t)||[];if(0===n.length)return a;var o=e(n),c=new Set(n.map(function(e){return e.name.toString()}));return a.forEach(function(e){var t=e.name.toString();if(c.has(t)){var r=o.findIndex(function(e){return e.name.toString()===t});r>=0&&(o[r]=e)}else o.push(e),c.add(t)}),o}function v(r){return function(n,a){var o=Reflect.getMetadata("form:validators",n.constructor)||[],c=e(o);c.push(t({name:a},r)),Reflect.defineMetadata("form:validators",c,n.constructor)}}function p(e){return(Reflect.getMetadata("form:validators",e)||[]).reduce(function(e,t){return e[t.name]={Rules:t.Rules,label:t.label},e},{})}export{d as formField,l as formPreSubmit,v as formValidate,m as getFormFields,s as getFormPreSubmit,p as getFormValidators,i as isFormRegistered,u as registerForm};
|
|
2
2
|
//# sourceMappingURL=decorator.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decorator.js","sources":["../../../src/form/decorator.ts"],"sourcesContent":["import 'reflect-metadata'\r\nimport { ComponentType } from 'react'\r\nimport { IFormInputBase } from './types'\r\nimport { IConfigValue, IFormValidatorConfig } from './validator'\r\n\r\nconst ClassRegistry = new Map<string, any>()\r\n\r\nexport function registerForm(name?: string) {\r\n return function <T extends { new (...args: any[]): {} }>(constructor: T) {\r\n const key = name || constructor.name\r\n ClassRegistry.set(key, constructor)\r\n class RegisteredClass extends constructor {\r\n __class = key\r\n constructor(...args: any[]) {\r\n super(...args)\r\n this.__class = key\r\n }\r\n }\r\n Object.defineProperty(RegisteredClass, 'name', { value: constructor.name })\r\n Object.defineProperty(RegisteredClass, '__class', { value: key })\r\n return RegisteredClass\r\n }\r\n}\r\n\r\n/**\r\n * Check whether a class (constructor) or an instance has been registered\r\n * with the @registerForm decorator.\r\n *\r\n * Accepts:\r\n * - the decorated constructor (function)\r\n * - the original constructor (function)\r\n * - an instance of the class\r\n *\r\n * Returns true when the underlying registry contains an entry for the\r\n * class key (either the custom name provided to the decorator or the\r\n * constructor name).\r\n */\r\nexport function isFormRegistered(target: any): boolean {\r\n if (!target) return false\r\n const ctor = typeof target === 'function' ? target : target?.constructor\r\n if (!ctor) return false\r\n const key = (ctor as any).__class || (ctor as any).name\r\n if (!key) return false\r\n return ClassRegistry.has(key)\r\n}\r\n\r\nexport interface IPreSubmitMetadata<T = any> {\r\n handler: (data: T, oldData: T) => Promise<any> | any\r\n}\r\n\r\nexport function formPreSubmit<T = any>(handler: IPreSubmitMetadata<T>['handler']) {\r\n return function <T extends { new (...args: any[]): {} }>(constructor: T) {\r\n Reflect.defineMetadata('form:presubmit', { handler }, constructor)\r\n return constructor\r\n }\r\n}\r\n\r\nexport function getFormPreSubmit(targetClass: any): IPreSubmitMetadata | undefined {\r\n return Reflect.getMetadata('form:presubmit', targetClass)\r\n}\r\n\r\nexport interface IFieldMetadata<T = any, O = {}> {\r\n name: keyof T | string\r\n label?: string\r\n placeholder?: string\r\n defaultValue?: any\r\n type?: any\r\n size?: Partial<Record<'xs' | 'sm' | 'md' | 'lg' | 'xl', number>>\r\n visible?: boolean | ((data?: T) => boolean)\r\n disabled?: boolean | ((data?: T) => boolean)\r\n renderInput?: ComponentType<IFormInputBase<T>>\r\n}\r\n\r\nexport function formField(options: Omit<IFieldMetadata, 'name'>) {\r\n return function (target: any, propertyKey: string) {\r\n const designType = Reflect.getMetadata('design:type', target, propertyKey)\r\n const actualType = options.type || designType\r\n\r\n // Get existing fields metadata - use hasOwnMetadata to avoid parent pollution\r\n const isMetaData = Reflect.hasOwnMetadata('form:fields', target.constructor)\r\n const existing: IFieldMetadata[] = isMetaData ? Reflect.getOwnMetadata('form:fields', target.constructor) : []\r\n\r\n // Check if this field already exists (override case)\r\n const existingIndex = existing.findIndex((f) => f.name === propertyKey)\r\n\r\n // Get default value from property if not explicitly provided\r\n // Need to create a temporary instance to get the initialized value\r\n let defaultValue = options.defaultValue\r\n if (defaultValue === undefined) {\r\n try {\r\n const tempInstance = new (target.constructor as any)()\r\n defaultValue = tempInstance[propertyKey]\r\n } catch {\r\n // If constructor fails, use undefined\r\n defaultValue = undefined\r\n }\r\n }\r\n\r\n const newField: IFieldMetadata = { name: propertyKey, type: actualType, label: options.label || propertyKey, ...options, defaultValue }\r\n\r\n if (existingIndex >= 0) {\r\n // Override existing field, keep position\r\n existing[existingIndex] = newField\r\n Reflect.defineMetadata('form:fields', existing, target.constructor)\r\n } else {\r\n // New field, append to end\r\n const fields = [...existing, newField]\r\n Reflect.defineMetadata('form:fields', fields, target.constructor)\r\n }\r\n }\r\n}\r\n\r\nexport const getFormFields = (targetClass: any): IFieldMetadata[] => {\r\n // Get parent class\r\n const parentClass = Object.getPrototypeOf(targetClass)\r\n\r\n // Get parent fields recursively\r\n const parentFields: IFieldMetadata[] = parentClass && parentClass !== Function.prototype ? getFormFields(parentClass) : []\r\n\r\n // Get current class fields\r\n const currentFields: IFieldMetadata[] = Reflect.getMetadata('form:fields', targetClass) || []\r\n\r\n // If no parent, return current fields directly\r\n if (parentFields.length === 0) {\r\n return currentFields\r\n }\r\n\r\n // Merge parent and current fields\r\n // Start with parent fields as base\r\n const mergedFields = [...parentFields]\r\n const fieldNames = new Set(parentFields.map((f) => f.name.toString()))\r\n\r\n // Process current class fields\r\n currentFields.forEach((currentField) => {\r\n const fieldName = currentField.name.toString()\r\n\r\n if (fieldNames.has(fieldName)) {\r\n // Override parent field - find and replace it in place\r\n const index = mergedFields.findIndex((f) => f.name.toString() === fieldName)\r\n if (index >= 0) {\r\n mergedFields[index] = currentField\r\n }\r\n } else {\r\n // New field - append to end\r\n mergedFields.push(currentField)\r\n fieldNames.add(fieldName)\r\n }\r\n })\r\n\r\n return mergedFields\r\n}\r\n\r\nexport interface IValidationMetadata extends IConfigValue {\r\n name: string\r\n}\r\n\r\nexport function formValidate(options: Omit<IValidationMetadata, 'name'>) {\r\n return function (target: any, propertyKey: string) {\r\n const existing: IValidationMetadata[] = Reflect.getMetadata('form:validators', target.constructor) || []\r\n const validators = [...existing]\r\n validators.push({ name: propertyKey, ...options })\r\n Reflect.defineMetadata('form:validators', validators, target.constructor)\r\n }\r\n}\r\n\r\nexport function getFormValidators<T = any>(targetClass: any): IFormValidatorConfig<T> {\r\n const metas: IValidationMetadata[] = Reflect.getMetadata('form:validators', targetClass) || []\r\n return metas.reduce<IFormValidatorConfig<T>>((acc, curr) => {\r\n acc[curr.name as keyof T] = { Rules: curr.Rules, label: curr.label }\r\n return acc\r\n }, {})\r\n}\r\n"],"names":["ClassRegistry","Map","registerForm","name","constructor","key","set","RegisteredClass","_constructor","_this","_classCallCheck","_len","arguments","length","args","Array","_key","_callSuper","this","concat","_defineProperty","__class","_inherits","_createClass","Object","defineProperty","value","isFormRegistered","target","ctor","has","formPreSubmit","handler","Reflect","defineMetadata","getFormPreSubmit","targetClass","getMetadata","formField","options","propertyKey","designType","actualType","type","existing","hasOwnMetadata","getOwnMetadata","existingIndex","findIndex","f","defaultValue","undefined","_unused","newField","_objectSpread","label","fields","_toConsumableArray","getFormFields","parentClass","getPrototypeOf","parentFields","Function","prototype","currentFields","mergedFields","fieldNames","Set","map","toString","forEach","currentField","fieldName","index","push","add","formValidate","validators","getFormValidators","reduce","acc","curr","Rules"],"mappings":"2NAKA,IAAMA,EAAgB,IAAIC,IAEpB,SAAUC,EAAaC,GAC3B,OAAO,SAAkDC,GACvD,IAAMC,EAAMF,GAAQC,EAAYD,KAChCH,EAAcM,IAAID,EAAKD,GAAY,IAC7BG,WAAgBC,GAEpB,SAAAD,IAA0B,IAAAE,EAAAC,OAAAH,GAAA,IAAA,IAAAI,EAAAC,UAAAC,OAAXC,EAAWC,IAAAA,MAAAJ,GAAAK,EAAA,EAAAA,EAAAL,EAAAK,IAAXF,EAAWE,GAAAJ,UAAAI,GAEN,OADlBP,EAAAQ,EAAAC,KAAAX,EAAAY,GAAAA,OAASL,IAAKM,EAAAX,EAAA,UAFNJ,GAGRI,EAAKY,QAAUhB,EAAGI,CACpB,CAAC,OAAAa,EAAAf,EAAAC,GAAAe,EAAAhB,EAAA,EAL2BH,GAS9B,OAFAoB,OAAOC,eAAelB,EAAiB,OAAQ,CAAEmB,MAAOtB,EAAYD,OACpEqB,OAAOC,eAAel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AAMsD,EAAgB,SAACtB,GAE5B,IAAMuB,EAAcnC,OAAOoC,eAAexB,GAGpCyB,EAAiCF,GAAeA,IAAgBG,SAASC,UAAYL,EAAcC,GAAe,GAGlHK,EAAkC/B,QAAQI,YAAY,cAAeD,IAAgB,GAG3F,GAA4B,IAAxByB,EAAahD,OACf,OAAOmD,EAKT,IAAMC,EAAYR,EAAOI,GACnBK,EAAa,IAAIC,IAAIN,EAAaO,IAAI,SAACnB,GAAC,OAAKA,EAAE9C,KAAKkE,UAAU,IAmBpE,OAhBAL,EAAcM,QAAQ,SAACC,GACrB,IAAMC,EAAYD,EAAapE,KAAKkE,WAEpC,GAAIH,EAAWpC,IAAI0C,GAAY,CAE7B,IAAMC,EAAQR,EAAajB,UAAU,SAACC,GAAC,OAAKA,EAAE9C,KAAKkE,aAAeG,IAC9DC,GAAS,IACXR,EAAaQ,GAASF,EAEzB,MAECN,EAAaS,KAAKH,GAClBL,EAAWS,IAAIH,EAEnB,GAEOP,CACT,EAMM,SAAUW,EAAarC,GAC3B,OAAO,SAAUX,EAAaY,GAC5B,IAAMI,EAAkCX,QAAQI,YAAY,kBAAmBT,EAAOxB,cAAgB,GAChGyE,EAAUpB,EAAOb,GACvBiC,EAAWH,KAAIpB,EAAA,CAAGnD,KAAMqC,GAAgBD,IACxCN,QAAQC,eAAe,kBAAmB2C,EAAYjD,EAAOxB,YAC9D,CACH,CAEM,SAAU0E,EAA2B1C,GAEzC,OADqCH,QAAQI,YAAY,kBAAmBD,IAAgB,IAC/E2C,OAAgC,SAACC,EAAKC,GAEjD,OADAD,EAAIC,EAAK9E,MAAmB,CAAE+E,MAAOD,EAAKC,MAAO3B,MAAO0B,EAAK1B,OACtDyB,CACR,EAAE,GACL"}
|
|
1
|
+
{"version":3,"file":"decorator.js","sources":["../../../src/form/decorator.ts"],"sourcesContent":["import 'reflect-metadata'\r\nimport { ComponentType } from 'react'\r\nimport { IFormInputBase } from './types'\r\nimport { IConfigValue, IFormValidatorConfig } from './validator'\r\n\r\nconst ClassRegistry = new Map<string, any>()\r\n\r\nexport function registerForm(name?: string) {\r\n return function <T extends { new (...args: any[]): {} }>(constructor: T) {\r\n const key = name || constructor.name\r\n ClassRegistry.set(key, constructor)\r\n class RegisteredClass extends constructor {\r\n __class = key\r\n constructor(...args: any[]) {\r\n super(...args)\r\n this.__class = key\r\n }\r\n }\r\n Object.defineProperty(RegisteredClass, 'name', { value: constructor.name })\r\n Object.defineProperty(RegisteredClass, '__class', { value: key })\r\n return RegisteredClass\r\n }\r\n}\r\n\r\n/**\r\n * Check whether a class (constructor) or an instance has been registered\r\n * with the @registerForm decorator.\r\n *\r\n * Accepts:\r\n * - the decorated constructor (function)\r\n * - the original constructor (function)\r\n * - an instance of the class\r\n *\r\n * Returns true when the underlying registry contains an entry for the\r\n * class key (either the custom name provided to the decorator or the\r\n * constructor name).\r\n */\r\nexport function isFormRegistered(target: any): boolean {\r\n if (!target) return false\r\n const ctor = typeof target === 'function' ? target : target?.constructor\r\n if (!ctor) return false\r\n const key = (ctor as any).__class || (ctor as any).name\r\n if (!key) return false\r\n return ClassRegistry.has(key)\r\n}\r\n\r\nexport interface IPreSubmitMetadata<T = any> {\r\n handler: (data: Partial<T>, oldData?: T) => Promise<any> | any\r\n}\r\n\r\nexport function formPreSubmit<T = any>(handler: IPreSubmitMetadata<T>['handler']) {\r\n return function <T extends { new (...args: any[]): {} }>(constructor: T) {\r\n Reflect.defineMetadata('form:presubmit', { handler }, constructor)\r\n return constructor\r\n }\r\n}\r\n\r\nexport function getFormPreSubmit<T = any>(targetClass: any): IPreSubmitMetadata<T> | undefined {\r\n return Reflect.getMetadata('form:presubmit', targetClass)\r\n}\r\n\r\nexport type ISizes = Partial<Record<'xs' | 'sm' | 'md' | 'lg' | 'xl', number>>\r\n\r\nexport interface IFieldMetadata<T = any, O = {}> {\r\n name: keyof T\r\n label?: string\r\n placeholder?: string\r\n defaultValue?: any\r\n type?: any\r\n sizes?: ISizes | ((data?: T, formState?: Partial<T>) => ISizes)\r\n visible?: boolean | ((data?: T, formState?: Partial<T>) => boolean)\r\n disabled?: boolean | ((data?: T, formState?: Partial<T>) => boolean)\r\n renderInput?: ComponentType<IFormInputBase<T>>\r\n}\r\n\r\nexport function formField<T = any>(options: Omit<IFieldMetadata<T>, 'name'>) {\r\n return function (target: any, propertyKey: string) {\r\n const designType = Reflect.getMetadata('design:type', target, propertyKey)\r\n const actualType = options.type || designType\r\n\r\n // Get existing fields metadata - use hasOwnMetadata to avoid parent pollution\r\n const isMetaData = Reflect.hasOwnMetadata('form:fields', target.constructor)\r\n const existing: IFieldMetadata<T>[] = isMetaData ? Reflect.getOwnMetadata('form:fields', target.constructor) : []\r\n\r\n // Check if this field already exists (override case)\r\n const existingIndex = existing.findIndex((f) => f.name === propertyKey)\r\n\r\n // Get default value from property if not explicitly provided\r\n // Need to create a temporary instance to get the initialized value\r\n let defaultValue = options.defaultValue\r\n if (defaultValue === undefined) {\r\n try {\r\n const tempInstance = new (target.constructor as any)()\r\n defaultValue = tempInstance[propertyKey]\r\n } catch {\r\n // If constructor fails, use undefined\r\n defaultValue = undefined\r\n }\r\n }\r\n\r\n const newField: IFieldMetadata<T> = {\r\n name: propertyKey as keyof T,\r\n type: actualType,\r\n label: options.label || propertyKey,\r\n ...options,\r\n defaultValue\r\n }\r\n\r\n if (existingIndex >= 0) {\r\n // Override existing field, keep position\r\n existing[existingIndex] = newField\r\n Reflect.defineMetadata('form:fields', existing, target.constructor)\r\n } else {\r\n // New field, append to end\r\n const fields = [...existing, newField]\r\n Reflect.defineMetadata('form:fields', fields, target.constructor)\r\n }\r\n }\r\n}\r\n\r\nexport function getFormFields<T = any>(targetClass: any): IFieldMetadata<T>[] {\r\n // Get parent class\r\n const parentClass = Object.getPrototypeOf(targetClass)\r\n\r\n // Get parent fields recursively\r\n const parentFields: IFieldMetadata<T>[] = parentClass && parentClass !== Function.prototype ? getFormFields<T>(parentClass) : []\r\n\r\n // Get current class fields\r\n const currentFields: IFieldMetadata<T>[] = Reflect.getMetadata('form:fields', targetClass) || []\r\n\r\n // If no parent, return current fields directly\r\n if (parentFields.length === 0) {\r\n return currentFields\r\n }\r\n\r\n // Merge parent and current fields\r\n // Start with parent fields as base\r\n const mergedFields = [...parentFields]\r\n const fieldNames = new Set(parentFields.map((f) => f.name.toString()))\r\n\r\n // Process current class fields\r\n currentFields.forEach((currentField) => {\r\n const fieldName = currentField.name.toString()\r\n\r\n if (fieldNames.has(fieldName)) {\r\n // Override parent field - find and replace it in place\r\n const index = mergedFields.findIndex((f) => f.name.toString() === fieldName)\r\n if (index >= 0) {\r\n mergedFields[index] = currentField\r\n }\r\n } else {\r\n // New field - append to end\r\n mergedFields.push(currentField)\r\n fieldNames.add(fieldName)\r\n }\r\n })\r\n\r\n return mergedFields\r\n}\r\n\r\nexport interface IValidationMetadata extends IConfigValue {\r\n name: string\r\n}\r\n\r\nexport function formValidate(options: Omit<IValidationMetadata, 'name'>) {\r\n return function (target: any, propertyKey: string) {\r\n const existing: IValidationMetadata[] = Reflect.getMetadata('form:validators', target.constructor) || []\r\n const validators = [...existing]\r\n validators.push({ name: propertyKey, ...options })\r\n Reflect.defineMetadata('form:validators', validators, target.constructor)\r\n }\r\n}\r\n\r\nexport function getFormValidators<T = any>(targetClass: any): IFormValidatorConfig<T> {\r\n const metas: IValidationMetadata[] = Reflect.getMetadata('form:validators', targetClass) || []\r\n return metas.reduce<IFormValidatorConfig<T>>((acc, curr) => {\r\n acc[curr.name as keyof T] = { Rules: curr.Rules, label: curr.label }\r\n return acc\r\n }, {})\r\n}\r\n"],"names":["ClassRegistry","Map","registerForm","name","constructor","key","set","RegisteredClass","_constructor","_this","_classCallCheck","_len","arguments","length","args","Array","_key","_callSuper","this","concat","_defineProperty","__class","_inherits","_createClass","Object","defineProperty","value","isFormRegistered","target","ctor","has","formPreSubmit","handler","Reflect","defineMetadata","getFormPreSubmit","targetClass","getMetadata","formField","options","propertyKey","designType","actualType","type","existing","hasOwnMetadata","getOwnMetadata","existingIndex","findIndex","f","defaultValue","undefined","_unused","newField","_objectSpread","label","fields","_toConsumableArray","getFormFields","parentClass","getPrototypeOf","parentFields","Function","prototype","currentFields","mergedFields","fieldNames","Set","map","toString","forEach","currentField","fieldName","index","push","add","formValidate","validators","getFormValidators","reduce","acc","curr","Rules"],"mappings":"2NAKA,IAAMA,EAAgB,IAAIC,IAEpB,SAAUC,EAAaC,GAC3B,OAAO,SAAkDC,GACvD,IAAMC,EAAMF,GAAQC,EAAYD,KAChCH,EAAcM,IAAID,EAAKD,GAAY,IAC7BG,WAAgBC,GAEpB,SAAAD,IAA0B,IAAAE,EAAAC,OAAAH,GAAA,IAAA,IAAAI,EAAAC,UAAAC,OAAXC,EAAWC,IAAAA,MAAAJ,GAAAK,EAAA,EAAAA,EAAAL,EAAAK,IAAXF,EAAWE,GAAAJ,UAAAI,GAEN,OADlBP,EAAAQ,EAAAC,KAAAX,EAAAY,GAAAA,OAASL,IAAKM,EAAAX,EAAA,UAFNJ,GAGRI,EAAKY,QAAUhB,EAAGI,CACpB,CAAC,OAAAa,EAAAf,EAAAC,GAAAe,EAAAhB,EAAA,EAL2BH,GAS9B,OAFAoB,OAAOC,eAAelB,EAAiB,OAAQ,CAAEmB,MAAOtB,EAAYD,OACpEqB,OAAOC,eAAelB,EAAiB,UAAW,CAAEmB,MAAOrB,IACpDE,CACR,CACH,CAeM,SAAUoB,EAAiBC,GAC/B,IAAKA,EAAQ,OAAO,EACpB,IAAMC,EAAyB,mBAAXD,EAAwBA,EAASA,aAAAA,EAAAA,EAAQxB,YAC7D,IAAKyB,EAAM,OAAO,EAClB,IAAMxB,EAAOwB,EAAaR,SAAYQ,EAAa1B,KACnD,QAAKE,GACEL,EAAc8B,IAAIzB,EAC3B,CAMM,SAAU0B,EAAuBC,GACrC,OAAO,SAAkD5B,GAEvD,OADA6B,QAAQC,eAAe,iBAAkB,CAAEF,QAAAA,GAAW5B,GAC/CA,CACR,CACH,CAEM,SAAU+B,EAA0BC,GACxC,OAAOH,QAA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ajB,UAAU,SAACC,GAAC,OAAKA,EAAE9C,KAAKkE,aAAeG,IAC9DC,GAAS,IACXR,EAAaQ,GAASF,EAEzB,MAECN,EAAaS,KAAKH,GAClBL,EAAWS,IAAIH,EAEnB,GAEOP,CACT,CAMM,SAAUW,EAAarC,GAC3B,OAAO,SAAUX,EAAaY,GAC5B,IAAMI,EAAkCX,QAAQI,YAAY,kBAAmBT,EAAOxB,cAAgB,GAChGyE,EAAUpB,EAAOb,GACvBiC,EAAWH,KAAIpB,EAAA,CAAGnD,KAAMqC,GAAgBD,IACxCN,QAAQC,eAAe,kBAAmB2C,EAAYjD,EAAOxB,YAC9D,CACH,CAEM,SAAU0E,EAA2B1C,GAEzC,OADqCH,QAAQI,YAAY,kBAAmBD,IAAgB,IAC/E2C,OAAgC,SAACC,EAAKC,GAEjD,OADAD,EAAIC,EAAK9E,MAAmB,CAAE+E,MAAOD,EAAKC,MAAO3B,MAAO0B,EAAK1B,OACtDyB,CACR,EAAE,GACL"}
|
|
@@ -0,0 +1,2 @@
|
|
|
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
|
+
//# sourceMappingURL=decorator.units.js.map
|
|
@@ -0,0 +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 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"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createClass as r,classCallCheck as e,defineProperty as t}from"../../_virtual/_rollupPluginBabelHelpers.js";import{FormBottomBarWrap as i}from"./create.form-grid-layout.units.js";import{createInputFileCsvLocalParser as o}from"./create.input-file.csv-local-parser.js";import{
|
|
1
|
+
import{createClass as r,classCallCheck as e,defineProperty as t}from"../../_virtual/_rollupPluginBabelHelpers.js";import{FormBottomBarWrap as i}from"./create.form-grid-layout.units.js";import{createInputFileCsvLocalParser as o}from"./create.input-file.csv-local-parser.js";import{createDecoratorForm as a}from"./decorator.form.js";import{FormValidator as m}from"./validator.js";import s from"./create.input.js";import c from"./modal-wrapper.js";import p from"./create.form-base.js";import l from"./create.input.file.js";import f from"./create.date-picker.js";import h from"./create.text-editor.js";import{createColorPicker as j}from"./create.color-picker.js";import u from"./create.date-expired.js";import d from"./create.form-comfirm.js";import n from"./create.select-simple.js";import F from"./create.select-with-api.js";import C from"./create.form-grid-layout.js";import v from"./create.input.image-file.js";import g from"./create.autocomplete.chips.js";var k=new(r(function r(){e(this,r),t(this,"ModalWrap",c),t(this,"BottomBarWrap",i),t(this,"FormValidator",m),t(this,"validator",m.initial),t(this,"createFormBase",p),t(this,"createFormComfirm",d),t(this,"createFormGridLayout",C),t(this,"createDecoratorForm",a),t(this,"createColorPicker",j),t(this,"createDateExpired",u),t(this,"createDatePicker",f),t(this,"createAutocompleteChip",g),t(this,"createInputFileCsvLocalParser",o),t(this,"createInputFile",l),t(this,"createInputImageFile",v),t(this,"createInput",s),t(this,"createSelectSimple",n),t(this,"createSelectWithApi",F),t(this,"createTextEditor",h)}));export{k as default};
|
|
2
2
|
//# sourceMappingURL=dino-form.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dino-form.js","sources":["../../../src/form/dino-form.tsx"],"sourcesContent":["import { FormBottomBarWrap } from './create.form-grid-layout.units'\r\nimport { createInputFileCsvLocalParser } from './create.input-file.csv-local-parser'\r\nimport
|
|
1
|
+
{"version":3,"file":"dino-form.js","sources":["../../../src/form/dino-form.tsx"],"sourcesContent":["import { FormBottomBarWrap } from './create.form-grid-layout.units'\r\nimport { createInputFileCsvLocalParser } from './create.input-file.csv-local-parser'\r\nimport createDecoratorForm from './decorator.form'\r\nimport FormValidator from './validator'\r\nimport createInput from './create.input'\r\nimport FormModalWrapper from './modal-wrapper'\r\nimport createFormBase from './create.form-base'\r\nimport CreateInputFile from './create.input.file'\r\nimport CreateDatePicker from './create.date-picker'\r\nimport CreateTextEditor from './create.text-editor'\r\nimport createColorPicker from './create.color-picker'\r\nimport CreateDateExpired from './create.date-expired'\r\nimport CreateFormComfirm from './create.form-comfirm'\r\nimport createSelectSimple from './create.select-simple'\r\nimport createSelectWithApi from './create.select-with-api'\r\nimport CreateFormGridLayout from './create.form-grid-layout'\r\nimport createInputImageFile from './create.input.image-file'\r\nimport CreateAutocompleteChip from './create.autocomplete.chips'\r\n\r\nclass DinoFormBase {\r\n //#region Base\r\n ModalWrap = FormModalWrapper\r\n BottomBarWrap = FormBottomBarWrap\r\n FormValidator = FormValidator\r\n validator = FormValidator.initial\r\n createFormBase = createFormBase\r\n createFormComfirm = CreateFormComfirm\r\n createFormGridLayout = CreateFormGridLayout\r\n createDecoratorForm = createDecoratorForm\r\n //#endregion\r\n\r\n //#region Inputs\r\n createColorPicker = createColorPicker\r\n createDateExpired = CreateDateExpired\r\n createDatePicker = CreateDatePicker\r\n createAutocompleteChip = CreateAutocompleteChip\r\n createInputFileCsvLocalParser = createInputFileCsvLocalParser\r\n createInputFile = CreateInputFile\r\n createInputImageFile = createInputImageFile\r\n createInput = createInput\r\n createSelectSimple = createSelectSimple\r\n createSelectWithApi = createSelectWithApi\r\n createTextEditor = CreateTextEditor\r\n //#endregion\r\n}\r\n\r\nconst DinoForm = new DinoFormBase()\r\nexport default DinoForm\r\n"],"names":["DinoForm","_createClass","DinoFormBase","_classCallCheck","_defineProperty","FormModalWrapper","FormBottomBarWrap","FormValidator","this","initial","createFormBase","CreateFormComfirm","CreateFormGridLayout","createDecoratorForm","createColorPicker","CreateDateExpired","CreateDatePicker","CreateAutocompleteChip","createInputFileCsvLocalParser","CreateInputFile","createInputImageFile","createInput","createSelectSimple","createSelectWithApi","CreateTextEditor"],"mappings":"67BAiBgE,IA6B1DA,EAAW,IA3BCC,EAAA,SAAAC,IAAAC,OAAAD,GAChBE,mBACYC,GAAgBD,uBACZE,GAAiBF,uBACjBG,GAAaH,EAAAI,KAAA,YACjBD,EAAcE,SAAOL,wBAChBM,GAAcN,2BACXO,GAAiBP,8BACdQ,GAAoBR,6BACrBS,GAGtBT,2BACoBU,GAAiBV,2BACjBW,GAAiBX,0BAClBY,GAAgBZ,gCACVa,GAAsBb,uCACfc,GAA6Bd,yBAC3Ce,GAAef,8BACVgB,GAAoBhB,qBAC7BiB,GAAWjB,4BACJkB,GAAkBlB,6BACjBmB,GAAmBnB,0BACtBoB,EAAgB"}
|