UNPKG

ziggurat.js

Version:

a tiny modular js library for templates and other shorthands

8 lines (7 loc) 2.56 kB
var zg;if(typeof HTML=="undefined"||HTML===null)throw new Error("can't find HTML. did you forget to import imperative-html?");zg={},zg.query=function(e){var t=document.querySelectorAll(e);return t.length===1?t[0]:t},zg.queryone=function(e){return document.querySelector(e)},zg.queryall=function(e){return document.querySelectorAll(e)},zg.deepfind=function(e,t){var n,s,o,i,a;t=t.trim(),o=function(){var e,n,o=t.split("."),i=[];for(e=0,n=o.length;e<n;e++)s=o[e],s!==""&&i.push(s);return i}();for(n=0,a=o.length;n<a;n++)if(i=o[n],e=e[i],e==null)throw new Error(`'${t}' not in data '${e}'`);return e} var element,fn_name,i,len,ref;zg.formdata=function(e){var t={};return new FormData(e).forEach(function(n,s){return Object.defineProperty(t,s,{get:function(){return e[s].value},set:function(t){return e[s].value=t}})}),t},ref=zg.queryall("form[zg-submit]");for(i=0,len=ref.length;i<len;i++)element=ref[i],fn_name=element.getAttribute("zg-submit"),element.onsubmit=function(e){var t;try{window[fn_name](zg.formdata(element))}catch(e){t=e,console.error(t)}return e.preventDefault,!1} zg.mirror=class{constructor(e,t){this.name=e,Object.defineProperty(this,"v",{get:function(){return this._value},set:function(e){var t,n,s,o,i;this._value=e,n=zg.queryall(`zg-bind[name=${this.name}]`),s=[];for(t=0,i=n.length;t<i;t++)o=n[t],s.push(o.innerText=this._value);return s}}),this.v=t}} zg.create=function(e,t){var n,s=zg.queryone("zg-template#"+e);if(s==null)throw new TypeError("no such template with name "+e);return n=function(e,t){var s,o,i,c=e.cloneNode(!0),a=[],r=c.childNodes;for(o=0,i=r.length;o<i;o++){switch(s=r[o],s.nodeName.toLowerCase()){case"zg-var":s=document.createTextNode(zg.deepfind(t,s.innerHTML))}s.children!=null&&s.replaceChildren(...n(s,t)),a.push(s)}return a},HTML.div(n(s,t))} zg.stream={},zg.HttpException=class HttpException extends Error{constructor(e){super(`Recieved code ${e} from server`),this.status=e}},zg.stream.text=async function*(e,t){if(n=await fetch(e,t),!n.ok)throw new zg.HttpException(n.statusCode);for(var n,s,o,a=n.body.getReader(),i=new TextDecoder;!0;)if(o=await a.read(),s=i.decode(o.value),s.length>0&&(yield s),o.done)return},zg.stream.lines=async function*(e,t){var n,s,o,a,r,c,i="",l=zg.stream.text(e,t);for await(r of l)i+=r,n=i.split(` `),n.length>1&&(yield n[0],n=n.slice(1),i=n.join(` `));o=[];for(s=0,c=n.length;s<c;s++)a=n[s],a.length>0?o.push(yield a):o.push(void 0);return o},zg.stream.jsonl=async function*(e,t){var n,o=zg.stream.lines(e,t),s=[];for await(n of o)try{s.push(yield JSON.parse(n))}catch{}return s}