All files / src/rendering dom-renderer.js

63.45% Statements 158/249
51.51% Branches 17/33
54.54% Functions 6/11
63.45% Lines 158/249

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 2881x 1x 1x 1x 1x 1x                       1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   5x 5x 5x 5x 5x 5x   1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x             7x 7x 7x 7x         7x   1x 1x 1x 1x 10x 10x 10x   10x 10x       10x       10x       10x           10x                       10x 10x 10x   1x 1x 1x 1x 10x       10x 10x 10x 10x 10x 10x   10x   1x 1x 1x 1x 10x 10x 10x 10x   10x 10x   10x 10x 3x 3x 3x   10x 10x 2x 2x 2x 3x 3x 3x 3x 2x 2x           2x   10x 10x   1x 1x 1x 1x 10x   10x   10x 10x 5x 5x   10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 2x 2x 2x 1x 1x 1x 1x 2x     10x 10x   1x 1x 1x 1x                                                                       1x 1x 1x 1x                 1x 1x 1x 1x             1x   1x 1x 1x 1x         1x 1x 1x 1x        
/**
 * DOM Renderer for Coherent.js
 * 
 * Provides client-side DOM rendering with hydration support.
 * Extends BaseRenderer for shared functionality.
 */
 
import { BaseRenderer } from './base-renderer.js';
import { 
    isCoherentObject,
    hasChildren,
    getChildren
} from '../core/object-utils.js';
import { VDOMDiffer } from './vdom-diff.js';
 
 
 
/**
 * DOM Renderer class - extends BaseRenderer for shared functionality
 */
export class DOMRenderer extends BaseRenderer {
    constructor(options = {}) {
        // Call parent constructor with DOM-specific defaults
        super({
            enableHydration: true,
            maxDepth: 100, // Lower depth for DOM rendering
            enableVDOMDiff: options.enableVDOMDiff !== false, // Enable VDOM diffing by default
            ...options
        });
        
        // Set up utilities for easy access
        this.utils = {
            isCoherentObject,
            hasChildren,
            getChildren
        };
 
        // Initialize virtual DOM differ for efficient updates
        if (this.config.enableVDOMDiff) {
            this.vdomDiffer = new VDOMDiffer();
            this.componentCache = new Map(); // Cache previous component states
        }
    }
 
    /**
     * Render component to DOM element
     */
    render(component, container = null) {
        this.resetMetrics();
        this.metrics.startTime = performance.now();
        
        try {
            const element = this.renderComponent(component, {}, 0);
            
            if (container && element) {
                // Clear container first if hydration is disabled
                if (!this.config.enableHydration) {
                    container.replaceChildren();
                }
                container.appendChild(element);
            }
            
            this.metrics.endTime = performance.now();
            return element;
        } catch (error) {
            this.recordError('render', error);
            console.error('Error rendering to DOM:', error);
            throw error;
        }
    }
 
    /**
     * Render component to DOM element (overrides BaseRenderer method)
     */
    renderComponent(component, options = {}, depth = 0) {
        // Use parent validation
        this.validateDepth(depth);
        this.metrics.elementsProcessed++;
 
        // Handle different component types
        if (component === null || component === undefined) {
            return document.createTextNode('');
        }
 
        if (typeof component === 'string') {
            return document.createTextNode(component);
        }
 
        if (typeof component === 'number' || typeof component === 'boolean') {
            return document.createTextNode(String(component));
        }
 
        if (typeof component === 'function') {
            // Execute function components using parent method
            const result = this.executeFunctionComponent(component, depth);
            return this.renderComponent(result, options, depth + 1);
        }
 
        if (Array.isArray(component)) {
            // Create a fragment for multiple elements
            const fragment = document.createDocumentFragment();
            component.forEach(child => {
                const childElement = this.renderComponent(child, options, depth + 1);
                if (childElement) {
                    fragment.appendChild(childElement);
                }
            });
            return fragment;
        }
 
        // Handle object-based components
        return this.renderObjectElement(component, depth);
    }
 
    /**
     * Render object-based element to DOM
     */
    renderObjectElement(component, depth) {
        if (!this.utils.isCoherentObject(component)) {
            return document.createTextNode(''); // Skip invalid objects
        }
 
        // Process object-based component (expects single element)
        const entries = Object.entries(component);
        if (entries.length > 0) {
            const [tagName, props] = entries[0];
            return this.renderDOMElement(tagName, props, depth + 1);
        }
        return document.createTextNode('');
    }
 
