UNPKG

@substrate-system/image

Version:
31 lines (29 loc) 11.8 kB
var w=Object.defineProperty;var b=(a,c,e)=>c in a?w(a,c,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[c]=e;var d=(a,c,e)=>(b(a,typeof c!="symbol"?c+"":c,e),e);(function(){const c=document.createElement("link").relList;if(c&&c.supports&&c.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))t(i);new MutationObserver(i=>{for(const n of i)if(n.type==="childList")for(const o of n.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&t(o)}).observe(document,{childList:!0,subtree:!0});function e(i){const n={};return i.integrity&&(n.integrity=i.integrity),i.referrerPolicy&&(n.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?n.credentials="include":i.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function t(i){if(i.ep)return;i.ep=!0;const n=e(i);fetch(i.href,n)}})();class f{constructor(c,e,t){this.isTonicTemplate=!0,this.unsafe=t,this.rawText=c,this.templateStrings=e}valueOf(){return this.rawText}toString(){return this.rawText}}const s=class s extends window.HTMLElement{constructor(){super();d(this,"elements");d(this,"nodes");d(this,"_props",s.getPropertyNames(this));const e=s._states[super.id];delete s._states[super.id],this._state=e||{},this.preventRenderOnReconnect=!1,this.props={},this.elements=[...this.children],this.elements.__children__=!0,this.nodes=[...this.childNodes],this.nodes.__children__=!0,this._events()}static get version(){return"15.4.14"}static get SPREAD(){return/\.\.\.\s?(__\w+__\w+__)/g}static get ESC(){return/["&'<>`/]/g}static get AsyncFunctionGenerator(){return(async function*(){}).constructor}static get AsyncFunction(){return(async function(){}).constructor}static get MAP(){return{'"':"&quot;","&":"&amp;","'":"&#x27;","<":"&lt;",">":"&gt;","`":"&#x60;","/":"&#x2F;"}}render(){throw new Error("Must be implemented by an instance")}get isTonicComponent(){return!0}static get tag(){return s.getTagName(this.name)}static _createId(){return`tonic${s._index++}`}static _normalizeAttrs(e,t={}){return[...e].forEach(i=>t[i.name]=i.value),t}_checkId(){const e=super.id;if(!e){const t=this.outerHTML.replace(this.innerHTML,"...");throw new Error(`Component: ${t} has no id`)}return e}get state(){return this._checkId(),this._state}set state(e){this._state=(this._checkId(),e)}_events(){const e=Object.getOwnPropertyNames(window.HTMLElement.prototype);for(const t of this._props)e.indexOf("on"+t)!==-1&&this.addEventListener(t,this)}_prop(e){const t=this._id,i=`__${t}__${s._createId()}__`;return s._data[t]=s._data[t]||{},s._data[t][i]=e,i}_placehold(e){const t=this._id,i=`placehold:${t}:${s._createId()}__`;return s._children[t]=s._children[t]||{},s._children[t][i]=e,i}static match(e,t){return e.matches||(e=e.parentElement),e.matches(t)?e:e.closest(t)}static getTagName(e){return e.match(/[A-Z][a-z0-9]*/g).join("-").toLowerCase()}static getPropertyNames(e){const t=[];for(;e&&e!==s.prototype;)t.push(...Object.getOwnPropertyNames(e)),e=Object.getPrototypeOf(e);return t}static add(e,t){if(!(t||e.name&&e.name.length>1))throw Error("Mangling. https://bit.ly/2TkJ6zP");if(t||(t=s.getTagName(e.name)),!s.ssr&&window.customElements.get(t))throw new Error(`Cannot Tonic.add(${e.name}, '${t}') twice`);if(!e.prototype||!e.prototype.isTonicComponent){const n={[e.name]:class extends s{}}[e.name];n.prototype.render=e,e=n}return e.prototype._props=s.getPropertyNames(e.prototype),s._reg[t]=e,s._tags=Object.keys(s._reg).join(),window.customElements.define(t,e),typeof e.stylesheet=="function"&&s.registerStyles(e.stylesheet),e}static registerStyles(e){if(s._stylesheetRegistry.includes(e))return;s._stylesheetRegistry.push(e);const t=document.createElement("style");s.nonce&&t.setAttribute("nonce",s.nonce),t.appendChild(document.createTextNode(e())),document.head&&document.head.appendChild(t)}static escape(e){return e.replace(s.ESC,t=>s.MAP[t])}static unsafeRawString(e,t){return new f(e,t,!0)}dispatch(e,t=null){const i={bubbles:!0,detail:t};this.dispatchEvent(new window.CustomEvent(e,i))}html(e,...t){const i=r=>{if(r&&r.__children__)return this._placehold(r);if(r&&r.isTonicTemplate)return r.rawText;switch(Object.prototype.toString.call(r)){case"[object HTMLCollection]":case"[object NodeList]":return this._placehold([...r]);case"[object Array]":return r.every(l=>l.isTonicTemplate&&!l.unsafe)?new f(r.join(` `),null,!1):this._prop(r);case"[object Object]":case"[object Function]":case"[object AsyncFunction]":case"[object Set]":case"[object Map]":case"[object WeakMap]":case"[object File]":return this._prop(r);case"[object NamedNodeMap]":return this._prop(s._normalizeAttrs(r));case"[object Number]":return`${r}__float`;case"[object String]":return s.escape(r);case"[object Boolean]":return`${r}__boolean`;case"[object Null]":return`${r}__null`;case"[object HTMLElement]":return this._placehold([r])}return typeof r=="object"&&r&&r.nodeType===1&&typeof r.cloneNode=="function"?this._placehold([r]):r},n=[];for(let r=0;r<e.length-1;r++)n.push(e[r],i(t[r]));n.push(e[e.length-1]);const o=n.join("").replace(s.SPREAD,(r,l)=>{const h=s._data[l.split("__")[1]][l];return Object.entries(h).map(([_,u])=>{const g=_.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return u===!0?g:u?`${g}="${s.escape(String(u))}"`:""}).filter(Boolean).join(" ")});return new f(o,e,!1)}scheduleReRender(e){return this.pendingReRender?this.pendingReRender:(this.pendingReRender=new Promise(t=>setTimeout(()=>{if(!this.isInDocument(this.shadowRoot||this))return;const i=this._set(this.shadowRoot||this,this.render);if(this.pendingReRender=null,i&&i.then)return i.then(()=>{this.updated&&this.updated(e),t(this)});this.updated&&this.updated(e),t(this)},0)),this.pendingReRender)}reRender(e=this.props){const t={...this.props};return this.props=typeof e=="function"?e(t):e,this.scheduleReRender(t)}handleEvent(e){this[e.type](e)}_drainIterator(e,t){return t.next().then(i=>{if(this._set(e,null,i.value),!i.done)return this._drainIterator(e,t)})}_set(e,t,i=""){this.willRender&&this.willRender();for(const n of e.querySelectorAll(s._tags)){if(!n.isTonicComponent)continue;const o=n.getAttribute("id");!o||!s._refIds.includes(o)||(s._states[o]=n.state)}if(t instanceof s.AsyncFunction)return t.call(this,this.html,this.props).then(n=>this._apply(e,n));if(t instanceof s.AsyncFunctionGenerator)return this._drainIterator(e,t.call(this));t===null?this._apply(e,i):t instanceof Function&&this._apply(e,t.call(this,this.html,this.props)||"")}_apply(e,t){if(t&&t.isTonicTemplate?t=t.rawText:typeof t=="string"&&(t=s.escape(t)),typeof t=="string"){if(this.stylesheet&&(t=`<style nonce=${s.nonce||""}>${this.stylesheet()}</style>${t}`),e.innerHTML=t,this.styles){const o=this.styles();for(const r of e.querySelectorAll("[styles]"))for(const l of r.getAttribute("styles").split(/\s+/))Object.assign(r.style,o[l.trim()])}const i=s._children[this._id]||{},n=(o,r)=>{if(o.nodeType===3){const h=o.textContent.trim();i[h]&&r(o,i[h],h)}const l=o.childNodes;if(l)for(let h=0;h<l.length;h++)n(l[h],r)};n(e,(o,r,l)=>{for(const h of r)o.parentNode.insertBefore(h,o);delete s._children[this._id][l],o.parentNode.removeChild(o)})}else e.innerHTML="",e.appendChild(t.cloneNode(!0))}connectedCallback(){this.root=this.shadowRoot||this,super.id&&!s._refIds.includes(super.id)&&s._refIds.push(super.id);const e=t=>t.replace(/-(.)/g,(i,n)=>n.toUpperCase());for(const{name:t,value:i}of this.attributes){const n=e(t),o=this.props[n]=i;if(/__\w+__\w+__/.test(o)){const{1:r}=o.split("__");this.props[n]=s._data[r][o]}else if(/\d+__float/.test(o))this.props[n]=parseFloat(o);else if(o==="null__null")this.props[n]=null;else if(/\w+__boolean/.test(o))this.props[n]=o.includes("true");else if(/placehold:\w+:\w+__/.test(o)){const{1:r}=o.split(":");this.props[n]=s._children[r][o][0]}}if(this.props=Object.assign(this.defaults?this.defaults():{},this.props),this._id=this._id||s._createId(),this.willConnect&&this.willConnect(),!!this.isInDocument(this.root)){if(!this.preventRenderOnReconnect){this._source?this.innerHTML=this._source:this._source=this.innerHTML;const t=this._set(this.root,this.render);if(t&&t.then)return t.then(()=>this.connected&&this.connected())}this.connected&&this.connected()}}isInDocument(e){const t=e.getRootNode();return t===document||t.toString()==="[object ShadowRoot]"}disconnectedCallback(){this.disconnected&&this.disconnected(),delete s._data[this._id],delete s._children[this._id]}};d(s,"_tags",""),d(s,"_refIds",[]),d(s,"_data",{}),d(s,"_states",{}),d(s,"_children",{}),d(s,"_reg",{}),d(s,"_stylesheetRegistry",[]),d(s,"_index",0),d(s,"ssr"),d(s,"nonce");let p=s;const E=[1024,768,480];function y(a){return A(a,E)}function A(a,c){return c.map(e=>R(a,e)).join(", ")}function R(a,c){const e=a.split("."),t=e.pop();return e.join(".")+`-${c}.${t} ${c}w`}class I extends p{render(){const{className:c,filename:e,decoding:t,loading:i,fetchpriority:n,sources:o}=this.props,r=this.props.sizes||["100vw"],l=this.props.class||c,h=o?A(e,o):y(e);return this.html`<div class=${"image"+(l?` ${l}`:"")}> <img srcset="${h}" sizes="${r}" src="${e}" decoding="${t||"auto"}" loading="${i||"lazy"}" fetchpriority="${n||"low"}" /> </div>`}}class C extends p{constructor(){super();const c=new window.Image;c.classList.add("sharp"),this.state={blurry:!0,imgLarge:c},c.onload=async()=>{this.state.blurry=!1,await this.reRender();const e=this.querySelector(".placeholder");c.classList.add("loaded"),e&&e.appendChild(c)}}getImg(){const{filename:c,sizes:e,sources:t}=this.props,{imgLarge:i}=this.state,n=t?A(c,t):y(c);i.setAttribute("srcset",n),i.setAttribute("sizes",e),i.src=c}render(){const{blurplaceholder:c,className:e}=this.props,t=this.props.class||e;return this.state.blurry&&this.getImg(),this.html`<div class="${"image placeholder"+(t?` ${t}`:"")}" > <img class="blurry" src=${c} /> </div>`}}const j="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAgICAgJCAkKCgkNDgwODRMSEBASEx0VFhUWFR0sHCAcHCAcLCcvJiQmLydGNzExN0ZRREBEUWJYWGJ8dnyiotkBCAgICAkICQoKCQ0ODA4NExIQEBITHRUWFRYVHSwcIBwcIBwsJy8mJCYvJ0Y3MTE3RlFEQERRYlhYYnx2fKKi2f/AABEIADIAMgMBIgACEQEDEQH/xAB4AAACAwEBAQAAAAAAAAAAAAAABgQFBwIDARAAAgEEAQMBBQYHAAAAAAAAAQIDAAQFERIGEzFyBxQhQVEVIiNhsbIzNTZxdIGRAQEBAQEAAAAAAAAAAAAAAAACAQMAEQEBAQEBAQEBAAAAAAAAAAABAAJBMRESIf/aAAwDAQACEQMRAD8A1vLJuKL1VRzQco6ZMov4cPqNVipsaoPrLknTmCGPlPMsY3rbECki/wA52LqVYJEkj7Z4EEnRP1q7v+nZ8xlLuRsiqRQvwijC8iBoE7rsez661aFUnfveSQvq2KgFaPHl8UURHuwW0AWIIBNOPSsI+0pXHjsmk296Js4feBcXFzB2zsq3H4BqfuhcbJZ45OcolO3UP9VHioB9EaM68aK9uNFaxoWSH4cXqqBCu9VYZL+EnqqBEwVdmi+15U5tYIbi5lRdM7EtTxYzRnH2bsVLCFCPy+FZXL1NiffXtvel7nMrrR8iuhkcUH7e4OXILrQ8kbo/0fpLky5NIrq7yYcbUlV/4gq5w8EcOPt0QaGm/Ws9yGdx+Ogcc4g7LyEYIBan7AXSXWIspk8PEDVyRWttUV9op0q7IEdlf70hdR9SW+NtzCjBp28LTll45ZrN0il7bkHT63qsCsMI2b6kvsdHkhIYFLyzkedEAgVO1o2NiEj3Vzw+4geWQn5/PVNvRlxDm7+XuKAibdtj6DVJucu0wuUzOPtotxyRwopJ8aQbP+91dezq5t7RsrJNKFkeJEiG6eRULPaZytK6sxdvLeCKIBHHxQ/Xl4Wnv2b3ofECzL7kgLbH5E7pD6pmN1KX1w3GVX5HY8EVc9Av3stFfIw43NnLzUfKRCvOlr1jh/WS2jdFeW6KztZc6od4+n8o6OVZbWUgg6IPGsT9k/8APb7/AAH/AHrRRVul/rH+p8h6o/2CukVfszfEb2aKKePWz3yYevI0jx+FMaBSyNvQ1v7oq69kvi6/KT9VooocnbbRRRUrf//Z",m=["50vw"];class L extends p{render(){return this.html`<div class="the-app"> <p>image</p> <image-tag id="tag-test" filename="/100.jpg" sizes=${m.join(", ")} ></image-tag> <p>blurred placeholder image</p> <blurred-image id="test" filename="/100.jpg" blurplaceholder=${j} sizes=${m.join(", ")} ></blurred-image> </div>`}}p.add(I,"image-tag");p.add(C,"blurred-image");p.add(L,"the-app");