// Parsing, filtering and sorting for the subscriptions page. // // Pure: no extension APIs and no DOM. The record shape is third-party data — // a publication at-uri can be missing or malformed, and `createdAt` is // optional — so every field is checked here rather than in the page. import { parseAtUri } from './atproto' export const SUBSCRIPTION_COLLECTION = 'site.standard.graph.subscription' /** One `site.standard.graph.subscription` record, as the page needs it. */ export interface SubscriptionEntry { /** The subscription record's own at-uri. */ uri: string /** Its record key, which is what a delete names. */ rkey: string /** The publication at-uri the record points at. */ publication: string /** The record's `createdAt`, only when it parses as a date. */ createdAt?: string } /** The publication fields the page shows, hydrated from its public record. */ export interface PublicationSummary { uri: string name: string description?: string /** The publication's own site, only when it is an http(s) URL. */ url?: string /** The site URL's host, for search and for the "site" sort. */ host?: string iconUrl?: string } /** A subscription plus whatever hydration has learned about its publication. */ export interface SubscriptionRow extends SubscriptionEntry { pub?: PublicationSummary /** The publication record could not be read. The row still works. */ failed?: boolean } export type SubscriptionSort = 'name' | 'site' | 'newest' | 'oldest' export const SORT_LABELS: Record = { name: 'Name', site: 'Site', newest: 'Newest', oldest: 'Oldest', } export function isSubscriptionSort(value: unknown): value is SubscriptionSort { return value === 'name' || value === 'site' || value === 'newest' || value === 'oldest' } export interface SubscriptionRecordValue { $type?: unknown publication?: unknown createdAt?: unknown } /** * A listed record as a subscription entry. Null for the values a page cannot * act on: a malformed record uri, a missing publication, or a publication * that is not an at-uri. A bad `createdAt` only costs the date. */ export function parseSubscription(record: { uri: string value: unknown }): SubscriptionEntry | null { const parsed = parseAtUri(record.uri) if (!parsed || parsed.collection !== SUBSCRIPTION_COLLECTION) return null const value = (record.value ?? {}) as SubscriptionRecordValue const publication = value.publication if (typeof publication !== 'string') return null const publicationUri = parseAtUri(publication) if (!publicationUri || publicationUri.collection !== 'site.standard.publication') return null return { uri: record.uri, rkey: parsed.rkey, publication, createdAt: parsedDate(value.createdAt), } } function parsedDate(value: unknown): string | undefined { if (typeof value !== 'string') return undefined return Number.isNaN(Date.parse(value)) ? undefined : value } /** An http(s) URL as a string, or undefined for anything else. */ export function safeHttpUrl(value: unknown): string | undefined { if (typeof value !== 'string' || !value.trim()) return undefined try { const url = new URL(value) return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : undefined } catch { return undefined } } export function hostOf(url: string | undefined): string | undefined { if (!url) return undefined try { return new URL(url).host || undefined } catch { return undefined } } /** What a row is called before (or without) its publication record. */ export function publicationFallback(uri: string): string { return parseAtUri(uri)?.did ?? uri } const collator = new Intl.Collator(undefined, { sensitivity: 'base', numeric: true }) function compareText(a: string, b: string): number { const result = collator.compare(a, b) return result !== 0 ? result : a < b ? -1 : a > b ? 1 : 0 } // A row whose publication record has not landed (or could not be read) sorts // after every named one. The sentinel keeps the fallback's display text intact // while making it a sort key of last resort. function nameOf(row: SubscriptionRow): string { return row.pub?.name ?? `￿${publicationFallback(row.publication)}` } function timeOf(row: SubscriptionRow): number | undefined { if (!row.createdAt) return undefined const at = Date.parse(row.createdAt) return Number.isNaN(at) ? undefined : at } /** * Search the fields a reader can see: name, description, URL and host. All * whitespace-separated terms must match, so "blog example" is a narrowing * query rather than one impossible string. */ export function filterSubscriptions( rows: readonly SubscriptionRow[], query: string, ): SubscriptionRow[] { const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean) if (terms.length === 0) return [...rows] return rows.filter((row) => { const haystack = [row.pub?.name, row.pub?.description, row.pub?.url, row.pub?.host] .filter((field): field is string => !!field) .join('\n') .toLowerCase() return terms.every((term) => haystack.includes(term)) }) } /** * A sorted copy of the rows. Missing values sort last rather than first, so a * publication whose record has not landed yet does not head the list; ties * fall back to the publication name and then its uri so the order is stable * across redraws. */ export function sortSubscriptions( rows: readonly SubscriptionRow[], sort: SubscriptionSort, ): SubscriptionRow[] { const copy = [...rows] switch (sort) { case 'name': return copy.sort( (a, b) => compareText(nameOf(a), nameOf(b)) || compareText(a.publication, b.publication), ) case 'site': return copy.sort((a, b) => { const ah = a.pub?.host const bh = b.pub?.host if (ah && bh) { const byHost = compareText(ah, bh) if (byHost !== 0) return byHost } else if (ah || bh) { return ah ? -1 : 1 } return compareText(nameOf(a), nameOf(b)) || compareText(a.publication, b.publication) }) case 'newest': return copy.sort((a, b) => byTime(a, b, 'desc')) case 'oldest': return copy.sort((a, b) => byTime(a, b, 'asc')) } } function byTime(a: SubscriptionRow, b: SubscriptionRow, direction: 'asc' | 'desc'): number { const at = timeOf(a) const bt = timeOf(b) if (at !== undefined && bt !== undefined && at !== bt) { return direction === 'desc' ? bt - at : at - bt } if (at !== undefined) return -1 if (bt !== undefined) return 1 return compareText(nameOf(a), nameOf(b)) || compareText(a.publication, b.publication) } export interface SubscriptionStats { total: number /** Distinct publication site hosts, among the records hydrated so far. */ hosts: number /** The newest subscription's `createdAt`, when any record carries one. */ newestAt?: string } export function subscriptionStats(rows: readonly SubscriptionRow[]): SubscriptionStats { const hosts = new Set() let newestAt: string | undefined let newest = Number.NEGATIVE_INFINITY for (const row of rows) { if (row.pub?.host) hosts.add(row.pub.host) const at = timeOf(row) if (at !== undefined && at > newest) { newest = at newestAt = row.createdAt } } return { total: rows.length, hosts: hosts.size, newestAt } } /** A compact local date, or '' when there is no usable date. */ export function formatSubscriptionDate(value: string | undefined): string { if (!value) return '' const at = Date.parse(value) if (Number.isNaN(at)) return '' return new Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'short', day: 'numeric', }).format(at) }