larust_live/component.rs
1use axum::http::StatusCode;
2use larust_core::AppError;
3use larust_http::session::Session;
4use larust_view::View;
5use serde::de::DeserializeOwned;
6use serde::Serialize;
7use std::collections::HashMap;
8use std::future::Future;
9
10/// A server-state-backed reactive component - Larust's Livewire-equivalent.
11/// Unlike Livewire, `Self`'s state never crosses the wire: it lives
12/// server-side, keyed by the user's session (see `larust-live::state`), and
13/// only an opaque component id is ever sent to/from the browser.
14///
15/// Implementors are typically small `#[derive(Serialize, Deserialize)]`
16/// structs holding just the fields a `wire:model`/`wire:model.live` field
17/// binds to, plus whatever else `render` needs to recompute its output.
18/// Prefer a struct with named fields - even a `wire:click`-only component
19/// with no `wire:model` bindings at all - over a fieldless unit struct
20/// (`struct Foo;`, which `serde_json` serializes as `Value::Null` rather
21/// than a JSON object): a client sending a non-empty `props` object for
22/// such a component (a bug, or a crafted request) is rejected with a
23/// clean 422, whereas an entirely-empty prop sync (the normal case for a
24/// `wire:click`-only component) works either way.
25///
26/// `mount`/`render`/`call` are `async` (spelled as `-> impl Future<..> +
27/// Send` rather than `async fn`, so the `+ Send` bound is explicit rather
28/// than relying on an external `#[trait_variant]`-style macro) because a
29/// real component routinely needs to do real async work - querying the
30/// database in `render` (a search box), or persisting a change to it from
31/// an action `wire:click` dispatches to in `call`. A sync-only trait would
32/// make that impossible to express here at all.
33pub trait WireComponent: Serialize + DeserializeOwned + Send + Sync + 'static {
34 /// A stable, app-chosen registration name - the string a
35 /// `@wire('name', ...)` call site names. Deliberately not
36 /// `std::any::type_name::<Self>()`: that string isn't stable across a
37 /// rename, and every already-mounted, session-stored instance would
38 /// silently stop resolving the moment it changed.
39 const NAME: &'static str;
40
41 /// Builds this component's initial state from the props its
42 /// `@wire(...)` call site passed. A prop name this component doesn't
43 /// recognize is simply ignored - the same "unset becomes nothing"
44 /// tolerance `@global`/`@stack` already have. `session` is the same
45 /// real session `call`'s own `session` param is - available here so a
46 /// component can capture per-viewer identity once, at mount time (e.g.
47 /// "does the current user own this record, so should they see edit/
48 /// delete controls" - `demo`'s `PostList` does exactly this), rather
49 /// than needing to be told it again on every subsequent render.
50 fn mount(
51 session: &Session,
52 props: &HashMap<String, serde_json::Value>,
53 ) -> impl Future<Output = Self> + Send;
54
55 /// Renders the current state. Typically ends with a
56 /// `larust_support::view!("components.name", { .. })` call - use
57 /// `View::into_html()`, not `into_response()`, since this is a fragment,
58 /// not a full page (a fragment must never get the dev-reload script
59 /// spliced into it).
60 fn render(&self) -> impl Future<Output = View> + Send;
61
62 /// Dispatches a `wire:click="action_name"`/`wire:submit="action_name"`-
63 /// style call, mutating `self` in place. `session` is the requesting
64 /// user's real session - the same one `mount()`'s surrounding
65 /// `@wire(...)` call site has, threaded through here so an action can
66 /// look up the logged-in user (`larust_support::auth::id(session)`) to
67 /// do real, per-user work (creating a record as its author, say), not
68 /// just mutate local component state. The default rejects every action
69 /// name - a display-only, `wire:model`-only component needs zero
70 /// action boilerplate; there's no silent-security-gap risk in
71 /// defaulting to "reject everything" the way `Policy<U>`'s
72 /// deliberately-defaultless abilities avoid a different risk
73 /// (accidentally-permissive authorization).
74 ///
75 /// Returning `Ok(Some(path))` tells the client to navigate the browser
76 /// to `path` instead of patching the current fragment in place -
77 /// Livewire's own `redirect()`, for the common case of an action that
78 /// finishes by taking the user somewhere else entirely (a form
79 /// `wire:submit` that creates a record and sends the browser to it).
80 /// `Ok(None)` is the normal case: re-render this component in place
81 /// with whatever `self` mutation the action made (including, e.g.,
82 /// setting a validation-errors field for the next render to display).
83 fn call(
84 &mut self,
85 _session: &Session,
86 action: &str,
87 _args: &serde_json::Value,
88 ) -> impl Future<Output = Result<Option<String>, AppError>> + Send {
89 async move {
90 Err(AppError::Http {
91 status: StatusCode::NOT_FOUND,
92 message: format!("component `{}` has no action `{action}`", Self::NAME),
93 })
94 }
95 }
96}