fjkit 0.1.0.dev0__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.
Files changed (127) hide show
  1. fjkit/__init__.py +49 -0
  2. fjkit/auth/__init__.py +54 -0
  3. fjkit/auth/csrf.py +88 -0
  4. fjkit/auth/errors.py +31 -0
  5. fjkit/auth/plugin.py +496 -0
  6. fjkit/auth/sources.py +24 -0
  7. fjkit/auth/stores.py +141 -0
  8. fjkit/auth/types.py +141 -0
  9. fjkit/cli/__init__.py +67 -0
  10. fjkit/cli/build_css.py +135 -0
  11. fjkit/cli/check.py +193 -0
  12. fjkit/cli/eject.py +562 -0
  13. fjkit/cli/ejected.py +202 -0
  14. fjkit/cli/vocabulary.py +85 -0
  15. fjkit/config.py +130 -0
  16. fjkit/errors.py +156 -0
  17. fjkit/flash.py +189 -0
  18. fjkit/forms.py +145 -0
  19. fjkit/htmx.py +76 -0
  20. fjkit/icons.py +60 -0
  21. fjkit/messages.py +227 -0
  22. fjkit/mounting.py +72 -0
  23. fjkit/plugins.py +223 -0
  24. fjkit/py.typed +0 -0
  25. fjkit/rendering.py +554 -0
  26. fjkit/signing.py +63 -0
  27. fjkit/static/brand/torii-bolt.png +0 -0
  28. fjkit/static/dist/fjkit-luma.css +2 -0
  29. fjkit/static/dist/fjkit-lyra.css +2 -0
  30. fjkit/static/dist/fjkit-maia.css +2 -0
  31. fjkit/static/dist/fjkit-mira.css +2 -0
  32. fjkit/static/dist/fjkit-nova.css +2 -0
  33. fjkit/static/dist/fjkit-rhea.css +2 -0
  34. fjkit/static/dist/fjkit-sera.css +2 -0
  35. fjkit/static/dist/fjkit-vega.css +2 -0
  36. fjkit/static/icons/lucide.json +1 -0
  37. fjkit/static/js/errors.js +117 -0
  38. fjkit/static/js/multiselect.js +126 -0
  39. fjkit/static/js/reveal.js +51 -0
  40. fjkit/static/js/select.js +113 -0
  41. fjkit/static/src/fjkit.css +385 -0
  42. fjkit/static/vendor/basecoat/base/base.css +136 -0
  43. fjkit/static/vendor/basecoat/basecoat-base.css +2 -0
  44. fjkit/static/vendor/basecoat/basecoat-components.css +39 -0
  45. fjkit/static/vendor/basecoat/basecoat-luma.css +2 -0
  46. fjkit/static/vendor/basecoat/basecoat-lyra.css +2 -0
  47. fjkit/static/vendor/basecoat/basecoat-maia.css +2 -0
  48. fjkit/static/vendor/basecoat/basecoat-mira.css +2 -0
  49. fjkit/static/vendor/basecoat/basecoat-nova.css +2 -0
  50. fjkit/static/vendor/basecoat/basecoat-rhea.css +2 -0
  51. fjkit/static/vendor/basecoat/basecoat-sera.css +2 -0
  52. fjkit/static/vendor/basecoat/basecoat-vega.css +2 -0
  53. fjkit/static/vendor/basecoat/basecoat.all.css +1 -0
  54. fjkit/static/vendor/basecoat/basecoat.css +1 -0
  55. fjkit/static/vendor/basecoat/components/accordion.css +27 -0
  56. fjkit/static/vendor/basecoat/components/alert.css +38 -0
  57. fjkit/static/vendor/basecoat/components/avatar.css +47 -0
  58. fjkit/static/vendor/basecoat/components/badge.css +6 -0
  59. fjkit/static/vendor/basecoat/components/breadcrumb.css +30 -0
  60. fjkit/static/vendor/basecoat/components/button-group.css +54 -0
  61. fjkit/static/vendor/basecoat/components/button.css +6 -0
  62. fjkit/static/vendor/basecoat/components/card.css +26 -0
  63. fjkit/static/vendor/basecoat/components/chart.css +56 -0
  64. fjkit/static/vendor/basecoat/components/checkbox.css +12 -0
  65. fjkit/static/vendor/basecoat/components/collapsible.css +21 -0
  66. fjkit/static/vendor/basecoat/components/combobox.css +99 -0
  67. fjkit/static/vendor/basecoat/components/command.css +140 -0
  68. fjkit/static/vendor/basecoat/components/dialog.css +101 -0
  69. fjkit/static/vendor/basecoat/components/drawer.css +89 -0
  70. fjkit/static/vendor/basecoat/components/dropdown-menu.css +56 -0
  71. fjkit/static/vendor/basecoat/components/empty.css +26 -0
  72. fjkit/static/vendor/basecoat/components/field.css +82 -0
  73. fjkit/static/vendor/basecoat/components/form.css +9 -0
  74. fjkit/static/vendor/basecoat/components/input-group.css +74 -0
  75. fjkit/static/vendor/basecoat/components/input.css +32 -0
  76. fjkit/static/vendor/basecoat/components/item.css +50 -0
  77. fjkit/static/vendor/basecoat/components/kbd.css +6 -0
  78. fjkit/static/vendor/basecoat/components/label.css +13 -0
  79. fjkit/static/vendor/basecoat/components/native-select.css +12 -0
  80. fjkit/static/vendor/basecoat/components/popover.css +107 -0
  81. fjkit/static/vendor/basecoat/components/progress.css +14 -0
  82. fjkit/static/vendor/basecoat/components/radio.css +11 -0
  83. fjkit/static/vendor/basecoat/components/range.css +50 -0
  84. fjkit/static/vendor/basecoat/components/scrollbar.css +46 -0
  85. fjkit/static/vendor/basecoat/components/select.css +64 -0
  86. fjkit/static/vendor/basecoat/components/sidebar.css +101 -0
  87. fjkit/static/vendor/basecoat/components/skeleton.css +6 -0
  88. fjkit/static/vendor/basecoat/components/switch.css +8 -0
  89. fjkit/static/vendor/basecoat/components/table.css +34 -0
  90. fjkit/static/vendor/basecoat/components/tabs.css +31 -0
  91. fjkit/static/vendor/basecoat/components/textarea.css +7 -0
  92. fjkit/static/vendor/basecoat/components/toast.css +57 -0
  93. fjkit/static/vendor/basecoat/components/tooltip.css +82 -0
  94. fjkit/static/vendor/basecoat/js/all.min.js +1 -0
  95. fjkit/static/vendor/basecoat/styles/luma.css +1376 -0
  96. fjkit/static/vendor/basecoat/styles/lyra.css +1379 -0
  97. fjkit/static/vendor/basecoat/styles/maia.css +1364 -0
  98. fjkit/static/vendor/basecoat/styles/mira.css +1373 -0
  99. fjkit/static/vendor/basecoat/styles/nova.css +1387 -0
  100. fjkit/static/vendor/basecoat/styles/rhea.css +1381 -0
  101. fjkit/static/vendor/basecoat/styles/sera.css +1397 -0
  102. fjkit/static/vendor/basecoat/styles/vega.css +1386 -0
  103. fjkit/static/vendor/htmx/htmx.min.js +1 -0
  104. fjkit/static/vendor/htmx/json-enc.js +38 -0
  105. fjkit/styles.py +30 -0
  106. fjkit/templates/errors/page.html +92 -0
  107. fjkit/templates/ui/attrs.html +18 -0
  108. fjkit/templates/ui/button.html +64 -0
  109. fjkit/templates/ui/data.html +362 -0
  110. fjkit/templates/ui/disclosure.html +89 -0
  111. fjkit/templates/ui/feedback.html +313 -0
  112. fjkit/templates/ui/form.html +595 -0
  113. fjkit/templates/ui/icon.html +13 -0
  114. fjkit/templates/ui/layout.html +189 -0
  115. fjkit/templates/ui/nav.html +110 -0
  116. fjkit/templates/ui/overlay.html +624 -0
  117. fjkit/templates/ui/shell.html +170 -0
  118. fjkit/templates/ui/sidebar.html +170 -0
  119. fjkit/templates/ui/table.html +427 -0
  120. fjkit/templates/ui/tabs.html +133 -0
  121. fjkit/templating.py +365 -0
  122. fjkit/vendored.py +46 -0
  123. fjkit-0.1.0.dev0.dist-info/METADATA +119 -0
  124. fjkit-0.1.0.dev0.dist-info/RECORD +127 -0
  125. fjkit-0.1.0.dev0.dist-info/WHEEL +4 -0
  126. fjkit-0.1.0.dev0.dist-info/entry_points.txt +2 -0
  127. fjkit-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
