All files / collaborative-str/src StrBinding.ts

37.65% Statements 61/162
16.47% Branches 14/85
33.33% Functions 6/18
40.97% Lines 59/144

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 2351x 1x 1x 1x                 1x 1x 3x 3x 3x 3x       3x                 3x 3x   3x 3x                                                       6x 6x 6x 6x 6x 4x 4x   2x 2x 2x 2x 8x 8x 8x 8x   2x 2x   3x 3x   3x 3x 3x       2x 2x 2x               3x                                                                                             3x                                                                                         3x 3x   3x                             3x 3x         3x   3x 3x 3x 3x 3x 3x 3x     3x 3x 3x 3x      
import {invokeFirstOnly} from './util';
import {Selection} from './Selection';
import {applyChange} from './util';
import {diff, diffEdit} from 'json-joy/lib/util/diff/str';
import type {CollaborativeStr, EditorFacade, SimpleChange} from './types';
 
const enum PATCH_OP_TYPE {
  DEL = -1,
  EQL = 0,
  INS = 1,
}
 
export class StrBinding {
  public static bind = (str: () => CollaborativeStr, editor: EditorFacade, polling?: boolean) => {
    const binding = new StrBinding(str, editor);
    binding.syncFromModel();
    binding.bind(polling);
    return binding.unbind;
  };
 
  protected readonly selection: Selection;
  protected readonly race = invokeFirstOnly();
 
  /**
   * Latest cached model view.
   * @readonly
   */
  public view: string;
 
  constructor(
    protected readonly str: () => CollaborativeStr,
    protected readonly editor: EditorFacade,
  ) {
    this.view = str().view();
    editor.selection = this.selection = new Selection();
  }
 
  // ---------------------------------------------------------------- Selection
 
  protected saveSelection() {
    const {editor, selection} = this;
    const str = this.str();
    if (!str) return;
    const [selectionStart, selectionEnd, selectionDirection] = editor.getSelection?.() || [-1, -1, 0];
    const {start, end} = selection;
    const now = Date.now();
    const tick = str.api.model.tick;
    // Return early to avoid excessive RGA queries.
    if (start === selectionStart && end === selectionEnd && (tick === selection.tick || now - selection.ts < 3000))
      return;
    selection.start = selectionStart;
    selection.end = selectionEnd;
    selection.dir = selectionDirection;
    selection.ts = now;
    selection.tick = tick;
    selection.startId = typeof selectionStart === 'number' ? (str.findId((selectionStart ?? 0) - 1) ?? null) : null;
    selection.endId = typeof selectionEnd === 'number' ? (str.findId((selectionEnd ?? 0) - 1) ?? null) : null;
  }
 
  // ----------------------------------------------------- Model-to-Editor sync
 
  public syncFromModel() {
    const editor = this.editor;
    const str = this.str();
    Iif (!str) return;
    const view = ((this.view = str.view()) as string | undefined) || '';
    if (editor.ins && editor.del) {
      const editorText = editor.get();
      if (view === editorText) return;
      // TODO: PERF: Construct `changes` from JSON CRDT Patches.
      const changes = diff(editorText, view);
      const changeLen = changes.length;
      let pos: number = 0;
      for (let i = 0; i < changeLen; i++) {
        const change = changes[i];
        const [type, text] = change;
        const len = text.length;
        switch (type as unknown as PATCH_OP_TYPE) {
          case PATCH_OP_TYPE.DEL:
            editor.del(pos, len);
            break;
          case PATCH_OP_TYPE.EQL:
            pos += len;
            break;
          case PATCH_OP_TYPE.INS:
            editor.ins(pos, text);
            pos += len;
            break;
        }
      }
    } else {
      editor.set(view);
      const {selection} = this;
      Iif (editor.setSelection) {
        const start = selection.startId ? str.findPos(selection.startId) + 1 : -1;
        const end = selection.endId ? str.findPos(selection.endId) + 1 : -1;
        editor.setSelection(start, end, selection.dir);
      }
    }
  }
 
