Gathering detailed insights and metrics for mst-form-type
Gathering detailed insights and metrics for mst-form-type
Gathering detailed insights and metrics for mst-form-type
Gathering detailed insights and metrics for mst-form-type
A tiny custom mobx-state-tree model type to handle common forms
npm install mst-form-type
Typescript
Module System
Node Version
NPM Version
TypeScript (92.68%)
JavaScript (7.13%)
Shell (0.19%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
2 Stars
21 Commits
2 Watchers
1 Branches
1 Contributors
Updated on Oct 11, 2024
Latest Version
2.1.0
Package Id
mst-form-type@2.1.0
Unpacked Size
32.79 kB
Size
8.94 kB
File Count
7
NPM Version
10.8.1
Node Version
20.16.0
Published on
Oct 11, 2024
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
This is a tiny custom Mobx State Tree type to handle common forms. It create a new custom types.model
based on form schema. If no error happens, it will return all fields values in Key-Value object via submit()
action. It will hold the last valid submission, as well as the last error. The package is easy to understand, and hope it can save some effort.
1// Old 2const schema = { 3 [key: string]: { 4 default: string | number 5 validator?: 'required' | ((...args: any[]) => boolean) | RegExp | undefined | null 6 } 7} 8 9// New 10interface FieldSchema { 11 id: string 12 type?: 'string' | 'number' | 'object' | 'array' | 'boolean' 13 default: TValue 14 validator?: TValidator 15 msg?: string 16} 17 18interface DynamicFields { 19 id: string 20 limit: number 21 schema: FieldSchema | FieldSchema[] 22 default: Array<Record<string, TValue>> 23 onAdd?: (arg) => any 24 onRemove?: (id: string) => any 25 onEdit?: (key: string) => void 26} 27 28interface FormSchema { 29 static: FieldSchema[] 30 dynamic?: DynamicFields[] 31}
1const dynamicForm: FormSchema = { 2 static: [ 3 { 4 id: 'name', 5 default: '', 6 validator: 'required', 7 }, 8 { 9 id: 'des', 10 default: '', 11 }, 12 ], 13 dynamic: [ 14 { 15 id: 'price', // group id 16 limit: 100, 17 schema: [ 18 { 19 id: 'itemName', 20 default: '', 21 validator: 'required', 22 }, 23 { 24 id: 'itemPrice', 25 default: 10, 26 }, 27 ], 28 default: [ 29 { 30 itemName: 'itemName1', 31 itemPrice: 5, 32 }, 33 { 34 itemName: 'itemName2', 35 itemPrice: 20, 36 }, 37 ], 38 onAdd: i => { 39 console.log('add', i) 40 }, 41 onRemove: i => { 42 console.log('remove', i) 43 }, 44 onEdit: key => { 45 console.log('edit', key) 46 }, 47 }, 48 ], 49} 50 51// render dynamic fields 52model.dynamicForm['price'].fields.map(fields => ({ ... })) 53 54// field action 55model.dynamicForm.onAdd('price') // this will use field default value in schema 56model.dynamicForm.onRemove('price', fields.id) 57 58// form action 59model.dynamicForm.submit() 60model.dynamicForm.reset() 61model.dynamicForm.clear('price') // this will clear all dynamic fields, including default ones
initVal
action, now init form by schema, and use reset to set form to init values.npm install -S mst-form-type
1import createForm from 'mst-form-type' 2 3const schema = { 4 static: FieldSchema[] 5 dynamic?: DynamicFields[] 6} 7 8const Main = types.model('Main', { 9 form: createForm(schema, 'name?') 10 ... 11}) 12 13// change field value 14form.setValue({ key, value }) 15// change dynamic field value 16form.setDynamicValue({ groupId, id, key, value }) 17// submit form 18form.submit() => { key1: value1, key2: value2, ... }
default export
The default exported method will generate a new custom types.model with all the fields in the schema as props, based on a base model type. The newly created form type will automatically initialize with the schema upon creation. Optionally, a name can be passed for tracking purposes; otherwise, it will default to the base model name.
1type TValidator = 'required' | ((...args: any[]) => boolean) | RegExp | undefined | null 2 3type TValue = string | boolean | number | Record<string, string> | Array<any> 4 5interface FieldSchema { 6 id: string 7 type?: 'string' | 'number' | 'boolean' | 'object' | 'array' 8 default: TValue 9 validator?: TValidator 10 msg?: string 11}
1type TValidator = 'required' | ((...args: any[]) => boolean) | RegExp | undefined | null 2 3type TValue = string | boolean | number | Record<string, string> | Array<any> 4 5interface FieldSchema { 6 id: string 7 type?: 'string' | 'number' | 'boolean' | 'object' | 'array' 8 default: TValue 9 validator?: TValidator 10 msg?: string 11}
id
types.identifier
. The key of each field in a form, and will become the form type props key. It should be unique and will be used to access field value and in setValue()
form action.
value
The props hold the field value. The value type can be string
, boolean
, number
, object
, array
. object
and array
will be tranform to types.frozen
as a MST leaf.
default
The default value of a field. The Mobx State Tree will decide prop
type based on the type of this value.
validator
Optional & Private. All validators will be called in valid()
before submit()
.
'required'
means this field cannot be falsy values, like 0
, ''
, or undefined
.
((...args: any[]) => boolean)
means a function return a boolean value. If returned true
, the validation will be treated passed.
RegExp
means the value will be used in RegExp.test()
. If returned true
, the validation will be treated passed.
undefined | null
will not be processed.
msg
Optional. Message shows when field is invalid. The default message is 'The input is invalid'
invalid
Compute value. Return revert value of invalid()
result
setValue(value)
Update field value.
valid()
Run field validator if it has.
reset()
Reset field value to default value.
actions below will be less frequent to use.
setValidator(rawValidator: TValidator)
Change field validator after initialization
init(field: IField)
Rerun field initialization
setErrorMsg(msg: string)
Change invalid message
clear()
Set field value to null
1form[id].value 2form[id].invalid 3form[id].setValue('new-value') 4form[id].reset() 5form[id].valid()
1interface DynamicFields { 2 id: string 3 limit: number 4 schema: FieldSchema | FieldSchema[] 5 default?: Array<Record<string, TValue>> 6 onAdd?: (field) => any 7 onRemove?: (field) => any 8 onEdit?: (field) => void 9}
id
types.identifier
. The key of each dynamic field group in a form, and will become the form type props key. It should be unique and will be used to access field value and in setDynamicValue()
form action.
fields
An array holds all dynamic field models. schema
in the interface is to define field schema here. Object in default
array will be used to create dynamic fields when form initializing.
limit
Optional. Maxium dynamic field allowed. default is -1
, means unlimited.
addFields(i, isInit = false)
Add new dynamic field i
. You don't need to pass isInit flag when calling the action. It is used for not calling onAdd
hooks in schema when initialization.
removeFields(id: string)
Remove the field with specific id
. This action will call the onRemove
hook if passed.
editField(id: string, fieldKey: string, value)
Edit fieldKey
field with id
to value
. This action will call the onEdit
hook if passed.
actions below will be less frequent to use.
getValues()
Get all dynamic field values/
valid()
Valid all dynamic field.
reset()
Reset all dynamic fields.
1form[id].fields.map(field => { ... }) 2form[id].addFields(field) 3form[id].removeFields('id') 4form[id].editField('id', 'key', 'value') 5form[id].getValues() // get all dynamic field values, rarely used 6form[id].valid() // valid all dynamic field, rarely used 7form[id].reset() // reset all dynamic field, rarely used
1interface FormSchema { 2 static: FieldSchema[] 3 dynamic?: DynamicFields[] 4}
fields
Every field in schema
will become a field prop
of form type. The type of each field will be based on default
value.
submission
A snapshot of last success submitted form values, in Key-Value object format.
error
An object in Key-Value format contains validation error of each field. This will be cleared on every valid()
call.
_internalStatus
Indicate the form status, has 4 values: 'init', 'pending', 'success', 'error'
. Usually you don't need it, it will change according to form status.
loading
Compute value. Return true
when form status is 'pending'. Designed for avoiding duplicated submission.
setValue({ key, value })
Set static field value in a form type. _internalStatus
is reserved.
setDynamicValue({ groupId, id, key, value })
Set dynamic field value in a form type. Each dynamic field has a field group id and a field id. Or you can use the setValue
action on instance to do the same job.
submit()
It will return all field values if passed validation in Key-Value format object. The last valid submission will be hold in submission
props.
The method will not submit the form in any form of action. It only output the form current values. You need to handle to real submission action yourself.
actions below will be less frequent to use.
init()
It will be called after new custom type created with schema. It will process the schema to get default values and validators.
valid()
It will run all validators in schema with current field values. It will be called in submit()
, and produce error
if any error happens.
reset()
It will set the form type to init
status, clearing submissions and errors. All fields will be set to default values passed by schema.
1form.setValue({ key, value }) 2form.setDynamicValue({ groupId, id, key, value }) 3form.submit() 4form.rest() 5form.onAdd(id, field) 6form.onRemove(groupId, fieldId) 7form.onEdit(groupId, fieldId, key, value) 8form.clear(groupId)
No vulnerabilities found.
No security vulnerabilities found.