All files / json-crdt-extensions/peritext/slice PersistedSlice.ts

70.17% Statements 80/114
33.33% Branches 11/33
58.82% Functions 10/17
74.52% Lines 79/106

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 22058x 58x 58x 58x 58x   58x               58x 58x 58x 58x 58x                                   58x   15053x 15053x 15053x 15053x 15053x 15053x 15053x 15053x 15053x 15053x 15053x 15053x 15053x 15053x 15053x 15053x               29012x   29012x   29012x   29012x     29012x 29012x   29012x 29012x 29012x 29012x 29012x       568x       7933x                             4x 4x                   7933x 7933x 7933x 4x 4x   7933x 7920x 7920x 7920x 7920x 7920x   7933x 7909x 7909x   7933x 7933x   7924x     7924x   7933x       11632x       3x 3x                                           66916x         29012x     147006x 147006x 147006x 147006x 147006x 14486x 14486x 14486x 14486x 14486x 14486x   147006x                                                                
import {hasOwnProperty as hasOwnProp} from '@jsonjoy.com/util/lib/hasOwnProperty';
import {Point} from '../rga/Point';
import {Range} from '../rga/Range';
import {updateNode} from '../../../json-crdt/hash';
import {printTree} from 'tree-dump/lib/printTree';
import type {Anchor} from '../rga/constants';
import {
  SliceHeaderMask,
  SliceHeaderShift,
  SliceBehavior,
  SliceTupleIndex,
  SliceBehaviorName,
  SliceTypeName,
} from './constants';
import {CONST} from '../../../json-hash';
import {Timestamp} from '../../../json-crdt-patch/clock';
import {prettyOneLine} from '../../../json-pretty';
import {validateType} from './util';
import {s} from '../../../json-crdt-patch';
import type {VecNode} from '../../../json-crdt/nodes';
import type {ITimestampStruct} from '../../../json-crdt-patch/clock';
import type {ArrChunk} from '../../../json-crdt/nodes';
import type {MutableSlice, SliceView, SliceType, SliceUpdateParams} from './types';
import type {Stateful} from '../types';
import type {Printable} from 'tree-dump/lib/types';
import type {AbstractRga} from '../../../json-crdt/nodes/rga';
import type {Model} from '../../../json-crdt/model';
import type {Peritext} from '../Peritext';
import type {Slices} from './Slices';
 
/**
 * A persisted slice is a slice that is stored in a {@link Model}. It is used for
 * rich-text formatting and annotations.
 *
 * @todo Maybe rename to "saved", "stored", "mutable".
 */
export class PersistedSlice<T = string> extends Range<T> implements MutableSlice<T>, Stateful, Printable {
  public static deserialize<T>(model: Model, txt: Peritext<T>, chunk: ArrChunk, tuple: VecNode): PersistedSlice<T> {
    const header = +(tuple.get(0)!.view() as SliceView[0]);
    const id1 = tuple.get(1)!.view() as ITimestampStruct;
    const id2 = (tuple.get(2)!.view() || id1) as ITimestampStruct;
    const type = tuple.get(3)!.view() as SliceType;
    Iif (typeof header !== 'number') throw new Error('INVALID_HEADER');
    Iif (!(id1 instanceof Timestamp)) throw new Error('INVALID_ID');
    Iif (!(id2 instanceof Timestamp)) throw new Error('INVALID_ID');
    validateType(type);
    const anchor1: Anchor = (header & SliceHeaderMask.X1Anchor) >>> SliceHeaderShift.X1Anchor;
    const anchor2: Anchor = (header & SliceHeaderMask.X2Anchor) >>> SliceHeaderShift.X2Anchor;
    const behavior: SliceBehavior = (header & SliceHeaderMask.Behavior) >>> SliceHeaderShift.Behavior;
    const rga = txt.str as unknown as AbstractRga<T>;
    const p1 = new Point<T>(rga, id1, anchor1);
    const p2 = new Point<T>(rga, id2, anchor2);
    const slice = new PersistedSlice<T>(model, txt, chunk, tuple, behavior, type, p1, p2);
    return slice;
  }
 
  /** @todo Use API node here. */
  protected readonly rga: AbstractRga<T>;
 
  constructor(
    /** The `Model` where the slice is stored. */
    protected readonly model: Model,
    /** The Peritext context. */
    protected readonly txt: Peritext<T>,
    /** The `arr` chunk of `arr` where the slice is stored. */
    protected readonly chunk: ArrChunk,
    /** The `vec` node which stores the serialized contents of this slice. */
    public readonly tuple: VecNode,
    behavior: SliceBehavior,
    type: SliceType,
    public start: Point<T>,
    public end: Point<T>,
  ) {
    super(txt.str as unknown as AbstractRga<T>, start, end);
    this.rga = txt.str as unknown as AbstractRga<T>;
    this.id = chunk.id;
    this.behavior = behavior;
    this.type = type;
  }
 
