UNPKG

alinea

Version:
94 lines (92 loc) 2.6 kB
import { atomFamily } from "../../chunks/chunk-WDCPVJJC.js"; import { atom } from "../../chunks/chunk-WJ67RR7S.js"; import { Doc, encodeStateAsUpdate, encodeStateVector } from "../../chunks/chunk-QUIANN6B.js"; import "../../chunks/chunk-AJJSW27C.js"; import "../../chunks/chunk-NZLE2WMY.js"; // src/dashboard/atoms/Edits.ts import { DOC_KEY } from "alinea/core/Doc"; import { Type } from "alinea/core/Type"; import { configAtom } from "./DashboardAtoms.js"; import { yAtom } from "./YAtom.js"; var Edits = class { #type; #entry; /** The mutable doc that we are editing */ doc = new Doc(); /** The state vector of the source doc */ sourceVector; sourceUpdate; /** The root map containing field data */ root = this.doc.getMap(DOC_KEY); /** Did we make any local changes? */ hasChanges = createChangesAtom(this.root); /** Clear local changes, reset to source */ resetChanges = atom(null, (get, set) => { this.applyEntryData(this.#entry.data); set(this.hasChanges, false); }); yUpdate = yAtom(this.root, () => { return this.getLocalUpdate(); }); constructor(type, entry) { this.#type = type; this.#entry = entry; this.applyEntryData(entry.data); this.sourceVector = encodeStateVector(this.doc); } hasData() { return !this.root.keys().next().done; } /** A Y.js update that contains our own edits */ getLocalUpdate() { return encodeStateAsUpdate(this.doc, this.sourceVector); } /** Update entry field data */ applyEntryData(entryData) { const clientID = this.doc.clientID; this.doc.clientID = 1; this.doc.transact(() => { Type.shape(this.#type).applyY(entryData, this.doc, DOC_KEY); }, "self"); this.doc.clientID = clientID; } /** The field data */ getEntryData(type) { return Type.shape(type).fromY(this.root); } }; function createChangesAtom(yMap) { const hasChanges = atom(false); hasChanges.onMount = (setAtom) => { const listener = (events, tx) => { if (tx.origin === "self") return; setAtom(true); }; yMap.observeDeep(listener); return () => yMap.unobserveDeep(listener); }; return hasChanges; } var entryEditsAtoms = atomFamily( (entry) => { return atom((get) => { const config = get(configAtom); const type = config.schema[entry.type]; return new Edits(type, entry); }); }, (a, b) => a.id === b.id && a.locale === b.locale && a.fileHash === b.fileHash && // This is a check for untranslated entries, where the path is cleared a.data.path === b.data.path ); export { Edits, entryEditsAtoms };