dinocollab-core 2.2.45 → 2.2.47
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/README.md +1 -1
- package/dist/components/index.js +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/data-surface/index.create.js +1 -1
- package/dist/src/data-surface/index.create.js.map +1 -1
- package/dist/src/data-surface/types.js.map +1 -1
- package/dist/src/data-surface/ui.units.js +1 -1
- package/dist/src/data-surface/ui.units.js.map +1 -1
- package/dist/src/data-view/create.active-filters-panel.js +1 -1
- package/dist/src/data-view/create.active-filters-panel.js.map +1 -1
- package/dist/src/data-view/dino.js +1 -1
- package/dist/src/data-view/dino.js.map +1 -1
- package/dist/src/data-view/filter-store.js +1 -1
- package/dist/src/data-view/filter-store.js.map +1 -1
- package/dist/src/data-view/query-param-url.js +1 -1
- package/dist/src/data-view/query-param-url.js.map +1 -1
- package/dist/src/form/create.date-expired.js +1 -1
- package/dist/src/form/create.date-expired.js.map +1 -1
- package/dist/src/form/create.date-picker.js +1 -1
- package/dist/src/form/create.date-picker.js.map +1 -1
- package/dist/src/form/create.form-comfirm.js +1 -1
- package/dist/src/form/create.form-comfirm.js.map +1 -1
- package/dist/src/form/create.form-grid-layout.js +1 -1
- package/dist/src/form/create.form-grid-layout.js.map +1 -1
- package/dist/src/form/create.input-file.csv-local-parser.js +1 -1
- package/dist/src/form/create.input-file.csv-local-parser.js.map +1 -1
- package/dist/src/form/create.input.js +1 -1
- package/dist/src/form/create.input.js.map +1 -1
- package/dist/src/form/create.select-with-api.js.map +1 -1
- package/dist/src/form/decorator.form.js +1 -1
- package/dist/src/form/decorator.form.js.map +1 -1
- package/dist/src/form/decorator.units.js +1 -1
- package/dist/src/form/decorator.units.js.map +1 -1
- package/dist/src/form/dino-form.js +1 -1
- package/dist/src/form/dino-form.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/table/index.js +1 -1
- package/dist/types/components/index.d.ts +0 -4
- package/dist/types/data-surface/index.create.d.ts +4 -2
- package/dist/types/data-surface/types.d.ts +1 -0
- package/dist/types/data-surface/ui.units.d.ts +1 -0
- package/dist/types/form/decorator.form.d.ts +2 -1
- package/dist/types/form/decorator.units.d.ts +1 -0
- package/dist/types/form/dino-form.d.ts +1 -3
- package/package.json +1 -2
- package/dist/src/components/text-editor.js +0 -2
- package/dist/src/components/text-editor.js.map +0 -1
- package/dist/src/components/text-editor.preview.js +0 -2
- package/dist/src/components/text-editor.preview.js.map +0 -1
- package/dist/src/form/create.text-editor.js +0 -2
- package/dist/src/form/create.text-editor.js.map +0 -1
- package/dist/types/components/text-editor.d.ts +0 -25
- package/dist/types/components/text-editor.preview.d.ts +0 -5
- package/dist/types/form/create.text-editor.d.ts +0 -42
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decorator.form.js","sources":["../../../src/form/decorator.form.tsx"],"sourcesContent":["import { ComponentType, FC, Fragment, useEffect, useMemo, useRef, useState } from 'react'\r\nimport { Box, BoxProps, CircularProgress, Grid, GridProps, Stack, styled, Typography } from '@mui/material'\r\nimport { fetchDelay } from '../utils'\r\nimport { IFormInputBase } from './types'\r\nimport { getErrorMessage } from './helpers'\r\nimport { FormFooter, IFormFooterProps, IFormFooterSlots } from './decorator.units'\r\nimport { getFormFields, getFormPreSubmit, getFormValidators, isFormRegistered } from './decorator'\r\nimport FormValidator, { IPartialError, IRuleOption } from './validator'\r\nimport createFormBase, { IFormBaseErrorHandlers, IFormBaseSlots } from './create.form-base'\r\nimport createInput from './create.input'\r\n\r\nexport interface IDecoratorFieldProps<T = any> extends IFormInputBase<T> {\r\n type?: any\r\n visible?: boolean | ((data: T) => boolean)\r\n renderInput?: ComponentType<IFormInputBase<T>>\r\n}\r\n\r\nfunction createDecoratorField<T>() {\r\n const InputInstance = createInput<T>({})\r\n\r\n const DecoratorField: FC<IDecoratorFieldProps<T>> = ({ type: inputType, renderInput, formContext, ...props }) => {\r\n const name = props.name\r\n const defaultValue = (name ? props.data?.[name] : props.defaultValue) ?? ''\r\n\r\n const { messageErrors, onBlur } = formContext ?? {}\r\n const err = getErrorMessage(formContext?.messageErrors, props.name as any)\r\n if (renderInput) {\r\n const InputComp = renderInput\r\n return <InputComp {...props} messageErrors={messageErrors} onBlur={onBlur} formContext={formContext} />\r\n }\r\n switch (inputType) {\r\n case String:\r\n return <InputInstance {...props} messageErrors={messageErrors} onBlur={onBlur} formContext={formContext} />\r\n case Number:\r\n return (\r\n <InputInstance\r\n {...props}\r\n slots={{ textFieldProps: { type: 'number' }, ...props.slots }}\r\n messageErrors={messageErrors}\r\n onBlur={onBlur}\r\n formContext={formContext}\r\n />\r\n )\r\n case Boolean:\r\n return (\r\n <div>\r\n <label>{props.label || name?.toString()}: </label>\r\n <input name={name?.toString()} type='checkbox' defaultChecked={defaultValue} />\r\n <span style={{ color: 'red' }}>{err.error ? err.message : ''}</span>\r\n </div>\r\n )\r\n default:\r\n return <div>Unsupported field type for {name?.toString()}</div>\r\n }\r\n }\r\n\r\n return DecoratorField\r\n}\r\n\r\nexport interface IDecoratorFormSlots<T> {\r\n top?: React.ReactNode\r\n bottom?: React.ReactNode\r\n isFooter?: React.ReactNode | boolean\r\n contentProps?: GridProps\r\n formBase?: IFormBaseSlots\r\n footer?: ComponentType<IFormFooterProps<T>>\r\n footerProps?: Omit<BoxProps, 'slots'>\r\n footerSlots?: IFormFooterSlots\r\n}\r\n\r\nexport interface IDecoratorFormProps<T = any> extends IFormBaseErrorHandlers<T> {\r\n configClass?: any\r\n data?: T\r\n onSubmit?: (data: Partial<T>, signal?: AbortSignal) => Promise<void>\r\n onError?: (error: any) => void\r\n onSubmitError?: (error: IPartialError<T>) => void\r\n onSuccess?: (data: Partial<T>) => void\r\n slots?: IDecoratorFormSlots<T>\r\n disableGutters?: boolean\r\n}\r\n\r\nexport type IDecoratorFormConfig<T> = Partial<Omit<IDecoratorFormProps<T>, 'configClass'>>\r\n\r\nexport const createDecoratorForm = function <T>(configClass: any, config?: IDecoratorFormConfig<T>): ComponentType<IDecoratorFormProps<T>> {\r\n const FormBase = createFormBase<T>({\r\n errorGetter: config?.errorGetter,\r\n errorCommonGetter: config?.errorCommonGetter\r\n })\r\n const DecoratorField = createDecoratorField<T>()\r\n\r\n const DecoratorForm: FC<IDecoratorFormProps<T>> = (props) => {\r\n const { slots } = props\r\n const fields = getFormFields<T>(props.configClass)\r\n const validators = getFormValidators<Partial<T>>(props.configClass)\r\n const preSubmitConfig = getFormPreSubmit<T>(props.configClass)\r\n const abortControllerRef = useRef<AbortController | null>(null)\r\n\r\n const [loading, setLoading] = useState(false)\r\n\r\n // If the provided configClass isn't registered via @registerForm,\r\n // show a simple, friendly error UI instead of throwing.\r\n if (!isFormRegistered(props.configClass)) {\r\n const name = props.configClass?.name || 'Unknown'\r\n return (\r\n <Box sx={{ border: '1px dashed #ccc', padding: 12, borderRadius: 4, color: '#333', background: '#fafafa' }}>\r\n <Typography variant='subtitle1' sx={{ fontWeight: 600, marginBottom: 6 }}>\r\n Form configuration not registered\r\n </Typography>\r\n <Typography variant='body1'>\r\n Configuration for \"{name}\" was not found. Did you forget to add <code>@registerForm</code> to the class?\r\n </Typography>\r\n </Box>\r\n )\r\n }\r\n\r\n const handleSubmit = async (data: any) => {\r\n // Create new AbortController for this submit\r\n const abortController = new AbortController()\r\n abortControllerRef.current = abortController\r\n const signal = abortController.signal\r\n\r\n let processedData = data\r\n try {\r\n // Execute presubmit handler if exists\r\n if (preSubmitConfig?.handler) {\r\n processedData = await preSubmitConfig.handler(data, props.data)\r\n // If handler returns null/undefined, use original data\r\n if (processedData === null || processedData === undefined) {\r\n processedData = data\r\n }\r\n }\r\n\r\n // Set loading state to true before calling onSubmit\r\n setLoading(true)\r\n\r\n // Call the original onSubmit with processed data and abort signal\r\n if (props.onSubmit) {\r\n await fetchDelay(() => props.onSubmit!(processedData, signal), 500) // Optional delay for UX purposes\r\n if (props.onSuccess) {\r\n props.onSuccess(processedData)\r\n }\r\n }\r\n setLoading(false) // Reset loading state after successful submit\r\n } catch (error) {\r\n if (props.onError) {\r\n props.onError(error)\r\n }\r\n setLoading(false) // Reset loading state on error\r\n throw error\r\n }\r\n }\r\n\r\n const renderFooter = () => {\r\n return FormBase.mapContext((context) => {\r\n if (slots?.isFooter === false) return <></>\r\n if (slots?.footer) {\r\n const FooterComponent = slots.footer\r\n return <FooterComponent formContext={context} />\r\n }\r\n\r\n const errorList = Object.values(context.messageErrors).filter(Boolean) as IRuleOption<T>[][]\r\n let message: string = ''\r\n if (errorList.length > 0) message = errorList[0]?.[0]?.message ?? 'An error has occurred, please check the form again'\r\n if (errorList.length > 1) {\r\n const remaining = errorList.length - 1\r\n message += ` (and ${remaining} more error${remaining > 1 ? 's' : ''})`\r\n }\r\n\r\n return <FormFooter slots={slots?.footerSlots} errorMessage={message} {...slots?.footerProps} />\r\n })\r\n }\r\n\r\n useEffect(() => {\r\n return () => {\r\n // Abort any pending request when component unmounts\r\n abortControllerRef.current?.abort()\r\n }\r\n }, [])\r\n\r\n const validate = useMemo(() => new FormValidator<Partial<T>>(validators), [validators])\r\n\r\n const rootClasses = useMemo(() => {\r\n const classes = [formClasses.root]\r\n if (props.disableGutters) classes.push(formClasses.disableGutters)\r\n return classes.join(' ')\r\n }, [props.disableGutters])\r\n\r\n return (\r\n <FormBase.Form flexBox onSubmit={handleSubmit} validate={validate} onError={props.onSubmitError} slots={slots?.formBase}>\r\n <DecoratorFormStyled className={rootClasses}>\r\n {props.slots?.top}\r\n <div className={formClasses.content}>\r\n <Grid container spacing={2} {...slots?.contentProps}>\r\n {fields.map((field) => {\r\n const { disabled, visible, sizes, ...fieldOther } = field\r\n return (\r\n <Fragment key={field.name.toString()}>\r\n {FormBase.mapContext((context) => {\r\n // Check visibility, default is visible (true or undefined)\r\n const isVisible = typeof visible === 'function' ? visible(props.data, context.modelState) : visible !== false\r\n if (!isVisible) return <></>\r\n // Check disabled state, default is enabled (false or undefined)\r\n const isDisabled = typeof disabled === 'function' ? disabled(props.data, context.modelState) : disabled === true\r\n // Determine sizes, default is full width (undefined)\r\n const finalSizes = typeof sizes === 'function' ? sizes(props.data, context.modelState) : sizes\r\n return (\r\n <Grid item xs={12} {...finalSizes}>\r\n <DecoratorField data={props.data} {...fieldOther} disabled={isDisabled} formContext={context} />\r\n </Grid>\r\n )\r\n })}\r\n </Fragment>\r\n )\r\n })}\r\n </Grid>\r\n </div>\r\n {renderFooter()}\r\n <Overlay className={loading ? 'loading' : ''}>\r\n <CircularProgress size={40} thickness={4} color='primary' />\r\n </Overlay>\r\n {props.slots?.bottom}\r\n </DecoratorFormStyled>\r\n </FormBase.Form>\r\n )\r\n }\r\n\r\n const DecoratorFormComp: FC<IDecoratorFormProps<T>> = (props) => {\r\n return <DecoratorForm configClass={configClass} {...config} {...props} />\r\n }\r\n return DecoratorFormComp\r\n}\r\nexport default createDecoratorForm\r\n\r\nconst formClasses = {\r\n root: 'DinoDecoratorForm-root',\r\n content: 'DinoDecoratorForm-content',\r\n disableGutters: 'DinoDecoratorForm-disableGutters'\r\n}\r\n\r\nconst DecoratorFormStyled = styled(Stack)(({ theme }) => ({\r\n flex: 1,\r\n minHeight: 0,\r\n [`& .${formClasses.content}`]: {\r\n flex: 1,\r\n minHeight: 0,\r\n padding: theme.spacing(2, 1.5),\r\n overflowY: 'auto'\r\n },\r\n [`&.${formClasses.disableGutters} .${formClasses.content}`]: { padding: 0 }\r\n}))\r\n\r\nconst Overlay = styled(Box)({\r\n position: 'absolute',\r\n top: 0,\r\n left: 0,\r\n width: '100%',\r\n height: '100%',\r\n backgroundColor: 'rgba(0, 0, 0, 0.3)',\r\n display: 'flex',\r\n alignItems: 'center',\r\n justifyContent: 'center',\r\n zIndex: 10,\r\n opacity: 0,\r\n visibility: 'hidden',\r\n transition: 'opacity 0.3s ease-in-out',\r\n pointerEvents: 'none',\r\n '&.loading': {\r\n opacity: 1,\r\n visibility: 'visible',\r\n pointerEvents: 'auto'\r\n }\r\n})\r\n"],"names":["createDecoratorForm","configClass","config","InputInstance","FormBase","createFormBase","errorGetter","errorCommonGetter","DecoratorField","createInput","_ref","_ref2","_props$data","inputType","type","renderInput","formContext","props","_objectWithoutProperties","_excluded","name","defaultValue","data","_ref3","messageErrors","onBlur","err","getErrorMessage","_jsx","_objectSpread","String","Number","slots","textFieldProps","Boolean","_jsxs","children","label","toString","defaultChecked","style","color","error","message","DecoratorForm","_props$slots","_props$slots2","fields","getFormFields","validators","getFormValidators","preSubmitConfig","getFormPreSubmit","abortControllerRef","useRef","_useState","useState","_useState2","_slicedToArray","loading","setLoading","isFormRegistered","_props$configClass","Box","sx","border","padding","borderRadius","background","Typography","variant","fontWeight","marginBottom","handleSubmit","_ref4","_asyncToGenerator","_regenerator","m","_callee","abortController","signal","processedData","_t","w","_context","p","n","AbortController","current","handler","v","onSubmit","fetchDelay","onSuccess","onError","a","_x","apply","this","arguments","useEffect","_abortControllerRef$c","abort","validate","useMemo","FormValidator","rootClasses","classes","formClasses","root","disableGutters","push","join","Form","flexBox","onSubmitError","formBase","DecoratorFormStyled","className","top","content","Grid","container","spacing","contentProps","map","field","disabled","visible","sizes","fieldOther","_excluded2","Fragment","mapContext","context","modelState","isDisabled","finalSizes","item","xs","_errorList$0$0$messag","_errorList$","isFooter","footer","FooterComponent","errorList","Object","values","filter","length","remaining","concat","FormFooter","footerSlots","errorMessage","footerProps","Overlay","CircularProgress","size","thickness","bottom","styled","Stack","_ref5","theme","_defineProperty","flex","minHeight","overflowY","position","left","width","height","backgroundColor","display","alignItems","justifyContent","zIndex","opacity","visibility","transition","pointerEvents"],"mappings":"83BAmFO,IAAMA,EAAsB,SAAaC,EAAkBC,GAChE,IAlEMC,EAkEAC,EAAWC,EAAkB,CACjCC,YAAaJ,aAAAA,EAAAA,EAAQI,YACrBC,kBAAmBL,aAAM,EAANA,EAAQK,oBAEvBC,GAtEAL,EAAgBM,EAAe,IAEe,SAAhCC,GAA4F,IAAAC,EAAAC,EAAnDC,EAASH,EAAfI,KAAiBC,EAAWL,EAAXK,YAAaC,EAAWN,EAAXM,YAAgBC,EAAKC,EAAAR,EAAAS,GAClGC,EAAOH,EAAMG,KACbC,EAA8D,QAAlDV,EAAIS,EAAiBR,QAAbA,EAAGK,EAAMK,YAANV,IAAUA,OAAVA,EAAAA,EAAaQ,GAAQH,EAAMI,oBAAY,IAAAV,EAAAA,EAAK,GAEzEY,EAAkCP,QAAAA,EAAe,CAAE,EAA3CQ,EAAaD,EAAbC,cAAeC,EAAMF,EAANE,OACjBC,EAAMC,EAAgBX,aAAAA,EAAAA,EAAaQ,cAAeP,EAAMG,MAC9D,GAAIL,EAEF,OAAOa,EADWb,EACDc,EAAAA,KAAKZ,GAAK,GAAA,CAAEO,cAAeA,EAAeC,OAAQA,EAAQT,YAAaA,KAE1F,OAAQH,GACN,KAAKiB,OACH,OAAOF,EAACzB,EAAa0B,EAAAA,KAAKZ,GAAK,GAAA,CAAEO,cAAeA,EAAeC,OAAQA,EAAQT,YAAaA,KAC9F,KAAKe,OACH,OACEH,EAACzB,EAAa0B,EAAAA,KACRZ,GAAK,GAAA,CACTe,MAAKH,EAAA,CAAII,eAAgB,CAAEnB,KAAM,WAAeG,EAAMe,OACtDR,cAAeA,EACfC,OAAQA,EACRT,YAAaA,KAGnB,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7B8C,KAAM,EACNC,UAAW,EACXrG,QAASkG,EAAMzC,QAAQ,EAAG,KAC1B6C,UAAW,SACZjB,KAAAA,OACK3C,EAAYE,eAAcyC,MAAAA,OAAK3C,EAAYY,SAAY,CAAEtD,QAAS,GAAG,GAGvE0F,EAAUK,EAAOlG,EAAPkG,CAAY,CAC1BQ,SAAU,WACVlD,IAAK,EACLmD,KAAM,EACNC,MAAO,OACPC,OAAQ,OACRC,gBAAiB,qBACjBC,QAAS,OACTC,WAAY,SACZC,eAAgB,SAChBC,OAAQ,GACRC,QAAS,EACTC,WAAY,SACZC,WAAY,2BACZC,cAAe,OACf,YAAa,CACXH,QAAS,EACTC,WAAY,UACZE,cAAe"}
|
|
1
|
+
{"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 loading?: 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\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} other 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 <div className={formClasses.content}>\r\n {props.slots?.top}\r\n <Grid container spacing={2} {...slots?.contentProps}>\r\n {fields.map((field) => {\r\n const { disabled, visible, sizes, ...fieldOther } = field\r\n return (\r\n <Fragment key={field.name.toString()}>\r\n {FormBase.mapContext((context) => {\r\n // Check visibility, default is visible (true or undefined)\r\n const isVisible = typeof visible === 'function' ? visible(props.data, context.modelState) : visible !== false\r\n if (!isVisible) return <></>\r\n // Check disabled state, default is enabled (false or undefined)\r\n const isDisabled = typeof disabled === 'function' ? disabled(props.data, context.modelState) : disabled === true\r\n // Determine sizes, default is full width (undefined)\r\n const finalSizes = typeof sizes === 'function' ? sizes(props.data, context.modelState) : sizes\r\n return (\r\n <Grid item xs={12} {...finalSizes}>\r\n <DecoratorField data={props.data} {...fieldOther} disabled={isDisabled} formContext={context} />\r\n </Grid>\r\n )\r\n })}\r\n </Fragment>\r\n )\r\n })}\r\n </Grid>\r\n {props.slots?.bottom}\r\n </div>\r\n {renderFooter()}\r\n <Overlay className={props.loading || loading ? 'loading' : ''}>\r\n <CircularProgress size={40} thickness={4} color='primary' />\r\n </Overlay>\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","content","top","Grid","container","spacing","contentProps","map","field","disabled","visible","sizes","fieldOther","_excluded2","Fragment","mapContext","context","modelState","isDisabled","finalSizes","item","xs","bottom","_errorList$0$0$messag","_errorList$","isFooter","footer","FooterComponent","errorList","Object","values","filter","length","remaining","concat","FormFooter","footerSlots","errorMessage","footerProps","Overlay","CircularProgress","size","thickness","styled","Stack","_ref5","theme","_defineProperty","flex","minHeight","overflowY","position","left","width","height","backgroundColor","display","alignItems","justifyContent","zIndex","opacity","visibility","transition","pointerEvents"],"mappings":"+7BAoFO,IAAMA,EAAsB,SAAaC,EAAmBC,GACjE,IAnEMC,EAmEAC,EAAWC,EAAkB,CACjCC,YAAaJ,aAAAA,EAAAA,EAAQI,YACrBC,kBAAmBL,aAAM,EAANA,EAAQK,oBAGvBC,GAxEAL,EAAgBM,EAAe,IAEe,SAAhCC,GAA4F,IAAAC,EAAAC,EAAnDC,EAASH,EAAfI,KAAiBC,EAAWL,EAAXK,YAAaC,EAAWN,EAAXM,YAAgBC,EAAKC,E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Spread2 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,
|
|
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,c=o.errorMessage,u=e(o,s);return a(m,r(r({className:[p].filter(Boolean).join(" ")},u),{},{children:[null==i?void 0:i.before,c&&t(l,{variant:"caption",color:"error",noWrap:!0,title:c,sx:{flex:1,fontWeight:600},children:c}),null==i?void 0:i.middle,t(n,{variant:"contained",color:"primary",type:"submit",size:"small",sx:{flex:"0 0 auto"},children:"Submit"}),null==i?void 0:i.after]}))},m=o(i)(function(e){var r=e.theme;return{display:"flex",justifyContent:"flex-end",alignItems:"center",padding:r.spacing(1,1.5),boxShadow:"rgba(145, 158, 171, 0.1) 0px 0px 2px 0px, rgba(145, 158, 171, 0.12) 0px 0px 24px -4px",gap:r.spacing(2)}});export{p as FormFooter};
|
|
2
2
|
//# sourceMappingURL=decorator.units.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decorator.units.js","sources":["../../../src/form/decorator.units.tsx"],"sourcesContent":["import { FC } from 'react'\r\nimport { Box, BoxProps, Button, styled, Typography } from '@mui/material'\r\nimport { IFormBaseContext } from './types'\r\n\r\nexport interface IFormFooterSlots {\r\n after?: React.ReactNode\r\n before?: React.ReactNode\r\n}\r\n\r\nexport interface IFormFooterProps<T = any> extends Omit<BoxProps, 'slots'> {\r\n formContext?: IFormBaseContext<T>\r\n}\r\n\r\ninterface IInternalFormFooterProps<T = any> extends IFormFooterProps<T> {\r\n 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","
|
|
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 middle?: 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 {slots?.middle}\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","children","before","_jsx","Typography","variant","color","noWrap","title","sx","flex","fontWeight","middle","Button","type","size","after","styled","Box","_ref","theme","display","justifyContent","alignItems","padding","spacing","boxShadow","gap"],"mappings":"kRAmBaA,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,CACxES,SAAA,CAAAZ,aAAAA,EAAAA,EAAOa,OACPX,GACCY,EAACC,GAAWC,QAAQ,UAAUC,MAAM,QAAQC,QAAO,EAAAC,MAAOjB,EAAckB,GAAI,CAAEC,KAAM,EAAGC,WAAY,KAChGV,SAAAV,IAGJF,aAAK,EAALA,EAAOuB,OACRT,EAACU,GAAOR,QAAQ,YAAYC,MAAM,UAAUQ,KAAK,SAASC,KAAK,QAAQN,GAAI,CAAEC,KAAM,YAE1ET,SAAA,WACRZ,aAAAA,EAAAA,EAAO2B,SAGd,EAEMpB,EAAeqB,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{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
|
|
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{createColorPicker as h}from"./create.color-picker.js";import u from"./create.date-expired.js";import j from"./create.form-comfirm.js";import d from"./create.select-simple.js";import n from"./create.select-with-api.js";import F from"./create.form-grid-layout.js";import C from"./create.input.image-file.js";import v from"./create.autocomplete.chips.js";var g=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",j),t(this,"createFormGridLayout",F),t(this,"createDecoratorForm",a),t(this,"createColorPicker",h),t(this,"createDateExpired",u),t(this,"createDatePicker",f),t(this,"createAutocompleteChip",v),t(this,"createInputFileCsvLocalParser",o),t(this,"createInputFile",l),t(this,"createInputImageFile",C),t(this,"createInput",s),t(this,"createSelectSimple",d),t(this,"createSelectWithApi",n)}));export{g 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 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
|
|
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 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 //#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"],"mappings":"s5BAgBgE,IA4B1DA,EAAW,IA1BCC,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,EAAmB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{defineProperty as e,createClass as r,classCallCheck as i}from"../../_virtual/_rollupPluginBabelHelpers.js";import{formatFileSize as u}from"../utils/helpers.js";var n
|
|
1
|
+
import{defineProperty as e,createClass as r,classCallCheck as i}from"../../_virtual/_rollupPluginBabelHelpers.js";import{formatFileSize as u}from"../utils/helpers.js";import"../utils/dayjs-config.js";import"../utils/query-param.js";var t,n;!function(e){e.Required="Required",e.Regex="Regex",e.RequiredValue="RequiredValue",e.Array="Array",e.Number="Number",e.Email="Email",e.PhoneNumber="PhoneNumber",e.Url="Url",e.File="File",e.FileRequired="FileRequired",e.Custom="Custom"}(n||(n={}));var s={Required:"The {0} is required",Regex:"The {0} is not match {1}",RequiredValue:"the {0} is not equal {1}",Array:"The {0} is not valid",Number:"{0} must be a number",Email:"The {0} is not valid",PhoneNumber:"The {0} is not valid",Url:"The {0} is not valid",File:"File size must be less than {1}",FileRequired:"The {0} is required",Custom:"Error Custom"},a=function(e,r){return r},l=r(function r(t){var l=this;i(this,r),e(this,"AddRules",function(e){var r,i=l.configs[e];i||(i={Rules:[]},l.configs[e]=i);for(var u=arguments.length,t=new Array(u>1?u-1:0),n=1;n<u;n++)t[n-1]=arguments[n];return(r=i.Rules).push.apply(r,t),l}),e(this,"Required",function(e,r){return null==r||""===r}),e(this,"Regex",function(e,r,i){return!!r&&!e.Value.test(r)}),e(this,"RequiredValue",function(e,r){return!!r&&r!==e.Value}),e(this,"Custom",function(e,r,i){return"function"!=typeof e.Value||e.Value(r,i)}),e(this,"Array",function(e,r){return!!r&&("number"!=typeof e.Value||(!Array.isArray(r)||r.length<=e.Value))}),e(this,"Number",function(e,r){return!!r&&isNaN(Number(r))}),e(this,"Email",function(e,r){if(!r)return!1;return!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r)}),e(this,"PhoneNumber",function(e,r){if(!r)return!1;return!/^(\+?\d{1,4}[\s-]?)?((\(\d{1,4}\))|\d{1,4})[\s-]?\d{1,4}[\s-]?\d{1,9}$/.test((null!=r?r:"").trim())}),e(this,"Url",function(e,r){if(!r)return!1;try{return new URL(r),!1}catch(e){return!0}}),e(this,"File",function(e,r){if(!r)return!1;var i=a(0,e.options),u=Array.isArray(r)?r:[r];return!!i&&(!0===i.all?u.reduce(function(e,r){return e+=r.size},0)>i.maxSize:u.some(function(e){return e.size>i.maxSize}))}),e(this,"FileRequired",function(e,r){return!!(Array.isArray(r)?r:[r]).filter(function(e){return!!e}).some(function(e){return e.size<=0})}),e(this,"RenderMessage",function(e,r,i,t){if(t&&"string"==typeof t)e.message=t;else if(!e.message)switch(e.message=s[e.rule].replace("{0}",null!=i?i:r),e.rule){case n.Regex:e.message=e.message.replace("{1}",e.Value.source);break;case n.RequiredValue:var l,o;e.message=e.message.replace("{1}",null!==(l=null===(o=e.Value)||void 0===o?void 0:o.toString())&&void 0!==l?l:"");break;case n.File:var c,f,m=a(0,e.options);if(!0===(null==m?void 0:m.all))e.message="Total file size must be less than ".concat(u((null!==(c=null==m?void 0:m.maxSize)&&void 0!==c?c:0)/1024));else e.message=e.message.replace("{1}",u((null!==(f=null==m?void 0:m.maxSize)&&void 0!==f?f:0)/1024))}return e.message=e.message.replace("{0}",r),e}),e(this,"run",function(e){var r=Object.keys(l.configs),i={};return r.forEach(function(r){var u=l.configs[r];if(u){var t=l.Executed(u,e[r],e);t.length<1||(i[r]=t.map(function(e){return l.RenderMessage(e.rule,r,u.label,e.value)}))}}),i}),e(this,"Executed",function(e,r,i){return e.Rules.map(function(e){var u=l[e.rule.toString()],t=u&&u(e,r,i);return{value:t,rule:e}}).filter(function(e){return e.value})}),this.configs=t});t=l,e(l,"initial",function(e){return new t(e)});var o=function(){return new l({})};export{l as FormValidator,n as SingleRuleValidate,o as createFormValidator,l as default,a as mapRuleOptions};
|
|
2
2
|
//# sourceMappingURL=validator.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.js","sources":["../../../src/form/validator.ts"],"sourcesContent":["import { formatFileSize } from '../utils'\r\n\r\nexport type IModelBase = { [key: string]: any }\r\n\r\nexport enum SingleRuleValidate {\r\n Required = 'Required',\r\n Regex = 'Regex',\r\n RequiredValue = 'RequiredValue',\r\n Array = 'Array',\r\n Number = 'Number',\r\n Email = 'Email',\r\n PhoneNumber = 'PhoneNumber',\r\n Url = 'Url',\r\n File = 'File',\r\n FileRequired = 'FileRequired',\r\n Custom = 'Custom'\r\n}\r\n\r\nconst MessageDefault = {\r\n Required: 'The {0} is required',\r\n Regex: 'The {0} is not match {1}',\r\n RequiredValue: 'the {0} is not equal {1}',\r\n Array: 'The {0} is not valid',\r\n Number: '{0} must be a number',\r\n Email: 'The {0} is not valid',\r\n PhoneNumber: 'The {0} is not valid',\r\n Url: 'The {0} is not valid',\r\n File: 'File size must be less than {1}',\r\n FileRequired: 'The {0} is required',\r\n Custom: 'Error Custom'\r\n}\r\n\r\nexport interface IRuleOptions {\r\n File: {\r\n maxSize: number\r\n // total size of files\r\n all?: boolean\r\n }\r\n}\r\n\r\nexport const mapRuleOptions = <TK extends keyof IRuleOptions>(key: TK, options?: IRuleOptions[TK]) => options\r\n\r\nexport interface IRuleOption<T = any> {\r\n rule: SingleRuleValidate\r\n message?: string\r\n Value?: RegExp | ((value: any, model: T) => boolean | string) | number | Array<any> | boolean\r\n options?: any\r\n}\r\n\r\nexport interface IConfigValue<T = any> {\r\n Rules: IRuleOption<T>[]\r\n label?: string\r\n}\r\n\r\nexport interface IModelError {\r\n message: string\r\n error: boolean\r\n}\r\n\r\nexport type IFormValidatorConfig<T> = {\r\n [key in keyof Extract<T, IModelBase>]?: IConfigValue<T>\r\n}\r\n\r\nexport type IPartialError<T> = {\r\n [key in keyof T]?: IRuleOption<T>[]\r\n}\r\n\r\nexport class FormValidator<T> {\r\n configs: IFormValidatorConfig<T>\r\n constructor(configs: IFormValidatorConfig<T>) {\r\n this.configs = configs\r\n }\r\n\r\n static initial = <T>(configs: IFormValidatorConfig<T>) => new FormValidator(configs)\r\n\r\n AddRules = (key: keyof T, ...rule: IRuleOption<T>[]) => {\r\n let fieldConfig = this.configs[key]\r\n if (!fieldConfig) {\r\n fieldConfig = { Rules: [] }\r\n this.configs[key] = fieldConfig\r\n }\r\n fieldConfig.Rules.push(...rule)\r\n return this\r\n }\r\n\r\n Required = (RuleOption: IRuleOption, value: any) => {\r\n return value === null || value === undefined || value === ''\r\n }\r\n Regex = (RuleOption: IRuleOption, value: string, Regex: RegExp) => {\r\n if (!value) return false\r\n return !(RuleOption.Value as RegExp).test(value)\r\n }\r\n RequiredValue = (RuleOption: IRuleOption, value: any) => {\r\n if (!value) return false\r\n return value !== RuleOption.Value\r\n }\r\n Custom = (RuleOption: IRuleOption, value: any, model: any) => {\r\n if (typeof RuleOption.Value === 'function') {\r\n return RuleOption.Value(value, model)\r\n }\r\n return true\r\n }\r\n Array = (RuleOption: IRuleOption, value: any) => {\r\n if (!value) return false\r\n if (typeof RuleOption.Value === 'number') {\r\n return Array.isArray(value) ? value.length <= RuleOption.Value : true\r\n }\r\n return true\r\n }\r\n Number = (RuleOption: IRuleOption, value: any) => {\r\n if (!value) return false\r\n return isNaN(Number(value))\r\n }\r\n Email = (RuleOption: IRuleOption, value: any) => {\r\n if (!value) return false\r\n const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/\r\n return !regex.test(value)\r\n }\r\n PhoneNumber = (RuleOption: IRuleOption, value: any) => {\r\n if (!value) return false\r\n const phoneRegex = /^(\\+?\\d{1,4}[\\s-]?)?((\\(\\d{1,4}\\))|\\d{1,4})[\\s-]?\\d{1,4}[\\s-]?\\d{1,9}$/\r\n return !phoneRegex.test((value ?? '').trim())\r\n }\r\n Url = (RuleOption: IRuleOption, value: any) => {\r\n if (!value) return false\r\n try {\r\n new URL(value)\r\n return false\r\n } catch (err) {\r\n return true\r\n }\r\n }\r\n File = (RuleOption: IRuleOption, value: any) => {\r\n if (!value) return false\r\n const options = mapRuleOptions('File', RuleOption.options)\r\n const files: File[] = Array.isArray(value) ? value : [value]\r\n if (!options) return false\r\n if (options.all === true) {\r\n const size = files.reduce((a, b) => {\r\n a += b.size\r\n return a\r\n }, 0)\r\n return size > options.maxSize\r\n } else {\r\n return files.some((x) => x.size > options.maxSize)\r\n }\r\n }\r\n FileRequired = (RuleOption: IRuleOption, value: any) => {\r\n const files: File[] = Array.isArray(value) ? value : [value]\r\n return !!files.filter((x) => !!x).some((x) => x.size <= 0)\r\n }\r\n RenderMessage = (RuleOption: IRuleOption, key: string, label?: string, message?: string | boolean) => {\r\n if (!!message && typeof message === 'string') {\r\n RuleOption.message = message\r\n } else if (!RuleOption.message) {\r\n RuleOption.message = MessageDefault[RuleOption.rule].replace('{0}', label ?? key)\r\n switch (RuleOption.rule) {\r\n case SingleRuleValidate.Regex: {\r\n RuleOption.message = RuleOption.message.replace('{1}', (RuleOption.Value as RegExp).source)\r\n break\r\n }\r\n case SingleRuleValidate.RequiredValue: {\r\n RuleOption.message = RuleOption.message.replace('{1}', RuleOption.Value?.toString() ?? '')\r\n break\r\n }\r\n case SingleRuleValidate.File: {\r\n const options = mapRuleOptions('File', RuleOption.options)\r\n if (options?.all === true) {\r\n RuleOption.message = `Total file size must be less than ${formatFileSize((options?.maxSize ?? 0) / 1024)}`\r\n } else {\r\n RuleOption.message = RuleOption.message.replace('{1}', formatFileSize((options?.maxSize ?? 0) / 1024))\r\n }\r\n break\r\n }\r\n default:\r\n break\r\n }\r\n }\r\n RuleOption.message = RuleOption.message.replace('{0}', key)\r\n return RuleOption\r\n }\r\n run = (model: T) => {\r\n const keys = Object.keys(this.configs)\r\n const data: IPartialError<T> = {}\r\n keys.forEach((key) => {\r\n const config = this.configs[key]\r\n if (!config) return\r\n const tmp = this.Executed(config, (model as any)[key], model)\r\n if (tmp.length < 1) return\r\n ;(data as any)[key] = tmp.map((x) => this.RenderMessage(x.rule, key, config.label, x.value))\r\n })\r\n return data\r\n }\r\n Executed = (Config: IConfigValue, valueField: any, model: any) => {\r\n return Config.Rules.map((Value) => {\r\n const action = (this as any)[Value.rule.toString()]\r\n const res = action && action(Value, valueField, model)\r\n return { value: typeof res === 'boolean' ? res : (res as string), rule: Value }\r\n }).filter((x) => x.value)\r\n }\r\n}\r\n\r\nexport default FormValidator\r\n\r\nexport const createFormValidator = <T>() => {\r\n return new FormValidator<Partial<T>>({})\r\n}\r\n"],"names":["SingleRuleValidate","MessageDefault","Required","Regex","RequiredValue","Array","Number","Email","PhoneNumber","Url","File","FileRequired","Custom","mapRuleOptions","key","options","FormValidator","_createClass","configs","_this","this","_classCallCheck","_defineProperty","_fieldConfig$Rules","fieldConfig","Rules","_len","arguments","length","rule","_key","push","apply","RuleOption","value","Value","test","model","isArray","isNaN","trim","URL","err","files","all","reduce","a","b","size","maxSize","some","x","filter","label","message","replace","source","_RuleOption$Value$toS","_RuleOption$Value","toString","_options$maxSize","_options$maxSize2","concat","formatFileSize","keys","Object","data","forEach","config","tmp","Executed","map","RenderMessage","Config","valueField","action","res","createFormValidator"],"mappings":"6KAIYA,GAAZ,SAAYA,GACVA,EAAA,SAAA,WACAA,EAAA,MAAA,QACAA,EAAA,cAAA,gBACAA,EAAA,MAAA,QACAA,EAAA,OAAA,SACAA,EAAA,MAAA,QACAA,EAAA,YAAA,cACAA,EAAA,IAAA,MACAA,EAAA,KAAA,OACAA,EAAA,aAAA,eACAA,EAAA,OAAA,QACD,CAZD,CAAYA,IAAAA,EAYX,CAAA,IAED,IAAMC,EAAiB,CACrBC,SAAU,sBACVC,MAAO,2BACPC,cAAe,2BACfC,MAAO,uBACPC,OAAQ,uBACRC,MAAO,uBACPC,YAAa,uBACbC,IAAK,uBACLC,KAAM,kCACNC,aAAc,sBACdC,OAAQ,gBAWGC,EAAiB,SAAgCC,EAASC,GAA0B,OAAKA,CAAO,EA2BhGC,EAAaC,EAExB,SAAAD,EAAYE,GAAgC,IAAAC,EAAAC,KAAAC,OAAAL,GAAAM,EAAAF,KAAA,WAMjC,SAACN,GAA2C,IAAAS,EACjDC,EAAcL,EAAKD,QAAQJ,GAC1BU,IACHA,EAAc,CAAEC,MAAO,IACvBN,EAAKD,QAAQJ,GAAOU,GACrB,IAAAE,IAAAA,EAAA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aAAO,EAAPA,EAASkC,eAAOY,IAAAA,EAAAA,EAAI,GAAK,OASxG,OADA5B,EAAWqB,QAAUrB,EAAWqB,QAAQC,QAAQ,MAAOzC,GAChDmB,IACRX,EAAAF,KAAA,MACK,SAACiB,GACL,IAAM2B,EAAOC,OAAOD,KAAK7C,EAAKD,SACxBgD,EAAyB,CAAE,EAQjC,OAPAF,EAAKG,QAAQ,SAACrD,GACZ,IAAMsD,EAASjD,EAAKD,QAAQJ,GAC5B,GAAKsD,EAAL,CACA,IAAMC,EAAMlD,EAAKmD,SAASF,EAAS/B,EAAcvB,GAAMuB,GACnDgC,EAAIzC,OAAS,IACfsC,EAAapD,GAAOuD,EAAIE,IAAI,SAACpB,GAAC,OAAKhC,EAAKqD,cAAcrB,EAAEtB,KAAMf,EAAKsD,EAAOf,MAAOF,EAAEjB,SAHxE,CAIf,GACOgC,IACR5C,kBACU,SAACmD,EAAsBC,EAAiBrC,GACjD,OAAOoC,EAAOhD,MAAM8C,IAAI,SAACpC,GACvB,IAAMwC,EAAUxD,EAAagB,EAAMN,KAAK8B,YAClCiB,EAAMD,GAAUA,EAAOxC,EAAOuC,EAAYrC,GAChD,MAAO,CAAEH,MAAkC0C,EAAuB/C,KAAMM,EAC1E,GAAGiB,OAAO,SAACD,GAAC,OAAKA,EAAEjB,UAhInBd,KAAKF,QAAUA,CACjB,KAJWF,EAAaM,EAAbN,EAMM,UAAA,SAAIE,GAAgC,OAAK,IAAIF,EAAcE,EAAQ,OAmIzE2D,EAAsB,WACjC,OAAO,IAAI7D,EAA0B,GACvC"}
|
|
1
|
+
{"version":3,"file":"validator.js","sources":["../../../src/form/validator.ts"],"sourcesContent":["import { formatFileSize } from '../utils'\r\n\r\nexport type IModelBase = { [key: string]: any }\r\n\r\nexport enum SingleRuleValidate {\r\n Required = 'Required',\r\n Regex = 'Regex',\r\n RequiredValue = 'RequiredValue',\r\n Array = 'Array',\r\n Number = 'Number',\r\n Email = 'Email',\r\n PhoneNumber = 'PhoneNumber',\r\n Url = 'Url',\r\n File = 'File',\r\n FileRequired = 'FileRequired',\r\n Custom = 'Custom'\r\n}\r\n\r\nconst MessageDefault = {\r\n Required: 'The {0} is required',\r\n Regex: 'The {0} is not match {1}',\r\n RequiredValue: 'the {0} is not equal {1}',\r\n Array: 'The {0} is not valid',\r\n Number: '{0} must be a number',\r\n Email: 'The {0} is not valid',\r\n PhoneNumber: 'The {0} is not valid',\r\n Url: 'The {0} is not valid',\r\n File: 'File size must be less than {1}',\r\n FileRequired: 'The {0} is required',\r\n Custom: 'Error Custom'\r\n}\r\n\r\nexport interface IRuleOptions {\r\n File: {\r\n maxSize: number\r\n // total size of files\r\n all?: boolean\r\n }\r\n}\r\n\r\nexport const mapRuleOptions = <TK extends keyof IRuleOptions>(key: TK, options?: IRuleOptions[TK]) => options\r\n\r\nexport interface IRuleOption<T = any> {\r\n rule: SingleRuleValidate\r\n message?: string\r\n Value?: RegExp | ((value: any, model: T) => boolean | string) | number | Array<any> | boolean\r\n options?: any\r\n}\r\n\r\nexport interface IConfigValue<T = any> {\r\n Rules: IRuleOption<T>[]\r\n label?: string\r\n}\r\n\r\nexport interface IModelError {\r\n message: string\r\n error: boolean\r\n}\r\n\r\nexport type IFormValidatorConfig<T> = {\r\n [key in keyof Extract<T, IModelBase>]?: IConfigValue<T>\r\n}\r\n\r\nexport type IPartialError<T> = {\r\n [key in keyof T]?: IRuleOption<T>[]\r\n}\r\n\r\nexport class FormValidator<T> {\r\n configs: IFormValidatorConfig<T>\r\n constructor(configs: IFormValidatorConfig<T>) {\r\n this.configs = configs\r\n }\r\n\r\n static initial = <T>(configs: IFormValidatorConfig<T>) => new FormValidator(configs)\r\n\r\n AddRules = (key: keyof T, ...rule: IRuleOption<T>[]) => {\r\n let fieldConfig = this.configs[key]\r\n if (!fieldConfig) {\r\n fieldConfig = { Rules: [] }\r\n this.configs[key] = fieldConfig\r\n }\r\n fieldConfig.Rules.push(...rule)\r\n return this\r\n }\r\n\r\n Required = (RuleOption: IRuleOption, value: any) => {\r\n return value === null || value === undefined || value === ''\r\n }\r\n Regex = (RuleOption: IRuleOption, value: string, Regex: RegExp) => {\r\n if (!value) return false\r\n return !(RuleOption.Value as RegExp).test(value)\r\n }\r\n RequiredValue = (RuleOption: IRuleOption, value: any) => {\r\n if (!value) return false\r\n return value !== RuleOption.Value\r\n }\r\n Custom = (RuleOption: IRuleOption, value: any, model: any) => {\r\n if (typeof RuleOption.Value === 'function') {\r\n return RuleOption.Value(value, model)\r\n }\r\n return true\r\n }\r\n Array = (RuleOption: IRuleOption, value: any) => {\r\n if (!value) return false\r\n if (typeof RuleOption.Value === 'number') {\r\n return Array.isArray(value) ? value.length <= RuleOption.Value : true\r\n }\r\n return true\r\n }\r\n Number = (RuleOption: IRuleOption, value: any) => {\r\n if (!value) return false\r\n return isNaN(Number(value))\r\n }\r\n Email = (RuleOption: IRuleOption, value: any) => {\r\n if (!value) return false\r\n const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/\r\n return !regex.test(value)\r\n }\r\n PhoneNumber = (RuleOption: IRuleOption, value: any) => {\r\n if (!value) return false\r\n const phoneRegex = /^(\\+?\\d{1,4}[\\s-]?)?((\\(\\d{1,4}\\))|\\d{1,4})[\\s-]?\\d{1,4}[\\s-]?\\d{1,9}$/\r\n return !phoneRegex.test((value ?? '').trim())\r\n }\r\n Url = (RuleOption: IRuleOption, value: any) => {\r\n if (!value) return false\r\n try {\r\n new URL(value)\r\n return false\r\n } catch (err) {\r\n return true\r\n }\r\n }\r\n File = (RuleOption: IRuleOption, value: any) => {\r\n if (!value) return false\r\n const options = mapRuleOptions('File', RuleOption.options)\r\n const files: File[] = Array.isArray(value) ? value : [value]\r\n if (!options) return false\r\n if (options.all === true) {\r\n const size = files.reduce((a, b) => {\r\n a += b.size\r\n return a\r\n }, 0)\r\n return size > options.maxSize\r\n } else {\r\n return files.some((x) => x.size > options.maxSize)\r\n }\r\n }\r\n FileRequired = (RuleOption: IRuleOption, value: any) => {\r\n const files: File[] = Array.isArray(value) ? value : [value]\r\n return !!files.filter((x) => !!x).some((x) => x.size <= 0)\r\n }\r\n RenderMessage = (RuleOption: IRuleOption, key: string, label?: string, message?: string | boolean) => {\r\n if (!!message && typeof message === 'string') {\r\n RuleOption.message = message\r\n } else if (!RuleOption.message) {\r\n RuleOption.message = MessageDefault[RuleOption.rule].replace('{0}', label ?? key)\r\n switch (RuleOption.rule) {\r\n case SingleRuleValidate.Regex: {\r\n RuleOption.message = RuleOption.message.replace('{1}', (RuleOption.Value as RegExp).source)\r\n break\r\n }\r\n case SingleRuleValidate.RequiredValue: {\r\n RuleOption.message = RuleOption.message.replace('{1}', RuleOption.Value?.toString() ?? '')\r\n break\r\n }\r\n case SingleRuleValidate.File: {\r\n const options = mapRuleOptions('File', RuleOption.options)\r\n if (options?.all === true) {\r\n RuleOption.message = `Total file size must be less than ${formatFileSize((options?.maxSize ?? 0) / 1024)}`\r\n } else {\r\n RuleOption.message = RuleOption.message.replace('{1}', formatFileSize((options?.maxSize ?? 0) / 1024))\r\n }\r\n break\r\n }\r\n default:\r\n break\r\n }\r\n }\r\n RuleOption.message = RuleOption.message.replace('{0}', key)\r\n return RuleOption\r\n }\r\n run = (model: T) => {\r\n const keys = Object.keys(this.configs)\r\n const data: IPartialError<T> = {}\r\n keys.forEach((key) => {\r\n const config = this.configs[key]\r\n if (!config) return\r\n const tmp = this.Executed(config, (model as any)[key], model)\r\n if (tmp.length < 1) return\r\n ;(data as any)[key] = tmp.map((x) => this.RenderMessage(x.rule, key, config.label, x.value))\r\n })\r\n return data\r\n }\r\n Executed = (Config: IConfigValue, valueField: any, model: any) => {\r\n return Config.Rules.map((Value) => {\r\n const action = (this as any)[Value.rule.toString()]\r\n const res = action && action(Value, valueField, model)\r\n return { value: typeof res === 'boolean' ? res : (res as string), rule: Value }\r\n }).filter((x) => x.value)\r\n }\r\n}\r\n\r\nexport default FormValidator\r\n\r\nexport const createFormValidator = <T>() => {\r\n return new FormValidator<Partial<T>>({})\r\n}\r\n"],"names":["SingleRuleValidate","MessageDefault","Required","Regex","RequiredValue","Array","Number","Email","PhoneNumber","Url","File","FileRequired","Custom","mapRuleOptions","key","options","FormValidator","_createClass","configs","_this","this","_classCallCheck","_defineProperty","_fieldConfig$Rules","fieldConfig","Rules","_len","arguments","length","rule","_key","push","apply","RuleOption","value","Value","test","model","isArray","isNaN","trim","URL","err","files","all","reduce","a","b","size","maxSize","some","x","filter","label","message","replace","source","_RuleOption$Value$toS","_RuleOption$Value","toString","_options$maxSize","_options$maxSize2","concat","formatFileSize","keys","Object","data","forEach","config","tmp","Executed","map","RenderMessage","Config","valueField","action","res","createFormValidator"],"mappings":"8OAIYA,GAAZ,SAAYA,GACVA,EAAA,SAAA,WACAA,EAAA,MAAA,QACAA,EAAA,cAAA,gBACAA,EAAA,MAAA,QACAA,EAAA,OAAA,SACAA,EAAA,MAAA,QACAA,EAAA,YAAA,cACAA,EAAA,IAAA,MACAA,EAAA,KAAA,OACAA,EAAA,aAAA,eACAA,EAAA,OAAA,QACD,CAZD,CAAYA,IAAAA,EAYX,CAAA,IAED,IAAMC,EAAiB,CACrBC,SAAU,sBACVC,MAAO,2BACPC,cAAe,2BACfC,MAAO,uBACPC,OAAQ,uBACRC,MAAO,uBACPC,YAAa,uBACbC,IAAK,uBACLC,KAAM,kCACNC,aAAc,sBACdC,OAAQ,gBAWGC,EAAiB,SAAgCC,EAASC,GAA0B,OAAKA,CAAO,EA2BhGC,EAAaC,EAExB,SAAAD,EAAYE,GAAgC,IAAAC,EAAAC,KAAAC,OAAAL,GAAAM,EAAAF,KAAA,WAMjC,SAACN,GAA2C,IAAAS,EACjDC,EAAcL,EAAKD,QAAQJ,GAC1BU,IACHA,EAAc,CAAEC,MAAO,IACvBN,EAAKD,QAAQJ,GAAOU,GACrB,IAAAE,IAAAA,EAAAC,UAAAC,OAL0BC,MAAsBxB,MAAAqB,EAAAA,EAAAA,OAAAI,EAAA,EAAAA,EAAAJ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AUrB,EAAWqB,QAAQC,QAAQ,MAAOzC,GAChDmB,IACRX,EAAAF,KAAA,MACK,SAACiB,GACL,IAAM2B,EAAOC,OAAOD,KAAK7C,EAAKD,SACxBgD,EAAyB,CAAE,EAQjC,OAPAF,EAAKG,QAAQ,SAACrD,GACZ,IAAMsD,EAASjD,EAAKD,QAAQJ,GAC5B,GAAKsD,EAAL,CACA,IAAMC,EAAMlD,EAAKmD,SAASF,EAAS/B,EAAcvB,GAAMuB,GACnDgC,EAAIzC,OAAS,IACfsC,EAAapD,GAAOuD,EAAIE,IAAI,SAACpB,GAAC,OAAKhC,EAAKqD,cAAcrB,EAAEtB,KAAMf,EAAKsD,EAAOf,MAAOF,EAAEjB,SAHxE,CAIf,GACOgC,IACR5C,kBACU,SAACmD,EAAsBC,EAAiBrC,GACjD,OAAOoC,EAAOhD,MAAM8C,IAAI,SAACpC,GACvB,IAAMwC,EAAUxD,EAAagB,EAAMN,KAAK8B,YAClCiB,EAAMD,GAAUA,EAAOxC,EAAOuC,EAAYrC,GAChD,MAAO,CAAEH,MAAkC0C,EAAuB/C,KAAMM,EAC1E,GAAGiB,OAAO,SAACD,GAAC,OAAKA,EAAEjB,UAhInBd,KAAKF,QAAUA,CACjB,KAJWF,EAAaM,EAAbN,EAMM,UAAA,SAAIE,GAAgC,OAAK,IAAIF,EAAcE,EAAQ,OAmIzE2D,EAAsB,WACjC,OAAO,IAAI7D,EAA0B,GACvC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{inherits as
|
|
1
|
+
import{inherits as r,createClass as e,objectSpread2 as t,classCallCheck as n,callSuper as o,defineProperty as i,regenerator as l}from"../../_virtual/_rollupPluginBabelHelpers.js";import{jsx as a}from"react/jsx-runtime";import u,{Component as s}from"react";import{Box as c,Tooltip as p,IconButton as d}from"@mui/material";import f from"@mui/icons-material/Edit";import m from"@mui/icons-material/Delete";import{mergeObjects as v}from"../utils/helpers.js";import"../utils/dayjs-config.js";import"../utils/query-param.js";import{MapTableBaseContext as h}from"./context.js";function g(g){var b=function(){function b(){var r;n(this,b);for(var e=arguments.length,s=new Array(e),c=0;c<e;c++)s[c]=arguments[c];return r=o(this,b,[].concat(s)),i(r,"getButtons",l().m(function r(e,n,o){var i,s,c,v,h,b,y,k,C,j,x,w,D,E,A,M,P,B;return l().w(function(r){for(;;)switch(r.n){case 0:if(!(C=null!==(i=null===(s=e.props)||void 0===s?void 0:s.before)&&void 0!==i?i:null==n?void 0:n.before)){r.n=1;break}return r.n=1,a(u.Fragment,{children:C(e.props.value,o)},"Before");case 1:if(j=null!==(c=null===(v=e.props)||void 0===v?void 0:v.formEdit)&&void 0!==c?c:null==n?void 0:n.formEdit,x=j?j(e.props.value,o):void 0,!j||!x){r.n=2;break}return w=n.buttonEditProps,D="function"==typeof w?w(e.props.value):w,r.n=2,a(p,{title:"Edit",arrow:!0,children:a("span",{children:a(d,t(t({color:"primary"},D),{},{onClick:function(r){var e;null==o||o.showModal(t({renderContent:function(){return x||a(u.Fragment,{})},sx:{display:"flex",justifyContent:"center",alignItems:"center"},backdropActivated:!0},null==g?void 0:g.buttonEditConfig)),null==D||null===(e=D.onClick)||void 0===e||e.call(D,r)},children:a(f,{fontSize:"small"})}))})},"Edit");case 2:if(E=null!==(h=null===(b=e.props)||void 0===b?void 0:b.formDelete)&&void 0!==h?h:null==n?void 0:n.formDelete,A=E?E(e.props.value,o):void 0,!E||!A){r.n=3;break}return M=n.buttonDeleteProps,P="function"==typeof M?M(e.props.value):M,r.n=3,a(p,{title:"Delete",arrow:!0,children:a("span",{children:a(d,t(t({color:"error"},P),{},{onClick:function(r){var e;null==o||o.showModal(t({renderContent:function(){return A||a(u.Fragment,{})},sx:{display:"flex",justifyContent:"center",alignItems:"center"},backdropActivated:!0},null==g?void 0:g.buttonDeleteConfig)),null==P||null===(e=P.onClick)||void 0===e||e.call(P,r)},children:a(m,{fontSize:"small"})}))})},"Delete");case 3:if(!(B=null!==(y=null===(k=e.props)||void 0===k?void 0:k.after)&&void 0!==y?y:null==n?void 0:n.after)){r.n=4;break}return r.n=4,a(u.Fragment,{children:B(e.props.value,o)},"After");case 4:return r.a(2)}},r)})),r}return r(b,s),e(b,[{key:"propsMerge",get:function(){return v(g,this.props)}},{key:"render",value:function(){var r=this;return h(function(e){return a(c,t(t({sx:{display:"flex",alignItems:"center",height:"100%"}},r.propsMerge.wrapProps),{},{children:Array.from(r.getButtons(r,r.propsMerge,e))}))})}}])}();return b}export{g as default};
|
|
2
2
|
//# sourceMappingURL=create.action-row.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.action-row.js","sources":["../../../src/table/create.action-row.tsx"],"sourcesContent":["import React, { Component, ComponentType } from 'react'\r\nimport { Box, BoxProps, IconButton, IconButtonProps, Tooltip } from '@mui/material'\r\nimport EditIcon from '@mui/icons-material/Edit'\r\nimport DeleteIcon from '@mui/icons-material/Delete'\r\nimport { mergeObjects } from '../utils'\r\nimport { GlobalModalState } from '../api-context'\r\nimport { ITableBaseContext, MapTableBaseContext } from './context'\r\n\r\nexport interface IActionRowProps<T> {\r\n value: T\r\n formEdit?: (value: T, tableContext: ITableBaseContext) => React.ReactNode\r\n formDelete?: (value: T, tableContext: ITableBaseContext) => React.ReactNode\r\n after?: (value: T, tableContext: ITableBaseContext) => React.ReactNode\r\n before?: (value: T, tableContext: ITableBaseContext) => React.ReactNode\r\n wrapProps?: BoxProps\r\n buttonEditProps?: IconButtonProps | ((value: T) => IconButtonProps)\r\n buttonDeleteProps?: IconButtonProps | ((value: T) => IconButtonProps)\r\n buttonEditConfig?: GlobalModalState\r\n buttonDeleteConfig?: GlobalModalState\r\n}\r\n\r\nfunction CreateActionRow<T>(params?: Omit<IActionRowProps<T>, 'value'>): ComponentType<IActionRowProps<T>> {\r\n class ActionRow extends Component<IActionRowProps<T>> {\r\n get propsMerge() {\r\n return mergeObjects<IActionRowProps<T>>(params, this.props)\r\n }\r\n\r\n getButtons = function* (that: ActionRow, thatProps: Omit<IActionRowProps<T>, 'value'>, tableContext: ITableBaseContext) {\r\n const beforeFunc = that.props?.before ?? thatProps?.before\r\n if (beforeFunc) {\r\n yield <React.Fragment key='Before'>{beforeFunc(that.props.value, tableContext)}</React.Fragment>\r\n }\r\n const editFunc = that.props?.formEdit ?? thatProps?.formEdit\r\n const editContent = editFunc ? editFunc(that.props.value, tableContext) : undefined\r\n if (editFunc && !!editContent) {\r\n const { buttonEditProps } = thatProps\r\n const p = typeof buttonEditProps === 'function' ? buttonEditProps(that.props.value) : buttonEditProps\r\n yield (\r\n <Tooltip title='Edit' arrow key='Edit'>\r\n <span>\r\n <IconButton\r\n color='primary'\r\n {...p}\r\n onClick={(e) => {\r\n tableContext?.showModal({\r\n renderContent: () => editContent || <React.Fragment />,\r\n sx: { display: 'flex', justifyContent: 'center', alignItems: 'center' },\r\n backdropActivated: true,\r\n ...params?.buttonEditConfig\r\n })\r\n p?.onClick?.(e)\r\n }}\r\n >\r\n <EditIcon fontSize='small' />\r\n </IconButton>\r\n </span>\r\n </Tooltip>\r\n )\r\n }\r\n const deleteFunc = that.props?.formDelete ?? thatProps?.formDelete\r\n const deleteContent = deleteFunc ? deleteFunc(that.props.value, tableContext) : undefined\r\n if (deleteFunc && !!deleteContent) {\r\n const { buttonDeleteProps } = thatProps\r\n const p = typeof buttonDeleteProps === 'function' ? buttonDeleteProps(that.props.value) : buttonDeleteProps\r\n yield (\r\n <Tooltip title='Delete' arrow key='Delete'>\r\n <span>\r\n <IconButton\r\n color='error'\r\n {...p}\r\n onClick={(e) => {\r\n tableContext?.showModal({\r\n renderContent: () => deleteContent || <React.Fragment />,\r\n sx: { display: 'flex', justifyContent: 'center', alignItems: 'center' },\r\n backdropActivated: true,\r\n ...params?.buttonDeleteConfig\r\n })\r\n p?.onClick?.(e)\r\n }}\r\n >\r\n <DeleteIcon fontSize='small' />\r\n </IconButton>\r\n </span>\r\n </Tooltip>\r\n )\r\n }\r\n const afterFunc = that.props?.after ?? thatProps?.after\r\n if (afterFunc) {\r\n yield <React.Fragment key='After'>{afterFunc(that.props.value, tableContext)}</React.Fragment>\r\n }\r\n }\r\n\r\n render() {\r\n return MapTableBaseContext((context) => (\r\n <Box sx={{ display: 'flex', alignItems: 'center', height: '100%' }} {...this.propsMerge.wrapProps}>\r\n {Array.from(this.getButtons(this, this.propsMerge, context))}\r\n </Box>\r\n ))\r\n }\r\n }\r\n\r\n return ActionRow\r\n}\r\nexport default CreateActionRow\r\n"],"names":["CreateActionRow","params","ActionRow","_this","_classCallCheck","_len","arguments","length","args","Array","_key","_callSuper","this","concat","_defineProperty","_regenerator","m","_callee","that","thatProps","tableContext","_that$props$before","_that$props","_that$props$formEdit","_that$props2","_that$props$formDelet","_that$props3","_that$props$after","_that$props4","beforeFunc","editFunc","editContent","buttonEditProps","p","deleteFunc","deleteContent","buttonDeleteProps","_p","afterFunc","w","_context","n","props","before","_jsx","React","Fragment","children","value","formEdit","undefined","Tooltip","title","arrow","IconButton","_objectSpread","color","onClick","e","_p$onClick","showModal","renderContent","sx","display","justifyContent","alignItems","backdropActivated","buttonEditConfig","call","EditIcon","fontSize","formDelete","_p$onClick2","buttonDeleteConfig","DeleteIcon","after","a","_inherits","Component","_createClass","key","get","mergeObjects","_this2","MapTableBaseContext","context","Box","height","propsMerge","wrapProps","from","getButtons"],"mappings":"
|
|
1
|
+
{"version":3,"file":"create.action-row.js","sources":["../../../src/table/create.action-row.tsx"],"sourcesContent":["import React, { Component, ComponentType } from 'react'\r\nimport { Box, BoxProps, IconButton, IconButtonProps, Tooltip } from '@mui/material'\r\nimport EditIcon from '@mui/icons-material/Edit'\r\nimport DeleteIcon from '@mui/icons-material/Delete'\r\nimport { mergeObjects } from '../utils'\r\nimport { GlobalModalState } from '../api-context'\r\nimport { ITableBaseContext, MapTableBaseContext } from './context'\r\n\r\nexport interface IActionRowProps<T> {\r\n value: T\r\n formEdit?: (value: T, tableContext: ITableBaseContext) => React.ReactNode\r\n formDelete?: (value: T, tableContext: ITableBaseContext) => React.ReactNode\r\n after?: (value: T, tableContext: ITableBaseContext) => React.ReactNode\r\n before?: (value: T, tableContext: ITableBaseContext) => React.ReactNode\r\n wrapProps?: BoxProps\r\n buttonEditProps?: IconButtonProps | ((value: T) => IconButtonProps)\r\n buttonDeleteProps?: IconButtonProps | ((value: T) => IconButtonProps)\r\n buttonEditConfig?: GlobalModalState\r\n buttonDeleteConfig?: GlobalModalState\r\n}\r\n\r\nfunction CreateActionRow<T>(params?: Omit<IActionRowProps<T>, 'value'>): ComponentType<IActionRowProps<T>> {\r\n class ActionRow extends Component<IActionRowProps<T>> {\r\n get propsMerge() {\r\n return mergeObjects<IActionRowProps<T>>(params, this.props)\r\n }\r\n\r\n getButtons = function* (that: ActionRow, thatProps: Omit<IActionRowProps<T>, 'value'>, tableContext: ITableBaseContext) {\r\n const beforeFunc = that.props?.before ?? thatProps?.before\r\n if (beforeFunc) {\r\n yield <React.Fragment key='Before'>{beforeFunc(that.props.value, tableContext)}</React.Fragment>\r\n }\r\n const editFunc = that.props?.formEdit ?? thatProps?.formEdit\r\n const editContent = editFunc ? editFunc(that.props.value, tableContext) : undefined\r\n if (editFunc && !!editContent) {\r\n const { buttonEditProps } = thatProps\r\n const p = typeof buttonEditProps === 'function' ? buttonEditProps(that.props.value) : buttonEditProps\r\n yield (\r\n <Tooltip title='Edit' arrow key='Edit'>\r\n <span>\r\n <IconButton\r\n color='primary'\r\n {...p}\r\n onClick={(e) => {\r\n tableContext?.showModal({\r\n renderContent: () => editContent || <React.Fragment />,\r\n sx: { display: 'flex', justifyContent: 'center', alignItems: 'center' },\r\n backdropActivated: true,\r\n ...params?.buttonEditConfig\r\n })\r\n p?.onClick?.(e)\r\n }}\r\n >\r\n <EditIcon fontSize='small' />\r\n </IconButton>\r\n </span>\r\n </Tooltip>\r\n )\r\n }\r\n const deleteFunc = that.props?.formDelete ?? thatProps?.formDelete\r\n const deleteContent = deleteFunc ? deleteFunc(that.props.value, tableContext) : undefined\r\n if (deleteFunc && !!deleteContent) {\r\n const { buttonDeleteProps } = thatProps\r\n const p = typeof buttonDeleteProps === 'function' ? buttonDeleteProps(that.props.value) : buttonDeleteProps\r\n yield (\r\n <Tooltip title='Delete' arrow key='Delete'>\r\n <span>\r\n <IconButton\r\n color='error'\r\n {...p}\r\n onClick={(e) => {\r\n tableContext?.showModal({\r\n renderContent: () => deleteContent || <React.Fragment />,\r\n sx: { display: 'flex', justifyContent: 'center', alignItems: 'center' },\r\n backdropActivated: true,\r\n ...params?.buttonDeleteConfig\r\n })\r\n p?.onClick?.(e)\r\n }}\r\n >\r\n <DeleteIcon fontSize='small' />\r\n </IconButton>\r\n </span>\r\n </Tooltip>\r\n )\r\n }\r\n const afterFunc = that.props?.after ?? thatProps?.after\r\n if (afterFunc) {\r\n yield <React.Fragment key='After'>{afterFunc(that.props.value, tableContext)}</React.Fragment>\r\n }\r\n }\r\n\r\n render() {\r\n return MapTableBaseContext((context) => (\r\n <Box sx={{ display: 'flex', alignItems: 'center', height: '100%' }} {...this.propsMerge.wrapProps}>\r\n {Array.from(this.getButtons(this, this.propsMerge, context))}\r\n </Box>\r\n ))\r\n }\r\n }\r\n\r\n return ActionRow\r\n}\r\nexport default CreateActionRow\r\n"],"names":["CreateActionRow","params","ActionRow","_this","_classCallCheck","_len","arguments","length","args","Array","_key","_callSuper","this","concat","_defineProperty","_regenerator","m","_callee","that","thatProps","tableContext","_that$props$before","_that$props","_that$props$formEdit","_that$props2","_that$props$formDelet","_that$props3","_that$props$after","_that$props4","beforeFunc","editFunc","editContent","buttonEditProps","p","deleteFunc","deleteContent","buttonDeleteProps","_p","afterFunc","w","_context","n","props","before","_jsx","React","Fragment","children","value","formEdit","undefined","Tooltip","title","arrow","IconButton","_objectSpread","color","onClick","e","_p$onClick","showModal","renderContent","sx","display","justifyContent","alignItems","backdropActivated","buttonEditConfig","call","EditIcon","fontSize","formDelete","_p$onClick2","buttonDeleteConfig","DeleteIcon","after","a","_inherits","Component","_createClass","key","get","mergeObjects","_this2","MapTableBaseContext","context","Box","height","prop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,EAAA,EACxDgB,GAAI,CAAEC,QAAS,OAAQC,eAAgB,SAAUC,WAAY,UAC7DC,mBAAmB,GAChBjE,aAAM,EAANA,EAAQwE,qBAEbxC,SAAU,QAATuC,EAADvC,EAAGwB,eAAO,IAAAe,GAAVA,EAAAJ,KAAAnC,EAAayB,EACd,EAEDX,SAAAH,EAAC8B,EAAU,CAACJ,SAAS,gBAfO,UAmBnC,KAAA,EAEoD,KAAjDhC,EAA6B,QAApBX,EAAaC,QAAbA,EAAGV,EAAKwB,aAALd,IAAUA,OAAVA,EAAAA,EAAY+C,aAAK,IAAAhD,EAAAA,EAAIR,aAAS,EAATA,EAAWwD,OACrC,CAAAnC,EAAAC,EAAA,EAAA,KAAA,CACX,OADWD,EAAAC,EAAA,EACLG,EAACC,EAAMC,SAAsB,CAAAC,SAAAT,EAAUpB,EAAKwB,MAAMM,MAAO5B,IAArC,SAAoE,KAAA,EAAA,OAAAoB,EAAAoC,EAAA,GAAA,EAAA3D,MAEjGd,CAAA,CAAA,OAAA0E,EAAA3E,EApEqB4E,GAoErBC,EAAA7E,EAAA,CAAA,CAAA8E,IAAA,aAAAC,IAnED,WACE,OAAOC,EAAiCjF,EAAQW,KAAK8B,MACvD,GAAC,CAAAsC,IAAA,SAAAhC,MAmED,WAAM,IAAAmC,EAAAvE,KACJ,OAAOwE,EAAoB,SAACC,GAAO,OACjCzC,EAAC0C,EAAG/B,EAAAA,EAAA,CAACO,GAAI,CAAEC,QAAS,OAAQE,WAAY,SAAUsB,OAAQ,SAAcJ,EAAKK,WAAWC,WAAS,CAAA,EAAA,CAAA1C,SAC9FtC,MAAMiF,KAAKP,EAAKQ,WAAWR,EAAMA,EAAKK,WAAYH,MAC/C,EAEV,IAAC,IAGH,OAAOnF,CACT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{inherits as e,createClass as o,objectSpread2 as r,classCallCheck as i,callSuper as a,defineProperty as t,toConsumableArray as l}from"../../_virtual/_rollupPluginBabelHelpers.js";import{jsx as n}from"react/jsx-runtime";import{Component as s,Fragment as d}from"react";import{DataGrid as u}from"@mui/x-data-grid";import{
|
|
1
|
+
import{inherits as e,createClass as o,objectSpread2 as r,classCallCheck as i,callSuper as a,defineProperty as t,toConsumableArray as l}from"../../_virtual/_rollupPluginBabelHelpers.js";import{jsx as n}from"react/jsx-runtime";import{Component as s,Fragment as d}from"react";import{DataGrid as u}from"@mui/x-data-grid";import{mergeObjects as p}from"../utils/helpers.js";import"../utils/dayjs-config.js";import"../utils/query-param.js";import{TableBaseContext as g}from"./context.js";import{customFilterOperators as m}from"./custom.filter-operators.js";import c from"./helpers.js";import f from"./toolbar-pannel.js";import{dinoTableClasses as h,TableStyled as v}from"./styled.js";import{GlobalModal as b,mapGlobalModalContext as y}from"../api-context/global-modal.js";function C(C){return function(){function P(e){var o;return i(this,P),o=a(this,P,[e]),t(o,"setTableQueryParams",function(e){o.tableQueryParams=p({},o.tableQueryParams,e)}),t(o,"renderWrapContext",function(e){var o=C.disableGlobalModalProvider?d:b;return n(o,{children:y(function(o){return n(g.Provider,{value:{showModal:o.show,closeModal:o.close},children:e})})})}),t(o,"getDataGridProps",function(){var e,r,i,a,t=c.mapInitialState(o.props.query,{columns:{columnVisibilityModel:C.columnVisibilityModel}}),l={getRowId:C.getRowId,initialState:t,columns:o.columns,rows:null!==(e=null===(r=o.props.data)||void 0===r?void 0:r.items)&&void 0!==e?e:[],checkboxSelection:!0,pagination:!0,density:null!==(i=null===(a=o.props.slots)||void 0===a?void 0:a.density)&&void 0!==i?i:"standard",filterDebounceMs:800,sx:{border:0},slots:{toolbar:o.mergeConfig.toolbar},rowSelectionModel:o.rowSelecteds,onRowSelectionModelChange:o.handleRowSelectionChange};if("server"===C.featureMode){var n,s,d={filterMode:"server",sortingMode:"server",paginationMode:"server",onPaginationModelChange:o.onPaginationModelChange,onFilterModelChange:o.onFilterModelChange,onSortModelChange:o.onSortModelChange,rowCount:null!==(n=null===(s=o.props.data)||void 0===s?void 0:s.rowTotal)&&void 0!==n?n:0,paginationModel:o.tableQueryParams.pagination,filterModel:o.tableQueryParams.filter,sortModel:c.mapSortModel(o.tableQueryParams.sort),loading:o.mergeConfig.loading};Object.assign(l,d)}return p(l,o.mergeConfig.dataGridProps)}),t(o,"initialColumns",function(){var e,i,a=o.mergeConfig,t=a.ActionRow,s=a.disableActionRow,d=[];return t&&!0!==s&&d.push(r({field:"Actions",minWidth:100,headerAlign:"right",align:"right",filterable:!1,sortable:!1,disableExport:!0,renderCell:function(e){return n(t,{value:e.row})}},C.actionRow)),e=d,i=Object.keys(C.columns).map(function(e){var o=r({field:e},C.columns[e]);return o.filterOperators=C.filterOperators?C.filterOperators(o):m(o),o}),e&&e.length>0&&i.push.apply(i,l(e)),i}),t(o,"onPaginationModelChange",function(e,r){o.mergeConfig.loading||(o.setTableQueryParams({pagination:e,detail:"pagination"}),o.handleChange())}),t(o,"onFilterModelChange",function(e,r){var i;if(!o.mergeConfig.loading){var a=o.tableQueryParams.pagination;o.setTableQueryParams({filter:e,pagination:{page:0,pageSize:null!==(i=null==a?void 0:a.pageSize)&&void 0!==i?i:25},detail:c.detectSearchType(e)}),o.handleChange()}}),t(o,"onSortModelChange",function(e,r){if(!o.mergeConfig.loading){var i,a,t,l,n,s=e,d=o.tableQueryParams.sort;if(null!=d&&d.length&&!s.length)if((null==d||null===(i=d[0])||void 0===i?void 0:i.field)===(null===(a=o.defaultTableQueryParams.sort)||void 0===a||null===(a=a[0])||void 0===a?void 0:a.field))s=[{field:null===(t=d[0])||void 0===t?void 0:t.field,sort:"desc"===(null===(l=d[0])||void 0===l?void 0:l.sort)?"asc":"desc"}];else s=null!==(n=o.defaultTableQueryParams.sort)&&void 0!==n?n:[];o.setTableQueryParams({sort:s,detail:"sort"}),o.handleChange()}}),t(o,"handleChange",function(){o.changeTimeout&&clearTimeout(o.changeTimeout),o.changeTimeout=setTimeout(function(){o.props.onChange&&o.props.onChange(o.tableQueryParams)},300)}),t(o,"handleRowSelectionChange",function(e,r){o.mergeConfig.maxSelcion&&e.length>o.mergeConfig.maxSelcion?o.rowSelecteds=e.slice(0,o.mergeConfig.maxSelcion):o.rowSelecteds=e,o.props.onRowSelectionChange&&o.props.onRowSelectionChange(o.rowSelecteds,r),o.forceUpdate()}),o.columns=o.initialColumns(),o.tableQueryParams=r({},e.query),o.defaultTableQueryParams=o.tableQueryParams,o.rowSelecteds=[],o}return e(P,s),o(P,[{key:"mergeConfig",get:function(){var e,o,i,a,t,l,s,d,u,g,m=p({},null==C?void 0:C.toolbarProps,null===(e=this.props.slots)||void 0===e?void 0:e.toolbarProps);return{toolbar:null!==(o=null===(i=this.props.slots)||void 0===i?void 0:i.toolbar)&&void 0!==o?o:function(){return n(f,r({},m))},ActionRow:null===(a=this.props.slots)||void 0===a?void 0:a.actionRow,disableActionRow:C.disableActionRow,columnVisibilityModel:C.columnVisibilityModel,maxSelcion:null!==(t=null===(l=this.props.slots)||void 0===l?void 0:l.maxSelection)&&void 0!==t?t:C.maxSelection,dataGridProps:p({},C.dataGridProps,null===(s=this.props.slots)||void 0===s?void 0:s.dataGridProps),wrapProps:p({},C.wrapProps,null===(d=this.props.slots)||void 0===d?void 0:d.wrapProps),loading:null!==(u=void 0!==this.props.loading?this.props.loading:null===(g=this.tableQueryParams)||void 0===g?void 0:g.loading)&&void 0!==u&&u}}},{key:"componentWillUnmount",value:function(){this.changeTimeout&&clearTimeout(this.changeTimeout)}},{key:"shouldComponentUpdate",value:function(e){var o;return"server"!==C.featureMode||(c.equalTableQueryParams(e.query,this.props.query)?JSON.stringify(e.data)!==JSON.stringify(this.props.data)||e.loading!==this.props.loading:(this.setTableQueryParams(null!==(o=e.query)&&void 0!==o?o:{}),!0))}},{key:"render",value:function(){var e,o=[h.root,null===(e=this.mergeConfig.wrapProps)||void 0===e?void 0:e.className];return this.renderWrapContext(n(v,r(r({},this.mergeConfig.wrapProps),{},{className:o.filter(function(e){return!!e}).join(" "),children:n(u,r({loading:this.props.loading},this.getDataGridProps()))})))}}])}()}export{C as CreateTable,C as default};
|
|
2
2
|
//# sourceMappingURL=create.table.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.table.js","sources":["../../../src/table/create.table.tsx"],"sourcesContent":["import { Component, Fragment } from 'react'\r\nimport { Box, BoxProps, styled } from '@mui/material'\r\nimport { DataGrid, DataGridProps, GridColDef, GridFeatureMode, GridFilterOperator } from '@mui/x-data-grid'\r\nimport { GridSortModel, GridValidRowModel, GridRowIdGetter, GridRowSelectionModel } from '@mui/x-data-grid'\r\nimport { GridCallbackDetails, GridColumnVisibilityModel, GridDensity, GridFilterModel, GridPaginationModel } from '@mui/x-data-grid'\r\nimport type { ComponentType, ReactNode } from 'react'\r\nimport { mergeObjects } from '../utils'\r\nimport { TableBaseContext } from './context'\r\nimport { IActionRowProps } from './create.action-row'\r\nimport { customFilterOperators } from './custom.filter-operators'\r\nimport { GlobalModal, mapGlobalModalContext } from '../api-context'\r\nimport { ICustomGridColDef, ICustomGridFilterModel, ICustomGridSortModel, ITableData, ITableQueryParams } from './types'\r\nimport TableHelper from './helpers'\r\nimport ToolbarPannel, { IToolbarPannelProps } from './toolbar-pannel'\r\nimport { dinoTableClasses, TableStyled } from './styled'\r\n\r\nexport interface ITableSlots<T> {\r\n maxSelection?: number\r\n density?: GridDensity\r\n toolbar?: ComponentType<IToolbarPannelProps>\r\n actionRow?: ComponentType<IActionRowProps<T>>\r\n toolbarProps?: IToolbarPannelProps\r\n dataGridProps?: DataGridProps\r\n wrapProps?: BoxProps\r\n}\r\n\r\nexport type ITableParamsSlots<T> = Pick<ITableSlots<T>, 'maxSelection' | 'toolbarProps' | 'dataGridProps' | 'wrapProps'>\r\n\r\nexport interface ITableProps<T> {\r\n data?: ITableData<T>\r\n query?: ITableQueryParams<T>\r\n loading?: boolean\r\n onChange?: (query: ITableQueryParams<T>) => void\r\n onRowSelectionChange?: DataGridProps['onRowSelectionModelChange']\r\n slots?: ITableSlots<T>\r\n}\r\n\r\nexport interface ITableParams<T extends GridValidRowModel> extends ITableParamsSlots<T> {\r\n featureMode?: GridFeatureMode\r\n getRowId: GridRowIdGetter<T>\r\n columns: ICustomGridColDef<T>\r\n filterOperators?: (config: GridColDef) => GridFilterOperator[]\r\n columnVisibilityModel?: Partial<Record<keyof T, boolean>>\r\n actionRow?: Omit<GridColDef, 'field'>\r\n disableActionRow?: boolean\r\n disableGlobalModalProvider?: boolean\r\n}\r\n\r\nexport function CreateTable<T extends GridValidRowModel>(params: ITableParams<T>): ComponentType<ITableProps<T>> {\r\n const generateColumns = (extendColDefs?: GridColDef[]) => {\r\n const columns = Object.keys(params.columns).map<GridColDef>((key) => {\r\n const obj = { field: key, ...params.columns[key] }\r\n obj.filterOperators = params.filterOperators ? params.filterOperators(obj) : customFilterOperators(obj)\r\n return obj\r\n })\r\n\r\n if (!!extendColDefs && extendColDefs.length > 0) columns.push(...extendColDefs)\r\n return columns\r\n }\r\n\r\n class Table extends Component<ITableProps<T>> {\r\n private tableQueryParams: ITableQueryParams<T>\r\n // private tableQueryParamsCache: ITableQueryParams<T> = {}\r\n private defaultTableQueryParams: ITableQueryParams<T>\r\n private columns: GridColDef<T>[]\r\n private rowSelecteds: GridRowSelectionModel\r\n private changeTimeout?: ReturnType<typeof setTimeout>\r\n constructor(props: ITableProps<T>) {\r\n super(props)\r\n this.columns = this.initialColumns()\r\n this.tableQueryParams = { ...props.query }\r\n this.defaultTableQueryParams = this.tableQueryParams\r\n this.rowSelecteds = []\r\n }\r\n\r\n get mergeConfig() {\r\n const toolbarPannelProps = mergeObjects({}, params?.toolbarProps, this.props.slots?.toolbarProps)\r\n return {\r\n toolbar: this.props.slots?.toolbar ?? (() => <ToolbarPannel {...toolbarPannelProps} />),\r\n ActionRow: this.props.slots?.actionRow,\r\n disableActionRow: params.disableActionRow,\r\n columnVisibilityModel: params.columnVisibilityModel,\r\n maxSelcion: this.props.slots?.maxSelection ?? params.maxSelection,\r\n dataGridProps: mergeObjects({}, params.dataGridProps, this.props.slots?.dataGridProps),\r\n wrapProps: mergeObjects({}, params.wrapProps, this.props.slots?.wrapProps),\r\n loading: (this.props.loading !== undefined ? this.props.loading : this.tableQueryParams?.loading) ?? false\r\n }\r\n }\r\n\r\n setTableQueryParams = (value: Partial<ITableQueryParams<T>>) => {\r\n this.tableQueryParams = mergeObjects({}, this.tableQueryParams, value)\r\n }\r\n\r\n componentWillUnmount() {\r\n if (this.changeTimeout) {\r\n clearTimeout(this.changeTimeout)\r\n }\r\n }\r\n\r\n shouldComponentUpdate(nextProps: Readonly<ITableProps<T>>): boolean {\r\n if (params.featureMode === 'server') {\r\n // Check if query changed\r\n if (!TableHelper.equalTableQueryParams(nextProps.query, this.props.query)) {\r\n this.setTableQueryParams(nextProps.query ?? {})\r\n return true\r\n }\r\n // Check if data or loading changed\r\n if (JSON.stringify(nextProps.data) !== JSON.stringify(this.props.data) || nextProps.loading !== this.props.loading) {\r\n return true\r\n }\r\n return false\r\n } else {\r\n return true\r\n }\r\n }\r\n\r\n render() {\r\n const rootClasses = [dinoTableClasses.root, this.mergeConfig.wrapProps?.className]\r\n return this.renderWrapContext(\r\n <TableStyled {...this.mergeConfig.wrapProps} className={rootClasses.filter((x) => !!x).join(' ')}>\r\n <DataGrid loading={this.props.loading} {...this.getDataGridProps()} />\r\n </TableStyled>\r\n )\r\n }\r\n\r\n renderWrapContext = (children: ReactNode) => {\r\n const WrapComponent = params.disableGlobalModalProvider ? Fragment : GlobalModal\r\n return (\r\n <WrapComponent>\r\n {mapGlobalModalContext((context) => (\r\n <TableBaseContext.Provider value={{ showModal: context.show, closeModal: context.close }}>{children}</TableBaseContext.Provider>\r\n ))}\r\n </WrapComponent>\r\n )\r\n }\r\n\r\n getDataGridProps = (): DataGridProps<T> => {\r\n const initialState = TableHelper.mapInitialState(this.props.query, {\r\n columns: { columnVisibilityModel: params.columnVisibilityModel as GridColumnVisibilityModel }\r\n })\r\n const obj: DataGridProps<T> = {\r\n getRowId: params.getRowId,\r\n initialState,\r\n columns: this.columns,\r\n rows: this.props.data?.items ?? [],\r\n checkboxSelection: true,\r\n pagination: true,\r\n density: this.props.slots?.density ?? 'standard',\r\n filterDebounceMs: 800,\r\n sx: { border: 0 },\r\n slots: { toolbar: this.mergeConfig.toolbar },\r\n rowSelectionModel: this.rowSelecteds,\r\n onRowSelectionModelChange: this.handleRowSelectionChange\r\n }\r\n if (params.featureMode === 'server') {\r\n const objServer: Partial<DataGridProps<T>> = {\r\n filterMode: 'server',\r\n sortingMode: 'server',\r\n paginationMode: 'server',\r\n onPaginationModelChange: this.onPaginationModelChange,\r\n onFilterModelChange: this.onFilterModelChange,\r\n onSortModelChange: this.onSortModelChange,\r\n rowCount: this.props.data?.rowTotal ?? 0,\r\n paginationModel: this.tableQueryParams.pagination,\r\n filterModel: this.tableQueryParams.filter as GridFilterModel,\r\n sortModel: TableHelper.mapSortModel(this.tableQueryParams.sort),\r\n loading: this.mergeConfig.loading\r\n }\r\n Object.assign(obj, objServer)\r\n }\r\n return mergeObjects(obj, this.mergeConfig.dataGridProps)\r\n }\r\n\r\n initialColumns = (): GridColDef<T>[] => {\r\n const { ActionRow, disableActionRow } = this.mergeConfig\r\n const list: GridColDef<T>[] = []\r\n if (!!ActionRow && disableActionRow !== true) {\r\n list.push({\r\n field: 'Actions',\r\n minWidth: 100,\r\n headerAlign: 'right',\r\n align: 'right',\r\n filterable: false,\r\n sortable: false,\r\n disableExport: true,\r\n renderCell: (value) => <ActionRow value={value.row} />,\r\n ...params.actionRow\r\n })\r\n }\r\n return generateColumns(list)\r\n }\r\n\r\n onPaginationModelChange = (model: GridPaginationModel, details: GridCallbackDetails<'pagination'>) => {\r\n if (this.mergeConfig.loading) return\r\n this.setTableQueryParams({ pagination: model, detail: 'pagination' })\r\n this.handleChange()\r\n }\r\n\r\n onFilterModelChange = (model: GridFilterModel, details: GridCallbackDetails<'filter'>) => {\r\n if (this.mergeConfig.loading) return\r\n const { pagination } = this.tableQueryParams\r\n this.setTableQueryParams({\r\n filter: model as ICustomGridFilterModel<T>,\r\n pagination: { page: 0, pageSize: pagination?.pageSize ?? 25 },\r\n detail: TableHelper.detectSearchType(model)\r\n })\r\n this.handleChange()\r\n }\r\n\r\n onSortModelChange = (model: GridSortModel, details: GridCallbackDetails<any>) => {\r\n if (this.mergeConfig.loading) return\r\n let sortValue = model as ICustomGridSortModel<T>\r\n const { sort } = this.tableQueryParams\r\n if (!!sort?.length && !sortValue.length) {\r\n if (sort?.[0]?.field === this.defaultTableQueryParams.sort?.[0]?.field) {\r\n sortValue = [{ field: sort[0]?.field, sort: sort[0]?.sort === 'desc' ? 'asc' : 'desc' }]\r\n } else {\r\n sortValue = this.defaultTableQueryParams.sort ?? []\r\n }\r\n }\r\n this.setTableQueryParams({ sort: sortValue, detail: 'sort' })\r\n this.handleChange()\r\n }\r\n\r\n handleChange = () => {\r\n if (this.changeTimeout) clearTimeout(this.changeTimeout)\r\n this.changeTimeout = setTimeout(() => {\r\n this.props.onChange && this.props.onChange(this.tableQueryParams)\r\n }, 300)\r\n }\r\n\r\n handleRowSelectionChange = (value: GridRowSelectionModel, details: GridCallbackDetails) => {\r\n if (this.mergeConfig.maxSelcion && value.length > this.mergeConfig.maxSelcion) {\r\n this.rowSelecteds = value.slice(0, this.mergeConfig.maxSelcion)\r\n } else {\r\n this.rowSelecteds = value\r\n }\r\n this.props.onRowSelectionChange && this.props.onRowSelectionChange(this.rowSelecteds, details)\r\n this.forceUpdate()\r\n }\r\n }\r\n\r\n return Table\r\n}\r\n\r\nexport default CreateTable\r\n"],"names":["CreateTable","params","Table","props","_this","_classCallCheck","_callSuper","_defineProperty","value","tableQueryParams","mergeObjects","children","WrapComponent","disableGlobalModalProvider","Fragment","GlobalModal","_jsx","mapGlobalModalContext","context","TableBaseContext","Provider","showModal","show","closeModal","close","_this$props$data$item","_this$props$data","_this$props$slots$den","_this$props$slots","initialState","TableHelper","mapInitialState","query","columns","columnVisibilityModel","obj","getRowId","rows","data","items","checkboxSelection","pagination","density","slots","filterDebounceMs","sx","border","toolbar","mergeConfig","rowSelectionModel","rowSelecteds","onRowSelectionModelChange","handleRowSelectionChange","featureMode","_this$props$data$rowT","_this$props$data2","objServer","filterMode","sortingMode","paginationMode","onPaginationModelChange","onFilterModelChange","onSortModelChange","rowCount","rowTotal","paginationModel","filterModel","filter","sortModel","mapSortModel","sort","loading","Object","assign","dataGridProps","extendColDefs","_this$mergeConfig","ActionRow","disableActionRow","list","push","_objectSpread","field","minWidth","headerAlign","align","filterable","sortable","disableExport","renderCell","row","actionRow","keys","map","key","filterOperators","customFilterOperators","length","apply","_toConsumableArray","model","details","setTableQueryParams","detail","handleChange","_pagination$pageSize","page","pageSize","detectSearchType","_sort$","_this$defaultTableQue","_sort$2","_sort$3","_this$defaultTableQue2","sortValue","defaultTableQueryParams","changeTimeout","clearTimeout","setTimeout","onChange","maxSelcion","slice","onRowSelectionChange","forceUpdate","initialColumns","_inherits","Component","_createClass","get","_this$props$slots2","_this$props$slots$too","_this$props$slots3","_this$props$slots4","_this$props$slots$max","_this$props$slots5","_this$props$slots6","_this$props$slots7","_ref","_this$tableQueryParam","toolbarPannelProps","toolbarProps","this","ToolbarPannel","maxSelection","wrapProps","undefined","nextProps","_nextProps$query","equalTableQueryParams","JSON","stringify","_this$mergeConfig$wra","rootClasses","dinoTableClasses","root","className","renderWrapContext","TableStyled","x","join","DataGrid","getDataGridProps"],"mappings":"4rBAgDM,SAAUA,EAAyCC,GAkMvD,kBA/KE,SAAAC,EAAYC,GAAqB,IAAAC,EAKT,OALSC,OAAAH,GAC/BE,EAAAE,EAAAJ,KAAAA,GAAMC,IAAMI,EAAAH,EAqBQ,sBAAA,SAACI,GACrBJ,EAAKK,iBAAmBC,EAAa,CAAE,EAAEN,EAAKK,iBAAkBD,KACjED,EAAAH,EAkCmB,oBAAA,SAACO,GACnB,IAAMC,EAAgBX,EAAOY,2BAA6BC,EAAWC,EACrE,OACEC,EAACJ,EACE,CAAAD,SAAAM,EAAsB,SAACC,GAAO,OAC7BF,EAACG,EAAiBC,UA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1I,MAAMoE,QAAwBsE,KAAK1I,MAAMoE,gBAAOmE,EAAGG,KAAKpI,wBAAgB,IAAAiI,OAAA,EAArBA,EAAuBnE,eAAO,IAAAkE,GAAAA,EAEpG,GAAC,CAAA3C,IAAA,uBAAAtF,MAMD,WACMqI,KAAKzB,eACPC,aAAawB,KAAKzB,cAEtB,GAAC,CAAAtB,IAAA,wBAAAtF,MAED,SAAsB0I,GAGyD,IAAAC,EAF7E,MAA2B,WAAvBlJ,EAAOoD,cAEJvB,EAAYsH,sBAAsBF,EAAUlH,MAAO6G,KAAK1I,MAAM6B,OAK/DqH,KAAKC,UAAUJ,EAAU5G,QAAU+G,KAAKC,UAAUT,KAAK1I,MAAMmC,OAAS4G,EAAU3E,UAAYsE,KAAK1I,MAAMoE,SAJzGsE,KAAKvC,oBAAmC,QAAhB6C,EAACD,EAAUlH,aAAKmH,IAAAA,EAAAA,EAAI,KACrC,GAUb,GAAC,CAAArD,IAAA,SAAAtF,MAED,WAAM,IAAA+I,EACEC,EAAc,CAACC,EAAiBC,KAAgCH,QAA5BA,EAAEV,KAAK7F,YAAYgG,qBAASO,SAA1BA,EAA4BI,WACxE,OAAOd,KAAKe,kBACV5I,EAAC6I,EAAW5E,EAAAA,EAAK,CAAA,EAAA4D,KAAK7F,YAAYgG,WAAS,CAAA,EAAA,CAAEW,UAAWH,EAAYrF,OAAO,SAAC2F,GAAC,QAAOA,CAAC,GAAEC,KAAK,cAC1F/I,EAACgJ,EAAQ/E,EAAA,CAACV,QAASsE,KAAK1I,MAAMoE,SAAasE,KAAKoB,wBAGtD,IAAC,GAwHL"}
|
|
1
|
+
{"version":3,"file":"create.table.js","sources":["../../../src/table/create.table.tsx"],"sourcesContent":["import { Component, Fragment } from 'react'\r\nimport { Box, BoxProps, styled } from '@mui/material'\r\nimport { DataGrid, DataGridProps, GridColDef, GridFeatureMode, GridFilterOperator } from '@mui/x-data-grid'\r\nimport { GridSortModel, GridValidRowModel, GridRowIdGetter, GridRowSelectionModel } from '@mui/x-data-grid'\r\nimport { GridCallbackDetails, GridColumnVisibilityModel, GridDensity, GridFilterModel, GridPaginationModel } from '@mui/x-data-grid'\r\nimport type { ComponentType, ReactNode } from 'react'\r\nimport { mergeObjects } from '../utils'\r\nimport { TableBaseContext } from './context'\r\nimport { IActionRowProps } from './create.action-row'\r\nimport { customFilterOperators } from './custom.filter-operators'\r\nimport { GlobalModal, mapGlobalModalContext } from '../api-context'\r\nimport { ICustomGridColDef, ICustomGridFilterModel, ICustomGridSortModel, ITableData, ITableQueryParams } from './types'\r\nimport TableHelper from './helpers'\r\nimport ToolbarPannel, { IToolbarPannelProps } from './toolbar-pannel'\r\nimport { dinoTableClasses, TableStyled } from './styled'\r\n\r\nexport interface ITableSlots<T> {\r\n maxSelection?: number\r\n density?: GridDensity\r\n toolbar?: ComponentType<IToolbarPannelProps>\r\n actionRow?: ComponentType<IActionRowProps<T>>\r\n toolbarProps?: IToolbarPannelProps\r\n dataGridProps?: DataGridProps\r\n wrapProps?: BoxProps\r\n}\r\n\r\nexport type ITableParamsSlots<T> = Pick<ITableSlots<T>, 'maxSelection' | 'toolbarProps' | 'dataGridProps' | 'wrapProps'>\r\n\r\nexport interface ITableProps<T> {\r\n data?: ITableData<T>\r\n query?: ITableQueryParams<T>\r\n loading?: boolean\r\n onChange?: (query: ITableQueryParams<T>) => void\r\n onRowSelectionChange?: DataGridProps['onRowSelectionModelChange']\r\n slots?: ITableSlots<T>\r\n}\r\n\r\nexport interface ITableParams<T extends GridValidRowModel> extends ITableParamsSlots<T> {\r\n featureMode?: GridFeatureMode\r\n getRowId: GridRowIdGetter<T>\r\n columns: ICustomGridColDef<T>\r\n filterOperators?: (config: GridColDef) => GridFilterOperator[]\r\n columnVisibilityModel?: Partial<Record<keyof T, boolean>>\r\n actionRow?: Omit<GridColDef, 'field'>\r\n disableActionRow?: boolean\r\n disableGlobalModalProvider?: boolean\r\n}\r\n\r\nexport function CreateTable<T extends GridValidRowModel>(params: ITableParams<T>): ComponentType<ITableProps<T>> {\r\n const generateColumns = (extendColDefs?: GridColDef[]) => {\r\n const columns = Object.keys(params.columns).map<GridColDef>((key) => {\r\n const obj = { field: key, ...params.columns[key] }\r\n obj.filterOperators = params.filterOperators ? params.filterOperators(obj) : customFilterOperators(obj)\r\n return obj\r\n })\r\n\r\n if (!!extendColDefs && extendColDefs.length > 0) columns.push(...extendColDefs)\r\n return columns\r\n }\r\n\r\n class Table extends Component<ITableProps<T>> {\r\n private tableQueryParams: ITableQueryParams<T>\r\n // private tableQueryParamsCache: ITableQueryParams<T> = {}\r\n private defaultTableQueryParams: ITableQueryParams<T>\r\n private columns: GridColDef<T>[]\r\n private rowSelecteds: GridRowSelectionModel\r\n private changeTimeout?: ReturnType<typeof setTimeout>\r\n constructor(props: ITableProps<T>) {\r\n super(props)\r\n this.columns = this.initialColumns()\r\n this.tableQueryParams = { ...props.query }\r\n this.defaultTableQueryParams = this.tableQueryParams\r\n this.rowSelecteds = []\r\n }\r\n\r\n get mergeConfig() {\r\n const toolbarPannelProps = mergeObjects({}, params?.toolbarProps, this.props.slots?.toolbarProps)\r\n return {\r\n toolbar: this.props.slots?.toolbar ?? (() => <ToolbarPannel {...toolbarPannelProps} />),\r\n ActionRow: this.props.slots?.actionRow,\r\n disableActionRow: params.disableActionRow,\r\n columnVisibilityModel: params.columnVisibilityModel,\r\n maxSelcion: this.props.slots?.maxSelection ?? params.maxSelection,\r\n dataGridProps: mergeObjects({}, params.dataGridProps, this.props.slots?.dataGridProps),\r\n wrapProps: mergeObjects({}, params.wrapProps, this.props.slots?.wrapProps),\r\n loading: (this.props.loading !== undefined ? this.props.loading : this.tableQueryParams?.loading) ?? false\r\n }\r\n }\r\n\r\n setTableQueryParams = (value: Partial<ITableQueryParams<T>>) => {\r\n this.tableQueryParams = mergeObjects({}, this.tableQueryParams, value)\r\n }\r\n\r\n componentWillUnmount() {\r\n if (this.changeTimeout) {\r\n clearTimeout(this.changeTimeout)\r\n }\r\n }\r\n\r\n shouldComponentUpdate(nextProps: Readonly<ITableProps<T>>): boolean {\r\n if (params.featureMode === 'server') {\r\n // Check if query changed\r\n if (!TableHelper.equalTableQueryParams(nextProps.query, this.props.query)) {\r\n this.setTableQueryParams(nextProps.query ?? {})\r\n return true\r\n }\r\n // Check if data or loading changed\r\n if (JSON.stringify(nextProps.data) !== JSON.stringify(this.props.data) || nextProps.loading !== this.props.loading) {\r\n return true\r\n }\r\n return false\r\n } else {\r\n return true\r\n }\r\n }\r\n\r\n render() {\r\n const rootClasses = [dinoTableClasses.root, this.mergeConfig.wrapProps?.className]\r\n return this.renderWrapContext(\r\n <TableStyled {...this.mergeConfig.wrapProps} className={rootClasses.filter((x) => !!x).join(' ')}>\r\n <DataGrid loading={this.props.loading} {...this.getDataGridProps()} />\r\n </TableStyled>\r\n )\r\n }\r\n\r\n renderWrapContext = (children: ReactNode) => {\r\n const WrapComponent = params.disableGlobalModalProvider ? Fragment : GlobalModal\r\n return (\r\n <WrapComponent>\r\n {mapGlobalModalContext((context) => (\r\n <TableBaseContext.Provider value={{ showModal: context.show, closeModal: context.close }}>{children}</TableBaseContext.Provider>\r\n ))}\r\n </WrapComponent>\r\n )\r\n }\r\n\r\n getDataGridProps = (): DataGridProps<T> => {\r\n const initialState = TableHelper.mapInitialState(this.props.query, {\r\n columns: { columnVisibilityModel: params.columnVisibilityModel as GridColumnVisibilityModel }\r\n })\r\n const obj: DataGridProps<T> = {\r\n getRowId: params.getRowId,\r\n initialState,\r\n columns: this.columns,\r\n rows: this.props.data?.items ?? [],\r\n checkboxSelection: true,\r\n pagination: true,\r\n density: this.props.slots?.density ?? 'standard',\r\n filterDebounceMs: 800,\r\n sx: { border: 0 },\r\n slots: { toolbar: this.mergeConfig.toolbar },\r\n rowSelectionModel: this.rowSelecteds,\r\n onRowSelectionModelChange: this.handleRowSelectionChange\r\n }\r\n if (params.featureMode === 'server') {\r\n const objServer: Partial<DataGridProps<T>> = {\r\n filterMode: 'server',\r\n sortingMode: 'server',\r\n paginationMode: 'server',\r\n onPaginationModelChange: this.onPaginationModelChange,\r\n onFilterModelChange: this.onFilterModelChange,\r\n onSortModelChange: this.onSortModelChange,\r\n rowCount: this.props.data?.rowTotal ?? 0,\r\n paginationModel: this.tableQueryParams.pagination,\r\n filterModel: this.tableQueryParams.filter as GridFilterModel,\r\n sortModel: TableHelper.mapSortModel(this.tableQueryParams.sort),\r\n loading: this.mergeConfig.loading\r\n }\r\n Object.assign(obj, objServer)\r\n }\r\n return mergeObjects(obj, this.mergeConfig.dataGridProps)\r\n }\r\n\r\n initialColumns = (): GridColDef<T>[] => {\r\n const { ActionRow, disableActionRow } = this.mergeConfig\r\n const list: GridColDef<T>[] = []\r\n if (!!ActionRow && disableActionRow !== true) {\r\n list.push({\r\n field: 'Actions',\r\n minWidth: 100,\r\n headerAlign: 'right',\r\n align: 'right',\r\n filterable: false,\r\n sortable: false,\r\n disableExport: true,\r\n renderCell: (value) => <ActionRow value={value.row} />,\r\n ...params.actionRow\r\n })\r\n }\r\n return generateColumns(list)\r\n }\r\n\r\n onPaginationModelChange = (model: GridPaginationModel, details: GridCallbackDetails<'pagination'>) => {\r\n if (this.mergeConfig.loading) return\r\n this.setTableQueryParams({ pagination: model, detail: 'pagination' })\r\n this.handleChange()\r\n }\r\n\r\n onFilterModelChange = (model: GridFilterModel, details: GridCallbackDetails<'filter'>) => {\r\n if (this.mergeConfig.loading) return\r\n const { pagination } = this.tableQueryParams\r\n this.setTableQueryParams({\r\n filter: model as ICustomGridFilterModel<T>,\r\n pagination: { page: 0, pageSize: pagination?.pageSize ?? 25 },\r\n detail: TableHelper.detectSearchType(model)\r\n })\r\n this.handleChange()\r\n }\r\n\r\n onSortModelChange = (model: GridSortModel, details: GridCallbackDetails<any>) => {\r\n if (this.mergeConfig.loading) return\r\n let sortValue = model as ICustomGridSortModel<T>\r\n const { sort } = this.tableQueryParams\r\n if (!!sort?.length && !sortValue.length) {\r\n if (sort?.[0]?.field === this.defaultTableQueryParams.sort?.[0]?.field) {\r\n sortValue = [{ field: sort[0]?.field, sort: sort[0]?.sort === 'desc' ? 'asc' : 'desc' }]\r\n } else {\r\n sortValue = this.defaultTableQueryParams.sort ?? []\r\n }\r\n }\r\n this.setTableQueryParams({ sort: sortValue, detail: 'sort' })\r\n this.handleChange()\r\n }\r\n\r\n handleChange = () => {\r\n if (this.changeTimeout) clearTimeout(this.changeTimeout)\r\n this.changeTimeout = setTimeout(() => {\r\n this.props.onChange && this.props.onChange(this.tableQueryParams)\r\n }, 300)\r\n }\r\n\r\n handleRowSelectionChange = (value: GridRowSelectionModel, details: GridCallbackDetails) => {\r\n if (this.mergeConfig.maxSelcion && value.length > this.mergeConfig.maxSelcion) {\r\n this.rowSelecteds = value.slice(0, this.mergeConfig.maxSelcion)\r\n } else {\r\n this.rowSelecteds = value\r\n }\r\n this.props.onRowSelectionChange && this.props.onRowSelectionChange(this.rowSelecteds, details)\r\n this.forceUpdate()\r\n }\r\n }\r\n\r\n return Table\r\n}\r\n\r\nexport default CreateTable\r\n"],"names":["CreateTable","params","Table","props","_this","_classCallCheck","_callSuper","_defineProperty","value","tableQueryParams","mergeObjects","children","WrapComponent","disableGlobalModalProvider","Fragment","GlobalModal","_jsx","mapGlobalModalContext","context","TableBaseContext","Provider","showModal","show","closeModal","close","_this$props$data$item","_this$props$data","_this$props$slots$den","_this$props$slots","initialState","TableHelper","mapInitialState","query","columns","columnVisibilityModel","obj","getRowId","rows","data","items","checkboxSelection","pagination","density","slots","filterDebounceMs","sx","border","toolbar","mergeConfig","rowSelectionModel","rowSelecteds","onRowSelectionModelChange","handleRowSelectionChange","featureMode","_this$props$data$rowT","_this$props$data2","objServer","filterMode","sortingMode","paginationMode","onPaginationModelChange","onFilterModelChange","onSortModelChange","rowCount","rowTotal","paginationModel","filterModel","filter","sortModel","mapSortModel","sort","loading","Object","assign","dataGridProps","extendColDefs","_this$mergeConfig","ActionRow","disableActionRow","list","push","_objectSpread","field","minWidth","headerAlign","align","filterable","sortable","disableExport","renderCell","row","actionRow","keys","map","key","filterOperators","customFilterOperators","length","apply","_toConsumableArray","model","details","setTableQueryParams","detail","handleChange","_pagination$pageSize","page","pageSize","detectSearchType","_sort$","_this$defaultTableQue","_sort$2","_sort$3","_this$defaultTableQue2","sortValue","defaultTableQueryParams","changeTimeout","clearTimeout","setTimeout","onChange","maxSelcion","slice","onRowSelectionChange","forceUpdate","initialColumns","_inherits","Component","_createClass","get","_this$props$slots2","_this$props$slots$too","_this$props$slots3","_this$props$slots4","_this$props$slots$max","_this$props$slots5","_this$props$slots6","_this$props$slots7","_ref","_this$tableQueryParam","toolbarPannelProps","toolbarProps","this","ToolbarPannel","maxSelection","wrapProps","undefined","nextProps","_nextProps$query","equalTableQueryParams","JSON","stringify","_this$mergeConfig$wra","rootClasses","dinoTableClasses","root","className","renderWrapContext","TableStyled","x","join","DataGrid","getDataGridProps"],"mappings":"6vBAgDM,SAAUA,EAAyCC,GAkMvD,kBA/KE,SAAAC,EAAYC,GAAqB,IAAAC,EAKT,OALSC,OAAAH,GAC/BE,EAAAE,EAAAJ,KAAAA,GAAMC,IAAMI,EAAAH,EAqBQ,sBAAA,SAACI,GACrBJ,EAAKK,iBAAmBC,EAAa,CAAE,EAAEN,EAAKK,iBAAkBD,KACjED,EAAAH,EAkCmB,oBAAA,SAACO,GACnB,IAAMC,EAAgBX,EAAOY,2BAA6BC,EAAWC,EACrE,OACEC,EAACJ,EACE,CAAAD,SAAAM,EAAsB,SAACC,GAAO,OAC7BF,EAACG,EAAiBC,UAASZ,MAAO,CAAEa,UAAWH,EAAQI,KAAMC,WAAYL,EAAQM,gBAAUb,GAC5F,OAGNJ,EAAAH,EAAA,mBAEkB,WAAuB,IAAAqB,EAAAC,EAAAC,EAAAC,EAClCC,EAAeC,EAAYC,gBAAgB3B,EAAKD,MAAM6B,MAAO,CACjEC,QAAS,CAAEC,sBAAuBjC,EAAOiC,yBAErCC,EAAwB,CAC5BC,SAAUnC,EAAOmC,SACjBP,aAAAA,EACAI,QAAS7B,EAAK6B,QAC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B,EAAYsH,sBAAsBF,EAAUlH,MAAO6G,KAAK1I,MAAM6B,OAK/DqH,KAAKC,UAAUJ,EAAU5G,QAAU+G,KAAKC,UAAUT,KAAK1I,MAAMmC,OAAS4G,EAAU3E,UAAYsE,KAAK1I,MAAMoE,SAJzGsE,KAAKvC,oBAAmC,QAAhB6C,EAACD,EAAUlH,aAAKmH,IAAAA,EAAAA,EAAI,KACrC,GAUb,GAAC,CAAArD,IAAA,SAAAtF,MAED,WAAM,IAAA+I,EACEC,EAAc,CAACC,EAAiBC,KAAgCH,QAA5BA,EAAEV,KAAK7F,YAAYgG,qBAASO,SAA1BA,EAA4BI,WACxE,OAAOd,KAAKe,kBACV5I,EAAC6I,EAAW5E,EAAAA,EAAK,CAAA,EAAA4D,KAAK7F,YAAYgG,WAAS,CAAA,EAAA,CAAEW,UAAWH,EAAYrF,OAAO,SAAC2F,GAAC,QAAOA,CAAC,GAAEC,KAAK,cAC1F/I,EAACgJ,EAAQ/E,EAAA,CAACV,QAASsE,KAAK1I,MAAMoE,SAAasE,KAAKoB,wBAGtD,IAAC,GAwHL"}
|
package/dist/src/table/dino.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createClass as r,classCallCheck as t,defineProperty as e,objectSpread2 as o,objectWithoutProperties as n}from"../../_virtual/_rollupPluginBabelHelpers.js";import{jsx as a}from"react/jsx-runtime";import{MapTableBaseContext as
|
|
1
|
+
import{createClass as r,classCallCheck as t,defineProperty as e,objectSpread2 as o,objectWithoutProperties as n}from"../../_virtual/_rollupPluginBabelHelpers.js";import{jsx as a}from"react/jsx-runtime";import i from"dayjs";import"../utils/dayjs-config.js";import"../utils/query-param.js";import{MapTableBaseContext as u}from"./context.js";import{BtnFormDetail as l,BtnDetail as s}from"./ui.buttons.js";import{CreateStatusCell as c,CellChips as m,CellBase as f,CellImageSmall as p,CellDate as v}from"./ui.units.js";import h from"./toolbar-pannel.js";import d from"./helpers.js";import{CreateTable as g}from"./create.table.js";import y from"./create.action-row.js";import{generateExportCsvOptions as j}from"./csv-export-helper.js";import{Breadcrumbs as b}from"../components/breadcrumbs.js";var C=["imageUrl","valueFormatter","typographyProps","typographyPropsGetter"],S=["formatString"],w="MM/DD/YYYY HH:mm",P=new(r(function r(){var P=this;t(this,r),e(this,"createTable",g),e(this,"createActionRow",y),e(this,"generateExportCsvOptions",j),e(this,"setUrlQuery",d.setUrlQuery),e(this,"getUrlQuery",d.getUrlQuery),e(this,"mapContext",u),e(this,"ToolbarPannel",h),e(this,"createToolbar",function(r){return function(t){return a(h,o({},o(o({},t),r)))}}),e(this,"BtnFormDetail",l),e(this,"BtnDetail",s),e(this,"createBreadcrumbConfigs",function(r){return r}),e(this,"createBreadcrumbs",function(r){return function(){return a(b,{value:r})}}),e(this,"createStatusCell",c),e(this,"formatterDate",function(r,t){var e,o,n=null!==(e=null==t?void 0:t.formatString)&&void 0!==e?e:w,a=null!==(o=null==t?void 0:t.showRelative)&&void 0!==o&&o;try{if(!r)return"";var u=i(r),l=u.format(n);return a?"".concat(l," (").concat(i().to(u),")"):l}catch(r){return""}}),e(this,"valueFormatterDate",function(r){return function(t){return P.formatterDate(t.value,r)}}),e(this,"renderCellChips",function(r){return function(t){var e;return a(m,o(o({},r),{},{value:null!==(e=t.value)&&void 0!==e?e:null==r?void 0:r.value}))}}),e(this,"renderCellStatus",function(r,t){var e=c(r,o({sx:{minWidth:"90px"}},t));return function(r){return a(e,{value:r.value})}}),e(this,"renderCellBase",function(r){return function(t){var e=null!=r?r:{},i=e.imageUrl,u=e.valueFormatter,l=e.typographyProps,s=e.typographyPropsGetter,c=n(e,C),m=u?u(t.value,t.row):void 0,p=i?i(t.value,t.row):void 0,v=null!=r&&r.icon?"function"==typeof r.icon?r.icon(t.value,t.row):r.icon:void 0,h=s?s(t.value,t.row):l;return a(f,o(o({value:t.value,valueFormatted:m},c),{},{imageUrl:p,icon:v,typographyProps:h}))}}),e(this,"renderCellImage",function(r,t){return function(e){var o;return a(p,{value:e.value,imageUri:null===(o=r(e.row))||void 0===o?void 0:o.toString(),fallbackSrc:null==t?void 0:t.fallbackSrc})}}),e(this,"renderCellDate",function(r){return function(t){var e=null!=r?r:{},i=e.formatString,u=n(e,S);return a(v,o(o({},u),{},{value:t.value,formatString:null!=i?i:w}))}})}));export{P as default};
|
|
2
2
|
//# sourceMappingURL=dino.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dino.js","sources":["../../../src/table/dino.tsx"],"sourcesContent":["import { GridRenderCellParams, GridTreeNodeWithRender, GridValueFormatterParams } from '@mui/x-data-grid'\r\nimport type { FC, ReactNode } from 'react'\r\nimport { dayjsCustom } from '../utils'\r\nimport { MapTableBaseContext } from './context'\r\nimport { BtnDetail, BtnFormDetail } from './ui.buttons'\r\nimport { Breadcrumbs, IBreadcrumbConfig } from '../components'\r\nimport { CreateStatusCell, IStatusCellOptions, IStatusCellConfig } from './ui.units'\r\nimport { CellBase, CellImageSmall, CellBaseOptions, CellChips, CellChipsProps, CellDate, CellDatePropsOwner } from './ui.units'\r\nimport ToolbarPannel, { IToolbarPannelProps } from './toolbar-pannel'\r\nimport TableHelper from './helpers'\r\nimport CreateTable from './create.table'\r\nimport CreateActionRow from './create.action-row'\r\nimport { TypographyProps } from '@mui/material'\r\nimport { generateExportCsvOptions } from './csv-export-helper'\r\n\r\nconst formatDateString = 'MM/DD/YYYY HH:mm'\r\n\r\ntype RenderCellBaseParams<T> = Omit<CellBaseOptions, 'imageUrl'> & {\r\n imageUrl?: (value: any, model: T) => string\r\n valueFormatter?: (value: any, model: T) => string\r\n icon?: ReactNode | ((value: any, model: T) => ReactNode)\r\n typographyPropsGetter?: (value: any, model: T) => TypographyProps & { [key: string]: any }\r\n}\r\n\r\ninterface FormatterDateOptions {\r\n formatString?: string\r\n showRelative?: boolean\r\n}\r\n\r\nclass DinoTableBase {\r\n //#region Base\r\n\r\n createTable = CreateTable\r\n\r\n createActionRow = CreateActionRow\r\n\r\n generateExportCsvOptions = generateExportCsvOptions\r\n\r\n setUrlQuery = TableHelper.setUrlQuery\r\n\r\n getUrlQuery = TableHelper.getUrlQuery\r\n\r\n mapContext = MapTableBaseContext\r\n\r\n ToolbarPannel = ToolbarPannel\r\n\r\n createToolbar = (props: IToolbarPannelProps): FC<IToolbarPannelProps> => {\r\n return (p) => <ToolbarPannel {...{ ...p, ...props }} />\r\n }\r\n\r\n BtnFormDetail = BtnFormDetail\r\n\r\n BtnDetail = BtnDetail\r\n\r\n createBreadcrumbConfigs = (value: IBreadcrumbConfig[]) => value\r\n\r\n createBreadcrumbs = (value: IBreadcrumbConfig[]): FC => {\r\n return () => <Breadcrumbs value={value} />\r\n }\r\n\r\n createStatusCell = CreateStatusCell\r\n //#endregion\r\n\r\n //#region Value Formatter\r\n formatterDate = (value: any, options?: FormatterDateOptions): string => {\r\n const f = options?.formatString ?? formatDateString\r\n const showRelative = options?.showRelative ?? false\r\n try {\r\n if (!value) return ''\r\n\r\n const date = dayjsCustom(value)\r\n const formatted = date.format(f)\r\n\r\n return showRelative ? `${formatted} (${dayjsCustom().to(date)})` : formatted\r\n } catch (error) {\r\n return ''\r\n }\r\n }\r\n\r\n valueFormatterDate = (options?: FormatterDateOptions) => {\r\n return (params: GridValueFormatterParams<any>) => this.formatterDate(params.value, options)\r\n }\r\n //#endregion\r\n\r\n //#region Render Cell\r\n renderCellChips = (params?: CellChipsProps) => {\r\n return function func(tableRow: GridRenderCellParams<any, any, any, GridTreeNodeWithRender>) {\r\n return <CellChips {...params} value={tableRow.value ?? params?.value} />\r\n }\r\n }\r\n\r\n renderCellStatus = function <E extends string>(config: IStatusCellConfig<E>, options?: IStatusCellOptions) {\r\n const StatusCellInstance = CreateStatusCell(config, { sx: { minWidth: '90px' }, ...options })\r\n return function func(tableRow: GridRenderCellParams<any, any, any, GridTreeNodeWithRender>) {\r\n return <StatusCellInstance value={tableRow.value} />\r\n }\r\n }\r\n\r\n renderCellBase = function <T = any>(options?: RenderCellBaseParams<T>) {\r\n return function func(tableRow: GridRenderCellParams<any, any, any, GridTreeNodeWithRender>) {\r\n const { imageUrl, valueFormatter, typographyProps, typographyPropsGetter, ...p } = options ?? {}\r\n const value = valueFormatter ? valueFormatter(tableRow.value, tableRow.row) : undefined\r\n const img = imageUrl ? imageUrl(tableRow.value, tableRow.row) : undefined\r\n const icon = options?.icon ? (typeof options.icon === 'function' ? options.icon(tableRow.value, tableRow.row) : options.icon) : undefined\r\n const mergedTypographyProps = typographyPropsGetter ? typographyPropsGetter(tableRow.value, tableRow.row) : typographyProps\r\n return <CellBase value={tableRow.value} valueFormatted={value} {...p} imageUrl={img} icon={icon} typographyProps={mergedTypographyProps} />\r\n }\r\n }\r\n\r\n renderCellImage = function <T>(selectImage: (value: T) => T[keyof T], options?: { fallbackSrc?: string }) {\r\n return function func(tableRow: GridRenderCellParams<any, any, any, GridTreeNodeWithRender>) {\r\n return <CellImageSmall value={tableRow.value} imageUri={selectImage(tableRow.row)?.toString()} fallbackSrc={options?.fallbackSrc} />\r\n }\r\n }\r\n\r\n renderCellDate = function (params?: CellDatePropsOwner) {\r\n return function func(tableRow: GridRenderCellParams<any, any, any, GridTreeNodeWithRender>) {\r\n const { formatString, ...props } = params ?? {}\r\n return <CellDate {...props} value={tableRow.value} formatString={formatString ?? formatDateString} />\r\n }\r\n }\r\n //#endregion\r\n}\r\n\r\nconst DinoTable = new DinoTableBase()\r\n\r\nexport default DinoTable\r\n"],"names":["formatDateString","DinoTable","_createClass","DinoTableBase","_this","this","_classCallCheck","_defineProperty","CreateTable","CreateActionRow","generateExportCsvOptions","TableHelper","setUrlQuery","getUrlQuery","MapTableBaseContext","ToolbarPannel","props","p","_jsx","_objectSpread","BtnFormDetail","BtnDetail","value","Breadcrumbs","CreateStatusCell","options","_options$formatString","_options$showRelative","f","formatString","showRelative","date","dayjsCustom","formatted","format","concat","to","error","params","formatterDate","tableRow","_tableRow$value","CellChips","config","StatusCellInstance","sx","minWidth","_ref","imageUrl","valueFormatter","typographyProps","typographyPropsGetter","_objectWithoutProperties","_excluded","row","undefined","img","icon","mergedTypographyProps","CellBase","valueFormatted","selectImage","_selectImage","CellImageSmall","imageUri","toString","fallbackSrc","_ref2","_excluded2","CellDate"],"mappings":"
|
|
1
|
+
{"version":3,"file":"dino.js","sources":["../../../src/table/dino.tsx"],"sourcesContent":["import { GridRenderCellParams, GridTreeNodeWithRender, GridValueFormatterParams } from '@mui/x-data-grid'\r\nimport type { FC, ReactNode } from 'react'\r\nimport { dayjsCustom } from '../utils'\r\nimport { MapTableBaseContext } from './context'\r\nimport { BtnDetail, BtnFormDetail } from './ui.buttons'\r\nimport { Breadcrumbs, IBreadcrumbConfig } from '../components'\r\nimport { CreateStatusCell, IStatusCellOptions, IStatusCellConfig } from './ui.units'\r\nimport { CellBase, CellImageSmall, CellBaseOptions, CellChips, CellChipsProps, CellDate, CellDatePropsOwner } from './ui.units'\r\nimport ToolbarPannel, { IToolbarPannelProps } from './toolbar-pannel'\r\nimport TableHelper from './helpers'\r\nimport CreateTable from './create.table'\r\nimport CreateActionRow from './create.action-row'\r\nimport { TypographyProps } from '@mui/material'\r\nimport { generateExportCsvOptions } from './csv-export-helper'\r\n\r\nconst formatDateString = 'MM/DD/YYYY HH:mm'\r\n\r\ntype RenderCellBaseParams<T> = Omit<CellBaseOptions, 'imageUrl'> & {\r\n imageUrl?: (value: any, model: T) => string\r\n valueFormatter?: (value: any, model: T) => string\r\n icon?: ReactNode | ((value: any, model: T) => ReactNode)\r\n typographyPropsGetter?: (value: any, model: T) => TypographyProps & { [key: string]: any }\r\n}\r\n\r\ninterface FormatterDateOptions {\r\n formatString?: string\r\n showRelative?: boolean\r\n}\r\n\r\nclass DinoTableBase {\r\n //#region Base\r\n\r\n createTable = CreateTable\r\n\r\n createActionRow = CreateActionRow\r\n\r\n generateExportCsvOptions = generateExportCsvOptions\r\n\r\n setUrlQuery = TableHelper.setUrlQuery\r\n\r\n getUrlQuery = TableHelper.getUrlQuery\r\n\r\n mapContext = MapTableBaseContext\r\n\r\n ToolbarPannel = ToolbarPannel\r\n\r\n createToolbar = (props: IToolbarPannelProps): FC<IToolbarPannelProps> => {\r\n return (p) => <ToolbarPannel {...{ ...p, ...props }} />\r\n }\r\n\r\n BtnFormDetail = BtnFormDetail\r\n\r\n BtnDetail = BtnDetail\r\n\r\n createBreadcrumbConfigs = (value: IBreadcrumbConfig[]) => value\r\n\r\n createBreadcrumbs = (value: IBreadcrumbConfig[]): FC => {\r\n return () => <Breadcrumbs value={value} />\r\n }\r\n\r\n createStatusCell = CreateStatusCell\r\n //#endregion\r\n\r\n //#region Value Formatter\r\n formatterDate = (value: any, options?: FormatterDateOptions): string => {\r\n const f = options?.formatString ?? formatDateString\r\n const showRelative = options?.showRelative ?? false\r\n try {\r\n if (!value) return ''\r\n\r\n const date = dayjsCustom(value)\r\n const formatted = date.format(f)\r\n\r\n return showRelative ? `${formatted} (${dayjsCustom().to(date)})` : formatted\r\n } catch (error) {\r\n return ''\r\n }\r\n }\r\n\r\n valueFormatterDate = (options?: FormatterDateOptions) => {\r\n return (params: GridValueFormatterParams<any>) => this.formatterDate(params.value, options)\r\n }\r\n //#endregion\r\n\r\n //#region Render Cell\r\n renderCellChips = (params?: CellChipsProps) => {\r\n return function func(tableRow: GridRenderCellParams<any, any, any, GridTreeNodeWithRender>) {\r\n return <CellChips {...params} value={tableRow.value ?? params?.value} />\r\n }\r\n }\r\n\r\n renderCellStatus = function <E extends string>(config: IStatusCellConfig<E>, options?: IStatusCellOptions) {\r\n const StatusCellInstance = CreateStatusCell(config, { sx: { minWidth: '90px' }, ...options })\r\n return function func(tableRow: GridRenderCellParams<any, any, any, GridTreeNodeWithRender>) {\r\n return <StatusCellInstance value={tableRow.value} />\r\n }\r\n }\r\n\r\n renderCellBase = function <T = any>(options?: RenderCellBaseParams<T>) {\r\n return function func(tableRow: GridRenderCellParams<any, any, any, GridTreeNodeWithRender>) {\r\n const { imageUrl, valueFormatter, typographyProps, typographyPropsGetter, ...p } = options ?? {}\r\n const value = valueFormatter ? valueFormatter(tableRow.value, tableRow.row) : undefined\r\n const img = imageUrl ? imageUrl(tableRow.value, tableRow.row) : undefined\r\n const icon = options?.icon ? (typeof options.icon === 'function' ? options.icon(tableRow.value, tableRow.row) : options.icon) : undefined\r\n const mergedTypographyProps = typographyPropsGetter ? typographyPropsGetter(tableRow.value, tableRow.row) : typographyProps\r\n return <CellBase value={tableRow.value} valueFormatted={value} {...p} imageUrl={img} icon={icon} typographyProps={mergedTypographyProps} />\r\n }\r\n }\r\n\r\n renderCellImage = function <T>(selectImage: (value: T) => T[keyof T], options?: { fallbackSrc?: string }) {\r\n return function func(tableRow: GridRenderCellParams<any, any, any, GridTreeNodeWithRender>) {\r\n return <CellImageSmall value={tableRow.value} imageUri={selectImage(tableRow.row)?.toString()} fallbackSrc={options?.fallbackSrc} />\r\n }\r\n }\r\n\r\n renderCellDate = function (params?: CellDatePropsOwner) {\r\n return function func(tableRow: GridRenderCellParams<any, any, any, GridTreeNodeWithRender>) {\r\n const { formatString, ...props } = params ?? {}\r\n return <CellDate {...props} value={tableRow.value} formatString={formatString ?? formatDateString} />\r\n }\r\n }\r\n //#endregion\r\n}\r\n\r\nconst DinoTable = new DinoTableBase()\r\n\r\nexport default DinoTable\r\n"],"names":["formatDateString","DinoTable","_createClass","DinoTableBase","_this","this","_classCallCheck","_defineProperty","CreateTable","CreateActionRow","generateExportCsvOptions","TableHelper","setUrlQuery","getUrlQuery","MapTableBaseContext","ToolbarPannel","props","p","_jsx","_objectSpread","BtnFormDetail","BtnDetail","value","Breadcrumbs","CreateStatusCell","options","_options$formatString","_options$showRelative","f","formatString","showRelative","date","dayjsCustom","formatted","format","concat","to","error","params","formatterDate","tableRow","_tableRow$value","CellChips","config","StatusCellInstance","sx","minWidth","_ref","imageUrl","valueFormatter","typographyProps","typographyPropsGetter","_objectWithoutProperties","_excluded","row","undefined","img","icon","mergedTypographyProps","CellBase","valueFormatted","selectImage","_selectImage","CellImageSmall","imageUri","toString","fallbackSrc","_ref2","_excluded2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C,aAAO,EAAPA,EAASyC,aACtH,IACF3D,EAAAF,KAAA,iBAEgB,SAAUiC,GACzB,OAAO,SAAcE,GACnB,IAAA2B,EAAmC7B,QAAAA,EAAU,CAAE,EAAvCT,EAAYsC,EAAZtC,aAAiBb,EAAKoC,EAAAe,EAAAC,GAC9B,OAAOlD,EAACmD,EAAQlD,EAAAA,KAAKH,GAAK,GAAA,CAAEM,MAAOkB,EAASlB,MAAOO,aAAcA,QAAAA,EAAgB7B,IAClF,GACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createClass as t,classCallCheck as
|
|
1
|
+
import{createClass as t,classCallCheck as r,defineProperty as e,objectSpread2 as i}from"../../_virtual/_rollupPluginBabelHelpers.js";import{encodeBase64 as l,tryParseObject as a,decodeBase64 as n}from"../utils/helpers.js";import"../utils/dayjs-config.js";import{QueryParam as u}from"../utils/query-param.js";var s=new(t(function t(){var s=this;r(this,t),e(this,"extractTableQueryParams",function(t){return t?{pagination:t.pagination,filter:t.filter,sort:t.sort,loading:t.loading}:{}}),e(this,"isEmpty",function(t,r){var e,i=s.extractTableQueryParams(t),l=!i.filter||i.filter.items.filter(function(t){return!!t.value}).length<1,a=!(null!==(e=t.filter)&&void 0!==e&&e.quickFilterValues)||t.filter.quickFilterValues.length<1;return l||a}),e(this,"equalTableQueryParams",function(t,r){return JSON.stringify(s.extractTableQueryParams(t))===JSON.stringify(s.extractTableQueryParams(r))}),e(this,"mapInitialState",function(t,r){return t?i({pagination:{paginationModel:t.pagination},filter:{filterModel:t.filter},sorting:{sortModel:s.mapSortModel(t.sort)}},r):null!=r?r:{}}),e(this,"mapSortModel",function(t){return null==t?void 0:t.map(function(t){return{field:t.field.toString(),sort:t.sort}})}),e(this,"detectSearchType",function(t){var r=t.quickFilterValues&&t.quickFilterValues.length>0,e=t.items&&t.items.length>0;return r&&!e?"quickSearch":e?"filter":void 0}),e(this,"extractToUrlQuery",function(t){var r,e=t.filter,i={filter:e,sort:t.sort,pagination:t.pagination},l=!(null!=e&&null!==(r=e.quickFilterValues)&&void 0!==r&&r.filter(function(t){return!!t}).length);return null!=e&&e.items.length||!l||(i.filter=void 0),i}),e(this,"equals",function(t,r){return JSON.stringify(s.extractToUrlQuery(t))===JSON.stringify(s.extractToUrlQuery(r))}),e(this,"setUrlQuery",function(t,r){try{if(s.equals(t,r))u.deletes("table");else{var e=s.extractToUrlQuery(t),i={table:l(JSON.stringify(e))};u.patch(i)}}catch(t){console.log("Set URL Query error:",t)}}),e(this,"getUrlQuery",function(t){var r,e=u.getAll();if(null==e||!e.table)return t;var i=a(n(null!==(r=e.table)&&void 0!==r?r:""),{});return Object.keys(i).length<1?t:i})}));export{s as default};
|
|
2
2
|
//# sourceMappingURL=helpers.js.map
|