vaderjs 1.3.3 → 1.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vaderjs",
3
- "version": "1.3.3",
3
+ "version": "1.3.5",
4
4
  "description": "A Reactive Framework for Building Content Rich Single-Page Applications (SPA)",
5
5
  "main": "index.js",
6
6
  "scripts": {
package/vader-min.js CHANGED
@@ -1 +1 @@
1
- let dom=[],states={},worker=new Worker(new URL("./worker.js",import.meta.url));export const useRef=t=>{const e=document.querySelector(`[ref="${t}"]`);return{current:e,update:t=>{const s=(new DOMParser).parseFromString(t,"text/html").body.firstChild;if(e){!s.isEqualNode(e)&&e.parentNode.replaceChild(s,e)}}}};let components=[];export class Component{constructor(){this.states={},this.name=this.constructor.name,this.executedEffects={},this.storedProps={},this.componentMounted=!1,this.hasMounted=!1,this.$_signal_subscribers=[],this.$_signal_subscribers_ran=[],this.effects={},this.$_useStore_subscribers=[],this.init(),this.Componentcontent=null,this.$_signal_dispatch_event=new CustomEvent("SignalDispatch",{detail:{hasUpdated:!1,state:null}}),this.$_signal_dispatch_cleanup_event=new CustomEvent("Signal_Cleanup_Dispatch",{detail:{state:null,lastState:null}}),this.snapshots=[],this.dom=[],this.cfr=!1}adapter(t){}init(){this.registerComponent()}registerComponent(){components.push(this)}setState(t,e){this.states[t]=e,this.updateComponent()}unmount(){this.componentMounted=!1,this.componentWillUnmount(),document.querySelector(`[data-component="${this.name}"]`).remove(),document.querySelector(`[data-component="${this.name}"]`)||(components=components.filter((t=>t.name!==this.name)))}componentUpdate(t,e,s){}componentDidMount(){}componentWillUnmount(){}signal=(t,e)=>{let s=!1,[n,i]=this.useState(t,e,(()=>{if(this.$_signal_subscribers.length>0){for(var t=0;t<this.$_signal_subscribers.length;t++)if(!s){if(this.$_signal_subscribers[t].runonce&&this.$_signal_subscribers_ran.includes(this.$_signal_subscribers[t]))break;return this.$_signal_subscribers[t].function(n),void this.$_signal_subscribers_ran.push(this.$_signal_subscribers[t])}}else this.$_signal_dispatch_event.detail.hasUpdated=!0,this.$_signal_dispatch_event.detail.state=n,window.dispatchEvent(this.$_signal_dispatch_event)}));return this.$_signal_subscribe=(t,e)=>(this.$_signal_subscribers.push({function:t,runonce:e}),t),this.$_signal_cleanup=t=>{this.lastState=n,this.$_signal_subscribers=this.$_signal_subscribers.filter((e=>e.function!==t)),this.$_signal_dispatch_cleanup_event.detail.state=this.states,this.$_signal_dispatch_cleanup_event.detail.lastState=this.lastState,window.dispatchEvent(this.$_signal_dispatch_event)},this.$_signal_dispatch=()=>{for(var t=0;t<this.$_signal_subscribers.length&&(!this.$_signal_subscribers[t].runonce||!this.$_signal_subscribers_ran.includes(this.$_signal_subscribers[t]));t++)this.$_signal_subscribers[t].function(n),this.$_signal_subscribers_ran.push(this.$_signal_subscribers[t])},this.$_signal_get=()=>n,this.$_signal_call=()=>{s=!0,this.$_signal_dispatch()},this.$_signal_set=t=>{i(t)},{subscribe:this.$_signal_subscribe,cleanup:this.$_signal_cleanup,dispatch:this.$_signal_dispatch,call:this.$_signal_call,set:this.$_signal_set,get:this.$_signal_get}};useAuth(t){let e=t.rulesets;if(!e)throw new Error("No rulesets provided");let s=t.user,n={can:t=>{let n=!1;return e.forEach((e=>{e.action===t&&e.condition(s)&&(n=!0)})),n},hasRole:t=>s.role&&s.role.includes(t),canWithRole:(t,e)=>n.can(t)&&n.hasRole(e),assignRule:t=>{e.some((e=>e.action===t.action))||e.push(t)},revokeRule:t=>{e=e.filter((e=>e.action!==t))},canAnyOf:t=>t.some((t=>n.can(t))),canAllOf:t=>t.every((t=>n.can(t))),canGroup:(t,e="any")=>"any"===e?n.canAnyOf(t):n.canAllOf(t)};return n}useReducer(t,e,s){return this.states[t]||(this.states[t]=s),[this.states[t],s=>{this.states[t]=e(this.states[t],s),this.updateComponent()}]}runEffects(){Object.keys(this.effects).forEach((t=>{this.effects[t].forEach((t=>{this.executedEffects[t]||(t(),this.executedEffects[t]=!0)}))}))}useSyncStore(t,e){let[s,n]=this.useState(t,e||localStorage.getItem(`$_vader_${t}`,(e=>{localStorage.setItem(`$_vader_${t}`,JSON.stringify(e)),this.$_useStore_subscribers.forEach((t=>{t(e)}))}))||{});return{getField:t=>s[t],setField:(t,e)=>{const i={...s,[t]:e};n(i)},subscribe:t=>this.$_useStore_subscribers.push(t),clear:t=>{let e=s;delete e[t],n(e)}}}useState(t,e,s=null){return this.states[t]||(this.states[t]=e),[this.states[t],e=>{this.states[t]=e,this.updateComponent(),"function"==typeof s&&s()}]}useRef(t){const e=this.dom[t];return{current:()=>e,update:t=>{const s=(new DOMParser).parseFromString(t,"text/html").body.firstChild;if(e){!s.isEqualNode(e)&&e.parentNode.replaceChild(s,e)}}}}useEffect(t,e){return this.effects[this.name]||(this.effects[this.name]=[]),this.effects[this.name].push(t),e.length>0?e.forEach((t=>{if(t.set)throw new Error("signal found, do not use effect and signals at the same time - signals are more efficient")})):this.hasMounted||(t(),this.hasMounted=!0),{cleanup:()=>{this.effects[this.name]=this.effects[this.name].filter((e=>e!==t))}}}$Function(t){let e=t.name;return e||(e="anonymous"+Math.floor(1e17*Math.random())),window[e]=t,`window.${e}()`}updateComponent(){const t=document.createDocumentFragment();Object.keys(components).forEach((async e=>{const{name:s}=components[e];let n=document.querySelector(`[data-component="${s}"]`),i={name:s,time:(new Date).getTime(),prev_state:this.states,prev_props:this.storedProps,content:n.innerHTML};if(!n)return;const r=await new Function("useState","useEffect","useAuth","useReducer","useSyncStore","signal","rf","props","render","return `"+await this.render()+"`;")(this.useState,this.useEffect,this.useAuth,this.useReducer,this.useSyncStore,this.signal,this.render);if(r!==n.innerHTML){if(this.snapshots.length>0){this.snapshots[this.snapshots.length-1]!==i&&this.snapshots.push(i)}else this.snapshots.push(i);this.componentUpdate(i.prev_state,i.prev_props,i.content),t.appendChild(document.createRange().createContextualFragment(r)),n.innerHTML="",n.appendChild(t),this.runEffects()}}))}validateClassName(t){return/^[a-zA-Z0-9-_]+$/.test(t)}html(t,...e){let s=setInterval((()=>{document.querySelector(`[data-component="${this.name}"]`)&&(clearInterval(s),this.componentMounted=!0,document.querySelector(`[data-component="${this.name}"]`)?.querySelectorAll("*").forEach((t=>{t.hasAttribute("ref")&&(this.dom[t.getAttribute("ref")]=t)})),this.componentDidMount())}),100),n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("data-component-script",this.name),worker.postMessage({strings:t,args:e,location:window.location.origin+window.location.pathname.replace(/\/[^\/]*$/,"")+"/public/",name:this.name});let i=new Promise(((t,e)=>{worker.onmessage=e=>{if(e.data.error)throw new Error(e.data.error);this.dom;let s=e.data.js,n=e.data.template;const i=this.useState.bind(this),r=this.useEffect.bind(this),a=this.useReducer.bind(this),o=this.useAuth.bind(this),c=this.useSyncStore.bind(this),u=this.signal.bind(this),h=this.$Function.bind(this);let l=this.states;const d=this.useRef.bind(this);new Function("useState","useEffect","useAuth","useReducer","useSyncStore","signal","$Function","dom","render","states","useRef",s)(i,r,o,a,c,u,h,this.dom,this.render,this.states,d),t(new Function("useRef","states","signal","useState","useReducer","useAuth","useSyncStore","useRef","$Function","return`"+n+"`")(d,l,u,i,a,o,c,d,h))},worker.onerror=t=>{e(t)}}));return i}async render(t){}}const Vader={Component:Component,useRef:useRef};export const component=()=>new Component;export const rf=(t,e)=>{window[t]=e};let cache={};async function handletemplate(t){let e=(new DOMParser).parseFromString(t,"text/html"),s=e.documentElement.querySelectorAll("*");if(s.length>0)for(var n=0;n<s.length;n++)if("INCLUDE"===s[n].nodeName){if(!s[n].getAttribute("src")||""===s[n].getAttribute("src"))throw new Error("Include tag must have src attribute");let t=s[n].getAttribute("src")?.split("/").pop()?.split(".")[0],i=await include(s[n].getAttribute("src"));i=i.replace(/`/g,"\\`"),cache[s[n].getAttribute("src")]=i,i=new Function(`return \`${i}\`;`)();let r=(new DOMParser).parseFromString(i,"text/html");r.querySelectorAll("include").forEach((t=>{t.remove()})),e.querySelectorAll(t).forEach((t=>{if(t.attributes.length>0)for(var s=0;s<t.attributes.length;s++){let e="{{"+t.attributes[s].name+"}}";r.body.innerHTML.includes(e)&&(r.body.innerHTML=r.body.innerHTML.replaceAll(e,t.attributes[s].value))}if(t.children.length>0&&r.body.querySelector("slot"))for(s=0;s<t.children.length;s++){r.body.querySelectorAll("slot").forEach((e=>{let n=e.getAttribute("id");(t.hasAttribute("key")&&t.getAttribute("key")===n||!t.hasAttribute("key")&&t.nodeName===n)&&t.children[s].innerHTML.length>0&&(e.outerHTML=t.children[s].innerHTML)}))}e.body.querySelectorAll("include").forEach((t=>{t.remove()})),e.body.outerHTML=e.body.outerHTML.replace(/`/g,"\\`"),e.body.outerHTML=e.body.outerHTML.replace(t.outerHTML,new Function(`return \`${r.body.outerHTML}\`;`)())}))}return e.body.outerHTML=e.body.outerHTML.replace(/`/g,"\\`"),t=new Function(`return \`${e.body.outerHTML}\`;`)()}export const include=async t=>(!t.startsWith("/")||t.includes("/src/")||document.documentElement.outerHTML.trim().includes("\x3c!-- #vader-disable_relative-paths --\x3e")||(t="/src/"+t),cache[t]?await handletemplate(new Function(`return \`${cache[t]}\`;`)()):fetch(`./${t}`).then((e=>{if(404===e.status)throw new Error(`No file found at ${t}`);return e.text()})).then((async e=>(cache[t]=e,e=await handletemplate(new Function(`return \`${e}\`;`)())))));export default Vader;
1
+ let dom=[],states={},worker=new Worker(new URL("./worker.js",import.meta.url));export const useRef=t=>{const e=document.querySelector(`[ref="${t}"]`);return{current:e,update:t=>{const s=(new DOMParser).parseFromString(t,"text/html").body.firstChild;if(e){!s.isEqualNode(e)&&e.parentNode.replaceChild(s,e)}}}};let components=[];export class Component{constructor(){this.states={},this.name=this.constructor.name,this.executedEffects={},this.storedProps={},this.componentMounted=!1,this.hasMounted=!1,this.$_signal_subscribers=[],this.$_signal_subscribers_ran=[],this.effects={},this.$_useStore_subscribers=[],this.init(),this.Componentcontent=null,this.$_signal_dispatch_event=new CustomEvent("SignalDispatch",{detail:{hasUpdated:!1,state:null}}),this.$_signal_dispatch_cleanup_event=new CustomEvent("Signal_Cleanup_Dispatch",{detail:{state:null,lastState:null}}),this.snapshots=[],this.dom=[],this.cfr=!1}adapter(t){}init(){this.registerComponent()}registerComponent(){components.push(this)}setState(t,e){this.states[t]=e,this.updateComponent()}unmount(){this.componentMounted=!1,this.componentWillUnmount(),document.querySelector(`[data-component="${this.name}"]`).remove(),document.querySelector(`[data-component="${this.name}"]`)||(components=components.filter((t=>t.name!==this.name)))}componentUpdate(t,e,s){}componentDidMount(){}componentWillUnmount(){}signal=(t,e)=>{let s=!1,[n,i]=this.useState(t,e,(()=>{if(this.$_signal_subscribers.length>0){for(var t=0;t<this.$_signal_subscribers.length;t++)if(!s){if(this.$_signal_subscribers[t].runonce&&this.$_signal_subscribers_ran.includes(this.$_signal_subscribers[t]))break;return this.$_signal_subscribers[t].function(n),void this.$_signal_subscribers_ran.push(this.$_signal_subscribers[t])}}else this.$_signal_dispatch_event.detail.hasUpdated=!0,this.$_signal_dispatch_event.detail.state=n,window.dispatchEvent(this.$_signal_dispatch_event)}));return this.$_signal_subscribe=(t,e)=>(this.$_signal_subscribers.push({function:t,runonce:e}),t),this.$_signal_cleanup=t=>{this.lastState=n,this.$_signal_subscribers=this.$_signal_subscribers.filter((e=>e.function!==t)),this.$_signal_dispatch_cleanup_event.detail.state=this.states,this.$_signal_dispatch_cleanup_event.detail.lastState=this.lastState,window.dispatchEvent(this.$_signal_dispatch_event)},this.$_signal_dispatch=()=>{for(var t=0;t<this.$_signal_subscribers.length&&(!this.$_signal_subscribers[t].runonce||!this.$_signal_subscribers_ran.includes(this.$_signal_subscribers[t]));t++)this.$_signal_subscribers[t].function(n),this.$_signal_subscribers_ran.push(this.$_signal_subscribers[t])},this.$_signal_get=()=>n,this.$_signal_call=()=>{s=!0,this.$_signal_dispatch()},this.$_signal_set=t=>{i(t)},{subscribe:this.$_signal_subscribe,cleanup:this.$_signal_cleanup,dispatch:this.$_signal_dispatch,call:this.$_signal_call,set:this.$_signal_set,get:this.$_signal_get}};useAuth(t){let e=t.rulesets;if(!e)throw new Error("No rulesets provided");let s=t.user,n={can:t=>{let n=!1;return e.forEach((e=>{e.action===t&&e.condition(s)&&(n=!0)})),n},hasRole:t=>s.role&&s.role.includes(t),canWithRole:(t,e)=>n.can(t)&&n.hasRole(e),assignRule:t=>{e.some((e=>e.action===t.action))||e.push(t)},revokeRule:t=>{e=e.filter((e=>e.action!==t))},canAnyOf:t=>t.some((t=>n.can(t))),canAllOf:t=>t.every((t=>n.can(t))),canGroup:(t,e="any")=>"any"===e?n.canAnyOf(t):n.canAllOf(t)};return n}useReducer(t,e,s){return this.states[t]||(this.states[t]=s),[this.states[t],s=>{this.states[t]=e(this.states[t],s),this.updateComponent()}]}runEffects(){Object.keys(this.effects).forEach((t=>{this.effects[t].forEach((t=>{this.executedEffects[t]||(t(),this.executedEffects[t]=!0)}))}))}useSyncStore(t,e){let[s,n]=this.useState(t,e||localStorage.getItem(`$_vader_${t}`,(e=>{localStorage.setItem(`$_vader_${t}`,JSON.stringify(e)),this.$_useStore_subscribers.forEach((t=>{t(e)}))}))||{});return{getField:t=>s[t],setField:(t,e)=>{const i={...s,[t]:e};n(i)},subscribe:t=>this.$_useStore_subscribers.push(t),clear:t=>{let e=s;delete e[t],n(e)}}}useState(t,e,s=null){return this.states[t]||(this.states[t]=e),[this.states[t],e=>{this.states[t]=e,this.updateComponent(),"function"==typeof s&&s()}]}useRef(t){const e=this.dom[t];return{current:()=>e,update:t=>{const s=(new DOMParser).parseFromString(t,"text/html").body.firstChild;if(e){!s.isEqualNode(e)&&e.parentNode.replaceChild(s,e)}}}}useEffect(t,e){return this.effects[this.name]||(this.effects[this.name]=[]),this.effects[this.name].push(t),e.length>0?e.forEach((t=>{if(t.set)throw new Error("signal found, do not use effect and signals at the same time - signals are more efficient")})):this.hasMounted||(t(),this.hasMounted=!0),{cleanup:()=>{this.effects[this.name]=this.effects[this.name].filter((e=>e!==t))}}}$Function(t){let e=t.name;return e||(e="anonymous"+Math.floor(1e17*Math.random())),window[e]=t,`window.${e}()`}updateComponent(){const t=document.createDocumentFragment();Object.keys(components).forEach((async e=>{const{name:s}=components[e];let n=document.querySelector(`[data-component="${s}"]`),i={name:s,time:(new Date).getTime(),prev_state:this.states,prev_props:this.storedProps,content:n.innerHTML};if(!n)return;const r=await new Function("useState","useEffect","useAuth","useReducer","useSyncStore","signal","rf","props","render","return `"+await this.render()+"`;")(this.useState,this.useEffect,this.useAuth,this.useReducer,this.useSyncStore,this.signal,this.render);if(r!==n.innerHTML){if(this.snapshots.length>0){this.snapshots[this.snapshots.length-1]!==i&&this.snapshots.push(i)}else this.snapshots.push(i);this.componentUpdate(i.prev_state,i.prev_props,i.content),t.appendChild(document.createRange().createContextualFragment(r)),n.innerHTML="",n.appendChild(t),this.runEffects()}}))}validateClassName(t){return/^[a-zA-Z0-9-_]+$/.test(t)}html(t,...e){let s=setInterval((()=>{document.querySelector(`[data-component="${this.name}"]`)&&(clearInterval(s),this.componentMounted=!0,document.querySelector(`[data-component="${this.name}"]`)?.querySelectorAll("*").forEach((t=>{t.hasAttribute("ref")&&(this.dom[t.getAttribute("ref")]=t)})),this.componentDidMount())}),100),n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("data-component-script",this.name),worker.postMessage({strings:t,args:e,location:window.location.origin+window.location.pathname.replace(/\/[^\/]*$/,"")+"/public/",name:this.name});let i=new Promise(((t,e)=>{worker.onmessage=e=>{if(e.data.error)throw new Error(e.data.error);this.dom;let s=e.data.js,n=e.data.template;const i=this.useState.bind(this),r=this.useEffect.bind(this),a=this.useReducer.bind(this),o=this.useAuth.bind(this),c=this.useSyncStore.bind(this),u=this.signal.bind(this),h=this.$Function.bind(this);let l=this.states;const d=this.useRef.bind(this);new Function("useState","useEffect","useAuth","useReducer","useSyncStore","signal","$Function","dom","render","states","useRef",s)(i,r,o,a,c,u,h,this.dom,this.render,this.states,d),t(handletemplate(new Function("useRef","states","signal","useState","useReducer","useAuth","useSyncStore","useRef","$Function","return`"+n+"`")(d,l,u,i,a,o,c,d,h)))},worker.onerror=t=>{e(t)}}));return i}async render(t){}}const Vader={Component:Component,useRef:useRef};export const component=()=>new Component;export const rf=(t,e)=>{window[t]=e};let cache={};async function handletemplate(t){let e=(new DOMParser).parseFromString(t,"text/html"),s=e.documentElement.querySelectorAll("*");if(s.length>0)for(var n=0;n<s.length;n++)if("INCLUDE"===s[n].nodeName){if(!s[n].getAttribute("src")||""===s[n].getAttribute("src"))throw new Error("Include tag must have src attribute");let t=s[n].getAttribute("src")?.split("/").pop()?.split(".")[0],i=await include(s[n].getAttribute("src"));i=i.replace(/`/g,"\\`"),cache[s[n].getAttribute("src")]=i,i=new Function(`return \`${i}\`;`)();let r=(new DOMParser).parseFromString(i,"text/html");r.querySelectorAll("include").forEach((t=>{t.remove()})),e.querySelectorAll(t).forEach((t=>{if(t.attributes.length>0)for(var s=0;s<t.attributes.length;s++){let e="{{"+t.attributes[s].name+"}}";r.body.innerHTML.includes(e)&&(r.body.innerHTML=r.body.innerHTML.replaceAll(e,t.attributes[s].value))}if(t.children.length>0&&r.body.querySelector("slot"))for(s=0;s<t.children.length;s++){r.body.querySelectorAll("slot").forEach((e=>{let n=e.getAttribute("id");(t.hasAttribute("key")&&t.getAttribute("key")===n||!t.hasAttribute("key")&&t.nodeName===n)&&t.children[s].innerHTML.length>0&&(e.outerHTML=t.children[s].innerHTML)}))}e.body.querySelectorAll("include").forEach((t=>{t.remove()})),e.body.outerHTML=e.body.outerHTML.replace(/`/g,"\\`"),e.body.outerHTML=e.body.outerHTML.replace(t.outerHTML,new Function(`return \`${r.body.outerHTML}\`;`)())}))}return e.body.outerHTML=e.body.outerHTML.replace(/`/g,"\\`"),t=new Function(`return \`${e.body.outerHTML}\`;`)()}export const include=async t=>(!t.startsWith("/")||t.includes("/src/")||document.documentElement.outerHTML.trim().includes("\x3c!-- #vader-disable_relative-paths --\x3e")||(t="/src/"+t),cache[t]?cache[t]:fetch(`./${t}`).then((e=>{if(404===e.status)throw new Error(`No file found at ${t}`);return e.text()})).then((async e=>(cache[t]=e,e))));export default Vader;
package/vader.js CHANGED
@@ -875,7 +875,7 @@ export class Component {
875
875
  );
876
876
 
877
877
  resolve(
878
- new Function(
878
+ handletemplate( new Function(
879
879
  "useRef",
880
880
  "states",
881
881
  "signal",
@@ -896,7 +896,7 @@ export class Component {
896
896
  useSyncStore,
897
897
  useRef,
898
898
  $Function
899
- )
899
+ ))
900
900
  );
901
901
  };
902
902
  worker.onerror = (e) => {
@@ -1092,7 +1092,7 @@ export const include = async (path) => {
1092
1092
  // @ts-ignore
1093
1093
  if (cache[path]) {
1094
1094
  // @ts-ignore
1095
- return await handletemplate(new Function(`return \`${cache[path]}\`;`)());
1095
+ return cache[path];
1096
1096
  } else {
1097
1097
  return fetch(`./${path}`)
1098
1098
  .then((res) => {
@@ -1105,7 +1105,7 @@ export const include = async (path) => {
1105
1105
  // @ts-ignore
1106
1106
  cache[path] = data;
1107
1107
 
1108
- data = await handletemplate(new Function(`return \`${data}\`;`)());
1108
+
1109
1109
 
1110
1110
  return data;
1111
1111
  });
package/worker-min.js CHANGED
@@ -1 +1 @@
1
- onmessage=e=>{let l=Date.now(),a=e.data.strings,t=e.data.args,s="",r=e.data.location.split("/").slice(0,-1).join("/"),c="";for(let e=0;e<a.length;e++)c+=a[e],e<t.length&&(c+=t[e]);let i=c.match(/--([^>]*)--/gs);if(i)for(;i.length;){let e=i.pop();c=c.replace(e,"")}if(c=c.replace(/(#+)(.*)/g,((e,l,a)=>{if(e.includes("<")&&e.includes(">"))return e;{let e=l.length;return`<h ${e} class="markdown_heading">${a}</h${e}>`}})),c=c.replace(/\*\*(.*?)\*\*/g,((e,l)=>`<b class="markdown_bold">${l}</b>`)),c=c.replace(/\*(.*?)\*/g,((e,l)=>`<i class="markdown_italic">${l}</i>`)),c=c.replace(/`(.*?)`/g,((e,l)=>`<code>${l}</code>`)),c=c.replace(/\[([^\]]+)\]\(([^)]+)\)/g,((e,l,a)=>`<a class="markdown_link" href="${a}">${l}</a>`)),c=c.replace(/!\[([^\]]+)\]\(([^)]+)\)/g,((e,l,a)=>`<img class="markdown_image" src="${a}" alt="${l}" />`)),c.split("\n").forEach(((e,l,a)=>{e.match(/^\s*-\s+(.*?)$/gm)&&(c=0!==l&&a[l-1].match(/^\s*-\s+(.*?)$/gm)?l!==a.length-1&&a[l+1].match(/^\s*-\s+(.*?)$/gm)?c.replace(e,`<li>${e.replace(/^\s*-\s+(.*?)$/gm,"$1")}</li>`):c.replace(e,`<li>${e.replace(/^\s*-\s+(.*?)$/gm,"$1")}</li></ul>`):c.replace(e,`<ul class="markdown_unordered" style="list-style-type:disc;list-style:inside"><li>${e.replace(/^\s*-\s+(.*?)$/gm,"$1")}</li>`))})),c.split("\n").forEach(((e,l,a)=>{e.match(/^\s*\d+\.\s+(.*?)$/gm)&&(c=0!==l&&a[l-1].match(/^\s*\d+\.\s+(.*?)$/gm)?l!==a.length-1&&a[l+1].match(/^\s*\d+\.\s+(.*?)$/gm)?c.replace(e,`<li>${e.replace(/^\s*\d+\.\s+(.*?)$/gm,"$1")}</li>`):c.replace(e,`<li>${e.replace(/^\s*\d+\.\s+(.*?)$/gm,"$1")}</li></ol>`):c.replace(e,`<ol class="markdown_ordered" style="list-style-type:decimal;"><li>${e.replace(/^\s*\d+\.\s+(.*?)$/gm,"$1")}</li>`))})),c=c.replace(/^\s*-\s+(.*?)$/gm,((e,l)=>`<li class="markdown_list_item">${l}</li>`)),c=c.replace(/^\s*---\s*$/gm,'<hr class="markdown_horizontal" />'),c=c.replace(/^\s*> (.*)$/gm,((e,l)=>`<blockquote class="markdown_blockquote">${l}</blockquote>`)),c=c.replace(/((?: *\|.*?)+)\n((?: *\|.*?)+)/gm,((e,l,a)=>{const t=l.split("|").slice(1,-1),s=a.split("|").slice(1,-1);let r='<table class="markdown_table">';return r+='<thead class="markdown_table_head"><tr class="markdown_table_row">',t.forEach((e=>{r+=`<th class="markdown_table_header_cell">${e}</th>`})),r+='</tr></thead><tbody class="markdown_table_body"><tr class="markdown_table_row">',s.forEach((e=>{r+=`<td class="markdown_table_body_cell">${e}</td>`})),r+="</tr></tbody></table>",r})),!c.includes("<body>"))throw new Error(`Vader Error: You must enclose your html in a body tag for all components. \n\n${c}`);c=c.replace(/classname/g,"class");let n=c.match(/<img([^>]*)>/g);if(n)for(let l=0;l<n.length;l++){let a=n[l],t=a.match(/src="([^"]*)"/);if(!a.match(/alt="([^"]*)"/)&&!c.includes("\x3c!-- #vader-disable_accessibility --\x3e"))throw new Error(`Vader Error: You must include an alt attribute in the image tag \n\n${a} of class ${e.data.name}. `);t&&t.forEach((l=>{if(l.includes("http")||c.includes("\x3c!-- #vader-disable_relative-paths --\x3e")){if(!l.includes("http")&&l.startsWith(".")&&!c.includes("\x3c!-- #vader-disable_relative-paths --\x3e"))throw new Error(`Vader Error: You cannot use absolute paths since relative paths are not disabled in ${e.data.file}. Use relative paths instead. \n\n${l}`)}else c=c.replace(`src="${l}"`,`src="${r}/${l}"`)}))}let o=c.match(/href="([^"]*)"/g);if(o)for(;o.length;){let l=o.pop();if(l=l.replace('href="',"").replace('"',""),l.includes("http")||c.includes("\x3c!-- #vader-disable_relative-paths --\x3e")){if(!l.includes("http")&&l.startsWith(".")&&!c.includes("\x3c!-- #vader-disable_relative-paths --\x3e"))throw new Error(`Vader Error: You cannot use absolute paths since relative paths are not disabled in ${e.data.file}. Use relative paths instead. \n\n${l}`)}else c=c.replace(`href="${l}"`,`href="#${l}"`)}let d=Date.now()-l,p=!1;(r.includes("localhost")||r.includes("127.0.0.1")&&!p)&&(p=!0,c+=`\${console.log('%c${e.data.name} component rendered in ${d}ms')}`);const h=c.split("<script>");h&&h.forEach(((e,l)=>{if(0===l)c=e;else{if(e.includes("// <![CDATA[ <-- For SVG support"))return;let l=e.split("<\/script>")[0];s+=l}}));let m=c.match(/(\$\(.*?\))/gs);if(m)for(;m.length;){let e=m.pop();c=c.replace(e,`\${${e.replace("$(","").replace(")","")}}`)}let $=c.match(/@title '([^>]*)'/);if($){let e=`{document.title = "${$[1]}", ""}`;c=c.replace($[0],"$"+e)}c=c.replaceAll('=""',"");let g=c.match(/@style{([^>]*)};/gs);if(g)for(let e=0;e<g.length;e++){if(!g[e].includes("style"))continue;g[e].match(/@style{([^>]*)};/).forEach((e=>{let l=e.replace("@style{","").replace("};","");l=l.replaceAll(",",";"),l=l.replaceAll(/'/g," "),c=c.replace(e,`style="${l}"`)}))}postMessage({template:`<div data-component=${e.data.name}>${c}</div>`,js:s||""})};
1
+ onmessage=e=>{let l=Date.now(),a=e.data.strings,t=e.data.args,s="",r=e.data.location.split("/").slice(0,-1).join("/"),c="";for(let e=0;e<a.length;e++)c+=a[e],e<t.length&&(c+=t[e]);let i=c.match(/--([^>]*)--/gs);if(i)for(;i.length;){let e=i.pop();c=c.replace(e,"")}if(c=c.replace(/(#+)([^<>\n]*)(?![^<]*>)(?![^{]*})/g,((e,l,a)=>{let t=l.length;return`<h${t} class="markdown_heading">${a}</h${t}>`})),c=c.replace(/\*\*(.*?)\*\*/g,((e,l)=>`<b class="markdown_bold">${l}</b>`)),c=c.replace(/\*(.*?)\*/g,((e,l)=>`<i class="markdown_italic">${l}</i>`)),c=c.replace(/`(.*?)`/g,((e,l)=>`<code>${l}</code>`)),c=c.replace(/\[([^\]]+)\]\(([^)]+)\)/g,((e,l,a)=>`<a class="markdown_link" href="${a}">${l}</a>`)),c=c.replace(/!\[([^\]]+)\]\(([^)]+)\)/g,((e,l,a)=>`<img class="markdown_image" src="${a}" alt="${l}" />`)),c.split("\n").forEach(((e,l,a)=>{e.match(/^\s*-\s+(.*?)$/gm)&&(c=0!==l&&a[l-1].match(/^\s*-\s+(.*?)$/gm)?l!==a.length-1&&a[l+1].match(/^\s*-\s+(.*?)$/gm)?c.replace(e,`<li>${e.replace(/^\s*-\s+(.*?)$/gm,"$1")}</li>`):c.replace(e,`<li>${e.replace(/^\s*-\s+(.*?)$/gm,"$1")}</li></ul>`):c.replace(e,`<ul class="markdown_unordered" style="list-style-type:disc;list-style:inside"><li>${e.replace(/^\s*-\s+(.*?)$/gm,"$1")}</li>`))})),c.split("\n").forEach(((e,l,a)=>{e.match(/^\s*\d+\.\s+(.*?)$/gm)&&(c=0!==l&&a[l-1].match(/^\s*\d+\.\s+(.*?)$/gm)?l!==a.length-1&&a[l+1].match(/^\s*\d+\.\s+(.*?)$/gm)?c.replace(e,`<li>${e.replace(/^\s*\d+\.\s+(.*?)$/gm,"$1")}</li>`):c.replace(e,`<li>${e.replace(/^\s*\d+\.\s+(.*?)$/gm,"$1")}</li></ol>`):c.replace(e,`<ol class="markdown_ordered" style="list-style-type:decimal;"><li>${e.replace(/^\s*\d+\.\s+(.*?)$/gm,"$1")}</li>`))})),c=c.replace(/^\s*-\s+(.*?)$/gm,((e,l)=>`<li class="markdown_list_item">${l}</li>`)),c=c.replace(/^\s*---\s*$/gm,'<hr class="markdown_horizontal" />'),c=c.replace(/^\s*> (.*)$/gm,((e,l)=>`<blockquote class="markdown_blockquote">${l}</blockquote>`)),c=c.replace(/((?: *\|.*?)+)\n((?: *\|.*?)+)/gm,((e,l,a)=>{const t=l.split("|").slice(1,-1),s=a.split("|").slice(1,-1);let r='<table class="markdown_table">';return r+='<thead class="markdown_table_head"><tr class="markdown_table_row">',t.forEach((e=>{r+=`<th class="markdown_table_header_cell">${e}</th>`})),r+='</tr></thead><tbody class="markdown_table_body"><tr class="markdown_table_row">',s.forEach((e=>{r+=`<td class="markdown_table_body_cell">${e}</td>`})),r+="</tr></tbody></table>",r})),!c.includes("<body>"))throw new Error(`Vader Error: You must enclose your html in a body tag for all components. \n\n${c}`);c=c.replace(/classname/g,"class");let o=c.match(/<img([^>]*)>/g);if(o)for(let l=0;l<o.length;l++){let a=o[l],t=a.match(/src="([^"]*)"/);if(!a.match(/alt="([^"]*)"/)&&!c.includes("\x3c!-- #vader-disable_accessibility --\x3e"))throw new Error(`Vader Error: You must include an alt attribute in the image tag \n\n${a} of class ${e.data.name}. `);t&&t.forEach((l=>{if(l.includes("http")||c.includes("\x3c!-- #vader-disable_relative-paths --\x3e")){if(!l.includes("http")&&l.startsWith(".")&&!c.includes("\x3c!-- #vader-disable_relative-paths --\x3e"))throw new Error(`Vader Error: You cannot use absolute paths since relative paths are not disabled in ${e.data.file}. Use relative paths instead. \n\n${l}`)}else c=c.replace(`src="${l}"`,`src="${r}/${l}"`)}))}let n=c.match(/href="([^"]*)"/g);if(n)for(;n.length;){let l=n.pop();if(l=l.replace('href="',"").replace('"',""),l.includes("http")||c.includes("\x3c!-- #vader-disable_relative-paths --\x3e")){if(!l.includes("http")&&l.startsWith(".")&&!c.includes("\x3c!-- #vader-disable_relative-paths --\x3e"))throw new Error(`Vader Error: You cannot use absolute paths since relative paths are not disabled in ${e.data.file}. Use relative paths instead. \n\n${l}`)}else c=c.replace(`href="${l}"`,`href="#${l}"`)}let d=Date.now()-l,p=!1;(r.includes("localhost")||r.includes("127.0.0.1")&&!p)&&(p=!0,c+=`\${console.log('%c${e.data.name} component rendered in ${d}ms')}`);const h=c.split("<script>");h&&h.forEach(((e,l)=>{if(0===l)c=e;else{if(e.includes("// <![CDATA[ <-- For SVG support"))return;let l=e.split("<\/script>")[0];s+=l}}));let m=c.match(/(\$\(.*?\))/gs);if(m)for(;m.length;){let e=m.pop();c=c.replace(e,`\${${e.replace("$(","").replace(")","")}}`)}let $=c.match(/@title '([^>]*)';/);if($){let e=`{document.title = "${$[1]}", ""}`;c=c.replace($[0],"$"+e)}let g=c.match(/@style{([^>]*)};/gs);if(g)for(let e=0;e<g.length;e++){if(!g[e].includes("style"))continue;let l=g[e];console.log(l);let a=l.replace("@style{","").replace("};","");a=a.replaceAll(",",";"),a=a.replaceAll(/[A-Z]/g,(e=>`-${e.toLowerCase()}`)),a=a.replaceAll(/'/g," "),c=c.replace(l,`style="${a}"`)}let u=c.match(/@stylesheet{([^>]*)};/);if(u){let e=u[1].replaceAll(" ","");e=e.replaceAll(",",";"),e=e.replaceAll(/[A-Z]/g,(e=>`-${e.toLowerCase()}`)),e=e.replaceAll(/'/g," "),c=c.replace(u[0],`<style>${e}</style>`)}postMessage({template:`<div data-component=${e.data.name}>${c}</div>`,js:s||""})};
package/worker.js CHANGED
@@ -13,6 +13,11 @@ onmessage = (e) => {
13
13
  }
14
14
 
15
15
  let comments = result.match(/--([^>]*)--/gs);
16
+ /**
17
+ * @example
18
+ *
19
+ * -- This is a comment --
20
+ */
16
21
  if (comments) {
17
22
  while (comments.length) {
18
23
  let comment = comments.pop();
@@ -21,16 +26,11 @@ onmessage = (e) => {
21
26
  }
22
27
  }
23
28
 
24
- // Convert headings (e.g., #1-6 Heading => <h1-6>Heading</h1-6>)
25
- // @ts-ignore
26
- result = result.replace(/(#+)(.*)/g, (match, hashes, text) => {
27
- if (!match.includes("<") || !match.includes(">")) {
29
+ result = result.replace(/(#+)([^<>\n]*)(?![^<]*>)(?![^{]*})/g, (match, hashes, text) => {
28
30
  let level = hashes.length;
29
- return `<h ${level} class="markdown_heading">${text}</h${level}>`;
30
- } else {
31
- return match;
32
- }
31
+ return `<h${level} class="markdown_heading">${text}</h${level}>`;
33
32
  });
33
+
34
34
 
35
35
  // Convert bold (e.g., **Bold** => <b>Bold</b>)
36
36
  result = result.replace(/\*\*(.*?)\*\*/g, (match, text) => {
@@ -259,15 +259,17 @@ onmessage = (e) => {
259
259
  }
260
260
  }
261
261
 
262
- let title = result.match(/@title '([^>]*)'/);
262
+ let title = result.match(/@title '([^>]*)';/);
263
263
  if (title) {
264
264
  let t = title[1];
265
265
  let ti = `{document.title = "${t}", ""}`;
266
266
  result = result.replace(title[0], "$" + ti);
267
267
  }
268
268
  // @ts-ignore
269
- result = result.replaceAll('=""', '')
269
+
270
+
270
271
  let styles = result.match(/@style{([^>]*)};/gs);
272
+
271
273
  if (styles) {
272
274
  for (let i = 0; i < styles.length; i++) {
273
275
  // make sure its in a tag
@@ -276,24 +278,47 @@ onmessage = (e) => {
276
278
  continue;
277
279
  }
278
280
  let style = styles[i];
279
-
280
-
281
- let s = style.match(/@style{([^>]*)};/);
282
-
283
- // @ts-ignore
284
- s.forEach((style) => {
281
+ console.log(style)
285
282
 
286
- let st = style.replace("@style{", "").replace("};", "");
287
- // @ts-ignore
288
- st = st.replaceAll(',', ';')
289
- // @ts-ignore
290
- st = st.replaceAll(/'/g, ' ')
291
-
292
- result = result.replace(style, `style="${st}"`);
293
- });
283
+ let css = style.replace("@style{", "").replace("};", "");
284
+ // @ts-ignore
285
+ css = css.replaceAll(",", ";");
286
+ // @ts-ignore
287
+ css = css.replaceAll(/[A-Z]/g, (match) => {
288
+ return `-${match.toLowerCase()}`;
289
+ }
290
+ );
291
+ //@ts-ignore
292
+ css = css.replaceAll(/'/g, " ");
293
+ result = result.replace(style, `style="${css}"`);
294
+
295
+
294
296
  }
295
297
  }
296
298
 
299
+ let stylsheet = result.match(/@stylesheet{([^>]*)};/);
300
+ if (stylsheet) {
301
+ let styles = stylsheet[1];
302
+ /**
303
+ * @stylesheet{
304
+ * body:{
305
+ * backgroundColor: red;
306
+ *
307
+ * }
308
+ * }
309
+ */
310
+
311
+ // @ts-ignore
312
+ let css = styles.replaceAll(" ", "");
313
+ css = css.replaceAll(",", ";");
314
+ css = css.replaceAll(/[A-Z]/g, (match) => {
315
+ return `-${match.toLowerCase()}`;
316
+ }
317
+ );
318
+ css = css.replaceAll(/'/g, " ");
319
+
320
+ result = result.replace(stylsheet[0], `<style>${css}</style>`);
321
+ }
297
322
  postMessage({
298
323
  template: `<div data-component=${e.data.name}>${result}</div>`,
299
324
  js: js ? js : ""