flask-deck 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flask_deck/__init__.py +184 -0
- flask_deck/adapters/__init__.py +23 -0
- flask_deck/adapters/sqlalchemy.py +272 -0
- flask_deck/audit.py +363 -0
- flask_deck/auth.py +462 -0
- flask_deck/branding.py +217 -0
- flask_deck/charts.py +514 -0
- flask_deck/cli.py +135 -0
- flask_deck/config.py +81 -0
- flask_deck/dashboard.py +416 -0
- flask_deck/deck.py +4153 -0
- flask_deck/demo.py +1066 -0
- flask_deck/events.py +309 -0
- flask_deck/exceptions.py +34 -0
- flask_deck/exporter.py +240 -0
- flask_deck/formatters.py +386 -0
- flask_deck/i18n.py +399 -0
- flask_deck/icons.py +92 -0
- flask_deck/importer.py +612 -0
- flask_deck/introspection.py +376 -0
- flask_deck/jobs.py +382 -0
- flask_deck/mfa.py +670 -0
- flask_deck/model_view.py +1097 -0
- flask_deck/py.typed +0 -0
- flask_deck/query.py +1220 -0
- flask_deck/schema_graph.py +137 -0
- flask_deck/security.py +373 -0
- flask_deck/sql_console.py +391 -0
- flask_deck/sso.py +293 -0
- flask_deck/static/css/deck.css +1333 -0
- flask_deck/static/js/deck.js +1433 -0
- flask_deck/storage.py +669 -0
- flask_deck/templates/flask_deck/audit_list.html +117 -0
- flask_deck/templates/flask_deck/base.html +454 -0
- flask_deck/templates/flask_deck/custom_page.html +12 -0
- flask_deck/templates/flask_deck/dashboard.html +32 -0
- flask_deck/templates/flask_deck/diagnostics.html +80 -0
- flask_deck/templates/flask_deck/error.html +15 -0
- flask_deck/templates/flask_deck/import_wizard.html +143 -0
- flask_deck/templates/flask_deck/jobs_list.html +95 -0
- flask_deck/templates/flask_deck/login.html +93 -0
- flask_deck/templates/flask_deck/login_mfa.html +59 -0
- flask_deck/templates/flask_deck/mfa_setup.html +121 -0
- flask_deck/templates/flask_deck/model_detail.html +124 -0
- flask_deck/templates/flask_deck/model_form.html +389 -0
- flask_deck/templates/flask_deck/model_list.html +489 -0
- flask_deck/templates/flask_deck/partials/drawer_detail.html +93 -0
- flask_deck/templates/flask_deck/partials/widget_grid.html +207 -0
- flask_deck/templates/flask_deck/rbac_matrix.html +59 -0
- flask_deck/templates/flask_deck/record_history.html +102 -0
- flask_deck/templates/flask_deck/schema_inspector.html +83 -0
- flask_deck/templates/flask_deck/sql_console.html +87 -0
- flask_deck-0.3.0.dist-info/METADATA +382 -0
- flask_deck-0.3.0.dist-info/RECORD +57 -0
- flask_deck-0.3.0.dist-info/WHEEL +4 -0
- flask_deck-0.3.0.dist-info/entry_points.txt +5 -0
- flask_deck-0.3.0.dist-info/licenses/LICENSE +21 -0
flask_deck/formatters.py
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import enum
|
|
4
|
+
import math
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from collections.abc import Callable, Mapping
|
|
7
|
+
from datetime import date, datetime, timezone
|
|
8
|
+
from decimal import ROUND_HALF_UP, Decimal
|
|
9
|
+
from typing import Any, ClassVar
|
|
10
|
+
|
|
11
|
+
from markupsafe import Markup, escape
|
|
12
|
+
|
|
13
|
+
from flask_deck.i18n import format_locale_decimal, to_user_timezone
|
|
14
|
+
from flask_deck.security import is_safe_display_url
|
|
15
|
+
|
|
16
|
+
VALID_TONES = frozenset({"neutral", "ok", "warn", "danger", "info"})
|
|
17
|
+
_TONE_ALIASES: dict[str, str] = {
|
|
18
|
+
"emerald": "ok",
|
|
19
|
+
"green": "ok",
|
|
20
|
+
"success": "ok",
|
|
21
|
+
"amber": "warn",
|
|
22
|
+
"yellow": "warn",
|
|
23
|
+
"warning": "warn",
|
|
24
|
+
"rose": "danger",
|
|
25
|
+
"red": "danger",
|
|
26
|
+
"error": "danger",
|
|
27
|
+
"indigo": "info",
|
|
28
|
+
"blue": "info",
|
|
29
|
+
"zinc": "neutral",
|
|
30
|
+
"gray": "neutral",
|
|
31
|
+
"muted": "neutral",
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def normalize_tone(tone: str) -> str:
|
|
36
|
+
lower = tone.strip().lower()
|
|
37
|
+
mapped = _TONE_ALIASES.get(lower, lower)
|
|
38
|
+
return mapped if mapped in VALID_TONES else "neutral"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Formatter(ABC):
|
|
42
|
+
"""Base cell formatter producing strictly CSP-safe and XSS-safe Markup."""
|
|
43
|
+
|
|
44
|
+
@abstractmethod
|
|
45
|
+
def format(self, value: Any, obj: Any | None = None) -> Markup | str:
|
|
46
|
+
"""Render a cell value safely."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class BadgeFormatter(Formatter):
|
|
50
|
+
"""Render status/enum strings as crisp semantic badges with indicator dots."""
|
|
51
|
+
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
tones: Mapping[str, str] | None = None,
|
|
55
|
+
*,
|
|
56
|
+
default_tone: str = "neutral",
|
|
57
|
+
labels: Mapping[str, str] | None = None,
|
|
58
|
+
) -> None:
|
|
59
|
+
self._tones = {str(k).lower(): normalize_tone(v) for k, v in (tones or {}).items()}
|
|
60
|
+
self._default_tone = normalize_tone(default_tone)
|
|
61
|
+
self._labels = {str(k).lower(): str(v) for k, v in (labels or {}).items()}
|
|
62
|
+
|
|
63
|
+
def format(self, value: Any, obj: Any | None = None) -> Markup:
|
|
64
|
+
if value is None:
|
|
65
|
+
return Markup('<span class="dk-null">—</span>')
|
|
66
|
+
raw = value.value if isinstance(value, enum.Enum) else str(value)
|
|
67
|
+
key = str(raw).lower()
|
|
68
|
+
tone = self._tones.get(key, self._default_tone)
|
|
69
|
+
display = self._labels.get(key, str(raw).replace("_", " "))
|
|
70
|
+
return Markup(
|
|
71
|
+
f'<span class="dk-badge dk-badge-{tone}">'
|
|
72
|
+
f'<span class="dk-dot" aria-hidden="true"></span>'
|
|
73
|
+
f"{escape(display)}</span>"
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class CurrencyFormatter(Formatter):
|
|
78
|
+
"""Format numeric or minor-unit currency values with tabular monospace alignment."""
|
|
79
|
+
|
|
80
|
+
_SYMBOLS: ClassVar[dict[str, str]] = {
|
|
81
|
+
"USD": "$",
|
|
82
|
+
"EUR": "€",
|
|
83
|
+
"GBP": "£",
|
|
84
|
+
"TRY": "₺",
|
|
85
|
+
"JPY": "¥",
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
def __init__(
|
|
89
|
+
self,
|
|
90
|
+
*,
|
|
91
|
+
currency: str = "USD",
|
|
92
|
+
divisor: int | float = 1,
|
|
93
|
+
decimals: int = 2,
|
|
94
|
+
) -> None:
|
|
95
|
+
self._symbol = self._SYMBOLS.get(currency.upper(), f"{currency.upper()} ")
|
|
96
|
+
self._divisor = Decimal(str(divisor))
|
|
97
|
+
self._decimals = decimals
|
|
98
|
+
|
|
99
|
+
def format(self, value: Any, obj: Any | None = None) -> Markup:
|
|
100
|
+
if value is None:
|
|
101
|
+
return Markup('<span class="dk-null">—</span>')
|
|
102
|
+
try:
|
|
103
|
+
amount = Decimal(str(value)) / self._divisor
|
|
104
|
+
if not amount.is_finite():
|
|
105
|
+
return Markup(f'<span class="dk-mono">{escape(str(value))}</span>')
|
|
106
|
+
quant = Decimal(10) ** -max(0, self._decimals)
|
|
107
|
+
rounded = amount.quantize(quant, rounding=ROUND_HALF_UP)
|
|
108
|
+
except Exception:
|
|
109
|
+
return Markup(f'<span class="dk-mono">{escape(str(value))}</span>')
|
|
110
|
+
sign = "-" if rounded < 0 else ""
|
|
111
|
+
formatted_num = format_locale_decimal(abs(rounded), decimals=self._decimals)
|
|
112
|
+
formatted = f"{sign}{self._symbol}{formatted_num}"
|
|
113
|
+
return Markup(f'<span class="dk-mono dk-tabular">{escape(formatted)}</span>')
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class RelativeTimeFormatter(Formatter):
|
|
117
|
+
"""Render UTC/naive datetimes as crisp relative time with user-timezone tooltip."""
|
|
118
|
+
|
|
119
|
+
def format(self, value: Any, obj: Any | None = None) -> Markup:
|
|
120
|
+
if value is None:
|
|
121
|
+
return Markup('<span class="dk-null">—</span>')
|
|
122
|
+
if isinstance(value, datetime):
|
|
123
|
+
dt = value if value.tzinfo is not None else value.replace(tzinfo=timezone.utc)
|
|
124
|
+
now = datetime.now(timezone.utc)
|
|
125
|
+
delta = now - dt
|
|
126
|
+
secs = int(delta.total_seconds())
|
|
127
|
+
local_dt = to_user_timezone(dt)
|
|
128
|
+
if secs < 0:
|
|
129
|
+
fut = abs(secs)
|
|
130
|
+
if fut < 60:
|
|
131
|
+
rel = f"in {fut}s"
|
|
132
|
+
elif fut < 3600:
|
|
133
|
+
rel = f"in {fut // 60}m"
|
|
134
|
+
elif fut < 86400:
|
|
135
|
+
rel = f"in {fut // 3600}h"
|
|
136
|
+
elif fut < 86400 * 30:
|
|
137
|
+
rel = f"in {fut // 86400}d"
|
|
138
|
+
else:
|
|
139
|
+
rel = local_dt.strftime("%Y-%m-%d")
|
|
140
|
+
elif secs < 60:
|
|
141
|
+
rel = f"{secs}s ago"
|
|
142
|
+
elif secs < 3600:
|
|
143
|
+
rel = f"{secs // 60}m ago"
|
|
144
|
+
elif secs < 86400:
|
|
145
|
+
rel = f"{secs // 3600}h ago"
|
|
146
|
+
elif secs < 86400 * 30:
|
|
147
|
+
rel = f"{secs // 86400}d ago"
|
|
148
|
+
else:
|
|
149
|
+
rel = local_dt.strftime("%Y-%m-%d")
|
|
150
|
+
tz_abbr = local_dt.tzname() or "UTC"
|
|
151
|
+
iso = f"{local_dt.strftime('%Y-%m-%d %H:%M')} {tz_abbr}"
|
|
152
|
+
return Markup(
|
|
153
|
+
f'<time class="dk-mono dk-tabular dk-muted" title="{escape(iso)}">{escape(rel)}</time>'
|
|
154
|
+
)
|
|
155
|
+
if isinstance(value, date):
|
|
156
|
+
iso = value.isoformat()
|
|
157
|
+
return Markup(f'<time class="dk-mono dk-tabular dk-muted">{escape(iso)}</time>')
|
|
158
|
+
return Markup(f'<span class="dk-mono">{escape(str(value))}</span>')
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class DateTimeFormatter(Formatter):
|
|
162
|
+
"""Render datetimes explicitly converted to the user's active ZoneInfo timezone."""
|
|
163
|
+
|
|
164
|
+
def __init__(self, *, fmt: str = "%Y-%m-%d %H:%M") -> None:
|
|
165
|
+
self._fmt = fmt
|
|
166
|
+
|
|
167
|
+
def format(self, value: Any, obj: Any | None = None) -> Markup:
|
|
168
|
+
if value is None:
|
|
169
|
+
return Markup('<span class="dk-null">—</span>')
|
|
170
|
+
if isinstance(value, datetime):
|
|
171
|
+
local_dt = to_user_timezone(value)
|
|
172
|
+
tz_abbr = local_dt.tzname() or "UTC"
|
|
173
|
+
display = f"{local_dt.strftime(self._fmt)} {tz_abbr}"
|
|
174
|
+
return Markup(
|
|
175
|
+
f'<time class="dk-mono dk-tabular dk-muted" title="{escape(local_dt.isoformat())}">'
|
|
176
|
+
f"{escape(display)}</time>"
|
|
177
|
+
)
|
|
178
|
+
if isinstance(value, date):
|
|
179
|
+
return Markup(f'<time class="dk-mono dk-tabular dk-muted">{escape(value.isoformat())}</time>')
|
|
180
|
+
return Markup(f'<span class="dk-mono">{escape(str(value))}</span>')
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class BooleanIconFormatter(Formatter):
|
|
184
|
+
"""Render booleans as crisp high-contrast semantic pills."""
|
|
185
|
+
|
|
186
|
+
def __init__(self, *, true_label: str = "Active", false_label: str = "Inactive") -> None:
|
|
187
|
+
self._true_label = true_label
|
|
188
|
+
self._false_label = false_label
|
|
189
|
+
|
|
190
|
+
def format(self, value: Any, obj: Any | None = None) -> Markup:
|
|
191
|
+
if value is None:
|
|
192
|
+
return Markup('<span class="dk-null">—</span>')
|
|
193
|
+
if bool(value):
|
|
194
|
+
return Markup(
|
|
195
|
+
f'<span class="dk-badge dk-badge-ok">'
|
|
196
|
+
f'<span class="dk-dot" aria-hidden="true"></span>'
|
|
197
|
+
f"{escape(self._true_label)}</span>"
|
|
198
|
+
)
|
|
199
|
+
return Markup(
|
|
200
|
+
f'<span class="dk-badge dk-badge-neutral">'
|
|
201
|
+
f'<span class="dk-dot" aria-hidden="true"></span>'
|
|
202
|
+
f"{escape(self._false_label)}</span>"
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class CodeFormatter(Formatter):
|
|
207
|
+
"""Render identifiers, slugs, or keys in compact monospace chips (optionally copyable)."""
|
|
208
|
+
|
|
209
|
+
def __init__(self, *, max_chars: int = 36, copyable: bool = False) -> None:
|
|
210
|
+
self._max_chars = max_chars
|
|
211
|
+
self._copyable = copyable
|
|
212
|
+
|
|
213
|
+
def format(self, value: Any, obj: Any | None = None) -> Markup:
|
|
214
|
+
if value is None:
|
|
215
|
+
return Markup('<span class="dk-null">—</span>')
|
|
216
|
+
text = str(value)
|
|
217
|
+
display = text if len(text) <= self._max_chars else f"{text[: self._max_chars - 1]}…"
|
|
218
|
+
if self._copyable:
|
|
219
|
+
return Markup(
|
|
220
|
+
'<span class="dk-copy-wrap">'
|
|
221
|
+
f'<code class="dk-code" title="{escape(text)}">{escape(display)}</code>'
|
|
222
|
+
f'<button type="button" class="dk-copy-btn" data-deck-copy="{escape(text)}" '
|
|
223
|
+
'title="Copy to clipboard" aria-label="Copy to clipboard">'
|
|
224
|
+
'<svg class="dk-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" '
|
|
225
|
+
'stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" '
|
|
226
|
+
'aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>'
|
|
227
|
+
'<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>'
|
|
228
|
+
"</button></span>"
|
|
229
|
+
)
|
|
230
|
+
return Markup(f'<code class="dk-code" title="{escape(text)}">{escape(display)}</code>')
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class AvatarFormatter(Formatter):
|
|
234
|
+
"""Render initials badge + name cleanly without relying on external image hosts."""
|
|
235
|
+
|
|
236
|
+
def format(self, value: Any, obj: Any | None = None) -> Markup:
|
|
237
|
+
if value is None:
|
|
238
|
+
return Markup('<span class="dk-null">—</span>')
|
|
239
|
+
text = str(value).strip()
|
|
240
|
+
parts = [p for p in text.split() if p]
|
|
241
|
+
initials = (
|
|
242
|
+
(parts[0][0] + parts[-1][0]).upper()
|
|
243
|
+
if len(parts) >= 2
|
|
244
|
+
else (text[:2].upper() if text else "?")
|
|
245
|
+
)
|
|
246
|
+
return Markup(
|
|
247
|
+
'<span class="dk-avatar-cell">'
|
|
248
|
+
f'<span class="dk-avatar" aria-hidden="true">{escape(initials)}</span>'
|
|
249
|
+
f'<span class="dk-avatar-name">{escape(text)}</span>'
|
|
250
|
+
"</span>"
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
class ProgressBarFormatter(Formatter):
|
|
255
|
+
"""Strict CSP-compliant progress bar using pure SVG (zero inline style attributes)."""
|
|
256
|
+
|
|
257
|
+
def __init__(
|
|
258
|
+
self,
|
|
259
|
+
*,
|
|
260
|
+
max_value: float = 100.0,
|
|
261
|
+
warn_below: float | None = None,
|
|
262
|
+
danger_below: float | None = None,
|
|
263
|
+
suffix: str = "%",
|
|
264
|
+
) -> None:
|
|
265
|
+
self._max_value = max(0.0001, float(max_value))
|
|
266
|
+
self._warn_below = warn_below
|
|
267
|
+
self._danger_below = danger_below
|
|
268
|
+
self._suffix = suffix
|
|
269
|
+
|
|
270
|
+
def format(self, value: Any, obj: Any | None = None) -> Markup:
|
|
271
|
+
if value is None:
|
|
272
|
+
return Markup('<span class="dk-null">—</span>')
|
|
273
|
+
try:
|
|
274
|
+
num = float(value)
|
|
275
|
+
except (TypeError, ValueError):
|
|
276
|
+
return Markup(f'<span class="dk-mono">{escape(str(value))}</span>')
|
|
277
|
+
if not math.isfinite(num):
|
|
278
|
+
return Markup(f'<span class="dk-mono">{escape(str(value))}</span>')
|
|
279
|
+
pct = max(0.0, min(100.0, (num / self._max_value) * 100.0))
|
|
280
|
+
bar_cls = "dk-prog-fill-ok"
|
|
281
|
+
if self._danger_below is not None and num <= self._danger_below:
|
|
282
|
+
bar_cls = "dk-prog-fill-danger"
|
|
283
|
+
elif self._warn_below is not None and num <= self._warn_below:
|
|
284
|
+
bar_cls = "dk-prog-fill-warn"
|
|
285
|
+
label = f"{int(num) if num.is_integer() else f'{num:.1f}'}{self._suffix}"
|
|
286
|
+
return Markup(
|
|
287
|
+
'<span class="dk-progress-cell">'
|
|
288
|
+
'<svg class="dk-progress-svg" viewBox="0 0 100 6" width="68" height="6" aria-hidden="true">'
|
|
289
|
+
'<rect class="dk-prog-track" x="0" y="0" width="100" height="6" rx="2"></rect>'
|
|
290
|
+
f'<rect class="{bar_cls}" x="0" y="0" width="{pct:.1f}" height="6" rx="2"></rect>'
|
|
291
|
+
"</svg>"
|
|
292
|
+
f'<span class="dk-mono dk-tabular dk-muted">{escape(label)}</span>'
|
|
293
|
+
"</span>"
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
class LinkFormatter(Formatter):
|
|
298
|
+
"""Render external/internal URLs safely, blocking javascript: and data: schemes."""
|
|
299
|
+
|
|
300
|
+
def __init__(self, *, label: str | None = None, new_tab: bool = True) -> None:
|
|
301
|
+
self._label = label
|
|
302
|
+
self._new_tab = new_tab
|
|
303
|
+
|
|
304
|
+
def format(self, value: Any, obj: Any | None = None) -> Markup:
|
|
305
|
+
if value is None or not str(value).strip():
|
|
306
|
+
return Markup('<span class="dk-null">—</span>')
|
|
307
|
+
url = str(value).strip()
|
|
308
|
+
if not is_safe_display_url(url):
|
|
309
|
+
return Markup(f'<span class="dk-mono dk-muted">{escape(url)}</span>')
|
|
310
|
+
display = self._label or url.removeprefix("https://").removeprefix("http://")
|
|
311
|
+
if len(display) > 36:
|
|
312
|
+
display = f"{display[:35]}…"
|
|
313
|
+
target = ' target="_blank" rel="noopener noreferrer"' if self._new_tab else ""
|
|
314
|
+
return Markup(f'<a class="dk-link" href="{escape(url)}"{target}>{escape(display)}</a>')
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
class ImageFormatter(Formatter):
|
|
318
|
+
"""Render stored image thumbnails opening a strict-CSP Lightbox modal on click."""
|
|
319
|
+
|
|
320
|
+
def __init__(
|
|
321
|
+
self,
|
|
322
|
+
*,
|
|
323
|
+
media_url_builder: Callable[[Any], str | None] | None = None,
|
|
324
|
+
field_name: str | None = None,
|
|
325
|
+
alt_prefix: str = "Image",
|
|
326
|
+
) -> None:
|
|
327
|
+
self._media_url_builder = media_url_builder
|
|
328
|
+
self._field_name = field_name
|
|
329
|
+
self._alt_prefix = alt_prefix
|
|
330
|
+
|
|
331
|
+
def format_with_url(self, value: Any, media_url: str | None) -> Markup:
|
|
332
|
+
if value is None or not str(value).strip():
|
|
333
|
+
return Markup('<span class="dk-null">—</span>')
|
|
334
|
+
key = str(value).strip()
|
|
335
|
+
filename = key.rsplit("/", 1)[-1]
|
|
336
|
+
url = media_url if media_url and is_safe_display_url(media_url) else (
|
|
337
|
+
key if is_safe_display_url(key) else None
|
|
338
|
+
)
|
|
339
|
+
if not url:
|
|
340
|
+
return Markup(f'<code class="dk-code">{escape(filename)}</code>')
|
|
341
|
+
return Markup(
|
|
342
|
+
f'<button type="button" class="dk-thumb-btn" data-deck-lightbox="{escape(url)}" '
|
|
343
|
+
f'data-lightbox-title="{escape(filename)}" title="Preview {escape(filename)}" '
|
|
344
|
+
f'aria-label="Preview {escape(filename)}">'
|
|
345
|
+
f'<img class="dk-thumb" src="{escape(url)}" alt="{escape(self._alt_prefix)}: {escape(filename)}" loading="lazy">'
|
|
346
|
+
"</button>"
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
def format(self, value: Any, obj: Any | None = None) -> Markup:
|
|
350
|
+
url = self._media_url_builder(obj) if (self._media_url_builder and obj is not None) else None
|
|
351
|
+
return self.format_with_url(value, url)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
class FileFormatter(Formatter):
|
|
355
|
+
"""Render stored file attachments as crisp downloadable monospace chips."""
|
|
356
|
+
|
|
357
|
+
def __init__(
|
|
358
|
+
self,
|
|
359
|
+
*,
|
|
360
|
+
media_url_builder: Callable[[Any], str | None] | None = None,
|
|
361
|
+
) -> None:
|
|
362
|
+
self._media_url_builder = media_url_builder
|
|
363
|
+
|
|
364
|
+
def format_with_url(self, value: Any, media_url: str | None) -> Markup:
|
|
365
|
+
if value is None or not str(value).strip():
|
|
366
|
+
return Markup('<span class="dk-null">—</span>')
|
|
367
|
+
key = str(value).strip()
|
|
368
|
+
filename = key.rsplit("/", 1)[-1]
|
|
369
|
+
short = filename if len(filename) <= 28 else f"{filename[:27]}…"
|
|
370
|
+
url = media_url if media_url and is_safe_display_url(media_url) else (
|
|
371
|
+
key if is_safe_display_url(key) else None
|
|
372
|
+
)
|
|
373
|
+
if not url:
|
|
374
|
+
return Markup(f'<code class="dk-code">{escape(short)}</code>')
|
|
375
|
+
return Markup(
|
|
376
|
+
f'<a class="dk-file-chip dk-mono" href="{escape(url)}" title="{escape(filename)}">'
|
|
377
|
+
'<svg class="dk-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" '
|
|
378
|
+
'stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" '
|
|
379
|
+
'aria-hidden="true"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19'
|
|
380
|
+
'a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>'
|
|
381
|
+
f"<span>{escape(short)}</span></a>"
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
def format(self, value: Any, obj: Any | None = None) -> Markup:
|
|
385
|
+
url = self._media_url_builder(obj) if (self._media_url_builder and obj is not None) else None
|
|
386
|
+
return self.format_with_url(value, url)
|