-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathturpial.min.js
14 lines (14 loc) · 12.1 KB
/
turpial.min.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
_______ _ _ _____ _____ _____ _ _ _____
|__ __| | | | __ \| __ \_ _| /\ | | | |/ ____|
| | | | | | |__) | |__) || | / \ | | | | (___
| | | | | | _ /| ___/ | | / /\ \ | | _ | |\___ \
| | | |__| | | \ \| | _| |_ / ____ \| |____ | |__| |____) |
|_| \____/|_| \_\_| |_____/_/ \_\______| \____/|_____/
* Turpial JS Library V. 1.0.0
* License: MIT.
* Copyright Yorman Maricuto, May 2019.
* @twitter: @MaricutoYorman, @Instagram: maricuto
* Micro-Library to create web components, multi-fetch elements, append styles, scripts, templating engine JSX
*/
class Turpial{constructor(e={}){this.birds=[],this.un=((e,t="")=>void 0===e?t:e),this.searchStr=((e,t,o=!1)=>{let s=e.search(t);return-1!==s&&(!0!==o||s)}),this.replacement=((e,t,o)=>e.split(t).join(o)),this.find=(e=>"string"==typeof e?document.getElementById(e):e),this.ext=".turpial.js",this.allowStateEvents=this.un(e.allowStateEvents,!1),this.loadModulesOnRoute=this.un(e.loadModulesOnRoute,!0),this.autoloader=this.un(e.autoloader,!1),this.autoloader_folder=this.un(e.autoloader_folder,""),this.cache=this.un(e.cache,"public"),this.public_path=this.un(e.public_path,""),this.core_path=this.un(e.core_path,""),this.folder=this.un(e.core_path,"/turpial/"),this.loader={},this.httpRequests=[],this.loader.show=this.un(e.loaderShow,null),this.loader.hide=this.un(e.loaderHide,null),this.views={},this.statusResources="loaded",this.resources={},this.myComponents=[],this.random_string=(e=>{void 0===e&&(e=6);for(var t="",o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",s=o.length,r=0;r<e;r++)t+=o.charAt(Math.floor(Math.random()*s));return t}),this.selectData=((e,t,o,s)=>{s=turpial.un(s,!1);var r="";return e.forEach(function(e,i){if(e[t]==o)return!0===s?void(r=i):void(r=e)}),r}),this.component={applyProps:(e,t)=>{const o=()=>{const o=document.querySelectorAll(e);Array.prototype.slice.call(o).forEach(function(e){t(e)})},s=()=>{if("loading"===this.statusResources)var e=0,t=setInterval(()=>e>6e3?(console.warn("error loading resources and applying components"),void clearInterval(t)):(e+=20,"loaded"===this.statusResources?(clearInterval(t),void o()):void 0),20);else o()};window.addEventListener("load",()=>{s()}),"complete"!==document.readyState||s()},set:e=>{const t=this,o=t.component;var s=e.props,r=e.tag;t.myComponents.push({tag:r,props:s});var i=t.un(e.extends,null);if(null!==i&&(i={extends:i}),void 0===window.customElements)return t.component.olderVerBrow=(()=>{}),void o.applyProps(r,s);void 0===window.customElements.get(r)&&window.customElements.define(r,class extends HTMLElement{constructor(t=e.props){super((e=>{o.applyProps(r,e)})(t))}},i)}},this.view={},this.models={},this.models.sources={},this.controller={},this.urls={},this.filesLoaded={},this.inject=(e=>{for(const t of e)"STYLE"===this.filesLoaded[t].tagName&&(this.filesLoaded[t].innerHTML=this.filesLoaded[t].text),document.head.appendChild(this.filesLoaded[t])}),this.models.fetch=(e=>{let t=this,o=e.type||"script";const s=t.un(e.cancelOnResend,null),r=t.un(e.options,null),i=t.un(e.method,"GET"),n=t.un(e.attributes,[]);e.url=e.url||[],e.file=e.file||e.url,e.files=e.files||e.file;var l=e.files;void 0===e.ready&&(e.ready=(()=>{})),"string"==typeof l&&(l=[l]);document.head;const a=[],u=[];let h=[];e.getString=(e=>e.clone().text()),e.fetching=(l=>{void 0!==t.filesLoaded[l]&&"script"===o&&t.filesLoaded[l].remove();var c=new XMLHttpRequest;c.open(i,l,!0);const d=[],p=[];if(null!==r){for(var f in r)p.push(r[f]);Object.keys(r).forEach(function(e,t){d.push([e,p[t]])}),d.forEach(function(e){c.setRequestHeader(e[0],e[1])})}if(c.onload=function(){if(c.status>=200&&c.status<400){var s,r=c.responseText;h.push(r),s="script"===o||"style"===o||"link"===o?o:"script";var i=document.createElement(s);n.map(e=>{i.setAttribute(e.name,e.content)}),"style"===o?i.type="text/css":"link"===o&&(i.rel="stylesheet",i.media="all",i.href=l),i.text=r,t.filesLoaded[l]=i,a.push(l)}else if("function"==typeof e.onerror&&c.status>=400)return e.onerror(c.status)},c.onerror=function(){t.filesLoaded[l]="",a.push("unloaded:"+l),u.push(l)},!0===s){let o="rq_"+t.un(e.id,t.random_string(4));if(void 0!==t.httpRequests[o])try{t.httpRequests[o].abort()}catch(e){console.warn("unable to cancel request.")}t.httpRequests[o]=c}"POST"!==i?c.send():c.send(e.data)}),t.statusResources="loading",(s=>{for(const t of s)e.fetching(t);var r=0;let i=setInterval(()=>{let n=!1;if(1e4===(r+=70)&&(n=!0,console.warn("¡Impossible to load all files.")),a.length!==s.length&&!0!==n);else{if(clearInterval(i),"script"===o||"style"===o||"link"===o)t.inject(s),e.ready();else if("text"===o){var l=[];for(var u of s)l.push(t.filesLoaded[u].innerHTML);e.ready(l)}t.statusResources="loaded"}},70)})(l)}),this.fetch=(e=>this.models.fetch(e)),this.include=(e=>this.models.fetch(e)),this.linkCSS=(e=>{e.type="link";var t=this;e.type="style",e.url=e.url||[],e.file=e.file||e.url,e.files=e.files||e.file;var o=[];return e.files.map(e=>{var s=document.createElement("link");s.setAttribute("media","all"),s.setAttribute("rel","stylesheet"),s.href=e;var r=t.mount(document.head,s);o.push(r)}),e.ready(o),o}),this.includeCSS=(e=>(e.type="style",this.models.fetch(e))),this.controller.views={path:e=>{const t=this.ext;var o=`${this.folder}views/`,s=e.views,r=this.resources,i=s.split("/"),n=o;if(1===i.length){var l=i[0];return n+=`${l}${t}`,r[l]={},n}var a=i.pop(),u=i.pop();l=a;return r[u]={},r[u][l]={},0===i.length?n+=`${u}/${l}${t}`:(i.forEach(function(e){n+=`${e}/`}),n+=`${u}/${l}${t}`),n}},this.view.load=(e=>{(e=e||{}).ready=e.ready||function(){},e.folder=this.autoloader_folder||"";const t=this.ext,o=this.app.parameters,s=this.app.controller_name,r=this.app.action_name,i=`${this.folder}${e.folder}${s}`;if(e.module=turpial.un(e.module,null),"index"===s)var n=`${i}${t}`;else if(0===o.length&&"index"!==s&&void 0===r)n=`${i}/index${t}`;else if(0===o.length&&"undefined"!==r)n=`${i}/${r}/index${t}`;else{n=`${i}/${r}`;o.forEach(function(e){n+=`/${e}`}),n+=t}"string"==typeof e.module&&(e.ext=e.ext||t,n=this.core_path+e.module+e.ext);var l={file:n,options:e.options||{},ready:()=>{e.ready()}};"function"==typeof e.error&&(l.error=(t=>{e.error(t)})),this.DataView=l,""!==e.module&&!1!==e.module&&this.fetch(l)}),this.controller.routes={getHost:e=>{!1!==(e=e||{}).loadModule&&!1!==this.loadModulesOnRoute||(e.relativeModules=!0);var t=window.location.href;t=(t=(t=(t=t.split("#"))[0]).split("?"))[0];let o=this.un(e.relativeModules,!1),s=t.search(this.public_path),r=t.slice(s,s+this.public_path.length);var i=(r=t.split(r)[0]+r).slice(-1);return i="/"!==i?"/":"",1==o?`${r}${i}`:(i=t.slice(-1),`${t}${i="/"!==i?"/":""}`)},set:e=>{const t=this;t.app={},e=e||{};var o=window.location.href.split("?");let s=(o=(o=o[0]).split("#"))[0].search(t.public_path);if(!(s>0))return void console.warn("bad_public_path_name");var r=(o=o[0].substr(s+t.public_path.length)).split("/"),i=0,n=0;t.app.parameters=[],r.forEach(function(e){""!=e&&(0===i&&(t.app.controller_name=e),1===i?t.app.action_name=e:i>1&&(t.app.parameters[n++]=e),i++)}),t.app.controller_name=t.app.controller_name||"index",t.app.action_name=t.app.action_name||"";let l=`${t.app.controller_name}/${t.app.action_name}/${t.app.parameters.join("/")}`;l=(l=l.split("//").join("/")).split("///").join("/"),t.app.props=e,t.app.path=l,t.host=t.controller.routes.getHost(),t.app.host=t.host},change:e=>{const t=this,o=e.type||"pushState";e.loadModule=t.un(e.loadModule,!0);let s=`${t.controller.routes.getHost(e)}${e.path}`;if(s===window.location.href)return;window.history[o](t.un(e.object),"",t.un(s)),!0===e.loadModule&&!0===t.loadModulesOnRoute&&t.urls.load(e);let r=t.un(e.title,!1);"string"==typeof r&&(document.title=r)},go:e=>{if("number"==typeof e)window.history.go(e);else if("back"===e)window.history.back();else{if("forward"!==e)return;window.history.forward()}this.controller.routes.set(),this.urls.load()}},this.router=((e,t)=>{t=t||function(){},"number"!=typeof e&&"string"!=typeof e?(this.controller.routes.change(e),this.stateEvent(),t()):this.controller.routes.go(e)}),this.routes=this.controller.routes.set,this.routes(),this.controller.components={},this.views.get=(e=>{if("object"==typeof e){"string"==typeof e.views&&(e.views=[e.views]);var t=[],o=this.controller.views;e.views.forEach(function(s,r){e.views=s,t[r]=o.path(e)}),Object.assign(e,{file:t,ready:e.ready}),this.fetch(e)}}),this.urls={},this.urls.load=(e=>{e=e||{};const t=this,o=t.app.controller_name,s=t.app.action_name,r=t.app.parameters;let i=t.urls[o]||!1;if(e.module=turpial.un(e.module,null),"string"==typeof e.module)return void t.view.load(e);if(!1===i)return void t.view.load(e);t.un(i.loadController,!0);let n=t.un(i.loadAction,!0),l=t.un(i.loadParameters,1e3),a=t.un(t.urls[o][s],!1);return"function"==typeof i.self?"function"==typeof a&&!0===n?r.length>l?void i.self(()=>{a(()=>{})}):void i.self(()=>{a(()=>{t.view.load(e)})}):!1===n&&"string"==typeof s?void i.self(()=>{a(()=>{})}):void i.self(()=>{t.view.load(e)}):void 0}),this.historyEvents={},this.URLNoHASH=function(e){return e.split("#")[0]},this.createHistoryEvent=function(e,t){e=this.URLNoHASH(window.location.href)+(e=e||""),this.historyEvents[e]=t},this.createHistoryEvent("",function(){}),this.stateEvent=(()=>{var e=this.historyEvents;"function"==typeof e[this.URLNoHASH(window.location.href)]&&e[this.URLNoHASH(window.location.href)]()}),!0===this.allowStateEvents&&window.addEventListener("popstate",this.stateEvent),!0===e.autoloader&&(window.addEventListener("load",()=>{this.urls.load()}),window.onpopstate=(e=>{this.controller.routes.set(),this.urls.load(),function(){void 0===window.customElements&&Array.prototype.slice.call(this.myComponents).forEach(function(e){this.component.set({tag:e.tag,props:e.props})})}()})),this.template=((e,t)=>{return function(e,t){if("object"==typeof(t=t||[])&&!Array.isArray(t)){var o=[];Object.values(t).map((e,s)=>{o.push({[Object.keys(t)[s]]:e})}),t=o}"object"==typeof e&&(e=e.innerHTML);var s=e;return t.forEach(function(t){var o=Object.keys(t),r=Object.values(t);o.forEach(function(t,o){t=`{{ ${t} }}`,e.search(t)>=0&&(s=function(e,t,o){return e.split(t).join(o)}(s,t,r[o]))})}),s}(e,t)})}map(e,t=[]){var o=this.birds[e];if("object"==typeof e?o=e:void 0===o&&(o=this.find(e)),"object"==typeof t){if(void 0===t[0])return o;o=o.children,t.forEach(function(e,s){o=void 0===t[s+1]?o[e]:o[e].children})}return o}createMap(e){var t=(e=this.find(e)).getAttribute("id");if(void 0!==t){var o=document.getElementById(t);this.birds[t]=o}}read(e,t=[]){return this.map(e,t)}selectorApp(e,t=[]){return"object"==typeof t&&!0===Number.isInteger(t[0])?this.map(e,t):t}delete(e){(e=this.find(e)).remove()}update(e,t=null,o="replace-selector",s=!0){if("string"==typeof t)var r=this.render(t),i=t;else r=t;if(null===r){var n=!1;r=t}else n=!0;var l=e;!0===s&&(o="replace-selector");var a=!1,u=l.parentNode;if("before"===o)u.insertBefore(r,l),a=r;else if("after"===o)u.insertBefore(r,l.nextSibling),a=r;else if("replace-selector"===o)u.replaceChild(r,l),a=r;else{if("inner"!==o)return console.warn("error-on-placement"),!1;!0===n?l.innerHTML=i:l.innerText=r,a=l}let h=l;return this.createMap(h),a}insert(e,t,o="inner"){return e=this.find(e),this.update(e,t,o,!1)}render(e){var t=document.createElement("template");return t.innerHTML=e,t=t.content.firstElementChild}mount(e,t){if("string"==typeof t)t=this.render(t);if(null===t)return void console.warn("need to be HTML string or object");let o=(e=this.find(e)).appendChild(t),s=e;return this.createMap(s),o}settings(e){if(void 0===e[0]){var t=[],o=0,s=[];for(var r in e)s.push(e[r]);s.forEach(function(e){t[o++]=e});var i=[];o=0;Object.keys(e).forEach(function(e){i[o++]=e});var n="";o=0;return i.forEach(function(e,o){n+=` ${e}="${t[o]}"`}),n}}createTag(e,t="",o=""){"object"==typeof t&&(t=this.settings(t));let s=`<${e}${t}>`;return s+=o,"br"!==e&&(s+=`</${e}>`),s}html(e,t,o){const s=this.replacement,r=this;if("code"===e&&(o=s(o,"<","<"),o=s(o,">",">"),o=s(o," "," ")),void 0===o)o=t,t="";if("object"==typeof o&&void 0!==o[0]){var i="";o.forEach(function(e,t){i+=`${e}`});var n=r.createTag(e,t,i)}else if("object"==typeof o)t=o,n=r.createTag(e,t,o="");else n=r.createTag(e,t,o);return n}el(e,t,o){return this.html(e,t,o)}}