  protected readonly onModelChange = () => {
    this.race(() => {
      this.syncFromModel();
      this.saveSelection();
    });
  };
 
  // ----------------------------------------------------- Editor-to-Model sync
 
  public syncFromEditor() {
    let view = this.view;
    const value = this.editor.get();
    if (value === view) return;
    const selection = this.selection;
    const caretPos: number | undefined = selection.start === selection.end ? (selection.start ?? undefined) : undefined;
    const changes = diffEdit(view, value, caretPos || 0);
    const changeLen = changes.length;
    const str = this.str();
    if (!str) return;
    str.api.transaction(() => {
      let pos: number = 0;
      for (let i = 0; i < changeLen; i++) {
        const change = changes[i];
        const [type, text] = change;
        switch (type as unknown as PATCH_OP_TYPE) {
          case PATCH_OP_TYPE.DEL: {
            view = applyChange(view, pos, text.length, '');
            str.del(pos, text.length);
            break;
          }
          case PATCH_OP_TYPE.EQL: {
            pos += text.length;
            break;
          }
          case PATCH_OP_TYPE.INS: {
            view = applyChange(view, pos, 0, text);
            str.ins(pos, text);
            pos += text.length;
            break;
          }
        }
      }
    });
    this.view = view;
    this.saveSelection();
  }
 
  private readonly onchange = (changes: SimpleChange[] | void, verify?: boolean) => {
    this.race(() => {
      // console.time('onchange');
      if (changes instanceof Array && changes.length > 0) {
        const str = this.str();
        if (!str) return;
        let applyChanges = true;
        if (verify) {
          let view = this.view;
          for (let i = 0; i < length; i++) {
            const change = changes[i];
            const [position, remove, insert] = change;
            view = applyChange(view, position, remove, insert);
          }
          const editor = this.editor;
          if ((editor.getLength && view.length !== editor.getLength()) || view !== editor.get()) applyChanges = false;
          else this.view = view;
        }
        if (applyChanges) {
          const length = changes.length;
          try {
            str.api.transaction(() => {
              let view = this.view;
              for (let i = 0; i < length; i++) {
                const change = changes[i];
                const [position, remove, insert] = change;
                view = applyChange(view, position, remove, insert);
                if (remove) str.del(position, remove);
                if (insert) str.ins(position, insert);
              }
              this.view = view;
            });
            this.saveSelection();
            // console.timeEnd('onchange');
            return;
          } catch {}
        }
      }
      this.syncFromEditor();
      // console.timeEnd('onchange');
    });
  };
 
  // ------------------------------------------------------------------ Polling
 
  public pollingInterval: number = 1000;
  private _p: number | null | unknown = null;
 
  private readonly pollChanges = () => {
    this._p = setTimeout(() => {
      this.race(() => {
        try {
          const view = this.view;
          const editor = this.editor;
          const needsSync = (editor.getLength ? view.length !== editor.getLength() : false) || view !== editor.get();
          if (needsSync) this.syncFromEditor();
        } catch {}
        if (this._p) this.pollChanges();
      });
    }, this.pollingInterval);
  };
 
  public stopPolling() {
    Iif (this._p) clearTimeout(this._p as any);
    this._p = null;
  }
 
  // ------------------------------------------------------------------ Binding
 
  private _s: (() => void) | null = null;
 
  public readonly bind = (polling?: boolean) => {
    this.syncFromModel();
    const editor = this.editor;
    editor.onchange = this.onchange;
    editor.onselection = () => this.saveSelection();
    Iif (polling) this.pollChanges();
    this._s = this.str().api.onChange.listen(this.onModelChange);
  };
 
  public readonly unbind = () => {
    this.stopPolling();
    this._s?.();
    this.editor.dispose?.();
  };
}