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

77.77% Statements 105/135
43.75% Branches 21/48
69.56% Functions 16/23
81.1% Lines 103/127

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 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 28062x 62x 62x 62x 62x   62x                 62x 62x 62x 62x 62x 62x 62x                                                 62x   15705x 15705x 15705x 15705x 15705x 15705x 15705x 15705x 15705x 15705x 15705x 15705x 15705x 15705x 15705x 15705x               30196x   30196x   30196x   30196x     30196x 30196x   30196x 30196x 30196x 30196x 30196x       568x       10357x                             4x 4x                   108x 108x                           10321x 10321x 10321x 10321x 4x 4x   10321x 10321x 10248x 10248x 10248x 10248x   10321x 10297x 10297x   10321x 10321x   10252x     10252x   10321x       11907x       81x 81x       18x 18x 6x   18x                   30x                   18x 18x 18x 6x 6x 6x 12x       36x 36x 36x 36x                 36x 36x 36x       68639x         30196x     149011x 149011x 149011x 149011x 149011x 15138x 15138x 15138x 15138x 15138x 15138x   149011x                                                                
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,
  SliceStacking,
  SliceTupleIndex,
  SliceStackingName,
  SliceTypeName,
  SliceTypeCon,
} from './constants';
import {CONST} from '../../../json-hash/hash';
import {Timestamp} from '../../../json-crdt-patch/clock';
import {prettyOneLine} from '../../../json-pretty';
import {validateType} from './util';
import {s} from '../../../json-crdt-patch';
import {JsonCrdtDiff} from '../../../json-crdt-diff/JsonCrdtDiff';
import {type Model, ObjApi} from '../../../json-crdt/model';
import type {ObjNode, 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,
  SliceTypeSteps,
  SliceTypeStep,
  TypeTag,
} 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 {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 stacking: SliceStacking = (header & SliceHeaderMask.Stacking) >>> SliceHeaderShift.Stacking;
    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, stacking, 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,
    stacking: SliceStacking,
    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.stacking = stacking;
    this.type = type;
  }
 
  public isSplit(): boolean {
    return this.stacking === SliceStacking.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 stacking: SliceStacking;
  public type: SliceType;
 
  public typeSteps(): SliceTypeSteps {
    const type = this.type ?? SliceTypeCon.p;
    return Array.isArray(type) ? type : [type];
  }
 
  public tagStep(): SliceTypeStep {
    const type = this.type;
    return Array.isArray(type) ? type[type.length - 1] : type;
  }
 
  public tag(): TypeTag {
    const step = this.tagStep();
    return Array.isArray(step) ? step[0] : step;
  }
 
  public update(params: SliceUpdateParams<T>): void {
    let updateHeader = false;
    const changes: [number, unknown][] = [];
    const stacking = params.stacking;
    if (stacking !== undefined) {
      this.stacking = stacking;
      updateHeader = true;
    }
    const range = params.range;
    if (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.stacking << SliceHeaderShift.Stacking) +
        (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 dataAsObj(): ObjApi<ObjNode> {
    const node = this.dataNode();
    if (!(node instanceof ObjApi)) {
      this.tupleApi().set([[SliceTupleIndex.Data, s.obj({})]]);
    }
    return this.dataNode() as unknown as ObjApi<ObjNode>;
  }
 
  /**
   * Overwrites the data of this slice with the given data.
   *
   * @param data Data to set for this slice. The data can be any JSON value, but
   *     it is recommended to use an object.
   */
  public setData(data: unknown): void {
    this.tupleApi().set([[SliceTupleIndex.Data, s.jsonCon(data)]]);
  }
 
  /**
   * Merges object data into the slice's data using JSON CRDT diffing.
   *
   * @param data Data to merge into the slice. If the data is an object, it will be
   *     merged with the existing data of the slice using JSON CRDT diffing.
   */
  public mergeData(data: unknown): void {
    const {model} = this;
    const diff = new JsonCrdtDiff(model);
    if (this.dataNode() instanceof ObjApi && !!data && typeof data === 'object' && !Array.isArray(data)) {
      const dataNode = this.dataAsObj();
      const patch = diff.diff(dataNode.node, data);
      model.applyPatch(patch);
    } else this.setData(data);
  }
 
  public getStore(): Slices<T> | undefined {
    const txt = this.txt;
    const sid = this.id.sid;
    let store = txt.savedSlices;
    if (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.stacking = slice.stacking;
      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 [${SliceStackingName[this.stacking]}] <${SliceTypeName[this.type]}>`;
    }
    return `slice [${SliceStackingName[this.stacking]}] ${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)}, ${
      SliceStackingName[this.stacking]
    }, ${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])
    );
  }
}