heavy-reactive 1.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.
Files changed (55) hide show
  1. package/.commitlintrc +2 -0
  2. package/.editorconfig +17 -0
  3. package/.gitattributes +2 -0
  4. package/.github/workflows/check-code.yml +48 -0
  5. package/.github/workflows/lint-commit.yml +15 -0
  6. package/.github/workflows/lint-request.yml +19 -0
  7. package/.github/workflows/release-job.yml +62 -0
  8. package/.husky/commit-msg +18 -0
  9. package/.husky/pre-commit +18 -0
  10. package/.prettierignore +2 -0
  11. package/.prettierrc +9 -0
  12. package/.vscode/extensions.json +3 -0
  13. package/.vscode/settings.json +27 -0
  14. package/.vscode/tasks.json +25 -0
  15. package/CHANGELOG.md +1 -0
  16. package/CONTRIBUTING.md +116 -0
  17. package/GLOSSARY.md +144 -0
  18. package/LICENSE +21 -0
  19. package/README.md +198 -0
  20. package/feature.reactivity/_common/changes.interface.ts +44 -0
  21. package/feature.reactivity/_common/dictionary-changes.interface.ts +54 -0
  22. package/feature.reactivity/_common/observable.interface.ts +22 -0
  23. package/feature.reactivity/_common/set-changes.interface.ts +50 -0
  24. package/feature.reactivity/_common/value-change.interface.ts +54 -0
  25. package/feature.reactivity/_common/value-container.interface.ts +12 -0
  26. package/feature.reactivity/dictionary/reactive-array.class.ts +0 -0
  27. package/feature.reactivity/dictionary/reactive-map.class.ts +0 -0
  28. package/feature.reactivity/dictionary/reactive-object.class.ts +0 -0
  29. package/feature.reactivity/reactivity-disabled.error.ts +11 -0
  30. package/feature.reactivity/reactivity.module.ts +458 -0
  31. package/feature.reactivity/readonly-access.error.ts +13 -0
  32. package/feature.reactivity/set/$difference.class.ts +272 -0
  33. package/feature.reactivity/set/$intersection.class.ts +137 -0
  34. package/feature.reactivity/set/$set.class.ts +1022 -0
  35. package/feature.reactivity/set/$union.class.ts +74 -0
  36. package/feature.reactivity/set/_combination/$combination.class.ts +179 -0
  37. package/feature.reactivity/set/_combination/$variadic-combination.class.ts +235 -0
  38. package/feature.reactivity/set/feature.projection-sets/$complement-via-set.class.ts +159 -0
  39. package/feature.reactivity/set/feature.projection-sets/$complement-via-val.class.ts +126 -0
  40. package/feature.reactivity/set/feature.projection-sets/$set-from-any.class.ts +382 -0
  41. package/feature.reactivity/set/feature.projection-sets/$set-from-set.class.ts +90 -0
  42. package/feature.reactivity/set/feature.projection-sets/$subset-via-set.class.ts +123 -0
  43. package/feature.reactivity/set/feature.projection-sets/$subset-via-val.class.ts +114 -0
  44. package/feature.reactivity/set/feature.projection-sets/feature.reactive-delta-buffer/delta-buffer-for-set.class.ts +235 -0
  45. package/feature.reactivity/set/feature.projection-sets/feature.reactive-delta-buffer/delta-buffer-for-value.class.ts +193 -0
  46. package/feature.reactivity/set/feature.projection-sets/types/dependency-set-resolver.type.ts +19 -0
  47. package/feature.reactivity/set/feature.projection-sets/types/dependency-value-resolver.type.ts +20 -0
  48. package/feature.reactivity/value/$value.class.ts +237 -0
  49. package/feature.set/index.ts +3 -0
  50. package/feature.set/set.prototype.difference.polyfill.ts +7 -0
  51. package/feature.set/set.prototype.intersection.polyfill.ts +6 -0
  52. package/feature.set/set.prototype.union.polyfill.ts +11 -0
  53. package/feature.typescript/maybe-promise.type.ts +1 -0
  54. package/package.json +51 -0
  55. package/tsconfig.json +116 -0
