import { splitGraphemes } from "unicode-segmenter/grapheme"; import { AvailableCoValueCore } from "../coValueCore/coValueCore.js"; import { TRANSACTION_CONFIG } from "../config.js"; import { JsonObject } from "../jsonValue.js"; import { DeletionOpPayload, OpID, RawCoList } from "./coList.js"; import { CoValueFrontier } from "../knownState.js"; export type StringifiedOpID = string & { __stringifiedOpID: true }; export function stringifyOpID(opID: OpID): StringifiedOpID { return `${opID.sessionID}:${opID.txIndex}:${opID.changeIdx}` as StringifiedOpID; } type PlaintextIdxMapping = { opIDbeforeIdx: OpID[]; opIDafterIdx: OpID[]; idxAfterOpID: { [opID: StringifiedOpID]: number }; idxBeforeOpID: { [opID: StringifiedOpID]: number }; }; /** * A collaborative plain text implementation that supports grapheme-accurate editing. * * Locale support: * - Locale can be specified in the meta field when creating the text: `{ meta: { locale: "ja-JP" } }` * - If no locale is specified, falls back to browser's locale (`navigator.language`) * - If browser locale is not available, defaults to 'en' * * @example * ```typescript * // With specific locale * const textJa = node.createCoValue({ * type: "coplaintext", * ruleset: { type: "unsafeAllowAll" }, * meta: { locale: "ja-JP" }, * ...Crypto.createdNowUnique(), * }); * * // Using browser locale * const text = node.createCoValue({ * type: "coplaintext", * ruleset: { type: "unsafeAllowAll" }, * meta: null, * ...Crypto.createdNowUnique(), * }); * ``` */ export class RawCoPlainText< Meta extends JsonObject | null = JsonObject | null, > extends RawCoList { /** @category 6. Meta */ type = "coplaintext" as const; _cachedMapping: WeakMap< NonNullable, PlaintextIdxMapping >; constructor( core: AvailableCoValueCore, options?: { atTimeFilter?: number; atFrontierFilter?: CoValueFrontier; }, ) { super(core, options); this._cachedMapping = new WeakMap(); } get mapping() { const entries = this.entries(); let mapping = this._cachedMapping.get(entries); if (mapping) { return mapping; } mapping = { opIDbeforeIdx: [], opIDafterIdx: [], idxAfterOpID: {}, idxBeforeOpID: {}, }; let idxBefore = 0; for (const entry of entries) { const idxAfter = idxBefore + 1; mapping.opIDafterIdx[idxBefore] = entry.opID; mapping.opIDbeforeIdx[idxAfter] = entry.opID; mapping.idxAfterOpID[stringifyOpID(entry.opID)] = idxAfter; mapping.idxBeforeOpID[stringifyOpID(entry.opID)] = idxBefore; idxBefore = idxAfter; } this._cachedMapping.set(entries, mapping); return mapping; } toString() { return this.entries() .map((entry) => entry.value) .join(""); } override atTime(time: number): this { return new RawCoPlainText(this.core, { atTimeFilter: time, }) as this; } override atFrontier(frontier: CoValueFrontier): this { return new RawCoPlainText(this.core, { atFrontierFilter: frontier, }) as this; } /** * Inserts `text` before the character at index `idx`. * If idx is 0, inserts at the start of the text. * * @param idx - The index of the character to insert before * @param text - The text to insert * @param privacy - Whether the operation should be private or trusting * @category 2. Editing */ insertBefore( idx: number, text: string, privacy: "private" | "trusting" = "private", ) { const graphemes = Array.from(splitGraphemes(text)); if (idx === 0) { // For insertions at start, prepend the first char and append the rest const firstChar = graphemes[0]; if (firstChar) { this.prepend(firstChar, 0, privacy); } if (graphemes.length > 1) { this.appendChars(graphemes.slice(1), 0, privacy); } } else { // For other insertions, append after the previous character this.appendChars(graphemes, idx - 1, privacy); } } appendChars( text: string[], position: number, privacy: "private" | "trusting" = "private", ) { const chunks = splitIntoChunks(text); for (const chunk of chunks) { this.appendItems(chunk, position, privacy); position += chunk.length; } } /** * Inserts `text` after the character at index `idx`. * * @param idx - The index of the character to insert after * @param text - The text to insert * @param privacy - Whether the operation should be private or trusting * @category 2. Editing */ insertAfter( idx: number, text: string, privacy: "private" | "trusting" = "private", ) { const graphemes = Array.from(splitGraphemes(text)); if (idx >= this.entries().length) { this.appendChars(graphemes, idx - 1, privacy); } else { this.appendChars(graphemes, idx, privacy); } } deleteRange( { from, to }: { from: number; to: number }, privacy: "private" | "trusting" = "private", ) { const ops: DeletionOpPayload[] = []; for (let idx = from; idx < to; ) { const insertion = this.mapping.opIDafterIdx[idx]; if (!insertion) { throw new Error("Invalid idx to delete " + idx); } ops.push({ op: "del", insertion, }); let nextIdx = idx + 1; while (!this.mapping.opIDbeforeIdx[nextIdx] && nextIdx < to) { nextIdx++; } idx = nextIdx; } this.core.makeTransaction(ops, privacy); this.processNewTransactions(); } /** @internal Helper method to split text into graphemes */ toGraphemes(text: string): string[] { return [...splitGraphemes(text)]; } /** @internal Helper method to join graphemes into a string */ fromGraphemes(graphemes: string[]): string { return graphemes.join(""); } } function splitIntoChunks(text: string[]) { const maxChunkSize = Math.ceil( TRANSACTION_CONFIG.MAX_RECOMMENDED_TX_SIZE / 200, ); const chunks: string[][] = []; for (let i = 0; i < text.length; i += maxChunkSize) { chunks.push(text.slice(i, i + maxChunkSize)); } return chunks; }