This repository has been archived by the owner on Jan 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
form.js
75 lines (62 loc) · 1.65 KB
/
form.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { getFormData } from './utils'
export default function form ({ main, get, elm, emit, update, msg }) {
const field = get('form-field')
main( _ => [
events,
exposing
])
const events = ({ on }) => {
on('form-field:change', validate)
on('submit', onsubmit)
}
const exposing = ({ expose }) => {
expose({ validate, setFields })
}
const setFields = ( fields ) => {
for( const name in fields )
field('set', name, fields[name], fields)
msg.set( s => s.data = Object.assign({}, s.data, fields) )
}
const validate = () => {
let isFormValid = true
let updateData = {}
field('map', ({ elm, state }) => {
if( elm.querySelector('[data-rules]') && !state.isValid ) {
isFormValid = false
}
const input = elm.querySelector('input, select, textarea')
if( input.type == 'checkbox' || input.type == 'radio' ) {
// updateData[input.name] = input.checked? input.value || input.name : ''
}else {
updateData[input.name] = input.value
}
})
if( isFormValid != msg.getState().isValid ){
msg.set( s => {
s.isValid = isFormValid
s.data = Object.assign(s.data, updateData)
})
emit(`form:${isFormValid? 'valid': 'invalid'}`, getFormData(elm))
}
}
const onsubmit = (e) => {
const { isValid } = msg.getState()
if( isValid ) {
emit('form:submit', getFormData(elm))
}
e.preventDefault()
}
/**
* @function update
* @description Updating form with parent states
*/
update( (props) => {
if( props && JSON.stringify(props) != JSON.stringify(msg.getState().data) ) {
msg.set( s => s.data = Object.assign({}, s.data, props.data) )
}
})
}
export const model = {
isValid: false,
data : {}
}