Skip to content

Commit

Permalink
Shorten URLs in CSV preview
Browse files Browse the repository at this point in the history
(links still work)
  • Loading branch information
stijn-uva committed Nov 29, 2024
1 parent 1396bb5 commit cb2ef69
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
34 changes: 32 additions & 2 deletions webtool/lib/template_filters.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import urllib.parse
import datetime
from math import floor

import markdown
import json
import ural
Expand Down Expand Up @@ -120,7 +122,7 @@ def _jinja2_filter_httpquery(data):
return ""

@app.template_filter("add_ahref")
def _jinja2_filter_add_ahref(content):
def _jinja2_filter_add_ahref(content, ellipsiate=0):
"""
Add HTML links to text
Expand All @@ -135,7 +137,11 @@ def _jinja2_filter_add_ahref(content):
return content

for link in set(ural.urls_from_text(str(content))):
content = content.replace(link, f'<a href="{link.replace("<", "%3C").replace(">", "%3E").replace(chr(34), "%22")}" rel="external">{link}</a>')
if ellipsiate > 0:
link_text = _jinja2_filter_ellipsiate(link, ellipsiate, True, "[&hellip;]")
else:
link_text = link
content = content.replace(link, f'<a href="{link.replace("<", "%3C").replace(">", "%3E").replace(chr(34), "%22")}" rel="external">{link_text}</a>')

return content

Expand Down Expand Up @@ -200,6 +206,30 @@ def _jinja2_filter_extension_to_noun(ext):
else:
return "item"

@app.template_filter("ellipsiate")
def _jinja2_filter_ellipsiate(text, length, inside=False, ellipsis_str="&hellip;"):
if len(text) <= length:
return text

elif not inside:
return text[:length] + ellipsis_str

else:
# two cases: URLs and normal text
# for URLs, try to only ellipsiate after the domain name
# this makes the URLs easier to read when shortened
if ural.is_url(text):
pre_part = "/".join(text.split("/")[:3])
if len(pre_part) < length - 6: # kind of arbitrary
before = len(pre_part) + 1
else:
before = floor(length / 2)
else:
before = floor(length / 2)

after = len(text) - before
return text[:before] + ellipsis_str + text[after:]

@app.template_filter('4chan_image')
def _jinja2_filter_4chan_image(image_4chan, post_id, board, image_md5):

Expand Down
2 changes: 1 addition & 1 deletion webtool/templates/preview/csv.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
{% endif %}
{% endif %}
<t{% if outer_loop.index == 1 %}h{% else %}d{% endif %}>
{{ cell|e|add_ahref|safe }}
{{ cell|e|add_ahref(ellipsiate=50)|safe }}
</t{% if outer_loop.index == 1 %}h{% else %}d{% endif %}>
{% endfor %}
</tr>
Expand Down

0 comments on commit cb2ef69

Please sign in to comment.