Last active
December 10, 2016 11:31
-
-
Save kana-sama/8fc20cd78066b3963865395e306b1cea to your computer and use it in GitHub Desktop.
Run here: http://widdersh.in/tricycle/
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 {makeDOMDriver, div, input, p} from '@cycle/dom'; | |
//========================================================= | |
// LIB | |
// Either monad | |
const pure = | |
value => | |
({ ok: true, value }) | |
const fail = | |
value => | |
({ ok: false, value }) | |
const applyM = | |
({ ok, value }, next) => | |
(ok ? next : fail)(value) | |
const pipeM = | |
(...fns) => value => | |
fns.reduce(applyM, value) | |
const pipe = | |
(...fns) => value => | |
pipeM(...fns)(pure(value)) | |
// Other | |
const path = | |
(...path) => value => | |
path.reduce((v, p) => v[p], value) | |
const wrap = | |
(...path) => | |
value => | |
path.reduceRight((v, p) => ({ [p]: v }), value) | |
const comp = | |
(...fns) => v => | |
fns.reduceRight((v, f) => f(v), v) | |
const update = | |
(subpath, mutate) => | |
comp(wrap(...subpath), mutate, path(...subpath)) | |
//========================================================= | |
const validateMinLength = | |
name => | |
name.length === 0 | |
? fail("Length must be > 0") | |
: pure(name) | |
const validateMaxLength = | |
name => | |
name.length > 10 | |
? fail("Length must be < 10") | |
: pure(name) | |
const validateFormat = | |
name => | |
/^[A-Z][a-z]*$/.test(name) | |
? pure(name) | |
: fail("Invalid format") | |
const validate = pipe( | |
validateMinLength, | |
validateMaxLength, | |
validateFormat | |
) | |
const statusColor = | |
({ ok }) => | |
ok ? "green" : "red" | |
const statusText = | |
({ ok, value }) => | |
ok | |
? `Hello ${ value }` | |
: `Error: ${ value }` | |
const nameStatus = | |
result => | |
p({ attrs: { style: `color: ${statusColor(result)}` } }, | |
statusText(result)) | |
const form = | |
name => div([ | |
input({ attrs: { value: name }}), | |
nameStatus(validate(name)) | |
]) | |
const main = update(["DOM"], DOM => DOM | |
.select('input') | |
.events('input') | |
.map(path("target", "value")) | |
.startWith("") | |
.map(form) | |
) | |
const sources = { | |
DOM: makeDOMDriver('.app') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment