All files / json-crdt-extensions/peritext/__tests__ render.ts

100% Statements 34/34
75% Branches 6/8
100% Functions 6/6
100% Lines 30/30

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    5x 5x   5x 513x 513x 513x 513x 513x     5x 336x 336x 336x 336x 336x     5x 190x 190x 190x 190x 513x   190x     5x 146x 146x 146x 190x   146x     5x 336x 146x    
import type {Block} from '../block/Block';
import type {Inline} from '../block/Inline';
import {LeafBlock} from '../block/LeafBlock';
import {stringify} from '../../../json-text/stringify';
 
const renderInline = (inline: Inline, tab: string): string => {
  const text = stringify(inline.text());
  const attr: any = {};
  const attributes = inline.attr();
  for (const key in attributes) attr[key] = attributes[key].map((a) => a.slice.data());
  return `${tab}${text} ${stringify(attr)}\n`;
};
 
const renderBlockHeader = (block: Block, tab: string, hash?: boolean): string => {
  const attr = block.attr();
  const attrStr = attr ? ' ' + stringify(attr) : '';
  const tag = `<${block.tag()}>`;
  const hashStr = hash ? ` #${block.hash.toString(36).slice(-3)}` : '';
  return tab + tag + attrStr + hashStr + '\n';
};
 
const renderLeafBlock = (block: LeafBlock, tab: string = '', hash?: boolean): string => {
  let str = '';
  str += renderBlockHeader(block, tab, hash);
  const texts = block.texts();
  for (const inline of texts) {
    str += renderInline(inline, tab + '  ');
  }
  return str;
};
 
const renderBlock = (block: Block, tab: string, hash?: boolean): string => {
  let str = '';
  str += renderBlockHeader(block, tab, hash);
  for (const b of block.children) {
    str += render(b, tab + '  ', hash);
  }
  return str;
};
 
export const render = (block: Block, tab: string = '', hash?: boolean): string => {
  if (block instanceof LeafBlock) return renderLeafBlock(block, tab, hash);
  else return renderBlock(block, tab, hash);
};