├── .gitignore ├── .npmrc ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── component.js ├── example ├── .npmrc ├── component.js ├── index.js ├── package.json ├── store.js ├── test.js └── view.js ├── h.js ├── html.js ├── index.js ├── package.json └── test.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | coverage/ 3 | dist/ 4 | tmp/ 5 | .sauce-credentials.json 6 | sauce_connect.log 7 | npm-debug.log* 8 | coverage.json 9 | .DS_Store 10 | *.swp 11 | .zuulrc 12 | generate 13 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | node_js: 2 | - '6' 3 | - '7' 4 | - '8' 5 | sudo: false 6 | language: node_js 7 | env: 8 | - CXX=g++-4.8 9 | addons: 10 | apt: 11 | sources: 12 | - ubuntu-toolchain-r-test 13 | packages: 14 | - g++-4.8 15 | script: npm run test 16 | # after_script: npm i -g codecov.io && cat ./coverage/lcov.info | codecov 17 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## `3.0.0` 2 | - parity with choo 6.6.0 3 | - lib namespace kept as `choo` for compatability with `choo-devtools` 4 | 5 | ## `2.0.0` 6 | ### breaking changes 7 | - adopted the choo v5 API ✨ 8 | - exposes `html`, `h`, and `component` aliases 9 | 10 | --- 11 | 12 | ## `1.1.0` 13 | - old skool rooch 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017 Yoshua Wuyts 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

choop

