-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
56 lines (49 loc) · 1.41 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { createStore, emptyNode, createElement as h } from "./core.js";
/** @typedef {{ count: number }} AppState */
/** @typedef {{ type: "INCREMENT" } | { type: "DECREMENT" }} AppAction */
/** @typedef {import("./core.js").Dispatch<AppState, AppAction>} AppDispatch */
/** @typedef {import("./core.js").GetState<AppState>} AppGetState */
/**
* @param {AppState} state
* @param {AppAction} action
* @returns {AppState}
*/
function update(state, action) {
switch (action.type) {
case "INCREMENT":
return { count: state.count + 1 };
case "DECREMENT":
return { count: state.count - 1 };
default:
return state;
}
}
const store = createStore({ count: 0 }, update);
/**
* @param {AppState} state
* @param {AppDispatch} dispatch
* @returns {HTMLElement}
*/
function view({ count }, dispatch) {
return h("div", {}, [
h("h1", {}, [count]),
h("button", { onclick: () => dispatch({ type: "DECREMENT" }) }, [
"Decrement",
]),
h("button", { onclick: () => dispatch({ type: "INCREMENT" }) }, [
"Increment",
]),
]);
}
const $root = /** @type {HTMLDivElement} */ (document.getElementById("root"));
/**
* @param {AppDispatch} dispatch
* @param {AppGetState} getState
*/
function render(dispatch, getState) {
emptyNode($root);
const $view = view(getState(), dispatch);
$root.appendChild($view);
}
store.subscribe(render);
render(store.dispatch, store.getState);