Skip to content

Commit

Permalink
Merge pull request #38 from otovo/feature/render-text-custom-mark
Browse files Browse the repository at this point in the history
bugfix: call custom mark render_text() on render
  • Loading branch information
Oleksandr Ivanov authored Mar 14, 2022
2 parents 5bf33f9 + e3ca1b1 commit 3a84cdd
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
14 changes: 13 additions & 1 deletion portabletext_html/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,19 @@ def _render_span(self, span: Span, block: Block) -> str:
marker_callable = block.marker_definitions.get(mark, DefaultMarkerDefinition)()
result += marker_callable.render_prefix(span, mark, block)

result += html.escape(span.text).replace('\n', '<br/>')
# to avoid rendering the text multiple times,
# only the first custom mark will be used
custom_mark_text_rendered = False
if sorted_marks:
for mark in sorted_marks:
if custom_mark_text_rendered or mark in prev_marks:
continue
marker_callable = block.marker_definitions.get(mark, DefaultMarkerDefinition)()
result += marker_callable.render_text(span, mark, block)
custom_mark_text_rendered = True

if not custom_mark_text_rendered:
result += html.escape(span.text).replace('\n', '<br/>')

for mark in reversed(sorted_marks):
if mark in next_marks:
Expand Down
2 changes: 1 addition & 1 deletion portabletext_html/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def _add_custom_marker_definitions(self) -> dict[str, Type[MarkerDefinition]]:
if definition['_type'] in self.marker_definitions:
marker = self.marker_definitions[definition['_type']]
marker_definitions[definition['_key']] = marker
del marker_definitions[definition['_type']]
# del marker_definitions[definition['_type']]
return marker_definitions

def get_node_siblings(self, node: Union[dict, Span]) -> Tuple[Optional[dict], Optional[dict]]:
Expand Down
8 changes: 7 additions & 1 deletion tests/test_marker_definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,14 @@ def render_prefix(cls: Type[MarkerDefinition], span: Span, marker: str, context:
else:
return super().render_prefix(span, marker, context)

@classmethod
def render_text(cls: Type[MarkerDefinition], span: Span, marker: str, context: Block) -> str:
marker_definition = next((md for md in context.markDefs if md['_key'] == marker), None)
condition = marker_definition.get('cloudCondition', '')
return span.text if not condition else ''

renderer = PortableTextRenderer(
{
blocks={
'_type': 'block',
'children': [{'_key': 'a1ph4', '_type': 'span', 'marks': ['some_id'], 'text': 'Sanity'}],
'markDefs': [{'_key': 'some_id', '_type': 'contractConditional', 'cloudCondition': False}],
Expand Down

0 comments on commit 3a84cdd

Please sign in to comment.