Wavy - View layer based on the Wave Architecture

by Julien Etienne

JavaScript

/*
 This is a quick and dirty implementation of a wave based view layer.
 
 * Name components using a hash followed by the component name.

 * You will be returned with just those selectors. 

 * If you do not provide a component name you will be returned with the entire element.
 
 * If you need to avoid hashes in text, use # 
*/

const wavy = (value, useData) => {
  const hashedSelectors = value.match(/ #\w+/g).map(value => value.slice(1)) || [];
  const markup = hashedSelectors.reduce((acc, value) => {
    acc = acc.replace(value, 'data-' + value.slice(1));
    return acc;
  }, value);
  const panel = document.createRange().createContextualFragment(markup);
  const selectors = hashedSelectors.reduce((acc,selector) => {
    const element = panel.querySelector('[data-' + selector.slice(1) + ']');
    const selectorName = selector.slice(1);
    if (!useData) {
      element.removeAttribute('data-' + selectorName);
    }
    acc[selectorName] = element;
    return acc;
  },{});
	return Object.keys(selectors).length > 0 ? selectors : panel.firstElementChild;
}

const element = wavy(`
	<div #component>
  	<h1 #greeting >Hello world</h1>
    <span>How are you &#35;sir</span>
  </div>
`);

const {component} = element;
document.body.appendChild(component)
console.log(element)