@view-models/core 2.2.0 → 3.0.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.
package/README.md CHANGED
@@ -1,5 +1,8 @@
1
1
  # @view-models/core
2
2
 
3
+ [![CI](https://github.com/sunesimonsen/view-models-core/actions/workflows/ci.yml/badge.svg)](https://github.com/sunesimonsen/view-models-core/actions/workflows/ci.yml)
4
+ [![Bundle Size](https://img.badgesize.io/https://unpkg.com/@view-models/core@2.2.0/dist/index.js?label=gzip&compression=gzip)](https://unpkg.com/@view-models/core@2.2.0/dist/index.js)
5
+
3
6
  A lightweight, framework-agnostic library for building reactive view models with TypeScript. Separate your business logic from your UI framework with a simple, testable pattern.
4
7
 
5
8
  ![View models banner](./view-models.png)
@@ -31,16 +34,20 @@ type CounterState = {
31
34
  };
32
35
 
33
36
  class CounterViewModel extends ViewModel<CounterState> {
37
+ constructor() {
38
+ super({ count: 0 });
39
+ }
40
+
34
41
  increment() {
35
- this.update(({ count }) => ({
36
- count: count + 1,
37
- }));
42
+ super.update({
43
+ count: super.state.count + 1,
44
+ });
38
45
  }
39
46
 
40
47
  decrement() {
41
- this.update(({ count }) => ({
42
- count: count - 1,
43
- }));
48
+ super.update({
49
+ count: super.state.count - 1,
50
+ });
44
51
  }
45
52
  }
46
53
  ```
@@ -77,10 +84,10 @@ describe("CounterViewModel", () => {
77
84
 
78
85
  ## View Models with Derived State
79
86
 
80
- When you need to compute derived values from your state (like counts, filtered lists, or formatted data), use `ViewModelWithDerivedState`:
87
+ When you need to compute derived values from your state (like counts, filtered lists, or formatted data), use `ViewModelWithComputedState`:
81
88
 
82
89
  ```typescript
83
- import { ViewModelWithDerivedState } from "@view-models/core";
90
+ import { ViewModelWithComputedState } from "@view-models/core";
84
91
 
85
92
  type TodoState = {
86
93
  items: Array<{ id: string; text: string; done: boolean }>;
@@ -92,7 +99,7 @@ type TodoDerivedState = TodoState & {
92
99
  remainingCount: number;
93
100
  };
94
101
 
95
- class TodoViewModel extends ViewModelWithDerivedState<
102
+ class TodoViewModel extends ViewModelWithComputedState<
96
103
  TodoState,
97
104
  TodoDerivedState
98
105
  > {
@@ -100,7 +107,7 @@ class TodoViewModel extends ViewModelWithDerivedState<
100
107
  super({ items: [] });
101
108
  }
102
109
 
103
- computeDerivedState({ items }: TodoState): TodoDerivedState {
110
+ computedState({ items }: TodoState): TodoDerivedState {
104
111
  return {
105
112
  items,
106
113
  totalCount: items.length,
@@ -110,17 +117,20 @@ class TodoViewModel extends ViewModelWithDerivedState<
110
117
  }
111
118
 
112
119
  addTodo(text: string) {
113
- this.update(({ items }) => ({
114
- items: [...items, { id: crypto.randomUUID(), text, done: false }],
115
- }));
120
+ super.update({
121
+ items: [
122
+ ...super.state.items,
123
+ { id: crypto.randomUUID(), text, done: false },
124
+ ],
125
+ });
116
126
  }
117
127
 
118
128
  toggleTodo(id: string) {
119
- this.update(({ items }) => ({
120
- items: items.map((item) =>
129
+ super.update({
130
+ items: super.state.items.map((item) =>
121
131
  item.id === id ? { ...item, done: !item.done } : item,
122
132
  ),
123
- }));
133
+ });
124
134
  }
125
135
  }
126
136
 
@@ -170,16 +180,14 @@ Always return new state objects from your updater functions:
170
180
 
171
181
  ```typescript
172
182
  // Good
173
- this.update(({ count }) => ({
174
- ...state,
175
- count: count + 1,
176
- }));
183
+ super.update({
184
+ count: super.state.count + 1,
185
+ });
177
186
 
178
187
  // Bad - mutates existing state
179
- this.update((state) => {
180
- state.count++;
181
- return state;
182
- });
188
+ const state = super.state;
189
+ state.count++;
190
+ super.update(state);
183
191
  ```
184
192
 
185
193
  ### Use Readonly Types
@@ -212,29 +220,29 @@ actions:
212
220
 
213
221
  ```typescript
214
222
  class TodosViewModel extends ViewModel<TodosState> {
215
- private api: API
223
+ private api: API;
216
224
 
217
225
  constructor(state: TodosState, api: API) {
218
- super(state)
219
- this.api = api
226
+ super(state);
227
+ this.api = api;
220
228
  }
221
229
 
222
230
  async loadTodos() {
223
- this.update((state) => ({ ...state, loading: true, failed: false }));
231
+ super.update({ loading: true, failed: false });
224
232
  try {
225
233
  const todos = await this.api.fetchTodos();
226
- this.update(() => ({ todos, loading: false }));
234
+ super.update({ todos, loading: false });
227
235
  } catch {
228
- this.update((state) => ({ ...state, loading: false: failed: true }));
236
+ super.update({ loading: false, failed: true });
229
237
  }
230
238
  }
231
239
 
232
240
  async addTodo(text: string) {
233
241
  try {
234
242
  const todo = await this.api.createTodo(text);
235
- this.update(({ todos }) => ({
236
- todos: [...todos, todo],
237
- }));
243
+ super.update({
244
+ todos: [...super.state.todos, todo],
245
+ });
238
246
  } catch {
239
247
  // TODO show error
240
248
  }
package/dist/index.d.ts CHANGED
@@ -1,12 +1,3 @@
1
- /**
2
- * Function that receives the current state and returns the new state.
3
- * The updater function should be pure and return a new state object.
4
- *
5
- * @template T - The state type
6
- * @param currentState - The current state
7
- * @returns The new state
8
- */
9
- type Updater<T> = (currentState: T) => T;
10
1
  /**
11
2
  * Function that gets called when the state changes.
12
3
  *
@@ -36,12 +27,12 @@ type ViewModelListener = () => void;
36
27
  * remainingCount: number;
37
28
  * };
38
29
  *
39
- * class TodoViewModel extends ViewModelWithDerivedState<TodoState, TodoDerivedState> {
30
+ * class TodoViewModel extends ViewModelWithComputedState<TodoState, TodoDerivedState> {
40
31
  * constructor() {
41
32
  * super({ items: [] });
42
33
  * }
43
34
  *
44
- * computeDerivedState({ items }: TodoState): TodoDerivedState {
35
+ * computedState({ items }: TodoState): TodoDerivedState {
45
36
  * return {
46
37
  * items,
47
38
  * totalCount: items.length,
@@ -51,9 +42,9 @@ type ViewModelListener = () => void;
51
42
  * }
52
43
  *
53
44
  * addTodo(text: string) {
54
- * this.update(({ items }) => ({
55
- * items: [...items, { id: crypto.randomUUID(), text, done: false }],
56
- * }));
45
+ * super.update({
46
+ * items: [...super.state.items, { id: crypto.randomUUID(), text, done: false }],
47
+ * });
57
48
  * }
58
49
  * }
59
50
  *
@@ -64,7 +55,7 @@ type ViewModelListener = () => void;
64
55
  * todos.addTodo('Learn ViewModels'); // Logs: Completed: 0
65
56
  * ```
66
57
  */
67
- declare abstract class ViewModelWithDerivedState<S, D> {
58
+ declare abstract class ViewModelWithComputedState<S extends object, D> {
68
59
  private _listeners;
69
60
  private _internalState;
70
61
  private _state;
@@ -91,7 +82,7 @@ declare abstract class ViewModelWithDerivedState<S, D> {
91
82
  * Create a new ViewModel with the given initial internal state.
92
83
  *
93
84
  * The constructor initializes the internal state and immediately computes
94
- * the derived state by calling `computeDerivedState`.
85
+ * the derived state by calling `computedState`.
95
86
  *
96
87
  * @param initialState - The initial internal state of the view model
97
88
  */
@@ -100,21 +91,19 @@ declare abstract class ViewModelWithDerivedState<S, D> {
100
91
  * Update the internal state, recompute derived state, and notify all subscribers.
101
92
  *
102
93
  * This method is protected and should only be called from within your view model subclass.
103
- * The updater function receives the current internal state and should return the new internal state.
94
+ * The partial state is merged with the current internal state to create the new internal state.
104
95
  * After updating, the derived state is automatically recomputed via `computeDerivedState`.
105
- * Always return a new state object to ensure immutability.
106
96
  *
107
- * @param updater - Function that receives current internal state and returns new internal state
97
+ * @param partial - Partial state to merge with the current internal state
108
98
  *
109
99
  * @example
110
100
  * ```typescript
111
- * this.update((currentState) => ({
112
- * ...currentState,
113
- * count: currentState.count + 1
114
- * }));
101
+ * super.update({
102
+ * count: super.state.count + 1
103
+ * });
115
104
  * ```
116
105
  */
117
- protected update(updater: Updater<S>): void;
106
+ protected update(partial: Partial<S>): void;
118
107
  /**
119
108
  * Compute the derived state from the internal state.
120
109
  *
@@ -128,7 +117,7 @@ declare abstract class ViewModelWithDerivedState<S, D> {
128
117
  *
129
118
  * @example
130
119
  * ```typescript
131
- * computeDerivedState({ count }: CounterState): CounterDerivedState {
120
+ * computedState({ count }: CounterState): CounterDerivedState {
132
121
  * return {
133
122
  * count,
134
123
  * isEven: count % 2 === 0,
@@ -137,11 +126,11 @@ declare abstract class ViewModelWithDerivedState<S, D> {
137
126
  * }
138
127
  * ```
139
128
  */
140
- abstract computeDerivedState(state: S): D;
129
+ abstract computedState(state: S): D;
141
130
  /**
142
131
  * Get the current derived state.
143
132
  *
144
- * This returns the derived state computed by `computeDerivedState`,
133
+ * This returns the derived state computed by `computedState`,
145
134
  * not the internal state.
146
135
  *
147
136
  * @returns The current derived state
@@ -167,7 +156,7 @@ declare abstract class ViewModelWithDerivedState<S, D> {
167
156
  * }
168
157
  *
169
158
  * increment() {
170
- * this.update(({ count }) => ({ count: count + 1 }));
159
+ * super.update({ count: super.state.count + 1 });
171
160
  * }
172
161
  * }
173
162
  *
@@ -178,15 +167,15 @@ declare abstract class ViewModelWithDerivedState<S, D> {
178
167
  * counter.increment(); // Logs: Count: 1
179
168
  * ```
180
169
  */
181
- declare abstract class ViewModel<S> extends ViewModelWithDerivedState<S, S> {
170
+ declare abstract class ViewModel<S extends object> extends ViewModelWithComputedState<S, S> {
182
171
  /**
183
172
  * Create a new ViewModel with the given initial state.
184
173
  *
185
174
  * @param initialState - The initial state of the view model
186
175
  */
187
176
  constructor(initialState: S);
188
- computeDerivedState(state: S): S;
177
+ computedState(state: S): S;
189
178
  }
190
179
 
191
- export { ViewModel, ViewModelWithDerivedState };
192
- export type { Updater, ViewModelListener };
180
+ export { ViewModel, ViewModelWithComputedState };
181
+ export type { ViewModelListener };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- class t{subscribe(t){return this.t.add(t),()=>{this.t.delete(t)}}constructor(t){this.t=new Set,this.i=t,this.h=this.computeDerivedState(this.i)}update(t){this.i=t(this.i),this.h=this.computeDerivedState(this.i);for(const t of this.t)t()}get state(){return this.h}}class s extends t{constructor(t){super(t)}computeDerivedState(t){return t}}export{s as ViewModel,t as ViewModelWithDerivedState};
1
+ class t{subscribe(t){return this.t.add(t),()=>{this.t.delete(t)}}constructor(t){this.t=new Set,this.i=t,this.h=this.computedState(this.i)}update(t){this.i={...this.i,...t},this.h=this.computedState(this.i);for(const t of this.t)t()}get state(){return this.h}}class s extends t{constructor(t){super(t)}computedState(t){return t}}export{s as ViewModel,t as ViewModelWithComputedState};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/ViewModelWithDerivedState.ts","../src/ViewModel.ts"],"sourcesContent":["/**\n * Function that receives the current state and returns the new state.\n * The updater function should be pure and return a new state object.\n *\n * @template T - The state type\n * @param currentState - The current state\n * @returns The new state\n */\nexport type Updater<T> = (currentState: T) => T;\n\n/**\n * Function that gets called when the state changes.\n *\n * @template T - The state type\n */\nexport type ViewModelListener = () => void;\n\n/**\n * Abstract base class for creating reactive view models with derived state.\n *\n * This class extends the basic ViewModel pattern by allowing you to compute\n * derived state from internal state. The internal state is managed privately,\n * while the derived state (which can include computed properties) is exposed\n * to subscribers.\n *\n * @template S - The internal state type (managed internally)\n * @template D - The derived state type (exposed to subscribers)\n *\n * @example\n * ```typescript\n * type TodoState = {\n * items: Array<{ id: string; text: string; done: boolean }>;\n * };\n *\n * type TodoDerivedState = TodoState & {\n * totalCount: number;\n * completedCount: number;\n * remainingCount: number;\n * };\n *\n * class TodoViewModel extends ViewModelWithDerivedState<TodoState, TodoDerivedState> {\n * constructor() {\n * super({ items: [] });\n * }\n *\n * computeDerivedState({ items }: TodoState): TodoDerivedState {\n * return {\n * items,\n * totalCount: items.length,\n * completedCount: items.filter(item => item.done).length,\n * remainingCount: items.filter(item => !item.done).length,\n * };\n * }\n *\n * addTodo(text: string) {\n * this.update(({ items }) => ({\n * items: [...items, { id: crypto.randomUUID(), text, done: false }],\n * }));\n * }\n * }\n *\n * const todos = new TodoViewModel();\n * todos.subscribe(() => {\n * console.log('Completed:', todos.state.completedCount);\n * });\n * todos.addTodo('Learn ViewModels'); // Logs: Completed: 0\n * ```\n */\nexport abstract class ViewModelWithDerivedState<S, D> {\n private _listeners: Set<ViewModelListener> = new Set();\n private _internalState: S;\n private _state: D;\n\n /**\n * Subscribe to state changes.\n *\n * The listener will be called immediately after any state update.\n *\n * @param listener - Function to call when state changes\n * @returns Function to unsubscribe the listener\n *\n * @example\n * ```typescript\n * const unsubscribe = viewModel.subscribe((state) => {\n * console.log('State changed:', state);\n * });\n *\n * // Later, when you want to stop listening:\n * unsubscribe();\n * ```\n */\n subscribe(listener: ViewModelListener): () => void {\n this._listeners.add(listener);\n return () => {\n this._listeners.delete(listener);\n };\n }\n\n /**\n * Create a new ViewModel with the given initial internal state.\n *\n * The constructor initializes the internal state and immediately computes\n * the derived state by calling `computeDerivedState`.\n *\n * @param initialState - The initial internal state of the view model\n */\n constructor(initialState: S) {\n this._internalState = initialState;\n this._state = this.computeDerivedState(this._internalState);\n }\n\n /**\n * Update the internal state, recompute derived state, and notify all subscribers.\n *\n * This method is protected and should only be called from within your view model subclass.\n * The updater function receives the current internal state and should return the new internal state.\n * After updating, the derived state is automatically recomputed via `computeDerivedState`.\n * Always return a new state object to ensure immutability.\n *\n * @param updater - Function that receives current internal state and returns new internal state\n *\n * @example\n * ```typescript\n * this.update((currentState) => ({\n * ...currentState,\n * count: currentState.count + 1\n * }));\n * ```\n */\n protected update(updater: Updater<S>) {\n this._internalState = updater(this._internalState);\n this._state = this.computeDerivedState(this._internalState);\n\n for (const listener of this._listeners) {\n listener();\n }\n }\n\n /**\n * Compute the derived state from the internal state.\n *\n * This abstract method must be implemented by subclasses to transform\n * the internal state into the derived state that will be exposed to\n * subscribers. This method is called automatically after each state\n * update and during initialization.\n *\n * @param state - The current internal state\n * @returns The derived state with any computed properties\n *\n * @example\n * ```typescript\n * computeDerivedState({ count }: CounterState): CounterDerivedState {\n * return {\n * count,\n * isEven: count % 2 === 0,\n * isPositive: count > 0,\n * };\n * }\n * ```\n */\n abstract computeDerivedState(state: S): D;\n\n /**\n * Get the current derived state.\n *\n * This returns the derived state computed by `computeDerivedState`,\n * not the internal state.\n *\n * @returns The current derived state\n */\n get state(): D {\n return this._state;\n }\n}\n","import { ViewModelWithDerivedState } from \"./ViewModelWithDerivedState.js\";\n\n/**\n * Abstract base class for creating reactive view models.\n *\n * A ViewModel manages state and notifies subscribers when the state changes.\n * Extend this class to create your own view models with custom business logic.\n *\n * @template S - The state type\n *\n * @example\n * ```typescript\n * type CounterState = { count: number };\n *\n * class CounterViewModel extends ViewModel<CounterState> {\n * constructor() {\n * super({ count: 0 });\n * }\n *\n * increment() {\n * this.update(({ count }) => ({ count: count + 1 }));\n * }\n * }\n *\n * const counter = new CounterViewModel();\n * const unsubscribe = counter.subscribe((state) => {\n * console.log('Count:', state.count);\n * });\n * counter.increment(); // Logs: Count: 1\n * ```\n */\nexport abstract class ViewModel<S> extends ViewModelWithDerivedState<S, S> {\n /**\n * Create a new ViewModel with the given initial state.\n *\n * @param initialState - The initial state of the view model\n */\n constructor(initialState: S) {\n super(initialState);\n }\n\n computeDerivedState(state: S): S {\n return state;\n }\n}\n"],"names":["ViewModelWithDerivedState","subscribe","listener","this","_listeners","add","delete","constructor","initialState","Set","_internalState","_state","computeDerivedState","update","updater","state","ViewModel","super"],"mappings":"MAoEsBA,EAuBpB,SAAAC,CAAUC,GAER,OADAC,KAAKC,EAAWC,IAAIH,GACb,KACLC,KAAKC,EAAWE,OAAOJ,GAE3B,CAUA,WAAAK,CAAYC,GArCJL,KAAAC,EAAqC,IAAIK,IAsC/CN,KAAKO,EAAiBF,EACtBL,KAAKQ,EAASR,KAAKS,oBAAoBT,KAAKO,EAC9C,CAoBU,MAAAG,CAAOC,GACfX,KAAKO,EAAiBI,EAAQX,KAAKO,GACnCP,KAAKQ,EAASR,KAAKS,oBAAoBT,KAAKO,GAE5C,IAAK,MAAMR,KAAYC,KAAKC,EAC1BF,GAEJ,CAkCA,SAAIa,GACF,OAAOZ,KAAKQ,CACd,EC7II,MAAgBK,UAAqBhB,EAMzC,WAAAO,CAAYC,GACVS,MAAMT,EACR,CAEA,mBAAAI,CAAoBG,GAClB,OAAOA,CACT"}
1
+ {"version":3,"file":"index.js","sources":["../src/ViewModelWithComputedState.ts","../src/ViewModel.ts"],"sourcesContent":["/**\n * Function that gets called when the state changes.\n *\n * @template T - The state type\n */\nexport type ViewModelListener = () => void;\n\n/**\n * Abstract base class for creating reactive view models with derived state.\n *\n * This class extends the basic ViewModel pattern by allowing you to compute\n * derived state from internal state. The internal state is managed privately,\n * while the derived state (which can include computed properties) is exposed\n * to subscribers.\n *\n * @template S - The internal state type (managed internally)\n * @template D - The derived state type (exposed to subscribers)\n *\n * @example\n * ```typescript\n * type TodoState = {\n * items: Array<{ id: string; text: string; done: boolean }>;\n * };\n *\n * type TodoDerivedState = TodoState & {\n * totalCount: number;\n * completedCount: number;\n * remainingCount: number;\n * };\n *\n * class TodoViewModel extends ViewModelWithComputedState<TodoState, TodoDerivedState> {\n * constructor() {\n * super({ items: [] });\n * }\n *\n * computedState({ items }: TodoState): TodoDerivedState {\n * return {\n * items,\n * totalCount: items.length,\n * completedCount: items.filter(item => item.done).length,\n * remainingCount: items.filter(item => !item.done).length,\n * };\n * }\n *\n * addTodo(text: string) {\n * super.update({\n * items: [...super.state.items, { id: crypto.randomUUID(), text, done: false }],\n * });\n * }\n * }\n *\n * const todos = new TodoViewModel();\n * todos.subscribe(() => {\n * console.log('Completed:', todos.state.completedCount);\n * });\n * todos.addTodo('Learn ViewModels'); // Logs: Completed: 0\n * ```\n */\nexport abstract class ViewModelWithComputedState<S extends object, D> {\n private _listeners: Set<ViewModelListener> = new Set();\n private _internalState: S;\n private _state: D;\n\n /**\n * Subscribe to state changes.\n *\n * The listener will be called immediately after any state update.\n *\n * @param listener - Function to call when state changes\n * @returns Function to unsubscribe the listener\n *\n * @example\n * ```typescript\n * const unsubscribe = viewModel.subscribe((state) => {\n * console.log('State changed:', state);\n * });\n *\n * // Later, when you want to stop listening:\n * unsubscribe();\n * ```\n */\n subscribe(listener: ViewModelListener): () => void {\n this._listeners.add(listener);\n return () => {\n this._listeners.delete(listener);\n };\n }\n\n /**\n * Create a new ViewModel with the given initial internal state.\n *\n * The constructor initializes the internal state and immediately computes\n * the derived state by calling `computedState`.\n *\n * @param initialState - The initial internal state of the view model\n */\n constructor(initialState: S) {\n this._internalState = initialState;\n this._state = this.computedState(this._internalState);\n }\n\n /**\n * Update the internal state, recompute derived state, and notify all subscribers.\n *\n * This method is protected and should only be called from within your view model subclass.\n * The partial state is merged with the current internal state to create the new internal state.\n * After updating, the derived state is automatically recomputed via `computeDerivedState`.\n *\n * @param partial - Partial state to merge with the current internal state\n *\n * @example\n * ```typescript\n * super.update({\n * count: super.state.count + 1\n * });\n * ```\n */\n protected update(partial: Partial<S>) {\n this._internalState = { ...this._internalState, ...partial };\n this._state = this.computedState(this._internalState);\n\n for (const listener of this._listeners) {\n listener();\n }\n }\n\n /**\n * Compute the derived state from the internal state.\n *\n * This abstract method must be implemented by subclasses to transform\n * the internal state into the derived state that will be exposed to\n * subscribers. This method is called automatically after each state\n * update and during initialization.\n *\n * @param state - The current internal state\n * @returns The derived state with any computed properties\n *\n * @example\n * ```typescript\n * computedState({ count }: CounterState): CounterDerivedState {\n * return {\n * count,\n * isEven: count % 2 === 0,\n * isPositive: count > 0,\n * };\n * }\n * ```\n */\n abstract computedState(state: S): D;\n\n /**\n * Get the current derived state.\n *\n * This returns the derived state computed by `computedState`,\n * not the internal state.\n *\n * @returns The current derived state\n */\n get state(): D {\n return this._state;\n }\n}\n","import { ViewModelWithComputedState } from \"./ViewModelWithComputedState.js\";\n\n/**\n * Abstract base class for creating reactive view models.\n *\n * A ViewModel manages state and notifies subscribers when the state changes.\n * Extend this class to create your own view models with custom business logic.\n *\n * @template S - The state type\n *\n * @example\n * ```typescript\n * type CounterState = { count: number };\n *\n * class CounterViewModel extends ViewModel<CounterState> {\n * constructor() {\n * super({ count: 0 });\n * }\n *\n * increment() {\n * super.update({ count: super.state.count + 1 });\n * }\n * }\n *\n * const counter = new CounterViewModel();\n * const unsubscribe = counter.subscribe((state) => {\n * console.log('Count:', state.count);\n * });\n * counter.increment(); // Logs: Count: 1\n * ```\n */\nexport abstract class ViewModel<\n S extends object,\n> extends ViewModelWithComputedState<S, S> {\n /**\n * Create a new ViewModel with the given initial state.\n *\n * @param initialState - The initial state of the view model\n */\n constructor(initialState: S) {\n super(initialState);\n }\n\n computedState(state: S): S {\n return state;\n }\n}\n"],"names":["ViewModelWithComputedState","subscribe","listener","this","_listeners","add","delete","constructor","initialState","Set","_internalState","_state","computedState","update","partial","state","ViewModel","super"],"mappings":"MA0DsBA,EAuBpB,SAAAC,CAAUC,GAER,OADAC,KAAKC,EAAWC,IAAIH,GACb,KACLC,KAAKC,EAAWE,OAAOJ,GAE3B,CAUA,WAAAK,CAAYC,GArCJL,KAAAC,EAAqC,IAAIK,IAsC/CN,KAAKO,EAAiBF,EACtBL,KAAKQ,EAASR,KAAKS,cAAcT,KAAKO,EACxC,CAkBU,MAAAG,CAAOC,GACfX,KAAKO,EAAiB,IAAKP,KAAKO,KAAmBI,GACnDX,KAAKQ,EAASR,KAAKS,cAAcT,KAAKO,GAEtC,IAAK,MAAMR,KAAYC,KAAKC,EAC1BF,GAEJ,CAkCA,SAAIa,GACF,OAAOZ,KAAKQ,CACd,ECjII,MAAgBK,UAEZhB,EAMR,WAAAO,CAAYC,GACVS,MAAMT,EACR,CAEA,aAAAI,CAAcG,GACZ,OAAOA,CACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@view-models/core",
3
- "version": "2.2.0",
3
+ "version": "3.0.0",
4
4
  "description": "A lightweight, framework-agnostic library for building reactive view models with TypeScript",
5
5
  "keywords": [
6
6
  "view",
package/src/ViewModel.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ViewModelWithDerivedState } from "./ViewModelWithDerivedState.js";
1
+ import { ViewModelWithComputedState } from "./ViewModelWithComputedState.js";
2
2
 
3
3
  /**
4
4
  * Abstract base class for creating reactive view models.
@@ -18,7 +18,7 @@ import { ViewModelWithDerivedState } from "./ViewModelWithDerivedState.js";
18
18
  * }
19
19
  *
20
20
  * increment() {
21
- * this.update(({ count }) => ({ count: count + 1 }));
21
+ * super.update({ count: super.state.count + 1 });
22
22
  * }
23
23
  * }
24
24
  *
@@ -29,7 +29,9 @@ import { ViewModelWithDerivedState } from "./ViewModelWithDerivedState.js";
29
29
  * counter.increment(); // Logs: Count: 1
30
30
  * ```
31
31
  */
32
- export abstract class ViewModel<S> extends ViewModelWithDerivedState<S, S> {
32
+ export abstract class ViewModel<
33
+ S extends object,
34
+ > extends ViewModelWithComputedState<S, S> {
33
35
  /**
34
36
  * Create a new ViewModel with the given initial state.
35
37
  *
@@ -39,7 +41,7 @@ export abstract class ViewModel<S> extends ViewModelWithDerivedState<S, S> {
39
41
  super(initialState);
40
42
  }
41
43
 
42
- computeDerivedState(state: S): S {
44
+ computedState(state: S): S {
43
45
  return state;
44
46
  }
45
47
  }
@@ -1,13 +1,3 @@
1
- /**
2
- * Function that receives the current state and returns the new state.
3
- * The updater function should be pure and return a new state object.
4
- *
5
- * @template T - The state type
6
- * @param currentState - The current state
7
- * @returns The new state
8
- */
9
- export type Updater<T> = (currentState: T) => T;
10
-
11
1
  /**
12
2
  * Function that gets called when the state changes.
13
3
  *
@@ -38,12 +28,12 @@ export type ViewModelListener = () => void;
38
28
  * remainingCount: number;
39
29
  * };
40
30
  *
41
- * class TodoViewModel extends ViewModelWithDerivedState<TodoState, TodoDerivedState> {
31
+ * class TodoViewModel extends ViewModelWithComputedState<TodoState, TodoDerivedState> {
42
32
  * constructor() {
43
33
  * super({ items: [] });
44
34
  * }
45
35
  *
46
- * computeDerivedState({ items }: TodoState): TodoDerivedState {
36
+ * computedState({ items }: TodoState): TodoDerivedState {
47
37
  * return {
48
38
  * items,
49
39
  * totalCount: items.length,
@@ -53,9 +43,9 @@ export type ViewModelListener = () => void;
53
43
  * }
54
44
  *
55
45
  * addTodo(text: string) {
56
- * this.update(({ items }) => ({
57
- * items: [...items, { id: crypto.randomUUID(), text, done: false }],
58
- * }));
46
+ * super.update({
47
+ * items: [...super.state.items, { id: crypto.randomUUID(), text, done: false }],
48
+ * });
59
49
  * }
60
50
  * }
61
51
  *
@@ -66,7 +56,7 @@ export type ViewModelListener = () => void;
66
56
  * todos.addTodo('Learn ViewModels'); // Logs: Completed: 0
67
57
  * ```
68
58
  */
69
- export abstract class ViewModelWithDerivedState<S, D> {
59
+ export abstract class ViewModelWithComputedState<S extends object, D> {
70
60
  private _listeners: Set<ViewModelListener> = new Set();
71
61
  private _internalState: S;
72
62
  private _state: D;
@@ -100,36 +90,34 @@ export abstract class ViewModelWithDerivedState<S, D> {
100
90
  * Create a new ViewModel with the given initial internal state.
101
91
  *
102
92
  * The constructor initializes the internal state and immediately computes
103
- * the derived state by calling `computeDerivedState`.
93
+ * the derived state by calling `computedState`.
104
94
  *
105
95
  * @param initialState - The initial internal state of the view model
106
96
  */
107
97
  constructor(initialState: S) {
108
98
  this._internalState = initialState;
109
- this._state = this.computeDerivedState(this._internalState);
99
+ this._state = this.computedState(this._internalState);
110
100
  }
111
101
 
112
102
  /**
113
103
  * Update the internal state, recompute derived state, and notify all subscribers.
114
104
  *
115
105
  * This method is protected and should only be called from within your view model subclass.
116
- * The updater function receives the current internal state and should return the new internal state.
106
+ * The partial state is merged with the current internal state to create the new internal state.
117
107
  * After updating, the derived state is automatically recomputed via `computeDerivedState`.
118
- * Always return a new state object to ensure immutability.
119
108
  *
120
- * @param updater - Function that receives current internal state and returns new internal state
109
+ * @param partial - Partial state to merge with the current internal state
121
110
  *
122
111
  * @example
123
112
  * ```typescript
124
- * this.update((currentState) => ({
125
- * ...currentState,
126
- * count: currentState.count + 1
127
- * }));
113
+ * super.update({
114
+ * count: super.state.count + 1
115
+ * });
128
116
  * ```
129
117
  */
130
- protected update(updater: Updater<S>) {
131
- this._internalState = updater(this._internalState);
132
- this._state = this.computeDerivedState(this._internalState);
118
+ protected update(partial: Partial<S>) {
119
+ this._internalState = { ...this._internalState, ...partial };
120
+ this._state = this.computedState(this._internalState);
133
121
 
134
122
  for (const listener of this._listeners) {
135
123
  listener();
@@ -149,7 +137,7 @@ export abstract class ViewModelWithDerivedState<S, D> {
149
137
  *
150
138
  * @example
151
139
  * ```typescript
152
- * computeDerivedState({ count }: CounterState): CounterDerivedState {
140
+ * computedState({ count }: CounterState): CounterDerivedState {
153
141
  * return {
154
142
  * count,
155
143
  * isEven: count % 2 === 0,
@@ -158,12 +146,12 @@ export abstract class ViewModelWithDerivedState<S, D> {
158
146
  * }
159
147
  * ```
160
148
  */
161
- abstract computeDerivedState(state: S): D;
149
+ abstract computedState(state: S): D;
162
150
 
163
151
  /**
164
152
  * Get the current derived state.
165
153
  *
166
- * This returns the derived state computed by `computeDerivedState`,
154
+ * This returns the derived state computed by `computedState`,
167
155
  * not the internal state.
168
156
  *
169
157
  * @returns The current derived state
package/src/index.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export * from "./ViewModel.js";
2
- export * from "./ViewModelWithDerivedState.js";
2
+ export * from "./ViewModelWithComputedState.js";