Something went wrong. Try again.
a tool for shared writing and social publishing
Something went wrong. Try again.
33 kB · 1125 lines
TypeScript
at perf/paste
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126import { DeepReadonly, Replicache, WriteTransaction } from "replicache";import type { Fact, ReplicacheMutators } from ".";import type { Attribute, Attributes, FilterAttributes } from "./attributes";import { SupabaseClient } from "@supabase/supabase-js";import { Database } from "supabase/database.types";import { generateKeyBetween } from "fractional-indexing";import { v7 } from "uuid";import { localImages } from "src/utils/addImage";
export type MutationContext = { permission_token_id: string; createEntity: (args: { entityID: string; permission_set: string; }) => Promise<boolean>; scanIndex: { eav: <A extends Attribute>( entity: string, attribute: A, ) => Promise<DeepReadonly<Fact<A>[]>>; }; deleteEntity: (entity: string) => Promise<void>; assertFact: <A extends Attribute>( f: Omit<Fact<A>, "id"> & { id?: string }, ) => Promise<void>; retractFact: (id: string) => Promise<void>; runOnServer( cb: (ctx: { supabase: SupabaseClient<Database> }) => Promise<void>, ): Promise<void>; runOnClient( cb: (ctx: { supabase: SupabaseClient<Database>; tx: WriteTransaction; }) => Promise<void>, ): Promise<void>;};
type Mutation<T> = ( args: T & { ignoreUndo?: true }, ctx: MutationContext,) => Promise<void>;
const addCanvasBlock: Mutation<{ parent: string; permission_set: string; factID: string; type: Fact<"block/type">["data"]["value"]; newEntityID: string; position: { x: number; y: number };}> = async (args, ctx) => { await ctx.createEntity({ entityID: args.newEntityID, permission_set: args.permission_set, }); await ctx.assertFact({ entity: args.parent, id: args.factID, data: { type: "spatial-reference", value: args.newEntityID, position: args.position, }, attribute: "canvas/block", }); await ctx.assertFact({ entity: args.newEntityID, data: { type: "block-type-union", value: args.type }, attribute: "block/type", });};
const addBlock: Mutation<{ parent: string; permission_set: string; factID: string; type: Fact<"block/type">["data"]["value"]; newEntityID: string; position: string;}> = async (args, ctx) => { await ctx.createEntity({ entityID: args.newEntityID, permission_set: args.permission_set, }); await ctx.assertFact({ entity: args.parent, id: args.factID, data: { type: "ordered-reference", value: args.newEntityID, position: args.position, }, attribute: "card/block", }); await ctx.assertFact({ entity: args.newEntityID, data: { type: "block-type-union", value: args.type }, attribute: "block/type", });};
const addLastBlock: Mutation<{ parent: string; factID: string; entity: string;}> = async (args, ctx) => { let children = await ctx.scanIndex.eav(args.parent, "card/block"); let lastChild = children.toSorted((a, b) => a.data.position > b.data.position ? 1 : -1, )[children.length - 1]; await ctx.assertFact({ entity: args.parent, id: args.factID, attribute: "card/block", data: { type: "ordered-reference", value: args.entity, position: generateKeyBetween(lastChild?.data.position || null, null), }, });};
const moveBlock: Mutation<{ oldParent: string; block: string; newParent: string; position: | { type: "first" } | { type: "end" } | { type: "after"; entity: string };}> = async (args, ctx) => { let children = ( await ctx.scanIndex.eav(args.oldParent, "card/block") ).toSorted((a, b) => (a.data.position > b.data.position ? 1 : -1)); let newSiblings = ( await ctx.scanIndex.eav(args.newParent, "card/block") ).toSorted((a, b) => (a.data.position > b.data.position ? 1 : -1)); let block = children.find((f) => f.data.value === args.block); if (!block) return; await ctx.retractFact(block.id); let newPosition; let pos = args.position; switch (pos.type) { case "first": { newPosition = generateKeyBetween( null, newSiblings[0]?.data.position || null, ); break; } case "end": { newPosition = generateKeyBetween( newSiblings[newSiblings.length - 1]?.data.position || null, null, ); break; } case "after": { let index = newSiblings.findIndex((f) => f.data.value == pos?.entity); newPosition = generateKeyBetween( newSiblings[index]?.data.position || null, newSiblings[index + 1]?.data.position || null, ); } } await ctx.assertFact({ id: block.id, entity: args.newParent, attribute: "card/block", data: { type: "ordered-reference", value: block.data.value, position: newPosition, }, });};const moveChildren: Mutation<{ oldParent: string; newParent: string; after: string | null;}> = async (args, ctx) => { let children = ( await ctx.scanIndex.eav(args.oldParent, "card/block") ).toSorted((a, b) => (a.data.position > b.data.position ? 1 : -1)); let newSiblings = ( await ctx.scanIndex.eav(args.newParent, "card/block") ).toSorted((a, b) => (a.data.position > b.data.position ? 1 : -1)); let index = newSiblings.findIndex((f) => f.data.value === args.after); let newPosition = generateKeyBetween( newSiblings[index]?.data.position || null, newSiblings[index + 1]?.data.position || null, ); for (let child of children) { await ctx.retractFact(child.id); await ctx.assertFact({ id: child.id, entity: args.newParent, attribute: "card/block", data: { type: "ordered-reference", value: child.data.value, position: newPosition, }, }); newPosition = generateKeyBetween( newPosition, newSiblings[index + 1]?.data.position || null, ); }};
const outdentBlock: Mutation<{ oldParent: string; newParent: string; after: string; block: string; excludeFromSiblings?: string[];}> = async (args, ctx) => { //we should be able to get normal siblings here as we care only about one level let newSiblings = ( await ctx.scanIndex.eav(args.newParent, "card/block") ).toSorted((a, b) => (a.data.position > b.data.position ? 1 : -1)); let currentSiblings = ( await ctx.scanIndex.eav(args.oldParent, "card/block") ).toSorted((a, b) => (a.data.position > b.data.position ? 1 : -1));
let currentFactIndex = currentSiblings.findIndex( (f) => f.data.value === args.block, ); if (currentFactIndex === -1) return; // Filter out blocks that are being processed separately (e.g., in multi-select outdent) let excludeSet = new Set(args.excludeFromSiblings || []); let currentSiblingsAfter = currentSiblings .slice(currentFactIndex + 1) .filter((sib) => !excludeSet.has(sib.data.value)); let currentChildren = ( await ctx.scanIndex.eav(args.block, "card/block") ).toSorted((a, b) => (a.data.position > b.data.position ? 1 : -1)); let lastPosition = currentChildren[currentChildren.length - 1]?.data.position || null; await ctx.retractFact(currentSiblings[currentFactIndex].id); for (let sib of currentSiblingsAfter) { await ctx.retractFact(sib.id); lastPosition = generateKeyBetween(lastPosition, null); await ctx.assertFact({ entity: args.block, id: sib.id, attribute: "card/block", data: { type: "ordered-reference", position: lastPosition, value: sib.data.value, }, }); }
let index = newSiblings.findIndex((f) => f.data.value === args.after); if (index === -1) return; let newPosition = generateKeyBetween( newSiblings[index]?.data.position, newSiblings[index + 1]?.data.position || null, ); await ctx.assertFact({ id: currentSiblings[currentFactIndex].id, entity: args.newParent, attribute: "card/block", data: { type: "ordered-reference", position: newPosition, value: args.block, }, });};
const addPageLinkBlock: Mutation<{ type: "canvas" | "doc"; permission_set: string; blockEntity: string; firstBlockEntity: string; firstBlockFactID: string; pageEntity: string;}> = async (args, ctx) => { await ctx.createEntity({ entityID: args.pageEntity, permission_set: args.permission_set, }); await ctx.assertFact({ entity: args.blockEntity, attribute: "block/card", data: { type: "reference", value: args.pageEntity }, }); await ctx.assertFact({ attribute: "page/type", entity: args.pageEntity, data: { type: "page-type-union", value: args.type }, }); await addBlock( { factID: args.firstBlockFactID, permission_set: args.permission_set, newEntityID: args.firstBlockEntity, type: "heading", parent: args.pageEntity, position: "a0", }, ctx, );};
const retractFact: Mutation<{ factID: string }> = async (args, ctx) => { await ctx.retractFact(args.factID);};
// Add a content page to a publication draft leaflet's nav, seeded with a// single empty text block.const addPublicationNavPage: Mutation<{ rootEntity: string; pageEntity: string; permission_set: string; navFactID: string; route: string; title: string; firstBlockEntity: string; firstBlockFactID: string;}> = async (args, ctx) => { let entries = await ctx.scanIndex.eav(args.rootEntity, "root/page"); let last = entries.toSorted((a, b) => a.data.position > b.data.position ? 1 : -1, )[entries.length - 1]; await ctx.createEntity({ entityID: args.pageEntity, permission_set: args.permission_set, }); await ctx.assertFact({ id: args.navFactID, entity: args.rootEntity, attribute: "root/page", data: { type: "ordered-reference", value: args.pageEntity, position: generateKeyBetween(last?.data.position || null, null), }, }); await ctx.assertFact({ entity: args.pageEntity, attribute: "page/type", data: { type: "page-type-union", value: "doc" }, }); await ctx.assertFact({ entity: args.pageEntity, attribute: "page/route", data: { type: "string", value: args.route }, }); await ctx.assertFact({ entity: args.pageEntity, attribute: "page/title", data: { type: "string", value: args.title }, }); await addBlock( { factID: args.firstBlockFactID, permission_set: args.permission_set, newEntityID: args.firstBlockEntity, type: "text", parent: args.pageEntity, position: "a0", }, ctx, );};
// Add an external link tab: same root/page list as content pages, but with an// external url and no content.const addPublicationNavLink: Mutation<{ rootEntity: string; linkEntity: string; permission_set: string; navFactID: string; url: string; title: string;}> = async (args, ctx) => { let entries = await ctx.scanIndex.eav(args.rootEntity, "root/page"); let last = entries.toSorted((a, b) => a.data.position > b.data.position ? 1 : -1, )[entries.length - 1]; await ctx.createEntity({ entityID: args.linkEntity, permission_set: args.permission_set, }); await ctx.assertFact({ id: args.navFactID, entity: args.rootEntity, attribute: "root/page", data: { type: "ordered-reference", value: args.linkEntity, position: generateKeyBetween(last?.data.position || null, null), }, }); await ctx.assertFact({ entity: args.linkEntity, attribute: "page/external-url", data: { type: "string", value: args.url }, }); await ctx.assertFact({ entity: args.linkEntity, attribute: "page/title", data: { type: "string", value: args.title }, });};
const removePublicationNavEntry: Mutation<{ rootEntity: string; entity: string;}> = async (args, ctx) => { let entries = await ctx.scanIndex.eav(args.rootEntity, "root/page"); let fact = entries.find((f) => f.data.value === args.entity); if (fact) await ctx.retractFact(fact.id); await ctx.deleteEntity(args.entity);};
const removeBlock: Mutation< { blockEntity: string } | { blockEntity: string }[]> = async (args, ctx) => { for (let block of [args].flat()) { let [image] = await ctx.scanIndex.eav(block.blockEntity, "block/image"); await ctx.runOnServer(async ({ supabase }) => { if (image) { let paths = image.data.src.split("/"); await supabase.storage .from("minilink-user-assets") .remove([paths[paths.length - 1]]);
// Clear cover image if this block is the cover image // First try leaflets_in_publications const { data: pubResult } = await supabase .from("leaflets_in_publications") .update({ cover_image: null }) .eq("leaflet", ctx.permission_token_id) .eq("cover_image", block.blockEntity) .select("leaflet");
// If no rows updated, try leaflets_to_documents if (!pubResult || pubResult.length === 0) { await supabase .from("leaflets_to_documents") .update({ cover_image: null }) .eq("leaflet", ctx.permission_token_id) .eq("cover_image", block.blockEntity); } } }); await ctx.runOnClient(async ({ tx }) => { if (image) { // Release the local preview's object URL. let localSrc = localImages.get(image.data.src); if (localSrc) { URL.revokeObjectURL(localSrc); localImages.delete(image.data.src); }
// Clear cover image in client state if this block was the cover image let currentCoverImage = await tx.get("publication_cover_image"); if (currentCoverImage === block.blockEntity) { await tx.set("publication_cover_image", null); } } }); await ctx.deleteEntity(block.blockEntity); }};
const deleteEntity: Mutation<{ entity: string }> = async (args, ctx) => { await ctx.deleteEntity(args.entity);};
export type FactInput = { [k in Attribute]: Omit<Fact<k>, "id"> & { id?: string };}[Attribute];const assertFact: Mutation<FactInput | Array<FactInput>> = async ( args, ctx,) => { for (let f of [args].flat()) { await ctx.assertFact(f); }};
const increaseHeadingLevel: Mutation<{ entityID: string }> = async ( args, ctx,) => { let blockType = (await ctx.scanIndex.eav(args.entityID, "block/type"))[0]; let headinglevel = ( await ctx.scanIndex.eav(args.entityID, "block/heading-level") )[0]; if (blockType?.data.value !== "heading") await ctx.assertFact({ entity: args.entityID, attribute: "block/type", data: { type: "block-type-union", value: "heading" }, });
if (!headinglevel || blockType?.data.value !== "heading") { return await ctx.assertFact({ entity: args.entityID, attribute: "block/heading-level", data: { type: "number", value: 1 }, }); } if (headinglevel?.data.value === 3) return; return await ctx.assertFact({ entity: args.entityID, attribute: "block/heading-level", data: { type: "number", value: headinglevel.data.value + 1 }, });};
const moveBlockUp: Mutation<{ entityID: string; parent: string }> = async ( args, ctx,) => { let children = (await ctx.scanIndex.eav(args.parent, "card/block")).toSorted( (a, b) => (a.data.position > b.data.position ? 1 : -1), ); let index = children.findIndex((f) => f.data.value === args.entityID); if (index === -1) return; let next = children[index - 1]; if (!next) return; await ctx.retractFact(children[index].id); await ctx.assertFact({ id: children[index].id, entity: args.parent, attribute: "card/block", data: { type: "ordered-reference", position: generateKeyBetween( children[index - 2]?.data.position || null, next.data.position, ), value: args.entityID, }, });};const moveBlockDown: Mutation<{ entityID: string; parent: string; permission_set?: string;}> = async (args, ctx) => { let children = (await ctx.scanIndex.eav(args.parent, "card/block")).toSorted( (a, b) => (a.data.position > b.data.position ? 1 : -1), ); let index = children.findIndex((f) => f.data.value === args.entityID); if (index === -1) return; let next = children[index + 1]; if (!next) { // If this is the last block, create a new empty block above it using the addBlock helper if (!args.permission_set) return; // Can't create block without permission_set
let newEntityID = v7(); let previousBlock = children[index - 1]; let position = generateKeyBetween( previousBlock?.data.position || null, children[index].data.position, );
// Call the addBlock mutation helper directly await addBlock( { parent: args.parent, permission_set: args.permission_set, factID: v7(), type: "text", newEntityID: newEntityID, position: position, }, ctx, ); return; } await ctx.retractFact(children[index].id); await ctx.assertFact({ id: children[index].id, entity: args.parent, attribute: "card/block", data: { type: "ordered-reference", position: generateKeyBetween( next.data.position, children[index + 2]?.data.position || null, ), value: args.entityID, }, });};
const createEntity: Mutation< Array<{ entityID: string; permission_set: string }>> = async (args, ctx) => { for (let newentity of args) { await ctx.createEntity(newentity); }};
const createDraft: Mutation<{ mailboxEntity: string; newEntity: string; permission_set: string; firstBlockEntity: string; firstBlockFactID: string;}> = async (args, ctx) => { let [existingDraft] = await ctx.scanIndex.eav( args.mailboxEntity, "mailbox/draft", ); if (existingDraft) return; await ctx.createEntity({ entityID: args.newEntity, permission_set: args.permission_set, }); await ctx.assertFact({ entity: args.mailboxEntity, attribute: "mailbox/draft", data: { type: "reference", value: args.newEntity }, }); await addBlock( { factID: args.firstBlockFactID, permission_set: args.permission_set, newEntityID: args.firstBlockEntity, type: "text", parent: args.newEntity, position: "a0", }, ctx, );};
const archiveDraft: Mutation<{ mailboxEntity: string; archiveEntity: string; newBlockEntity: string; entity_set: string;}> = async (args, ctx) => { let [existingDraft] = await ctx.scanIndex.eav( args.mailboxEntity, "mailbox/draft", ); if (!existingDraft) return;
let [archive] = await ctx.scanIndex.eav( args.mailboxEntity, "mailbox/archive", ); let archiveEntity = archive?.data.value; if (!archive) { archiveEntity = args.archiveEntity; await ctx.createEntity({ entityID: archiveEntity, permission_set: args.entity_set, }); await ctx.assertFact({ entity: args.mailboxEntity, attribute: "mailbox/archive", data: { type: "reference", value: archiveEntity }, }); }
let archiveChildren = await ctx.scanIndex.eav(archiveEntity, "card/block"); let firstChild = archiveChildren.toSorted((a, b) => a.data.position > b.data.position ? 1 : -1, )[0];
await ctx.createEntity({ entityID: args.newBlockEntity, permission_set: args.entity_set, }); await ctx.assertFact({ entity: args.newBlockEntity, attribute: "block/type", data: { type: "block-type-union", value: "card" }, });
await ctx.assertFact({ entity: args.newBlockEntity, attribute: "block/card", data: { type: "reference", value: existingDraft.data.value }, });
await ctx.assertFact({ entity: archiveEntity, attribute: "card/block", data: { type: "ordered-reference", value: args.newBlockEntity, position: generateKeyBetween(null, firstChild?.data.position), }, });
await ctx.retractFact(existingDraft.id);};
const retractAttribute: Mutation<{ entity: string; attribute: | keyof FilterAttributes<{ cardinality: "one" }> | Array<keyof FilterAttributes<{ cardinality: "one" }>>;}> = async (args, ctx) => { for (let a of [args.attribute].flat()) { let fact = (await ctx.scanIndex.eav(args.entity, a))[0]; if (fact) await ctx.retractFact(fact.id); }};
const toggleTodoState: Mutation<{ entityID: string }> = async (args, ctx) => { let [checked] = await ctx.scanIndex.eav(args.entityID, "block/check-list"); if (!checked) { await ctx.assertFact({ entity: args.entityID, attribute: "block/check-list", data: { type: "boolean", value: false }, }); } else if (!checked.data.value) { await ctx.assertFact({ entity: args.entityID, attribute: "block/check-list", data: { type: "boolean", value: true }, }); } else { await ctx.retractFact(checked.id); }};
const addPollOption: Mutation<{ pollEntity: string; pollOptionEntity: string; pollOptionName: string; permission_set: string; factID: string;}> = async (args, ctx) => { await ctx.createEntity({ entityID: args.pollOptionEntity, permission_set: args.permission_set, });
await ctx.assertFact({ entity: args.pollOptionEntity, attribute: "poll-option/name", data: { type: "string", value: args.pollOptionName }, });
let children = await ctx.scanIndex.eav(args.pollEntity, "poll/options"); let lastChild = children.toSorted((a, b) => a.data.position > b.data.position ? 1 : -1, )[children.length - 1];
await ctx.assertFact({ entity: args.pollEntity, id: args.factID, attribute: "poll/options", data: { type: "ordered-reference", value: args.pollOptionEntity, position: generateKeyBetween(lastChild?.data.position || null, null), }, });};
const removePollOption: Mutation<{ optionEntity: string;}> = async (args, ctx) => { await ctx.deleteEntity(args.optionEntity);};
const updatePublicationDraft: Mutation<{ title?: string; description?: string; tags?: string[]; cover_image?: string | null; localPublishedAt?: string | null; preferences?: { showComments?: boolean; showMentions?: boolean; showRecommends?: boolean; } | null;}> = async (args, ctx) => { await ctx.runOnServer(async (serverCtx) => { const updates: { description?: string; title?: string; tags?: string[]; cover_image?: string | null; preferences?: { showComments?: boolean; showMentions?: boolean; showRecommends?: boolean; } | null; } = {}; if (args.description !== undefined) updates.description = args.description; if (args.title !== undefined) updates.title = args.title; if (args.tags !== undefined) updates.tags = args.tags; if (args.cover_image !== undefined) updates.cover_image = args.cover_image; if (args.preferences !== undefined) updates.preferences = args.preferences;
if (Object.keys(updates).length > 0) { // First try to update leaflets_in_publications (for publications) const { data: pubResult } = await serverCtx.supabase .from("leaflets_in_publications") .update(updates) .eq("leaflet", ctx.permission_token_id) .select("leaflet");
// If no rows were updated in leaflets_in_publications, // try leaflets_to_documents (for standalone documents) if (!pubResult || pubResult.length === 0) { await serverCtx.supabase .from("leaflets_to_documents") .update(updates) .eq("leaflet", ctx.permission_token_id); } } }); await ctx.runOnClient(async ({ tx }) => { if (args.title !== undefined) await tx.set("publication_title", args.title); if (args.description !== undefined) await tx.set("publication_description", args.description); if (args.tags !== undefined) await tx.set("publication_tags", args.tags); if (args.cover_image !== undefined) await tx.set("publication_cover_image", args.cover_image); if (args.localPublishedAt !== undefined) await tx.set("publication_local_published_at", args.localPublishedAt); if (args.preferences !== undefined) await tx.set("post_preferences", args.preferences); });};
const updateLeafletMetadata: Mutation<{ title?: string; description?: string | null;}> = async (args, ctx) => { await ctx.runOnServer(async (serverCtx) => { const updates: { title?: string; description?: string | null } = {}; if (args.title !== undefined) updates.title = args.title; if (args.description !== undefined) updates.description = args.description; if (Object.keys(updates).length === 0) return;
const { data: writerToken } = await serverCtx.supabase .from("permission_tokens") .select("root_entity, permission_token_rights(write)") .eq("id", ctx.permission_token_id) .single(); if (!writerToken) return; const hasWrite = writerToken.permission_token_rights.some((r) => r.write); if (!hasWrite) return;
await serverCtx.supabase .from("permission_tokens") .update(updates) .eq("root_entity", writerToken.root_entity); });};
// Toggle a draft contributor (the byline for this draft). The selected dids// live in the leaflet_contributors table and are pulled into Replicache under// the "draft_contributors" key, so the byline syncs live across collaborators.const toggleDraftContributor: Mutation<{ contributor_did: string; selected: boolean;}> = async (args, ctx) => { await ctx.runOnServer(async ({ supabase }) => { let { contributor_did } = args; let leaflet = ctx.permission_token_id;
if (!args.selected) { await supabase .from("leaflet_contributors") .delete() .eq("leaflet", leaflet) .eq("contributor_did", contributor_did); return; }
// Adding: the target must be the publication owner or a confirmed contributor. let { data: link } = await supabase .from("leaflets_in_publications") .select("publication, publications(identity_did)") .eq("leaflet", leaflet) .maybeSingle(); if (!link?.publication) return;
let isOwner = contributor_did === link.publications?.identity_did; if (!isOwner) { let { data: pubContrib } = await supabase .from("publication_contributors") .select("confirmed") .eq("publication_uri", link.publication) .eq("contributor_did", contributor_did) .maybeSingle(); if (!pubContrib?.confirmed) return; }
await supabase .from("leaflet_contributors") .upsert( { leaflet, contributor_did }, { onConflict: "leaflet,contributor_did", ignoreDuplicates: true }, ); }); await ctx.runOnClient(async ({ tx }) => { let current = (await tx.get<string[]>("draft_contributors")) ?? []; let next = args.selected ? current.includes(args.contributor_did) ? current : [...current, args.contributor_did] : current.filter((d) => d !== args.contributor_did); await tx.set("draft_contributors", next); });};
const createFootnote: Mutation<{ footnoteEntityID: string; blockID: string; permission_set: string; position: string;}> = async (args, ctx) => { await ctx.createEntity({ entityID: args.footnoteEntityID, permission_set: args.permission_set, }); await ctx.assertFact({ entity: args.blockID, attribute: "block/footnote", data: { type: "ordered-reference", value: args.footnoteEntityID, position: args.position, }, });};
const deleteFootnote: Mutation<{ footnoteEntityID: string; blockID: string;}> = async (args, ctx) => { let footnotes = await ctx.scanIndex.eav(args.blockID, "block/footnote"); let fact = footnotes.find((f) => f.data.value === args.footnoteEntityID); if (fact) await ctx.retractFact(fact.id); await ctx.deleteEntity(args.footnoteEntityID);};
// A comment and a reply share the same body: an entity holding the YJS// content plus author/created-at facts, all carrying the author's did so the// server's authentication gate (sessionDid must match author_did) verifies// authorship. Content is a base64-encoded YJS update, composed locally and// only persisted on submit.async function createAuthoredEntity( ctx: MutationContext, args: { entityID: string; permission_set: string; authorDid: string; createdAt: string; content: string; },) { await ctx.createEntity({ entityID: args.entityID, permission_set: args.permission_set, }); await ctx.assertFact({ entity: args.entityID, attribute: "block/text", data: { type: "text", value: args.content }, author_did: args.authorDid, }); await ctx.assertFact({ entity: args.entityID, attribute: "comment/author", data: { type: "string", value: args.authorDid }, author_did: args.authorDid, }); await ctx.assertFact({ entity: args.entityID, attribute: "comment/created-at", data: { type: "string", value: args.createdAt }, author_did: args.authorDid, });}
const createComment: Mutation<{ commentEntityID: string; blockID: string; permission_set: string; position: string; authorDid: string; createdAt: string; anchorStart: number; anchorEnd: number; content: string;}> = async (args, ctx) => { await createAuthoredEntity(ctx, { ...args, entityID: args.commentEntityID }); await ctx.assertFact({ entity: args.blockID, attribute: "block/comment", data: { type: "ordered-reference", value: args.commentEntityID, position: args.position, }, }); await ctx.assertFact({ entity: args.commentEntityID, attribute: "comment/anchor-start", data: { type: "number", value: args.anchorStart }, }); await ctx.assertFact({ entity: args.commentEntityID, attribute: "comment/anchor-end", data: { type: "number", value: args.anchorEnd }, });};
const createCommentReply: Mutation<{ replyEntityID: string; commentEntityID: string; permission_set: string; position: string; authorDid: string; createdAt: string; content: string;}> = async (args, ctx) => { await createAuthoredEntity(ctx, { ...args, entityID: args.replyEntityID }); await ctx.assertFact({ entity: args.commentEntityID, attribute: "comment/reply", data: { type: "ordered-reference", value: args.replyEntityID, position: args.position, }, });};
const deleteComment: Mutation<{ commentEntityID: string; blockID: string;}> = async (args, ctx) => { // Fired both when a thread is resolved and by the editor's orphan diff when a // comment's anchor text is deleted. Deletes the root comment and all replies. let comments = await ctx.scanIndex.eav(args.blockID, "block/comment"); let fact = comments.find((f) => f.data.value === args.commentEntityID); if (fact) await ctx.retractFact(fact.id); let replies = await ctx.scanIndex.eav(args.commentEntityID, "comment/reply"); for (let reply of replies) { await ctx.deleteEntity(reply.data.value); } await ctx.deleteEntity(args.commentEntityID);};
const deleteCommentReply: Mutation<{ replyEntityID: string; commentEntityID: string;}> = async (args, ctx) => { let replies = await ctx.scanIndex.eav(args.commentEntityID, "comment/reply"); let fact = replies.find((f) => f.data.value === args.replyEntityID); if (fact) await ctx.retractFact(fact.id); await ctx.deleteEntity(args.replyEntityID);};
// Replace a comment or reply body in place. Only the original author may// edit. The new content is a full YJS doc state with no shared history with// the old one, so we retract the existing block/text and assert the new value// rather than letting assertFact merge two independent docs together.const editComment: Mutation<{ entityID: string; authorDid: string; content: string;}> = async (args, ctx) => { let author = await ctx.scanIndex.eav(args.entityID, "comment/author"); if (author[0]?.data.value !== args.authorDid) return; let existing = await ctx.scanIndex.eav(args.entityID, "block/text"); for (let fact of existing) await ctx.retractFact(fact.id); await ctx.assertFact({ entity: args.entityID, attribute: "block/text", data: { type: "text", value: args.content }, author_did: args.authorDid, });};
export const mutations = { retractAttribute, addBlock, addCanvasBlock, addLastBlock, outdentBlock, moveBlockUp, moveBlockDown, addPageLinkBlock, addPublicationNavPage, addPublicationNavLink, removePublicationNavEntry, moveBlock, assertFact, retractFact, removeBlock, deleteEntity, moveChildren, increaseHeadingLevel, archiveDraft, toggleTodoState, createDraft, createEntity, addPollOption, removePollOption, updatePublicationDraft, updateLeafletMetadata, toggleDraftContributor, createFootnote, deleteFootnote, createComment, createCommentReply, deleteComment, deleteCommentReply, editComment,};