artalk 2.4.2 → 2.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var __defProp=Object.defineProperty,__defProps=Object.defineProperties,__getOwnPropDescs=Object.getOwnPropertyDescriptors,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=(t,e,i)=>e in t?__defProp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,__spreadValues=(t,e)=>{for(var i in e||(e={}))__hasOwnProp.call(e,i)&&__defNormalProp(t,i,e[i]);if(__getOwnPropSymbols)for(var i of __getOwnPropSymbols(e))__propIsEnum.call(e,i)&&__defNormalProp(t,i,e[i]);return t},__spreadProps=(t,e)=>__defProps(t,__getOwnPropDescs(e)),__publicField=(t,e,i)=>(__defNormalProp(t,"symbol"!=typeof e?e+"":e,i),i),__async=(t,e,i)=>new Promise(((n,s)=>{var a=t=>{try{o(i.next(t))}catch(e){s(e)}},r=t=>{try{o(i.throw(t))}catch(e){s(e)}},o=t=>t.done?n(t.value):Promise.resolve(t.value).then(a,r);o((i=i.apply(t,e)).next())})),Artalk=function(t){"use strict";const e={placeholder:"Leave a comment",noComment:"No Comment",send:"Send",save:"Save",nick:"Nickname",email:"Email",link:"Website",emoticon:"Emoji",preview:"Preview",image:"Image",uploadFail:"Upload Failed",commentFail:"Failed to comment",restoredMsg:"Content has been restored",onlyAdminCanReply:"Only admin can reply",uploadLoginMsg:"Please fill in your name and email to upload",counter:"{count} Comments",sortLatest:"Latest",sortOldest:"Oldest",sortBest:"Best",sortAuthor:"Author",openComment:"Open Comment",closeComment:"Close Comment",listLoadFailMsg:"Failed to load comments",listRetry:"Click to retry",loadMore:"Load More",admin:"Admin",reply:"Reply",voteUp:"Up",voteDown:"Down",voteFail:"Vote Failed",readMore:"Read More",actionConfirm:"Confirm",collapse:"Collapse",collapsed:"Collapsed",collapsedMsg:"This comment has been collapsed",expand:"Expand",approved:"Approved",pending:"Pending",pendingMsg:"Pending, visible only to commenter.",edit:"Edit",editCancel:"Cancel Edit",delete:"Delete",deleteConfirm:"Confirm",pin:"Pin",unpin:"Unpin",seconds:"seconds ago",minutes:"minutes ago",hours:"hours ago",days:"days ago",now:"just now",adminCheck:"Enter admin password:",captchaCheck:"Enter the CAPTCHA to continue:",confirm:"Confirm",cancel:"Cancel",msgCenter:"Messages",ctrlCenter:"Admin",frontend:"Frontend",backend:"Backend",loading:"Loading",loadFail:"Load Failed",editing:"Editing",editFail:"Edit Failed",deleting:"Deleting",deleteFail:"Delete Failed",reqGot:"Request got",reqAborted:"Request timed out or terminated unexpectedly"},i={en:e,"en-US":e,"zh-CN":{placeholder:"键入内容...",noComment:"「此时无声胜有声」",send:"发送评论",save:"保存评论",nick:"昵称",email:"邮箱",link:"网址",emoticon:"表情",preview:"预览",image:"图片",uploadFail:"上传失败",commentFail:"评论失败",restoredMsg:"内容已自动恢复",onlyAdminCanReply:"仅管理员可评论",uploadLoginMsg:"填入你的名字邮箱才能上传哦",counter:"{count} 条评论",sortLatest:"最新",sortOldest:"最早",sortBest:"最热",sortAuthor:"作者",openComment:"打开评论",closeComment:"关闭评论",listLoadFailMsg:"无法获取评论列表数据",listRetry:"点击重新获取",loadMore:"加载更多",admin:"管理员",reply:"回复",voteUp:"赞同",voteDown:"反对",voteFail:"投票失败",readMore:"阅读更多",actionConfirm:"确认操作",collapse:"折叠",collapsed:"已折叠",collapsedMsg:"该评论已被系统或管理员折叠",expand:"展开",approved:"已审",pending:"待审",pendingMsg:"审核中,仅本人可见。",edit:"编辑",editCancel:"取消编辑",delete:"删除",deleteConfirm:"确认删除",pin:"置顶",unpin:"取消置顶",seconds:"秒前",minutes:"分钟前",hours:"小时前",days:"天前",now:"刚刚",adminCheck:"键入密码来验证管理员身份:",captchaCheck:"键入验证码继续:",confirm:"确认",cancel:"取消",msgCenter:"通知中心",ctrlCenter:"控制中心",frontend:"前端",backend:"后端",loading:"加载中",loadFail:"加载失败",editing:"修改中",editFail:"修改失败",deleting:"删除中",deleteFail:"删除失败",reqGot:"请求响应",reqAborted:"请求超时或意外终止"}};function n(t,e,n={}){var s;"string"==typeof t&&(s=(s=t).replace(/^([a-zA-Z]+)(-[a-zA-Z]+)?$/,((t,e,i)=>e.toLowerCase()+(i||"").toUpperCase())),t=i[s]?i[s]:window.ArtalkI18n&&window.ArtalkI18n[s]?window.ArtalkI18n[s]:i.en);let a=(null==t?void 0:t[e])||e;return a=a.replace(/\{\s*(\w+?)\s*\}/g,((t,e)=>n[e]||"")),a}class s{constructor(t){__publicField(this,"ctx"),__publicField(this,"data"),this.ctx=t;const e=JSON.parse(window.localStorage.getItem("ArtalkUser")||"{}");this.data={nick:e.nick||"",email:e.email||"",link:e.link||"",token:e.token||"",isAdmin:e.isAdmin||!1}}update(t={}){Object.entries(t).forEach((([t,e])=>{this.data[t]=e})),window.localStorage.setItem("ArtalkUser",JSON.stringify(this.data)),this.ctx.trigger("user-changed",this.ctx.user.data)}logout(){this.update({token:"",isAdmin:!1})}checkHasBasicUserInfo(){return!!this.data.nick&&!!this.data.email}}class a{constructor(t){__publicField(this,"$el"),__publicField(this,"ctx"),__publicField(this,"conf"),this.ctx=t,this.conf=t.conf}$t(t,e={}){return this.ctx.$t(t,e)}}var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},o={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},l={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},c=/(&amp;|&lt;|&gt;|&quot;|&#39;)/g,d=/[&<>"']/g;function h(t){return o[t]}function u(t){return l[t]}function p(t){return null==t?"":String(t).replace(d,h)}function m(t){return null==t?"":String(t).replace(c,u)}p.options=m.options={};var g={encode:p,escape:p,decode:m,unescape:m,version:"1.0.0-browser"};var f=function t(e){for(var i,n,s=Array.prototype.slice.call(arguments,1);s.length;)for(n in i=s.shift())i.hasOwnProperty(n)&&("[object Object]"===Object.prototype.toString.call(e[n])?e[n]=t(e[n],i[n]):e[n]=i[n]);return e},y=function(t){return"string"==typeof t?t.toLowerCase():t};function $(t,e){return t[e]=!0,t}var _=function(t){return t.reduce($,{})},v={uris:_(["background","base","cite","href","longdesc","src","usemap"])},k={voids:_(["area","br","col","hr","img","wbr","input","base","basefont","link","meta"])},b=g,x=y,w=k,C=/^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/,S=/^<\s*\/\s*([\w:-]+)[^>]*>/,L=/([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,T=/^</,E=/^<\s*\//;var A=g,F=y,B=v,O=k;var M=f,P=function(t,e){for(var i,n=function(){var t=[];return t.lastItem=function(){return t[t.length-1]},t}(),s=t;t;)a();function a(){i=!0,function(){"\x3c!--"===t.substr(0,4)?(n=t.indexOf("--\x3e"))>=0&&(e.comment&&e.comment(t.substring(4,n)),t=t.substring(n+3),i=!1):E.test(t)?r(S,l):T.test(t)&&r(C,o);var n;!function(){if(!i)return;var n,s=t.indexOf("<");s>=0?(n=t.substring(0,s),t=t.substring(s)):(n=t,t="");e.chars&&e.chars(n)}()}();var n=t===s;s=t,n&&(t="")}function r(e,n){var s=t.match(e);s&&(t=t.substring(s[0].length),s[0].replace(e,n),i=!1)}function o(t,i,s,a){var r={},o=x(i),l=w.voids[o]||!!a;s.replace(L,(function(t,e,i,n,s){r[e]=void 0===i&&void 0===n&&void 0===s?void 0:b.decode(i||n||s||"")})),l||n.push(o),e.start&&e.start(o,r,l)}function l(t,i){var s,a=0,r=x(i);if(r)for(a=n.length-1;a>=0&&n[a]!==r;a--);if(a>=0){for(s=n.length-1;s>=a;s--)e.end&&e.end(n[s]);n.length=a}}l()},R=function(t,e){var i,n=e||{};return o(),{start:function(t,e,r){var o=F(t);if(i.ignoring)return void a(o);if(-1===(n.allowedTags||[]).indexOf(o))return void a(o);if(n.filter&&!n.filter({tag:o,attrs:e}))return void a(o);s("<"),s(o),Object.keys(e).forEach((function(t){var i=e[t],a=(n.allowedClasses||{})[o]||[],r=(n.allowedAttributes||{})[o]||[],l=F(t);("class"===l&&-1===r.indexOf(l)?(i=i.split(" ").filter((function(t){return a&&-1!==a.indexOf(t)})).join(" ").trim()).length:-1!==r.indexOf(l)&&(!0!==B.uris[l]||function(t){var e=t[0];if("#"===e||"/"===e)return!0;var i=t.indexOf(":");if(-1===i)return!0;var s=t.indexOf("?");if(-1!==s&&i>s)return!0;var a=t.indexOf("#");return-1!==a&&i>a||n.allowedSchemes.some(r);function r(e){return 0===t.indexOf(e+":")}}(i)))&&(s(" "),s(t),"string"==typeof i&&(s('="'),s(A.encode(i)),s('"')))})),s(r?"/>":">")},end:function(t){var e=F(t);-1!==(n.allowedTags||[]).indexOf(e)&&!1===i.ignoring?(s("</"),s(e),s(">")):r(e)},chars:function(t){!1===i.ignoring&&s(n.transformText?n.transformText(t):t)}};function s(e){t.push(e)}function a(t){O.voids[t]||(!1===i.ignoring?i={ignoring:t,depth:1}:i.ignoring===t&&i.depth++)}function r(t){i.ignoring===t&&--i.depth<=0&&o()}function o(){i={ignoring:!1,depth:0}}},D={allowedAttributes:{a:["href","name","target","title","aria-label"],iframe:["allowfullscreen","frameborder","src"],img:["src","alt","title","aria-label"]},allowedClasses:{},allowedSchemes:["http","https","mailto"],allowedTags:["a","abbr","article","b","blockquote","br","caption","code","del","details","div","em","h1","h2","h3","h4","h5","h6","hr","i","img","ins","kbd","li","main","mark","ol","p","pre","section","span","strike","strong","sub","summary","sup","table","tbody","td","th","thead","tr","u","ul"],filter:null};function I(t,e,i){var n=[],s=!0===i?e:M({},D,e),a=R(n,s);return P(t,a),n.join("")}I.defaults=D;var q=I,W={exports:{}};W.exports=function(){function t(t,e){return t(e={exports:{}},e.exports),e.exports}var e=t((function(t){var e=t.exports=function(){return new RegExp("(?:"+e.line().source+")|(?:"+e.block().source+")","gm")};e.line=function(){return/(?:^|\s)\/\/(.+?)$/gm},e.block=function(){return/\/\*([\S\s]*?)\*\//gm}})),i=["23AC69","91C132","F19726","E8552D","1AAB8E","E1147F","2980C1","1BA1E6","9FA0A0","F19726","E30B20","E30B20","A3338B"];function n(t){return'<span style="color: slategray">'+t+"</span>"}return function(t,s){void 0===s&&(s={});var a=s.colors;void 0===a&&(a=i);var r=0,o={},l=new RegExp("("+/[\u4E00-\u9FFF\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\uac00-\ud7af\u0400-\u04FF]+|\w+/.source+"|"+/</.source+")|("+e().source+")","gmi");return t.replace(l,(function(t,e,i){if(i)return n(i);if("<"===e)return"&lt;";var s;o[e]?s=o[e]:(s=a[r],o[e]=s);var l='<span style="color: #'+s+'">'+e+"</span>";return r=++r%a.length,l}))}}();const N=W.exports;function U(t=""){const e=document.createElement("div");return e.innerHTML=t.trim(),e.firstElementChild||e}function H(t){return parseFloat(getComputedStyle(t,null).height.replace("px",""))}function j(t){const e=RegExp(`[?&]${t}=([^&]*)`).exec(window.location.search);return e&&decodeURIComponent(e[1].replace(/\+/g," "))}function V(t){const e=t.getBoundingClientRect();return{top:e.top+window.scrollY,left:e.left+window.scrollX}}function z(t,e){let i=t.toString();for(;i.length<e;)i=`0${i}`;return i}function G(t,e){try{const i=t.getTime(),n=(new Date).getTime()-i,s=Math.floor(n/864e5);if(0===s){const t=n%864e5,i=Math.floor(t/36e5);if(0===i){const i=t%36e5,n=Math.floor(i/6e4);if(0===n){const t=i%6e4;return`${Math.round(t/1e3)} ${e.$t("seconds")}`}return`${n} ${e.$t("minutes")}`}return`${i} ${e.$t("hours")}`}return s<0?e.$t("now"):s<8?`${s} ${e.$t("days")}`:function(t){const e=z(t.getDate(),2),i=z(t.getMonth()+1,2);return`${z(t.getFullYear(),2)}-${i}-${e}`}(t)}catch(i){return console.error(i)," - "}}function Q(t,e){if(!t)return;const i=t.getElementsByTagName("img");if(!i.length)return;let n=i.length;for(let s=0;s<i.length;s++)i[s].complete?n--:i[s].addEventListener("load",(()=>{n--,0===n&&e()})),0===n&&e()}function K(t,e){var i;let n=null==(i=t.markedInstance)?void 0:i.parse(e);n||(n=e.replace(/```\s*([^]+?.*?[^]+?[^]+?)```/g,((t,e)=>`<pre><code>${N(e)}</code></pre>`)).replace(/!\[(.*?)\]\((.*?)\)/g,((t,e,i)=>`<img src="${i}" alt="${e}" />`)).replace(/\[(.*?)\]\((.*?)\)/g,((t,e,i)=>`<a href="${i}" target="_blank">${e}</a>`)).replace(/\n/g,"<br>"));let s=q(n,{allowedClasses:{},allowedSchemes:["http","https","mailto"],allowedTags:["a","abbr","article","b","blockquote","br","caption","code","del","details","div","em","h1","h2","h3","h4","h5","h6","hr","i","img","ins","kbd","li","main","mark","ol","p","pre","section","span","strike","strong","sub","summary","sup","table","tbody","td","th","thead","tr","u","ul"],allowedAttributes:{"*":["title","accesskey"],a:["href","name","target","aria-label","rel"],img:["src","alt","title","atk-emoticon","aria-label"],code:["class"],span:["class","style"]},filter:t=>([["code",/^hljs\W+language-(.*)$/],["span",/^(hljs-.*)$/]].forEach((([e,i])=>{t.tag===e&&t.attrs.class&&!i.test(t.attrs.class)&&delete t.attrs.class})),"span"===t.tag&&t.attrs.style&&!/^color:(\W+)?#[0-9a-f]{3,6};?$/i.test(t.attrs.style)&&delete t.attrs.style,!0)});return t.markedReplacers.forEach((t=>{"function"==typeof t&&(s=t(s))})),s}function Y(){return __async(this,null,(function*(){const t=navigator.userAgent;if(!navigator.userAgentData||!navigator.userAgentData.getHighEntropyValues)return t;const e=navigator.userAgentData;let i=null;try{i=yield e.getHighEntropyValues(["platformVersion"])}catch(s){return console.error(s),t}const n=Number(i.platformVersion.split(".")[0]);return"Windows"===e.platform&&n>=13?t.replace(/Windows NT 10.0/,"Windows NT 11.0"):"macOS"===e.platform&&n>=11?t.replace(/(Mac OS X \d+_\d+_\d+|Mac OS X)/,`Mac OS X ${i.platformVersion.replace(/\./g,"_")}`):t}))}function X(t){let e;try{e=new URL(t)}catch(i){return!1}return"http:"===e.protocol||"https:"===e.protocol}function J(t,e){return function(t,e){return`${t.replace(/\/$/,"")}/${e.replace(/^\//,"")}`}(t.conf.server,e)}function Z(t,e){const i=t=>t&&"object"==typeof t;return i(t)&&i(e)?(Object.keys(e).forEach((n=>{const s=t[n],a=e[n];Array.isArray(s)&&Array.isArray(a)?t[n]=s.concat(a):i(s)&&i(a)?t[n]=Z(__spreadValues({},s),a):t[n]=a})),t):e}function tt(t,e){let i=t.querySelector(":scope > .atk-loading");i||(i=U('<div class="atk-loading atk-fade-in" style="display: none;">\n <div class="atk-loading-spinner">\n <svg viewBox="25 25 50 50"><circle cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10"></circle></svg>\n </div>\n </div>'),(null==e?void 0:e.transparentBg)&&(i.style.background="transparent"),t.appendChild(i)),i.style.display="";const n=i.querySelector(".atk-loading-spinner");n&&(n.style.display="none",window.setTimeout((()=>{n.style.display=""}),500))}function et(t){const e=t.querySelector(":scope > .atk-loading");e&&(e.style.display="none")}function it(t,e=!0){const i=V(t).top+H(t)/2-document.documentElement.clientHeight/2;e?window.scroll({top:i>0?i:0,left:0}):window.scroll(0,i>0?i:0)}function nt(t,e,i){const n=U(`<div class="atk-notify atk-fade-in" style="background-color: ${{s:"#57d59f",e:"#ff6f6c",w:"#ffc721",i:"#2ebcfc"}[i]}"><span class="atk-notify-content"></span></div>`);n.querySelector(".atk-notify-content").innerHTML=function(t){const e=document.createElement("div");return e.innerText=t,e.innerHTML}(e).replace("\n","<br/>"),t.appendChild(n);const s=()=>{n.classList.add("atk-fade-out"),setTimeout((()=>{n.remove()}),200)};let a;a=window.setTimeout((()=>{s()}),3e3),n.addEventListener("click",(()=>{s(),window.clearTimeout(a)}))}function st(t,e){!function(t,e,i="in"){t.classList.add(`atk-fade-${i}`);const n=()=>{t.classList.remove(`atk-fade-${i}`),t.removeEventListener("animationend",n),e&&e()};t.addEventListener("animationend",n)}(t,e,"in")}function at(t,e,i='<span class="atk-error-title">Artalk Error</span>'){let n=t.querySelector(".atk-error-layer");if(null===e)return void(null!==n&&n.remove());n||(n=U(`<div class="atk-error-layer">${i}<span class="atk-error-text"></span></div>`),t.appendChild(n));const s=n.querySelector(".atk-error-text");s.innerHTML="",null!==e&&(e instanceof HTMLElement?s.appendChild(e):s.innerText=e)}const rt=class extends a{constructor(t,e,i){super(t),__publicField(this,"name"),__publicField(this,"$wrap"),__publicField(this,"$mask"),__publicField(this,"maskClickHideEnable",!0),__publicField(this,"afterHide"),this.name=e;const{$wrap:n,$mask:s}=lt(t);this.$wrap=n,this.$mask=s,this.$el=this.$wrap.querySelector(`[data-layer-name="${e}"].atk-layer-item`),null===this.$el&&(i?this.$el=i:(this.$el=U(),this.$el.classList.add("atk-layer-item"))),this.$el.setAttribute("data-layer-name",e),this.$el.style.display="none",this.$wrap.append(this.$el)}getName(){return this.name}getWrapEl(){return this.$wrap}getEl(){return this.$el}show(){this.fireAllActionTimer(),this.$wrap.style.display="block",this.$mask.style.display="block",this.$mask.classList.add("atk-fade-in"),this.$el.style.display="",this.$mask.onclick=()=>{this.maskClickHideEnable&&this.hide()},this.pageBodyScrollBarHide()}hide(){this.afterHide&&this.afterHide(),this.$wrap.classList.add("atk-fade-out"),this.$el.style.display="none",this.pageBodyScrollBarShow(),this.newActionTimer((()=>{this.$wrap.style.display="none",this.checkCleanLayer()}),450),this.newActionTimer((()=>{this.$wrap.style.display="none",this.$wrap.classList.remove("atk-fade-out")}),200)}setMaskClickHide(t){this.maskClickHideEnable=t}pageBodyScrollBarHide(){document.body.style.overflow="hidden";const t=parseInt(window.getComputedStyle(document.body,null).getPropertyValue("padding-right"),10);document.body.style.paddingRight=`${function(){const t=document.createElement("p");t.style.width="100%",t.style.height="200px";const e=document.createElement("div");e.style.position="absolute",e.style.top="0px",e.style.left="0px",e.style.visibility="hidden",e.style.width="200px",e.style.height="150px",e.style.overflow="hidden",e.appendChild(t),document.body.appendChild(e);const i=t.offsetWidth;e.style.overflow="scroll";let n=t.offsetWidth;return i===n&&(n=e.clientWidth),document.body.removeChild(e),i-n}()+t||0}px`}pageBodyScrollBarShow(){document.body.style.overflow=rt.BodyOrgOverflow,document.body.style.paddingRight=rt.BodyOrgPaddingRight}newActionTimer(t,e){const i=()=>{t(),rt.actionTimers=rt.actionTimers.filter((t=>t.act!==i))},n=window.setTimeout((()=>i()),e);rt.actionTimers.push({act:i,tid:n})}fireAllActionTimer(){rt.actionTimers.forEach((t=>{clearTimeout(t.tid),t.act()}))}disposeNow(){this.$el.remove(),this.pageBodyScrollBarShow(),this.checkCleanLayer()}dispose(){this.hide(),this.$el.remove(),this.checkCleanLayer()}checkCleanLayer(){0===this.getWrapEl().querySelectorAll(".atk-layer-item").length&&(this.$wrap.style.display="none")}};let ot=rt;function lt(t){let e=document.querySelector(`.atk-layer-wrap#ctx-${t.cid}`);e||(e=U(`<div class="atk-layer-wrap" id="ctx-${t.cid}" style="display: none;"><div class="atk-layer-mask"></div></div>`),document.body.appendChild(e));const i=e.querySelector(".atk-layer-mask");return{$wrap:e,$mask:i}}function ct(t,e,i,n){return __async(this,null,(function*(){var s,a;if(t.user.data.token){const e=new Headers(i.headers);e.set("Authorization",`Bearer ${t.user.data.token}`),i.headers=e}const r=yield function(t,e,i,n){var s;const a=new AbortController;null==(s=n.signal)||s.addEventListener("abort",(()=>a.abort()));let r=fetch(e,__spreadProps(__spreadValues({},n),{signal:a.signal}));if(i>0){const t=setTimeout((()=>a.abort()),i);r.finally((()=>{clearTimeout(t)}))}return r=r.catch((e=>{throw"AbortError"===(e||{}).name?new Error(t.$t("reqAborted")):e})),r}(t,e,n||t.conf.reqTimeout||15e3,i),o=r.status,l=[401,400].includes(o);if(!r.ok&&!l)throw new Error(`${t.$t("reqGot")} ${o}`);let c=yield r.json();const d=(n,s)=>{ct(t,e,i).then((t=>{n(t)})).catch((t=>{s(t)}))};if((null==(s=c.data)?void 0:s.need_captcha)?c=yield new Promise(((e,i)=>{t.checkCaptcha({imgData:c.data.img_data,iframe:c.data.iframe,onSuccess:()=>{d(e,i)},onCancel:()=>{i(c)}})})):((null==(a=c.data)?void 0:a.need_login)||l)&&(c=yield new Promise(((e,i)=>{t.checkAdmin({onSuccess:()=>{d(e,i)},onCancel:()=>{i(c)}})}))),!c.success)throw c;return c}))}function dt(t){const e=new FormData;return Object.keys(t).forEach((i=>e.append(i,String(t[i])))),e}__publicField(ot,"BodyOrgOverflow"),__publicField(ot,"BodyOrgPaddingRight"),__publicField(ot,"actionTimers",[]),function(){function t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function e(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,n.key,n)}}function i(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}function n(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&a(t,e)}function s(t){return(s=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function a(t,e){return(a=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function o(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function l(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function c(t,e){return!e||"object"!=typeof e&&"function"!=typeof e?l(t):e}function d(t){var e=o();return function(){var i,n=s(t);if(e){var a=s(this).constructor;i=Reflect.construct(n,arguments,a)}else i=n.apply(this,arguments);return c(this,i)}}function h(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=s(t)););return t}function u(t,e,i){return(u="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,i){var n=h(t,e);if(n){var s=Object.getOwnPropertyDescriptor(n,e);return s.get?s.get.call(i):s.value}})(t,e,i||t)}var p=function(){function e(){t(this,e),Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}return i(e,[{key:"addEventListener",value:function(t,e,i){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:e,options:i})}},{key:"removeEventListener",value:function(t,e){if(t in this.listeners)for(var i=this.listeners[t],n=0,s=i.length;n<s;n++)if(i[n].callback===e)return void i.splice(n,1)}},{key:"dispatchEvent",value:function(t){if(t.type in this.listeners){for(var e=this.listeners[t.type].slice(),i=0,n=e.length;i<n;i++){var s=e[i];try{s.callback.call(this,t)}catch(a){Promise.resolve().then((function(){throw a}))}s.options&&s.options.once&&this.removeEventListener(t.type,s.callback)}return!t.defaultPrevented}}}]),e}(),m=function(e){n(r,e);var a=d(r);function r(){var e;return t(this,r),(e=a.call(this)).listeners||p.call(l(e)),Object.defineProperty(l(e),"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(l(e),"onabort",{value:null,writable:!0,configurable:!0}),e}return i(r,[{key:"toString",value:function(){return"[object AbortSignal]"}},{key:"dispatchEvent",value:function(t){"abort"===t.type&&(this.aborted=!0,"function"==typeof this.onabort&&this.onabort.call(this,t)),u(s(r.prototype),"dispatchEvent",this).call(this,t)}}]),r}(p),g=function(){function e(){t(this,e),Object.defineProperty(this,"signal",{value:new m,writable:!0,configurable:!0})}return i(e,[{key:"abort",value:function(){var t;try{t=new Event("abort")}catch(e){"undefined"!=typeof document?document.createEvent?(t=document.createEvent("Event")).initEvent("abort",!1,!1):(t=document.createEventObject()).type="abort":t={type:"abort",bubbles:!1,cancelable:!1}}this.signal.dispatchEvent(t)}},{key:"toString",value:function(){return"[object AbortController]"}}]),e}();function f(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):"function"==typeof t.Request&&!t.Request.prototype.hasOwnProperty("signal")||!t.AbortController}function y(t){"function"==typeof t&&(t={fetch:t});var e=t,i=e.fetch,n=e.Request,s=void 0===n?i.Request:n,a=e.AbortController,r=e.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,o=void 0!==r&&r;if(!f({fetch:i,Request:s,AbortController:a,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o}))return{fetch:i,Request:l};var l=s;(l&&!l.prototype.hasOwnProperty("signal")||o)&&((l=function(t,e){var i;e&&e.signal&&(i=e.signal,delete e.signal);var n=new s(t,e);return i&&Object.defineProperty(n,"signal",{writable:!1,enumerable:!1,configurable:!0,value:i}),n}).prototype=s.prototype);var c=i;return{fetch:function(t,e){var i=l&&l.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(i){var n;try{n=new DOMException("Aborted","AbortError")}catch(a){(n=new Error("Aborted")).name="AbortError"}if(i.aborted)return Promise.reject(n);var s=new Promise((function(t,e){i.addEventListener("abort",(function(){return e(n)}),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([s,c(t,e)])}return c(t,e)},Request:l}}"undefined"!=typeof Symbol&&Symbol.toStringTag&&(g.prototype[Symbol.toStringTag]="AbortController",m.prototype[Symbol.toStringTag]="AbortSignal"),function(t){if(f(t))if(t.fetch){var e=y(t),i=e.fetch,n=e.Request;t.fetch=i,t.Request=n,Object.defineProperty(t,"AbortController",{writable:!0,enumerable:!1,configurable:!0,value:g}),Object.defineProperty(t,"AbortSignal",{writable:!0,enumerable:!1,configurable:!0,value:m})}else console.warn("fetch() is not available, cannot install abortcontroller-polyfill")}("undefined"!=typeof self?self:r)}();class ht{constructor(t,e){__publicField(this,"api"),__publicField(this,"ctx"),this.api=t,this.ctx=e}POST(t,e){return __async(this,null,(function*(){return function(t,e,i){return __async(this,null,(function*(){const n={method:"POST"};return i=__spreadValues({site_name:t.conf.site||""},i||{}),n.body=dt(i),(yield ct(t,e,n)).data||{}}))}(this.ctx,this.api.baseURL+t,e)}))}Fetch(t,e,i){return __async(this,null,(function*(){return ct(this.ctx,this.api.baseURL+t,e,i)}))}}const ut={comment:class extends ht{get(t,e,i,n){const s={page_key:this.ctx.conf.pageKey,site_name:this.ctx.conf.site||"",limit:e,offset:t};return i&&(s.flat_mode=i),this.ctx.user.checkHasBasicUserInfo()&&(s.name=this.ctx.user.data.nick,s.email=this.ctx.user.data.email),n&&n(s),this.POST("/get",s)}add(t){return __async(this,null,(function*(){const e={name:t.nick,email:t.email,link:t.link,content:t.content,rid:t.rid,page_key:t.page_key,ua:yield Y()};t.page_title&&(e.page_title=t.page_title),t.site_name&&(e.site_name=t.site_name);return(yield this.POST("/add",e)).comment}))}commentEdit(t){return __async(this,null,(function*(){const e=__spreadValues({},t);return(yield this.POST("/admin/comment-edit",e)).comment}))}commentDel(t,e){const i={id:String(t),site_name:e||""};return this.POST("/admin/comment-del",i)}vote(t,e){return __async(this,null,(function*(){const i={site_name:this.ctx.conf.site||"",target_id:t,type:e};this.ctx.user.checkHasBasicUserInfo()&&(i.name=this.ctx.user.data.nick,i.email=this.ctx.user.data.email);return yield this.POST("/vote",i)}))}},page:class extends ht{pageGet(t,e,i){return __async(this,null,(function*(){const n={site_name:t||"",offset:e||0,limit:i||15};return yield this.POST("/admin/page-get",n)}))}pageEdit(t){return __async(this,null,(function*(){const e={id:t.id,key:t.key,title:t.title,admin_only:t.admin_only,site_name:t.site_name||this.ctx.conf.site};return(yield this.POST("/admin/page-edit",e)).page}))}pageDel(t,e){const i={key:String(t),site_name:e||""};return this.POST("/admin/page-del",i)}pageFetch(t,e,i){return __async(this,null,(function*(){const n={};t&&(n.id=t),e&&(n.site_name=e),i&&(n.get_status=i);return yield this.POST("/admin/page-fetch",n)}))}pv(){return __async(this,null,(function*(){const t={site_name:this.ctx.conf.site||"",page_key:this.ctx.conf.pageKey||"",page_title:this.ctx.conf.pageTitle||""};return(yield this.POST("/pv",t)).pv}))}stat(t,e,i){return __async(this,null,(function*(){const n={type:t,site_name:this.ctx.conf.site||""};e&&(n.page_keys=Array.isArray(e)?e.join(","):e),i&&(n.limit=i);return yield this.POST("/stat",n)}))}},site:class extends ht{siteGet(){return __async(this,null,(function*(){return(yield this.POST("/admin/site-get",{})).sites}))}siteAdd(t,e){return __async(this,null,(function*(){const i={name:t,urls:e,site_name:""};return(yield this.POST("/admin/site-add",i)).site}))}siteEdit(t){return __async(this,null,(function*(){const e={id:t.id,name:t.name||"",urls:t.urls||""};return(yield this.POST("/admin/site-edit",e)).site}))}siteDel(t,e=!1){const i={id:t,del_content:e};return this.POST("/admin/site-del",i)}export(){return __async(this,null,(function*(){var t;return(null==(t=(yield this.Fetch("/admin/export",{method:"POST"},0)).data)?void 0:t.data)||""}))}},user:class extends ht{login(t,e,i){return __async(this,null,(function*(){const n={name:t,email:e,password:i};this.ctx.conf.site&&(n.site_name=this.ctx.conf.site);return(yield this.POST("/login",n)).token}))}userGet(t,e){const i=new AbortController,n={name:t,email:e,site_name:this.ctx.conf.site||""};return{req:this.Fetch("/user-get",{method:"POST",body:dt(n),signal:i.signal}).then((t=>({user:t.data.user,is_login:t.data.is_login,unread:t.data.unread||[],unread_count:t.data.unread_count||0}))),abort:()=>{i.abort()}}}loginStatus(){return __async(this,null,(function*(){return(yield this.POST("/login-status",{name:this.ctx.user.data.nick,email:this.ctx.user.data.email}))||{is_login:!1,is_admin:!1}}))}logout(){return __async(this,null,(function*(){return this.POST("/logout")}))}markRead(t,e=!1){const i={site_name:this.ctx.conf.site||"",notify_key:t};return e&&(delete i.notify_key,i.read_all=!0,i.name=this.ctx.user.data.nick,i.email=this.ctx.user.data.email),this.POST("/mark-read",i)}},system:class extends ht{conf(){return __async(this,null,(function*(){const t=(yield this.POST("/conf")).frontend_conf||{};return t.emoticons&&"string"==typeof t.emoticons&&(t.emoticons=t.emoticons.trim(),t.emoticons.startsWith("[")||t.emoticons.startsWith("{")?t.emoticons=JSON.parse(t.emoticons):"false"===t.emoticons&&(t.emoticons=!1)),t}))}getSettings(){return __async(this,null,(function*(){return yield this.POST("/admin/setting-get")}))}saveSettings(t){return __async(this,null,(function*(){return yield this.POST("/admin/setting-save",{data:t})}))}},captcha:class extends ht{captchaGet(){return __async(this,null,(function*(){return(yield this.POST("/captcha/refresh")).img_data||""}))}captchaCheck(t){return __async(this,null,(function*(){return(yield this.POST("/captcha/check",{value:t})).img_data||""}))}captchaStatus(){return __async(this,null,(function*(){return(yield this.POST("/captcha/status"))||{is_pass:!1}}))}},admin:class extends ht{cacheFlushAll(){return this.POST("/admin/cache-flush",{flush_all:!0})}cacheWarmUp(){return this.POST("/admin/cache-warm",{})}},upload:class extends ht{imgUpload(t){return __async(this,null,(function*(){const e={name:this.ctx.user.data.nick,email:this.ctx.user.data.email,page_key:this.ctx.conf.pageKey};this.ctx.conf.site&&(e.site_name=this.ctx.conf.site);const i=dt(e);i.set("file",t);const n={method:"POST",body:i};return(yield this.Fetch("/img-upload",n)).data||{}}))}}};class pt{constructor(t){__publicField(this,"ctx"),__publicField(this,"baseURL"),this.ctx=t,this.baseURL=`${t.conf.server}/api`,Object.entries(ut).forEach((([t,e])=>{this[t]=new e(this,this.ctx)}))}}const mt="2.4.2",gt=window||{},ft=navigator||{};class yt{constructor(t,e){__publicField(this,"ctx"),__publicField(this,"conf"),__publicField(this,"$el"),__publicField(this,"isLoading",!1),__publicField(this,"msgRecTimer"),__publicField(this,"msgRecTimerFunc"),__publicField(this,"isConfirming",!1),__publicField(this,"confirmRecTimer"),this.ctx=t,this.$el=U('<span class="atk-common-action-btn"></span>'),this.conf="object"!=typeof e?{text:e}:e,this.$el.innerText=this.getText(),this.conf.adminOnly&&this.$el.setAttribute("atk-only-admin-show","")}get isMessaging(){return!!this.msgRecTimer}appendTo(t){return t.append(this.$el),this}getText(){return"string"==typeof this.conf.text?this.conf.text:this.conf.text()}setClick(t){this.$el.onclick=e=>{if(e.stopPropagation(),!this.isLoading){if(this.conf.confirm&&!this.isMessaging){const t=()=>{this.isConfirming=!1,this.$el.classList.remove("atk-btn-confirm"),this.$el.innerText=this.getText()};if(!this.isConfirming)return this.isConfirming=!0,this.$el.classList.add("atk-btn-confirm"),this.$el.innerText=this.conf.confirmText||this.ctx.$t("actionConfirm"),void(this.confirmRecTimer=window.setTimeout((()=>t()),5e3));this.confirmRecTimer&&window.clearTimeout(this.confirmRecTimer),t()}if(this.msgRecTimer)return this.fireMsgRecTimer(),void this.clearMsgRecTimer();t()}}}updateText(t){t&&(this.conf.text=t),this.setLoading(!1),this.$el.innerText=this.getText()}setLoading(t,e){this.isLoading!==t&&(this.isLoading=t,t?(this.$el.classList.add("atk-btn-loading"),this.$el.innerText=e||`${this.ctx.$t("loading")}...`):(this.$el.classList.remove("atk-btn-loading"),this.$el.innerText=this.getText()))}setError(t){this.setMsg(t,"atk-btn-error")}setWarn(t){this.setMsg(t,"atk-btn-warn")}setSuccess(t){this.setMsg(t,"atk-btn-success")}setMsg(t,e,i,n){this.setLoading(!1),e&&this.$el.classList.add(e),this.$el.innerText=t,this.setMsgRecTimer((()=>{this.$el.innerText=this.getText(),e&&this.$el.classList.remove(e),n&&n()}),i||2500)}setMsgRecTimer(t,e){this.fireMsgRecTimer(),this.clearMsgRecTimer(),this.msgRecTimerFunc=t,this.msgRecTimer=window.setTimeout((()=>{t(),this.clearMsgRecTimer()}),e)}fireMsgRecTimer(){this.msgRecTimerFunc&&this.msgRecTimerFunc()}clearMsgRecTimer(){this.msgRecTimer&&window.clearTimeout(this.msgRecTimer),this.msgRecTimer=void 0,this.msgRecTimerFunc=void 0}}class $t{constructor(t){__publicField(this,"comment"),__publicField(this,"$el"),__publicField(this,"$main"),__publicField(this,"$header"),__publicField(this,"$headerNick"),__publicField(this,"$headerBadgeWrap"),__publicField(this,"$body"),__publicField(this,"$content"),__publicField(this,"$childrenWrap"),__publicField(this,"$actions"),__publicField(this,"voteBtnUp"),__publicField(this,"voteBtnDown"),__publicField(this,"$replyTo"),__publicField(this,"$replyAt"),this.comment=t}get ctx(){return this.comment.ctx}get data(){return this.comment.getData()}get cConf(){return this.comment.getConf()}render(){return this.$el=U('<div class="atk-comment-wrap">\n <div class="atk-comment">\n <div class="atk-avatar"></div>\n <div class="atk-main">\n <div class="atk-header">\n <span class="atk-item atk-nick"></span>\n <span class="atk-badge-wrap"></span>\n <span class="atk-item atk-date"></span>\n </div>\n <div class="atk-body">\n <div class="atk-content"></div>\n </div>\n <div class="atk-footer">\n <div class="atk-actions"></div>\n </div>\n </div>\n </div>\n</div>\n'),this.$main=this.$el.querySelector(".atk-main"),this.$header=this.$el.querySelector(".atk-header"),this.$body=this.$el.querySelector(".atk-body"),this.$content=this.$body.querySelector(".atk-content"),this.$actions=this.$el.querySelector(".atk-actions"),this.$el.setAttribute("data-comment-id",`${this.data.id}`),this.renderAvatar(),this.renderHeader(),this.renderContent(),this.renderReplyAt(),this.renderReplyTo(),this.renderPending(),this.renderActions(),this.recoveryChildrenWrap(),this.$el}renderAvatar(){const t=this.$el.querySelector(".atk-avatar"),e=U("<img />");if(e.src=this.comment.getGravatarURL(),this.data.link){const i=U('<a target="_blank" rel="noreferrer noopener nofollow"></a>');i.href=X(this.data.link)?this.data.link:`https://${this.data.link}`,i.append(e),t.append(i)}else t.append(e)}renderHeader(){this.renderHeader_Nick(),this.renderHeader_VerifyBadge(),this.renderHeader_Date(),this.renderHeader_UABadge()}renderHeader_Nick(){if(this.$headerNick=this.$el.querySelector(".atk-nick"),this.data.link){const t=U('<a target="_blank" rel="noreferrer noopener nofollow"></a>');t.innerText=this.data.nick,t.href=X(this.data.link)?this.data.link:`https://${this.data.link}`,this.$headerNick.append(t)}else this.$headerNick.innerText=this.data.nick}renderHeader_VerifyBadge(){this.$headerBadgeWrap=this.$el.querySelector(".atk-badge-wrap"),this.$headerBadgeWrap.innerHTML="";const t=this.data.badge_name,e=this.data.badge_color;if(t){const i=U('<span class="atk-badge"></span>');i.innerText=t.replace("管理员",this.ctx.$t("admin")),i.style.backgroundColor=e||"",this.$headerBadgeWrap.append(i)}if(this.data.is_pinned){const t=U(`<span class="atk-pinned-badge">${this.ctx.$t("pin")}</span>`);this.$headerBadgeWrap.append(t)}}renderHeader_Date(){const t=this.$el.querySelector(".atk-date");t.innerText=this.comment.getDateFormatted(),t.setAttribute("data-atk-comment-date",String(+new Date(this.data.date)))}renderHeader_UABadge(){if(this.ctx.conf.uaBadge){let t=this.$header.querySelector("atk-ua-wrap");t||(t=U('<span class="atk-ua-wrap"></span>'),this.$header.append(t)),t.innerHTML="";const e=U('<span class="atk-ua ua-browser"></span>'),i=U('<span class="atk-ua ua-os"></span>'),n=this.comment.getUserUA();e.innerText=n.browser,i.innerText=n.os,t.append(e),t.append(i)}}renderContent(){if(!this.data.is_collapsed)return this.$content.innerHTML=this.comment.getContentMarked(),void this.$content.classList.remove("atk-hide","atk-collapsed");this.$content.classList.add("atk-hide","atk-type-collapsed");const t=U(`\n <div class="atk-collapsed">\n <span class="atk-text">${this.ctx.$t("collapsedMsg")}</span>\n <span class="atk-show-btn">${this.ctx.$t("expand")}</span>\n </div>`);this.$body.insertAdjacentElement("beforeend",t);const e=t.querySelector(".atk-show-btn");e.addEventListener("click",(t=>{t.stopPropagation(),this.$content.classList.contains("atk-hide")?(this.$content.innerHTML=this.comment.getContentMarked(),this.$content.classList.remove("atk-hide"),st(this.$content),e.innerHTML=this.ctx.$t("collapse")):(this.$content.innerHTML="",this.$content.classList.add("atk-hide"),e.innerHTML=this.ctx.$t("expand"))}))}renderReplyAt(){this.cConf.isFlatMode||0===this.data.rid||this.cConf.replyTo&&(this.$replyAt=U('<span class="atk-item atk-reply-at"><span class="atk-arrow"></span><span class="atk-nick"></span></span>'),this.$replyAt.querySelector(".atk-nick").innerText=`${this.cConf.replyTo.nick}`,this.$replyAt.onclick=()=>{this.comment.getActions().goToReplyComment()},this.$headerBadgeWrap.insertAdjacentElement("afterend",this.$replyAt))}renderReplyTo(){if(!this.cConf.isFlatMode)return;if(!this.cConf.replyTo)return;this.$replyTo=U(`\n <div class="atk-reply-to">\n <div class="atk-meta">${this.ctx.$t("reply")} <span class="atk-nick"></span>:</div>\n <div class="atk-content"></div>\n </div>`);const t=this.$replyTo.querySelector(".atk-nick");t.innerText=`@${this.cConf.replyTo.nick}`,t.onclick=()=>{this.comment.getActions().goToReplyComment()};let e=K(this.ctx,this.cConf.replyTo.content);this.cConf.replyTo.is_collapsed&&(e=`[${this.ctx.$t("collapsed")}]`),this.$replyTo.querySelector(".atk-content").innerHTML=e,this.$body.prepend(this.$replyTo)}renderPending(){if(!this.data.is_pending)return;const t=U(`<div class="atk-pending">${this.ctx.$t("pendingMsg")}</div>`);this.$body.prepend(t)}renderActions(){this.renderActions_Vote(),this.renderActions_Reply(),this.renderActions_Collapse(),this.renderActions_Moderator(),this.renderActions_Pin(),this.renderActions_Edit(),this.renderActions_Del()}renderActions_Vote(){this.ctx.conf.vote&&(this.voteBtnUp=new yt(this.ctx,(()=>`${this.ctx.$t("voteUp")} (${this.data.vote_up||0})`)).appendTo(this.$actions),this.voteBtnUp.setClick((()=>{this.comment.getActions().vote("up")})),this.ctx.conf.voteDown&&(this.voteBtnDown=new yt(this.ctx,(()=>`${this.ctx.$t("voteDown")} (${this.data.vote_down||0})`)).appendTo(this.$actions),this.voteBtnDown.setClick((()=>{this.comment.getActions().vote("down")}))))}renderActions_Reply(){if(!this.data.is_allow_reply)return;const t=U(`<span>${this.ctx.$t("reply")}</span>`);this.$actions.append(t),t.addEventListener("click",(t=>{t.stopPropagation(),this.cConf.onReplyBtnClick?this.cConf.onReplyBtnClick():this.ctx.replyComment(this.data,this.$el)}))}renderActions_Collapse(){const t=new yt(this.ctx,{text:()=>this.data.is_collapsed?this.ctx.$t("expand"):this.ctx.$t("collapse"),adminOnly:!0});t.appendTo(this.$actions),t.setClick((()=>{this.comment.getActions().adminEdit("collapsed",t)}))}renderActions_Moderator(){const t=new yt(this.ctx,{text:()=>this.data.is_pending?this.ctx.$t("pending"):this.ctx.$t("approved"),adminOnly:!0});t.appendTo(this.$actions),t.setClick((()=>{this.comment.getActions().adminEdit("pending",t)}))}renderActions_Pin(){const t=new yt(this.ctx,{text:()=>this.data.is_pinned?this.ctx.$t("unpin"):this.ctx.$t("pin"),adminOnly:!0});t.appendTo(this.$actions),t.setClick((()=>{this.comment.getActions().adminEdit("pinned",t)}))}renderActions_Edit(){const t=new yt(this.ctx,{text:this.ctx.$t("edit"),adminOnly:!0});t.appendTo(this.$actions),t.setClick((()=>{this.ctx.editComment(this.data,this.$el)}))}renderActions_Del(){const t=new yt(this.ctx,{text:this.ctx.$t("delete"),confirm:!0,confirmText:this.ctx.$t("deleteConfirm"),adminOnly:!0});t.appendTo(this.$actions),t.setClick((()=>{this.comment.getActions().adminDelete(t)}))}checkHeightLimit(){this.checkHeightLimitArea("content"),this.checkHeightLimitArea("children")}checkHeightLimitArea(t){const e=this.ctx.conf.heightLimit.children,i=this.ctx.conf.heightLimit.content;if("children"===t&&!e)return;if("content"===t&&!i)return;let n;"children"===t&&(n=e),"content"===t&&(n=i);const s=t=>{t&&H(t)>n&&this.heightLimitAdd(t,n)};"children"===t?s(this.$childrenWrap):"content"===t&&(s(this.$content),s(this.$replyTo),Q(this.$content,(()=>{s(this.$content)})),this.$replyTo&&Q(this.$replyTo,(()=>{s(this.$replyTo)})))}heightLimitRemove(t){t&&t.classList.contains("atk-height-limit")&&(t.classList.remove("atk-height-limit"),Array.from(t.children).forEach((t=>{t.classList.contains("atk-height-limit-btn")&&t.remove()})),t.style.height="",t.style.overflow="")}heightLimitRemoveForChildren(){this.$childrenWrap&&this.heightLimitRemove(this.$childrenWrap)}heightLimitAdd(t,e){if(!t)return;if(t.classList.contains("atk-height-limit"))return;t.classList.add("atk-height-limit"),t.style.height=`${e}px`,t.style.overflow="hidden";const i=U(`<div class="atk-height-limit-btn">${this.ctx.$t("readMore")}</span>`);i.onclick=e=>{e.stopPropagation(),this.heightLimitRemove(t);const i=this.comment.getChildren();1===i.length&&i[0].getRender().heightLimitRemove(i[0].getRender().$content)},t.append(i)}playFadeAnim(){st(this.comment.getRender().$el)}playFadeAnimForBody(){st(this.comment.getRender().$body)}getChildrenWrap(){return this.$childrenWrap}renderChildrenWrap(){return this.$childrenWrap||(this.$childrenWrap=U('<div class="atk-comment-children"></div>'),this.$main.append(this.$childrenWrap)),this.$childrenWrap}recoveryChildrenWrap(){this.$childrenWrap&&this.$main.append(this.$childrenWrap)}setUnread(t){t?this.$el.classList.add("atk-unread"):this.$el.classList.remove("atk-unread")}setOpenable(t){t?this.$el.classList.add("atk-openable"):this.$el.classList.remove("atk-openable")}setOpenURL(t){this.setOpenable(!0),this.$el.onclick=e=>{e.preventDefault(),window.open(t),this.cConf.openEvt&&this.cConf.openEvt()}}setOpenAction(t){this.setOpenable(!0),this.$el.onclick=e=>{e.preventDefault(),t()}}}class _t{constructor(t){__publicField(this,"comment"),this.comment=t}get ctx(){return this.comment.ctx}get data(){return this.comment.getData()}get cConf(){return this.comment.getConf()}vote(t){const e="up"===t?this.comment.getRender().voteBtnUp:this.comment.getRender().voteBtnDown;this.ctx.getApi().comment.vote(this.data.id,`comment_${t}`).then((t=>{var e,i;this.data.vote_up=t.up,this.data.vote_down=t.down,null==(e=this.comment.getRender().voteBtnUp)||e.updateText(),null==(i=this.comment.getRender().voteBtnDown)||i.updateText()})).catch((t=>{null==e||e.setError(this.ctx.$t("voteFail")),console.log(t)}))}adminEdit(t,e){if(e.isLoading)return;e.setLoading(!0,`${this.ctx.$t("editing")}...`);const i=__spreadValues({},this.data);"collapsed"===t?i.is_collapsed=!i.is_collapsed:"pending"===t?i.is_pending=!i.is_pending:"pinned"===t&&(i.is_pinned=!i.is_pinned),this.ctx.getApi().comment.commentEdit(i).then((t=>{e.setLoading(!1),this.comment.setData(t),this.ctx.listRefreshUI()})).catch((t=>{console.error(t),e.setError(this.ctx.$t("editFail"))}))}adminDelete(t){t.isLoading||(t.setLoading(!0,`${this.ctx.$t("deleting")}...`),this.ctx.getApi().comment.commentDel(this.data.id,this.data.site_name).then((()=>{t.setLoading(!1),this.cConf.onDelete&&this.cConf.onDelete(this.comment)})).catch((e=>{console.error(e),t.setError(this.ctx.$t("deleteFail"))})))}goToReplyComment(){const t=window.location.hash,e=`#atk-comment-${this.data.rid}`;window.location.hash=e,e===t&&window.dispatchEvent(new Event("hashchange"))}}class vt extends a{constructor(t,e,i){super(t),__publicField(this,"renderInstance"),__publicField(this,"actionInstance"),__publicField(this,"data"),__publicField(this,"cConf"),__publicField(this,"parent"),__publicField(this,"children",[]),__publicField(this,"nestCurt"),__publicField(this,"nestMax"),this.nestMax=t.conf.nestMax||3,this.cConf=i,this.data=__spreadValues({},e),this.data.date=this.data.date.replace(/-/g,"/"),this.parent=null,this.nestCurt=1,this.actionInstance=new _t(this),this.renderInstance=new $t(this)}render(){const t=this.renderInstance.render();this.$el&&this.$el.replaceWith(t),this.$el=t,this.cConf.afterRender&&this.cConf.afterRender()}getActions(){return this.actionInstance}getRender(){return this.renderInstance}getData(){return this.data}setData(t){this.data=t,this.render(),this.getRender().playFadeAnimForBody()}getParent(){return this.parent}getChildren(){return this.children}getNestCurt(){return this.nestCurt}getIsRoot(){return 0===this.data.rid}getID(){return this.data.id}putChild(t,e="append"){t.parent=this,t.nestCurt=this.nestCurt+1,this.children.push(t);const i=this.getChildrenEl();"append"===e?i.append(t.getEl()):"prepend"===e&&i.prepend(t.getEl()),t.getRender().playFadeAnim(),t.getRender().checkHeightLimitArea("content")}getChildrenEl(){let t=this.getRender().getChildrenWrap();return t||(t=this.nestCurt<this.nestMax?this.getRender().renderChildrenWrap():this.parent.getChildrenEl()),t}getParents(){const t=[],e=i=>{i.parent&&(t.push(i.parent),e(i.parent))};return e(this),t}getEl(){return this.$el}getGravatarURL(){return t=this.ctx,e=this.data.email_encrypted,`${t.conf.gravatar.mirror.replace(/\/$/,"")}/${e}?d=${encodeURIComponent(t.conf.gravatar.default)}&s=80`;var t,e}getContentMarked(){return K(this.ctx,this.data.content)}getDateFormatted(){return G(new Date(this.data.date),this.ctx)}getUserUA(){const t=function(t){const e=String(t||ft.userAgent),i={os:"",osVersion:"",engine:"",browser:"",device:"",language:"",version:""},n={Trident:e.includes("Trident")||e.includes("NET CLR"),Presto:e.includes("Presto"),WebKit:e.includes("AppleWebKit"),Gecko:e.includes("Gecko/")},s={Safari:e.includes("Safari"),Chrome:e.includes("Chrome")||e.includes("CriOS"),IE:e.includes("MSIE")||e.includes("Trident"),Edge:e.includes("Edge")||e.includes("Edg"),Firefox:e.includes("Firefox")||e.includes("FxiOS"),"Firefox Focus":e.includes("Focus"),Chromium:e.includes("Chromium"),Opera:e.includes("Opera")||e.includes("OPR"),Vivaldi:e.includes("Vivaldi"),Yandex:e.includes("YaBrowser"),Kindle:e.includes("Kindle")||e.includes("Silk/"),360:e.includes("360EE")||e.includes("360SE"),UC:e.includes("UC")||e.includes(" UBrowser"),QQBrowser:e.includes("QQBrowser"),QQ:e.includes("QQ/"),Baidu:e.includes("Baidu")||e.includes("BIDUBrowser"),Maxthon:e.includes("Maxthon"),Sogou:e.includes("MetaSr")||e.includes("Sogou"),LBBROWSER:e.includes("LBBROWSER"),"2345Explorer":e.includes("2345Explorer"),TheWorld:e.includes("TheWorld"),MIUI:e.includes("MiuiBrowser"),Quark:e.includes("Quark"),Qiyu:e.includes("Qiyu"),Wechat:e.includes("MicroMessenger"),Taobao:e.includes("AliApp(TB"),Alipay:e.includes("AliApp(AP"),Weibo:e.includes("Weibo"),Douban:e.includes("com.douban.frodo"),Suning:e.includes("SNEBUY-APP"),iQiYi:e.includes("IqiyiApp")},a={Windows:e.includes("Windows"),Linux:e.includes("Linux")||e.includes("X11"),macOS:e.includes("Macintosh"),Android:e.includes("Android")||e.includes("Adr"),Ubuntu:e.includes("Ubuntu"),FreeBSD:e.includes("FreeBSD"),Debian:e.includes("Debian"),"Windows Phone":e.includes("IEMobile")||e.includes("Windows Phone"),BlackBerry:e.includes("BlackBerry")||e.includes("RIM"),MeeGo:e.includes("MeeGo"),Symbian:e.includes("Symbian"),iOS:e.includes("like Mac OS X"),"Chrome OS":e.includes("CrOS"),WebOS:e.includes("hpwOS")},r={Mobile:e.includes("Mobi")||e.includes("iPh")||e.includes("480"),Tablet:e.includes("Tablet")||e.includes("Pad")||e.includes("Nexus 7")};r.Mobile?r.Mobile=!e.includes("iPad"):s.Chrome&&e.includes("Edg")?(s.Chrome=!1,s.Edge=!0):gt.showModalDialog&&gt.chrome&&(s.Chrome=!1,s[360]=!0),i.device="PC",i.language=(()=>{const t=(ft.browserLanguage||ft.language).split("-");return t[1]&&(t[1]=t[1].toUpperCase()),t.join("_")})();const o={engine:n,browser:s,os:a,device:r};Object.entries(o).forEach((([t,e])=>{Object.entries(e).forEach((([e,n])=>{!0===n&&(i[t]=e)}))}));const l={Windows:()=>{const t=e.replace(/^.*Windows NT ([\d.]+);.*$/,"$1");return{6.4:"10",6.3:"8.1",6.2:"8",6.1:"7","6.0":"Vista",5.2:"XP",5.1:"XP","5.0":"2000","10.0":"10","11.0":"11"}[t]||t},Android:()=>e.replace(/^.*Android ([\d.]+);.*$/,"$1"),iOS:()=>e.replace(/^.*OS ([\d_]+) like.*$/,"$1").replace(/_/g,"."),Debian:()=>e.replace(/^.*Debian\/([\d.]+).*$/,"$1"),"Windows Phone":()=>e.replace(/^.*Windows Phone( OS)? ([\d.]+);.*$/,"$2"),macOS:()=>e.replace(/^.*Mac OS X ([\d_]+).*$/,"$1").replace(/_/g,"."),WebOS:()=>e.replace(/^.*hpwOS\/([\d.]+);.*$/,"$1")};i.osVersion="",l[i.os]&&(i.osVersion=l[i.os](),i.osVersion===e&&(i.osVersion=""));const c={Safari:()=>e.replace(/^.*Version\/([\d.]+).*$/,"$1"),Chrome:()=>e.replace(/^.*Chrome\/([\d.]+).*$/,"$1").replace(/^.*CriOS\/([\d.]+).*$/,"$1"),IE:()=>e.replace(/^.*MSIE ([\d.]+).*$/,"$1").replace(/^.*rv:([\d.]+).*$/,"$1"),Edge:()=>e.replace(/^.*(Edge|Edg|Edg[A-Z]{1})\/([\d.]+).*$/,"$2"),Firefox:()=>e.replace(/^.*Firefox\/([\d.]+).*$/,"$1").replace(/^.*FxiOS\/([\d.]+).*$/,"$1"),"Firefox Focus":()=>e.replace(/^.*Focus\/([\d.]+).*$/,"$1"),Chromium:()=>e.replace(/^.*Chromium\/([\d.]+).*$/,"$1"),Opera:()=>e.replace(/^.*Opera\/([\d.]+).*$/,"$1").replace(/^.*OPR\/([\d.]+).*$/,"$1"),Vivaldi:()=>e.replace(/^.*Vivaldi\/([\d.]+).*$/,"$1"),Yandex:()=>e.replace(/^.*YaBrowser\/([\d.]+).*$/,"$1"),Kindle:()=>e.replace(/^.*Version\/([\d.]+).*$/,"$1"),Maxthon:()=>e.replace(/^.*Maxthon\/([\d.]+).*$/,"$1"),QQBrowser:()=>e.replace(/^.*QQBrowser\/([\d.]+).*$/,"$1"),QQ:()=>e.replace(/^.*QQ\/([\d.]+).*$/,"$1"),Baidu:()=>e.replace(/^.*BIDUBrowser[\s/]([\d.]+).*$/,"$1"),UC:()=>e.replace(/^.*UC?Browser\/([\d.]+).*$/,"$1"),Sogou:()=>e.replace(/^.*SE ([\d.X]+).*$/,"$1").replace(/^.*SogouMobileBrowser\/([\d.]+).*$/,"$1"),"2345Explorer":()=>e.replace(/^.*2345Explorer\/([\d.]+).*$/,"$1"),TheWorld:()=>e.replace(/^.*TheWorld ([\d.]+).*$/,"$1"),MIUI:()=>e.replace(/^.*MiuiBrowser\/([\d.]+).*$/,"$1"),Quark:()=>e.replace(/^.*Quark\/([\d.]+).*$/,"$1"),Qiyu:()=>e.replace(/^.*Qiyu\/([\d.]+).*$/,"$1"),Wechat:()=>e.replace(/^.*MicroMessenger\/([\d.]+).*$/,"$1"),Taobao:()=>e.replace(/^.*AliApp\(TB\/([\d.]+).*$/,"$1"),Alipay:()=>e.replace(/^.*AliApp\(AP\/([\d.]+).*$/,"$1"),Weibo:()=>e.replace(/^.*weibo__([\d.]+).*$/,"$1"),Douban:()=>e.replace(/^.*com.douban.frodo\/([\d.]+).*$/,"$1"),Suning:()=>e.replace(/^.*SNEBUY-APP([\d.]+).*$/,"$1"),iQiYi:()=>e.replace(/^.*IqiyiVersion\/([\d.]+).*$/,"$1")};return i.version="",c[i.browser]&&(i.version=c[i.browser](),i.version===e&&(i.version="")),i.version.indexOf(".")&&(i.version=i.version.substring(0,i.version.indexOf("."))),"iOS"===i.os&&e.includes("iPad")?i.os="iPadOS":"Edge"!==i.browser||e.includes("Edg")?"MIUI"===i.browser?i.os="Android":"Chrome"===i.browser&&Number(i.version)>27||"Opera"===i.browser&&Number(i.version)>12||"Yandex"===i.browser?i.engine="Blink":void 0===i.browser&&(i.browser="Unknow App"):i.engine="EdgeHTML",i}(this.data.ua);return{browser:`${t.browser} ${t.version}`,os:`${t.os} ${t.osVersion}`}}getConf(){return this.cConf}}class kt{constructor(t,e){__publicField(this,"conf"),__publicField(this,"total"),__publicField(this,"$el"),__publicField(this,"$input"),__publicField(this,"inputTimer"),__publicField(this,"$prevBtn"),__publicField(this,"$nextBtn"),__publicField(this,"page",1),this.total=t,this.conf=e,this.$el=U('<div class="atk-pagination-wrap">\n <div class="atk-pagination">\n <div class="atk-btn atk-btn-prev">Prev</div>\n <input type="text" class="atk-input" aria-label="Enter the number of page" />\n <div class="atk-btn atk-btn-next">Next</div>\n </div>\n </div>'),this.$input=this.$el.querySelector(".atk-input"),this.$input.value=`${this.page}`,this.$input.oninput=()=>this.input(),this.$input.onkeydown=t=>this.keydown(t),this.$prevBtn=this.$el.querySelector(".atk-btn-prev"),this.$nextBtn=this.$el.querySelector(".atk-btn-next"),this.$prevBtn.onclick=()=>this.prev(),this.$nextBtn.onclick=()=>this.next(),this.checkDisabled()}get pageSize(){return this.conf.pageSize}get offset(){return this.pageSize*(this.page-1)}get maxPage(){return Math.ceil(this.total/this.pageSize)}update(t,e){this.page=Math.ceil(t/this.pageSize)+1,this.total=e,this.setInput(this.page),this.checkDisabled()}setInput(t){this.$input.value=`${t}`}input(t=!1){window.clearTimeout(this.inputTimer);const e=this.$input.value.trim(),i=()=>{if(""===e)return void this.setInput(this.page);let t=Number(e);Number.isNaN(t)||t<1?this.setInput(this.page):(t>this.maxPage&&(this.setInput(this.maxPage),t=this.maxPage),this.change(t))};t?i():this.inputTimer=window.setTimeout((()=>i()),800)}prev(){const t=this.page-1;t<1||this.change(t)}next(){const t=this.page+1;t>this.maxPage||this.change(t)}change(t){this.page=t,this.conf.onChange(this.offset),this.setInput(t),this.checkDisabled()}checkDisabled(){this.page+1>this.maxPage?this.$nextBtn.classList.add("atk-disabled"):this.$nextBtn.classList.remove("atk-disabled"),this.page-1<1?this.$prevBtn.classList.add("atk-disabled"):this.$prevBtn.classList.remove("atk-disabled")}keydown(t){const e=t.keyCode||t.which;if(38===e){const t=Number(this.$input.value)+1;if(t>this.maxPage)return;this.setInput(t),this.input()}else if(40===e){const t=Number(this.$input.value)-1;if(t<1)return;this.setInput(t),this.input()}else 13===e&&this.input(!0)}setLoading(t){t?tt(this.$el):et(this.$el)}}class bt{constructor(t){__publicField(this,"conf"),__publicField(this,"$el"),__publicField(this,"$loading"),__publicField(this,"$text"),__publicField(this,"offset",0),__publicField(this,"total",0),__publicField(this,"origText","Load More"),this.conf=t,this.origText=this.conf.text||this.origText,this.$el=U(`<div class="atk-list-read-more" style="display: none;">\n <div class="atk-list-read-more-inner">\n <div class="atk-loading-icon" style="display: none;"></div>\n <span class="atk-text">${this.origText}</span>\n </div>\n </div>`),this.$loading=this.$el.querySelector(".atk-loading-icon"),this.$text=this.$el.querySelector(".atk-text"),this.$el.onclick=()=>{this.click()}}get hasMore(){return this.total>this.offset+this.conf.pageSize}click(){this.hasMore&&this.conf.onClick(this.offset+this.conf.pageSize),this.checkDisabled()}show(){this.$el.style.display=""}hide(){this.$el.style.display="none"}setLoading(t){this.$loading.style.display=t?"":"none",this.$text.style.display=t?"none":""}showErr(t){this.setLoading(!1),this.$text.innerText=t,this.$el.classList.add("atk-err"),window.setTimeout((()=>{this.$text.innerText=this.origText,this.$el.classList.remove("atk-err")}),2e3)}update(t,e){this.offset=t,this.total=e,this.checkDisabled()}checkDisabled(){this.hasMore?this.show():this.hide()}}class xt extends a{constructor(t){super(t),__publicField(this,"$commentsWrap"),__publicField(this,"data"),__publicField(this,"isLoading",!1),__publicField(this,"noCommentText"),__publicField(this,"flatMode",!1),__publicField(this,"nestSortBy"),__publicField(this,"pageMode","pagination"),__publicField(this,"pageSize",20),__publicField(this,"scrollListenerAt"),__publicField(this,"repositionAt"),__publicField(this,"pagination"),__publicField(this,"readMoreBtn"),__publicField(this,"autoLoadScrollEvent"),__publicField(this,"renderComment"),__publicField(this,"paramsEditor"),__publicField(this,"onAfterLoad"),__publicField(this,"unread",[]),__publicField(this,"unreadHighlight"),this.$el=U('<div class="atk-list-lite">\n <div class="atk-list-comments-wrap"></div>\n </div>'),this.$commentsWrap=this.$el.querySelector(".atk-list-comments-wrap"),this.noCommentText=t.conf.noComment||t.$t("noComment"),this.nestSortBy=this.ctx.conf.nestSort||"DATE_ASC",window.setInterval((()=>{this.$el.querySelectorAll("[data-atk-comment-date]").forEach((t=>{const e=t.getAttribute("data-atk-comment-date");t.innerText=G(new Date(Number(e)),this.ctx)}))}),3e4)}getData(){return this.data}clearData(){this.data=void 0}getCommentsWrapEl(){return this.$commentsWrap}setLoading(t,e=!1){this.isLoading=t,e?function(t,e){t?tt(e):et(e)}(t,this.$el):"read-more"===this.pageMode?this.readMoreBtn.setLoading(t):"pagination"===this.pageMode&&this.pagination.setLoading(t)}fetchComments(t){return __async(this,null,(function*(){if(this.isLoading)return;const e=0===t,i=t=>this.setLoading(t,e);let n;i(!0),this.ctx.trigger("list-load"),e&&"read-more"===this.pageMode&&this.ctx.clearAllComments();try{n=yield this.ctx.getApi().comment.get(t,this.pageSize,this.flatMode,this.paramsEditor)}catch(s){throw this.onError(s.msg||String(s),t,s.data),s}finally{i(!1)}at(this.$el,null);try{this.onLoad(n,t)}catch(s){throw this.onError(String(s),t),s}finally{i(!1)}}))}onLoad(t,e){var i,n;"pagination"===this.pageMode&&this.ctx.clearAllComments(),this.data=t;const s=(null==(i=t.api_version)?void 0:i.fe_min_version)||"0.0.0";this.ctx.conf.versionCheck&&this.versionCheck("frontend",s,mt)||this.ctx.conf.versionCheck&&this.versionCheck("backend","2.2.0",null==(n=t.api_version)?void 0:n.version)||(t.conf&&"boolean"==typeof t.conf.img_upload&&(this.ctx.conf.imgUpload=t.conf.img_upload),this.importComments(t.comments),this.refreshPagination(e,this.flatMode?t.total:t.total_roots),this.refreshUI(),this.ctx.updateNotifies(t.unread||[]),this.ctx.trigger("list-loaded"),this.ctx.trigger("conf-updated"),this.onAfterLoad&&this.onAfterLoad(t))}refreshPagination(t,e){const i="pagination"===this.pageMode,n="read-more"===this.pageMode;(i?!!this.pagination:!!this.readMoreBtn)||this.initPagination(),i&&this.pagination.update(t,e),n&&this.readMoreBtn.update(t,e)}initPagination(){if("read-more"===this.pageMode&&(this.readMoreBtn=new bt({pageSize:this.pageSize,onClick:t=>__async(this,null,(function*(){yield this.fetchComments(t)})),text:this.ctx.$t("loadMore")}),this.$el.append(this.readMoreBtn.$el),this.conf.pagination.autoLoad)){const t=this.scrollListenerAt||document;this.autoLoadScrollEvent&&t.removeEventListener("scroll",this.autoLoadScrollEvent),this.autoLoadScrollEvent=()=>{var t;if("read-more"!==this.pageMode||!(null==(t=this.readMoreBtn)?void 0:t.hasMore)||this.isLoading)return;const e=this.$el.querySelector(".atk-list-comments-wrap > .atk-comment-wrap:nth-last-child(3)");e&&function(t,e=document.documentElement){const i=e.clientHeight,n=e.scrollTop,s=n+i,a=t.getBoundingClientRect();return a.top+n+a.height<=s}(e,this.scrollListenerAt)&&this.readMoreBtn.click()},t.addEventListener("scroll",this.autoLoadScrollEvent)}"pagination"===this.pageMode&&(this.pagination=new kt(this.flatMode?this.data.total:this.data.total_roots,{pageSize:this.pageSize,onChange:t=>__async(this,null,(function*(){if(!0===this.ctx.conf.editorTravel&&this.ctx.editorTravelBack(),yield this.fetchComments(t),this.repositionAt){(this.scrollListenerAt||window).scroll({top:this.repositionAt?V(this.repositionAt).top:0,left:0})}}))}),this.$el.append(this.pagination.$el))}onError(t,e,i){var n;if(t=String(t),console.error(t),0!==e&&"read-more"===this.pageMode)return void(null==(n=this.readMoreBtn)||n.showErr(this.$t("loadFail")));const s=U(`<span>${t},${this.$t("listLoadFailMsg")}<br/></span>`),a=U(`<span style="cursor:pointer;">${this.$t("listRetry")}</span>`);a.onclick=()=>this.fetchComments(0),s.appendChild(a);const r=U('<span atk-only-admin-show> | <span style="cursor:pointer;">打开控制台</span></span>');s.appendChild(r),this.ctx.user.data.isAdmin||r.classList.add("atk-hide");let o="";if(null==i?void 0:i.err_no_site){const t={create_name:this.ctx.conf.site,create_urls:`${window.location.protocol}//${window.location.host}`};o=`sites|${JSON.stringify(t)}`}r.onclick=()=>this.ctx.showSidebar({view:o}),at(this.$el,s)}refreshUI(){const t=this.ctx.getCommentList().length<=0;let e=this.$commentsWrap.querySelector(".atk-list-no-comment");t?e||(e=U('<div class="atk-list-no-comment"></div>'),e.innerHTML=this.noCommentText,this.$commentsWrap.appendChild(e)):null==e||e.remove(),this.ctx.checkAdminShowEl()}reload(){this.fetchComments(0)}createComment(t,e){e||(e=this.ctx.getCommentDataList());const i=new vt(this.ctx,t,{isFlatMode:this.flatMode,afterRender:()=>{this.renderComment&&this.renderComment(i)},onDelete:t=>{this.ctx.deleteComment(t),this.refreshUI()},replyTo:t.rid?e.find((e=>e.id===t.rid)):void 0});return i.render(),this.ctx.getCommentList().push(i),i}importComments(t){this.flatMode?t.forEach((e=>{this.putCommentFlatMode(e,t,"append")})):this.importCommentsNest(t)}importCommentsNest(t){const e=function(t,e="DATE_DESC",i=2){const n=[];t.filter((t=>0===t.rid)).forEach((e=>{const s={id:e.id,comment:e,children:[],level:1};s.parent=s,n.push(s),function e(n){const s=t.filter((t=>t.rid===n.id));0!==s.length&&(n.level>=i&&(n=n.parent),s.forEach((t=>{const i={id:t.id,comment:t,children:[],parent:n,level:n.level+1};n.children.push(i),e(i)})))}(s)}));const s=(i,n)=>{let s=i.id-n.id;return"DATE_ASC"===e?s=+new Date(i.comment.date)-+new Date(n.comment.date):"DATE_DESC"===e?s=+new Date(n.comment.date)-+new Date(i.comment.date):"SRC_INDEX"===e?s=t.indexOf(i.comment)-t.indexOf(n.comment):"VOTE_UP_DESC"===e&&(s=n.comment.vote_up-i.comment.vote_up),s};return function t(e){e.forEach((e=>{e.children=e.children.sort(s),t(e.children)}))}(n),n}(t,this.nestSortBy,this.conf.nestMax);e.forEach((e=>{const i=this.createComment(e.comment,t);this.$commentsWrap.appendChild(i.getEl()),i.getRender().playFadeAnim();const n=this;!function e(i,s){s.children.forEach((s=>{const a=s.comment,r=n.createComment(a,t);i.putChild(r),e(r,s)}))}(i,e),i.getRender().checkHeightLimit()}))}putCommentFlatMode(t,e,i){t.is_collapsed&&(t.is_allow_reply=!1);const n=this.createComment(t,e);return t.visible&&("append"===i&&this.$commentsWrap.append(n.getEl()),"prepend"===i&&this.$commentsWrap.prepend(n.getEl()),n.getRender().playFadeAnim()),n.getRender().checkHeightLimit(),n}insertComment(t){if(this.flatMode){it(this.putCommentFlatMode(t,this.ctx.getCommentDataList(),"prepend").getEl())}else{const e=this.createComment(t);if(0===t.rid)this.$commentsWrap.prepend(e.getEl());else{const i=this.ctx.findComment(t.rid);i&&(i.putChild(e,"DATE_ASC"===this.nestSortBy?"append":"prepend"),e.getParents().forEach((t=>{t.getRender().heightLimitRemoveForChildren()})))}e.getRender().checkHeightLimit(),it(e.getEl()),e.getRender().playFadeAnim()}this.data&&(this.data.total+=1),this.refreshUI(),this.ctx.trigger("list-loaded"),this.ctx.trigger("list-inserted",t)}updateComment(t){const e=this.ctx.findComment(t.id);e&&e.setData(t)}updateUnread(t){this.unread=t,!0===this.unreadHighlight&&this.ctx.getCommentList().forEach((t=>{const e=this.unread.find((e=>e.comment_id===t.getID()));e?(t.getRender().setUnread(!0),t.getRender().setOpenAction((()=>{window.open(e.read_link),this.unread=this.unread.filter((e=>e.comment_id!==t.getID())),this.ctx.updateNotifies(this.unread)}))):t.getRender().setUnread(!1)}))}versionCheck(t,e,i){const n=1===function(t,e){const i=t.split("."),n=e.split(".");for(let s=0;s<3;s++){const t=Number(i[s]),e=Number(n[s]);if(t>e)return 1;if(e>t)return-1;if(!Number.isNaN(t)&&Number.isNaN(e))return 1;if(Number.isNaN(t)&&!Number.isNaN(e))return-1}return 0}(e,i);if(n){const n=U(`<div>Artalk ${this.$t(t)}版本已过时,请更新以获得完整体验<br/>如果你是管理员,请前往 “<a href="https://artalk.js.org/" target="_blank">官方文档</a>” 获得帮助<br/><br/><span style="color: var(--at-color-meta);">当前${this.$t(t)}版本 ${i},需求版本 >= ${e}</span><br/><br/></div>`),s=U('<span style="cursor:pointer;">忽略</span>');s.onclick=()=>{at(this.$el.parentElement,null),this.ctx.conf.versionCheck=!1,this.ctx.trigger("conf-updated"),this.fetchComments(0)},n.append(s),at(this.$el.parentElement,n,'<span class="atk-warn-title">Artalk Warn</span>')}return n}}class wt extends xt{constructor(t){const e=U('<div class="atk-list">\n <div class="atk-list-header">\n <div class="atk-comment-count">\n <div class="atk-text"></div>\n </div>\n <div class="atk-right-action">\n <span data-action="admin-close-comment" class="atk-hide" atk-only-admin-show></span>\n <span data-action="open-sidebar" class="atk-hide atk-on">\n <span class="atk-unread-badge" style="display: none;"></span>\n <div class="atk-text"></div>\n </span>\n </div>\n </div>\n <div class="atk-list-body"></div>\n <div class="atk-list-footer">\n <div class="atk-copyright"></div>\n </div>\n</div>\n');super(t),__publicField(this,"$closeCommentBtn"),__publicField(this,"$openSidebarBtn"),__publicField(this,"$unreadBadge"),__publicField(this,"$commentCount"),__publicField(this,"$commentCountNum"),__publicField(this,"$dropdownWrap"),__publicField(this,"goToCommentFounded",!1),__publicField(this,"goToCommentDelay",!0),e.querySelector(".atk-list-body").append(this.$el),this.$el=e,(!0===this.ctx.conf.flatMode||this.conf.nestMax&&this.conf.nestMax<=1||"auto"===this.ctx.conf.flatMode&&window.matchMedia("(max-width: 768px)").matches)&&(this.flatMode=!0),this.pageMode=this.conf.pagination.readMore?"read-more":"pagination",this.pageSize=this.conf.pagination.pageSize||20,this.repositionAt=this.$el,this.initListActionBtn(),this.$commentCount=this.$el.querySelector(".atk-comment-count"),this.$commentCount.innerHTML=this.$t("counter",{count:'<span class="atk-comment-count-num">0</span>'}),this.$commentCountNum=this.$commentCount.querySelector(".atk-comment-count-num"),this.ctx.conf.listSort&&this.initDropdown(),this.$el.querySelector(".atk-copyright").innerHTML='Powered By <a href="https://artalk.js.org" target="_blank" title="Artalk v2.4.2">Artalk</a>'}initListActionBtn(){this.$openSidebarBtn=this.$el.querySelector('[data-action="open-sidebar"]'),this.$closeCommentBtn=this.$el.querySelector('[data-action="admin-close-comment"]'),this.$unreadBadge=this.$el.querySelector(".atk-unread-badge"),this.$openSidebarBtn.addEventListener("click",(()=>{this.ctx.showSidebar()})),this.$closeCommentBtn.addEventListener("click",(()=>{this.data&&(this.data.page.admin_only=!this.data.page.admin_only,this.adminPageEditSave())}))}refreshUI(){var t;super.refreshUI(),this.$commentCountNum.innerText=String(Number(null==(t=this.data)?void 0:t.total)||0),this.ctx.user.data.nick&&this.ctx.user.data.email?this.$openSidebarBtn.classList.remove("atk-hide"):this.$openSidebarBtn.classList.add("atk-hide"),this.ctx.checkAdminShowEl(),this.$openSidebarBtn.querySelector(".atk-text").innerText=this.ctx.user.data.isAdmin?this.$t("ctrlCenter"):this.$t("msgCenter"),this.data&&this.data.page&&!0===this.data.page.admin_only?(this.ctx.editorClose(),this.$closeCommentBtn.innerHTML=this.$t("openComment")):(this.ctx.editorOpen(),this.$closeCommentBtn.innerHTML=this.$t("closeComment"))}onLoad(t,e){super.onLoad(t,e),this.goToCommentFounded||this.checkGoToCommentByUrlHash(),!0===this.ctx.conf.editorTravel&&this.ctx.editorTravelBack()}checkGoToCommentByUrlHash(){let t=Number(j("atk_comment"));if(!t){const e=window.location.hash.match(/#atk-comment-([0-9]+)/);if(!e||!e[1]||Number.isNaN(Number(e[1])))return;t=Number(e[1])}if(!t)return;const e=this.ctx.findComment(t);if(!e)return void(this.readMoreBtn?this.readMoreBtn.click():this.pagination&&this.pagination.next());const i=j("atk_notify_key");i&&this.ctx.getApi().user.markRead(i).then((()=>{this.unread=this.unread.filter((e=>e.comment_id!==t)),this.updateUnread(this.unread)})),e.getParents().forEach((t=>{t.getRender().heightLimitRemoveForChildren()}));const n=()=>{it(e.getEl(),!1),e.getEl().classList.remove("atk-flash-once"),window.setTimeout((()=>{e.getEl().classList.add("atk-flash-once")}),150)};this.goToCommentDelay?window.setTimeout((()=>n()),350):n(),this.goToCommentFounded=!0}adminPageEditSave(){this.data&&this.data.page&&(this.ctx.editorShowLoading(),this.ctx.getApi().page.pageEdit(this.data.page).then((t=>{this.data&&(this.data.page=__spreadValues({},t)),this.refreshUI()})).catch((t=>{this.ctx.editorShowNotify(`${this.$t("editFail")}: ${t.msg||String(t)}`,"e")})).finally((()=>{this.ctx.editorHideLoading()})))}showUnreadBadge(t){t>0?(this.$unreadBadge.innerText=`${Number(t||0)}`,this.$unreadBadge.style.display="block"):this.$unreadBadge.style.display="none"}initDropdown(){this.$dropdownWrap=this.$commentCount,this.$commentCount.classList.add("atk-dropdown-wrap"),this.$dropdownWrap.append(U('<span class="atk-arrow-down-icon"></span>'));const t=t=>{this.paramsEditor=e=>{t(e)},this.fetchComments(0)},e=[[this.$t("sortLatest"),()=>{t((t=>{t.sort_by="date_desc"}))}],[this.$t("sortBest"),()=>{t((t=>{t.sort_by="vote"}))}],[this.$t("sortOldest"),()=>{t((t=>{t.sort_by="date_asc"}))}],[this.$t("sortAuthor"),()=>{t((t=>{t.view_only_admin=!0}))}]];let i=0;const n=U('<ul class="atk-dropdown atk-fade-in"></ul>');e.forEach(((t,e)=>{const s=t[0],a=t[1],r=U('<li class="atk-dropdown-item"><span></span></li>'),o=r.querySelector("span");o.innerText=s,o.onclick=()=>{((t,e,s,a)=>{a(),i=t,n.querySelectorAll(".active").forEach((t=>{t.classList.remove("active")})),e.classList.add("active"),n.style.display="none",setTimeout((()=>{n.style.display=""}),80)})(e,r,0,a)},n.append(r),e===i&&r.classList.add("active")})),this.$dropdownWrap.append(n)}updateUnread(t){super.updateUnread(t),this.showUnreadBadge((null==t?void 0:t.length)||0)}}class Ct{constructor(t,e){__publicField(this,"api"),__publicField(this,"editor"),__publicField(this,"list"),__publicField(this,"sidebarLayer"),__publicField(this,"checkerLauncher"),__publicField(this,"cid"),__publicField(this,"conf"),__publicField(this,"user"),__publicField(this,"$root"),__publicField(this,"markedInstance"),__publicField(this,"markedReplacers",[]),__publicField(this,"commentList",[]),__publicField(this,"eventList",[]),this.cid=+new Date,this.conf=t,this.user=new s(this),this.$root=e||document.createElement("div"),this.$root.setAttribute("atk-run-id",this.cid.toString()),this.$root.classList.add("artalk"),this.$root.innerHTML="",this.api=new pt(this)}setApi(t){this.api=t}setEditor(t){this.editor=t}setList(t){this.list=t}setSidebarLayer(t){this.sidebarLayer=t}setCheckerLauncher(t){this.checkerLauncher=t}getApi(){return this.api}getCommentList(){return this.commentList}getCommentDataList(){return this.commentList.map((t=>t.getData()))}findComment(t){return this.commentList.find((e=>e.getData().id===t))}deleteComment(t){let e;if("number"==typeof t){const i=this.findComment(t);if(!i)throw Error(`Comment ${t} cannot be found`);e=i}else e=t;if(e.getEl().remove(),this.commentList.splice(this.commentList.indexOf(e),1),this.list){const t=this.list.getData();t&&(t.total-=1),this.list.refreshUI()}}clearAllComments(){this.list&&(this.list.getCommentsWrapEl().innerHTML="",this.list.clearData()),this.commentList=[]}insertComment(t){var e;null==(e=this.list)||e.insertComment(t)}updateComment(t){var e;null==(e=this.list)||e.updateComment(t)}replyComment(t,e,i){this.editor.setReply(t,e,i)}cancelReplyComment(){this.editor.cancelReply()}editComment(t,e){this.editor.setEditComment(t,e)}cancelEditComment(){this.editor.cancelEditComment()}updateNotifies(t){var e;null==(e=this.list)||e.updateUnread(t)}listReload(){var t;null==(t=this.list)||t.reload()}reload(){this.listReload()}listRefreshUI(){var t;null==(t=this.list)||t.refreshUI()}listHashGotoCheck(){if(!this.list||this.list instanceof wt)return;const t=this.list;t.goToCommentDelay=!1,t.checkGoToCommentByUrlHash()}editorOpen(){this.editor.open()}editorClose(){this.editor.close()}editorShowLoading(){this.editor.showLoading()}editorHideLoading(){this.editor.hideLoading()}editorShowNotify(t,e){this.editor.showNotify(t,e)}editorTravel(t){this.editor.travel(t)}editorTravelBack(){this.editor.travelBack()}showSidebar(t){this.sidebarLayer.show(t)}hideSidebar(){this.sidebarLayer.hide()}checkAdmin(t){this.checkerLauncher.checkAdmin(t)}checkCaptcha(t){this.checkerLauncher.checkCaptcha(t)}checkAdminShowEl(){const t=[];this.$root.querySelectorAll("[atk-only-admin-show]").forEach((e=>t.push(e)));const{$wrap:e}=lt(this);e&&e.querySelectorAll("[atk-only-admin-show]").forEach((e=>t.push(e)));const i=document.querySelector(".atk-sidebar");i&&i.querySelectorAll("[atk-only-admin-show]").forEach((e=>t.push(e))),t.forEach((t=>{this.user.data.isAdmin?t.classList.remove("atk-hide"):t.classList.add("atk-hide")}))}on(t,e,i="internal"){this.eventList.push({name:t,handler:e,scope:i})}off(t,e,i="internal"){this.eventList=this.eventList.filter((n=>e?!(n.name===t&&n.handler===e&&n.scope===i):!(n.name===t&&n.scope===i)))}trigger(t,e,i){this.eventList.filter((e=>e.name===t&&(!i||e.scope===i))).map((t=>t.handler)).forEach((t=>t(e)))}$t(t,e={}){return n(this.conf.locale,t,e)}setDarkMode(t){const e="atk-dark-mode";this.conf.darkMode=t,this.trigger("conf-updated"),this.conf.darkMode?this.$root.classList.add(e):this.$root.classList.remove(e);const{$wrap:i}=lt(this);i&&(this.conf.darkMode?i.classList.add(e):i.classList.remove(e))}}const St={el:"",pageKey:"",pageTitle:"",server:"",site:"",placeholder:"",noComment:"",sendBtn:"",darkMode:!1,editorTravel:!0,flatMode:"auto",nestMax:2,nestSort:"DATE_ASC",emoticons:"https://cdn.jsdelivr.net/gh/ArtalkJS/Emoticons/grps/default.json",vote:!0,voteDown:!1,uaBadge:!0,listSort:!0,preview:!0,countEl:"#ArtalkCount",pvEl:"#ArtalkPV",gravatar:{default:"mp",mirror:"https://sdn.geekzu.org/avatar/"},pagination:{pageSize:20,readMore:!0,autoLoad:!0},heightLimit:{content:300,children:400},imgUpload:!0,reqTimeout:15e3,versionCheck:!0,useBackendConf:!1,locale:"zh-CN"};St.vote=!1,St.uaBadge=!1,St.emoticons=!1;class Lt{constructor(t,e){return __publicField(this,"ctx"),__publicField(this,"$el"),__publicField(this,"$content"),__publicField(this,"$actions"),this.ctx=t,this.$el=U('<div class="atk-layer-dialog-wrap">\n <div class="atk-layer-dialog">\n <div class="atk-layer-dialog-content"></div>\n <div class="atk-layer-dialog-actions"></div>\n </div>\n </div>'),this.$actions=this.$el.querySelector(".atk-layer-dialog-actions"),this.$content=this.$el.querySelector(".atk-layer-dialog-content"),this.$content.appendChild(e),this}setYes(t){const e=U(`<button data-action="confirm">${this.ctx.$t("confirm")}</button>`);return e.onclick=this.onBtnClick(t),this.$actions.appendChild(e),this}setNo(t){const e=U(`<button data-action="cancel">${this.ctx.$t("cancel")}</button>`);return e.onclick=this.onBtnClick(t),this.$actions.appendChild(e),this}onBtnClick(t){return e=>{const i=t(e.currentTarget,this);void 0!==i&&!0!==i||this.$el.remove()}}}const Tt={request:(t,e,i)=>t.ctx.getApi().captcha.captchaCheck(i),body(t,e){if(t.captchaConf.iframe){const i=U('<div class="atk-checker-iframe-wrap"></div>'),n=U('<iframe class="atk-fade-in"></iframe>');n.style.display="none",tt(i,{transparentBg:!0}),n.src=`${t.ctx.conf.server}/api/captcha/get?t=${+new Date}`,n.onload=()=>{n.style.display="",et(i)},i.append(n);const s=U('<div class="atk-close-btn"><i class="atk-icon atk-icon-close"></i></div>');i.append(s),e.hideInteractInput();let a=!1;const r=t=>new Promise((e=>{window.setTimeout((()=>{e(null)}),t)}));return function i(){return __async(this,null,(function*(){if(yield r(1e3),a)return;let n=!1;try{n=(yield t.ctx.getApi().captcha.captchaStatus()).is_pass}catch(s){n=!1}n?e.triggerSuccess():i()}))}(),s.onclick=()=>{a=!0,e.cancel()},i}const i=U(`<span><img class="atk-captcha-img" src="${t.captchaConf.imgData||""}">${t.ctx.$t("captchaCheck")}</span>`);return i.querySelector(".atk-captcha-img").onclick=()=>{const e=i.querySelector(".atk-captcha-img");t.ctx.getApi().captcha.captchaGet().then((t=>{e.setAttribute("src",t)})).catch((t=>{console.error("Failed to get captcha image ",t)}))},i},onSuccess(t,e,i,n,s){t.captchaConf.val=n},onError(t,e,i,n,s){s.querySelector(".atk-captcha-img").click()}},Et={inputType:"password",request(t,e,i){const n={name:t.ctx.user.data.nick,email:t.ctx.user.data.email,password:i};return t.ctx.getApi().user.login(n.name,n.email,n.password)},body:(t,e)=>U(`<span>${t.ctx.$t("adminCheck")}</span>`),onSuccess(t,e,i,n,s){t.ctx.user.update({isAdmin:!0,token:i}),t.ctx.trigger("user-changed",t.ctx.user.data),t.ctx.listReload()},onError(t,e,i,n,s){}};class At{constructor(t){__publicField(this,"ctx"),__publicField(this,"launched",[]),__publicField(this,"captchaConf",{}),this.ctx=t}checkCaptcha(t){this.captchaConf.imgData=t.imgData,this.captchaConf.iframe=t.iframe,this.fire(Tt,t)}checkAdmin(t){this.fire(Et,t)}fire(t,e){if(this.launched.includes(t))return;this.launched.push(t);const i=new ot(this.ctx,`checker-${(new Date).getTime()}`);i.setMaskClickHide(!1),i.show();let n=!1;const s={getLayer:()=>i,hideInteractInput:()=>{n=!0},triggerSuccess:()=>{this.close(t,i),t.onSuccess&&t.onSuccess(this,s,"","",a),e.onSuccess&&e.onSuccess("",l.$el)},cancel:()=>{this.close(t,i),e.onCancel&&e.onCancel()}},a=U();a.appendChild(t.body(this,s));const r=U(`<input id="check" type="${t.inputType||"text"}" autocomplete="off" required placeholder="">`);let o;a.appendChild(r),setTimeout((()=>r.focus()),80),r.onkeyup=t=>{"Enter"!==t.key&&13!==t.keyCode||(t.preventDefault(),i.getEl().querySelector('button[data-action="confirm"]').click())};const l=new Lt(this.ctx,a);l.setYes((n=>{const c=r.value.trim();o||(o=n.innerText);const d=()=>{n.innerText=o||"",n.classList.remove("error")};return n.innerText=`${this.ctx.$t("loading")}...`,t.request(this,s,c).then((n=>{this.close(t,i),t.onSuccess&&t.onSuccess(this,s,n,c,a),e.onSuccess&&e.onSuccess(c,l.$el)})).catch((e=>{var i;i=String(e.msg||String(e)),n.innerText=i,n.classList.add("error"),t.onError&&t.onError(this,s,e,c,a);const o=setTimeout((()=>d()),3e3);r.onfocus=()=>{d(),clearTimeout(o)}})),!1})),l.setNo((()=>(this.close(t,i),e.onCancel&&e.onCancel(),!1))),n&&(r.style.display="none",l.$el.querySelector(".atk-layer-dialog-actions").style.display="none"),i.getEl().append(l.$el),e.onMount&&e.onMount(l.$el)}close(t,e){e.disposeNow(),this.launched=this.launched.filter((e=>e!==t))}}class Ft{constructor(t){__publicField(this,"editor"),__publicField(this,"$panel"),__publicField(this,"$btn"),__publicField(this,"onHeaderInput"),this.editor=t}get ctx(){return this.editor.ctx}registerPanel(t="<div></div>"){return this.$panel=U(t),this.$panel}registerBtn(t){return this.$btn=U(`<span class="atk-plug-btn" data-plug-name="${this.constructor.name}">${t}</span>`),this.$btn}registerHeaderInputEvt(t){this.onHeaderInput=t}getPanel(){return this.$panel}getBtn(){return this.$btn}}__publicField(Ft,"Name");class Bt extends Ft{constructor(t){super(t),__publicField(this,"emoticons",[]),__publicField(this,"loadingTask",null),__publicField(this,"$grpWrap"),__publicField(this,"$grpSwitcher"),__publicField(this,"isListLoaded",!1),__publicField(this,"isImgLoaded",!1),this.editor=t,this.registerPanel('<div class="atk-editor-plug-emoticons"></div>'),this.registerBtn(this.ctx.$t("emoticon")),window.setTimeout((()=>{this.loadEmoticonsData()}),1e3)}onPanelShow(){(()=>{__async(this,null,(function*(){yield this.loadEmoticonsData(),this.isImgLoaded||(this.initEmoticonsList(),this.isImgLoaded=!0),setTimeout((()=>{this.changeListHeight()}),30)}))})()}onPanelHide(){this.$panel.parentElement.style.height=""}loadEmoticonsData(){return __async(this,null,(function*(){this.isListLoaded||(null===this.loadingTask?(this.loadingTask=(()=>__async(this,null,(function*(){tt(this.$panel),this.emoticons=yield this.handleData(this.ctx.conf.emoticons),et(this.$panel),this.loadingTask=null,this.isListLoaded=!0})))(),yield this.loadingTask):yield this.loadingTask)}))}handleData(t){return __async(this,null,(function*(){if(!Array.isArray(t)&&["object","string"].includes(typeof t)&&(t=[t]),!Array.isArray(t))return at(this.$panel,"表情包数据必须为 Array/Object/String 类型"),et(this.$panel),[];const e=e=>{"object"==typeof e&&(e.name&&t.find((t=>t.name===e.name))||t.push(e))},i=t=>__async(this,null,(function*(){yield Promise.all(t.map(((t,n)=>__async(this,null,(function*(){if("object"!=typeof t||Array.isArray(t)){if(Array.isArray(t))yield i(t);else if("string"==typeof t){const n=yield this.remoteLoad(t);Array.isArray(n)?yield i(n):"object"==typeof n&&e(n)}}else e(t)})))))}));return yield i(t),t.forEach((t=>{if(this.isOwOFormat(t)){this.convertOwO(t).forEach((t=>{e(t)}))}else Array.isArray(t)&&t.forEach((t=>{e(t)}))})),t=t.filter((t=>"object"==typeof t&&!Array.isArray(t)&&!!t&&!!t.name)),this.solveNullKey(t),this.solveSameKey(t),t}))}remoteLoad(t){return __async(this,null,(function*(){if(!t)return[];try{const e=yield fetch(t);return yield e.json()}catch(e){return et(this.$panel),at(this.$panel,`表情加载失败 ${String(e)}`),[]}}))}solveNullKey(t){t.forEach((t=>{t.items.forEach(((e,i)=>{e.key||(e.key=`${t.name} ${i+1}`)}))}))}solveSameKey(t){const e={};t.forEach((t=>{t.items.forEach((t=>{t.key&&""!==String(t.key).trim()&&(e[t.key]?e[t.key]++:e[t.key]=1,e[t.key]>1&&(t.key=`${t.key} ${e[t.key]}`))}))}))}isOwOFormat(t){try{return"object"==typeof t&&!!Object.values(t).length&&Array.isArray(Object.keys(Object.values(t)[0].container))&&Object.keys(Object.values(t)[0].container[0]).includes("icon")}catch(e){return!1}}convertOwO(t){const e=[];return Object.entries(t).forEach((([t,i])=>{const n={name:t,type:i.type,items:[]};i.container.forEach(((e,i)=>{const s=e.icon;if(/<(img|IMG)/.test(s)){const t=/src=["'](.*?)["']/.exec(s);t&&t.length>1&&(e.icon=t[1])}n.items.push({key:e.text||`${t} ${i+1}`,val:e.icon})})),e.push(n)})),e}initEmoticonsList(){this.$grpWrap=U('<div class="atk-grp-wrap"></div>'),this.$panel.append(this.$grpWrap),this.emoticons.forEach(((t,e)=>{const i=U('<div class="atk-grp" style="display: none;"></div>');this.$grpWrap.append(i),i.setAttribute("data-index",String(e)),i.setAttribute("data-grp-name",t.name),i.setAttribute("data-type",t.type),t.items.forEach((e=>{const n=U('<span class="atk-item"></span>');if(i.append(n),e.key&&!new RegExp(`^(${t.name})?\\s?[0-9]+$`).test(e.key)&&n.setAttribute("title",e.key),"image"===t.type){const t=document.createElement("img");t.src=e.val,t.alt=e.key,n.append(t)}else n.innerText=e.val;n.onclick=()=>{"image"===t.type?this.editor.insertContent(`:[${e.key}]`):this.editor.insertContent(e.val||"")}}))})),this.emoticons.length>1&&(this.$grpSwitcher=U('<div class="atk-grp-switcher"></div>'),this.$panel.append(this.$grpSwitcher),this.emoticons.forEach(((t,e)=>{const i=U("<span />");i.innerText=t.name,i.setAttribute("data-index",String(e)),i.onclick=()=>this.openGrp(e),this.$grpSwitcher.append(i)}))),this.emoticons.length>0&&this.openGrp(0)}openGrp(t){var e,i,n;Array.from(this.$grpWrap.children).forEach((e=>{const i=e;i.getAttribute("data-index")!==String(t)?i.style.display="none":i.style.display=""})),null==(e=this.$grpSwitcher)||e.querySelectorAll("span.active").forEach((t=>t.classList.remove("active"))),null==(n=null==(i=this.$grpSwitcher)?void 0:i.querySelector(`span[data-index="${t}"]`))||n.classList.add("active"),this.changeListHeight()}changeListHeight(){}transEmoticonImageText(t){return this.emoticons&&Array.isArray(this.emoticons)?(this.emoticons.forEach((e=>{"image"===e.type&&Object.entries(e.items).forEach((([e,i])=>{t=t.split(`:[${i.key}]`).join(`<img src="${i.val}" atk-emoticon="${i.key}">`)}))})),t):t}}__publicField(Bt,"Name","emoticons");class Ot extends Ft{constructor(t){super(t),__publicField(this,"$imgUploadInput"),__publicField(this,"allowImgExts",["png","jpg","jpeg","gif","bmp","svg","webp"]),this.$imgUploadInput=document.createElement("input"),this.$imgUploadInput.type="file",this.$imgUploadInput.style.display="none",this.$imgUploadInput.accept=this.allowImgExts.map((t=>`.${t}`)).join(",");const e=this.registerBtn(`${this.ctx.$t("image")}`);e.after(this.$imgUploadInput),e.onclick=()=>{const t=this.$imgUploadInput;t.onchange=()=>{(()=>{__async(this,null,(function*(){if(!t.files||0===t.files.length)return;const e=t.files[0];this.uploadImg(e)}))})()},t.click()},this.ctx.on("conf-updated",(()=>{this.ctx.conf.imgUpload||(this.getBtn().setAttribute("atk-only-admin-show",""),this.ctx.checkAdminShowEl())}));const i=t=>{if(t)for(let e=0;e<t.length;e++){const i=t[e];this.uploadImg(i)}};this.editor.$textarea.addEventListener("dragover",(t=>{t.stopPropagation(),t.preventDefault()})),this.editor.$textarea.addEventListener("drop",(t=>{var e;const n=null==(e=t.dataTransfer)?void 0:e.files;(null==n?void 0:n.length)&&(t.preventDefault(),i(n))})),this.editor.$textarea.addEventListener("paste",(t=>{var e;const n=null==(e=t.clipboardData)?void 0:e.files;(null==n?void 0:n.length)&&(t.preventDefault(),i(n))}))}uploadImg(t){return __async(this,null,(function*(){const e=/[^.]+$/.exec(t.name);if(!e||!this.allowImgExts.includes(e[0]))return;if(!this.ctx.user.checkHasBasicUserInfo())return void this.editor.showNotify(this.ctx.$t("uploadLoginMsg"),"w");let i="\n";""===this.editor.$textarea.value.trim()&&(i="");const n=`${i}![](Uploading ${t.name}...)`;let s;this.editor.insertContent(n);try{s=this.ctx.conf.imgUploader?{img_url:yield this.ctx.conf.imgUploader(t)}:yield this.ctx.getApi().upload.imgUpload(t)}catch(a){console.error(a),this.editor.showNotify(`${this.ctx.$t("uploadFail")},${a.msg}`,"e")}if(s&&s.img_url){let t=s.img_url;X(t)||(t=J(this.ctx,t)),this.editor.setContent(this.editor.$textarea.value.replace(n,`${i}![](${t})`))}else this.editor.setContent(this.editor.$textarea.value.replace(n,""))}))}}__publicField(Ot,"Name","upload");class Mt extends Ft{constructor(t){super(t),__publicField(this,"isBind",!1),this.registerPanel('<div class="atk-editor-plug-preview"></div>');let e=this.editor.$t("preview");this.ctx.markedInstance&&(e+=' <i title="Markdown is supported"><svg class="markdown" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M14.85 3H1.15C.52 3 0 3.52 0 4.15v7.69C0 12.48.52 13 1.15 13h13.69c.64 0 1.15-.52 1.15-1.15v-7.7C16 3.52 15.48 3 14.85 3zM9 11H7V8L5.5 9.92 4 8v3H2V5h2l1.5 2L7 5h2v6zm2.99.5L9.5 8H11V5h2v3h1.5l-2.51 3.5z"></path></svg></i>'),this.registerBtn(e)}onPanelShow(){if(this.updateContent(),!this.isBind){const t=()=>{this.updateContent()};this.editor.$textarea.addEventListener("input",t),this.editor.$textarea.addEventListener("change",t),this.isBind=!0}}updateContent(){"none"!==this.$panel.style.display&&(this.$panel.innerHTML=this.editor.getContentMarked())}}__publicField(Mt,"Name","preview");class Pt extends Ft{constructor(t){super(t),__publicField(this,"queryUserInfo",{timeout:null,abortFunc:null}),this.registerHeaderInputEvt(((t,e)=>{"nick"!==t&&"email"!==t||this.fetchUserInfo()})),this.editor.$link.addEventListener("change",(()=>{const t=this.editor.$link.value.trim();t&&!/^(http|https):\/\//.test(t)&&(this.editor.$link.value=`https://${t}`,this.ctx.user.update({link:this.editor.$link.value}))}))}fetchUserInfo(){this.ctx.user.logout(),this.queryUserInfo.timeout&&window.clearTimeout(this.queryUserInfo.timeout),this.queryUserInfo.abortFunc&&this.queryUserInfo.abortFunc(),this.queryUserInfo.timeout=window.setTimeout((()=>{this.queryUserInfo.timeout=null;const{req:t,abort:e}=this.ctx.getApi().user.userGet(this.ctx.user.data.nick,this.ctx.user.data.email);this.queryUserInfo.abortFunc=e,t.then((t=>{var e;t.is_login||this.ctx.user.logout(),this.ctx.updateNotifies(t.unread),this.ctx.user.checkHasBasicUserInfo()&&!t.is_login&&(null==(e=t.user)?void 0:e.is_admin)&&this.showLoginDialog(),t.user&&t.user.link&&(this.editor.$link.value=t.user.link,this.ctx.user.update({link:t.user.link}))})).catch((()=>{})).finally((()=>{this.queryUserInfo.abortFunc=null}))}),400)}showLoginDialog(){this.ctx.checkAdmin({onSuccess:()=>{}})}}__publicField(Pt,"Name","headerInput");class Rt extends a{constructor(t){super(t),__publicField(this,"$header"),__publicField(this,"$nick"),__publicField(this,"$email"),__publicField(this,"$link"),__publicField(this,"$textareaWrap"),__publicField(this,"$textarea"),__publicField(this,"$bottom"),__publicField(this,"$submitBtn"),__publicField(this,"$notifyWrap"),__publicField(this,"isTraveling",!1),__publicField(this,"replyComment",null),__publicField(this,"$sendReply",null),__publicField(this,"editComment",null),__publicField(this,"$editCancelBtn",null),__publicField(this,"ENABLED_PLUGS",[Bt,Ot,Mt,Pt]),__publicField(this,"plugList",{}),__publicField(this,"openedPlugName",null),__publicField(this,"$plugPanelWrap"),__publicField(this,"$plugBtnWrap"),this.$el=U('<div class="atk-main-editor">\n <div class="atk-header">\n <input name="nick" class="atk-nick" type="text" required="required">\n <input name="email" class="atk-email" type="email" required="required">\n <input name="link" class="atk-link" type="url">\n </div>\n <div class="atk-textarea-wrap">\n <textarea class="atk-textarea"></textarea>\n </div>\n <div class="atk-plug-panel-wrap" style="display: none;"></div>\n <div class="atk-bottom">\n <div class="atk-item atk-plug-btn-wrap"></div>\n <div class="atk-item">\n <button type="button" class="atk-send-btn"></button>\n </div>\n </div>\n <div class="atk-notify-wrap"></div>\n</div>\n'),this.$header=this.$el.querySelector(".atk-header"),this.$nick=this.$header.querySelector('[name="nick"]'),this.$email=this.$header.querySelector('[name="email"]'),this.$link=this.$header.querySelector('[name="link"]'),this.$textareaWrap=this.$el.querySelector(".atk-textarea-wrap"),this.$textarea=this.$el.querySelector(".atk-textarea"),this.$bottom=this.$el.querySelector(".atk-bottom"),this.$submitBtn=this.$el.querySelector(".atk-send-btn"),this.$notifyWrap=this.$el.querySelector(".atk-notify-wrap"),this.$plugBtnWrap=this.$el.querySelector(".atk-plug-btn-wrap"),this.$plugPanelWrap=this.$el.querySelector(".atk-plug-panel-wrap"),this.initLocalStorage(),this.initHeader(),this.initTextarea(),this.initPlugs(),this.initSubmitBtn(),this.ctx.on("conf-updated",(()=>{}))}get user(){return this.ctx.user}get $inputs(){return{nick:this.$nick,email:this.$email,link:this.$link}}get isReplyMode(){return null!==this.replyComment}get isEditMode(){return null!==this.editComment}initLocalStorage(){const t=window.localStorage.getItem("ArtalkContent")||"";""!==t.trim()&&(this.showNotify(this.$t("restoredMsg"),"i"),this.setContent(t)),this.$textarea.addEventListener("input",(()=>this.saveToLocalStorage()))}saveToLocalStorage(){window.localStorage.setItem("ArtalkContent",this.getContentOriginal().trim())}initHeader(){Object.entries(this.$inputs).forEach((([t,e])=>{e.value=this.user.data[t]||"",e.addEventListener("input",(()=>this.onHeaderInput(t,e))),e.placeholder=`${this.$t(t)}`}))}onHeaderInput(t,e){this.isEditMode||(this.user.update({[t]:e.value.trim()}),Object.entries(this.plugList).forEach((([i,n])=>{n.onHeaderInput&&n.onHeaderInput(t,e)})))}initTextarea(){this.$textarea.placeholder=this.ctx.conf.placeholder||this.$t("placeholder"),this.$textarea.addEventListener("keydown",(t=>{9===(t.keyCode||t.which)&&(t.preventDefault(),this.insertContent("\t"))})),this.$textarea.addEventListener("input",(()=>{this.adjustTextareaHeight()}))}refreshSendBtnText(){this.isEditMode?this.$submitBtn.innerText=this.$t("save"):this.$submitBtn.innerText=this.ctx.conf.sendBtn||this.$t("send")}initSubmitBtn(){this.refreshSendBtnText(),this.$submitBtn.addEventListener("click",(()=>this.submit()))}getFinalContent(){let t=this.getContentOriginal();return this.plugList.emoticons&&(t=this.plugList.emoticons.transEmoticonImageText(t)),t}getContentOriginal(){return this.$textarea.value||""}getContentMarked(){return K(this.ctx,this.getFinalContent())}setContent(t){this.$textarea.value=t,this.saveToLocalStorage(),this.plugList.preview&&this.plugList.preview.updateContent(),window.setTimeout((()=>{this.adjustTextareaHeight()}),80)}insertContent(t){if(document.selection)this.$textarea.focus(),document.selection.createRange().text=t,this.$textarea.focus();else if(this.$textarea.selectionStart||0===this.$textarea.selectionStart){const e=this.$textarea.selectionStart,i=this.$textarea.selectionEnd,n=this.$textarea.scrollTop;this.setContent(this.$textarea.value.substring(0,e)+t+this.$textarea.value.substring(i,this.$textarea.value.length)),this.$textarea.focus(),this.$textarea.selectionStart=e+t.length,this.$textarea.selectionEnd=e+t.length,this.$textarea.scrollTop=n}else this.$textarea.focus(),this.$textarea.value+=t}adjustTextareaHeight(){const t=this.$textarea.offsetHeight-this.$textarea.clientHeight;this.$textarea.style.height="0px",this.$textarea.style.height=`${this.$textarea.scrollHeight+t}px`}setReply(t,e,i=!0){this.isEditMode&&this.cancelEditComment(),this.isReplyMode&&this.cancelReply(),null===this.$sendReply&&(this.$sendReply=U(`<div class="atk-send-reply">${this.$t("reply")} <span class="atk-text"></span><span class="atk-cancel">×</span></div>`),this.$sendReply.querySelector(".atk-text").innerText=`@${t.nick}`,this.$sendReply.addEventListener("click",(()=>{this.cancelReply()})),this.$textareaWrap.append(this.$sendReply)),this.replyComment=t,!0===this.ctx.conf.editorTravel&&this.travel(e),i&&it(this.$el),this.$textarea.focus()}cancelReply(){null!==this.$sendReply&&(this.$sendReply.remove(),this.$sendReply=null),this.replyComment=null,!0===this.ctx.conf.editorTravel&&this.travelBack()}setEditComment(t,e){this.isEditMode&&this.cancelEditComment(),this.isReplyMode&&this.cancelReply(),null===this.$editCancelBtn&&(this.$editCancelBtn=U(`<div class="atk-send-reply">${this.$t("editCancel")}<span class="atk-cancel">×</span></div>`),this.$editCancelBtn.onclick=()=>{this.cancelEditComment()},this.$textareaWrap.append(this.$editCancelBtn)),this.editComment=t,this.$header.style.display="none",this.travel(e),this.$nick.value=t.nick,this.$email.value=t.email||"",this.$link.value=t.link,this.setContent(t.content),this.$textarea.focus(),this.refreshSendBtnText()}cancelEditComment(){null!==this.$editCancelBtn&&(this.$editCancelBtn.remove(),this.$editCancelBtn=null),this.editComment=null,this.travelBack(),this.$nick.value=this.user.data.nick,this.$email.value=this.user.data.email,this.$link.value=this.user.data.link,this.setContent(""),this.refreshSendBtnText(),this.$header.style.display=""}showNotify(t,e){nt(this.$notifyWrap,t,e)}showLoading(){tt(this.$el)}hideLoading(){et(this.$el)}submit(){return __async(this,null,(function*(){""!==this.getFinalContent().trim()?(this.ctx.trigger("editor-submit"),this.showLoading(),this.isEditMode?yield this.submitEdit():yield this.submitAdd(),this.hideLoading()):this.$textarea.focus()}))}submitAdd(){return __async(this,null,(function*(){try{const t=yield this.ctx.getApi().comment.add({content:this.getFinalContent(),nick:this.user.data.nick,email:this.user.data.email,link:this.user.data.link,rid:null===this.replyComment?0:this.replyComment.id,page_key:null===this.replyComment?this.ctx.conf.pageKey:this.replyComment.page_key,page_title:null===this.replyComment?this.ctx.conf.pageTitle:void 0,site_name:null===this.replyComment?this.ctx.conf.site:this.replyComment.site_name});null!==this.replyComment&&this.replyComment.page_key!==this.ctx.conf.pageKey&&window.open(`${this.replyComment.page_url}#atk-comment-${t.id}`),this.ctx.insertComment(t),this.setContent(""),this.cancelReply(),this.ctx.trigger("editor-submitted")}catch(t){console.error(t),this.showNotify(`${this.$t("commentFail")},${t.msg||String(t)}`,"e")}}))}submitEdit(){return __async(this,null,(function*(){try{const t={content:this.getFinalContent(),nick:this.$nick.value,email:this.$email.value,link:this.$link.value},e=yield this.ctx.getApi().comment.commentEdit(__spreadValues(__spreadValues({},this.editComment),t));this.ctx.updateComment(e),this.setContent(""),this.cancelEditComment(),this.ctx.trigger("editor-submitted")}catch(t){console.error(t),this.showNotify(`${this.$t("commentFail")},${t.msg||String(t)}`,"e")}}))}close(){this.$textareaWrap.querySelector(".atk-comment-closed")||this.$textareaWrap.prepend(U(`<div class="atk-comment-closed">${this.$t("onlyAdminCanReply")}</div>`)),this.user.data.isAdmin?(this.$textarea.style.display="",this.$bottom.style.display=""):(this.$textarea.style.display="none",this.closePlugPanel(),this.$bottom.style.display="none")}open(){var t;null==(t=this.$textareaWrap.querySelector(".atk-comment-closed"))||t.remove(),this.$textarea.style.display="",this.$bottom.style.display=""}travel(t){if(this.isTraveling)return;this.isTraveling=!0,this.$el.after(U('<div class="atk-editor-travel-placeholder"></div>'));const e=U("<div></div>");t.after(e),e.replaceWith(this.$el),this.$el.classList.add("atk-fade-in")}travelBack(){var t;this.isTraveling&&(this.isTraveling=!1,null==(t=this.ctx.$root.querySelector(".atk-editor-travel-placeholder"))||t.replaceWith(this.$el),null!==this.replyComment&&this.cancelReply())}initPlugs(){this.plugList={},this.$plugPanelWrap.innerHTML="",this.$plugPanelWrap.style.display="none",this.openedPlugName=null,this.$plugBtnWrap.innerHTML="";const t=[];this.conf.emoticons||t.push("emoticons"),this.conf.preview||t.push("preview"),this.ENABLED_PLUGS.forEach((e=>{const i=e.Name;if(t.includes(i))return;const n=new e(this);this.plugList[i]=n;const s=n.getBtn();if(s){this.$plugBtnWrap.appendChild(s),s.onclick=s.onclick||(()=>{this.$plugBtnWrap.querySelectorAll(".active").forEach((t=>t.classList.remove("active"))),i!==this.openedPlugName?(this.openPlugPanel(i),s.classList.add("active")):this.closePlugPanel()});const t=n.getPanel();t&&(t.setAttribute("data-plug-name",i),t.style.display="none",this.$plugPanelWrap.appendChild(t))}}))}openPlugPanel(t){Object.entries(this.plugList).forEach((([e,i])=>{const n=i.getPanel();n&&(e===t?(n.style.display="",i.onPanelShow&&i.onPanelShow()):(n.style.display="none",i.onPanelHide&&i.onPanelHide()))})),this.$plugPanelWrap.style.display="",this.openedPlugName=t}closePlugPanel(){if(!this.openedPlugName)return;const t=this.plugList[this.openedPlugName];t&&(t.onPanelHide&&t.onPanelHide(),this.$plugPanelWrap.style.display="none",this.openedPlugName=null)}}class Dt extends a{constructor(t){super(t),__publicField(this,"layer"),__publicField(this,"$header"),__publicField(this,"$closeBtn"),__publicField(this,"$iframeWrap"),__publicField(this,"$iframe"),__publicField(this,"firstShow",!0),this.$el=U('<div class="atk-sidebar-layer">\n <div class="atk-sidebar-inner">\n <div class="atk-sidebar-header">\n <div class="atk-sidebar-close"><i class="atk-icon atk-icon-close"></i></div>\n </div>\n <div class="atk-sidebar-iframe-wrap"></div>\n </div>\n</div>\n'),this.$header=this.$el.querySelector(".atk-sidebar-header"),this.$closeBtn=this.$header.querySelector(".atk-sidebar-close"),this.$iframeWrap=this.$el.querySelector(".atk-sidebar-iframe-wrap"),this.$closeBtn.onclick=()=>{this.hide()},this.ctx.on("user-changed",(()=>{this.firstShow=!0}))}show(){return __async(this,arguments,(function*(t={}){if(this.$el.style.transform="",null==this.layer&&(this.layer=new ot(this.ctx,"sidebar",this.$el),this.layer.afterHide=()=>{!0===this.ctx.conf.editorTravel&&this.ctx.editorTravelBack()}),this.layer.show(),setTimeout((()=>{this.$el.style.transform="translate(0, 0)"}),20),(()=>{__async(this,null,(function*(){var e;const i=yield this.ctx.getApi().user.loginStatus();i.is_admin&&!i.is_login&&(null==(e=this.layer)||e.hide(),this.firstShow=!0,this.ctx.checkAdmin({onSuccess:()=>{setTimeout((()=>{this.show(t)}),500)},onCancel:()=>{}}))}))})(),this.ctx.updateNotifies([]),this.firstShow){this.$iframeWrap.innerHTML="",this.$iframe=U("<iframe></iframe>");const e=J(this.ctx,"/sidebar/"),i={pageKey:this.conf.pageKey,site:this.conf.site||"",user:JSON.stringify(this.ctx.user.data),time:+new Date};t.view&&(i.view=t.view),this.conf.darkMode&&(i.darkMode="1");const n=new URLSearchParams(i);this.iframeLoad(`${e}?${n.toString()}`),this.$iframeWrap.append(this.$iframe),this.firstShow=!1}else{const t=this.$iframe.src.includes("darkMode=1");this.conf.darkMode&&!t&&this.iframeLoad(`${this.$iframe.src}&darkMode=1`),!this.conf.darkMode&&t&&this.iframeLoad(this.$iframe.src.replace("&darkMode=1",""))}this.ctx.trigger("sidebar-show")}))}hide(){var t;this.$el.style.transform="",null==(t=this.layer)||t.hide(),this.ctx.trigger("sidebar-hide")}iframeLoad(t){this.$iframe&&(this.$iframe.src=t,tt(this.$iframeWrap),this.$iframe.onload=()=>{et(this.$iframeWrap)})}}function It(t){return __async(this,null,(function*(){const e=t.ctx.conf.countEl;e&&document.querySelector(e)&&qt(t,{api:"page_comment",countEl:e});const i=t.pvAdd?yield t.ctx.getApi().page.pv():void 0,n=t.ctx.conf.pvEl;n&&document.querySelector(n)&&qt(t,{api:"page_pv",countEl:n,curtPageCount:i})}))}function qt(t,e){return __async(this,null,(function*(){let i={};const n=t.ctx.conf.pageKey;e.curtPageCount&&(i[n]=e.curtPageCount);let s=Array.from(document.querySelectorAll(e.countEl)).map((t=>t.getAttribute("data-page-key")||n)).filter((t=>void 0===i[t]));if(s=[...new Set(s)],s.length>0){const n=yield t.ctx.getApi().page.stat(e.api,s);i=__spreadValues(__spreadValues({},i),n)}document.querySelectorAll(e.countEl).forEach((t=>{const e=t.getAttribute("data-page-key")||n;t.innerHTML=`${Number(i[e]||0)}`}))}))}const Wt=class{constructor(t){if(__publicField(this,"conf"),__publicField(this,"ctx"),__publicField(this,"$root"),__publicField(this,"instancePlugins",[]),this.conf=Wt.HandelBaseConf(t),this.conf.el instanceof HTMLElement&&(this.$root=this.conf.el),this.ctx=new Ct(this.conf,this.$root),this.conf.useBackendConf)return this.loadConfRemoteAndInitComponents();this.initComponents()}initComponents(){this.initLocale(),this.initLayer(),this.initDarkMode(),function(e){try{if(!t.marked.name)return}catch(a){return}const i=new t.marked.Renderer,n=i.link;i.link=(t,e,s)=>{const a=null==t?void 0:t.startsWith(`${window.location.protocol}//${window.location.hostname}`);return n.call(i,t,e,s).replace(/^<a /,`<a target="_blank" ${a?"":'rel="noreferrer noopener nofollow"'} `)},i.code=(t,e)=>{const i=e||"plaintext";let n=t;return window.hljs?i&&window.hljs.getLanguage(i)&&(n=window.hljs.highlight(i,t).value):n=N(t),`<pre rel="${i}">\n<code class="hljs language-${i}">${n.replace(/&amp;/g,"&")}</code>\n</pre>`};const s=t.marked;t.marked.setOptions({renderer:i,pedantic:!1,gfm:!0,breaks:!0,smartLists:!0,smartypants:!0,xhtml:!1,sanitize:!1,silent:!0}),e.markedInstance=s}(this.ctx);const e={checkerLauncher:()=>{const t=new At(this.ctx);this.ctx.setCheckerLauncher(t)},editor:()=>{const t=new Rt(this.ctx);this.ctx.setEditor(t),this.$root.appendChild(t.$el)},list:()=>{const t=new wt(this.ctx);this.ctx.setList(t),this.$root.appendChild(t.$el),t.fetchComments(0)},sidebarLayer:()=>{const t=new Dt(this.ctx);this.ctx.setSidebarLayer(t),this.$root.appendChild(t.$el)},eventsDefault:()=>{this.initEventBind()}};Object.entries(e).forEach((([t,e])=>{Wt.DisabledComponents.includes(t)||e()})),Wt.Plugins.forEach((t=>{"function"==typeof t&&t(this.ctx)}))}static HandelBaseConf(t){const e=Z(Wt.defaults,t);if("string"==typeof e.el&&e.el)try{const t=document.querySelector(e.el);if(!t)throw Error(`Target element "${e.el}" was not found.`);e.el=t}catch(i){throw console.error(i),new Error("Please check your Artalk `el` config.")}return e.server=e.server.replace(/\/$/,"").replace(/\/api\/?$/,""),e.pageKey||(e.pageKey=`${window.location.pathname}`),e.pageTitle||(e.pageTitle=`${document.title}`),e}loadConfRemoteAndInitComponents(){return __async(this,null,(function*(){return yield this.loadConfRemote(),this.initComponents(),this}))}loadConfRemote(){return __async(this,null,(function*(){tt(this.$root);let t={};try{t=yield this.ctx.getApi().system.conf()}catch(e){console.error("Load config from remote err",e)}this.ctx.conf=Z(this.ctx.conf,t),et(this.$root)}))}initEventBind(){window.addEventListener("hashchange",(()=>{this.ctx.listHashGotoCheck()})),this.ctx.on("user-changed",(()=>{this.ctx.checkAdminShowEl(),this.ctx.listRefreshUI()}))}initLocale(){"auto"===this.conf.locale&&(this.conf.locale=navigator.language)}initLayer(){ot.BodyOrgOverflow=document.body.style.overflow,ot.BodyOrgPaddingRight=document.body.style.paddingRight}initDarkMode(){if("auto"===this.conf.darkMode){const t=window.matchMedia("(prefers-color-scheme: dark)");t.addEventListener("change",(t=>{this.setDarkMode(t.matches)})),this.setDarkMode(t.matches)}else this.setDarkMode(this.conf.darkMode||!1)}on(t,e){this.ctx.on(t,e,"external")}off(t,e){this.ctx.off(t,e,"external")}trigger(t,e){this.ctx.trigger(t,e,"external")}reload(){this.ctx.listReload()}setDarkMode(t){this.ctx.setDarkMode(t)}use(t){this.instancePlugins.push(t),"function"==typeof t&&t(this.ctx)}static use(t){this.Plugins.push(t)}static Use(t){this.use(t),console.warn("`Use(...)` is deprecated, replace it with lowercase `use(...)`.")}static LoadCountWidget(t){const e=this.HandelBaseConf(t);It({ctx:new Ct(e),pvAdd:!1})}};let Nt=Wt;return __publicField(Nt,"ListLite",xt),__publicField(Nt,"defaults",St),__publicField(Nt,"Plugins",[t=>{It({ctx:t,pvAdd:!0})}]),__publicField(Nt,"DisabledComponents",[]),Nt}(marked);
1
+ var __defProp=Object.defineProperty,__defProps=Object.defineProperties,__getOwnPropDescs=Object.getOwnPropertyDescriptors,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=(t,e,i)=>e in t?__defProp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,__spreadValues=(t,e)=>{for(var i in e||(e={}))__hasOwnProp.call(e,i)&&__defNormalProp(t,i,e[i]);if(__getOwnPropSymbols)for(var i of __getOwnPropSymbols(e))__propIsEnum.call(e,i)&&__defNormalProp(t,i,e[i]);return t},__spreadProps=(t,e)=>__defProps(t,__getOwnPropDescs(e)),__publicField=(t,e,i)=>(__defNormalProp(t,"symbol"!=typeof e?e+"":e,i),i),__async=(t,e,i)=>new Promise(((n,s)=>{var a=t=>{try{o(i.next(t))}catch(e){s(e)}},r=t=>{try{o(i.throw(t))}catch(e){s(e)}},o=t=>t.done?n(t.value):Promise.resolve(t.value).then(a,r);o((i=i.apply(t,e)).next())})),Artalk=function(t){"use strict";const e={placeholder:"Leave a comment",noComment:"No Comment",send:"Send",save:"Save",nick:"Nickname",email:"Email",link:"Website",emoticon:"Emoji",preview:"Preview",image:"Image",uploadFail:"Upload Failed",commentFail:"Failed to comment",restoredMsg:"Content has been restored",onlyAdminCanReply:"Only admin can reply",uploadLoginMsg:"Please fill in your name and email to upload",counter:"{count} Comments",sortLatest:"Latest",sortOldest:"Oldest",sortBest:"Best",sortAuthor:"Author",openComment:"Open Comment",closeComment:"Close Comment",listLoadFailMsg:"Failed to load comments",listRetry:"Click to retry",loadMore:"Load More",admin:"Admin",reply:"Reply",voteUp:"Up",voteDown:"Down",voteFail:"Vote Failed",readMore:"Read More",actionConfirm:"Confirm",collapse:"Collapse",collapsed:"Collapsed",collapsedMsg:"This comment has been collapsed",expand:"Expand",approved:"Approved",pending:"Pending",pendingMsg:"Pending, visible only to commenter.",edit:"Edit",editCancel:"Cancel Edit",delete:"Delete",deleteConfirm:"Confirm",pin:"Pin",unpin:"Unpin",seconds:"seconds ago",minutes:"minutes ago",hours:"hours ago",days:"days ago",now:"just now",adminCheck:"Enter admin password:",captchaCheck:"Enter the CAPTCHA to continue:",confirm:"Confirm",cancel:"Cancel",msgCenter:"Messages",ctrlCenter:"Admin",frontend:"Frontend",backend:"Backend",loading:"Loading",loadFail:"Load Failed",editing:"Editing",editFail:"Edit Failed",deleting:"Deleting",deleteFail:"Delete Failed",reqGot:"Request got",reqAborted:"Request timed out or terminated unexpectedly"},i={en:e,"en-US":e,"zh-CN":{placeholder:"键入内容...",noComment:"「此时无声胜有声」",send:"发送评论",save:"保存评论",nick:"昵称",email:"邮箱",link:"网址",emoticon:"表情",preview:"预览",image:"图片",uploadFail:"上传失败",commentFail:"评论失败",restoredMsg:"内容已自动恢复",onlyAdminCanReply:"仅管理员可评论",uploadLoginMsg:"填入你的名字邮箱才能上传哦",counter:"{count} 条评论",sortLatest:"最新",sortOldest:"最早",sortBest:"最热",sortAuthor:"作者",openComment:"打开评论",closeComment:"关闭评论",listLoadFailMsg:"无法获取评论列表数据",listRetry:"点击重新获取",loadMore:"加载更多",admin:"管理员",reply:"回复",voteUp:"赞同",voteDown:"反对",voteFail:"投票失败",readMore:"阅读更多",actionConfirm:"确认操作",collapse:"折叠",collapsed:"已折叠",collapsedMsg:"该评论已被系统或管理员折叠",expand:"展开",approved:"已审",pending:"待审",pendingMsg:"审核中,仅本人可见。",edit:"编辑",editCancel:"取消编辑",delete:"删除",deleteConfirm:"确认删除",pin:"置顶",unpin:"取消置顶",seconds:"秒前",minutes:"分钟前",hours:"小时前",days:"天前",now:"刚刚",adminCheck:"键入密码来验证管理员身份:",captchaCheck:"键入验证码继续:",confirm:"确认",cancel:"取消",msgCenter:"通知中心",ctrlCenter:"控制中心",frontend:"前端",backend:"后端",loading:"加载中",loadFail:"加载失败",editing:"修改中",editFail:"修改失败",deleting:"删除中",deleteFail:"删除失败",reqGot:"请求响应",reqAborted:"请求超时或意外终止"}};function n(t,e,n={}){var s;"string"==typeof t&&(s=(s=t).replace(/^([a-zA-Z]+)(-[a-zA-Z]+)?$/,((t,e,i)=>e.toLowerCase()+(i||"").toUpperCase())),t=i[s]?i[s]:window.ArtalkI18n&&window.ArtalkI18n[s]?window.ArtalkI18n[s]:i.en);let a=(null==t?void 0:t[e])||e;return a=a.replace(/\{\s*(\w+?)\s*\}/g,((t,e)=>n[e]||"")),a}class s{constructor(t){__publicField(this,"ctx"),__publicField(this,"data"),this.ctx=t;const e=JSON.parse(window.localStorage.getItem("ArtalkUser")||"{}");this.data={nick:e.nick||"",email:e.email||"",link:e.link||"",token:e.token||"",isAdmin:e.isAdmin||!1}}update(t={}){Object.entries(t).forEach((([t,e])=>{this.data[t]=e})),window.localStorage.setItem("ArtalkUser",JSON.stringify(this.data)),this.ctx.trigger("user-changed",this.ctx.user.data)}logout(){this.update({token:"",isAdmin:!1})}checkHasBasicUserInfo(){return!!this.data.nick&&!!this.data.email}}var a="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},r={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},o={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},l=/(&amp;|&lt;|&gt;|&quot;|&#39;)/g,c=/[&<>"']/g;function d(t){return r[t]}function h(t){return o[t]}function u(t){return null==t?"":String(t).replace(c,d)}function p(t){return null==t?"":String(t).replace(l,h)}u.options=p.options={};var m={encode:u,escape:u,decode:p,unescape:p,version:"1.0.0-browser"};var g=function t(e){for(var i,n,s=Array.prototype.slice.call(arguments,1);s.length;)for(n in i=s.shift())i.hasOwnProperty(n)&&("[object Object]"===Object.prototype.toString.call(e[n])?e[n]=t(e[n],i[n]):e[n]=i[n]);return e},f=function(t){return"string"==typeof t?t.toLowerCase():t};function y(t,e){return t[e]=!0,t}var $=function(t){return t.reduce(y,{})},_={uris:$(["background","base","cite","href","longdesc","src","usemap"])},v={voids:$(["area","br","col","hr","img","wbr","input","base","basefont","link","meta"])},k=m,b=f,x=v,w=/^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/,C=/^<\s*\/\s*([\w:-]+)[^>]*>/,S=/([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,L=/^</,T=/^<\s*\//;var E=m,A=f,F=_,M=v;var O=g,B=function(t,e){for(var i,n=function(){var t=[];return t.lastItem=function(){return t[t.length-1]},t}(),s=t;t;)a();function a(){i=!0,function(){"\x3c!--"===t.substr(0,4)?(n=t.indexOf("--\x3e"))>=0&&(e.comment&&e.comment(t.substring(4,n)),t=t.substring(n+3),i=!1):T.test(t)?r(C,l):L.test(t)&&r(w,o);var n;!function(){if(!i)return;var n,s=t.indexOf("<");s>=0?(n=t.substring(0,s),t=t.substring(s)):(n=t,t="");e.chars&&e.chars(n)}()}();var n=t===s;s=t,n&&(t="")}function r(e,n){var s=t.match(e);s&&(t=t.substring(s[0].length),s[0].replace(e,n),i=!1)}function o(t,i,s,a){var r={},o=b(i),l=x.voids[o]||!!a;s.replace(S,(function(t,e,i,n,s){r[e]=void 0===i&&void 0===n&&void 0===s?void 0:k.decode(i||n||s||"")})),l||n.push(o),e.start&&e.start(o,r,l)}function l(t,i){var s,a=0,r=b(i);if(r)for(a=n.length-1;a>=0&&n[a]!==r;a--);if(a>=0){for(s=n.length-1;s>=a;s--)e.end&&e.end(n[s]);n.length=a}}l()},P=function(t,e){var i,n=e||{};return o(),{start:function(t,e,r){var o=A(t);if(i.ignoring)return void a(o);if(-1===(n.allowedTags||[]).indexOf(o))return void a(o);if(n.filter&&!n.filter({tag:o,attrs:e}))return void a(o);s("<"),s(o),Object.keys(e).forEach((function(t){var i=e[t],a=(n.allowedClasses||{})[o]||[],r=(n.allowedAttributes||{})[o]||[],l=A(t);("class"===l&&-1===r.indexOf(l)?(i=i.split(" ").filter((function(t){return a&&-1!==a.indexOf(t)})).join(" ").trim()).length:-1!==r.indexOf(l)&&(!0!==F.uris[l]||function(t){var e=t[0];if("#"===e||"/"===e)return!0;var i=t.indexOf(":");if(-1===i)return!0;var s=t.indexOf("?");if(-1!==s&&i>s)return!0;var a=t.indexOf("#");return-1!==a&&i>a||n.allowedSchemes.some(r);function r(e){return 0===t.indexOf(e+":")}}(i)))&&(s(" "),s(t),"string"==typeof i&&(s('="'),s(E.encode(i)),s('"')))})),s(r?"/>":">")},end:function(t){var e=A(t);-1!==(n.allowedTags||[]).indexOf(e)&&!1===i.ignoring?(s("</"),s(e),s(">")):r(e)},chars:function(t){!1===i.ignoring&&s(n.transformText?n.transformText(t):t)}};function s(e){t.push(e)}function a(t){M.voids[t]||(!1===i.ignoring?i={ignoring:t,depth:1}:i.ignoring===t&&i.depth++)}function r(t){i.ignoring===t&&--i.depth<=0&&o()}function o(){i={ignoring:!1,depth:0}}},R={allowedAttributes:{a:["href","name","target","title","aria-label"],iframe:["allowfullscreen","frameborder","src"],img:["src","alt","title","aria-label"]},allowedClasses:{},allowedSchemes:["http","https","mailto"],allowedTags:["a","abbr","article","b","blockquote","br","caption","code","del","details","div","em","h1","h2","h3","h4","h5","h6","hr","i","img","ins","kbd","li","main","mark","ol","p","pre","section","span","strike","strong","sub","summary","sup","table","tbody","td","th","thead","tr","u","ul"],filter:null};function D(t,e,i){var n=[],s=!0===i?e:O({},R,e),a=P(n,s);return B(t,a),n.join("")}D.defaults=R;var q=D,I={exports:{}};I.exports=function(){function t(t,e){return t(e={exports:{}},e.exports),e.exports}var e=t((function(t){var e=t.exports=function(){return new RegExp("(?:"+e.line().source+")|(?:"+e.block().source+")","gm")};e.line=function(){return/(?:^|\s)\/\/(.+?)$/gm},e.block=function(){return/\/\*([\S\s]*?)\*\//gm}})),i=["23AC69","91C132","F19726","E8552D","1AAB8E","E1147F","2980C1","1BA1E6","9FA0A0","F19726","E30B20","E30B20","A3338B"];function n(t){return'<span style="color: slategray">'+t+"</span>"}return function(t,s){void 0===s&&(s={});var a=s.colors;void 0===a&&(a=i);var r=0,o={},l=new RegExp("("+/[\u4E00-\u9FFF\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\uac00-\ud7af\u0400-\u04FF]+|\w+/.source+"|"+/</.source+")|("+e().source+")","gmi");return t.replace(l,(function(t,e,i){if(i)return n(i);if("<"===e)return"&lt;";var s;o[e]?s=o[e]:(s=a[r],o[e]=s);var l='<span style="color: #'+s+'">'+e+"</span>";return r=++r%a.length,l}))}}();const W=I.exports;function N(t=""){const e=document.createElement("div");return e.innerHTML=t.trim(),e.firstElementChild||e}function U(t){return parseFloat(getComputedStyle(t,null).height.replace("px",""))}function H(t){const e=RegExp(`[?&]${t}=([^&]*)`).exec(window.location.search);return e&&decodeURIComponent(e[1].replace(/\+/g," "))}function j(t){const e=t.getBoundingClientRect();return{top:e.top+window.scrollY,left:e.left+window.scrollX}}function V(t,e){let i=t.toString();for(;i.length<e;)i=`0${i}`;return i}function z(t,e){try{const i=t.getTime(),n=(new Date).getTime()-i,s=Math.floor(n/864e5);if(0===s){const t=n%864e5,i=Math.floor(t/36e5);if(0===i){const i=t%36e5,n=Math.floor(i/6e4);if(0===n){const t=i%6e4;return`${Math.round(t/1e3)} ${e.$t("seconds")}`}return`${n} ${e.$t("minutes")}`}return`${i} ${e.$t("hours")}`}return s<0?e.$t("now"):s<8?`${s} ${e.$t("days")}`:function(t){const e=V(t.getDate(),2),i=V(t.getMonth()+1,2);return`${V(t.getFullYear(),2)}-${i}-${e}`}(t)}catch(i){return console.error(i)," - "}}function G(t,e){if(!t)return;const i=t.getElementsByTagName("img");if(!i.length)return;let n=i.length;for(let s=0;s<i.length;s++)i[s].complete?n--:i[s].addEventListener("load",(()=>{n--,0===n&&e()})),0===n&&e()}function Q(t,e){var i;let n=null==(i=t.markedInstance)?void 0:i.parse(e);n||(n=e.replace(/```\s*([^]+?.*?[^]+?[^]+?)```/g,((t,e)=>`<pre><code>${W(e)}</code></pre>`)).replace(/!\[(.*?)\]\((.*?)\)/g,((t,e,i)=>`<img src="${i}" alt="${e}" />`)).replace(/\[(.*?)\]\((.*?)\)/g,((t,e,i)=>`<a href="${i}" target="_blank">${e}</a>`)).replace(/\n/g,"<br>"));let s=q(n,{allowedClasses:{},allowedSchemes:["http","https","mailto","data"],allowedTags:["a","abbr","article","b","blockquote","br","caption","code","del","details","div","em","h1","h2","h3","h4","h5","h6","hr","i","img","ins","kbd","li","main","mark","ol","p","pre","section","span","strike","strong","sub","summary","sup","table","tbody","td","th","thead","tr","u","ul"],allowedAttributes:{"*":["title","accesskey"],a:["href","name","target","aria-label","rel"],img:["src","alt","title","atk-emoticon","aria-label"],code:["class"],span:["class","style"]},filter:t=>([["code",/^hljs\W+language-(.*)$/],["span",/^(hljs-.*)$/]].forEach((([e,i])=>{t.tag===e&&t.attrs.class&&!i.test(t.attrs.class)&&delete t.attrs.class})),"span"===t.tag&&t.attrs.style&&!/^color:(\W+)?#[0-9a-f]{3,6};?$/i.test(t.attrs.style)&&delete t.attrs.style,!0)});return t.markedReplacers.forEach((t=>{"function"==typeof t&&(s=t(s))})),s}function K(){return __async(this,null,(function*(){const t=navigator.userAgent;if(!navigator.userAgentData||!navigator.userAgentData.getHighEntropyValues)return t;const e=navigator.userAgentData;let i=null;try{i=yield e.getHighEntropyValues(["platformVersion"])}catch(s){return console.error(s),t}const n=Number(i.platformVersion.split(".")[0]);return"Windows"===e.platform&&n>=13?t.replace(/Windows NT 10.0/,"Windows NT 11.0"):"macOS"===e.platform&&n>=11?t.replace(/(Mac OS X \d+_\d+_\d+|Mac OS X)/,`Mac OS X ${i.platformVersion.replace(/\./g,"_")}`):t}))}function Y(t){let e;try{e=new URL(t)}catch(i){return!1}return"http:"===e.protocol||"https:"===e.protocol}function X(t,e){return function(t,e){return`${t.replace(/\/$/,"")}/${e.replace(/^\//,"")}`}(t.conf.server,e)}function J(t,e){const i=t=>t&&"object"==typeof t;return i(t)&&i(e)?(Object.keys(e).forEach((n=>{const s=t[n],a=e[n];Array.isArray(s)&&Array.isArray(a)?t[n]=s.concat(a):i(s)&&i(a)?t[n]=J(__spreadValues({},s),a):t[n]=a})),t):e}class Z{constructor(t){__publicField(this,"$el"),__publicField(this,"ctx"),__publicField(this,"conf"),this.ctx=t,this.conf=t.conf}$t(t,e={}){return this.ctx.$t(t,e)}}function tt(t,e){let i=t.querySelector(":scope > .atk-loading");i||(i=N('<div class="atk-loading atk-fade-in" style="display: none;">\n <div class="atk-loading-spinner">\n <svg viewBox="25 25 50 50"><circle cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10"></circle></svg>\n </div>\n </div>'),(null==e?void 0:e.transparentBg)&&(i.style.background="transparent"),t.appendChild(i)),i.style.display="";const n=i.querySelector(".atk-loading-spinner");n&&(n.style.display="none",window.setTimeout((()=>{n.style.display=""}),500))}function et(t){const e=t.querySelector(":scope > .atk-loading");e&&(e.style.display="none")}function it(t,e=!0){const i=j(t).top+U(t)/2-document.documentElement.clientHeight/2;e?window.scroll({top:i>0?i:0,left:0}):window.scroll(0,i>0?i:0)}function nt(t,e,i){const n=N(`<div class="atk-notify atk-fade-in" style="background-color: ${{s:"#57d59f",e:"#ff6f6c",w:"#ffc721",i:"#2ebcfc"}[i]}"><span class="atk-notify-content"></span></div>`);n.querySelector(".atk-notify-content").innerHTML=function(t){const e=document.createElement("div");return e.innerText=t,e.innerHTML}(e).replace("\n","<br/>"),t.appendChild(n);const s=()=>{n.classList.add("atk-fade-out"),setTimeout((()=>{n.remove()}),200)};let a;a=window.setTimeout((()=>{s()}),3e3),n.addEventListener("click",(()=>{s(),window.clearTimeout(a)}))}function st(t,e){!function(t,e,i="in"){t.classList.add(`atk-fade-${i}`);const n=()=>{t.classList.remove(`atk-fade-${i}`),t.removeEventListener("animationend",n),e&&e()};t.addEventListener("animationend",n)}(t,e,"in")}function at(t,e,i='<span class="atk-error-title">Artalk Error</span>'){let n=t.querySelector(".atk-error-layer");if(null===e)return void(null!==n&&n.remove());n||(n=N(`<div class="atk-error-layer">${i}<span class="atk-error-text"></span></div>`),t.appendChild(n));const s=n.querySelector(".atk-error-text");s.innerHTML="",null!==e&&(e instanceof HTMLElement?s.appendChild(e):s.innerText=e)}const rt=class extends Z{constructor(t,e,i){super(t),__publicField(this,"name"),__publicField(this,"$wrap"),__publicField(this,"$mask"),__publicField(this,"maskClickHideEnable",!0),__publicField(this,"afterHide"),this.name=e;const{$wrap:n,$mask:s}=lt(t);this.$wrap=n,this.$mask=s,this.$el=this.$wrap.querySelector(`[data-layer-name="${e}"].atk-layer-item`),null===this.$el&&(i?this.$el=i:(this.$el=N(),this.$el.classList.add("atk-layer-item"))),this.$el.setAttribute("data-layer-name",e),this.$el.style.display="none",this.$wrap.append(this.$el)}getName(){return this.name}getWrapEl(){return this.$wrap}getEl(){return this.$el}show(){this.fireAllActionTimer(),this.$wrap.style.display="block",this.$mask.style.display="block",this.$mask.classList.add("atk-fade-in"),this.$el.style.display="",this.$mask.onclick=()=>{this.maskClickHideEnable&&this.hide()},this.pageBodyScrollBarHide()}hide(){this.afterHide&&this.afterHide(),this.$wrap.classList.add("atk-fade-out"),this.$el.style.display="none",this.pageBodyScrollBarShow(),this.newActionTimer((()=>{this.$wrap.style.display="none",this.checkCleanLayer()}),450),this.newActionTimer((()=>{this.$wrap.style.display="none",this.$wrap.classList.remove("atk-fade-out")}),200)}setMaskClickHide(t){this.maskClickHideEnable=t}pageBodyScrollBarHide(){document.body.style.overflow="hidden";const t=parseInt(window.getComputedStyle(document.body,null).getPropertyValue("padding-right"),10);document.body.style.paddingRight=`${function(){const t=document.createElement("p");t.style.width="100%",t.style.height="200px";const e=document.createElement("div");e.style.position="absolute",e.style.top="0px",e.style.left="0px",e.style.visibility="hidden",e.style.width="200px",e.style.height="150px",e.style.overflow="hidden",e.appendChild(t),document.body.appendChild(e);const i=t.offsetWidth;e.style.overflow="scroll";let n=t.offsetWidth;return i===n&&(n=e.clientWidth),document.body.removeChild(e),i-n}()+t||0}px`}pageBodyScrollBarShow(){document.body.style.overflow=rt.BodyOrgOverflow,document.body.style.paddingRight=rt.BodyOrgPaddingRight}newActionTimer(t,e){const i=()=>{t(),rt.actionTimers=rt.actionTimers.filter((t=>t.act!==i))},n=window.setTimeout((()=>i()),e);rt.actionTimers.push({act:i,tid:n})}fireAllActionTimer(){rt.actionTimers.forEach((t=>{clearTimeout(t.tid),t.act()}))}disposeNow(){this.$el.remove(),this.pageBodyScrollBarShow(),this.checkCleanLayer()}dispose(){this.hide(),this.$el.remove(),this.checkCleanLayer()}checkCleanLayer(){0===this.getWrapEl().querySelectorAll(".atk-layer-item").length&&(this.$wrap.style.display="none")}};let ot=rt;function lt(t){let e=document.querySelector(`.atk-layer-wrap#ctx-${t.cid}`);e||(e=N(`<div class="atk-layer-wrap" id="ctx-${t.cid}" style="display: none;"><div class="atk-layer-mask"></div></div>`),document.body.appendChild(e));const i=e.querySelector(".atk-layer-mask");return{$wrap:e,$mask:i}}function ct(t,e,i,n){return __async(this,null,(function*(){var s,a;if(t.user.data.token){const e=new Headers(i.headers);e.set("Authorization",`Bearer ${t.user.data.token}`),i.headers=e}const r=yield function(t,e,i,n){var s;const a=new AbortController;null==(s=n.signal)||s.addEventListener("abort",(()=>a.abort()));let r=fetch(e,__spreadProps(__spreadValues({},n),{signal:a.signal}));if(i>0){const t=setTimeout((()=>a.abort()),i);r.finally((()=>{clearTimeout(t)}))}return r=r.catch((e=>{throw"AbortError"===(e||{}).name?new Error(t.$t("reqAborted")):e})),r}(t,e,n||t.conf.reqTimeout||15e3,i),o=r.status,l=[401,400].includes(o);if(!r.ok&&!l)throw new Error(`${t.$t("reqGot")} ${o}`);let c=yield r.json();const d=(n,s)=>{ct(t,e,i).then((t=>{n(t)})).catch((t=>{s(t)}))};if((null==(s=c.data)?void 0:s.need_captcha)?c=yield new Promise(((e,i)=>{t.checkCaptcha({imgData:c.data.img_data,iframe:c.data.iframe,onSuccess:()=>{d(e,i)},onCancel:()=>{i(c)}})})):((null==(a=c.data)?void 0:a.need_login)||l)&&(c=yield new Promise(((e,i)=>{t.checkAdmin({onSuccess:()=>{d(e,i)},onCancel:()=>{i(c)}})}))),!c.success)throw c;return c}))}function dt(t){const e=new FormData;return Object.keys(t).forEach((i=>e.append(i,String(t[i])))),e}__publicField(ot,"BodyOrgOverflow"),__publicField(ot,"BodyOrgPaddingRight"),__publicField(ot,"actionTimers",[]),function(){function t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function e(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,n.key,n)}}function i(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function n(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&r(t,e)}function s(t){return(s=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function r(t,e){return(r=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}function o(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function l(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function c(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return l(t)}function d(t){var e=o();return function(){var i,n=s(t);if(e){var a=s(this).constructor;i=Reflect.construct(n,arguments,a)}else i=n.apply(this,arguments);return c(this,i)}}function h(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=s(t)););return t}function u(){return u="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,i){var n=h(t,e);if(n){var s=Object.getOwnPropertyDescriptor(n,e);return s.get?s.get.call(arguments.length<3?t:i):s.value}},u.apply(this,arguments)}var p=function(){function e(){t(this,e),Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}return i(e,[{key:"addEventListener",value:function(t,e,i){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:e,options:i})}},{key:"removeEventListener",value:function(t,e){if(t in this.listeners)for(var i=this.listeners[t],n=0,s=i.length;n<s;n++)if(i[n].callback===e)return void i.splice(n,1)}},{key:"dispatchEvent",value:function(t){if(t.type in this.listeners){for(var e=this.listeners[t.type].slice(),i=0,n=e.length;i<n;i++){var s=e[i];try{s.callback.call(this,t)}catch(a){Promise.resolve().then((function(){throw a}))}s.options&&s.options.once&&this.removeEventListener(t.type,s.callback)}return!t.defaultPrevented}}}]),e}(),m=function(e){n(r,e);var a=d(r);function r(){var e;return t(this,r),(e=a.call(this)).listeners||p.call(l(e)),Object.defineProperty(l(e),"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(l(e),"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(l(e),"reason",{value:void 0,writable:!0,configurable:!0}),e}return i(r,[{key:"toString",value:function(){return"[object AbortSignal]"}},{key:"dispatchEvent",value:function(t){"abort"===t.type&&(this.aborted=!0,"function"==typeof this.onabort&&this.onabort.call(this,t)),u(s(r.prototype),"dispatchEvent",this).call(this,t)}}]),r}(p),g=function(){function e(){t(this,e),Object.defineProperty(this,"signal",{value:new m,writable:!0,configurable:!0})}return i(e,[{key:"abort",value:function(t){var e;try{e=new Event("abort")}catch(n){"undefined"!=typeof document?document.createEvent?(e=document.createEvent("Event")).initEvent("abort",!1,!1):(e=document.createEventObject()).type="abort":e={type:"abort",bubbles:!1,cancelable:!1}}var i=t;if(void 0===i)if("undefined"==typeof document)(i=new Error("This operation was aborted")).name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(s){(i=new Error("This operation was aborted")).name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(e)}},{key:"toString",value:function(){return"[object AbortController]"}}]),e}();function f(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):"function"==typeof t.Request&&!t.Request.prototype.hasOwnProperty("signal")||!t.AbortController}function y(t){"function"==typeof t&&(t={fetch:t});var e=t,i=e.fetch,n=e.Request,s=void 0===n?i.Request:n,a=e.AbortController,r=e.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,o=void 0!==r&&r;if(!f({fetch:i,Request:s,AbortController:a,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o}))return{fetch:i,Request:l};var l=s;(l&&!l.prototype.hasOwnProperty("signal")||o)&&((l=function(t,e){var i;e&&e.signal&&(i=e.signal,delete e.signal);var n=new s(t,e);return i&&Object.defineProperty(n,"signal",{writable:!1,enumerable:!1,configurable:!0,value:i}),n}).prototype=s.prototype);var c=i;return{fetch:function(t,e){var i=l&&l.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(i){var n;try{n=new DOMException("Aborted","AbortError")}catch(a){(n=new Error("Aborted")).name="AbortError"}if(i.aborted)return Promise.reject(n);var s=new Promise((function(t,e){i.addEventListener("abort",(function(){return e(n)}),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([s,c(t,e)])}return c(t,e)},Request:l}}"undefined"!=typeof Symbol&&Symbol.toStringTag&&(g.prototype[Symbol.toStringTag]="AbortController",m.prototype[Symbol.toStringTag]="AbortSignal"),function(t){if(f(t))if(t.fetch){var e=y(t),i=e.fetch,n=e.Request;t.fetch=i,t.Request=n,Object.defineProperty(t,"AbortController",{writable:!0,enumerable:!1,configurable:!0,value:g}),Object.defineProperty(t,"AbortSignal",{writable:!0,enumerable:!1,configurable:!0,value:m})}else console.warn("fetch() is not available, cannot install abortcontroller-polyfill")}("undefined"!=typeof self?self:a)}();class ht{constructor(t,e){__publicField(this,"api"),__publicField(this,"ctx"),this.api=t,this.ctx=e}POST(t,e){return __async(this,null,(function*(){return function(t,e,i){return __async(this,null,(function*(){const n={method:"POST"};return i=__spreadValues({site_name:t.conf.site||""},i||{}),n.body=dt(i),(yield ct(t,e,n)).data||{}}))}(this.ctx,this.api.baseURL+t,e)}))}Fetch(t,e,i){return __async(this,null,(function*(){return ct(this.ctx,this.api.baseURL+t,e,i)}))}}const ut={comment:class extends ht{get(t,e,i,n){const s={page_key:this.ctx.conf.pageKey,site_name:this.ctx.conf.site||"",limit:e,offset:t};return i&&(s.flat_mode=i),this.ctx.user.checkHasBasicUserInfo()&&(s.name=this.ctx.user.data.nick,s.email=this.ctx.user.data.email),n&&n(s),this.POST("/get",s)}add(t){return __async(this,null,(function*(){const e={name:t.nick,email:t.email,link:t.link,content:t.content,rid:t.rid,page_key:t.page_key,ua:yield K()};t.page_title&&(e.page_title=t.page_title),t.site_name&&(e.site_name=t.site_name);return(yield this.POST("/add",e)).comment}))}commentEdit(t){return __async(this,null,(function*(){const e=__spreadValues({},t);return(yield this.POST("/admin/comment-edit",e)).comment}))}commentDel(t,e){const i={id:String(t),site_name:e||""};return this.POST("/admin/comment-del",i)}vote(t,e){return __async(this,null,(function*(){const i={site_name:this.ctx.conf.site||"",target_id:t,type:e};this.ctx.user.checkHasBasicUserInfo()&&(i.name=this.ctx.user.data.nick,i.email=this.ctx.user.data.email);return yield this.POST("/vote",i)}))}},page:class extends ht{pageGet(t,e,i){return __async(this,null,(function*(){const n={site_name:t||"",offset:e||0,limit:i||15};return yield this.POST("/admin/page-get",n)}))}pageEdit(t){return __async(this,null,(function*(){const e={id:t.id,key:t.key,title:t.title,admin_only:t.admin_only,site_name:t.site_name||this.ctx.conf.site};return(yield this.POST("/admin/page-edit",e)).page}))}pageDel(t,e){const i={key:String(t),site_name:e||""};return this.POST("/admin/page-del",i)}pageFetch(t,e,i){return __async(this,null,(function*(){const n={};t&&(n.id=t),e&&(n.site_name=e),i&&(n.get_status=i);return yield this.POST("/admin/page-fetch",n)}))}pv(){return __async(this,null,(function*(){const t={site_name:this.ctx.conf.site||"",page_key:this.ctx.conf.pageKey||"",page_title:this.ctx.conf.pageTitle||""};return(yield this.POST("/pv",t)).pv}))}stat(t,e,i){return __async(this,null,(function*(){const n={type:t,site_name:this.ctx.conf.site||""};e&&(n.page_keys=Array.isArray(e)?e.join(","):e),i&&(n.limit=i);return yield this.POST("/stat",n)}))}},site:class extends ht{siteGet(){return __async(this,null,(function*(){return(yield this.POST("/admin/site-get",{})).sites}))}siteAdd(t,e){return __async(this,null,(function*(){const i={name:t,urls:e,site_name:""};return(yield this.POST("/admin/site-add",i)).site}))}siteEdit(t){return __async(this,null,(function*(){const e={id:t.id,name:t.name||"",urls:t.urls||""};return(yield this.POST("/admin/site-edit",e)).site}))}siteDel(t,e=!1){const i={id:t,del_content:e};return this.POST("/admin/site-del",i)}export(){return __async(this,null,(function*(){var t;return(null==(t=(yield this.Fetch("/admin/export",{method:"POST"},0)).data)?void 0:t.data)||""}))}},user:class extends ht{login(t,e,i){return __async(this,null,(function*(){const n={name:t,email:e,password:i};this.ctx.conf.site&&(n.site_name=this.ctx.conf.site);return yield this.POST("/login",n)}))}userGet(t,e){const i=new AbortController,n={name:t,email:e,site_name:this.ctx.conf.site||""};return{req:this.Fetch("/user-get",{method:"POST",body:dt(n),signal:i.signal}).then((t=>({user:t.data.user,is_login:t.data.is_login,unread:t.data.unread||[],unread_count:t.data.unread_count||0}))),abort:()=>{i.abort()}}}loginStatus(){return __async(this,null,(function*(){return(yield this.POST("/login-status",{name:this.ctx.user.data.nick,email:this.ctx.user.data.email}))||{is_login:!1,is_admin:!1}}))}logout(){return __async(this,null,(function*(){return this.POST("/logout")}))}markRead(t,e=!1){const i={site_name:this.ctx.conf.site||"",notify_key:t};return e&&(delete i.notify_key,i.read_all=!0,i.name=this.ctx.user.data.nick,i.email=this.ctx.user.data.email),this.POST("/mark-read",i)}userList(t,e,i){return __async(this,null,(function*(){const n={offset:t||0,limit:e||15};i&&(n.type=i);return yield this.POST("/admin/user-get",n)}))}userAdd(t,e){return __async(this,null,(function*(){const i={name:t.name||"",email:t.email||"",password:e||"",link:t.link||"",is_admin:t.is_admin||!1,site_names:t.site_names_raw||"",receive_email:t.receive_email||!0,badge_name:t.badge_name||"",badge_color:t.badge_color||""};return(yield this.POST("/admin/user-add",i)).user}))}userEdit(t,e){return __async(this,null,(function*(){const i={id:t.id,name:t.name||"",email:t.email||"",password:e||"",link:t.link||"",is_admin:t.is_admin||!1,site_names:t.site_names_raw||"",receive_email:t.receive_email||!0,badge_name:t.badge_name||"",badge_color:t.badge_color||""};return(yield this.POST("/admin/user-edit",i)).user}))}userDel(t){return this.POST("/admin/user-del",{id:String(t)})}},system:class extends ht{conf(){return __async(this,null,(function*(){const t=(yield this.POST("/conf")).frontend_conf||{};return t.emoticons&&"string"==typeof t.emoticons&&(t.emoticons=t.emoticons.trim(),t.emoticons.startsWith("[")||t.emoticons.startsWith("{")?t.emoticons=JSON.parse(t.emoticons):"false"===t.emoticons&&(t.emoticons=!1)),t}))}getSettings(){return __async(this,null,(function*(){return yield this.POST("/admin/setting-get")}))}saveSettings(t){return __async(this,null,(function*(){return yield this.POST("/admin/setting-save",{data:t})}))}version(){return __async(this,null,(function*(){const t=yield fetch(`${this.api.baseURL}/version`,{method:"POST"});return yield t.json()}))}},captcha:class extends ht{captchaGet(){return __async(this,null,(function*(){return(yield this.POST("/captcha/refresh")).img_data||""}))}captchaCheck(t){return __async(this,null,(function*(){return(yield this.POST("/captcha/check",{value:t})).img_data||""}))}captchaStatus(){return __async(this,null,(function*(){return(yield this.POST("/captcha/status"))||{is_pass:!1}}))}},admin:class extends ht{cacheFlushAll(){return this.POST("/admin/cache-flush",{flush_all:!0})}cacheWarmUp(){return this.POST("/admin/cache-warm",{})}},upload:class extends ht{imgUpload(t){return __async(this,null,(function*(){const e={name:this.ctx.user.data.nick,email:this.ctx.user.data.email,page_key:this.ctx.conf.pageKey};this.ctx.conf.site&&(e.site_name=this.ctx.conf.site);const i=dt(e);i.set("file",t);const n={method:"POST",body:i};return(yield this.Fetch("/img-upload",n)).data||{}}))}}};class pt{constructor(t){__publicField(this,"ctx"),this.ctx=t,Object.entries(ut).forEach((([t,e])=>{this[t]=new e(this,this.ctx)}))}get baseURL(){return`${this.ctx.conf.server}/api`}}const mt="2.4.4",gt=window||{},ft=navigator||{};class yt{constructor(t,e){__publicField(this,"ctx"),__publicField(this,"conf"),__publicField(this,"$el"),__publicField(this,"isLoading",!1),__publicField(this,"msgRecTimer"),__publicField(this,"msgRecTimerFunc"),__publicField(this,"isConfirming",!1),__publicField(this,"confirmRecTimer"),this.ctx=t,this.$el=N('<span class="atk-common-action-btn"></span>'),this.conf="object"!=typeof e?{text:e}:e,this.$el.innerText=this.getText(),this.conf.adminOnly&&this.$el.setAttribute("atk-only-admin-show","")}get isMessaging(){return!!this.msgRecTimer}appendTo(t){return t.append(this.$el),this}getText(){return"string"==typeof this.conf.text?this.conf.text:this.conf.text()}setClick(t){this.$el.onclick=e=>{if(e.stopPropagation(),!this.isLoading){if(this.conf.confirm&&!this.isMessaging){const t=()=>{this.isConfirming=!1,this.$el.classList.remove("atk-btn-confirm"),this.$el.innerText=this.getText()};if(!this.isConfirming)return this.isConfirming=!0,this.$el.classList.add("atk-btn-confirm"),this.$el.innerText=this.conf.confirmText||this.ctx.$t("actionConfirm"),void(this.confirmRecTimer=window.setTimeout((()=>t()),5e3));this.confirmRecTimer&&window.clearTimeout(this.confirmRecTimer),t()}if(this.msgRecTimer)return this.fireMsgRecTimer(),void this.clearMsgRecTimer();t()}}}updateText(t){t&&(this.conf.text=t),this.setLoading(!1),this.$el.innerText=this.getText()}setLoading(t,e){this.isLoading!==t&&(this.isLoading=t,t?(this.$el.classList.add("atk-btn-loading"),this.$el.innerText=e||`${this.ctx.$t("loading")}...`):(this.$el.classList.remove("atk-btn-loading"),this.$el.innerText=this.getText()))}setError(t){this.setMsg(t,"atk-btn-error")}setWarn(t){this.setMsg(t,"atk-btn-warn")}setSuccess(t){this.setMsg(t,"atk-btn-success")}setMsg(t,e,i,n){this.setLoading(!1),e&&this.$el.classList.add(e),this.$el.innerText=t,this.setMsgRecTimer((()=>{this.$el.innerText=this.getText(),e&&this.$el.classList.remove(e),n&&n()}),i||2500)}setMsgRecTimer(t,e){this.fireMsgRecTimer(),this.clearMsgRecTimer(),this.msgRecTimerFunc=t,this.msgRecTimer=window.setTimeout((()=>{t(),this.clearMsgRecTimer()}),e)}fireMsgRecTimer(){this.msgRecTimerFunc&&this.msgRecTimerFunc()}clearMsgRecTimer(){this.msgRecTimer&&window.clearTimeout(this.msgRecTimer),this.msgRecTimer=void 0,this.msgRecTimerFunc=void 0}}class $t{constructor(t){__publicField(this,"comment"),__publicField(this,"$el"),__publicField(this,"$main"),__publicField(this,"$header"),__publicField(this,"$headerNick"),__publicField(this,"$headerBadgeWrap"),__publicField(this,"$body"),__publicField(this,"$content"),__publicField(this,"$childrenWrap"),__publicField(this,"$actions"),__publicField(this,"voteBtnUp"),__publicField(this,"voteBtnDown"),__publicField(this,"$replyTo"),__publicField(this,"$replyAt"),this.comment=t}get ctx(){return this.comment.ctx}get data(){return this.comment.getData()}get cConf(){return this.comment.getConf()}render(){return this.$el=N('<div class="atk-comment-wrap">\n <div class="atk-comment">\n <div class="atk-avatar"></div>\n <div class="atk-main">\n <div class="atk-header">\n <span class="atk-item atk-nick"></span>\n <span class="atk-badge-wrap"></span>\n <span class="atk-item atk-date"></span>\n </div>\n <div class="atk-body">\n <div class="atk-content"></div>\n </div>\n <div class="atk-footer">\n <div class="atk-actions"></div>\n </div>\n </div>\n </div>\n</div>\n'),this.$main=this.$el.querySelector(".atk-main"),this.$header=this.$el.querySelector(".atk-header"),this.$body=this.$el.querySelector(".atk-body"),this.$content=this.$body.querySelector(".atk-content"),this.$actions=this.$el.querySelector(".atk-actions"),this.$el.setAttribute("data-comment-id",`${this.data.id}`),this.renderAvatar(),this.renderHeader(),this.renderContent(),this.renderReplyAt(),this.renderReplyTo(),this.renderPending(),this.renderActions(),this.recoveryChildrenWrap(),this.$el}renderAvatar(){const t=this.$el.querySelector(".atk-avatar"),e=N("<img />"),i=this.ctx.conf.avatarURLBuilder;if(e.src=i?i(this.data):this.comment.getGravatarURL(),this.data.link){const i=N('<a target="_blank" rel="noreferrer noopener nofollow"></a>');i.href=Y(this.data.link)?this.data.link:`https://${this.data.link}`,i.append(e),t.append(i)}else t.append(e)}renderHeader(){this.renderHeader_Nick(),this.renderHeader_VerifyBadge(),this.renderHeader_Date(),this.renderHeader_UABadge()}renderHeader_Nick(){if(this.$headerNick=this.$el.querySelector(".atk-nick"),this.data.link){const t=N('<a target="_blank" rel="noreferrer noopener nofollow"></a>');t.innerText=this.data.nick,t.href=Y(this.data.link)?this.data.link:`https://${this.data.link}`,this.$headerNick.append(t)}else this.$headerNick.innerText=this.data.nick}renderHeader_VerifyBadge(){this.$headerBadgeWrap=this.$el.querySelector(".atk-badge-wrap"),this.$headerBadgeWrap.innerHTML="";const t=this.data.badge_name,e=this.data.badge_color;if(t){const i=N('<span class="atk-badge"></span>');i.innerText=t.replace("管理员",this.ctx.$t("admin")),i.style.backgroundColor=e||"",this.$headerBadgeWrap.append(i)}if(this.data.is_pinned){const t=N(`<span class="atk-pinned-badge">${this.ctx.$t("pin")}</span>`);this.$headerBadgeWrap.append(t)}}renderHeader_Date(){const t=this.$el.querySelector(".atk-date");t.innerText=this.comment.getDateFormatted(),t.setAttribute("data-atk-comment-date",String(+new Date(this.data.date)))}renderHeader_UABadge(){if(this.ctx.conf.uaBadge){let t=this.$header.querySelector("atk-ua-wrap");t||(t=N('<span class="atk-ua-wrap"></span>'),this.$header.append(t)),t.innerHTML="";const e=N('<span class="atk-ua ua-browser"></span>'),i=N('<span class="atk-ua ua-os"></span>'),n=this.comment.getUserUA();e.innerText=n.browser,i.innerText=n.os,t.append(e),t.append(i)}}renderContent(){if(!this.data.is_collapsed)return this.$content.innerHTML=this.comment.getContentMarked(),void this.$content.classList.remove("atk-hide","atk-collapsed");this.$content.classList.add("atk-hide","atk-type-collapsed");const t=N(`\n <div class="atk-collapsed">\n <span class="atk-text">${this.ctx.$t("collapsedMsg")}</span>\n <span class="atk-show-btn">${this.ctx.$t("expand")}</span>\n </div>`);this.$body.insertAdjacentElement("beforeend",t);const e=t.querySelector(".atk-show-btn");e.addEventListener("click",(t=>{t.stopPropagation(),this.$content.classList.contains("atk-hide")?(this.$content.innerHTML=this.comment.getContentMarked(),this.$content.classList.remove("atk-hide"),st(this.$content),e.innerHTML=this.ctx.$t("collapse")):(this.$content.innerHTML="",this.$content.classList.add("atk-hide"),e.innerHTML=this.ctx.$t("expand"))}))}renderReplyAt(){this.cConf.isFlatMode||0===this.data.rid||this.cConf.replyTo&&(this.$replyAt=N('<span class="atk-item atk-reply-at"><span class="atk-arrow"></span><span class="atk-nick"></span></span>'),this.$replyAt.querySelector(".atk-nick").innerText=`${this.cConf.replyTo.nick}`,this.$replyAt.onclick=()=>{this.comment.getActions().goToReplyComment()},this.$headerBadgeWrap.insertAdjacentElement("afterend",this.$replyAt))}renderReplyTo(){if(!this.cConf.isFlatMode)return;if(!this.cConf.replyTo)return;this.$replyTo=N(`\n <div class="atk-reply-to">\n <div class="atk-meta">${this.ctx.$t("reply")} <span class="atk-nick"></span>:</div>\n <div class="atk-content"></div>\n </div>`);const t=this.$replyTo.querySelector(".atk-nick");t.innerText=`@${this.cConf.replyTo.nick}`,t.onclick=()=>{this.comment.getActions().goToReplyComment()};let e=Q(this.ctx,this.cConf.replyTo.content);this.cConf.replyTo.is_collapsed&&(e=`[${this.ctx.$t("collapsed")}]`),this.$replyTo.querySelector(".atk-content").innerHTML=e,this.$body.prepend(this.$replyTo)}renderPending(){if(!this.data.is_pending)return;const t=N(`<div class="atk-pending">${this.ctx.$t("pendingMsg")}</div>`);this.$body.prepend(t)}renderActions(){this.renderActions_Vote(),this.renderActions_Reply(),this.renderActions_Collapse(),this.renderActions_Moderator(),this.renderActions_Pin(),this.renderActions_Edit(),this.renderActions_Del()}renderActions_Vote(){this.ctx.conf.vote&&(this.voteBtnUp=new yt(this.ctx,(()=>`${this.ctx.$t("voteUp")} (${this.data.vote_up||0})`)).appendTo(this.$actions),this.voteBtnUp.setClick((()=>{this.comment.getActions().vote("up")})),this.ctx.conf.voteDown&&(this.voteBtnDown=new yt(this.ctx,(()=>`${this.ctx.$t("voteDown")} (${this.data.vote_down||0})`)).appendTo(this.$actions),this.voteBtnDown.setClick((()=>{this.comment.getActions().vote("down")}))))}renderActions_Reply(){if(!this.data.is_allow_reply)return;const t=N(`<span>${this.ctx.$t("reply")}</span>`);this.$actions.append(t),t.addEventListener("click",(t=>{t.stopPropagation(),this.cConf.onReplyBtnClick?this.cConf.onReplyBtnClick():this.ctx.replyComment(this.data,this.$el)}))}renderActions_Collapse(){const t=new yt(this.ctx,{text:()=>this.data.is_collapsed?this.ctx.$t("expand"):this.ctx.$t("collapse"),adminOnly:!0});t.appendTo(this.$actions),t.setClick((()=>{this.comment.getActions().adminEdit("collapsed",t)}))}renderActions_Moderator(){const t=new yt(this.ctx,{text:()=>this.data.is_pending?this.ctx.$t("pending"):this.ctx.$t("approved"),adminOnly:!0});t.appendTo(this.$actions),t.setClick((()=>{this.comment.getActions().adminEdit("pending",t)}))}renderActions_Pin(){const t=new yt(this.ctx,{text:()=>this.data.is_pinned?this.ctx.$t("unpin"):this.ctx.$t("pin"),adminOnly:!0});t.appendTo(this.$actions),t.setClick((()=>{this.comment.getActions().adminEdit("pinned",t)}))}renderActions_Edit(){const t=new yt(this.ctx,{text:this.ctx.$t("edit"),adminOnly:!0});t.appendTo(this.$actions),t.setClick((()=>{this.ctx.editComment(this.data,this.$el)}))}renderActions_Del(){const t=new yt(this.ctx,{text:this.ctx.$t("delete"),confirm:!0,confirmText:this.ctx.$t("deleteConfirm"),adminOnly:!0});t.appendTo(this.$actions),t.setClick((()=>{this.comment.getActions().adminDelete(t)}))}checkHeightLimit(){this.checkHeightLimitArea("content"),this.checkHeightLimitArea("children")}checkHeightLimitArea(t){const e=this.ctx.conf.heightLimit.children,i=this.ctx.conf.heightLimit.content;if("children"===t&&!e)return;if("content"===t&&!i)return;let n;"children"===t&&(n=e),"content"===t&&(n=i);const s=t=>{t&&U(t)>n&&this.heightLimitAdd(t,n)};"children"===t?s(this.$childrenWrap):"content"===t&&(s(this.$content),s(this.$replyTo),G(this.$content,(()=>{s(this.$content)})),this.$replyTo&&G(this.$replyTo,(()=>{s(this.$replyTo)})))}heightLimitRemove(t){t&&t.classList.contains("atk-height-limit")&&(t.classList.remove("atk-height-limit"),Array.from(t.children).forEach((t=>{t.classList.contains("atk-height-limit-btn")&&t.remove()})),t.style.height="",t.style.overflow="")}heightLimitRemoveForChildren(){this.$childrenWrap&&this.heightLimitRemove(this.$childrenWrap)}heightLimitAdd(t,e){if(!t)return;if(t.classList.contains("atk-height-limit"))return;t.classList.add("atk-height-limit"),t.style.height=`${e}px`,t.style.overflow="hidden";const i=N(`<div class="atk-height-limit-btn">${this.ctx.$t("readMore")}</span>`);i.onclick=e=>{e.stopPropagation(),this.heightLimitRemove(t);const i=this.comment.getChildren();1===i.length&&i[0].getRender().heightLimitRemove(i[0].getRender().$content)},t.append(i)}playFadeAnim(){st(this.comment.getRender().$el)}playFadeAnimForBody(){st(this.comment.getRender().$body)}getChildrenWrap(){return this.$childrenWrap}renderChildrenWrap(){return this.$childrenWrap||(this.$childrenWrap=N('<div class="atk-comment-children"></div>'),this.$main.append(this.$childrenWrap)),this.$childrenWrap}recoveryChildrenWrap(){this.$childrenWrap&&this.$main.append(this.$childrenWrap)}setUnread(t){t?this.$el.classList.add("atk-unread"):this.$el.classList.remove("atk-unread")}setOpenable(t){t?this.$el.classList.add("atk-openable"):this.$el.classList.remove("atk-openable")}setOpenURL(t){this.setOpenable(!0),this.$el.onclick=e=>{e.preventDefault(),window.open(t),this.cConf.openEvt&&this.cConf.openEvt()}}setOpenAction(t){this.setOpenable(!0),this.$el.onclick=e=>{e.preventDefault(),t()}}}class _t{constructor(t){__publicField(this,"comment"),this.comment=t}get ctx(){return this.comment.ctx}get data(){return this.comment.getData()}get cConf(){return this.comment.getConf()}vote(t){const e="up"===t?this.comment.getRender().voteBtnUp:this.comment.getRender().voteBtnDown;this.ctx.getApi().comment.vote(this.data.id,`comment_${t}`).then((t=>{var e,i;this.data.vote_up=t.up,this.data.vote_down=t.down,null==(e=this.comment.getRender().voteBtnUp)||e.updateText(),null==(i=this.comment.getRender().voteBtnDown)||i.updateText()})).catch((t=>{null==e||e.setError(this.ctx.$t("voteFail")),console.log(t)}))}adminEdit(t,e){if(e.isLoading)return;e.setLoading(!0,`${this.ctx.$t("editing")}...`);const i=__spreadValues({},this.data);"collapsed"===t?i.is_collapsed=!i.is_collapsed:"pending"===t?i.is_pending=!i.is_pending:"pinned"===t&&(i.is_pinned=!i.is_pinned),this.ctx.getApi().comment.commentEdit(i).then((t=>{e.setLoading(!1),this.comment.setData(t),this.ctx.listRefreshUI()})).catch((t=>{console.error(t),e.setError(this.ctx.$t("editFail"))}))}adminDelete(t){t.isLoading||(t.setLoading(!0,`${this.ctx.$t("deleting")}...`),this.ctx.getApi().comment.commentDel(this.data.id,this.data.site_name).then((()=>{t.setLoading(!1),this.cConf.onDelete&&this.cConf.onDelete(this.comment)})).catch((e=>{console.error(e),t.setError(this.ctx.$t("deleteFail"))})))}goToReplyComment(){const t=window.location.hash,e=`#atk-comment-${this.data.rid}`;window.location.hash=e,e===t&&window.dispatchEvent(new Event("hashchange"))}}class vt extends Z{constructor(t,e,i){super(t),__publicField(this,"renderInstance"),__publicField(this,"actionInstance"),__publicField(this,"data"),__publicField(this,"cConf"),__publicField(this,"parent"),__publicField(this,"children",[]),__publicField(this,"nestCurt"),__publicField(this,"nestMax"),this.nestMax=t.conf.nestMax||3,this.cConf=i,this.data=__spreadValues({},e),this.data.date=this.data.date.replace(/-/g,"/"),this.parent=null,this.nestCurt=1,this.actionInstance=new _t(this),this.renderInstance=new $t(this)}render(){const t=this.renderInstance.render();this.$el&&this.$el.replaceWith(t),this.$el=t,this.cConf.afterRender&&this.cConf.afterRender()}getActions(){return this.actionInstance}getRender(){return this.renderInstance}getData(){return this.data}setData(t){this.data=t,this.render(),this.getRender().playFadeAnimForBody()}getParent(){return this.parent}getChildren(){return this.children}getNestCurt(){return this.nestCurt}getIsRoot(){return 0===this.data.rid}getID(){return this.data.id}putChild(t,e="append"){t.parent=this,t.nestCurt=this.nestCurt+1,this.children.push(t);const i=this.getChildrenEl();"append"===e?i.append(t.getEl()):"prepend"===e&&i.prepend(t.getEl()),t.getRender().playFadeAnim(),t.getRender().checkHeightLimitArea("content")}getChildrenEl(){let t=this.getRender().getChildrenWrap();return t||(t=this.nestCurt<this.nestMax?this.getRender().renderChildrenWrap():this.parent.getChildrenEl()),t}getParents(){const t=[],e=i=>{i.parent&&(t.push(i.parent),e(i.parent))};return e(this),t}getEl(){return this.$el}getGravatarURL(){return t=this.ctx,e=this.data.email_encrypted,`${t.conf.gravatar.mirror.replace(/\/$/,"")}/${e}?d=${encodeURIComponent(t.conf.gravatar.default)}&s=80`;var t,e}getContentMarked(){return Q(this.ctx,this.data.content)}getDateFormatted(){return z(new Date(this.data.date),this.ctx)}getUserUA(){const t=function(t){const e=String(t||ft.userAgent),i={os:"",osVersion:"",engine:"",browser:"",device:"",language:"",version:""},n={Trident:e.includes("Trident")||e.includes("NET CLR"),Presto:e.includes("Presto"),WebKit:e.includes("AppleWebKit"),Gecko:e.includes("Gecko/")},s={Safari:e.includes("Safari"),Chrome:e.includes("Chrome")||e.includes("CriOS"),IE:e.includes("MSIE")||e.includes("Trident"),Edge:e.includes("Edge")||e.includes("Edg"),Firefox:e.includes("Firefox")||e.includes("FxiOS"),"Firefox Focus":e.includes("Focus"),Chromium:e.includes("Chromium"),Opera:e.includes("Opera")||e.includes("OPR"),Vivaldi:e.includes("Vivaldi"),Yandex:e.includes("YaBrowser"),Kindle:e.includes("Kindle")||e.includes("Silk/"),360:e.includes("360EE")||e.includes("360SE"),UC:e.includes("UC")||e.includes(" UBrowser"),QQBrowser:e.includes("QQBrowser"),QQ:e.includes("QQ/"),Baidu:e.includes("Baidu")||e.includes("BIDUBrowser"),Maxthon:e.includes("Maxthon"),Sogou:e.includes("MetaSr")||e.includes("Sogou"),LBBROWSER:e.includes("LBBROWSER"),"2345Explorer":e.includes("2345Explorer"),TheWorld:e.includes("TheWorld"),MIUI:e.includes("MiuiBrowser"),Quark:e.includes("Quark"),Qiyu:e.includes("Qiyu"),Wechat:e.includes("MicroMessenger"),Taobao:e.includes("AliApp(TB"),Alipay:e.includes("AliApp(AP"),Weibo:e.includes("Weibo"),Douban:e.includes("com.douban.frodo"),Suning:e.includes("SNEBUY-APP"),iQiYi:e.includes("IqiyiApp")},a={Windows:e.includes("Windows"),Linux:e.includes("Linux")||e.includes("X11"),macOS:e.includes("Macintosh"),Android:e.includes("Android")||e.includes("Adr"),Ubuntu:e.includes("Ubuntu"),FreeBSD:e.includes("FreeBSD"),Debian:e.includes("Debian"),"Windows Phone":e.includes("IEMobile")||e.includes("Windows Phone"),BlackBerry:e.includes("BlackBerry")||e.includes("RIM"),MeeGo:e.includes("MeeGo"),Symbian:e.includes("Symbian"),iOS:e.includes("like Mac OS X"),"Chrome OS":e.includes("CrOS"),WebOS:e.includes("hpwOS")},r={Mobile:e.includes("Mobi")||e.includes("iPh")||e.includes("480"),Tablet:e.includes("Tablet")||e.includes("Pad")||e.includes("Nexus 7")};r.Mobile?r.Mobile=!e.includes("iPad"):s.Chrome&&e.includes("Edg")?(s.Chrome=!1,s.Edge=!0):gt.showModalDialog&&gt.chrome&&(s.Chrome=!1,s[360]=!0),i.device="PC",i.language=(()=>{const t=(ft.browserLanguage||ft.language).split("-");return t[1]&&(t[1]=t[1].toUpperCase()),t.join("_")})();const o={engine:n,browser:s,os:a,device:r};Object.entries(o).forEach((([t,e])=>{Object.entries(e).forEach((([e,n])=>{!0===n&&(i[t]=e)}))}));const l={Windows:()=>{const t=e.replace(/^.*Windows NT ([\d.]+);.*$/,"$1");return{6.4:"10",6.3:"8.1",6.2:"8",6.1:"7","6.0":"Vista",5.2:"XP",5.1:"XP","5.0":"2000","10.0":"10","11.0":"11"}[t]||t},Android:()=>e.replace(/^.*Android ([\d.]+);.*$/,"$1"),iOS:()=>e.replace(/^.*OS ([\d_]+) like.*$/,"$1").replace(/_/g,"."),Debian:()=>e.replace(/^.*Debian\/([\d.]+).*$/,"$1"),"Windows Phone":()=>e.replace(/^.*Windows Phone( OS)? ([\d.]+);.*$/,"$2"),macOS:()=>e.replace(/^.*Mac OS X ([\d_]+).*$/,"$1").replace(/_/g,"."),WebOS:()=>e.replace(/^.*hpwOS\/([\d.]+);.*$/,"$1")};i.osVersion="",l[i.os]&&(i.osVersion=l[i.os](),i.osVersion===e&&(i.osVersion=""));const c={Safari:()=>e.replace(/^.*Version\/([\d.]+).*$/,"$1"),Chrome:()=>e.replace(/^.*Chrome\/([\d.]+).*$/,"$1").replace(/^.*CriOS\/([\d.]+).*$/,"$1"),IE:()=>e.replace(/^.*MSIE ([\d.]+).*$/,"$1").replace(/^.*rv:([\d.]+).*$/,"$1"),Edge:()=>e.replace(/^.*(Edge|Edg|Edg[A-Z]{1})\/([\d.]+).*$/,"$2"),Firefox:()=>e.replace(/^.*Firefox\/([\d.]+).*$/,"$1").replace(/^.*FxiOS\/([\d.]+).*$/,"$1"),"Firefox Focus":()=>e.replace(/^.*Focus\/([\d.]+).*$/,"$1"),Chromium:()=>e.replace(/^.*Chromium\/([\d.]+).*$/,"$1"),Opera:()=>e.replace(/^.*Opera\/([\d.]+).*$/,"$1").replace(/^.*OPR\/([\d.]+).*$/,"$1"),Vivaldi:()=>e.replace(/^.*Vivaldi\/([\d.]+).*$/,"$1"),Yandex:()=>e.replace(/^.*YaBrowser\/([\d.]+).*$/,"$1"),Kindle:()=>e.replace(/^.*Version\/([\d.]+).*$/,"$1"),Maxthon:()=>e.replace(/^.*Maxthon\/([\d.]+).*$/,"$1"),QQBrowser:()=>e.replace(/^.*QQBrowser\/([\d.]+).*$/,"$1"),QQ:()=>e.replace(/^.*QQ\/([\d.]+).*$/,"$1"),Baidu:()=>e.replace(/^.*BIDUBrowser[\s/]([\d.]+).*$/,"$1"),UC:()=>e.replace(/^.*UC?Browser\/([\d.]+).*$/,"$1"),Sogou:()=>e.replace(/^.*SE ([\d.X]+).*$/,"$1").replace(/^.*SogouMobileBrowser\/([\d.]+).*$/,"$1"),"2345Explorer":()=>e.replace(/^.*2345Explorer\/([\d.]+).*$/,"$1"),TheWorld:()=>e.replace(/^.*TheWorld ([\d.]+).*$/,"$1"),MIUI:()=>e.replace(/^.*MiuiBrowser\/([\d.]+).*$/,"$1"),Quark:()=>e.replace(/^.*Quark\/([\d.]+).*$/,"$1"),Qiyu:()=>e.replace(/^.*Qiyu\/([\d.]+).*$/,"$1"),Wechat:()=>e.replace(/^.*MicroMessenger\/([\d.]+).*$/,"$1"),Taobao:()=>e.replace(/^.*AliApp\(TB\/([\d.]+).*$/,"$1"),Alipay:()=>e.replace(/^.*AliApp\(AP\/([\d.]+).*$/,"$1"),Weibo:()=>e.replace(/^.*weibo__([\d.]+).*$/,"$1"),Douban:()=>e.replace(/^.*com.douban.frodo\/([\d.]+).*$/,"$1"),Suning:()=>e.replace(/^.*SNEBUY-APP([\d.]+).*$/,"$1"),iQiYi:()=>e.replace(/^.*IqiyiVersion\/([\d.]+).*$/,"$1")};return i.version="",c[i.browser]&&(i.version=c[i.browser](),i.version===e&&(i.version="")),i.version.indexOf(".")&&(i.version=i.version.substring(0,i.version.indexOf("."))),"iOS"===i.os&&e.includes("iPad")?i.os="iPadOS":"Edge"!==i.browser||e.includes("Edg")?"MIUI"===i.browser?i.os="Android":"Chrome"===i.browser&&Number(i.version)>27||"Opera"===i.browser&&Number(i.version)>12||"Yandex"===i.browser?i.engine="Blink":void 0===i.browser&&(i.browser="Unknow App"):i.engine="EdgeHTML",i}(this.data.ua);return{browser:`${t.browser} ${t.version}`,os:`${t.os} ${t.osVersion}`}}getConf(){return this.cConf}}class kt{constructor(t,e){__publicField(this,"conf"),__publicField(this,"total"),__publicField(this,"$el"),__publicField(this,"$input"),__publicField(this,"inputTimer"),__publicField(this,"$prevBtn"),__publicField(this,"$nextBtn"),__publicField(this,"page",1),this.total=t,this.conf=e,this.$el=N('<div class="atk-pagination-wrap">\n <div class="atk-pagination">\n <div class="atk-btn atk-btn-prev">Prev</div>\n <input type="text" class="atk-input" aria-label="Enter the number of page" />\n <div class="atk-btn atk-btn-next">Next</div>\n </div>\n </div>'),this.$input=this.$el.querySelector(".atk-input"),this.$input.value=`${this.page}`,this.$input.oninput=()=>this.input(),this.$input.onkeydown=t=>this.keydown(t),this.$prevBtn=this.$el.querySelector(".atk-btn-prev"),this.$nextBtn=this.$el.querySelector(".atk-btn-next"),this.$prevBtn.onclick=()=>this.prev(),this.$nextBtn.onclick=()=>this.next(),this.checkDisabled()}get pageSize(){return this.conf.pageSize}get offset(){return this.pageSize*(this.page-1)}get maxPage(){return Math.ceil(this.total/this.pageSize)}update(t,e){this.page=Math.ceil(t/this.pageSize)+1,this.total=e,this.setInput(this.page),this.checkDisabled()}setInput(t){this.$input.value=`${t}`}input(t=!1){window.clearTimeout(this.inputTimer);const e=this.$input.value.trim(),i=()=>{if(""===e)return void this.setInput(this.page);let t=Number(e);Number.isNaN(t)||t<1?this.setInput(this.page):(t>this.maxPage&&(this.setInput(this.maxPage),t=this.maxPage),this.change(t))};t?i():this.inputTimer=window.setTimeout((()=>i()),800)}prev(){const t=this.page-1;t<1||this.change(t)}next(){const t=this.page+1;t>this.maxPage||this.change(t)}change(t){this.page=t,this.conf.onChange(this.offset),this.setInput(t),this.checkDisabled()}checkDisabled(){this.page+1>this.maxPage?this.$nextBtn.classList.add("atk-disabled"):this.$nextBtn.classList.remove("atk-disabled"),this.page-1<1?this.$prevBtn.classList.add("atk-disabled"):this.$prevBtn.classList.remove("atk-disabled")}keydown(t){const e=t.keyCode||t.which;if(38===e){const t=Number(this.$input.value)+1;if(t>this.maxPage)return;this.setInput(t),this.input()}else if(40===e){const t=Number(this.$input.value)-1;if(t<1)return;this.setInput(t),this.input()}else 13===e&&this.input(!0)}setLoading(t){t?tt(this.$el):et(this.$el)}}class bt{constructor(t){__publicField(this,"conf"),__publicField(this,"$el"),__publicField(this,"$loading"),__publicField(this,"$text"),__publicField(this,"offset",0),__publicField(this,"total",0),__publicField(this,"origText","Load More"),this.conf=t,this.origText=this.conf.text||this.origText,this.$el=N(`<div class="atk-list-read-more" style="display: none;">\n <div class="atk-list-read-more-inner">\n <div class="atk-loading-icon" style="display: none;"></div>\n <span class="atk-text">${this.origText}</span>\n </div>\n </div>`),this.$loading=this.$el.querySelector(".atk-loading-icon"),this.$text=this.$el.querySelector(".atk-text"),this.$el.onclick=()=>{this.click()}}get hasMore(){return this.total>this.offset+this.conf.pageSize}click(){this.hasMore&&this.conf.onClick(this.offset+this.conf.pageSize),this.checkDisabled()}show(){this.$el.style.display=""}hide(){this.$el.style.display="none"}setLoading(t){this.$loading.style.display=t?"":"none",this.$text.style.display=t?"none":""}showErr(t){this.setLoading(!1),this.$text.innerText=t,this.$el.classList.add("atk-err"),window.setTimeout((()=>{this.$text.innerText=this.origText,this.$el.classList.remove("atk-err")}),2e3)}update(t,e){this.offset=t,this.total=e,this.checkDisabled()}checkDisabled(){this.hasMore?this.show():this.hide()}}class xt extends Z{constructor(t){super(t),__publicField(this,"$commentsWrap"),__publicField(this,"data"),__publicField(this,"isLoading",!1),__publicField(this,"noCommentText"),__publicField(this,"_nestSortBy"),__publicField(this,"_flatMode"),__publicField(this,"_pageMode"),__publicField(this,"_pageSize"),__publicField(this,"scrollListenerAt"),__publicField(this,"repositionAt"),__publicField(this,"pagination"),__publicField(this,"readMoreBtn"),__publicField(this,"autoLoadScrollEvent"),__publicField(this,"renderComment"),__publicField(this,"paramsEditor"),__publicField(this,"onAfterLoad"),__publicField(this,"unread",[]),__publicField(this,"unreadHighlight"),__publicField(this,"confLoaded",!1),this.$el=N('<div class="atk-list-lite">\n <div class="atk-list-comments-wrap"></div>\n </div>'),this.$commentsWrap=this.$el.querySelector(".atk-list-comments-wrap"),window.setInterval((()=>{this.$el.querySelectorAll("[data-atk-comment-date]").forEach((t=>{const e=t.getAttribute("data-atk-comment-date");t.innerText=z(new Date(Number(e)),this.ctx)}))}),3e4),this.ctx.on("conf-loaded",(()=>{}))}get nestSortBy(){return void 0!==this._nestSortBy?this._nestSortBy:this.ctx.conf.nestSort||"DATE_ASC"}set nestSortBy(t){this._nestSortBy=t}get flatMode(){return void 0!==this._flatMode?this._flatMode:!0===this.ctx.conf.flatMode||Number(this.ctx.conf.nestMax)<=1||!("auto"!==this.ctx.conf.flatMode||!window.matchMedia("(max-width: 768px)").matches)}set flatMode(t){this._flatMode=t}get pageMode(){return this._pageMode||(this.conf.pagination.readMore?"read-more":"pagination")}set pageMode(t){this._pageMode=t}get pageSize(){return this._pageSize||this.conf.pagination.pageSize}set pageSize(t){this._pageSize=t}getData(){return this.data}clearData(){this.data=void 0}getCommentsWrapEl(){return this.$commentsWrap}setLoading(t,e=!1){this.isLoading=t,e?function(t,e){t?tt(e):et(e)}(t,this.$el):"read-more"===this.pageMode?this.readMoreBtn.setLoading(t):"pagination"===this.pageMode&&this.pagination.setLoading(t)}fetchComments(t){return __async(this,null,(function*(){if(this.isLoading)return;const e=0===t,i=t=>this.setLoading(t,e);let n;i(!0),this.ctx.trigger("list-load"),("read-more"===this.pageMode&&e||"pagination"===this.pageMode)&&this.ctx.clearAllComments();try{n=yield this.ctx.getApi().comment.get(t,this.pageSize,this.flatMode,this.paramsEditor)}catch(s){throw this.onError(s.msg||String(s),t,s.data),s}finally{i(!1)}at(this.$el,null);try{this.onLoad(n,t)}catch(s){throw this.onError(String(s),t),s}finally{i(!1)}}))}onLoad(t,e){var i,n;this.data=t,this.confLoaded||(this.conf.useBackendConf?this.ctx.updateConf(t.conf.frontend_conf):this.ctx.updateConf({}),this.confLoaded=!0);const s=(null==(i=t.api_version)?void 0:i.fe_min_version)||"0.0.0";this.ctx.conf.versionCheck&&this.versionCheck("frontend",s,mt)||this.ctx.conf.versionCheck&&this.versionCheck("backend","2.3.0",null==(n=t.api_version)?void 0:n.version)||(this.importComments(t.comments),this.refreshPagination(e,this.flatMode?t.total:t.total_roots),this.refreshUI(),this.ctx.updateNotifies(t.unread||[]),this.ctx.trigger("list-loaded"),this.onAfterLoad&&this.onAfterLoad(t))}refreshPagination(t,e){const i="pagination"===this.pageMode,n="read-more"===this.pageMode;(i?!!this.pagination:!!this.readMoreBtn)||this.initPagination(),i&&this.pagination.update(t,e),n&&this.readMoreBtn.update(t,e)}initPagination(){if("read-more"===this.pageMode&&(this.readMoreBtn=new bt({pageSize:this.pageSize,onClick:t=>__async(this,null,(function*(){yield this.fetchComments(t)})),text:this.ctx.$t("loadMore")}),this.$el.append(this.readMoreBtn.$el),this.conf.pagination.autoLoad)){const t=this.scrollListenerAt||document;this.autoLoadScrollEvent&&t.removeEventListener("scroll",this.autoLoadScrollEvent),this.autoLoadScrollEvent=()=>{var t;if("read-more"!==this.pageMode||!(null==(t=this.readMoreBtn)?void 0:t.hasMore)||this.isLoading)return;const e=this.$el.querySelector(".atk-list-comments-wrap > .atk-comment-wrap:nth-last-child(3)");e&&function(t,e=document.documentElement){const i=e.clientHeight,n=e.scrollTop,s=n+i,a=t.getBoundingClientRect();return a.top+n+a.height<=s}(e,this.scrollListenerAt)&&this.readMoreBtn.click()},t.addEventListener("scroll",this.autoLoadScrollEvent)}"pagination"===this.pageMode&&(this.pagination=new kt(this.flatMode?this.data.total:this.data.total_roots,{pageSize:this.pageSize,onChange:t=>__async(this,null,(function*(){if(!0===this.ctx.conf.editorTravel&&this.ctx.editorTravelBack(),yield this.fetchComments(t),this.repositionAt){(this.scrollListenerAt||window).scroll({top:this.repositionAt?j(this.repositionAt).top:0,left:0})}}))}),this.$el.append(this.pagination.$el))}onError(t,e,i){var n;if(this.confLoaded||this.ctx.updateConf({}),t=String(t),console.error(t),0!==e&&"read-more"===this.pageMode)return void(null==(n=this.readMoreBtn)||n.showErr(this.$t("loadFail")));const s=N(`<span>${t},${this.$t("listLoadFailMsg")}<br/></span>`),a=N(`<span style="cursor:pointer;">${this.$t("listRetry")}</span>`);a.onclick=()=>this.fetchComments(0),s.appendChild(a);const r=N('<span atk-only-admin-show> | <span style="cursor:pointer;">打开控制台</span></span>');s.appendChild(r),this.ctx.user.data.isAdmin||r.classList.add("atk-hide");let o="";if(null==i?void 0:i.err_no_site){const t={create_name:this.ctx.conf.site,create_urls:`${window.location.protocol}//${window.location.host}`};o=`sites|${JSON.stringify(t)}`}r.onclick=()=>this.ctx.showSidebar({view:o}),at(this.$el,s)}refreshUI(){const t=this.ctx.getCommentList().length<=0;let e=this.$commentsWrap.querySelector(".atk-list-no-comment");t?e||(e=N('<div class="atk-list-no-comment"></div>'),e.innerHTML=this.noCommentText||this.ctx.conf.noComment||this.ctx.$t("noComment"),this.$commentsWrap.appendChild(e)):null==e||e.remove(),this.ctx.checkAdminShowEl()}reload(){this.fetchComments(0)}createComment(t,e){e||(e=this.ctx.getCommentDataList());const i=new vt(this.ctx,t,{isFlatMode:this.flatMode,afterRender:()=>{this.renderComment&&this.renderComment(i)},onDelete:t=>{this.ctx.deleteComment(t),this.refreshUI()},replyTo:t.rid?e.find((e=>e.id===t.rid)):void 0});return i.render(),this.ctx.getCommentList().push(i),i}importComments(t){this.flatMode?t.forEach((e=>{this.putCommentFlatMode(e,t,"append")})):this.importCommentsNest(t)}importCommentsNest(t){const e=function(t,e="DATE_DESC",i=2){const n=[];t.filter((t=>0===t.rid)).forEach((e=>{const s={id:e.id,comment:e,children:[],level:1};s.parent=s,n.push(s),function e(n){const s=t.filter((t=>t.rid===n.id));0!==s.length&&(n.level>=i&&(n=n.parent),s.forEach((t=>{const i={id:t.id,comment:t,children:[],parent:n,level:n.level+1};n.children.push(i),e(i)})))}(s)}));const s=(i,n)=>{let s=i.id-n.id;return"DATE_ASC"===e?s=+new Date(i.comment.date)-+new Date(n.comment.date):"DATE_DESC"===e?s=+new Date(n.comment.date)-+new Date(i.comment.date):"SRC_INDEX"===e?s=t.indexOf(i.comment)-t.indexOf(n.comment):"VOTE_UP_DESC"===e&&(s=n.comment.vote_up-i.comment.vote_up),s};return function t(e){e.forEach((e=>{e.children=e.children.sort(s),t(e.children)}))}(n),n}(t,this.nestSortBy,this.conf.nestMax);e.forEach((e=>{const i=this.createComment(e.comment,t);this.$commentsWrap.appendChild(i.getEl()),i.getRender().playFadeAnim();const n=this;!function e(i,s){s.children.forEach((s=>{const a=s.comment,r=n.createComment(a,t);i.putChild(r),e(r,s)}))}(i,e),i.getRender().checkHeightLimit()}))}putCommentFlatMode(t,e,i){t.is_collapsed&&(t.is_allow_reply=!1);const n=this.createComment(t,e);return t.visible&&("append"===i&&this.$commentsWrap.append(n.getEl()),"prepend"===i&&this.$commentsWrap.prepend(n.getEl()),n.getRender().playFadeAnim()),n.getRender().checkHeightLimit(),n}insertComment(t){if(this.flatMode){it(this.putCommentFlatMode(t,this.ctx.getCommentDataList(),"prepend").getEl())}else{const e=this.createComment(t);if(0===t.rid)this.$commentsWrap.prepend(e.getEl());else{const i=this.ctx.findComment(t.rid);i&&(i.putChild(e,"DATE_ASC"===this.nestSortBy?"append":"prepend"),e.getParents().forEach((t=>{t.getRender().heightLimitRemoveForChildren()})))}e.getRender().checkHeightLimit(),it(e.getEl()),e.getRender().playFadeAnim()}this.data&&(this.data.total+=1),this.refreshUI(),this.ctx.trigger("list-loaded"),this.ctx.trigger("list-inserted",t)}updateComment(t){const e=this.ctx.findComment(t.id);e&&e.setData(t)}updateUnread(t){this.unread=t,!0===this.unreadHighlight&&this.ctx.getCommentList().forEach((t=>{const e=this.unread.find((e=>e.comment_id===t.getID()));e?(t.getRender().setUnread(!0),t.getRender().setOpenAction((()=>{window.open(e.read_link),this.unread=this.unread.filter((e=>e.comment_id!==t.getID())),this.ctx.updateNotifies(this.unread)}))):t.getRender().setUnread(!1)}))}versionCheck(t,e,i){const n=1===function(t,e){const i=t.split("."),n=e.split(".");for(let s=0;s<3;s++){const t=Number(i[s]),e=Number(n[s]);if(t>e)return 1;if(e>t)return-1;if(!Number.isNaN(t)&&Number.isNaN(e))return 1;if(Number.isNaN(t)&&!Number.isNaN(e))return-1}return 0}(e,i);if(n){const n=N(`<div>Artalk ${this.$t(t)}版本已过时,请更新以获得完整体验<br/>如果你是管理员,请前往 “<a href="https://artalk.js.org/" target="_blank">官方文档</a>” 获得帮助<br/><br/><span style="color: var(--at-color-meta);">当前${this.$t(t)}版本 ${i},需求版本 >= ${e}</span><br/><br/></div>`),s=N('<span style="cursor:pointer;">忽略</span>');s.onclick=()=>{at(this.$el.parentElement,null),this.ctx.conf.versionCheck=!1,this.fetchComments(0)},n.append(s),at(this.$el.parentElement,n,'<span class="atk-warn-title">Artalk Warn</span>')}return n}}class wt extends xt{constructor(t){const e=N('<div class="atk-list">\n <div class="atk-list-header">\n <div class="atk-comment-count">\n <div class="atk-text"></div>\n </div>\n <div class="atk-right-action">\n <span data-action="admin-close-comment" class="atk-hide" atk-only-admin-show></span>\n <span data-action="open-sidebar" class="atk-hide atk-on">\n <span class="atk-unread-badge" style="display: none;"></span>\n <div class="atk-text"></div>\n </span>\n </div>\n </div>\n <div class="atk-list-body"></div>\n <div class="atk-list-footer">\n <div class="atk-copyright"></div>\n </div>\n</div>\n');super(t),__publicField(this,"$closeCommentBtn"),__publicField(this,"$openSidebarBtn"),__publicField(this,"$unreadBadge"),__publicField(this,"$commentCount"),__publicField(this,"$commentCountNum"),__publicField(this,"$dropdownWrap"),__publicField(this,"goToCommentFounded",!1),__publicField(this,"goToCommentDelay",!0),__publicField(this,"dropdownLoaded",!1),e.querySelector(".atk-list-body").append(this.$el),this.$el=e,this.repositionAt=this.$el,this.initListActionBtn(),this.$commentCount=this.$el.querySelector(".atk-comment-count"),this.$commentCount.innerHTML=this.$t("counter",{count:'<span class="atk-comment-count-num">0</span>'}),this.$commentCountNum=this.$commentCount.querySelector(".atk-comment-count-num"),this.$el.querySelector(".atk-copyright").innerHTML='Powered By <a href="https://artalk.js.org" target="_blank" title="Artalk v2.4.4">Artalk</a>'}initListActionBtn(){this.$openSidebarBtn=this.$el.querySelector('[data-action="open-sidebar"]'),this.$closeCommentBtn=this.$el.querySelector('[data-action="admin-close-comment"]'),this.$unreadBadge=this.$el.querySelector(".atk-unread-badge"),this.$openSidebarBtn.addEventListener("click",(()=>{this.ctx.showSidebar()})),this.$closeCommentBtn.addEventListener("click",(()=>{this.data&&(this.data.page.admin_only=!this.data.page.admin_only,this.adminPageEditSave())}))}refreshUI(){var t;super.refreshUI(),this.$commentCountNum.innerText=String(Number(null==(t=this.data)?void 0:t.total)||0),this.ctx.user.data.nick&&this.ctx.user.data.email?this.$openSidebarBtn.classList.remove("atk-hide"):this.$openSidebarBtn.classList.add("atk-hide"),this.ctx.checkAdminShowEl(),this.$openSidebarBtn.querySelector(".atk-text").innerText=this.ctx.user.data.isAdmin?this.$t("ctrlCenter"):this.$t("msgCenter"),this.data&&this.data.page&&!0===this.data.page.admin_only?(this.ctx.editorClose(),this.$closeCommentBtn.innerHTML=this.$t("openComment")):(this.ctx.editorOpen(),this.$closeCommentBtn.innerHTML=this.$t("closeComment")),this.ctx.conf.listSort&&this.initDropdown()}onLoad(t,e){super.onLoad(t,e),this.goToCommentFounded||this.checkGoToCommentByUrlHash(),!0===this.ctx.conf.editorTravel&&this.ctx.editorTravelBack()}checkGoToCommentByUrlHash(){let t=Number(H("atk_comment"));if(!t){const e=window.location.hash.match(/#atk-comment-([0-9]+)/);if(!e||!e[1]||Number.isNaN(Number(e[1])))return;t=Number(e[1])}if(!t)return;const e=this.ctx.findComment(t);if(!e)return void(this.readMoreBtn?this.readMoreBtn.click():this.pagination&&this.pagination.next());const i=H("atk_notify_key");i&&this.ctx.getApi().user.markRead(i).then((()=>{this.unread=this.unread.filter((e=>e.comment_id!==t)),this.updateUnread(this.unread)})),e.getParents().forEach((t=>{t.getRender().heightLimitRemoveForChildren()}));const n=()=>{it(e.getEl(),!1),e.getEl().classList.remove("atk-flash-once"),window.setTimeout((()=>{e.getEl().classList.add("atk-flash-once")}),150)};this.goToCommentDelay?window.setTimeout((()=>n()),350):n(),this.goToCommentFounded=!0}adminPageEditSave(){this.data&&this.data.page&&(this.ctx.editorShowLoading(),this.ctx.getApi().page.pageEdit(this.data.page).then((t=>{this.data&&(this.data.page=__spreadValues({},t)),this.refreshUI()})).catch((t=>{this.ctx.editorShowNotify(`${this.$t("editFail")}: ${t.msg||String(t)}`,"e")})).finally((()=>{this.ctx.editorHideLoading()})))}showUnreadBadge(t){t>0?(this.$unreadBadge.innerText=`${Number(t||0)}`,this.$unreadBadge.style.display="block"):this.$unreadBadge.style.display="none"}initDropdown(){if(this.dropdownLoaded)return;this.dropdownLoaded=!0,this.$dropdownWrap=this.$commentCount,this.$commentCount.classList.add("atk-dropdown-wrap"),this.$dropdownWrap.append(N('<span class="atk-arrow-down-icon"></span>'));const t=t=>{this.paramsEditor=e=>{t(e)},this.fetchComments(0)},e=[[this.$t("sortLatest"),()=>{t((t=>{t.sort_by="date_desc"}))}],[this.$t("sortBest"),()=>{t((t=>{t.sort_by="vote"}))}],[this.$t("sortOldest"),()=>{t((t=>{t.sort_by="date_asc"}))}],[this.$t("sortAuthor"),()=>{t((t=>{t.view_only_admin=!0}))}]];let i=0;const n=N('<ul class="atk-dropdown atk-fade-in"></ul>');e.forEach(((t,e)=>{const s=t[0],a=t[1],r=N('<li class="atk-dropdown-item"><span></span></li>'),o=r.querySelector("span");o.innerText=s,o.onclick=()=>{((t,e,s,a)=>{a(),i=t,n.querySelectorAll(".active").forEach((t=>{t.classList.remove("active")})),e.classList.add("active"),n.style.display="none",setTimeout((()=>{n.style.display=""}),80)})(e,r,0,a)},n.append(r),e===i&&r.classList.add("active")})),this.$dropdownWrap.append(n)}updateUnread(t){super.updateUnread(t),this.showUnreadBadge((null==t?void 0:t.length)||0)}}class Ct{constructor(t,e){__publicField(this,"api"),__publicField(this,"editor"),__publicField(this,"list"),__publicField(this,"sidebarLayer"),__publicField(this,"checkerLauncher"),__publicField(this,"cid"),__publicField(this,"conf"),__publicField(this,"user"),__publicField(this,"$root"),__publicField(this,"markedInstance"),__publicField(this,"markedReplacers",[]),__publicField(this,"commentList",[]),__publicField(this,"eventList",[]),__publicField(this,"darkModeMedia",window.matchMedia("(prefers-color-scheme: dark)")),__publicField(this,"darkModeAutoFunc"),this.cid=+new Date,this.conf=t,this.user=new s(this),this.$root=e||document.createElement("div"),this.$root.setAttribute("atk-run-id",this.cid.toString()),this.$root.classList.add("artalk"),this.$root.innerHTML="",this.api=new pt(this),this.on("conf-loaded",(()=>{this.refreshDarkModeConf()}))}setApi(t){this.api=t}setEditor(t){this.editor=t}setList(t){this.list=t}setSidebarLayer(t){this.sidebarLayer=t}setCheckerLauncher(t){this.checkerLauncher=t}getApi(){return this.api}getCommentList(){return this.commentList}getCommentDataList(){return this.commentList.map((t=>t.getData()))}findComment(t){return this.commentList.find((e=>e.getData().id===t))}deleteComment(t){let e;if("number"==typeof t){const i=this.findComment(t);if(!i)throw Error(`Comment ${t} cannot be found`);e=i}else e=t;if(e.getEl().remove(),this.commentList.splice(this.commentList.indexOf(e),1),this.list){const t=this.list.getData();t&&(t.total-=1),this.list.refreshUI()}}clearAllComments(){this.list&&(this.list.getCommentsWrapEl().innerHTML="",this.list.clearData()),this.commentList=[]}insertComment(t){var e;null==(e=this.list)||e.insertComment(t)}updateComment(t){var e;null==(e=this.list)||e.updateComment(t)}replyComment(t,e,i){this.editor.setReply(t,e,i)}cancelReplyComment(){this.editor.cancelReply()}editComment(t,e){this.editor.setEditComment(t,e)}cancelEditComment(){this.editor.cancelEditComment()}updateNotifies(t){var e;null==(e=this.list)||e.updateUnread(t)}listReload(){var t;null==(t=this.list)||t.reload()}reload(){this.listReload()}listRefreshUI(){var t;null==(t=this.list)||t.refreshUI()}listHashGotoCheck(){if(!this.list||this.list instanceof wt)return;const t=this.list;t.goToCommentDelay=!1,t.checkGoToCommentByUrlHash()}editorOpen(){this.editor.open()}editorClose(){this.editor.close()}editorShowLoading(){this.editor.showLoading()}editorHideLoading(){this.editor.hideLoading()}editorShowNotify(t,e){this.editor.showNotify(t,e)}editorTravel(t){this.editor.travel(t)}editorTravelBack(){this.editor.travelBack()}showSidebar(t){this.sidebarLayer.show(t)}hideSidebar(){this.sidebarLayer.hide()}checkAdmin(t){this.checkerLauncher.checkAdmin(t)}checkCaptcha(t){this.checkerLauncher.checkCaptcha(t)}checkAdminShowEl(){const t=[];this.$root.querySelectorAll("[atk-only-admin-show]").forEach((e=>t.push(e)));const{$wrap:e}=lt(this);e&&e.querySelectorAll("[atk-only-admin-show]").forEach((e=>t.push(e)));const i=document.querySelector(".atk-sidebar");i&&i.querySelectorAll("[atk-only-admin-show]").forEach((e=>t.push(e))),t.forEach((t=>{this.user.data.isAdmin?t.classList.remove("atk-hide"):t.classList.add("atk-hide")}))}on(t,e,i="internal"){this.eventList.push({name:t,handler:e,scope:i})}off(t,e,i="internal"){this.eventList=this.eventList.filter((n=>e?!(n.name===t&&n.handler===e&&n.scope===i):!(n.name===t&&n.scope===i)))}trigger(t,e,i){this.eventList.filter((e=>e.name===t&&(!i||e.scope===i))).map((t=>t.handler)).forEach((t=>t(e)))}$t(t,e={}){return n(this.conf.locale,t,e)}setDarkMode(t){const e="atk-dark-mode";this.conf.darkMode=t,t?this.$root.classList.add(e):this.$root.classList.remove(e);const{$wrap:i}=lt(this);i&&(t?i.classList.add(e):i.classList.remove(e))}refreshDarkModeConf(){"auto"===this.conf.darkMode?(this.setDarkMode(this.darkModeMedia.matches),this.darkModeAutoFunc||(this.darkModeAutoFunc=t=>{this.setDarkMode(t.matches)},this.darkModeMedia.addEventListener("change",this.darkModeAutoFunc))):(this.darkModeAutoFunc&&this.darkModeMedia.removeEventListener("change",this.darkModeAutoFunc),this.setDarkMode(this.conf.darkMode||!1))}updateConf(t){this.conf=J(this.conf,t),this.trigger("conf-loaded")}}const St={el:"",pageKey:"",pageTitle:"",server:"",site:"",placeholder:"",noComment:"",sendBtn:"",darkMode:!1,editorTravel:!0,flatMode:"auto",nestMax:2,nestSort:"DATE_ASC",emoticons:"https://cdn.jsdelivr.net/gh/ArtalkJS/Emoticons/grps/default.json",vote:!0,voteDown:!1,uaBadge:!0,listSort:!0,preview:!0,countEl:"#ArtalkCount",pvEl:"#ArtalkPV",gravatar:{default:"mp",mirror:"https://cravatar.cn/avatar/"},pagination:{pageSize:20,readMore:!0,autoLoad:!0},heightLimit:{content:300,children:400},imgUpload:!0,reqTimeout:15e3,versionCheck:!0,useBackendConf:!0,locale:"zh-CN"};St.vote=!1,St.uaBadge=!1,St.emoticons=!1;class Lt{constructor(t,e){return __publicField(this,"ctx"),__publicField(this,"$el"),__publicField(this,"$content"),__publicField(this,"$actions"),this.ctx=t,this.$el=N('<div class="atk-layer-dialog-wrap">\n <div class="atk-layer-dialog">\n <div class="atk-layer-dialog-content"></div>\n <div class="atk-layer-dialog-actions"></div>\n </div>\n </div>'),this.$actions=this.$el.querySelector(".atk-layer-dialog-actions"),this.$content=this.$el.querySelector(".atk-layer-dialog-content"),this.$content.appendChild(e),this}setYes(t){const e=N(`<button data-action="confirm">${this.ctx.$t("confirm")}</button>`);return e.onclick=this.onBtnClick(t),this.$actions.appendChild(e),this}setNo(t){const e=N(`<button data-action="cancel">${this.ctx.$t("cancel")}</button>`);return e.onclick=this.onBtnClick(t),this.$actions.appendChild(e),this}onBtnClick(t){return e=>{const i=t(e.currentTarget,this);void 0!==i&&!0!==i||this.$el.remove()}}}const Tt={request:(t,e,i)=>t.ctx.getApi().captcha.captchaCheck(i),body(t,e){if(t.captchaConf.iframe){const i=N('<div class="atk-checker-iframe-wrap"></div>'),n=N('<iframe class="atk-fade-in"></iframe>');n.style.display="none",tt(i,{transparentBg:!0}),n.src=`${t.ctx.conf.server}/api/captcha/get?t=${+new Date}`,n.onload=()=>{n.style.display="",et(i)},i.append(n);const s=N('<div class="atk-close-btn"><i class="atk-icon atk-icon-close"></i></div>');i.append(s),e.hideInteractInput();let a=!1;const r=t=>new Promise((e=>{window.setTimeout((()=>{e(null)}),t)}));return function i(){return __async(this,null,(function*(){if(yield r(1e3),a)return;let n=!1;try{n=(yield t.ctx.getApi().captcha.captchaStatus()).is_pass}catch(s){n=!1}n?e.triggerSuccess():i()}))}(),s.onclick=()=>{a=!0,e.cancel()},i}const i=N(`<span><img class="atk-captcha-img" src="${t.captchaConf.imgData||""}">${t.ctx.$t("captchaCheck")}</span>`);return i.querySelector(".atk-captcha-img").onclick=()=>{const e=i.querySelector(".atk-captcha-img");t.ctx.getApi().captcha.captchaGet().then((t=>{e.setAttribute("src",t)})).catch((t=>{console.error("Failed to get captcha image ",t)}))},i},onSuccess(t,e,i,n,s){t.captchaConf.val=n},onError(t,e,i,n,s){s.querySelector(".atk-captcha-img").click(),s.querySelector('input[type="text"]').value=""}},Et={inputType:"password",request(t,e,i){const n={name:t.ctx.user.data.nick,email:t.ctx.user.data.email,password:i};return(()=>__async(this,null,(function*(){return(yield t.ctx.getApi().user.login(n.name,n.email,n.password)).token})))()},body:(t,e)=>N(`<span>${t.ctx.$t("adminCheck")}</span>`),onSuccess(t,e,i,n,s){t.ctx.user.update({isAdmin:!0,token:i}),t.ctx.trigger("user-changed",t.ctx.user.data),t.ctx.listReload()},onError(t,e,i,n,s){}};class At{constructor(t){__publicField(this,"ctx"),__publicField(this,"launched",[]),__publicField(this,"captchaConf",{}),this.ctx=t}checkCaptcha(t){this.captchaConf.imgData=t.imgData,this.captchaConf.iframe=t.iframe,this.fire(Tt,t)}checkAdmin(t){this.fire(Et,t)}fire(t,e){if(this.launched.includes(t))return;this.launched.push(t);const i=new ot(this.ctx,`checker-${(new Date).getTime()}`);i.setMaskClickHide(!1),i.show();let n=!1;const s={getLayer:()=>i,hideInteractInput:()=>{n=!0},triggerSuccess:()=>{this.close(t,i),t.onSuccess&&t.onSuccess(this,s,"","",a),e.onSuccess&&e.onSuccess("",l.$el)},cancel:()=>{this.close(t,i),e.onCancel&&e.onCancel()}},a=N();a.appendChild(t.body(this,s));const r=N(`<input id="check" type="${t.inputType||"text"}" autocomplete="off" required placeholder="">`);let o;a.appendChild(r),setTimeout((()=>r.focus()),80),r.onkeyup=t=>{"Enter"!==t.key&&13!==t.keyCode||(t.preventDefault(),i.getEl().querySelector('button[data-action="confirm"]').click())};const l=new Lt(this.ctx,a);l.setYes((n=>{const c=r.value.trim();o||(o=n.innerText);const d=()=>{n.innerText=o||"",n.classList.remove("error")};return n.innerText=`${this.ctx.$t("loading")}...`,t.request(this,s,c).then((n=>{this.close(t,i),t.onSuccess&&t.onSuccess(this,s,n,c,a),e.onSuccess&&e.onSuccess(c,l.$el)})).catch((e=>{var i;i=String(e.msg||String(e)),n.innerText=i,n.classList.add("error"),t.onError&&t.onError(this,s,e,c,a);const o=setTimeout((()=>d()),3e3);r.onfocus=()=>{d(),clearTimeout(o)}})),!1})),l.setNo((()=>(this.close(t,i),e.onCancel&&e.onCancel(),!1))),n&&(r.style.display="none",l.$el.querySelector(".atk-layer-dialog-actions").style.display="none"),i.getEl().append(l.$el),e.onMount&&e.onMount(l.$el)}close(t,e){e.disposeNow(),this.launched=this.launched.filter((e=>e!==t))}}class Ft{constructor(t){__publicField(this,"editor"),__publicField(this,"$panel"),__publicField(this,"$btn"),__publicField(this,"onHeaderInput"),this.editor=t}get ctx(){return this.editor.ctx}registerPanel(t="<div></div>"){return this.$panel=N(t),this.$panel}registerBtn(t){return this.$btn=N(`<span class="atk-plug-btn" data-plug-name="${this.constructor.name}">${t}</span>`),this.$btn}registerHeaderInputEvt(t){this.onHeaderInput=t}getPanel(){return this.$panel}getBtn(){return this.$btn}}__publicField(Ft,"Name");class Mt extends Ft{constructor(t){super(t),__publicField(this,"emoticons",[]),__publicField(this,"loadingTask",null),__publicField(this,"$grpWrap"),__publicField(this,"$grpSwitcher"),__publicField(this,"isListLoaded",!1),__publicField(this,"isImgLoaded",!1),this.editor=t,this.registerPanel('<div class="atk-editor-plug-emoticons"></div>'),this.registerBtn(this.ctx.$t("emoticon")),window.setTimeout((()=>{this.loadEmoticonsData()}),1e3)}onPanelShow(){(()=>{__async(this,null,(function*(){yield this.loadEmoticonsData(),this.isImgLoaded||(this.initEmoticonsList(),this.isImgLoaded=!0),setTimeout((()=>{this.changeListHeight()}),30)}))})()}onPanelHide(){this.$panel.parentElement.style.height=""}loadEmoticonsData(){return __async(this,null,(function*(){this.isListLoaded||(null===this.loadingTask?(this.loadingTask=(()=>__async(this,null,(function*(){tt(this.$panel),this.emoticons=yield this.handleData(this.ctx.conf.emoticons),et(this.$panel),this.loadingTask=null,this.isListLoaded=!0})))(),yield this.loadingTask):yield this.loadingTask)}))}handleData(t){return __async(this,null,(function*(){if(!Array.isArray(t)&&["object","string"].includes(typeof t)&&(t=[t]),!Array.isArray(t))return at(this.$panel,"表情包数据必须为 Array/Object/String 类型"),et(this.$panel),[];const e=e=>{"object"==typeof e&&(e.name&&t.find((t=>t.name===e.name))||t.push(e))},i=t=>__async(this,null,(function*(){yield Promise.all(t.map(((t,n)=>__async(this,null,(function*(){if("object"!=typeof t||Array.isArray(t)){if(Array.isArray(t))yield i(t);else if("string"==typeof t){const n=yield this.remoteLoad(t);Array.isArray(n)?yield i(n):"object"==typeof n&&e(n)}}else e(t)})))))}));return yield i(t),t.forEach((t=>{if(this.isOwOFormat(t)){this.convertOwO(t).forEach((t=>{e(t)}))}else Array.isArray(t)&&t.forEach((t=>{e(t)}))})),t=t.filter((t=>"object"==typeof t&&!Array.isArray(t)&&!!t&&!!t.name)),this.solveNullKey(t),this.solveSameKey(t),t}))}remoteLoad(t){return __async(this,null,(function*(){if(!t)return[];try{const e=yield fetch(t);return yield e.json()}catch(e){return et(this.$panel),at(this.$panel,`表情加载失败 ${String(e)}`),[]}}))}solveNullKey(t){t.forEach((t=>{t.items.forEach(((e,i)=>{e.key||(e.key=`${t.name} ${i+1}`)}))}))}solveSameKey(t){const e={};t.forEach((t=>{t.items.forEach((t=>{t.key&&""!==String(t.key).trim()&&(e[t.key]?e[t.key]++:e[t.key]=1,e[t.key]>1&&(t.key=`${t.key} ${e[t.key]}`))}))}))}isOwOFormat(t){try{return"object"==typeof t&&!!Object.values(t).length&&Array.isArray(Object.keys(Object.values(t)[0].container))&&Object.keys(Object.values(t)[0].container[0]).includes("icon")}catch(e){return!1}}convertOwO(t){const e=[];return Object.entries(t).forEach((([t,i])=>{const n={name:t,type:i.type,items:[]};i.container.forEach(((e,i)=>{const s=e.icon;if(/<(img|IMG)/.test(s)){const t=/src=["'](.*?)["']/.exec(s);t&&t.length>1&&(e.icon=t[1])}n.items.push({key:e.text||`${t} ${i+1}`,val:e.icon})})),e.push(n)})),e}initEmoticonsList(){this.$grpWrap=N('<div class="atk-grp-wrap"></div>'),this.$panel.append(this.$grpWrap),this.emoticons.forEach(((t,e)=>{const i=N('<div class="atk-grp" style="display: none;"></div>');this.$grpWrap.append(i),i.setAttribute("data-index",String(e)),i.setAttribute("data-grp-name",t.name),i.setAttribute("data-type",t.type),t.items.forEach((e=>{const n=N('<span class="atk-item"></span>');if(i.append(n),e.key&&!new RegExp(`^(${t.name})?\\s?[0-9]+$`).test(e.key)&&n.setAttribute("title",e.key),"image"===t.type){const t=document.createElement("img");t.src=e.val,t.alt=e.key,n.append(t)}else n.innerText=e.val;n.onclick=()=>{"image"===t.type?this.editor.insertContent(`:[${e.key}]`):this.editor.insertContent(e.val||"")}}))})),this.emoticons.length>1&&(this.$grpSwitcher=N('<div class="atk-grp-switcher"></div>'),this.$panel.append(this.$grpSwitcher),this.emoticons.forEach(((t,e)=>{const i=N("<span />");i.innerText=t.name,i.setAttribute("data-index",String(e)),i.onclick=()=>this.openGrp(e),this.$grpSwitcher.append(i)}))),this.emoticons.length>0&&this.openGrp(0)}openGrp(t){var e,i,n;Array.from(this.$grpWrap.children).forEach((e=>{const i=e;i.getAttribute("data-index")!==String(t)?i.style.display="none":i.style.display=""})),null==(e=this.$grpSwitcher)||e.querySelectorAll("span.active").forEach((t=>t.classList.remove("active"))),null==(n=null==(i=this.$grpSwitcher)?void 0:i.querySelector(`span[data-index="${t}"]`))||n.classList.add("active"),this.changeListHeight()}changeListHeight(){}transEmoticonImageText(t){return this.emoticons&&Array.isArray(this.emoticons)?(this.emoticons.forEach((e=>{"image"===e.type&&Object.entries(e.items).forEach((([e,i])=>{t=t.split(`:[${i.key}]`).join(`<img src="${i.val}" atk-emoticon="${i.key}">`)}))})),t):t}}__publicField(Mt,"Name","emoticons");class Ot extends Ft{constructor(t){super(t),__publicField(this,"$imgUploadInput"),__publicField(this,"allowImgExts",["png","jpg","jpeg","gif","bmp","svg","webp"]),this.$imgUploadInput=document.createElement("input"),this.$imgUploadInput.type="file",this.$imgUploadInput.style.display="none",this.$imgUploadInput.accept=this.allowImgExts.map((t=>`.${t}`)).join(",");const e=this.registerBtn(`${this.ctx.$t("image")}`);e.after(this.$imgUploadInput),e.onclick=()=>{const t=this.$imgUploadInput;t.onchange=()=>{(()=>{__async(this,null,(function*(){if(!t.files||0===t.files.length)return;const e=t.files[0];this.uploadImg(e)}))})()},t.click()},this.ctx.on("conf-loaded",(()=>{this.ctx.conf.imgUpload||(this.getBtn().setAttribute("atk-only-admin-show",""),this.ctx.checkAdminShowEl())}));const i=t=>{if(t)for(let e=0;e<t.length;e++){const i=t[e];this.uploadImg(i)}};this.editor.$textarea.addEventListener("dragover",(t=>{t.stopPropagation(),t.preventDefault()})),this.editor.$textarea.addEventListener("drop",(t=>{var e;const n=null==(e=t.dataTransfer)?void 0:e.files;(null==n?void 0:n.length)&&(t.preventDefault(),i(n))})),this.editor.$textarea.addEventListener("paste",(t=>{var e;const n=null==(e=t.clipboardData)?void 0:e.files;(null==n?void 0:n.length)&&(t.preventDefault(),i(n))}))}uploadImg(t){return __async(this,null,(function*(){const e=/[^.]+$/.exec(t.name);if(!e||!this.allowImgExts.includes(e[0]))return;if(!this.ctx.user.checkHasBasicUserInfo())return void this.editor.showNotify(this.ctx.$t("uploadLoginMsg"),"w");let i="\n";""===this.editor.$textarea.value.trim()&&(i="");const n=`${i}![](Uploading ${t.name}...)`;let s;this.editor.insertContent(n);try{s=this.ctx.conf.imgUploader?{img_url:yield this.ctx.conf.imgUploader(t)}:yield this.ctx.getApi().upload.imgUpload(t)}catch(a){console.error(a),this.editor.showNotify(`${this.ctx.$t("uploadFail")},${a.msg}`,"e")}if(s&&s.img_url){let t=s.img_url;Y(t)||(t=X(this.ctx,t)),this.editor.setContent(this.editor.$textarea.value.replace(n,`${i}![](${t})`))}else this.editor.setContent(this.editor.$textarea.value.replace(n,""))}))}}__publicField(Ot,"Name","upload");class Bt extends Ft{constructor(t){super(t),__publicField(this,"isBind",!1),this.registerPanel('<div class="atk-editor-plug-preview"></div>');let e=this.editor.$t("preview");this.ctx.markedInstance&&(e+=' <i title="Markdown is supported"><svg class="markdown" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M14.85 3H1.15C.52 3 0 3.52 0 4.15v7.69C0 12.48.52 13 1.15 13h13.69c.64 0 1.15-.52 1.15-1.15v-7.7C16 3.52 15.48 3 14.85 3zM9 11H7V8L5.5 9.92 4 8v3H2V5h2l1.5 2L7 5h2v6zm2.99.5L9.5 8H11V5h2v3h1.5l-2.51 3.5z"></path></svg></i>'),this.registerBtn(e)}onPanelShow(){if(this.updateContent(),!this.isBind){const t=()=>{this.updateContent()};this.editor.$textarea.addEventListener("input",t),this.editor.$textarea.addEventListener("change",t),this.isBind=!0}}updateContent(){"none"!==this.$panel.style.display&&(this.$panel.innerHTML=this.editor.getContentMarked())}}__publicField(Bt,"Name","preview");class Pt extends Ft{constructor(t){super(t),__publicField(this,"queryUserInfo",{timeout:null,abortFunc:null}),this.registerHeaderInputEvt(((t,e)=>{"nick"!==t&&"email"!==t||this.fetchUserInfo()})),this.editor.$link.addEventListener("change",(()=>{const t=this.editor.$link.value.trim();t&&!/^(http|https):\/\//.test(t)&&(this.editor.$link.value=`https://${t}`,this.ctx.user.update({link:this.editor.$link.value}))}))}fetchUserInfo(){this.ctx.user.logout(),this.queryUserInfo.timeout&&window.clearTimeout(this.queryUserInfo.timeout),this.queryUserInfo.abortFunc&&this.queryUserInfo.abortFunc(),this.queryUserInfo.timeout=window.setTimeout((()=>{this.queryUserInfo.timeout=null;const{req:t,abort:e}=this.ctx.getApi().user.userGet(this.ctx.user.data.nick,this.ctx.user.data.email);this.queryUserInfo.abortFunc=e,t.then((t=>{var e;t.is_login||this.ctx.user.logout(),this.ctx.updateNotifies(t.unread),this.ctx.user.checkHasBasicUserInfo()&&!t.is_login&&(null==(e=t.user)?void 0:e.is_admin)&&this.showLoginDialog(),t.user&&t.user.link&&(this.editor.$link.value=t.user.link,this.ctx.user.update({link:t.user.link}))})).catch((()=>{})).finally((()=>{this.queryUserInfo.abortFunc=null}))}),400)}showLoginDialog(){this.ctx.checkAdmin({onSuccess:()=>{}})}}__publicField(Pt,"Name","headerInput");class Rt extends Z{constructor(t){super(t),__publicField(this,"$header"),__publicField(this,"$nick"),__publicField(this,"$email"),__publicField(this,"$link"),__publicField(this,"$textareaWrap"),__publicField(this,"$textarea"),__publicField(this,"$bottom"),__publicField(this,"$submitBtn"),__publicField(this,"$notifyWrap"),__publicField(this,"isTraveling",!1),__publicField(this,"replyComment",null),__publicField(this,"$sendReply",null),__publicField(this,"editComment",null),__publicField(this,"$editCancelBtn",null),__publicField(this,"ENABLED_PLUGS",[Mt,Ot,Bt,Pt]),__publicField(this,"plugList",{}),__publicField(this,"openedPlugName",null),__publicField(this,"$plugPanelWrap"),__publicField(this,"$plugBtnWrap"),this.$el=N('<div class="atk-main-editor">\n <div class="atk-header">\n <input name="nick" class="atk-nick" type="text" required="required">\n <input name="email" class="atk-email" type="email" required="required">\n <input name="link" class="atk-link" type="url">\n </div>\n <div class="atk-textarea-wrap">\n <textarea class="atk-textarea"></textarea>\n </div>\n <div class="atk-plug-panel-wrap" style="display: none;"></div>\n <div class="atk-bottom">\n <div class="atk-item atk-plug-btn-wrap"></div>\n <div class="atk-item">\n <button type="button" class="atk-send-btn"></button>\n </div>\n </div>\n <div class="atk-notify-wrap"></div>\n</div>\n'),this.$header=this.$el.querySelector(".atk-header"),this.$nick=this.$header.querySelector('[name="nick"]'),this.$email=this.$header.querySelector('[name="email"]'),this.$link=this.$header.querySelector('[name="link"]'),this.$textareaWrap=this.$el.querySelector(".atk-textarea-wrap"),this.$textarea=this.$el.querySelector(".atk-textarea"),this.$bottom=this.$el.querySelector(".atk-bottom"),this.$submitBtn=this.$el.querySelector(".atk-send-btn"),this.$notifyWrap=this.$el.querySelector(".atk-notify-wrap"),this.$plugBtnWrap=this.$el.querySelector(".atk-plug-btn-wrap"),this.$plugPanelWrap=this.$el.querySelector(".atk-plug-panel-wrap"),this.ctx.on("conf-loaded",(()=>{this.initLocalStorage(),this.initHeader(),this.initTextarea(),this.initSubmitBtn(),this.initPlugs()}))}get user(){return this.ctx.user}get $inputs(){return{nick:this.$nick,email:this.$email,link:this.$link}}get isReplyMode(){return null!==this.replyComment}get isEditMode(){return null!==this.editComment}initLocalStorage(){const t=window.localStorage.getItem("ArtalkContent")||"";""!==t.trim()&&(this.showNotify(this.$t("restoredMsg"),"i"),this.setContent(t)),this.$textarea.addEventListener("input",(()=>this.saveToLocalStorage()))}saveToLocalStorage(){window.localStorage.setItem("ArtalkContent",this.getContentOriginal().trim())}initHeader(){Object.entries(this.$inputs).forEach((([t,e])=>{e.value=this.user.data[t]||"",e.addEventListener("input",(()=>this.onHeaderInput(t,e))),e.placeholder=`${this.$t(t)}`}))}onHeaderInput(t,e){this.isEditMode||(this.user.update({[t]:e.value.trim()}),Object.entries(this.plugList).forEach((([i,n])=>{n.onHeaderInput&&n.onHeaderInput(t,e)})))}initTextarea(){this.$textarea.placeholder=this.ctx.conf.placeholder||this.$t("placeholder"),this.$textarea.addEventListener("keydown",(t=>{9===(t.keyCode||t.which)&&(t.preventDefault(),this.insertContent("\t"))})),this.$textarea.addEventListener("input",(()=>{this.adjustTextareaHeight()}))}refreshSendBtnText(){this.isEditMode?this.$submitBtn.innerText=this.$t("save"):this.$submitBtn.innerText=this.ctx.conf.sendBtn||this.$t("send")}initSubmitBtn(){this.refreshSendBtnText(),this.$submitBtn.addEventListener("click",(()=>this.submit()))}getFinalContent(){let t=this.getContentOriginal();return this.plugList.emoticons&&(t=this.plugList.emoticons.transEmoticonImageText(t)),t}getContentOriginal(){return this.$textarea.value||""}getContentMarked(){return Q(this.ctx,this.getFinalContent())}setContent(t){this.$textarea.value=t,this.saveToLocalStorage(),this.plugList.preview&&this.plugList.preview.updateContent(),window.setTimeout((()=>{this.adjustTextareaHeight()}),80)}insertContent(t){if(document.selection)this.$textarea.focus(),document.selection.createRange().text=t,this.$textarea.focus();else if(this.$textarea.selectionStart||0===this.$textarea.selectionStart){const e=this.$textarea.selectionStart,i=this.$textarea.selectionEnd,n=this.$textarea.scrollTop;this.setContent(this.$textarea.value.substring(0,e)+t+this.$textarea.value.substring(i,this.$textarea.value.length)),this.$textarea.focus(),this.$textarea.selectionStart=e+t.length,this.$textarea.selectionEnd=e+t.length,this.$textarea.scrollTop=n}else this.$textarea.focus(),this.$textarea.value+=t}adjustTextareaHeight(){const t=this.$textarea.offsetHeight-this.$textarea.clientHeight;this.$textarea.style.height="0px",this.$textarea.style.height=`${this.$textarea.scrollHeight+t}px`}setReply(t,e,i=!0){this.isEditMode&&this.cancelEditComment(),this.isReplyMode&&this.cancelReply(),null===this.$sendReply&&(this.$sendReply=N(`<div class="atk-send-reply">${this.$t("reply")} <span class="atk-text"></span><span class="atk-cancel">×</span></div>`),this.$sendReply.querySelector(".atk-text").innerText=`@${t.nick}`,this.$sendReply.addEventListener("click",(()=>{this.cancelReply()})),this.$textareaWrap.append(this.$sendReply)),this.replyComment=t,!0===this.ctx.conf.editorTravel&&this.travel(e),i&&it(this.$el),this.$textarea.focus()}cancelReply(){null!==this.$sendReply&&(this.$sendReply.remove(),this.$sendReply=null),this.replyComment=null,!0===this.ctx.conf.editorTravel&&this.travelBack()}setEditComment(t,e){this.isEditMode&&this.cancelEditComment(),this.isReplyMode&&this.cancelReply(),null===this.$editCancelBtn&&(this.$editCancelBtn=N(`<div class="atk-send-reply">${this.$t("editCancel")}<span class="atk-cancel">×</span></div>`),this.$editCancelBtn.onclick=()=>{this.cancelEditComment()},this.$textareaWrap.append(this.$editCancelBtn)),this.editComment=t,this.$header.style.display="none",this.travel(e),this.$nick.value=t.nick,this.$email.value=t.email||"",this.$link.value=t.link,this.setContent(t.content),this.$textarea.focus(),this.refreshSendBtnText()}cancelEditComment(){null!==this.$editCancelBtn&&(this.$editCancelBtn.remove(),this.$editCancelBtn=null),this.editComment=null,this.travelBack(),this.$nick.value=this.user.data.nick,this.$email.value=this.user.data.email,this.$link.value=this.user.data.link,this.setContent(""),this.refreshSendBtnText(),this.$header.style.display=""}showNotify(t,e){nt(this.$notifyWrap,t,e)}showLoading(){tt(this.$el)}hideLoading(){et(this.$el)}submit(){return __async(this,null,(function*(){""!==this.getFinalContent().trim()?(this.ctx.trigger("editor-submit"),this.showLoading(),this.isEditMode?yield this.submitEdit():yield this.submitAdd(),this.hideLoading()):this.$textarea.focus()}))}submitAdd(){return __async(this,null,(function*(){try{const t=yield this.ctx.getApi().comment.add({content:this.getFinalContent(),nick:this.user.data.nick,email:this.user.data.email,link:this.user.data.link,rid:null===this.replyComment?0:this.replyComment.id,page_key:null===this.replyComment?this.ctx.conf.pageKey:this.replyComment.page_key,page_title:null===this.replyComment?this.ctx.conf.pageTitle:void 0,site_name:null===this.replyComment?this.ctx.conf.site:this.replyComment.site_name});null!==this.replyComment&&this.replyComment.page_key!==this.ctx.conf.pageKey&&window.open(`${this.replyComment.page_url}#atk-comment-${t.id}`),this.ctx.insertComment(t),this.setContent(""),this.cancelReply(),this.ctx.trigger("editor-submitted")}catch(t){console.error(t),this.showNotify(`${this.$t("commentFail")},${t.msg||String(t)}`,"e")}}))}submitEdit(){return __async(this,null,(function*(){try{const t={content:this.getFinalContent(),nick:this.$nick.value,email:this.$email.value,link:this.$link.value},e=yield this.ctx.getApi().comment.commentEdit(__spreadValues(__spreadValues({},this.editComment),t));this.ctx.updateComment(e),this.setContent(""),this.cancelEditComment(),this.ctx.trigger("editor-submitted")}catch(t){console.error(t),this.showNotify(`${this.$t("commentFail")},${t.msg||String(t)}`,"e")}}))}close(){this.$textareaWrap.querySelector(".atk-comment-closed")||this.$textareaWrap.prepend(N(`<div class="atk-comment-closed">${this.$t("onlyAdminCanReply")}</div>`)),this.user.data.isAdmin?(this.$textarea.style.display="",this.$bottom.style.display=""):(this.$textarea.style.display="none",this.closePlugPanel(),this.$bottom.style.display="none")}open(){var t;null==(t=this.$textareaWrap.querySelector(".atk-comment-closed"))||t.remove(),this.$textarea.style.display="",this.$bottom.style.display=""}travel(t){if(this.isTraveling)return;this.isTraveling=!0,this.$el.after(N('<div class="atk-editor-travel-placeholder"></div>'));const e=N("<div></div>");t.after(e),e.replaceWith(this.$el),this.$el.classList.add("atk-fade-in")}travelBack(){var t;this.isTraveling&&(this.isTraveling=!1,null==(t=this.ctx.$root.querySelector(".atk-editor-travel-placeholder"))||t.replaceWith(this.$el),null!==this.replyComment&&this.cancelReply())}initPlugs(){this.plugList={},this.$plugPanelWrap.innerHTML="",this.$plugPanelWrap.style.display="none",this.openedPlugName=null,this.$plugBtnWrap.innerHTML="";const t=[];this.conf.imgUpload||t.push("upload"),this.conf.emoticons||t.push("emoticons"),this.conf.preview||t.push("preview"),this.ENABLED_PLUGS.forEach((e=>{const i=e.Name;if(t.includes(i))return;const n=new e(this);this.plugList[i]=n;const s=n.getBtn();if(s){this.$plugBtnWrap.appendChild(s),s.onclick=s.onclick||(()=>{this.$plugBtnWrap.querySelectorAll(".active").forEach((t=>t.classList.remove("active"))),i!==this.openedPlugName?(this.openPlugPanel(i),s.classList.add("active")):this.closePlugPanel()});const t=n.getPanel();t&&(t.setAttribute("data-plug-name",i),t.style.display="none",this.$plugPanelWrap.appendChild(t))}}))}openPlugPanel(t){Object.entries(this.plugList).forEach((([e,i])=>{const n=i.getPanel();n&&(e===t?(n.style.display="",i.onPanelShow&&i.onPanelShow()):(n.style.display="none",i.onPanelHide&&i.onPanelHide()))})),this.$plugPanelWrap.style.display="",this.openedPlugName=t}closePlugPanel(){if(!this.openedPlugName)return;const t=this.plugList[this.openedPlugName];t&&(t.onPanelHide&&t.onPanelHide(),this.$plugPanelWrap.style.display="none",this.openedPlugName=null)}}class Dt extends Z{constructor(t){super(t),__publicField(this,"layer"),__publicField(this,"$header"),__publicField(this,"$closeBtn"),__publicField(this,"$iframeWrap"),__publicField(this,"$iframe"),__publicField(this,"firstShow",!0),this.$el=N('<div class="atk-sidebar-layer">\n <div class="atk-sidebar-inner">\n <div class="atk-sidebar-header">\n <div class="atk-sidebar-close"><i class="atk-icon atk-icon-close"></i></div>\n </div>\n <div class="atk-sidebar-iframe-wrap"></div>\n </div>\n</div>\n'),this.$header=this.$el.querySelector(".atk-sidebar-header"),this.$closeBtn=this.$header.querySelector(".atk-sidebar-close"),this.$iframeWrap=this.$el.querySelector(".atk-sidebar-iframe-wrap"),this.$closeBtn.onclick=()=>{this.hide()},this.ctx.on("user-changed",(()=>{this.firstShow=!0}))}show(){return __async(this,arguments,(function*(t={}){if(this.$el.style.transform="",null==this.layer&&(this.layer=new ot(this.ctx,"sidebar",this.$el),this.layer.afterHide=()=>{!0===this.ctx.conf.editorTravel&&this.ctx.editorTravelBack()}),this.layer.show(),(()=>{__async(this,null,(function*(){var e;const i=yield this.ctx.getApi().user.loginStatus();i.is_admin&&!i.is_login&&(null==(e=this.layer)||e.hide(),this.firstShow=!0,this.ctx.checkAdmin({onSuccess:()=>{setTimeout((()=>{this.show(t)}),500)},onCancel:()=>{}}))}))})(),this.firstShow){this.$iframeWrap.innerHTML="",this.$iframe=N("<iframe></iframe>");const e=X(this.ctx,"/sidebar/"),i={pageKey:this.conf.pageKey,site:this.conf.site||"",user:JSON.stringify(this.ctx.user.data),time:+new Date};t.view&&(i.view=t.view),this.conf.darkMode&&(i.darkMode="1");const n=new URLSearchParams(i);this.iframeLoad(`${e}?${n.toString()}`),this.$iframeWrap.append(this.$iframe),this.firstShow=!1}else{const t=this.$iframe.src.includes("darkMode=1");this.conf.darkMode&&!t&&this.iframeLoad(`${this.$iframe.src}&darkMode=1`),!this.conf.darkMode&&t&&this.iframeLoad(this.$iframe.src.replace("&darkMode=1",""))}setTimeout((()=>{this.$el.style.transform="translate(0, 0)"}),100),setTimeout((()=>{this.ctx.updateNotifies([])}),0),this.ctx.trigger("sidebar-show")}))}hide(){var t;this.$el.style.transform="",null==(t=this.layer)||t.hide(),this.ctx.trigger("sidebar-hide")}iframeLoad(t){this.$iframe&&(this.$iframe.src=t,tt(this.$iframeWrap),this.$iframe.onload=()=>{et(this.$iframeWrap)})}}function qt(t){return __async(this,null,(function*(){const e=t.ctx.conf.countEl;e&&document.querySelector(e)&&It(t,{api:"page_comment",countEl:e});const i=t.pvAdd?yield t.ctx.getApi().page.pv():void 0,n=t.ctx.conf.pvEl;n&&document.querySelector(n)&&It(t,{api:"page_pv",countEl:n,curtPageCount:i})}))}function It(t,e){return __async(this,null,(function*(){let i={};const n=t.ctx.conf.pageKey;e.curtPageCount&&(i[n]=e.curtPageCount);let s=Array.from(document.querySelectorAll(e.countEl)).map((t=>t.getAttribute("data-page-key")||n)).filter((t=>void 0===i[t]));if(s=[...new Set(s)],s.length>0){const n=yield t.ctx.getApi().page.stat(e.api,s);i=__spreadValues(__spreadValues({},i),n)}document.querySelectorAll(e.countEl).forEach((t=>{const e=t.getAttribute("data-page-key")||n;t.innerHTML=`${Number(i[e]||0)}`}))}))}const Wt=class{constructor(t){__publicField(this,"conf"),__publicField(this,"ctx"),__publicField(this,"$root"),__publicField(this,"instancePlugins",[]),this.conf=Wt.HandelBaseConf(t),this.conf.el instanceof HTMLElement&&(this.$root=this.conf.el),this.ctx=new Ct(this.conf,this.$root),this.initComponents()}initComponents(){this.initLocale(),this.initLayer(),function(e){try{if(!t.marked.name)return}catch(a){return}const i=new t.marked.Renderer,n=i.link;i.link=(t,e,s)=>{const a=null==t?void 0:t.startsWith(`${window.location.protocol}//${window.location.hostname}`);return n.call(i,t,e,s).replace(/^<a /,`<a target="_blank" ${a?"":'rel="noreferrer noopener nofollow"'} `)},i.code=(t,e)=>{const i=e||"plaintext";let n=t;return window.hljs?i&&window.hljs.getLanguage(i)&&(n=window.hljs.highlight(i,t).value):n=W(t),`<pre rel="${i}">\n<code class="hljs language-${i}">${n.replace(/&amp;/g,"&")}</code>\n</pre>`};const s=t.marked;t.marked.setOptions({renderer:i,pedantic:!1,gfm:!0,breaks:!0,smartLists:!0,smartypants:!0,xhtml:!1,sanitize:!1,silent:!0}),e.markedInstance=s}(this.ctx);const e={checkerLauncher:()=>{const t=new At(this.ctx);this.ctx.setCheckerLauncher(t)},editor:()=>{const t=new Rt(this.ctx);this.ctx.setEditor(t),this.$root.appendChild(t.$el)},list:()=>{const t=new wt(this.ctx);this.ctx.setList(t),this.$root.appendChild(t.$el),t.fetchComments(0)},sidebarLayer:()=>{const t=new Dt(this.ctx);this.ctx.setSidebarLayer(t)},eventsDefault:()=>{this.initEventBind()}};Object.entries(e).forEach((([t,e])=>{Wt.DisabledComponents.includes(t)||e()})),Wt.Plugins.forEach((t=>{"function"==typeof t&&t(this.ctx)}))}static HandelBaseConf(t){const e=J(Wt.defaults,t);if("string"==typeof e.el&&e.el)try{const t=document.querySelector(e.el);if(!t)throw Error(`Target element "${e.el}" was not found.`);e.el=t}catch(i){throw console.error(i),new Error("Please check your Artalk `el` config.")}return e.server=e.server.replace(/\/$/,"").replace(/\/api\/?$/,""),e.pageKey||(e.pageKey=`${window.location.pathname}`),e.pageTitle||(e.pageTitle=`${document.title}`),e}initEventBind(){window.addEventListener("hashchange",(()=>{this.ctx.listHashGotoCheck()})),this.ctx.on("user-changed",(()=>{this.ctx.checkAdminShowEl(),this.ctx.listRefreshUI()}))}initLocale(){"auto"===this.conf.locale&&(this.conf.locale=navigator.language)}initLayer(){ot.BodyOrgOverflow=document.body.style.overflow,ot.BodyOrgPaddingRight=document.body.style.paddingRight}on(t,e){this.ctx.on(t,e,"external")}off(t,e){this.ctx.off(t,e,"external")}trigger(t,e){this.ctx.trigger(t,e,"external")}reload(){this.ctx.listReload()}setDarkMode(t){this.ctx.setDarkMode(t)}use(t){this.instancePlugins.push(t),"function"==typeof t&&t(this.ctx)}static use(t){this.Plugins.push(t)}static Use(t){this.use(t),console.warn("`Use(...)` is deprecated, replace it with lowercase `use(...)`.")}static LoadCountWidget(t){const e=this.HandelBaseConf(t);qt({ctx:new Ct(e),pvAdd:!1})}};let Nt=Wt;return __publicField(Nt,"ListLite",xt),__publicField(Nt,"defaults",St),__publicField(Nt,"Plugins",[t=>{t.conf.useBackendConf?t.on("list-loaded",(()=>{qt({ctx:t,pvAdd:!0})})):qt({ctx:t,pvAdd:!0})}]),__publicField(Nt,"DisabledComponents",[]),Nt}(marked);