Something went wrong. Try again.
your personal website on atproto - mirror blento.app
Something went wrong. Try again.
TypeScript
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437import { getDetailedProfile, listRecords, resolveHandle, parseUri, getRecord } from '$lib/atproto';import { CardDefinitionsByType } from '$lib/cards';import type { CacheService } from '$lib/cache';import { createEmptyCard } from '$lib/helper';import type { Item, PronounsRecord, WebsiteData } from '$lib/types';import { error } from '@sveltejs/kit';import type { ActorIdentifier, Did } from '@atcute/lexicons';
import { isDid, isHandle } from '@atcute/lexicons/syntax';import { fixAllCollisions, compactItems, hasOverlaps } from '$lib/layout';
const CURRENT_CACHE_VERSION = 1;
function formatPronouns( record: PronounsRecord | undefined, profile: WebsiteData['profile'] | undefined): string | undefined { // nearhorizon.actor.pronouns - https://github.com/skydeval/atproto-pronouns if (record?.value?.sets?.length) { const sets = record.value.sets; const displayMode = record.value.displayMode ?? 'all'; const setsToShow = displayMode === 'firstOnly' ? sets.slice(0, 1) : sets; return setsToShow.map((s) => s.forms.join('/')).join(' · '); } // fallback to bsky pronouns const pronouns = (profile as Record<string, unknown>)?.pronouns; if (pronouns && typeof pronouns === 'string') return pronouns; return undefined;}
export async function getCache(identifier: ActorIdentifier, page: string, cache?: CacheService) { try { const cachedResult = await cache?.getBlento(identifier);
if (!cachedResult) return; const result = JSON.parse(cachedResult);
if (!result.version || result.version !== CURRENT_CACHE_VERSION) { console.log('skipping cache because of version mismatch'); return; }
result.page = 'blento.' + page;
result.publication = (result.publications as Awaited<ReturnType<typeof listRecords>>).find( (v) => parseUri(v.uri)?.rkey === result.page )?.value; result.publication ??= { name: result.profile?.displayName || result.profile?.handle, description: result.profile?.description };
delete result['publications'];
return checkData(result); } catch (error) { console.log('getting cached result failed', error); }}
export async function loadData( handle: ActorIdentifier, cache: CacheService | undefined, forceUpdate: boolean = false, page: string = 'self', env?: Record<string, string | undefined>): Promise<WebsiteData> { if (!handle) throw error(404); if (handle === 'favicon.ico') throw error(404);
if (!forceUpdate) { const cachedResult = await getCache(handle, page, cache);
if (cachedResult) return cachedResult; }
let did: Did | undefined = undefined; if (isHandle(handle)) { did = await resolveHandle({ handle }); } else if (isDid(handle)) { did = handle; } else { throw error(404); }
const [cards, mainPublication, pages, profile, pronounsRecord] = await Promise.all([ listRecords({ did, collection: 'app.blento.card', limit: 0 }).catch((e) => { console.error('error getting records for collection app.blento.card', e); return [] as Awaited<ReturnType<typeof listRecords>>; }), getRecord({ did, collection: 'site.standard.publication', rkey: 'blento.self' }).catch(() => { console.error('error getting record for collection site.standard.publication'); return undefined; }), listRecords({ did, collection: 'app.blento.page' }).catch(() => { console.error('error getting records for collection app.blento.page'); return [] as Awaited<ReturnType<typeof listRecords>>; }), getDetailedProfile({ did }), getRecord({ did, collection: 'app.nearhorizon.actor.pronouns', rkey: 'self' }).catch(() => undefined) ]);
const additionalData = await loadAdditionalData( cards.map((v) => ({ ...v.value })) as Item[], { did, handle, cache }, env );
const result = { page: 'blento.' + page, handle, did, cards: (cards.map((v) => { return { ...v.value }; }) ?? []) as Item[], publications: [mainPublication, ...pages].filter((v) => v), additionalData, profile, pronouns: formatPronouns(pronounsRecord, profile), pronounsRecord: pronounsRecord as PronounsRecord | undefined, updatedAt: Date.now(), version: CURRENT_CACHE_VERSION };
// Only cache results that have cards to avoid caching PDS errors if (result.cards.length > 0) { const stringifiedResult = JSON.stringify(result); await cache?.putBlento(did, handle as string, stringifiedResult); }
const parsedResult = structuredClone(result) as any;
parsedResult.publication = ( parsedResult.publications as Awaited<ReturnType<typeof listRecords>> ).find((v) => parseUri(v.uri)?.rkey === parsedResult.page)?.value; parsedResult.publication ??= { name: profile?.displayName || profile?.handle, description: profile?.description };
delete parsedResult['publications'];
return checkData(parsedResult);}
export async function loadCardData( handle: ActorIdentifier, rkey: string, cache: CacheService | undefined, env?: Record<string, string | undefined>): Promise<WebsiteData> { if (!handle) throw error(404); if (handle === 'favicon.ico') throw error(404);
let did: Did | undefined = undefined; if (isHandle(handle)) { did = await resolveHandle({ handle }); } else if (isDid(handle)) { did = handle; } else { throw error(404); }
const [cardRecord, profile, pronounsRecord] = await Promise.all([ getRecord({ did, collection: 'app.blento.card', rkey }).catch(() => undefined), getDetailedProfile({ did }), getRecord({ did, collection: 'app.nearhorizon.actor.pronouns', rkey: 'self' }).catch(() => undefined) ]);
if (!cardRecord?.value) { throw error(404, 'Card not found'); }
const card = migrateCard(structuredClone(cardRecord.value) as Item); const page = card.page ?? 'blento.self';
const publication = await getRecord({ did, collection: page === 'blento.self' ? 'site.standard.publication' : 'app.blento.page', rkey: page }).catch(() => undefined);
const cards = [card]; const resolvedHandle = profile?.handle || (isHandle(handle) ? handle : did);
const additionalData = await loadAdditionalData( cards, { did, handle: resolvedHandle, cache }, env );
const result = { page, handle: resolvedHandle, did, cards, publication: publication?.value ?? ({ name: profile?.displayName || profile?.handle, description: profile?.description } as WebsiteData['publication']), additionalData, profile, pronouns: formatPronouns(pronounsRecord, profile), pronounsRecord: pronounsRecord as PronounsRecord | undefined, updatedAt: Date.now(), version: CURRENT_CACHE_VERSION };
return result;}
export async function loadCardTypeData( handle: ActorIdentifier, type: string, cardData: Record<string, unknown>, cache: CacheService | undefined, env?: Record<string, string | undefined>): Promise<WebsiteData> { if (!handle) throw error(404); if (handle === 'favicon.ico') throw error(404);
const cardDef = CardDefinitionsByType[type]; if (!cardDef) { throw error(404, 'Card type not found'); }
let did: Did | undefined = undefined; if (isHandle(handle)) { did = await resolveHandle({ handle }); } else if (isDid(handle)) { did = handle; } else { throw error(404); }
const [publication, profile, pronounsRecord] = await Promise.all([ getRecord({ did, collection: 'site.standard.publication', rkey: 'blento.self' }).catch(() => undefined), getDetailedProfile({ did }), getRecord({ did, collection: 'app.nearhorizon.actor.pronouns', rkey: 'self' }).catch(() => undefined) ]);
const card = createEmptyCard('blento.self'); card.cardType = type;
cardDef.createNew?.(card); card.cardData = { ...card.cardData, ...cardData };
const cards = [card]; const resolvedHandle = profile?.handle || (isHandle(handle) ? handle : did);
const additionalData = await loadAdditionalData( cards, { did, handle: resolvedHandle, cache }, env );
const result = { page: 'blento.self', handle: resolvedHandle, did, cards, publication: publication?.value ?? ({ name: profile?.displayName || profile?.handle, description: profile?.description } as WebsiteData['publication']), additionalData, profile, pronouns: formatPronouns(pronounsRecord, profile), pronounsRecord: pronounsRecord as PronounsRecord | undefined, updatedAt: Date.now(), version: CURRENT_CACHE_VERSION };
return checkData(result);}
function migrateCard(card: Item): Item { if (!card.version) { card.x *= 2; card.y *= 2; card.h *= 2; card.w *= 2; card.mobileX *= 2; card.mobileY *= 2; card.mobileH *= 2; card.mobileW *= 2; card.version = 1; }
if (!card.version || card.version < 2) { card.page = 'blento.self'; card.version = 2; }
const cardDef = CardDefinitionsByType[card.cardType]; cardDef?.migrate?.(card);
return card;}
async function loadAdditionalData( cards: Item[], { did, handle, cache }: { did: Did; handle: string; cache?: CacheService }, env?: Record<string, string | undefined>) { const cardTypes = new Set(cards.map((v) => v.cardType ?? '') as string[]); const cardTypesArray = Array.from(cardTypes); const additionDataPromises: Record<string, Promise<unknown>> = {};
for (const cardType of cardTypesArray) { const cardDef = CardDefinitionsByType[cardType]; const items = cards.filter((v) => cardType === v.cardType);
try { if (cardDef?.loadDataServer) { additionDataPromises[cardType] = cardDef.loadDataServer(items, { did, handle, cache, env }); } else if (cardDef?.loadData) { additionDataPromises[cardType] = cardDef.loadData(items, { did, handle, cache }); } } catch { console.error('error getting additional data for', cardType); } }
await Promise.all(Object.values(additionDataPromises));
const additionalData: Record<string, unknown> = {}; for (const [key, value] of Object.entries(additionDataPromises)) { try { additionalData[key] = await value; } catch (error) { console.log('error loading', key, error); } }
return additionalData;}
function checkData(data: WebsiteData): WebsiteData { data = migrateData(data);
const cards = data.cards.filter((v) => v.page === data.page);
if (cards.length > 0) { // Detect overlaps before fixing — flag is used by the edit UI const desktopOverlaps = hasOverlaps(cards, false); const mobileOverlaps = hasOverlaps(cards, true); data.hasLayoutIssue = desktopOverlaps || mobileOverlaps;
if (data.hasLayoutIssue) { console.log('[checkData] Layout issues detected:'); if (desktopOverlaps) console.log(' - Desktop has overlapping cards'); if (mobileOverlaps) console.log(' - Mobile has overlapping cards');
// Log before positions const before = cards.map((c) => ({ id: c.id, type: c.cardType, desktop: `(${c.x},${c.y},${c.w}x${c.h})`, mobile: `(${c.mobileX},${c.mobileY},${c.mobileW}x${c.mobileH})` }));
fixAllCollisions(cards, false); fixAllCollisions(cards, true); compactItems(cards, false); compactItems(cards, true);
// Log changes for (let i = 0; i < cards.length; i++) { const c = cards[i]; const b = before[i]; const newDesktop = `(${c.x},${c.y},${c.w}x${c.h})`; const newMobile = `(${c.mobileX},${c.mobileY},${c.mobileW}x${c.mobileH})`; if (newDesktop !== b.desktop || newMobile !== b.mobile) { console.log( ` ${b.type} ${b.id}: ` + (newDesktop !== b.desktop ? `desktop ${b.desktop} → ${newDesktop} ` : '') + (newMobile !== b.mobile ? `mobile ${b.mobile} → ${newMobile}` : '') ); } } } else { fixAllCollisions(cards, false); fixAllCollisions(cards, true); compactItems(cards, false); compactItems(cards, true); } }
data.cards = cards;
return data;}
function migrateData(data: WebsiteData): WebsiteData { for (const card of data.cards) { migrateCard(card); } return data;}