All files / json-crdt-extensions/peritext/editor EditorSlices.ts

100% Statements 22/22
50% Branches 1/2
100% Functions 12/12
100% Lines 19/19

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 5057x               57x   9849x 9849x       1611x 1611x 1611x 1611x   1611x       178x       553x       16x       864x 864x 864x 864x 864x 864x         613x      
import {PersistedSlice} from '../slice/PersistedSlice';
import type {Peritext} from '../Peritext';
import type {SliceType} from '../slice/types';
import type {MarkerSlice} from '../slice/MarkerSlice';
import type {Slices} from '../slice/Slices';
import type {ITimestampStruct} from '../../../json-crdt-patch';
import type {Cursor} from './Cursor';
 
export class EditorSlices<T = string> {
  constructor(
    protected readonly txt: Peritext<T>,
    public readonly slices: Slices<T>,
  ) {}
 
  protected insAtCursors<S extends PersistedSlice<T>>(callback: (cursor: Cursor<T>) => S): S[] {
    const slices: S[] = [];
    this.txt.editor.forCursor((cursor) => {
      const slice = callback(cursor);
      slices.push(slice);
    });
    return slices;
  }
 
  public insStack(type: SliceType, data?: unknown | ITimestampStruct): PersistedSlice<T>[] {
    return this.insAtCursors((cursor) => this.slices.insStack(cursor.range(), type, data));
  }
 
  public insOverwrite(type: SliceType, data?: unknown | ITimestampStruct): PersistedSlice<T>[] {
    return this.insAtCursors((cursor) => this.slices.insOverwrite(cursor.range(), type, data));
  }
 
  public insErase(type: SliceType, data?: unknown | ITimestampStruct): PersistedSlice<T>[] {
    return this.insAtCursors((cursor) => this.slices.insErase(cursor.range(), type, data));
  }
 
  public insMarker(type: SliceType, data?: unknown, separator?: string): MarkerSlice<T>[] {
    return this.insAtCursors((cursor) => {
      this.txt.editor.collapseCursor(cursor);
      const after = cursor.start.clone();
      after.refAfter();
      const marker = this.slices.insMarkerAfter(after.id, type, data, separator);
      return marker;
    });
  }
 
  public del(sliceOrId: PersistedSlice<T> | ITimestampStruct): void {
    this.slices.del(sliceOrId instanceof PersistedSlice ? sliceOrId.id : sliceOrId);
  }
}