From 15e279a2a5ab896de085a6689087fcfc1bd25a6d Mon Sep 17 00:00:00 2001 From: Roberto Tonino Date: Wed, 2 Jun 2021 17:51:56 +0200 Subject: [PATCH] test: added remaining utils tests --- public/js/bundle.js | 2 +- src/utils/utils.js | 31 +++++++++++++++++++++++++++---- tests/unit/utils/texts.spec.js | 17 +++++++++++++++++ tests/unit/utils/utils.spec.js | 33 +++++++++++++++++++++++++++++++++ 4 files changed, 78 insertions(+), 5 deletions(-) create mode 100644 tests/unit/utils/texts.spec.js create mode 100644 tests/unit/utils/utils.spec.js diff --git a/public/js/bundle.js b/public/js/bundle.js index 347fb28..369230f 100644 --- a/public/js/bundle.js +++ b/public/js/bundle.js @@ -2507,7 +2507,7 @@ a { `;styleInject(css_248z$2);class CustomSocket extends WebSocket{constructor(a){super(a);this.listeners={}}emit(a,n){if(this.readyState!==WebSocket.OPEN)return!1;this.send(JSON.stringify({key:a,data:n}))}on(a,n){Object.keys(this.listeners).includes(a)||(this.listeners[a]=n,this.addEventListener("message",r=>{const i=JSON.parse(r.data);i.key===a&&n(i.data)}))}off(a){Object.keys(this.listeners).includes(a)&&(this.removeEventListener("message",this.listeners[a]),delete this.listeners[a])}}const socket=new CustomSocket("ws://"+location.host+"/");var __vue_render__$w=function(e,a){var n=a._c;return n("div",{directives:[{name:"show",rawName:"v-show",value:!a.props.hidden,expression:"!props.hidden"}],staticClass:"flex justify-center items-center flex-col flex-1 h-full",class:a.props.additionalClasses},[n("span",{staticClass:"mb-5"},[a._v(a._s(a.props.text||"Loading..."))]),a._v(" "),a._m(0)])},__vue_staticRenderFns__$w=[function(e,a){var n=a._c;return n("div",{staticClass:"lds-ring"},[n("div"),a._v(" "),n("div"),a._v(" "),n("div"),a._v(" "),n("div")])}];const __vue_inject_styles__$w=function(e){!e||e("data-v-4e4e821e_0",{source:".lds-ring[data-v-4e4e821e]{display:inline-block;position:relative;width:80px;height:80px}.lds-ring div[data-v-4e4e821e]{box-sizing:border-box;display:block;position:absolute;width:64px;height:64px;margin:8px;border:8px solid #fff;border-radius:50%;animation:lds-ring-data-v-4e4e821e 1.2s cubic-bezier(.5,0,.5,1) infinite;border-color:#fff transparent transparent transparent}.lds-ring div[data-v-4e4e821e]:nth-child(1){animation-delay:-.45s}.lds-ring div[data-v-4e4e821e]:nth-child(2){animation-delay:-.3s}.lds-ring div[data-v-4e4e821e]:nth-child(3){animation-delay:-.15s}@keyframes lds-ring-data-v-4e4e821e{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}",map:void 0,media:void 0})},__vue_scope_id__$w="data-v-4e4e821e",__vue_module_identifier__$d=void 0,__vue_is_functional_template__$w=!0;function __vue_normalize__$w(e,a,n,r,i,s,l,c){const o=(typeof n=="function"?n.options:n)||{};o.__file="BaseLoadingPlaceholder.vue",o.render||(o.render=e.render,o.staticRenderFns=e.staticRenderFns,o._compiled=!0,i&&(o.functional=!0)),o._scopeId=r;{let u;if(a&&(u=function(d){a.call(this,l(d))}),u!==void 0)if(o.functional){const d=o.render;o.render=function(h,m){return u.call(m),d(h,m)}}else{const d=o.beforeCreate;o.beforeCreate=d?[].concat(d,u):[u]}}return o}function __vue_create_injector__$d(){const e=document.head||document.getElementsByTagName("head")[0],a=__vue_create_injector__$d.styles||(__vue_create_injector__$d.styles={}),n=typeof navigator!="undefined"&&/msie [6-9]\\b/.test(navigator.userAgent.toLowerCase());return function(i,s){if(document.querySelector('style[data-vue-ssr-id~="'+i+'"]'))return;const l=n?s.media||"default":i,c=a[l]||(a[l]={ids:[],parts:[],element:void 0});if(!c.ids.includes(i)){let o=s.source,u=c.ids.length;if(c.ids.push(i),s.map&&(o+=` /*# sourceURL=`+s.map.sources[0]+" */",o+=` /*# sourceMappingURL=data:application/json;base64,`+btoa(unescape(encodeURIComponent(JSON.stringify(s.map))))+" */"),n&&(c.element=c.element||document.querySelector("style[data-group="+l+"]")),!c.element){const d=c.element=document.createElement("style");d.type="text/css",s.media&&d.setAttribute("media",s.media),n&&(d.setAttribute("data-group",l),d.setAttribute("data-next-index","0")),e.appendChild(d)}if(n&&(u=parseInt(c.element.getAttribute("data-next-index")),c.element.setAttribute("data-next-index",u+1)),c.element.styleSheet)c.parts.push(o),c.element.styleSheet.cssText=c.parts.filter(Boolean).join(` -`);else{const d=document.createTextNode(o),f=c.element.childNodes;f[u]&&c.element.removeChild(f[u]),f.length?c.element.insertBefore(d,f[u]):c.element.appendChild(d)}}}}var BaseLoadingPlaceholder=__vue_normalize__$w({render:__vue_render__$w,staticRenderFns:__vue_staticRenderFns__$w},__vue_inject_styles__$w,{},__vue_scope_id__$w,__vue_is_functional_template__$w,__vue_module_identifier__$d,__vue_create_injector__$d);function fetchData(e,a={},n="GET"){const r=new URL(`${window.location.origin}/api/${e}`);return Object.keys(a).forEach(i=>{r.searchParams.append(i,a[i])}),fetch(r.href,{method:n}).then(i=>i.json()).catch(i=>(console.error("There has been a problem with your fetch operation:",i),Promise.reject(i)))}const postToServer=(e,a)=>{const n=new URL(`${window.location.origin}/api/${e}`);return fetch(n,{body:JSON.stringify(a),headers:{"Content-Type":"application/json"},method:"POST"}).then(r=>{if(!r.ok)throw new Error("Network response was not ok");return r.json()}).catch(r=>{console.error("There has been a problem with your fetch operation:",r)})};function sendAddToQueue(e,a=null){if(!e)throw new Error("No URL given to sendAddToQueue function!");fetchData("addToQueue",{url:e,bitrate:a},"POST")}function aggregateDownloadLinks(e){const a=[];return e.forEach(n=>{a.push(n.link)}),a.join(";")}function generatePath(e){if(!e)throw new Error("No element passed to the generatePath function!");const a=[e];for(;(e=e.parentNode)&&e!==document;)a.push(e);return a}function isValidURL(e){const a=e.toLowerCase();if(a.startsWith("http")){if(a.includes("deezer.com")||a.includes("deezer.page.link")||a.includes("open.spotify.com")||a.includes("link.tospotify.com"))return!0}else if(a.startsWith("spotify:"))return!0;return!1}function convertDuration(e){let a,n;return a=Math.floor(e/60),n=e-a*60,n<10&&(n="0"+n),a+":"+n}function convertDurationSeparated(e){let a,n,r;return n=Math.floor(e/60),a=Math.floor(n/60),r=e-n*60,n-=a*60,[a,n,r]}function numberWithDots(e){return e.toString().replace(/\B(?=(\d{3})+(?!\d))/g,".")}function debounce$1(e,a,n){let r;return function(){const i=this,s=arguments,l=function(){r=null,n||e.apply(i,s)},c=n&&!r;clearTimeout(r),r=setTimeout(l,a),c&&e.apply(i,s)}}function copyToClipboard(e){const a=document.createElement("input");document.body.appendChild(a),a.setAttribute("type","text"),a.setAttribute("value",e),a.select(),a.setSelectionRange(0,99999),document.execCommand("copy"),a.remove()}function getPropertyWithFallback(e,...a){for(const n of a){const i=/\./.test(n)?n.split(".").reduce((s,l)=>{if(s)return s[l]},e):e[n];if(typeof i!="undefined")return i}return null}var Utils={isValidURL,convertDuration,convertDurationSeparated,numberWithDots,debounce:debounce$1};const downloadQualities=[{objName:"flac",label:"FLAC",value:9},{objName:"320kbps",label:"MP3 320kbps",value:3},{objName:"128kbps",label:"MP3 128kbps",value:1},{objName:"realityAudioHQ",label:"360 Reality Audio [HQ]",value:15},{objName:"realityAudioMQ",label:"360 Reality Audio [MQ]",value:14},{objName:"realityAudioLQ",label:"360 Reality Audio [LQ]",value:13}];var script$u={data(){return{menuOpen:!1,xPos:0,yPos:0,deezerHref:"",generalHref:"",imgSrc:""}},computed:{options(){const e={cut:{label:this.$t("globals.cut"),show:!1,position:1,action:()=>{document.execCommand("Cut")}},copy:{label:this.$t("globals.copy"),show:!1,position:2,action:()=>{document.execCommand("Copy")}},copyLink:{label:this.$t("globals.copyLink"),show:!1,position:3,action:()=>{copyToClipboard(this.generalHref)}},copyImageLink:{label:this.$t("globals.copyImageLink"),show:!1,position:4,action:()=>{copyToClipboard(this.imgSrc)}},copyDeezerLink:{label:this.$t("globals.copyDeezerLink"),show:!1,position:5,action:()=>{copyToClipboard(this.deezerHref)}},paste:{label:this.$t("globals.paste"),show:!1,position:6,action:()=>{clipboard in navigator?navigator.clipboard.readText().then(n=>{document.execCommand("insertText",void 0,n)}):document.execCommand("paste")}}},a=Object.values(e).length+1;return downloadQualities.forEach((n,r)=>{e[n.objName]={label:`${this.$t("globals.download",{thing:n.label})}`,show:!1,position:a+r,action:sendAddToQueue.bind(null,this.deezerHref,n.value)}}),e},sortedOptions(){return Object.values(this.options).sort((e,a)=>e.position{this.menuOpen=!1,this.options.copyLink.show=!1,this.options.copyDeezerLink.show=!1,this.options.copyImageLink.show=!1,downloadQualities.forEach(e=>{this.options[e.objName].show=!1})}).catch(e=>{console.error(e)})},positionMenu(e,a){this.xPos=`${e}px`,this.yPos=`${a}px`,this.$nextTick().then(()=>{const{innerHeight:n,innerWidth:r}=window,i=e+this.$refs.contextMenu.getBoundingClientRect().width,s=a+this.$refs.contextMenu.getBoundingClientRect().height;if(i>r){const l=i-r+15;this.xPos=`${e-l}px`}if(s>n){const l=s-n+15;this.yPos=`${a-l}px`}})},showDeezerOptions(e){e||(this.options.copyDeezerLink.show=!0),downloadQualities.forEach(a=>{this.options[a.objName].show=!0})}}};const __vue_script__$u=script$u;var __vue_render__$v=function(){var e=this,a=e.$createElement,n=e._self._c||a;return n("div",{directives:[{name:"show",rawName:"v-show",value:e.menuOpen,expression:"menuOpen"}],ref:"contextMenu",staticClass:"context-menu",style:{top:e.yPos,left:e.xPos}},e._l(e.sortedOptions,function(r){return n("button",{directives:[{name:"show",rawName:"v-show",value:r.show,expression:"option.show"}],key:r.label,staticClass:"btn menu-option",on:{click:function(i){return i.preventDefault(),r.action(i)}}},[n("span",{staticClass:"menu-option__text"},[e._v(e._s(r.label))])])}),0)},__vue_staticRenderFns__$v=[];const __vue_inject_styles__$v=function(e){!e||e("data-v-56c7988a_0",{source:".context-menu[data-v-56c7988a]{position:absolute;top:0;left:0;min-width:100px;border-radius:7px;background:var(--secondary-background);box-shadow:4px 10px 18px 0 rgba(0,0,0,.15);overflow:hidden;z-index:10000}.menu-option[data-v-56c7988a]{display:flex;align-items:center;width:100%;height:40px;padding-left:10px;padding-right:10px;color:var(--foreground);cursor:pointer}.menu-option[data-v-56c7988a]:hover{background:var(--table-highlight);filter:brightness(150%)}.menu-option__text[data-v-56c7988a]{text-transform:capitalize}button[data-v-56c7988a]{color:var(--primary-text);color:unset;background-color:var(--primary-color);background-color:unset;min-width:unset;position:unset;border:unset;border-radius:unset;font-family:unset;font-weight:unset;font-size:unset;padding:unset;margin-right:unset;height:unset;text-transform:unset;cursor:unset;transition:unset}button[data-v-56c7988a]:focus{outline:0}button[data-v-56c7988a]:active{background-color:unset;transform:unset}button[data-v-56c7988a]:hover{background:unset;border:unset}",map:void 0,media:void 0})},__vue_scope_id__$v="data-v-56c7988a",__vue_module_identifier__$c=void 0,__vue_is_functional_template__$v=!1;function __vue_normalize__$v(e,a,n,r,i,s,l,c){const o=(typeof n=="function"?n.options:n)||{};o.__file="TheContextMenu.vue",o.render||(o.render=e.render,o.staticRenderFns=e.staticRenderFns,o._compiled=!0,i&&(o.functional=!0)),o._scopeId=r;{let u;if(a&&(u=function(d){a.call(this,l(d))}),u!==void 0)if(o.functional){const d=o.render;o.render=function(h,m){return u.call(m),d(h,m)}}else{const d=o.beforeCreate;o.beforeCreate=d?[].concat(d,u):[u]}}return o}function __vue_create_injector__$c(){const e=document.head||document.getElementsByTagName("head")[0],a=__vue_create_injector__$c.styles||(__vue_create_injector__$c.styles={}),n=typeof navigator!="undefined"&&/msie [6-9]\\b/.test(navigator.userAgent.toLowerCase());return function(i,s){if(document.querySelector('style[data-vue-ssr-id~="'+i+'"]'))return;const l=n?s.media||"default":i,c=a[l]||(a[l]={ids:[],parts:[],element:void 0});if(!c.ids.includes(i)){let o=s.source,u=c.ids.length;if(c.ids.push(i),s.map&&(o+=` +`);else{const d=document.createTextNode(o),f=c.element.childNodes;f[u]&&c.element.removeChild(f[u]),f.length?c.element.insertBefore(d,f[u]):c.element.appendChild(d)}}}}var BaseLoadingPlaceholder=__vue_normalize__$w({render:__vue_render__$w,staticRenderFns:__vue_staticRenderFns__$w},__vue_inject_styles__$w,{},__vue_scope_id__$w,__vue_is_functional_template__$w,__vue_module_identifier__$d,__vue_create_injector__$d);function fetchData(e,a={},n="GET"){const r=new URL(`${window.location.origin}/api/${e}`);return Object.keys(a).forEach(i=>{r.searchParams.append(i,a[i])}),fetch(r.href,{method:n}).then(i=>i.json()).catch(i=>(console.error("There has been a problem with your fetch operation:",i),Promise.reject(i)))}const postToServer=(e,a)=>{const n=new URL(`${window.location.origin}/api/${e}`);return fetch(n,{body:JSON.stringify(a),headers:{"Content-Type":"application/json"},method:"POST"}).then(r=>{if(!r.ok)throw new Error("Network response was not ok");return r.json()}).catch(r=>{console.error("There has been a problem with your fetch operation:",r)})};function sendAddToQueue(e,a=null){if(!e)throw new Error("No URL given to sendAddToQueue function!");fetchData("addToQueue",{url:e,bitrate:a},"POST")}function aggregateDownloadLinks(e){return e.map(n=>n.link).join(";")}function generatePath(e){if(!e)throw new Error("No element passed to the generatePath function!");const a=[e];for(;(e=e.parentNode)&&e!==document;)a.push(e);return a}function isValidURL(e){const a=e.toLowerCase();if(a.startsWith("http")){if(a.includes("deezer.com")||a.includes("deezer.page.link")||a.includes("open.spotify.com")||a.includes("link.tospotify.com"))return!0}else if(a.startsWith("spotify:"))return!0;return!1}function convertDuration(e){let a,n;return a=Math.floor(e/60),n=e-a*60,n<10&&(n="0"+n),a+":"+n}function convertDurationSeparated(e){let a,n,r;return n=Math.floor(e/60),a=Math.floor(n/60),r=e-n*60,n-=a*60,[a,n,r]}const numberWithDots=e=>e.toString().replace(/\B(?=(\d{3})+(?!\d))/g,".");function debounce$1(e,a,n){let r;return function(){const i=this,s=arguments,l=function(){r=null,n||e.apply(i,s)},c=n&&!r;clearTimeout(r),r=setTimeout(l,a),c&&e.apply(i,s)}}function copyToClipboard(e){const a=document.createElement("input");document.body.appendChild(a),a.setAttribute("type","text"),a.setAttribute("value",e),a.select(),a.setSelectionRange(0,99999),document.execCommand("copy"),a.remove()}function getPropertyWithFallback(e,...a){for(const n of a){const i=/\./.test(n)?n.split(".").reduce((s,l)=>{if(s)return s[l]},e):e[n];if(typeof i!="undefined")return i}return null}var Utils={isValidURL,convertDuration,convertDurationSeparated,numberWithDots,debounce:debounce$1};const downloadQualities=[{objName:"flac",label:"FLAC",value:9},{objName:"320kbps",label:"MP3 320kbps",value:3},{objName:"128kbps",label:"MP3 128kbps",value:1},{objName:"realityAudioHQ",label:"360 Reality Audio [HQ]",value:15},{objName:"realityAudioMQ",label:"360 Reality Audio [MQ]",value:14},{objName:"realityAudioLQ",label:"360 Reality Audio [LQ]",value:13}];var script$u={data(){return{menuOpen:!1,xPos:0,yPos:0,deezerHref:"",generalHref:"",imgSrc:""}},computed:{options(){const e={cut:{label:this.$t("globals.cut"),show:!1,position:1,action:()=>{document.execCommand("Cut")}},copy:{label:this.$t("globals.copy"),show:!1,position:2,action:()=>{document.execCommand("Copy")}},copyLink:{label:this.$t("globals.copyLink"),show:!1,position:3,action:()=>{copyToClipboard(this.generalHref)}},copyImageLink:{label:this.$t("globals.copyImageLink"),show:!1,position:4,action:()=>{copyToClipboard(this.imgSrc)}},copyDeezerLink:{label:this.$t("globals.copyDeezerLink"),show:!1,position:5,action:()=>{copyToClipboard(this.deezerHref)}},paste:{label:this.$t("globals.paste"),show:!1,position:6,action:()=>{clipboard in navigator?navigator.clipboard.readText().then(n=>{document.execCommand("insertText",void 0,n)}):document.execCommand("paste")}}},a=Object.values(e).length+1;return downloadQualities.forEach((n,r)=>{e[n.objName]={label:`${this.$t("globals.download",{thing:n.label})}`,show:!1,position:a+r,action:sendAddToQueue.bind(null,this.deezerHref,n.value)}}),e},sortedOptions(){return Object.values(this.options).sort((e,a)=>e.position{this.menuOpen=!1,this.options.copyLink.show=!1,this.options.copyDeezerLink.show=!1,this.options.copyImageLink.show=!1,downloadQualities.forEach(e=>{this.options[e.objName].show=!1})}).catch(e=>{console.error(e)})},positionMenu(e,a){this.xPos=`${e}px`,this.yPos=`${a}px`,this.$nextTick().then(()=>{const{innerHeight:n,innerWidth:r}=window,i=e+this.$refs.contextMenu.getBoundingClientRect().width,s=a+this.$refs.contextMenu.getBoundingClientRect().height;if(i>r){const l=i-r+15;this.xPos=`${e-l}px`}if(s>n){const l=s-n+15;this.yPos=`${a-l}px`}})},showDeezerOptions(e){e||(this.options.copyDeezerLink.show=!0),downloadQualities.forEach(a=>{this.options[a.objName].show=!0})}}};const __vue_script__$u=script$u;var __vue_render__$v=function(){var e=this,a=e.$createElement,n=e._self._c||a;return n("div",{directives:[{name:"show",rawName:"v-show",value:e.menuOpen,expression:"menuOpen"}],ref:"contextMenu",staticClass:"context-menu",style:{top:e.yPos,left:e.xPos}},e._l(e.sortedOptions,function(r){return n("button",{directives:[{name:"show",rawName:"v-show",value:r.show,expression:"option.show"}],key:r.label,staticClass:"btn menu-option",on:{click:function(i){return i.preventDefault(),r.action(i)}}},[n("span",{staticClass:"menu-option__text"},[e._v(e._s(r.label))])])}),0)},__vue_staticRenderFns__$v=[];const __vue_inject_styles__$v=function(e){!e||e("data-v-56c7988a_0",{source:".context-menu[data-v-56c7988a]{position:absolute;top:0;left:0;min-width:100px;border-radius:7px;background:var(--secondary-background);box-shadow:4px 10px 18px 0 rgba(0,0,0,.15);overflow:hidden;z-index:10000}.menu-option[data-v-56c7988a]{display:flex;align-items:center;width:100%;height:40px;padding-left:10px;padding-right:10px;color:var(--foreground);cursor:pointer}.menu-option[data-v-56c7988a]:hover{background:var(--table-highlight);filter:brightness(150%)}.menu-option__text[data-v-56c7988a]{text-transform:capitalize}button[data-v-56c7988a]{color:var(--primary-text);color:unset;background-color:var(--primary-color);background-color:unset;min-width:unset;position:unset;border:unset;border-radius:unset;font-family:unset;font-weight:unset;font-size:unset;padding:unset;margin-right:unset;height:unset;text-transform:unset;cursor:unset;transition:unset}button[data-v-56c7988a]:focus{outline:0}button[data-v-56c7988a]:active{background-color:unset;transform:unset}button[data-v-56c7988a]:hover{background:unset;border:unset}",map:void 0,media:void 0})},__vue_scope_id__$v="data-v-56c7988a",__vue_module_identifier__$c=void 0,__vue_is_functional_template__$v=!1;function __vue_normalize__$v(e,a,n,r,i,s,l,c){const o=(typeof n=="function"?n.options:n)||{};o.__file="TheContextMenu.vue",o.render||(o.render=e.render,o.staticRenderFns=e.staticRenderFns,o._compiled=!0,i&&(o.functional=!0)),o._scopeId=r;{let u;if(a&&(u=function(d){a.call(this,l(d))}),u!==void 0)if(o.functional){const d=o.render;o.render=function(h,m){return u.call(m),d(h,m)}}else{const d=o.beforeCreate;o.beforeCreate=d?[].concat(d,u):[u]}}return o}function __vue_create_injector__$c(){const e=document.head||document.getElementsByTagName("head")[0],a=__vue_create_injector__$c.styles||(__vue_create_injector__$c.styles={}),n=typeof navigator!="undefined"&&/msie [6-9]\\b/.test(navigator.userAgent.toLowerCase());return function(i,s){if(document.querySelector('style[data-vue-ssr-id~="'+i+'"]'))return;const l=n?s.media||"default":i,c=a[l]||(a[l]={ids:[],parts:[],element:void 0});if(!c.ids.includes(i)){let o=s.source,u=c.ids.length;if(c.ids.push(i),s.map&&(o+=` /*# sourceURL=`+s.map.sources[0]+" */",o+=` /*# sourceMappingURL=data:application/json;base64,`+btoa(unescape(encodeURIComponent(JSON.stringify(s.map))))+" */"),n&&(c.element=c.element||document.querySelector("style[data-group="+l+"]")),!c.element){const d=c.element=document.createElement("style");d.type="text/css",s.media&&d.setAttribute("media",s.media),n&&(d.setAttribute("data-group",l),d.setAttribute("data-next-index","0")),e.appendChild(d)}if(n&&(u=parseInt(c.element.getAttribute("data-next-index")),c.element.setAttribute("data-next-index",u+1)),c.element.styleSheet)c.parts.push(o),c.element.styleSheet.cssText=c.parts.filter(Boolean).join(` `);else{const d=document.createTextNode(o),f=c.element.childNodes;f[u]&&c.element.removeChild(f[u]),f.length?c.element.insertBefore(d,f[u]):c.element.appendChild(d)}}}}var TheContextMenu=__vue_normalize__$v({render:__vue_render__$v,staticRenderFns:__vue_staticRenderFns__$v},__vue_inject_styles__$v,__vue_script__$u,__vue_scope_id__$v,__vue_is_functional_template__$v,__vue_module_identifier__$c,__vue_create_injector__$c);/*! diff --git a/src/utils/utils.js b/src/utils/utils.js index 3a7f540..8a56095 100644 --- a/src/utils/utils.js +++ b/src/utils/utils.js @@ -2,6 +2,7 @@ * Climbs the DOM until the root is reached, storing every node passed. * @param {HTMLElement} el * @return {Array} Contains all the nodes between el and the root + * @since 0.0.0 */ export function generatePath(el) { if (!el) { @@ -17,6 +18,11 @@ export function generatePath(el) { return path } +/** + * @param {string} text + * @returns {boolean} + * @since 0.0.0 + */ export function isValidURL(text) { const lowerCaseText = text.toLowerCase() @@ -35,6 +41,11 @@ export function isValidURL(text) { return false } +/** + * @param {number} duration + * @returns {string} + * @since 0.0.0 + */ export function convertDuration(duration) { // Convert from seconds only to mm:ss format let mm, ss @@ -47,6 +58,11 @@ export function convertDuration(duration) { return mm + ':' + ss } +/** + * @param {number} duration + * @returns {[number, number, number]} + * @since 0.0.0 + */ export function convertDurationSeparated(duration) { let hh, mm, ss mm = Math.floor(duration / 60) @@ -56,9 +72,13 @@ export function convertDurationSeparated(duration) { return [hh, mm, ss] } -export function numberWithDots(x) { - return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.') -} +/** + * @param {number} x + * @returns {string} + * @since 0.0.0 + * @deprecated + */ +export const numberWithDots = x => x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.') // On scroll event, returns currentTarget = null // Probably on other events too @@ -82,7 +102,9 @@ export function debounce(func, wait, immediate) { * Workaround to copy to the clipboard cross-OS by generating a * ghost input and copying the passed String * - * @param {string} text Text to copy + * @param {string} text Text to copy + * @returns void + * @since 0.0.0 */ export function copyToClipboard(text) { const ghostInput = document.createElement('input') @@ -100,6 +122,7 @@ export function copyToClipboard(text) { * @param {object|array} obj * @param {...any} props * @returns {any|null} property requested + * @since 0.0.0 */ export function getPropertyWithFallback(obj, ...props) { for (const prop of props) { diff --git a/tests/unit/utils/texts.spec.js b/tests/unit/utils/texts.spec.js new file mode 100644 index 0000000..eefafff --- /dev/null +++ b/tests/unit/utils/texts.spec.js @@ -0,0 +1,17 @@ +import { upperCaseFirstLowerCaseRest } from '../../../src/utils/texts' + +describe('texts utils', () => { + describe('upperCaseFirstLowerCaseRest', () => { + it('converts a full uppercase string', () => { + expect(upperCaseFirstLowerCaseRest('TEST STRING')).toBe('Test string') + }) + + it('converts a full lowercase string', () => { + expect(upperCaseFirstLowerCaseRest('test string')).toBe('Test string') + }) + + it('converts a mixed string', () => { + expect(upperCaseFirstLowerCaseRest("i wOn'T woRK")).toBe("I won't work") + }) + }) +}) diff --git a/tests/unit/utils/utils.spec.js b/tests/unit/utils/utils.spec.js new file mode 100644 index 0000000..0e64e59 --- /dev/null +++ b/tests/unit/utils/utils.spec.js @@ -0,0 +1,33 @@ +import { isValidURL, convertDuration, convertDurationSeparated } from '../../../src/utils/utils' + +describe('utils utils (needs refactor)', () => { + describe('isValidURL', () => { + it('returns a positive result with all supported URLs', () => { + expect(isValidURL('https://www.deezer.com')).toBe(true) + expect(isValidURL('https://deezer.page.link')).toBe(true) + expect(isValidURL('https://open.spotify.com')).toBe(true) + expect(isValidURL('https://link.tospotify.com')).toBe(true) + expect(isValidURL('spotify:something')).toBe(true) + }) + + it('returns a negative result with a not supported URL', () => { + expect(isValidURL('https://www.google.com')).toBe(false) + }) + }) + + describe('convertDuration', () => { + it('converts seconds in the correct format', () => { + expect(convertDuration(120)).toBe('2:00') + expect(convertDuration(60)).toBe('1:00') + expect(convertDuration(30)).toBe('0:30') + }) + }) + + describe('convertDurationSeparated', () => { + it('converts seconds in the correct format', () => { + expect(convertDurationSeparated(120)).toStrictEqual([0, 2, 0]) + expect(convertDurationSeparated(60)).toStrictEqual([0, 1, 0]) + expect(convertDurationSeparated(30)).toStrictEqual([0, 0, 30]) + }) + }) +})