from __future__ import annotations

def register(app):
    @app.template_filter("truncate")
    def truncate(text, max_length=100):
        """
        Truncate text to max_length characters and add an ellipsis character (…)
        if it was longer.
        """
        if text is None:
            return ""

        text = str(text)

        if len(text) <= max_length:
            return text

        # Leave space for the ellipsis itself
        if max_length <= 1:
            return "…"

        return text[:max_length - 1] + "…"