neo.mjs 10.0.0-beta.3 → 10.0.0-beta.5

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 (76) hide show
  1. package/.github/RELEASE_NOTES/v10.0.0-beta.4.md +41 -0
  2. package/ServiceWorker.mjs +2 -2
  3. package/apps/portal/index.html +1 -1
  4. package/apps/portal/view/ViewportController.mjs +1 -1
  5. package/apps/portal/view/home/FooterContainer.mjs +1 -1
  6. package/apps/portal/view/learn/MainContainerController.mjs +6 -6
  7. package/examples/button/effect/MainContainer.mjs +207 -0
  8. package/examples/button/effect/app.mjs +6 -0
  9. package/examples/button/effect/index.html +11 -0
  10. package/examples/button/effect/neo-config.json +6 -0
  11. package/learn/guides/{Collections.md → datahandling/Collections.md} +6 -6
  12. package/learn/guides/datahandling/Grids.md +621 -0
  13. package/learn/guides/{Records.md → datahandling/Records.md} +4 -3
  14. package/learn/guides/{StateProviders.md → datahandling/StateProviders.md} +146 -1
  15. package/learn/guides/fundamentals/DeclarativeVDOMWithEffects.md +166 -0
  16. package/learn/guides/fundamentals/ExtendingNeoClasses.md +359 -0
  17. package/learn/guides/{Layouts.md → uibuildingblocks/Layouts.md} +40 -38
  18. package/learn/guides/{form_fields → userinteraction/form_fields}/ComboBox.md +3 -3
  19. package/learn/tree.json +64 -57
  20. package/package.json +3 -3
  21. package/src/DefaultConfig.mjs +2 -2
  22. package/src/Neo.mjs +244 -88
  23. package/src/button/Effect.mjs +435 -0
  24. package/src/collection/Base.mjs +35 -3
  25. package/src/component/Base.mjs +72 -61
  26. package/src/container/Base.mjs +28 -24
  27. package/src/controller/Base.mjs +87 -63
  28. package/src/core/Base.mjs +207 -33
  29. package/src/core/Compare.mjs +3 -13
  30. package/src/core/Config.mjs +230 -0
  31. package/src/core/ConfigSymbols.mjs +3 -0
  32. package/src/core/Effect.mjs +127 -0
  33. package/src/core/EffectBatchManager.mjs +68 -0
  34. package/src/core/EffectManager.mjs +38 -0
  35. package/src/core/Util.mjs +3 -18
  36. package/src/data/RecordFactory.mjs +22 -3
  37. package/src/grid/Container.mjs +8 -4
  38. package/src/grid/column/Component.mjs +1 -1
  39. package/src/state/Provider.mjs +343 -452
  40. package/src/state/createHierarchicalDataProxy.mjs +124 -0
  41. package/src/tab/header/EffectButton.mjs +75 -0
  42. package/src/util/Function.mjs +52 -5
  43. package/src/vdom/Helper.mjs +9 -10
  44. package/src/vdom/VNode.mjs +1 -1
  45. package/src/worker/App.mjs +0 -5
  46. package/test/siesta/siesta.js +32 -0
  47. package/test/siesta/tests/CollectionBase.mjs +10 -10
  48. package/test/siesta/tests/VdomHelper.mjs +22 -59
  49. package/test/siesta/tests/config/AfterSetConfig.mjs +100 -0
  50. package/test/siesta/tests/config/Basic.mjs +149 -0
  51. package/test/siesta/tests/config/CircularDependencies.mjs +166 -0
  52. package/test/siesta/tests/config/CustomFunctions.mjs +69 -0
  53. package/test/siesta/tests/config/Hierarchy.mjs +94 -0
  54. package/test/siesta/tests/config/MemoryLeak.mjs +92 -0
  55. package/test/siesta/tests/config/MultiLevelHierarchy.mjs +85 -0
  56. package/test/siesta/tests/core/Effect.mjs +131 -0
  57. package/test/siesta/tests/core/EffectBatching.mjs +322 -0
  58. package/test/siesta/tests/neo/MixinStaticConfig.mjs +138 -0
  59. package/test/siesta/tests/state/Provider.mjs +537 -0
  60. package/test/siesta/tests/state/createHierarchicalDataProxy.mjs +217 -0
  61. package/learn/guides/ExtendingNeoClasses.md +0 -331
  62. /package/learn/guides/{Tables.md → datahandling/Tables.md} +0 -0
  63. /package/learn/guides/{ApplicationBootstrap.md → fundamentals/ApplicationBootstrap.md} +0 -0
  64. /package/learn/guides/{ConfigSystemDeepDive.md → fundamentals/ConfigSystemDeepDive.md} +0 -0
  65. /package/learn/guides/{DeclarativeComponentTreesVsImperativeVdom.md → fundamentals/DeclarativeComponentTreesVsImperativeVdom.md} +0 -0
  66. /package/learn/guides/{InstanceLifecycle.md → fundamentals/InstanceLifecycle.md} +0 -0
  67. /package/learn/guides/{MainThreadAddons.md → fundamentals/MainThreadAddons.md} +0 -0
  68. /package/learn/guides/{Mixins.md → specificfeatures/Mixins.md} +0 -0
  69. /package/learn/guides/{MultiWindow.md → specificfeatures/MultiWindow.md} +0 -0
  70. /package/learn/guides/{PortalApp.md → specificfeatures/PortalApp.md} +0 -0
  71. /package/learn/guides/{ComponentsAndContainers.md → uibuildingblocks/ComponentsAndContainers.md} +0 -0
  72. /package/learn/guides/{CustomComponents.md → uibuildingblocks/CustomComponents.md} +0 -0
  73. /package/learn/guides/{WorkingWithVDom.md → uibuildingblocks/WorkingWithVDom.md} +0 -0
  74. /package/learn/guides/{Forms.md → userinteraction/Forms.md} +0 -0
  75. /package/learn/guides/{events → userinteraction/events}/CustomEvents.md +0 -0
  76. /package/learn/guides/{events → userinteraction/events}/DomEvents.md +0 -0
