UNPKG

@muban/template

Version:

Writing templates for Muban components during development

52 lines (51 loc) 2 kB
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; /* eslint-disable @typescript-eslint/no-explicit-any */ import htm from 'htm'; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore import vhtml from 'vhtml'; /** * Function to turn falsy boolean prop values to the string 'false' */ export function processFalsyBooleanProps(props) { if (props === null) return props; return Object.fromEntries(Object.entries(props).map(function (_a) { var key = _a[0], value = _a[1]; return [key, value === false && key.includes('data-') ? 'false' : value]; })); } /** * Proxy function between html and vhtml to modify the DOM structure */ function h(type, props) { var children = []; for (var _i = 2; _i < arguments.length; _i++) { children[_i - 2] = arguments[_i]; } // If more prop modifier functions like processFalsyBooleanProps are added we could pipe them here var processedProps = processFalsyBooleanProps(props); return vhtml(type, processedProps, children); } // the template tag to render HTML strings in muban templates export var html = function (strings) { var values = []; for (var _i = 1; _i < arguments.length; _i++) { values[_i - 1] = arguments[_i]; } try { return htm.bind(h).apply(void 0, __spreadArray([strings], values, false)); } catch (e) { // throw a custom error message, since the built-in html parse errors are not useful at all throw new Error("Error parsing muban template. Most likely, your html template is malformed.\n\nThe template that gave the error is:\n".concat(strings.join('${}'))); } };