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

65.38% Statements 17/26
25% Branches 2/8
25% Functions 2/8
61.9% Lines 13/21

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 5757x 57x                   57x   120x 204x 120x           289x 289x 289x 289x 649x 649x   289x                                                        
import {printTree} from 'tree-dump/lib/printTree';
import {Block} from './Block';
import type {Path} from '@jsonjoy.com/json-pointer';
import type {PeritextMlAttributes, PeritextMlElement} from './types';
 
export interface IBlock<Attr = unknown> {
  readonly path: Path;
  readonly attr?: Attr;
  readonly parent: IBlock | null;
}
 
export class LeafBlock<Attr = unknown> extends Block<Attr> {
  public text(): string {
    let str = '';
    for (let iterator = this.texts0(), inline = iterator(); inline; inline = iterator()) str += inline.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];
    for (const inline of this.texts()) {
      const child = inline.toJson();
      if (child) node.push(child);
    }
    return node;
  }
 
  // ---------------------------------------------------------------- Printable
  public toStringName(): string {
    return 'LeafBlock';
  }
 
  public toString(tab: string = ''): string {
    const header = this.toStringHeader();
    const texts = [...this.texts()];
    const hasSlices = !!texts.length;
    return (
      header +
      printTree(tab, [
        this.marker ? (tab) => this.marker!.toString(tab) : null,
        !hasSlices
          ? null
          : (tab) =>
              'nodes' +
              printTree(
                tab,
                texts.map((inline) => (tab) => inline.toString(tab)),
              ),
      ])
    );
  }
}