fjkit/flash.py ADDED
@@ -0,0 +1,189 @@
1
+ """`FlashPlugin` — a message that survives a redirect.
2
+
3
+ `fjkit.messages` shows a message on the current response. This layer sits above
4
+ it and covers the one case that layer cannot reach: a redirect replaces the
5
+ page, so the document that would have shown the message is gone before the
6
+ response arrives. `HX-Trigger` cannot help — it names an event for a page about
7
+ to be discarded — and a full navigation runs no JavaScript at all.
8
+
9
+ The cookie jar does survive. A flash is written as a short-lived signed cookie
10
+ on the response that redirects, read back on the request that lands, queued
11
+ into `fjkit.messages` like any other message, and cleared once it has been
12
+ shown — so it appears exactly once and not again on reload.
13
+
14
+ That last step is why this is a plugin and `fjkit.messages` is core. Signing
15
+ needs a secret, and requiring one from every app — including one with no forms
16
+ and nothing to say — would stop `mount_fjkit(app)` from working with no config
17
+ at all. Everything that needs no secret is core.
18
+
19
+ Registering the plugin is the whole setup. `ui/shell.html` renders the toaster
20
+ region and fills it from the message queue, so no template in the app changes:
21
+
22
+ flash = FlashPlugin(secret=os.environ["FJKIT_SECRET"])
23
+ config = FjkitConfig(template_dir=…, plugins=(flash,))
24
+
25
+ Nothing here is specific to sessions. `AuthPlugin` takes one of these to
26
+ explain why it bounced you, and so can a route that just finished something:
27
+
28
+ flash.add(response, "Saved", category="success")
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import json
34
+ from collections.abc import Sequence
35
+ from datetime import timedelta
36
+ from typing import Any
37
+
38
+ from fastapi import Request, Response
39
+ from starlette.middleware.base import BaseHTTPMiddleware
40
+
41
+ from fjkit.messages import Category, Message
42
+ from fjkit.messages import extend as _queue
43
+ from fjkit.messages import shown as _was_shown
44
+ from fjkit.plugins import AppSetup
45
+ from fjkit.signing import sign, unsign
46
+
47
+ __all__ = ["FlashMessage", "FlashPlugin"]
48
+
49
+ #: Core's `Message`, under the name this module shipped it as. A flash is an
50
+ #: ordinary message that took a longer route to the page, so a second type
51
+ #: would mean two names for one thing and a conversion between them at the seam.
52
+ FlashMessage = Message
53
+
54
+
55
+ class FlashPlugin:
56
+ """Messages that outlive the response that produced them.
57
+
58
+ The cookie is signed rather than encrypted: it holds strings the app is
59
+ about to show the user anyway, so there is nothing to hide. The signature
60
+ stops whoever holds the browser from writing a message — an unsigned flash
61
+ cookie makes a site display any text an attacker likes, which is a phishing
62
+ tool.
63
+ """
64
+
65
+ name = "flash"
66
+
67
+ def __init__(
68
+ self,
69
+ *,
70
+ secret: str | bytes,
71
+ cookie_name: str = "fjkit_flash",
72
+ max_age: timedelta = timedelta(minutes=5),
73
+ path: str = "/",
74
+ secure: bool = True,
75
+ ) -> None:
76
+ self.secret = secret.encode("utf-8") if isinstance(secret, str) else secret
77
+ self.cookie_name = cookie_name
78
+ self.max_age = max_age
79
+ self.path = path
80
+ self.secure = secure
81
+
82
+ # ---------------------------------------------------------------- plugin
83
+
84
+ def mount(self, setup: AppSetup) -> None:
85
+ setup.add_middleware(_FlashMiddleware, plugin=self)
86
+
87
+ #: No `extend`. This plugin contributes no context key of its own: the
88
+ #: cookie is queued into `fjkit.messages`, which the shell already renders,
89
+ #: so a template never learns that a message arrived by cookie rather than
90
+ #: from the handler it is rendering. That is the point of layering the two —
91
+ #: one loop in the shell, not one per delivery mechanism.
92
+
93
+ # ------------------------------------------------------------- app-facing
94
+
95
+ def add(
96
+ self,
97
+ response: Response,
98
+ title: str,
99
+ text: str | None = None,
100
+ *,
101
+ category: Category = "info",
102
+ ) -> None:
103
+ """Queue a message for whatever page the browser lands on next.
104
+
105
+ Set it on the response that redirects, not on the one that renders: a
106
+ message rendered into the page it was raised on needs no cookie to get
107
+ there.
108
+ """
109
+ self.set(response, [FlashMessage(title=title, text=text, category=category)])
110
+
111
+ def set(self, response: Response, messages: Sequence[FlashMessage]) -> None:
112
+ """Replace the queue outright. `add` is the one-message form."""
113
+ payload = json.dumps(
114
+ [{"title": m.title, "text": m.text, "category": m.category} for m in messages],
115
+ separators=(",", ":"),
116
+ ).encode("utf-8")
117
+ response.set_cookie(
118
+ self.cookie_name,
119
+ self._sign(payload),
120
+ max_age=int(self.max_age.total_seconds()),
121
+ path=self.path,
122
+ secure=self.secure,
123
+ httponly=True,
124
+ samesite="lax",
125
+ )
126
+
127
+ def clear(self, response: Response) -> None:
128
+ response.delete_cookie(self.cookie_name, path=self.path)
129
+
130
+ # -------------------------------------------------------------- internals
131
+
132
+ def load(self, request: Request) -> tuple[FlashMessage, ...]:
133
+ raw = request.cookies.get(self.cookie_name)
134
+ if not raw:
135
+ return ()
136
+ payload = self._unsign(raw)
137
+ if payload is None:
138
+ return ()
139
+ try:
140
+ data = json.loads(payload)
141
+ return tuple(
142
+ FlashMessage(
143
+ title=str(item["title"]),
144
+ text=item.get("text"),
145
+ category=item.get("category", "info"),
146
+ )
147
+ for item in data
148
+ )
149
+ except (ValueError, TypeError, KeyError):
150
+ # A cookie this process cannot read is not a message. Dropping it
151
+ # beats 500-ing every page until the user clears their cookies.
152
+ return ()
153
+
154
+ def _sign(self, payload: bytes) -> str:
155
+ return sign(self.secret, payload)
156
+
157
+ def _unsign(self, raw: str) -> bytes | None:
158
+ return unsign(self.secret, raw)
159
+
160
+
161
+ class _FlashMiddleware(BaseHTTPMiddleware):
162
+ """Queue on the way in, clear on the way out — but only once it was shown.
163
+
164
+ "Shown" is `fjkit.messages.shown()`, set by delivery: a template iterating
165
+ the queue, or the queue being drained into an `HX-Trigger`. Carrying the
166
+ cookie is not enough — a page load fires more requests than the page (an
167
+ htmx poll, a prefetch), and any of them would otherwise eat the message and
168
+ leave the page it belonged to empty.
169
+ """
170
+
171
+ def __init__(self, app: Any, *, plugin: FlashPlugin) -> None:
172
+ super().__init__(app)
173
+ self.plugin = plugin
174
+
175
+ async def dispatch(self, request: Request, call_next: Any) -> Response:
176
+ carried = self.plugin.load(request)
177
+ if carried:
178
+ _queue(request, carried)
179
+
180
+ response = await call_next(request)
181
+
182
+ # Skip the clear when the handler set a new flash on its way out: that
183
+ # one is for the next page, and clearing it here would swallow it.
184
+ replaced = any(
185
+ cookie.startswith(f"{self.plugin.cookie_name}=") for cookie in response.headers.getlist("set-cookie")
186
+ )
187
+ if carried and _was_shown(request) and not replaced:
188
+ self.plugin.clear(response)
189
+ return response
fjkit/forms.py ADDED
@@ -0,0 +1,145 @@
1
+ """Names a validation failure the way a form names its fields.
2
+
3
+ errors = field_errors(exc, request_scoped=True)
4
+ errors.title # "Field required", or None
5
+
6
+ `fjkit.errors` renders the navigation error page from this and reads
7
+ `.messages()` for a toast. `static/js/errors.js` does the same `loc`-to-name
8
+ derivation in the browser; `field_name` here and `fieldName` there must agree.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Iterator, Mapping, Sequence
14
+ from typing import Any
15
+
16
+ __all__ = [
17
+ "NO_ERRORS",
18
+ "FieldErrors",
19
+ "field_errors",
20
+ "field_name",
21
+ "label",
22
+ ]
23
+
24
+ #: Where FastAPI puts a form or JSON body field. Stripped from `loc` so a field
25
+ #: is named the way the form names it: `title`, not `body.title`. Other
26
+ #: prefixes stay — a failure in the query string or a path segment is not a
27
+ #: field on this form, and flattening it to a bare name would light up an
28
+ #: unrelated input.
29
+ _BODY = "body"
30
+
31
+ #: Pydantic's word for "this body was not JSON at all", and the one failure
32
+ #: whose `loc` names no field: it reads `("body", <offset>)`, a position in the
33
+ #: text. `field_name` cannot detect it, because `("body", 0)` is also what a
34
+ #: body that is a list reports about its first item — the two shapes are
35
+ #: identical and only the type tells them apart. Left to `field_name`, an
36
+ #: unreadable body becomes a field called `1` and a toast reading "2: JSON
37
+ #: decode error", which names a byte to a person who typed characters.
38
+ #:
39
+ #: Only JSON reaches here. A urlencoded body has no parse step that can fail
40
+ #: this way: what is not a pair is not a field.
41
+ _UNPARSABLE = frozenset({"json_invalid"})
42
+
43
+
44
+ class _ByField(Mapping[str, str]):
45
+ """A mapping readable as `errors.title`; an absent name answers `None`."""
46
+
47
+ __slots__ = ("_by_field",)
48
+
49
+ def __init__(self, by_field: Mapping[str, str]) -> None:
50
+ self._by_field = dict(by_field)
51
+
52
+ def __getattr__(self, name: str) -> str | None:
53
+ if name.startswith("_"):
54
+ raise AttributeError(name)
55
+ return self._by_field.get(name)
56
+
57
+ def __getitem__(self, key: str) -> str:
58
+ return self._by_field[key]
59
+
60
+ def __iter__(self) -> Iterator[str]:
61
+ return iter(self._by_field)
62
+
63
+ def __len__(self) -> int:
64
+ return len(self._by_field)
65
+
66
+ def __repr__(self) -> str:
67
+ return f"{type(self).__name__}({self._by_field!r})"
68
+
69
+
70
+ class FieldErrors(_ByField):
71
+ """Field name -> the first message for it."""
72
+
73
+ __slots__ = ("_general",)
74
+
75
+ def __init__(self, by_field: Mapping[str, str], general: Sequence[str] = ()) -> None:
76
+ super().__init__(by_field)
77
+ self._general = tuple(general)
78
+
79
+ @property
80
+ def general(self) -> tuple[str, ...]:
81
+ """Messages with no field: a model-level rule, a malformed body, a `loc`
82
+ outside the body.
83
+ """
84
+ return self._general
85
+
86
+ def __repr__(self) -> str:
87
+ return f"FieldErrors({self._by_field!r}, general={self._general!r})"
88
+
89
+ def messages(self) -> tuple[str, ...]:
90
+ """Every message, field ones first and prefixed with `label(name)`."""
91
+ return (*(f"{label(name)}: {text}" for name, text in self._by_field.items()), *self._general)
92
+
93
+
94
+ def field_errors(exc: Any, *, request_scoped: bool) -> FieldErrors:
95
+ """Read `exc.errors()` into `FieldErrors`.
96
+
97
+ `request_scoped=True` for FastAPI's `RequestValidationError`, whose `loc`
98
+ starts with where the value came from (`("body", "title")`); `False` for a
99
+ pydantic `ValidationError`, whose `loc` is `("title",)`. An unparsable
100
+ body (`_UNPARSABLE`) goes to `general`.
101
+ """
102
+ by_field: dict[str, str] = {}
103
+ general: list[str] = []
104
+ for detail in getattr(exc, "errors", lambda: ())():
105
+ message = str(detail.get("msg", "Invalid value"))
106
+ if detail.get("type") in _UNPARSABLE:
107
+ general.append(message)
108
+ continue
109
+ name = field_name(detail.get("loc", ()), request_scoped=request_scoped)
110
+ if name is None:
111
+ general.append(message)
112
+ elif name not in by_field:
113
+ by_field[name] = message
114
+ return FieldErrors(by_field, general)
115
+
116
+
117
+ def field_name(loc: Sequence[Any], *, request_scoped: bool) -> str | None:
118
+ """The form field a `loc` refers to, or `None`.
119
+
120
+ Request-scoped: `("body", "title")` -> `"title"`; anything not under
121
+ `body` -> `None`. Model-scoped: `("title",)` -> `"title"`; empty -> `None`.
122
+ Nested paths are joined with dots: `("body", "items", 0, "title")` ->
123
+ `"items.0.title"`.
124
+ """
125
+ parts = tuple(loc)
126
+ if request_scoped:
127
+ if not parts or parts[0] != _BODY:
128
+ return None
129
+ parts = parts[1:]
130
+ if not parts:
131
+ return None
132
+ return ".".join(str(part) for part in parts)
133
+
134
+
135
+ def label(name: str) -> str:
136
+ """`owner_name` -> `Owner name`, `items.0.title` -> `Items 1 title`.
137
+ Indexes are shown one-based.
138
+ """
139
+ parts = []
140
+ for part in name.split("."):
141
+ parts.append(str(int(part) + 1) if part.isdigit() else part.replace("_", " "))
142
+ return " ".join(parts).strip().capitalize()
143
+
144
+
145
+ NO_ERRORS = FieldErrors({})
fjkit/htmx.py ADDED
@@ -0,0 +1,76 @@
1
+ """The `HX-*` headers, named once.
2
+
3
+ from fjkit import htmx
4
+
5
+ if htmx.is_swap(request):
6
+ htmx.retarget(response, "#board", swap="outerHTML")
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import MutableMapping
12
+
13
+ from fastapi import Request, Response
14
+
15
+ __all__ = [
16
+ "is_boosted",
17
+ "is_htmx",
18
+ "is_swap",
19
+ "prompt",
20
+ "reswap",
21
+ "retarget",
22
+ "target",
23
+ ]
24
+
25
+ #: Anything that accepts `headers["HX-Retarget"] = …`: a `Response`, a
26
+ #: `MutableHeaders`, or the plain dict `@render` builds a reply from. Typed as
27
+ #: the intersection rather than as `Response`, because the caller that matters
28
+ #: is an exception handler that has not built its response yet.
29
+ Headers = MutableMapping[str, str]
30
+
31
+
32
+ def is_htmx(request: Request) -> bool:
33
+ """True for any request htmx made, boosted navigations included."""
34
+ return request.headers.get("hx-request", "").lower() == "true"
35
+
36
+
37
+ def is_boosted(request: Request) -> bool:
38
+ """True when htmx is performing an ordinary navigation on a link's behalf."""
39
+ return request.headers.get("hx-boosted", "").lower() == "true"
40
+
41
+
42
+ def is_swap(request: Request) -> bool:
43
+ """True for an htmx request that is replacing part of the page — htmx and
44
+ not boosted.
45
+ """
46
+ return is_htmx(request) and not is_boosted(request)
47
+
48
+
49
+ def target(request: Request) -> str | None:
50
+ """The id of the element this swap is aimed at, if htmx named one."""
51
+ return request.headers.get("hx-target") or None
52
+
53
+
54
+ def prompt(request: Request) -> str | None:
55
+ """Whatever `hx-prompt` collected, if the trigger asked for something."""
56
+ return request.headers.get("hx-prompt") or None
57
+
58
+
59
+ def retarget(response: Response | Headers, selector: str, *, swap: str | None = None) -> None:
60
+ """Set `HX-Retarget`, and `HX-Reswap` when `swap` is given. Pass `swap`:
61
+ `hx-swap` was written for the original target.
62
+ """
63
+ headers = _headers(response)
64
+ headers["HX-Retarget"] = selector
65
+ if swap is not None:
66
+ headers["HX-Reswap"] = swap
67
+
68
+
69
+ def reswap(response: Response | Headers, swap: str) -> None:
70
+ """Override `hx-swap` for this response only. `retarget` usually implies it."""
71
+ _headers(response)["HX-Reswap"] = swap
72
+
73
+
74
+ def _headers(response: Response | Headers) -> Headers:
75
+ """The headers of a `Response`, or the mapping itself."""
76
+ return response.headers if isinstance(response, Response) else response
fjkit/icons.py ADDED
@@ -0,0 +1,60 @@
1
+ """Inline Lucide icons.
2
+
3
+ A dict lookup and one `<svg>` — no icon font, no sprite request, no runtime JS.
4
+ Only the icons a page calls reach the response, so shipping the whole set costs
5
+ package size and nothing on the wire.
6
+
7
+ The set is loaded from JSON on first use rather than imported as a Python
8
+ module, for two reasons: `import fjkit` stays fast for an app that renders no
9
+ icons on its hot path, and a version bump is a one-line diff in a data file
10
+ instead of a 20,000-line one in the source tree.
11
+
12
+ Regenerate with: uv run python packages/fjkit/scripts/vendor_icons.py
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from difflib import get_close_matches
19
+ from functools import cache
20
+
21
+ from markupsafe import Markup
22
+
23
+ from fjkit.config import STATIC_DIR
24
+
25
+ __all__ = ["path", "names", "version"]
26
+
27
+ _DATA = STATIC_DIR / "icons" / "lucide.json"
28
+
29
+
30
+ @cache
31
+ def _icons() -> dict[str, str]:
32
+ return json.loads(_DATA.read_text(encoding="utf-8"))["icons"]
33
+
34
+
35
+ @cache
36
+ def version() -> str:
37
+ """The vendored lucide-static version. Reported in the shell's footer."""
38
+ return json.loads(_DATA.read_text(encoding="utf-8"))["version"]
39
+
40
+
41
+ def path(name: str) -> Markup:
42
+ """The inner SVG markup for one icon.
43
+
44
+ Raises `KeyError` on an unknown name rather than rendering an empty box,
45
+ because a silently missing icon is the kind of bug that ships. The
46
+ suggestion earns its place: among 1,767 names, `arrow-right` and
47
+ `arrow-right-circle` are a coin flip from memory.
48
+ """
49
+ icons = _icons()
50
+ try:
51
+ return Markup(icons[name])
52
+ except KeyError:
53
+ suggestion = get_close_matches(name, icons, n=3)
54
+ hint = f" Did you mean: {', '.join(suggestion)}?" if suggestion else ""
55
+ raise KeyError(f"fjkit has no icon named {name!r}.{hint}") from None
56
+
57
+
58
+ def names() -> list[str]:
59
+ """Every available icon name, sorted. Used by the docs page and tests."""
60
+ return sorted(_icons())
fjkit/messages.py ADDED
@@ -0,0 +1,227 @@
1
+ """A message shown to the person who made the current request.
2
+
3
+ Three layers deep, and this is the middle one:
4
+
5
+ 1. **The surface** — `ui/feedback.html`'s `toaster()` region and `toast()`
6
+ macro. Already core: `ui/shell.html` renders the region on every page,
7
+ whether or not anything is in it.
8
+ 2. **Getting a message onto this response** — here.
9
+ 3. **Surviving a redirect** — `fjkit.flash`, a plugin rather than core because
10
+ it needs a signing secret.
11
+
12
+ Layer 3 is not a superset of layer 2. `FlashPlugin` writes a signed cookie,
13
+ because a redirect replaces the page and the document that would have shown the
14
+ message is gone before it arrives. The reverse holds too: on a response that is
15
+ not a redirect, a cookie is a round trip for a message about to be rendered
16
+ anyway. So the two are layered rather than merged, and flash queues into this
17
+ module.
18
+
19
+ from fjkit import messages
20
+
21
+ messages.add(request, "Saved", category="success")
22
+
23
+ How it reaches the browser depends on what the response is, and the caller
24
+ never has to know which:
25
+
26
+ full page render -> the shell renders it, straight into the toaster
27
+ htmx swap -> `HX-Trigger`, and the shell's listener raises it
28
+
29
+ `HX-Trigger` rather than markup, because a fragment carries no toaster: an htmx
30
+ swap replaces one region, and the region a toast belongs in is elsewhere on the
31
+ page. It also works on a response htmx will not swap at all — htmx reads
32
+ `HX-Trigger` in `handleAjaxResponse` before it consults `responseHandling` for
33
+ the status code, so a 422 or a 500 can still raise a toast on the page the user
34
+ is looking at. That is the whole delivery mechanism for `fjkit.errors`.
35
+
36
+ A message is consumed by being **iterated**, not by being looked at. See
37
+ `_Queue`.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import json
43
+ from collections.abc import Iterator, Sequence
44
+ from dataclasses import dataclass
45
+ from typing import Any, Literal
46
+
47
+ from fastapi import Request
48
+
49
+ __all__ = [
50
+ "TOAST_EVENT",
51
+ "Category",
52
+ "Message",
53
+ "add",
54
+ "extend",
55
+ "queue",
56
+ "shown",
57
+ "trigger_header",
58
+ ]
59
+
60
+ #: What a message means, not what colour it is. `toast()` maps each to an icon
61
+ #: and a timeout, and `fjkit.css` maps each to a role token — so "error is red"
62
+ #: is decided once, in the stylesheet, and survives a rebrand.
63
+ Category = Literal["info", "success", "warning", "error"]
64
+
65
+ #: The DOM event `HX-Trigger` names, and the one `ui/shell.html` listens for.
66
+ #: Namespaced because it lands on `document.body`, where an app's own events
67
+ #: live too.
68
+ TOAST_EVENT = "fjkit:toast"
69
+
70
+ _SLOT = "fjkit_messages"
71
+ _SHOWN = "fjkit_messages_shown"
72
+
73
+
74
+ @dataclass(frozen=True, slots=True)
75
+ class Message:
76
+ """One message. `category` picks the icon, the timeout and the role colour."""
77
+
78
+ title: str
79
+ text: str | None = None
80
+ category: Category = "info"
81
+
82
+ def as_detail(self) -> dict[str, str]:
83
+ """Return the shape Basecoat's toaster constructor takes.
84
+
85
+ `text` is renamed to `description` here rather than in the dataclass:
86
+ the field is called `text` everywhere in fjkit and in `toast()`, and a
87
+ vendored library's parameter name is not a reason to rename a field
88
+ across the kit's own API.
89
+ """
90
+ detail: dict[str, str] = {"category": self.category, "title": self.title}
91
+ if self.text is not None:
92
+ detail["description"] = self.text
93
+ return detail
94
+
95
+
96
+ def queue(request: Request | None) -> _Queue:
97
+ """Return this request's messages, creating the queue on first use.
98
+
99
+ Lazy rather than built in middleware: core adds no middleware, so an app
100
+ that never raises a message pays nothing — not a stack frame, not an
101
+ attribute.
102
+
103
+ `request` may be `None`. The docs-site builder and the render benchmark
104
+ drive the same templates with `request=None`, and the shell reads this on
105
+ every page; a render with nowhere to put a message has none.
106
+ """
107
+ state = getattr(request, "state", None)
108
+ if state is None:
109
+ return _Queue(None)
110
+ existing = getattr(state, _SLOT, None)
111
+ if existing is None:
112
+ existing = _Queue(request)
113
+ setattr(state, _SLOT, existing)
114
+ return existing
115
+
116
+
117
+ def add(request: Request, title: str, text: str | None = None, *, category: Category = "info") -> None:
118
+ """Show a message on this response. The one-message form of `extend`."""
119
+ queue(request).append(Message(title=title, text=text, category=category))
120
+
121
+
122
+ def extend(request: Request, messages: Sequence[Message]) -> None:
123
+ """Queue several at once. `FlashPlugin` uses it to hand over its cookie."""
124
+ queue(request).extend(messages)
125
+
126
+
127
+ def shown(request: Request) -> bool:
128
+ """Whether this request's messages actually reached the browser.
129
+
130
+ True once they have been iterated into a template or serialised into an
131
+ `HX-Trigger`. `FlashPlugin` reads it to decide whether to clear its cookie:
132
+ a message queued but never rendered has not been shown, and clearing it
133
+ would lose it.
134
+ """
135
+ return bool(getattr(request.state, _SHOWN, False))
136
+
137
+
138
+ def trigger_header(request: Request, existing: str | None = None) -> str | None:
139
+ """The `HX-Trigger` value carrying this request's messages, or `None`.
140
+
141
+ Shaped as `{"fjkit:toast": {"messages": [...]}}`.
142
+
143
+ Merges rather than replaces. A handler may already have set `HX-Trigger`
144
+ for its own event, and dropping it because a toast happened to be queued is
145
+ a bug that surfaces only when both are in play. htmx accepts a bare event
146
+ name as well as a JSON object, so a plain string is promoted to
147
+ `{"<name>": null}` before ours is added.
148
+ """
149
+ pending = getattr(request.state, _SLOT, None)
150
+ if not pending:
151
+ return existing
152
+
153
+ events: dict[str, Any] = {}
154
+ if existing:
155
+ text = existing.strip()
156
+ if text.startswith("{"):
157
+ try:
158
+ events = json.loads(text)
159
+ except ValueError:
160
+ # Not ours to repair, and not ours to discard either: keep it
161
+ # as an event name so the handler's intent survives.
162
+ events = {text: None}
163
+ else:
164
+ events = {name.strip(): None for name in text.split(",") if name.strip()}
165
+
166
+ # `{"messages": [...]}` and not the bare list, because htmx unwraps the two
167
+ # differently: a plain object becomes `event.detail`, while anything else —
168
+ # an array included — is wrapped as `{value: …}`. Sending an object keeps
169
+ # the payload in the shape the listener reads, rather than making the shell
170
+ # depend on a rule inside a vendored file.
171
+ events[TOAST_EVENT] = {"messages": [message.as_detail() for message in pending.drain()]}
172
+ return json.dumps(events, separators=(",", ":"))
173
+
174
+
175
+ class _Queue:
176
+ """The messages, plus the fact of having been delivered.
177
+
178
+ Consumption is **iteration**. `{% for m in fjkit_messages(request) %}` marks
179
+ them shown; `{% if fjkit_messages(request) %}` does not, because asking
180
+ whether there is anything to show is not showing it.
181
+
182
+ That distinction is load-bearing for `FlashPlugin`, which clears its cookie
183
+ only once the message reached a page. A page load fires more requests than
184
+ the page — an htmx poll, a prefetch — and "this request carried the cookie"
185
+ would let any of them eat the message. "A render happened" is not enough
186
+ either: an htmx swap renders a partial, and a partial carries no toaster.
187
+ Django's messages framework draws the line in the same place, for the same
188
+ reason.
189
+ """
190
+
191
+ __slots__ = ("_messages", "_request")
192
+
193
+ def __init__(self, request: Request | None) -> None:
194
+ self._messages: list[Message] = []
195
+ self._request = request
196
+
197
+ def append(self, message: Message) -> None:
198
+ self._messages.append(message)
199
+
200
+ def extend(self, messages: Sequence[Message]) -> None:
201
+ self._messages.extend(messages)
202
+
203
+ def drain(self) -> tuple[Message, ...]:
204
+ """Take the messages for delivery down a channel that is not a template.
205
+
206
+ Emptying the queue stops a message being delivered twice when a
207
+ response both carries an `HX-Trigger` and renders a toaster.
208
+ """
209
+ self._mark()
210
+ taken = tuple(self._messages)
211
+ self._messages.clear()
212
+ return taken
213
+
214
+ def _mark(self) -> None:
215
+ if self._request is not None:
216
+ setattr(self._request.state, _SHOWN, True)
217
+
218
+ def __bool__(self) -> bool:
219
+ return bool(self._messages)
220
+
221
+ def __len__(self) -> int:
222
+ return len(self._messages)
223
+
224
+ def __iter__(self) -> Iterator[Message]:
225
+ if self._messages:
226
+ self._mark()
227
+ return iter(tuple(self._messages))