slicejs-web-framework 3.3.7 → 3.4.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.
@@ -1,338 +1,366 @@
1
- /**
2
- * EventManager - Sistema de eventos pub/sub para Slice.js
3
- * Ubicación: /Slice/Components/Structural/EventManager/EventManager.js
4
- *
5
- * Características:
6
- * - Suscripciones globales y vinculadas a componentes
7
- * - Auto-limpieza cuando componentes se destruyen
8
- * - API simple: subscribe, subscribeOnce, unsubscribe, emit
9
- */
10
- /**
11
- * @typedef {Object} EventManagerBind
12
- * @property {(eventName: string, callback: Function) => string|null} subscribe
13
- * @property {(eventName: string, callback: Function) => string|null} subscribeOnce
14
- * @property {(eventName: string, data?: any) => void} emit
15
- */
16
-
17
-
18
- export default class EventManager {
19
- constructor() {
20
- // Map<eventName, Map<subscriptionId, { callback, componentSliceId, once }>>
21
- this.subscriptions = new Map();
22
-
23
- // Map<sliceId, Set<{ eventName, subscriptionId }>> - Para auto-cleanup
24
- this.componentSubscriptions = new Map();
25
-
26
- // Contador para IDs únicos
27
- this.idCounter = 0;
28
- }
29
-
30
- init() {
31
- return true;
32
- }
33
-
34
- // ============================================
35
- // API PRINCIPAL
36
- // ============================================
37
-
38
- /**
39
- * Suscribirse a un evento
40
- * @param {string} eventName - Nombre del evento
41
- * @param {(data?: any) => void} callback - Funcion a ejecutar cuando se emita el evento
42
- * @param {{ component?: HTMLElement }} [options]
43
- * @returns {string|null} subscriptionId - ID para desuscribirse
44
- *
45
- * @example
46
- * // Suscripcion global
47
- * const id = slice.events.subscribe('user:login', (user) => {
48
- * console.log('Usuario:', user);
49
- * });
50
- *
51
- * // Suscripcion con auto-cleanup
52
- * slice.events.subscribe('user:login', (user) => {
53
- * this.actualizar(user);
54
- * }, { component: this });
55
- */
56
- subscribe(eventName, callback, options = {}) {
57
- if (typeof callback !== 'function') {
58
- slice.logger.logError('EventManager', 'El callback debe ser una función');
59
- return null;
60
- }
61
-
62
- const subscriptionId = `evt_${++this.idCounter}`;
63
-
64
- // Crear Map para este evento si no existe
65
- if (!this.subscriptions.has(eventName)) {
66
- this.subscriptions.set(eventName, new Map());
67
- }
68
-
69
- // Guardar la suscripción
70
- this.subscriptions.get(eventName).set(subscriptionId, {
71
- callback,
72
- componentSliceId: options.component?.sliceId || null,
73
- once: false,
74
- });
75
-
76
- // Si hay componente, registrar para auto-cleanup
77
- if (options.component?.sliceId) {
78
- this._registerComponentSubscription(options.component.sliceId, eventName, subscriptionId);
79
- }
80
-
81
- slice.logger.logInfo('EventManager', `Suscrito a "${eventName}" [${subscriptionId}]`);
82
-
83
- return subscriptionId;
84
- }
85
-
86
- /**
87
- * Suscribirse a un evento una sola vez
88
- * @param {string} eventName - Nombre del evento
89
- * @param {(data?: any) => void} callback - Funcion a ejecutar
90
- * @param {{ component?: HTMLElement }} [options]
91
- * @returns {string|null} subscriptionId
92
- *
93
- * @example
94
- * slice.events.subscribeOnce('app:ready', () => {
95
- * console.log('App lista!');
96
- * });
97
- */
98
- subscribeOnce(eventName, callback, options = {}) {
99
- if (typeof callback !== 'function') {
100
- slice.logger.logError('EventManager', 'El callback debe ser una función');
101
- return null;
102
- }
103
-
104
- const subscriptionId = `evt_${++this.idCounter}`;
105
-
106
- if (!this.subscriptions.has(eventName)) {
107
- this.subscriptions.set(eventName, new Map());
108
- }
109
-
110
- this.subscriptions.get(eventName).set(subscriptionId, {
111
- callback,
112
- componentSliceId: options.component?.sliceId || null,
113
- once: true,
114
- });
115
-
116
- if (options.component?.sliceId) {
117
- this._registerComponentSubscription(options.component.sliceId, eventName, subscriptionId);
118
- }
119
-
120
- slice.logger.logInfo('EventManager', `Suscrito (once) a "${eventName}" [${subscriptionId}]`);
121
-
122
- return subscriptionId;
123
- }
124
-
125
- /**
126
- * Desuscribirse de un evento
127
- * @param {string} eventName - Nombre del evento
128
- * @param {string} subscriptionId - ID de la suscripcion
129
- * @returns {boolean} true si se elimino correctamente
130
- *
131
- * @example
132
- * const id = slice.events.subscribe('evento', callback);
133
- * // Despues...
134
- * slice.events.unsubscribe('evento', id);
135
- */
136
- unsubscribe(eventName, subscriptionId) {
137
- if (!this.subscriptions.has(eventName)) {
138
- return false;
139
- }
140
-
141
- const removed = this.subscriptions.get(eventName).delete(subscriptionId);
142
-
143
- // Limpiar Map vacío
144
- if (this.subscriptions.get(eventName).size === 0) {
145
- this.subscriptions.delete(eventName);
146
- }
147
-
148
- if (removed) {
149
- slice.logger.logInfo('EventManager', `Desuscrito de "${eventName}" [${subscriptionId}]`);
150
- }
151
-
152
- return removed;
153
- }
154
-
155
- /**
156
- * Emitir un evento
157
- * @param {string} eventName - Nombre del evento
158
- * @param {any} [data] - Datos a pasar a los callbacks
159
- * @returns {void}
160
- *
161
- * @example
162
- * slice.events.emit('user:login', { id: 123, name: 'Juan' });
163
- * slice.events.emit('cart:cleared'); // Sin datos
164
- */
165
- emit(eventName, data = null) {
166
- slice.logger.logInfo('EventManager', `Emitiendo "${eventName}"`, data);
167
-
168
- if (!this.subscriptions.has(eventName)) {
169
- return;
170
- }
171
-
172
- const toRemove = [];
173
-
174
- // Notificar a todos los suscriptores
175
- for (const [subscriptionId, subscription] of this.subscriptions.get(eventName)) {
176
- // Verificar que el componente aún existe (si aplica)
177
- if (subscription.componentSliceId) {
178
- if (!slice.controller.activeComponents.has(subscription.componentSliceId)) {
179
- // Componente ya no existe, marcar para eliminar
180
- toRemove.push(subscriptionId);
181
- continue;
182
- }
183
- }
184
-
185
- // Ejecutar callback
186
- try {
187
- subscription.callback(data);
188
- } catch (error) {
189
- slice.logger.logError('EventManager', `Error en callback de "${eventName}" [${subscriptionId}]`, error);
190
- }
191
-
192
- // Si es subscribeOnce, marcar para eliminar
193
- if (subscription.once) {
194
- toRemove.push(subscriptionId);
195
- }
196
- }
197
-
198
- // Limpiar suscripciones marcadas
199
- toRemove.forEach((id) => {
200
- this.subscriptions.get(eventName).delete(id);
201
- });
202
-
203
- // Limpiar Map vacío
204
- if (this.subscriptions.get(eventName).size === 0) {
205
- this.subscriptions.delete(eventName);
206
- }
207
- }
208
-
209
- // ============================================
210
- // BIND - Vinculación a Componente
211
- // ============================================
212
-
213
- /**
214
- * Vincular el EventManager a un componente para auto-cleanup
215
- * @param {HTMLElement} component - Componente Slice con sliceId
216
- * @returns {EventManagerBind|null} API vinculada al componente
217
- *
218
- * @example
219
- * class MiComponente extends HTMLElement {
220
- * async init() {
221
- * this.events = slice.events.bind(this);
222
- *
223
- * this.events.subscribe('user:login', (user) => {
224
- * this.actualizar(user);
225
- * });
226
- * }
227
- * }
228
- */
229
- bind(component) {
230
- if (!component?.sliceId) {
231
- slice.logger.logError('EventManager', 'bind() requiere un componente Slice válido con sliceId');
232
- return null;
233
- }
234
-
235
- const self = this;
236
-
237
- return {
238
- /**
239
- * Suscribirse a un evento (auto-cleanup)
240
- */
241
- subscribe: (eventName, callback) => {
242
- return self.subscribe(eventName, callback, { component });
243
- },
244
-
245
- /**
246
- * Suscribirse una sola vez (auto-cleanup)
247
- */
248
- subscribeOnce: (eventName, callback) => {
249
- return self.subscribeOnce(eventName, callback, { component });
250
- },
251
-
252
- /**
253
- * Emitir un evento
254
- */
255
- emit: (eventName, data) => {
256
- self.emit(eventName, data);
257
- },
258
- };
259
- }
260
-
261
- // ============================================
262
- // AUTO-CLEANUP
263
- // ============================================
264
-
265
- /**
266
- * Registrar suscripción para un componente (interno)
267
- */
268
- _registerComponentSubscription(sliceId, eventName, subscriptionId) {
269
- if (!this.componentSubscriptions.has(sliceId)) {
270
- this.componentSubscriptions.set(sliceId, new Set());
271
- }
272
- this.componentSubscriptions.get(sliceId).add({ eventName, subscriptionId });
273
- }
274
-
275
- /**
276
- * Limpiar todas las suscripciones de un componente
277
- * Se llama automáticamente cuando el componente se destruye
278
- * @param {string} sliceId - ID del componente
279
- * @returns {number} Cantidad de suscripciones eliminadas
280
- */
281
- cleanupComponent(sliceId) {
282
- if (!this.componentSubscriptions.has(sliceId)) {
283
- return 0;
284
- }
285
-
286
- const subscriptions = this.componentSubscriptions.get(sliceId);
287
- let count = 0;
288
-
289
- for (const { eventName, subscriptionId } of subscriptions) {
290
- if (this.unsubscribe(eventName, subscriptionId)) {
291
- count++;
292
- }
293
- }
294
-
295
- this.componentSubscriptions.delete(sliceId);
296
-
297
- if (count > 0) {
298
- slice.logger.logInfo('EventManager', `Limpiadas ${count} suscripción(es) de ${sliceId}`);
299
- }
300
-
301
- return count;
302
- }
303
-
304
- // ============================================
305
- // UTILIDADES
306
- // ============================================
307
-
308
- /**
309
- * Verificar si hay suscriptores para un evento
310
- * @param {string} eventName - Nombre del evento
311
- * @returns {boolean}
312
- */
313
- hasSubscribers(eventName) {
314
- return this.subscriptions.has(eventName) && this.subscriptions.get(eventName).size > 0;
315
- }
316
-
317
- /**
318
- * Obtener cantidad de suscriptores para un evento
319
- * @param {string} eventName - Nombre del evento
320
- * @returns {number}
321
- */
322
- subscriberCount(eventName) {
323
- if (!this.subscriptions.has(eventName)) {
324
- return 0;
325
- }
326
- return this.subscriptions.get(eventName).size;
327
- }
328
-
329
- /**
330
- * Limpiar TODAS las suscripciones (usar con cuidado)
331
- */
332
- clear() {
333
- this.subscriptions.clear();
334
- this.componentSubscriptions.clear();
335
- this.idCounter = 0;
336
- slice.logger.logInfo('EventManager', 'Todas las suscripciones eliminadas');
337
- }
338
- }
1
+ /**
2
+ * EventManager - Sistema de eventos pub/sub para Slice.js
3
+ * Ubicación: /Slice/Components/Structural/EventManager/EventManager.js
4
+ *
5
+ * Características:
6
+ * - Suscripciones globales y vinculadas a componentes
7
+ * - Auto-limpieza cuando componentes se destruyen
8
+ * - API simple: subscribe, subscribeOnce, unsubscribe, emit
9
+ */
10
+ /**
11
+ * @typedef {Object} EventManagerBind
12
+ * @property {(eventName: string, callback: Function) => string|null} subscribe
13
+ * @property {(eventName: string, callback: Function) => string|null} subscribeOnce
14
+ * @property {(eventName: string, data?: any) => void} emit
15
+ */
16
+
17
+
18
+ export default class EventManager {
19
+ constructor() {
20
+ // Map<eventName, Map<subscriptionId, { callback, componentSliceId, once }>>
21
+ this.subscriptions = new Map();
22
+
23
+ // Map<sliceId, Set<{ eventName, subscriptionId }>> - Para auto-cleanup
24
+ this.componentSubscriptions = new Map();
25
+
26
+ // Ring buffer de últimos emits (max 500) — solo se llena cuando el debugger está abierto
27
+ this.emitHistory = [];
28
+
29
+ // Contador de emits por evento en la sesión actual de grabación
30
+ this.emitCounts = new Map();
31
+
32
+ // Flag: solo grabamos cuando algún debugger UI está visible
33
+ this._recording = false;
34
+
35
+ // Contador para IDs únicos
36
+ this.idCounter = 0;
37
+ }
38
+
39
+ init() {
40
+ return true;
41
+ }
42
+
43
+ // ============================================
44
+ // API PRINCIPAL
45
+ // ============================================
46
+
47
+ /**
48
+ * Suscribirse a un evento
49
+ * @param {string} eventName - Nombre del evento
50
+ * @param {(data?: any) => void} callback - Funcion a ejecutar cuando se emita el evento
51
+ * @param {{ component?: HTMLElement }} [options]
52
+ * @returns {string|null} subscriptionId - ID para desuscribirse
53
+ *
54
+ * @example
55
+ * // Suscripcion global
56
+ * const id = slice.events.subscribe('user:login', (user) => {
57
+ * console.log('Usuario:', user);
58
+ * });
59
+ *
60
+ * // Suscripcion con auto-cleanup
61
+ * slice.events.subscribe('user:login', (user) => {
62
+ * this.actualizar(user);
63
+ * }, { component: this });
64
+ */
65
+ subscribe(eventName, callback, options = {}) {
66
+ if (typeof callback !== 'function') {
67
+ slice.logger.logError('EventManager', 'El callback debe ser una función');
68
+ return null;
69
+ }
70
+
71
+ const subscriptionId = `evt_${++this.idCounter}`;
72
+
73
+ // Crear Map para este evento si no existe
74
+ if (!this.subscriptions.has(eventName)) {
75
+ this.subscriptions.set(eventName, new Map());
76
+ }
77
+
78
+ // Guardar la suscripción
79
+ this.subscriptions.get(eventName).set(subscriptionId, {
80
+ callback,
81
+ componentSliceId: options.component?.sliceId || null,
82
+ once: false,
83
+ });
84
+
85
+ // Si hay componente, registrar para auto-cleanup
86
+ if (options.component?.sliceId) {
87
+ this._registerComponentSubscription(options.component.sliceId, eventName, subscriptionId);
88
+ }
89
+
90
+ slice.logger.logInfo('EventManager', `Suscrito a "${eventName}" [${subscriptionId}]`);
91
+
92
+ return subscriptionId;
93
+ }
94
+
95
+ /**
96
+ * Suscribirse a un evento una sola vez
97
+ * @param {string} eventName - Nombre del evento
98
+ * @param {(data?: any) => void} callback - Funcion a ejecutar
99
+ * @param {{ component?: HTMLElement }} [options]
100
+ * @returns {string|null} subscriptionId
101
+ *
102
+ * @example
103
+ * slice.events.subscribeOnce('app:ready', () => {
104
+ * console.log('App lista!');
105
+ * });
106
+ */
107
+ /**
108
+ * Activar registro de emits (lo llama el debugger al abrirse).
109
+ */
110
+ startRecording() {
111
+ this._recording = true;
112
+ this.emitHistory = [];
113
+ this.emitCounts = new Map();
114
+ }
115
+
116
+ /**
117
+ * Desactivar registro de emits (lo llama el debugger al cerrarse).
118
+ */
119
+ stopRecording() {
120
+ this._recording = false;
121
+ }
122
+
123
+ subscribeOnce(eventName, callback, options = {}) {
124
+ if (typeof callback !== 'function') {
125
+ slice.logger.logError('EventManager', 'El callback debe ser una función');
126
+ return null;
127
+ }
128
+
129
+ const subscriptionId = `evt_${++this.idCounter}`;
130
+
131
+ if (!this.subscriptions.has(eventName)) {
132
+ this.subscriptions.set(eventName, new Map());
133
+ }
134
+
135
+ this.subscriptions.get(eventName).set(subscriptionId, {
136
+ callback,
137
+ componentSliceId: options.component?.sliceId || null,
138
+ once: true,
139
+ });
140
+
141
+ if (options.component?.sliceId) {
142
+ this._registerComponentSubscription(options.component.sliceId, eventName, subscriptionId);
143
+ }
144
+
145
+ slice.logger.logInfo('EventManager', `Suscrito (once) a "${eventName}" [${subscriptionId}]`);
146
+
147
+ return subscriptionId;
148
+ }
149
+
150
+ /**
151
+ * Desuscribirse de un evento
152
+ * @param {string} eventName - Nombre del evento
153
+ * @param {string} subscriptionId - ID de la suscripcion
154
+ * @returns {boolean} true si se elimino correctamente
155
+ *
156
+ * @example
157
+ * const id = slice.events.subscribe('evento', callback);
158
+ * // Despues...
159
+ * slice.events.unsubscribe('evento', id);
160
+ */
161
+ unsubscribe(eventName, subscriptionId) {
162
+ if (!this.subscriptions.has(eventName)) {
163
+ return false;
164
+ }
165
+
166
+ const removed = this.subscriptions.get(eventName).delete(subscriptionId);
167
+
168
+ // Limpiar Map vacío
169
+ if (this.subscriptions.get(eventName).size === 0) {
170
+ this.subscriptions.delete(eventName);
171
+ }
172
+
173
+ if (removed) {
174
+ slice.logger.logInfo('EventManager', `Desuscrito de "${eventName}" [${subscriptionId}]`);
175
+ }
176
+
177
+ return removed;
178
+ }
179
+
180
+ /**
181
+ * Emitir un evento
182
+ * @param {string} eventName - Nombre del evento
183
+ * @param {any} [data] - Datos a pasar a los callbacks
184
+ * @returns {void}
185
+ *
186
+ * @example
187
+ * slice.events.emit('user:login', { id: 123, name: 'Juan' });
188
+ * slice.events.emit('cart:cleared'); // Sin datos
189
+ */
190
+ emit(eventName, ...args) {
191
+ slice.logger.info('EventManager', `Emitting "${eventName}"`, args[0] ?? null);
192
+
193
+ // Solo grabamos el histórico si algún debugger está abierto
194
+ if (this._recording) {
195
+ this.emitHistory.push({ eventName, timestamp: Date.now() });
196
+ if (this.emitHistory.length > 500) this.emitHistory.shift();
197
+ this.emitCounts.set(eventName, (this.emitCounts.get(eventName) || 0) + 1);
198
+ }
199
+
200
+ if (!this.subscriptions.has(eventName)) {
201
+ return;
202
+ }
203
+
204
+ const toRemove = [];
205
+
206
+ for (const [subscriptionId, subscription] of this.subscriptions.get(eventName)) {
207
+ if (subscription.componentSliceId) {
208
+ if (!slice.controller.activeComponents.has(subscription.componentSliceId)) {
209
+ toRemove.push(subscriptionId);
210
+ continue;
211
+ }
212
+ }
213
+
214
+ try {
215
+ subscription.callback(...args);
216
+ } catch (error) {
217
+ slice.logger.error('EventManager', `Error in callback for "${eventName}" [${subscriptionId}]`, error);
218
+ }
219
+
220
+ // Si es subscribeOnce, marcar para eliminar
221
+ if (subscription.once) {
222
+ toRemove.push(subscriptionId);
223
+ }
224
+ }
225
+
226
+ // Limpiar suscripciones marcadas
227
+ toRemove.forEach((id) => {
228
+ this.subscriptions.get(eventName).delete(id);
229
+ });
230
+
231
+ // Limpiar Map vacío
232
+ if (this.subscriptions.get(eventName).size === 0) {
233
+ this.subscriptions.delete(eventName);
234
+ }
235
+ }
236
+
237
+ // ============================================
238
+ // BIND - Vinculación a Componente
239
+ // ============================================
240
+
241
+ /**
242
+ * Vincular el EventManager a un componente para auto-cleanup
243
+ * @param {HTMLElement} component - Componente Slice con sliceId
244
+ * @returns {EventManagerBind|null} API vinculada al componente
245
+ *
246
+ * @example
247
+ * class MiComponente extends HTMLElement {
248
+ * async init() {
249
+ * this.events = slice.events.bind(this);
250
+ *
251
+ * this.events.subscribe('user:login', (user) => {
252
+ * this.actualizar(user);
253
+ * });
254
+ * }
255
+ * }
256
+ */
257
+ bind(component) {
258
+ if (!component?.sliceId) {
259
+ slice.logger.logError('EventManager', 'bind() requiere un componente Slice válido con sliceId');
260
+ return null;
261
+ }
262
+
263
+ const self = this;
264
+
265
+ return {
266
+ /**
267
+ * Suscribirse a un evento (auto-cleanup)
268
+ */
269
+ subscribe: (eventName, callback) => {
270
+ return self.subscribe(eventName, callback, { component });
271
+ },
272
+
273
+ /**
274
+ * Suscribirse una sola vez (auto-cleanup)
275
+ */
276
+ subscribeOnce: (eventName, callback) => {
277
+ return self.subscribeOnce(eventName, callback, { component });
278
+ },
279
+
280
+ /**
281
+ * Emitir un evento
282
+ */
283
+ emit: (eventName, data) => {
284
+ self.emit(eventName, data);
285
+ },
286
+ };
287
+ }
288
+
289
+ // ============================================
290
+ // AUTO-CLEANUP
291
+ // ============================================
292
+
293
+ /**
294
+ * Registrar suscripción para un componente (interno)
295
+ */
296
+ _registerComponentSubscription(sliceId, eventName, subscriptionId) {
297
+ if (!this.componentSubscriptions.has(sliceId)) {
298
+ this.componentSubscriptions.set(sliceId, new Set());
299
+ }
300
+ this.componentSubscriptions.get(sliceId).add({ eventName, subscriptionId });
301
+ }
302
+
303
+ /**
304
+ * Limpiar todas las suscripciones de un componente
305
+ * Se llama automáticamente cuando el componente se destruye
306
+ * @param {string} sliceId - ID del componente
307
+ * @returns {number} Cantidad de suscripciones eliminadas
308
+ */
309
+ cleanupComponent(sliceId) {
310
+ if (!this.componentSubscriptions.has(sliceId)) {
311
+ return 0;
312
+ }
313
+
314
+ const subscriptions = this.componentSubscriptions.get(sliceId);
315
+ let count = 0;
316
+
317
+ for (const { eventName, subscriptionId } of subscriptions) {
318
+ if (this.unsubscribe(eventName, subscriptionId)) {
319
+ count++;
320
+ }
321
+ }
322
+
323
+ this.componentSubscriptions.delete(sliceId);
324
+
325
+ if (count > 0) {
326
+ slice.logger.logInfo('EventManager', `Limpiadas ${count} suscripción(es) de ${sliceId}`);
327
+ }
328
+
329
+ return count;
330
+ }
331
+
332
+ // ============================================
333
+ // UTILIDADES
334
+ // ============================================
335
+
336
+ /**
337
+ * Verificar si hay suscriptores para un evento
338
+ * @param {string} eventName - Nombre del evento
339
+ * @returns {boolean}
340
+ */
341
+ hasSubscribers(eventName) {
342
+ return this.subscriptions.has(eventName) && this.subscriptions.get(eventName).size > 0;
343
+ }
344
+
345
+ /**
346
+ * Obtener cantidad de suscriptores para un evento
347
+ * @param {string} eventName - Nombre del evento
348
+ * @returns {number}
349
+ */
350
+ subscriberCount(eventName) {
351
+ if (!this.subscriptions.has(eventName)) {
352
+ return 0;
353
+ }
354
+ return this.subscriptions.get(eventName).size;
355
+ }
356
+
357
+ /**
358
+ * Limpiar TODAS las suscripciones (usar con cuidado)
359
+ */
360
+ clear() {
361
+ this.subscriptions.clear();
362
+ this.componentSubscriptions.clear();
363
+ this.idCounter = 0;
364
+ slice.logger.logInfo('EventManager', 'Todas las suscripciones eliminadas');
365
+ }
366
+ }