@uistate/core 5.2.0 → 5.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/index.js +2 -9
  2. package/package.json +4 -10
  3. package/queryClient.js +55 -0
  4. package/cssState.js +0 -212
  5. package/examples/001-counter/README.md +0 -44
  6. package/examples/001-counter/index.html +0 -33
  7. package/examples/002-counter-improved/README.md +0 -44
  8. package/examples/002-counter-improved/index.html +0 -47
  9. package/examples/003-input-reactive/README.md +0 -44
  10. package/examples/003-input-reactive/index.html +0 -33
  11. package/examples/004-computed-state/README.md +0 -45
  12. package/examples/004-computed-state/index.html +0 -65
  13. package/examples/005-conditional-rendering/README.md +0 -42
  14. package/examples/005-conditional-rendering/index.html +0 -39
  15. package/examples/006-list-rendering/README.md +0 -49
  16. package/examples/006-list-rendering/index.html +0 -63
  17. package/examples/007-form-validation/README.md +0 -52
  18. package/examples/007-form-validation/index.html +0 -102
  19. package/examples/008-undo-redo/README.md +0 -70
  20. package/examples/008-undo-redo/index.html +0 -108
  21. package/examples/009-localStorage-side-effects/README.md +0 -72
  22. package/examples/009-localStorage-side-effects/index.html +0 -57
  23. package/examples/010-decoupled-components/README.md +0 -74
  24. package/examples/010-decoupled-components/index.html +0 -93
  25. package/examples/011-async-patterns/README.md +0 -98
  26. package/examples/011-async-patterns/index.html +0 -132
  27. package/examples/028-counter-improved-eventTest/LICENSE +0 -55
  28. package/examples/028-counter-improved-eventTest/README.md +0 -131
  29. package/examples/028-counter-improved-eventTest/app/store.js +0 -9
  30. package/examples/028-counter-improved-eventTest/index.html +0 -49
  31. package/examples/028-counter-improved-eventTest/runtime/core/behaviors.runtime.js +0 -282
  32. package/examples/028-counter-improved-eventTest/runtime/core/eventState.js +0 -100
  33. package/examples/028-counter-improved-eventTest/runtime/core/eventStateNew.js +0 -149
  34. package/examples/028-counter-improved-eventTest/runtime/core/helpers.js +0 -212
  35. package/examples/028-counter-improved-eventTest/runtime/core/router.js +0 -271
  36. package/examples/028-counter-improved-eventTest/store.d.ts +0 -8
  37. package/examples/028-counter-improved-eventTest/style.css +0 -170
  38. package/examples/028-counter-improved-eventTest/tests/README.md +0 -208
  39. package/examples/028-counter-improved-eventTest/tests/counter.test.js +0 -116
  40. package/examples/028-counter-improved-eventTest/tests/eventTest.js +0 -176
  41. package/examples/028-counter-improved-eventTest/tests/generateTypes.js +0 -168
  42. package/examples/028-counter-improved-eventTest/tests/run.js +0 -20
  43. package/examples/030-todo-app-with-eventTest/LICENSE +0 -55
  44. package/examples/030-todo-app-with-eventTest/README.md +0 -121
  45. package/examples/030-todo-app-with-eventTest/app/router.js +0 -25
  46. package/examples/030-todo-app-with-eventTest/app/store.js +0 -16
  47. package/examples/030-todo-app-with-eventTest/app/views/home.js +0 -11
  48. package/examples/030-todo-app-with-eventTest/app/views/todoDemo.js +0 -88
  49. package/examples/030-todo-app-with-eventTest/index.html +0 -65
  50. package/examples/030-todo-app-with-eventTest/runtime/core/behaviors.runtime.js +0 -282
  51. package/examples/030-todo-app-with-eventTest/runtime/core/eventState.js +0 -100
  52. package/examples/030-todo-app-with-eventTest/runtime/core/eventStateNew.js +0 -149
  53. package/examples/030-todo-app-with-eventTest/runtime/core/helpers.js +0 -212
  54. package/examples/030-todo-app-with-eventTest/runtime/core/router.js +0 -271
  55. package/examples/030-todo-app-with-eventTest/store.d.ts +0 -18
  56. package/examples/030-todo-app-with-eventTest/style.css +0 -170
  57. package/examples/030-todo-app-with-eventTest/tests/README.md +0 -208
  58. package/examples/030-todo-app-with-eventTest/tests/eventTest.js +0 -176
  59. package/examples/030-todo-app-with-eventTest/tests/generateTypes.js +0 -189
  60. package/examples/030-todo-app-with-eventTest/tests/run.js +0 -20
  61. package/examples/030-todo-app-with-eventTest/tests/todos.test.js +0 -167
  62. package/examples/031-todo-app-with-eventTest/LICENSE +0 -55
  63. package/examples/031-todo-app-with-eventTest/README.md +0 -54
  64. package/examples/031-todo-app-with-eventTest/TUTORIAL.md +0 -390
  65. package/examples/031-todo-app-with-eventTest/WHY_EVENTSTATE.md +0 -777
  66. package/examples/031-todo-app-with-eventTest/app/bridges.js +0 -113
  67. package/examples/031-todo-app-with-eventTest/app/router.js +0 -26
  68. package/examples/031-todo-app-with-eventTest/app/store.js +0 -15
  69. package/examples/031-todo-app-with-eventTest/app/views/home.js +0 -46
  70. package/examples/031-todo-app-with-eventTest/app/views/todoDemo.js +0 -69
  71. package/examples/031-todo-app-with-eventTest/devtools/dock.js +0 -41
  72. package/examples/031-todo-app-with-eventTest/devtools/stateTracker.dock.js +0 -10
  73. package/examples/031-todo-app-with-eventTest/devtools/stateTracker.js +0 -246
  74. package/examples/031-todo-app-with-eventTest/devtools/telemetry.js +0 -104
  75. package/examples/031-todo-app-with-eventTest/devtools/typeGenerator.js +0 -339
  76. package/examples/031-todo-app-with-eventTest/index.html +0 -103
  77. package/examples/031-todo-app-with-eventTest/package-lock.json +0 -2184
  78. package/examples/031-todo-app-with-eventTest/package.json +0 -24
  79. package/examples/031-todo-app-with-eventTest/runtime/core/behaviors.runtime.js +0 -282
  80. package/examples/031-todo-app-with-eventTest/runtime/core/eventState.js +0 -100
  81. package/examples/031-todo-app-with-eventTest/runtime/core/eventStateNew.js +0 -149
  82. package/examples/031-todo-app-with-eventTest/runtime/core/helpers.js +0 -212
  83. package/examples/031-todo-app-with-eventTest/runtime/core/router.js +0 -271
  84. package/examples/031-todo-app-with-eventTest/runtime/extensions/boundary.js +0 -36
  85. package/examples/031-todo-app-with-eventTest/runtime/extensions/converge.js +0 -63
  86. package/examples/031-todo-app-with-eventTest/runtime/extensions/eventState.plus.js +0 -210
  87. package/examples/031-todo-app-with-eventTest/runtime/extensions/hydrate.js +0 -157
  88. package/examples/031-todo-app-with-eventTest/runtime/extensions/queryBinding.js +0 -69
  89. package/examples/031-todo-app-with-eventTest/runtime/forms/computed.js +0 -78
  90. package/examples/031-todo-app-with-eventTest/runtime/forms/meta.js +0 -51
  91. package/examples/031-todo-app-with-eventTest/runtime/forms/submitWithBoundary.js +0 -28
  92. package/examples/031-todo-app-with-eventTest/runtime/forms/validators.js +0 -55
  93. package/examples/031-todo-app-with-eventTest/store.d.ts +0 -23
  94. package/examples/031-todo-app-with-eventTest/style.css +0 -170
  95. package/examples/031-todo-app-with-eventTest/tests/README.md +0 -208
  96. package/examples/031-todo-app-with-eventTest/tests/eventTest.js +0 -176
  97. package/examples/031-todo-app-with-eventTest/tests/generateTypes.js +0 -191
  98. package/examples/031-todo-app-with-eventTest/tests/run.js +0 -20
  99. package/examples/031-todo-app-with-eventTest/tests/todos.test.js +0 -192
  100. package/examples/032-todo-app-with-eventTest/LICENSE +0 -55
  101. package/examples/032-todo-app-with-eventTest/README.md +0 -54
  102. package/examples/032-todo-app-with-eventTest/TUTORIAL.md +0 -390
  103. package/examples/032-todo-app-with-eventTest/WHY_EVENTSTATE.md +0 -777
  104. package/examples/032-todo-app-with-eventTest/app/actions/index.js +0 -153
  105. package/examples/032-todo-app-with-eventTest/app/bridges.js +0 -113
  106. package/examples/032-todo-app-with-eventTest/app/router.js +0 -26
  107. package/examples/032-todo-app-with-eventTest/app/store.js +0 -15
  108. package/examples/032-todo-app-with-eventTest/app/views/home.js +0 -46
  109. package/examples/032-todo-app-with-eventTest/app/views/todoDemo.js +0 -69
  110. package/examples/032-todo-app-with-eventTest/devtools/dock.js +0 -41
  111. package/examples/032-todo-app-with-eventTest/devtools/stateTracker.dock.js +0 -10
  112. package/examples/032-todo-app-with-eventTest/devtools/stateTracker.js +0 -246
  113. package/examples/032-todo-app-with-eventTest/devtools/telemetry.js +0 -104
  114. package/examples/032-todo-app-with-eventTest/devtools/typeGenerator.js +0 -339
  115. package/examples/032-todo-app-with-eventTest/index.html +0 -87
  116. package/examples/032-todo-app-with-eventTest/package-lock.json +0 -2184
  117. package/examples/032-todo-app-with-eventTest/package.json +0 -24
  118. package/examples/032-todo-app-with-eventTest/runtime/core/behaviors.runtime.js +0 -282
  119. package/examples/032-todo-app-with-eventTest/runtime/core/eventState.js +0 -100
  120. package/examples/032-todo-app-with-eventTest/runtime/core/eventStateNew.js +0 -149
  121. package/examples/032-todo-app-with-eventTest/runtime/core/helpers.js +0 -212
  122. package/examples/032-todo-app-with-eventTest/runtime/core/router.js +0 -271
  123. package/examples/032-todo-app-with-eventTest/runtime/extensions/boundary.js +0 -36
  124. package/examples/032-todo-app-with-eventTest/runtime/extensions/converge.js +0 -63
  125. package/examples/032-todo-app-with-eventTest/runtime/extensions/eventState.plus.js +0 -210
  126. package/examples/032-todo-app-with-eventTest/runtime/extensions/hydrate.js +0 -157
  127. package/examples/032-todo-app-with-eventTest/runtime/extensions/queryBinding.js +0 -69
  128. package/examples/032-todo-app-with-eventTest/runtime/forms/computed.js +0 -78
  129. package/examples/032-todo-app-with-eventTest/runtime/forms/meta.js +0 -51
  130. package/examples/032-todo-app-with-eventTest/runtime/forms/submitWithBoundary.js +0 -28
  131. package/examples/032-todo-app-with-eventTest/runtime/forms/validators.js +0 -55
  132. package/examples/032-todo-app-with-eventTest/store.d.ts +0 -23
  133. package/examples/032-todo-app-with-eventTest/style.css +0 -170
  134. package/examples/032-todo-app-with-eventTest/tests/README.md +0 -208
  135. package/examples/032-todo-app-with-eventTest/tests/eventTest.js +0 -176
  136. package/examples/032-todo-app-with-eventTest/tests/generateTypes.js +0 -191
  137. package/examples/032-todo-app-with-eventTest/tests/run.js +0 -20
  138. package/examples/032-todo-app-with-eventTest/tests/todos.test.js +0 -192
  139. package/playground/exercise001.html +0 -38
  140. package/playground/exercise002.html +0 -49
  141. package/stateSerializer.js +0 -267
  142. package/templateManager.js +0 -216
@@ -1,55 +0,0 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
-
11
- "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
-
13
- "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
-
15
- "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
-
17
- "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
-
19
- "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
-
21
- "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work.
22
-
23
- "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
-
25
- "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
-
27
- "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
-
29
- 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
-
31
- 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
-
33
- 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
-
35
- (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
-
37
- (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
-
39
- (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
-
41
- (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
-
43
- You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
-
45
- 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
-
47
- 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
-
49
- 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
-
51
- 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
-
53
- 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
-
55
- END OF TERMS AND CONDITIONS
@@ -1,121 +0,0 @@
1
- # 030 Todo App with eventTest
2
-
3
- A complete todo app demonstrating the UIstate framework features, bridging from the simple examples (001-011) to a real application.
4
-
5
- ## What This Example Shows
6
-
7
- This is the **bridge** between learning the primitive (`eventState.js`) and using the full framework:
8
-
9
- ✅ **Same primitive from 001-011** - `runtime/core/eventState.js` (~80 lines)
10
- ✅ **Declarative templates** - `data-bind` and `data-on` attributes
11
- ✅ **Client-side routing** - Multi-page SPA with loading states
12
- ✅ **Event-sequence testing** - `eventTest.js` for testing state changes
13
- ✅ **Direct state manipulation** - No action registry, just `store.set()`
14
-
15
- ## Structure
16
-
17
- ```
18
- app/
19
- ├── store.js → Store initialization
20
- ├── router.js → Route configuration
21
- └── views/
22
- ├── home.js → Simple counter view
23
- └── todoDemo.js → Todo app with add/toggle/filter
24
-
25
- runtime/core/
26
- ├── eventState.js → The 80-line reactive primitive
27
- ├── behaviors.runtime.js → Declarative bindings (data-bind, data-on)
28
- └── router.js → Simple client-side router
29
-
30
- tests/
31
- ├── eventTest.js → Event-sequence testing framework
32
- ├── todos.test.js → Tests for todo app
33
- └── run.js → Test runner
34
- ```
35
-
36
- ## Key Features
37
-
38
- ### 1. Direct State Manipulation
39
-
40
- Views use `store.set()` directly - no action registry:
41
-
42
- ```javascript
43
- // Add todo
44
- const items = store.get('todos.items') || [];
45
- const newTodo = { id: Date.now(), text, done: false };
46
- store.set('todos.items', [...items, newTodo]);
47
-
48
- // Toggle todo
49
- const updated = items.map(item =>
50
- item.id === t.id ? { ...item, done: !item.done } : item
51
- );
52
- store.set('todos.items', updated);
53
- ```
54
-
55
- ### 2. Declarative Bindings
56
-
57
- HTML attributes for reactive UI:
58
-
59
- ```html
60
- <!-- Bind theme to body attribute -->
61
- <body data-bind="data-theme: ui.theme">
62
-
63
- <!-- Button with action pipeline -->
64
- <button data-on="click: toggleTheme() | log('theme changed')">
65
- Toggle Theme
66
- </button>
67
- ```
68
-
69
- ### 3. Event-Sequence Testing
70
-
71
- Test state changes as event sequences:
72
-
73
- ```javascript
74
- import { eventTest } from './eventTest.js';
75
-
76
- eventTest('add todo', ({ store, trigger, assertPath }) => {
77
- trigger(() => {
78
- const items = store.get('todos.items') || [];
79
- store.set('todos.items', [...items, { id: 1, text: 'Test', done: false }]);
80
- });
81
-
82
- assertPath('todos.items', (items) => items.length === 1);
83
- });
84
- ```
85
-
86
- ## Run It
87
-
88
- ```bash
89
- # Install dependencies
90
- npm install
91
-
92
- # Open in browser
93
- open index.html
94
-
95
- # Run tests
96
- npm test
97
- ```
98
-
99
- ## Progression from 001-011
100
-
101
- **Examples 001-011:** Learn `eventState.js` primitive
102
- **Example 030:** See the framework features (routing, templates, testing)
103
- **Next steps:** Advanced features (devtools, forms, extensions)
104
-
105
- ## What Makes This Different
106
-
107
- **Other frameworks:**
108
- - Testing is separate (React Testing Library, Vue Test Utils)
109
- - State management is opaque (virtual DOM, reactivity magic)
110
- - Need build tools (JSX, SFC compilers)
111
-
112
- **UIstate (030):**
113
- - Testing is **architectural** (event-sequence assertions)
114
- - State management is **transparent** (events all the way down)
115
- - No build step (runs directly in browser)
116
-
117
- ## Learn More
118
-
119
- - See `tests/todos.test.js` for testing examples
120
- - See `runtime/core/behaviors.runtime.js` for how `data-bind` works
121
- - See `runtime/core/eventState.js` for the core primitive
@@ -1,25 +0,0 @@
1
- // Simple router setup for the todo app example
2
- import store from './store.js';
3
- import { createRouter } from '../runtime/core/router.js';
4
- import * as home from './views/home.js';
5
- import * as todoDemo from './views/todoDemo.js';
6
-
7
- const routes = [
8
- { path: '/', view: 'home', component: home },
9
- { path: '/todo-demo', view: 'todoDemo', component: todoDemo },
10
- ];
11
-
12
- // Initialize router with correct config object
13
- const router = createRouter({
14
- routes,
15
- store,
16
- rootSelector: '[data-route-root]',
17
- debug: true
18
- });
19
-
20
- // Start the router after DOM is ready
21
- if (document.readyState === 'loading') {
22
- document.addEventListener('DOMContentLoaded', () => router.start());
23
- } else {
24
- router.start();
25
- }
@@ -1,16 +0,0 @@
1
- // store.js — singleton eventState store for the SPA
2
- import { createEventState } from '../runtime/core/eventStateNew.js';
3
-
4
- const initial = {
5
- ui: {
6
- route: { path: '/', view: 'home', params: {}, query: {}, transitioning: false },
7
- theme: 'light'
8
- },
9
- todos: {
10
- items: [],
11
- filter: 'all'
12
- }
13
- };
14
-
15
- const store = createEventState(initial);
16
- export default store;
@@ -1,11 +0,0 @@
1
- // views/home.js — Home route
2
- export async function boot({ store, el, signal }){
3
- const container = document.createElement('main');
4
- container.style.cssText = 'max-width: 600px; margin: 2rem auto; padding: 0 1rem;';
5
- container.innerHTML = `
6
- <h1>Home works!</h1>
7
- <p>This is the home page of the todo app example.</p>
8
- <p><a href="/todo-demo" data-link>Go to Todo App Demo →</a></p>
9
- `;
10
- el.appendChild(container);
11
- }
@@ -1,88 +0,0 @@
1
- // views/todoDemo.js — Minimal Todo app demo (imperative renderer, no bootstrap)
2
- export async function boot({ store, el, signal }){
3
- const main = document.createElement('main');
4
- main.innerHTML = `
5
- <h1>Todo app demo</h1>
6
- <section class="beh-section">
7
- <div style="display:flex; gap:8px; align-items:center; flex-wrap:wrap">
8
- <input id="newTodo" placeholder="New todo" />
9
- <button id="addTodo" class="btn">Add</button>
10
- <div style="display:flex; gap:6px; align-items:center">
11
- <button id="fAll" class="btn">All</button>
12
- <button id="fActive" class="btn">Active</button>
13
- <button id="fCompleted" class="btn">Completed</button>
14
- <button id="clearCompleted" class="btn" style="background:#b91c1c; color:white">Clear Completed</button>
15
- </div>
16
- <span id="filterBadge" style="padding:2px 6px; border:1px solid #888; border-radius:8px; font-size:.85em; color:#555">filter: all</span>
17
- </div>
18
- <ul id="todos" style="margin-top:10px; padding-left: 18px;"></ul>
19
- </section>
20
- `;
21
- el.appendChild(main);
22
-
23
- const input = main.querySelector('#newTodo');
24
- const ul = main.querySelector('#todos');
25
- const btnAdd = main.querySelector('#addTodo');
26
- const btnAll = main.querySelector('#fAll');
27
- const btnAct = main.querySelector('#fActive');
28
- const btnDone = main.querySelector('#fCompleted');
29
- const btnClear = main.querySelector('#clearCompleted');
30
-
31
- // Direct state manipulation (no intent pattern)
32
- const itemsPath = 'todos.items';
33
- const filterPath = 'todos.filter';
34
-
35
- // Add todo
36
- btnAdd?.addEventListener('click', () => {
37
- const text = (input?.value || '').trim();
38
- if (!text) return;
39
- const items = store.get(itemsPath) || [];
40
- const newTodo = { id: Date.now(), text, done: false };
41
- store.set(itemsPath, [...items, newTodo]);
42
- input.value = '';
43
- });
44
- input?.addEventListener('keydown', (e) => { if (e.key === 'Enter') btnAdd?.click(); });
45
-
46
- // Filter buttons
47
- btnAll?.addEventListener('click', () => store.set(filterPath, 'all'));
48
- btnAct?.addEventListener('click', () => store.set(filterPath, 'active'));
49
- btnDone?.addEventListener('click', () => store.set(filterPath, 'completed'));
50
-
51
- // Clear completed
52
- btnClear?.addEventListener('click', () => {
53
- const items = store.get(itemsPath) || [];
54
- store.set(itemsPath, items.filter(t => !t.done));
55
- });
56
-
57
- // Render
58
- function render(){
59
- const items = store.get(itemsPath) || [];
60
- const filter = store.get(filterPath) || 'all';
61
- const badge = main.querySelector('#filterBadge');
62
- if (badge) badge.textContent = `filter: ${filter}`;
63
- ul.replaceChildren();
64
- let rows = items;
65
- if (filter === 'active') rows = items.filter(t => !t.done);
66
- else if (filter === 'completed') rows = items.filter(t => !!t.done);
67
- rows.forEach((t) => {
68
- const li = document.createElement('li');
69
- li.style.display = 'flex'; li.style.gap = '8px'; li.style.alignItems = 'center';
70
- const cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = !!t.done;
71
- cb.addEventListener('change', () => {
72
- const items = store.get(itemsPath) || [];
73
- const updated = items.map(item =>
74
- item.id === t.id ? { ...item, done: !item.done } : item
75
- );
76
- store.set(itemsPath, updated);
77
- });
78
- const span = document.createElement('span'); span.textContent = t.text; if (t.done) span.style.textDecoration = 'line-through';
79
- li.appendChild(cb); li.appendChild(span); ul.appendChild(li);
80
- });
81
- }
82
- const off1 = store.subscribe(itemsPath, render);
83
- const off2 = store.subscribe(filterPath, render);
84
- render();
85
-
86
- if (signal) signal.addEventListener('abort', () => { try { off1 && off1(); off2 && off2(); } catch {} });
87
- return () => { try { off1 && off1(); off2 && off2(); } catch {} };
88
- }
@@ -1,65 +0,0 @@
1
- <!doctype html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width, initial-scale=1" />
6
- <title>030 Todo App with eventTest</title>
7
- <link rel="stylesheet" href="style.css">
8
- </head>
9
- <body data-theme="light" data-bind="data-theme: ui.theme">
10
- <nav style="display:flex; gap:10px; align-items:center; padding:10px 12px;">
11
- <a href="/" data-link>Home</a>
12
- <a href="/todo-demo" data-link>Todo app demo</a>
13
- <span style="flex:1"></span>
14
- <button class="btn" title="Toggle theme" data-on="click: toggleTheme() | log('toggle theme') | logPath('ui.theme')">Theme</button>
15
- </nav>
16
- <div data-route-root>
17
- <main style="max-width: 600px; margin: 2rem auto; padding: 0 1rem;">
18
- <h1>Home works!</h1>
19
- <p>This is the home page of the todo app example.</p>
20
- <p><a href="/todo-demo" data-link>Go to Todo App Demo →</a></p>
21
- </main>
22
- </div>
23
-
24
- <!-- Router setup -->
25
- <script type="module" src="./app/router.js"></script>
26
- <!-- Behaviors runtime (declarative data-bind and data-on) -->
27
- <script type="module">
28
- import store from './app/store.js';
29
- import { installBehaviors } from './runtime/core/behaviors.runtime.js';
30
-
31
- // Inline actions for nav buttons
32
- const registry = {
33
- toggleTheme(ctx) {
34
- const cur = ctx.get('ui.theme');
35
- const next = (cur === 'dark') ? 'light' : 'dark';
36
- ctx.set('ui.theme', next);
37
- },
38
- log(ctx, ...args) {
39
- console.log('[action]', ...args);
40
- },
41
- logPath(ctx, path) {
42
- console.log('[action]', String(path), ctx.get(String(path)));
43
- }
44
- };
45
-
46
- installBehaviors(store, {
47
- registry,
48
- root: document,
49
- writablePrefixes: ['ui.', 'todos.'],
50
- debug: false
51
- });
52
-
53
- // Initialize theme
54
- if (!store.get('ui.theme')) {
55
- const prefersDark = window.matchMedia?.('(prefers-color-scheme: dark)').matches;
56
- store.set('ui.theme', prefersDark ? 'dark' : 'light');
57
- }
58
-
59
- // Persist theme to localStorage
60
- store.subscribe('ui.theme', (theme) => {
61
- localStorage.setItem('ui.theme', theme);
62
- });
63
- </script>
64
- </body>
65
- </html>
@@ -1,282 +0,0 @@
1
- // behaviors.runtime.js — minimal parser + dispatcher for data-on/data-bind
2
- // Install with: installBehaviors(store, { registry, root, writablePrefixes })
3
-
4
- export function installBehaviors(store, { registry = {}, root = document, writablePrefixes = ['ui.'], writableWhitelist = [], debug = false, onStep = null } = {}){
5
- const subsByPath = new Map();
6
- const repeaters = [];
7
- const trackOff = (el, off) => { const arr = subsByPath.get(el) || []; arr.push(off); subsByPath.set(el, arr); };
8
- const unbindNode = (node) => {
9
- // Unsubscribe any subs registered for this node and its descendants
10
- const cleanup = (n) => {
11
- const offs = subsByPath.get(n);
12
- if (offs) { offs.forEach(off => { try { off(); } catch{} }); subsByPath.delete(n); }
13
- n.childNodes && n.childNodes.forEach && n.childNodes.forEach(cleanup);
14
- };
15
- try { cleanup(node); } catch {}
16
- };
17
-
18
- const bindEl = (el) => {
19
- // data-bind: "text: ui.counter; value: ui.name"
20
- const bindAttr = el.getAttribute?.('data-bind');
21
- if (bindAttr){
22
- for (const part of bindAttr.split(';')){
23
- const seg = part.trim(); if (!seg) continue;
24
- const [propRaw, pathRaw] = seg.split(':');
25
- const prop = (propRaw||'').trim();
26
- const path = (pathRaw||'').trim();
27
- const render = () => {
28
- const v = store.get(path);
29
- if (prop === 'text') el.textContent = v ?? '';
30
- else if (prop === 'value') el.value = v ?? '';
31
- else el.setAttribute(prop, v ?? '');
32
- };
33
- render();
34
- const off = store.subscribe(path, render);
35
- trackOff(el, off);
36
- }
37
- }
38
-
39
- // data-on: "click: inc(ui.counter,1) | set(ui.last,'clicked'); input: setFrom(ui.name,target.value)"
40
- const onAttr = el.getAttribute?.('data-on');
41
- if (onAttr){
42
- for (const rule of onAttr.split(';')){
43
- const seg = rule.trim(); if (!seg) continue;
44
- // Split only at the first ':' to avoid breaking on URLs like https://
45
- const colonAt = seg.indexOf(':');
46
- if (colonAt === -1) continue;
47
- const evt = seg.slice(0, colonAt).trim();
48
- const pipeRaw = seg.slice(colonAt + 1);
49
- const steps = String(pipeRaw||'').split('|').map(s=>s.trim()).filter(Boolean);
50
- el.addEventListener(evt, (event) => {
51
- for (const step of steps){
52
- const m = step.match(/^(\w+)\((.*)\)$/);
53
- const name = m ? m[1] : step;
54
- const argsStr = m ? m[2] : '';
55
- const args = parseArgs(argsStr);
56
- const fn = registry[name]; if (!fn) { if (console && console.warn) console.warn('[behaviors] missing action', name); continue; }
57
- const ctx = {
58
- store,
59
- el,
60
- event,
61
- get: (p) => store.get(p),
62
- set: (p, v) => {
63
- // writable guards: prefixes AND optional whitelist patterns
64
- const path = String(p);
65
- const okPrefix = writablePrefixes.some(pref => path === pref.slice(0, -1) || path.startsWith(pref));
66
- const okWhitelist = !writableWhitelist.length || writableWhitelist.some(pat => matchPattern(pat, path));
67
- if (!(okPrefix && okWhitelist)) {
68
- if (debug) console.warn('[behaviors] blocked write', { path, reason: 'guard' });
69
- try { onStep && onStep({ el, event, name, args, phase: 'blocked', blocked: true, write: path, reason: 'guard' }); } catch{}
70
- return;
71
- }
72
- store.set(p, v);
73
- // annotate successful write
74
- try { onStep && onStep({ el, event, name, args, phase: 'applied', blocked: false, write: path }); } catch{}
75
- },
76
- };
77
- try {
78
- try { onStep && onStep({ el, event, name, args, phase: 'started', blocked: false }); } catch{}
79
- fn(ctx, ...args);
80
- } catch (e) { console.warn('[behaviors] action error', name, e); }
81
- }
82
- });
83
- }
84
- }
85
-
86
- // data-repeat: very small, read-only repeater with simple scope for item.*
87
- // Example:
88
- // <li data-repeat="item in ui.items" data-key="item.id"><span class="txt" data-bind="text: item.name"></span></li>
89
- // <li data-repeat-empty>Empty</li>
90
- const repExpr = el.getAttribute?.('data-repeat');
91
- if (repExpr) {
92
- const parsed = parseRepeat(repExpr);
93
- if (!parsed) return;
94
- const { itemName, idxName, listPath, keyExpr } = parsed;
95
- // Detach template and install renderer anchored by a comment
96
- const parent = el.parentNode;
97
- if (!parent) return;
98
- const anchor = document.createComment('repeat-anchor');
99
- parent.insertBefore(anchor, el);
100
- parent.removeChild(el);
101
-
102
- const emptyEl = parent.querySelector?.('[data-repeat-empty]') || null;
103
-
104
- // State for keyed reconciliation
105
- const nodesByKey = new Map();
106
-
107
- const renderList = () => {
108
- const list = store.get(listPath) || [];
109
- // Toggle empty placeholder
110
- if (emptyEl) {
111
- try {
112
- const isEmpty = !Array.isArray(list) || list.length === 0;
113
- if (isEmpty) { emptyEl.removeAttribute('hidden'); emptyEl.style && (emptyEl.style.display = ''); }
114
- else { emptyEl.setAttribute('hidden', ''); emptyEl.style && (emptyEl.style.display = 'none'); }
115
- } catch {}
116
- }
117
-
118
- if (!Array.isArray(list)) return;
119
-
120
- // Build a fragment in order with keyed clones
121
- const frag = document.createDocumentFragment();
122
- const nextNodesByKey = new Map();
123
-
124
- for (let idx = 0; idx < list.length; idx++) {
125
- const item = list[idx];
126
- const key = resolveKey(item, idx, keyExpr);
127
- let node = nodesByKey.get(key);
128
- if (!node) {
129
- node = el.cloneNode(true);
130
- // Simple scoped binding for common cases used in tests:
131
- // - text: item.name
132
- // - attributes with {{item.id}}
133
- // Apply text bindings manually
134
- node.querySelectorAll?.('[data-bind]').forEach((n) => {
135
- const bindAttr = n.getAttribute('data-bind') || '';
136
- bindAttr.split(';').map(s => s.trim()).filter(Boolean).forEach((seg) => {
137
- const [propRaw, pathRaw] = seg.split(':');
138
- const prop = (propRaw||'').trim();
139
- const pth = (pathRaw||'').trim();
140
- let val;
141
- if (pth === idxName && idxName) {
142
- val = idx;
143
- } else if (pth.startsWith(itemName + '.')) {
144
- val = getByPath(item, pth.slice(itemName.length + 1));
145
- }
146
- if (pth === itemName) val = item; // not deeply rendered, but allow truthy check
147
- if (val !== undefined) {
148
- if (prop === 'text') n.textContent = val ?? '';
149
- else if (prop === 'value') n.value = val ?? '';
150
- else n.setAttribute(prop, val ?? '');
151
- }
152
- });
153
- // Prevent behaviors runtime from also binding this node to store paths like "item.*"
154
- n.removeAttribute('data-bind');
155
- });
156
- // Interpolate {{item.*}} in attributes used by tests (e.g., data-id)
157
- node.querySelectorAll('*').forEach((n) => {
158
- for (const attr of Array.from(n.attributes || [])){
159
- const m = /\{\{\s*(?:item\.(.+?)|(idx))\s*\}\}/g;
160
- if (m.test(attr.value)){
161
- const replaced = attr.value.replace(/\{\{\s*(?:item\.(.+?)|(idx))\s*\}\}/g, (_, pItem, pIdx) => {
162
- if (pIdx && idxName) return String(idx);
163
- const v = getByPath(item, pItem);
164
- return v == null ? '' : String(v);
165
- });
166
- n.setAttribute(attr.name, replaced);
167
- }
168
- }
169
- });
170
- }
171
- nextNodesByKey.set(key, node);
172
- frag.appendChild(node);
173
- }
174
-
175
- // Replace current range (between anchor and next non-render node) with frag
176
- // Simple strategy: remove all nodes after anchor until a repeat-empty (which we keep)
177
- let cursor = anchor.nextSibling;
178
- while (cursor && cursor !== emptyEl) {
179
- const next = cursor.nextSibling;
180
- parent.removeChild(cursor);
181
- cursor = next;
182
- }
183
- parent.insertBefore(frag, emptyEl || null);
184
- nodesByKey.clear();
185
- nextNodesByKey.forEach((v,k)=>nodesByKey.set(k,v));
186
- };
187
-
188
- renderList();
189
- const off = store.subscribe(listPath, renderList);
190
- repeaters.push({ off });
191
- trackOff(el, off);
192
- }
193
- };
194
-
195
- // initial scan
196
- const all = root.querySelectorAll?.('[data-bind], [data-on], [data-repeat]') || [];
197
- all.forEach(bindEl);
198
-
199
- // observe new nodes
200
- const mo = new MutationObserver((mutList) => {
201
- for (const m of mutList){
202
- m.addedNodes && m.addedNodes.forEach(node => {
203
- if (node.nodeType !== 1) return;
204
- if (node.matches?.('[data-bind], [data-on], [data-repeat]')) bindEl(node);
205
- node.querySelectorAll?.('[data-bind], [data-on], [data-repeat]').forEach(bindEl);
206
- });
207
- // cleanup removed
208
- m.removedNodes && m.removedNodes.forEach(node => {
209
- if (node.nodeType !== 1) return;
210
- unbindNode(node);
211
- });
212
- }
213
- });
214
- if (root && root instanceof Document) mo.observe(document.body, { childList: true, subtree: true });
215
-
216
- return () => {
217
- mo.disconnect();
218
- subsByPath.forEach(offs => offs.forEach(off => { try { off(); } catch{} }));
219
- subsByPath.clear();
220
- };
221
- }
222
-
223
- function parseArgs(s){
224
- if (!s.trim()) return [];
225
- // split by commas not inside quotes
226
- const parts = s.split(',').map(p=>p.trim());
227
- return parts.map(coerceArg);
228
- }
229
-
230
- function coerceArg(x){
231
- if (x === '') return '';
232
- if ((x.startsWith('"') && x.endsWith('"')) || (x.startsWith("'") && x.endsWith("'"))) return x.slice(1,-1);
233
- if (x === 'true') return true;
234
- if (x === 'false') return false;
235
- if (x === 'null') return null;
236
- if (!Number.isNaN(Number(x))) return Number(x);
237
- return x; // pass path strings etc.
238
- }
239
-
240
- function matchPattern(pattern, path){
241
- // Very small wildcard: '*' matches a single segment, '**' matches the rest
242
- if (pattern === path) return true;
243
- const pSegs = String(pattern).split('.');
244
- const sSegs = String(path).split('.');
245
- let i = 0, j = 0;
246
- while (i < pSegs.length && j < sSegs.length){
247
- const part = pSegs[i];
248
- if (part === '**'){ return true; }
249
- if (part === '*' || part === sSegs[j]){ i++; j++; continue; }
250
- return false;
251
- }
252
- // Allow trailing '**'
253
- while (i < pSegs.length && pSegs[i] === '**') i++;
254
- return i === pSegs.length && j === sSegs.length;
255
- }
256
-
257
- // Dev-only explicit export to support unit tests in 010-005
258
- export { matchPattern };
259
-
260
- function parseRepeat(expr){
261
- // "item in ui.items" or "(item, idx) in ui.items"
262
- const m = String(expr).match(/^\s*\(?\s*([a-zA-Z_$][\w$]*)\s*(?:,\s*([a-zA-Z_$][\w$]*))?\s*\)?\s+in\s+([\w$.]+)\s*$/);
263
- if (!m) return null;
264
- const itemName = m[1];
265
- const idxName = m[2] || null;
266
- const listPath = m[3];
267
- // Optional data-key attribute is read from element attribute when rendering
268
- return { itemName, idxName, listPath, keyExpr: `${itemName}.id` };
269
- }
270
-
271
- function resolveKey(item, idx, keyExpr){
272
- // For now only support item.id; fallback to index
273
- const v = (item && (item.id != null)) ? item.id : idx;
274
- return String(v);
275
- }
276
-
277
- function getByPath(obj, path){
278
- const segs = String(path).split('.');
279
- let cur = obj;
280
- for (const s of segs){ if (cur == null) return undefined; cur = cur[s]; }
281
- return cur;
282
- }