  public isSplit(): boolean {
    return this.behavior === SliceBehavior.Marker;
  }
 
  protected tupleApi() {
    return this.model.api.wrap(this.tuple);
  }
 
  // ---------------------------------------------------------------- mutations
 
  public set(start: Point<T>, end: Point<T> = start): void {
    super.set(start, end);
    this.update({range: this});
  }
 
  /**
   * Expand range left and right to contain all invisible space: (1) tombstones,
   * (2) anchors of non-deleted adjacent chunks.
   */
  public expand(): void {
    super.expand();
    this.update({range: this});
  }
 
  // ------------------------------------------------------------- MutableSlice
 
  public readonly id: ITimestampStruct;
  public behavior: SliceBehavior;
  public type: SliceType;
 
  public update(params: SliceUpdateParams<T>): void {
    let updateHeader = false;
    const changes: [number, unknown][] = [];
    if (params.behavior !== undefined) {
      this.behavior = params.behavior;
      updateHeader = true;
    }
    if (params.range) {
      const range = params.range;
      updateHeader = true;
      changes.push([SliceTupleIndex.X1, s.con(range.start.id)], [SliceTupleIndex.X2, s.con(range.end.id)]);
      this.start = range.start;
      this.end = range.start === range.end ? range.end.clone() : range.end;
    }
    if (params.type !== undefined) {
      this.type = params.type;
      changes.push([SliceTupleIndex.Type, s.con(this.type)]);
    }
    if (hasOwnProp(params, 'data')) changes.push([SliceTupleIndex.Data, params.data]);
    if (updateHeader) {
      const header =
        (this.behavior << SliceHeaderShift.Behavior) +
        (this.start.anchor << SliceHeaderShift.X1Anchor) +
        (this.end.anchor << SliceHeaderShift.X2Anchor);
      changes.push([SliceTupleIndex.Header, s.con(header)]);
    }
    this.tupleApi().set(changes);
  }
 
  public data(): unknown | undefined {
    return this.tuple.get(SliceTupleIndex.Data)?.view();
  }
 
  public dataNode() {
    const node = this.tuple.get(SliceTupleIndex.Data);
    return node && this.model.api.wrap(node);
  }
 
  public getStore(): Slices<T> | undefined {
    const txt = this.txt;
    const sid = this.id.sid;
    let store = txt.savedSlices;
    Iif (sid === store.set.doc.clock.sid) return store;
    store = txt.localSlices;
    Iif (sid === store.set.doc.clock.sid) return store;
    store = txt.extraSlices;
    Iif (sid === store.set.doc.clock.sid) return store;
    return;
  }
 
  public del(): void {
    const store = this.getStore();
    Iif (!store) return;
    store.del(this.id);
  }
 
  public isDel(): boolean {
    return this.chunk.del;
  }
 
  // ----------------------------------------------------------------- Stateful
 
  public hash: number = 0;
 
  public refresh(): number {
    let state = CONST.START_STATE;
    state = updateNode(state, this.tuple);
    const changed = state !== this.hash;
    this.hash = state;
    if (changed) {
      const tuple = this.tuple;
      const slice = PersistedSlice.deserialize<T>(this.model, this.txt, this.chunk, tuple);
      this.behavior = slice.behavior;
      this.type = slice.type;
      this.start = slice.start;
      this.end = slice.end;
    }
    return this.hash;
  }
 
  // ---------------------------------------------------------------- Printable
 
  public toStringName(): string {
    Iif (typeof this.type === 'number' && Math.abs(this.type) <= 64 && SliceTypeName[this.type]) {
      return `slice [${SliceBehaviorName[this.behavior]}] <${SliceTypeName[this.type]}>`;
    }
    return `slice [${SliceBehaviorName[this.behavior]}] ${JSON.stringify(this.type)}`;
  }
 
  protected toStringHeaderName(): string {
    const data = this.data();
    const dataFormatted = data ? prettyOneLine(data) : '∅';
    const dataLengthBreakpoint = 32;
    const header = `${this.toStringName()} ${super.toString('', true)}, ${
      SliceBehaviorName[this.behavior]
    }, ${JSON.stringify(this.type)}${dataFormatted.length < dataLengthBreakpoint ? `, ${dataFormatted}` : ''}`;
    return header;
  }
 
  public toStringHeader(tab: string = ''): string {
    const data = this.data();
    const dataFormatted = data ? prettyOneLine(data) : '';
    const dataLengthBreakpoint = 32;
    return (
      this.toStringHeaderName() +
      printTree(tab, [dataFormatted.length < dataLengthBreakpoint ? null : (tab) => dataFormatted])
    );
  }
}