Last active
April 11, 2017 08:05
-
-
Save jvanbruegge/20d6dae510bece3afd8f82e52ffcb2d2 to your computer and use it in GitHub Desktop.
A simple todo test in Cyclejs and xstream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
div, span, p, input, ul, li, button, body | |
} | |
from '@cycle/dom' | |
import xs from 'xstream' | |
export function Todo(sources) { | |
const action$ = intent(sources.DOM); | |
const model$ = action$ | |
.fold((state, reducer) => reducer(state), { | |
currentTodos: [], | |
value: '' | |
}); | |
const vdom$ = view(model$); | |
const sinks = { | |
DOM: vdom$ | |
} | |
return sinks | |
} | |
function intent(DOM) { | |
const getIdStream = selector => DOM.select(selector).event('click') | |
.map(ev => ev.target.getAttribute('data-id')) | |
.map(parseInt) | |
.filter(v => !isNaN(v)); | |
const writeTodo$ = DOM.select('input[type=text]').events('input') | |
.map(ev => ev.target.value) | |
.map(v => prevState => ({ ...prevState, value: v })); | |
const addTodo$ = DOM.select('input[type=text]').events('keydown') | |
.filter(ev => ev.which === 13) | |
.mapTo(prevState => ({ | |
...prevState, | |
currentTodos: prevState.currentTodos.concat([{ | |
value: prevState.value, | |
id: prevState.currentTodos.length, // length is already one more than the items inside | |
completed: false | |
}]), | |
value: '' | |
})); | |
const deleteTodo$ = getIdStream('.delete') | |
.map(id => prevState => ({ | |
...prevState, | |
currentTodos: prevState.currentTodos | |
.filter(e => e.id !== id) | |
})); | |
const completeTodo$ = getIdStream('.complete') | |
.map(id => prevState => ({ | |
...prevState, | |
currentTodos: prevState.currentTodos | |
.map(todo => todo.id !== id ? todo : { ...todo, completed: !todo.completed }) | |
})); | |
return xs.merge(writeTodo$, addTodo$, deleteTodo$, completeTodo$); | |
} | |
function view(state$) { | |
return state$.map((state) => { | |
return div({ | |
attrs: { | |
class: 'todo' | |
} | |
}, [ | |
input({ | |
props: { | |
type: 'text', | |
value: state.value | |
} | |
}), | |
ul({ | |
attrs: { | |
class: 'text' | |
} | |
}, state.currentTodos.map((todo) => { | |
return li({ | |
attrs: { | |
class: todo.completed ? 'completed' : 'open' | |
} | |
}, [ | |
span(todo.value), | |
button({ | |
attrs: { | |
class: 'delete', | |
'data-id': todo.id | |
} | |
}, 'XXXXX'), | |
button({ | |
attrs: { | |
class: 'complete', | |
'data-id': todo.id | |
} | |
}, 'CCCCC') | |
]); | |
})) | |
]); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment