@snupo/jmc 1.1.0 → 1.2.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.
@@ -0,0 +1,193 @@
1
+ # jmc design guide
2
+
3
+ This guide is for Claude, and other coding agents, working in an app built with jmc. Read it before you change model, view or controller code. It describes how such an app is structured and the rules that keep that structure intact. People new to the codebase can read it too.
4
+
5
+ For the API itself (`patch`, `updateview`, components, props), see the [readme](readme.md).
6
+
7
+ ## The core idea
8
+
9
+ Apps that use jmc follow a well-defined MVC architecture. The code lives in three folders:
10
+
11
+ ```
12
+ model/
13
+ view/
14
+ controller/
15
+ ```
16
+
17
+ Each part has one job, and the boundaries between them are strict.
18
+
19
+ ### Model
20
+
21
+ The model is a plain JavaScript object (POJO): no proxies, no observables, no setters, no classes with behaviour. A value changes by plain assignment.
22
+
23
+ The model is held by a variable that is never reassigned. That variable is either `m`, or more often `vm`, a view model that holds the domain model in its field `m`. The view model adds the state that only the UI cares about, such as the current selection or an open dialog. Usually `vm` or `m` is global.
24
+
25
+ ```ts
26
+ // model/model.ts
27
+ export const vm = {
28
+ m: { todos: [] as Todo[] }, // the domain model
29
+ filter: 'all' as Filter, // UI state
30
+ editing: undefined as Todo | undefined,
31
+ }
32
+ ```
33
+
34
+ Because `vm` and `m` never change identity, every part of the app can hold on to them. Content changes happen inside them: assign fields, push to arrays, replace sub-objects. Never write `vm = …` or `vm.m = …` to "reset" state. Clear or reassign the fields instead.
35
+
36
+ ### View
37
+
38
+ The view is written in TSX. The TSX creates vdom objects, and jmc uses them to update the real DOM.
39
+
40
+ When the vdom comes from a function component, jmc attaches that function to the DOM element it created. Calling `updateview(element)` runs the function again with the current model and updates that element. Making view updates this easy is a central idea of jmc: you don't track what changed, you re-render the part of the page that might be affected.
41
+
42
+ ```tsx
43
+ // view/todolist.tsx
44
+ export const TodoList = () =>
45
+ <ul id='todos'>
46
+ {vm.m.todos.map(t => <li class={cc({ done: t.done })}>{t.text}</li>)}
47
+ </ul>
48
+ ```
49
+
50
+ The view turns model values into DOM elements, and nothing else. It operates on a **read-only** model. TypeScript can enforce this with jmc's `DeepReadonly` type: the view reads the model through a read-only alias of the same object.
51
+
52
+ ```ts
53
+ // model/model.ts
54
+ export const rvm: DeepReadonly<typeof vm> = vm // the view imports rvm, controllers import vm
55
+ ```
56
+
57
+ This comes at a cost: `DeepReadonly` changes the model's types as the view sees them. With a complex model, the resulting types and error messages can get hard for people to read. A project may therefore decide to follow the rule without `tsc` enforcing it. Where it is not enforced, the programmer must keep to it.
58
+
59
+ Whether to enforce it is the project's decision. **Don't add or remove `DeepReadonly` enforcement without asking first.** Follow the project's existing choice, and don't loosen types or add casts to get around it.
60
+
61
+ User input in the view goes to a controller method. The view never handles it by changing the model itself.
62
+
63
+ ```tsx
64
+ <button onclick={() => todoctrl.add(vm.newtext)}>Add</button>
65
+ ```
66
+
67
+ ### Controller
68
+
69
+ Controllers are typically stateless and usually global singletons.
70
+
71
+ - **Only controllers update the model.**
72
+ - **Only controllers call `updateview`**, after they changed the model.
73
+
74
+ A controller method has two parts:
75
+
76
+ 1. modify the model
77
+ 2. call `updateview()` for the parts of the view that might be affected
78
+
79
+ ```ts
80
+ // controller/todocontroller.ts
81
+ class TodoController {
82
+ add(text: string) {
83
+ vm.m.todos.push({ text, done: false }) // 1. modify the model
84
+ updateview('#todos', '#count') // 2. update the affected view
85
+ }
86
+ toggle(t: Todo) {
87
+ t.done = !t.done
88
+ updateview('#todos', '#count')
89
+ }
90
+ }
91
+ export const todoctrl = rebind(new TodoController())
92
+ ```
93
+
94
+ `rebind` binds the methods to the instance, so they can also be passed directly as event handlers.
95
+
96
+ This isn't specific to controllers. In JavaScript, a method passed on by itself (as an event handler, a callback, `arr.map(o.f)`) loses its `this`. So apply `rebind` to every instance of a class whose methods use `this`: `rebind(new X())`, or `rebind(this)` in the constructor. jmc does this for class components already, so don't call it there.
97
+
98
+ `rebind` binds only the methods of the object's own class, not methods inherited from a base class. For those, call `rebind(o, Base.prototype)` as well.
99
+
100
+ An asynchronous controller method follows the same pattern after each `await`: change the model, then update the view.
101
+
102
+ ```ts
103
+ async load() {
104
+ vm.loading = true
105
+ updateview('#status')
106
+ vm.m.todos = await fetchtodos()
107
+ vm.loading = false
108
+ updateview()
109
+ }
110
+ ```
111
+
112
+ ## Rules
113
+
114
+ When you write or change code in a jmc app:
115
+
116
+ - **Don't change the model in the view.** That includes event handlers written inline in TSX: they call a controller method. It also includes mutating array methods: `vm.m.todos.sort(…)` in a view sorts the model. Use `toSorted`, `toReversed`, `filter`, `map` or a copy.
117
+ - **Don't call `updateview` from the view or the model.** Class components calling `this.updateview()` for their own local state are the exception, see below.
118
+ - **Don't reassign `m` or `vm`.** Change their contents.
119
+ - **Keep the model plain.** Don't add proxies, signals, observables, stores, getters with side effects, or state libraries. Derived values are computed in the view, or in plain functions the view calls.
120
+ - **Keep controllers stateless.** State belongs in the model or view model, where the view can see it.
121
+ - **After changing the model, update every part of the view it might affect.** If you are unsure which parts that are, update a larger part. `updateview()` with no arguments updates the whole page and is always correct. Updating too much only costs time; updating too little leaves the page showing stale data, which is a bug.
122
+ - **Give update targets a stable handle.** The root element of a function component that controllers update on its own gets an `id` or a class, so a controller can name it in `updateview('#todos')`.
123
+
124
+ ### Class components
125
+
126
+ A class component is like a function component that can hold state. Its `view()` method plays the part of the function, and jmc creates the instance once and reuses it as long as the same class is rendered at the same place. Fields of the instance survive re-renders, and the component can update itself with `this.updateview()`.
127
+
128
+ ```tsx
129
+ class Dropdown extends Component<{ items: string[], onpick: (s: string) => void }> {
130
+ open = false
131
+ toggle() { this.open = !this.open; this.updateview() }
132
+ view(): H {
133
+ return <div class={cc('dropdown', { open: this.open })}>
134
+ <button onclick={this.toggle}>▾</button>
135
+ {this.open && <ul>{this.props.items.map(s => <li onclick={() => this.props.onpick(s)}>{s}</li>)}</ul>}
136
+ </div>
137
+ }
138
+ }
139
+ ```
140
+
141
+ Use a class component for a self-contained widget whose state no other part of the app needs, like `open` above. Such a component is its own small model and controller. State that the rest of the app reads or changes belongs in the model, and the code that changes it belongs in a controller. In the example, `onpick` would be a controller method.
142
+
143
+ `mounted()` runs once after the first render, and `update(uc)` runs before each re-render (return `true` to skip it). See the readme for all members.
144
+
145
+ ### Islands
146
+
147
+ Content managed by another library, such as a map or an editor, lives in an element marked `const`. jmc renders it once and leaves it alone afterwards. Controllers still own the model. The island's `update` callback passes model changes on to the library. See the readme for details.
148
+
149
+ ## Updating the view
150
+
151
+ `updateview(...)` updates right away: when it returns, the DOM shows the current model. Use it by default.
152
+
153
+ Three variants don't update right away. They queue the update and run all queued updates together later, and an element queued several times is updated once:
154
+
155
+ | function | runs the queued updates | use it when |
156
+ |---|---|---|
157
+ | `updateviewaf(...)` | at the next animation frame | events fire faster than the screen redraws: `mousemove`, `pointermove`, `scroll`, `resize`, dragging. The view updates at most once per frame. |
158
+ | `updateviewmicro(...)` | at the next microtask | one action calls several controller methods that each update the view. Their updates collapse into one, still before the browser paints. |
159
+ | `updateviewsync(...)` | immediately, together with everything queued | you need the DOM up to date now, for example to measure or focus an element, while other updates are queued. |
160
+
161
+ `flush()` runs everything queued, immediately.
162
+
163
+ After `updateviewaf` or `updateviewmicro`, the DOM is not updated yet. Code that reads the DOM right after the call, measures it or focuses an element sees the old state. Use `updateview` or `updateviewsync` there.
164
+
165
+ All of them take the same arguments as `updateview`: selectors, elements, a depth number, an update context object. Like `updateview`, they are called only by controllers.
166
+
167
+ ## Utilities
168
+
169
+ jmc exports a few helpers. Use them instead of writing your own:
170
+
171
+ | helper | what it does | typical use |
172
+ |---|---|---|
173
+ | `cc(...)` | joins class names. Objects contribute their keys with truthy values | `class={cc('item', { active: t === vm.selected, done: t.done })}` in the view |
174
+ | `<When cond={…}>` | renders its children only if `cond` is true | conditional blocks with several children. For a single element, `{cond && <p>…</p>}` is enough |
175
+ | `lazy(f)` | a prop value that is evaluated at each render, not when the JSX is created | a prop that must read the model at update time |
176
+ | `DeepReadonly<T>` | a type that makes all nested fields read-only | the view's read-only access to the model, see [View](#view) |
177
+ | `rebind(o)` | binds the prototype methods of `o` to `o` | every class instance whose methods use `this`, such as controllers: `export const todoctrl = rebind(new TodoController())`, so `onclick={todoctrl.clear}` works. Class components are rebound by jmc already |
178
+ | `closestby(node, pred)` | the nearest ancestor of `node`, or `node` itself, matching `pred` | event delegation: find the item element from `event.target` |
179
+ | `focuselement(node)` | focuses the node | in `mounted`, or in a controller after `updateview` |
180
+ | `mount({ … })` | puts values on `globalThis` | debugging: `mount({ vm, todoctrl })` makes model and controllers reachable in the browser console |
181
+ | `loggedmethods(o)` | wraps `o` so that each method call is logged with its arguments and result | debugging controllers: `export const todoctrl = loggedmethods(rebind(new TodoController()))` shows every action in the console. `loggedmethodscolored(color, o)` picks the log color |
182
+
183
+ `jmcconfig.debug = true` marks each component root with its name (`comp="TodoList"`), so the dev tools show which component rendered what.
184
+
185
+ ## Where things go
186
+
187
+ | you need to… | put it in |
188
+ |---|---|
189
+ | store data or UI state | a field of `m` or `vm`, in `model/` |
190
+ | show data | a component in `view/` |
191
+ | react to a click, input or other event | a controller method in `controller/`, called from the view |
192
+ | load or save data | a controller method, which updates the model and then the view |
193
+ | compute a value derived from the model | a plain function, called by the view |
package/package.json CHANGED
@@ -17,7 +17,7 @@
17
17
  },
18
18
  "homepage": "https://github.com/snuup/jmc#readme",
19
19
  "bugs": "https://github.com/snuup/jmc/issues",
20
- "version": "1.1.0",
20
+ "version": "1.2.0",
21
21
  "publishConfig": {
22
22
  "access": "public"
23
23
  },
@@ -41,7 +41,8 @@
41
41
  "sideEffects": false,
42
42
  "files": [
43
43
  "dist",
44
- "src"
44
+ "src",
45
+ "design-guide.md"
45
46
  ],
46
47
  "scripts": {
47
48
  "prebuild": "rimraf dist",
package/readme.md CHANGED
@@ -23,6 +23,16 @@ patch(document.body, <App />)
23
23
 
24
24
  Upgrading from 1.0? See [UPGRADING.md](UPGRADING.md).
25
25
 
26
+ ## Working with Claude and other coding agents
27
+
28
+ jmc ships a [design guide](design-guide.md) that explains to coding agents how a jmc app is structured: model, view and controller, and the rules between them. To have Claude follow it in your app, reference it from your project's `CLAUDE.md`:
29
+
30
+ ```md
31
+ This app uses jmc. Follow @node_modules/@snupo/jmc/design-guide.md
32
+ ```
33
+
34
+ The `@` import loads the guide into every session, and it stays current when you update jmc.
35
+
26
36
  ## Install
27
37
 
28
38
  ```sh