bsky-comments 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Florian Schepp
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,241 @@
1
+ # bsky-comments
2
+
3
+ A **zero-dependency Web Component** to embed Bluesky discussion threads on any website.
4
+
5
+ - **Lightweight:** < 2kb (gzipped). No heavy SDKs.
6
+ - **Universal:** Works with any framework — React, Vue, Svelte, Astro, or just plain HTML.
7
+ - **Styleable:** Renders Light DOM (not Shadow DOM) for easy styling via CSS/Tailwind.
8
+
9
+ ## Why bsky-comments?
10
+
11
+ Most Bluesky embed libraries fall into two categories: **React Wrappers** (which bundle the heavy official SDK) or **Shadow DOM Widgets** (which are hard to style).
12
+
13
+ **bsky-comments is different:**
14
+
15
+ | Feature | bsky-comments | Typical React Library | Standard Web Component |
16
+ | :------ | :------------ | :-------------------- | :--------------------- |
17
+ | **Input** | **Public URL** OR **AT-URI** | **AT-URI** Only | **AT-URI** Only |
18
+ | **Styling** | **Light DOM** (Use Tailwind/CSS) | CSS Modules / Props | **Shadow DOM** (Locked) |
19
+ | **Engine** | **Native Fetch** (<2kb) | **@atproto/api** (~60kb) | **Lit / Stencil** (~15kb) |
20
+ | **Frameworks** | **All** (Universal) | React Only | All |
21
+
22
+ ### Key Differentiators
23
+
24
+ 1. **Dual Input Modes:**
25
+ - **Easy Mode:** Just paste the public `https://bsky.app/...` link. We handle the handle resolution automatically.
26
+ - **Direct Mode:** Pass the `at://did:plc...` URI to skip resolution for maximum performance (great for static builds).
27
+
28
+ 2. **Headless / Light DOM:**
29
+ We do not use Shadow DOM. This means your global CSS, **Tailwind classes**, and font settings apply immediately to the comments. No fighting against style encapsulation.
30
+
31
+ 3. **Zero Dependencies:**
32
+ We don't bundle the official AT Protocol SDK. We use lightweight, native HTTP requests to fetch only the data needed to render the thread.
33
+
34
+ ## Installation
35
+
36
+ ### npm / pnpm / yarn
37
+
38
+ ```bash
39
+ npm install bsky-comments
40
+ ```
41
+
42
+ ### CDN (No Build Step)
43
+
44
+ Drop this into any HTML page — no bundler required:
45
+
46
+ ```html
47
+ <script type="module" src="https://unpkg.com/bsky-comments"></script>
48
+
49
+ <bsky-comments post="https://bsky.app/profile/me.bsky.social/post/3lwt25ajsic2k"></bsky-comments>
50
+ ```
51
+
52
+ ## Usage
53
+
54
+ ### Option 1: The Easy Way (Web Link)
55
+
56
+ Just copy the URL from your browser address bar. The component handles the resolution automatically.
57
+
58
+ ```html
59
+ <bsky-comments
60
+ post="https://bsky.app/profile/me.bsky.social/post/3lwt25ajsic2k"
61
+ ></bsky-comments>
62
+ ```
63
+
64
+ ### Option 2: The Direct Way (AT-URI)
65
+
66
+ If you are generating your site programmatically (e.g. Astro/Next.js) and already know the DID, use the URI to skip the resolution step for maximum performance.
67
+
68
+ ```html
69
+ <bsky-comments
70
+ uri="at://did:plc:vb7cn66.../app.bsky.feed.post/3lwt25ajsic2k"
71
+ ></bsky-comments>
72
+ ```
73
+
74
+ ## Customizing Icons
75
+
76
+ You can customize the Like and Reply icons in two ways:
77
+
78
+ ### 1. Via Attributes (SVG or Emoji)
79
+
80
+ You can pass raw strings (or even SVG code) directly into the attributes.
81
+
82
+ ```html
83
+ <bsky-comments
84
+ post="..."
85
+ icon-like="💙"
86
+ icon-reply="↩️"
87
+ ></bsky-comments>
88
+
89
+ <!-- Using SVGs -->
90
+ <bsky-comments
91
+ post="..."
92
+ icon-like='<svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="..."/></svg>'
93
+ ></bsky-comments>
94
+ ```
95
+
96
+ ### 2. Via CSS (Recommended)
97
+
98
+ Since we wrap icons in specific classes, you can hide the default icon and use CSS/Tailwind to add your own via background-image or pseudo-elements.
99
+
100
+ ```css
101
+ /* Hide default text/emoji */
102
+ .bsky-icon-like {
103
+ display: inline-block;
104
+ width: 16px;
105
+ height: 16px;
106
+ color: transparent; /* Hide the emoji */
107
+ background-image: url('/heart-icon.svg');
108
+ background-size: contain;
109
+ background-repeat: no-repeat;
110
+ }
111
+ ```
112
+
113
+ ## API Reference
114
+
115
+ | Attribute | Type | Default | Description |
116
+ | :-------- | :--- | :------ | :---------- |
117
+ | `post` | string | `null` | The public web URL (e.g., `https://bsky.app/...`). The component will automatically resolve the handle to a DID. |
118
+ | `uri` | string | `null` | The internal AT-URI (e.g., `at://did:plc:...`). If provided, this takes precedence over `post`. |
119
+ | `sort` | string | `asc` | Sort order for comments: `asc` (oldest first) or `desc` (newest first). |
120
+ | `service` | string | `public.api.bsky.app` | The PDS endpoint. Use this for self-hosted instances. |
121
+ | `icon-like` | string | `❤️` | Custom HTML/Text for the Like icon. |
122
+ | `icon-reply` | string | `💬` | Custom HTML/Text for the Reply icon. |
123
+
124
+ ## Styling Reference
125
+
126
+ This component renders **Semantic HTML** in the Light DOM. You can style it using standard CSS or Tailwind.
127
+
128
+ ### HTML Structure
129
+
130
+ ```html
131
+ <div class="bsky-container">
132
+ <div class="bsky-header">
133
+ <span>Discussion found on <a>Bluesky</a></span>
134
+ <a class="bsky-reply-link">Reply to join discussion</a>
135
+ </div>
136
+ <div class="bsky-comment">
137
+ <div class="bsky-comment-header">
138
+ <img class="bsky-avatar" src="..." />
139
+ <div class="bsky-meta">
140
+ <a class="bsky-author">Display Name</a>
141
+ <span class="bsky-handle">@handle.bsky.social</span>
142
+ <a class="bsky-date">· Jan 5, 2026</a>
143
+ </div>
144
+ </div>
145
+ <div class="bsky-body">
146
+ <p>Comment text...</p>
147
+ </div>
148
+ <div class="bsky-actions">
149
+ <span class="bsky-like">
150
+ <span class="bsky-icon bsky-icon-like">❤️</span>
151
+ <span class="bsky-count">12</span>
152
+ </span>
153
+ <span class="bsky-reply">
154
+ <span class="bsky-icon bsky-icon-reply">💬</span>
155
+ <span class="bsky-count">2</span>
156
+ </span>
157
+ </div>
158
+
159
+ <!-- Nested Replies -->
160
+ <div class="bsky-replies">
161
+ <div class="bsky-comment">...</div>
162
+ </div>
163
+ </div>
164
+ </div>
165
+ ```
166
+
167
+ ### Tailwind Example
168
+
169
+ ```html
170
+ <div class="
171
+ [&_.bsky-comment]:border-l-2 [&_.bsky-comment]:border-gray-200 [&_.bsky-comment]:pl-4 [&_.bsky-comment]:mb-4
172
+ [&_.bsky-actions]:text-sm [&_.bsky-actions]:text-gray-500 [&_.bsky-actions]:flex [&_.bsky-actions]:gap-4
173
+ ">
174
+ <bsky-comments post="..." />
175
+ </div>
176
+ ```
177
+
178
+ ## Framework Integration
179
+
180
+ ### React / Next.js
181
+
182
+ ```tsx
183
+ import 'bsky-comments';
184
+
185
+ export function BlogPost() {
186
+ return (
187
+ <div className="comments-section">
188
+ <bsky-comments post="https://bsky.app/profile/..." />
189
+ </div>
190
+ );
191
+ }
192
+ ```
193
+
194
+ ### Vue / Nuxt
195
+
196
+ ```vue
197
+ <script setup>
198
+ import 'bsky-comments';
199
+ </script>
200
+
201
+ <template>
202
+ <bsky-comments :post="currentUrl" />
203
+ </template>
204
+ ```
205
+
206
+ ### Svelte / SvelteKit
207
+
208
+ ```svelte
209
+ <script>
210
+ import 'bsky-comments';
211
+ </script>
212
+
213
+ <bsky-comments post="https://bsky.app/profile/..." />
214
+ ```
215
+
216
+ ### Astro
217
+
218
+ ```astro
219
+ ---
220
+ import 'bsky-comments';
221
+ ---
222
+
223
+ <bsky-comments post="https://bsky.app/profile/..." />
224
+ ```
225
+
226
+ Or use the CDN approach without an import:
227
+
228
+ ```astro
229
+ ---
230
+ ---
231
+
232
+ <bsky-comments post="https://bsky.app/profile/..." />
233
+
234
+ <script>
235
+ import 'bsky-comments';
236
+ </script>
237
+ ```
238
+
239
+ ## License
240
+
241
+ MIT
@@ -0,0 +1,53 @@
1
+ /**
2
+ * <bsky-comments> Web Component
3
+ */
4
+ export declare class BskyComments extends HTMLElement {
5
+ private _post;
6
+ private _uri;
7
+ private _service;
8
+ private _iconLike;
9
+ private _iconReply;
10
+ private _sortOrder;
11
+ private _depth;
12
+ private _data;
13
+ private _loading;
14
+ private _error;
15
+ private _connected;
16
+ private _abortController;
17
+ static get observedAttributes(): string[];
18
+ attributeChangedCallback(name: string, oldValue: string, newValue: string): void;
19
+ connectedCallback(): void;
20
+ disconnectedCallback(): void;
21
+ private init;
22
+ private resolveUrlToUri;
23
+ private fetchThread;
24
+ private escapeHtml;
25
+ private renderRichText;
26
+ private formatDate;
27
+ private sortReplies;
28
+ private renderComment;
29
+ private render;
30
+ }
31
+ export interface BskyCommentsAttributes {
32
+ post?: string;
33
+ uri?: string;
34
+ sort?: 'asc' | 'desc';
35
+ service?: string;
36
+ 'icon-like'?: string;
37
+ 'icon-reply'?: string;
38
+ depth?: number | string;
39
+ children?: unknown;
40
+ class?: string;
41
+ id?: string;
42
+ style?: string;
43
+ }
44
+ declare global {
45
+ interface HTMLElementTagNameMap {
46
+ 'bsky-comments': BskyComments;
47
+ }
48
+ namespace JSX {
49
+ interface IntrinsicElements {
50
+ 'bsky-comments': BskyCommentsAttributes;
51
+ }
52
+ }
53
+ }
@@ -0,0 +1,187 @@
1
+ var u = Object.defineProperty;
2
+ var _ = (d, l, e) => l in d ? u(d, l, { enumerable: !0, configurable: !0, writable: !0, value: e }) : d[l] = e;
3
+ var o = (d, l, e) => _(d, typeof l != "symbol" ? l + "" : l, e);
4
+ const m = "https://public.api.bsky.app/xrpc";
5
+ class v extends HTMLElement {
6
+ constructor() {
7
+ super(...arguments);
8
+ o(this, "_post", null);
9
+ o(this, "_uri", null);
10
+ o(this, "_service", m);
11
+ o(this, "_iconLike", "❤️");
12
+ o(this, "_iconReply", "💬");
13
+ o(this, "_sortOrder", "asc");
14
+ o(this, "_depth", 10);
15
+ o(this, "_data", null);
16
+ o(this, "_loading", !1);
17
+ o(this, "_error", null);
18
+ o(this, "_connected", !1);
19
+ o(this, "_abortController", null);
20
+ }
21
+ static get observedAttributes() {
22
+ return ["post", "uri", "service", "icon-like", "icon-reply", "sort", "depth"];
23
+ }
24
+ attributeChangedCallback(e, s, t) {
25
+ if (s !== t) {
26
+ switch (e) {
27
+ case "post":
28
+ this._post = t;
29
+ break;
30
+ case "uri":
31
+ this._uri = t;
32
+ break;
33
+ case "service":
34
+ this._service = t || m;
35
+ break;
36
+ case "icon-like":
37
+ this._iconLike = t || "❤️";
38
+ break;
39
+ case "icon-reply":
40
+ this._iconReply = t || "💬";
41
+ break;
42
+ case "sort":
43
+ this._sortOrder = t === "desc" ? "desc" : "asc";
44
+ break;
45
+ case "depth":
46
+ this._depth = Math.max(1, parseInt(t, 10) || 10);
47
+ break;
48
+ }
49
+ this._connected && (["post", "uri", "service"].includes(e) ? (this._post || this._uri) && this.init() : this.render());
50
+ }
51
+ }
52
+ connectedCallback() {
53
+ this._connected = !0, (this._post || this._uri) && this.init();
54
+ }
55
+ disconnectedCallback() {
56
+ var e;
57
+ this._connected = !1, (e = this._abortController) == null || e.abort(), this._abortController = null;
58
+ }
59
+ async init() {
60
+ var s;
61
+ (s = this._abortController) == null || s.abort(), this._abortController = new AbortController();
62
+ const { signal: e } = this._abortController;
63
+ this._loading = !0, this._error = null, this.render();
64
+ try {
65
+ let t = this._uri;
66
+ if (!t && this._post && (t = await this.resolveUrlToUri(this._post, e)), e.aborted) return;
67
+ t ? await this.fetchThread(t, e) : this._data = null;
68
+ } catch (t) {
69
+ if (e.aborted) return;
70
+ this._error = t.message;
71
+ } finally {
72
+ e.aborted || (this._loading = !1, this.render());
73
+ }
74
+ }
75
+ async resolveUrlToUri(e, s) {
76
+ const t = e.match(/profile\/([^\/]+)\/post\/([^\/]+)/);
77
+ if (!t) throw new Error("Invalid Bluesky URL");
78
+ const [, r, i] = t;
79
+ if (r.startsWith("did:")) return `at://${r}/app.bsky.feed.post/${i}`;
80
+ const n = await fetch(`${this._service}/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(r)}`, { signal: s });
81
+ if (!n.ok) throw new Error("Could not resolve handle");
82
+ const p = await n.json();
83
+ if (!p.did) throw new Error("No DID found");
84
+ return `at://${p.did}/app.bsky.feed.post/${i}`;
85
+ }
86
+ async fetchThread(e, s) {
87
+ var i;
88
+ const t = await fetch(`${this._service}/app.bsky.feed.getPostThread?uri=${encodeURIComponent(e)}&depth=${this._depth}`, { signal: s });
89
+ if (!t.ok) throw new Error("Failed to fetch thread");
90
+ const r = await t.json();
91
+ ((i = r.thread) == null ? void 0 : i.$type) === "app.bsky.feed.defs#threadViewPost" ? this._data = r.thread : this._data = null;
92
+ }
93
+ escapeHtml(e) {
94
+ return e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
95
+ }
96
+ renderRichText(e) {
97
+ const { text: s, facets: t } = e;
98
+ if (!t || t.length === 0) return this.escapeHtml(s);
99
+ const r = new TextEncoder(), i = new TextDecoder(), n = r.encode(s), p = [...t].sort((y, h) => y.index.byteStart - h.index.byteStart);
100
+ let c = "", f = 0;
101
+ for (const y of p) {
102
+ const { byteStart: h, byteEnd: k } = y.index;
103
+ if (h < f || k > n.length) continue;
104
+ c += this.escapeHtml(i.decode(n.slice(f, h)));
105
+ const b = this.escapeHtml(i.decode(n.slice(h, k))), a = y.features[0];
106
+ a ? a.$type === "app.bsky.richtext.facet#link" && a.uri ? c += `<a href="${this.escapeHtml(a.uri)}" target="_blank" rel="noopener noreferrer">${b}</a>` : a.$type === "app.bsky.richtext.facet#mention" && a.did ? c += `<a href="https://bsky.app/profile/${encodeURIComponent(a.did)}" target="_blank" rel="noopener noreferrer">${b}</a>` : a.$type === "app.bsky.richtext.facet#tag" && a.tag ? c += `<a href="https://bsky.app/hashtag/${encodeURIComponent(a.tag)}" target="_blank" rel="noopener noreferrer">${b}</a>` : c += b : c += b, f = k;
107
+ }
108
+ return c += this.escapeHtml(i.decode(n.slice(f))), c;
109
+ }
110
+ formatDate(e) {
111
+ return "· " + new Date(e).toLocaleDateString(void 0, { month: "short", day: "numeric", year: "numeric" });
112
+ }
113
+ sortReplies(e) {
114
+ return [...e].sort((s, t) => {
115
+ const r = new Date(s.post.indexedAt).getTime(), i = new Date(t.post.indexedAt).getTime();
116
+ return this._sortOrder === "asc" ? r - i : i - r;
117
+ });
118
+ }
119
+ renderComment(e) {
120
+ if (!e.post) return "";
121
+ const { post: s, replies: t } = e, r = s.uri.split("/").pop() || "", i = `https://bsky.app/profile/${encodeURIComponent(s.author.handle)}/post/${encodeURIComponent(r)}`, n = t && t.length > 0 ? `<div class="bsky-replies">
122
+ ${this.sortReplies(t).map((p) => this.renderComment(p)).join("")}
123
+ </div>` : "";
124
+ return `
125
+ <div class="bsky-comment">
126
+ <div class="bsky-comment-header">
127
+ ${s.author.avatar ? `<img src="${this.escapeHtml(s.author.avatar)}" alt="${this.escapeHtml(s.author.handle)}" class="bsky-avatar" loading="lazy" />` : '<div class="bsky-avatar-placeholder"></div>'}
128
+ <div class="bsky-meta">
129
+ <a href="https://bsky.app/profile/${encodeURIComponent(s.author.handle)}" target="_blank" rel="noopener noreferrer" class="bsky-author">
130
+ ${this.escapeHtml(s.author.displayName || s.author.handle)}
131
+ </a>
132
+ <span class="bsky-handle">@${this.escapeHtml(s.author.handle)}</span>
133
+ <a href="${i}" target="_blank" rel="noopener noreferrer" class="bsky-date">
134
+ ${this.formatDate(s.indexedAt)}
135
+ </a>
136
+ </div>
137
+ </div>
138
+ <div class="bsky-body"><p>${this.renderRichText(s.record)}</p></div>
139
+ <div class="bsky-actions">
140
+ <span class="bsky-like"><span class="bsky-icon bsky-icon-like">${this._iconLike}</span>${s.likeCount ?? 0}</span>
141
+ <span class="bsky-reply"><span class="bsky-icon bsky-icon-reply">${this._iconReply}</span>${s.replyCount ?? 0}</span>
142
+ </div>
143
+ ${n}
144
+ </div>
145
+ `;
146
+ }
147
+ render() {
148
+ if (this._loading) {
149
+ this.innerHTML = '<div class="bsky-loading">Loading comments...</div>';
150
+ return;
151
+ }
152
+ if (this._error) {
153
+ this.innerHTML = `<div class="bsky-error">Error: ${this.escapeHtml(this._error)}</div>`;
154
+ return;
155
+ }
156
+ if (!this._uri && !this._post) {
157
+ this.innerHTML = "";
158
+ return;
159
+ }
160
+ if (!this._data) {
161
+ this.innerHTML = `
162
+ <div class="bsky-empty">
163
+ <p class="bsky-empty-text">No discussion found for this post.</p>
164
+ </div>
165
+ `;
166
+ return;
167
+ }
168
+ const e = `https://bsky.app/profile/${encodeURIComponent(this._data.post.author.handle)}/post/${encodeURIComponent(this._data.post.uri.split("/").pop() || "")}`, t = (this._data.replies ? this.sortReplies(this._data.replies) : []).map((r) => this.renderComment(r)).join("") || "";
169
+ this.innerHTML = `
170
+ <div class="bsky-container">
171
+ <div class="bsky-header">
172
+ <span class="bsky-header-text">
173
+ Discussion found on <a href="${e}" target="_blank" rel="noopener noreferrer">Bluesky</a>
174
+ </span>
175
+ <a href="${e}" target="_blank" rel="noopener noreferrer" class="bsky-reply-btn">
176
+ Reply to join discussion
177
+ </a>
178
+ </div>
179
+ ${t || '<div class="bsky-no-replies">No replies yet. Be the first to comment!</div>'}
180
+ </div>
181
+ `;
182
+ }
183
+ }
184
+ customElements.get("bsky-comments") || customElements.define("bsky-comments", v);
185
+ export {
186
+ v as BskyComments
187
+ };
@@ -0,0 +1,40 @@
1
+ (function(n,i){typeof exports=="object"&&typeof module<"u"?i(exports):typeof define=="function"&&define.amd?define(["exports"],i):(n=typeof globalThis<"u"?globalThis:n||self,i(n.BskyComments=n.BskyComments||{}))})(this,function(n){"use strict";var k=Object.defineProperty;var _=(n,i,p)=>i in n?k(n,i,{enumerable:!0,configurable:!0,writable:!0,value:p}):n[i]=p;var a=(n,i,p)=>_(n,typeof i!="symbol"?i+"":i,p);const i="https://public.api.bsky.app/xrpc";class p extends HTMLElement{constructor(){super(...arguments);a(this,"_post",null);a(this,"_uri",null);a(this,"_service",i);a(this,"_iconLike","❤️");a(this,"_iconReply","💬");a(this,"_sortOrder","asc");a(this,"_depth",10);a(this,"_data",null);a(this,"_loading",!1);a(this,"_error",null);a(this,"_connected",!1);a(this,"_abortController",null)}static get observedAttributes(){return["post","uri","service","icon-like","icon-reply","sort","depth"]}attributeChangedCallback(t,s,e){if(s!==e){switch(t){case"post":this._post=e;break;case"uri":this._uri=e;break;case"service":this._service=e||i;break;case"icon-like":this._iconLike=e||"❤️";break;case"icon-reply":this._iconReply=e||"💬";break;case"sort":this._sortOrder=e==="desc"?"desc":"asc";break;case"depth":this._depth=Math.max(1,parseInt(e,10)||10);break}this._connected&&(["post","uri","service"].includes(t)?(this._post||this._uri)&&this.init():this.render())}}connectedCallback(){this._connected=!0,(this._post||this._uri)&&this.init()}disconnectedCallback(){var t;this._connected=!1,(t=this._abortController)==null||t.abort(),this._abortController=null}async init(){var s;(s=this._abortController)==null||s.abort(),this._abortController=new AbortController;const{signal:t}=this._abortController;this._loading=!0,this._error=null,this.render();try{let e=this._uri;if(!e&&this._post&&(e=await this.resolveUrlToUri(this._post,t)),t.aborted)return;e?await this.fetchThread(e,t):this._data=null}catch(e){if(t.aborted)return;this._error=e.message}finally{t.aborted||(this._loading=!1,this.render())}}async resolveUrlToUri(t,s){const e=t.match(/profile\/([^\/]+)\/post\/([^\/]+)/);if(!e)throw new Error("Invalid Bluesky URL");const[,r,o]=e;if(r.startsWith("did:"))return`at://${r}/app.bsky.feed.post/${o}`;const c=await fetch(`${this._service}/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(r)}`,{signal:s});if(!c.ok)throw new Error("Could not resolve handle");const h=await c.json();if(!h.did)throw new Error("No DID found");return`at://${h.did}/app.bsky.feed.post/${o}`}async fetchThread(t,s){var o;const e=await fetch(`${this._service}/app.bsky.feed.getPostThread?uri=${encodeURIComponent(t)}&depth=${this._depth}`,{signal:s});if(!e.ok)throw new Error("Failed to fetch thread");const r=await e.json();((o=r.thread)==null?void 0:o.$type)==="app.bsky.feed.defs#threadViewPost"?this._data=r.thread:this._data=null}escapeHtml(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}renderRichText(t){const{text:s,facets:e}=t;if(!e||e.length===0)return this.escapeHtml(s);const r=new TextEncoder,o=new TextDecoder,c=r.encode(s),h=[...e].sort((m,f)=>m.index.byteStart-f.index.byteStart);let d="",b=0;for(const m of h){const{byteStart:f,byteEnd:u}=m.index;if(f<b||u>c.length)continue;d+=this.escapeHtml(o.decode(c.slice(b,f)));const y=this.escapeHtml(o.decode(c.slice(f,u))),l=m.features[0];l?l.$type==="app.bsky.richtext.facet#link"&&l.uri?d+=`<a href="${this.escapeHtml(l.uri)}" target="_blank" rel="noopener noreferrer">${y}</a>`:l.$type==="app.bsky.richtext.facet#mention"&&l.did?d+=`<a href="https://bsky.app/profile/${encodeURIComponent(l.did)}" target="_blank" rel="noopener noreferrer">${y}</a>`:l.$type==="app.bsky.richtext.facet#tag"&&l.tag?d+=`<a href="https://bsky.app/hashtag/${encodeURIComponent(l.tag)}" target="_blank" rel="noopener noreferrer">${y}</a>`:d+=y:d+=y,b=u}return d+=this.escapeHtml(o.decode(c.slice(b))),d}formatDate(t){return"· "+new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}sortReplies(t){return[...t].sort((s,e)=>{const r=new Date(s.post.indexedAt).getTime(),o=new Date(e.post.indexedAt).getTime();return this._sortOrder==="asc"?r-o:o-r})}renderComment(t){if(!t.post)return"";const{post:s,replies:e}=t,r=s.uri.split("/").pop()||"",o=`https://bsky.app/profile/${encodeURIComponent(s.author.handle)}/post/${encodeURIComponent(r)}`,c=e&&e.length>0?`<div class="bsky-replies">
2
+ ${this.sortReplies(e).map(h=>this.renderComment(h)).join("")}
3
+ </div>`:"";return`
4
+ <div class="bsky-comment">
5
+ <div class="bsky-comment-header">
6
+ ${s.author.avatar?`<img src="${this.escapeHtml(s.author.avatar)}" alt="${this.escapeHtml(s.author.handle)}" class="bsky-avatar" loading="lazy" />`:'<div class="bsky-avatar-placeholder"></div>'}
7
+ <div class="bsky-meta">
8
+ <a href="https://bsky.app/profile/${encodeURIComponent(s.author.handle)}" target="_blank" rel="noopener noreferrer" class="bsky-author">
9
+ ${this.escapeHtml(s.author.displayName||s.author.handle)}
10
+ </a>
11
+ <span class="bsky-handle">@${this.escapeHtml(s.author.handle)}</span>
12
+ <a href="${o}" target="_blank" rel="noopener noreferrer" class="bsky-date">
13
+ ${this.formatDate(s.indexedAt)}
14
+ </a>
15
+ </div>
16
+ </div>
17
+ <div class="bsky-body"><p>${this.renderRichText(s.record)}</p></div>
18
+ <div class="bsky-actions">
19
+ <span class="bsky-like"><span class="bsky-icon bsky-icon-like">${this._iconLike}</span>${s.likeCount??0}</span>
20
+ <span class="bsky-reply"><span class="bsky-icon bsky-icon-reply">${this._iconReply}</span>${s.replyCount??0}</span>
21
+ </div>
22
+ ${c}
23
+ </div>
24
+ `}render(){if(this._loading){this.innerHTML='<div class="bsky-loading">Loading comments...</div>';return}if(this._error){this.innerHTML=`<div class="bsky-error">Error: ${this.escapeHtml(this._error)}</div>`;return}if(!this._uri&&!this._post){this.innerHTML="";return}if(!this._data){this.innerHTML=`
25
+ <div class="bsky-empty">
26
+ <p class="bsky-empty-text">No discussion found for this post.</p>
27
+ </div>
28
+ `;return}const t=`https://bsky.app/profile/${encodeURIComponent(this._data.post.author.handle)}/post/${encodeURIComponent(this._data.post.uri.split("/").pop()||"")}`,e=(this._data.replies?this.sortReplies(this._data.replies):[]).map(r=>this.renderComment(r)).join("")||"";this.innerHTML=`
29
+ <div class="bsky-container">
30
+ <div class="bsky-header">
31
+ <span class="bsky-header-text">
32
+ Discussion found on <a href="${t}" target="_blank" rel="noopener noreferrer">Bluesky</a>
33
+ </span>
34
+ <a href="${t}" target="_blank" rel="noopener noreferrer" class="bsky-reply-btn">
35
+ Reply to join discussion
36
+ </a>
37
+ </div>
38
+ ${e||'<div class="bsky-no-replies">No replies yet. Be the first to comment!</div>'}
39
+ </div>
40
+ `}}customElements.get("bsky-comments")||customElements.define("bsky-comments",p),n.BskyComments=p,Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})});
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "bsky-comments",
3
+ "version": "1.0.0",
4
+ "description": "A zero-dependency Web Component to embed Bluesky discussion threads on any website.",
5
+ "type": "module",
6
+ "main": "./dist/bsky-comments.umd.cjs",
7
+ "module": "./dist/bsky-comments.js",
8
+ "types": "./dist/bsky-comments.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/bsky-comments.d.ts",
12
+ "import": "./dist/bsky-comments.js",
13
+ "require": "./dist/bsky-comments.umd.cjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "devDependencies": {
20
+ "jsdom": "^28.1.0",
21
+ "typescript": "^5.2.0",
22
+ "vite": "^5.0.0",
23
+ "vite-plugin-dts": "^3.0.0",
24
+ "vitest": "^4.0.18"
25
+ },
26
+ "keywords": [
27
+ "web-component",
28
+ "bluesky",
29
+ "comments",
30
+ "at-protocol",
31
+ "social",
32
+ "embed",
33
+ "bsky"
34
+ ],
35
+ "license": "MIT",
36
+ "author": "Florian Schepp",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/florianschepp/bsky-comments.git"
40
+ },
41
+ "homepage": "https://github.com/florianschepp/bsky-comments#readme",
42
+ "bugs": {
43
+ "url": "https://github.com/florianschepp/bsky-comments/issues"
44
+ },
45
+ "scripts": {
46
+ "dev": "vite",
47
+ "build": "tsc && vite build",
48
+ "test": "vitest run"
49
+ }
50
+ }