@@ -0,0 +1,217 @@
1
+ import Neo from '../../../../src/Neo.mjs';
2
+ import * as core from '../../../../src/core/_export.mjs';
3
+ import {createHierarchicalDataProxy} from '../../../../src/state/createHierarchicalDataProxy.mjs';
4
+ import Effect from '../../../../src/core/Effect.mjs';
5
+ import EffectManager from '../../../../src/core/EffectManager.mjs';
6
+ import Config from '../../../../src/core/Config.mjs';
7
+ import Base from '../../../../src/core/Base.mjs';
8
+
9
+ // Mock StateProvider for testing purposes
10
+ class MockStateProvider extends Base {
11
+ static config = {
12
+ className: 'Mock.State.Provider',
13
+ data_: null
14
+ }
15
+
16
+ #dataConfigs = {};
17
+
18
+ construct(config) {
19
+ super.construct(config);
20
+ }
21
+
22
+ afterSetData(value, oldValue) {
23
+ console.log(value);
24
+ if (value) {
25
+ this.processDataObject(value);
26
+ }
27
+ }
28
+
29
+ processDataObject(obj, path = '') {
30
+ Object.entries(obj).forEach(([key, value]) => {
31
+ const fullPath = path ? `${path}.${key}` : key;
32
+ if (Neo.typeOf(value) === 'Object') {
33
+ this.processDataObject(value, fullPath);
34
+ } else {
35
+ const clonedValue = Neo.isObject(value) ? Neo.clone(value, true) : value; // Deep clone objects
36
+ this.#dataConfigs[fullPath] = new Config(clonedValue);
37
+ }
38
+ });
39
+ }
40
+
41
+ getDataConfig(path) {
42
+ return this.#dataConfigs[path] || null;
43
+ }
44
+
45
+ getOwnerOfDataProperty(path) {
46
+ if (this.#dataConfigs[path]) {
47
+ return {owner: this, propertyName: path};
48
+ }
49
+ const parent = this.getParent();
50
+ if (parent) {
51
+ return parent.getOwnerOfDataProperty(path);
52
+ }
53
+ return null;
54
+ }
55
+
56
+ hasNestedDataStartingWith(path) {
57
+ const pathWithDot = `${path}.`;
58
+ if (Object.keys(this.#dataConfigs).some(key => key.startsWith(pathWithDot))) {
59
+ return true;
60
+ }
61
+ const parent = this.getParent();
62
+ return parent ? parent.hasNestedDataStartingWith(path) : false;
63
+ }
64
+
65
+ getParent() {
66
+ // For testing, we'll manually set a parent
67
+ return this._parent || null;
68
+ }
69
+ }
70
+ Neo.setupClass(MockStateProvider);
71
+
72
+ StartTest(t => {
73
+ t.it('should resolve data from a single provider', t => {
74
+ const provider = Neo.create(MockStateProvider, {data: {name: 'Neo', version: 10}});
75
+ let effectRunCount = 0;
76
+
77
+ const effect = new Effect({
78
+ fn: () => {
79
+ effectRunCount++;
80
+ const proxy = createHierarchicalDataProxy(provider);
81
+ if (effectRunCount === 1) {
82
+ t.is(proxy.name, 'Neo', 'Should get name from proxy (initial)');
83
+ t.is(proxy.version, 10, 'Should get version from proxy (initial)');
84
+ } else if (effectRunCount === 2) {
85
+ t.is(proxy.name, 'Neo.mjs', 'Should get name from proxy (updated)');
86
+ t.is(proxy.version, 10, 'Should get version from proxy (unchanged)');
87
+ }
88
+ }
89
+ });
90
+
91
+ t.is(effectRunCount, 1, 'Effect should run once initially');
92
+ t.is(effect.dependencies.size, 2, 'Effect should track 2 dependencies');
93
+
94
+ provider.getDataConfig('name').set('Neo.mjs');
95
+ t.is(effectRunCount, 2, 'Effect should re-run when dependency changes');
96
+
97
+ effect.destroy();
98
+ provider.destroy();
99
+ });
100
+
101
+ t.it('should resolve nested data from a single provider', t => {
102
+ const provider = Neo.create(MockStateProvider, {data: {user: {firstName: 'John', lastName: 'Doe'}}});
103
+ let effectRunCount = 0;
104
+
105
+ const effect = new Effect({
106
+ fn: () => {
107
+ effectRunCount++;
108
+ const proxy = createHierarchicalDataProxy(provider);
109
+ if (effectRunCount === 1) {
110
+ t.is(proxy.user.firstName, 'John', 'Should get nested firstName (initial)');
111
+ t.is(proxy.user.lastName, 'Doe', 'Should get nested lastName (initial)');
112
+ } else if (effectRunCount === 2) {
113
+ t.is(proxy.user.firstName, 'Jane', 'Should get nested firstName (updated)');
114
+ t.is(proxy.user.lastName, 'Doe', 'Should get nested lastName (unchanged)');
115
+ }
116
+ }
117
+ });
118
+
119
+ t.is(effectRunCount, 1, 'Effect should run once initially');
120
+ t.is(effect.dependencies.size, 2, 'Effect should track 2 nested dependencies');
121
+
122
+ provider.getDataConfig('user.firstName').set('Jane');
123
+ t.is(effectRunCount, 2, 'Effect should re-run when nested dependency changes');
124
+
125
+ effect.destroy();
126
+ provider.destroy();
127
+ });
128
+
129
+ t.it('should resolve data from parent providers', t => {
130
+ const parentProvider = Neo.create(MockStateProvider, {data: {appTitle: 'My App', user: {firstName: 'Parent'}}});
131
+ const childProvider = Neo.create(MockStateProvider, {data: {user: {lastName: 'Child'}}});
132
+ childProvider._parent = parentProvider; // Manually set parent
133
+
134
+ let effectRunCount = 0;
135
+
136
+ const effect = new Effect({
137
+ fn: () => {
138
+ effectRunCount++;
139
+ const proxy = createHierarchicalDataProxy(childProvider);
140
+ if (effectRunCount === 1) {
141
+ t.is(proxy.appTitle, 'My App', 'Should get appTitle from parent (initial)');
142
+ t.is(proxy.user.firstName, 'Parent', 'Should get firstName from parent (initial)');
143
+ t.is(proxy.user.lastName, 'Child', 'Should get lastName from child (initial)');
144
+ } else if (effectRunCount === 2) {
145
+ t.is(proxy.appTitle, 'New App Title', 'Should get appTitle from parent (updated)');
146
+ t.is(proxy.user.firstName, 'Parent', 'Should get firstName from parent (unchanged)');
147
+ t.is(proxy.user.lastName, 'Child', 'Should get lastName from child (unchanged)');
148
+ } else if (effectRunCount === 3) {
149
+ t.is(proxy.appTitle, 'New App Title', 'Should get appTitle from parent (unchanged)');
150
+ t.is(proxy.user.firstName, 'Parent', 'Should get firstName from parent (unchanged)');
151
+ t.is(proxy.user.lastName, 'New Child', 'Should get lastName from child (updated)');
152
+ } else if (effectRunCount === 4) {
153
+ t.is(proxy.appTitle, 'New App Title', 'Should get appTitle from parent (unchanged)');
154
+ t.is(proxy.user.firstName, 'New Parent', 'Should get firstName from parent (updated)');
155
+ t.is(proxy.user.lastName, 'New Child', 'Should get lastName from child (unchanged)');
156
+ }
157
+ }
158
+ });
159
+
160
+ t.is(effectRunCount, 1, 'Effect should run once initially');
161
+ t.is(effect.dependencies.size, 3, 'Effect should track 3 dependencies across hierarchy');
162
+
163
+ parentProvider.getDataConfig('appTitle').set('New App Title');
164
+ t.is(effectRunCount, 2, 'Effect should re-run when parent dependency changes');
165
+
166
+ childProvider.getDataConfig('user.lastName').set('New Child');
167
+ t.is(effectRunCount, 3, 'Effect should re-run when child dependency changes');
168
+
169
+ parentProvider.getDataConfig('user.firstName').set('New Parent');
170
+ t.is(effectRunCount, 4, 'Effect should re-run when parent nested dependency changes');
171
+
172
+ effect.destroy();
173
+ parentProvider.destroy();
174
+ childProvider.destroy();
175
+ });
176
+
177
+ t.it('should handle properties that are not data or nested paths', t => {
178
+ const provider = Neo.create(MockStateProvider, {data: {foo: 'bar'}});
179
+ let effectRunCount = 0;
180
+
181
+ const effect = new Effect({
182
+ fn: () => {
183
+ effectRunCount++;
184
+ const proxy = createHierarchicalDataProxy(provider);
185
+ t.is(proxy.nonExistent, null, 'Should return null for non-existent property');
186
+ t.is(proxy.foo, 'bar', 'Should still get existing data');
187
+ }
188
+ });
189
+
190
+ t.is(effectRunCount, 1, 'Effect should run once initially');
191
+ t.is(effect.dependencies.size, 1, 'Effect should only track existing data dependencies');
192
+
193
+ effect.destroy();
194
+ provider.destroy();
195
+ });
196
+
197
+ t.it('should not track dependencies when no effect is active', t => {
198
+ const provider = Neo.create(MockStateProvider, {data: {test: 123}});
199
+ const proxy = createHierarchicalDataProxy(provider);
200
+
201
+ // No active effect
202
+ t.is(EffectManager.getActiveEffect(), null, 'No active effect');
203
+
204
+ // Access property without active effect
205
+ const value = proxy.test;
206
+ t.is(value, 123, 'Should get value correctly');
207
+
208
+ // Verify no dependencies were added to a non-existent effect
209
+ const mockEffect = { addDependency: t.fail }; // If this is called, test fails
210
+ EffectManager.push(mockEffect); // Temporarily push a mock effect
211
+ EffectManager.pop(); // Immediately pop it
212
+
213
+ t.pass('No error when accessing proxy without active effect');
214
+
215
+ provider.destroy();
216
+ });
217
+ });
@@ -1,331 +0,0 @@
1
- # Extending Neo Classes
2
-
3
- Neo.mjs is built upon a robust and consistent class system. Understanding how to extend framework classes is fundamental to building custom functionality, whether you're creating new UI components, defining data structures, or implementing application logic.
4
-
5
- This guide covers the universal principles of class extension in Neo.mjs, which apply across all class types, not just UI components.
6
-
7
- ## 1. The `static config` Block: Defining Properties
8
-
9
- Every Neo.mjs class utilizes a `static config` block. This is where you define the properties that instances of your class will possess. These properties can be simple values, objects, or even other Neo.mjs class configurations.
10
-
11
- ```javascript readonly
12
- class MyBaseClass extends Neo.core.Base {
13
- static config = {
14
- className: 'My.Base.Class', // Unique identifier for the class
15
- myString : 'Hello',
16
- myNumber : 123
17
- }
18
- }
19
-
20
- export default Neo.setupClass(MyBaseClass);
21
- ```
22
-
23
- Common configs you'll encounter include `className` (a unique string identifier for your class) and `ntype` (a shorthand alias for component creation).
24
-
25
- ## 2. Reactive Configs: The Trailing Underscore (`_`)
26
-
27
- A cornerstone of Neo.mjs's reactivity is the trailing underscore (`_`) convention for configs defined in `static config`. When you append an underscore to a config name (e.g., `myConfig_`), the framework automatically generates a reactive getter and setter for it.
28
-
29
- ```javascript readonly
30
- class MyReactiveClass extends Neo.core.Base {
31
- static config = {
32
- className : 'My.Reactive.Class',
33
- myReactiveConfig_: 'initial value' // This config is reactive
34
- }
35
-
36
- onConstructed() {
37
- super.onConstructed();
38
- console.log(this.myReactiveConfig); // Accesses the getter
39
- this.myReactiveConfig = 'new value'; // Triggers the setter
40
- }
41
- }
42
-
43
- export default Neo.setupClass(MyReactiveClass);
44
- ```
45
-
46
- Assigning a new value to a reactive property (e.g., `this.myReactiveProp = 'new value'`) triggers its setter, which in turn can invoke lifecycle hooks, enabling automatic updates and side effects. Properties without the underscore are static and do not trigger this reactive behavior.
47
-
48
- ## 3. Configuration Lifecycle Hooks (`beforeSet`, `afterSet`, `beforeGet`)
49
-
50
- For every reactive config (`myConfig_`), Neo.mjs provides three optional lifecycle hooks that you can implement in your class. These methods are automatically called by the framework during the config's lifecycle, offering powerful interception points:
51
-
52
- * **`beforeSetMyConfig(value, oldValue)`**:
53
- * **Purpose**: Intercepts the value *before* it is set. Ideal for validation, type coercion, or transforming the incoming value.
54
- * **Return Value**: Return the (potentially modified) `value` that should be set. Returning `undefined` or `null` will prevent the value from being set.
55
-
56
- * **`afterSetMyConfig(value, oldValue)`**:
57
- * **Purpose**: Executed *after* the value has been successfully set. Ideal for triggering side effects, updating the UI (e.g., calling `this.update()` for components), or firing events.
58
- * **Return Value**: None.
59
-
60
- * **`beforeGetMyConfig(value)`**:
61
- * **Purpose**: Intercepts the value *before* it is returned by the getter. Useful for lazy initialization, computing values on demand, or returning a transformed version of the stored value.
62
- * **Return Value**: Return the `value` that should be returned by the getter.
63
-
64
- ### Overriding Lifecycle Hooks: `super` vs. Full Override
65
-
66
- When extending a Neo.mjs class, you often need to customize the behavior of inherited lifecycle hooks (like `afterSet*`, `onConstructed`, etc.). You have two primary approaches:
67
-
68
- #### 1. Extending Parent Behavior (Calling `super`)
69
-
70
- This is the most common and recommended approach. By calling `super.methodName(...)`, you ensure that the parent class's implementation of the hook is executed. You can then add your custom logic either before or after the `super` call.
71
-
72
- This approach is crucial for maintaining the framework's intended behavior and ensuring that inherited features continue to function correctly.
73
-
74
- ```javascript readonly
75
- import Button from '../../src/button/Base.mjs';
76
-
77
- class MyExtendedButton extends Button {
78
- static config = {
79
- className: 'My.Extended.Component',
80
- // text_ config is inherited from Button.Base
81
- // We can set a default value here if needed, or rely on button.Base's default
82
- text: 'New Default Text'
83
- }
84
-
85
- // Example: Adding logic after the parent's afterSetText
86
- afterSetText(value, oldValue) {
87
- // Add your custom pre-processing logic here
88
- super.afterSetText(value, oldValue);
89
- console.log(`Custom logic: Button text changed to "${value}"`);
90
- // Add your custom post-processing logic here
91
- }
92
- }
93
-
94
- export default Neo.setupClass(MyExtendedButton);
95
- ```
96
-
97
- #### 2. Completely Overriding Parent Behavior (No `super` Call)
98
-
99
- In rare cases, you might want to completely replace the parent class's implementation of a hook. This is achieved by simply omitting the `super` call within your overridden method.
100
-
101
- **Caution**: Use this approach with extreme care. You must fully understand the parent's implementation and ensure that your override does not break essential framework functionality or inherited features. This is generally reserved for advanced scenarios where you need full control over the hook's execution.
102
-
103
- ```javascript readonly
104
- import Button from '../../src/button/Base.mjs';
105
-
106
- class MyFullyOverriddenButton extends Button {
107
- static config = {
108
- className: 'My.Fully.Overridden.Component',
109
- text : 'New Default Text'
110
- }
111
-
112
- // Example: Completely overriding afterSetText
113
- afterSetText(value, oldValue) {
114
- // No super.afterSetText(value, oldValue); call
115
- console.log(`Fully custom logic: Button text changed to "${value}"`);
116
- // The parent's afterSetText will NOT be executed
117
- // This means that in this case you need to take care on your own to map the text value to the vdom.
118
- }
119
- }
120
-
121
- export default Neo.setupClass(MyFullyOverriddenButton);
122
- ```
123
-
124
-
125
-
126
- ```javascript readonly
127
- class MyHookedClass extends Neo.core.Base {
128
- static config = {
129
- className: 'My.Hooked.Class',
130
- myValue_ : 0
131
- }
132
-
133
- beforeSetMyValue(value, oldValue) {
134
- if (typeof value !== 'number' || value < 0) {
135
- console.warn('myValue must be a non-negative number!');
136
- return 0; // Default to 0 if invalid
137
- }
138
- return value;
139
- }
140
-
141
- afterSetMyValue(value, oldValue) {
142
- console.log(`myValue changed from ${oldValue} to ${value}`);
143
- // In a component, you might call this.update() here
144
- }
145
-
146
- beforeGetMyValue(value) {
147
- // Example: lazy initialization or computed value
148
- if (value === 0 && !this._initialized) {
149
- console.log('Initializing myValue on first access');
150
- this._initialized = true;
151
- return 10; // Return a default initial value
152
- }
153
- return value;
154
- }
155
- }
156
-
157
- export default Neo.setupClass(MyHookedClass);
158
- ```
159
-
160
- ## 4. The Role of `Neo.setupClass()` and the Global `Neo` Namespace
161
-
162
- When you define a class in Neo.mjs and pass it to `Neo.setupClass()`, the framework performs several crucial operations. One of the most significant is to **enhance the global `Neo` namespace** with a reference to your newly defined class.
163
-
164
- This means that after `Neo.setupClass(MyClass)` is executed, your class becomes accessible globally via `Neo.[your.class.name]`, where `[your.class.name]` corresponds to the `className` config you defined (e.g., `Neo.button.Base`, `Neo.form.field.Text`, or your custom `My.Custom.Class`).
165
-
166
- **Implications for Class Extension and Usage:**
167
-
168
- * **Global Accessibility**: You can refer to any framework class (or your own custom classes after they've been set up) using their full `Neo` namespace path (e.g., `Neo.button.Base`, `Neo.container.Base`) anywhere in your application code, even without an explicit ES module import for that specific class.
169
- * **Convenience vs. Best Practice**: While `extends Neo.button.Base` might technically work without an `import Button from '...'`, it is generally **not recommended** for application code. Explicit ES module imports (e.g., `import Button from '../button/Base.mjs';`) are preferred because they:
170
- * **Improve Readability**: Clearly show the dependencies of your module.
171
- * **Enhance Tooling**: Enable better static analysis, auto-completion, and refactoring support in modern IDEs.
172
- * **Ensure Consistency**: Promote a consistent and predictable coding style.
173
- * **Framework Internal Use**: The global `Neo` namespace is heavily utilized internally by the framework itself for its class registry, dependency resolution, and dynamic instantiation (e.g., when using `ntype` or `module` configs).
174
-
175
- Understanding this mechanism clarifies how Neo.mjs manages its class system and provides the underlying flexibility for its configuration-driven approach.
176
-
177
- ## 5. Practical Examples: Models, Stores, and Controllers
178
-
179
- The principles of class extension apply universally across all Neo.mjs class types.
180
-
181
- ### Extending `Neo.data.Model`
182
-
183
- Models define the structure and behavior of individual data records. While reactive configs can be used for class-level properties of a Model (e.g., a global setting for all products), properties that vary per record (like `price` or `discount`) should be defined as fields within the `fields` array. Neo.mjs provides `convert` and `calculate` functions directly on field definitions for per-record logic.
184
-
185
- ```javascript readonly
186
- import Model from '../../src/data/Model.mjs';
187
-
188
- class ProductModel extends Model {
189
- static config = {
190
- className: 'App.model.Product',
191
- fields: [
192
- {name: 'id', type: 'Number'},
193
- {name: 'name', type: 'String'},
194
- {name: 'price', type: 'Number', defaultValue: 0,
195
- // Use a convert function for field-level validation or transformation
196
- convert: value => {
197
- if (typeof value !== 'number' || value < 0) {
198
- console.warn('Price field must be a non-negative number!');
199
- return 0;
200
- }
201
- return value;
202
- }
203
- },
204
- {name: 'discount', type: 'Number', defaultValue: 0,
205
- // Use a convert function for field-level validation or transformation
206
- convert: value => {
207
- if (typeof value !== 'number' || value < 0 || value > 1) {
208
- console.warn('Discount field must be a number between 0 and 1!');
209
- return 0;
210
- }
211
- return value;
212
- }
213
- },
214
- {name: 'discountedPrice', type: 'Number',
215
- // Use a calculate function for derived values based on other fields in the record
216
- calculate: (data) => {
217
- // 'data' contains the raw field values of the current record
218
- return data.price * (1 - data.discount);
219
- }
220
- }
221
- ]
222
- }
223
- }
224
-
225
- Neo.setupClass(ProductModel);
226
- ```
227
-
228
- ### Extending `Neo.data.Store`
229
-
230
- Stores manage collections of data records, often using a defined `Model`.
231
-
232
- ```javascript readonly
233
- import Store from '../../src/data/Store.mjs';
234
- import ProductModel from './ProductModel.mjs'; // Assuming ProductModel is in the same directory
235
-
236
- class ProductsStore extends Store {
237
- static config = {
238
- className: 'App.store.Products',
239
- model : ProductModel, // Use our custom ProductModel
240
- autoLoad : true,
241
- url : '/api/products', // Example API endpoint
242
- sorters : [{
243
- property : 'name',
244
- direction: 'ASC'
245
- }]
246
- }
247
-
248
- // Custom method to filter by price range
249
- filterByPriceRange(min, max) {
250
- // The idiomatic way to apply filters is by setting the 'filters' config.
251
- // This replaces any existing filters.
252
- this.filters = [{
253
- property: 'price',
254
- operator: '>=',
255
- value : min
256
- }, {
257
- property: 'price',
258
- operator: '<=',
259
- value : max
260
- }];
261
- }
262
-
263
- // To add filters without replacing existing ones, you would typically
264
- // read the current filters, add new ones, and then set the filters config.
265
- // Example (conceptual, not part of the class):
266
- /*
267
- addPriceRangeFilter(min, max) {
268
- const currentFilters = this.filters ? [...this.filters] : [];
269
- currentFilters.push({
270
- property: 'price',
271
- operator: '>=',
272
- value : min
273
- }, {
274
- property: 'price',
275
- operator: '<=',
276
- value : max
277
- });
278
- this.filters = currentFilters;
279
- }
280
- */
281
- }
282
-
283
- Neo.setupClass(ProductsStore);
284
- ```
285
-
286
- ### Extending `Neo.controller.Component`
287
-
288
- Controllers encapsulate logic related to components, often handling events or managing state.
289
-
290
- ```javascript readonly
291
- import ComponentController from '../../src/controller/Component.mjs';
292
-
293
- class MyCustomController extends ComponentController {
294
- static config = {
295
- className: 'App.controller.MyCustom',
296
- // A reactive property to manage a piece of controller-specific state
297
- isActive_: false
298
- }
299
-
300
- onConstructed() {
301
- super.onConstructed();
302
- console.log('MyCustomController constructed!');
303
- }
304
-
305
- afterSetIsActive(value, oldValue) {
306
- console.log(`Controller active state changed from ${oldValue} to ${value}`);
307
- // Perform actions based on active state change
308
- if (value) {
309
- this.doSomethingActive();
310
- } else {
311
- this.doSomethingInactive();
312
- }
313
- }
314
-
315
- doSomethingActive() {
316
- console.log('Controller is now active!');
317
- // Example: enable a feature, start a timer
318
- }
319
-
320
- doSomethingInactive() {
321
- console.log('Controller is now inactive!');
322
- // Example: disable a feature, clear a timer
323
- }
324
- }
325
-
326
- Neo.setupClass(MyCustomController);
327
- ```
328
-
329
- ## Conclusion
330
-
331
- The class extension mechanism, coupled with the reactive config system and `Neo.setupClass()`, forms the backbone of development in Neo.mjs. By mastering these principles, you can create highly modular, maintainable, and powerful applications that seamlessly integrate with the framework's core.