|
| 1 | +from typing import OrderedDict |
| 2 | + |
| 3 | +from jsondoc.models.block.base import BlockBase |
| 4 | +from jsondoc.models.page import Page |
| 5 | + |
| 6 | + |
| 7 | +def extract_blocks( |
| 8 | + input_obj: Page | BlockBase | list[BlockBase], |
| 9 | +) -> dict[str, BlockBase]: |
| 10 | + """ |
| 11 | + Creates a mapping of block IDs to Block objects from various input types. |
| 12 | +
|
| 13 | + Args: |
| 14 | + input_obj: Can be either a Page object, a single Block object, or a list of Block objects |
| 15 | +
|
| 16 | + Returns: |
| 17 | + A dictionary mapping block IDs (strings) to their corresponding Block objects |
| 18 | + """ |
| 19 | + block_map: dict[str, BlockBase] = OrderedDict() |
| 20 | + |
| 21 | + # Handle Page input |
| 22 | + if isinstance(input_obj, Page): |
| 23 | + # Process all blocks in the page |
| 24 | + for block in input_obj.children: |
| 25 | + _process_block_and_children(block, block_map) |
| 26 | + |
| 27 | + # Handle single Block input |
| 28 | + elif isinstance(input_obj, BlockBase): |
| 29 | + _process_block_and_children(input_obj, block_map) |
| 30 | + |
| 31 | + # Handle list of Blocks input |
| 32 | + elif isinstance(input_obj, list): |
| 33 | + for block in input_obj: |
| 34 | + if isinstance(block, BlockBase): |
| 35 | + _process_block_and_children(block, block_map) |
| 36 | + |
| 37 | + return block_map |
| 38 | + |
| 39 | + |
| 40 | +def _process_block_and_children( |
| 41 | + block: BlockBase, block_map: dict[str, BlockBase] |
| 42 | +) -> None: |
| 43 | + """ |
| 44 | + Helper function to process a block and its children recursively, adding them to the block map. |
| 45 | +
|
| 46 | + Args: |
| 47 | + block: The block to process |
| 48 | + block_map: The dictionary mapping block IDs to Block objects |
| 49 | + """ |
| 50 | + # Add the current block to the map |
| 51 | + block_map[block.id] = block |
| 52 | + |
| 53 | + # Process children recursively if they exist |
| 54 | + if hasattr(block, "children") and block.children: |
| 55 | + for child in block.children: |
| 56 | + _process_block_and_children(child, block_map) |
0 commit comments