better code
Massimo Melina committed
Feb 8, 2023 at 11:03 UTC
73688c119a73c97b2629003be23142a22ff82854
1 file changed
+14
-4
mui-grid-form/StringField.ts
+14
-4
@@ -1,16 +1,25 @@
1
// This file is part of HFS - Copyright 2021-2023, Massimo Melina <a@rejetto.com> - License https://www.gnu.org/licenses/gpl-3.0.txt
2
3
-import { createElement as h, useEffect, useRef, useState } from 'react'
3
+import { createElement as h, ReactNode, useEffect, useRef, useState } from 'react'
4
import { FieldProps } from '.'
5
import { InputAdornment, TextField } from '@mui/material'
6
7
-export function StringField({ value, onChange, min, max, required, getApi, typing, start, end, ...props }: FieldProps<string>) {
7
+interface StringProps extends FieldProps<string> {
8
+ typing?: boolean
9
+ onTyping?: (v: string) => boolean
10
+ min?: number
11
+ max?: number
12
+ required?: boolean
13
+ start?: ReactNode
14
+ end?: ReactNode
15
+}
16
+export function StringField({ value, onChange, min, max, required, getApi, typing, start, end, onTyping, ...props }: StringProps) {
17
const normalized = value ?? ''
18
getApi?.({
19
getError() {
20
return !value && required ? "required"
12
- : value?.length! < min ? "too short"
13
- : value?.length! > max ? "too long"
21
+ : value?.length! < min! ? "too short"
22
+ : value?.length! > max! ? "too long"
23
: false
24
}
25
})
@@ -29,6 +38,7 @@ export function StringField({ value, onChange, min, max, required, getApi, typin
38
value: state,
39
onChange(ev) {
40
const val = ev.target.value
41
+ if (onTyping?.(val) === false) return
42
setState(val)
43
if (typing // change state as the user is typing
44
|| document.activeElement !== ev.target) // autofill ongoing, don't wait onBlur event, just go