diff --git a/main/utils.py b/main/utils.py index fdfd60f3f..98f318d04 100644 --- a/main/utils.py +++ b/main/utils.py @@ -4,7 +4,7 @@ import re from enum import Flag, auto from pathlib import Path -from typing import Tuple +from typing import Optional, Tuple from uuid import UUID, uuid4 from django.http import HttpRequest @@ -109,3 +109,11 @@ def valid_key(key: str, request: HttpRequest) -> bool: digest = hmac.new(key.encode("utf-8"), request.body, hashlib.sha1).hexdigest() sig_parts = request.headers["X-Hub-Signature"].split("=", 1) return hmac.compare_digest(sig_parts[1], digest) + + +def truncate_words(content: str, length: int, suffix: Optional[str] = "...") -> str: + """Truncate text to < length chars, keeping words intact""" + if len(content) <= length: + return content + else: + return content[: (length - len(suffix))].rsplit(" ", 1)[0] + suffix diff --git a/main/utils_test.py b/main/utils_test.py index 6f8d7dbcc..9b439fd03 100644 --- a/main/utils_test.py +++ b/main/utils_test.py @@ -7,6 +7,7 @@ get_file_extension, is_valid_uuid, remove_trailing_slashes, + truncate_words, valid_key, ) @@ -95,3 +96,11 @@ def test_valid_key(mocker, key, is_valid): headers={"X-Hub-Signature": "sha1=6a4e7673fa9c3afbb2860ae03ac2082958313a9c"}, ) assert valid_key(key, mock_request) is is_valid + + +@pytest.mark.parametrize( + "text, truncated", [["Hello world", "Hello___"], ["HelloWorld", "HelloW___"]] +) +def test_truncate_words(text, truncated): + """ truncate_words returns expected result""" + assert truncate_words(text, 9, suffix="___") == truncated diff --git a/static/js/components/PublishDrawer.tsx b/static/js/components/PublishDrawer.tsx index 941009452..2987ab5c0 100644 --- a/static/js/components/PublishDrawer.tsx +++ b/static/js/components/PublishDrawer.tsx @@ -149,8 +149,7 @@ export default function PublishDrawer(props: Props): JSX.Element { {website.content_warnings && !isEmpty(website.content_warnings) ? (
- This site is missing information that could affect publishing - output. + This site has issues that could affect publishing output.