1
+ const contactsState = [ ]
2
+
3
+
4
+ function renderContacts ( state ) {
5
+ return state . map ( ( contact , index ) => {
6
+ return contact . editMode ? `
7
+ <div class="contact-card-editor">
8
+ Name: <input name="name" type="text" value="${ contact . name } "> <br>
9
+ Phone: <input name="phone" type="text" value="${ contact . phone } "> <br>
10
+ Photo <input name="photo" type="text" value="${ contact . photo } "> <br>
11
+
12
+ <button data-action="save" data-index="${ index } "> Save </button>
13
+ </div>
14
+ ` : `
15
+ <div class="contact-card">
16
+ <p> Name: ${ contact . name } </p>
17
+ <p> Phone: ${ contact . phone } </p>
18
+ <p> Photo: ${ contact . photo } </p>
19
+
20
+ <button data-action="delete" data-index="${ index } "> Delete </button>
21
+ <button data-action="edit" data-index="${ index } "> Edit </button>
22
+ </div>
23
+ `
24
+ } ) . reduce ( ( acc , val ) => acc + val , '' )
25
+ }
26
+
27
+ function paintContacts ( ) {
28
+ document . getElementById ( 'contacts' ) . innerHTML = renderContacts ( contactsState )
29
+ }
30
+
31
+ // paintContacts()
32
+
33
+ function addContact ( e ) {
34
+ const inputElements = [ ...document . querySelectorAll ( '#contact-editor > input' ) ]
35
+ const inputs = reduceStateFromInputElements ( inputElements )
36
+ contactsState . push ( inputs )
37
+ paintContacts ( )
38
+ }
39
+
40
+ const reduceStateFromInputElements = inputElements =>
41
+ inputElements . reduce ( ( acc , val ) => ( {
42
+ ...acc ,
43
+ [ val . name ] : [ val . value ]
44
+ } ) , { } )
45
+
46
+
47
+
48
+ document . getElementById ( 'contacts' ) . addEventListener ( 'click' , e => {
49
+ // const {index, action} = e.target.dataset
50
+ const index = e . target . dataset . index
51
+ const action = e . target . dataset . action
52
+
53
+ // console.log(action, index)
54
+
55
+ if ( ! action ) {
56
+ return ;
57
+ }
58
+
59
+ switch ( action ) {
60
+ case 'delete' :
61
+ contactsState . splice ( index , 1 )
62
+ break
63
+ case 'edit' :
64
+ contactsState [ index ] . editMode = true
65
+ break ;
66
+ case 'save' :
67
+ const inputNodes = [ ...e . target . parentNode . querySelectorAll ( 'input' ) ]
68
+ const contactState = reduceStateFromInputElements ( inputNodes )
69
+ contactsState [ index ] = contactState
70
+ break ;
71
+ }
72
+
73
+ paintContacts ( )
74
+ } )
0 commit comments