From 8b18e8d82d9d9c228883e1bed8743525556d8cfd Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:23:56 +0800 Subject: [PATCH 1/2] fix(client): add static assets cache headers and script auto-init Add web/public/_headers to provide 24h cache-control and CORS headers for /client/* assets. Implement autoInit and scheduleAutoInit in client bundle to support zero-config one-line script embedding with data-* attributes, window.CALINE_CONFIG fallback, and container auto-creation. Checkpoint: HyyoBCjDuicFPajSTdAcA --- client/src/index.ts | 220 +++++++++++++++++++++++++++++++++++-- client/test/bundle.test.ts | 13 +++ client/test/widget.test.ts | 148 +++++++++++++++++++++++++ web/public/_headers | 7 ++ web/public/client/v1.js | 40 +++---- 5 files changed, 399 insertions(+), 29 deletions(-) create mode 100644 web/public/_headers diff --git a/client/src/index.ts b/client/src/index.ts index 65073cd..600012a 100644 --- a/client/src/index.ts +++ b/client/src/index.ts @@ -16,8 +16,8 @@ import { recentComments } from "./widgets/recent" import "./styles/theme.css" export interface CalineInitOptions { - el: string | HTMLElement - serverURL: string + el?: string | HTMLElement + serverURL?: string path?: string lang?: string pageSize?: number @@ -44,15 +44,43 @@ export class CalineWidget { private loadMoreBtn!: HTMLButtonElement constructor(options: CalineInitOptions) { - const el = - typeof options.el === "string" - ? document.querySelector(options.el) - : options.el + let el = options.el if (!el) { - throw new Error(`Caline: container '${options.el}' not found`) + if (typeof document !== "undefined") { + el = + document.querySelector("#caline") || + document.querySelector("#comments") || + document.querySelector("#waline") || + document.querySelector("[data-caline]") || + undefined + } + } else if (typeof el === "string" && typeof document !== "undefined") { + el = document.querySelector(el) || undefined + } + + if (!el) { + throw new Error( + `Caline: container '${options.el || "#caline"}' not found` + ) } this.container = el as HTMLElement - this.serverUrl = options.serverURL.replace(/\/+$/, "") + this.container.dataset.calineInitialized = "true" + + let serverUrl = options.serverURL + if (!serverUrl) { + if (typeof window !== "undefined" && window.location?.origin) { + serverUrl = window.location.origin + } else { + serverUrl = "" + } + if (typeof console !== "undefined" && console.warn) { + console.warn( + "[Caline] serverURL is not specified, falling back to location.origin:", + serverUrl + ) + } + } + this.serverUrl = (serverUrl || "").replace(/\/+$/, "") this.path = options.path || (typeof window !== "undefined" ? window.location.pathname : "/") @@ -272,22 +300,196 @@ export function init(options: CalineInitOptions): CalineWidget { return new CalineWidget(options) } +function findCurrentScript(): HTMLScriptElement | null { + if (typeof document === "undefined") return null + if ( + document.currentScript && + document.currentScript instanceof HTMLScriptElement + ) { + return document.currentScript + } + const scripts = Array.from( + document.querySelectorAll("script") + ) + for (let i = scripts.length - 1; i >= 0; i--) { + const s = scripts[i] + if ( + s.hasAttribute("data-server-url") || + s.hasAttribute("data-caline") || + (s.src && (s.src.includes("/client/v1.js") || s.src.includes("v1.js"))) + ) { + return s + } + } + return null +} + +export function autoInit(): CalineWidget | null { + if (typeof window === "undefined" || typeof document === "undefined") { + return null + } + + const globalConfig = + ( + window as unknown as { + CALINE_CONFIG?: Partial + } + ).CALINE_CONFIG || {} + + const script = findCurrentScript() + const scriptDataset = script ? script.dataset : {} + + let serverURL = + globalConfig.serverURL || + scriptDataset.serverUrl || + script?.getAttribute("data-server-url") || + "" + + if (!serverURL && script?.src) { + try { + const parsed = new URL(script.src, window.location.href) + if (parsed.protocol === "http:" || parsed.protocol === "https:") { + serverURL = parsed.origin + } + } catch { + // ignore + } + } + + let el: HTMLElement | null = null + const targetSelector = + globalConfig.el || scriptDataset.el || script?.getAttribute("data-el") + + if (targetSelector) { + if (typeof targetSelector === "string") { + el = document.querySelector(targetSelector) + } else if (targetSelector instanceof HTMLElement) { + el = targetSelector + } + } else { + el = + document.querySelector("#caline") || + document.querySelector("#comments") || + document.querySelector("#waline") || + document.querySelector("[data-caline]") + } + + if (!serverURL && el?.getAttribute("data-server-url")) { + serverURL = el.getAttribute("data-server-url") || "" + } + + if (!serverURL) { + serverURL = window.location.origin || "" + if (typeof console !== "undefined" && console.warn) { + console.warn( + "[Caline] serverURL is not specified, falling back to location.origin:", + serverURL + ) + } + } + + // 若仍没有容器,但脚本在 DOM 中,自动在 script 后插入 #caline 容器 + if (!el && script && script.parentNode) { + const autoDiv = document.createElement("div") + autoDiv.id = "caline" + autoDiv.className = "caline-container" + script.parentNode.insertBefore(autoDiv, script.nextSibling) + el = autoDiv + } + + if (!el) { + return null + } + + if (el.dataset.calineInitialized === "true") { + return null + } + + const path = + globalConfig.path || + scriptDataset.path || + script?.getAttribute("data-path") || + el.getAttribute("data-path") || + undefined + + const lang = + globalConfig.lang || + scriptDataset.lang || + script?.getAttribute("data-lang") || + el.getAttribute("data-lang") || + undefined + + const rawPageSize = + globalConfig.pageSize || + scriptDataset.pageSize || + script?.getAttribute("data-page-size") || + el.getAttribute("data-page-size") + const pageSize = rawPageSize ? Number(rawPageSize) : undefined + + const rawWordLimit = + globalConfig.wordLimit || + scriptDataset.wordLimit || + script?.getAttribute("data-word-limit") || + el.getAttribute("data-word-limit") + const wordLimit = rawWordLimit ? Number(rawWordLimit) : undefined + + const widget = init({ + el, + serverURL, + path, + lang, + pageSize, + wordLimit + }) + + // 联动触发独立计数挂件自动填充 + if (serverURL) { + if (document.querySelector("[data-caline-count]")) { + commentCount({ serverURL }).catch(() => {}) + } + if (document.querySelector("[data-caline-pageview]")) { + pageview({ serverURL }).catch(() => {}) + } + } + + return widget +} + +export function scheduleAutoInit(): void { + if (typeof document === "undefined") return + + if (document.readyState === "loading") { + document.addEventListener( + "DOMContentLoaded", + () => { + autoInit() + }, + { once: true } + ) + } else { + autoInit() + } +} + // 导出独立挂件与工具函数 export { commentCount, pageview, reaction } from "./widgets/counters" export { recentComments } from "./widgets/recent" export const Caline = { init, + autoInit, + scheduleAutoInit, commentCount, pageview, reaction, recentComments } -// 全局挂载支持 (支持 + ` + + const widget = autoInit() + expect(widget).not.toBeNull() + const container = document.querySelector("#my-comments") + expect(container?.classList.contains("cl-root")).toBe(true) + expect(container?.getAttribute("data-caline-initialized")).toBe("true") + expect(container?.querySelector(".cl-btn-primary")?.textContent).toBe( + "Submit" + ) + }) + + it("supports 'one line script works' by automatically creating #caline container", () => { + document.body.innerHTML = ` +
+

Blog Post

+ +
+ ` + + const widget = autoInit() + expect(widget).not.toBeNull() + const generatedContainer = document.querySelector("#caline") + expect(generatedContainer).not.toBeNull() + expect(generatedContainer?.classList.contains("cl-root")).toBe(true) + expect(generatedContainer?.getAttribute("data-caline-initialized")).toBe( + "true" + ) + }) + + it("autoInit reads global window.CALINE_CONFIG", () => { + ;(window as unknown as { CALINE_CONFIG: unknown }).CALINE_CONFIG = { + serverURL: "https://caline.example.com", + path: "/custom/path" + } + document.body.innerHTML = '
' + + const widget = autoInit() + expect(widget).not.toBeNull() + expect( + document.querySelector("#caline")?.classList.contains("cl-root") + ).toBe(true) + }) + + it("autoInit avoids duplicate initialization on already initialized containers", () => { + document.body.innerHTML = ` +
+ + ` + + const first = autoInit() + expect(first).not.toBeNull() + const second = autoInit() + expect(second).toBeNull() + }) + + it("scheduleAutoInit waits for DOMContentLoaded if document.readyState is loading", () => { + document.body.innerHTML = '
' + const addEventSpy = vi.spyOn(document, "addEventListener") + + // 模拟 document.readyState === "loading" + Object.defineProperty(document, "readyState", { + value: "loading", + configurable: true + }) + + scheduleAutoInit() + expect(addEventSpy).toHaveBeenCalledWith( + "DOMContentLoaded", + expect.any(Function), + { once: true } + ) + + // 恢复 readyState + Object.defineProperty(document, "readyState", { + value: "complete", + configurable: true + }) + }) + }) }) diff --git a/web/public/_headers b/web/public/_headers new file mode 100644 index 0000000..fb0e6c5 --- /dev/null +++ b/web/public/_headers @@ -0,0 +1,7 @@ +# Cloudflare Workers Static Assets custom headers +/client/* + Cache-Control: public, max-age=86400, stale-while-revalidate=604800 + Access-Control-Allow-Origin: * + +/assets/* + Cache-Control: public, max-age=31536000, immutable diff --git a/web/public/client/v1.js b/web/public/client/v1.js index 06bbf8b..7754a48 100644 --- a/web/public/client/v1.js +++ b/web/public/client/v1.js @@ -1,22 +1,22 @@ (function(){if(typeof document!=="undefined"){var st=document.getElementById("caline-style");if(!st){st=document.createElement("style");st.id="caline-style";st.textContent=":root{--cl-color-primary:#3b82f6;--cl-color-primary-hover:#2563eb;--cl-color-bg:#fff;--cl-color-card:#f8fafc;--cl-color-text:#1e293b;--cl-color-text-muted:#64748b;--cl-color-border:#e2e8f0;--cl-color-danger:#ef4444;--cl-color-danger-hover:#dc2626;--cl-color-badge:#e0f2fe;--cl-color-badge-text:#0369a1;--cl-radius:6px;--cl-font-size:14px;--cl-font-size-sm:12px}@media (prefers-color-scheme:dark){:root{--cl-color-primary:#60a5fa;--cl-color-primary-hover:#93c5fd;--cl-color-bg:#0f172a;--cl-color-card:#1e293b;--cl-color-text:#f1f5f9;--cl-color-text-muted:#94a3b8;--cl-color-border:#334155;--cl-color-danger:#f87171;--cl-color-danger-hover:#ef4444;--cl-color-badge:#0369a1;--cl-color-badge-text:#e0f2fe}}.dark,[data-theme=dark]{--cl-color-primary:#60a5fa;--cl-color-primary-hover:#93c5fd;--cl-color-bg:#0f172a;--cl-color-card:#1e293b;--cl-color-text:#f1f5f9;--cl-color-text-muted:#94a3b8;--cl-color-border:#334155;--cl-color-danger:#f87171;--cl-color-danger-hover:#ef4444;--cl-color-badge:#0369a1;--cl-color-badge-text:#e0f2fe}.cl-root{box-sizing:border-box;font-size:var(--cl-font-size);color:var(--cl-color-text);font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif;line-height:1.5}.cl-root *,.cl-root :before,.cl-root :after{box-sizing:inherit}.cl-editor-container{border:1px solid var(--cl-color-border);border-radius:var(--cl-radius);background-color:var(--cl-color-bg);margin-bottom:24px;padding:12px}.cl-editor-meta-inputs{flex-wrap:wrap;gap:8px;margin-bottom:8px;display:flex}.cl-input{min-width:120px;font-size:var(--cl-font-size-sm);border:1px solid var(--cl-color-border);border-radius:var(--cl-radius);background:var(--cl-color-bg);color:var(--cl-color-text);outline:none;flex:1;padding:6px 10px;transition:border-color .15s}.cl-input:focus{border-color:var(--cl-color-primary)}.cl-textarea{width:100%;min-height:90px;font-size:var(--cl-font-size);border:1px solid var(--cl-color-border);border-radius:var(--cl-radius);background:var(--cl-color-bg);color:var(--cl-color-text);resize:vertical;outline:none;padding:8px 10px;font-family:inherit;transition:border-color .15s}.cl-textarea:focus{border-color:var(--cl-color-primary)}.cl-editor-preview{border:1px solid var(--cl-color-border);border-radius:var(--cl-radius);background:var(--cl-color-card);min-height:90px;margin-bottom:8px;padding:8px 10px;overflow-x:auto}.cl-editor-footer{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:8px;margin-top:8px;display:flex}.cl-editor-tools{align-items:center;gap:8px;display:flex}.cl-tool-btn{border:1px solid var(--cl-color-border);border-radius:var(--cl-radius);font-size:var(--cl-font-size-sm);color:var(--cl-color-text-muted);cursor:pointer;background:0 0;padding:4px 8px;transition:all .15s}.cl-tool-btn:hover{color:var(--cl-color-text);border-color:var(--cl-color-primary)}.cl-tool-btn.active{background-color:var(--cl-color-primary);color:#fff;border-color:var(--cl-color-primary)}.cl-word-limit{font-size:var(--cl-font-size-sm);color:var(--cl-color-text-muted)}.cl-word-limit.error{color:var(--cl-color-danger);font-weight:600}.cl-btn{border-radius:var(--cl-radius);font-size:var(--cl-font-size-sm);cursor:pointer;border:none;padding:6px 16px;font-weight:500;transition:background-color .15s}.cl-btn-primary{background-color:var(--cl-color-primary);color:#fff}.cl-btn-primary:hover:not(:disabled){background-color:var(--cl-color-primary-hover)}.cl-btn:disabled{opacity:.6;cursor:not-allowed}.cl-btn-secondary{border:1px solid var(--cl-color-border);color:var(--cl-color-text);background-color:#0000}.cl-btn-danger{background-color:var(--cl-color-danger);color:#fff}.cl-btn-danger:hover:not(:disabled){background-color:var(--cl-color-danger-hover)}.cl-emoji-panel{border:1px solid var(--cl-color-border);border-radius:var(--cl-radius);background:var(--cl-color-bg);grid-template-columns:repeat(8,1fr);gap:4px;max-width:320px;margin-top:6px;padding:8px;display:grid;box-shadow:0 4px 12px #0000001a}.cl-emoji-btn{cursor:pointer;background:0 0;border:none;border-radius:4px;padding:4px;font-size:18px}.cl-emoji-btn:hover{background-color:var(--cl-color-card)}.cl-header{border-bottom:1px solid var(--cl-color-border);justify-content:space-between;align-items:center;margin-bottom:16px;padding-bottom:12px;display:flex}.cl-count-title{font-weight:600}.cl-sort-bar{gap:8px;display:flex}.cl-sort-btn{font-size:var(--cl-font-size-sm);color:var(--cl-color-text-muted);cursor:pointer;background:0 0;border:none;padding:2px 4px}.cl-sort-btn.active{color:var(--cl-color-primary);font-weight:600}.cl-item{border-bottom:1px solid var(--cl-color-border);gap:12px;padding:12px 0;display:flex}.cl-avatar-wrap{flex-shrink:0}.cl-avatar{object-fit:cover;background-color:var(--cl-color-card);border-radius:50%;width:40px;height:40px}.cl-content-wrap{flex:1;min-width:0}.cl-meta-line{flex-wrap:wrap;align-items:center;gap:6px;margin-bottom:4px;display:flex}.cl-nick{color:var(--cl-color-text);font-weight:600;text-decoration:none}.cl-nick:hover{color:var(--cl-color-primary)}.cl-badge{background-color:var(--cl-color-badge);color:var(--cl-color-badge-text);border-radius:10px;padding:1px 6px;font-size:10px;font-weight:500}.cl-sticky-tag{background-color:var(--cl-color-primary);color:#fff;border-radius:4px;padding:1px 6px;font-size:10px;font-weight:500}.cl-time{font-size:var(--cl-font-size-sm);color:var(--cl-color-text-muted);margin-left:auto}.cl-comment-text{word-break:break-word;margin:6px 0}.cl-comment-text p{margin:4px 0}.cl-actions{align-items:center;gap:12px;margin-top:6px;display:flex}.cl-action-btn{font-size:var(--cl-font-size-sm);color:var(--cl-color-text-muted);cursor:pointer;background:0 0;border:none;padding:0}.cl-action-btn:hover{color:var(--cl-color-primary)}.cl-action-btn.cl-liked{color:var(--cl-color-danger);font-weight:600}.cl-replies-list{border-left:2px solid var(--cl-color-border);margin-top:10px;padding-left:12px}.cl-reply-item{gap:8px;padding:8px 0;display:flex}.cl-reply-avatar{object-fit:cover;border-radius:50%;width:28px;height:28px}.cl-at-user{color:var(--cl-color-primary);margin-right:4px;font-weight:500}.cl-inline-code{background-color:var(--cl-color-card);border-radius:4px;padding:2px 4px;font-family:monospace;font-size:.9em}.cl-code-block{background-color:var(--cl-color-card);border-radius:var(--cl-radius);padding:8px 12px;font-family:monospace;font-size:.9em;overflow-x:auto}.cl-blockquote{border-left:3px solid var(--cl-color-border);color:var(--cl-color-text-muted);margin:4px 0;padding-left:10px}.cl-link{color:var(--cl-color-primary);text-decoration:underline}.cl-load-more-wrap{text-align:center;margin:16px 0}.cl-empty-state{text-align:center;color:var(--cl-color-text-muted);padding:32px 0}.cl-login-notice{text-align:center;background:var(--cl-color-card);border-radius:var(--cl-radius);color:var(--cl-color-text-muted);margin-bottom:20px;padding:16px}.cl-login-link{color:var(--cl-color-primary);cursor:pointer;text-decoration:underline}\n/*$vite$:1*/";document.head.appendChild(st);}}})(); -(function(k){Object.defineProperties(k,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});function C(t){"@babel/helpers - typeof";return C=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},C(t)}function X(t,e){if(C(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var i=n.call(t,e||"default");if(C(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Z(t){var e=X(t,"string");return C(e)=="symbol"?e:e+""}function m(t,e,n){return(e=Z(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var S=class{constructor(t){m(this,"serverUrl",void 0),this.serverUrl=t.replace(/\/+$/,"")}async request(t,e={},n={}){const i=`${this.serverUrl}${t}`,r={Accept:"application/json",...n};e.body&&typeof e.body=="string"&&(r["Content-Type"]="application/json");const c=await(await fetch(i,{...e,headers:{...r,...e.headers},credentials:"include"})).json();if("error"in c)throw new Error(c.error.message||`Request failed with code ${c.error.code}`);return c.data}async listComments(t){const e=new URLSearchParams;return e.set("url",t.url),t.page&&e.set("page",String(t.page)),t.pageSize&&e.set("pageSize",String(t.pageSize)),t.sort&&e.set("sort",t.sort),this.request(`/api/comments?${e.toString()}`)}async createComment(t,e){const n={};return e&&(n.Authorization=`Bearer ${e}`),this.request("/api/comments",{method:"POST",body:JSON.stringify(t),headers:n})}async updateComment(t,e,n){const i={};return n&&(i["X-Edit-Token"]=n),this.request(`/api/comments/${t}`,{method:"PATCH",body:JSON.stringify(e),headers:i})}async deleteComment(t,e){const n={};return e&&(n["X-Edit-Token"]=e),this.request(`/api/comments/${t}`,{method:"DELETE",headers:n})}async likeComment(t){return this.request(`/api/comments/${t}/like`,{method:"POST"})}async getCommentCounts(t){return this.request(`/api/comments/count?urls=${encodeURIComponent(t.join(","))}`)}async getRecentComments(t=10){return this.request(`/api/comments/recent?count=${t}`)}async postView(t){return this.request("/api/pages/view",{method:"POST",body:JSON.stringify(t)})}async postReaction(t){return this.request("/api/pages/reaction",{method:"POST",body:JSON.stringify(t)})}},F=["😀","😃","😄","😁","😆","😅","🤣","😂","🙂","🙃","😉","😊","😇","🥰","😍","🤩","😘","😋","😜","🤔","🤫","🤗","🤐","🫡","👍","👎","👏","🙌","🤝","🙏","✌️","🎉","🔥","✨","💯","❤️","💔","🌟","💡","☕","👀","🚀","💪","😎","🥺","😭","😤","😴"];function v(t){return t.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function Q(t){const e=t.trim().replace(/\s+/g,"");return/^(?:javascript|data|vbscript):/i.test(e)?"#":e}function q(t){if(!t)return!1;const e=t.trim().replace(/\s+/g,"");return/^https?:\/\//i.test(e)}function tt(t){if(!t?.trim())return"";let e=v(t);const n=[];e=e.replace(/```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/g,(a,s,u)=>{const g=n.length;return n.push(`
${u.trim()}
`),`§§§CODEBLOCK${g}§§§`}),e=e.replace(/`([^`\n]+)`/g,'$1'),e=e.replace(/(?:^|\s)@([a-zA-Z0-9_\u4e00-\u9fa5]+)/g,(a,s)=>` @${s}`),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(a,s,u)=>`${s}`),e=e.replace(/\*\*(.*?)\*\*/g,"$1"),e=e.replace(/\*(.*?)\*/g,"$1");const i=e.split(` -`),r=[];let c=!1,o=[];for(const a of i)a.startsWith("> ")?(c=!0,o.push(a.slice(5))):(c&&(r.push(`
${o.join("
")}
`),o=[],c=!1),r.push(a));c&&r.push(`
${o.join("
")}
`);let l=r.join(` -`);return l=l.split(/\n{2,}/).map(a=>`

${a.replace(/\n/g,"
")}

`).join(""),l=l.replace(/

§§§CODEBLOCK(\d+)§§§<\/p>/g,(a,s)=>n[Number(s)]||""),l=l.replace(/§§§CODEBLOCK(\d+)§§§/g,(a,s)=>n[Number(s)]||""),l}var M="caline_guest_profile",_="caline_edit_tokens",N="caline_liked_comments";function et(){if(typeof window>"u"||!window.localStorage)return{nick:"",mail:"",link:""};try{const t=localStorage.getItem(M);return t?JSON.parse(t):{nick:"",mail:"",link:""}}catch{return{nick:"",mail:"",link:""}}}function nt(t){if(!(typeof window>"u"||!window.localStorage))try{localStorage.setItem(M,JSON.stringify(t))}catch{}}function E(t){if(typeof window>"u"||!window.localStorage)return null;try{const e=localStorage.getItem(_);if(!e)return null;const n=JSON.parse(e),i=n[t];return i?Date.now()>i.expiresAt?(delete n[t],localStorage.setItem(_,JSON.stringify(n)),null):i.token:null}catch{return null}}function O(t,e){if(!(typeof window>"u"||!window.localStorage))try{const n=localStorage.getItem(_),i=n?JSON.parse(n):{};i[t]={token:e,expiresAt:Date.now()+9e5};const r=Date.now();for(const c of Object.keys(i))i[c].expiresAt"u"||!window.localStorage))try{const e=localStorage.getItem(_);if(!e)return;const n=JSON.parse(e);delete n[t],localStorage.setItem(_,JSON.stringify(n))}catch{}}function T(t){if(typeof window>"u"||!window.localStorage)return!1;try{const e=localStorage.getItem(N);return e?JSON.parse(e).includes(t):!1}catch{return!1}}function P(t){if(!(typeof window>"u"||!window.localStorage))try{const e=localStorage.getItem(N),n=e?JSON.parse(e):[];n.includes(t)||(n.push(t),localStorage.setItem(N,JSON.stringify(n)))}catch{}}function A(t){const e=document.createElement("div");if(e.className="cl-editor-container",t.isAllDisabled)return e.innerHTML=`

`,e;if(t.isGuestDisabled)return e.innerHTML=` +(function(w){Object.defineProperties(w,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});function _(t){"@babel/helpers - typeof";return _=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_(t)}function Z(t,e){if(_(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var i=n.call(t,e||"default");if(_(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Q(t){var e=Z(t,"string");return _(e)=="symbol"?e:e+""}function m(t,e,n){return(e=Q(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var C=class{constructor(t){m(this,"serverUrl",void 0),this.serverUrl=t.replace(/\/+$/,"")}async request(t,e={},n={}){const i=`${this.serverUrl}${t}`,r={Accept:"application/json",...n};e.body&&typeof e.body=="string"&&(r["Content-Type"]="application/json");const c=await(await fetch(i,{...e,headers:{...r,...e.headers},credentials:"include"})).json();if("error"in c)throw new Error(c.error.message||`Request failed with code ${c.error.code}`);return c.data}async listComments(t){const e=new URLSearchParams;return e.set("url",t.url),t.page&&e.set("page",String(t.page)),t.pageSize&&e.set("pageSize",String(t.pageSize)),t.sort&&e.set("sort",t.sort),this.request(`/api/comments?${e.toString()}`)}async createComment(t,e){const n={};return e&&(n.Authorization=`Bearer ${e}`),this.request("/api/comments",{method:"POST",body:JSON.stringify(t),headers:n})}async updateComment(t,e,n){const i={};return n&&(i["X-Edit-Token"]=n),this.request(`/api/comments/${t}`,{method:"PATCH",body:JSON.stringify(e),headers:i})}async deleteComment(t,e){const n={};return e&&(n["X-Edit-Token"]=e),this.request(`/api/comments/${t}`,{method:"DELETE",headers:n})}async likeComment(t){return this.request(`/api/comments/${t}/like`,{method:"POST"})}async getCommentCounts(t){return this.request(`/api/comments/count?urls=${encodeURIComponent(t.join(","))}`)}async getRecentComments(t=10){return this.request(`/api/comments/recent?count=${t}`)}async postView(t){return this.request("/api/pages/view",{method:"POST",body:JSON.stringify(t)})}async postReaction(t){return this.request("/api/pages/reaction",{method:"POST",body:JSON.stringify(t)})}},tt=["😀","😃","😄","😁","😆","😅","🤣","😂","🙂","🙃","😉","😊","😇","🥰","😍","🤩","😘","😋","😜","🤔","🤫","🤗","🤐","🫡","👍","👎","👏","🙌","🤝","🙏","✌️","🎉","🔥","✨","💯","❤️","💔","🌟","💡","☕","👀","🚀","💪","😎","🥺","😭","😤","😴"];function v(t){return t.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function et(t){const e=t.trim().replace(/\s+/g,"");return/^(?:javascript|data|vbscript):/i.test(e)?"#":e}function x(t){if(!t)return!1;const e=t.trim().replace(/\s+/g,"");return/^https?:\/\//i.test(e)}function nt(t){if(!t?.trim())return"";let e=v(t);const n=[];e=e.replace(/```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/g,(a,s,u)=>{const f=n.length;return n.push(`
${u.trim()}
`),`§§§CODEBLOCK${f}§§§`}),e=e.replace(/`([^`\n]+)`/g,'$1'),e=e.replace(/(?:^|\s)@([a-zA-Z0-9_\u4e00-\u9fa5]+)/g,(a,s)=>` @${s}`),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(a,s,u)=>`${s}`),e=e.replace(/\*\*(.*?)\*\*/g,"$1"),e=e.replace(/\*(.*?)\*/g,"$1");const i=e.split(` +`),r=[];let c=!1,l=[];for(const a of i)a.startsWith("> ")?(c=!0,l.push(a.slice(5))):(c&&(r.push(`
${l.join("
")}
`),l=[],c=!1),r.push(a));c&&r.push(`
${l.join("
")}
`);let o=r.join(` +`);return o=o.split(/\n{2,}/).map(a=>`

${a.replace(/\n/g,"
")}

`).join(""),o=o.replace(/

§§§CODEBLOCK(\d+)§§§<\/p>/g,(a,s)=>n[Number(s)]||""),o=o.replace(/§§§CODEBLOCK(\d+)§§§/g,(a,s)=>n[Number(s)]||""),o}var z="caline_guest_profile",S="caline_edit_tokens",A="caline_liked_comments";function it(){if(typeof window>"u"||!window.localStorage)return{nick:"",mail:"",link:""};try{const t=localStorage.getItem(z);return t?JSON.parse(t):{nick:"",mail:"",link:""}}catch{return{nick:"",mail:"",link:""}}}function rt(t){if(!(typeof window>"u"||!window.localStorage))try{localStorage.setItem(z,JSON.stringify(t))}catch{}}function E(t){if(typeof window>"u"||!window.localStorage)return null;try{const e=localStorage.getItem(S);if(!e)return null;const n=JSON.parse(e),i=n[t];return i?Date.now()>i.expiresAt?(delete n[t],localStorage.setItem(S,JSON.stringify(n)),null):i.token:null}catch{return null}}function R(t,e){if(!(typeof window>"u"||!window.localStorage))try{const n=localStorage.getItem(S),i=n?JSON.parse(n):{};i[t]={token:e,expiresAt:Date.now()+9e5};const r=Date.now();for(const c of Object.keys(i))i[c].expiresAt"u"||!window.localStorage))try{const e=localStorage.getItem(S);if(!e)return;const n=JSON.parse(e);delete n[t],localStorage.setItem(S,JSON.stringify(n))}catch{}}function q(t){if(typeof window>"u"||!window.localStorage)return!1;try{const e=localStorage.getItem(A);return e?JSON.parse(e).includes(t):!1}catch{return!1}}function j(t){if(!(typeof window>"u"||!window.localStorage))try{const e=localStorage.getItem(A),n=e?JSON.parse(e):[];n.includes(t)||(n.push(t),localStorage.setItem(A,JSON.stringify(n)))}catch{}}function D(t){const e=document.createElement("div");if(e.className="cl-editor-container",t.isAllDisabled)return e.innerHTML=`

`,e;if(t.isGuestDisabled)return e.innerHTML=` - `,e;const n=et(),i=t.wordLimit||1e3;let r=!1,c=!1;if(t.replyTarget){const f=document.createElement("div");f.style.cssText="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;font-size:12px;color:var(--cl-color-text-muted);",f.innerHTML=` + `,e;const n=it(),i=t.wordLimit||1e3;let r=!1,c=!1;if(t.replyTarget){const p=document.createElement("div");p.style.cssText="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;font-size:12px;color:var(--cl-color-text-muted);",p.innerHTML=` 回复 @${t.replyTarget.nick} - `,f.querySelector(".cl-reply-cancel")?.addEventListener("click",()=>{t.replyTarget?.onCancel()}),e.appendChild(f)}const o=document.createElement("div");o.className="cl-editor-meta-inputs",o.innerHTML=` + `,p.querySelector(".cl-reply-cancel")?.addEventListener("click",()=>{t.replyTarget?.onCancel()}),e.appendChild(p)}const l=document.createElement("div");l.className="cl-editor-meta-inputs",l.innerHTML=` - `,e.appendChild(o);const l=document.createElement("textarea");l.className="cl-textarea",l.placeholder=t.t("placeholder_content");const a=document.createElement("div");a.className="cl-editor-preview",a.style.display="none",e.appendChild(l),e.appendChild(a);const s=document.createElement("div");s.className="cl-emoji-panel",s.style.display="none";for(const f of F){const w=document.createElement("button");w.type="button",w.className="cl-emoji-btn",w.textContent=f,w.addEventListener("click",()=>{const x=l.selectionStart,$=l.selectionEnd,L=l.value;l.value=L.substring(0,x)+f+L.substring($),l.focus(),l.selectionStart=l.selectionEnd=x+f.length,h()}),s.appendChild(w)}e.appendChild(s);const u=document.createElement("div");u.className="cl-editor-footer";const g=document.createElement("div");g.className="cl-editor-tools";const y=document.createElement("button");y.type="button",y.className="cl-tool-btn",y.textContent="😀",y.addEventListener("click",()=>{c=!c,s.style.display=c?"grid":"none",y.classList.toggle("active",c)});const d=document.createElement("button");d.type="button",d.className="cl-tool-btn",d.textContent=t.t("btn_preview"),d.addEventListener("click",()=>{r=!r,r?(a.innerHTML=tt(l.value),a.style.display="block",l.style.display="none",d.classList.add("active")):(a.style.display="none",l.style.display="block",d.classList.remove("active"))});const b=document.createElement("span");b.className="cl-word-limit",b.textContent=`0 / ${i}`;function h(){const f=l.value.length;b.textContent=`${f} / ${i}`,f>i?(b.classList.add("error"),p.disabled=!0):(b.classList.remove("error"),p.disabled=f===0)}l.addEventListener("input",h),g.appendChild(y),g.appendChild(d),g.appendChild(b);const p=document.createElement("button");return p.type="button",p.className="cl-btn cl-btn-primary",p.textContent=t.t("btn_submit"),p.disabled=!0,p.addEventListener("click",async()=>{const f=o.querySelector(".cl-input-nick"),w=o.querySelector(".cl-input-mail"),x=o.querySelector(".cl-input-link"),$=f?.value.trim(),L=w?.value.trim(),G=x?.value.trim(),V=l.value.trim();if(!$){alert(t.t("error_empty_nick")),f?.focus();return}if(!V){alert(t.t("error_empty_content")),l.focus();return}nt({nick:$,mail:L,link:G}),p.disabled=!0,p.textContent=t.t("btn_submitting");try{await t.onSubmit({nick:$,mail:L,link:G,content:V}),l.value="",h(),r&&d.click()}catch(Y){const at=Y instanceof Error?Y.message:t.t("error_network");alert(at)}finally{p.disabled=!1,p.textContent=t.t("btn_submit")}}),u.appendChild(g),u.appendChild(p),e.appendChild(u),e}function rt(t){const e=document.createElement("div");if(e.className="cl-tree-container",t.items.length===0)return e.innerHTML=`
${t.t("no_comments")}
`,e;for(const n of t.items){const i=lt(n,t);e.appendChild(i)}return e}function lt(t,e){const n=document.createElement("div");n.className="cl-item",n.dataset.id=String(t.id);const i=E(t.id),r=T(t.id),c=v(t.nick||e.t("guest")),o=q(t.link),l=o?v(t.link.trim()):"",a=o?`${c}`:`${c}`,s=t.sticky?`${e.t("sticky")}`:"",u=t.badge?`${v(t.badge)}`:"",g=t.level!==void 0?`Lv.${t.level}`:"",y=new Date(t.createdAt).toLocaleDateString();n.innerHTML=` + `,e.appendChild(l);const o=document.createElement("textarea");o.className="cl-textarea",o.placeholder=t.t("placeholder_content");const a=document.createElement("div");a.className="cl-editor-preview",a.style.display="none",e.appendChild(o),e.appendChild(a);const s=document.createElement("div");s.className="cl-emoji-panel",s.style.display="none";for(const p of tt){const k=document.createElement("button");k.type="button",k.className="cl-emoji-btn",k.textContent=p,k.addEventListener("click",()=>{const N=o.selectionStart,$=o.selectionEnd,L=o.value;o.value=L.substring(0,N)+p+L.substring($),o.focus(),o.selectionStart=o.selectionEnd=N+p.length,h()}),s.appendChild(k)}e.appendChild(s);const u=document.createElement("div");u.className="cl-editor-footer";const f=document.createElement("div");f.className="cl-editor-tools";const g=document.createElement("button");g.type="button",g.className="cl-tool-btn",g.textContent="😀",g.addEventListener("click",()=>{c=!c,s.style.display=c?"grid":"none",g.classList.toggle("active",c)});const d=document.createElement("button");d.type="button",d.className="cl-tool-btn",d.textContent=t.t("btn_preview"),d.addEventListener("click",()=>{r=!r,r?(a.innerHTML=nt(o.value),a.style.display="block",o.style.display="none",d.classList.add("active")):(a.style.display="none",o.style.display="block",d.classList.remove("active"))});const b=document.createElement("span");b.className="cl-word-limit",b.textContent=`0 / ${i}`;function h(){const p=o.value.length;b.textContent=`${p} / ${i}`,p>i?(b.classList.add("error"),y.disabled=!0):(b.classList.remove("error"),y.disabled=p===0)}o.addEventListener("input",h),f.appendChild(g),f.appendChild(d),f.appendChild(b);const y=document.createElement("button");return y.type="button",y.className="cl-btn cl-btn-primary",y.textContent=t.t("btn_submit"),y.disabled=!0,y.addEventListener("click",async()=>{const p=l.querySelector(".cl-input-nick"),k=l.querySelector(".cl-input-mail"),N=l.querySelector(".cl-input-link"),$=p?.value.trim(),L=k?.value.trim(),Y=N?.value.trim(),F=o.value.trim();if(!$){alert(t.t("error_empty_nick")),p?.focus();return}if(!F){alert(t.t("error_empty_content")),o.focus();return}rt({nick:$,mail:L,link:Y}),y.disabled=!0,y.textContent=t.t("btn_submitting");try{await t.onSubmit({nick:$,mail:L,link:Y,content:F}),o.value="",h(),r&&d.click()}catch(X){const ut=X instanceof Error?X.message:t.t("error_network");alert(ut)}finally{y.disabled=!1,y.textContent=t.t("btn_submit")}}),u.appendChild(f),u.appendChild(y),e.appendChild(u),e}function ct(t){const e=document.createElement("div");if(e.className="cl-tree-container",t.items.length===0)return e.innerHTML=`
${t.t("no_comments")}
`,e;for(const n of t.items){const i=lt(n,t);e.appendChild(i)}return e}function lt(t,e){const n=document.createElement("div");n.className="cl-item",n.dataset.id=String(t.id);const i=E(t.id),r=q(t.id),c=v(t.nick||e.t("guest")),l=x(t.link),o=l?v(t.link.trim()):"",a=l?`${c}`:`${c}`,s=t.sticky?`${e.t("sticky")}`:"",u=t.badge?`${v(t.badge)}`:"",f=t.level!==void 0?`Lv.${t.level}`:"",g=new Date(t.createdAt).toLocaleDateString();n.innerHTML=`
${c}
@@ -25,8 +25,8 @@ ${a} ${s} ${u} - ${g} - ${y} + ${f} + ${g}
${t.contentHtml}
@@ -39,16 +39,16 @@
- `;const d=n.querySelector(".cl-btn-like");d?.addEventListener("click",async()=>{if(!T(t.id))try{const h=await e.onLike(t.id);P(t.id),d.classList.add("cl-liked"),d.textContent=`${e.t("liked")} (${h})`}catch(h){alert(h instanceof Error?h.message:e.t("error_network"))}}),n.querySelector(".cl-btn-reply")?.addEventListener("click",()=>{e.onReply(t,t.id)}),i&&U(n,t.id,t.contentHtml,i,e);const b=n.querySelector(".cl-replies-list");if(t.replies&&t.replies.length>0)for(const h of t.replies){const p=ct(h,t.id,e);b.appendChild(p)}return n}function ct(t,e,n){const i=document.createElement("div");i.className="cl-reply-item",i.dataset.id=String(t.id);const r=E(t.id),c=T(t.id),o=v(t.nick||n.t("guest")),l=q(t.link),a=l?v(t.link.trim()):"",s=l?`${o}`:`${o}`,u=t.badge?`${v(t.badge)}`:"",g=t.level!==void 0?`Lv.${t.level}`:"",y=new Date(t.createdAt).toLocaleDateString(),d=t.replyTo?`@${v(t.replyTo.nick)}`:"";i.innerHTML=` + `;const d=n.querySelector(".cl-btn-like");d?.addEventListener("click",async()=>{if(!q(t.id))try{const h=await e.onLike(t.id);j(t.id),d.classList.add("cl-liked"),d.textContent=`${e.t("liked")} (${h})`}catch(h){alert(h instanceof Error?h.message:e.t("error_network"))}}),n.querySelector(".cl-btn-reply")?.addEventListener("click",()=>{e.onReply(t,t.id)}),i&&B(n,t.id,t.contentHtml,i,e);const b=n.querySelector(".cl-replies-list");if(t.replies&&t.replies.length>0)for(const h of t.replies){const y=at(h,t.id,e);b.appendChild(y)}return n}function at(t,e,n){const i=document.createElement("div");i.className="cl-reply-item",i.dataset.id=String(t.id);const r=E(t.id),c=q(t.id),l=v(t.nick||n.t("guest")),o=x(t.link),a=o?v(t.link.trim()):"",s=o?`${l}`:`${l}`,u=t.badge?`${v(t.badge)}`:"",f=t.level!==void 0?`Lv.${t.level}`:"",g=new Date(t.createdAt).toLocaleDateString(),d=t.replyTo?`@${v(t.replyTo.nick)}`:"";i.innerHTML=`
- ${o} + ${l}
${s} ${u} - ${g} - ${y} + ${f} + ${g}
${d}${t.contentHtml}
@@ -60,25 +60,25 @@ ${r?``:""}
- `;const b=i.querySelector(".cl-btn-like");return b?.addEventListener("click",async()=>{if(!T(t.id))try{const h=await n.onLike(t.id);P(t.id),b.classList.add("cl-liked"),b.textContent=`${n.t("liked")} (${h})`}catch(h){alert(h instanceof Error?h.message:n.t("error_network"))}}),i.querySelector(".cl-btn-reply")?.addEventListener("click",()=>{n.onReply(t,e)}),r&&U(i,t.id,t.contentHtml,r,n),i}function U(t,e,n,i,r){const c=t.querySelector(".cl-btn-edit"),o=t.querySelector(".cl-btn-delete"),l=t.querySelector(".cl-comment-text");c?.addEventListener("click",()=>{if(!E(e)){alert(r.t("edit_expired")),c.remove(),o?.remove();return}const a=document.createElement("div");a.style.marginTop="8px";const s=document.createElement("textarea");s.className="cl-textarea",s.style.minHeight="60px",s.value=(l.textContent||"").trim();const u=document.createElement("div");u.style.cssText="display:flex;gap:8px;margin-top:6px;",u.innerHTML=` + `;const b=i.querySelector(".cl-btn-like");return b?.addEventListener("click",async()=>{if(!q(t.id))try{const h=await n.onLike(t.id);j(t.id),b.classList.add("cl-liked"),b.textContent=`${n.t("liked")} (${h})`}catch(h){alert(h instanceof Error?h.message:n.t("error_network"))}}),i.querySelector(".cl-btn-reply")?.addEventListener("click",()=>{n.onReply(t,e)}),r&&B(i,t.id,t.contentHtml,r,n),i}function B(t,e,n,i,r){const c=t.querySelector(".cl-btn-edit"),l=t.querySelector(".cl-btn-delete"),o=t.querySelector(".cl-comment-text");c?.addEventListener("click",()=>{if(!E(e)){alert(r.t("edit_expired")),c.remove(),l?.remove();return}const a=document.createElement("div");a.style.marginTop="8px";const s=document.createElement("textarea");s.className="cl-textarea",s.style.minHeight="60px",s.value=(o.textContent||"").trim();const u=document.createElement("div");u.style.cssText="display:flex;gap:8px;margin-top:6px;",u.innerHTML=` - `,a.appendChild(s),a.appendChild(u);const g=l.style.display;l.style.display="none",l.parentNode?.insertBefore(a,l.nextSibling),a.querySelector(".cl-edit-cancel")?.addEventListener("click",()=>{a.remove(),l.style.display=g}),a.querySelector(".cl-edit-save")?.addEventListener("click",async()=>{const y=s.value.trim();if(y)try{const d=await r.onUpdate(e,y,i);l.innerHTML=d,a.remove(),l.style.display=g}catch(d){alert(d instanceof Error?d.message:r.t("edit_expired"))}})}),o?.addEventListener("click",async()=>{if(!E(e)){alert(r.t("edit_expired")),c?.remove(),o.remove();return}if(confirm(r.t("delete_confirm")))try{await r.onDelete(e,i),it(e),t.remove()}catch(a){alert(a instanceof Error?a.message:r.t("edit_expired"))}})}var j={placeholder_nick:"昵称 *",placeholder_mail:"邮箱 (Gravatar)",placeholder_link:"网址 (https://)",placeholder_content:"支持 Markdown 语法...",btn_submit:"发表评论",btn_submitting:"发送中...",btn_reply:"回复",btn_cancel:"取消",btn_preview:"预览",btn_edit:"编辑",btn_delete:"删除",btn_save:"保存",sort_newest:"最新",sort_oldest:"最早",sort_hottest:"最热",comments_count:"条评论",no_comments:"暂无评论,来抢沙发吧~",sticky:"置顶",login_to_comment:"登录后发表评论",login_prompt:"已有账号?点击登录",guest_closed:"当前仅允许登录用户发表评论",all_closed:"全站评论功能已关闭",edit_expired:"已超过 15 分钟编辑期限,请联系管理员",delete_confirm:"确定要删除这条评论吗?",like:"赞",liked:"已赞",load_more:"加载更多",loading:"加载中...",error_network:"网络请求失败,请稍后重试",error_empty_nick:"请填写昵称",error_empty_content:"评论内容不能为空",error_word_limit:"字数超出限制",recent_title:"最新评论",pageview:"次浏览",guest:"访客",admin:"管理员",verified:"已认证"},ot={placeholder_nick:"Nickname *",placeholder_mail:"Email (Gravatar)",placeholder_link:"Website (https://)",placeholder_content:"Markdown supported...",btn_submit:"Submit",btn_submitting:"Submitting...",btn_reply:"Reply",btn_cancel:"Cancel",btn_preview:"Preview",btn_edit:"Edit",btn_delete:"Delete",btn_save:"Save",sort_newest:"Newest",sort_oldest:"Oldest",sort_hottest:"Hottest",comments_count:"comments",no_comments:"No comments yet.",sticky:"Pinned",login_to_comment:"Sign in to comment",login_prompt:"Already have an account? Sign in",guest_closed:"Only registered users can comment",all_closed:"Comments are disabled",edit_expired:"Edit window expired (15m), please contact admin",delete_confirm:"Are you sure you want to delete this comment?",like:"Like",liked:"Liked",load_more:"Load more",loading:"Loading...",error_network:"Network error, please try again later",error_empty_nick:"Nickname is required",error_empty_content:"Content cannot be empty",error_word_limit:"Character limit exceeded",recent_title:"Recent Comments",pageview:"Views",guest:"Guest",admin:"Admin",verified:"Verified"};function z(t){if(t){const e=t.toLowerCase();if(e.startsWith("zh"))return"zh-CN";if(e.startsWith("en"))return"en"}if(typeof document<"u"&&document.documentElement.lang){const e=document.documentElement.lang.toLowerCase();if(e.startsWith("zh"))return"zh-CN";if(e.startsWith("en"))return"en"}return"zh-CN"}function R(t){const e=t==="en"?ot:j;return function(i){return e[i]??j[i]??i}}async function B(t){const e=new S(t.serverURL),n=t.selector||"[data-caline-count]",i=typeof document<"u"?Array.from(document.querySelectorAll(n)):[];let r=t.urls||[];if(r.length===0&&i.length>0&&(r=i.map(o=>o.getAttribute("data-caline-count")||o.getAttribute("data-path")||"").filter(Boolean)),r.length===0)return{};const c=await e.getCommentCounts(r);for(const o of i){const l=o.getAttribute("data-caline-count")||o.getAttribute("data-path")||"";l&&c[l]!==void 0&&(o.textContent=String(c[l]))}return c}async function D(t){const e=new S(t.serverURL),n=t.url||(typeof window<"u"?window.location.pathname:"");if(!n)return 0;const i=await e.postView({url:n}),r=t.selector||"[data-caline-pageview]";if(typeof document<"u"){const c=document.querySelectorAll(r);for(const o of c)(o.getAttribute("data-path")||n)===n&&(o.textContent=String(i.pageview))}return i.pageview}async function J(t){const e=new S(t.serverURL),n=t.url||(typeof window<"u"?window.location.pathname:"");return n?e.postReaction({url:n,type:t.type}):null}async function I(t){const e=typeof t.el=="string"?document.querySelector(t.el):t.el;if(!e)return;const n=z(t.lang),i=R(n),r=new S(t.serverURL);e.innerHTML=`
${i("loading")}
`;try{const c=await r.getRecentComments(t.count||5);if(!c||c.length===0){e.innerHTML=`
${i("no_comments")}
`;return}e.innerHTML=`
${c.map(o=>{const l=v(o.nick||i("guest")),a=q(o.link),s=a?v(o.link.trim()):"",u=a?`${l}`:`${l}`;return` -
+ `,a.appendChild(s),a.appendChild(u);const f=o.style.display;o.style.display="none",o.parentNode?.insertBefore(a,o.nextSibling),a.querySelector(".cl-edit-cancel")?.addEventListener("click",()=>{a.remove(),o.style.display=f}),a.querySelector(".cl-edit-save")?.addEventListener("click",async()=>{const g=s.value.trim();if(g)try{const d=await r.onUpdate(e,g,i);o.innerHTML=d,a.remove(),o.style.display=f}catch(d){alert(d instanceof Error?d.message:r.t("edit_expired"))}})}),l?.addEventListener("click",async()=>{if(!E(e)){alert(r.t("edit_expired")),c?.remove(),l.remove();return}if(confirm(r.t("delete_confirm")))try{await r.onDelete(e,i),ot(e),t.remove()}catch(a){alert(a instanceof Error?a.message:r.t("edit_expired"))}})}var I={placeholder_nick:"昵称 *",placeholder_mail:"邮箱 (Gravatar)",placeholder_link:"网址 (https://)",placeholder_content:"支持 Markdown 语法...",btn_submit:"发表评论",btn_submitting:"发送中...",btn_reply:"回复",btn_cancel:"取消",btn_preview:"预览",btn_edit:"编辑",btn_delete:"删除",btn_save:"保存",sort_newest:"最新",sort_oldest:"最早",sort_hottest:"最热",comments_count:"条评论",no_comments:"暂无评论,来抢沙发吧~",sticky:"置顶",login_to_comment:"登录后发表评论",login_prompt:"已有账号?点击登录",guest_closed:"当前仅允许登录用户发表评论",all_closed:"全站评论功能已关闭",edit_expired:"已超过 15 分钟编辑期限,请联系管理员",delete_confirm:"确定要删除这条评论吗?",like:"赞",liked:"已赞",load_more:"加载更多",loading:"加载中...",error_network:"网络请求失败,请稍后重试",error_empty_nick:"请填写昵称",error_empty_content:"评论内容不能为空",error_word_limit:"字数超出限制",recent_title:"最新评论",pageview:"次浏览",guest:"访客",admin:"管理员",verified:"已认证"},st={placeholder_nick:"Nickname *",placeholder_mail:"Email (Gravatar)",placeholder_link:"Website (https://)",placeholder_content:"Markdown supported...",btn_submit:"Submit",btn_submitting:"Submitting...",btn_reply:"Reply",btn_cancel:"Cancel",btn_preview:"Preview",btn_edit:"Edit",btn_delete:"Delete",btn_save:"Save",sort_newest:"Newest",sort_oldest:"Oldest",sort_hottest:"Hottest",comments_count:"comments",no_comments:"No comments yet.",sticky:"Pinned",login_to_comment:"Sign in to comment",login_prompt:"Already have an account? Sign in",guest_closed:"Only registered users can comment",all_closed:"Comments are disabled",edit_expired:"Edit window expired (15m), please contact admin",delete_confirm:"Are you sure you want to delete this comment?",like:"Like",liked:"Liked",load_more:"Load more",loading:"Loading...",error_network:"Network error, please try again later",error_empty_nick:"Nickname is required",error_empty_content:"Content cannot be empty",error_word_limit:"Character limit exceeded",recent_title:"Recent Comments",pageview:"Views",guest:"Guest",admin:"Admin",verified:"Verified"};function J(t){if(t){const e=t.toLowerCase();if(e.startsWith("zh"))return"zh-CN";if(e.startsWith("en"))return"en"}if(typeof document<"u"&&document.documentElement.lang){const e=document.documentElement.lang.toLowerCase();if(e.startsWith("zh"))return"zh-CN";if(e.startsWith("en"))return"en"}return"zh-CN"}function W(t){const e=t==="en"?st:I;return function(i){return e[i]??I[i]??i}}async function H(t){const e=new C(t.serverURL),n=t.selector||"[data-caline-count]",i=typeof document<"u"?Array.from(document.querySelectorAll(n)):[];let r=t.urls||[];if(r.length===0&&i.length>0&&(r=i.map(l=>l.getAttribute("data-caline-count")||l.getAttribute("data-path")||"").filter(Boolean)),r.length===0)return{};const c=await e.getCommentCounts(r);for(const l of i){const o=l.getAttribute("data-caline-count")||l.getAttribute("data-path")||"";o&&c[o]!==void 0&&(l.textContent=String(c[o]))}return c}async function M(t){const e=new C(t.serverURL),n=t.url||(typeof window<"u"?window.location.pathname:"");if(!n)return 0;const i=await e.postView({url:n}),r=t.selector||"[data-caline-pageview]";if(typeof document<"u"){const c=document.querySelectorAll(r);for(const l of c)(l.getAttribute("data-path")||n)===n&&(l.textContent=String(i.pageview))}return i.pageview}async function K(t){const e=new C(t.serverURL),n=t.url||(typeof window<"u"?window.location.pathname:"");return n?e.postReaction({url:n,type:t.type}):null}async function G(t){const e=typeof t.el=="string"?document.querySelector(t.el):t.el;if(!e)return;const n=J(t.lang),i=W(n),r=new C(t.serverURL);e.innerHTML=`
${i("loading")}
`;try{const c=await r.getRecentComments(t.count||5);if(!c||c.length===0){e.innerHTML=`
${i("no_comments")}
`;return}e.innerHTML=`
${c.map(l=>{const o=v(l.nick||i("guest")),a=x(l.link),s=a?v(l.link.trim()):"",u=a?`${o}`:`${o}`;return` +
- ${l} + ${o}
${u} - ${new Date(o.createdAt).toLocaleDateString()} + ${new Date(l.createdAt).toLocaleDateString()}
- ${o.contentHtml} + ${l.contentHtml}
- `}).join("")}
`}catch{e.innerHTML=`
${i("error_network")}
`}}var W=class{constructor(t){m(this,"container",void 0),m(this,"serverUrl",void 0),m(this,"path",void 0),m(this,"client",void 0),m(this,"pageSize",void 0),m(this,"wordLimit",void 0),m(this,"currentSort","newest"),m(this,"currentPage",1),m(this,"totalPages",1),m(this,"totalComments",0),m(this,"comments",[]),m(this,"t",void 0),m(this,"editorContainer",void 0),m(this,"treeContainer",void 0),m(this,"countTitle",void 0),m(this,"loadMoreBtn",void 0);const e=typeof t.el=="string"?document.querySelector(t.el):t.el;if(!e)throw new Error(`Caline: container '${t.el}' not found`);this.container=e,this.serverUrl=t.serverURL.replace(/\/+$/,""),this.path=t.path||(typeof window<"u"?window.location.pathname:"/"),this.pageSize=t.pageSize||10,this.wordLimit=t.wordLimit||1e3;const n=z(t.lang);this.t=R(n),this.client=new S(this.serverUrl),this.renderSkeleton(),this.loadComments()}renderSkeleton(){this.container.classList.add("cl-root"),this.container.innerHTML=` + `}).join("")}
`}catch{e.innerHTML=`
${i("error_network")}
`}}var V=class{constructor(t){m(this,"container",void 0),m(this,"serverUrl",void 0),m(this,"path",void 0),m(this,"client",void 0),m(this,"pageSize",void 0),m(this,"wordLimit",void 0),m(this,"currentSort","newest"),m(this,"currentPage",1),m(this,"totalPages",1),m(this,"totalComments",0),m(this,"comments",[]),m(this,"t",void 0),m(this,"editorContainer",void 0),m(this,"treeContainer",void 0),m(this,"countTitle",void 0),m(this,"loadMoreBtn",void 0);let e=t.el;if(e?typeof e=="string"&&typeof document<"u"&&(e=document.querySelector(e)||void 0):typeof document<"u"&&(e=document.querySelector("#caline")||document.querySelector("#comments")||document.querySelector("#waline")||document.querySelector("[data-caline]")||void 0),!e)throw new Error(`Caline: container '${t.el||"#caline"}' not found`);this.container=e,this.container.dataset.calineInitialized="true";let n=t.serverURL;n||(typeof window<"u"&&window.location?.origin?n=window.location.origin:n="",typeof console<"u"&&console.warn&&console.warn("[Caline] serverURL is not specified, falling back to location.origin:",n)),this.serverUrl=(n||"").replace(/\/+$/,""),this.path=t.path||(typeof window<"u"?window.location.pathname:"/"),this.pageSize=t.pageSize||10,this.wordLimit=t.wordLimit||1e3;const i=J(t.lang);this.t=W(i),this.client=new C(this.serverUrl),this.renderSkeleton(),this.loadComments()}renderSkeleton(){this.container.classList.add("cl-root"),this.container.innerHTML=`
0 ${this.t("comments_count")}
@@ -92,4 +92,4 @@ - `,this.editorContainer=this.container.querySelector(".cl-editor-slot"),this.treeContainer=this.container.querySelector(".cl-tree-slot"),this.countTitle=this.container.querySelector(".cl-count-title"),this.loadMoreBtn=this.container.querySelector(".cl-btn-load-more");const t=this.container.querySelectorAll(".cl-sort-btn");for(const e of t)e.addEventListener("click",()=>{for(const i of t)i.classList.remove("active");e.classList.add("active");const n=e.getAttribute("data-sort");this.currentSort!==n&&(this.currentSort=n,this.currentPage=1,this.loadComments(!0))});this.loadMoreBtn.addEventListener("click",()=>{this.currentPage{const n=await this.client.createComment({url:this.path,content:e.content,nick:e.nick,mail:e.mail,link:e.link});n.editToken&&O(n.comment.id,n.editToken),this.currentPage=1,await this.loadComments(!0)}});this.editorContainer.appendChild(t)}async loadComments(t=!0){t&&(this.treeContainer.innerHTML=`
${this.t("loading")}
`);try{const e=await this.client.listComments({url:this.path,page:this.currentPage,pageSize:this.pageSize,sort:this.currentSort});this.totalComments=e.total,this.totalPages=e.totalPages,this.countTitle.textContent=`${this.totalComments} ${this.t("comments_count")}`,t?this.comments=e.items:this.comments=[...this.comments,...e.items],this.treeContainer.innerHTML="";const n=rt({items:this.comments,t:this.t,onReply:(r,c)=>{this.showReplyEditor(r,c)},onLike:async r=>(await this.client.likeComment(r)).likeCount,onUpdate:async(r,c,o)=>(await this.client.updateComment(r,{content:c},o)).contentHtml,onDelete:async(r,c)=>{await this.client.deleteComment(r,c),this.totalComments=Math.max(0,this.totalComments-1),this.countTitle.textContent=`${this.totalComments} ${this.t("comments_count")}`}});this.treeContainer.appendChild(n);const i=this.container.querySelector(".cl-load-more-wrap");this.currentPage${this.t("error_network")}
`}}showReplyEditor(t,e){const n=this.treeContainer.querySelector(".cl-reply-editor-slot");n&&n.remove();const i=this.treeContainer.querySelector(`[data-id="${t.id}"]`);if(!i)return;const r=document.createElement("div");r.className="cl-reply-editor-slot",r.style.marginTop="8px";const c=A({t:this.t,wordLimit:this.wordLimit,serverUrl:this.serverUrl,replyTarget:{nick:t.nick||this.t("guest"),onCancel:()=>r.remove()},onSubmit:async l=>{const a=await this.client.createComment({url:this.path,content:l.content,pid:t.id,rid:e,nick:l.nick,mail:l.mail,link:l.link});a.editToken&&O(a.comment.id,a.editToken),r.remove(),this.currentPage=1,await this.loadComments(!0)}});r.appendChild(c);const o=i.querySelector(".cl-content-wrap");o?o.appendChild(r):i.appendChild(r)}};function K(t){return new W(t)}var H={init:K,commentCount:B,pageview:D,reaction:J,recentComments:I};if(typeof window<"u"){const t=window;t.Caline=H}k.Caline=H,k.default=H,k.CalineWidget=W,k.commentCount=B,k.init=K,k.pageview=D,k.reaction=J,k.recentComments=I})(this.Caline=this.Caline||{}); + `,this.editorContainer=this.container.querySelector(".cl-editor-slot"),this.treeContainer=this.container.querySelector(".cl-tree-slot"),this.countTitle=this.container.querySelector(".cl-count-title"),this.loadMoreBtn=this.container.querySelector(".cl-btn-load-more");const t=this.container.querySelectorAll(".cl-sort-btn");for(const e of t)e.addEventListener("click",()=>{for(const i of t)i.classList.remove("active");e.classList.add("active");const n=e.getAttribute("data-sort");this.currentSort!==n&&(this.currentSort=n,this.currentPage=1,this.loadComments(!0))});this.loadMoreBtn.addEventListener("click",()=>{this.currentPage{const n=await this.client.createComment({url:this.path,content:e.content,nick:e.nick,mail:e.mail,link:e.link});n.editToken&&R(n.comment.id,n.editToken),this.currentPage=1,await this.loadComments(!0)}});this.editorContainer.appendChild(t)}async loadComments(t=!0){t&&(this.treeContainer.innerHTML=`
${this.t("loading")}
`);try{const e=await this.client.listComments({url:this.path,page:this.currentPage,pageSize:this.pageSize,sort:this.currentSort});this.totalComments=e.total,this.totalPages=e.totalPages,this.countTitle.textContent=`${this.totalComments} ${this.t("comments_count")}`,t?this.comments=e.items:this.comments=[...this.comments,...e.items],this.treeContainer.innerHTML="";const n=ct({items:this.comments,t:this.t,onReply:(r,c)=>{this.showReplyEditor(r,c)},onLike:async r=>(await this.client.likeComment(r)).likeCount,onUpdate:async(r,c,l)=>(await this.client.updateComment(r,{content:c},l)).contentHtml,onDelete:async(r,c)=>{await this.client.deleteComment(r,c),this.totalComments=Math.max(0,this.totalComments-1),this.countTitle.textContent=`${this.totalComments} ${this.t("comments_count")}`}});this.treeContainer.appendChild(n);const i=this.container.querySelector(".cl-load-more-wrap");this.currentPage${this.t("error_network")}
`}}showReplyEditor(t,e){const n=this.treeContainer.querySelector(".cl-reply-editor-slot");n&&n.remove();const i=this.treeContainer.querySelector(`[data-id="${t.id}"]`);if(!i)return;const r=document.createElement("div");r.className="cl-reply-editor-slot",r.style.marginTop="8px";const c=D({t:this.t,wordLimit:this.wordLimit,serverUrl:this.serverUrl,replyTarget:{nick:t.nick||this.t("guest"),onCancel:()=>r.remove()},onSubmit:async o=>{const a=await this.client.createComment({url:this.path,content:o.content,pid:t.id,rid:e,nick:o.nick,mail:o.mail,link:o.link});a.editToken&&R(a.comment.id,a.editToken),r.remove(),this.currentPage=1,await this.loadComments(!0)}});r.appendChild(c);const l=i.querySelector(".cl-content-wrap");l?l.appendChild(r):i.appendChild(r)}};function O(t){return new V(t)}function dt(){if(typeof document>"u")return null;if(document.currentScript&&document.currentScript instanceof HTMLScriptElement)return document.currentScript;const t=Array.from(document.querySelectorAll("script"));for(let e=t.length-1;e>=0;e--){const n=t[e];if(n.hasAttribute("data-server-url")||n.hasAttribute("data-caline")||n.src&&(n.src.includes("/client/v1.js")||n.src.includes("v1.js")))return n}return null}function T(){if(typeof window>"u"||typeof document>"u")return null;const t=window.CALINE_CONFIG||{},e=dt(),n=e?e.dataset:{};let i=t.serverURL||n.serverUrl||e?.getAttribute("data-server-url")||"";if(!i&&e?.src)try{const d=new URL(e.src,window.location.href);(d.protocol==="http:"||d.protocol==="https:")&&(i=d.origin)}catch{}let r=null;const c=t.el||n.el||e?.getAttribute("data-el");if(c?typeof c=="string"?r=document.querySelector(c):c instanceof HTMLElement&&(r=c):r=document.querySelector("#caline")||document.querySelector("#comments")||document.querySelector("#waline")||document.querySelector("[data-caline]"),!i&&r?.getAttribute("data-server-url")&&(i=r.getAttribute("data-server-url")||""),i||(i=window.location.origin||"",typeof console<"u"&&console.warn&&console.warn("[Caline] serverURL is not specified, falling back to location.origin:",i)),!r&&e&&e.parentNode){const d=document.createElement("div");d.id="caline",d.className="caline-container",e.parentNode.insertBefore(d,e.nextSibling),r=d}if(!r||r.dataset.calineInitialized==="true")return null;const l=t.path||n.path||e?.getAttribute("data-path")||r.getAttribute("data-path")||void 0,o=t.lang||n.lang||e?.getAttribute("data-lang")||r.getAttribute("data-lang")||void 0,a=t.pageSize||n.pageSize||e?.getAttribute("data-page-size")||r.getAttribute("data-page-size"),s=a?Number(a):void 0,u=t.wordLimit||n.wordLimit||e?.getAttribute("data-word-limit")||r.getAttribute("data-word-limit"),f=u?Number(u):void 0,g=O({el:r,serverURL:i,path:l,lang:o,pageSize:s,wordLimit:f});return i&&(document.querySelector("[data-caline-count]")&&H({serverURL:i}).catch(()=>{}),document.querySelector("[data-caline-pageview]")&&M({serverURL:i}).catch(()=>{})),g}function P(){typeof document>"u"||(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{T()},{once:!0}):T())}var U={init:O,autoInit:T,scheduleAutoInit:P,commentCount:H,pageview:M,reaction:K,recentComments:G};if(typeof window<"u"){const t=window;t.Caline=U,P()}w.Caline=U,w.default=U,w.CalineWidget=V,w.autoInit=T,w.commentCount=H,w.init=O,w.pageview=M,w.reaction=K,w.recentComments=G,w.scheduleAutoInit=P})(this.Caline=this.Caline||{}); From 3f6f7278bae89aa22b25456c8ee03c6ef0e598b6 Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:34:22 +0800 Subject: [PATCH 2/2] fix(client): add intent gate and head protection for autoInit Gate autoInit to execute only when explicit intent is declared via window.CALINE_CONFIG, script data-* attributes, or caline containers. Prevent inserting container div when script is located inside head. Checkpoint: s66D420pXvmab99oeQc3R --- client/src/index.ts | 46 ++++++++++++++++++++++---- client/test/widget.test.ts | 25 +++++++++++++++ web/public/client/v1.js | 66 +++++++++++++++++++------------------- 3 files changed, 98 insertions(+), 39 deletions(-) diff --git a/client/src/index.ts b/client/src/index.ts index 600012a..5ce0b0f 100644 --- a/client/src/index.ts +++ b/client/src/index.ts @@ -336,9 +336,35 @@ export function autoInit(): CalineWidget | null { } ).CALINE_CONFIG || {} + const hasGlobalConfig = + typeof globalConfig === "object" && + globalConfig !== null && + Object.keys(globalConfig).length > 0 + const script = findCurrentScript() const scriptDataset = script ? script.dataset : {} + const hasScriptIntent = Boolean( + script && + (script.hasAttribute("data-caline") || + script.hasAttribute("data-server-url") || + script.hasAttribute("data-el") || + script.hasAttribute("data-path") || + script.hasAttribute("data-lang")) + ) + + const explicitCalineContainer = document.querySelector( + "[data-caline], #caline" + ) + + const hasIntent = + hasGlobalConfig || hasScriptIntent || Boolean(explicitCalineContainer) + + // 严格门控:仅在检测到明确自动初始化意图时才允许执行,未满足条件直接返回 null + if (!hasIntent) { + return null + } + let serverURL = globalConfig.serverURL || scriptDataset.serverUrl || @@ -368,10 +394,11 @@ export function autoInit(): CalineWidget | null { } } else { el = - document.querySelector("#caline") || - document.querySelector("#comments") || - document.querySelector("#waline") || - document.querySelector("[data-caline]") + explicitCalineContainer || + (hasGlobalConfig || hasScriptIntent + ? document.querySelector("#comments") || + document.querySelector("#waline") + : null) } if (!serverURL && el?.getAttribute("data-server-url")) { @@ -388,8 +415,15 @@ export function autoInit(): CalineWidget | null { } } - // 若仍没有容器,但脚本在 DOM 中,自动在 script 后插入 #caline 容器 - if (!el && script && script.parentNode) { + // 若仍没有容器,但脚本在 DOM 的 body 中(排除 head),自动在 script 后插入 #caline 容器 + const isInsideHead = Boolean( + script && + (script.closest?.("head") || + (script.parentNode && + script.parentNode.nodeName.toLowerCase() === "head")) + ) + + if (!el && script && script.parentNode && !isInsideHead) { const autoDiv = document.createElement("div") autoDiv.id = "caline" autoDiv.className = "caline-container" diff --git a/client/test/widget.test.ts b/client/test/widget.test.ts index f61ee83..fed6ad4 100644 --- a/client/test/widget.test.ts +++ b/client/test/widget.test.ts @@ -412,6 +412,31 @@ Reply to @alice and @bob expect(second).toBeNull() }) + it("autoInit gates execution and returns null when no intent or configuration is declared", () => { + document.body.innerHTML = ` +
+ + ` + + const widget = autoInit() + expect(widget).toBeNull() + expect( + document.querySelector("#comments")?.classList.contains("cl-root") + ).toBe(false) + expect(document.querySelector("#caline")).toBeNull() + }) + + it("autoInit does not insert div container inside document.head", () => { + document.head.innerHTML = ` + + ` + document.body.innerHTML = "
No container
" + + const widget = autoInit() + expect(widget).toBeNull() + expect(document.head.querySelector("div")).toBeNull() + }) + it("scheduleAutoInit waits for DOMContentLoaded if document.readyState is loading", () => { document.body.innerHTML = '
' const addEventSpy = vi.spyOn(document, "addEventListener") diff --git a/web/public/client/v1.js b/web/public/client/v1.js index 7754a48..29bd8bc 100644 --- a/web/public/client/v1.js +++ b/web/public/client/v1.js @@ -1,37 +1,37 @@ (function(){if(typeof document!=="undefined"){var st=document.getElementById("caline-style");if(!st){st=document.createElement("style");st.id="caline-style";st.textContent=":root{--cl-color-primary:#3b82f6;--cl-color-primary-hover:#2563eb;--cl-color-bg:#fff;--cl-color-card:#f8fafc;--cl-color-text:#1e293b;--cl-color-text-muted:#64748b;--cl-color-border:#e2e8f0;--cl-color-danger:#ef4444;--cl-color-danger-hover:#dc2626;--cl-color-badge:#e0f2fe;--cl-color-badge-text:#0369a1;--cl-radius:6px;--cl-font-size:14px;--cl-font-size-sm:12px}@media (prefers-color-scheme:dark){:root{--cl-color-primary:#60a5fa;--cl-color-primary-hover:#93c5fd;--cl-color-bg:#0f172a;--cl-color-card:#1e293b;--cl-color-text:#f1f5f9;--cl-color-text-muted:#94a3b8;--cl-color-border:#334155;--cl-color-danger:#f87171;--cl-color-danger-hover:#ef4444;--cl-color-badge:#0369a1;--cl-color-badge-text:#e0f2fe}}.dark,[data-theme=dark]{--cl-color-primary:#60a5fa;--cl-color-primary-hover:#93c5fd;--cl-color-bg:#0f172a;--cl-color-card:#1e293b;--cl-color-text:#f1f5f9;--cl-color-text-muted:#94a3b8;--cl-color-border:#334155;--cl-color-danger:#f87171;--cl-color-danger-hover:#ef4444;--cl-color-badge:#0369a1;--cl-color-badge-text:#e0f2fe}.cl-root{box-sizing:border-box;font-size:var(--cl-font-size);color:var(--cl-color-text);font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif;line-height:1.5}.cl-root *,.cl-root :before,.cl-root :after{box-sizing:inherit}.cl-editor-container{border:1px solid var(--cl-color-border);border-radius:var(--cl-radius);background-color:var(--cl-color-bg);margin-bottom:24px;padding:12px}.cl-editor-meta-inputs{flex-wrap:wrap;gap:8px;margin-bottom:8px;display:flex}.cl-input{min-width:120px;font-size:var(--cl-font-size-sm);border:1px solid var(--cl-color-border);border-radius:var(--cl-radius);background:var(--cl-color-bg);color:var(--cl-color-text);outline:none;flex:1;padding:6px 10px;transition:border-color .15s}.cl-input:focus{border-color:var(--cl-color-primary)}.cl-textarea{width:100%;min-height:90px;font-size:var(--cl-font-size);border:1px solid var(--cl-color-border);border-radius:var(--cl-radius);background:var(--cl-color-bg);color:var(--cl-color-text);resize:vertical;outline:none;padding:8px 10px;font-family:inherit;transition:border-color .15s}.cl-textarea:focus{border-color:var(--cl-color-primary)}.cl-editor-preview{border:1px solid var(--cl-color-border);border-radius:var(--cl-radius);background:var(--cl-color-card);min-height:90px;margin-bottom:8px;padding:8px 10px;overflow-x:auto}.cl-editor-footer{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:8px;margin-top:8px;display:flex}.cl-editor-tools{align-items:center;gap:8px;display:flex}.cl-tool-btn{border:1px solid var(--cl-color-border);border-radius:var(--cl-radius);font-size:var(--cl-font-size-sm);color:var(--cl-color-text-muted);cursor:pointer;background:0 0;padding:4px 8px;transition:all .15s}.cl-tool-btn:hover{color:var(--cl-color-text);border-color:var(--cl-color-primary)}.cl-tool-btn.active{background-color:var(--cl-color-primary);color:#fff;border-color:var(--cl-color-primary)}.cl-word-limit{font-size:var(--cl-font-size-sm);color:var(--cl-color-text-muted)}.cl-word-limit.error{color:var(--cl-color-danger);font-weight:600}.cl-btn{border-radius:var(--cl-radius);font-size:var(--cl-font-size-sm);cursor:pointer;border:none;padding:6px 16px;font-weight:500;transition:background-color .15s}.cl-btn-primary{background-color:var(--cl-color-primary);color:#fff}.cl-btn-primary:hover:not(:disabled){background-color:var(--cl-color-primary-hover)}.cl-btn:disabled{opacity:.6;cursor:not-allowed}.cl-btn-secondary{border:1px solid var(--cl-color-border);color:var(--cl-color-text);background-color:#0000}.cl-btn-danger{background-color:var(--cl-color-danger);color:#fff}.cl-btn-danger:hover:not(:disabled){background-color:var(--cl-color-danger-hover)}.cl-emoji-panel{border:1px solid var(--cl-color-border);border-radius:var(--cl-radius);background:var(--cl-color-bg);grid-template-columns:repeat(8,1fr);gap:4px;max-width:320px;margin-top:6px;padding:8px;display:grid;box-shadow:0 4px 12px #0000001a}.cl-emoji-btn{cursor:pointer;background:0 0;border:none;border-radius:4px;padding:4px;font-size:18px}.cl-emoji-btn:hover{background-color:var(--cl-color-card)}.cl-header{border-bottom:1px solid var(--cl-color-border);justify-content:space-between;align-items:center;margin-bottom:16px;padding-bottom:12px;display:flex}.cl-count-title{font-weight:600}.cl-sort-bar{gap:8px;display:flex}.cl-sort-btn{font-size:var(--cl-font-size-sm);color:var(--cl-color-text-muted);cursor:pointer;background:0 0;border:none;padding:2px 4px}.cl-sort-btn.active{color:var(--cl-color-primary);font-weight:600}.cl-item{border-bottom:1px solid var(--cl-color-border);gap:12px;padding:12px 0;display:flex}.cl-avatar-wrap{flex-shrink:0}.cl-avatar{object-fit:cover;background-color:var(--cl-color-card);border-radius:50%;width:40px;height:40px}.cl-content-wrap{flex:1;min-width:0}.cl-meta-line{flex-wrap:wrap;align-items:center;gap:6px;margin-bottom:4px;display:flex}.cl-nick{color:var(--cl-color-text);font-weight:600;text-decoration:none}.cl-nick:hover{color:var(--cl-color-primary)}.cl-badge{background-color:var(--cl-color-badge);color:var(--cl-color-badge-text);border-radius:10px;padding:1px 6px;font-size:10px;font-weight:500}.cl-sticky-tag{background-color:var(--cl-color-primary);color:#fff;border-radius:4px;padding:1px 6px;font-size:10px;font-weight:500}.cl-time{font-size:var(--cl-font-size-sm);color:var(--cl-color-text-muted);margin-left:auto}.cl-comment-text{word-break:break-word;margin:6px 0}.cl-comment-text p{margin:4px 0}.cl-actions{align-items:center;gap:12px;margin-top:6px;display:flex}.cl-action-btn{font-size:var(--cl-font-size-sm);color:var(--cl-color-text-muted);cursor:pointer;background:0 0;border:none;padding:0}.cl-action-btn:hover{color:var(--cl-color-primary)}.cl-action-btn.cl-liked{color:var(--cl-color-danger);font-weight:600}.cl-replies-list{border-left:2px solid var(--cl-color-border);margin-top:10px;padding-left:12px}.cl-reply-item{gap:8px;padding:8px 0;display:flex}.cl-reply-avatar{object-fit:cover;border-radius:50%;width:28px;height:28px}.cl-at-user{color:var(--cl-color-primary);margin-right:4px;font-weight:500}.cl-inline-code{background-color:var(--cl-color-card);border-radius:4px;padding:2px 4px;font-family:monospace;font-size:.9em}.cl-code-block{background-color:var(--cl-color-card);border-radius:var(--cl-radius);padding:8px 12px;font-family:monospace;font-size:.9em;overflow-x:auto}.cl-blockquote{border-left:3px solid var(--cl-color-border);color:var(--cl-color-text-muted);margin:4px 0;padding-left:10px}.cl-link{color:var(--cl-color-primary);text-decoration:underline}.cl-load-more-wrap{text-align:center;margin:16px 0}.cl-empty-state{text-align:center;color:var(--cl-color-text-muted);padding:32px 0}.cl-login-notice{text-align:center;background:var(--cl-color-card);border-radius:var(--cl-radius);color:var(--cl-color-text-muted);margin-bottom:20px;padding:16px}.cl-login-link{color:var(--cl-color-primary);cursor:pointer;text-decoration:underline}\n/*$vite$:1*/";document.head.appendChild(st);}}})(); -(function(w){Object.defineProperties(w,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});function _(t){"@babel/helpers - typeof";return _=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_(t)}function Z(t,e){if(_(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var i=n.call(t,e||"default");if(_(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Q(t){var e=Z(t,"string");return _(e)=="symbol"?e:e+""}function m(t,e,n){return(e=Q(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var C=class{constructor(t){m(this,"serverUrl",void 0),this.serverUrl=t.replace(/\/+$/,"")}async request(t,e={},n={}){const i=`${this.serverUrl}${t}`,r={Accept:"application/json",...n};e.body&&typeof e.body=="string"&&(r["Content-Type"]="application/json");const c=await(await fetch(i,{...e,headers:{...r,...e.headers},credentials:"include"})).json();if("error"in c)throw new Error(c.error.message||`Request failed with code ${c.error.code}`);return c.data}async listComments(t){const e=new URLSearchParams;return e.set("url",t.url),t.page&&e.set("page",String(t.page)),t.pageSize&&e.set("pageSize",String(t.pageSize)),t.sort&&e.set("sort",t.sort),this.request(`/api/comments?${e.toString()}`)}async createComment(t,e){const n={};return e&&(n.Authorization=`Bearer ${e}`),this.request("/api/comments",{method:"POST",body:JSON.stringify(t),headers:n})}async updateComment(t,e,n){const i={};return n&&(i["X-Edit-Token"]=n),this.request(`/api/comments/${t}`,{method:"PATCH",body:JSON.stringify(e),headers:i})}async deleteComment(t,e){const n={};return e&&(n["X-Edit-Token"]=e),this.request(`/api/comments/${t}`,{method:"DELETE",headers:n})}async likeComment(t){return this.request(`/api/comments/${t}/like`,{method:"POST"})}async getCommentCounts(t){return this.request(`/api/comments/count?urls=${encodeURIComponent(t.join(","))}`)}async getRecentComments(t=10){return this.request(`/api/comments/recent?count=${t}`)}async postView(t){return this.request("/api/pages/view",{method:"POST",body:JSON.stringify(t)})}async postReaction(t){return this.request("/api/pages/reaction",{method:"POST",body:JSON.stringify(t)})}},tt=["😀","😃","😄","😁","😆","😅","🤣","😂","🙂","🙃","😉","😊","😇","🥰","😍","🤩","😘","😋","😜","🤔","🤫","🤗","🤐","🫡","👍","👎","👏","🙌","🤝","🙏","✌️","🎉","🔥","✨","💯","❤️","💔","🌟","💡","☕","👀","🚀","💪","😎","🥺","😭","😤","😴"];function v(t){return t.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function et(t){const e=t.trim().replace(/\s+/g,"");return/^(?:javascript|data|vbscript):/i.test(e)?"#":e}function x(t){if(!t)return!1;const e=t.trim().replace(/\s+/g,"");return/^https?:\/\//i.test(e)}function nt(t){if(!t?.trim())return"";let e=v(t);const n=[];e=e.replace(/```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/g,(a,s,u)=>{const f=n.length;return n.push(`
${u.trim()}
`),`§§§CODEBLOCK${f}§§§`}),e=e.replace(/`([^`\n]+)`/g,'$1'),e=e.replace(/(?:^|\s)@([a-zA-Z0-9_\u4e00-\u9fa5]+)/g,(a,s)=>` @${s}`),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(a,s,u)=>`${s}`),e=e.replace(/\*\*(.*?)\*\*/g,"$1"),e=e.replace(/\*(.*?)\*/g,"$1");const i=e.split(` -`),r=[];let c=!1,l=[];for(const a of i)a.startsWith("> ")?(c=!0,l.push(a.slice(5))):(c&&(r.push(`
${l.join("
")}
`),l=[],c=!1),r.push(a));c&&r.push(`
${l.join("
")}
`);let o=r.join(` -`);return o=o.split(/\n{2,}/).map(a=>`

${a.replace(/\n/g,"
")}

`).join(""),o=o.replace(/

§§§CODEBLOCK(\d+)§§§<\/p>/g,(a,s)=>n[Number(s)]||""),o=o.replace(/§§§CODEBLOCK(\d+)§§§/g,(a,s)=>n[Number(s)]||""),o}var z="caline_guest_profile",S="caline_edit_tokens",A="caline_liked_comments";function it(){if(typeof window>"u"||!window.localStorage)return{nick:"",mail:"",link:""};try{const t=localStorage.getItem(z);return t?JSON.parse(t):{nick:"",mail:"",link:""}}catch{return{nick:"",mail:"",link:""}}}function rt(t){if(!(typeof window>"u"||!window.localStorage))try{localStorage.setItem(z,JSON.stringify(t))}catch{}}function E(t){if(typeof window>"u"||!window.localStorage)return null;try{const e=localStorage.getItem(S);if(!e)return null;const n=JSON.parse(e),i=n[t];return i?Date.now()>i.expiresAt?(delete n[t],localStorage.setItem(S,JSON.stringify(n)),null):i.token:null}catch{return null}}function R(t,e){if(!(typeof window>"u"||!window.localStorage))try{const n=localStorage.getItem(S),i=n?JSON.parse(n):{};i[t]={token:e,expiresAt:Date.now()+9e5};const r=Date.now();for(const c of Object.keys(i))i[c].expiresAt"u"||!window.localStorage))try{const e=localStorage.getItem(S);if(!e)return;const n=JSON.parse(e);delete n[t],localStorage.setItem(S,JSON.stringify(n))}catch{}}function q(t){if(typeof window>"u"||!window.localStorage)return!1;try{const e=localStorage.getItem(A);return e?JSON.parse(e).includes(t):!1}catch{return!1}}function j(t){if(!(typeof window>"u"||!window.localStorage))try{const e=localStorage.getItem(A),n=e?JSON.parse(e):[];n.includes(t)||(n.push(t),localStorage.setItem(A,JSON.stringify(n)))}catch{}}function D(t){const e=document.createElement("div");if(e.className="cl-editor-container",t.isAllDisabled)return e.innerHTML=`

`,e;if(t.isGuestDisabled)return e.innerHTML=` +(function(w){Object.defineProperties(w,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});function _(t){"@babel/helpers - typeof";return _=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_(t)}function Z(t,e){if(_(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var i=n.call(t,e||"default");if(_(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Q(t){var e=Z(t,"string");return _(e)=="symbol"?e:e+""}function f(t,e,n){return(e=Q(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var C=class{constructor(t){f(this,"serverUrl",void 0),this.serverUrl=t.replace(/\/+$/,"")}async request(t,e={},n={}){const i=`${this.serverUrl}${t}`,o={Accept:"application/json",...n};e.body&&typeof e.body=="string"&&(o["Content-Type"]="application/json");const l=await(await fetch(i,{...e,headers:{...o,...e.headers},credentials:"include"})).json();if("error"in l)throw new Error(l.error.message||`Request failed with code ${l.error.code}`);return l.data}async listComments(t){const e=new URLSearchParams;return e.set("url",t.url),t.page&&e.set("page",String(t.page)),t.pageSize&&e.set("pageSize",String(t.pageSize)),t.sort&&e.set("sort",t.sort),this.request(`/api/comments?${e.toString()}`)}async createComment(t,e){const n={};return e&&(n.Authorization=`Bearer ${e}`),this.request("/api/comments",{method:"POST",body:JSON.stringify(t),headers:n})}async updateComment(t,e,n){const i={};return n&&(i["X-Edit-Token"]=n),this.request(`/api/comments/${t}`,{method:"PATCH",body:JSON.stringify(e),headers:i})}async deleteComment(t,e){const n={};return e&&(n["X-Edit-Token"]=e),this.request(`/api/comments/${t}`,{method:"DELETE",headers:n})}async likeComment(t){return this.request(`/api/comments/${t}/like`,{method:"POST"})}async getCommentCounts(t){return this.request(`/api/comments/count?urls=${encodeURIComponent(t.join(","))}`)}async getRecentComments(t=10){return this.request(`/api/comments/recent?count=${t}`)}async postView(t){return this.request("/api/pages/view",{method:"POST",body:JSON.stringify(t)})}async postReaction(t){return this.request("/api/pages/reaction",{method:"POST",body:JSON.stringify(t)})}},tt=["😀","😃","😄","😁","😆","😅","🤣","😂","🙂","🙃","😉","😊","😇","🥰","😍","🤩","😘","😋","😜","🤔","🤫","🤗","🤐","🫡","👍","👎","👏","🙌","🤝","🙏","✌️","🎉","🔥","✨","💯","❤️","💔","🌟","💡","☕","👀","🚀","💪","😎","🥺","😭","😤","😴"];function b(t){return t.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function et(t){const e=t.trim().replace(/\s+/g,"");return/^(?:javascript|data|vbscript):/i.test(e)?"#":e}function A(t){if(!t)return!1;const e=t.trim().replace(/\s+/g,"");return/^https?:\/\//i.test(e)}function nt(t){if(!t?.trim())return"";let e=b(t);const n=[];e=e.replace(/```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/g,(a,s,m)=>{const g=n.length;return n.push(`
${m.trim()}
`),`§§§CODEBLOCK${g}§§§`}),e=e.replace(/`([^`\n]+)`/g,'$1'),e=e.replace(/(?:^|\s)@([a-zA-Z0-9_\u4e00-\u9fa5]+)/g,(a,s)=>` @${s}`),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(a,s,m)=>`${s}`),e=e.replace(/\*\*(.*?)\*\*/g,"$1"),e=e.replace(/\*(.*?)\*/g,"$1");const i=e.split(` +`),o=[];let l=!1,c=[];for(const a of i)a.startsWith("> ")?(l=!0,c.push(a.slice(5))):(l&&(o.push(`
${c.join("
")}
`),c=[],l=!1),o.push(a));l&&o.push(`
${c.join("
")}
`);let r=o.join(` +`);return r=r.split(/\n{2,}/).map(a=>`

${a.replace(/\n/g,"
")}

`).join(""),r=r.replace(/

§§§CODEBLOCK(\d+)§§§<\/p>/g,(a,s)=>n[Number(s)]||""),r=r.replace(/§§§CODEBLOCK(\d+)§§§/g,(a,s)=>n[Number(s)]||""),r}var z="caline_guest_profile",S="caline_edit_tokens",x="caline_liked_comments";function it(){if(typeof window>"u"||!window.localStorage)return{nick:"",mail:"",link:""};try{const t=localStorage.getItem(z);return t?JSON.parse(t):{nick:"",mail:"",link:""}}catch{return{nick:"",mail:"",link:""}}}function rt(t){if(!(typeof window>"u"||!window.localStorage))try{localStorage.setItem(z,JSON.stringify(t))}catch{}}function E(t){if(typeof window>"u"||!window.localStorage)return null;try{const e=localStorage.getItem(S);if(!e)return null;const n=JSON.parse(e),i=n[t];return i?Date.now()>i.expiresAt?(delete n[t],localStorage.setItem(S,JSON.stringify(n)),null):i.token:null}catch{return null}}function R(t,e){if(!(typeof window>"u"||!window.localStorage))try{const n=localStorage.getItem(S),i=n?JSON.parse(n):{};i[t]={token:e,expiresAt:Date.now()+9e5};const o=Date.now();for(const l of Object.keys(i))i[l].expiresAt"u"||!window.localStorage))try{const e=localStorage.getItem(S);if(!e)return;const n=JSON.parse(e);delete n[t],localStorage.setItem(S,JSON.stringify(n))}catch{}}function T(t){if(typeof window>"u"||!window.localStorage)return!1;try{const e=localStorage.getItem(x);return e?JSON.parse(e).includes(t):!1}catch{return!1}}function j(t){if(!(typeof window>"u"||!window.localStorage))try{const e=localStorage.getItem(x),n=e?JSON.parse(e):[];n.includes(t)||(n.push(t),localStorage.setItem(x,JSON.stringify(n)))}catch{}}function B(t){const e=document.createElement("div");if(e.className="cl-editor-container",t.isAllDisabled)return e.innerHTML=`

`,e;if(t.isGuestDisabled)return e.innerHTML=` - `,e;const n=it(),i=t.wordLimit||1e3;let r=!1,c=!1;if(t.replyTarget){const p=document.createElement("div");p.style.cssText="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;font-size:12px;color:var(--cl-color-text-muted);",p.innerHTML=` + `,e;const n=it(),i=t.wordLimit||1e3;let o=!1,l=!1;if(t.replyTarget){const d=document.createElement("div");d.style.cssText="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;font-size:12px;color:var(--cl-color-text-muted);",d.innerHTML=` 回复 @${t.replyTarget.nick} - `,p.querySelector(".cl-reply-cancel")?.addEventListener("click",()=>{t.replyTarget?.onCancel()}),e.appendChild(p)}const l=document.createElement("div");l.className="cl-editor-meta-inputs",l.innerHTML=` + `,d.querySelector(".cl-reply-cancel")?.addEventListener("click",()=>{t.replyTarget?.onCancel()}),e.appendChild(d)}const c=document.createElement("div");c.className="cl-editor-meta-inputs",c.innerHTML=` - `,e.appendChild(l);const o=document.createElement("textarea");o.className="cl-textarea",o.placeholder=t.t("placeholder_content");const a=document.createElement("div");a.className="cl-editor-preview",a.style.display="none",e.appendChild(o),e.appendChild(a);const s=document.createElement("div");s.className="cl-emoji-panel",s.style.display="none";for(const p of tt){const k=document.createElement("button");k.type="button",k.className="cl-emoji-btn",k.textContent=p,k.addEventListener("click",()=>{const N=o.selectionStart,$=o.selectionEnd,L=o.value;o.value=L.substring(0,N)+p+L.substring($),o.focus(),o.selectionStart=o.selectionEnd=N+p.length,h()}),s.appendChild(k)}e.appendChild(s);const u=document.createElement("div");u.className="cl-editor-footer";const f=document.createElement("div");f.className="cl-editor-tools";const g=document.createElement("button");g.type="button",g.className="cl-tool-btn",g.textContent="😀",g.addEventListener("click",()=>{c=!c,s.style.display=c?"grid":"none",g.classList.toggle("active",c)});const d=document.createElement("button");d.type="button",d.className="cl-tool-btn",d.textContent=t.t("btn_preview"),d.addEventListener("click",()=>{r=!r,r?(a.innerHTML=nt(o.value),a.style.display="block",o.style.display="none",d.classList.add("active")):(a.style.display="none",o.style.display="block",d.classList.remove("active"))});const b=document.createElement("span");b.className="cl-word-limit",b.textContent=`0 / ${i}`;function h(){const p=o.value.length;b.textContent=`${p} / ${i}`,p>i?(b.classList.add("error"),y.disabled=!0):(b.classList.remove("error"),y.disabled=p===0)}o.addEventListener("input",h),f.appendChild(g),f.appendChild(d),f.appendChild(b);const y=document.createElement("button");return y.type="button",y.className="cl-btn cl-btn-primary",y.textContent=t.t("btn_submit"),y.disabled=!0,y.addEventListener("click",async()=>{const p=l.querySelector(".cl-input-nick"),k=l.querySelector(".cl-input-mail"),N=l.querySelector(".cl-input-link"),$=p?.value.trim(),L=k?.value.trim(),Y=N?.value.trim(),F=o.value.trim();if(!$){alert(t.t("error_empty_nick")),p?.focus();return}if(!F){alert(t.t("error_empty_content")),o.focus();return}rt({nick:$,mail:L,link:Y}),y.disabled=!0,y.textContent=t.t("btn_submitting");try{await t.onSubmit({nick:$,mail:L,link:Y,content:F}),o.value="",h(),r&&d.click()}catch(X){const ut=X instanceof Error?X.message:t.t("error_network");alert(ut)}finally{y.disabled=!1,y.textContent=t.t("btn_submit")}}),u.appendChild(f),u.appendChild(y),e.appendChild(u),e}function ct(t){const e=document.createElement("div");if(e.className="cl-tree-container",t.items.length===0)return e.innerHTML=`
${t.t("no_comments")}
`,e;for(const n of t.items){const i=lt(n,t);e.appendChild(i)}return e}function lt(t,e){const n=document.createElement("div");n.className="cl-item",n.dataset.id=String(t.id);const i=E(t.id),r=q(t.id),c=v(t.nick||e.t("guest")),l=x(t.link),o=l?v(t.link.trim()):"",a=l?`${c}`:`${c}`,s=t.sticky?`${e.t("sticky")}`:"",u=t.badge?`${v(t.badge)}`:"",f=t.level!==void 0?`Lv.${t.level}`:"",g=new Date(t.createdAt).toLocaleDateString();n.innerHTML=` + `,e.appendChild(c);const r=document.createElement("textarea");r.className="cl-textarea",r.placeholder=t.t("placeholder_content");const a=document.createElement("div");a.className="cl-editor-preview",a.style.display="none",e.appendChild(r),e.appendChild(a);const s=document.createElement("div");s.className="cl-emoji-panel",s.style.display="none";for(const d of tt){const k=document.createElement("button");k.type="button",k.className="cl-emoji-btn",k.textContent=d,k.addEventListener("click",()=>{const N=r.selectionStart,$=r.selectionEnd,L=r.value;r.value=L.substring(0,N)+d+L.substring($),r.focus(),r.selectionStart=r.selectionEnd=N+d.length,h()}),s.appendChild(k)}e.appendChild(s);const m=document.createElement("div");m.className="cl-editor-footer";const g=document.createElement("div");g.className="cl-editor-tools";const p=document.createElement("button");p.type="button",p.className="cl-tool-btn",p.textContent="😀",p.addEventListener("click",()=>{l=!l,s.style.display=l?"grid":"none",p.classList.toggle("active",l)});const u=document.createElement("button");u.type="button",u.className="cl-tool-btn",u.textContent=t.t("btn_preview"),u.addEventListener("click",()=>{o=!o,o?(a.innerHTML=nt(r.value),a.style.display="block",r.style.display="none",u.classList.add("active")):(a.style.display="none",r.style.display="block",u.classList.remove("active"))});const v=document.createElement("span");v.className="cl-word-limit",v.textContent=`0 / ${i}`;function h(){const d=r.value.length;v.textContent=`${d} / ${i}`,d>i?(v.classList.add("error"),y.disabled=!0):(v.classList.remove("error"),y.disabled=d===0)}r.addEventListener("input",h),g.appendChild(p),g.appendChild(u),g.appendChild(v);const y=document.createElement("button");return y.type="button",y.className="cl-btn cl-btn-primary",y.textContent=t.t("btn_submit"),y.disabled=!0,y.addEventListener("click",async()=>{const d=c.querySelector(".cl-input-nick"),k=c.querySelector(".cl-input-mail"),N=c.querySelector(".cl-input-link"),$=d?.value.trim(),L=k?.value.trim(),Y=N?.value.trim(),F=r.value.trim();if(!$){alert(t.t("error_empty_nick")),d?.focus();return}if(!F){alert(t.t("error_empty_content")),r.focus();return}rt({nick:$,mail:L,link:Y}),y.disabled=!0,y.textContent=t.t("btn_submitting");try{await t.onSubmit({nick:$,mail:L,link:Y,content:F}),r.value="",h(),o&&u.click()}catch(X){const ut=X instanceof Error?X.message:t.t("error_network");alert(ut)}finally{y.disabled=!1,y.textContent=t.t("btn_submit")}}),m.appendChild(g),m.appendChild(y),e.appendChild(m),e}function ct(t){const e=document.createElement("div");if(e.className="cl-tree-container",t.items.length===0)return e.innerHTML=`
${t.t("no_comments")}
`,e;for(const n of t.items){const i=lt(n,t);e.appendChild(i)}return e}function lt(t,e){const n=document.createElement("div");n.className="cl-item",n.dataset.id=String(t.id);const i=E(t.id),o=T(t.id),l=b(t.nick||e.t("guest")),c=A(t.link),r=c?b(t.link.trim()):"",a=c?`${l}`:`${l}`,s=t.sticky?`${e.t("sticky")}`:"",m=t.badge?`${b(t.badge)}`:"",g=t.level!==void 0?`Lv.${t.level}`:"",p=new Date(t.createdAt).toLocaleDateString();n.innerHTML=`
- ${c} + ${l}
${a} ${s} - ${u} - ${f} - ${g} + ${m} + ${g} + ${p}
${t.contentHtml}
- ${i?``:""} @@ -39,46 +39,46 @@
- `;const d=n.querySelector(".cl-btn-like");d?.addEventListener("click",async()=>{if(!q(t.id))try{const h=await e.onLike(t.id);j(t.id),d.classList.add("cl-liked"),d.textContent=`${e.t("liked")} (${h})`}catch(h){alert(h instanceof Error?h.message:e.t("error_network"))}}),n.querySelector(".cl-btn-reply")?.addEventListener("click",()=>{e.onReply(t,t.id)}),i&&B(n,t.id,t.contentHtml,i,e);const b=n.querySelector(".cl-replies-list");if(t.replies&&t.replies.length>0)for(const h of t.replies){const y=at(h,t.id,e);b.appendChild(y)}return n}function at(t,e,n){const i=document.createElement("div");i.className="cl-reply-item",i.dataset.id=String(t.id);const r=E(t.id),c=q(t.id),l=v(t.nick||n.t("guest")),o=x(t.link),a=o?v(t.link.trim()):"",s=o?`${l}`:`${l}`,u=t.badge?`${v(t.badge)}`:"",f=t.level!==void 0?`Lv.${t.level}`:"",g=new Date(t.createdAt).toLocaleDateString(),d=t.replyTo?`@${v(t.replyTo.nick)}`:"";i.innerHTML=` + `;const u=n.querySelector(".cl-btn-like");u?.addEventListener("click",async()=>{if(!T(t.id))try{const h=await e.onLike(t.id);j(t.id),u.classList.add("cl-liked"),u.textContent=`${e.t("liked")} (${h})`}catch(h){alert(h instanceof Error?h.message:e.t("error_network"))}}),n.querySelector(".cl-btn-reply")?.addEventListener("click",()=>{e.onReply(t,t.id)}),i&&D(n,t.id,t.contentHtml,i,e);const v=n.querySelector(".cl-replies-list");if(t.replies&&t.replies.length>0)for(const h of t.replies){const y=at(h,t.id,e);v.appendChild(y)}return n}function at(t,e,n){const i=document.createElement("div");i.className="cl-reply-item",i.dataset.id=String(t.id);const o=E(t.id),l=T(t.id),c=b(t.nick||n.t("guest")),r=A(t.link),a=r?b(t.link.trim()):"",s=r?`${c}`:`${c}`,m=t.badge?`${b(t.badge)}`:"",g=t.level!==void 0?`Lv.${t.level}`:"",p=new Date(t.createdAt).toLocaleDateString(),u=t.replyTo?`@${b(t.replyTo.nick)}`:"";i.innerHTML=`
- ${l} + ${c}
${s} - ${u} - ${f} - ${g} + ${m} + ${g} + ${p}
-
${d}${t.contentHtml}
+
${u}${t.contentHtml}
- - ${r?``:""} - ${r?``:""} + ${o?``:""} + ${o?``:""}
- `;const b=i.querySelector(".cl-btn-like");return b?.addEventListener("click",async()=>{if(!q(t.id))try{const h=await n.onLike(t.id);j(t.id),b.classList.add("cl-liked"),b.textContent=`${n.t("liked")} (${h})`}catch(h){alert(h instanceof Error?h.message:n.t("error_network"))}}),i.querySelector(".cl-btn-reply")?.addEventListener("click",()=>{n.onReply(t,e)}),r&&B(i,t.id,t.contentHtml,r,n),i}function B(t,e,n,i,r){const c=t.querySelector(".cl-btn-edit"),l=t.querySelector(".cl-btn-delete"),o=t.querySelector(".cl-comment-text");c?.addEventListener("click",()=>{if(!E(e)){alert(r.t("edit_expired")),c.remove(),l?.remove();return}const a=document.createElement("div");a.style.marginTop="8px";const s=document.createElement("textarea");s.className="cl-textarea",s.style.minHeight="60px",s.value=(o.textContent||"").trim();const u=document.createElement("div");u.style.cssText="display:flex;gap:8px;margin-top:6px;",u.innerHTML=` - - - `,a.appendChild(s),a.appendChild(u);const f=o.style.display;o.style.display="none",o.parentNode?.insertBefore(a,o.nextSibling),a.querySelector(".cl-edit-cancel")?.addEventListener("click",()=>{a.remove(),o.style.display=f}),a.querySelector(".cl-edit-save")?.addEventListener("click",async()=>{const g=s.value.trim();if(g)try{const d=await r.onUpdate(e,g,i);o.innerHTML=d,a.remove(),o.style.display=f}catch(d){alert(d instanceof Error?d.message:r.t("edit_expired"))}})}),l?.addEventListener("click",async()=>{if(!E(e)){alert(r.t("edit_expired")),c?.remove(),l.remove();return}if(confirm(r.t("delete_confirm")))try{await r.onDelete(e,i),ot(e),t.remove()}catch(a){alert(a instanceof Error?a.message:r.t("edit_expired"))}})}var I={placeholder_nick:"昵称 *",placeholder_mail:"邮箱 (Gravatar)",placeholder_link:"网址 (https://)",placeholder_content:"支持 Markdown 语法...",btn_submit:"发表评论",btn_submitting:"发送中...",btn_reply:"回复",btn_cancel:"取消",btn_preview:"预览",btn_edit:"编辑",btn_delete:"删除",btn_save:"保存",sort_newest:"最新",sort_oldest:"最早",sort_hottest:"最热",comments_count:"条评论",no_comments:"暂无评论,来抢沙发吧~",sticky:"置顶",login_to_comment:"登录后发表评论",login_prompt:"已有账号?点击登录",guest_closed:"当前仅允许登录用户发表评论",all_closed:"全站评论功能已关闭",edit_expired:"已超过 15 分钟编辑期限,请联系管理员",delete_confirm:"确定要删除这条评论吗?",like:"赞",liked:"已赞",load_more:"加载更多",loading:"加载中...",error_network:"网络请求失败,请稍后重试",error_empty_nick:"请填写昵称",error_empty_content:"评论内容不能为空",error_word_limit:"字数超出限制",recent_title:"最新评论",pageview:"次浏览",guest:"访客",admin:"管理员",verified:"已认证"},st={placeholder_nick:"Nickname *",placeholder_mail:"Email (Gravatar)",placeholder_link:"Website (https://)",placeholder_content:"Markdown supported...",btn_submit:"Submit",btn_submitting:"Submitting...",btn_reply:"Reply",btn_cancel:"Cancel",btn_preview:"Preview",btn_edit:"Edit",btn_delete:"Delete",btn_save:"Save",sort_newest:"Newest",sort_oldest:"Oldest",sort_hottest:"Hottest",comments_count:"comments",no_comments:"No comments yet.",sticky:"Pinned",login_to_comment:"Sign in to comment",login_prompt:"Already have an account? Sign in",guest_closed:"Only registered users can comment",all_closed:"Comments are disabled",edit_expired:"Edit window expired (15m), please contact admin",delete_confirm:"Are you sure you want to delete this comment?",like:"Like",liked:"Liked",load_more:"Load more",loading:"Loading...",error_network:"Network error, please try again later",error_empty_nick:"Nickname is required",error_empty_content:"Content cannot be empty",error_word_limit:"Character limit exceeded",recent_title:"Recent Comments",pageview:"Views",guest:"Guest",admin:"Admin",verified:"Verified"};function J(t){if(t){const e=t.toLowerCase();if(e.startsWith("zh"))return"zh-CN";if(e.startsWith("en"))return"en"}if(typeof document<"u"&&document.documentElement.lang){const e=document.documentElement.lang.toLowerCase();if(e.startsWith("zh"))return"zh-CN";if(e.startsWith("en"))return"en"}return"zh-CN"}function W(t){const e=t==="en"?st:I;return function(i){return e[i]??I[i]??i}}async function H(t){const e=new C(t.serverURL),n=t.selector||"[data-caline-count]",i=typeof document<"u"?Array.from(document.querySelectorAll(n)):[];let r=t.urls||[];if(r.length===0&&i.length>0&&(r=i.map(l=>l.getAttribute("data-caline-count")||l.getAttribute("data-path")||"").filter(Boolean)),r.length===0)return{};const c=await e.getCommentCounts(r);for(const l of i){const o=l.getAttribute("data-caline-count")||l.getAttribute("data-path")||"";o&&c[o]!==void 0&&(l.textContent=String(c[o]))}return c}async function M(t){const e=new C(t.serverURL),n=t.url||(typeof window<"u"?window.location.pathname:"");if(!n)return 0;const i=await e.postView({url:n}),r=t.selector||"[data-caline-pageview]";if(typeof document<"u"){const c=document.querySelectorAll(r);for(const l of c)(l.getAttribute("data-path")||n)===n&&(l.textContent=String(i.pageview))}return i.pageview}async function K(t){const e=new C(t.serverURL),n=t.url||(typeof window<"u"?window.location.pathname:"");return n?e.postReaction({url:n,type:t.type}):null}async function G(t){const e=typeof t.el=="string"?document.querySelector(t.el):t.el;if(!e)return;const n=J(t.lang),i=W(n),r=new C(t.serverURL);e.innerHTML=`
${i("loading")}
`;try{const c=await r.getRecentComments(t.count||5);if(!c||c.length===0){e.innerHTML=`
${i("no_comments")}
`;return}e.innerHTML=`
${c.map(l=>{const o=v(l.nick||i("guest")),a=x(l.link),s=a?v(l.link.trim()):"",u=a?`${o}`:`${o}`;return` -
+ `;const v=i.querySelector(".cl-btn-like");return v?.addEventListener("click",async()=>{if(!T(t.id))try{const h=await n.onLike(t.id);j(t.id),v.classList.add("cl-liked"),v.textContent=`${n.t("liked")} (${h})`}catch(h){alert(h instanceof Error?h.message:n.t("error_network"))}}),i.querySelector(".cl-btn-reply")?.addEventListener("click",()=>{n.onReply(t,e)}),o&&D(i,t.id,t.contentHtml,o,n),i}function D(t,e,n,i,o){const l=t.querySelector(".cl-btn-edit"),c=t.querySelector(".cl-btn-delete"),r=t.querySelector(".cl-comment-text");l?.addEventListener("click",()=>{if(!E(e)){alert(o.t("edit_expired")),l.remove(),c?.remove();return}const a=document.createElement("div");a.style.marginTop="8px";const s=document.createElement("textarea");s.className="cl-textarea",s.style.minHeight="60px",s.value=(r.textContent||"").trim();const m=document.createElement("div");m.style.cssText="display:flex;gap:8px;margin-top:6px;",m.innerHTML=` + + + `,a.appendChild(s),a.appendChild(m);const g=r.style.display;r.style.display="none",r.parentNode?.insertBefore(a,r.nextSibling),a.querySelector(".cl-edit-cancel")?.addEventListener("click",()=>{a.remove(),r.style.display=g}),a.querySelector(".cl-edit-save")?.addEventListener("click",async()=>{const p=s.value.trim();if(p)try{const u=await o.onUpdate(e,p,i);r.innerHTML=u,a.remove(),r.style.display=g}catch(u){alert(u instanceof Error?u.message:o.t("edit_expired"))}})}),c?.addEventListener("click",async()=>{if(!E(e)){alert(o.t("edit_expired")),l?.remove(),c.remove();return}if(confirm(o.t("delete_confirm")))try{await o.onDelete(e,i),ot(e),t.remove()}catch(a){alert(a instanceof Error?a.message:o.t("edit_expired"))}})}var I={placeholder_nick:"昵称 *",placeholder_mail:"邮箱 (Gravatar)",placeholder_link:"网址 (https://)",placeholder_content:"支持 Markdown 语法...",btn_submit:"发表评论",btn_submitting:"发送中...",btn_reply:"回复",btn_cancel:"取消",btn_preview:"预览",btn_edit:"编辑",btn_delete:"删除",btn_save:"保存",sort_newest:"最新",sort_oldest:"最早",sort_hottest:"最热",comments_count:"条评论",no_comments:"暂无评论,来抢沙发吧~",sticky:"置顶",login_to_comment:"登录后发表评论",login_prompt:"已有账号?点击登录",guest_closed:"当前仅允许登录用户发表评论",all_closed:"全站评论功能已关闭",edit_expired:"已超过 15 分钟编辑期限,请联系管理员",delete_confirm:"确定要删除这条评论吗?",like:"赞",liked:"已赞",load_more:"加载更多",loading:"加载中...",error_network:"网络请求失败,请稍后重试",error_empty_nick:"请填写昵称",error_empty_content:"评论内容不能为空",error_word_limit:"字数超出限制",recent_title:"最新评论",pageview:"次浏览",guest:"访客",admin:"管理员",verified:"已认证"},st={placeholder_nick:"Nickname *",placeholder_mail:"Email (Gravatar)",placeholder_link:"Website (https://)",placeholder_content:"Markdown supported...",btn_submit:"Submit",btn_submitting:"Submitting...",btn_reply:"Reply",btn_cancel:"Cancel",btn_preview:"Preview",btn_edit:"Edit",btn_delete:"Delete",btn_save:"Save",sort_newest:"Newest",sort_oldest:"Oldest",sort_hottest:"Hottest",comments_count:"comments",no_comments:"No comments yet.",sticky:"Pinned",login_to_comment:"Sign in to comment",login_prompt:"Already have an account? Sign in",guest_closed:"Only registered users can comment",all_closed:"Comments are disabled",edit_expired:"Edit window expired (15m), please contact admin",delete_confirm:"Are you sure you want to delete this comment?",like:"Like",liked:"Liked",load_more:"Load more",loading:"Loading...",error_network:"Network error, please try again later",error_empty_nick:"Nickname is required",error_empty_content:"Content cannot be empty",error_word_limit:"Character limit exceeded",recent_title:"Recent Comments",pageview:"Views",guest:"Guest",admin:"Admin",verified:"Verified"};function J(t){if(t){const e=t.toLowerCase();if(e.startsWith("zh"))return"zh-CN";if(e.startsWith("en"))return"en"}if(typeof document<"u"&&document.documentElement.lang){const e=document.documentElement.lang.toLowerCase();if(e.startsWith("zh"))return"zh-CN";if(e.startsWith("en"))return"en"}return"zh-CN"}function W(t){const e=t==="en"?st:I;return function(i){return e[i]??I[i]??i}}async function H(t){const e=new C(t.serverURL),n=t.selector||"[data-caline-count]",i=typeof document<"u"?Array.from(document.querySelectorAll(n)):[];let o=t.urls||[];if(o.length===0&&i.length>0&&(o=i.map(c=>c.getAttribute("data-caline-count")||c.getAttribute("data-path")||"").filter(Boolean)),o.length===0)return{};const l=await e.getCommentCounts(o);for(const c of i){const r=c.getAttribute("data-caline-count")||c.getAttribute("data-path")||"";r&&l[r]!==void 0&&(c.textContent=String(l[r]))}return l}async function M(t){const e=new C(t.serverURL),n=t.url||(typeof window<"u"?window.location.pathname:"");if(!n)return 0;const i=await e.postView({url:n}),o=t.selector||"[data-caline-pageview]";if(typeof document<"u"){const l=document.querySelectorAll(o);for(const c of l)(c.getAttribute("data-path")||n)===n&&(c.textContent=String(i.pageview))}return i.pageview}async function G(t){const e=new C(t.serverURL),n=t.url||(typeof window<"u"?window.location.pathname:"");return n?e.postReaction({url:n,type:t.type}):null}async function K(t){const e=typeof t.el=="string"?document.querySelector(t.el):t.el;if(!e)return;const n=J(t.lang),i=W(n),o=new C(t.serverURL);e.innerHTML=`
${i("loading")}
`;try{const l=await o.getRecentComments(t.count||5);if(!l||l.length===0){e.innerHTML=`
${i("no_comments")}
`;return}e.innerHTML=`
${l.map(c=>{const r=b(c.nick||i("guest")),a=A(c.link),s=a?b(c.link.trim()):"",m=a?`${r}`:`${r}`;return` +
- ${o} + ${r}
- ${u} - ${new Date(l.createdAt).toLocaleDateString()} + ${m} + ${new Date(c.createdAt).toLocaleDateString()}
- ${l.contentHtml} + ${c.contentHtml}
- `}).join("")}
`}catch{e.innerHTML=`
${i("error_network")}
`}}var V=class{constructor(t){m(this,"container",void 0),m(this,"serverUrl",void 0),m(this,"path",void 0),m(this,"client",void 0),m(this,"pageSize",void 0),m(this,"wordLimit",void 0),m(this,"currentSort","newest"),m(this,"currentPage",1),m(this,"totalPages",1),m(this,"totalComments",0),m(this,"comments",[]),m(this,"t",void 0),m(this,"editorContainer",void 0),m(this,"treeContainer",void 0),m(this,"countTitle",void 0),m(this,"loadMoreBtn",void 0);let e=t.el;if(e?typeof e=="string"&&typeof document<"u"&&(e=document.querySelector(e)||void 0):typeof document<"u"&&(e=document.querySelector("#caline")||document.querySelector("#comments")||document.querySelector("#waline")||document.querySelector("[data-caline]")||void 0),!e)throw new Error(`Caline: container '${t.el||"#caline"}' not found`);this.container=e,this.container.dataset.calineInitialized="true";let n=t.serverURL;n||(typeof window<"u"&&window.location?.origin?n=window.location.origin:n="",typeof console<"u"&&console.warn&&console.warn("[Caline] serverURL is not specified, falling back to location.origin:",n)),this.serverUrl=(n||"").replace(/\/+$/,""),this.path=t.path||(typeof window<"u"?window.location.pathname:"/"),this.pageSize=t.pageSize||10,this.wordLimit=t.wordLimit||1e3;const i=J(t.lang);this.t=W(i),this.client=new C(this.serverUrl),this.renderSkeleton(),this.loadComments()}renderSkeleton(){this.container.classList.add("cl-root"),this.container.innerHTML=` + `}).join("")}
`}catch{e.innerHTML=`
${i("error_network")}
`}}var V=class{constructor(t){f(this,"container",void 0),f(this,"serverUrl",void 0),f(this,"path",void 0),f(this,"client",void 0),f(this,"pageSize",void 0),f(this,"wordLimit",void 0),f(this,"currentSort","newest"),f(this,"currentPage",1),f(this,"totalPages",1),f(this,"totalComments",0),f(this,"comments",[]),f(this,"t",void 0),f(this,"editorContainer",void 0),f(this,"treeContainer",void 0),f(this,"countTitle",void 0),f(this,"loadMoreBtn",void 0);let e=t.el;if(e?typeof e=="string"&&typeof document<"u"&&(e=document.querySelector(e)||void 0):typeof document<"u"&&(e=document.querySelector("#caline")||document.querySelector("#comments")||document.querySelector("#waline")||document.querySelector("[data-caline]")||void 0),!e)throw new Error(`Caline: container '${t.el||"#caline"}' not found`);this.container=e,this.container.dataset.calineInitialized="true";let n=t.serverURL;n||(typeof window<"u"&&window.location?.origin?n=window.location.origin:n="",typeof console<"u"&&console.warn&&console.warn("[Caline] serverURL is not specified, falling back to location.origin:",n)),this.serverUrl=(n||"").replace(/\/+$/,""),this.path=t.path||(typeof window<"u"?window.location.pathname:"/"),this.pageSize=t.pageSize||10,this.wordLimit=t.wordLimit||1e3;const i=J(t.lang);this.t=W(i),this.client=new C(this.serverUrl),this.renderSkeleton(),this.loadComments()}renderSkeleton(){this.container.classList.add("cl-root"),this.container.innerHTML=`
0 ${this.t("comments_count")}
@@ -92,4 +92,4 @@ - `,this.editorContainer=this.container.querySelector(".cl-editor-slot"),this.treeContainer=this.container.querySelector(".cl-tree-slot"),this.countTitle=this.container.querySelector(".cl-count-title"),this.loadMoreBtn=this.container.querySelector(".cl-btn-load-more");const t=this.container.querySelectorAll(".cl-sort-btn");for(const e of t)e.addEventListener("click",()=>{for(const i of t)i.classList.remove("active");e.classList.add("active");const n=e.getAttribute("data-sort");this.currentSort!==n&&(this.currentSort=n,this.currentPage=1,this.loadComments(!0))});this.loadMoreBtn.addEventListener("click",()=>{this.currentPage{const n=await this.client.createComment({url:this.path,content:e.content,nick:e.nick,mail:e.mail,link:e.link});n.editToken&&R(n.comment.id,n.editToken),this.currentPage=1,await this.loadComments(!0)}});this.editorContainer.appendChild(t)}async loadComments(t=!0){t&&(this.treeContainer.innerHTML=`
${this.t("loading")}
`);try{const e=await this.client.listComments({url:this.path,page:this.currentPage,pageSize:this.pageSize,sort:this.currentSort});this.totalComments=e.total,this.totalPages=e.totalPages,this.countTitle.textContent=`${this.totalComments} ${this.t("comments_count")}`,t?this.comments=e.items:this.comments=[...this.comments,...e.items],this.treeContainer.innerHTML="";const n=ct({items:this.comments,t:this.t,onReply:(r,c)=>{this.showReplyEditor(r,c)},onLike:async r=>(await this.client.likeComment(r)).likeCount,onUpdate:async(r,c,l)=>(await this.client.updateComment(r,{content:c},l)).contentHtml,onDelete:async(r,c)=>{await this.client.deleteComment(r,c),this.totalComments=Math.max(0,this.totalComments-1),this.countTitle.textContent=`${this.totalComments} ${this.t("comments_count")}`}});this.treeContainer.appendChild(n);const i=this.container.querySelector(".cl-load-more-wrap");this.currentPage${this.t("error_network")}
`}}showReplyEditor(t,e){const n=this.treeContainer.querySelector(".cl-reply-editor-slot");n&&n.remove();const i=this.treeContainer.querySelector(`[data-id="${t.id}"]`);if(!i)return;const r=document.createElement("div");r.className="cl-reply-editor-slot",r.style.marginTop="8px";const c=D({t:this.t,wordLimit:this.wordLimit,serverUrl:this.serverUrl,replyTarget:{nick:t.nick||this.t("guest"),onCancel:()=>r.remove()},onSubmit:async o=>{const a=await this.client.createComment({url:this.path,content:o.content,pid:t.id,rid:e,nick:o.nick,mail:o.mail,link:o.link});a.editToken&&R(a.comment.id,a.editToken),r.remove(),this.currentPage=1,await this.loadComments(!0)}});r.appendChild(c);const l=i.querySelector(".cl-content-wrap");l?l.appendChild(r):i.appendChild(r)}};function O(t){return new V(t)}function dt(){if(typeof document>"u")return null;if(document.currentScript&&document.currentScript instanceof HTMLScriptElement)return document.currentScript;const t=Array.from(document.querySelectorAll("script"));for(let e=t.length-1;e>=0;e--){const n=t[e];if(n.hasAttribute("data-server-url")||n.hasAttribute("data-caline")||n.src&&(n.src.includes("/client/v1.js")||n.src.includes("v1.js")))return n}return null}function T(){if(typeof window>"u"||typeof document>"u")return null;const t=window.CALINE_CONFIG||{},e=dt(),n=e?e.dataset:{};let i=t.serverURL||n.serverUrl||e?.getAttribute("data-server-url")||"";if(!i&&e?.src)try{const d=new URL(e.src,window.location.href);(d.protocol==="http:"||d.protocol==="https:")&&(i=d.origin)}catch{}let r=null;const c=t.el||n.el||e?.getAttribute("data-el");if(c?typeof c=="string"?r=document.querySelector(c):c instanceof HTMLElement&&(r=c):r=document.querySelector("#caline")||document.querySelector("#comments")||document.querySelector("#waline")||document.querySelector("[data-caline]"),!i&&r?.getAttribute("data-server-url")&&(i=r.getAttribute("data-server-url")||""),i||(i=window.location.origin||"",typeof console<"u"&&console.warn&&console.warn("[Caline] serverURL is not specified, falling back to location.origin:",i)),!r&&e&&e.parentNode){const d=document.createElement("div");d.id="caline",d.className="caline-container",e.parentNode.insertBefore(d,e.nextSibling),r=d}if(!r||r.dataset.calineInitialized==="true")return null;const l=t.path||n.path||e?.getAttribute("data-path")||r.getAttribute("data-path")||void 0,o=t.lang||n.lang||e?.getAttribute("data-lang")||r.getAttribute("data-lang")||void 0,a=t.pageSize||n.pageSize||e?.getAttribute("data-page-size")||r.getAttribute("data-page-size"),s=a?Number(a):void 0,u=t.wordLimit||n.wordLimit||e?.getAttribute("data-word-limit")||r.getAttribute("data-word-limit"),f=u?Number(u):void 0,g=O({el:r,serverURL:i,path:l,lang:o,pageSize:s,wordLimit:f});return i&&(document.querySelector("[data-caline-count]")&&H({serverURL:i}).catch(()=>{}),document.querySelector("[data-caline-pageview]")&&M({serverURL:i}).catch(()=>{})),g}function P(){typeof document>"u"||(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{T()},{once:!0}):T())}var U={init:O,autoInit:T,scheduleAutoInit:P,commentCount:H,pageview:M,reaction:K,recentComments:G};if(typeof window<"u"){const t=window;t.Caline=U,P()}w.Caline=U,w.default=U,w.CalineWidget=V,w.autoInit=T,w.commentCount=H,w.init=O,w.pageview=M,w.reaction=K,w.recentComments=G,w.scheduleAutoInit=P})(this.Caline=this.Caline||{}); + `,this.editorContainer=this.container.querySelector(".cl-editor-slot"),this.treeContainer=this.container.querySelector(".cl-tree-slot"),this.countTitle=this.container.querySelector(".cl-count-title"),this.loadMoreBtn=this.container.querySelector(".cl-btn-load-more");const t=this.container.querySelectorAll(".cl-sort-btn");for(const e of t)e.addEventListener("click",()=>{for(const i of t)i.classList.remove("active");e.classList.add("active");const n=e.getAttribute("data-sort");this.currentSort!==n&&(this.currentSort=n,this.currentPage=1,this.loadComments(!0))});this.loadMoreBtn.addEventListener("click",()=>{this.currentPage{const n=await this.client.createComment({url:this.path,content:e.content,nick:e.nick,mail:e.mail,link:e.link});n.editToken&&R(n.comment.id,n.editToken),this.currentPage=1,await this.loadComments(!0)}});this.editorContainer.appendChild(t)}async loadComments(t=!0){t&&(this.treeContainer.innerHTML=`
${this.t("loading")}
`);try{const e=await this.client.listComments({url:this.path,page:this.currentPage,pageSize:this.pageSize,sort:this.currentSort});this.totalComments=e.total,this.totalPages=e.totalPages,this.countTitle.textContent=`${this.totalComments} ${this.t("comments_count")}`,t?this.comments=e.items:this.comments=[...this.comments,...e.items],this.treeContainer.innerHTML="";const n=ct({items:this.comments,t:this.t,onReply:(o,l)=>{this.showReplyEditor(o,l)},onLike:async o=>(await this.client.likeComment(o)).likeCount,onUpdate:async(o,l,c)=>(await this.client.updateComment(o,{content:l},c)).contentHtml,onDelete:async(o,l)=>{await this.client.deleteComment(o,l),this.totalComments=Math.max(0,this.totalComments-1),this.countTitle.textContent=`${this.totalComments} ${this.t("comments_count")}`}});this.treeContainer.appendChild(n);const i=this.container.querySelector(".cl-load-more-wrap");this.currentPage${this.t("error_network")}
`}}showReplyEditor(t,e){const n=this.treeContainer.querySelector(".cl-reply-editor-slot");n&&n.remove();const i=this.treeContainer.querySelector(`[data-id="${t.id}"]`);if(!i)return;const o=document.createElement("div");o.className="cl-reply-editor-slot",o.style.marginTop="8px";const l=B({t:this.t,wordLimit:this.wordLimit,serverUrl:this.serverUrl,replyTarget:{nick:t.nick||this.t("guest"),onCancel:()=>o.remove()},onSubmit:async r=>{const a=await this.client.createComment({url:this.path,content:r.content,pid:t.id,rid:e,nick:r.nick,mail:r.mail,link:r.link});a.editToken&&R(a.comment.id,a.editToken),o.remove(),this.currentPage=1,await this.loadComments(!0)}});o.appendChild(l);const c=i.querySelector(".cl-content-wrap");c?c.appendChild(o):i.appendChild(o)}};function O(t){return new V(t)}function dt(){if(typeof document>"u")return null;if(document.currentScript&&document.currentScript instanceof HTMLScriptElement)return document.currentScript;const t=Array.from(document.querySelectorAll("script"));for(let e=t.length-1;e>=0;e--){const n=t[e];if(n.hasAttribute("data-server-url")||n.hasAttribute("data-caline")||n.src&&(n.src.includes("/client/v1.js")||n.src.includes("v1.js")))return n}return null}function q(){if(typeof window>"u"||typeof document>"u")return null;const t=window.CALINE_CONFIG||{},e=typeof t=="object"&&t!==null&&Object.keys(t).length>0,n=dt(),i=n?n.dataset:{},o=!!(n&&(n.hasAttribute("data-caline")||n.hasAttribute("data-server-url")||n.hasAttribute("data-el")||n.hasAttribute("data-path")||n.hasAttribute("data-lang"))),l=document.querySelector("[data-caline], #caline");if(!(e||o||l))return null;let c=t.serverURL||i.serverUrl||n?.getAttribute("data-server-url")||"";if(!c&&n?.src)try{const d=new URL(n.src,window.location.href);(d.protocol==="http:"||d.protocol==="https:")&&(c=d.origin)}catch{}let r=null;const a=t.el||i.el||n?.getAttribute("data-el");a?typeof a=="string"?r=document.querySelector(a):a instanceof HTMLElement&&(r=a):r=l||(e||o?document.querySelector("#comments")||document.querySelector("#waline"):null),!c&&r?.getAttribute("data-server-url")&&(c=r.getAttribute("data-server-url")||""),c||(c=window.location.origin||"",typeof console<"u"&&console.warn&&console.warn("[Caline] serverURL is not specified, falling back to location.origin:",c));const s=!!(n&&(n.closest?.("head")||n.parentNode&&n.parentNode.nodeName.toLowerCase()==="head"));if(!r&&n&&n.parentNode&&!s){const d=document.createElement("div");d.id="caline",d.className="caline-container",n.parentNode.insertBefore(d,n.nextSibling),r=d}if(!r||r.dataset.calineInitialized==="true")return null;const m=t.path||i.path||n?.getAttribute("data-path")||r.getAttribute("data-path")||void 0,g=t.lang||i.lang||n?.getAttribute("data-lang")||r.getAttribute("data-lang")||void 0,p=t.pageSize||i.pageSize||n?.getAttribute("data-page-size")||r.getAttribute("data-page-size"),u=p?Number(p):void 0,v=t.wordLimit||i.wordLimit||n?.getAttribute("data-word-limit")||r.getAttribute("data-word-limit"),h=v?Number(v):void 0,y=O({el:r,serverURL:c,path:m,lang:g,pageSize:u,wordLimit:h});return c&&(document.querySelector("[data-caline-count]")&&H({serverURL:c}).catch(()=>{}),document.querySelector("[data-caline-pageview]")&&M({serverURL:c}).catch(()=>{})),y}function P(){typeof document>"u"||(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{q()},{once:!0}):q())}var U={init:O,autoInit:q,scheduleAutoInit:P,commentCount:H,pageview:M,reaction:G,recentComments:K};if(typeof window<"u"){const t=window;t.Caline=U,P()}w.Caline=U,w.default=U,w.CalineWidget=V,w.autoInit=q,w.commentCount=H,w.init=O,w.pageview=M,w.reaction=G,w.recentComments=K,w.scheduleAutoInit=P})(this.Caline=this.Caline||{});