UNPKG

hmpl-dom

Version:

A module for using HMPL syntax directly in HTML, without the need for compilation on the JavaScript side

1 lines 2.02 kB
!function(t,e){"object"==typeof module&&module.exports?module.exports=e():"function"==typeof define&&define.amd?define([],e):t.hmplDOM=t.hmplDOM||e()}("undefined"!=typeof self?self:this,(function(){return function(){"use strict";const t="InitError",e="TemplateError",n="data-hmpl",o="hmpl",i="data-config-id",r="configId",a=t=>{throw new Error(t)},l=t=>"object"==typeof t&&!Array.isArray(t)&&null!==t,s=e=>{l(e)||a(`${t}: HMPLTemplateConfig must be an object`),e.hasOwnProperty("id")&&e.hasOwnProperty("value")||a(`${t}: Missing "id" or "value" property`),"string"!=typeof e.id&&a(`${t}: ID must be a string`),l(e.value)||a(`${t}: Value must be an object`)};let c=!1;const u=new Map,d=t=>{"complete"===document.readyState||"interactive"===document.readyState?t():document.addEventListener("DOMContentLoaded",t)},p=()=>{const t=document.querySelectorAll(`template[${n}], template[${o}]`);for(let l=0;l<t.length;l++){const s=t[l],c=s.hasAttribute(n),d=s.hasAttribute(o);c&&d&&a(`${e}: Cannot use both ${n} and ${o} attributes`);const p=s.hasAttribute(i),m=s.hasAttribute(r);p&&m&&a(`${e}: Cannot use both ${i} and ${r} attributes`);const h=s.getAttribute(i)||s.getAttribute(r);let f;""===h&&a(`${e}: configId cannot be empty. Use ${i} or ${r} attribute`),h&&(f=u.get(h),f||a(`${e}: Option with id "${h}" not found. Make sure to define it in init() call`));const $=s.innerHTML;s.content.children.length>1&&a(`${e}: Template must contain exactly one root element, found ${s.content.children.length}`),0===s.content.children.length&&a(`${e}: Template must contain at least one element`);const b=f?.value.compile||{},y=f?.value.templateFunction||{},g=hmpl.compile($,b)(y);g&&g.response&&s.replaceWith(g.response)}};queueMicrotask((()=>{c||d(p)}));return{init:(e=[])=>{c&&a(`${t}: init() can only be called once`),c=!0,(e=>{const n=[];for(let o=0;o<e.length;o++){const i=e[o].id;n.indexOf(i)>-1?a(`${t}: ID with value "${i}" already exists`):n.push(i)}})(e);for(let t=0;t<e.length;t++){const n=e[t];s(n),u.set(n.id,n)}d(p)}}}()}));