@@ -0,0 +1,272 @@
1
+ import { ISetChanges } from "../_common/set-changes.interface.js"
2
+ import { $VariadicCombination } from "./_combination/$variadic-combination.class.js"
3
+ import { $Set } from "./$set.class.js"
4
+ import { $Combination } from "./_combination/$combination.class.js"
5
+
6
+ /**
7
+ * Options for constructing a reactive `$Difference<T>` set.
8
+ *
9
+ * @template TValue The type of values in the sets.
10
+ */
11
+ export interface IDifferenceOptions<TValue> {
12
+ /**
13
+ * The base set from which all other sets will be subtracted.
14
+ */
15
+ superset: $Set<TValue>
16
+
17
+ /**
18
+ * One or more sets whose values should be excluded from the result.
19
+ */
20
+ subsets: Array<$Set<TValue>>
21
+
22
+ /**
23
+ * Optional debug label for introspection.
24
+ */
25
+ label?: string
26
+
27
+ /**
28
+ * Whether the difference set should be active/reactive upon creation.
29
+ * Defaults to `true`.
30
+ */
31
+ enabled?: boolean
32
+ }
33
+
34
+ /**
35
+ * Reactive set representing the difference between a base set and one or more excluded sets.
36
+ *
37
+ * `$Difference<T>` continuously computes the set of items that exist in the **base** set
38
+ * but are **not present** in any of the **excluded** sets.
39
+ *
40
+ * This class extends `$VariadicCombination<T>` and is fully reactive:
41
+ * any change to the base or excluded sets automatically updates the result.
42
+ *
43
+ * The resulting set is:
44
+ * - **readonly** – direct mutations will throw a `ReadonlyAccessError`;
45
+ * - **reactive** – emits `onChange` when the computed difference changes;
46
+ * - **derived** – entirely driven by its input sets.
47
+ *
48
+ * @template TValue The type of elements in the sets.
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * const $base = $set(['a', 'b', 'c', 'd'])
53
+ * const $excluded = $set(['b', 'd'])
54
+ *
55
+ * const $visible = new $Difference($base, [$excluded])
56
+ *
57
+ * console.log([...$visible]) // ['a', 'c']
58
+ *
59
+ * $excluded.delete('b')
60
+ * console.log([...$visible]) // ['a', 'c', 'b']
61
+ * ```
62
+ */
63
+ export class $Difference<TValue> extends $VariadicCombination<TValue> {
64
+ /**
65
+ * The base set from which all excluded values are subtracted.
66
+ *
67
+ * This set defines the upper bound of possible values in the result.
68
+ * Items are only present in the result if they are in this set
69
+ * and are not present in any of the excluded subsets.
70
+ *
71
+ * Assigned during construction and never reassigned.
72
+ */
73
+ protected readonly superset: $Set<TValue>
74
+
75
+ /**
76
+ * Creates a new reactive difference set.
77
+ *
78
+ * @param options Configuration object:
79
+ * - `superset`: the base set to subtract from;
80
+ * - `subsets`: one or more sets to subtract (excluded sets);
81
+ * - `label`: optional debug label;
82
+ * - `enabled`: whether the result is initially reactive.
83
+ *
84
+ * @remarks
85
+ * - Emits a warning if `superset` is also listed in `subsets` — this is logically meaningless.
86
+ * - Automatically mounts the `superset` if reactivity is enabled.
87
+ * - If the superset is also a derived set (e.g. another `$Combination`), sets up parent switching logic.
88
+ */
89
+ constructor(options: IDifferenceOptions<TValue>) {
90
+ if (options.subsets.includes(options.superset))
91
+ console.warn("The subtraction of the superminity from itself does not make sense - it requires optimization.")
92
+
93
+ super(options)
94
+
95
+ this.superset = options.superset
96
+
97
+ if (this.enabled) this.mountSuperset()
98
+
99
+ if (options.superset instanceof $Combination) this.watchParentReactivity(options.superset)
100
+ }
101
+
102
+ // ################# PARENT REACTIVE NODE ####################
103
+
104
+ /**
105
+ * Returns whether the parent node (i.e. the superset) is currently reactive.
106
+ *
107
+ * If the `superset` is itself a combination (i.e. a derived structure),
108
+ * its `.enabled` state is used. Otherwise, it is assumed to be always enabled.
109
+ */
110
+ protected get isParentEnabled() {
111
+ if (this.superset instanceof $Combination) return this.superset.enabled
112
+ return true
113
+ }
114
+
115
+ /**
116
+ * Returns whether this node is currently reactive.
117
+ *
118
+ * The node is considered enabled only if both:
119
+ * - this node itself is marked as enabled (`isLocallyEnabled`);
120
+ * - its parent (if any) is also enabled (`isParentEnabled`).
121
+ */
122
+ public get enabled() {
123
+ return this.isLocallyEnabled && this.isParentEnabled
124
+ }
125
+
126
+ /**
127
+ * Marks this node as enabled, and activates it only if the parent is also enabled.
128
+ *
129
+ * Triggers `onActivated()` if the node becomes active.
130
+ */
131
+ protected activate() {
132
+ this.isLocallyEnabled = true
133
+ if (this.isParentEnabled) this.onActivated()
134
+ }
135
+
136
+ /**
137
+ * Marks this node as disabled, and deactivates it only if the parent is still enabled.
138
+ *
139
+ * Triggers `onDeactivated()` if the node was previously active.
140
+ */
141
+ protected deactivate() {
142
+ this.isLocallyEnabled = false
143
+ if (this.isParentEnabled) this.onDeactivated()
144
+ }
145
+
146
+ /**
147
+ * Subscribes to reactivity state changes of the parent (superset).
148
+ *
149
+ * This allows `$Difference` to mirror the enabled/disabled state of the parent node.
150
+ *
151
+ * @param parent The superset to track for reactivity changes.
152
+ */
153
+ protected watchParentReactivity(parent: $Combination<TValue>) {
154
+ parent.onSwitch.subscribe(() => {
155
+ if (this.isLocallyEnabled && parent.enabled) this.onActivated()
156
+ if (this.isLocallyEnabled && !parent.enabled) this.onDeactivated()
157
+ })
158
+ }
159
+
160
+ // ################# SUPERSET ####################
161
+
162
+ /**
163
+ * Lifecycle hook triggered when this difference becomes fully enabled.
164
+ *
165
+ * - Calls the parent implementation.
166
+ * - Mounts the superset, so its values are included in the result.
167
+ */
168
+ protected onActivated(): void {
169
+ super.onActivated()
170
+ this.mountSuperset()
171
+ }
172
+
173
+ /**
174
+ * Lifecycle hook triggered when this difference becomes disabled.
175
+ *
176
+ * - Calls the parent implementation.
177
+ * - Unsubscribes from the superset and stops tracking its changes.
178
+ */
179
+ protected onDeactivated(): void {
180
+ super.onDeactivated()
181
+ this.unmountSuperset()
182
+ }
183
+
184
+ /**
185
+ * Initializes tracking of the superset:
186
+ * - Applies its current content as the initial `increment`;
187
+ * - Starts listening to future changes.
188
+ */
189
+ protected mountSuperset(): void {
190
+ this.handleChangesOfSuperset({ increment: this.superset, decrement: undefined })
191
+ this.listenSupersetChanges()
192
+ }
193
+
194
+ /**
195
+ * Stops listening to changes from the superset.
196
+ *
197
+ * Aborts the corresponding subscription signal, if present.
198
+ */
199
+ protected unmountSuperset(): void {
200
+ this.subsetChangeControllers.get(this.superset)?.abort()
201
+ }
202
+
203
+ /**
204
+ * Subscribes to the superset's `onChange` signal.
205
+ *
206
+ * All future changes will be handled by `handleChangesOfSuperset`.
207
+ * The subscription is abortable and tracked in `changeSubscriptions`.
208
+ */
209
+ protected listenSupersetChanges() {
210
+ const controller = new AbortController()
211
+ this.subsetChangeControllers.set(this.superset, controller)
212
+ this.superset.onChange.subscribe((changes) => this.handleChangesOfSuperset(changes), { signal: controller.signal })
213
+ }
214
+
215
+ /**
216
+ * Processes changes coming from the superset.
217
+ *
218
+ * - Removes all `decrement` values from `occurrences`;
219
+ * - Adds `increment` values that are not currently excluded.
220
+ *
221
+ * Only items not already excluded will be added to the result.
222
+ *
223
+ * @param param0 The changes to apply from the superset.
224
+ */
225
+ protected handleChangesOfSuperset({ increment = new Set(), decrement }: ISetChanges<TValue>) {
226
+ for (const item of decrement ?? []) this.valueOccurrences.delete(item)
227
+ const nonOccuredIncrementItems = [...increment].filter((item) => !this.valueOccurrences.get(item))
228
+ this.applyChanges({ decrement, increment: new Set(nonOccuredIncrementItems) })
229
+ }
230
+
231
+ // #################
232
+
233
+ /**
234
+ * Recalculates the result when an excluded subset changes.
235
+ *
236
+ * - When a value is added to an excluded set and it's the first time it's excluded,
237
+ * it is removed from the result (`decrement`).
238
+ * - When a value is removed from an excluded set and it is no longer excluded by any subset,
239
+ * it is restored to the result (`increment`).
240
+ *
241
+ * @param param0 Changes from one of the excluded subsets.
242
+ */
243
+ protected recalculateOnSubsetChange({ increment: addedToExcludedSet, decrement: removedFromExcludedSet }: ISetChanges<TValue>) {
244
+ const addedBackToResult = new Set<TValue>()
245
+ const removedFromResult = new Set<TValue>()
246
+
247
+ for (const item of addedToExcludedSet ?? []) {
248
+ const prevCount = this.valueOccurrences.get(item) ?? 0
249
+ const nextCount = prevCount + 1
250
+
251
+ this.valueOccurrences.set(item, nextCount)
252
+
253
+ if (nextCount === 1) removedFromResult.add(item)
254
+ }
255
+
256
+ for (const item of removedFromExcludedSet ?? []) {
257
+ const prevCount = this.valueOccurrences.get(item)
258
+ if (!prevCount) continue
259
+
260
+ const nextCount = prevCount - 1
261
+
262
+ if (nextCount === 0) {
263
+ this.valueOccurrences.delete(item)
264
+ addedBackToResult.add(item)
265
+ } else {
266
+ this.valueOccurrences.set(item, nextCount)
267
+ }
268
+ }
269
+
270
+ this.applyChanges({ increment: addedBackToResult, decrement: removedFromResult })
271
+ }
272
+ }
@@ -0,0 +1,137 @@
1
+ import { $Set } from "./$set.class.js"
2
+ import { ISetChanges } from "../_common/set-changes.interface.js"
3
+ import { $VariadicCombination } from "./_combination/$variadic-combination.class.js"
4
+ import { difference } from "#set/index.js"
5
+
6
+ /**
7
+ * Reactive set that computes the intersection of multiple source sets.
8
+ *
9
+ * `$Intersection<T>` tracks a dynamic list of reactive sets (inputs),
10
+ * and continuously computes their intersection — i.e., only values
11
+ * that are present in **every** source set are included in the result.
12
+ *
13
+ * This class is a specialized form of `$VariadicCombination<T>` and `$Combination<T>`,
14
+ * and is useful for deriving consistent shared state between multiple inputs.
15
+ *
16
+ * The resulting set is:
17
+ * - read-only: all mutation methods throw `ReadonlyAccessError`;
18
+ * - reactive: emits `onChange` when the intersection result changes;
19
+ * - derived: changes automatically as inputs change.
20
+ *
21
+ * @template TValue The type of values stored in each source set.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * const $setA = $set(['a', 'b', 'c'])
26
+ * const $setB = $set(['b', 'c', 'd'])
27
+ *
28
+ * const $common = new $Intersection([$setA, $setB])
29
+ *
30
+ * console.log([...$common]) // ['b', 'c']
31
+ *
32
+ * $setA.delete('b')
33
+ * console.log([...$common]) // ['c']
34
+ * ```
35
+ *
36
+ * @remarks
37
+ * This class is not intended for direct mutation.
38
+ * Use the source sets to control the state.
39
+ */
40
+ export class $Intersection<TValue> extends $VariadicCombination<TValue> {
41
+ /**
42
+ * Handles a change event from one of the input sets and updates the intersection accordingly.
43
+ *
44
+ * The method updates the internal `occurrences` map — a counter of how many input sets
45
+ * currently contain each value. When a value reaches the full count of subsets,
46
+ * it is considered part of the intersection and added to the result.
47
+ *
48
+ * - If an added item now exists in all subsets, it is added to the intersection.
49
+ * - Removed items reduce their count; if the count drops below the total, the item is removed.
50
+ *
51
+ * @param param0 The change object from a subset's `onChange` event.
52
+ */
53
+ protected recalculateOnSubsetChange({ increment: addedToSubset, decrement: removedFromSubset }: ISetChanges<TValue>): void {
54
+ const addedToIntersection = new Set<TValue>()
55
+ const removedFromIntersection = removedFromSubset
56
+
57
+ for (const item of addedToSubset ?? []) {
58
+ const prevCount = this.valueOccurrences.get(item) ?? 0
59
+ const nextCount = prevCount + 1
60
+
61
+ this.valueOccurrences.set(item, nextCount)
62
+
63
+ if (nextCount === this.includedSubsets.size) addedToIntersection.add(item)
64
+ }
65
+
66
+ for (const item of removedFromSubset ?? []) {
67
+ const prevCount = this.valueOccurrences.get(item) ?? 0
68
+ const nextOccurrencesNumber = prevCount - 1
69
+
70
+ this.valueOccurrences.set(item, nextOccurrencesNumber)
71
+
72
+ if (nextOccurrencesNumber === 0) this.valueOccurrences.delete(item)
73
+ else this.valueOccurrences.set(item, nextOccurrencesNumber)
74
+ }
75
+
76
+ this.applyChanges({ increment: addedToIntersection, decrement: removedFromIntersection })
77
+ }
78
+
79
+ /**
80
+ * Mounts a new subset into the intersection and updates internal tracking.
81
+ *
82
+ * - All values in the new subset are counted in `occurrences`.
83
+ * - Any values currently in the intersection but missing from the new subset
84
+ * are removed, since they no longer appear in all subsets.
85
+ *
86
+ * This method is typically called by `$VariadicCombination` when a new source is added.
87
+ *
88
+ * @param subset A new `$Set<TValue>` to include in the intersection.
89
+ */
90
+ protected mountSubset(subset: $Set<TValue>) {
91
+ this.listenSubsetChanges(subset)
92
+
93
+ for (const item of subset) {
94
+ const prevCount = this.valueOccurrences.get(item) ?? 0
95
+ const nextCount = prevCount + 1
96
+
97
+ this.valueOccurrences.set(item, nextCount)
98
+ }
99
+
100
+ const decrement = difference(this, subset)
101
+ if (decrement.size) this.applyChanges({ increment: undefined, decrement })
102
+ }
103
+
104
+ /**
105
+ * Unmounts a subset from the intersection.
106
+ *
107
+ * - Removes its contributions from `occurrences`.
108
+ * - For any values that were previously excluded because this subset was missing them,
109
+ * re-checks whether they now qualify for the intersection.
110
+ *
111
+ * If the intersection is currently disabled (e.g. in `immutable` state), this method is inert.
112
+ *
113
+ * @param subset The subset to remove from participation.
114
+ */
115
+ protected unmountSubset(subset: $Set<TValue>) {
116
+ this.subsetChangeControllers.get(subset)?.abort()
117
+
118
+ if (this.enabled) {
119
+ const increment = new Set<TValue>()
120
+
121
+ for (const item of subset) {
122
+ const prevCount = this.valueOccurrences.get(item) ?? 0
123
+ const nextCount = prevCount - 1
124
+
125
+ if (nextCount === 0) this.valueOccurrences.delete(item)
126
+ else this.valueOccurrences.set(item, nextCount)
127
+ }
128
+
129
+ for (const item of difference(new Set(this.valueOccurrences.keys()), subset)) {
130
+ const prevCount = this.valueOccurrences.get(item) ?? 0
131
+ if (prevCount === this.includedSubsets.size) increment.add(item)
132
+ }
133
+
134
+ if (increment.size) this.applyChanges({ increment, decrement: undefined })
135
+ }
136
+ }
137
+ }