async function resolvePds(did) { let res; if (did.startsWith("did:plc:")) { res = await fetch(`https://plc.directory/${encodeURIComponent(did)}`); } else if (did.startsWith("did:web")) { let domain = did.slice("did:web:".length); res = await fetch(`https://${domain}/.well-known/did.json`) } if (!res.ok) { throw new Error(`Lookup failed for "${did}": ${res.status} ${res.statusText}`); } const doc = await res.json(); const atprotoService = doc.service?.find( (s) => s.id === "#atproto_pds" || s.type === "AtprotoPersonalDataServer" ); if (!atprotoService?.serviceEndpoint) { throw new Error(`No ATProto PDS service endpoint found in DID document for "${did}"`); } return atprotoService.serviceEndpoint; } async function listRecords(pdsUrl, did, collection, limit = 50, cursor = null) { const url = new URL(`${pdsUrl}/xrpc/com.atproto.repo.listRecords`); url.searchParams.set("repo", did); url.searchParams.set("collection", collection); url.searchParams.set("limit", String(limit)); if (cursor) { url.searchParams.set("cursor", cursor); } const res = await fetch(url.toString()); if (!res.ok) { throw new Error(`listRecords failed for "${collection}" in "${did}": ${res.status} ${res.statusText}`); } const body = await res.json(); const result = [body.records, body.cursor]; return result; } async function getRecord(pdsUrl, did, collection, rkey) { const url = new URL(`${pdsUrl}/xrpc/com.atproto.repo.getRecord`); url.searchParams.set("repo", did); url.searchParams.set("collection", collection); url.searchParams.set("rkey", rkey); const res = await fetch(url.toString()); if (!res.ok) { throw new Error(`getRecord failed for (collection, rkey) = (${collection}, ${rkey}) in "${did}": ${res.status} ${res.statusText}`); } const body = await res.json(); return body; } function createCard(text, tags = []) { const grid = document.getElementById("card-grid"); const card = document.createElement("div"); card.className = "card"; const body = document.createElement("p"); body.className = "card-body"; body.textContent = text; card.appendChild(body); if (tags.length > 0) { const tagRow = document.createElement("div"); tagRow.className = "card-tags"; for (const tag of tags) { const span = document.createElement("span"); span.className = "tag"; span.textContent = tag; tagRow.appendChild(span); } card.appendChild(tagRow); } grid.appendChild(card); } function extractPlaintext(record) { if (record.value.textContent) { return record.value.textContent; } else { // the "site.standard.document" lexicon schema requires the // contents of the document to be on the `content` property. // https://pdsls.dev/at://did:plc:re3ebnp5v7ffagz6rb6xfei4/com.atproto.lexicon.schema/site.standard.document#record:defs.main.record.properties.content let content = record.value.content; // Leaflet extends the `content` property in the "site.standard.document" // lexicon schema with the "pub.leaflet.content" schema. // https://pdsls.dev/at://did:plc:btxrwcaeyodrap5mnjw2fvmz/com.atproto.lexicon.schema/pub.leaflet.content if (content.$type != "pub.leaflet.content") { throw new Error("Non-leaflet documents not supported"); } // In the "pub.leaflet.content" schema, `content` has a `pages` property. // `pages` is an array of unions containing references to // "pub.leaflet.pages.linearDocument" and "pub.leaflet.pages.canvas". // We will only work with "pub.leaflet.pages.linearDocument". // // Leaflet appears to use an array of unions for the "page within a page" // feature that is has. Thus, only the 0th page concerns us. let page = content.pages[0]; if (page.$type != "pub.leaflet.pages.linearDocument") { return ""; } // These pages have an array-type `blocks` property. // https://pdsls.dev/at://did:plc:btxrwcaeyodrap5mnjw2fvmz/com.atproto.lexicon.schema/pub.leaflet.pages.linearDocument#record:defs.main.properties.blocks // // This array may contain blocks such as "pub.leaflet.blocks.image", // "pub.leaflet.blocks.math", "pub.leaflet.blocks.text", etc. // We are only interested in "pub.leaflet.blocks.text". // // The `block` type itself stores its actual references in // the identically named property within itself. // https://pdsls.dev/at://did:plc:btxrwcaeyodrap5mnjw2fvmz/com.atproto.lexicon.schema/pub.leaflet.pages.linearDocument#record:defs.block.properties.block let textBlocks = page.blocks .filter((block) => block.block.$type == "pub.leaflet.blocks.text") .map((block) => block.block); // Each "pub.leaflet.blocks.text" block must have a `plaintext` property. // This is exactly what we want. // https://pdsls.dev/at://did:plc:btxrwcaeyodrap5mnjw2fvmz/com.atproto.lexicon.schema/pub.leaflet.blocks.text let joinedPlaintext = textBlocks .map((block) => block.plaintext) .join("\n\n"); return joinedPlaintext; } } function getRkey(atUri) { return atUri.split("/").at(-1); } const DID = window.APP_CONFIG.DID ?? "did:plc:iocjtodmfhclusqhdr3eshom"; const PUBLICATION_RKEY = window.APP_CONFIG.PUBLICATION_RKEY ?? "3mh77ercajk2f"; const fetchLimit = 100; const COLLECTION = "site.standard.document"; const loadMoreBtn = document.getElementById("load-more-btn"); const nothingMoreRow = document.getElementById("nothing-more-to-show-row"); const loadingIndicatorRow = document.getElementById("loading-indicator-row"); const errorRow = document.getElementById("error-row"); const loadingStates = [loadMoreBtn, nothingMoreRow, loadingIndicatorRow, errorRow]; // show only the given state // hide all states if null function showLoadingState(state) { for (const lstate of loadingStates) { lstate.classList.add("hidden"); } if (state) { state.classList.remove("hidden"); } } function presentError(error) { errorRow.innerHTML = `

An error occured: ${error}

`; } class BatchLoader { constructor() { this.loading = false; this.records = []; this.matchedRecordsInBatch = []; this.noMatchingRecordFound = true; this.areRecordsAhead = false; this.cursor; this.pds; this.pubUrl; this.seenUri = new Set(); } // The `site` property in the "site.standard.document" lexicon schema: /* site: type: "string" format: "uri" description: "Points to a publication record (at://) or a publication url (https://) for loose documents. Avoid trailing slashes." */ // https://pdsls.dev/at://did:plc:re3ebnp5v7ffagz6rb6xfei4/com.atproto.lexicon.schema/site.standard.document matchesPub(site) { if (site.startsWith("at://")) { return getRkey(site) == PUBLICATION_RKEY; } else if (site.startsWith("https://")) { if (this.pubUrl) { return site == this.pubUrl; } else { throw new Error("Attempted to match publication URL before having obtained it"); } } } batchHasMatchingRecords() { return this.matchedRecordsInBatch.length != 0; } async fetchNextRecordsBatch() { let recordsAndCursor; try { recordsAndCursor = await listRecords(this.pds, DID, COLLECTION, fetchLimit, this.cursor); } catch (error) { throw new Error(`Failed to list records: ${error}`, { cause: error }); } this.records = recordsAndCursor[0]; this.cursor = recordsAndCursor[1]; console.log(`Fetched ${this.records.length} total records`); console.log(`Cursor: ${JSON.stringify(this.cursor)}`); } collectMatchingRecordsInBatch() { for (const record of this.records) { if (this.matchesPub(record.value.site)) { if (!this.seenUri.has(record.uri)) { this.noMatchingRecordFound = false; this.matchedRecordsInBatch.push(record); this.seenUri.add(record.uri); } } } console.log(`Collected ${this.matchedRecordsInBatch.length} records matching publication.`); } async fetchAndCollectRecordsBatch() { await this.fetchNextRecordsBatch(); this.collectMatchingRecordsInBatch(); } createCards() { for (const record of this.matchedRecordsInBatch) { createCard(extractPlaintext(record), record.value.tags); } console.log(`Created ${this.matchedRecordsInBatch.length} cards.`); } async loadNextCardsBatch() { showLoadingState(loadingIndicatorRow); await this.fetchAndCollectRecordsBatch(); this.createCards(); showLoadingState(null); } async storePubUrl() { try { let record = await getRecord(this.pds, DID, "site.standard.publication", PUBLICATION_RKEY); this.pubUrl = record.value.url; } catch (error) { throw new Error(`Failed to obtain publication URL: ${error}`, { cause: error }); } console.log(`Publication URL: ${this.pubUrl}`); } async storePdsUrl() { try { this.pds = await resolvePds(DID); } catch (error) { throw new Error(`Failed to resolve PDS: ${error}`, { cause: error }); } console.log(`PDS: ${this.pds}`); } async necessarilyLoadAvailableCards(initial_load) { if (initial_load) { console.log("Fetching a new batch of documents"); this.matchedRecordsInBatch = []; await this.loadNextCardsBatch(); } while (!this.batchHasMatchingRecords() && this.cursor) { console.log("Fetching a new batch of documents until at least one in the given pub is found") this.matchedRecordsInBatch = []; await this.loadNextCardsBatch(); } } createCardsForAheadRecords() { this.areRecordsAhead = false; this.createCards(); console.log("Created cards for records fetched ahead of time."); } async fetchAhead() { if (this.batchHasMatchingRecords() && this.cursor) { this.matchedRecordsInBatch = []; showLoadingState(loadingIndicatorRow); console.log("Fetching ahead to see if any more documents can be loaded."); while (!this.batchHasMatchingRecords() && this.cursor) { console.log("Fetching document records without creating cards."); await this.fetchAndCollectRecordsBatch(); } if (this.batchHasMatchingRecords()) { console.log("Found matching records ahead. Cards will be created for them on next load"); showLoadingState(loadMoreBtn); this.areRecordsAhead = true; } else { console.log("No more matching records found."); showLoadingState(null); this.areRecordsAhead = false; } } } async loadCards(initial_load) { if (this.loading) { return; } else { this.loading = true; } if (!this.pds) { await this.storePdsUrl(); } if (!this.pubUrl) { await this.storePubUrl(); } if (!this.areRecordsAhead) { await this.necessarilyLoadAvailableCards(initial_load); } else { this.createCardsForAheadRecords(); } await this.fetchAhead(); if (initial_load && this.noMatchingRecordFound) { nothingMoreRow.innerHTML = `

Nothing to show!

`; showLoadingState(nothingMoreRow); } this.loading = false; } } let loader = new BatchLoader(); (async() => { showLoadingState(loadingIndicatorRow); try { await loader.loadCards(true); } catch (error) { presentError(error); showLoadingState(errorRow); } })(); loadMoreBtn.addEventListener("click", async function() { showLoadingState(null); if (loader.cursor) { try { await loader.loadCards(false); } catch (error) { presentError(error); showLoadingState(errorRow); } } });