All files / src/components lifecycle.js

35.96% Statements 187/520
100% Branches 3/3
5.71% Functions 2/35
35.96% Lines 187/520

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 5971x 1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x                                                   1x 1x 1x 1x       1x 1x 1x 1x                         1x 1x 1x 1x                                 1x 1x 1x 1x                           1x 1x 1x 1x                                       1x 1x 1x 1x                                   1x 1x 1x 1x                                                                                                         1x 1x 1x 1x         1x 1x 1x 1x         1x 1x 1x 1x                                             1x 1x 1x 1x         1x 1x 1x 1x                   1x           1x 1x 1x 1x                         1x   1x 1x 1x 1x 1x 3x 3x 3x   1x 1x 1x 1x                                               1x 1x 1x 1x                                                   1x 1x 1x 1x                                                 1x 1x 1x 1x                 1x 1x 1x 1x                                     1x 1x 1x 1x                                   1x 1x 1x 1x       1x 1x 1x 1x                         1x   1x 1x 1x 1x   1x 1x 1x 1x 3x   3x 27x           27x 3x   3x 3x   1x 1x 1x 1x   1x       1x       1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x   1x   1x 1x 1x 1x                 1x   1x 1x 1x 1x   1x   1x 1x 1x 1x   1x   1x 1x 1x 1x   1x   1x 1x 1x 1x       1x   1x 1x 1x 1x                                 1x
/**
 * Component Lifecycle System for Coherent.js
 * Provides hooks and events for component lifecycle management
 */
 
import { globalErrorHandler } from '../utils/error-handler.js';
import { ReactiveState } from '../state/reactive-state.js';
 
/**
 * Lifecycle phases
 */
export const LIFECYCLE_PHASES = {
    BEFORE_CREATE: 'beforeCreate',
    CREATED: 'created',
    BEFORE_MOUNT: 'beforeMount',
    MOUNTED: 'mounted',
    BEFORE_UPDATE: 'beforeUpdate',
    UPDATED: 'updated',
    BEFORE_UNMOUNT: 'beforeUnmount',
    UNMOUNTED: 'unmounted',
    ERROR: 'error'
};
 
/**
 * Component instance tracker
 */
const componentInstances = new WeakMap();
const componentRegistry = new Map();
 
/**
 * Component lifecycle manager
 */
export class ComponentLifecycle {
    constructor(component, options = {}) {
        this.component = component;
        this.id = this.generateId();
        this.options = options;
        this.phase = null;
        this.hooks = new Map();
        this.state = new ReactiveState();
        this.props = {};
        this.context = {};
        this.isMounted = false;
        this.isDestroyed = false;
        this.children = new Set();
        this.parent = null;
        this.eventHandlers = new Map();
        this.timers = new Set();
        this.subscriptions = new Set();
 
        // Register instance
        componentInstances.set(component, this);
        componentRegistry.set(this.id, this);
 
        // Initialize lifecycle
        this.executeHook(LIFECYCLE_PHASES.BEFORE_CREATE);
        this.executeHook(LIFECYCLE_PHASES.CREATED);
    }
 
