a tool for shared writing and social publishing
1import type { Block } from "components/Blocks/Block"; 2 3export function parseBlocksToList(blocks: Block[]) { 4 let parsed: ParsedBlocks = []; 5 for (let i = 0; i < blocks.length; i++) { 6 let b = blocks[i]; 7 if (!b.listData) parsed.push({ type: "block", block: b }); 8 else { 9 let previousBlock = parsed[parsed.length - 1]; 10 if ( 11 !previousBlock || 12 previousBlock.type !== "list" || 13 previousBlock.depth > b.listData.depth 14 ) 15 parsed.push({ 16 type: "list", 17 depth: b.listData.depth, 18 children: [ 19 { 20 type: "list", 21 block: b, 22 depth: b.listData.depth, 23 children: [], 24 }, 25 ], 26 }); 27 else { 28 let depth = b.listData.depth; 29 if (depth === previousBlock.depth) 30 previousBlock.children.push({ 31 type: "list", 32 block: b, 33 depth: b.listData.depth, 34 children: [], 35 }); 36 else { 37 let parent = 38 previousBlock.children[previousBlock.children.length - 1]; 39 while (depth > 1) { 40 if ( 41 parent.children[parent.children.length - 1] && 42 parent.children[parent.children.length - 1].depth < 43 b.listData.depth 44 ) { 45 parent = parent.children[parent.children.length - 1]; 46 } 47 depth -= 1; 48 } 49 parent.children.push({ 50 type: "list", 51 block: b, 52 depth: b.listData.depth, 53 children: [], 54 }); 55 } 56 } 57 } 58 } 59 return parsed; 60} 61 62type ParsedBlocks = Array< 63 | { type: "block"; block: Block } 64 | { type: "list"; depth: number; children: List[] } 65>; 66 67export type List = { 68 type: "list"; 69 block: Block; 70 depth: number; 71 children: List[]; 72};