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

79.41% Statements 108/136
48.93% Branches 23/47
80% Functions 20/25
83.46% Lines 106/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 280 281 282 283 284 285 286 28765x 65x 65x 65x 65x   65x                 65x 65x 65x 65x 65x   65x 65x   65x                               65x   15851x 15851x 15851x 15851x 15851x 15851x 15851x 15851x 15851x 15851x 15851x 15851x 15851x 15851x 15851x               30462x   30462x   30462x   30462x   30462x 30462x   30462x 30462x 30462x 30462x       580x       10797x                                         4x 4x                 10761x 10761x 10761x 10761x 4x 4x   10761x 10761x 10654x 10654x 10654x 10654x   10761x 10737x   10761x 10761x   10658x     10658x   10761x       54x 54x 54x 54x                 54x 54x 54x       66381x           54743x       191x 191x 191x       120x       54552x       108x 108x           11094x       81x 81x       18x 18x 6x   18x                   30x                   18x 18x 18x 6x 6x 6x 12x         30462x     143731x 143731x 143731x 143731x 143731x 15284x 15284x 15284x 15284x 15284x   143731x                                                                  
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 {NodeBuilder, s} from '../../../json-crdt-patch';
import * as schema from './schema';
import {JsonCrdtDiff} from '../../../json-crdt-diff/JsonCrdtDiff';
import {type ArrApi, ConApi, type Model, type NodeApi, ObjApi, VecApi} from '../../../json-crdt/model';
import {ArrNode, ConNode, type ObjNode, type VecNode} from '../../../json-crdt/nodes';
import {NestedType} from './NestedType';
import type {ITimestampStruct} from '../../../json-crdt-patch/clock';
import type {ArrChunk, JsonNode} from '../../../json-crdt/nodes';
import type {MutableSlice, SliceView, SliceType, SliceUpdateParams, SliceTypeSteps, SliceTypeStep} 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;
    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');
    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, p1, p2);
    validateType(slice.type());
    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,
    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;
  }
 
  public isSplit(): boolean {
    return this.stacking === SliceStacking.Marker;
  }
 
  protected tupleApi() {
    return this.model.api.wrap(this.tuple);
  }
 
  // protected setType(schema: NodeBuilder): void {
  //   this.tupleApi().set([
  //     [SliceTupleIndex.Type, schema.type(type as SliceTypeSteps)],
  //   ]);
  // }
 
  // ---------------------------------------------------------------- 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});
  }
 
  /** -------------------------------------------------- {@link MutableSlice} */
 
  public readonly id: ITimestampStruct;
  public stacking: SliceStacking;
 
  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) {
      changes.push([SliceTupleIndex.Type, params.type instanceof NodeBuilder ? params.type : s.jsonCon(params.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 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;
  }
 
  // -------------------------------------------------- slice type manipulation
 
  public typeNode() {
    return this.tuple.get(SliceTupleIndex.Type);
  }
 
  public typeApi() {
    const node = this.typeNode();
    Iif (!node) return;
    return this.model.api.wrap(node);
  }
 
  public nestedType(): NestedType<T> {
    return new NestedType<T>(this);
  }
 
  public type(): SliceType {
    return this.typeNode()?.view() as SliceType;
  }
 
  public typeSteps(): SliceTypeSteps {
    const type = this.type() ?? SliceTypeCon.p;
    return Array.isArray(type) ? type : [type];
  }
 
  // -------------------------------------------------- slice data manipulation
 
  public data(): unknown | undefined {
    return this.tuple.get(SliceTupleIndex.Data)?.view();
  }
 
  public dataNode(): NodeApi<JsonNode<unknown>> | undefined {
    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);
  }
 
  /** ------------------------------------------------------ {@link 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.start = slice.start;
      this.end = slice.end;
    }
    return this.hash;
  }
 
  /** ----------------------------------------------------- {@link Printable} */
 
  public toStringName(): string {
    const type = this.type();
    Iif (typeof type === 'number' && Math.abs(type) <= 64 && SliceTypeName[type]) {
      return `slice [${SliceStackingName[this.stacking]}] <${SliceTypeName[type]}>`;
    }
    return `slice [${SliceStackingName[this.stacking]}] ${JSON.stringify(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])
    );
  }
}