chadtmiller.com/spaces-bookclub
Book club: a Svelte demo app for atproto spaces (@atproto/lex-space)
0
0
import { type SpaceRefString, isSpaceRefString } from '@atproto/lex'
import { club } from './atproto.ts'
// Invite links are app URLs: /join/<host DID>/<club key>. The club's space
// type is implied, so the link maps back to exactly one space.
const JOIN_PATH = /^\/join\/(did:[a-z]+:[^/]+)\/([^/]+)\/?$/
const PENDING_KEY = 'bookclub:pending-invite'
export function inviteLink(uri: SpaceRefString): string {
const { spaceDid, skey } = parseSpaceRef(uri)
return new URL(`/join/${spaceDid}/${skey}`, window.location.origin).href
}
/** The club an invite link points to, or null if it isn't one. */
export function clubFromInviteLink(input: string): SpaceRefString | null {
let url: URL
try {
url = new URL(input.trim(), window.location.origin)
} catch {
return null
}
const match = JOIN_PATH.exec(url.pathname)
if (!match) return null
const uri = `at://${decodeURIComponent(match[1])}/space/${club.nsid}/${decodeURIComponent(match[2])}`
return isSpaceRefString(uri) ? uri : null
}
/**
* Takes the invite link the page was opened with, if any, and keeps it until
* the user is signed in: signing in leaves the app (OAuth redirect) and
* returns to the root URL.
*/
export function captureInviteFromLocation(): void {
const uri = clubFromInviteLink(window.location.href)
if (!uri) return
localStorage.setItem(PENDING_KEY, uri)
history.replaceState(null, '', '/')
}
export function pendingInvite(): SpaceRefString | null {
const uri = localStorage.getItem(PENDING_KEY)
return uri && isSpaceRefString(uri) ? uri : null
}
export function clearPendingInvite(): void {
localStorage.removeItem(PENDING_KEY)
}
function parseSpaceRef(uri: SpaceRefString) {
// at://<spaceDid>/space/<spaceType>/<skey>
const [, , spaceDid, , , skey] = uri.split('/')
return { spaceDid, skey }
}