All files / json-crdt-extensions/peritext/block Block.ts

80.15% Statements 105/131
70% Branches 28/40
54.16% Functions 13/24
82.3% Lines 93/113

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 22157x 57x 57x 57x 57x 57x 57x                                 57x 6139x   6139x     6139x 6139x 6139x 6139x 6139x   6139x                           783x 783x 783x       783x               8x 8x 8x 8x 8x 28x 4x 4x   24x 24x 24x 18x 2x 2x   16x         4x       878x 878x 878x 878x 878x 3627x 2677x 2677x 2677x 2153x 2153x               878x 878x 878x 878x 878x 878x 878x 878x 878x 878x 2959x 2749x 2749x 2749x 2099x 2099x 2099x 2099x 878x 878x 878x 302x 302x     2099x 210x 210x   2099x               758x                           157x 157x 157x 157x 157x 289x 157x         6139x     4541x 4541x 4541x 4541x 4541x 781x 781x   3760x   4541x 4541x                                                                            
import {printTree} from 'tree-dump/lib/printTree';
import {CONST, updateJson, updateNum} from '../../../json-hash';
import {MarkerOverlayPoint} from '../overlay/MarkerOverlayPoint';
import {UndefEndIter, type UndefIterator} from '../../../util/iterator';
import {Inline} from './Inline';
import {formatType} from '../slice/util';
import {Range} from '../rga/Range';
import type {Point} from '../rga/Point';
import type {OverlayPoint} from '../overlay/OverlayPoint';
import type {Path} from '@jsonjoy.com/json-pointer';
import type {Printable} from 'tree-dump';
import type {Peritext} from '../Peritext';
import type {Stateful} from '../types';
import type {OverlayTuple} from '../overlay/types';
import type {PeritextMlAttributes, PeritextMlElement} from './types';
 
export interface IBlock {
  readonly path: Path;
  readonly parent: IBlock | null;
}
 
type T = string;
 
export class Block<Attr = unknown> extends Range implements IBlock, Printable, Stateful {
  public parent: Block | null = null;
 
  public children: Block[] = [];
 
  constructor(
    public readonly txt: Peritext,
    public readonly path: Path,
    public readonly marker: MarkerOverlayPoint | undefined,
    public start: Point,
    public end: Point,
  ) {
    super(txt.str, start, end);
  }
 
  /**
   * @returns Stable unique identifier within a list of blocks. Used for React
   * or other rendering library keys.
   */
  public key(): number | string {
    Iif (!this.marker) return this.tag();
    const id = this.marker.id;
    return id.sid.toString(36) + id.time.toString(36);
  }
 
  public tag(): number | string {
    const path = this.path;
    const length = path.length;
    return length ? path[length - 1] : '';
  }
 
  public attr(): Attr | undefined {
    return this.marker?.data() as Attr | undefined;
  }
 
  /**
   * Iterate through all overlay points of this block, until the next marker
   * (regardless if that marker is a child or not).
   */
  public points0(withMarker: boolean = false): UndefIterator<OverlayPoint<T>> {
    const txt = this.txt;
    const overlay = txt.overlay;
    const iterator = overlay.points0(this.marker);
    let closed = false;
    return () => {
      if (withMarker) {
        withMarker = false;
        return this.marker ?? overlay.START;
      }
      Iif (closed) return;
      const point = iterator();
      if (!point) return;
      if (point instanceof MarkerOverlayPoint) {
        closed = true;
        return;
      }
      return point;
    };
  }
 
  public points(withMarker?: boolean): IterableIterator<OverlayPoint<T>> {
    return new UndefEndIter(this.points0(withMarker));
  }
 
  protected tuples0(): UndefIterator<OverlayTuple<T>> {
    const overlay = this.txt.overlay;
    const marker = this.marker;
    const iterator = overlay.tuples0(marker);
    let closed = false;
    return () => {
      if (closed) return;
      let pair = iterator();
      while (!marker && pair && pair[1] && pair[1].cmpSpatial(this.start) < 0) pair = iterator();
      if (!pair) return (closed = true), void 0;
      if (!pair[1] || pair[1] instanceof MarkerOverlayPoint) closed = true;
      return pair;
    };
  }
 
  /**
   * @todo Consider moving inline-related methods to {@link LeafBlock}.
   */
  public texts0(): UndefIterator<Inline> {
    const txt = this.txt;
    const iterator = this.tuples0();
    const start = this.start;
    const end = this.end;
    const startIsMarker = txt.overlay.isMarker(start.id);
    const endIsMarker = txt.overlay.isMarker(end.id);
    let isFirst = true;
    let next = iterator();
    let closed = false;
    return () => {
      if (closed) return;
      const pair = next;
      next = iterator();
      if (!pair) return;
      const [overlayPoint1, overlayPoint2] = pair;
      let point1: Point = overlayPoint1;
      let point2: Point = overlayPoint2;
      if (isFirst) {
        isFirst = false;
        if (start.cmpSpatial(overlayPoint1) > 0) point1 = start;
        if (startIsMarker) {
          point1 = point1.clone();
          point1.step(1);
        }
      }
      if (!endIsMarker && end.cmpSpatial(overlayPoint2) < 0) {
        closed = true;
        point2 = end;
      }
      return new Inline(txt, overlayPoint1, overlayPoint2, point1, point2);
    };
  }
 
  /**
   * @todo Consider moving inline-related methods to {@link LeafBlock}.
   */
  public texts(): IterableIterator<Inline> {
    return new UndefEndIter(this.texts0());
  }
 
  public text(): string {
    let str = '';
    const children = this.children;
    const length = children.length;
    for (let i = 0; i < length; i++) str += children[i].text();
    return str;
  }
 
  // ------------------------------------------------------------------- export
 
  public toJson(): PeritextMlElement {
    const data = this.attr();
    const attr: PeritextMlAttributes | null = data !== void 0 ? {data} : null;
    const node: PeritextMlElement = [this.tag(), attr];
    const children = this.children;
    const length = children.length;
    for (let i = 0; i < length; i++) node.push(children[i].toJson());
    return node;
  }
 
  // ----------------------------------------------------------------- Stateful
 
  public hash: number = 0;
 
  public refresh(): number {
    const {path, children} = this;
    let state = CONST.START_STATE;
    state = updateJson(state, path);
    const marker = this.marker;
    if (marker) {
      state = updateNum(state, marker.marker.refresh());
      state = updateNum(state, marker.textHash);
    } else {
      state = updateNum(state, this.txt.overlay.leadingTextHash);
    }
    for (let i = 0; i < children.length; i++) state = updateNum(state, children[i].refresh());
    return (this.hash = state);
  }
 
  // ---------------------------------------------------------------- Printable
 
  public toStringName(): string {
    return 'Block';
  }
 
  protected toStringHeader(): string {
    const hash = `#${this.hash.toString(36).slice(-4)}`;
    const tag = this.path.map((step) => formatType(step)).join('.');
    const header = `${super.toString('', true)} ${hash} ${tag} `;
    return header;
  }
 
  public toString(tab: string = ''): string {
    const header = this.toStringHeader();
    const hasChildren = !!this.children.length;
    return (
      header +
      printTree(tab, [
        this.marker ? (tab) => this.marker!.toString(tab) : null,
        this.marker && hasChildren ? () => '' : null,
        hasChildren
          ? (tab) =>
              'children' +
              printTree(
                tab,
                this.children.map(
                  (child, i) => (tab) => `${i + 1}. ` + child.toString(tab + '  ' + ' '.repeat(String(i + 1).length)),
                ),
              )
          : null,
      ])
    );
  }
}