UNPKG

uhtml-ssr

Version:

uhtml for Service Worker, Web Worker, NodeJS, and other SSR cases

49 lines (39 loc) 1.02 kB
import {MapSet, WeakMapSet} from '@webreflection/mapset'; import {render as $render, html, svg} from './index.js'; // Sender (SW, Worker, postMessage) const ids = new WeakMapSet; let id = 0; const tag = type => (template, ...values) => ({ id: ids.get(template) || ids.set(template, id++), type, values, template }); html.json = tag('html'); svg.json = tag('svg'); // Receiver (onmessage, from SW, Workers, etc) const templates = new MapSet; const unroll = ({type, template, values, id}) => ( (type === 'svg' ? svg : html).apply( null, [ templates.get(id) || templates.set(id, template) ].concat(values.map(asJSON)) ) ); const asJSON = value => isJSON(value) ? unroll(value) : value; const isJSON = thing => ( typeof thing === 'object' && thing !== null && 'id' in thing && 'type' in thing && 'values' in thing && 'template' in thing ); const render = (where, what) => $render( where, isJSON(what) ? unroll(what) : what ); export {render, html, svg};