typecho-core
Version:
An element-drived engine working well with XHR-intensive front-end. Originally designed for Typecho.
13 lines (12 loc) • 36.2 kB
JavaScript
/**!
* lrc-file-parser.js v2.4.0
* Homepage: https://github.com/lyswhut/lrc-file-parser#readme
* License: MIT
*/
var Lyric=function(){"use strict";function t(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,n)}return i}function e(e){for(var i=1;i<arguments.length;i++){var n=null!=arguments[i]?arguments[i]:{};i%2?t(Object(n),!0).forEach((function(t){r(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):t(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function i(t){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i(t)}function n(t,e){for(var i=0;i<e.length;i++){var n=e[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,l(n.key),n)}}function r(t,e,i){return(e=l(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function s(t){return function(t){if(Array.isArray(t))return o(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||a(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(t,e){if(t){if("string"==typeof t)return o(t,e);var i=Object.prototype.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?o(t,e):void 0}}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,n=new Array(e);i<e;i++)n[i]=t[i];return n}function u(t,e){var i="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!i){if(Array.isArray(t)||(i=a(t))||e&&t&&"number"==typeof t.length){i&&(t=i);var n=0,r=function(){};return{s:r,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,o=!0,u=!1;return{s:function(){i=i.call(t)},n:function(){var t=i.next();return o=t.done,t},e:function(t){u=!0,s=t},f:function(){try{o||null==i.return||i.return()}finally{if(u)throw s}}}}function l(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}var c=/^(?:\[[\d:.]+\])+/g,h=/\d{1,3}(:\d{1,3}){0,2}(?:\.\d{1,3})/g,f={title:"ti",artist:"ar",album:"al",offset:"offset",by:"by"},m="object"==("undefined"==typeof performance?"undefined":i(performance))&&performance.now?performance.now.bind(performance):Date.now.bind(Date),y=function(){},d={invokeTime:0,animationFrameId:null,timeoutId:null,callback:null,thresholdTime:200,run:function(){var t=this;this.animationFrameId=window.requestAnimationFrame((function(){t.animationFrameId=null;var e=t.invokeTime-m();if(e>0)return e<t.thresholdTime?void t.run():t.timeoutId=setTimeout((function(){t.timeoutId=null,t.run()}),e-t.thresholdTime);t.callback(e)}))},start:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:y,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;this.callback=t,this.invokeTime=m()+e,this.run()},clear:function(){this.animationFrameId&&(window.cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.timeoutId&&(window.clearTimeout(this.timeoutId),this.timeoutId=null),this.callback=null}},v=/^0+(\d+)/,p=/:0+(\d+)/g,b=/\.0+(\d+)/,L=function(t){return t.replace(v,"$1").replace(p,":$1").replace(b,".$1")},g=function(t,e){for(var i=e.split(/\r\n|\n|\r/),n=0;n<i.length;n++){var r=i[n].trim(),s=c.exec(r);if(s){var a=s[0],o=r.replace(c,"").trim();if(o){var l=a.match(h);if(null==l)continue;var f,m=u(l);try{for(m.s();!(f=m.n()).done;){var y=f.value,d=t[L(y)];d&&d.extendedLyrics.push(o)}}catch(t){m.e(t)}finally{m.f()}}}}},_={title:"",artist:"",album:"",offset:0,by:""},k=function(){function t(i){var n=i.lyric,s=void 0===n?"":n,a=i.extendedLyrics,o=void 0===a?[]:a,u=i.offset,l=void 0===u?150:u,c=i.playbackRate,h=void 0===c?1:c,f=i.onPlay,m=void 0===f?y:f,d=i.onSetLyric,v=void 0===d?y:d,p=i.isRemoveBlankLine,b=void 0===p||p;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),r(this,"lyric",void 0),r(this,"extendedLyrics",void 0),r(this,"tags",void 0),r(this,"lines",void 0),r(this,"onPlay",void 0),r(this,"onSetLyric",void 0),r(this,"isPlay",void 0),r(this,"curLineNum",void 0),r(this,"maxLine",void 0),r(this,"offset",void 0),r(this,"isRemoveBlankLine",void 0),r(this,"_playbackRate",void 0),r(this,"_performanceTime",void 0),r(this,"_startTime",void 0),this.lyric=s,this.extendedLyrics=o,this.tags=e({},_),this.lines=[],this.onPlay=m,this.onSetLyric=v,this.isPlay=!1,this.curLineNum=0,this.maxLine=0,this.offset=l,this.isRemoveBlankLine=b,this._playbackRate=h,this._performanceTime=0,this._startTime=0,this._init()}var i,a,o;return i=t,a=[{key:"_init",value:function(){null==this.lyric&&(this.lyric=""),null==this.extendedLyrics&&(this.extendedLyrics=[]),this._initTag(),this._initLines(),this.onSetLyric(this.lines)}},{key:"_initTag",value:function(){this.tags=e({},_);for(var t=0,i=Object.keys(_);t<i.length;t++){var n=i[t],r=this.lyric.match(new RegExp("\\[".concat(f[n],":([^\\]]*)]"),"i"));r&&(this.tags[n]=r[1])}if(this.tags.offset){var s=parseInt(this.tags.offset);this.tags.offset=Number.isNaN(s)?0:s}else this.tags.offset=0}},{key:"_initLines",value:function(){this.lines=[];for(var t=this.lyric.split(/\r\n|\n|\r/),e={},i=t.length,n=0;n<i;n++){var r=t[n].trim(),a=c.exec(r);if(a){var o=a[0],l=r.replace(c,"").trim();if(l||!this.isRemoveBlankLine){var f=o.match(h);if(null==f)continue;var m,y=u(f);try{for(y.s();!(m=y.n()).done;){var d=m.value,v=L(d);if(e[v])e[v].extendedLyrics.push(l);else{var p=v.split(":");if(!(p.length>3)){if(p.length<3)for(var b=3-p.length;b--;)p.unshift("0");p[2].includes(".")&&p.splice.apply(p,[2,1].concat(s(p[2].split(".")))),e[v]={time:60*parseInt(p[0])*60*1e3+60*parseInt(p[1])*1e3+1e3*parseInt(p[2])+parseInt(p[3]||"0"),text:l,extendedLyrics:[]}}}}}catch(t){y.e(t)}finally{y.f()}}}}var _,k=u(this.extendedLyrics);try{for(k.s();!(_=k.n()).done;){var w=_.value;g(e,w)}}catch(t){k.e(t)}finally{k.f()}this.lines=Object.values(e),this.lines.sort((function(t,e){return t.time-e.time})),this.maxLine=this.lines.length-1}},{key:"_currentTime",value:function(){return(m()-this._performanceTime)*this._playbackRate+this._startTime}},{key:"_findCurLineNum",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(t<=0)return 0;for(var i=this.lines.length,n=e;n<i;n++)if(t<=this.lines[n].time)return 0===n?0:n-1;return i-1}},{key:"_handleMaxLine",value:function(){this.onPlay(this.curLineNum,this.lines[this.curLineNum].text),this.pause()}},{key:"_refresh",value:function(){var t=this;if(this.curLineNum++,this.curLineNum>=this.maxLine)this._handleMaxLine();else{var e=this.lines[this.curLineNum],i=this._currentTime(),n=i-e.time;if(n>=0||0===this.curLineNum){var r=(this.lines[this.curLineNum+1].time-e.time-n)/this._playbackRate;if(r>0)this.isPlay&&d.start((function(){t.isPlay&&t._refresh()}),r),this.onPlay(this.curLineNum,e.text);else{var s=this._findCurLineNum(i,this.curLineNum+1);s>this.curLineNum&&(this.curLineNum=s-1),this._refresh()}}else this.curLineNum=this._findCurLineNum(i,this.curLineNum)-1,this._refresh()}}},{key:"play",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.lines.length&&(this.pause(),this.isPlay=!0,this._performanceTime=m()-Math.trunc(this.tags.offset+this.offset),this._startTime=t,this.curLineNum=this._findCurLineNum(this._currentTime())-1,this._refresh())}},{key:"pause",value:function(){if(this.isPlay&&(this.isPlay=!1,d.clear(),this.curLineNum!==this.maxLine)){var t=this._findCurLineNum(this._currentTime());this.curLineNum!==t&&(this.curLineNum=t,this.onPlay(t,this.lines[t].text))}}},{key:"setPlaybackRate",value:function(t){this._playbackRate=t,this.lines.length&&this.isPlay&&this.play(this._currentTime())}},{key:"setLyric",value:function(t,e){this.isPlay&&this.pause(),this.lyric=t,this.extendedLyrics=e,this._init()}}],a&&n(i.prototype,a),o&&n(i,o),Object.defineProperty(i,"prototype",{writable:!1}),t}();return k}();
/* cisum.js */
let Cisum=window.Cisum||{};Cisum={initialized:!1,init:async function(t,e={}){if(!this.initialized){if(window.Howl||await TypechoCore.engine.requestResource("https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-y/howler/2.2.3/howler.core.min.js"),!window.Howl)return console.warn("需要 Howler 依赖,但其加载失败。");this.dataFetcher.setEndpoint(e.endpoint),this.dataFetcher.setSchemas(e.schemas),this.ui.setButtonTemplate(e.buttonTemplate),this.ui.init(t),this.controller.init(),this.lyric.init(),this.converter.init(),this.initialized=!0}},queue:{list:[],current:null,currentIndex:-1,get:function(t,e=!0){t>Cisum.queue.list.length-1?t=0:t<0&&(t=Cisum.queue.list.length-1);const i=this.list.at(t);return e&&(this.current=i,this.currentIndex=t,TypechoCore.trigger(Cisum.ui.container,"cisum:readyForPlay",{data:i})),i},next:function(){return Cisum.controller.isShuffle?this.random():this.currentIndex+1},previous:function(){return Cisum.controller.isShuffle?this.random():this.currentIndex-1},add:function(t,e){if(t&&"object"!=typeof t)return;t=Cisum.dataFetcher.filter(t);const i=this.find(t);if(i>=0){if(i===this.currentIndex)return;this.list.splice(i,1)}let n;switch(this.currentIndex=this.find(this.current),e){case"before":n=this.currentIndex;break;case"after":n=this.currentIndex+1;break;case"start":n=0;break;default:n=this.list.length}return this.list.splice(n,0,t),this.currentIndex=this.find(this.current),Cisum.ui.updatePlaylist(),Cisum.ui.updatePlaylistPlaying(),n},bulkSet:function(t,e=!1){if(!Array.isArray(t))return;if(0===t.length)return void console.warn("由于歌单为空,故无法插入。");const i=t.map((t=>Cisum.dataFetcher.filter(t)));if(e)this.list=this.list.concat(i);else{this._reset(),this.list=i;const t=this.get(0,!0);Cisum.ui.updateElements(t)}Cisum.ui.updatePlaylist(),Cisum.ui.updatePlaylistPlaying()},find:function(t,e=Cisum.queue.list){for(let i=0;i<e.length;i++)if(Cisum.utils.equals(e[i],t))return i;return-1},random:function(){return Math.floor(Math.random()*(this.list.length-1))},_reset:function(){this.list=[],this.current=null,this.currentIndex=-1}},engine:{current:null,fade:{enabled:!0,fadeInDuration:365,fadeOutDuration:225},play:function(){!this.current&&Cisum.queue.current?this._play(Cisum.queue.current):(this._tryFadeIn(),this.current.play())},pause:function(){this.current&&this._tryFadeOut(this.current.pause)},playPrevious:function(){this.playByIndex(Cisum.queue.previous())},playNext:function(t=!1){t&&Cisum.controller.isLoop?this.playByIndex(Cisum.queue.currentIndex,!0):this.playByIndex(Cisum.queue.next())},playByData:function(t){const e=Cisum.queue,i=e.find(t);let n;return i===e.currentIndex?(Cisum.controller.actionPlay(),n=i):(e.add(t,"before"),this.playByIndex(e.currentIndex-1),n=e.currentIndex),TypechoCore.trigger(Cisum.ui.container,"cisum:naturalSwitch"),n},playByIndex:function(t,e=!1){if(t=Number(t),Number.isNaN(t))return;if(!e&&t===Cisum.queue.currentIndex)return;const i=Cisum.queue.get(t,!0);Cisum.ui.updateElements(i),Cisum.ui.updatePlaylistPlaying(),this._play(i)},_play:function(t){this.current&&this._tryFadeOut(this.current.stop),this.current=new window.Howl({src:t.url,format:["mp3"],preload:!0,autoplay:!1,onload:()=>{},onplay:()=>{Cisum.controller.isPlaying=!0,Cisum.ui.updateControls("playing"),Cisum.ui._initializeVisualizer(),t.lrc?Cisum.dataFetcher.fetchLyric(t.lrc).then((t=>{Cisum.lyric.setLyric(t),Cisum.lyric.play()})).catch((()=>Cisum.lyric.hide())):Cisum.lyric.hide(),Cisum.converter.trigger("cisum:play",t)},onpause:()=>{Cisum.controller.isPlaying=!1,Cisum.ui.updateControls("paused"),Cisum.lyric.pause(),Cisum.converter.trigger("cisum:pause",t)},onend:()=>{Cisum.engine.playNext(!0),TypechoCore.trigger(Cisum.ui.container,"cisum:naturalSwitch")}}),Cisum.converter.trigger("cisum:play",t),this.play()},_tryFadeIn:function(){this.fade.enabled&&this.current&&this.current.fade(0,1,this.fade.fadeInDuration)},_tryFadeOut:function(t){if("function"==typeof t&&this.current){if(!this.fade.enabled)return t();this.current.once("fade",t),this.current.fade(1,0,this.fade.fadeOutDuration)}}},controller:{isPlaying:!1,isMuted:!1,isShuffle:!1,isLoop:!1,showLyric:!1,showVisualizer:!1,blockIdle:!1,init:function(){this.actionLyricToggle(),this.actionVisualizerToggle()},actionPlay:function(){this.isPlaying?Cisum.engine.pause():Cisum.engine.play()},actionShuffle:function(){let t;this.isShuffle?(this.isShuffle=!1,t="-shuffle"):(this.isShuffle=!0,this.isLoop=!1,t="shuffle"),Cisum.ui.updateControls(t)},actionLoop:function(){let t;this.isLoop?(this.isLoop=!1,t="-loop"):(this.isLoop=!0,this.isShuffle=!1,t="loop"),Cisum.ui.updateControls(t)},actionIdleToggle:function(){this.blockIdle=!this.blockIdle,this.blockIdle?this._idleSuspendCallback():this._idleRecoverCallback(),Cisum.ui.toggle("controls","idleToggle",this.blockIdle)},actionPrevious:()=>Cisum.engine.playPrevious(),actionNext:()=>Cisum.engine.playNext(),actionPlaylistScroll:()=>Cisum.ui.scrollToPlaylistPlaying(),actionPlaylistTop:()=>Cisum.ui.scrollToPlaylistTop(),actionLyricToggle:()=>Cisum.controller._actionToggle("lyric"),actionVisualizerToggle:()=>Cisum.controller._actionToggle("visualizer"),setIdleCallbacks:function(t,e){"function"==typeof t&&(this._idleSuspendCallback=t),"function"==typeof e&&(this._idleRecoverCallback=e)},_idleSuspendCallback:function(){},_idleRecoverCallback:function(){},_actionToggle:t=>{const e="show"+Cisum.utils.upperFirst(t);this[e]=!this[e],Cisum.ui.toggle("elements",t,!this[e],"u-hidden"),Cisum.ui.toggle("controls",`${t}Toggle`,this[e])}},ui:{container:null,elements:{cover:null,artist:null,title:null,lyric:null,visualizer:null,playlist:null},controls:{play:null,shuffle:null,loop:null,next:null,previous:null,playlistScroll:null,playlistTop:null,lyricToggle:null,visualizerToggle:null,idleToggle:null},buttonTemplate:null,activePlaylistItemClass:"is-active",playlistScrollOffset:-35,_originalPlaylistContent:null,init:function(t){this.container=t,this._fetchElements("elements"),this._fetchElements("controls"),this._initializeControls(),this._initializePlaylist()},toggle:function(t,e,i=!0,n="is-active"){const s=this[t][e];s&&(i?s.classList.add(n):s.classList.remove(n))},setButtonTemplate:function(t){Cisum.utils.checkSchema(t)&&(this.buttonTemplate=t)},setPlaylistScrollOffset:function(t){(t=parseInt(String(t)))&&(this.playlistScrollOffset=t)},getButton:function(t){return this.buttonTemplate?.replace(/%s/g,t)||t},updateElements:function(t){const e=this.elements;e.cover.dataset.src=t.cover,e.cover.classList.add("lazyload"),e.title.innerText=t.name,e.title.setAttribute("title",t.name),e.artist.innerText=t.artist},updateControls:function(t){if(!t)return;const e=this.controls.play;switch(t){case"loading":this.container.classList.add("is-loading"),e.style.pointerEvents="none";break;case"loaded":this.container.classList.remove("is-loading"),e.style.pointerEvents="";break;case"playing":e.innerHTML=this.getButton("pause");break;case"stop":case"paused":e.innerHTML=this.getButton("play_arrow");break;case"shuffle":this._enableShuffle();break;case"-shuffle":this._disableShuffle();break;case"loop":this._enableLoop();break;case"-loop":this._disableLoop()}},updateLyric:function(t,e){const i=this.elements.lyric;Number(i.dataset.line)!==t&&(i.classList.toggle("lyric-toggle"),i.innerText=e,i.dataset.line=t)},updatePlaylist:function(){const t=Cisum.queue.list;if(this.elements.playlist&&0!==t.length){this.elements.playlist.innerHTML=this._originalPlaylistContent;for(let e=0;e<t.length;e++){const i=this._playlistItemFactory(t[e],e);this.elements.playlist.appendChild(i)}}},updatePlaylistPlaying:function(t=Cisum.queue.currentIndex,e=Cisum.ui.elements.playlist){const i=this._fetchPlayingItem(e);i&&i.classList.remove("is-active");const n=this._fetchToPlayItem(t,e);n&&n.classList.add("is-active")},scrollToPlaylistPlaying:function(t=Cisum.ui.elements.playlist){const e=this._fetchPlayingItem(t);e&&TypechoCore.utils.scrollTo(e,{legacy:!0,offset:this.playlistScrollOffset})},scrollToPlaylistTop:function(){const t=this.elements.playlist.querySelector("li");TypechoCore.utils.scrollTo(t,{block:"center"})},_disableLoop:function(){this.toggle("controls","loop",!1)},_disableShuffle:function(){this.toggle("controls","shuffle",!1)},_enableLoop:function(){this.toggle("controls","loop",!0),this._disableShuffle()},_enableShuffle:function(){this.toggle("controls","shuffle",!0),this._disableLoop()},_fetchElements:function(t){for(const e in this[t])this[t].hasOwnProperty(e)&&(this[t][e]=document.getElementById("cisum-"+e))},_fetchPlayingItem:function(t){const e="."+this.activePlaylistItemClass;return t.querySelector(e)},_fetchToPlayItem:function(t,e){const i=`[data-index="${t}"]`;return e.querySelector(i)},_initializeControls:function(){for(const t in this.controls)if(this.controls.hasOwnProperty(t)){const e=Cisum.controller,i=e["action"+Cisum.utils.upperFirst(t)];"function"==typeof i&&this.controls[t].addEventListener("click",i.bind(e))}},_initializePlaylist:function(){this._originalPlaylistContent=this.elements.playlist.innerHTML,this.elements.playlist.addEventListener("dblclick",(t=>{const e=t.target;if(e instanceof HTMLElement&&"LI"===e.tagName){const t=e.dataset.index;Cisum.engine.playByIndex(t)}}))},_playlistItemFactory(t,e){const i=document.createElement("li");return i.dataset.index=String(e),i.innerHTML=`${e+1}. ${t.name}<span>${t.artist}</span>`,i},_initializeVisualizer:function(){const t=document.getElementById("cisum-visualizer");if(!t)return;const e=window.Howler.ctx,i=t.getContext("2d");let n=null;n=e.createAnalyser();Cisum.engine.current._sounds[0]._node.connect(n),n.fftSize=128;const s=n.frequencyBinCount,l=new Uint8Array(s),a=t.width/s;let r=0;const o=({bufferLength:e,dataArray:n,barWidth:s})=>{let l;for(let a=0;a<e;a++){l=.75*n[a+10];const e=a*l/10,o=5*a,c=l/4-16;i.fillStyle=`rgb(${e}, ${o}, ${c})`,i.fillRect(r,t.height-l,s,l),r+=s}};this.elements.visualizer=t,function e(){r=0,i.clearRect(0,0,t.width,t.height),n.getByteFrequencyData(l),o({bufferLength:s,dataArray:l,barWidth:a}),requestAnimationFrame(e)}()}},dataFetcher:{endpoint:"",cache:{},schemas:{song:null,playlist:null,songUrl:null,lyric:null},setEndpoint:function(t){this.endpoint=t},setSchemas:function(t){for(const e in t)this.schemas.hasOwnProperty(e)&&Cisum.utils.checkSchema(t[e])&&(this.schemas[e]=t[e])},filter:function(t){return{url:t.src||t.url,name:t.name||t.title,cover:t.cover||t.pic,artist:t.artist,lrc:t.lrc}},fetchPlaylistById:function(t,e=t=>Cisum.queue.bulkSet(t)){const i=this._setupFinalUrl("playlist",t);this.fetchPlaylistByUrl(i,e)},fetchPlaylistByUrl:function(t,e){fetch(t).then((t=>t.json())).then((t=>"function"==typeof e&&e(t))).catch((t=>{TypechoCore.ui.flashMessage("歌单设置失败,前往控制台了解更多信息。"),console.warn("歌单数据获取失败。",t)}))},fetchSong:function(t){const e=this._setupFinalUrl("song",t),i=this._getCache(e);return i?Promise.resolve(i):fetch(e).then((t=>t.json())).then((t=>(this._setCache(e,t),t))).catch((t=>console.warn("音乐数据获取失败。",t)))},fetchLyric:function(t){const e=this._getCache(t);return e?Promise.resolve(e):fetch(t).then((t=>t.text())).then((e=>(this._setCache(t,e),e))).catch((t=>Cisum.lyric.setLyric("")))},_setupFinalUrl:function(t,e){const i=this.schemas[t];return i?this.endpoint+i.replace(/%s/g,e):""},_setCache:function(t,e){this.cache[t]=e},_getCache:function(t){return this.cache[t]}},lyric:{instance:null,lyricString:null,init:function(){window.Lyric&&(this.instance=new window.Lyric({onPlay:(t,e)=>Cisum.ui.updateLyric(t,e)}))},play:function(){this.show();const t=1e3*Cisum.engine.current.seek();this.instance.play(t)},pause:function(){this.instance.pause()},show:function(){const t=Cisum.ui.elements.lyric;t&&(t.style.display="")},hide:function(){const t=Cisum.ui.elements.lyric;t&&(t.style.display="none")},setLyric:function(t){"string"==typeof t&&this.instance&&(this.lyricString=t,this.instance.setLyric(t))}},converter:{validTypes:["standalone","playlist"],elements:[],playlists:{},init:function(){TypechoCore.xhr.register((function(){this.elements=[],this.playlists={}}),!1,"send",this)},convert:function(t){if(!(t instanceof HTMLElement))return;const e=t.dataset.type||"standalone";this.validTypes.includes(e)&&(this._componentFactory(e,t),this.elements.push(t))},trigger:function(t,e){this.elements.forEach((i=>TypechoCore.trigger(i,t,e)))},_componentFactory:function(t,e){const i=e.dataset.id,n=Cisum.dataFetcher;switch(t){case"standalone":i?n.fetchSong(i).then((t=>this._standaloneHandler(t,e))):this._standaloneHandler(e.dataset,e);break;case"playlist":i&&n.fetchPlaylistById(i,(t=>{const n=t.map((t=>Cisum.dataFetcher.filter(t)));this.playlists[i]=n,this._playlistHandler(n,e)}))}},_standaloneHandler:function(t,e){const{data:i,inner:n,actionContainer:s}=this._filterAndSetupBasisContent(t,e),l=document.createElement("button"),a=document.createElement("button"),r=function(t){const e=t.detail;let n,s=!1;try{s=Cisum.utils.equals(e,i)}catch(t){}n=s&&Cisum.controller.isPlaying?"pause":"play_arrow",l.innerHTML=Cisum.ui.getButton(n)};e.classList.add("music-standalone"),e.addEventListener("cisum:play",r),e.addEventListener("cisum:pause",r),l.setAttribute("title","现在播放"),r({detail:Cisum.queue.current}),a.setAttribute("title","稍后播放"),a.innerHTML=Cisum.ui.getButton("add"),l.addEventListener("click",(t=>{Cisum.engine.playByData(i),t.stopPropagation()})),a.addEventListener("click",(()=>{Cisum.queue.add(i,"after"),a.innerHTML=Cisum.ui.getButton("done"),a.style.pointerEvents="none",setTimeout((()=>{a.innerHTML=Cisum.ui.getButton("add"),a.style.pointerEvents=""}),2e3)})),s.appendChild(l),s.appendChild(a)},_playlistHandler:function(t,e){const{data:i,inner:n,actionContainer:s}=this._filterAndSetupBasisContent(e.dataset,e);e.classList.add("music-playlist","p-player--playlistContainer");const l=document.createElement("button");l.setAttribute("title","播放此歌单"),l.innerHTML=Cisum.ui.getButton("play_arrow"),s.appendChild(l);const a=document.createElement("ul");a.classList.add("p-playerWidget--playlist");for(let e=0;e<t.length;e++){const i=Cisum.ui._playlistItemFactory(t[e],e);a.appendChild(i)}e.addEventListener("dblclick",(t=>{const i=t.target,n=e.dataset.id;if(i instanceof HTMLElement&&"LI"===i.tagName){const t=i.dataset.index,e=this.playlists[n].at(t);Cisum.engine.playByData(e)}})),e.addEventListener("cisum:play",(t=>{const i=t.detail,n=e.dataset.id,s=this.playlists[n],l=Cisum.queue.find(i,s);l>=0&&Cisum.ui.updatePlaylistPlaying(l,a)})),e.appendChild(a)},_filterAndSetupBasisContent:function(t,e){Array.isArray(t)&&(t=t.at(0)),t=Cisum.dataFetcher.filter(t);const i=document.createElement("div");i.classList.add("p-playerWidget--inner"),e.innerHTML=`<img data-src="${t.cover}" alt="小控件“${t.name}”的背景图" class="p-player--coverBg p-playerWidget--background lazyload">`,i.innerHTML=`<img data-src="${t.cover}" alt="小控件“${t.name}”的封面" class="p-playerWidget--cover lazyload"><div class="p-playerWidget--info"><h4 class="p-playerWidget--title">${t.name}</h4><p class="p-playerWidget--description">${t.artist}</p></div>`;const n=document.createElement("div");return n.classList.add("p-playerWidget--actions"),i.appendChild(n),e.appendChild(i),{data:t,inner:i,actionContainer:n}}},utils:{checkSchema:function(t){return t&&"string"==typeof t&&t.includes("%s")},upperFirst:function(t){return t.charAt(0).toUpperCase()+t.slice(1)},equals:function(t,e){return t.name===e.name&&t.artist===e.artist}}};
/* citizenCore.js */
!function(e,t){const o="https://registry.npmmirror.com/@fancyapps/ui/5.0.36/files/dist/",r=new URL(t.currentScript.src).origin+TypechoCore.utils.getRelativePath();TypechoCore.state("citizenRoot",r),TypechoCore.utils.bindKey((function(){try{t.querySelector(".p-search .p-header--button.js-switchable").click()}catch(e){console.warn("搜索控件丢失。",e)}}),(e=>{const o=t.activeElement.tagName;return!["INPUT","DIV","TEXTAREA","SELECT"].includes(o)&&191===e.which}),!0);const c=t.querySelectorAll(".p-header .js-switchable");for(const e of c)TypechoCore.ui.switchable(e);TypechoCore.Element.animateIn=e=>e,TypechoCore.Element.themeSwitch=function(o){if(!function(t){let o;try{o=e[t];const r="__storage_test__";return o.setItem(r,r),o.removeItem(r),!0}catch(e){return e instanceof DOMException&&(22===e.code||1014===e.code||"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&o&&0!==o.length}}("localStorage"))return console.warn("由于 LocalStorage 不可用,明暗切换已被禁用。");o.addEventListener("click",(function(e){TypechoCore.trigger(t,"citizen:themeSwitched"),t.documentElement.classList.toggle("skin-dark");const o=t.documentElement.classList.contains("skin-dark");localStorage.setItem("citizenTheme",o?"dark":"light")}))},TypechoCore.Element.loaderIndicator=function(e){const t=e.dataset.icon??"switcher";e.style.backgroundImage="url(https://registry.npmmirror.com/typecho-core/latest/files/citizen/spinners/"+t+".svg)",t.endsWith("no_animation")&&(e.style.animation="none"),TypechoCore.xhr.register((()=>TypechoCore.ui.fadeOut(e,100))),TypechoCore.xhr.register((()=>TypechoCore.ui.fadeIn(e,100)),!1,"send")},TypechoCore.Element.classicHeader=function(e){TypechoCore.ui.sticky(e,{minWindowHeight:251,setCss:!1});const t=e.querySelector(".p-header--end");TypechoCore.xhr.register((function(){const e=TypechoCore.content.registerPageTitle(".firstHeading");e?t.classList.add("switchable"):t.classList.remove("switchable"),t.style.setProperty("--page-title",`'${e}'`)}),!0,"success")},TypechoCore.Element.contentArea=async function(e){TypechoCore.content.registerArea();const t=e.querySelectorAll("h2, h3");for(const e of t)e.setAttribute("id",e.innerText);const o=e.querySelectorAll("img");for(const e of o)e.classList.add("lazyload"),e.dataset.src=e.src;await TypechoCore.Element.toc(e),await TypechoCore.Element.fancybox(e),TypechoCore.Element.prismJS(e),TypechoCore.Processor.cisumConverter(e),e.dataset.contentLoading="loaded"},TypechoCore.Element.fancybox=async function(r){const c=r.dataset.type;if(c&&c.includes("carousel"))return void TypechoCore.Element.carousel(r).then();const s=r.classList.contains("js-gallery")?"img":"img.js-lightbox",n=r.querySelectorAll("figure.image_resized"),a=r.querySelectorAll(s),i=r.querySelectorAll("a.js-lightbox");if(n.length+a.length+i.length!==0&&(await TypechoCore.engine.requestResource([o+"fancybox/fancybox.umd.js",o+"fancybox/fancybox.css"]),void 0!==e.Fancybox)){for(const e of n){const o=e.querySelector(":scope > img"),r=e.querySelector(":scope > figcaption"),c=o.getAttribute("alt");if(!o||!c)continue;const s=t.createElement("a");s.href=o.dataset.src,s.dataset.caption=r?.textContent||c,s.dataset.fancybox="article-figures",o.replaceWith(s),s.appendChild(o)}for(const e of a){if(!e.hasAttribute("alt")||e.hasAttribute("href"))continue;const o=e.parentElement;if(o&&"A"===o.tagName)continue;const r=t.createElement("a");r.href=e.dataset.src,r.dataset.caption=e.getAttribute("alt"),r.dataset.fancybox=e.dataset.fancyboxSeries||"standalone-figures",e.replaceWith(r),r.appendChild(e)}for(const e of i){const t=e.getAttribute("href"),[o,r]=t.split("?"),c=new URLSearchParams(r||""),s=c.get("data_caption")||"";c.delete("data_caption");const n=c.toString();e.href=o+(n?`?${n}`:""),e.dataset.fancybox="",e.dataset.caption=s}return e.Fancybox.bind("[data-fancybox]",{l10n:"zh",Hash:!1}),Promise.resolve(r)}},TypechoCore.Element.carousel=async function(r){const c=r.querySelectorAll("img");if(0===c.length)return;const s=TypechoCore.ui.inspector(r,"正在加载 Carousel。"),n=`${o}carousel/carousel.`,a=`${o}fancybox/fancybox.`;await TypechoCore.engine.requestResource([`${n}umd.js`,`${n}thumbs.umd.js`,`${n}css`,`${n}thumbs.css`,`${a}umd.js`,`${a}css`]);let i="modern",l=!1,u=!1,h={Thumbs:e.Thumbs};switch(r.dataset.type){case"classic-carousel":i="classic";break;case"adaptive-carousel":l=!0;break;case"autoPlay-carousel":u={timeout:3e3},await TypechoCore.engine.requestResource([`${n}autoplay.umd.js`,`${n}autoplay.css`]),h.Autoplay=e.Autoplay}const d={l10n:"zh_CN",adaptiveHeight:l,Thumbs:{type:i},AutoPlay:u},y=TypechoCore.state("citizen.carouselIndex");c.forEach((e=>{const o=t.createElement("div"),r=t.createElement("img"),c=e.getAttribute("alt"),s=e.getAttribute("src"),n=e.getAttribute("title");o.classList.add("f-carousel__slide"),o.dataset.thumbSrc=e.dataset.thumbSrc||s,r.dataset.src=s,r.dataset.lazySrc=s,r.dataset.fancybox=`carousel-${y}`,r.dataset.caption=c||n,e.replaceWith(o),o.appendChild(r)})),TypechoCore.state("citizen.carouselIndex",y+1),new e.Carousel(r,d,h),s.remove(),e.Fancybox.bind("[data-fancybox]",{l10n:"zh",Hash:!1})},TypechoCore.Element.prismJS=function(t){const o=t.getElementsByTagName("pre");if(0===o.length)return;const c=[];for(let e=0;e<o.length;e++){const t=TypechoCore.ui.inspector(o[e],"正在高亮代码。");c.push(t)}TypechoCore.engine.requestResource([r+"prism/prism.min.js",r+"prism/prism.min.css"]).then((function(){if(void 0!==e.Prism){for(let e=0;e<o.length;e++)o[e].getElementsByTagName("code").length>0&&(o[e].className="line-numbers");e.Prism.highlightAll(!1,null),c.forEach((e=>e.remove()))}}))},TypechoCore.Element.toc=async function(o){const r=t.getElementById("toc");if(!r||0===r.length)return;if(0===o.querySelectorAll("h2").length)return r.remove();await TypechoCore.engine.requestResource(["https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-y/tocbot/4.18.2/tocbot.min.js","https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-y/tocbot/4.18.2/tocbot.min.css"]);const c=e.tocbot;c.init({headingSelector:"h2",activeLinkClass:"is-active",tocSelector:".toc-target",contentSelector:".p-content",ignoreSelector:".js-toc-ignore",hasInnerContainers:!0,scrollSmooth:!0,scrollSmoothDuration:40,headingsOffset:20,scrollSmoothOffset:-20,includeTitleTags:!0});const s=r.querySelector(".js-switchable");TypechoCore.ui.switchable(s),TypechoCore.xhr.registerOnce((function(){c.destroy(),e.onscroll=null}))},TypechoCore.Element.fabulous=function(e){const o="fab_record",r=Number(TypechoCore.content.cid);if(!TypechoCore.content.permalink)return console.warn("TypechoCore 的 content.permalink 成员属性接口未生效。","只有在提供了 permalink 属性的页面中,Fabulous 功能才能够正常工作。"),e.setAttribute("title","此操作当前不可用。浏览控制台以进一步了解信息。"),void(e.style.cursor="not-allowed");if(TypechoCore.storage.localStorageArrayExists(o,r))return e.classList.add("animation","liked","confetti","noEffect");let c=["#7d32f5","#f6e434","#63fdf1","#e672da","#295dfe","#6e57ff"],s=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),n=e=>{let o=t.createElement("i");o.style.setProperty("--x",s(-260,260)+"px"),o.style.setProperty("--y",s(-160,160)+"px"),o.style.setProperty("--r",s(0,360)+"deg"),o.style.setProperty("--s",s(.6,1)),o.style.setProperty("--b",c[s(0,5)]),e.appendChild(o)};e.addEventListener("click",(function(t){let c=e.children[1].textContent;function s(){e.classList.remove("animation","liked","confetti"),e.children[1].innerText=parseInt(c)-1}if(e.classList.contains("animation"))s();else{e.classList.add("animation");for(let t=0;t<60;t++)n(e);if(setTimeout((()=>{e.classList.add("confetti"),setTimeout((()=>{e.classList.add("liked"),e.children[1].innerText=parseInt(c)+1}),400),setTimeout((()=>{e.querySelectorAll("i").forEach((e=>e.remove()))}),600)}),260),TypechoCore.storage.localStorageArrayExists(o,r))return t.preventDefault();TypechoCore.xhr.request({url:TypechoCore.content.permalink+"/increaseField",method:"POST",responseType:"json"}).then((function(e){TypechoCore.storage.localStorageArray("fab_record",e.cid)}),(function(e){s(),TypechoCore.ui.flashMessage("操作未能完成,可能是由于网络或服务器错误导致。"),console.error("小猫爪发生错误。",e)}))}t.preventDefault()}))},TypechoCore.Element.cisum=function(e){const o=TypechoCore.ui.inspector(e,"正在加载播放器。"),r=e.dataset.playlist,c=e.dataset.endpoint,s=t.getElementById("cisum-trigger");TypechoCore.ui.switchable(s).addEventListener("switchable:hide",(()=>{const e=t.querySelector(".p-player--playlist"),o=TypechoCore.utils.getPair(e);!e.classList.contains("u-hidden")&&o.click()})),Cisum.init(e,{endpoint:c,schemas:{song:"?type=song&id=%s",playlist:"?type=playlist&id=%s"},buttonTemplate:'<span class="ui-icon material-icons">%s</span>'}).then((()=>{o.remove(),r&&Cisum.dataFetcher.fetchPlaylistById(r);const t=TypechoCore.ui.idleByTimeout(e,(()=>e.classList.add("is-idle")),(()=>e.classList.remove("is-idle")),3e3,1e3);t.suspend();const c=Cisum.controller;c.setIdleCallbacks(t.suspend,t.recover),TypechoCore.ui.float(e,{onDragging:()=>t.suspend(!1),onDragEnd:()=>!c.blockIdle&&t.recover(),onBackOriginal:()=>t.suspend(!0)});const s=TypechoCore.content.getArea();TypechoCore.Processor.cisumConverter(s)})),e.addEventListener("cisum:readyForPlay",(function(t){const o=t.detail.data;e.querySelectorAll(".js-playerCover").forEach((e=>{e.dataset.src=o.cover,e.classList.add("lazyload")}))}));e.addEventListener("cisum:naturalSwitch",(function(){const t=e.classList.contains("js-floatDragged"),o=e.classList.contains("u-hidden");!t&&o&&TypechoCore.utils.getPair(e).click()}))},TypechoCore.Processor.cisumConverter=function(e){if(!Cisum.initialized||!e)return;e.querySelectorAll("figure.music").forEach((e=>Cisum.converter.convert(e)))},TypechoCore.register("theme-switch"),TypechoCore.register("loader-indicator"),TypechoCore.register("classic-header"),TypechoCore.register("fancybox"),TypechoCore.register("content-area"),TypechoCore.register("fabulous"),TypechoCore.register("cisum")}(window,document);
/* tapTop.js */
!function(e,t){"use strict";let n,o=null,s=!1,i=!1,l=!1,r=e.pageYOffset||t.documentElement.scrollTop,c=null,u=null,a=null;const d=t.querySelector(".progress-wrap path"),f=d?d.getTotalLength():0;function m(l){if(s)return;let a=e.pageYOffset||t.documentElement.scrollTop,d=r;if(r=a,a>d)"down"!==c&&(c="down",u=d);else{if(!(a<d))return;"up"!==c&&(c="up",u=d)}if(i){if("up"!==c||r<100)return void(n&&(n.cancel(),n=null));if(u-a<30)return}n||(n=function(t,n){n||(n=0);let o=e.requestAnimationFrame||function(t){return e.setTimeout(t,1e3/60)},s=Date.now(),i={};return i.id=o((function e(){Date.now()-s>=n?t():i.id=o(e)})),i.cancel=function(){(e.cancelAnimationFrame||e.clearTimeout)(this.id)},i}((function(){n=null,r<10?g():(p(),v(),o=setTimeout(g,3e3))}),50))}function p(){l||(a.classList.remove("hidden"),a.classList.add("active-progress"),l=!0)}function g(){l&&(a.classList.add("hidden"),a.classList.remove("active-progress"),l=!1)}function h(){const n=e.scrollY,o=t.documentElement.scrollHeight-t.documentElement.clientHeight;d.style.strokeDashoffset=f-n*f/o}function v(){clearTimeout(o)}function T(){r>0&&(v(),p())}function y(){v()}function L(t){s=!0,setTimeout((()=>{s=!1}),500),g(),e.scrollTo({top:0,behavior:"smooth"})}!function(){if(!a&&(a=t.querySelector(".js-scrollButton"),a))"up"===a.dataset.triggerType&&(i=!0),a.addEventListener("mouseenter focus",T),a.addEventListener("mouseleave blur",y),a.addEventListener("click",L),f&&(d.style.transition=d.style.WebkitTransition="none",d.style.strokeDasharray=f+" "+f,d.style.strokeDashoffset=f,d.getBoundingClientRect(),d.style.transition=d.style.WebkitTransition="stroke-dashoffset 10ms linear",h(),e.addEventListener("scroll",h)),e.addEventListener("scroll",m)}()}(window,document);