-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
352 lines (313 loc) · 10.8 KB
/
Copy pathindex.js
File metadata and controls
352 lines (313 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/**
* Array methods that mutate the array and should trigger events
* @constant {string[]}
*/
const ARRAY_MUTATORS = [
'push', 'pop', 'shift', 'unshift',
'splice', 'sort', 'reverse', 'fill', 'copyWithin'
]
/**
* Base class for creating reactive contexts with event-driven state management.
*
* Reactive fields emit events when their values are read or changed. Objects
* and arrays can be reassigned at any level, but doing so will remove their
* nested reactivity (a warning will be logged).
*
* @example Basic usage
* class AppContext extends ReactiveContext {
* constructor() {
* super()
* this.createReactiveFields({
* state: {
* count: 0,
* user: { name: '', authenticated: false }
* },
* items: []
* })
* }
* }
*
* const ctx = new AppContext()
*
* // Listening to reads
* ctx.on('state:count:read', (data) => {
* console.log(`Count was read: ${data.value}`)
* })
*
* // Listening to changes
* ctx.on('state:count:change', (data) => {
* console.log(`Count: ${data.old_value} → ${data.new_value}`)
* })
*
* // Primitive read (emit event)
* const x = ctx.state.count // ✅ Emits 'state:count:read' and 'state:read'
*
* // Primitive changes (emit events)
* ctx.state.count = 5 // ✅ Emits 'state:count:change' and 'state:change'
* ctx.state.user.name = 'John' // ✅ Emits 'state.user:name:change' and 'state.user:change'
*
* // Array mutations (emit events)
* ctx.items.push('new item') // ✅ Emits 'items:change'
* ctx.items[0] = 'modified' // ✅ Emits 'items:0:change' and 'items:change'
*
* // Object/array reassignment (allowed with warning, loses nested reactivity)
* ctx.state.user = { name: 'Jane' } // ⚠️ Warning + emits event
*/
export class ReactiveContext {
#listeners = {}
#proxy_cache = new WeakMap()
#fields = {}
/**
* Creates reactive fields that emit events on reads and changes.
*
* @param {Object} definitions - Object mapping field names to initial values
* @throws {TypeError} If a field name already exists on the instance
*
* @example
* this.createReactiveFields({
* state: { count: 0, loading: false },
* user: { profile: { name: '', avatar: null } },
* tags: []
* })
*/
createReactiveFields(definitions) {
for (const [field_name, initial_value] of Object.entries(definitions)) {
if (Object.prototype.hasOwnProperty.call(this, field_name)) {
throw new TypeError(`Field '${field_name}' already exists`)
}
this.#fields[field_name] = this.#createReactive(initial_value, field_name)
Object.defineProperty(this, field_name, {
get: () => this.#fields[field_name],
set: (new_value) => {
const old_value = this.#fields[field_name]
if (old_value !== null && old_value !== undefined && typeof old_value === 'object') {
const type = Array.isArray(old_value) ? 'array' : 'object'
console.warn(
`⚠️ Reassigning root ${type} '${field_name}' removes its reactivity. ` +
`Consider modifying its properties instead.`
)
}
this.#fields[field_name] = this.#createReactive(new_value, field_name)
this.#emit(`${field_name}:change`, {
prop: field_name,
old_value,
new_value,
timestamp: Date.now()
})
},
enumerable: true,
configurable: false
})
}
}
/**
* Creates a deeply reactive proxy for an object or array.
*
* @private
* @param {Object|Array} target - Value to make reactive
* @param {string} namespace - Event namespace for this level
* @returns {Proxy|*} Reactive proxy for objects/arrays, original value for primitives
*/
#createReactive(target, namespace) {
if (target === null || typeof target !== 'object') {
return target
}
if (this.#proxy_cache.has(target)) {
return this.#proxy_cache.get(target)
}
const proxy = new Proxy(target, {
get: (obj, prop) => {
const value = obj[prop]
if (Array.isArray(obj) && ARRAY_MUTATORS.includes(prop)) {
return (...args) => {
const result = Array.prototype[prop].apply(obj, args)
this.#emit(`${namespace}:change`, {
method: prop,
args,
length: obj.length,
timestamp: Date.now()
})
return result
}
}
if (value !== null && typeof value === 'object') {
return this.#createReactive(value, `${namespace}.${prop}`)
}
// Emit read events for primitive values
if (typeof prop === 'string' && !prop.startsWith('_')) {
this.#emit(`${namespace}:${prop}:read`, {
prop,
value,
timestamp: Date.now()
})
this.#emit(`${namespace}:read`, {
prop,
value,
timestamp: Date.now()
})
}
return value
},
set: (obj, prop, new_value) => {
const old_value = obj[prop]
if (old_value !== null && old_value !== undefined && typeof old_value === 'object') {
const type = Array.isArray(old_value) ? 'array' : 'object'
console.warn(
`⚠️ Reassigning ${type} '${prop}' removes its reactivity. ` +
`Consider modifying its properties instead.`
)
}
obj[prop] = new_value
this.#emit(`${namespace}:${prop}:change`, {
prop,
old_value,
new_value,
timestamp: Date.now()
})
this.#emit(`${namespace}:change`, {
prop,
old_value,
new_value,
timestamp: Date.now()
})
return true
}
})
this.#proxy_cache.set(target, proxy)
return proxy
}
/**
* Emits an event to all registered listeners.
*
* @private
* @param {string} event - Event name
* @param {*} data - Data to pass to listeners
*/
#emit(event, data) {
if (!this.#listeners[event]) return
for (const callback of this.#listeners[event]) {
try {
callback(data, this)
} catch (error) {
console.error(`Error in listener for "${event}":`, error)
}
}
}
/**
* Registers an event listener.
*
* @param {string} event - Event name (e.g., 'state:count:change', 'state:count:read')
* @param {Function} callback - Handler receiving (data, context) parameters
* @returns {Function} Cleanup function to unregister the listener
*
* @example Specific property change listener
* const cleanup = ctx.on('state:count:change', (data, context) => {
* console.log(`Count: ${data.old_value} → ${data.new_value}`)
* })
*
* cleanup() // Remove listener
*
* @example Specific property read listener
* ctx.on('state:count:read', (data) => {
* console.log(`Count was read: ${data.value}`)
* })
*
* @example Generic namespace listener
* ctx.on('state:change', (data) => {
* console.log(`Property '${data.prop}' changed`)
* })
*
* @example Array listener
* ctx.on('items:change', (data) => {
* if (data.method) {
* console.log(`Array.${data.method}() called`)
* }
* })
*/
on(event, callback) {
if (!this.#listeners[event]) {
this.#listeners[event] = []
}
this.#listeners[event].push(callback)
return () => this.off(event, callback)
}
/**
* Removes a specific event listener.
*
* @param {string} event - Event name
* @param {Function} callback - Handler function to remove
*
* @example
* const handler = (data) => console.log(data)
* ctx.on('state:change', handler)
* ctx.off('state:change', handler)
*/
off(event, callback) {
if (!this.#listeners[event]) return
const index = this.#listeners[event].indexOf(callback)
if (index > -1) {
this.#listeners[event].splice(index, 1)
}
}
/**
* Registers a one-time listener that removes itself after execution.
*
* @param {string} event - Event name
* @param {Function} callback - Handler function
* @returns {Function} Cleanup function
*
* @example
* ctx.once('state:ready:change', (data) => {
* console.log('State ready for the first time')
* })
*/
once(event, callback) {
const wrapper = (data, ctx) => {
callback(data, ctx)
this.off(event, wrapper)
}
return this.on(event, wrapper)
}
/**
* Removes all listeners for an event, or all listeners entirely.
*
* @param {string|null} [event=null] - Event name, or null for all
*
* @example
* ctx.removeAllListeners('state:change') // Specific event
* ctx.removeAllListeners() // All events
*/
removeAllListeners(event = null) {
if (event) {
this.#listeners[event] = []
} else {
this.#listeners = {}
}
}
/**
* Gets all event names with registered listeners.
*
* @returns {string[]} Array of event names
*/
getRegisteredEvents() {
return Object.keys(this.#listeners)
}
/**
* Gets the listener count for an event.
*
* @param {string} event - Event name
* @returns {number} Number of listeners
*/
getListenerCount(event) {
return this.#listeners[event]?.length ?? 0
}
/**
* Checks if an event has listeners.
*
* @param {string} event - Event name
* @returns {boolean} True if listeners exist
*/
hasListeners(event) {
return this.getListenerCount(event) > 0
}
}