Skip to content

Commit

Permalink
Simplify transforming links to widgets
Browse files Browse the repository at this point in the history
  • Loading branch information
ihabunek committed Nov 4, 2023
1 parent 199a966 commit bc4c54f
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions toot/tui/richtext.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
from urwid.util import decompose_tagmarkup


# Matches anchor titles with an ETX separator followed by href
ANCHOR_PATTERN = re.compile(r"(^.+)\x03(.+$)")


class ContentParser:
def __init__(self):
self.palette_names = []
Expand Down Expand Up @@ -102,27 +106,27 @@ def text_to_widget(self, attr, markup) -> urwid.Widget:
if not has_urwidgets:
return urwid.Text((attr, markup))

TRANSFORM = {
# convert http[s] URLs to Hyperlink widgets for nesting in a TextEmbed widget
re.compile(r"(^.+)\x03(.+$)"): lambda g: (
len(g[1]),
urwid.Filler(Hyperlink(g[2], anchor_attr, g[1])),
),
}
markup_list = []

# Convert http[s] URLs to Hyperlink widgets for nesting in a TextEmbed widget
def _groups_to_widget(groups):
return (
len(groups[1]),
urwid.Filler(Hyperlink(groups[2], anchor_attr, groups[1])),
)

for run in markup:
if isinstance(run, tuple):
txt, attr_list = decompose_tagmarkup(run)
# find anchor titles with an ETX separator followed by href
m = re.match(r"(^.+)\x03(.+$)", txt)

m = ANCHOR_PATTERN.match(txt)
if m:
anchor_attr = self.get_best_anchor_attr(attr_list)
markup_list.append(
parse_text(
txt,
TRANSFORM,
lambda pattern, groups, span: TRANSFORM[pattern](groups),
[ANCHOR_PATTERN],
lambda pattern, groups, span: _groups_to_widget(groups),
)
)
else:
Expand Down

0 comments on commit bc4c54f

Please sign in to comment.