92 lines · 3.1 KB
import * as vscode from "vscode";
import type * as Y from "yjs";
import type { RoomClient } from "./room-client";

const LOCAL = "vscode-local";

/**
 * Two-way binding between one VS Code TextDocument and its Y.Text. Local edits become Yjs ops; remote
 * ops become WorkspaceEdits. If an interleaving ever leaves the two out of step, the document is
 * re-synced from the shared text, which is the source of truth.
 */
export class DocumentBinding implements vscode.Disposable {
  private applying = 0;
  private readonly observer: (event: Y.YTextEvent, transaction: Y.Transaction) => void;
  private chain: Promise<void> = Promise.resolve();
  private pending = false;
  private readonly text: Y.Text;

  constructor(
    private readonly room: RoomClient,
    readonly document: vscode.TextDocument,
    readonly path: string,
  ) {
    this.text = room.text(path);
    this.observer = (_event, transaction) => {
      if (transaction.origin === LOCAL) return;
      this.queueRemote();
    };
    this.text.observe(this.observer);
    if (document.getText() !== this.text.toString()) this.queueRemote();
  }

  onLocalChange(event: vscode.TextDocumentChangeEvent): void {
    if (this.applying > 0 || event.contentChanges.length === 0) return;
    if (!this.room.writable) return this.queueRemote();
    const changes = [...event.contentChanges].sort((left, right) => right.rangeOffset - left.rangeOffset);
    this.room.doc.transact(() => {
      for (const change of changes) {
        if (change.rangeLength > 0) this.text.delete(change.rangeOffset, change.rangeLength);
        if (change.text) this.text.insert(change.rangeOffset, change.text);