mirror of
https://github.com/chinchang/web-maker.git
synced 2025-05-06 18:45:31 +02:00
1 line
54 KiB
JavaScript
1 line
54 KiB
JavaScript
'serviceWorker'in navigator&&-1===document.cookie.indexOf('wmdebug')&&window.addEventListener('load',function(){navigator.serviceWorker.register('service-worker.js').then(function(e){e.onupdatefound=function(){var t=e.installing;t.onstatechange=function(){switch(t.state){case'installed':navigator.serviceWorker.controller?console.log('New or updated content is available.'):(console.log('Content is now available offline!'),window.alertsService&&window.alertsService.add('Web Maker is now ready to be used offline.'));break;case'redundant':console.error('The installing service worker became redundant.');}}}}).catch(function(t){console.error('Error during service worker registration:',t)})}),function(){window.DEBUG=-1<document.cookie.indexOf('wmdebug'),window.$=document.querySelector.bind(document),window.$all=(e)=>[...document.querySelectorAll(e)];var e='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';Node.prototype.nextUntil=function(e){const t=[...this.parentNode.querySelectorAll(e)],s=t.indexOf(this);return t[s+1]},window.requestIdleCallback=window.requestIdleCallback||function(e){setTimeout(e,10)},Node.prototype.previousUntil=function(e){const t=[...this.parentNode.querySelectorAll(e)],s=t.indexOf(this);return t[s-1]},window.utils={semverCompare:function(e,t){for(var s=e.split('.'),o=t.split('.'),a=0;3>a;a++){var i=+s[a],n=+o[a];if(i>n)return 1;if(n>i)return-1;if(!isNaN(i)&&isNaN(n))return 1;if(isNaN(i)&&!isNaN(n))return-1}return 0},generateRandomId:function(t){for(var s='',o=t||10;o--;)s+=e[~~(Math.random()*e.length)];return s},onButtonClick:function(e,t){e.addEventListener('click',function(s){return t(s),!1})},addInfiniteLoopProtection:function(e){var t=1,s=[],i='_wmloopvar';return esprima.parse(e,{tolerant:!0,range:!0,jsx:!0},function(e){switch(e.type){case'DoWhileStatement':case'ForStatement':case'ForInStatement':case'ForOfStatement':case'WhileStatement':var o=1+e.body.range[0],a=e.body.range[1],n='\nif (Date.now() - %d > 1000) { window.top.previewException(new Error("Infinite loop")); break;}\n'.replace('%d',i+t),l='';'BlockStatement'!==e.body.type&&(n='{'+n,l='}',--o),s.push({pos:o,str:n}),s.push({pos:a,str:l}),s.push({pos:e.range[0],str:'var %d = Date.now();\n'.replace('%d',i+t)}),++t;break;default:}}),s.sort(function(e,t){return t.pos-e.pos}).forEach(function(t){e=e.slice(0,t.pos)+t.str+e.slice(t.pos)}),e},getHumanDate:function(e){var t=new Date(e),s=t.getDate()+' '+['January','February','March','April','May','June','July','August','September','October','November','December'][t.getMonth()]+' '+t.getFullYear();return s},log:function(){window.DEBUG&&console.log(...arguments)},once:function(e,t,s){e.addEventListener(t,function(i){return i.target.removeEventListener(t,arguments.callee),s(i)})},downloadFile:function(e,t){function s(){var s=document.createElement('a');s.href=window.URL.createObjectURL(t),s.download=e,s.style.display='none',document.body.appendChild(s),s.click(),s.remove()}window.IS_EXTENSION?chrome.downloads.download({url:window.URL.createObjectURL(t),filename:e,saveAs:!0},()=>{chrome.runtime.lastError&&s()}):s()}},window.chrome=window.chrome||{},window.chrome.i18n={getMessage:()=>{}},window.IS_EXTENSION=!!window.chrome.extension,window.IS_EXTENSION?document.body.classList.add('is-extension'):document.body.classList.add('is-app')}(),(()=>{async function e(){return i?i:(utils.log('Initializing firestore'),i=new Promise((e,t)=>s?e(s):firebase.firestore().enablePersistence().then(function(){s=firebase.firestore(),utils.log('firebase db ready',s),e(s)}).catch(function(e){t(e.code),'failed-precondition'===e.code?(alert('Opening Web Maker web app in multiple tabs isn\'t supported at present and it seems like you already have it opened in another tab. Please use in one tab.'),window.trackEvent('fn','multiTabError')):'unimplemented'===e.code})),i)}const t=1;var s,i,o={get:(e,s)=>{const i={};'string'==typeof e?(i[e]=JSON.parse(window.localStorage.getItem(e)),setTimeout(()=>s(i),t)):(Object.keys(e).forEach((t)=>{const s=window.localStorage.getItem(t);i[t]=s===void 0||null===s?e[t]:JSON.parse(s)}),setTimeout(()=>s(i),t))},set:(e,s)=>{Object.keys(e).forEach((t)=>{window.localStorage.setItem(t,JSON.stringify(e[t]))}),setTimeout(()=>{if(s)return s()},t)}};const a=chrome&&chrome.storage?chrome.storage.local:o,n=chrome&&chrome.storage?chrome.storage.sync:o;window.db={getDb:e,getUser:async function(t){const s=await e();return s.doc(`users/${t}`).get().then((e)=>{if(!e.exists)return s.doc(`users/${t}`).set({},{merge:!0});const i=e.data();return Object.assign(window.user,i),i})},getUserLastSeenVersion:async function(){const e=deferred();return n.get({lastSeenVersion:''},(t)=>{e.resolve(t.lastSeenVersion)}),e.promise},setUserLastSeenVersion:async function(t){if(n.set({lastSeenVersion:t},function(){}),window.user){const s=await e();s.doc(`users/${window.user.uid}`).update({lastSeenVersion:t})}},getSettings:function(e){const t=deferred();return n.get(e,(e)=>{t.resolve(e)}),t.promise},local:a,sync:n}})(),window.logout=function(){firebase.auth().signOut()};function login(e){var t;return'facebook'===e?t=new firebase.auth.FacebookAuthProvider:'twitter'===e?t=new firebase.auth.TwitterAuthProvider:'google'===e?(t=new firebase.auth.GoogleAuthProvider,t.addScope('https://www.googleapis.com/auth/userinfo.profile')):t=new firebase.auth.GithubAuthProvider,firebase.auth().signInWithPopup(t).then(function(){window.trackEvent('fn','loggedIn',e),window.db.local.set({lastAuthProvider:e})}).catch(function(e){alert('You have already signed up with the same email using different social login'),utils.log(e)})}window.login=login,window.trackEvent=function(e,t,s,i){return window.DEBUG?void utils.log('trackevent',e,t,s,i):void(window.ga&&ga('send','event',e,t,s,i))},navigator.onLine&&!window.DEBUG&&setTimeout(function(){(function(e,t,s,i,o,n,a){e.GoogleAnalyticsObject=o,e[o]=e[o]||function(){(e[o].q=e[o].q||[]).push(arguments)},e[o].l=1*new Date,n=t.createElement(s),a=t.getElementsByTagName(s)[0],n.async=1,n.src=i,a.parentNode.insertBefore(n,a)})(window,document,'script','https://www.google-analytics.com/analytics.js','ga'),ga('create','UA-87786708-1'),ga('send','pageview')},100),function(){window.deferred=function(){var e={},t=new Promise(function(t,s){e.resolve=t,e.reject=s});return e.promise=t,Object.assign(e,t)}}(),function(e){window.loadJS=function(t){var s=deferred(),i=e.document.getElementsByTagName('script')[0],o=e.document.createElement('script');return o.src=t,o.async=!0,i.parentNode.insertBefore(o,i),o.onload=function(){s.resolve()},s.promise}}(window),function(){const e=$('#js-alerts-container');var t;window.alertsService={add:function(s){e.textContent=s,e.classList.add('is-active'),clearTimeout(t),t=setTimeout(function(){e.classList.remove('is-active')},2e3)}}}(),window.jsLibs=[{url:'https://code.jquery.com/jquery-3.2.1.min.js',label:'jQuery',type:'js'},{url:'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js',label:'Bootstrap 3',type:'js'},{url:'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js',label:'Bootstrap 4',type:'js'},{url:'https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.3/js/foundation.min.js',label:'Foundation',type:'js'},{url:'https://semantic-ui.com/dist/semantic.min.js',label:'Semantic UI',type:'js'},{url:'https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js',label:'Angular',type:'js'},{url:'https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.production.min.js',label:'React',type:'js'},{url:'https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.production.min.js',label:'React DOM',type:'js'},{url:'https://unpkg.com/vue',label:'Vue.js',type:'js'},{url:'https://cdnjs.cloudflare.com/ajax/libs/three.js/89/three.min.js',label:'Three.js',type:'js'},{url:'https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js',label:'D3',type:'js'},{url:'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js',label:'Underscore',type:'js'},{url:'https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/TweenMax.min.js',label:'Greensock TweenMax',type:'js'},{url:'https://cdnjs.cloudflare.com/ajax/libs/uikit/2.27.4/js/uikit.min.js',label:'UIkit 2',type:'js'},{url:'https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.39/js/uikit.min.js',label:'UIkit 3',type:'js'}],window.cssLibs=[{url:'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css',label:'Bootstrap 3',type:'css'},{url:'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css',label:'Bootstrap 4',type:'css'},{url:'https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.3/css/foundation.min.css',label:'Foundation',type:'css'},{url:'https://semantic-ui.com/dist/semantic.min.css',label:'Semantic UI',type:'css'},{url:'https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css',label:'Bulma',type:'css'},{url:'https://cdnjs.cloudflare.com/ajax/libs/hint.css/2.5.0/hint.min.css',label:'Hint.css',type:'css'},{url:'https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css',label:'Tailwind.css',type:'css'},{url:'https://cdnjs.cloudflare.com/ajax/libs/uikit/2.27.4/css/uikit.min.css',label:'UIkit 2',type:'css'},{url:'https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.39/css/uikit.min.css',label:'UIkit 3',type:'css'},{url:'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css',label:'Animate.css',type:'css'},{url:'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css',label:'FontAwesome 4',type:'css'},{url:'https://use.fontawesome.com/releases/v5.0.6/css/all.css',label:'FontAwesome 5',type:'css'}],function(){class e{constructor(e,t){this.t=e,this.filter=t.filter,this.selectedCallback=t.selectedCallback;var s=document.createElement('div');s.classList.add('btn-group'),e.parentElement.insertBefore(s,e),s.insertBefore(e,null),this.list=document.createElement('ul'),this.list.classList.add('dropdown__menu'),this.list.classList.add('autocomplete-dropdown'),s.insertBefore(this.list,null),this.loader=document.createElement('div'),this.loader.classList.add('loader'),this.loader.classList.add('autocomplete__loader'),this.loader.style.display='none',s.insertBefore(this.loader,null),setTimeout(()=>{requestIdleCallback(()=>{document.body.appendChild(this.list),this.list.style.position='fixed'})},100),this.t.addEventListener('input',(t)=>this.onInput(t)),this.t.addEventListener('keydown',(t)=>this.onKeyDown(t)),this.t.addEventListener('blur',(t)=>this.closeSuggestions(t)),this.list.addEventListener('mousedown',(t)=>this.onListMouseDown(t))}get currentLineNumber(){return this.t.value.substr(0,this.t.selectionStart).split('\n').length}get currentLine(){var e=this.currentLineNumber;return this.t.value.split('\n')[e-1]}closeSuggestions(){this.list.classList.remove('is-open'),this.isShowingSuggestions=!1}getList(e){return fetch('https://api.cdnjs.com/libraries?search='+e).then((e)=>e.json().then((e)=>e.results))}replaceCurrentLine(e){var t=this.t.value.split('\n');t.splice(this.currentLineNumber-1,1,e),this.t.value=t.join('\n')}onInput(){var e=this.currentLine;if(e){if(-1!==e.indexOf('/')||e.match(/https*:\/\//))return;clearTimeout(this.timeout),this.timeout=setTimeout(()=>{this.loader.style.display='block',this.getList(e).then((e)=>{if(this.loader.style.display='none',!e.length)return void this.closeSuggestions();this.list.innerHTML='',this.filter&&(e=e.filter(this.filter));for(var t=0;t<Math.min(e.length,10);t++)this.list.innerHTML+=`<li data-url="${e[t].latest}"><a>${e[t].name}</a></li>`;this.isShowingSuggestions=!0,this.textareaBounds||(this.textareaBounds=this.t.getBoundingClientRect(),this.list.style.top=this.textareaBounds.bottom+'px',this.list.style.left=this.textareaBounds.left+'px',this.list.style.width=this.textareaBounds.width+'px'),this.list.classList.add('is-open')})},500)}}onKeyDown(e){var t;this.isShowingSuggestions&&(27===e.keyCode&&(this.closeSuggestions(),e.stopPropagation()),40===e.keyCode&&this.isShowingSuggestions?(t=this.list.querySelector('.selected'),t?(t.classList.remove('selected'),t.nextElementSibling.classList.add('selected')):this.list.querySelector('li:first-child').classList.add('selected'),this.list.querySelector('.selected').scrollIntoView(!1),e.preventDefault()):38===e.keyCode&&this.isShowingSuggestions?(t=this.list.querySelector('.selected'),t?(t.classList.remove('selected'),t.previousElementSibling.classList.add('selected')):this.list.querySelector('li:first-child').classList.add('selected'),this.list.querySelector('.selected').scrollIntoView(!1),e.preventDefault()):13===e.keyCode&&this.isShowingSuggestions&&(t=this.list.querySelector('.selected'),this.selectSuggestion(t.dataset.url),this.closeSuggestions()))}onListMouseDown(e){var t=e.target;t.parentElement.dataset.url&&this.selectSuggestion(t.parentElement.dataset.url)}selectSuggestion(e){this.selectedCallback?this.selectedCallback.call(null,e):this.replaceCurrentLine(e),this.closeSuggestions()}}window.TextareaAutoComplete=e}(),(()=>{window.itemService={async getItem(e){var t=await window.db.getDb();return t.doc(`items/${e}`).get().then((e)=>e.data())},async getUserItemIds(){if(window.user)return new Promise((e)=>{e(window.user.items||{})});var e=await window.db.getDb();return e.doc(`users/${window.user.uid}`).get().then((e)=>e.exists?e.data().items:{})},async getAllItems(){var e=Date.now(),t=deferred();let s=await this.getUserItemIds();s=Object.getOwnPropertyNames(s||{}),utils.log('itemids',s),s.length||t.resolve([]);var i=await window.db.getDb();const o=[];return i.collection('items').where('createdBy','==',window.user.uid).onSnapshot(function(s){s.forEach(function(e){o.push(e.data())}),utils.log('Items fetched in ',Date.now()-e,'ms'),t.resolve(o)},function(){t.resolve([])}),t.promise},async setUser(){const e=await window.db.getDb();return e.doc(`users/${window.user.uid}`).set({items:{}})},async setItem(e,t){const s=deferred();var i;if(db.local.set({[e]:t},()=>{!window.IS_EXTENSION&&window.user&&navigator.onLine||s.resolve()}),'code'===e)return!1;if(window.user){var o=await window.db.getDb();utils.log(`Starting to save item ${e}`),t.createdBy=window.user.uid,i=o.collection('items').doc(e).set(t,{merge:!0}).then((e)=>{utils.log('Document written',e),s.resolve()}).catch(s.reject)}return window.user&&navigator.onLine?i:s.promise},saveItems(e){var t=deferred();return window.user?window.db.getDb().then((s)=>{const i=s.batch();for(var o in e)e[o].createdBy=window.user.uid,i.set(s.doc(`items/${o}`),e[o]),i.update(s.doc(`users/${window.user.uid}`),{[`items.${o}`]:!0}),window.user.items=window.user.items||{},window.user.items[o]=!0;i.commit().then(t.resolve)}):(window.db.local.set(e,t.resolve),window.db.local.get({items:{}},function(t){for(var s in e)t.items[s]=!0;window.db.local.set({items:t.items})})),t.promise},async removeItem(e){if(!window.user){var t=deferred();return db.local.remove(e,t.resolve),t.promise}const s=await window.db.getDb();return utils.log(`Starting to save item ${e}`),s.collection('items').doc(e).delete().then((e)=>{utils.log('Document removed',e)}).catch((e)=>utils.log(e))},async setItemForUser(e){if(!window.user)return window.db.local.get({items:{}},function(t){t.items[e]=!0,window.db.local.set({items:t.items})});const t=await window.db.getDb();return t.collection('users').doc(window.user.uid).update({[`items.${e}`]:!0}).then((t)=>{utils.log(`Item ${e} set for user`,t),window.user.items=window.user.items||{},window.user.items[e]=!0}).catch((e)=>utils.log(e))},async unsetItemForUser(e){if(!window.user)return window.db.local.get({items:{}},function(t){delete t.items[e],db.local.set({items:t.items})});const t=await window.db.getDb();return t.collection('users').doc(window.user.uid).update({[`items.${e}`]:firebase.firestore.FieldValue.delete()}).then((t)=>{delete window.user.items[e],utils.log(`Item ${e} unset for user`,t)}).catch((e)=>utils.log(e))}}})(),function(e,t){function s(){clearTimeout(s.timeout),s.timeout=setTimeout(function(){const e=2===oe||5===oe?'width':'height';[je,Ee,xe].forEach(function(t){const s=t.getBoundingClientRect(),i=s[e];100>i?t.classList.add('is-minimized'):t.classList.remove('is-minimized'),-1===t.style[e].indexOf(`100% - ${2*ye}px`)?t.classList.remove('is-maximized'):t.classList.add('is-maximized')})},50)}function i(e){if(e.classList.contains('is-minimized')||e.classList.contains('is-maximized'))e.classList.remove('is-minimized'),e.classList.remove('is-maximized'),ce.setSizes([33.3,33.3,33.3]);else{const s=parseInt(e.dataset.codeWrapId,10);var t=[`${ye}px`,`${ye}px`,`${ye}px`];t[s]=`calc(100% - ${2*ye}px)`,ce.setSizes(t),e.classList.add('is-maximized')}}function o(){var e;return e=ne&&ne.mainSizes?3===oe?[ne.mainSizes[1],ne.mainSizes[0]]:ne.mainSizes:5===oe?[75,25]:[50,50],e}function a(){ce&&ce.destroy(),de&&de.destroy();var e={direction:2===oe||5===oe?'horizontal':'vertical',minSize:ye,gutterSize:6,onDragStart:function(){document.body.classList.add('is-dragging')},onDragEnd:function(){s(),document.body.classList.remove('is-dragging')}};e.sizes=ne&&ne.sizes?ne.sizes:[33.33,33.33,33.33],ce=Split(['#js-html-code','#js-css-code','#js-js-code'],e),de=Split(['#js-code-side','#js-demo-side'],{direction:2===oe?'vertical':'horizontal',minSize:150,gutterSize:6,sizes:o(),onDragEnd:function(){Se.refreshOnResize&&setTimeout(function(){Y.setPreviewContent(!0)},1)}})}function n(e){return oe===e?(de.setSizes(o()),ce.setSizes(ne.sizes||[33.33,33.33,33.33]),void(oe=e)):void(oe=e,[1,2,3,4,5].forEach((e)=>{window[`layoutBtn${e}`].classList.remove('selected'),document.body.classList.remove(`layout-${e}`)}),$('#layoutBtn'+e).classList.add('selected'),document.body.classList.add('layout-'+e),a(),Y.setPreviewContent(!0))}function l(){utils.log('onExternalLibChange'),r(),Y.setPreviewContent(!0),e.add('Libraries updated.')}function r(){var e=0;e+=Fe.value.split('\n').filter((e)=>!!e).length,e+=ze.value.split('\n').filter((e)=>!!e).length,e?($('#js-external-lib-count').textContent=e,$('#js-external-lib-count').style.display='inline'):$('#js-external-lib-count').style.display='none'}function d(e,t){const s=deferred();return db.local.set({[e]:t},s.resolve),s.promise}function c(){var s=!ne.id;ne.id=ne.id||'item-'+utils.generateRandomId(),saveBtn.classList.add('is-loading'),g().then(()=>{saveBtn.classList.remove('is-loading'),!ue&&Se.autoSave&&(ue=!0,e.add('Auto-save enabled.'))}),s&&t.setItemForUser(ne.id)}function m(){ue&&le&&c()}function u(){var e,t=2===oe||5===oe?'width':'height';try{e=[je.style[t],Ee.style[t],xe.style[t]]}catch(t){e=[33.33,33.33,33.33]}finally{return e}}function p(){var e,t=2===oe?'height':'width';try{e=[+$('#js-code-side').style[t].match(/([\d.]+)%/)[1],+$('#js-demo-side').style[t].match(/([\d.]+)%/)[1]]}catch(t){e=[50,50]}finally{return e}}function g(s){return ne.title=Pe.value,ne.html=Y.cm.html.getValue(),ne.css=Y.cm.css.getValue(),ne.js=Y.cm.js.getValue(),ne.htmlMode=ve,ne.cssMode=fe,ne.jsMode=be,ee[fe].hasSettings&&(ne.cssSettings={acssConfig:Y.acssSettingsCm.getValue()}),ne.updatedOn=Date.now(),ne.layoutMode=oe,ne.externalLibs={js:Fe.value,css:ze.value},ne.sizes=u(),ne.mainSizes=p(),utils.log('saving key',s||ne.id,ne),t.setItem(s||ne.id,ne).then(function(){window.user&&!navigator.onLine?e.add('Item saved locally. Will save to account when you are online.'):e.add('Item saved.'),le=0,saveBtn.classList.remove('is-marked')})}function h(e){var t='';e.length?(e.sort(function(e,t){return t.updatedOn-e.updatedOn}),e.forEach(function(e){t+='<div class="js-saved-item-tile saved-item-tile" data-item-id="'+e.id+'"><div class="saved-item-tile__btns"><a class="js-saved-item-tile__fork-btn saved-item-tile__btn hint--left hint--medium" aria-label="Creates a duplicate of this creation (Ctrl/\u2318 + F)">Fork<span class="show-when-selected">(Ctrl/\u2318 + F)</span></a><a class="js-saved-item-tile__remove-btn saved-item-tile__btn hint--left" aria-label="Remove">X</a></div><h3 class="saved-item-tile__title">'+e.title+'</h3><span class="saved-item-tile__meta">Last updated: '+utils.getHumanDate(e.updatedOn)+'</span></div>'}),savedItemCountEl.textContent='('+e.length+')',savedItemCountEl.style.display='inline'):(t+='<h2 class="opacity--30">Nothing saved here.</h2>',savedItemCountEl.style.display='none'),Te.querySelector('#js-saved-items-wrap').innerHTML=t,v()}function v(e){!1===e?Te.classList.remove('is-open'):Te.classList.toggle('is-open'),Le=Te.classList.contains('is-open'),Le?searchInput.focus():(searchInput.value='',me&&me.focus()),document.body.classList[Le?'add':'remove']('overlay-visible')}async function b(e){var s=deferred();re=re||{};var o=[];return window.user?(o=await t.getAllItems(),utils.log('got items'),e&&o.forEach((e)=>{re[e.id]=e}),s.resolve(o),s.promise):(db.local.get('items',function(t){var a=Object.getOwnPropertyNames(t.items||{});a.length||s.resolve([]),trackEvent('fn','fetchItems',a.length);for(let n=0;n<a.length;n++)db.local.get(a[n],function(t){e&&(re[a[n]]=t[a[n]]),o.push(t[a[n]]),a.length===o.length&&s.resolve(o)})}),s.promise)}function f(){openItemsBtn.classList.add('is-loading'),b(!0).then(function(e){openItemsBtn.classList.remove('is-loading'),h(e)})}function y(e){ne=e,utils.log('Current Item set',e),ue=!1,le=0,saveBtn.classList.remove('is-marked')}function S(t){if(le){var s=confirm('You have unsaved changes in your current work. Do you want to discard unsaved changes and continue?');if(!s)return}const i=JSON.parse(JSON.stringify(t));delete i.id,i.title='(Forked) '+t.title,i.updatedOn=Date.now(),y(i),w(),e.add(`"${t.title}" was forked`),trackEvent('fn','itemForked')}function C(){var t=new Date;y({title:'Untitled '+t.getDate()+'-'+(t.getMonth()+1)+'-'+t.getHours()+':'+t.getMinutes(),html:'',css:'',js:'',externalLibs:{js:'',css:''},layoutMode:oe}),w(),e.add('New item created')}function L(t){y(re[t]),w(),e.add('Saved item loaded')}function k(s){var i=document.querySelector('.js-saved-item-tile[data-item-id="'+s+'"]'),o=confirm(`Are you sure you want to delete "${re[s].title}"?`);o&&(i.remove(),t.unsetItemForUser(s),t.removeItem(s).then(()=>{e.add('Item removed.'),ne.id===s&&C()}),delete re[s],trackEvent('fn','itemRemoved'))}function w(){Pe.value=ne.title||'Untitled',Fe.value=ne.externalLibs&&ne.externalLibs.js||'',ze.value=ne.externalLibs&&ne.externalLibs.css||'',utils.log('refresh editor'),ve=ne.htmlMode||Se.htmlMode||X.HTML,fe=ne.cssMode||Se.cssMode||Z.CSS,be=ne.jsMode||Se.jsMode||Q.JS,Y.cm.html.setValue(ne.html),Y.cm.css.setValue(ne.css),Y.cm.js.setValue(ne.js),Y.cm.html.refresh(),Y.cm.css.refresh(),Y.cm.js.refresh(),Y.acssSettingsCm.setValue(ne.cssSettings?ne.cssSettings.acssConfig:''),Y.acssSettingsCm.refresh(),Y.clearConsole(),r(),Promise.all([x(ve),M(fe),T(be)]).then(()=>Y.setPreviewContent(!0)),n(ne.layoutMode||Se.layoutMode)}function j(){helpModal.classList.remove('is-modal-visible'),notificationsModal.classList.remove('is-modal-visible'),addLibraryModal.classList.remove('is-modal-visible'),onboardModal.classList.remove('is-modal-visible'),settingsModal.classList.remove('is-modal-visible'),cssSettingsModal.classList.remove('is-modal-visible'),keyboardShortcutsModal.classList.remove('is-modal-visible'),loginModal.classList.remove('is-modal-visible'),profileModal.classList.remove('is-modal-visible'),pledgeModal.classList.remove('is-modal-visible'),v(!1),document.dispatchEvent(new Event('overlaysClosed'))}function E(e){function t(){ee[e].hasLoaded=!0,i.resolve()}const s='lib/transpilers';var i=deferred();return ee[e].hasLoaded?(i.resolve(),i.promise):(e===X.JADE?loadJS(`${s}/jade.js`).then(t):e===X.MARKDOWN?loadJS(`${s}/marked.js`).then(t):e===Z.LESS?loadJS(`${s}/less.min.js`).then(t):e===Z.SCSS||e===Z.SASS?loadJS(`${s}/sass.js`).then(function(){ae=new Sass(`${s}/sass.worker.js`),t()}):e===Z.STYLUS?loadJS(`${s}/stylus.min.js`).then(t):e===Z.ACSS?loadJS(`${s}/atomizer.browser.js`).then(t):e===Q.COFFEESCRIPT?loadJS(`${s}/coffee-script.js`).then(t):e===Q.ES6?loadJS(`${s}/babel.min.js`).then(t):e===Q.TS?loadJS(`${s}/typescript.js`).then(t):i.resolve(),i.promise)}function x(e){return ve=e,De.textContent=ee[e].label,De.parentElement.querySelector('select').value=e,Y.cm.html.setOption('mode',ee[e].cmMode),CodeMirror.autoLoadMode(Y.cm.html,ee[e].cmPath||ee[e].cmMode),E(e)}function M(e){return fe=e,Oe.textContent=ee[e].label,Oe.parentElement.querySelector('select').value=e,Y.cm.css.setOption('mode',ee[e].cmMode),Y.cm.css.setOption('readOnly',ee[e].cmDisable),cssSettingsBtn.classList[ee[e].hasSettings?'remove':'add']('hide'),CodeMirror.autoLoadMode(Y.cm.css,ee[e].cmPath||ee[e].cmMode),E(e)}function T(e){return be=e,Ae.textContent=ee[e].label,Ae.parentElement.querySelector('select').value=e,Y.cm.js.setOption('mode',ee[e].cmMode),CodeMirror.autoLoadMode(Y.cm.js,ee[e].cmPath||ee[e].cmMode),E(e)}function I(){var e=deferred(),t=Y.cm.html.getValue();return ve===X.HTML?e.resolve(t):ve===X.MARKDOWN?e.resolve(marked?marked(t):t):ve===X.JADE&&e.resolve(window.jade?jade.render(t):t),e.promise}function D(){var e=deferred(),t=Y.cm.css.getValue();if(A('css'),fe===Z.CSS)e.resolve(t);else if(fe===Z.SCSS||fe===Z.SASS)ae&&t?ae.compile(t,{indentedSyntax:fe===Z.SASS},function(t){t.line&&t.message&&P('css',[{lineNumber:t.line-1,message:t.message}]),e.resolve(t.text)}):e.resolve(t);else if(fe===Z.LESS)less.render(t).then(function(t){e.resolve(t.css)},function(e){P('css',[{lineNumber:e.line,message:e.message}])});else if(fe===Z.STYLUS)stylus(t).render(function(t,s){if(t){window.err=t;var i=t.message.split('\n');i.pop(),P('css',[{lineNumber:+t.message.match(/stylus:(\d+):/)[1]-298,message:i.pop()}])}e.resolve(s)});else if(fe===Z.ACSS)if(!window.atomizer)e.resolve('');else{const t=Y.cm.html.getValue(),i=atomizer.findClassNames(t);var s;try{s=atomizer.getConfig(i,JSON.parse(Y.acssSettingsCm.getValue()))}catch(t){s=atomizer.getConfig(i,{})}const o=atomizer.getCss(s);Y.cm.css.setValue(o),e.resolve(o)}return e.promise}function O(e){var t=deferred(),s=Y.cm.js.getValue();if(A('js'),!s)return t.resolve(''),t.promise;if(be===Q.JS)try{esprima.parse(s,{tolerant:!0})}catch(t){P('js',[{lineNumber:t.lineNumber-1,message:t.description}])}finally{!1!==e&&(s=utils.addInfiniteLoopProtection(s)),t.resolve(s)}else if(be===Q.COFFEESCRIPT){if(!window.CoffeeScript)return t.resolve(''),t.promise;try{s=CoffeeScript.compile(s,{bare:!0})}catch(t){P('js',[{lineNumber:t.location.first_line,message:t.message}])}finally{!1!==e&&(s=utils.addInfiniteLoopProtection(s)),t.resolve(s)}}else if(be===Q.ES6){if(!window.Babel)return t.resolve(''),t.promise;try{esprima.parse(s,{tolerant:!0,jsx:!0})}catch(t){P('js',[{lineNumber:t.lineNumber-1,message:t.description}])}finally{s=Babel.transform(s,{presets:['latest','stage-2','react']}).code,!1!==e&&(s=utils.addInfiniteLoopProtection(s)),t.resolve(s)}}else if(be===Q.TS)try{if(!window.ts)return t.resolve(''),t.promise;if(s=ts.transpileModule(s,{reportDiagnostics:!0,compilerOptions:{noEmitOnError:!0,diagnostics:!0,module:ts.ModuleKind.ES2015}}),s.diagnostics.length)throw{description:s.diagnostics[0].messageText,lineNumber:ts.getLineOfLocalPosition(s.diagnostics[0].file,s.diagnostics[0].start)};!1!==e&&(s=utils.addInfiniteLoopProtection(s.outputText)),t.resolve(s)}catch(t){P('js',[{lineNumber:t.lineNumber-1,message:t.description}])}return t.promise}function A(e){Y.cm[e].clearGutter('error-gutter')}function P(e,t){var s=Y.cm[e];t.forEach(function(t){s.operation(function(){var e=document.createElement('div');e.setAttribute('data-title',t.message),e.classList.add('gutter-error-marker'),s.setGutterMarker(t.lineNumber,'error-gutter',e)})})}function B(e,t,s,i){var o=Fe.value.split('\n').reduce(function(e,t){return e+(t?'\n<script src="'+t+'"></script>':'')},''),a=ze.value.split('\n').reduce(function(e,t){return e+(t?'\n<link rel="stylesheet" href="'+t+'"></link>':'')},''),n='<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8" />\n'+a+'\n<style id="webmakerstyle">\n'+t+'\n</style>\n</head>\n<body>\n'+e+'\n'+o+'\n';if(i||(n+='<script src="'+(chrome.extension?chrome.extension.getURL('lib/screenlog.js'):`${location.origin}${te}/lib/screenlog.js`)+'"></script>'),be===Q.ES6&&(n+='<script src="'+(chrome.extension?chrome.extension.getURL('lib/transpilers/babel-polyfill.min.js'):`${location.origin}${te}/lib/transpilers/babel-polyfill.min.js`)+'"></script>'),'string'==typeof s)n+='<script>\n'+s+'\n//# sourceURL=userscript.js';else{var l=chrome.i18n.getMessage()?`chrome-extension://${chrome.i18n.getMessage('@@extension_id')}`:`${location.origin}`;n+='<script src="'+`filesystem:${l}/temporary/script.js`+'">'}return n+='\n</script>\n</body>\n</html>',n}function F(e,t,s){function i(e){return function(){utils.log(arguments),trackEvent('fn','error',e),F.errorCount=(F.errorCount||0)+1,4===F.errorCount&&setTimeout(function(){alert('Oops! Seems like your preview isn\'t updating. Please try the following steps until it fixes:\n - Refresh Web Maker\n - Restart browser\n - Update browser\n - Reinstall Web Maker (don\'t forget to export all your creations from saved items pane (click the OPEN button) before reinstalling)\n\nIf nothing works, please tweet out to @webmakerApp.'),trackEvent('ui','writeFileMessageSeen')},1e3)}}var o=!1;window.webkitRequestFileSystem(window.TEMPORARY,5242880,function(a){a.root.getFile(e,{create:!0},function(e){e.createWriter((e)=>{e.onwriteend=function(){return o?s():(o=!0,e.seek(0),e.write(t),!1)},e.truncate(0)},i('createWriterFail'))},i('getFileFail'))},i('webkitRequestFileSystemFail'))}function z(e,t,s){const i=!window.webkitRequestFileSystem||!window.IS_EXTENSION;var o=B(e,t,i?s:null),a=new Blob([o],{type:'text/plain;charset=UTF-8'}),n=new Blob([s],{type:'text/plain;charset=UTF-8'});!trackEvent.hasTrackedCode&&(e||t||s)&&(trackEvent('fn','hasCode'),trackEvent.hasTrackedCode=!0),i?Y.detachedWindow?(utils.log('\u2709\uFE0F Sending message to detached window'),Y.detachedWindow.postMessage({contents:o},'*')):(we.src=we.src,setTimeout(()=>{we.contentDocument.open(),we.contentDocument.write(o),we.contentDocument.close()},10)):F('script.js',n,function(){F('preview.html',a,function(){var e=chrome.i18n.getMessage()?`chrome-extension://${chrome.i18n.getMessage('@@extension_id')}`:`${location.origin}`,t=`filesystem:${e}/temporary/preview.html`;Y.detachedWindow?Y.detachedWindow.postMessage(t,'*'):we.src=t})})}function N(){var e=I(),t=D(),s=O(!1);Promise.all([e,t,s]).then(function(e){var t=e[0],s=e[1],i=e[2],o=B(t,s,i,!0),a=new Date,n=['web-maker',a.getFullYear(),a.getMonth()+1,a.getDate(),a.getHours(),a.getMinutes(),a.getSeconds()].join('-');n+='.html',ne.title&&(n=ne.title);var l=new Blob([o],{type:'text/html;charset=UTF-8'});utils.downloadFile(n,l),trackEvent('fn','saveFileComplete')})}function V(e,t){var s=CodeMirror(e,{mode:t.mode,lineNumbers:!0,lineWrapping:!0,autofocus:t.autofocus||!1,autoCloseBrackets:!0,autoCloseTags:!0,matchBrackets:!0,matchTags:t.matchTags||!1,tabMode:'indent',keyMap:'sublime',theme:'monokai',lint:!!t.lint,tabSize:2,foldGutter:!0,styleActiveLine:!0,gutters:t.gutters||[],profile:t.profile||'',extraKeys:{Up:function(e){Le||CodeMirror.commands.goLineUp(e)},Down:function(e){Le||CodeMirror.commands.goLineDown(e)},"Shift-Tab":function(e){CodeMirror.commands.indentAuto(e)},Tab:function(e){if(t.emmet){const t=e.execCommand('emmetExpandAbbreviation');if(!0===t)return}const s=$('[data-setting=indentWith]:checked');e.somethingSelected()||s&&'spaces'!==s.value?CodeMirror.commands.defaultTab(e):CodeMirror.commands.insertSoftTab(e)},Enter:'emmetInsertLineBreak'}});return s.on('focus',(e)=>{me=e}),s.on('change',function(e,t){clearTimeout(se),se=setTimeout(function(){'setValue'!==t.origin&&(!1!==Se.autoPreview&&Y.setPreviewContent(),saveBtn.classList.add('is-marked'),le+=1,0==le%ge&&le>=ge&&(saveBtn.classList.add('animated'),saveBtn.classList.add('wobble'),saveBtn.addEventListener('animationend',()=>{saveBtn.classList.remove('animated'),saveBtn.classList.remove('wobble')})),trackEvent.previewCount=(trackEvent.previewCount||0)+1,4===trackEvent.previewCount&&trackEvent('fn','usingPreview'))},pe)}),s.addKeyMap({"Ctrl-Space":'autocomplete'}),t.noAutocomplete||s.on('inputRead',function(e,t){Se.autoComplete&&'+input'===t.origin&&';'!==t.text[0]&&','!==t.text[0]&&' '!==t.text[0]&&CodeMirror.commands.autocomplete(s,null,{completeSingle:!1})}),s}function U(){Y.toggleModal(settingsModal)}function _(s){var i=[],o={};s.forEach((e)=>{re[e.id]?i.push(e.id):(utils.log('merging',e.id),o[e.id]=e)});var a=s.length-i.length;if(i.length){var n=confirm(i.length+' creations already exist. Do you want to replace them?');n&&(utils.log('shouldreplace',n),s.forEach((e)=>{o[e.id]=e}),a=s.length)}a&&t.saveItems(o).then(()=>{e.add(a+' creations imported successfully.'),trackEvent('fn','itemsImported',a)}),v(!1)}function W(t){var e=t.target.files[0],s=new FileReader;s.onload=function(e){var t;try{t=JSON.parse(e.target.result),utils.log(t),_(t)}catch(e){utils.log(e),alert('Oops! Selected file is corrupted. Please select a file that was generated by clicking the "Export" button.')}},s.readAsText(e,'utf-8')}function R(e){function t(){var e='filesystem:chrome-extension://'+chrome.i18n.getMessage('@@extension_id')+'/temporary/'+d;chrome.downloads.download({url:e},function(){chrome.runtime.lastError&&window.open(e)})}function s(t){utils.log(t)}for(var o=atob(e.split(',')[1]),a=e.split(',')[0].split(':')[1].split(';')[0],n=new ArrayBuffer(o.length),l=new Uint8Array(n),r=0;r<o.length;r++)l[r]=o.charCodeAt(r);var i=new Blob([n],{type:a}),c=i.size+512,m=new Date,d=['web-maker-screenshot',m.getFullYear(),m.getMonth()+1,m.getDate(),m.getHours(),m.getMinutes(),m.getSeconds()].join('-');d+='.png',window.webkitRequestFileSystem(window.TEMPORARY,c,(e)=>{e.root.getFile(d,{create:!0},(e)=>{e.createWriter((e)=>{e.onwriteend=t,e.write(i)},s)},s)},s)}function q(){var e=deferred();return window.IS_EXTENSION?(chrome.permissions.contains({permissions:['downloads']},function(t){t?e.resolve():chrome.permissions.request({permissions:['downloads']},function(t){t?(trackEvent('fn','downloadsPermGiven'),e.resolve()):e.reject()})}),e.promise):(e.resolve(),e.promise)}function K(){$('[data-setting=preserveLastCode]').checked=Se.preserveLastCode,$('[data-setting=replaceNewTab]').checked=Se.replaceNewTab,$('[data-setting=htmlMode]').value=Se.htmlMode,$('[data-setting=cssMode]').value=Se.cssMode,$('[data-setting=jsMode]').value=Se.jsMode,$('[data-setting=indentSize]').value=Se.indentSize,indentationSizeValueEl.textContent=Se.indentSize,$('[data-setting=indentWith][value='+(Se.indentWith||'spaces')+']').checked=!0,$('[data-setting=isCodeBlastOn]').checked=Se.isCodeBlastOn,$('[data-setting=editorTheme]').value=Se.editorTheme,$('[data-setting=keymap][value='+(Se.keymap||'sublime')+']').checked=!0,$('[data-setting=fontSize]').value=Se.fontSize||16,$('[data-setting=refreshOnResize]').checked=Se.refreshOnResize,$('[data-setting=autoPreview]').checked=Se.autoPreview,$('[data-setting=editorFont]').value=Se.editorFont,$('[data-setting=editorCustomFont]').value=Se.editorCustomFont,$('[data-setting=autoSave]').checked=Se.autoSave,$('[data-setting=autoComplete]').checked=Se.autoComplete,$('[data-setting=preserveConsoleLogs]').checked=Se.preserveConsoleLogs,$('[data-setting=lightVersion]').checked=Se.lightVersion,$('[data-setting=lineWrap]').checked=Se.lineWrap}function H(e){function t(t){const e=s(`[d-${t}]`);e.forEach(function(s){s.addEventListener(t,function(i){Y[s.getAttribute(`d-${t}`)].call(window,i)})})}e instanceof Node||(e=document);const s=(t)=>[...e.querySelectorAll(t)];t('click'),t('change'),t('input'),t('keyup');const i=s(`[d-open-modal]`);i.forEach(function(e){utils.onButtonClick(e,function(){Y.toggleModal(window[e.getAttribute('d-open-modal')]),trackEvent(e.getAttribute('data-event-category'),e.getAttribute('data-event-action'))})});const o=s(`[d-html]`);o.forEach(function(e){fetch(e.getAttribute('d-html')).then((t)=>{e.removeAttribute('d-html'),t.text().then((t)=>{requestIdleCallback(()=>{e.innerHTML=t,H(e)})})})})}var Y=Y||{},G='3.0.0';window.DEBUG&&(window.scope=Y);const J={preserveLastCode:!0,replaceNewTab:!1,htmlMode:'html',jsMode:'js',cssMode:'css',isCodeBlastOn:!1,indentWith:'spaces',indentSize:2,editorTheme:'monokai',keymap:'sublime',fontSize:16,refreshOnResize:!1,autoPreview:!0,editorFont:'FiraCode',editorCustomFont:'',autoSave:!0,autoComplete:!0,preserveConsoleLogs:!0,lightVersion:!1,lineWrap:!0};var X={HTML:'html',MARKDOWN:'markdown',JADE:'jade'},Z={CSS:'css',SCSS:'scss',SASS:'sass',LESS:'less',STYLUS:'stylus',ACSS:'acss'},Q={JS:'js',ES6:'es6',COFFEESCRIPT:'coffee',TS:'typescript'},ee={};ee[X.HTML]={label:'HTML',cmMode:'htmlmixed',codepenVal:'none'},ee[X.MARKDOWN]={label:'Markdown',cmMode:'markdown',codepenVal:'markdown'},ee[X.JADE]={label:'Pug',cmMode:'pug',codepenVal:'pug'},ee[Q.JS]={label:'JS',cmMode:'javascript',codepenVal:'none'},ee[Q.COFFEESCRIPT]={label:'CoffeeScript',cmMode:'coffeescript',codepenVal:'coffeescript'},ee[Q.ES6]={label:'ES6 (Babel)',cmMode:'jsx',codepenVal:'babel'},ee[Q.TS]={label:'TypeScript',cmPath:'jsx',cmMode:'text/typescript-jsx',codepenVal:'typescript'},ee[Z.CSS]={label:'CSS',cmPath:'css',cmMode:'css',codepenVal:'none'},ee[Z.SCSS]={label:'SCSS',cmPath:'css',cmMode:'text/x-scss',codepenVal:'scss'},ee[Z.SASS]={label:'SASS',cmMode:'sass',codepenVal:'sass'},ee[Z.LESS]={label:'LESS',cmPath:'css',cmMode:'text/x-less',codepenVal:'less'},ee[Z.STYLUS]={label:'Stylus',cmMode:'stylus',codepenVal:'stylus'},ee[Z.ACSS]={label:'Atomic CSS',cmPath:'css',cmMode:'css',codepenVal:'notsupported',cmDisable:!0,hasSettings:!0};const te=chrome.extension||window.DEBUG?'/':'/app';var se,ie,oe,ae,ne,le,re,de,ce,me,ue,pe=500,ge=15,he=!0,ve=X.HTML,be=Q.JS,fe=Z.CSS,ye=33,Se={},Ce={html:null,css:null,js:null},Le=!1,ke=0,we=$('#demo-frame'),je=$('#js-html-code'),Ee=$('#js-css-code'),xe=$('#js-js-code'),Me=$('#js-codepen-form'),Te=$('#js-saved-items-pane'),Ie=$('#js-saved-items-pane-close-btn'),De=$('#js-html-mode-label'),Oe=$('#js-css-mode-label'),Ae=$('#js-js-mode-label'),Pe=$('#js-title-input'),Be=$('#js-add-library-select'),Fe=$('#js-external-js'),ze=$('#js-external-css');Y.cm={},Y.frame=we,Y.demoFrameDocument=we.contentDocument||we.contentWindow.document,window.previewException=function(e){console.error('Possible infinite loop detected.',e.stack),window.onMessageFromConsole('Possible infinite loop detected.',e.stack)},window.onunload=function(){g('code'),Y.detachedWindow&&Y.detachedWindow.close()},Y.setPreviewContent=function(e){Se.preserveConsoleLogs||Y.clearConsole();var t={html:Y.cm.html.getValue(),css:Y.cm.css.getValue(),js:Y.cm.js.getValue()};utils.log('\uD83D\uDD0E setPreviewContent',e);const s=Y.detachedWindow?Y.detachedWindow.document.querySelector('iframe'):we;if(!e&&t.html===Ce.html&&t.js===Ce.js)D().then(function(e){s.contentDocument.querySelector('#webmakerstyle')&&(s.contentDocument.querySelector('#webmakerstyle').textContent=e)});else{var i=I(),o=D(),a=O();Promise.all([i,o,a]).then(function(e){z(e[0],e[1],e[2])})}Ce.html=t.html,Ce.css=t.css,Ce.js=t.js},Y.cm.html=V(je,{mode:'htmlmixed',profile:'xhtml',gutters:['CodeMirror-linenumbers','CodeMirror-foldgutter'],noAutocomplete:!0,matchTags:{bothTags:!0},emmet:!0}),Y.cm.css=V(Ee,{mode:'css',gutters:['error-gutter','CodeMirror-linenumbers','CodeMirror-foldgutter'],emmet:!0}),Inlet(Y.cm.css),Y.cm.js=V(xe,{mode:'javascript',gutters:['error-gutter','CodeMirror-linenumbers','CodeMirror-foldgutter']}),Inlet(Y.cm.js),Y.consoleCm=CodeMirror(consoleLogEl,{mode:'javascript',lineWrapping:!0,theme:'monokai',foldGutter:!0,readOnly:!0,gutters:['CodeMirror-foldgutter']}),Y.onModalSettingsLinkClick=function(){U(),trackEvent('ui','onboardSettingsBtnClick')},Y.onShowInTabClicked=function(){trackEvent('ui','onboardShowInTabClick')},Y.onDontShowInTabClicked=function(){trackEvent('ui','onboardDontShowInTabClick')},Y.exportItems=function(t){q().then(()=>{b().then(function(e){var t=new Date,s=['web-maker-export',t.getFullYear(),t.getMonth()+1,t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds()].join('-');s+='.json';var i=new Blob([JSON.stringify(e,!1,2)],{type:'application/json;charset=UTF-8'});utils.downloadFile(s,i),trackEvent('ui','exportBtnClicked')})}),t.preventDefault()},Y.onImportBtnClicked=function(t){var e=document.createElement('input');e.type='file',e.style.display='none',e.accept='accept="application/json',document.body.appendChild(e),e.addEventListener('change',W),e.click(),trackEvent('ui','importBtnClicked'),t.preventDefault()},Y.takeScreenshot=function(t){q().then(()=>{function e(t){var s=document.createElement('canvas'),i=we.getBoundingClientRect();s.width=i.width,s.height=i.height;var o=s.getContext('2d'),a=window.devicePixelRatio||1;o.drawImage(t,i.left*a,i.top*a,i.width*a,i.height*a,0,0,i.width,i.height),t.removeEventListener('load',e),R(s.toDataURL())}var t=document.createElement('style');t.textContent='[class*="hint"]:after, [class*="hint"]:before { display: none!important; }',document.body.appendChild(t),setTimeout(()=>{chrome.tabs.captureVisibleTab(null,{format:'png',quality:100},function(s){if(t.remove(),s){var i=new Image;i.src=s,i.addEventListener('load',()=>e(i,s))}})},50),trackEvent('ui','takeScreenshotBtnClick')}),t.preventDefault()},Y.updateSetting=function(t){if(t){var s=t.target.dataset.setting,i={},o=t.target;utils.log(s,'checkbox'===o.type?o.checked:o.value),Se[s]='checkbox'===o.type?o.checked:o.value,i[s]=Se[s],db.sync.set(i,function(){e.add('Setting saved')}),window.user&&window.db.getDb().then((e)=>{e.collection('users').doc(window.user.uid).update({[`settings.${s}`]:Se[s]}).then((e)=>{utils.log(`Setting "${s}" for user`,e)}).catch((e)=>utils.log(e))}),trackEvent('ui','updatePref-'+s,Se[s])}runBtn.classList[Se.autoPreview?'add':'remove']('hide'),je.querySelector('.CodeMirror').style.fontSize=Se.fontSize,Ee.querySelector('.CodeMirror').style.fontSize=Se.fontSize,xe.querySelector('.CodeMirror').style.fontSize=Se.fontSize,consoleEl.querySelector('.CodeMirror').style.fontSize=Se.fontSize,indentationSizeValueEl.textContent=$('[data-setting=indentSize]').value,editorThemeLinkTag.href=`lib/codemirror/theme/${Se.editorTheme}.css`,fontStyleTag.textContent=fontStyleTemplate.textContent.replace(/fontname/g,('other'===Se.editorFont?Se.editorCustomFont:Se.editorFont)||'FiraCode'),customEditorFontInput.classList['other'===Se.editorFont?'remove':'add']('hide'),['html','js','css'].forEach((e)=>{Y.cm[e].setOption('indentWithTabs','spaces'!==$('[data-setting=indentWith]:checked').value),Y.cm[e].setOption('blastCode',!!$('[data-setting=isCodeBlastOn]').checked&&{effect:2,shake:!1}),Y.cm[e].setOption('indentUnit',+$('[data-setting=indentSize]').value),Y.cm[e].setOption('tabSize',+$('[data-setting=indentSize]').value),Y.cm[e].setOption('theme',$('[data-setting=editorTheme]').value),Y.cm[e].setOption('keyMap',$('[data-setting=keymap]:checked').value),Y.cm[e].setOption('lineWrapping',$('[data-setting=lineWrap]').checked),Y.cm[e].refresh()}),Y.consoleCm.setOption('theme',$('[data-setting=editorTheme]').value),Y.acssSettingsCm.setOption('theme',$('[data-setting=editorTheme]').value),Se.autoSave?!ie&&(ie=setInterval(m,15000)):(clearInterval(ie),ie=null),document.body.classList[Se.lightVersion?'add':'remove']('light-version')},Y.onNewBtnClick=function(){if(trackEvent('ui','newBtnClick'),le){var e=confirm('You have unsaved changes. Do you still want to create something new?');e&&C()}else C()},Y.onOpenBtnClick=function(){trackEvent('ui','openBtnClick'),f()},Y.onSaveBtnClick=function(){trackEvent('ui','saveBtnClick',ne.id?'saved':'new'),c()},Y.toggleModal=function(e){e.classList.toggle('is-modal-visible'),document.body.classList[e.classList.contains('is-modal-visible')?'add':'remove']('overlay-visible')},Y.onSearchInputChange=function(t){const e=t.target.value;let s;for(const[i,o]of Object.entries(re))s=$(`#js-saved-items-pane [data-item-id=${i}]`),-1===o.title.toLowerCase().indexOf(e)?s.classList.add('hide'):s.classList.remove('hide');trackEvent('ui','searchInputType')},Y.toggleConsole=function(){consoleEl.classList.toggle('is-minimized'),trackEvent('ui','consoleToggle')},Y.clearConsole=window.clearConsole=function(){Y.consoleCm.setValue(''),ke=0,logCountEl.textContent=ke},Y.onClearConsoleBtnClick=function(){Y.clearConsole(),trackEvent('ui','consoleClearBtnClick')},Y.evalConsoleExpr=function(t){(76===t.which||12===t.which)&&t.ctrlKey?(Y.clearConsole(),trackEvent('ui','consoleClearKeyboardShortcut')):13===t.which&&(window.onMessageFromConsole('> '+t.target.value),we.contentWindow._wmEvaluate(t.target.value),t.target.value='',trackEvent('fn','evalConsoleExpr'))},window.onMessageFromConsole=function(){[...arguments].forEach(function(e){e&&e.indexOf&&-1!==e.indexOf('filesystem:chrome-extension')&&(e=e.replace(/filesystem:chrome-extension.*\.js:(\d+):*(\d*)/g,'script $1:$2'));try{Y.consoleCm.replaceRange(e+' '+((e+'').match(/\[object \w+]/)?JSON.stringify(e):'')+'\n',{line:Infinity})}catch(t){Y.consoleCm.replaceRange('\uD83C\uDF00\n',{line:Infinity})}Y.consoleCm.scrollTo(0,Infinity),ke++}),logCountEl.textContent=ke},Y.openDetachedPreview=function(){if(trackEvent('ui','detachPreviewBtnClick'),Y.detachedWindow)return void Y.detachedWindow.focus();var e=we.getBoundingClientRect();const t=e.width,s=e.height;document.body.classList.add('is-detached-mode'),globalConsoleContainerEl.insertBefore(consoleEl,null),Y.detachedWindow=window.open('./preview.html','Web Maker',`width=${t},height=${s},resizable,scrollbars=yes,status=1`),setTimeout(()=>{Y.setPreviewContent(!0)},1500);var i=window.setInterval(function(){Y.detachedWindow&&Y.detachedWindow.closed&&(clearInterval(i),document.body.classList.remove('is-detached-mode'),$('#js-demo-side').insertBefore(consoleEl,null),Y.detachedWindow=null,Y.setPreviewContent(!0))},500)},Y.openCssSettingsModal=function(){Y.toggleModal(cssSettingsModal),setTimeout(()=>{Y.acssSettingsCm.refresh(),Y.acssSettingsCm.focus()},500),trackEvent('ui','cssSettingsBtnClick')},Y.onModalCloseBtnClick=function(t){j(),t.preventDefault()},Y.openSupportDeveloperModal=function(t){j(),trackEvent('ui',t.target.dataset.eventAction),Y.toggleModal(pledgeModal)},Y.updateProfileUi=()=>{window.user?(document.body.classList.add('is-logged-in'),headerAvatarImg.src=profileAvatarImg.src=window.user.photoURL||'data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 24 24\'%3E%3Cpath fill=\'#ccc\' d=\'M12,19.2C9.5,19.2 7.29,17.92 6,16C6.03,14 10,12.9 12,12.9C14,12.9 17.97,14 18,16C16.71,17.92 14.5,19.2 12,19.2M12,5A3,3 0 0,1 15,8A3,3 0 0,1 12,11A3,3 0 0,1 9,8A3,3 0 0,1 12,5M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12C22,6.47 17.5,2 12,2Z\' /%3E%3C/svg%3E',profileUserName.textContent=window.user.displayName||'Anonymous Creator'):(document.body.classList.remove('is-logged-in'),headerAvatarImg.src=profileAvatarImg.src='',profileUserName.textContent='Anonymous Creator')},Y.login=(t)=>{const e=t.target.dataset.authProvider;trackEvent('ui','loginProviderClick',e),window.login(e),t&&t.preventDefault()},Y.logout=(t)=>{if(t.preventDefault(),le){var e=confirm('You have unsaved changes. Do you still want to logout?');if(!e)return}trackEvent('fn','loggedOut'),window.logout()},Y.closeAllOverlays=j,function(){function t(e){return function(){return d('layoutMode',e),trackEvent('ui','toggleLayoutClick',e),n(e),!1}}function o(t){consoleEl.style.height=p+u-t.pageY+'px'}firebase.initializeApp({apiKey:'AIzaSyBl8Dz7ZOE7aP75mipYl2zKdLSRzBU2fFc',authDomain:'web-maker-app.firebaseapp.com',databaseURL:'https://web-maker-app.firebaseio.com',projectId:'web-maker-app',storageBucket:'web-maker-app.appspot.com',messagingSenderId:'560473480645'}),firebase.auth().onAuthStateChanged(function(t){Y.closeAllOverlays(),t?(utils.log('You are -> ',t),e.add('You are now logged in!'),Y.user=window.user=t,window.db.getUser(t.uid).then((e)=>{e&&(Object.assign(Se,t.settings),K(),Y.updateSetting())})):delete window.user,Y.updateProfileUi()});var a;CodeMirror.modeURL=`lib/codemirror/mode/%N/%N.js`,layoutBtn1.addEventListener('click',t(1)),layoutBtn2.addEventListener('click',t(2)),layoutBtn3.addEventListener('click',t(3)),layoutBtn4.addEventListener('click',t(4)),layoutBtn5.addEventListener('click',t(5)),notificationsBtn.addEventListener('click',function(){return Y.toggleModal(notificationsModal),notificationsModal.classList.contains('is-modal-visible')&&!he&&(he=!0,notificationsBtn.classList.remove('has-new'),window.db.setUserLastSeenVersion(G)),trackEvent('ui','notificationButtonClick',G),!1}),codepenBtn.addEventListener('click',function(t){if(fe===Z.ACSS)return alert('Oops! CodePen doesn\'t supports Atomic CSS currently.'),void t.preventDefault();var e={title:'A Web Maker experiment',html:Y.cm.html.getValue(),css:Y.cm.css.getValue(),js:Y.cm.js.getValue(),html_pre_processor:ee[ve].codepenVal,css_pre_processor:ee[fe].codepenVal,js_pre_processor:ee[be].codepenVal,css_external:ze.value.split('\n').join(';'),js_external:Fe.value.split('\n').join(';')};ne.title.match(/Untitled\s\d\d*-\d/)||(e.title=ne.title),e=JSON.stringify(e),Me.querySelector('input').value=e,Me.submit(),trackEvent('ui','openInCodepen'),t.preventDefault()}),utils.onButtonClick(saveHtmlBtn,function(){N(),trackEvent('ui','saveHtmlClick')}),utils.onButtonClick(Ie,v),utils.onButtonClick(Te,function(t){t.target.classList.contains('js-saved-item-tile')&&(setTimeout(function(){L(t.target.dataset.itemId)},350),v()),t.target.classList.contains('js-saved-item-tile__remove-btn')?k(t.target.parentElement.parentElement.dataset.itemId):t.target.classList.contains('js-saved-item-tile__fork-btn')&&(v(),setTimeout(function(){S(re[t.target.parentElement.parentElement.dataset.itemId])},350))}),Pe.addEventListener('blur',function(){ne.id&&(c(),trackEvent('ui','titleChanged'))}),$all('.js-mode-select').forEach((e)=>{e.addEventListener('change',function(t){var e=t.target.value,s=t.target.dataset.type,i='html'===s?ve:'css'===s?fe:be;i!==e&&('html'===s?x(e).then(()=>Y.setPreviewContent(!0)):'js'===s?T(e).then(()=>Y.setPreviewContent(!0)):'css'===s&&M(e).then(()=>Y.setPreviewContent(!0)),trackEvent('ui','updateCodeMode',e))})});var r=$all('.js-code-collapse-btn');r.forEach(function(e){e.addEventListener('click',function(t){var e=t.currentTarget.parentElement.parentElement.parentElement;return i(e),trackEvent('ui','paneCollapseBtnClick',e.dataset.type),!1})}),[je,Ee,xe].forEach(function(e){e.addEventListener('transitionend',function(){s()})}),window.addEventListener('keydown',function(e){(e.ctrlKey||e.metaKey)&&83===e.keyCode&&(e.preventDefault(),c(),trackEvent('ui','saveItemKeyboardShortcut')),(e.ctrlKey||e.metaKey)&&e.shiftKey&&53===e.keyCode?(e.preventDefault(),Y.setPreviewContent(!0),trackEvent('ui','previewKeyboardShortcut')):(e.ctrlKey||e.metaKey)&&79===e.keyCode?(e.preventDefault(),f(),trackEvent('ui','openCreationKeyboardShortcut')):(e.ctrlKey||e.metaKey)&&e.shiftKey&&191===e.keyCode?(e.preventDefault(),Y.toggleModal(keyboardShortcutsModal),trackEvent('ui','showKeyboardShortcutsShortcut')):27===e.keyCode&&j()}),Te.addEventListener('keydown',function(e){if(!Le)return;const t=e.ctrlKey||e.metaKey,s=t&&70===e.keyCode,i=40===e.keyCode,o=38===e.keyCode,a=13===e.keyCode,n=$('.js-saved-item-tile.selected'),l=0!==$all('.js-saved-item-tile').length;if((i||o)&&l){const e=i?'nextUntil':'previousUntil';n?(n.classList.remove('selected'),n[e]('.js-saved-item-tile:not(.hide)').classList.add('selected')):$('.js-saved-item-tile:not(.hide)').classList.add('selected'),$('.js-saved-item-tile.selected').scrollIntoView(!1)}a&&n&&(setTimeout(function(){L(n.dataset.itemId)},350),v()),s&&(e.preventDefault(),setTimeout(function(){S(re[n.dataset.itemId])},350),v(),trackEvent('ui','forkKeyboardShortcut'))}),window.addEventListener('click',function(t){'string'!=typeof t.target.className||-1!==t.target.className.indexOf('modal-overlay')&&j()}),window.addEventListener('dblclick',function(t){var e=t.target;if(e.classList.contains('js-console__header')&&(Y.toggleConsole(),trackEvent('ui','consoleToggleDblClick')),e.classList.contains('js-code-wrap__header')){var s=e.parentElement;i(s),trackEvent('ui','paneHeaderDblClick',s.dataset.type)}});var m=window.jsLibs.reduce((e,t)=>e+`<option data-type="${t.type}" value="${t.url}">${t.label}</option>`,'');Be.children[1].innerHTML=m,m=window.cssLibs.reduce((e,t)=>e+`<option data-type="${t.type}" value="${t.url}">${t.label}</option>`,''),Be.children[2].innerHTML=m,Be.addEventListener('change',function(t){var e=t.target;e.value&&($('#js-external-'+e.selectedOptions[0].dataset.type).value+='\n'+e.value,trackEvent('ui','addLibrarySelect',e.selectedOptions[0].label),l(),e.value='')}),Fe.addEventListener('blur',l),ze.addEventListener('blur',l),new TextareaAutoComplete(Fe,{filter:(e)=>e.latest.match(/\.js$/)}),new TextareaAutoComplete(ze,{filter:(e)=>e.latest.match(/\.css$/)}),new TextareaAutoComplete(externalLibrarySearchInput,{selectedCallback:(e)=>{const t=e.match(/\.js$/)?Fe:ze;t.value=`${t.value}\n${e}`,externalLibrarySearchInput.value=''}});var u,p;$('.js-console__header').addEventListener('mousedown',(t)=>{u=t.pageY,p=consoleEl.getBoundingClientRect().height,$('#demo-frame').classList.add('pointer-none'),window.addEventListener('mousemove',o)}),$('.js-console__header').addEventListener('mouseup',()=>{window.removeEventListener('mousemove',o),$('#demo-frame').classList.remove('pointer-none')}),db.local.get({layoutMode:1,code:''},function(e){n(e.layoutMode),Se.layoutMode=e.layoutMode,e.code&&(a=e.code)}),db.getSettings(J).then((e)=>{e.preserveLastCode&&a?(le=0,a.id&&window.IS_EXTENSION?db.local.get(a.id,function(e){e[a.id]&&(utils.log('Load item ',a.id),ne=e[a.id],w())}):(utils.log('Load last unsaved item',a),ne=a,w())):C(),Object.assign(Se,e),K(),Y.updateSetting()}),db.getUserLastSeenVersion().then((e)=>{e||(onboardModal.classList.add('is-modal-visible'),-1===document.cookie.indexOf('onboarded')&&(trackEvent('ui','onboardModalSeen',G),document.cookie='onboarded=1'),window.db.setUserLastSeenVersion(G)),e&&-1!==utils.semverCompare(e,G)||(notificationsBtn.classList.add('has-new'),he=!1)}),Y.acssSettingsCm=CodeMirror.fromTextArea(acssSettingsTextarea,{mode:'application/ld+json'}),Y.acssSettingsCm.on('blur',()=>{Y.setPreviewContent(!0)});var g='';['3024-day','3024-night','abcdef','ambiance','base2tone-meadow-dark','base16-dark','base16-light','bespin','blackboard','cobalt','colorforth','dracula','duotone-dark','duotone-light','eclipse','elegant','erlang-dark','hopscotch','icecoder','isotope','lesser-dark','liquibyte','material','mbo','mdn-like','midnight','monokai','neat','neo','night','panda-syntax','paraiso-dark','paraiso-light','pastel-on-dark','railscasts','rubyblue','seti','solarized dark','solarized light','the-matrix','tomorrow-night-bright','tomorrow-night-eighties','ttcn','twilight','vibrant-ink','xq-dark','xq-light','yeti','zenburn'].forEach((e)=>{g+='<option value="'+e+'">'+e+'</option>'}),document.querySelector('[data-setting="editorTheme"]').innerHTML=g,requestAnimationFrame(H)}()}(window.alertsService,window.itemService),function(e){function t(e){s&&(!e||e!==s)&&(s.classList.remove('open'),s=null)}var s;(function(){var i=e('[dropdown]');i.forEach(function(e){e.addEventListener('click',function(i){t(i.currentTarget),i.currentTarget.classList.toggle('open'),s=i.currentTarget,i.stopPropagation()})}),document.addEventListener('click',function(){t()})})()}($all); |