Repository navigation
Expand file tree
/
Copy pathBlueskyLikes.astro
More file actions
467 lines (387 loc) · 16.5 KB
/
Copy pathBlueskyLikes.astro
File metadata and controls
467 lines (387 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
---
interface Props {
blueskyPostURI?: string;
}
const { blueskyPostURI } = Astro.props;
---
{blueskyPostURI && (
<div class="mt-8 pt-6 border-t border-line-strong">
<h3 class="text-xl font-medium mb-4">Bluesky Interactions</h3>
<!-- Likes Section -->
<div id="bluesky-likes" data-post-uri={blueskyPostURI} aria-live="polite" aria-busy="true" class="flex flex-col items-start gap-3 mb-6">
<div class="flex items-center text-text-muted">
<div class="loading-spinner mr-2" aria-hidden="true"></div>
<span>Loading likes...</span>
</div>
</div>
<!-- Comments Section -->
<div id="bluesky-comments" data-post-uri={blueskyPostURI} aria-live="polite" aria-busy="true" class="flex flex-col items-start gap-3 mt-6">
<h4 class="text-lg font-medium mb-2">Comments</h4>
<div class="comments-container w-full">
<div class="flex items-center text-text-muted">
<div class="loading-spinner mr-2" aria-hidden="true"></div>
<span>Loading comments...</span>
</div>
</div>
</div>
</div>
)}
<script>
// Set maximum number of avatars to display
const LIMIT = 24;
// Use the public Bluesky API endpoint
const BSKY_PUBLIC_API = "https://public.api.bsky.app/xrpc/";
const IDENTIFIER = import.meta.env?.BLUESKY_IDENTIFIER || "ashley.dev";
// Using my actual Bluesky DID that we resolved
const MY_DID = "did:plc:5tgxxpsiv36w3e37im6kd2se";
class BlueskyInteractionsManager {
private likesContainer: HTMLElement | null = null;
private commentsContainer: HTMLElement | null = null;
private postURI: string | null = null;
constructor() {
// Initialize immediately instead of waiting for DOMContentLoaded
// This fixes timing issues in Astro's hydration
this.init();
}
private async init() {
// Small delay to ensure DOM is fully loaded in Astro's hydration
setTimeout(async () => {
this.likesContainer = document.getElementById('bluesky-likes');
this.commentsContainer = document.getElementById('bluesky-comments');
if (!this.likesContainer || !this.commentsContainer) {
console.warn("Bluesky containers not found in DOM");
return;
}
// Both containers should have the same post URI
this.postURI = this.likesContainer.dataset.postUri || null;
if (!this.postURI) {
console.warn("No Bluesky post URI found");
return;
}
// Ensure the post URI is properly formatted
if (!this.postURI.startsWith("at://")) {
// If we only have a post ID (like from the URL: 3lm34df764s2w)
if (!this.postURI.includes('/')) {
this.postURI = `at://${MY_DID}/app.bsky.feed.post/${this.postURI}`;
}
}
// Fetch interactions
await Promise.all([
this.fetchLikes(),
this.fetchComments()
]);
}, 100);
}
private async fetchLikes() {
if (!this.postURI || !this.likesContainer) return;
try {
const getLikesURL = `${BSKY_PUBLIC_API}app.bsky.feed.getLikes?limit=${LIMIT}&uri=${encodeURIComponent(this.postURI)}`;
const getPostURL = `${BSKY_PUBLIC_API}app.bsky.feed.getPosts?uris=${encodeURIComponent(this.postURI)}`;
// Fetch both post data (for total like count) and likes data
const [postResponse, likesResponse] = await Promise.all([
fetch(getPostURL),
fetch(getLikesURL)
]);
if (!postResponse.ok) {
throw new Error(`Failed to fetch post data: ${postResponse.status}`);
}
if (!likesResponse.ok) {
throw new Error(`Failed to fetch likes data: ${likesResponse.status}`);
}
const postData = await postResponse.json();
const likesData = await likesResponse.json();
// Get total like count from post data
const totalLikesCount = postData.posts?.[0]?.likeCount || 0;
// Render likes if available
if (likesData.likes?.length > 0) {
this.renderLikes(likesData.likes, totalLikesCount);
} else {
this.renderEmptyLikes();
}
} catch (error) {
console.error('Error fetching Bluesky likes:', error);
this.renderLikesError();
}
}
private async fetchComments() {
if (!this.postURI || !this.commentsContainer) return;
try {
// Fetch thread data to get replies
const threadURL = `${BSKY_PUBLIC_API}app.bsky.feed.getPostThread?uri=${encodeURIComponent(this.postURI)}`;
const threadResponse = await fetch(threadURL);
if (!threadResponse.ok) {
throw new Error(`Failed to fetch thread: ${threadResponse.status}`);
}
const threadData = await threadResponse.json();
// Get the replies from the thread
const replies = threadData.thread?.replies || [];
// Extract the comments
const comments = replies.map((reply: any) => {
const post = reply.post;
return {
uri: post.uri,
createdAt: post.indexedAt || post.createdAt,
text: post.record.text,
actor: post.author
};
});
// Render the comments
if (comments.length > 0) {
this.renderComments(comments);
} else {
this.renderEmptyComments();
}
} catch (error) {
console.error('Error fetching Bluesky comments:', error);
this.renderCommentsError();
}
}
private renderLikes(likes: any[], totalCount: number) {
if (!this.likesContainer) return;
this.likesContainer.setAttribute('aria-busy', 'false');
// Create elements for the likes count and avatars
const likesCount = document.createElement('h4');
likesCount.className = 'text-lg font-medium mb-2';
likesCount.textContent = `${totalCount} ${totalCount === 1 ? 'Like' : 'Likes'}`;
const avatarsContainer = document.createElement('ul');
avatarsContainer.className = 'flex flex-wrap gap-2 items-center';
avatarsContainer.style.minHeight = '50px'; // Prevent layout shift
avatarsContainer.style.listStyle = 'none';
avatarsContainer.style.padding = '0';
// Add avatars
likes.forEach(like => {
const avatarItem = document.createElement('li');
avatarItem.className = 'w-10 h-10 rounded-full overflow-hidden';
avatarItem.style.marginRight = '-0.5rem'; // Overlap avatars like in whitep4nth3r's design
avatarItem.style.filter = 'drop-shadow(0px 0.125rem 0.125rem rgba(0, 0, 0, 0.25))';
if (like.actor.avatar) {
const profileLink = document.createElement('a');
profileLink.href = `https://bsky.app/profile/${like.actor.handle}`;
profileLink.target = '_blank';
profileLink.rel = 'noopener noreferrer';
profileLink.className = 'block w-full h-full rounded-full';
profileLink.setAttribute(
'aria-label',
`View ${like.actor.displayName || like.actor.handle} on Bluesky`
);
const img = document.createElement('img');
img.className = 'w-full h-full rounded-full';
img.src = like.actor.avatar.replace("avatar", "avatar_thumbnail");
img.alt = like.actor.displayName || like.actor.handle;
img.title = like.actor.displayName || like.actor.handle;
img.width = 40;
img.height = 40;
img.loading = 'lazy';
img.decoding = 'async';
profileLink.appendChild(img);
avatarItem.appendChild(profileLink);
} else {
const profileLink = document.createElement('a');
profileLink.href = `https://bsky.app/profile/${like.actor.handle}`;
profileLink.target = '_blank';
profileLink.rel = 'noopener noreferrer';
profileLink.className = 'flex w-full h-full justify-center items-center rounded-full bg-primary text-black font-bold';
profileLink.setAttribute(
'aria-label',
`View ${like.actor.displayName || like.actor.handle} on Bluesky`
);
profileLink.textContent = '@';
avatarItem.appendChild(profileLink);
}
avatarsContainer.appendChild(avatarItem);
});
// If there are more likes than what we display, show how many more
if (totalCount > likes.length) {
const moreItem = document.createElement('li');
moreItem.className = 'w-10 h-10 rounded-full flex justify-center items-center bg-primary text-black font-bold';
moreItem.textContent = `+${totalCount - likes.length}`;
moreItem.setAttribute('aria-label', `${totalCount - likes.length} more likes`);
avatarsContainer.appendChild(moreItem);
}
// Add a link to the Bluesky post
const viewOnBluesky = document.createElement('a');
viewOnBluesky.className = 'text-sm text-primary hover:underline mt-2 block';
viewOnBluesky.href = `https://bsky.app/profile/${IDENTIFIER}/post/${this.postURI?.split('/').pop()}`;
viewOnBluesky.target = '_blank';
viewOnBluesky.rel = 'noopener noreferrer';
viewOnBluesky.textContent = 'Like this post on Bluesky to see your face here';
// Clear existing content and append new elements
this.likesContainer.innerHTML = '';
this.likesContainer.appendChild(likesCount);
this.likesContainer.appendChild(avatarsContainer);
this.likesContainer.appendChild(viewOnBluesky);
}
private renderEmptyLikes() {
if (!this.likesContainer) return;
this.likesContainer.setAttribute('aria-busy', 'false');
this.likesContainer.innerHTML = `
<h4 class="text-lg font-medium mb-2">0 Likes</h4>
<p class="text-text-muted">Be the first to like this post on Bluesky!</p>
<a class="text-sm text-primary hover:underline mt-2 block"
href="https://bsky.app/profile/${IDENTIFIER}/post/${this.postURI?.split('/').pop()}"
target="_blank"
rel="noopener noreferrer">
Like this post on Bluesky
</a>
`;
}
private renderComments(comments: any[]) {
if (!this.commentsContainer) return;
this.commentsContainer.setAttribute('aria-busy', 'false');
const commentsWrapper = this.commentsContainer.querySelector('.comments-container');
if (!commentsWrapper) return;
// Clear existing content
commentsWrapper.innerHTML = '';
// Sort comments by creation date
const sortedComments = [...comments].sort((a, b) =>
new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
);
// Create comment elements
sortedComments.forEach(comment => {
const commentEl = document.createElement('div');
commentEl.className = 'comment bg-surface rounded-lg border border-line p-4 mb-3 w-full';
// Comment header with author info
const commentHeader = document.createElement('div');
commentHeader.className = 'flex flex-wrap items-center mb-2';
// Author info wrapper (for better mobile layout)
const authorInfoWrapper = document.createElement('div');
authorInfoWrapper.className = 'flex items-center mr-auto';
// Author avatar
const authorAvatar = document.createElement('img');
authorAvatar.className = 'w-6 h-6 rounded-full border border-line mr-2';
authorAvatar.width = 24;
authorAvatar.height = 24;
authorAvatar.loading = 'lazy';
authorAvatar.decoding = 'async';
authorAvatar.src = comment.actor.avatar?.replace("avatar", "avatar_thumbnail") || 'https://bsky.social/static/default-avatar.webp';
authorAvatar.alt = `${comment.actor.displayName || comment.actor.handle}'s avatar`;
// Author name
const authorName = document.createElement('span');
authorName.className = 'font-medium text-gray-200 mr-1';
authorName.textContent = comment.actor.displayName || '';
// Author handle
const authorHandle = document.createElement('span');
authorHandle.className = 'text-gray-400 text-sm';
authorHandle.textContent = `@${comment.actor.handle}`;
// Timestamp
const timestamp = document.createElement('span');
timestamp.className = 'text-text-muted text-xs mt-1 w-full md:w-auto md:mt-0 md:ml-auto';
// Format timestamp
const date = new Date(comment.createdAt);
const formattedDate = new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric'
}).format(date);
timestamp.textContent = formattedDate;
// Comment text
const commentText = document.createElement('div');
commentText.className = 'text-gray-300 text-sm';
commentText.textContent = comment.text;
// Create "View on Bluesky" link
const viewLink = document.createElement('a');
viewLink.className = 'text-xs text-primary hover:underline mt-2 inline-block';
viewLink.href = `https://bsky.app/profile/${comment.actor.handle}/post/${comment.uri.split('/').pop()}`;
viewLink.target = '_blank';
viewLink.rel = 'noopener noreferrer';
viewLink.textContent = 'View on Bluesky';
// Assemble comment element
authorInfoWrapper.appendChild(authorAvatar);
authorInfoWrapper.appendChild(authorName);
authorInfoWrapper.appendChild(authorHandle);
commentHeader.appendChild(authorInfoWrapper);
commentHeader.appendChild(timestamp);
commentEl.appendChild(commentHeader);
commentEl.appendChild(commentText);
commentEl.appendChild(viewLink);
commentsWrapper.appendChild(commentEl);
});
}
private renderEmptyComments() {
if (!this.commentsContainer) return;
this.commentsContainer.setAttribute('aria-busy', 'false');
const commentsWrapper = this.commentsContainer.querySelector('.comments-container');
if (!commentsWrapper) return;
commentsWrapper.innerHTML = `
<p class="text-text-muted">No comments yet</p>
<a class="text-sm text-primary hover:underline mt-2 block"
href="https://bsky.app/profile/${IDENTIFIER}/post/${this.postURI?.split('/').pop()}"
target="_blank"
rel="noopener noreferrer">
Comment on this post on Bluesky
</a>
`;
}
private renderLikesError() {
if (!this.likesContainer) return;
this.likesContainer.setAttribute('aria-busy', 'false');
this.likesContainer.innerHTML = '<p class="text-text-muted">Unable to load likes</p>';
}
private renderCommentsError() {
if (!this.commentsContainer) return;
this.commentsContainer.setAttribute('aria-busy', 'false');
const commentsWrapper = this.commentsContainer.querySelector('.comments-container');
if (!commentsWrapper) return;
commentsWrapper.innerHTML = '<p class="text-text-muted">Unable to load comments</p>';
}
}
// Initialize the interactions manager
const manager = new BlueskyInteractionsManager();
</script>
<style>
.loading-spinner {
border: 2px solid rgba(255, 255, 255, 0.1);
border-top-color: var(--color-primary, #F43F5E);
border-radius: 50%;
width: 1rem;
height: 1rem;
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
#bluesky-comments {
position: relative;
width: 100%;
}
.comments-container {
width: 100%;
position: relative;
}
/* Fix for horizontal overflow in comments */
.comment {
overflow-wrap: break-word;
word-wrap: break-word;
word-break: break-word;
hyphens: auto;
max-width: 100%;
box-sizing: border-box; /* Ensure padding is included in width calculation */
}
.comment .text-gray-300 {
overflow-wrap: break-word;
word-wrap: break-word;
word-break: break-word;
hyphens: auto;
max-width: 100%;
}
/* Ensure avatar images don't cause layout shifts */
.comment img.w-6 {
min-width: 24px;
min-height: 24px;
}
/* Ensure comments take full width of container */
@media (max-width: 768px) {
#bluesky-comments {
max-width: 100vw;
padding-left: 0;
padding-right: 0;
}
.comments-container {
margin-right: 0;
width: 100%;
}
.comment {
width: 100%;
}
}
</style>