changeset 1583:9865013da86c

browser(template): add `bare_jid` and fix `date_fmt`
author Goffi <goffi@goffi.org>
date Tue, 28 Nov 2023 17:54:30 +0100
parents f52b89365002
children eab815e48795
files libervia/web/pages/_browser/template.py
diffstat 1 files changed, 23 insertions(+), 22 deletions(-) [+]
line wrap: on
line diff
--- a/libervia/web/pages/_browser/template.py	Tue Nov 28 17:53:56 2023 +0100
+++ b/libervia/web/pages/_browser/template.py	Tue Nov 28 17:54:30 2023 +0100
@@ -3,6 +3,7 @@
 from js_modules.nunjucks import nunjucks
 from browser import window, document
 import javascript
+import jid
 
 
 safe = nunjucks.runtime.SafeString.new
@@ -94,6 +95,13 @@
     return ret
 
 
+def _bare_jid(full_jid: str|jid.JID) -> str:
+    """Return the bare JID"""
+    return str(jid.JID(str(full_jid)).bare)
+
+env.addFilter("bare_jid", _bare_jid)
+
+
 def _next_gidx(value):
     """Use next current global index as suffix"""
     next_ = gidx.next(value)
@@ -162,9 +170,7 @@
 env.addGlobal("icon", _icon_use)
 
 
-def _date_fmt(
-    timestamp, *args
-):
+def _date_fmt(timestamp, *args):
     """Date formatting
 
     cf. libervia.backend.tools.common.date_utils for arguments details
@@ -178,29 +184,24 @@
 
     if fmt == "auto_day":
         fmt, auto_limit, auto_old_fmt, auto_new_fmt = "auto", 0, "short", "HH:mm"
+
     if fmt == "auto":
         limit = moment().startOf('day').subtract(auto_limit, 'days')
-        m_fmt = auto_old_fmt if date < limit else auto_new_fmt
+        fmt = auto_old_fmt if date < limit else auto_new_fmt
 
-    elif fmt == "short":
-        m_fmt = "DD/MM/YY" if date_only else "DD/MM/YY HH:mm"
-    elif fmt == "medium":
-        m_fmt = "ll" if date_only else "lll"
-    elif fmt == "long":
-        m_fmt = "LL" if date_only else "LLL"
-    elif fmt == "full":
-        m_fmt = "dddd, LL" if date_only else "LLLL"
-    elif fmt == "relative":
-        return date.fromNow()
-    elif fmt == "iso":
-        if date_only:
-            m_fmt == "YYYY-MM-DD"
-        else:
-            return date.toISOString()
-    else:
-        raise NotImplementedError("free format is not implemented yet")
+    format_mapping = {
+        "short": "DD/MM/YY" if date_only else "DD/MM/YY HH:mm",
+        "medium": "DD MMM YYYY" if date_only else "DD MMM YYYY HH:mm",
+        "long": "D MMMM YYYY" if date_only else "D MMMM YYYY HH:mm",
+        "full": "dddd, D MMMM YYYY" if date_only else "dddd, D MMMM YYYY HH:mm",
+        "relative": date.fromNow(),
+        "iso": date.toISOString() if not date_only else "YYYY-MM-DD"
+    }
 
-    return date.format(m_fmt)
+    # if `fmt` doesn't match any mapping, it's a free format
+    m_fmt = format_mapping.get(fmt, fmt)
+
+    return m_fmt if fmt in ["relative", "iso"] else date.format(m_fmt)
 
 env.addFilter("date_fmt", _date_fmt)