diff --git a/CHANGELOG.md b/CHANGELOG.md index d357f514..7b270ff0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,38 @@ since the previous tag. ## [Unreleased] +### Editor without a provider; WriteGate; the editor-chunk fence (P2.2) + +Desktop Phase 2, P2.2. The web editor behaves as before: it still gets its +provider, and nothing passes the new read-only prop. The editor chunk goes +from +15,284 B to +15,578 B (+294 B of P2.2's 300 B line in the D23 ledger), +and the budget drops from 23.5 KB to +16,864 B (`main` plus the 1,580 B +ledger), leaving 1,286 B for the ledger's other lines. No schema or protocol +change; no Deploy note. + +#### Added + +- **Editor:** `DocumentEditor` takes the session's Awareness and accepts no + provider. With none, the connection chip isn't rendered and no socket + opens. Carets use the Awareness directly, and the extension list depends + on it rather than on the provider, so attaching a provider later never + rebuilds the extensions (no `setOptions`). +- **Editor:** `WriteGate` (`extensions/write-gate/`), a `filterTransaction` + plugin over a ref. With the new `readOnly` prop, no local ProseMirror + change reaches the document, including the writes plugins make when a + document opens. Changes from collaborators still apply. The schema + guard's repair writes Yjs directly and is not gated yet; it must be when + something first sets `readOnly`. +- **Editor:** the decoration host (`extensions/decoration-host/`): declared + layers each get a plugin holding a `DecorationSet`, set by the meta-only + `setDecorationLayer` command, either mapped or cleared on document + changes. No layer is declared yet; comments and Find will declare theirs. + +#### Changed + +- **Build:** `scripts/check-editor-chunk-size.ts` budget is `main` at + P2.2 plus the D23 ledger (+16,864 B), and it prints exact bytes. + ### Desktop P2.1b: `local-session`, the batcher and `MemoryDocStore` The second half of desktop plan P2.1: the platform-neutral storage path that diff --git a/components/document-editor/document-editor-config.ts b/components/document-editor/document-editor-config.ts index 484c94eb..de09cc58 100644 --- a/components/document-editor/document-editor-config.ts +++ b/components/document-editor/document-editor-config.ts @@ -31,6 +31,7 @@ import type { EditorState, Transaction } from "@tiptap/pm/state"; import { StarterKit } from "@tiptap/starter-kit"; import DOMPurify from "dompurify"; import { Marked, type marked } from "marked"; +import type { Awareness } from "y-protocols/awareness"; import type * as Y from "yjs"; import { HorizontalRule } from "@/components/tiptap-node/horizontal-rule-node/horizontal-rule-node-extension"; @@ -45,6 +46,7 @@ import { renderCaret, renderCaretSelection, } from "@/extensions/collaboration-caret/safe-caret-render"; +import { DecorationHost } from "@/extensions/decoration-host/decoration-host"; import { EditorActionShortcuts } from "@/extensions/editor-action-shortcuts"; import { HeadingDrag } from "@/extensions/heading-drag"; import { @@ -65,6 +67,7 @@ import { FastTableOfContents } from "@/extensions/table-of-contents"; import { FontSize, TextColor } from "@/extensions/text-style-marks"; import { TitleDocument } from "@/extensions/title-document"; import { TokenHighlight } from "@/extensions/token-highlight"; +import { WriteGate } from "@/extensions/write-gate/write-gate"; import { SUBSCRIPT_SHORTCUT } from "@/lib/app-shortcuts"; import { lowlight } from "@/lib/lowlight"; @@ -143,7 +146,15 @@ function createMarkedInstance(): typeof marked { interface BuildDocumentEditorExtensionsOptions { documentId: string; ydoc: Y.Doc; - provider: HocuspocusProvider; + /** + * The session's one Awareness. It outlives any provider, so attaching or + * detaching one never rebuilds the extensions (no `setOptions`). + */ + awareness: Awareness; + /** The provider of the moment, if any; read, never a dependency. */ + getProvider: () => HocuspocusProvider | null; + /** WriteGate's check: false blocks every local document change. */ + canWrite: () => boolean; onFoldChange: (foldedIds: Set) => void; onFilterChange: (state: HeadingFilterCallbackState) => void; onTocUpdate: (anchors: TableOfContentData) => void; @@ -176,7 +187,9 @@ function createHeadingFilterFoldAdapter() { export function buildDocumentEditorExtensions({ documentId, ydoc, - provider, + awareness, + getProvider, + canWrite, onFoldChange, onFilterChange, onTocUpdate, @@ -234,11 +247,22 @@ export function buildDocumentEditorExtensions({ CaretBlockVisible, RepeatFormatting, SlashTrigger, + // The caret reads only `provider.awareness` (3.x runtime), so it gets + // the session's Awareness and works with no provider at all. UniqueID + // finds this option too and waits for its "synced" event: forwarded to + // the provider of the moment, as before (none on desktop Local). CollaborationCaret.configure({ - provider, + provider: { + awareness, + on: (event: string, fn: () => void) => getProvider()?.on(event, fn), + off: (event: string, fn: () => void) => getProvider()?.off(event, fn), + }, render: renderCaret, selectionRender: renderCaretSelection, }), + WriteGate.configure({ canWrite }), + // Comment highlights and Find hits declare their layers here (rule 6). + DecorationHost, HorizontalRule, TextAlign.configure({ types: ["heading", "paragraph"] }), TaskList, diff --git a/components/document-editor/document-editor.tsx b/components/document-editor/document-editor.tsx index 4dfdd2d9..9491472b 100644 --- a/components/document-editor/document-editor.tsx +++ b/components/document-editor/document-editor.tsx @@ -14,6 +14,8 @@ import { useState, useSyncExternalStore, } from "react"; +import type { HocuspocusProvider } from "@hocuspocus/provider"; +import type { Awareness } from "y-protocols/awareness"; import type * as Y from "yjs"; import { focusRovingItem, Toolbar } from "@/components/ui/toolbar"; @@ -91,11 +93,20 @@ interface DocumentEditorProps { playgroundRegenerateTrigger?: number; /** The Playground tab's Regenerate, also run from the palette. */ onPlaygroundRegenerate?: () => void; + /** + * View only: no local ProseMirror change reaches the document, plugin + * writes on open included (WriteGate, details spec §1). The schema + * guard's Yjs repair is not gated yet. The web sandbox never sets it. + */ + readOnly?: boolean; } type DocumentEditorContentProps = DocumentEditorProps & { ydoc: Y.Doc; - provider: import("@hocuspocus/provider").HocuspocusProvider; + /** The session's one Awareness: carets and names, with or without a provider. */ + awareness: Awareness; + /** Null for a document with no server (desktop Local): nothing dials out. */ + provider: HocuspocusProvider | null; documentId: string; /** Why the server refuses edits (size, deleted, outdated…), if it does. */ rejectedReason: string | null; @@ -145,12 +156,14 @@ const EDITOR_PROPS = { function DocumentEditorContent({ ydoc, + awareness, provider, documentId, onTitleChange, initialContent, playgroundRegenerateTrigger, onPlaygroundRegenerate, + readOnly, rejectedReason, serverSynced, }: DocumentEditorContentProps) { @@ -191,22 +204,32 @@ function DocumentEditorContent({ // A repair deferred while refused (offline budget) runs now. if (rejectedReason === null) schemaGuard.onWritable(); }, [rejectedReason, schemaGuard]); + // Read by the extensions, never their deps: WriteGate on every + // transaction (from the first one on), UniqueID when it waits for a sync. + const liveRef = useRef({ provider, readOnly }); + useEffect(() => { + liveRef.current = { provider, readOnly }; + }, [provider, readOnly]); // `useEditor` compares its options on every render and, when any differ, // calls `editor.setOptions`: a full view update that also re-syncs the - // whole document to Yjs. Keep every option stable between renders. + // whole document to Yjs. Keep every option stable between renders: the + // deps hold the Awareness, never the provider, so attaching one later + // keeps this array. const extensions = useMemo( () => buildDocumentEditorExtensions({ documentId, ydoc, - provider, + awareness, + getProvider: () => liveRef.current.provider, + canWrite: () => !liveRef.current.readOnly, onFoldChange: setFoldedIds, onFilterChange: setFilterState, onTocUpdate: tocStore.set, onInvalidContent: schemaGuard.onInvalidContent, }), - [documentId, ydoc, provider, tocStore, schemaGuard], + [documentId, ydoc, awareness, tocStore, schemaGuard], ); const editor = useEditor({ @@ -235,8 +258,8 @@ function DocumentEditorContent({ // Stop accepting input the server would drop or the schema can't hold. useEffect(() => { - if (editor) editor.setEditable(reason === null); - }, [editor, reason]); + if (editor) editor.setEditable(reason === null && !readOnly); + }, [editor, reason, readOnly]); const headingFilter = useHeadingFilter({ editor, @@ -431,7 +454,8 @@ function DocumentEditorContent({ rejectedReason={rejectedReason} /> )} - + {/* Its connection state opens the shared socket: only with a provider. */} + {provider && } ); @@ -443,12 +467,13 @@ export function DocumentEditor({ initialContent, playgroundRegenerateTrigger, onPlaygroundRegenerate, + readOnly, }: DocumentEditorProps = {}) { const docId = documentId ?? "default"; - const { ydoc, provider, synced, serverSynced, rejectedReason } = + const { ydoc, awareness, provider, synced, serverSynced, rejectedReason } = useYjsDocument(docId); - if (!synced || !ydoc || !provider) { + if (!synced || !ydoc || !awareness) { return ( <> {/* Refused with no device copy: explain instead of loading forever. */} @@ -463,12 +488,14 @@ export function DocumentEditor({ return ( diff --git a/docs/superpowers/specs/2026-11-15-desktop-architecture.md b/docs/superpowers/specs/2026-11-15-desktop-architecture.md index 5356fb1a..2a8e37dc 100644 --- a/docs/superpowers/specs/2026-11-15-desktop-architecture.md +++ b/docs/superpowers/specs/2026-11-15-desktop-architecture.md @@ -208,7 +208,7 @@ Each port has its own types-only file in `lib/platform/` (P2.1): `doc-session.ts **Shared editor changes** stay within their lines in the editor-chunk ledger (owner D23, ≈1,540 B gz in all, ≈1,580–1,660 B with D41's conditional phone line; P2.2's line, no provider plus `WriteGate` and the decoration-host stub, is 300 B; details spec §1 rule 5), checked by the chunk script on both targets, with `EDITOR_CHUNK_BUDGET_BYTES` lowered to `main` plus the ledger: -1. **`provider` becomes `HocuspocusProvider | null`.** `CollaborationCaret` is configured with the session's stable `awareness` (**decided in P2.2**, against the extension's runtime). The `useMemo` deps hold `awareness`, never the provider, so a provider attached later never rebuilds the extensions array. +1. **`provider` becomes `HocuspocusProvider | null`.** `CollaborationCaret` is configured with the session's stable `awareness` (**decided in P2.2**, against the extension's runtime: the caret reads only `provider.awareness`, so it gets `{ awareness, on, off }`; UniqueID also finds that option and waits for its `"synced"` event, so `on` and `off` forward to the provider of the moment through a ref, and with no provider nothing is waited for). The `useMemo` deps hold `awareness`, never the provider, so a provider attached later never rebuilds the extensions array. 2. **`CollabStatusGroup` renders only when `provider` is non-null.** Today it calls `useConnectionState`, which **creates the shared socket**, so a Local document would dial the server. The desktop chip is rendered by the desktop shell, outside the editor chunk. 3. **Seeding stays as it is.** `authoritative` feeds the existing `serverSynced` prop, and `local-session` sets it once hydrate finishes, because the library *is* the authority. The seed effect (`use-document-editor-effects.ts:78`) runs unchanged, and `data-server-synced` doubles as the readiness hook for the `local` and `electron` projects. (Live) A joined document becomes authoritative only after its first server sync. diff --git a/docs/superpowers/specs/2026-11-15-desktop-documents-and-editor-details.md b/docs/superpowers/specs/2026-11-15-desktop-documents-and-editor-details.md index f96b89cb..d160ac5f 100644 --- a/docs/superpowers/specs/2026-11-15-desktop-documents-and-editor-details.md +++ b/docs/superpowers/specs/2026-11-15-desktop-documents-and-editor-details.md @@ -56,7 +56,7 @@ These came out of the staff feasibility review. Each one was checked against the | Line | PR (owner) | Cap (gz) | |---|---|---| - | No provider, `WriteGate` and the decoration host | P2.2 | 300 B | + | No provider, `WriteGate` and the decoration host | P2.2 | 300 B (measured 294 B) | | Comments hook | P4.9 | 150 B | | Smart-quotes gate | P2.9c-1 | 150 B | | i18n core (`t()`, registry labels, `lang`/`dir`; also pays L3's `matchShortcut` / `visualStep` bytes, languages §3.7.1) | L1a | 400 B | @@ -68,7 +68,7 @@ These came out of the staff feasibility review. Each one was checked against the | Undo-gesture handler, **only if spike M18 shows native undo mutates the DOM** (D41, v8) | M19 | 80 B, conditional | | **Total** | | **1,580 B, or 1,660 B with the undo handler** | - - **Headroom:** 4,385 B real (the 24,064 B budget less `main` at 19,679 B, latest CHANGELOG entry). The ledger takes about a third of it, with or without the conditional line. + - **Headroom:** 4,385 B real when D23 was decided (the 24,064 B budget less `main` at 19,679 B). By P2.2, `main` had shrunk to +15,284 B (08b7663), so P2.2 set the fence at +16,864 B (15,284 + 1,580) in `scripts/check-editor-chunk-size.ts`; after P2.2 1,286 B remain for the other lines. - **Phones (D41):** M27's hardware-keyboard listener (shortcut glyphs) stays **out** of the editor chunk. - **Fencing:** P2.2 lowers `EDITOR_CHUNK_BUDGET_BYTES` to the size on `main` plus the ledger total, so unrelated work can't spend these bytes. Raising it needs an amendment to this rule. While D41's conditional 80 B undo line is unconfirmed, the fence is `main` + 1,580 B. If spike M18 confirms the line, the fence rises to `main` + 1,660 B with no further approval (pre-approved by D41). - **A PR that would go over its line** stops for a budget review. A line's unused bytes don't move to another line without an amendment. diff --git a/extensions/decoration-host/decoration-host.ts b/extensions/decoration-host/decoration-host.ts new file mode 100644 index 00000000..cd2eea07 --- /dev/null +++ b/extensions/decoration-host/decoration-host.ts @@ -0,0 +1,81 @@ +import { Extension } from "@tiptap/core"; +import { Plugin } from "@tiptap/pm/state"; +import { DecorationSet } from "@tiptap/pm/view"; + +export interface DecorationLayer { + /** The layer's name, e.g. "comments" or "find". */ + name: string; + /** + * Map the set through document changes (`DecorationSet.map`) instead of + * clearing it. Comments map; hits that are recomputed anyway clear. + */ + map?: boolean; +} + +export interface DecorationHostOptions { + layers: DecorationLayer[]; +} + +/** The meta every layer reads: `{ name, set }`. */ +const LAYER_META = "decorationLayer"; + +declare module "@tiptap/core" { + interface Commands { + decorationHost: { + /** + * Shows `set` (built against the current document) as layer `name`; + * `DecorationSet.empty` clears it. Meta-only: never the document, Yjs + * or undo. + */ + setDecorationLayer: (name: string, set: DecorationSet) => ReturnType; + }; + } +} + +/** + * Decoration host (details spec §1 rule 6), the `action-preview` pattern + * made general: each declared layer is one eager plugin whose only state + * is a `DecorationSet`, set by the meta-only `setDecorationLayer` command. + * All logic (finding hits, anchoring comments) lives in the layer's lazy + * chunk, which never calls `registerPlugin` (that re-creates every plugin + * view): a layer is declared here, in the extensions array, once. A local + * or remote document change maps a `map: true` layer and clears the rest. + */ +export const DecorationHost = Extension.create({ + name: "decorationHost", + + addOptions: () => ({ layers: [] }), + + addCommands: () => ({ + setDecorationLayer: + (name, set) => + ({ tr }) => { + // No steps, so no history entry and nothing for Yjs. + tr.setMeta(LAYER_META, { name, set }); + return true; + }, + }), + + addProseMirrorPlugins() { + return this.options.layers.map( + ({ name, map }) => + new Plugin({ + state: { + init: () => DecorationSet.empty, + apply(tr, set) { + const next = tr.getMeta(LAYER_META); + if (next?.name === name) return next.set; + // Mapping or clearing an empty set returns it unchanged. + if (!tr.docChanged) return set; + return map ? set.map(tr.mapping, tr.doc) : DecorationSet.empty; + }, + }, + props: { + decorations(state) { + return this.getState(state); + }, + }, + }), + ); + }, +}); diff --git a/extensions/write-gate/write-gate.ts b/extensions/write-gate/write-gate.ts new file mode 100644 index 00000000..d9e13ceb --- /dev/null +++ b/extensions/write-gate/write-gate.ts @@ -0,0 +1,36 @@ +import { Extension } from "@tiptap/core"; +import { isChangeOrigin } from "@tiptap/extension-collaboration"; +import { Plugin } from "@tiptap/pm/state"; + +export interface WriteGateOptions { + /** + * Whether this window may change the document. Required. Read on every + * transaction, so pass a function over a ref: it must not wait for + * `setEditable`, which runs in an effect after the editor is created. + */ + canWrite: () => boolean; +} + +/** + * Read-only enforced before a change exists (details spec §1 rules 1–2): a + * Yjs update is never dropped once made (later updates from the same + * client would strand), so a read-only document must not make one. Filters + * every local transaction that changes the document while `canWrite()` is + * false, appended ones included, so the plugins that write when a document + * opens (heading ids, the title, the trailing node, the outline) are gated + * too. Changes arriving from Yjs and meta-only transactions (folds, + * previews, decorations) always pass. `setEditable` still blocks typing. + */ +export const WriteGate = Extension.create({ + name: "writeGate", + + addProseMirrorPlugins() { + const { canWrite } = this.options; + return [ + new Plugin({ + filterTransaction: (tr) => + !tr.docChanged || isChangeOrigin(tr) || canWrite(), + }), + ]; + }, +}); diff --git a/hooks/use-yjs-document.ts b/hooks/use-yjs-document.ts index 4195a526..f788b4c2 100644 --- a/hooks/use-yjs-document.ts +++ b/hooks/use-yjs-document.ts @@ -51,6 +51,8 @@ export function useYjsDocument(documentId: string) { return { ydoc, + /** The session's one Awareness (DocSession shape); the provider's here. */ + awareness: providerRef?.awareness ?? null, provider: providerRef, synced, serverSynced, diff --git a/scripts/check-editor-chunk-size.ts b/scripts/check-editor-chunk-size.ts index b8de46ff..604c9dff 100644 --- a/scripts/check-editor-chunk-size.ts +++ b/scripts/check-editor-chunk-size.ts @@ -1,8 +1,8 @@ /** - * Editor bundle gate (spec §7, contract §5.1): the lazy editor chunk group - * may grow by at most `EDITOR_CHUNK_BUDGET_BYTES` gzipped over the baseline - * measured on `58a9d22` (the `integrate/smart-toolbar-ab` tip, before any - * smart-toolbar v1 track merged). + * Editor bundle gate (spec §7, contract §5.1; desktop D23): the lazy editor + * chunk group may grow by at most `EDITOR_CHUNK_BUDGET_BYTES` gzipped over + * the baseline measured on `58a9d22` (the `integrate/smart-toolbar-ab` tip, + * before any smart-toolbar v1 track merged). * * The editor is a `next/dynamic` import (`components/editor-app`). Turbopack * emits a loader that fetches the editor's chunk group with @@ -21,14 +21,25 @@ import { join } from "node:path"; /** Gzipped bytes of the editor chunk group at `58a9d22`. */ export const EDITOR_CHUNK_BASELINE_BYTES = 377_888; /** - * Allowed growth for the whole smart toolbar v1. Spec §7 said +6 KB gz; - * owner decision O1 (contract §10 A9) lazy-loads what is not needed at - * first paint and sets the budget to the measured remainder (18.43 KB on - * the r2 integration), rounded up to the next 0.5 KB. A11 raises it to - * 20 KB for the r2 fix waves (owner, 2026-11-13), and A12 to 23.5 KB for - * PR E (owner, 2026-11-13). Raising it again needs a new contract amendment. + * Growth on `main` (08b7663) when P2.2 set the fence: the smart toolbar v1 + * and everything merged before the desktop work. Its old 23.5 KB budget + * (contract A12) is replaced by the fence below. */ -export const EDITOR_CHUNK_BUDGET_BYTES = 23.5 * 1024; +export const EDITOR_CHUNK_MAIN_GROWTH_BYTES = 15_284; +/** + * The D23 editor-chunk ledger (desktop details spec §1 rule 5): every line + * the desktop, library and v1 feature work may add to this chunk, each + * measured in its PR. While D41's conditional 80 B undo line is + * unconfirmed the total is 1,580 B; if spike M18 confirms it, this becomes + * 1,660 B with no further approval. + */ +export const EDITOR_CHUNK_LEDGER_BYTES = 1_580; +/** + * The fence (D23): `main` plus the ledger, so unrelated work can't spend + * the ledger's bytes. Raising it needs an amendment to that rule. + */ +export const EDITOR_CHUNK_BUDGET_BYTES = + EDITOR_CHUNK_MAIN_GROWTH_BYTES + EDITOR_CHUNK_LEDGER_BYTES; /** Only `document-editor.tsx` renders this string. */ const EDITOR_MARKER = "Main content area, start typing to enter text."; @@ -75,13 +86,13 @@ function main() { const nextDir = dirFlag === -1 ? ".next" : process.argv[dirFlag + 1]; const { files, gzipBytes } = measureEditorChunk(nextDir); const growth = gzipBytes - EDITOR_CHUNK_BASELINE_BYTES; - const kb = (bytes: number) => `${(bytes / 1024).toFixed(1)} KB`; + const bytes = (n: number) => `${n.toLocaleString("en-US")} B`; console.log( - `Editor chunk group (${files.length} files): ${kb(gzipBytes)} gz`, + `Editor chunk group (${files.length} files): ${bytes(gzipBytes)} gz`, ); for (const file of files) console.log(` ${file}`); console.log( - `Baseline ${kb(EDITOR_CHUNK_BASELINE_BYTES)}, growth ${growth >= 0 ? "+" : ""}${kb(growth)}, budget +${kb(EDITOR_CHUNK_BUDGET_BYTES)}`, + `Baseline ${bytes(EDITOR_CHUNK_BASELINE_BYTES)}, growth ${growth >= 0 ? "+" : ""}${bytes(growth)}, budget +${bytes(EDITOR_CHUNK_BUDGET_BYTES)} (${bytes(EDITOR_CHUNK_BUDGET_BYTES - growth)} left)`, ); if (growth > EDITOR_CHUNK_BUDGET_BYTES) { console.error( diff --git a/tests/e2e/filter.spec.ts b/tests/e2e/filter.spec.ts index 0a9334ed..df3742a8 100644 --- a/tests/e2e/filter.spec.ts +++ b/tests/e2e/filter.spec.ts @@ -1,20 +1,7 @@ -import { expect, type Page, test } from "@playwright/test"; +import { expect, test } from "@playwright/test"; import { EditorPage } from "./helpers/editor-page"; -/** The headings must be on the server before a shared link opens. */ -async function waitForServerCopy(page: Page): Promise { - await page.waitForFunction(() => { - const caret = window.__tiptap_editor?.extensionManager.extensions.find( - (extension) => extension.name === "collaborationCaret", - ); - const provider = caret?.options.provider as - | { hasUnsyncedChanges: boolean } - | undefined; - return provider !== undefined && !provider.hasUnsyncedChanges; - }); -} - test.describe("heading filter", () => { let editorPage: EditorPage; @@ -48,7 +35,8 @@ test.describe("heading filter", () => { test("a ?filter= link applies the filter once the doc syncs", async ({ page, }) => { - await waitForServerCopy(page); + // The headings must be on the server before a shared link opens. + await editorPage.expectSavedToServer(); await page.goto("/?filter=alpha&mode=or"); await editorPage.waitForSync(); @@ -80,7 +68,8 @@ test.describe("heading filter", () => { test("a ?filter= link over the cap applies only its first 8 words", async ({ page, }) => { - await waitForServerCopy(page); + // The headings must be on the server before a shared link opens. + await editorPage.expectSavedToServer(); // Beta and Gamma come 9th and 10th, so they must be dropped unmatched. const kept = ["alpha", "w2", "w3", "w4", "w5", "w6", "w7", "w8"]; await page.goto(`/?filter=${[...kept, "beta", "gamma"].join("|")}&mode=or`); diff --git a/tests/e2e/helpers/editor-page.ts b/tests/e2e/helpers/editor-page.ts index 147b2a9f..25715da7 100644 --- a/tests/e2e/helpers/editor-page.ts +++ b/tests/e2e/helpers/editor-page.ts @@ -310,12 +310,25 @@ export class EditorPage { () => { const notice = document.querySelector(".document-size-notice"); if (notice) return { refusal: notice.textContent ?? "" }; + // The caret's `provider` option is the editor's Awareness holder, + // not the provider: its `on` forwards to the provider of the moment + // and returns what that returns, and `HocuspocusProvider.on` + // returns the provider itself (`this`). Null with no provider. const caret = window.__tiptap_editor?.extensionManager.extensions.find( (extension) => extension.name === "collaborationCaret", ); - const provider = caret?.options.provider as - | { isSynced: boolean; hasUnsyncedChanges: boolean } + const forward = caret?.options.provider as + | { on: (event: string, fn: () => void) => unknown } | undefined; + const probe = () => {}; + const provider = forward?.on("tinydocy:probe", probe) as + | { + isSynced: boolean; + hasUnsyncedChanges: boolean; + off: (event: string, fn: () => void) => void; + } + | undefined; + provider?.off("tinydocy:probe", probe); if (!provider?.isSynced || provider.hasUnsyncedChanges) return false; return { refusal: null }; }, diff --git a/tests/helpers/editor-schema.ts b/tests/helpers/editor-schema.ts index dcdbe60f..a2d17e31 100644 --- a/tests/helpers/editor-schema.ts +++ b/tests/helpers/editor-schema.ts @@ -1,6 +1,6 @@ -import type { HocuspocusProvider } from "@hocuspocus/provider"; import { getSchema } from "@tiptap/core"; import type { Schema } from "@tiptap/pm/model"; +import type { Awareness } from "y-protocols/awareness"; import * as Y from "yjs"; import { buildDocumentEditorExtensions } from "@/components/document-editor/document-editor-config"; @@ -11,7 +11,9 @@ export function getEditorSchema(): Schema { buildDocumentEditorExtensions({ documentId: "schema-test", ydoc: new Y.Doc(), - provider: {} as HocuspocusProvider, + awareness: {} as Awareness, + getProvider: () => null, + canWrite: () => true, onFoldChange() {}, onFilterChange() {}, onTocUpdate() {}, diff --git a/tests/unit/components/document-editor-markdown.test.ts b/tests/unit/components/document-editor-markdown.test.ts index d9b2c1d1..2b3ca9d0 100644 --- a/tests/unit/components/document-editor-markdown.test.ts +++ b/tests/unit/components/document-editor-markdown.test.ts @@ -1,18 +1,20 @@ import { describe, expect, it } from "bun:test"; -import type { HocuspocusProvider } from "@hocuspocus/provider"; import { Editor } from "@tiptap/core"; import { marked } from "marked"; +import type { Awareness } from "y-protocols/awareness"; import * as Y from "yjs"; import { buildDocumentEditorExtensions } from "@/components/document-editor/document-editor-config"; -/** The app's extensions, minus the two that need a live provider. */ +/** The app's extensions, minus the two collaboration ones (Yjs binding, carets). */ function buildEditor(): Editor { const extensions = buildDocumentEditorExtensions({ documentId: "markdown-test", ydoc: new Y.Doc(), - provider: {} as HocuspocusProvider, + awareness: {} as Awareness, + getProvider: () => null, + canWrite: () => true, onFoldChange() {}, onFilterChange() {}, onTocUpdate() {}, diff --git a/tests/unit/components/document-editor-no-provider.test.tsx b/tests/unit/components/document-editor-no-provider.test.tsx new file mode 100644 index 00000000..10a0488b --- /dev/null +++ b/tests/unit/components/document-editor-no-provider.test.tsx @@ -0,0 +1,179 @@ +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + it, + mock, + spyOn, +} from "bun:test"; + +import type { HocuspocusProvider } from "@hocuspocus/provider"; +import { Editor } from "@tiptap/core"; +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { Awareness } from "y-protocols/awareness"; +import * as Y from "yjs"; + +import * as yjsDocumentModule from "@/hooks/use-yjs-document"; +import * as hocuspocusModule from "@/lib/hocuspocus"; + +( + globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } +).IS_REACT_ACT_ENVIRONMENT = true; + +type YjsDocument = ReturnType; + +/** What the mocked session hands the editor; tests change it, then render. */ +let session: YjsDocument; + +/** Calls that would create (or reuse) the shared WebSocket. */ +let socketRequests = 0; +const socketStub = { + status: "connected", + connect() {}, + on() {}, + off() {}, +}; + +// mock.module is process-wide: the real modules go back in afterAll. +const realUseYjsDocument = yjsDocumentModule.useYjsDocument; +const realGetSocket = hocuspocusModule.getSharedHocuspocusSocket; +mock.module("@/hooks/use-yjs-document", () => ({ + ...yjsDocumentModule, + useYjsDocument: () => session, +})); +mock.module("@/lib/hocuspocus", () => ({ + ...hocuspocusModule, + getSharedHocuspocusSocket: () => { + socketRequests++; + return socketStub; + }, +})); +afterAll(() => { + mock.module("@/hooks/use-yjs-document", () => ({ + ...yjsDocumentModule, + useYjsDocument: realUseYjsDocument, + })); + mock.module("@/lib/hocuspocus", () => ({ + ...hocuspocusModule, + getSharedHocuspocusSocket: realGetSocket, + })); +}); + +const { DocumentEditor } = await import( + "@/components/document-editor/document-editor" +); + +/** Counts WebSocket constructions, whatever creates them. */ +let socketsOpened = 0; +const RealWebSocket = globalThis.WebSocket; +beforeAll(() => { + globalThis.WebSocket = class extends EventTarget { + constructor() { + super(); + socketsOpened++; + } + } as unknown as typeof WebSocket; +}); +afterAll(() => { + globalThis.WebSocket = RealWebSocket; +}); + +/** `useEditor` calls it when an option changes: a full view update. */ +const setOptions = spyOn(Editor.prototype, "setOptions"); +afterAll(() => setOptions.mockRestore()); + +let root: Root | undefined; +let container: HTMLElement | undefined; +let awareness: Awareness | undefined; +afterEach(async () => { + await act(async () => root?.unmount()); + container?.remove(); + awareness?.destroy(); + root = undefined; + container = undefined; + awareness = undefined; + socketRequests = 0; + socketsOpened = 0; + setOptions.mockClear(); +}); + +function localSession() { + const ydoc = new Y.Doc(); + awareness = new Awareness(ydoc); + return { + ydoc, + awareness, + provider: null, + synced: true, + serverSynced: true, + rejectedReason: null, + }; +} + +/** A provider double sharing the session's Awareness, as Live attaches. */ +const providerFor = (shared: Awareness) => + ({ + awareness: shared, + isSynced: true, + on() {}, + off() {}, + }) as unknown as HocuspocusProvider; + +async function render() { + await act(async () => { + root?.render(); + }); + // Tiptap creates the editor in an effect and emits `create` on a timer. + await act(() => new Promise((resolve) => setTimeout(resolve, 30))); +} + +async function mount() { + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); + await render(); +} + +describe("DocumentEditor without a provider", () => { + it("mounts an editable editor and opens no socket", async () => { + session = localSession(); + await mount(); + expect(container?.querySelector(".document-editor")).not.toBeNull(); + expect(window.__tiptap_editor?.isEditable).toBe(true); + // The connection chip (and its socket) belongs to a provider only. + expect(container?.querySelector("[data-collab-status]")).toBeNull(); + expect(socketRequests).toBe(0); + expect(socketsOpened).toBe(0); + }); + + it("keeps its extensions when a provider attaches", async () => { + const local = localSession(); + session = local; + await mount(); + const editor = window.__tiptap_editor; + const optionCalls = setOptions.mock.calls.length; + + session = { ...local, provider: providerFor(local.awareness) }; + await render(); + expect(window.__tiptap_editor).toBe(editor); + expect(setOptions.mock.calls.length).toBe(optionCalls); + // With a provider, the chip and its connection come back. + expect(socketRequests).toBeGreaterThan(0); + }); + + it("would rebuild them for a new Awareness (control)", async () => { + const local = localSession(); + session = local; + await mount(); + const optionCalls = setOptions.mock.calls.length; + + const other = new Awareness(local.ydoc); + session = { ...local, awareness: other }; + await render(); + other.destroy(); + expect(setOptions.mock.calls.length).toBeGreaterThan(optionCalls); + }); +}); diff --git a/tests/unit/editor-actions/shortcut-bindings.test.ts b/tests/unit/editor-actions/shortcut-bindings.test.ts index a390af10..9bc3faeb 100644 --- a/tests/unit/editor-actions/shortcut-bindings.test.ts +++ b/tests/unit/editor-actions/shortcut-bindings.test.ts @@ -8,7 +8,7 @@ */ import { afterEach, describe, expect, it } from "bun:test"; -import type { HocuspocusProvider } from "@hocuspocus/provider"; +import type { Awareness } from "y-protocols/awareness"; import * as Y from "yjs"; import type { buildDocumentEditorExtensions as BuildExtensions } from "@/components/document-editor/document-editor-config"; @@ -43,7 +43,9 @@ async function loadEditor(): Promise<{ const extensions = buildDocumentEditorExtensions({ documentId: "keys", ydoc: new Y.Doc(), - provider: {} as HocuspocusProvider, + awareness: {} as Awareness, + getProvider: () => null, + canWrite: () => true, onFoldChange() {}, onFilterChange() {}, onTocUpdate() {}, diff --git a/tests/unit/extensions/decoration-host.test.ts b/tests/unit/extensions/decoration-host.test.ts new file mode 100644 index 00000000..ab300a5a --- /dev/null +++ b/tests/unit/extensions/decoration-host.test.ts @@ -0,0 +1,86 @@ +import { afterEach, describe, expect, it } from "bun:test"; + +import { Editor } from "@tiptap/core"; +import { Decoration, DecorationSet } from "@tiptap/pm/view"; +import { StarterKit } from "@tiptap/starter-kit"; + +import { DecorationHost } from "@/extensions/decoration-host/decoration-host"; + +let editor: Editor | undefined; +afterEach(() => { + editor?.destroy(); + editor = undefined; +}); + +function create(layers: { name: string; map?: boolean }[]): Editor { + editor = new Editor({ + element: document.createElement("div"), + extensions: [ + StarterKit.configure({ undoRedo: false }), + DecorationHost.configure({ layers }), + ], + content: "

Hello world

", + }); + return editor; +} + +/** Highlights "world" (positions 7–12) in the current document. */ +const worldSet = (e: Editor) => + DecorationSet.create(e.state.doc, [ + Decoration.inline(7, 12, { class: "hit" }), + ]); + +/** The text under each drawn decoration. */ +const hits = (e: Editor) => + [...e.view.dom.querySelectorAll(".hit")].map((node) => node.textContent); + +describe("DecorationHost", () => { + it("adds one plugin per declared layer, none without", () => { + const count = (layers: { name: string }[]) => { + const e = new Editor({ + element: document.createElement("div"), + extensions: [DecorationHost.configure({ layers }), StarterKit], + }); + const plugins = e.state.plugins.length; + e.destroy(); + return plugins; + }; + expect(count([{ name: "a" }, { name: "b" }]) - count([])).toBe(2); + // The command is there for lazy layers; with none declared it is inert. + expect( + create([]).commands.setDecorationLayer("find", DecorationSet.empty), + ).toBe(true); + }); + + it("shows and clears a layer without touching the document or undo", () => { + const e = create([{ name: "find" }]); + const doc = e.state.doc; + e.commands.setDecorationLayer("find", worldSet(e)); + expect(hits(e)).toEqual(["world"]); + expect(e.state.doc).toBe(doc); + e.commands.setDecorationLayer("find", DecorationSet.empty); + expect(hits(e)).toEqual([]); + }); + + it("leaves other layers alone", () => { + const e = create([{ name: "find" }, { name: "comments", map: true }]); + e.commands.setDecorationLayer("comments", worldSet(e)); + e.commands.setDecorationLayer("find", worldSet(e)); + e.commands.setDecorationLayer("find", DecorationSet.empty); + expect(hits(e)).toEqual(["world"]); + }); + + it("clears a plain layer on a document change", () => { + const e = create([{ name: "find" }]); + e.commands.setDecorationLayer("find", worldSet(e)); + e.commands.insertContentAt(1, "Oh "); + expect(hits(e)).toEqual([]); + }); + + it("maps a map: true layer through a document change", () => { + const e = create([{ name: "comments", map: true }]); + e.commands.setDecorationLayer("comments", worldSet(e)); + e.commands.insertContentAt(1, "Oh "); + expect(hits(e)).toEqual(["world"]); + }); +}); diff --git a/tests/unit/extensions/write-gate.test.ts b/tests/unit/extensions/write-gate.test.ts new file mode 100644 index 00000000..811a94a7 --- /dev/null +++ b/tests/unit/extensions/write-gate.test.ts @@ -0,0 +1,203 @@ +import { afterEach, describe, expect, it } from "bun:test"; + +import type { HocuspocusProvider } from "@hocuspocus/provider"; +import { Editor, getSchema, type JSONContent } from "@tiptap/core"; +import { prosemirrorJSONToYDoc } from "@tiptap/y-tiptap"; +import { Awareness } from "y-protocols/awareness"; +import * as Y from "yjs"; + +import { buildDocumentEditorExtensions } from "@/components/document-editor/document-editor-config"; +import { headingFoldPluginKey } from "@/extensions/heading-fold"; + +const text = (value: string): JSONContent => ({ type: "text", text: value }); + +const heading = (level: number, value: string, id?: string): JSONContent => ({ + type: "heading", + attrs: id ? { level, id, "data-toc-id": id } : { level }, + content: [text(value)], +}); + +/** Unnamed headings: the outline names them when the editor is created. */ +const UNNAMED: JSONContent = { + type: "doc", + content: [heading(1, "Title"), heading(2, "Section")], +}; + +const NAMED: JSONContent = { + type: "doc", + content: [ + heading(1, "Title", "t"), + heading(2, "Section", "s"), + { type: "paragraph", content: [text("Body")] }, + ], +}; + +/** A provider stand-in: UniqueID only subscribes to "synced". */ +function fakeProvider() { + const listeners = new Map void>(); + // Like HocuspocusProvider's EventEmitter, `on` returns the provider. + const provider = { + on(event: string, fn: () => void) { + listeners.set(event, fn); + return provider; + }, + off: (event: string) => listeners.delete(event), + } as unknown as HocuspocusProvider; + return { provider, listeners, sync: () => listeners.get("synced")?.() }; +} + +interface OpenOptions { + canWrite?: () => boolean; + getProvider?: () => HocuspocusProvider | null; +} + +const extensionsFor = ( + ydoc: Y.Doc, + awareness: Awareness, + { canWrite = () => true, getProvider = () => null }: OpenOptions = {}, +) => + buildDocumentEditorExtensions({ + documentId: "write-gate", + ydoc, + awareness, + getProvider, + canWrite, + onFoldChange() {}, + onFilterChange() {}, + onTocUpdate() {}, + }); + +/** A Y.Doc holding `content` in the editor's fragment. */ +function seededDoc(content: JSONContent): Y.Doc { + const schema = getSchema(extensionsFor(new Y.Doc(), {} as Awareness)); + return prosemirrorJSONToYDoc(schema, content, "default"); +} + +let editor: Editor | undefined; +let awareness: Awareness | undefined; +afterEach(() => { + editor?.destroy(); + awareness?.destroy(); + editor = undefined; + awareness = undefined; +}); + +/** + * Opens the app's editor on `ydoc` and waits for `create` (Tiptap emits it + * on a timer); returns the Yjs updates it makes. + */ +async function open(ydoc: Y.Doc, options?: OpenOptions): Promise { + const updates: Uint8Array[] = []; + ydoc.on("update", (update: Uint8Array) => updates.push(update)); + awareness = new Awareness(ydoc); + editor = new Editor({ + element: document.createElement("div"), + extensions: extensionsFor(ydoc, awareness, options), + }); + await new Promise((resolve) => setTimeout(resolve, 20)); + return updates; +} + +const headingIds = () => { + const ids: unknown[] = []; + editor?.state.doc.forEach((node) => { + if (node.type.name === "heading") ids.push(node.attrs["data-toc-id"]); + }); + return ids; +}; + +const title = () => editor?.state.doc.firstChild?.textContent; + +describe("WriteGate", () => { + it("lets the opening writes through when writable", async () => { + await open(seededDoc(UNNAMED)); + // Control for the next test: the outline names both headings. + expect(headingIds().every((id) => typeof id === "string")).toBe(true); + }); + + it("blocks the opening writes when read-only", async () => { + const { provider, sync } = fakeProvider(); + const updates = await open(seededDoc(UNNAMED), { + canWrite: () => false, + getProvider: () => provider, + }); + // UniqueID's first-sync pass is gated too. + sync(); + expect(headingIds()).toEqual([null, null]); + expect(updates).toHaveLength(0); + // The content still renders from Yjs. + expect(editor?.state.doc.textContent).toBe("TitleSection"); + }); + + it("blocks local edits but not a collaborator's", async () => { + const ydoc = seededDoc(NAMED); + let writable = true; + const updates = await open(ydoc, { canWrite: () => writable }); + editor?.commands.insertContentAt(1, "My "); + expect(updates.length).toBeGreaterThan(0); + + writable = false; + const before = updates.length; + editor?.commands.insertContentAt(1, "Local "); + expect(updates.length).toBe(before); + expect(title()).toBe("My Title"); + + // A collaborator's change arrives through Yjs and is shown. + const remote = new Y.Doc(); + Y.applyUpdate(remote, Y.encodeStateAsUpdate(ydoc)); + const first = remote.getXmlFragment("default").get(0) as Y.XmlElement; + (first.get(0) as Y.XmlText).insert(0, "Remote "); + Y.applyUpdate( + ydoc, + Y.encodeStateAsUpdate(remote, Y.encodeStateVector(ydoc)), + ); + expect(title()).toBe("Remote My Title"); + }); + + it("lets meta-only transactions through", async () => { + await open(seededDoc(NAMED), { canWrite: () => false }); + // A fold is meta-only: it works on a read-only document. + editor?.commands.toggleFold("s"); + const folded = editor && headingFoldPluginKey.getState(editor.state); + expect([...(folded?.foldedIds ?? [])]).toEqual(["s"]); + }); +}); + +describe("no provider", () => { + it("opens and edits with the session's Awareness alone", async () => { + const ydoc = seededDoc(NAMED); + await open(ydoc); + editor?.commands.insertContentAt(1, "Local "); + expect(ydoc.getXmlFragment("default").toString()).toContain("Local Title"); + // The caret publishes this user on the session's Awareness. + editor?.commands.updateUser({ name: "Ada", color: "#000000" }); + expect(awareness?.getLocalState()?.user?.name).toBe("Ada"); + }); + + it("forwards UniqueID's wait for a sync to the provider of the moment", async () => { + let current: HocuspocusProvider | null = null; + const { provider, listeners } = fakeProvider(); + current = provider; + await open(seededDoc(UNNAMED), { getProvider: () => current }); + // As before this change: UniqueID waits on the real provider's sync. + expect(listeners.has("synced")).toBe(true); + listeners.get("synced")?.(); + expect(listeners.has("synced")).toBe(false); + }); + + it("hands back the provider from the caret's on (e2e helpers find it so)", async () => { + const { provider } = fakeProvider(); + let current: HocuspocusProvider | null = null; + await open(seededDoc(NAMED), { getProvider: () => current }); + const caret = editor?.extensionManager.extensions.find( + (extension) => extension.name === "collaborationCaret", + ); + const forward = caret?.options.provider as { + on: (event: string, fn: () => void) => unknown; + }; + const probe = () => {}; + expect(forward.on("probe", probe)).toBeUndefined(); + current = provider; + expect(forward.on("probe", probe)).toBe(provider); + }); +});