Skip to content

Commit

Permalink
Make target block search recursive
Browse files Browse the repository at this point in the history
  • Loading branch information
notmatthancock committed Jul 30, 2024
1 parent c56fdd7 commit 08f29d0
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 14 deletions.
42 changes: 30 additions & 12 deletions n2y/plugins/internallinks.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,32 @@ def is_internal_link(href: typing.Optional[str], notion_id: str) -> bool:
return href is not None and href.startswith(f"/{notion_id.replace('-', '')}")


def find_target_block(page: Page, target_id: str) -> Block:
page_block: ChildPageBlock = page.block
if page_block is None:
raise ValueError("Page.block is None")
def find_target_block(block: Block, target_id: str) -> Block:
"""Recursively search for a block with a given ID"""
if block.notion_id == target_id:
return block
if block.children is None:
return None
for child in block.children:
if isinstance(child, Block):
target = find_target_block(child, target_id)
if target is not None:
return target
return None

try:
return next(
child for child in page_block.children if child.notion_id == target_id
)
except StopIteration:
logger.error(f"Page missing block with target id '{target_id}'")
raise

# def find_target_block(page: Page, target_id: str) -> Block:
# page_block: ChildPageBlock = page.block
# if page_block is None:
# raise ValueError("Page.block is None")

# try:
# return next(
# child for child in page_block.children if child.notion_id == target_id
# )
# except StopIteration:
# logger.error(f"Page missing block with target id '{target_id}'")
# raise


class NotionInternalLink(TextRichText):
Expand All @@ -64,7 +78,11 @@ def to_pandoc(self):
)
return super().to_pandoc()

target_block = find_target_block(self.block.page, target_id)
target_block = find_target_block(self.block.page.block, target_id)
if target_block is None:
logger.error(f"Internal link target block not found: {target_id}")
# Fallback to default behavior for TextRichText conversion
return super().to_pandoc()
header_id = header_id_from_text(target_block.rich_text.to_plain_text())
self.href = f"#{header_id}"
return super().to_pandoc()
Expand Down
4 changes: 2 additions & 2 deletions tests/test_plugin_internallinks.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ def mock_page_with_link_to_header(

def test_find_target_block():
page, heading, paragraph = mock_page_with_link_to_header()
assert find_target_block(page, target_id=heading.notion_id) is heading
assert find_target_block(page, target_id=paragraph.notion_id) is paragraph
assert find_target_block(page.block, target_id=heading.notion_id) is heading
assert find_target_block(page.block, target_id=paragraph.notion_id) is paragraph


def test_internal_link_to_pandoc():
Expand Down

0 comments on commit 08f29d0

Please sign in to comment.