15
15
* limitations under the License.
16
16
*/
17
17
import { JsonInput , type JsonInputProps } from '@mantine/core' ;
18
+ import { omit } from 'rambdax' ;
18
19
import { useMemo } from 'react' ;
19
20
import {
20
21
type FieldValues ,
@@ -24,19 +25,20 @@ import {
24
25
25
26
import { genControllerProps } from './util' ;
26
27
27
- export type FormItemJsonInputProps < T extends FieldValues > =
28
- UseControllerProps < T > &
29
- JsonInputProps & {
30
- toObject ?: boolean ;
31
- } ;
28
+ export type FormItemJsonInputProps < T extends FieldValues > = UseControllerProps < T > &
29
+ JsonInputProps & {
30
+ toObject ?: boolean ;
31
+ objValue ?: unknown ;
32
+ } ;
32
33
33
34
export const FormItemJsonInput = < T extends FieldValues > (
34
35
props : FormItemJsonInputProps < T >
35
36
) => {
37
+ const { objValue = { } } = props ;
36
38
const {
37
39
controllerProps,
38
40
restProps : { toObject, ...restProps } ,
39
- } = genControllerProps ( props , props . toObject ? { } : '' ) ;
41
+ } = genControllerProps ( props , props . toObject ? objValue : '' ) ;
40
42
const {
41
43
field : { value : rawVal , onChange : fOnChange , ...restField } ,
42
44
fieldState,
@@ -45,9 +47,9 @@ export const FormItemJsonInput = <T extends FieldValues>(
45
47
if ( ! toObject ) return rawVal ;
46
48
if ( typeof rawVal === 'string' ) return rawVal ;
47
49
const val = JSON . stringify ( rawVal , null , 2 ) ;
48
- if ( val === '{}' ) return '' ;
50
+ if ( val === JSON . stringify ( objValue ) ) return '' ;
49
51
return val ;
50
- } , [ rawVal , toObject ] ) ;
52
+ } , [ rawVal , toObject , objValue ] ) ;
51
53
52
54
return (
53
55
< JsonInput
@@ -59,7 +61,7 @@ export const FormItemJsonInput = <T extends FieldValues>(
59
61
try {
60
62
res = JSON . parse ( val ) ;
61
63
} catch {
62
- res = val . length === 0 ? { } : val ;
64
+ res = val . length === 0 ? objValue : val ;
63
65
}
64
66
}
65
67
fOnChange ( res ) ;
@@ -69,7 +71,7 @@ export const FormItemJsonInput = <T extends FieldValues>(
69
71
autosize
70
72
resize = "vertical"
71
73
{ ...restField }
72
- { ...restProps }
74
+ { ...omit ( [ 'objValue' ] , restProps ) }
73
75
/>
74
76
) ;
75
77
} ;
0 commit comments