All files / core/src shadow-dom.js

84.09% Statements 74/88
80.64% Branches 75/93
90.9% Functions 10/11
85% Lines 68/80

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              17x 15x   14x           13x 1x     12x           13x 13x 6x 6x 6x       12x 12x   12x         12x     39x   38x 10x 10x     28x 27x 7x 20x 20x 9x           12x 12x           39x   38x 10x     28x 28x   27x   20x 20x 20x 9x   20x           28x     12x       12x         39x 38x     38x 10x     28x     28x         28x 20x 20x     20x 3x   3x 3x 3x       20x     20x         20x 20x 11x 9x 9x     20x             8x       14x                 14x 14x 14x                                        
/**
 * Shadow DOM Component System for Coherent.js
 * Provides true style encapsulation using native Shadow DOM
 */
 
// Check if Shadow DOM is supported
export function isShadowDOMSupported() {
  if (typeof window === 'undefined') return false;
  if (typeof window.Element === 'undefined') return false;
  
  return 'attachShadow' in window.Element.prototype && 
         'getRootNode' in window.Element.prototype;
}
 
// Create a Shadow DOM component
export function createShadowComponent(element, componentDef, options = {}) {
  if (!isShadowDOMSupported()) {
    throw new Error('Shadow DOM is not supported in this environment');
  }
  
  const shadowRoot = element.attachShadow({ 
    mode: options.mode || 'closed',
    delegatesFocus: options.delegatesFocus || false
  });
  
  // Extract and inject styles
  const styles = extractStyles(componentDef);
  if (styles && typeof window !== 'undefined' && window.document) {
    const styleElement = window.document.createElement('style');
    styleElement.textContent = styles;
    shadowRoot.appendChild(styleElement);
  }
  
  // Render component content
  const content = renderToShadowDOM(componentDef);
  shadowRoot.innerHTML += content;
  
  return shadowRoot;
}
 
// Extract CSS from component definition
function extractStyles(componentDef) {
  let allStyles = '';
  
  function extractFromElement(element) {
    if (!element || typeof element !== 'object') return;
    
    if (Array.isArray(element)) {
      element.forEach(extractFromElement);
      return;
    }
    
    for (const [tagName, props] of Object.entries(element)) {
      if (tagName === 'style' && typeof props === 'object' && props.text) {
        allStyles += `${props.text  }\n`;
      } else Eif (typeof props === 'object' && props !== null) {
        if (props.children) {
          extractFromElement(props.children);
        }
      }
    }
  }
  
  extractFromElement(componentDef);
  return allStyles;
}
 
// Render component content for Shadow DOM (without style tags)
function renderToShadowDOM(componentDef) {
  function stripStyles(element) {
    if (!element || typeof element !== 'object') return element;
    
    if (Array.isArray(element)) {
      return element.map(stripStyles);
    }
    
    const result = {};
    for (const [tagName, props] of Object.entries(element)) {
      // Skip style elements - they're handled separately
      if (tagName === 'style') continue;
      
      if (typeof props === 'object' && props !== null) {
        const cleanProps = { ...props };
        if (cleanProps.children) {
          cleanProps.children = stripStyles(cleanProps.children);
        }
        result[tagName] = cleanProps;
      } else E{
        result[tagName] = props;
      }
    }
    
    return result;
  }
  
  const cleanComponent = stripStyles(componentDef);
  
  // Import renderRaw from main module (avoiding circular deps)
  // This would need to be properly imported in real usage
  return renderComponentContent(cleanComponent);
}
 
// Simple DOM-based rendering for Shadow DOM content
function renderComponentContent(obj) {
  if (obj === null || obj === undefined) return '';
  Iif (typeof obj === 'string' || typeof obj === 'number') {
    return escapeHTML(String(obj));
  }
  if (Array.isArray(obj)) {
    return obj.map(renderComponentContent).join('');
  }
  
  Iif (typeof obj !== 'object') return escapeHTML(String(obj));
 
  // Handle text content
  Iif (obj.text !== undefined) {
    return escapeHTML(String(obj.text));
  }
 
  // Handle HTML elements
  for (const [tagName, props] of Object.entries(obj)) {
    if (typeof props === 'object' && props !== null) {
      const { children, text, ...attributes } = props;
      
      // Build attributes string
      const attrsStr = Object.entries(attributes)
        .filter(([, value]) => value !== null && value !== undefined && value !== false)
        .map(([key, value]) => {
          const attrName = key === 'className' ? 'class' : key;
          Iif (value === true) return attrName;
          return `${attrName}="${escapeHTML(String(value))}"`;
        })
        .join(' ');
      
      const openTag = attrsStr ? `<${tagName} ${attrsStr}>` : `<${tagName}>`;
      
      // Handle void elements
      Iif (['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
           'link', 'meta', 'param', 'source', 'track', 'wbr'].includes(tagName)) {
        return openTag.replace('>', ' />');
      }
      
      let content = '';
      if (text !== undefined) {
        content = escapeHTML(String(text));
      } else Eif (children) {
        content = renderComponentContent(children);
      }
      
      return `${openTag}${content}</${tagName}>`;
    } else Eif (typeof props === 'string') {
      const content = escapeHTML(props);
      return `<${tagName}>${content}</${tagName}>`;
    }
  }
 
  return '';
}
 
function escapeHTML(text) {
  Iif (typeof window === 'undefined' || !window.document) {
    // Server-side fallback
    return String(text)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;');
  }
  const div = window.document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}
 
// Hybrid rendering: Shadow DOM on client, scoped on server
export function renderWithBestEncapsulation(componentDef, containerElement = null) {
  if (isShadowDOMSupported() && containerElement) {
    // Use Shadow DOM for true isolation
    return createShadowComponent(containerElement, componentDef);
  } else {
    // Fallback to scoped rendering
    // This would import from main module in real usage
    console.warn('Shadow DOM not available, falling back to scoped rendering');
    return null; // Would return scoped render result
  }
}
 
export default {
  isShadowDOMSupported,
  createShadowComponent,
  renderWithBestEncapsulation
};