// The editor's working copy of a spec, and the pure logic that turns it into // the writes a save needs: every unsaved node becomes a create or an // update-in-place, and each update (or delete) first archives the previous // state as a group.standards.version record linked through `prev`. import { atUri, COLLECTIONS, DEFAULT_COLOUR, DEFAULT_EMOJI, blobCid, type BlockContent, type BlockNode, type BlockRecord, type EditorView, type ListItem, normalizeList, type RichText, type SectionNode, type SectionRecord, type SpecColour, type SpecDoc, type SpecRecord, type SpecStatus, type VersionRecord, } from './types.ts'; import { IdAllocator, isValidShortname, slugify } from './slug.ts'; import { isEmpty, normalizeFacets } from './richtext.ts'; import { editorView } from './fold.ts'; import { firstEmoji, isColour } from './banner.ts'; import { unresolvedRefView } from './refs.ts'; import type { RefView } from './types.ts'; export type DraftBlock = { rkey: string; content: BlockContent; /** The record as last saved, or null if this block was never written. */ saved: BlockRecord | null; }; export type DraftSection = { rkey: string; title: RichText; id: string; /** true once the author edited the id by hand; otherwise it follows the title. */ idTouched: boolean; content: DraftBlock[]; subsections: DraftSection[]; saved: SectionRecord | null; }; export type Draft = { did: string; rkey: string; shortname: string; title: RichText; abstract: RichText; editors: string[]; status: SpecStatus; colour: SpecColour; emoji: string; /** Catalogue references (group.standards.ref URIs) whose terms this spec references. */ imports: string[]; sections: DraftSection[]; createdAt: string; saved: SpecRecord | null; /** Live records removed from the tree since the last save: [collection, rkey, lastSavedRecord]. */ removed: { collection: string; rkey: string; record: SectionRecord | BlockRecord }[]; }; export type Write = | { $type: 'com.atproto.repo.applyWrites#create'; collection: string; rkey: string; value: Record } | { $type: 'com.atproto.repo.applyWrites#update'; collection: string; rkey: string; value: Record } | { $type: 'com.atproto.repo.applyWrites#delete'; collection: string; rkey: string }; export type SavePlan = { writes: Write[]; spec: SpecRecord; changed: boolean }; // --- construction -------------------------------------------------------------- export function emptyParagraph(): BlockContent { return { $type: 'group.standards.block#paragraph', text: { text: '' } }; } /** An untyped, empty block: the thing "/" turns into something. */ export function isPlaceholder(b: DraftBlock): boolean { return !b.saved && b.content.$type === 'group.standards.block#paragraph' && b.content.text.text.trim() === ''; } export function newDraft(did: string, rkey: string, shortname: string, title: string, now: string): Draft { return { did, rkey, shortname, title: { text: title }, abstract: { text: '' }, editors: [did], status: 'proposal', colour: DEFAULT_COLOUR, emoji: DEFAULT_EMOJI, imports: [], sections: [], createdAt: now, saved: null, removed: [], }; } /** A new section starts with one empty, untyped block. */ export function newSection(rkey: string, blockRkey: string, title = ''): DraftSection { return { rkey, title: { text: title }, id: slugify(title, 'section'), idTouched: false, content: [newBlock(blockRkey, emptyParagraph())], subsections: [], saved: null, }; } export function newBlock(rkey: string, content: BlockContent): DraftBlock { return { rkey, content, saved: null }; } /** Build a draft from a folded document (the records as currently saved). */ export function draftFromDoc(doc: SpecDoc): Draft { const specRecord = specRecordFromDoc(doc); return { did: doc.did, rkey: rkeyOf(doc.uri), shortname: doc.shortname, title: doc.title, abstract: doc.abstract ?? { text: '' }, editors: [...doc.editors.map((e) => e.did)], status: doc.status, colour: isColour(doc.colour) ? doc.colour : DEFAULT_COLOUR, emoji: firstEmoji(doc.emoji ?? '') || DEFAULT_EMOJI, imports: (doc.imports ?? []).map((i) => i.uri), sections: doc.sections.map(sectionFromNode), createdAt: doc.createdAt, saved: specRecord, removed: [], }; } function specRecordFromDoc(doc: SpecDoc): SpecRecord { const rec: SpecRecord = { $type: COLLECTIONS.spec, shortname: doc.shortname, title: doc.title, editors: doc.editors.map((e) => e.did), status: doc.status, sections: doc.sections.map((s) => s.uri), createdAt: doc.createdAt, updatedAt: doc.updatedAt, }; if (doc.abstract) rec.abstract = doc.abstract; if (doc.colour) rec.colour = doc.colour; if (doc.emoji) rec.emoji = doc.emoji; if (doc.imports?.length) rec.imports = doc.imports.map((i) => i.uri); if (doc.label) rec.label = doc.label; if (doc.prev) rec.prev = doc.prev; return rec; } function sectionFromNode(s: SectionNode): DraftSection { const saved: SectionRecord = { $type: COLLECTIONS.section, title: s.title, id: s.id, content: s.content.map((b) => b.uri), subsections: s.subsections.map((x) => x.uri), }; if (s.prev) saved.prev = s.prev; return { rkey: rkeyOf(s.uri), title: s.title, id: s.id, idTouched: s.id !== slugify(s.title.text, 'section'), content: s.content.map(blockFromNode), subsections: s.subsections.map(sectionFromNode), saved, }; } function blockFromNode(b: BlockNode): DraftBlock { const saved: BlockRecord = { $type: COLLECTIONS.block, content: b.content }; if (b.prev) saved.prev = b.prev; return { rkey: rkeyOf(b.uri), content: b.content, saved }; } function rkeyOf(uri: string): string { return uri.slice(uri.lastIndexOf('/') + 1); } // --- validation ----------------------------------------------------------------- export type DraftError = { path: string; message: string }; export function validateDraft(d: Draft): DraftError[] { const errors: DraftError[] = []; if (isEmpty(d.title)) errors.push({ path: 'title', message: 'The title cannot be empty.' }); if (!isValidShortname(d.shortname)) errors.push({ path: 'shortname', message: 'The shortname must be a slug.' }); if (d.editors.length === 0) errors.push({ path: 'editors', message: 'There must be at least one editor.' }); const ids = new Map(); const visit = (sections: DraftSection[], path: string) => { sections.forEach((s, i) => { const p = `${path}.${i}`; if (isEmpty(s.title)) errors.push({ path: `${p}.title`, message: 'Section titles cannot be empty.' }); if (!s.id.trim()) errors.push({ path: `${p}.id`, message: 'Section ids cannot be empty.' }); else if (ids.has(s.id)) errors.push({ path: `${p}.id`, message: `Duplicate section id "${s.id}".` }); else ids.set(s.id, p); for (const b of s.content) { if (b.content.$type === 'group.standards.block#blob' && !blobCid(b.content.blob)) { errors.push({ path: `${p}.content`, message: `An image block in "${s.title.text || s.id}" has no image yet.` }); } } visit(s.subsections, `${p}.subsections`); }); }; visit(d.sections, 'sections'); return errors; } /** Give every section whose id still follows its title a unique slug. */ export function reslugSections(sections: DraftSection[]): DraftSection[] { const fixed = new IdAllocator(); const collect = (ss: DraftSection[]) => { for (const s of ss) { if (s.idTouched) fixed.reserve(s.id); collect(s.subsections); } }; collect(sections); const apply = (ss: DraftSection[]): DraftSection[] => ss.map((s) => ({ ...s, id: s.idTouched ? s.id : fixed.take(slugify(s.title.text, 'section')), subsections: apply(s.subsections), })); return apply(sections); } // --- the save plan ------------------------------------------------------------- export type PlanOptions = { tid: () => string; now: string; label?: string; /** Write a new spec version even if nothing changed (a snapshot). */ force?: boolean; }; function stable(v: unknown): string { return JSON.stringify(v, (_k, val) => { if (val && typeof val === 'object' && !Array.isArray(val)) { const o = val as Record; return Object.keys(o) .sort() .reduce>((acc, k) => { if (o[k] !== undefined) acc[k] = o[k]; return acc; }, {}); } return val; }); } function same(a: unknown, b: unknown): boolean { return stable(a) === stable(b); } function cleanRichText(rt: RichText): RichText { return normalizeFacets(rt); } function cleanContent(c: BlockContent): BlockContent { switch (c.$type) { case 'group.standards.block#paragraph': return { $type: c.$type, text: cleanRichText(c.text) }; case 'group.standards.block#blob': { const out: BlockContent = { $type: c.$type, blob: c.blob }; if (c.alt) out.alt = c.alt; if (c.caption && c.caption.text.trim()) out.caption = cleanRichText(c.caption); return out; } case 'group.standards.block#code': { const out: BlockContent = { $type: c.$type, code: c.code }; if (c.language) out.language = c.language; return out; } case 'group.standards.block#math': return { $type: c.$type, tex: c.tex }; case 'group.standards.block#list': return cleanList(c); case 'group.standards.block#definitionList': return { $type: c.$type, items: c.items.map((d) => ({ $type: 'group.standards.block#definition', term: cleanRichText(d.term), description: cleanRichText(d.description), })), }; default: return c; } } function cleanList(l: Extract): typeof l { const list = normalizeList(l); return { $type: list.$type, ordered: list.ordered, items: list.items.map((it) => { const out: ListItem = { $type: it.$type, text: cleanRichText(it.text) }; if (it.list && it.list.items.length) out.list = cleanList(it.list); return out; }), }; } // Saved records are normalized the same way before comparison, so a record // written by another tool (or with facets in a different order) doesn't read // as dirty when nothing meaningful changed. function cleanBlockRecord(r: BlockRecord): BlockRecord { const out: BlockRecord = { $type: r.$type, content: cleanContent(r.content) }; if (r.prev) out.prev = r.prev; return out; } function cleanSectionRecord(r: SectionRecord): SectionRecord { const out: SectionRecord = { $type: r.$type, title: cleanRichText(r.title), id: r.id, content: [...r.content], subsections: [...r.subsections], }; if (r.prev) out.prev = r.prev; return out; } function cleanSpecRecord(r: SpecRecord): SpecRecord { const out: SpecRecord = { $type: r.$type, shortname: r.shortname, title: cleanRichText(r.title), editors: [...r.editors], status: r.status, sections: [...r.sections], createdAt: r.createdAt, updatedAt: r.updatedAt, }; if (r.abstract && r.abstract.text.trim()) out.abstract = cleanRichText(r.abstract); if (isColour(r.colour)) out.colour = r.colour; if (r.emoji && firstEmoji(r.emoji)) out.emoji = firstEmoji(r.emoji); if (r.imports?.length) out.imports = [...r.imports]; if (r.label) out.label = r.label; if (r.prev) out.prev = r.prev; return out; } /** * Compute the writes for a save. Blocks and sections are handled bottom-up so * that parents can reference children by URI (rkeys are minted when nodes * are created in the draft, so URIs are known before anything is written). * Untyped empty blocks that were never saved are left out. */ export function planSave(d: Draft, opts: PlanOptions): SavePlan { const writes: Write[] = []; const did = d.did; let changed = false; const archive = (collection: string, rkey: string, record: SpecRecord | SectionRecord | BlockRecord): string => { const vrkey = opts.tid(); const value: VersionRecord = { $type: COLLECTIONS.version, of: atUri(did, collection, rkey), record, createdAt: opts.now, }; writes.push({ $type: 'com.atproto.repo.applyWrites#create', collection: COLLECTIONS.version, rkey: vrkey, value }); return atUri(did, COLLECTIONS.version, vrkey); }; const saveBlock = (b: DraftBlock): string => { const uri = atUri(did, COLLECTIONS.block, b.rkey); const next: BlockRecord = { $type: COLLECTIONS.block, content: cleanContent(b.content) }; if (!b.saved) { writes.push({ $type: 'com.atproto.repo.applyWrites#create', collection: COLLECTIONS.block, rkey: b.rkey, value: next }); changed = true; return uri; } if (b.saved.prev) next.prev = b.saved.prev; if (same(next, cleanBlockRecord(b.saved))) return uri; next.prev = archive(COLLECTIONS.block, b.rkey, b.saved); writes.push({ $type: 'com.atproto.repo.applyWrites#update', collection: COLLECTIONS.block, rkey: b.rkey, value: next }); changed = true; return uri; }; const saveSection = (s: DraftSection): string => { const uri = atUri(did, COLLECTIONS.section, s.rkey); const content = s.content.filter((b) => !isPlaceholder(b)).map(saveBlock); const subsections = s.subsections.map(saveSection); const next: SectionRecord = { $type: COLLECTIONS.section, title: cleanRichText(s.title), id: s.id, content, subsections, }; if (!s.saved) { writes.push({ $type: 'com.atproto.repo.applyWrites#create', collection: COLLECTIONS.section, rkey: s.rkey, value: next }); changed = true; return uri; } if (s.saved.prev) next.prev = s.saved.prev; if (same(next, cleanSectionRecord(s.saved))) return uri; next.prev = archive(COLLECTIONS.section, s.rkey, s.saved); writes.push({ $type: 'com.atproto.repo.applyWrites#update', collection: COLLECTIONS.section, rkey: s.rkey, value: next }); changed = true; return uri; }; const sections = d.sections.map(saveSection); // removed live records: archive their last state, then delete them for (const r of d.removed) { archive(r.collection, r.rkey, r.record); writes.push({ $type: 'com.atproto.repo.applyWrites#delete', collection: r.collection, rkey: r.rkey }); changed = true; } const spec: SpecRecord = { $type: COLLECTIONS.spec, shortname: d.shortname, title: cleanRichText(d.title), editors: [...d.editors], status: d.status, colour: d.colour, emoji: d.emoji, sections, createdAt: d.createdAt, updatedAt: d.saved?.updatedAt ?? opts.now, }; if (!isEmpty(d.abstract)) spec.abstract = cleanRichText(d.abstract); if (d.imports.length) spec.imports = [...d.imports]; if (!d.saved) { spec.updatedAt = opts.now; if (opts.label) spec.label = opts.label; writes.push({ $type: 'com.atproto.repo.applyWrites#create', collection: COLLECTIONS.spec, rkey: d.rkey, value: spec }); return { writes, spec, changed: true }; } if (d.saved.label) spec.label = d.saved.label; if (d.saved.prev) spec.prev = d.saved.prev; const metadataChanged = !same(spec, cleanSpecRecord(d.saved)); if (!changed && !metadataChanged && !opts.force) return { writes: [], spec: d.saved, changed: false }; spec.prev = archive(COLLECTIONS.spec, d.rkey, d.saved); spec.updatedAt = opts.now; if (opts.label) spec.label = opts.label; else delete spec.label; writes.push({ $type: 'com.atproto.repo.applyWrites#update', collection: COLLECTIONS.spec, rkey: d.rkey, value: spec }); return { writes, spec, changed: true }; } /** After a successful save: mark every node as saved with the records just written. */ export function markSaved(d: Draft, plan: SavePlan): Draft { const written = new Map>(); for (const w of plan.writes) { if (w.$type !== 'com.atproto.repo.applyWrites#delete') written.set(`${w.collection}/${w.rkey}`, w.value); } const block = (b: DraftBlock): DraftBlock => { const v = written.get(`${COLLECTIONS.block}/${b.rkey}`) as BlockRecord | undefined; return v ? { ...b, saved: v } : b; }; const section = (s: DraftSection): DraftSection => { const v = written.get(`${COLLECTIONS.section}/${s.rkey}`) as SectionRecord | undefined; return { ...s, content: s.content.map(block), subsections: s.subsections.map(section), saved: v ?? s.saved, }; }; return { ...d, sections: d.sections.map(section), saved: plan.spec, removed: [] }; } /** Does the draft differ from what was last saved? (Cheap check for the UI.) */ export function isDirty(d: Draft): boolean { return planSave(d, { tid: () => 'x', now: d.saved?.updatedAt ?? '' }).changed; } /** The draft as a SpecDoc, for previewing with the normal renderers. */ export function draftToDoc( d: Draft, handle?: string, editors?: (did: string) => Partial | undefined, imports?: (uri: string) => RefView | undefined, ): SpecDoc { const section = (s: DraftSection): SectionNode => ({ uri: atUri(d.did, COLLECTIONS.section, s.rkey), title: s.title, id: s.id, content: s.content .filter((b) => !isPlaceholder(b)) .map((b) => ({ uri: atUri(d.did, COLLECTIONS.block, b.rkey), content: b.content })), subsections: s.subsections.map(section), }); const doc: SpecDoc = { uri: atUri(d.did, COLLECTIONS.spec, d.rkey), did: d.did, shortname: d.shortname, title: d.title, editors: d.editors.map((did) => editorView(did, editors?.(did))), status: d.status, colour: d.colour, emoji: d.emoji, sections: d.sections.map(section), createdAt: d.createdAt, updatedAt: d.saved?.updatedAt ?? d.createdAt, }; if (handle) doc.handle = handle; if (!isEmpty(d.abstract)) doc.abstract = d.abstract; if (d.imports.length) doc.imports = d.imports.map((uri) => imports?.(uri) ?? unresolvedRefView(uri)); if (d.saved?.label) doc.label = d.saved.label; return doc; }