Created
October 8, 2016 01:21
-
-
Save tmcw/21373409b3bd5fd1811d5a54e3273880 to your computer and use it in GitHub Desktop.
This file contains 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
const choo = require('choo') | |
const html = require('choo/html') | |
module.exports = function(content, desire, prefill) { | |
const app = choo() | |
app.model({ | |
state: { | |
content: content, | |
regex: ``, | |
desire: desire, | |
valid: true | |
}, | |
subscriptions: [ | |
(send, done) => { | |
setTimeout(() => { | |
send('update', prefill, () => { | |
done(); | |
}); | |
}, 10); | |
} | |
], | |
reducers: { | |
update: (data, state) => ({ | |
regex: data, | |
valid: !!(() => { | |
try { | |
new RegExp(data); | |
return true; | |
} catch (e) { } | |
})(), | |
success: (() => { | |
try { | |
return JSON.stringify(state.content.match(new RegExp(data)).slice(1)) === | |
JSON.stringify(desire); | |
} catch (e) { | |
return false; | |
} | |
})(), | |
match: (() => { | |
try { | |
return state.content.match(new RegExp(data)); | |
} catch (e) { | |
return [] | |
} | |
})() | |
}) | |
} | |
}) | |
const mainView = (state, prev, send) => html` | |
<div> | |
<div style='font-weight:bold;text-decoration:underline;'>content</div> | |
<div style='padding:5px;border:1px solid #000'>${state.content}</div> | |
<div style='font-weight:bold;text-decoration:underline;'>regular expression ${!state.valid ? html`<span style='color:red'>invalid!</span>` : null}</div> | |
<input | |
style='width:100%;box-sizing:border-box;border:1px solid blue;padding:5px;' | |
type='text' | |
value=${state.regex} | |
oninput=${(e) => send('update', e.target.value)} /> | |
<div style='font-weight:bold;text-decoration:underline;'>result</div> | |
<div style='border:1px solid #000; padding: 5px; ${state.success ? ' background: #f2fce0' : ''}'> | |
${state.match ? | |
html` | |
<div> | |
<div style='text-decoration:underline;font-weight:bold;'>all matched text</div> | |
<div>${state.match[0]}</div> | |
<div style='text-decoration:underline;font-weight:bold;'>captured groups</div> | |
<div> | |
${state.match.slice(1).map((group, i) => { | |
return html`<div>#${i}: ${group}</div>` | |
})} | |
</div> | |
</div> | |
` : html`<div style='font-style:italic;'>no match</div>`} | |
</div> | |
</div> | |
` | |
app.router((route) => [ | |
route('/', mainView) | |
]) | |
return app.start(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment