-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
67 lines (54 loc) · 1.66 KB
/
Copy pathmain.ts
File metadata and controls
67 lines (54 loc) · 1.66 KB
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
57
58
59
60
61
62
63
64
65
66
67
import { batch, createStore, computed, effect, persist, withHistory } from './src';
// 1. Create a Store
const myStore = createStore('appStore', {
count: 0
});
// 2. Apply Plugins
// Persist state to localStorage
persist(myStore);
// Add Undo/Redo history
const history = withHistory(myStore);
// 3. Create a derived computed value
const doubleCount = computed(() => myStore.state.count.value * 2);
// 4. DOM Elements
const elCount = document.getElementById('count')!;
const elDouble = document.getElementById('double-count')!;
const btnInc = document.getElementById('btn-inc')!;
const btnDec = document.getElementById('btn-dec')!;
const btnBatch = document.getElementById('btn-batch')!;
const btnUndo = document.getElementById('btn-undo')! as HTMLButtonElement;
const btnRedo = document.getElementById('btn-redo')! as HTMLButtonElement;
// 5. Effects (Reactivity)
effect(() => {
elCount.textContent = String(myStore.state.count.value);
});
effect(() => {
elDouble.textContent = String(doubleCount.value);
});
// History effect to update buttons
effect(() => {
// Read state to trigger effect on changes
myStore.state.count.value;
btnUndo.disabled = !history.canUndo;
btnRedo.disabled = !history.canRedo;
});
// 6. Events
btnInc.addEventListener('click', () => {
myStore.state.count.value++;
});
btnDec.addEventListener('click', () => {
myStore.state.count.value--;
});
btnBatch.addEventListener('click', () => {
batch(() => {
myStore.state.count.value++;
myStore.state.count.value++;
myStore.state.count.value++;
});
});
btnUndo.addEventListener('click', () => {
history.undo();
});
btnRedo.addEventListener('click', () => {
history.redo();
});