    /**
     * Render a single DOM element
     */
    renderDOMElement(tagName, props, depth) {
        // Create element with namespace support
        const element = this.config.namespace 
            ? document.createElementNS(this.config.namespace, tagName)
            : document.createElement(tagName);
 
        // Set attributes
        this.setDOMAttributes(element, props);
 
        // Handle text content
        if (props && props.text !== undefined) {
            const text = typeof props.text === 'function' ? props.text() : props.text;
            element.textContent = String(text);
        }
 
        // Handle children
        if (props && this.utils.hasChildren(props)) {
            const children = this.utils.getChildren(props);
            if (Array.isArray(children)) {
                children.forEach(child => {
                    const childElement = this.renderComponent(child, {}, depth + 1);
                    if (childElement) {
                        element.appendChild(childElement);
                    }
                });
            } else if (children) {
                const childElement = this.renderComponent(children, {}, depth + 1);
                if (childElement) {
                    element.appendChild(childElement);
                }
            }
        }
 
        return element;
    }
 
    /**
     * Set DOM attributes from props
     */
    setDOMAttributes(element, props) {
        if (!props || typeof props !== 'object') return;
 
        const skipProps = ['text', 'children'];
 
        for (const [key, value] of Object.entries(props)) {
            if (skipProps.includes(key) || value === undefined || value === null) {
                continue;
            }
 
            if (typeof value === 'function') {
                // Handle event listeners
                if (key.startsWith('on')) {
                    // Normalize DOM event names to lowercase (e.g., onClick -> 'click')
                    const eventType = key.slice(2).toLowerCase();
                    // Store listener reference for potential cleanup
                    element.addEventListener(eventType, value);
                    element._listeners = element._listeners || [];
                    element._listeners.push({ type: eventType, handler: value });
                }
                continue;
            }
            if (key === 'class' || key === 'className') {
                element.className = String(value);
            } else if (typeof value === 'boolean') {
                if (value) {
                    element.setAttribute(key, '');
                } else {
                    element.removeAttribute(key);
                }
            } else {
                element.setAttribute(key, String(value));
            }
        }
    }
 
    /**
     * Update existing DOM element with new component using virtual DOM diffing
     */
    update(element, newComponent, componentId = 'default') {
        if (!this.config.enableVDOMDiff || !this.vdomDiffer) {
            // Fallback to full re-render
            return this.render(newComponent, element.parentNode);
        }
 
        const oldComponent = this.componentCache.get(componentId);
        
        if (!oldComponent) {
            // First render, cache the component and render normally
            this.componentCache.set(componentId, newComponent);
            return this.render(newComponent, element.parentNode);
        }
 
        // Perform virtual DOM diffing
        try {
            const patchCount = this.vdomDiffer.update(element, oldComponent, newComponent);
            
            // Update cache with new component
            this.componentCache.set(componentId, newComponent);
            
            // Log performance metrics
            if (this.config.enableMonitoring) {
                this.metrics.patchesApplied = (this.metrics.patchesApplied || 0) + patchCount;
            }
            
            return element;
        } catch (error) {
            console.warn('VDOM diffing failed, falling back to full re-render:', error);
            // Clear corrupted cache entry
            this.componentCache.delete(componentId);
            // Fall back to full re-render
            return this.render(newComponent, element.parentNode);
        }
    }
 
    /**
     * Clear component cache (useful for development or memory management)
     */
    clearCache() {
        if (this.componentCache) {
            this.componentCache.clear();
        }
        if (this.vdomDiffer) {
            this.vdomDiffer.clearCache();
        }
    }
 
    /**
     * Get cache statistics
     */
    getCacheStats() {
        return {
            componentsCached: this.componentCache ? this.componentCache.size : 0,
            vdomCached: this.vdomDiffer ? this.vdomDiffer.cache.size : 0,
            patchesApplied: this.metrics.patchesApplied || 0
        };
    }
}
 
/**
 * Main DOM render function - converts object components to DOM elements
 */
export function renderToDOM(component, container = null, options = {}) {
    const renderer = new DOMRenderer(options);
    return renderer.render(component, container);
}
 
/**
 * Update DOM element with new component using virtual DOM diffing
 */
export function updateDOM(element, newComponent, componentId, options = {}) {
    const renderer = new DOMRenderer(options);
    return renderer.update(element, newComponent, componentId);
}