diff --git a/client/src/index.ts b/client/src/index.ts index 5ce0b0f..4f31ac2 100644 --- a/client/src/index.ts +++ b/client/src/index.ts @@ -51,7 +51,7 @@ export class CalineWidget { document.querySelector("#caline") || document.querySelector("#comments") || document.querySelector("#waline") || - document.querySelector("[data-caline]") || + document.querySelector("[data-caline]:not(script)") || undefined } } else if (typeof el === "string" && typeof document !== "undefined") { @@ -354,7 +354,7 @@ export function autoInit(): CalineWidget | null { ) const explicitCalineContainer = document.querySelector( - "[data-caline], #caline" + "[data-caline]:not(script), #caline" ) const hasIntent = diff --git a/client/test/widget.test.ts b/client/test/widget.test.ts index fed6ad4..3f57689 100644 --- a/client/test/widget.test.ts +++ b/client/test/widget.test.ts @@ -348,6 +348,30 @@ Reply to @alice and @bob ).toBe(true) }) + it("Caline.init container fallback excludes + ` + expect(() => init({ serverURL: "https://example.com" })).toThrow( + "Caline: container '#caline' not found" + ) + const scriptTag = document.querySelector("script") + expect(scriptTag?.classList.contains("cl-root")).toBe(false) + }) + + it("Caline.init container fallback matches
while ignoring +
+ ` + const widget = init({ serverURL: "https://example.com" }) + expect(widget).toBeDefined() + const realContainer = document.querySelector("#real-container") + expect(realContainer?.classList.contains("cl-root")).toBe(true) + const scriptTag = document.querySelector("script") + expect(scriptTag?.classList.contains("cl-root")).toBe(false) + }) + it("autoInit reads data attributes from script tag and mounts to container", () => { document.body.innerHTML = `
@@ -386,6 +410,103 @@ Reply to @alice and @bob ) }) + it("autoInit handles + + ` + + const widget = autoInit() + expect(widget).not.toBeNull() + const scriptTag = document.querySelector("script") + expect(scriptTag?.classList.contains("cl-root")).toBe(false) + const insertedDiv = scriptTag?.nextElementSibling as HTMLElement + expect(insertedDiv).not.toBeNull() + expect(insertedDiv.id).toBe("caline") + expect(insertedDiv.classList.contains("cl-root")).toBe(true) + expect(insertedDiv.getAttribute("data-caline-initialized")).toBe("true") + }) + + it("autoInit handles + + ` + + const widget = autoInit() + expect(widget).not.toBeNull() + const scriptTag = document.querySelector("script") + expect(scriptTag?.classList.contains("cl-root")).toBe(false) + const insertedDiv = scriptTag?.nextElementSibling as HTMLElement + expect(insertedDiv).not.toBeNull() + expect(insertedDiv.id).toBe("caline") + expect(insertedDiv.classList.contains("cl-root")).toBe(true) + expect(insertedDiv.getAttribute("data-caline-initialized")).toBe("true") + }) + + it("autoInit preserves existing container
without regression", () => { + document.body.innerHTML = ` +
+ + ` + + const widget = autoInit() + expect(widget).not.toBeNull() + const scriptTag = document.querySelector("script") + expect(scriptTag?.classList.contains("cl-root")).toBe(false) + const targetDiv = document.querySelector("#explicit-div") + expect(targetDiv?.classList.contains("cl-root")).toBe(true) + expect(targetDiv?.getAttribute("data-caline-initialized")).toBe("true") + // Should not insert another #caline div + expect(document.querySelectorAll("#caline").length).toBe(0) + }) + + it("autoInit preserves existing container
without regression", () => { + document.body.innerHTML = ` +
+ + ` + + const widget = autoInit() + expect(widget).not.toBeNull() + const container = document.querySelector("#caline") + expect(container?.classList.contains("cl-root")).toBe(true) + expect(container?.getAttribute("data-caline-initialized")).toBe("true") + expect(document.querySelectorAll("#caline").length).toBe(1) + }) + + it("autoInit preserves existing container #comments without regression", () => { + document.body.innerHTML = ` +
+ + ` + + const widget = autoInit() + expect(widget).not.toBeNull() + const container = document.querySelector("#comments") + expect(container?.classList.contains("cl-root")).toBe(true) + expect(container?.getAttribute("data-caline-initialized")).toBe("true") + expect(document.querySelector("#caline")).toBeNull() + }) + + it("autoInit preserves existing container #waline without regression", () => { + document.body.innerHTML = ` +
+ + ` + + const widget = autoInit() + expect(widget).not.toBeNull() + const container = document.querySelector("#waline") + expect(container?.classList.contains("cl-root")).toBe(true) + expect(container?.getAttribute("data-caline-initialized")).toBe("true") + expect(document.querySelector("#caline")).toBeNull() + }) + it("autoInit reads global window.CALINE_CONFIG", () => { ;(window as unknown as { CALINE_CONFIG: unknown }).CALINE_CONFIG = { serverURL: "https://caline.example.com", diff --git a/web/public/client/v1.js b/web/public/client/v1.js index 29bd8bc..19611a3 100644 --- a/web/public/client/v1.js +++ b/web/public/client/v1.js @@ -78,7 +78,7 @@
- `}).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=` + `}).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]:not(script)")||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:(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||{}); + `,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]:not(script), #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||{});