|
| 1 | +window.createToDoJuicer=(state)=>{ |
| 2 | +constjuicer=newwindow.Juicer({initialState:state,dev:true}) |
| 3 | + |
| 4 | +letid=0 |
| 5 | + |
| 6 | +functionfindToDoFromId(todos,id){ |
| 7 | +consti=todos.findIndex(t=>t.id=id) |
| 8 | +returntodos[i] |
| 9 | +} |
| 10 | + |
| 11 | +juicer.action('addTodo',({},_state)=>{ |
| 12 | +if(_state.newTodo.length===0){ |
| 13 | +return{errorText:"cannot create empty todo"} |
| 14 | +}else{ |
| 15 | +id++ |
| 16 | + |
| 17 | +consttodo={ |
| 18 | +title:_state.newTodo, |
| 19 | +isComplete:false, |
| 20 | +isEditing:false, |
| 21 | + id |
| 22 | +} |
| 23 | + |
| 24 | +return{newTodo:'',todos:[todo, ..._state.todos]} |
| 25 | +} |
| 26 | +}) |
| 27 | + |
| 28 | +juicer.action('textInput',({ text},_state)=>{ |
| 29 | +return{newTodo:text} |
| 30 | +}) |
| 31 | + |
| 32 | +juicer.action('setFilter',({ filter},_state)=>{ |
| 33 | +return{ filter} |
| 34 | +}) |
| 35 | + |
| 36 | +juicer.action('toggleAll',({},_state)=>{ |
| 37 | +return{ |
| 38 | +todos:_state.todos.map((t)=>{ |
| 39 | +t.isComplete=true |
| 40 | +returnt |
| 41 | +}) |
| 42 | +} |
| 43 | +}) |
| 44 | + |
| 45 | +juicer.action('toggleDone',({ id},_state)=>{ |
| 46 | +consttodo=findToDoFromId(_state.todos,id) |
| 47 | +if(todo){ |
| 48 | +todo.isComplete=!todo.isComplete |
| 49 | +return{todos:_state.todos} |
| 50 | +}else{ |
| 51 | +throwError(`could not find todo with id${id}`) |
| 52 | +} |
| 53 | +}) |
| 54 | + |
| 55 | +juicer.action('toggleEdit',({ id},_state)=>{ |
| 56 | +consttodo=findToDoFromId(_state.todos,id) |
| 57 | +if(todo){ |
| 58 | +todo.isEditing=!todo.isEditing |
| 59 | +return{todos:_state.todos,isEditing:todo.isEditing} |
| 60 | +}else{ |
| 61 | +throwError(`could not find todo with id${id}`) |
| 62 | +} |
| 63 | +}) |
| 64 | + |
| 65 | +juicer.action('updateTodo',({ id, title},_state)=>{ |
| 66 | +consttodo=findToDoFromId(_state.todos,id) |
| 67 | +if(todo){ |
| 68 | +todo.title=title |
| 69 | +return{todos:_state.todos} |
| 70 | +}else{ |
| 71 | +throwError(`could not find todo with id${id}`) |
| 72 | +} |
| 73 | +}) |
| 74 | + |
| 75 | +juicer.action('clearCompleted',({},_state)=>{ |
| 76 | +return{todos:_state.todos.filter(t=>t.isComplete===false)} |
| 77 | +}) |
| 78 | + |
| 79 | +juicer.action('delete',({ id},_state)=>{ |
| 80 | +return{todos:_state.todos.filter(t=>t.id!==id)} |
| 81 | +}) |
| 82 | + |
| 83 | +juicer.reaction(["todos","filter"],(changedState,_state)=>{ |
| 84 | +constfilters={ |
| 85 | +all:(t)=>{returnt}, |
| 86 | +completed:(t)=>{returnt.isComplete===true}, |
| 87 | +active:(t)=>{returnt.isComplete===false} |
| 88 | +} |
| 89 | + |
| 90 | +return{ |
| 91 | +filteredTodos:_state.todos.filter(filters[_state.filter]), |
| 92 | +remainingTodos:_state.todos.filter(filters['active']).length |
| 93 | +} |
| 94 | +}) |
| 95 | + |
| 96 | +returnjuicer |
| 97 | +} |