UNPKG

@muban/template

Version:

Writing templates for Muban components during development

60 lines (59 loc) 2.41 kB
"use strict"; 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)); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.html = exports.processFalsyBooleanProps = void 0; /* eslint-disable @typescript-eslint/no-explicit-any */ var htm_1 = __importDefault(require("htm")); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore var vhtml_1 = __importDefault(require("vhtml")); /** * Function to turn falsy boolean prop values to the string 'false' */ 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]; })); } exports.processFalsyBooleanProps = processFalsyBooleanProps; /** * 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 (0, vhtml_1.default)(type, processedProps, children); } // the template tag to render HTML strings in muban templates var html = function (strings) { var values = []; for (var _i = 1; _i < arguments.length; _i++) { values[_i - 1] = arguments[_i]; } try { return htm_1.default.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('${}'))); } }; exports.html = html;