UNPKG

node-red-contrib-uibuilder

Version:

Easily create data-driven web UI's for Node-RED. Single- & Multi-page. Multiple UI's. Work with existing web development workflows or mix and match with no-code/low-code features.

3 lines (2 loc) 27.5 kB
var S=Object.create;var w=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var C=Object.getPrototypeOf,x=Object.prototype.hasOwnProperty;var M=(f,t,e)=>t in f?w(f,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):f[t]=e;var E=(f=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(f,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):f)(function(f){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+f+'" is not supported')});var A=(f,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of k(t))!x.call(f,n)&&n!==e&&w(f,n,{get:()=>t[n],enumerable:!(r=$(t,n))||r.enumerable});return f};var v=(f,t,e)=>(e=f!=null?S(C(f)):{},A(t||!f||!f.__esModule?w(e,"default",{value:f,enumerable:!0}):e,f));var y=(f,t,e)=>M(f,typeof t!="symbol"?t+"":t,e);var i,j=(i=class{constructor(t,e,r){y(this,"version","7.2.0-esm.min");y(this,"sanitiseExtraTags",["uib-var"]);y(this,"sanitiseExtraAttribs",["variable","report","undefined"]);y(this,"ui_md_plugins");if(t)i.win=t;else throw new Error("Ui:constructor. Current environment does not include `window`, UI functions cannot be used.");i.doc=i.win.document,e?i.log=e:i.log=function(){return function(){}},r?this.syntaxHighlight=r:this.syntaxHighlight=function(){},i.win.markdownit&&(i.mdOpts={html:!0,xhtmlOut:!1,linkify:!0,_highlight:!0,_strict:!1,_view:"html",langPrefix:"language-",highlight:function(n,a){if(a&&window.hljs&&window.hljs.getLanguage(a))try{return'<pre class="">\n <code class="hljs border">'.concat(window.hljs.highlight(n,{language:a,ignoreIllegals:!0}).value,"</code></pre>")}finally{}return'<pre class="hljs border"><code>'.concat(i.md.utils.escapeHtml(n).trim(),"</code></pre>")}},i.md=i.win.markdownit(i.mdOpts))}_markDownIt(){if(i.win.markdownit&&(!this.ui_md_plugins&&i.win.uibuilder&&i.win.uibuilder.ui_md_plugins&&(this.ui_md_plugins=i.win.uibuilder.ui_md_plugins),i.mdOpts={html:!0,xhtmlOut:!1,linkify:!0,_highlight:!0,_strict:!1,_view:"html",langPrefix:"language-",highlight:function(t,e){if(window.hljs)if(e&&window.hljs.getLanguage(e))try{return'<pre><code class="hljs border language-'.concat(e,'" data-language="').concat(e,'" title="Source language: \'').concat(e,"'\">").concat(window.hljs.highlight(t,{language:e,ignoreIllegals:!0}).value,"</code></pre>")}finally{}else try{let r=window.hljs.highlightAuto(t);return'<pre><code class="hljs border language-'.concat(r.language,'" data-language="').concat(r.language,'" title="Source language estimated by HighlightJS: \'').concat(r.language,"'\">").concat(r.value,"</code></pre>")}finally{}return'<pre><code class="border">'.concat(i.md.utils.escapeHtml(t).trim(),"</code></pre>")}},i.md=i.win.markdownit(i.mdOpts),this.ui_md_plugins)){if(!Array.isArray(this.ui_md_plugins)){i.log("error","Ui:_markDownIt:plugins","Could not load plugins, ui_md_plugins is not an array")();return}this.ui_md_plugins.forEach(t=>{if(typeof t=="string")i.md.use(i.win[t]);else{let e=Object.keys(t)[0];i.md.use(i.win[e],t[e])}})}}_showNotification(t){t.topic&&!t.title&&(t.title=t.topic),t.title||(t.title="uibuilder notification"),t.payload&&!t.body&&(t.body=t.payload),t.body||(t.body=" No message given.");try{let e=new Notification(t.title,t);return new Promise((r,n)=>{e.addEventListener("close",a=>{a.currentTarget.userAction="close",r(a)}),e.addEventListener("click",a=>{a.currentTarget.userAction="click",r(a)}),e.addEventListener("error",a=>{a.currentTarget.userAction="error",n(a)})})}catch{return Promise.reject(new Error("Browser refused to create a Notification"))}}_uiAdd(t,e){i.log("trace","Ui:_uiManager:add","Starting _uiAdd")(),t.components.forEach((r,n)=>{i.log("trace","Ui:_uiAdd:components-forEach:".concat(n),"Component to add: ",r)();let a;switch(r.type){case"html":{r.ns="html",a=i.doc.createElement("div");break}case"svg":{r.ns="svg",a=i.doc.createElementNS("http://www.w3.org/2000/svg","svg");break}default:{r.ns="dom",a=i.doc.createElement(r.type);break}}!r.slot&&t.payload&&(r.slot=t.payload),this._uiComposeComponent(a,r);let l;r.parentEl?l=r.parentEl:t.parentEl?l=t.parentEl:r.parent?l=i.doc.querySelector(r.parent):t.parent&&(l=i.doc.querySelector(t.parent)),l||(i.log("info","Ui:_uiAdd","No parent found, adding to body")(),l=i.doc.querySelector("body")),r.position&&r.position==="first"?l.insertBefore(a,l.firstChild):r.position&&Number.isInteger(Number(r.position))?l.insertBefore(a,l.children[r.position]):l.appendChild(a),r.components&&this._uiExtendEl(a,r.components,r.ns)})}_uiComposeComponent(t,e){e.attributes&&Object.keys(e.attributes).forEach(r=>{r==="class"&&Array.isArray(e.attributes[r])&&e.attributes[r].join(" "),i.log("trace","_uiComposeComponent:attributes-forEach","Attribute: '".concat(r,"', value: '").concat(e.attributes[r],"'"))(),r==="value"&&(t.value=e.attributes[r]),r.startsWith("xlink:")?t.setAttributeNS("http://www.w3.org/1999/xlink",r,e.attributes[r]):t.setAttribute(r,e.attributes[r])}),e.id&&t.setAttribute("id",e.id),e.type==="svg"&&(t.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns","http://www.w3.org/2000/svg"),t.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink")),e.events&&Object.keys(e.events).forEach(r=>{r.toLowerCase==="onclick"&&(r="click");try{t.addEventListener(r,n=>{new Function("evt","".concat(e.events[r],"(evt)"))(n)})}catch(n){i.log("error","Ui:_uiComposeComponent","Add event '".concat(r,"' for element '").concat(e.type,"': Cannot add event handler. ").concat(n.message))()}}),e.properties&&Object.keys(e.properties).forEach(r=>{t[r]=e.properties[r],["value","checked"].includes(r)&&(t.dispatchEvent(new Event("input")),t.dispatchEvent(new Event("change")))}),e.slot&&this.replaceSlot(t,e.slot),e.slotMarkdown&&this.replaceSlotMarkdown(t,e)}_uiExtendEl(t,e,r=""){e.forEach((n,a)=>{i.log("trace","Ui:_uiExtendEl:components-forEach:".concat(a),n)();let l;n.ns=r,n.ns==="html"?(l=t,this.replaceSlot(t,n.slot)):n.ns==="svg"?(l=i.doc.createElementNS("http://www.w3.org/2000/svg",n.type),this._uiComposeComponent(l,n),t.appendChild(l)):(l=i.doc.createElement(n.type==="html"?"div":n.type),this._uiComposeComponent(l,n),t.appendChild(l)),n.components&&this._uiExtendEl(l,n.components,n.ns)})}_uiLoad(t){t.components&&(Array.isArray(t.components)||(t.components=[t.components]),t.components.forEach(async e=>{Promise.resolve().then(()=>v(E(e)))})),t.srcScripts&&(Array.isArray(t.srcScripts)||(t.srcScripts=[t.srcScripts]),t.srcScripts.forEach(e=>{this.loadScriptSrc(e)})),t.txtScripts&&(Array.isArray(t.txtScripts)||(t.txtScripts=[t.txtScripts]),this.loadScriptTxt(t.txtScripts.join("\n"))),t.srcStyles&&(Array.isArray(t.srcStyles)||(t.srcStyles=[t.srcStyles]),t.srcStyles.forEach(e=>{this.loadStyleSrc(e)})),t.txtStyles&&(Array.isArray(t.txtStyles)||(t.txtStyles=[t.txtStyles]),this.loadStyleTxt(t.txtStyles.join("\n")))}_uiManager(t){t._ui&&(Array.isArray(t._ui)||(t._ui=[t._ui]),t._ui.forEach((e,r)=>{if(e.mode&&!e.method&&(e.method=e.mode),!e.method){i.log("error","Ui:_uiManager","No method defined for msg._ui[".concat(r,"]. Ignoring. "),e)();return}switch(e.payload=t.payload,e.topic=t.topic,e.method){case"add":{this._uiAdd(e,!1);break}case"remove":{this._uiRemove(e,!1);break}case"removeAll":{this._uiRemove(e,!0);break}case"replace":{this._uiReplace(e);break}case"update":{this._uiUpdate(e);break}case"load":{this._uiLoad(e);break}case"reload":{this._uiReload();break}case"notify":{this.showDialog("notify",e,t);break}case"alert":{this.showDialog("alert",e,t);break}default:{i.log("error","Ui:_uiManager","Invalid msg._ui[".concat(r,"].method (").concat(e.method,"). Ignoring"))();break}}}))}_uiReload(){i.log("trace","Ui:uiManager:reload","reloading")(),location.reload()}_uiRemove(t,e=!1){t.components.forEach(r=>{let n;e!==!0?n=[i.doc.querySelector(r)]:n=i.doc.querySelectorAll(r),n.forEach(a=>{try{a.remove()}catch(l){i.log("trace","Ui:_uiRemove","Could not remove. ".concat(l.message))()}})})}_uiReplace(t){i.log("trace","Ui:_uiReplace","Starting")(),t.components.forEach((e,r)=>{i.log("trace","Ui:_uiReplace:components-forEach:".concat(r),"Component to replace: ",e)();let n;if(e.id?n=i.doc.getElementById(e.id):e.selector||e.select?n=i.doc.querySelector(e.selector):e.name?n=i.doc.querySelector('[name="'.concat(e.name,'"]')):e.type&&(n=i.doc.querySelector(e.type)),i.log("trace","Ui:_uiReplace:components-forEach:".concat(r),"Element to replace: ",n)(),n==null){i.log("trace","Ui:_uiReplace:components-forEach:".concat(r,":noReplace"),"Cannot find the DOM element. Adding instead.",e)(),this._uiAdd({components:[e]},!1);return}let a;switch(e.type){case"html":{e.ns="html",a=i.doc.createElement("div");break}case"svg":{e.ns="svg",a=i.doc.createElementNS("http://www.w3.org/2000/svg","svg");break}default:{e.ns="dom",a=i.doc.createElement(e.type);break}}this._uiComposeComponent(a,e),n.replaceWith(a),e.components&&this._uiExtendEl(a,e.components,e.ns)})}_uiUpdate(t){i.log("trace","UI:_uiUpdate:update","Starting _uiUpdate",t)(),t.components||(t.components=[Object.assign({},t)]),t.components.forEach((e,r)=>{i.log("trace","_uiUpdate:components-forEach","Start loop #".concat(r),e)();let n;if(e.parentEl?n=e.parentEl:e.id?n=i.doc.querySelectorAll("#".concat(e.id)):e.selector||e.select?n=i.doc.querySelectorAll(e.selector):e.name?n=i.doc.querySelectorAll('[name="'.concat(e.name,'"]')):e.type&&(n=i.doc.querySelectorAll(e.type)),n===void 0||n.length<1){i.log("warn","Ui:_uiManager:update","Cannot find the DOM element. Ignoring.",e)();return}i.log("trace","_uiUpdate:components-forEach","Element(s) to update. Count: ".concat(n.length),n)(),!e.slot&&e.payload&&(e.slot=e.payload),n.forEach((a,l)=>{if(i.log("trace","_uiUpdate:components-forEach","Updating element #".concat(l),a)(),this._uiComposeComponent(a,e),e.components){i.log("trace","_uiUpdate:nested-component","Element #".concat(l," - nested-component"),e,a)();let o={_ui:[]};e.components.forEach((s,u)=>{let c=s.method||e.method||t.method;s.method&&delete s.method,Array.isArray(s)||(s=[s]),i.log("trace","_uiUpdate:nested-component","Element #".concat(l," - nested-component #").concat(u),s)(),o._ui.push({method:c,parentEl:a,components:s})}),i.log("trace","_uiUpdate:nested-component","Element #".concat(l," - nested-component new manager"),o)(),this._uiManager(o)}})})}$(t,e,r){if(r||(r=i.doc),e||(e="el"),!r||!r.nodeType)return i.log(1,"Uib:$","Invalid context element. Must be a valid HTML element.",r)(),null;let n=r.querySelector(t);if(!n||!n.nodeType)return i.log(1,"Uib:$","No element found or element is not an HTML element for CSS selector ".concat(t))(),null;if(n.nodeName==="TEMPLATE"&&(n=n.content.firstElementChild,!n))return i.log(0,"Uib:$","Template selected for CSS selector ".concat(t," but it is empty"))(),null;let a;try{switch(e.toLowerCase()){case"text":{a=n.innerText;break}case"html":{a=n.innerHTML;break}case"attr":case"attributes":{a={};for(let l of n.attributes)a[l.name]=l.value;break}default:{a=n;break}}}catch(l){a=n,i.log(1,"Uib:$",'Could not process output type "'.concat(e,'" for CSS selector ').concat(t,", returned the DOM element. ").concat(l.message),l)()}return a}$$(t,e){return e||(e=i.doc),!e||!e.nodeType?(i.log(1,"Uib:$$","Invalid context element. Must be a valid HTML element.",e)(),null):Array.from(e.querySelectorAll(t))}addClass(t,e){Array.isArray(t)||(t=[t]),e&&e.classList.add(...t)}applyTemplate(t,e,r){var s;r||(r={}),r.onlyOnce||(r.onlyOnce=!1),r.mode||(r.mode="insert");let n=i.doc.getElementById(t);if(!n||n.tagName!=="TEMPLATE"){i.log("error","Ui:applyTemplate","Source must be a <template>. id='".concat(t,"'"))();return}let a=i.doc.getElementById(e);if(!a){i.log("error","Ui:applyTemplate","Target not found: id='".concat(e,"'"))();return}let l=(s=a.innerHTML)!=null?s:"";l&&r.mode==="replace"&&i.log("warn","Ui:applyTemplate","Target element is not empty, content is replaced. id='".concat(e,"'"))();let o;if(r.onceOnly===!0?o=i.doc.adoptNode(n.content):o=i.doc.importNode(n.content,!0),o){if(r.attributes){let u=o.firstElementChild;Object.keys(r.attributes).forEach(c=>{u.setAttribute(c,r.attributes[c])})}if(r.mode==="insert")a.appendChild(o);else if(r.mode==="replace")a.innerHTML="",a.appendChild(o);else if(r.mode==="wrap"&&(a.innerHTML="",a.appendChild(o),l)){let u=a.getElementsByTagName("slot");u.length>0&&(u[0].innerHTML=l)}}else i.log("warn","Ui:applyTemplate","No valid content found in template")()}convertMarkdown(t){if(!t)return"";if(!i.win.markdownit)return t;i.md||this._markDownIt();try{return i.md.render(t.trim())}catch(e){return i.log(0,"uibuilder:convertMarkdown","Could not render Markdown. ".concat(e.message),e)(),'<p class="border error">Could not render Markdown<p>'}}async include(t,e){if(!fetch)return i.log(0,"Ui:include","Current environment does not include `fetch`, skipping.")(),"Current environment does not include `fetch`, skipping.";if(!t)return i.log(0,"Ui:include","url parameter must be provided, skipping.")(),"url parameter must be provided, skipping.";if(!e||!e.id)return i.log(0,"Ui:include","uiOptions parameter MUST be provided and must contain at least an `id` property, skipping.")(),"uiOptions parameter MUST be provided and must contain at least an `id` property, skipping.";let r;try{r=await fetch(t)}catch(u){return i.log(0,"Ui:include","Fetch of file '".concat(t,"' failed. "),u.message)(),u.message}if(!r.ok)return i.log(0,"Ui:include","Fetch of file '".concat(t,"' failed. Status='").concat(r.statusText,"'"))(),r.statusText;let n=await r.headers.get("content-type"),a=null;n&&(n.includes("text/html")?a="html":n.includes("application/json")?a="json":n.includes("multipart/form-data")?a="form":n.includes("image/")?a="image":n.includes("video/")?a="video":n.includes("application/pdf")?a="pdf":n.includes("text/plain")&&(a="text"));let l="",o="Include successful",s;switch(a){case"html":{s=await r.text(),l=s;break}case"json":{s=await r.json(),l='<pre class="syntax-highlight">',l+=this.syntaxHighlight(s),l+="</pre>";break}case"form":{s=await r.formData(),l='<pre class="syntax-highlight">',l+=this.syntaxHighlight(s),l+="</pre>";break}case"image":{s=await r.blob(),l='<img src="'.concat(URL.createObjectURL(s),'">'),i.win.DOMPurify&&(o="Include successful. BUT DOMPurify loaded which may block its use.",i.log("warn","Ui:include:image",o)());break}case"video":{s=await r.blob(),l='<video controls autoplay><source src="'.concat(URL.createObjectURL(s),'"></video>'),i.win.DOMPurify&&(o="Include successful. BUT DOMPurify loaded which may block its use.",i.log("warn","Ui:include:video",o)());break}case"pdf":case"text":default:{s=await r.blob(),l='<iframe style="resize:both;width:inherit;height:inherit;" src="'.concat(URL.createObjectURL(s),'">'),i.win.DOMPurify&&(o="Include successful. BUT DOMPurify loaded which may block its use.",i.log("warn","Ui:include:".concat(a),o)());break}}return e.type="div",e.slot=l,e.parent||(e.parent="body"),e.attributes||(e.attributes={class:"included"}),this._uiReplace({components:[e]}),i.log("trace","Ui:include:".concat(a),o)(),o}loadScriptSrc(t){let e=i.doc.createElement("script");e.src=t,e.async=!1,i.doc.head.appendChild(e)}loadScriptTxt(t){let e=i.doc.createElement("script");e.async=!1,e.textContent=t,i.doc.head.appendChild(e)}loadStyleSrc(t){let e=i.doc.createElement("link");e.href=t,e.rel="stylesheet",e.type="text/css",i.doc.head.appendChild(e)}loadStyleTxt(t){let e=i.doc.createElement("style");e.textContent=t,i.doc.head.appendChild(e)}loadui(t){if(!fetch){i.log(0,"Ui:loadui","Current environment does not include `fetch`, skipping.")();return}if(!t){i.log(0,"Ui:loadui","url parameter must be provided, skipping.")();return}fetch(t).then(e=>{if(e.ok===!1)throw new Error("Could not load '".concat(t,"'. Status ").concat(e.status,", Error: ").concat(e.statusText));i.log("trace","Ui:loadui:then1","Loaded '".concat(t,"'. Status ").concat(e.status,", ").concat(e.statusText))();let r=e.headers.get("content-type");if(!r||!r.includes("application/json"))throw new TypeError("Fetch '".concat(t,"' did not return JSON, ignoring"));return e.json()}).then(e=>e!==void 0?(i.log("trace","Ui:loadui:then2","Parsed JSON successfully obtained")(),this._uiManager({_ui:e}),!0):!1).catch(e=>{i.log("warn","Ui:loadui:catch","Error. ",e)()})}moveElement(t){let{sourceSelector:e,targetSelector:r,moveType:n,position:a}=t;if(!document.querySelector(e)){i.log(0,"Ui:moveElement","Source element not found")();return}if(!document.querySelector(r)){i.log(0,"Ui:moveElement","Target element not found")();return}}nodeGet(t,e){let r={id:t.id===""?void 0:t.id,name:t.name,children:t.childNodes.length,type:t.nodeName,attributes:void 0,isUserInput:!!t.validity,userInput:t.validity?{value:t.value,validity:void 0,willValidate:t.willValidate,valueAsDate:t.valueAsDate,valueAsNumber:t.valueAsNumber,type:t.type}:void 0};if(["UL","OL"].includes(t.nodeName)){let n=i.doc.querySelectorAll("".concat(e," li"));n&&(r.list={entries:n.length})}if(t.nodeName==="DL"){let n=i.doc.querySelectorAll("".concat(e," dt"));n&&(r.list={entries:n.length})}if(t.nodeName==="TABLE"){let n=i.doc.querySelectorAll("".concat(e," > tbody > tr")),a=i.doc.querySelectorAll("".concat(e," > thead > tr")),l=i.doc.querySelectorAll("".concat(e," > tbody > tr:last-child > *"));(n||a||l)&&(r.table={headRows:a?a.length:0,bodyRows:n?n.length:0,columns:l?l.length:0})}if(t.nodeName!=="#text"&&t.attributes&&t.attributes.length>0){r.attributes={};for(let n of t.attributes)n.name!=="id"&&(r.attributes[n.name]=t.attributes[n.name].value),n.name==="class"&&(r.classes=Array.from(t.classList))}t.nodeName==="#text"&&(r.text=t.textContent),t.validity&&(r.userInput.validity={});for(let n in t.validity)r.userInput.validity[n]=t.validity[n];return r}async notification(t){if(typeof t=="string"&&(t={body:t}),typeof Notification>"u")return Promise.reject(new Error("Notifications not available in this browser"));let e=Notification.permission;return e==="denied"?Promise.reject(new Error("Notifications not permitted by user")):e==="granted"?this._showNotification(t):(e=await Notification.requestPermission(),e==="granted"?this._showNotification(t):Promise.reject(new Error("Notifications not permitted by user")))}removeClass(t,e){if(!t){e.removeAttribute("class");return}Array.isArray(t)||(t=[t]),e&&e.classList.remove(...t)}replaceSlot(t,e){if(!t)return;e||(e=""),e=this.sanitiseHTML(e);let r=i.doc.createRange().createContextualFragment(e),n=i.doc.createRange();n.selectNodeContents(t),n.deleteContents(),t.append(r)}replaceSlotMarkdown(t,e){t&&e.slotMarkdown&&(e.slotMarkdown=this.convertMarkdown(e.slotMarkdown),e.slotMarkdown=this.sanitiseHTML(e.slotMarkdown),t.innerHTML=e.slotMarkdown)}sanitiseHTML(t){return i.win.DOMPurify?i.win.DOMPurify.sanitize(t,{ADD_TAGS:this.sanitiseExtraTags,ADD_ATTR:this.sanitiseExtraAttribs}):t}showDialog(t,e,r){let n="";if(r.payload&&typeof r.payload=="string"&&(n+="<div>".concat(r.payload,"</div>")),e.content&&(n+="<div>".concat(e.content,"</div>")),n===""){i.log(1,"Ui:showDialog","Toast content is blank. Not shown.")();return}!e.title&&r.topic&&(e.title=r.topic),e.title&&(n='<p class="toast-head">'.concat(e.title,"</p><p>").concat(n,"</p>")),e.noAutohide&&(e.noAutoHide=e.noAutohide),e.noAutoHide&&(e.autohide=!e.noAutoHide),e.autoHideDelay?(e.autohide||(e.autohide=!0),e.delay=e.autoHideDelay):e.autoHideDelay=1e4,Object.prototype.hasOwnProperty.call(e,"autohide")||(e.autohide=!0),t==="alert"&&(e.modal=!0,e.autohide=!1,n='<svg viewBox="0 0 192.146 192.146" style="width:30;background-color:transparent;"><path d="M108.186 144.372c0 7.054-4.729 12.32-12.037 12.32h-.254c-7.054 0-11.92-5.266-11.92-12.32 0-7.298 5.012-12.31 12.174-12.31s11.91 4.992 12.037 12.31zM88.44 125.301h15.447l2.951-61.298H85.46l2.98 61.298zm101.932 51.733c-2.237 3.664-6.214 5.921-10.493 5.921H12.282c-4.426 0-8.51-2.384-10.698-6.233a12.34 12.34 0 0 1 .147-12.349l84.111-149.22c2.208-3.722 6.204-5.96 10.522-5.96h.332c4.445.107 8.441 2.618 10.513 6.546l83.515 149.229c1.993 3.8 1.905 8.363-.352 12.066zm-10.493-6.4L96.354 21.454l-84.062 149.18h167.587z" /></svg> '.concat(n));let a=i.doc.getElementById("toaster");a===null&&(a=i.doc.createElement("div"),a.id="toaster",a.title="Click to clear all notifcations",a.setAttribute("class","toaster"),a.setAttribute("role","dialog"),a.setAttribute("arial-label","Toast message"),a.onclick=function(){a.remove()},i.doc.body.insertAdjacentElement("afterbegin",a));let l=i.doc.createElement("div");l.title="Click to clear this notifcation",l.setAttribute("class","toast ".concat(e.variant?e.variant:""," ").concat(t)),l.innerHTML=n,l.setAttribute("role","alertdialog"),e.modal&&l.setAttribute("aria-modal",e.modal),l.onclick=function(o){o.stopPropagation(),l.remove(),a.childElementCount<1&&a.remove()},a.insertAdjacentElement(e.appendToast===!0?"beforeend":"afterbegin",l),e.autohide===!0&&setInterval(()=>{l.remove(),a.childElementCount<1&&a.remove()},e.autoHideDelay)}ui(t){let e={};t._ui?e=t:e._ui=t,this._uiManager(e)}uiGet(t,e=null){let r=i.doc.querySelectorAll(t),n=[];return r.forEach(a=>{if(e){e==="classes"&&(e="class");let l=a.getAttribute(e);if(l==null)try{l=a[e]}catch{}if(l==null)e.toLowerCase()==="value"?n.push(a.innerText):n.push("Property '".concat(e,"' not found"));else{let o={},s=l.constructor.name.toLowerCase();if(s==="namednodemap")for(let u of l)o[u.name]=l[u.name].value;else if(!s.includes("map"))o[e]=l;else{let u={};for(let c in l)u[c]=l[c]}o.class&&(o.classes=Array.from(a.classList)),n.push(o)}}else n.push(this.nodeGet(a,t))}),n}uiEnhanceElement(t,e){this._uiComposeComponent(t,e)}createTable(t=[],e={parent:"body"}){if(!e.parent)throw new Error("[ui.js:createTable] opts.parent must be provided");this.buildHtmlTable(t,e)}buildHtmlTable(t,e={}){let r,n=Object.prototype.toString.apply(t);if(n==="[object Array]"||n==="[object Object]")r=Object.keys(t),t=Object.values(t);else{let c=i.doc.createElement("p");return c.textContent="Input data is not an array or an object, cannot create a table.",c}r.length>1e3&&i.log(1,"Uib:buildHtmlTable","Warning, data is ".concat(r.length," rows. Anything over 1,000 can get very slow to complete."))();let a=i.doc.createElement("table"),l=i.doc.createElement("thead"),o=i.doc.createElement("tr");if(!e.cols){if(t.length<1)throw new Error("[ui.js:buildHtmlTable] When no opts.cols is provided, data must contain at least 1 row");let c=Object.prototype.toString.apply(t[0])!=="[object Array]";o.dataset.colReference="",e.cols=[],Object.keys(t[0]).forEach((d,h)=>{e.cols.push({index:h,hasName:c,name:c?d:void 0,key:d!=null?d:h,title:d})})}a.cols=e.cols,e.cols.forEach(c=>{let d=i.doc.createElement("th");d.textContent=c.title,c.hasName===!0&&(d.dataset.colName=name),o.appendChild(d)}),l.appendChild(o),a.appendChild(l);let s=i.doc.createElement("tbody");a.appendChild(s);let u={allowHTML:!0,cols:e.cols};if(t.forEach((c,d)=>{isNaN(Number(r[d]))?u.rowId=r[d]:u.rowId=void 0,this.tblAddRow(a,c,u)}),e.parent){let c;typeof e.parent=="string"?c=i.doc.querySelector(e.parent):c=e.parent;try{c.appendChild(a)}catch(d){throw new Error("[ui.js:buildHtmlTable] Could not add table to parent. ".concat(d.message))}return}return a}tblAddRow(t,e={},r={}){let n=Object.prototype.toString.apply(t);if(Object.prototype.toString.apply(r)!=="[object Object]")throw new Error("[tblAddDataRow] options must be an object");let a=Object.prototype.toString.apply(e);if(a!=="[object Object]"&&a!=="[object Array]")throw new Error("[tblAddDataRow] rowData MUST be an object or an array containing column/cell data for each column");let l;if(n==="[object HTMLTableElement]")l=t;else if(l=i.doc.querySelector(t),!l)throw new Error('[tblAddDataRow] Table with CSS Selector "'.concat(t,'" not found'));r.body||(r.body=0),"allowHTML"in r||(r.allowHTML=!1);let o=l.getElementsByTagName("tbody")[r.body];if(!o)throw new Error("[tblAddDataRow] Table must have a tbody tag, tbody section ".concat(r.body," does not exist"));r.cols||(r.cols=this.tblGetColMeta(l));let s=r.cols,u=i.doc.createElement("tr");r.rowId&&(u.id=r.rowId);let c=[];for(let d of s){let h=i.doc.createElement("td");h.colMeta=d,d.hasName&&(h.dataset.colName=d.name),c.push(h)}if(Object.keys(e).forEach((d,h,L)=>{let b=c.find(m=>{var p;return((p=m==null?void 0:m.colMeta)==null?void 0:p.name)===d}),g;if(b)g=e[d];else{let m=Number(d);isNaN(m)&&(m=h),m<=c.length-1&&(b=c[m],g=Object.values(e)[m])}b&&(r.allowHTML?b.innerHTML=this.sanitiseHTML(g):b.textContent=g)}),u.append(...c),"afterRow"in r){let d=o.rows[r.afterRow];if(d)return d.after(u)}else if("beforeRow"in r){let d=o.rows[r.beforeRow];if(d)return d.before(u)}else if("replaceRow"in r){let d=o.rows[r.replaceRow];if(d)return d.replaceWith(u)}return o.appendChild(u)}tblAddListener(t,e={},r={}){let n=i.doc.querySelector(t);if(!n)throw new Error('Table with CSS Selector "'.concat(t,'" not found'));if(typeof r!="object")throw new Error('The "out" argument MUST be an object');e.eventScope||(e.eventScope="row"),e.returnType||(e.returnType="text"),e.eventType||(e.eventType="click"),e.pad||(e.pad=3),e.logLevel||(e.logLevel=2),"send"in e||(e.send=!0),n.querySelector("tbody").addEventListener(e.eventType,a=>{Object.keys(r).forEach(s=>delete r[s]);let l=a.target.closest("tr"),o=a.target.closest("td");if(l){r.clickType=e.eventScope,r.eventType=e.eventType;let s=r.rowIndex=l.rowIndex,u=r.cellIndex=o.cellIndex+1;if(l.id&&(r.rowId=l.id),e.eventScope==="row")l.querySelectorAll("td").forEach(c=>{let d=this.tblGetCellName(c,e.pad);r[d]=e.returnType==="text"?c.textContent.trim():c.innerHTML});else{let c=this.tblGetCellName(o,e.pad);r[c]=e.returnType==="text"?o.textContent.trim():o.innerHTML}i.log(e.logLevel,"Ui:tblAddClickListener","".concat(e.eventScope," ").concat(e.eventType," on row=").concat(s,", col=").concat(u,", data: "),r)(),e.send===!0&&i.win.uibuilder&&i.win.uibuilder.send({topic:"".concat(t," ").concat(e.eventScope," ").concat(e.eventType),payload:r})}})}tblFindColMeta(t,e,r){if(!e&&!r)throw new Error("[tblFindColMeta] Either the column metadata array or the HTML table element must be provided");!e&&r&&(e=this.tblGetColMeta(r));let n;if(e[t])n=e[t];else{let a=e.find(l=>l.name===t||l.index===Number(t));a&&(n=a)}return n}tblGetCellName(t,e=3){var r;return(r=t.getAttribute("data-col-name"))!=null?r:"C".concat(String(t.cellIndex+1).padStart(e,"0"))}tblGetColMeta(t,e={}){var l,o,s;if(e.pad||(e.pad=3),t.cols)return t.cols;let r=(l=t.querySelector("tr[data-col-reference]"))==null?void 0:l.children;if(r||(r=(o=t.querySelector("thead>tr:first-of-type"))==null?void 0:o.children),r||(r=(s=t.querySelector("tr:first-of-type"))==null?void 0:s.children),!r)return i.log(1,"Ui:tblGetColMeta","No columns found in table")(),[];let n=[],a;for(a of r){let u=!!a.dataset.colName,c=a.dataset.colName,d=a.cellIndex+1,h=u?c:"C".concat(String(a.cellIndex+1).padStart(e.pad,"0"));n.push({index:d,hasName:u,name:c,key:h,title:a.textContent})}return t.cols=n,n}tblRemoveRow(t,e,r={}){let n=Object.prototype.toString.apply(t);if(Object.prototype.toString.apply(r)!=="[object Object]")throw new Error("[tblRemoveRow] options must be an object");let a;if(n==="[object HTMLTableElement]")a=t;else if(a=i.doc.querySelector(t),!a)throw new Error('[tblRemoveRow] Table with CSS Selector "'.concat(t,'" not found'));r.body||(r.body=0);let l=a.getElementsByTagName("tbody")[r.body];if(!l)throw new Error("[tblAddDataRow] Table must have a tbody tag, tbody section ".concat(r.body," does not exist"));l.deleteRow(e)}},y(i,"win"),y(i,"doc"),y(i,"log"),y(i,"mdOpts"),y(i,"md"),i),N=j;export{N as default}; //# sourceMappingURL=ui.esm.min.js.map