All files describeReactElement.js

100% Statements 19/19
100% Branches 11/11
100% Functions 4/4
100% Lines 17/17
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        16x   16x 1x     15x 14x   13x   13x 13x 11x     13x   13x 5x 5x 9x 9x   5x           8x        
import propertiesForElement from './propertiesForElement';
import flatten from 'array-flatten';
 
function describeReactElement(element, indentation = 0) {
  const indention = ' '.repeat(indentation * 2);
 
  if (typeof(element) === 'string') {
    return `${indention}${element}`;
  }
 
  if (typeof(element) === 'undefined') { return; }
  if (element === false) { return; }
 
  const elementName = element.type.name || element.type;
 
  const {children: elementChildren, ...elementProperties} = propertiesForElement(element);
  const properties = Object.keys(elementProperties).map((key) => {
    return `${key}='${elementProperties[key]}'`;
  });
 
  const tagIntroduction = [elementName, ...properties].join(' ');
 
  if (elementChildren) {
    const children = flatten([elementChildren]);
    const childDescriptions = children.map((childElement) => {
      return describeReactElement(childElement, indentation + 1);      
    }).filter((description) => typeof(description) === 'string');
 
    return [
      `${indention}<${tagIntroduction}>`,
      ...childDescriptions,
      `${indention}</${elementName}>`
    ].join("\n");
  } else {
    return `${indention}<${tagIntroduction} />`;
  }
}
 
export default describeReactElement;