2 | 3 |
4 | 🚂🚋🚋🚋🚋🚋 + ⚛ 5 |
6 |
7 | Full on choo architecture on top of the tiny preact engine. 8 |
9 |
10 | Currently up-to-date with choo 6.13.1 11 |
12 | 13 |
14 | 15 |
16 | 17 | 18 | API stability 20 | 21 | 22 | 23 | NPM version 25 | 26 | 27 | 31 | 32 | 33 | Standard 35 | 36 |
37 | 38 |
39 | 40 | Ever wondered what would happen if [`preact`](https://github.com/developit/preact) and [`choo`](https://github.com/yoshuawuyts/choo) got a baby? 41 | 42 | Welp, wonder no longer - here's the answer. Full on `choo` architecture plus a couple `preact` goodies like [`h()`](https://preactjs.com/guide/differences-to-react#what-s-included-) and [components](https://preactjs.com/guide/lifecycle-methods). No JSX, only template strings via [hyperx](https://github.com/substack/hyperx). But you can use JSX if you want to. We even get almost all of the React ecosystem through [preact-compat](https://github.com/developit/preact-compat) 🎉🎉🎉🎉 43 | 44 | ## Example 45 | 46 | ```js 47 | var html = require('choop/html') 48 | var devtools = require('choo-devtools') 49 | var choop = require('choop') 50 | 51 | var app = choop() 52 | app.use(devtools()) 53 | app.use(countStore) 54 | app.route('/', mainView) 55 | app.mount('body') 56 | 57 | function mainView (state, emit) { 58 | return html` 59 |
60 |

count is ${state.count}

61 | 62 |
63 | ` 64 | 65 | function onclick () { 66 | emit('increment', 1) 67 | } 68 | } 69 | 70 | function countStore (state, emitter) { 71 | state.count = 0 72 | emitter.on('increment', function (count) { 73 | state.count += count 74 | emitter.emit('render') 75 | }) 76 | } 77 | ``` 78 | 79 | See? Same same as `choo`! 80 | 81 | Only difference is `preact` will append our app to the element passed into `mount`. So instead of our main view returning `` we return `
` (or whatever we want the root to be). 82 | 83 | ## Components 84 | 85 | You can create stateful components right out of the box with `choop`: 86 | 87 | ```js 88 | var Component = require('choop/component') 89 | var html = require('choop/html') 90 | 91 | class ClickMe extends Component { 92 | constructor () { 93 | super() 94 | this.state = { n: 0 } 95 | this.handleClick = () => { 96 | this.setState({ n: this.state.n + 1 }) 97 | } 98 | } 99 | render (props, state) { 100 | return html` 101 |
102 |

clicked ${state.n} times

103 | 104 |
105 | ` 106 | } 107 | } 108 | ``` 109 | 110 | And then render them in your views using `h()`: 111 | 112 | ```js 113 | var html = require('choop/html') 114 | var h = require('choop/h') 115 | 116 | var ClickMe = require('./ClickMe') 117 | 118 | function view (state, emit) { 119 | return html` 120 | 121 | ${h(ClickMe)} 122 | 123 | ` 124 | } 125 | ``` 126 | 127 | Optionally pass data a.k.a. `props`: 128 | 129 | ```js 130 | h(MyComponent, { someData: 'beep' }) 131 | ``` 132 | 133 | You can use `props` or an additional constructor function to pass `emit` into your components. 134 | 135 | **`state.cache`** 136 | 137 | `choo` version `6.11.0` introduced a `state.cache` helper for managing `nanocomponent` instances. This is not included in `choop` since component instance management is taken care of by `preact`. 138 | 139 | ## More Examples 140 | 141 | - **Basic**: https://esnextb.in/?gist=f9f339a9d108f156aa885bca96723d36 142 | - **Using JSX**: https://esnextb.in/?gist=84fd53fc0ea53240da89bef9573c9644 143 | - **Rendering `choop` (`preact`) component**: https://esnextb.in/?gist=28005d951a7347fb652eab669c5ffa1e 144 | - **Rendering `Nanocomponent`**: https://esnextb.in/?gist=01daeea0b216632edf3f0e27b8f0b89a 145 | - **Rendering `React` component**: https://choop-react.glitch.me/ ([source](https://glitch.com/edit/#!/choop-react?path=public/client.js:1:0)) 146 | 147 | ## FAQ 148 | 149 | ### Should I use this? 150 | Sometimes you gotta use `react`, and the best thing to do in that case might be to jump on the `preact` train, grab a bag of architecture and go to town. This might not be for me, but perhaps it's useful for you. Here you go! 🎁 151 | 152 | ### What's the real difference here? 153 | [`nanomorph`](https://github.com/choojs/nanomorph) is replaced by [`preact`](https://github.com/developit/preact) 154 | 155 | ### How do I run react widgets in choop? 156 | Like [this](https://github.com/preact-compat/react): 157 | 158 | ``` 159 | npm i -S preact preact-compat 160 | npm i -S preact-compat/react preact-compat/react-dom 161 | ``` 162 | 163 | ### What's the size? 164 | 165 | Something like `8.7 kB` 166 | 167 | ### What about choo? 168 | Yeah, what about me? (_drumroll_) 169 | 170 | ## Installation 171 | ```sh 172 | $ npm install choop 173 | ``` 174 | -------------------------------------------------------------------------------- /component.js: -------------------------------------------------------------------------------- 1 | var Preact = require('preact') 2 | class Component extends Preact.Component {} 3 | module.exports = Component -------------------------------------------------------------------------------- /example/.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false -------------------------------------------------------------------------------- /example/component.js: -------------------------------------------------------------------------------- 1 | var choop = require('..') 2 | var html = require('../html') 3 | var h = require('../h') 4 | var Component = require('../component') 5 | 6 | class ClickMe extends Component { 7 | constructor (props) { 8 | super(props) 9 | this.state = { n: 0 } 10 | this.handleClick = () => { 11 | this.setState({ n: this.state.n + 1 }) 12 | } 13 | } 14 | render (props, state) { 15 | return html` 16 |
17 |

clicked ${state.n} times

18 | 19 |
20 | ` 21 | } 22 | } 23 | 24 | function view (state, emit) { 25 | return html` 26 |
27 | ${h(ClickMe)} 28 |
29 | ` 30 | } 31 | 32 | var app = choop() 33 | 34 | app.route('/', view) 35 | 36 | app.mount('body') 37 | -------------------------------------------------------------------------------- /example/index.js: -------------------------------------------------------------------------------- 1 | var css = require('sheetify') 2 | var choo = require('../') 3 | 4 | css('todomvc-common/base.css') 5 | css('todomvc-app-css/index.css') 6 | 7 | var app = choo() 8 | if (process.env.NODE_ENV !== 'production') { 9 | app.use(require('choo-devtools')()) 10 | } 11 | app.use(require('./store')) 12 | 13 | app.route('/', require('./view')) 14 | app.route('#active', require('./view')) 15 | app.route('#completed', require('./view')) 16 | app.route('*', require('./view')) 17 | 18 | if (module.parent) module.exports = app 19 | else app.mount('body') 20 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "choo-todomvc-example", 3 | "version": "1.0.0", 4 | "private": true, 5 | "scripts": { 6 | "start": "bankai start", 7 | "start-component": "bankai start component.js", 8 | "build": "bankai build", 9 | "inspect": "bankai inspect", 10 | "test": "standard && node test.js" 11 | }, 12 | "dependencies": { 13 | "choo-devtools": "2.0.0", 14 | "sheetify": "^6.0.1", 15 | "todomvc-app-css": "^2.0.6", 16 | "todomvc-common": "^1.0.3" 17 | }, 18 | "devDependencies": { 19 | "bankai": "^9.0.1", 20 | "standard": "^9.0.1" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /example/store.js: -------------------------------------------------------------------------------- 1 | module.exports = todoStore 2 | 3 | function todoStore (state, emitter) { 4 | if (!state.todos) { 5 | state.todos = {} 6 | 7 | state.todos.active = [] 8 | state.todos.done = [] 9 | state.todos.all = [] 10 | 11 | state.todos.idCounter = 0 12 | } 13 | 14 | // Always reset when application boots 15 | state.todos.input = '' 16 | 17 | // Register emitters after DOM is loaded to speed up DOM loading 18 | emitter.on('DOMContentLoaded', function () { 19 | // CRUD 20 | emitter.on('todos:create', create) 21 | emitter.on('todos:update', update) 22 | emitter.on('todos:delete', del) 23 | 24 | // Special 25 | emitter.on('todos:input', oninput) 26 | 27 | // Shorthand 28 | emitter.on('todos:edit', edit) 29 | emitter.on('todos:unedit', unedit) 30 | emitter.on('todos:toggle', toggle) 31 | emitter.on('todos:toggleAll', toggleAll) 32 | emitter.on('todos:deleteCompleted', deleteCompleted) 33 | }) 34 | 35 | function oninput (text) { 36 | state.todos.input = text 37 | } 38 | 39 | function create (name) { 40 | var item = { 41 | id: state.todos.idCounter, 42 | editing: false, 43 | done: false, 44 | name: name 45 | } 46 | 47 | state.todos.idCounter += 1 48 | state.todos.active.push(item) 49 | state.todos.all.push(item) 50 | emitter.emit('render') 51 | } 52 | 53 | function edit (id) { 54 | state.todos.all.forEach(function (todo) { 55 | if (todo.id === id) todo.editing = true 56 | }) 57 | emitter.emit('render') 58 | } 59 | 60 | function unedit (id) { 61 | state.todos.all.forEach(function (todo) { 62 | if (todo.id === id) todo.editing = false 63 | }) 64 | emitter.emit('render') 65 | } 66 | 67 | function update (newTodo) { 68 | var todo = state.todos.all.filter(function (todo) { 69 | return todo.id === newTodo.id 70 | })[0] 71 | 72 | if (newTodo.done && todo.done === false) { 73 | state.todos.active.splice(state.todos.active.indexOf(todo), 1) 74 | state.todos.done.push(todo) 75 | } else if (newTodo.done === false && todo.done) { 76 | state.todos.done.splice(state.todos.done.indexOf(todo), 1) 77 | state.todos.active.push(todo) 78 | } 79 | 80 | Object.assign(todo, newTodo) 81 | emitter.emit('render') 82 | } 83 | 84 | function del (id) { 85 | var i = null 86 | var todo = null 87 | state.todos.all.forEach(function (_todo, j) { 88 | if (_todo.id === id) { 89 | i = j 90 | todo = _todo 91 | } 92 | }) 93 | state.todos.all.splice(i, 1) 94 | 95 | if (todo.done) { 96 | var done = state.todos.done 97 | var doneIndex 98 | done.forEach(function (_todo, j) { 99 | if (_todo.id === id) { 100 | doneIndex = j 101 | } 102 | }) 103 | done.splice(doneIndex, 1) 104 | } else { 105 | var active = state.todos.active 106 | var activeIndex 107 | active.forEach(function (_todo, j) { 108 | if (_todo.id === id) { 109 | activeIndex = j 110 | } 111 | }) 112 | active.splice(activeIndex, 1) 113 | } 114 | emitter.emit('render') 115 | } 116 | 117 | function deleteCompleted (data) { 118 | var done = state.todos.done 119 | done.forEach(function (todo) { 120 | var index = state.todos.all.indexOf(todo) 121 | state.todos.all.splice(index, 1) 122 | }) 123 | state.todos.done = [] 124 | emitter.emit('render') 125 | } 126 | 127 | function toggle (id) { 128 | var todo = state.todos.all.filter(function (todo) { 129 | return todo.id === id 130 | })[0] 131 | var done = todo.done 132 | todo.done = !done 133 | var arr = done ? state.todos.done : state.todos.active 134 | var target = done ? state.todos.active : state.todos.done 135 | var index = arr.indexOf(todo) 136 | arr.splice(index, 1) 137 | target.push(todo) 138 | emitter.emit('render') 139 | } 140 | 141 | function toggleAll (data) { 142 | var todos = state.todos.all 143 | var allDone = state.todos.all.length && 144 | state.todos.done.length === state.todos.all.length 145 | 146 | todos.forEach(function (todo) { 147 | todo.done = !allDone 148 | }) 149 | 150 | if (allDone) { 151 | state.todos.done = [] 152 | state.todos.active = state.todos.all 153 | } else { 154 | state.todos.done = state.todos.all 155 | state.todos.active = [] 156 | } 157 | 158 | emitter.emit('render') 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /example/test.js: -------------------------------------------------------------------------------- 1 | var EventEmitter = require('events').EventEmitter 2 | var spok = require('spok') 3 | var tape = require('tape') 4 | 5 | var todoStore = require('./store') 6 | 7 | tape('should initialize empty state', function (t) { 8 | var emitter = new EventEmitter() 9 | var state = {} 10 | todoStore(state, emitter) 11 | spok(t, state, { 12 | todos: { 13 | idCounter: 0, 14 | active: spok.arrayElements(0), 15 | done: spok.arrayElements(0), 16 | all: spok.arrayElements(0) 17 | } 18 | }) 19 | t.end() 20 | }) 21 | 22 | tape('restore previous state', function (t) { 23 | var emitter = new EventEmitter() 24 | var state = { 25 | todos: { 26 | idCounter: 100, 27 | active: [], 28 | done: [], 29 | all: [] 30 | } 31 | } 32 | todoStore(state, emitter) 33 | spok(t, state, { 34 | todos: { 35 | idCounter: 100 36 | } 37 | }) 38 | t.end() 39 | }) 40 | 41 | tape('todos:create', function (t) { 42 | var emitter = new EventEmitter() 43 | var state = {} 44 | todoStore(state, emitter) 45 | emitter.emit('DOMContentLoaded') 46 | 47 | emitter.emit('todos:create', 'same as it ever was') 48 | spok(t, state.todos, { 49 | all: spok.arrayElements(1), 50 | active: spok.arrayElements(1), 51 | done: spok.arrayElements(0) 52 | }) 53 | spok(t, state.todos.all[0], { 54 | name: 'same as it ever was', 55 | editing: false, 56 | done: false, 57 | id: 0 58 | }) 59 | 60 | emitter.emit('todos:create', 'and another one down') 61 | spok(t, state.todos, { 62 | all: spok.arrayElements(2), 63 | active: spok.arrayElements(2), 64 | done: spok.arrayElements(0) 65 | }) 66 | spok(t, state.todos.all[1], { 67 | name: 'and another one down', 68 | editing: false, 69 | done: false, 70 | id: 1 71 | }) 72 | 73 | t.end() 74 | }) 75 | 76 | tape('todos:update', function (t) { 77 | var emitter = new EventEmitter() 78 | var state = {} 79 | todoStore(state, emitter) 80 | emitter.emit('DOMContentLoaded') 81 | 82 | emitter.emit('todos:create', 'same as it ever was') 83 | emitter.emit('todos:create', 'and another one down') 84 | 85 | emitter.emit('todos:update', { 86 | id: 0, 87 | editing: true, 88 | name: 'been here all along' 89 | }) 90 | spok(t, state.todos.all[0], { 91 | name: 'been here all along', 92 | editing: true, 93 | done: false, 94 | id: 0 95 | }) 96 | 97 | emitter.emit('todos:update', { 98 | done: true, 99 | id: 1 100 | }) 101 | spok(t, state.todos, { 102 | all: spok.arrayElements(2), 103 | active: spok.arrayElements(1), 104 | done: spok.arrayElements(1) 105 | }) 106 | 107 | emitter.emit('todos:update', { 108 | done: false, 109 | id: 1 110 | }) 111 | spok(t, state.todos, { 112 | all: spok.arrayElements(2), 113 | active: spok.arrayElements(2), 114 | done: spok.arrayElements(0) 115 | }) 116 | 117 | t.end() 118 | }) 119 | 120 | // tape('todos:delete') 121 | // tape('todos:edit') 122 | // tape('todos:unedit') 123 | // tape('todos:toggle') 124 | // tape('todos:toggleAll') 125 | // tape('todos:deleteCompleted') 126 | -------------------------------------------------------------------------------- /example/view.js: -------------------------------------------------------------------------------- 1 | var html = require('../html') // cannot require choo/html because it's a nested repo 2 | 3 | module.exports = mainView 4 | 5 | function mainView (state, emit) { 6 | emit('log:debug', 'Rendering main view') 7 | return html` 8 |
9 |
10 | ${Header(state, emit)} 11 | ${TodoList(state, emit)} 12 | ${Footer(state, emit)} 13 |
14 | 19 |
20 | ` 21 | } 22 | 23 | function Header (state, emit) { 24 | return html` 25 |
26 |

todos

27 | 32 |
33 | ` 34 | 35 | function createTodo (e) { 36 | var value = e.target.value 37 | if (!value) return 38 | if (e.keyCode === 13) { 39 | emit('todos:input', '') 40 | emit('todos:create', value) 41 | } else { 42 | emit('todos:input', value) 43 | } 44 | } 45 | } 46 | 47 | function Footer (state, emit) { 48 | var filter = state.href.replace(/^\//, '') || '' 49 | var activeCount = state.todos.active.length 50 | var hasDone = state.todos.done.length 51 | 52 | return html` 53 | 65 | ` 66 | 67 | function filterButton (name, filter, currentFilter, emit) { 68 | var filterClass = filter === currentFilter 69 | ? 'selected' 70 | : '' 71 | 72 | var uri = '#' + name.toLowerCase() 73 | if (uri === '#all') uri = '/' 74 | return html` 75 |
  • 76 | 77 | ${name} 78 | 79 |
  • 80 | ` 81 | } 82 | 83 | function deleteCompleted (emit) { 84 | return html` 85 | 88 | ` 89 | 90 | function deleteAllCompleted () { 91 | emit('todos:deleteCompleted') 92 | } 93 | } 94 | } 95 | 96 | function TodoItem (todo, emit) { 97 | var clx = classList({ completed: todo.done, editing: todo.editing }) 98 | return html` 99 |
  • 100 |
    101 | 106 | 107 | 111 |
    112 | 117 |
  • 118 | ` 119 | 120 | function toggle (e) { 121 | emit('todos:toggle', todo.id) 122 | } 123 | 124 | function edit (e) { 125 | emit('todos:edit', todo.id) 126 | } 127 | 128 | function destroy (e) { 129 | emit('todos:delete', todo.id) 130 | } 131 | 132 | function update (e) { 133 | emit('todos:update', { 134 | id: todo.id, 135 | editing: false, 136 | name: e.target.value 137 | }) 138 | } 139 | 140 | function handleEditKeydown (e) { 141 | if (e.keyCode === 13) update(e) // Enter 142 | else if (e.code === 27) emit('todos:unedit') // Escape 143 | } 144 | 145 | function classList (classes) { 146 | var str = '' 147 | var keys = Object.keys(classes) 148 | for (var i = 0, len = keys.length; i < len; i++) { 149 | var key = keys[i] 150 | var val = classes[key] 151 | if (val) str += (key + ' ') 152 | } 153 | return str 154 | } 155 | } 156 | 157 | function TodoList (state, emit) { 158 | var filter = state.href.replace(/^\//, '') || '' 159 | var items = filter === 'completed' 160 | ? state.todos.done 161 | : filter === 'active' 162 | ? state.todos.active 163 | : state.todos.all 164 | 165 | var allDone = state.todos.done.length === state.todos.all.length 166 | 167 | var nodes = items.map(function (todo) { 168 | return TodoItem(todo, emit) 169 | }) 170 | 171 | return html` 172 |
    173 | 178 | 181 | 184 |
    185 | ` 186 | 187 | function toggleAll () { 188 | emit('todos:toggleAll') 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /h.js: -------------------------------------------------------------------------------- 1 | module.exports = require('preact').h 2 | -------------------------------------------------------------------------------- /html.js: -------------------------------------------------------------------------------- 1 | var h = require('preact').h 2 | var hyperx = require('hyperx') 3 | module.exports = hyperx(h) 4 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | var scrollToAnchor = require('scroll-to-anchor') 2 | var documentReady = require('document-ready') 3 | var nanotiming = require('nanotiming') 4 | var nanorouter = require('nanorouter') 5 | var preact = require('preact') 6 | var rendertostring = require('preact-render-to-string').render 7 | var nanoquery = require('nanoquery') 8 | var nanohref = require('nanohref') 9 | var nanoraf = require('nanoraf') 10 | var nanobus = require('nanobus') 11 | var assert = require('assert') 12 | var xtend = require('xtend') 13 | 14 | module.exports = Choo 15 | 16 | var HISTORY_OBJECT = {} 17 | 18 | function Choo (opts) { 19 | if (!(this instanceof Choo)) return new Choo(opts) 20 | opts = opts || {} 21 | 22 | assert.equal(typeof opts, 'object', 'choo: opts should be type object') 23 | 24 | var self = this 25 | 26 | // define events used by choo 27 | this._events = { 28 | DOMCONTENTLOADED: 'DOMContentLoaded', 29 | DOMTITLECHANGE: 'DOMTitleChange', 30 | REPLACESTATE: 'replaceState', 31 | PUSHSTATE: 'pushState', 32 | NAVIGATE: 'navigate', 33 | POPSTATE: 'popState', 34 | RENDER: 'render' 35 | } 36 | 37 | // properties for internal use only 38 | this._historyEnabled = opts.history === undefined ? true : opts.history 39 | this._hrefEnabled = opts.href === undefined ? true : opts.href 40 | this._hashEnabled = opts.hash === undefined ? true : opts.hash 41 | this._hasWindow = typeof window !== 'undefined' 42 | this._loaded = false 43 | this._stores = [] 44 | this._tree = null 45 | this._treeref = null 46 | 47 | // state 48 | var _state = { 49 | events: this._events, 50 | components: {} 51 | } 52 | if (this._hasWindow) { 53 | this.state = window.initialState 54 | ? xtend(window.initialState, _state) 55 | : _state 56 | delete window.initialState 57 | } else { 58 | this.state = _state 59 | } 60 | 61 | // properties that are part of the API 62 | this.router = nanorouter({ curry: true }) 63 | this.emitter = nanobus('choo.emit') 64 | this.emit = this.emitter.emit.bind(this.emitter) 65 | 66 | // listen for title changes; available even when calling .toString() 67 | if (this._hasWindow) this.state.title = document.title 68 | this.emitter.prependListener(this._events.DOMTITLECHANGE, function (title) { 69 | assert.equal(typeof title, 'string', 'events.DOMTitleChange: title should be type string') 70 | self.state.title = title 71 | if (self._hasWindow) document.title = title 72 | }) 73 | } 74 | 75 | Choo.prototype.route = function (route, handler) { 76 | assert.equal(typeof route, 'string', 'choo.route: route should be type string') 77 | assert.equal(typeof handler, 'function', 'choo.handler: route should be type function') 78 | this.router.on(route, handler) 79 | } 80 | 81 | Choo.prototype.use = function (cb) { 82 | assert.equal(typeof cb, 'function', 'choo.use: cb should be type function') 83 | var self = this 84 | this._stores.push(function (state) { 85 | var msg = 'choo.use' 86 | msg = cb.storeName ? msg + '(' + cb.storeName + ')' : msg 87 | var endTiming = nanotiming(msg) 88 | cb(state, self.emitter, self) 89 | endTiming() 90 | }) 91 | } 92 | 93 | Choo.prototype.start = function () { 94 | assert.equal(typeof window, 'object', 'choo.start: window was not found. .start() must be called in a browser, use .toString() if running in Node') 95 | 96 | var self = this 97 | if (this._historyEnabled) { 98 | this.emitter.prependListener(this._events.NAVIGATE, function () { 99 | self._matchRoute() 100 | if (self._loaded) { 101 | self.emitter.emit(self._events.RENDER) 102 | setTimeout(scrollToAnchor.bind(null, window.location.hash), 0) 103 | } 104 | }) 105 | 106 | this.emitter.prependListener(this._events.POPSTATE, function () { 107 | self.emitter.emit(self._events.NAVIGATE) 108 | }) 109 | 110 | this.emitter.prependListener(this._events.PUSHSTATE, function (href) { 111 | assert.equal(typeof href, 'string', 'events.pushState: href should be type string') 112 | window.history.pushState(HISTORY_OBJECT, null, href) 113 | self.emitter.emit(self._events.NAVIGATE) 114 | }) 115 | 116 | this.emitter.prependListener(this._events.REPLACESTATE, function (href) { 117 | assert.equal(typeof href, 'string', 'events.replaceState: href should be type string') 118 | window.history.replaceState(HISTORY_OBJECT, null, href) 119 | self.emitter.emit(self._events.NAVIGATE) 120 | }) 121 | 122 | window.onpopstate = function () { 123 | self.emitter.emit(self._events.POPSTATE) 124 | } 125 | 126 | if (self._hrefEnabled) { 127 | nanohref(function (location) { 128 | var href = location.href 129 | var hash = location.hash 130 | if (href === window.location.href) { 131 | if (!self._hashEnabled && hash) scrollToAnchor(hash) 132 | return 133 | } 134 | self.emitter.emit(self._events.PUSHSTATE, href) 135 | }) 136 | } 137 | } 138 | 139 | this._stores.forEach(function (initStore) { 140 | initStore(self.state) 141 | }) 142 | 143 | this._matchRoute() 144 | this._tree = this._prerender(this.state) 145 | assert.ok(this._tree, 'choo.start: no valid DOM node returned for location ' + this.state.href) 146 | 147 | this.emitter.prependListener(self._events.RENDER, nanoraf(function () { 148 | var renderTiming = nanotiming('choo.render') 149 | var newTree = self._prerender(self.state) 150 | assert.ok(newTree, 'choo.render: no valid DOM node returned for location ' + self.state.href) 151 | 152 | var morphTiming = nanotiming('choo.morph') 153 | self._treeref = preact.render(newTree, self._tree, self._treeref) 154 | morphTiming() 155 | 156 | renderTiming() 157 | })) 158 | 159 | documentReady(function () { 160 | self.emitter.emit(self._events.DOMCONTENTLOADED) 161 | self._loaded = true 162 | }) 163 | 164 | return this._tree 165 | } 166 | 167 | Choo.prototype.mount = function mount (selector) { 168 | if (typeof window !== 'object') { 169 | assert.ok(typeof selector === 'string', 'choo.mount: selector should be type String') 170 | this.selector = selector 171 | return this 172 | } 173 | 174 | assert.ok(typeof selector === 'string' || typeof selector === 'object', 'choo.mount: selector should be type String or HTMLElement') 175 | 176 | var self = this 177 | 178 | documentReady(function () { 179 | var renderTiming = nanotiming('choo.render') 180 | var newTree = self.start() 181 | if (typeof selector === 'string') { 182 | self._tree = document.querySelector(selector) 183 | } else { 184 | self._tree = selector 185 | } 186 | 187 | assert.ok(self._tree, 'choo.mount: could not query selector: ' + selector) 188 | 189 | var morphTiming = nanotiming('choo.morph') 190 | self._treeref = preact.render(newTree, self._tree, self._tree.lastChild) 191 | morphTiming() 192 | 193 | renderTiming() 194 | }) 195 | } 196 | 197 | Choo.prototype.toString = function (location, state) { 198 | this.state = xtend(this.state, state || {}) 199 | 200 | assert.notEqual(typeof window, 'object', 'choo.mount: window was found. .toString() must be called in Node, use .start() or .mount() if running in the browser') 201 | assert.equal(typeof location, 'string', 'choo.toString: location should be type string') 202 | assert.equal(typeof this.state, 'object', 'choo.toString: state should be type object') 203 | 204 | var self = this 205 | this._stores.forEach(function (initStore) { 206 | initStore(self.state) 207 | }) 208 | 209 | this._matchRoute(location) 210 | var html = this._prerender(this.state) 211 | assert.ok(html, 'choo.toString: no valid value returned for the route ' + location) 212 | assert(!Array.isArray(html), 'choo.toString: return value was an array for the route ' + location) 213 | return typeof html.outerHTML === 'string' ? html.outerHTML : rendertostring(html) 214 | } 215 | 216 | Choo.prototype._matchRoute = function (locationOverride) { 217 | var location, queryString 218 | if (locationOverride) { 219 | location = locationOverride.replace(/\?.+$/, '').replace(/\/$/, '') 220 | if (!this._hashEnabled) location = location.replace(/#.+$/, '') 221 | queryString = locationOverride 222 | } else { 223 | location = window.location.pathname.replace(/\/$/, '') 224 | if (this._hashEnabled) location += window.location.hash.replace(/^#/, '/') 225 | queryString = window.location.search 226 | } 227 | var matched = this.router.match(location) 228 | this._handler = matched.cb 229 | this.state.href = location 230 | this.state.query = nanoquery(queryString) 231 | this.state.route = matched.route 232 | this.state.params = matched.params 233 | return this.state 234 | } 235 | 236 | Choo.prototype._prerender = function (state) { 237 | var routeTiming = nanotiming("choo.prerender('" + state.route + "')") 238 | var res = this._handler(state, this.emit) 239 | routeTiming() 240 | return res 241 | } 242 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "choop", 3 | "version": "3.2.1", 4 | "description": "Choo x Preact", 5 | "main": "index.js", 6 | "scripts": { 7 | "build": "mkdir -p dist/ && browserify index -p bundle-collapser/plugin > dist/bundle.js && browserify index -g unassertify -g uglifyify -p bundle-collapser/plugin | uglifyjs > dist/bundle.min.js && zopfli -i 100 dist/bundle.min.js && wc -c < dist/bundle.min.js.gz | pretty-bytes", 8 | "deps": "dependency-check --entry ./html.js . && dependency-check . --extra --no-dev --entry ./html.js", 9 | "inspect": "browserify --full-paths index -g unassertify -g uglifyify | discify --open", 10 | "prepublish": "npm run build", 11 | "start": "bankai start example", 12 | "test": "standard && npm run deps && node test.js" 13 | }, 14 | "repository": "choojs/choop", 15 | "keywords": [ 16 | "choo", 17 | "preact", 18 | "client", 19 | "frontend", 20 | "framework", 21 | "minimal", 22 | "composable", 23 | "tiny", 24 | "power", 25 | "modules", 26 | "lolreact", 27 | "lolol", 28 | "react", 29 | "no seriously", 30 | "lol" 31 | ], 32 | "license": "MIT", 33 | "dependencies": { 34 | "document-ready": "^2.0.1", 35 | "hyperx": "^2.4.0", 36 | "nanobus": "^4.3.5", 37 | "nanohref": "^3.1.0", 38 | "nanoquery": "^1.2.0", 39 | "nanoraf": "^3.1.0", 40 | "nanorouter": "^3.1.1", 41 | "nanotiming": "^7.3.1", 42 | "preact": "^8.3.1", 43 | "preact-render-to-string": "^4.1.0", 44 | "scroll-to-anchor": "^1.1.0", 45 | "xtend": "^4.0.1" 46 | }, 47 | "devDependencies": { 48 | "browserify": "^16.2.3", 49 | "bundle-collapser": "^1.3.0", 50 | "dependency-check": "^3.2.1", 51 | "discify": "^1.6.3", 52 | "node-zopfli": "^2.0.2", 53 | "pretty-bytes-cli": "^2.0.0", 54 | "spok": "^0.9.1", 55 | "standard": "^12.0.1", 56 | "tape": "^4.9.1", 57 | "uglifyify": "^5.0.1", 58 | "uglifyjs": "^2.4.11", 59 | "unassertify": "^2.1.1" 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | // var tape = require('tape') 2 | --------------------------------------------------------------------------------