    /**
     * Generate unique component ID
     */
    generateId() {
        return `comp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    }
 
    /**
     * Add lifecycle hook
     */
    hook(phase, callback) {
        if (typeof callback !== 'function') {
            throw new Error(`Hook callback must be a function for phase: ${phase}`);
        }
 
        if (!this.hooks.has(phase)) {
            this.hooks.set(phase, []);
        }
 
        this.hooks.get(phase).push(callback);
        return this;
    }
 
    /**
     * Execute hooks for a specific phase
     */
    async executeHook(phase, ...args) {
        if (this.isDestroyed) {
            return;
        }
 
        this.phase = phase;
        const hooks = this.hooks.get(phase) || [];
 
        for (const hook of hooks) {
            try {
                await hook.call(this, ...args);
            } catch (error) {
                this.handleError(error, phase);
            }
        }
    }
 
    /**
     * Handle component errors
     */
    handleError(error, phase) {
        const enhancedError = globalErrorHandler.handle(error, {
            component: this.component,
            context: {
                phase,
                componentId: this.id,
                props: this.props,
                state: this.state.toObject()
            }
        });
 
        this.executeHook(LIFECYCLE_PHASES.ERROR, enhancedError);
    }
 
    /**
     * Mount component
     */
    async mount(container, props = {}) {
        if (this.isMounted) {
            console.warn(`Component ${this.id} is already mounted`);
            return;
        }
 
        this.props = props;
        this.container = container;
 
        await this.executeHook(LIFECYCLE_PHASES.BEFORE_MOUNT, container, props);
 
        try {
            // Actual mounting logic would be handled by the renderer
            this.isMounted = true;
            await this.executeHook(LIFECYCLE_PHASES.MOUNTED, container);
        } catch (error) {
            this.handleError(error, 'mount');
        }
    }
 
    /**
     * Update component
     */
    async update(newProps = {}) {
        if (!this.isMounted || this.isDestroyed) {
            return;
        }
 
        const oldProps = this.props;
        this.props = { ...this.props, ...newProps };
 
        await this.executeHook(LIFECYCLE_PHASES.BEFORE_UPDATE, newProps, oldProps);
 
        try {
            // Update logic would be handled by the renderer
            await this.executeHook(LIFECYCLE_PHASES.UPDATED, this.props, oldProps);
        } catch (error) {
            this.handleError(error, 'update');
        }
    }
 
    /**
     * Unmount component
     */
    async unmount() {
        if (!this.isMounted || this.isDestroyed) {
            return;
        }
 
        await this.executeHook(LIFECYCLE_PHASES.BEFORE_UNMOUNT);
 
        try {
            // Cleanup children
            for (const child of this.children) {
                await child.unmount();
            }
 
            // Cleanup subscriptions
            this.subscriptions.forEach(unsub => {
                try {
                    unsub();
                } catch (error) {
                    console.warn('Error cleaning up subscription:', error);
                }
            });
 
            // Clear timers
            this.timers.forEach(timer => {
                clearTimeout(timer);
                clearInterval(timer);
            });
 
            // Remove event handlers
            this.eventHandlers.forEach((handler, element) => {
                handler.events.forEach((listeners, event) => {
                    listeners.forEach(listener => {
                        element.removeEventListener(event, listener);
                    });
                });
            });
 
            // Cleanup state
            this.state.destroy();
 
            this.isMounted = false;
            this.isDestroyed = true;
 
            await this.executeHook(LIFECYCLE_PHASES.UNMOUNTED);
 
            // Unregister
            componentRegistry.delete(this.id);
 
        } catch (error) {
            this.handleError(error, 'unmount');
        }
    }
 
    /**
     * Add child component
     */
    addChild(child) {
        child.parent = this;
        this.children.add(child);
    }
 
    /**
     * Remove child component
     */
    removeChild(child) {
        child.parent = null;
        this.children.delete(child);
    }
 
    /**
     * Add event listener with automatic cleanup
     */
    addEventListener(element, event, listener, options = {}) {
        if (!this.eventHandlers.has(element)) {
            this.eventHandlers.set(element, {
                events: new Map()
            });
        }
 
        const handler = this.eventHandlers.get(element);
        
        if (!handler.events.has(event)) {
            handler.events.set(event, new Set());
        }
 
        handler.events.get(event).add(listener);
        element.addEventListener(event, listener, options);
 
        // Return cleanup function
        return () => {
            handler.events.get(event).delete(listener);
            element.removeEventListener(event, listener);
        };
    }
 
    /**
     * Add subscription with automatic cleanup
     */
    addSubscription(unsubscribe) {
        this.subscriptions.add(unsubscribe);
        return unsubscribe;
    }
 
    /**
     * Set timer with automatic cleanup
     */
    setTimeout(callback, delay) {
        const timer = setTimeout(() => {
            this.timers.delete(timer);
            callback();
        }, delay);
 
        this.timers.add(timer);
        return timer;
    }
 
    setInterval(callback, interval) {
        const timer = setInterval(callback, interval);
        this.timers.add(timer);
        return timer;
    }
 
    /**
     * Get component statistics
     */
    getStats() {
        return {
            id: this.id,
            phase: this.phase,
            isMounted: this.isMounted,
            isDestroyed: this.isDestroyed,
            childCount: this.children.size,
            eventHandlers: this.eventHandlers.size,
            subscriptions: this.subscriptions.size,
            timers: this.timers.size,
            state: this.state.getStats()
        };
    }
}
 
/**
 * Event system for components
 */
export class ComponentEventSystem {
    constructor() {
        this.events = new Map();
        this.globalHandlers = new Map();
    }
 
    /**
     * Emit event to component or globally
     */
    emit(eventName, data = {}, target = null) {
        const event = {
            name: eventName,
            data,
            target,
            timestamp: Date.now(),
            stopped: false,
            preventDefault: false
        };
 
        // Target specific component
        if (target) {
            const instance = componentInstances.get(target);
            if (instance) {
                this._notifyHandlers(instance.id, event);
            }
        } else {
            // Global event
            this._notifyGlobalHandlers(event);
        }
 
        return event;
    }
 
    /**
     * Listen for events on component or globally
     */
    on(eventName, handler, componentId = null) {
        if (componentId) {
            // Component-specific event
            if (!this.events.has(componentId)) {
                this.events.set(componentId, new Map());
            }
            
            const componentEvents = this.events.get(componentId);
            if (!componentEvents.has(eventName)) {
                componentEvents.set(eventName, new Set());
            }
            
            componentEvents.get(eventName).add(handler);
        } else {
            // Global event
            if (!this.globalHandlers.has(eventName)) {
                this.globalHandlers.set(eventName, new Set());
            }
            
            this.globalHandlers.get(eventName).add(handler);
        }
 
        // Return unsubscribe function
        return () => this.off(eventName, handler, componentId);
    }
 
    /**
     * Remove event handler
     */
    off(eventName, handler, componentId = null) {
        if (componentId) {
            const componentEvents = this.events.get(componentId);
            if (componentEvents && componentEvents.has(eventName)) {
                componentEvents.get(eventName).delete(handler);
                
                // Cleanup empty sets
                if (componentEvents.get(eventName).size === 0) {
                    componentEvents.delete(eventName);
                    if (componentEvents.size === 0) {
                        this.events.delete(componentId);
                    }
                }
            }
        } else {
            const handlers = this.globalHandlers.get(eventName);
            if (handlers) {
                handlers.delete(handler);
                if (handlers.size === 0) {
                    this.globalHandlers.delete(eventName);
                }
            }
        }
    }
 
    /**
     * Listen once
     */
    once(eventName, handler, componentId = null) {
        const onceHandler = (event) => {
            handler(event);
            this.off(eventName, onceHandler, componentId);
        };
 
        return this.on(eventName, onceHandler, componentId);
    }
 
    /**
     * Notify component handlers
     */
    _notifyHandlers(componentId, event) {
        const componentEvents = this.events.get(componentId);
        if (componentEvents && componentEvents.has(event.name)) {
            const handlers = componentEvents.get(event.name);
            for (const handler of handlers) {
                if (event.stopped) break;
                
                try {
                    handler(event);
                } catch (error) {
                    globalErrorHandler.handle(error, {
                        type: 'event-handler-error',
                        context: { event, handler: handler.toString() }
                    });
                }
            }
        }
    }
 
    /**
     * Notify global handlers
     */
    _notifyGlobalHandlers(event) {
        const handlers = this.globalHandlers.get(event.name);
        if (handlers) {
            for (const handler of handlers) {
                if (event.stopped) break;
                
                try {
                    handler(event);
                } catch (error) {
                    globalErrorHandler.handle(error, {
                        type: 'global-event-handler-error',
                        context: { event, handler: handler.toString() }
                    });
                }
            }
        }
    }
 
    /**
     * Clean up events for a component
     */
    cleanup(componentId) {
        this.events.delete(componentId);
    }
 
    /**
     * Get event statistics
     */
    getStats() {
        return {
            componentEvents: this.events.size,
            globalEvents: this.globalHandlers.size,
            totalHandlers: Array.from(this.events.values()).reduce((sum, events) => {
                return sum + Array.from(events.values()).reduce((eventSum, handlers) => {
                    return eventSum + handlers.size;
                }, 0);
            }, 0) + Array.from(this.globalHandlers.values()).reduce((sum, handlers) => {
                return sum + handlers.size;
            }, 0)
        };
    }
}
 
/**
 * Global event system instance
 */
export const eventSystem = new ComponentEventSystem();
 
/**
 * Lifecycle hooks factory
 */
export function createLifecycleHooks() {
    const hooks = {};
 
    Object.values(LIFECYCLE_PHASES).forEach(phase => {
        hooks[phase] = (callback) => {
            // This would be called during component creation
            const instance = getCurrentInstance();
            if (instance) {
                instance.hook(phase, callback);
            }
        };
    });
 
    return hooks;
}
 
/**
 * Get current component instance (context-based)
 */
let currentInstance = null;
 
export function getCurrentInstance() {
    return currentInstance;
}
 
export function setCurrentInstance(instance) {
    currentInstance = instance;
}
 
/**
 * Lifecycle hooks for direct use
 */
export const useHooks = createLifecycleHooks();
 
/**
 * Utility functions for component management
 */
export const componentUtils = {
    /**
     * Get component lifecycle instance
     */
    getLifecycle(component) {
        return componentInstances.get(component);
    },
 
    /**
     * Create component with lifecycle
     */
    createWithLifecycle(component, options = {}) {
        const lifecycle = new ComponentLifecycle(component, options);
        return {
            component,
            lifecycle,
            mount: lifecycle.mount.bind(lifecycle),
            unmount: lifecycle.unmount.bind(lifecycle),
            update: lifecycle.update.bind(lifecycle)
        };
    },
 
    /**
     * Get all component instances
     */
    getAllInstances() {
        return Array.from(componentRegistry.values());
    },
 
    /**
     * Find component by ID
     */
    findById(id) {
        return componentRegistry.get(id);
    },
 
    /**
     * Emit event to component
     */
    emit(component, eventName, data) {
        return eventSystem.emit(eventName, data, component);
    },
 
    /**
     * Listen to component events
     */
    listen(component, eventName, handler) {
        const lifecycle = componentInstances.get(component);
        return eventSystem.on(eventName, handler, lifecycle?.id);
    }
};
 
/**
 * Component decorator for automatic lifecycle management
 */
export function withLifecycle(component, options = {}) {
    return function LifecycleComponent(props = {}) {
        const instance = componentUtils.getLifecycle(component);
        
        if (!instance) {
            const lifecycle = new ComponentLifecycle(component, options);
            setCurrentInstance(lifecycle);
        }
 
        const result = typeof component === 'function' ? component(props) : component;
        
        setCurrentInstance(null);
        
        return result;
    };
}
 
export default ComponentLifecycle;